/**
  * 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;
 }
 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);
     }
 }
 /**
  * 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' => '*****@*****.**', '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();
 }
 /**
  * A method to test the MAX_Delivery_log_logConversion() function.
  */
 function test_MAX_Delivery_log_logConversion()
 {
     $aConf =& $GLOBALS['_MAX']['CONF'];
     $aConf['maintenance']['operationInterval'] = 60;
     $GLOBALS['_MAX']['NOW'] = time();
     $oNowDate = new Date($GLOBALS['_MAX']['NOW']);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oNowDate);
     $intervalStart = $aDates['start']->format('%Y-%m-%d %H:%M:%S');
     $oConversionDate = new Date();
     $oConversionDate->copy($oNowDate);
     $oConversionDate->subtractSeconds(60);
     $_SERVER['REMOTE_ADDR'] = '127.0.0.99';
     // Test to ensure that the openXDeliveryLog plugin's data bucket
     // table does not exist
     $oTable = new OA_DB_Table();
     $tableExists = $oTable->extistsTable($aConf['table']['prefix'] . 'data_bkt_a');
     $this->assertFalse($tableExists);
     // Test calling the main logging function without any plugins installed,
     // to ensure that this does not result in any kind of error
     $aConversion = array('action_type' => MAX_CONNECTION_AD_CLICK, 'tracker_type' => MAX_CONNECTION_TYPE_SALE, 'status' => MAX_CONNECTION_STATUS_APPROVED, 'cid' => 2, 'zid' => 3, 'dt' => $GLOBALS['_MAX']['NOW'] - 60, 'window' => 60);
     MAX_Delivery_log_logConversion(1, $aConversion);
     // Install the openXDeliveryLog plugin
     TestEnv::installPluginPackage('openXDeliveryLog', false);
     // Test to ensure that the openXDeliveryLog plugin's data bucket
     // table now does exist
     $tableExists = $oTable->extistsTable($aConf['table']['prefix'] . 'data_bkt_a');
     $this->assertTrue($tableExists);
     // Ensure that there are is nothing logged in the data bucket table
     $doData_bkt_a = OA_Dal::factoryDO('data_bkt_a');
     $doData_bkt_a->find();
     $rows = $doData_bkt_a->getRowCount();
     $this->assertEqual($rows, 0);
     // Call the conversion logging function
     $aConversionInfo = MAX_Delivery_log_logConversion(1, $aConversion);
     // Ensure that the data was logged correctly
     $doData_bkt_a = OA_Dal::factoryDO('data_bkt_a');
     $doData_bkt_a->find();
     $rows = $doData_bkt_a->getRowCount();
     $this->assertEqual($rows, 1);
     $doData_bkt_a = OA_Dal::factoryDO('data_bkt_a');
     $doData_bkt_a->server_conv_id = 1;
     $doData_bkt_a->find();
     $rows = $doData_bkt_a->getRowCount();
     $this->assertEqual($rows, 1);
     $doData_bkt_a->fetch();
     $this->assertEqual($doData_bkt_a->server_ip, 'singleDB');
     $this->assertEqual($doData_bkt_a->tracker_id, 1);
     $this->assertEqual($doData_bkt_a->date_time, $oNowDate->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($doData_bkt_a->action_date_time, $oConversionDate->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($doData_bkt_a->creative_id, 2);
     $this->assertEqual($doData_bkt_a->zone_id, 3);
     $this->assertEqual($doData_bkt_a->ip_address, '127.0.0.99');
     $this->assertEqual($doData_bkt_a->action, MAX_CONNECTION_AD_CLICK);
     $this->assertEqual($doData_bkt_a->window, 60);
     $this->assertEqual($doData_bkt_a->status, MAX_CONNECTION_STATUS_APPROVED);
     $this->assertTrue(is_array($aConversionInfo));
     $this->assertTrue(is_array($aConversionInfo['deliveryLog:oxLogConversion:logConversion']));
     $this->assertEqual($aConversionInfo['deliveryLog:oxLogConversion:logConversion']['server_conv_id'], 1);
     $this->assertEqual($aConversionInfo['deliveryLog:oxLogConversion:logConversion']['server_raw_ip'], 'singleDB');
     $aConversion['cid'] = 5;
     // Call the conversion logging function
     $aConversionInfo = MAX_Delivery_log_logConversion(1, $aConversion);
     // Ensure that the data was logged correctly
     $doData_bkt_a = OA_Dal::factoryDO('data_bkt_a');
     $doData_bkt_a->find();
     $rows = $doData_bkt_a->getRowCount();
     $this->assertEqual($rows, 2);
     $doData_bkt_a = OA_Dal::factoryDO('data_bkt_a');
     $doData_bkt_a->server_conv_id = 1;
     $doData_bkt_a->find();
     $rows = $doData_bkt_a->getRowCount();
     $this->assertEqual($rows, 1);
     $doData_bkt_a->fetch();
     $this->assertEqual($doData_bkt_a->server_ip, 'singleDB');
     $this->assertEqual($doData_bkt_a->tracker_id, 1);
     $this->assertEqual($doData_bkt_a->date_time, $oNowDate->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($doData_bkt_a->action_date_time, $oConversionDate->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($doData_bkt_a->creative_id, 2);
     $this->assertEqual($doData_bkt_a->zone_id, 3);
     $this->assertEqual($doData_bkt_a->ip_address, '127.0.0.99');
     $this->assertEqual($doData_bkt_a->action, MAX_CONNECTION_AD_CLICK);
     $this->assertEqual($doData_bkt_a->window, 60);
     $this->assertEqual($doData_bkt_a->status, MAX_CONNECTION_STATUS_APPROVED);
     $doData_bkt_a = OA_Dal::factoryDO('data_bkt_a');
     $doData_bkt_a->server_conv_id = 2;
     $doData_bkt_a->find();
     $rows = $doData_bkt_a->getRowCount();
     $this->assertEqual($rows, 1);
     $doData_bkt_a->fetch();
     $this->assertEqual($doData_bkt_a->server_ip, 'singleDB');
     $this->assertEqual($doData_bkt_a->tracker_id, 1);
     $this->assertEqual($doData_bkt_a->date_time, $oNowDate->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($doData_bkt_a->action_date_time, $oConversionDate->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($doData_bkt_a->creative_id, 5);
     $this->assertEqual($doData_bkt_a->zone_id, 3);
     $this->assertEqual($doData_bkt_a->ip_address, '127.0.0.99');
     $this->assertEqual($doData_bkt_a->action, MAX_CONNECTION_AD_CLICK);
     $this->assertEqual($doData_bkt_a->window, 60);
     $this->assertEqual($doData_bkt_a->status, MAX_CONNECTION_STATUS_APPROVED);
     $this->assertTrue(is_array($aConversionInfo));
     $this->assertTrue(is_array($aConversionInfo['deliveryLog:oxLogConversion:logConversion']));
     $this->assertEqual($aConversionInfo['deliveryLog:oxLogConversion:logConversion']['server_conv_id'], 2);
     $this->assertEqual($aConversionInfo['deliveryLog:oxLogConversion:logConversion']['server_raw_ip'], 'singleDB');
     // Uninstall the openXDeliveryLog plugin
     TestEnv::uninstallPluginPackage('openXDeliveryLog', false);
     // Restore the test configuration file
     TestEnv::restoreConfig();
 }
Exemple #5
0
 /**
  * A method to activate/deactivate campaigns, based on the date and/or the inventory
  * requirements (impressions, clicks and/or conversions). Also sends email reports
  * for any campaigns that are activated/deactivated, as well as sending email reports
  * for any campaigns that are likely to expire in the near future.
  *
  * @param Date $oDate The current date/time.
  * @return string Report on the campaigns activated/deactivated.
  */
 function manageCampaigns($oDate)
 {
     $aConf = $GLOBALS['_MAX']['CONF'];
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oEmail =& $oServiceLocator->get('OA_Email');
     if ($oEmail === false) {
         $oEmail = new OA_Email();
         $oServiceLocator->register('OA_Email', $oEmail);
     }
     $report = "\n";
     // Select all campaigns in the system, where:
     //    The campaign is ACTIVE and:
     //    - The end date stored for the campaign is not null; or
     //    - The campaign has a lifetime impression, click or conversion
     //      target set.
     //
     //    That is:
     //    - It is possible for the active campaign to be automatically
     //      stopped, as it has a valid end date. (No limitations are
     //      applied to those campaigns tested, as the ME may not have
     //      run for a while, and if so, even campaigns with an end date
     //      of many, many weeks ago should be tested to ensure they are
     //      [belatedly] halted.)
     //    - It is possible for the active campaign to be automatically
     //      stopped, as it has at leaast one lifetime target that could
     //      have been reached.
     //
     //    The campaign is INACTIVE and:
     //    - The start date stored for the campaign is not null; and
     //    - The weight is greater than zero; and
     //    - The end date stored for the campaign is either null, or is
     //      greater than "today" less one day.
     //
     //    That is:
     //    - It is possible for the inactive campaign to be automatically
     //      started, as it has a valid start date. (No limitations are
     //      applied to those campaigns tested, as the ME may not have run
     //      for a while, and if so, even campaigns with an activation date
     //      of many, many weeks ago should be tested to ensure they are
     //      [belatedy] enabled.)
     //    - The campaign is not in a permanently inactive state, as a
     //      result of the weight being less then one, which means that
     //      it cannot be activated.
     //    - The test to start the campaign is unlikely to fail on account
     //      of the end date. (Inactive campaigns with start dates may have
     //      passed the start date, but they may also have passed the end
     //      date - unfortunately, because the dates are not stored in UTC,
     //      it's not possible to know exactly which campaigns have passed
     //      the end date or not, until the values are converted to UTC based
     //      on the Advertiser Account timezone preference - so it's necessary
     //      to get some campaigns that might be passed the end date, and do
     //      the converstion to UTC and test to check.)
     $prefix = $this->getTablePrefix();
     $oYesterdayDate = new Date();
     $oYesterdayDate->copy($oDate);
     $oYesterdayDate->subtractSeconds(SECONDS_PER_DAY);
     $query = "\n            SELECT\n                cl.clientid AS advertiser_id,\n                cl.account_id AS advertiser_account_id,\n                cl.agencyid AS agency_id,\n                cl.contact AS contact,\n                cl.email AS email,\n                cl.reportdeactivate AS send_activate_deactivate_email,\n                ca.campaignid AS campaign_id,\n                ca.campaignname AS campaign_name,\n                ca.views AS targetimpressions,\n                ca.clicks AS targetclicks,\n                ca.conversions AS targetconversions,\n                ca.status AS status,\n                ca.activate AS start,\n                ca.expire AS end\n            FROM\n                {$prefix}campaigns AS ca,\n                {$prefix}clients AS cl\n            WHERE\n                ca.clientid = cl.clientid\n                AND\n                ca.status = " . $this->oDbh->quote(OA_ENTITY_STATUS_RUNNING, 'integer') . "\n                AND\n                (\n                    ca.expire " . OA_Dal::notEqualNoDateString() . "\n                    OR\n                    (\n                        ca.views > 0\n                        OR\n                        ca.clicks > 0\n                        OR\n                        ca.conversions > 0\n                    )\n                )\n            UNION ALL\n            SELECT\n                cl.clientid AS advertiser_id,\n                cl.account_id AS advertiser_account_id,\n                cl.agencyid AS agency_id,\n                cl.contact AS contact,\n                cl.email AS email,\n                cl.reportdeactivate AS send_activate_deactivate_email,\n                ca.campaignid AS campaign_id,\n                ca.campaignname AS campaign_name,\n                ca.views AS targetimpressions,\n                ca.clicks AS targetclicks,\n                ca.conversions AS targetconversions,\n                ca.status AS status,\n                ca.activate AS start,\n                ca.expire AS end\n            FROM\n                {$prefix}campaigns AS ca,\n                {$prefix}clients AS cl\n            WHERE\n                ca.clientid = cl.clientid\n                AND\n                ca.status != " . $this->oDbh->quote(OA_ENTITY_STATUS_RUNNING, 'integer') . "\n                AND\n                ca.activate " . OA_Dal::notEqualNoDateString() . "\n                AND\n                (\n                    ca.weight > 0\n                    OR\n                    ca.priority > 0\n                )\n                AND\n                (\n                    ca.expire >= " . $this->oDbh->quote($oYesterdayDate->format('%Y-%m-%d'), 'timestamp') . "\n                    OR\n                    ca.expire " . OA_Dal::equalNoDateString() . "\n                )\n            ORDER BY\n                advertiser_id";
     $rsResult = $this->oDbh->query($query);
     if (PEAR::isError($rsResult)) {
         return MAX::raiseError($rsResult, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
     }
     OA::debug('- Found ' . $rsResult->numRows() . ' campaigns to test for activation/deactivation', PEAR_LOG_DEBUG);
     while ($aCampaign = $rsResult->fetchRow()) {
         if ($aCampaign['status'] == OA_ENTITY_STATUS_RUNNING) {
             // The campaign is currently running, look at the campaign
             $disableReason = 0;
             $canExpireSoon = false;
             if ($aCampaign['targetimpressions'] > 0 || $aCampaign['targetclicks'] > 0 || $aCampaign['targetconversions'] > 0) {
                 // The campaign has an impression, click and/or conversion target,
                 // so get the sum total statistics for the campaign
                 $query = "\n                        SELECT\n                            SUM(dia.impressions) AS impressions,\n                            SUM(dia.clicks) AS clicks,\n                            SUM(dia.conversions) AS conversions\n                        FROM\n                            " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['data_intermediate_ad'], true) . " AS dia,\n                            " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['banners'], true) . " AS b\n                        WHERE\n                            dia.ad_id = b.bannerid\n                            AND b.campaignid = {$aCampaign['campaign_id']}";
                 $rsResultInner = $this->oDbh->query($query);
                 $valuesRow = $rsResultInner->fetchRow();
                 if (!is_null($valuesRow['impressions']) || !is_null($valuesRow['clicks']) || !is_null($valuesRow['conversions'])) {
                     // There were impressions, clicks and/or conversions for this
                     // campaign, so find out if campaign targets have been passed
                     if (is_null($valuesRow['impressions'])) {
                         // No impressions
                         $valuesRow['impressions'] = 0;
                     }
                     if (is_null($valuesRow['clicks'])) {
                         // No clicks
                         $valuesRow['clicks'] = 0;
                     }
                     if (is_null($valuesRow['conversions'])) {
                         // No conversions
                         $valuesRow['conversions'] = 0;
                     }
                     if ($aCampaign['targetimpressions'] > 0) {
                         if ($aCampaign['targetimpressions'] <= $valuesRow['impressions']) {
                             // The campaign has an impressions target, and this has been
                             // passed, so update and disable the campaign
                             $disableReason |= OX_CAMPAIGN_DISABLED_IMPRESSIONS;
                         }
                     }
                     if ($aCampaign['targetclicks'] > 0) {
                         if ($aCampaign['targetclicks'] <= $valuesRow['clicks']) {
                             // The campaign has a click target, and this has been
                             // passed, so update and disable the campaign
                             $disableReason |= OX_CAMPAIGN_DISABLED_CLICKS;
                         }
                     }
                     if ($aCampaign['targetconversions'] > 0) {
                         if ($aCampaign['targetconversions'] <= $valuesRow['conversions']) {
                             // The campaign has a target limitation, and this has been
                             // passed, so update and disable the campaign
                             $disableReason |= OX_CAMPAIGN_DISABLED_CONVERSIONS;
                         }
                     }
                     if ($disableReason) {
                         // One of the campaign targets was exceeded, so disable
                         $message = '- Exceeded a campaign quota: Deactivating campaign ID ' . "{$aCampaign['campaign_id']}: {$aCampaign['campaign_name']}";
                         OA::debug($message, PEAR_LOG_INFO);
                         $report .= $message . "\n";
                         $doCampaigns = OA_Dal::factoryDO('campaigns');
                         $doCampaigns->campaignid = $aCampaign['campaign_id'];
                         $doCampaigns->find();
                         $doCampaigns->fetch();
                         $doCampaigns->status = OA_ENTITY_STATUS_EXPIRED;
                         $result = $doCampaigns->update();
                         if ($result == false) {
                             return MAX::raiseError($rows, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
                         }
                         phpAds_userlogSetUser(phpAds_userMaintenance);
                         phpAds_userlogAdd(phpAds_actionDeactiveCampaign, $aCampaign['campaign_id']);
                     } else {
                         // The campaign didn't have a diable reason,
                         // it *might* possibly be diabled "soon"...
                         $canExpireSoon = true;
                     }
                 }
             }
             // Does the campaign need to be disabled due to the date?
             if ($aCampaign['end'] != OA_Dal::noDateValue()) {
                 // The campaign has a valid end date, stored in the timezone of the advertiser;
                 // create an end date in the advertiser's timezone, set the time, and then
                 // convert to UTC so that it can be compared with the MSE run time, which is
                 // in UTC
                 $aAdvertiserPrefs = OA_Preferences::loadAccountPreferences($aCampaign['advertiser_account_id'], true);
                 $oTimezone = new Date_Timezone($aAdvertiserPrefs['timezone']);
                 $oEndDate = new Date();
                 $oEndDate->convertTZ($oTimezone);
                 $oEndDate->setDate($aCampaign['end'] . ' 23:59:59');
                 // Campaigns end at the end of the day
                 $oEndDate->toUTC();
                 if ($oDate->after($oEndDate)) {
                     // The end date has been passed; disable the campaign
                     $disableReason |= OX_CAMPAIGN_DISABLED_DATE;
                     $message = "- Passed campaign end time of '{$aCampaign['end']} 23:59:59 {$aAdvertiserPrefs['timezone']} (" . $oEndDate->format('%Y-%m-%d %H:%M:%S') . ' ' . $oEndDate->tz->getShortName() . ")': Deactivating campaign ID {$aCampaign['campaign_id']}: {$aCampaign['campaign_name']}";
                     OA::debug($message, PEAR_LOG_INFO);
                     $report .= $message . "\n";
                     $doCampaigns = OA_Dal::factoryDO('campaigns');
                     $doCampaigns->campaignid = $aCampaign['campaign_id'];
                     $doCampaigns->find();
                     $doCampaigns->fetch();
                     $doCampaigns->status = OA_ENTITY_STATUS_EXPIRED;
                     $result = $doCampaigns->update();
                     if ($result == false) {
                         return MAX::raiseError($rows, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
                     }
                     phpAds_userlogSetUser(phpAds_userMaintenance);
                     phpAds_userlogAdd(phpAds_actionDeactiveCampaign, $aCampaign['campaign_id']);
                 } else {
                     // The campaign wasn't disabled based on the end
                     // date, to it *might* possibly be disabled "soon"...
                     $canExpireSoon = true;
                 }
             }
             if ($disableReason) {
                 // The campaign was disabled, so send the appropriate
                 // message to the campaign's contact
                 $query = "\n                        SELECT\n                            bannerid AS advertisement_id,\n                            description AS description,\n                            alt AS alt,\n                            url AS url\n                        FROM\n                            " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['banners'], true) . "\n                        WHERE\n                            campaignid = {$aCampaign['campaign_id']}";
                 OA::debug("- Getting the advertisements for campaign ID {$aCampaign['campaign_id']}", PEAR_LOG_DEBUG);
                 $rsResultAdvertisement = $this->oDbh->query($query);
                 if (PEAR::isError($rsResultAdvertisement)) {
                     return MAX::raiseError($rsResultAdvertisement, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
                 }
                 while ($advertisementRow = $rsResultAdvertisement->fetchRow()) {
                     $advertisements[$advertisementRow['advertisement_id']] = array($advertisementRow['description'], $advertisementRow['alt'], $advertisementRow['url']);
                 }
                 if ($aCampaign['send_activate_deactivate_email'] == 't') {
                     $oEmail->sendCampaignActivatedDeactivatedEmail($aCampaign['campaign_id'], $disableReason);
                 }
             } else {
                 if ($canExpireSoon) {
                     // The campaign has NOT been deactivated - test to see if it will
                     // be deactivated "soon", and send email(s) warning of this as required
                     $oEmail->sendCampaignImpendingExpiryEmail($oDate, $aCampaign['campaign_id']);
                 }
             }
         } else {
             // The campaign is not active - does it need to be enabled,
             // based on the campaign starting date?
             if ($aCampaign['start'] != OA_Dal::noDateValue()) {
                 // The campaign has a valid start date, stored in the timezone of the advertiser;
                 // create an end date in the advertiser's timezone, set the time, and then
                 // convert to UTC so that it can be compared with the MSE run time, which is
                 // in UTC
                 $aAdvertiserPrefs = OA_Preferences::loadAccountPreferences($aCampaign['advertiser_account_id'], true);
                 $oTimezone = new Date_Timezone($aAdvertiserPrefs['timezone']);
                 $oStartDate = new Date();
                 $oStartDate->convertTZ($oTimezone);
                 $oStartDate->setDate($aCampaign['start'] . ' 00:00:00');
                 // Campaigns start at the start of the day
                 $oStartDate->toUTC();
                 if ($aCampaign['end'] != OA_Dal::noDateValue()) {
                     // The campaign has a valid end date, stored in the timezone of the advertiser;
                     // create an end date in the advertiser's timezone, set the time, and then
                     // convert to UTC so that it can be compared with the MSE run time, which is
                     // in UTC
                     $oEndDate = new Date();
                     $oEndDate->convertTZ($oTimezone);
                     $oEndDate->setDate($aCampaign['end'] . ' 23:59:59');
                     // Campaign end at the end of the day
                     $oEndDate->toUTC();
                 } else {
                     $oEndDate = null;
                 }
                 if ($oDate->after($oStartDate)) {
                     // The start date has been passed; find out if there are any impression, click
                     // or conversion targets for the campaign (i.e. if the target values are > 0)
                     $remainingImpressions = 0;
                     $remainingClicks = 0;
                     $remainingConversions = 0;
                     if ($aCampaign['targetimpressions'] > 0 || $aCampaign['targetclicks'] > 0 || $aCampaign['targetconversions'] > 0) {
                         // The campaign has an impression, click and/or conversion target,
                         // so get the sum total statistics for the campaign so far
                         $query = "\n                                SELECT\n                                    SUM(dia.impressions) AS impressions,\n                                    SUM(dia.clicks) AS clicks,\n                                    SUM(dia.conversions) AS conversions\n                                FROM\n                                    " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['data_intermediate_ad'], true) . " AS dia,\n                                    " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['banners'], true) . " AS b\n                                WHERE\n                                    dia.ad_id = b.bannerid\n                                    AND b.campaignid = {$aCampaign['campaign_id']}";
                         $rsResultInner = $this->oDbh->query($query);
                         $valuesRow = $rsResultInner->fetchRow();
                         // Set the remaining impressions, clicks and conversions for the campaign
                         $remainingImpressions = $aCampaign['targetimpressions'] - $valuesRow['impressions'];
                         $remainingClicks = $aCampaign['targetclicks'] - $valuesRow['clicks'];
                         $remainingConversions = $aCampaign['targetconversions'] - $valuesRow['conversions'];
                     }
                     // In order for the campaign to be activated, need to test:
                     // 1) That there is no impression target (<= 0), or, if there is an impression target (> 0),
                     //    then there must be remaining impressions to deliver (> 0); and
                     // 2) That there is no click target (<= 0), or, if there is a click target (> 0),
                     //    then there must be remaining clicks to deliver (> 0); and
                     // 3) That there is no conversion target (<= 0), or, if there is a conversion target (> 0),
                     //    then there must be remaining conversions to deliver (> 0); and
                     // 4) Either there is no end date, or the end date has not been passed
                     if (($aCampaign['targetimpressions'] <= 0 || $aCampaign['targetimpressions'] > 0 && $remainingImpressions > 0) && ($aCampaign['targetclicks'] <= 0 || $aCampaign['targetclicks'] > 0 && $remainingClicks > 0) && ($aCampaign['targetconversions'] <= 0 || $aCampaign['targetconversions'] > 0 && $remainingConversions > 0) && (is_null($oEndDate) || $oEndDate->format('%Y-%m-%d') != OA_Dal::noDateValue() && Date::compare($oDate, $oEndDate) < 0)) {
                         $message = "- Passed campaign start time of '{$aCampaign['start']} 00:00:00 {$aAdvertiserPrefs['timezone']} (" . $oStartDate->format('%Y-%m-%d %H:%M:%S') . ' ' . $oStartDate->tz->getShortName() . ")': Activating campaign ID {$aCampaign['campaign_id']}: {$aCampaign['campaign_name']}";
                         OA::debug($message, PEAR_LOG_INFO);
                         $report .= $message . "\n";
                         $doCampaigns = OA_Dal::factoryDO('campaigns');
                         $doCampaigns->campaignid = $aCampaign['campaign_id'];
                         $doCampaigns->find();
                         $doCampaigns->fetch();
                         $doCampaigns->status = OA_ENTITY_STATUS_RUNNING;
                         $result = $doCampaigns->update();
                         if ($result == false) {
                             return MAX::raiseError($rows, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
                         }
                         phpAds_userlogSetUser(phpAds_userMaintenance);
                         phpAds_userlogAdd(phpAds_actionActiveCampaign, $aCampaign['campaign_id']);
                         // Get the advertisements associated with the campaign
                         $query = "\n                                SELECT\n                                    bannerid AS advertisement_id,\n                                    description AS description,\n                                    alt AS alt,\n                                    url AS url\n                                FROM\n                                    " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['banners'], true) . "\n                                WHERE\n                                    campaignid = {$aCampaign['campaign_id']}";
                         OA::debug("- Getting the advertisements for campaign ID {$aCampaign['campaign_id']}", PEAR_LOG_DEBUG);
                         $rsResultAdvertisement = $this->oDbh->query($query);
                         if (PEAR::isError($rsResultAdvertisement)) {
                             return MAX::raiseError($rsResultAdvertisement, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
                         }
                         while ($advertisementRow = $rsResultAdvertisement->fetchRow()) {
                             $advertisements[$advertisementRow['advertisement_id']] = array($advertisementRow['description'], $advertisementRow['alt'], $advertisementRow['url']);
                         }
                         if ($aCampaign['send_activate_deactivate_email'] == 't') {
                             $oEmail->sendCampaignActivatedDeactivatedEmail($aCampaign['campaign_id']);
                         }
                     }
                 }
             }
         }
     }
 }
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;
}
 /**
  * A private method to convert the ZIF update type from _getUpdateTypeRequired() into
  * a range of operation intervals where all zones require their ZIF values to be updated.
  *
  * @access private
  * @param mixed $type The update type required. Possible values are the same as
  *                    those returned from the
  *                    {@link OA_Maintenance_Priority_AdServer_Task_ForecastZoneImpressions::getUpdateTypeRequired()}
  *                    method.
  * @return array An array of hashes where keys are operation interval IDs, and
  *               values are PEAR Dates. One element in the array indicates a
  *               contiguous range, two elements indicate a non-contiguous range.
  */
 function _getOperationIntervalRanges($type)
 {
     // Initialise result array
     $aResult = array();
     switch (true) {
         case is_bool($type) && $type === false:
             // Update none, return an empty array
             return $aResult;
         case is_bool($type) && $type === true:
             // Update all - need one week's worth of operation intervals up until the end
             // of the operation interval *after* the one that statistics have been updated
             // to, as we need to predict one interval ahead of now
             $oStatsDates = OX_OperationInterval::convertDateToNextOperationIntervalStartAndEndDates($this->oDateNow);
             $oStartDate = new Date();
             $oStartDate->copy($oStatsDates['start']);
             $oStartDate->subtractSeconds(SECONDS_PER_WEEK);
             $startId = OX_OperationInterval::convertDateToOperationIntervalID($oStartDate);
             $totalIntervals = OX_OperationInterval::operationIntervalsPerWeek();
             break;
         case is_array($type) && $type[0] < $type[1]:
             // A contiguous (ie. inter-week) range, where the first operation interval
             // ID is the lower bound, and the second operation interval ID is the upper
             // The start operation interval ID is the operation interval ID right after
             // the operation interval ID that priority was updated to (ie. $type[0])
             $aDates = OX_OperationInterval::convertDateToNextOperationIntervalStartAndEndDates($this->oPriorityUpdatedToDate);
             $oStartDate = $aDates['start'];
             $startId = OX_OperationInterval::nextOperationIntervalID($type[0], 1);
             $totalIntervals = $type[1] - $type[0];
             break;
         case is_array($type) && $type[0] > $type[1]:
             // A non-contiguous range, so calculate as above, but use the first operation
             // interval ID as the upper bound, and the second operation interval ID as the
             // lower bound in the proceeding week
             // The start operation interval ID is the operation interval ID right after
             // the operation interval ID that priority was updated to (ie. $type[0])
             $aDates = OX_OperationInterval::convertDateToNextOperationIntervalStartAndEndDates($this->oPriorityUpdatedToDate);
             $oStartDate = $aDates['start'];
             $startId = OX_OperationInterval::nextOperationIntervalID($type[0], 1);
             $totalIntervals = OX_OperationInterval::operationIntervalsPerWeek() - $type[0] + $type[1];
             break;
         default:
             OA::debug('OA_Maintenance_Priority_AdServer_Task_ForecastZoneImpressions::getOperationIntRangeByType() called with unexpected type, exiting', PEAR_LOG_CRIT);
             exit;
     }
     // Build the update range array
     $aRange = array();
     $totalIntervalPerWeek = OX_OperationInterval::operationIntervalsPerWeek();
     for ($x = $startId, $y = 0; $y < $totalIntervals; $x++, $y++) {
         if ($x == $totalIntervalPerWeek) {
             $x = 0;
         }
         $aDates = array();
         $aDates['start'] = new Date($oStartDate);
         //->format('%Y-%m-%d %H:%M:%S');
         $oEndDate = new Date();
         $oEndDate->copy($oStartDate);
         $oEndDate->addSeconds(OX_OperationInterval::secondsPerOperationInterval() - 1);
         $aDates['end'] = $oEndDate;
         //->format('%Y-%m-%d %H:%M:%S');
         unset($oEndDate);
         $aRange[$x] = $aDates;
         $oStartDate->addSeconds(OX_OperationInterval::secondsPerOperationInterval());
     }
     // Is the update range array a contiguous (inter-weeek) range?
     if (array_key_exists($totalIntervalPerWeek - 1, $aRange) && array_key_exists(0, $aRange)) {
         // The range contains the first and the last operation interval IDs, is the
         // last date before the first date?
         $oFirstIntervalStartDate = new Date($aRange[0]['start']);
         $oLastIntervalStartDate = new Date($aRange[$totalIntervalPerWeek - 1]['start']);
         if ($oLastIntervalStartDate->before($oFirstIntervalStartDate)) {
             // It's a non-contiguous range, so split into two ranges
             $aRange1 = array();
             $aRange2 = array();
             for ($x = $startId; $x < $totalIntervalPerWeek; $x++) {
                 $aRange1[$x] = $aRange[$x];
             }
             for ($x = 0; $x < $startId; $x++) {
                 if (isset($aRange[$x])) {
                     $aRange2[$x] = $aRange[$x];
                 }
             }
             $aResult[] = $aRange1;
             $aResult[] = $aRange2;
             return $aResult;
         }
     }
     $aResult[] = $aRange;
     return $aResult;
 }
Exemple #8
0
 /**
  * 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;
 }
Exemple #9
0
 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;
 }
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();
 /**
  * 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();
     // What's the current OI?
     $currentIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oServiceLocator->get('now'));
     $aResult = $oDal->getPreviousWeekZoneForcastImpressions(1);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), OX_OperationInterval::operationIntervalsPerWeek());
     for ($operationIntervalID = 0; $operationIntervalID < OX_OperationInterval::operationIntervalsPerWeek(); $operationIntervalID++) {
         $this->assertTrue(is_array($aResult[$operationIntervalID]));
         $this->assertEqual(count($aResult[$operationIntervalID]), 3);
         $this->assertEqual($aResult[$operationIntervalID]['zone_id'], 1);
         if ($operationIntervalID == $firstIntervalID || $operationIntervalID == $currentIntervalID) {
             // Current and previous OI forecasts should be the same
             $this->assertEqual($aResult[$operationIntervalID]['forecast_impressions'], 4000);
         } elseif ($operationIntervalID == $secondIntervalID) {
             $this->assertEqual($aResult[$operationIntervalID]['forecast_impressions'], 5000);
         } else {
             $this->assertEqual($aResult[$operationIntervalID]['forecast_impressions'], 4500);
             // average between both known forecast
         }
         $this->assertEqual($aResult[$operationIntervalID]['operation_interval_id'], $operationIntervalID);
     }
     DataGenerator::cleanUp();
 }
Exemple #12
0
 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;
     }
 }
 /**
  * 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();
     // Test 4: Run, with plugins installed and with the migration required for a single
     //         operation interval + migration of raw data set to occur
     $doApplication_variable = OA_Dal::factoryDO('application_variable');
     $doApplication_variable->name = 'mse_process_raw';
     $doApplication_variable->value = '1';
     $doApplication_variable->insert();
     $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_4', array('summariseBucketsRaw', 'summariseBucketsRawSupplementary', 'summariseBucketsAggregate', 'migrateRawRequests', 'migrateRawImpressions', 'migrateRawClicks'));
     $oDal = new MockOX_Dal_Maintenance_Statistics_Test_4($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->expectOnce('migrateRawRequests', array($oStartDate, $oEndDate));
     $oDal->expectOnce('migrateRawImpressions', array($oStartDate, $oEndDate));
     $oDal->expectOnce('migrateRawClicks', array($oStartDate, $oEndDate));
     $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();
     $doApplication_variable = OA_Dal::factoryDO('application_variable');
     $doApplication_variable->name = 'mse_process_raw';
     $doApplication_variable->value = '1';
     $doApplication_variable->find();
     $rows = $doApplication_variable->getRowCount();
     $this->assertEqual($rows, 0);
     // Test 5: Run, with plugins installed and with the migration required for multiple
     //         operation intervals
     $oNowDate = new Date('2008-08-28 11: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 10:59:59');
     $oServiceLocator->register('Maintenance_Statistics_Controller', $oMaintenanceStatistics);
     Mock::generatePartial($oDalMaintenanceStatsticsClassName, 'MockOX_Dal_Maintenance_Statistics_Test_5', array('summariseBucketsRaw', 'summariseBucketsRawSupplementary', 'summariseBucketsAggregate', 'migrateRawRequests', 'migrateRawImpressions', 'migrateRawClicks'));
     $oDal = new MockOX_Dal_Maintenance_Statistics_Test_5($this);
     $oDal->expectCallCount('summariseBucketsRaw', 3);
     $oDal->expectCallCount('summariseBucketsRawSupplementary', 3);
     $oDal->expectCallCount('summariseBucketsAggregate', 3);
     $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->expectAt(0, 'summariseBucketsRaw', array($aConf['table']['prefix'] . 'data_intermediate_ad_connection', $oComponent->getStatisticsMigration(), array('start' => $oStartDate, 'end' => $oEndDate)));
     $oStartDate = new Date('2008-08-28 08:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 10:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(1, 'summariseBucketsRaw', array($aConf['table']['prefix'] . 'data_intermediate_ad_connection', $oComponent->getStatisticsMigration(), array('start' => $oStartDate, 'end' => $oEndDate)));
     $oStartDate = new Date('2008-08-28 09:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 11:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(2, '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->expectAt(0, 'summariseBucketsRawSupplementary', array($aConf['table']['prefix'] . 'data_intermediate_ad_variable_value', $oComponent->getStatisticsMigration(), array('start' => $oStartDate, 'end' => $oEndDate)));
     $oStartDate = new Date('2008-08-28 08:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 10:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(1, 'summariseBucketsRawSupplementary', array($aConf['table']['prefix'] . 'data_intermediate_ad_variable_value', $oComponent->getStatisticsMigration(), array('start' => $oStartDate, 'end' => $oEndDate)));
     $oStartDate = new Date('2008-08-28 09:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 11:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(2, '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->expectAt(0, '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 11:01:00'")));
     $oStartDate = new Date('2008-08-28 08:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 10:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(1, '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 09:00:00'", 'interval_end' => "'2008-08-28 09:59:59'", 'creative_id' => 0, 'updated' => "'2008-08-28 11:01:00'")));
     $oStartDate = new Date('2008-08-28 09:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 11:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(2, '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 10:00:00'", 'interval_end' => "'2008-08-28 10:59:59'", 'creative_id' => 0, 'updated' => "'2008-08-28 11: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();
     // Test 6: Run, with plugins installed and with the migration required for multiple
     //         operation intervals + migration of raw data set to occur
     $doApplication_variable = OA_Dal::factoryDO('application_variable');
     $doApplication_variable->name = 'mse_process_raw';
     $doApplication_variable->value = '1';
     $doApplication_variable->insert();
     $oNowDate = new Date('2008-08-28 11: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 10:59:59');
     $oServiceLocator->register('Maintenance_Statistics_Controller', $oMaintenanceStatistics);
     Mock::generatePartial($oDalMaintenanceStatsticsClassName, 'MockOX_Dal_Maintenance_Statistics_Test_6', array('summariseBucketsRaw', 'summariseBucketsRawSupplementary', 'summariseBucketsAggregate', 'migrateRawRequests', 'migrateRawImpressions', 'migrateRawClicks'));
     $oDal = new MockOX_Dal_Maintenance_Statistics_Test_6($this);
     $oDal->expectCallCount('summariseBucketsRaw', 3);
     $oDal->expectCallCount('summariseBucketsRawSupplementary', 3);
     $oDal->expectCallCount('summariseBucketsAggregate', 3);
     $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->expectAt(0, 'summariseBucketsRaw', array($aConf['table']['prefix'] . 'data_intermediate_ad_connection', $oComponent->getStatisticsMigration(), array('start' => $oStartDate, 'end' => $oEndDate)));
     $oStartDate = new Date('2008-08-28 08:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 10:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(1, 'summariseBucketsRaw', array($aConf['table']['prefix'] . 'data_intermediate_ad_connection', $oComponent->getStatisticsMigration(), array('start' => $oStartDate, 'end' => $oEndDate)));
     $oStartDate = new Date('2008-08-28 09:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 11:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(2, '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->expectAt(0, 'summariseBucketsRawSupplementary', array($aConf['table']['prefix'] . 'data_intermediate_ad_variable_value', $oComponent->getStatisticsMigration(), array('start' => $oStartDate, 'end' => $oEndDate)));
     $oStartDate = new Date('2008-08-28 08:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 10:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(1, 'summariseBucketsRawSupplementary', array($aConf['table']['prefix'] . 'data_intermediate_ad_variable_value', $oComponent->getStatisticsMigration(), array('start' => $oStartDate, 'end' => $oEndDate)));
     $oStartDate = new Date('2008-08-28 09:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 11:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(2, '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->expectAt(0, '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 11:01:00'")));
     $oStartDate = new Date('2008-08-28 08:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 10:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(1, '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 09:00:00'", 'interval_end' => "'2008-08-28 09:59:59'", 'creative_id' => 0, 'updated' => "'2008-08-28 11:01:00'")));
     $oStartDate = new Date('2008-08-28 09:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 11:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(2, '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 10:00:00'", 'interval_end' => "'2008-08-28 10:59:59'", 'creative_id' => 0, 'updated' => "'2008-08-28 11:01:00'")));
     $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->expectAt(0, 'migrateRawRequests', array($oStartDate, $oEndDate));
     $oDal->expectAt(0, 'migrateRawImpressions', array($oStartDate, $oEndDate));
     $oDal->expectAt(0, 'migrateRawClicks', array($oStartDate, $oEndDate));
     $oStartDate = new Date('2008-08-28 08:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 10:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(1, 'migrateRawRequests', array($oStartDate, $oEndDate));
     $oDal->expectAt(1, 'migrateRawImpressions', array($oStartDate, $oEndDate));
     $oDal->expectAt(1, 'migrateRawClicks', array($oStartDate, $oEndDate));
     $oStartDate = new Date('2008-08-28 09:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 11:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(2, 'migrateRawRequests', array($oStartDate, $oEndDate));
     $oDal->expectAt(2, 'migrateRawImpressions', array($oStartDate, $oEndDate));
     $oDal->expectAt(2, 'migrateRawClicks', array($oStartDate, $oEndDate));
     $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();
     $doApplication_variable = OA_Dal::factoryDO('application_variable');
     $doApplication_variable->name = 'mse_process_raw';
     $doApplication_variable->value = '1';
     $doApplication_variable->find();
     $rows = $doApplication_variable->getRowCount();
     $this->assertEqual($rows, 0);
     // Uninstall the installed plugins
     TestEnv::uninstallPluginPackage('openXDeliveryLog', false);
     // Reset the testing environment
     TestEnv::restoreEnv();
 }
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;
        }
    }
}
 /**
  * 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;
             }
         }
     }
 }
Exemple #16
0
 /**
  * A method to return the forcast impressions for a zone, indexed by operation interval,
  * from the current operation interval through the past week. If no forecast stored in
  * the database, uses the defualt value from the configuration file.
  *
  * @param integer $zoneId The Zone ID.
  * @return mixed An array on success, false on failure. The array is of the format:
  *                   array(
  *                       [operation_interval_id] => array(
  *                                                      ['zone_id']               => zone_id,
  *                                                      ['forecast_impressions']  => forecast_impressions,
  *                                                      ['operation_interval_id'] => operation_interval_id
  *                                                  )
  *                       [operation_interval_id] => array(
  *                                                      ['zone_id']               => zone_id,
  *                                                      ['forecast_impressions']  => forecast_impressions,
  *                                                      ['operation_interval_id'] => operation_interval_id
  *                                                  )
  *                                   .
  *                                   .
  *                                   .
  *                   )
  */
 function getPreviousWeekZoneForcastImpressions($zoneId)
 {
     if (empty($zoneId) || !is_numeric($zoneId)) {
         OA::debug('Invalid zone ID argument', PEAR_LOG_ERR);
         return false;
     }
     $aConf = $GLOBALS['_MAX']['CONF'];
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oDate =& $oServiceLocator->get('now');
     if (!$oDate) {
         return false;
     }
     // Get the start and end ranges of the current week
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
     $oDateWeekStart = new Date();
     $oDateWeekStart->copy($aDates['end']);
     $oDateWeekStart->subtractSeconds(SECONDS_PER_WEEK - 1);
     $oDateWeekEnd = new Date();
     $oDateWeekEnd->copy($aDates['end']);
     // Select the zone forecasts from the database
     $tableName = $this->_getTablename('data_summary_zone_impression_history');
     $query = "\n            SELECT\n                zone_id AS zone_id,\n                forecast_impressions AS forecast_impressions,\n                operation_interval_id AS operation_interval_id,\n                interval_start AS interval_start,\n                interval_end AS interval_end\n            FROM\n                {$tableName}\n            WHERE\n                zone_id = {$zoneId}\n                AND operation_interval = {$aConf['maintenance']['operationInterval']}\n                AND interval_start >= '" . $oDateWeekStart->format('%Y-%m-%d %H:%M:%S') . "'\n                AND interval_end <= '" . $oDateWeekEnd->format('%Y-%m-%d %H:%M:%S') . "'\n                AND zone_id != 0\n            ORDER BY\n                interval_start";
     $rc = $this->oDbh->query($query);
     if (!PEAR::isError($rc)) {
         // Sort the results into an array indexed by the operation interval ID
         $aFinalResult = array();
         while ($aRow = $rc->fetchRow()) {
             $aFinalResult[$aRow['operation_interval_id']] = array('zone_id' => $aRow['zone_id'], 'forecast_impressions' => $aRow['forecast_impressions'], 'operation_interval_id' => $aRow['operation_interval_id']);
         }
     }
     // Check each operation interval ID has a forecast impression value,
     // and if not, set to the system default.
     for ($operationIntervalID = 0; $operationIntervalID < OX_OperationInterval::operationIntervalsPerWeek(); $operationIntervalID++) {
         if (!isset($aFinalResult[$operationIntervalID])) {
             $aFinalResult[$operationIntervalID] = array('zone_id' => $zoneId, 'forecast_impressions' => ZONE_FORECAST_DEFAULT_ZONE_IMPRESSIONS, 'operation_interval_id' => $operationIntervalID);
         }
     }
     return $aFinalResult;
 }
 /**
  * Tests that an e-mail reporting on impending campaign expiration
  * is able to be generated correctly.
  */
 function testSendAndPrepareCampaignImpendingExpiryEmail()
 {
     $adminContact = 'Andrew Hill';
     $adminName = 'OpenX Limited';
     $adminMail = '*****@*****.**';
     $adminCompany = 'Admin company name';
     $adminAccountId = 100;
     $agencyName = 'Agency Ltd.';
     $agencyContact = 'Mr. Foo Bar Agency';
     $agencyMail = '*****@*****.**';
     $advertiserName = 'Foo Client';
     $advertiserMail = '*****@*****.**';
     $advertiserUsername = '******';
     $aConf =& $GLOBALS['_MAX']['CONF'];
     $aConf['webpath']['admin'] = 'example.com';
     $aConf['email']['fromAddress'] = $adminMail;
     $aConf['email']['fromName'] = $adminName;
     $aConf['email']['fromCompany'] = $adminCompany;
     $aConf['email']['useManagerDetails'] = true;
     $aConf['email']['logOutgoing'] = true;
     $mockName = uniqid('PartialMockOA_Email_');
     Mock::generatePartial('OA_Email', $mockName, array('sendMail'));
     $oEmail = new $mockName();
     $oEmail->setReturnValue('sendMail', true);
     // Prepare valid test data
     $dateReason = 'date';
     $dateValue = '2007-05-15';
     $impReason = 'impressions';
     $impValue = 100;
     // The tests below assume that the number of days before a campaign expires when the
     $oCampaignDate = new Date($dateValue);
     $oCampaignDate->setHour(23);
     $oCampaignDate->setMinute(59);
     $oCampaignDate->setSecond(59);
     $oCampaignDate->toUTC();
     $oTwoDaysPriorDate = new Date($dateValue);
     $oTwoDaysPriorDate->subtractSeconds(2 * 24 * 60 * 60 - 10);
     $oNowDate = new Date($dateValue);
     // Prepare an admin user
     // Create the admin account
     $doAccounts = OA_Dal::factoryDO('accounts');
     $doAccounts->account_name = 'System Administrator';
     $doAccounts->account_type = OA_ACCOUNT_ADMIN;
     $adminAccountId = DataGenerator::generateOne($doAccounts);
     // Setup the admin account id
     $doAppVar = OA_Dal::factoryDO('application_variable');
     $doAppVar->name = 'admin_account_id';
     $doAppVar->value = $adminAccountId;
     // Create an user
     $doAdminUser = OA_Dal::factoryDO('users');
     $doAdminUser->contact_name = $adminContact;
     $doAdminUser->email_address = $adminMail;
     $doAdminUser->username = $adminName;
     $doAdminUser->password = md5('password');
     $doAdminUser->language = 'en';
     $doAdminUser->default_account_id = $adminAccountId;
     $adminUserId = DataGenerator::generateOne($doAdminUser);
     $doAdminUser = OA_Dal::staticGetDO('users', $adminUserId);
     $aAdminUser = $doAdminUser->toArray();
     // Create admin account-user association
     $doAUA = OA_Dal::factoryDO('account_user_assoc');
     $doAUA->account_id = $adminAccountId;
     $doAUA->user_id = $adminUserId;
     $doAUA->insert();
     // Prepare an agency
     $doAgency = OA_Dal::factoryDO('agency');
     $doAgency->name = $agencyName;
     $doAgency->contact = $agencyContact;
     $doAgency->email = $agencyMail;
     $agencyId = DataGenerator::generateOne($doAgency);
     $doAgency = OA_Dal::staticGetDO('agency', $agencyId);
     //get('agencyid', $agencyId);
     $agencyAccountId = $doAgency->account_id;
     // Prepare an agency user
     $doUser = OA_Dal::factoryDO('users');
     $doUser->contact_name = $agencyContact;
     $doUser->email_address = $agencyMail;
     $doUser->username = $agencyName;
     $doUser->language = 'en';
     $agencyUserId = DataGenerator::generateOne($doUser);
     $doAgencyUser = OA_Dal::staticGetDO('users', $agencyUserId);
     $aAgencyUser = $doAgencyUser->toArray();
     $oUserAccess = new OA_Admin_UI_UserAccess();
     // Agency user
     $oUserAccess->linkUserToAccount($agencyUserId, $doAgency->account_id, array(), array());
     // Generate an advertiser owned by the agency with no email adddress,
     // but no placements, and ensure false is returned
     $doClients = OA_Dal::factoryDO('clients');
     $doClients->agencyid = $agencyId;
     $doClients->clientname = $advertiserName;
     $doClients->email = '';
     $advertiserId1 = DataGenerator::generateOne($doClients);
     $doClients = OA_Dal::staticGetDO('clients', 'clientid', $advertiserId1);
     // ->get('clientid', $advertiserId1);
     $advertiserAccountId = $doClients->account_id;
     // Create an advertiser user
     $doUser = OA_Dal::factoryDO('users');
     $doUser->contact_name = $advertiserName;
     $doUser->email_address = $advertiserMail;
     $doUser->username = $advertiserUsername;
     $doUser->language = 'en';
     $userId = DataGenerator::generateOne($doUser);
     $doAdvertiserUser = OA_Dal::staticGetDO('users', $userId);
     $aAdvertiserUser = $doAdvertiserUser->toArray();
     // Link the advertiser user
     $oUserAccess->linkUserToAccount($userId, $doClients->account_id, array(), array());
     // Create a campaign
     $doPlacements = OA_Dal::factoryDO('campaigns');
     $doPlacements->clientid = $advertiserId1;
     $doPlacements->campaignname = 'Default Campaign';
     $doPlacements->views = 50;
     $doPlacements->expire_time = $oCampaignDate->getDate(DATE_FORMAT_ISO);
     $placementId = DataGenerator::generateOne($doPlacements);
     $doPlacements = OA_Dal::staticGetDO('campaigns', $placementId);
     $aCampaign = $doPlacements->toArray();
     $result = $oEmail->sendCampaignImpendingExpiryEmail($oNowDate, $placementId);
     // No emails should be sent yet because the preferences weren't set
     $this->assertEqual($result, 0);
     // No entries in userlog
     $doUserLog = OA_Dal::factoryDO('userlog');
     $doUserLog->find();
     $this->assertFalse($doUserLog->fetch());
     // Create the preference
     $doPreferences = OA_Dal::factoryDO('preferences');
     $doPreferences->preference_name = 'warn_email_admin';
     $doPreferences->account_type = OA_ACCOUNT_ADMIN;
     $warnEmailAdminPreferenceId = DataGenerator::generateOne($doPreferences);
     // Set the admin preference
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $adminAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailAdminPreferenceId;
     $doAccount_Preference_Assoc->value = 1;
     DataGenerator::generateOne($doAccount_Preference_Assoc);
     // Create the admin threshold preference
     $doPreferences = OA_Dal::factoryDO('preferences');
     $doPreferences->preference_name = 'warn_email_admin_impression_limit';
     $doPreferences->account_type = OA_ACCOUNT_ADMIN;
     $warnEmailAdminImpLimitPreferenceId = DataGenerator::generateOne($doPreferences);
     // Set the admin preference
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $adminAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailAdminImpLimitPreferenceId;
     $doAccount_Preference_Assoc->value = 100;
     DataGenerator::generateOne($doAccount_Preference_Assoc);
     // Create the admin day warning
     $doPreferences = OA_Dal::factoryDO('preferences');
     $doPreferences->preference_name = 'warn_email_admin_day_limit';
     $doPreferences->account_type = OA_ACCOUNT_ADMIN;
     $warnEmailAdminDayLimitPreferenceId = DataGenerator::generateOne($doPreferences);
     // Set the admin preference
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $adminAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailAdminDayLimitPreferenceId;
     $doAccount_Preference_Assoc->value = 2;
     DataGenerator::generateOne($doAccount_Preference_Assoc);
     // Set the agency preferences
     $doPreferences = OA_Dal::factoryDO('preferences');
     $doPreferences->preference_name = 'warn_email_manager';
     $doPreferences->account_type = OA_ACCOUNT_MANAGER;
     $warnEmailManagerPreferenceId = DataGenerator::generateOne($doPreferences);
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $agencyAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailManagerPreferenceId;
     $doAccount_Preference_Assoc->value = 0;
     DataGenerator::generateOne($doAccount_Preference_Assoc);
     $doPreferences = OA_Dal::factoryDO('preferences');
     $doPreferences->preference_name = 'warn_email_manager_impression_limit';
     $doPreferences->account_type = OA_ACCOUNT_MANAGER;
     $warnEmailManagerImpLimitPreferenceId = DataGenerator::generateOne($doPreferences);
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $agencyAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailManagerImpLimitPreferenceId;
     $doAccount_Preference_Assoc->value = 100;
     DataGenerator::generateOne($doAccount_Preference_Assoc);
     $doPreferences = OA_Dal::factoryDO('preferences');
     $doPreferences->preference_name = 'warn_email_manager_day_limit';
     $doPreferences->account_type = OA_ACCOUNT_MANAGER;
     $warnEmailManagerDayLimitPreferenceId = DataGenerator::generateOne($doPreferences);
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $agencyAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailManagerDayLimitPreferenceId;
     $doAccount_Preference_Assoc->value = 2;
     DataGenerator::generateOne($doAccount_Preference_Assoc);
     // Set the advertiser preferences
     $doPreferences = OA_Dal::factoryDO('preferences');
     $doPreferences->preference_name = 'warn_email_advertiser';
     $doPreferences->account_type = OA_ACCOUNT_ADVERTISER;
     $warnEmailAdvertiserPreferenceId = DataGenerator::generateOne($doPreferences);
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $advertiserAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailAdvertiserPreferenceId;
     $doAccount_Preference_Assoc->value = 0;
     DataGenerator::generateOne($doAccount_Preference_Assoc);
     $doPreferences = OA_Dal::factoryDO('preferences');
     $doPreferences->preference_name = 'warn_email_advertiser_impression_limit';
     $doPreferences->account_type = OA_ACCOUNT_ADVERTISER;
     $warnEmailAdvertiserImpLimitPreferenceId = DataGenerator::generateOne($doPreferences);
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $advertiserAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailAdvertiserImpLimitPreferenceId;
     $doAccount_Preference_Assoc->value = 100;
     DataGenerator::generateOne($doAccount_Preference_Assoc);
     $doPreferences = OA_Dal::factoryDO('preferences');
     $doPreferences->preference_name = 'warn_email_advertiser_day_limit';
     $doPreferences->account_type = OA_ACCOUNT_ADVERTISER;
     $warnEmailAdvertiserDayLimitPreferenceId = DataGenerator::generateOne($doPreferences);
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $advertiserAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailAdvertiserDayLimitPreferenceId;
     $doAccount_Preference_Assoc->value = 2;
     DataGenerator::generateOne($doAccount_Preference_Assoc);
     // Create another user linked to the advertiser account and ensure that an additional email is sent
     $doUser = OA_Dal::factoryDO('users');
     $doUser->contact_name = '2_' . $advertiserName;
     $doUser->email_address = '2_' . $advertiserMail;
     $doUser->username = '******' . $clientName;
     $doUser->language = 'de';
     $advertiserUserId2 = DataGenerator::generateOne($doUser);
     $doAdvertiserUser2 = OA_Dal::staticGetDO('users', $advertiserUserId2);
     $aAdvertiserUser2 = $doAdvertiserUser2->toArray();
     // Link the advertiser user
     $oUserAccess->linkUserToAccount($advertiserUserId2, $doClients->account_id, array(), array());
     // If the advertiser preference is off, then the advertiser should not be sent emails
     // even if the admin/manager preference is on
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $advertiserAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailAdvertiserPreferenceId;
     $doAccount_Preference_Assoc->value = 0;
     $doAccount_Preference_Assoc->update();
     // And turning off the manager preference should leave just agency emails (2)
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $agencyAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailManagerPreferenceId;
     $doAccount_Preference_Assoc->value = 0;
     $doAccount_Preference_Assoc->update();
     // -- The above sets up the environment for the tests below -- //
     // Check the body when passing in the admin user:
     $expectedSubject = "Impending campaign expiration: {$advertiserName}";
     $expectedContents = "Dear {$adminContact},\n\n";
     $expectedContents .= "The campaign belonging to {$advertiserName} shown below is due to end on {$dateValue}.\n\n";
     $expectedContents .= "As a result, the campaign will soon be automatically disabled, and the\n";
     $expectedContents .= "following banners in the campaign will also be disabled:\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "-------------------------------------------------------\n\n";
     $expectedContents .= " There are currently no banners defined for this campaign.\n\n";
     $expectedContents .= "-------------------------------------------------------\n\n\n";
     $expectedContents .= "Regards,\n   {$adminName}, {$adminCompany}";
     // Clear cache
     $oEmail->clearCache();
     Language_Loader::load('default', $aAdminUser['language']);
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oTwoDaysPriorDate, $placementId);
     $aResult = $oEmail->prepareCampaignImpendingExpiryEmail($aAdminUser, $advertiserId1, $placementId, $dateReason, $dateValue, 'admin');
     $this->assertEqual($numSent, 1);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     // One entry in userlog
     $doUserLog = OA_Dal::factoryDO('userlog');
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 1);
     $this->assertEqual($aUserLog[0]['action'], phpAds_actionWarningMailed);
     // Turn off email logging and send mail again
     $aConf['email']['logOutgoing'] = false;
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oTwoDaysPriorDate, $placementId);
     $this->assertEqual($numSent, 1);
     // Still one entry in userlog
     $doUserLog = OA_Dal::factoryDO('userlog');
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 1);
     // Set email logging back to true
     $aConf['email']['logOutgoing'] = true;
     // Manager user
     $expectedSubject = "Impending campaign expiration: {$advertiserName}";
     $expectedContents = "Dear {$aAgencyUser['contact_name']},\n\n";
     $expectedContents .= "The campaign belonging to {$advertiserName} shown below is due to end on {$dateValue}.\n\n";
     $expectedContents .= "As a result, the campaign will soon be automatically disabled, and the\n";
     $expectedContents .= "following banners in the campaign will also be disabled:\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "-------------------------------------------------------\n\n";
     $expectedContents .= " There are currently no banners defined for this campaign.\n\n";
     $expectedContents .= "-------------------------------------------------------\n\n\n";
     $expectedContents .= "Regards,\n   " . $aConf['email']['fromName'] . ", " . $aConf['email']['fromCompany'];
     Language_Loader::load('default', $aAgencyUser['language']);
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oTwoDaysPriorDate, $placementId);
     $aResult = $oEmail->prepareCampaignImpendingExpiryEmail($aAgencyUser, $advertiserId1, $placementId, $dateReason, $dateValue, 'manager');
     $this->assertEqual($numSent, 1);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     // Should create another entry in userlog
     $doUserLog = OA_Dal::factoryDO('userlog');
     $doUserLog->action = phpAds_actionWarningMailed;
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 2);
     // Use email from details instead of the owning account's details
     $aConf['email']['useManagerDetails'] = false;
     // Manager user
     $expectedSubject = "Impending campaign expiration: {$advertiserName}";
     $expectedContents = "Dear {$aAgencyUser['contact_name']},\n\n";
     $expectedContents .= "The campaign belonging to {$advertiserName} shown below is due to end on {$dateValue}.\n\n";
     $expectedContents .= "As a result, the campaign will soon be automatically disabled, and the\n";
     $expectedContents .= "following banners in the campaign will also be disabled:\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "-------------------------------------------------------\n\n";
     $expectedContents .= " There are currently no banners defined for this campaign.\n\n";
     $expectedContents .= "-------------------------------------------------------\n\n\n";
     $expectedContents .= "Regards,\n   " . $aConf['email']['fromName'] . ", " . $aConf['email']['fromCompany'];
     Language_Loader::load('default', $aAgencyUser['language']);
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oTwoDaysPriorDate, $placementId);
     $aResult = $oEmail->prepareCampaignImpendingExpiryEmail($aAgencyUser, $advertiserId1, $placementId, $dateReason, $dateValue, 'manager');
     $this->assertEqual($numSent, 1);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     // Use email from empty details and test that not Regards are added
     $aConf['email']['fromAddress'] = '';
     $aConf['email']['fromName'] = '';
     $aConf['email']['fromCompany'] = '';
     // Manager user
     $expectedSubject = "Impending campaign expiration: {$advertiserName}";
     $expectedContents = "Dear {$aAgencyUser['contact_name']},\n\n";
     $expectedContents .= "The campaign belonging to {$advertiserName} shown below is due to end on {$dateValue}.\n\n";
     $expectedContents .= "As a result, the campaign will soon be automatically disabled, and the\n";
     $expectedContents .= "following banners in the campaign will also be disabled:\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "-------------------------------------------------------\n\n";
     $expectedContents .= " There are currently no banners defined for this campaign.\n\n";
     $expectedContents .= "-------------------------------------------------------\n\n\n";
     Language_Loader::load('default', $aAgencyUser['language']);
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oTwoDaysPriorDate, $placementId);
     $aResult = $oEmail->prepareCampaignImpendingExpiryEmail($aAgencyUser, $advertiserId1, $placementId, $dateReason, $dateValue, 'manager');
     $this->assertEqual($numSent, 1);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     $aConf['email']['useManagerDetails'] = true;
     $aConf['email']['fromAddress'] = $adminMail;
     $aConf['email']['fromName'] = $adminName;
     $aConf['email']['fromCompany'] = $adminCompany;
     // Should create another entry in userlog
     $doUserLog = OA_Dal::factoryDO('userlog');
     $doUserLog->action = phpAds_actionWarningMailed;
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 4);
     // The following should never be sent because a campaign without banners should never deliver (and therefore never reach the "remaining" threshold)
     $expectedSubject = "Impending campaign expiration: {$advertiserName}";
     $expectedContents = "Dear {$aAdminUser['contact_name']},\n\n";
     $expectedContents .= "The campaign belonging to {$advertiserName} shown below has less than {$impValue} impressions remaining.\n\n";
     $expectedContents .= "As a result, the campaign will soon be automatically disabled, and the\n";
     $expectedContents .= "following banners in the campaign will also be disabled:\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "-------------------------------------------------------\n\n";
     $expectedContents .= " There are currently no banners defined for this campaign.\n\n";
     $expectedContents .= "-------------------------------------------------------\n\n\n";
     $expectedContents .= "Regards,\n   {$adminName}, {$adminCompany}";
     Language_Loader::load('default', $aAdminUser['language']);
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oNowDate, $placementId);
     $aResult = $oEmail->prepareCampaignImpendingExpiryEmail($aAdminUser, $advertiserId1, $placementId, $impReason, $impValue, 'admin');
     $this->assertEqual($numSent, 0);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     $expectedSubject = "Impending campaign expiration: {$advertiserName}";
     $expectedContents = "Dear {$aAgencyUser['contact_name']},\n\n";
     $expectedContents .= "The campaign belonging to {$advertiserName} shown below has less than {$impValue} impressions remaining.\n\n";
     $expectedContents .= "As a result, the campaign will soon be automatically disabled, and the\n";
     $expectedContents .= "following banners in the campaign will also be disabled:\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "-------------------------------------------------------\n\n";
     $expectedContents .= " There are currently no banners defined for this campaign.\n\n";
     $expectedContents .= "-------------------------------------------------------\n\n\n";
     $expectedContents .= "Regards,\n   " . $aConf['email']['fromName'] . ", " . $aConf['email']['fromCompany'];
     Language_Loader::load('default', $aAgencyUser['language']);
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oNowDate, $placementId);
     $aResult = $oEmail->prepareCampaignImpendingExpiryEmail($aAgencyUser, $advertiserId1, $placementId, $impReason, $impValue, 'manager');
     $this->assertEqual($numSent, 0);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     // Emails not sent, nothing new in userlog
     $doUserLog = OA_Dal::factoryDO('userlog');
     $doUserLog->action = phpAds_actionWarningMailed;
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 4);
     // Add some banners and retest
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $placementId;
     $doBanners->description = 'Test Banner';
     $doBanners->url = '';
     $bannerId1 = DataGenerator::generateOne($doBanners);
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $placementId;
     $doBanners->description = 'Test Banner';
     $doBanners->url = 'http://www.fornax.net/';
     $bannerId2 = DataGenerator::generateOne($doBanners);
     $expectedSubject = "Impending campaign expiration: {$advertiserName}";
     $expectedContents = "Dear {$aAdminUser['contact_name']},\n\n";
     $expectedContents .= "The campaign belonging to {$advertiserName} shown below is due to end on {$dateValue}.\n\n";
     $expectedContents .= "As a result, the campaign will soon be automatically disabled, and the\n";
     $expectedContents .= "following banners in the campaign will also be disabled:\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "-------------------------------------------------------\n\n";
     $expectedContents .= " Banner [id{$bannerId1}] Test Banner\n\n";
     $expectedContents .= " Banner [id{$bannerId2}] Test Banner\n";
     $expectedContents .= "  linked to: http://www.fornax.net/\n\n";
     $expectedContents .= "-------------------------------------------------------\n\n\n";
     $expectedContents .= "Regards,\n   {$adminName}, {$adminCompany}";
     Language_Loader::load('default', $aAdminUser['language']);
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oTwoDaysPriorDate, $placementId);
     $aResult = $oEmail->prepareCampaignImpendingExpiryEmail($aAdminUser, $advertiserId1, $placementId1, $dateReason, $dateValue, 'admin');
     $this->assertEqual($numSent, 1);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     $doUserLog = OA_Dal::factoryDO('userlog');
     $doUserLog->action = phpAds_actionWarningMailed;
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 5);
     $expectedSubject = "Impending campaign expiration: {$advertiserName}";
     $expectedContents = "Dear {$aAdvertiserUser['contact_name']},\n\n";
     $expectedContents .= "Your campaign shown below is due to end on {$dateValue}.\n\n";
     $expectedContents .= "As a result, the campaign will soon be automatically disabled, and the\n";
     $expectedContents .= "following banners in the campaign will also be disabled:\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "-------------------------------------------------------\n\n";
     $expectedContents .= " Banner [id{$bannerId1}] Test Banner\n\n";
     $expectedContents .= " Banner [id{$bannerId2}] Test Banner\n";
     $expectedContents .= "  linked to: http://www.fornax.net/\n\n";
     $expectedContents .= "-------------------------------------------------------\n\n\n";
     $expectedContents .= "Regards,\n   {$agencyContact}, {$agencyName}";
     Language_Loader::load('default', $aAdvertiserUser['language']);
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oTwoDaysPriorDate, $placementId);
     $aResult = $oEmail->prepareCampaignImpendingExpiryEmail($aAdvertiserUser, $advertiserId1, $placementId, $dateReason, $dateValue, 'advertiser');
     $this->assertEqual($numSent, 1);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     $doUserLog = OA_Dal::factoryDO('userlog');
     $doUserLog->action = phpAds_actionWarningMailed;
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 6);
     // Clear userlog table
     $doUserLog = OA_Dal::factoryDO('userlog');
     $doUserLog->whereAdd('1=1');
     $doUserLog->delete(DB_DATAOBJECT_WHEREADD_ONLY);
     // Enable the warn_email_advertiser preference and retest
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $advertiserAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailAdvertiserPreferenceId;
     $doAccount_Preference_Assoc->value = 1;
     $doAccount_Preference_Assoc->update();
     // Clear cache
     $oEmail->clearCache();
     // So should now send 1 admin and 2 advertiser emails
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oTwoDaysPriorDate, $placementId);
     $this->assertEqual($numSent, 3);
     $doUserLog = OA_Dal::factoryDO('userlog');
     $doUserLog->action = phpAds_actionWarningMailed;
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 3);
     $expectedSubject = "Impending campaign expiration: {$advertiserName}";
     $expectedContents = "Dear {$adminContact},\n\n";
     $expectedContents .= "The campaign belonging to {$advertiserName} shown below has less than {$impValue} impressions remaining.\n\n";
     $expectedContents .= "As a result, the campaign will soon be automatically disabled, and the\n";
     $expectedContents .= "following banners in the campaign will also be disabled:\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "-------------------------------------------------------\n\n";
     $expectedContents .= " Banner [id{$bannerId1}] Test Banner\n\n";
     $expectedContents .= " Banner [id{$bannerId2}] Test Banner\n";
     $expectedContents .= "  linked to: http://www.fornax.net/\n\n";
     $expectedContents .= "-------------------------------------------------------\n\n\n";
     $expectedContents .= "Regards,\n   {$adminName}, {$adminCompany}";
     $aResult = $oEmail->prepareCampaignImpendingExpiryEmail($aAdminUser, $advertiserId1, $placementId, $impReason, $impValue, 'admin');
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oTwoDaysPriorDate, $placementId);
     $this->assertEqual($numSent, 3);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     $doUserLog = OA_Dal::factoryDO('userlog');
     $doUserLog->action = phpAds_actionWarningMailed;
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 6);
     // Clear cache
     $oEmail->clearCache();
     // Enable the warn_email_manager preference and retest
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $agencyAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailManagerPreferenceId;
     $doAccount_Preference_Assoc->value = 1;
     $doAccount_Preference_Assoc->update();
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oTwoDaysPriorDate, $placementId);
     $this->assertEqual($numSent, 4);
     $doUserLog = OA_Dal::factoryDO('userlog');
     $doUserLog->action = phpAds_actionWarningMailed;
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 10);
     // Turn off email logging and send mail again
     $aConf['email']['logOutgoing'] = false;
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oTwoDaysPriorDate, $placementId);
     $this->assertEqual($numSent, 4);
     // No new entries in user log
     $doUserLog = OA_Dal::factoryDO('userlog');
     $doUserLog->action = phpAds_actionWarningMailed;
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 10);
     // Set email logging back to true
     $aConf['email']['logOutgoing'] = true;
     $expectedSubject = "Impending campaign expiration: {$advertiserName}";
     $expectedContents = "Dear {$aAdvertiserUser['contact_name']},\n\n";
     $expectedContents .= "Your campaign shown below has less than {$impValue} impressions remaining.\n\n";
     $expectedContents .= "As a result, the campaign will soon be automatically disabled, and the\n";
     $expectedContents .= "following banners in the campaign will also be disabled:\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "-------------------------------------------------------\n\n";
     $expectedContents .= " Banner [id{$bannerId1}] Test Banner\n\n";
     $expectedContents .= " Banner [id{$bannerId2}] Test Banner\n";
     $expectedContents .= "  linked to: http://www.fornax.net/\n\n";
     $expectedContents .= "-------------------------------------------------------\n\n\n";
     $expectedContents .= "Regards,\n   {$agencyContact}, {$agencyName}";
     $aResult = $oEmail->prepareCampaignImpendingExpiryEmail($aAdvertiserUser, $advertiserId1, $placementId, $impReason, $impValue, 'advertiser');
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     // Check that advertiser2's email is send in their desired language (german)
     $expectedSubject = "Bevorstehende Deaktivierung der Kampagne: {$advertiserName}";
     $expectedContents = "Sehr geehrte(r) {$aAdvertiserUser2['contact_name']},\n\n";
     $expectedContents .= "Unten angegebene Ihre Kampagne hat weniger als {$impValue} Impressions übrig.\n\n";
     $expectedContents .= "Auf Grund dessen wird die Kampagne bald deaktiviert und weiter unten angegebene Banner aus dieser Kampagne werden deaktiviert:\n";
     $expectedContents .= "\nKampagne [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "-------------------------------------------------------\n\n";
     $expectedContents .= " Banner [id{$bannerId1}] Test Banner\n\n";
     $expectedContents .= " Banner [id{$bannerId2}] Test Banner\n";
     $expectedContents .= "  verknüpft mit: http://www.fornax.net/\n\n";
     $expectedContents .= "-------------------------------------------------------\n\n\n";
     $expectedContents .= "Mit freundlichem Gruß\n   {$agencyContact}, {$agencyName}";
     $aResult = $oEmail->prepareCampaignImpendingExpiryEmail($aAdvertiserUser2, $advertiserId1, $placementId, $impReason, $impValue, 'advertiser');
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     DataGenerator::cleanUp(array('accounts', 'account_user_assoc'));
 }
 public function _commonTest($oMaxDalMaintenance, $priority)
 {
     $oNow = new Date();
     $doClients = OA_Dal::factoryDO('clients');
     $idClient = DataGenerator::generateOne($doClients, true);
     $agencyId1 = DataGenerator::getReferenceId('agency');
     // Test 1
     $result = $oMaxDalMaintenance->getAgencyCampaignsDeliveriesToDate($agencyId1);
     $this->assertTrue(is_array($result));
     $this->assertEqual(count($result), 0);
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->status = OA_ENTITY_STATUS_RUNNING;
     $doCampaigns->clientid = $idClient;
     $oYesterday = new Date();
     $oYesterday->subtractSeconds(86400);
     $oTomorrow = new Date();
     $oTomorrow->addSeconds(86400);
     $doCampaigns->activate_time = $oYesterday->format('%Y-%m-%d %H:%M:%S');
     $doCampaigns->expire_time = $oTomorrow->format('%Y-%m-%d %H:%M:%S');
     $doCampaigns->priority = '1';
     $doCampaigns->active = 1;
     $doCampaigns->views = 100;
     $doCampaigns->clicks = 200;
     $doCampaigns->conversions = 300;
     $doCampaigns->updated = $oNow->format('%Y-%m-%d %H:%M:%S');
     $idCampaign = DataGenerator::generateOne($doCampaigns);
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $idCampaign;
     $doBanners->active = 1;
     $doBanners->status = OA_ENTITY_STATUS_RUNNING;
     $doBanners->acls_updated = $oNow->format('%Y-%m-%d %H:%M:%S');
     $doBanners->updated = $oNow->format('%Y-%m-%d %H:%M:%S');
     $idBanner = DataGenerator::generateOne($doBanners);
     $doInterAd = OA_Dal::factoryDO('data_intermediate_ad');
     $doInterAd->operation_interval = 60;
     $doInterAd->operation_interval_id = 0;
     $doInterAd->ad_id = $idBanner;
     $doInterAd->day = '2005-06-24';
     $doInterAd->creative_id = 0;
     $doInterAd->zone_id = 1;
     $doInterAd->requests = 500;
     $doInterAd->impressions = 475;
     $doInterAd->clicks = 25;
     $doInterAd->conversions = 5;
     $doInterAd->updated = $oNow->format('%Y-%m-%d %H:%M:%S');
     $doInterAd->interval_start = '2005-06-24 10:00:00';
     $doInterAd->date_time = '2005-06-24 10:00:00';
     $doInterAd->interval_end = '2005-06-24 10:59:59';
     $doInterAd->hour = 10;
     $idInterAd = DataGenerator::generateOne($doInterAd);
     $doInterAd->interval_start = '2005-06-24 11:00:00';
     $doInterAd->date_time = '2005-06-24 11:00:00';
     $doInterAd->interval_end = '2005-06-24 11:59:59';
     $doInterAd->hour = 11;
     $idInterAd = DataGenerator::generateOne($doInterAd);
     $result = $oMaxDalMaintenance->getAgencyCampaignsDeliveriesToDate($agencyId1);
     $this->assertTrue(is_array($result));
     $this->assertEqual(count($result), 1);
     foreach ($result as $id => $data) {
         $this->assertEqual($idCampaign, $id);
     }
     $this->assertEqual($result[$idCampaign]['sum_impressions'], 950);
     $this->assertEqual($result[$idCampaign]['sum_clicks'], 50);
     $this->assertEqual($result[$idCampaign]['sum_conversions'], 10);
     // Test 3
     $doClients = OA_Dal::factoryDO('clients');
     $idClient2 = DataGenerator::generateOne($doClients, true);
     $agencyId2 = DataGenerator::getReferenceId('agency');
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->clientid = $idClient2;
     $doCampaigns->priority = $priority;
     $doCampaigns->ecpm_enabled = 1;
     $doCampaigns->status = OA_ENTITY_STATUS_RUNNING;
     $doCampaigns->revenue_type = MAX_FINANCE_CPC;
     $this->idCampaign2 = DataGenerator::generateOne($doCampaigns);
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $this->idCampaign2;
     $doBanners->status = OA_ENTITY_STATUS_RUNNING;
     $idBanner2 = DataGenerator::generateOne($doBanners);
     $doInterAd->ad_id = $idBanner2;
     $idInterAd = DataGenerator::generateOne($doInterAd);
     // Check that results for agency 1 are still the same
     $result = $oMaxDalMaintenance->getAgencyCampaignsDeliveriesToDate($agencyId1);
     $this->assertTrue(is_array($result));
     $this->assertEqual(count($result), 1);
     foreach ($result as $id => $data) {
         $this->assertEqual($idCampaign, $id);
     }
     $this->assertEqual($result[$idCampaign]['sum_impressions'], 950);
     $this->assertEqual($result[$idCampaign]['sum_clicks'], 50);
     $this->assertEqual($result[$idCampaign]['sum_conversions'], 10);
     // Check results for agency 2
     $result = $oMaxDalMaintenance->getAgencyCampaignsDeliveriesToDate($agencyId2);
     $this->assertTrue(is_array($result));
     $this->assertEqual(count($result), 1);
     foreach ($result as $id => $data) {
         $this->assertEqual($this->idCampaign2, $id);
     }
     $this->assertEqual($result[$this->idCampaign2]['sum_impressions'], 475);
     $this->assertEqual($result[$this->idCampaign2]['sum_clicks'], 25);
     $this->assertEqual($result[$this->idCampaign2]['sum_conversions'], 5);
     return array($agencyId1, $agencyId2);
 }
 /**
  * A method to convert a Date into an array containing the start
  * and end Dates of the operation interval before the operation
  * interval that the date is in.
  *
  * @static
  * @param Date $oDate The date to convert.
  * @param integer $operationInterval Optional length of the operation interval
  *                                   in minutes. If not given, will use the
  *                                   currently defined operation interval.
  * @return array An array of the start and end Dates of the operation interval.
  */
 function convertDateToPreviousOperationIntervalStartAndEndDates($oDate, $operationInterval = 0)
 {
     // Get the start and end Dates of the operation interval that
     // contains the current date
     $aResult = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate, $operationInterval);
     // Subtract one second from the start Date
     $oNewDate = new Date();
     $oNewDate->copy($aResult['start']);
     $oNewDate->subtractSeconds(1);
     // Return the result from the new date
     return OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oNewDate, $operationInterval);
 }
Exemple #20
0
 /**
  * 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;
 }
 function testDeleteUnverifiedUsers()
 {
     DataGenerator::cleanUp();
     $doUsers = OA_Dal::factoryDO('users');
     $cExistingUsers = $doUsers->count();
     // this user was created recently
     $doUsers = OA_Dal::factoryDO('users');
     $date = new Date();
     $date->subtractSeconds(SECONDS_PER_DAY);
     $doUsers->date_created = $doUsers->formatDate($date);
     $this->createUser($doUsers);
     // this user was created over a month ago - should be deleted
     $overMonthAgoSeconds = 31 * SECONDS_PER_DAY;
     $doUsers = OA_Dal::factoryDO('users');
     $date->subtractSeconds($overMonthAgoSeconds);
     $doUsers->date_created = $doUsers->formatDate($date);
     $this->createUser($doUsers);
     // this was created over a month ago but is verified
     $doUsers = OA_Dal::factoryDO('users');
     $date = new Date();
     $date->subtractSeconds($overMonthAgoSeconds);
     $doUsers->date_created = $doUsers->formatDate($date);
     $doUsers->sso_user_id = 123;
     $this->createUser($doUsers);
     $doUsers = OA_Dal::factoryDO('users');
     $this->assertEqual($doUsers->count(), 3 + $cExistingUsers);
     $doUsers = OA_Dal::factoryDO('users');
     $doUsers->deleteUnverifiedUsers(28 * SECONDS_PER_DAY);
     // check if one record was deleted
     $doUsers = OA_Dal::factoryDO('users');
     $this->assertEqual($doUsers->count(), 2 + $cExistingUsers);
 }
 /**
  * Returns an array of conversions.
  *
  * @param array $aParams
  * @return array
  */
 function getConversions($aParams)
 {
     $conf = $GLOBALS['_MAX']['CONF'];
     $oDbh =& OA_DB::singleton();
     $where = '';
     if (!empty($aParams['day'])) {
         $aParams['day_begin'] = $aParams['day_end'] = $aParams['day'];
     }
     if (!empty($aParams['day_begin'])) {
         $oStart = new Date($aParams['day_begin']);
         $oStart->setHour(0);
         $oStart->setMinute(0);
         $oStart->setSecond(0);
         $oStart->toUTC();
         $where .= ' AND ac.tracker_date_time >= ' . $oDbh->quote($oStart->format('%Y-%m-%d %H:%M:%S'), 'timestamp');
     }
     if (!empty($aParams['day_end'])) {
         $oEnd = new Date($aParams['day_end']);
         $oEnd->setHour(23);
         $oEnd->setMinute(59);
         $oEnd->setSecond(59);
         $oEnd->toUTC();
         $where .= ' AND ac.tracker_date_time <= ' . $oDbh->quote($oEnd->format('%Y-%m-%d %H:%M:%S'), 'timestamp');
     }
     if (!empty($aParams['month'])) {
         $oStart = new Date("{$aParams['month']}-01");
         $oStart->setHour(0);
         $oStart->setMinute(0);
         $oStart->setSecond(0);
         $oEnd = new Date(Date_Calc::beginOfNextMonth($oStart->getDay(), $oStart->getMonth, $oStart->getYear(), '%Y-%m-%d'));
         $oEnd->setHour(0);
         $oEnd->setMinute(0);
         $oEnd->setSecond(0);
         $oEnd->subtractSeconds(1);
         $oStart->toUTC();
         $oEnd->toUTC();
         $where .= ' AND ac.tracker_date_time >= ' . $oDbh->quote($oStart->format('%Y-%m-%d %H:%M:%S'), 'timestamp');
         $where .= ' AND ac.tracker_date_time <= ' . $oDbh->quote($oEnd->format('%Y-%m-%d %H:%M:%S'), 'timestamp');
     }
     if (!empty($aParams['day_hour'])) {
         $oStart = new Date("{$aParams['day_hour']}:00:00");
         $oStart->setMinute(0);
         $oStart->setSecond(0);
         $oEnd = new Date($oStart);
         $oStart->setMinute(59);
         $oStart->setSecond(59);
         $where .= ' AND ac.tracker_date_time >= ' . $oDbh->quote($oStart->format('%Y-%m-%d %H:%M:%S'), 'timestamp');
         $where .= ' AND ac.tracker_date_time <= ' . $oDbh->quote($oEnd->format('%Y-%m-%d %H:%M:%S'), 'timestamp');
     }
     if (!empty($aParams['agency_id'])) {
         $where .= ' AND c.agencyid=' . $oDbh->quote($aParams['agency_id'], 'integer');
     }
     if (!empty($aParams['clientid'])) {
         $where .= ' AND c.clientid=' . $oDbh->quote($aParams['clientid'], 'integer');
     }
     if (isset($aParams['zonesIds'])) {
         $where .= ' AND ac.zone_id IN (' . $oDbh->escape(implode(',', $aParams['zonesIds'])) . ")";
     }
     if (!empty($aParams['campaignid'])) {
         $where .= ' AND m.campaignid=' . $oDbh->quote($aParams['campaignid'], 'integer');
     }
     if (!empty($aParams['bannerid'])) {
         $where .= ' AND d.bannerid=' . $oDbh->quote($aParams['bannerid'], 'integer');
     }
     if (!empty($aParams['statuses'])) {
         $where .= ' AND ac.connection_status IN (' . $oDbh->escape(implode(',', $aParams['statuses'])) . ')';
     }
     if (isset($aParams['startRecord']) && is_numeric($aParams['startRecord']) && is_numeric($aParams['perPage'])) {
         $limit = ' LIMIT ' . $oDbh->quote($aParams['perPage'], 'text', false) . ' OFFSET ' . $oDbh->quote($aParams['startRecord'], 'text', false);
     } elseif (!empty($aParams['perPage'])) {
         $limit = ' LIMIT ' . $oDbh->quote($aParams['perPage'], 'integer', false) . ' OFFSET 0';
     } else {
         $limit = '';
     }
     $query = "SELECT\n            ac.data_intermediate_ad_connection_id as connection_id,\n            c.clientid,\n            m.campaignid,\n            m.campaignname AS campaignname,\n            ac.tracker_id as tracker_id,\n            ac.connection_status,\n            ac.connection_date_time AS connection_date_time,\n            ac.tracker_date_time as date_time,\n            t.trackername,\n            ac.tracker_ip_address,\n            ac.tracker_country,\n            ac.connection_action,\n            t.type AS connection_type,\n            ac.tracker_country,\n            ac.ad_id,\n            ac.creative_id,\n            ac.zone_id,\n            ac.comments\n        FROM\n            {$conf['table']['prefix']}{$conf['table']['clients']} AS c,\n            {$conf['table']['prefix']}{$conf['table']['data_intermediate_ad_connection']} AS ac,\n            {$conf['table']['prefix']}{$conf['table']['banners']} AS d,\n            {$conf['table']['prefix']}{$conf['table']['campaigns']} AS m,\n            {$conf['table']['prefix']}{$conf['table']['trackers']} AS t\n        WHERE\n            c.clientid=m.clientid\n            AND m.campaignid=d.campaignid\n            AND d.bannerid=ac.ad_id\n            AND t.trackerid=ac.tracker_id\n            AND ac.inside_window = 1\n            " . $where . "\n        ORDER BY\n            ac.tracker_date_time\n        {$limit}";
     $aStats = $oDbh->queryAll($query, null, MDB2_FETCHMODE_DEFAULT, true);
     $oNow = new Date();
     foreach (array_keys($aStats) as $k) {
         $oDate = new Date($aStats[$k]['date_time']);
         $oDate->setTZbyID('UTC');
         $oDate->convertTZ($oNow->tz);
         $aStats[$k]['date_time'] = $oDate->format('%Y-%m-%d %H:%M:%S');
         $oDate = new Date($aStats[$k]['connection_date_time']);
         $oDate->setTZbyID('UTC');
         $oDate->convertTZ($oNow->tz);
         $aStats[$k]['connection_date_time'] = $oDate->format('%Y-%m-%d %H:%M:%S');
     }
     return $aStats;
 }
 /**
  * A private method to run the "midnight" general pruning tasks.
  *
  * @access private
  */
 function _runGeneralPruning()
 {
     if (empty($GLOBALS['_MAX']['CONF']['maintenance']['pruneDataTables'])) {
         return;
     }
     // Calculate the date before which it is valid to prune data
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oNowDate =& $oServiceLocator->get('now');
     if (is_null($oNowDate) || !is_a($oNowDate, 'Date')) {
         return;
     }
     $oPruneDate = new Date();
     $oPruneDate->copy($oNowDate);
     $oPruneDate->subtractSeconds(OA_MAINTENANCE_FIXED_PRUNING * SECONDS_PER_DAY);
     $oFormattedPruneDate = $this->oDbh->quote($oPruneDate->format('%Y-%m-%d %H:%M:%S'), 'timestamp');
     $oFormattedPruneTimestamp = $this->oDbh->quote($oPruneDate->getTime(), 'integer');
     // Prune old data from the log_maintenance_statistics table
     $doLog_maintenance_statistics = OA_Dal::factoryDO('log_maintenance_statistics');
     $doLog_maintenance_statistics->whereAdd("start_run < {$oFormattedPruneDate}");
     $doLog_maintenance_statistics->delete(true);
     // Prune old data from the log_maintenance_priority table
     $doLog_maintenance_priority = OA_Dal::factoryDO('log_maintenance_priority');
     $doLog_maintenance_priority->whereAdd("start_run < {$oFormattedPruneDate}");
     $doLog_maintenance_priority->delete(true);
     // Prune old data from the userlog table
     $doUserlog = OA_Dal::factoryDO('userlog');
     $doUserlog->whereAdd("timestamp < {$oFormattedPruneTimestamp}");
     $doUserlog->delete(true);
 }
 /**
  * A method to return the forecast impressions for a zone, indexed by operation interval,
  * from the current operation interval through the past week. If no forecast stored in
  * the database for a given OI, uses average of forecasts found.
  *
  * @param integer $zoneId The Zone ID.
  * @return mixed An array on success, false on failure. The array is of the format:
  *                   array(
  *                       [operation_interval_id] => array(
  *                                                      ['zone_id']               => zone_id,
  *                                                      ['_impressions']  => forecast_impressions,
  *                                                      ['operation_interval_id'] => operation_interval_id
  *                                                  )
  *                       [operation_interval_id] => array(
  *                                                      ['zone_id']               => zone_id,
  *                                                      ['forecast_impressions']  => forecast_impressions,
  *                                                      ['operation_interval_id'] => operation_interval_id
  *                                                  )
  *                                   .
  *                                   .
  *                                   .
  *                   )
  */
 function getPreviousWeekZoneForcastImpressions($zoneId)
 {
     if (empty($zoneId) || !is_numeric($zoneId)) {
         OA::debug('Invalid zone ID argument', PEAR_LOG_ERR);
         return false;
     }
     $aConf = $GLOBALS['_MAX']['CONF'];
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oDate =& $oServiceLocator->get('now');
     if (!$oDate) {
         return false;
     }
     // Get previous OI
     $oPreviousOI = new Date($oDate);
     $oPreviousOI->subtractSeconds(OX_OperationInterval::getOperationInterval() * 60);
     // Get the start and end ranges of the current week, up to the previous OI
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oPreviousOI);
     $oDateWeekStart = new Date();
     $oDateWeekStart->copy($aDates['end']);
     $oDateWeekStart->subtractSeconds(SECONDS_PER_WEEK - 1);
     $oDateWeekEnd = new Date();
     $oDateWeekEnd->copy($aDates['end']);
     // Select the zone forecasts from the database
     $tableName = $this->_getTablename('data_intermediate_ad');
     $oneHourInterval = OA_Dal::quoteInterval(1, 'hour');
     $query = "\n            SELECT\n                SUM(impressions) AS forecast_impressions,\n                operation_interval_id AS operation_interval_id,\n                interval_start AS interval_start,\n                interval_end AS interval_end\n            FROM\n            {$tableName}\n            WHERE\n                zone_id = {$zoneId}\n                AND operation_interval = {$aConf['maintenance']['operationInterval']}\n                AND interval_start >= '" . $oDateWeekStart->format('%Y-%m-%d %H:%M:%S') . "'\n                AND interval_end <= '" . $oDateWeekEnd->format('%Y-%m-%d %H:%M:%S') . "'\n                AND date_time > DATE_SUB('" . $oDateWeekStart->format('%Y-%m-%d %H:%M:%S') . "', {$oneHourInterval})\n                AND date_time < DATE_ADD('" . $oDateWeekEnd->format('%Y-%m-%d %H:%M:%S') . "', {$oneHourInterval})\n                AND zone_id != 0\n            GROUP BY\n            \tinterval_start,\n            \tinterval_end,\n            \toperation_interval_id\n            ORDER BY\n                interval_start";
     $rc = $this->oDbh->query($query);
     $totalForecastImpressions = 0;
     $count = 0;
     if (!PEAR::isError($rc)) {
         // Sort the results into an array indexed by the operation interval ID
         $aFinalResult = array();
         while ($aRow = $rc->fetchRow()) {
             $aFinalResult[$aRow['operation_interval_id']] = array('zone_id' => $zoneId, 'forecast_impressions' => $aRow['forecast_impressions'], 'operation_interval_id' => $aRow['operation_interval_id']);
             $count++;
             $totalForecastImpressions += $aRow['forecast_impressions'];
         }
     }
     $averageForecastImpressions = 0;
     if ($count > 0) {
         $averageForecastImpressions = floor($totalForecastImpressions / $count);
     }
     if ($averageForecastImpressions == 0) {
         $averageForecastImpressions = $this->getZoneForecastDefaultZoneImpressions();
     }
     // Check each operation interval ID has a forecast impression value,
     // and if not, set to the system default.
     for ($operationIntervalID = 0; $operationIntervalID < OX_OperationInterval::operationIntervalsPerWeek(); $operationIntervalID++) {
         if (!isset($aFinalResult[$operationIntervalID])) {
             $aFinalResult[$operationIntervalID] = array('zone_id' => $zoneId, 'forecast_impressions' => $averageForecastImpressions, 'operation_interval_id' => $operationIntervalID);
         }
     }
     // Overwrite current OI with previous OI to match the zone forecasting algorithm
     $currOI = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $prevOI = OX_OperationInterval::previousOperationIntervalID($currOI);
     $aFinalResult[$currOI]['forecast_impressions'] = $aFinalResult[$prevOI]['forecast_impressions'];
     // Return data
     return $aFinalResult;
 }
 /**
  * Method to test the getZonesForecastsForAllZones method.
  *
  * Requirements:
  * Test 1: Test with no Date registered in the service locator, ensure false returned.
  * Test 2: Test with a Date registered in the service locator, no data in the database,
  *         and ensure no data is returned.
  * Test 3: Test with forecast data but no actual impressions
  * Test 3.5: Test with actual data but no forecast impressions
  * Test 4: Test with data both in, and not in, the current OI, and ensure the correct
  *         data is returned.
  * Test 5: Repeat Test 4, but with additional zones (that don't have data) in the zones
  *         table.
  */
 function testGetAllZonesImpInv()
 {
     $conf = $GLOBALS['_MAX']['CONF'];
     $oDbh =& OA_DB::singleton();
     $oMaxDalMaintenance = new OA_Dal_Maintenance_Priority();
     $zoneForecastDefaultZoneImpressions = 0;
     // $oMaxDalMaintenance->getZoneForecastDefaultZoneImpressions();
     // Test 1
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oServiceLocator->remove('now');
     $result =& $oMaxDalMaintenance->getZonesForecastsForAllZones();
     $this->assertFalse($result);
     // Test 2
     $oDate = new Date();
     $oServiceLocator->register('now', $oDate);
     $result =& $oMaxDalMaintenance->getZonesForecastsForAllZones();
     $this->assertEqual($result, array(0 => $zoneForecastDefaultZoneImpressions));
     // Zone 0
     // Test 3
     // generate the first zone
     $aZones = $this->_generateTestZones(1);
     //         only generate previous OI delivered impressions, should return zone 0 only
     $oDate =& $oServiceLocator->get('now');
     $oNewDate = new Date();
     $oNewDate->copy($oDate);
     $oNewDate->subtractSeconds($conf['maintenance']['operationInterval'] * 60 + 1);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oNewDate);
     $this->_generateTestHistory(1, $aDates, 42, 0);
     $result =& $oMaxDalMaintenance->getZonesForecastsForAllZones();
     $expected = array(0 => $zoneForecastDefaultZoneImpressions, 1 => $zoneForecastDefaultZoneImpressions);
     $this->assertEqual($result, $expected);
     // Test 3.5
     // generate the second zone
     $aZones = $this->_generateTestZones(1);
     //     only generate previous OI forecasted impressions, should return zone 0 only
     $oNewDate = new Date();
     $oNewDate->copy($aDates['start']);
     $oNewDate->subtractSeconds(1);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oNewDate);
     $this->_generateTestHistory(2, $aDates, 0, 37);
     $result =& $oMaxDalMaintenance->getZonesForecastsForAllZones();
     $expected = array(0 => $zoneForecastDefaultZoneImpressions, 1 => $zoneForecastDefaultZoneImpressions, 2 => $zoneForecastDefaultZoneImpressions);
     $this->assertEqual($result, $expected);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 4
     $oDate =& $oServiceLocator->get('now');
     // generate three zone
     $this->_generateTestZones(3);
     // set forecast and impressions for OI - 1
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
     $this->_generateTestHistory(1, $aDates, 42, 100);
     $this->_generateTestHistory(2, $aDates, 5, 2);
     $this->_generateTestHistory(3, $aDates, 9999, 9999);
     $result =& $oMaxDalMaintenance->getZonesForecastsForAllZones();
     $expected = array(0 => $zoneForecastDefaultZoneImpressions, 1 => 42, 2 => 5, 3 => 9999);
     $this->assertEqual($result, $expected);
     // Test 5
     // New zone must appear in the array with default forecast
     $aZones = $this->_generateTestZones(1);
     $result =& $oMaxDalMaintenance->getZonesForecastsForAllZones();
     $expected = array(0 => $zoneForecastDefaultZoneImpressions, 1 => 42, 2 => 5, 3 => 9999, 4 => $zoneForecastDefaultZoneImpressions);
     $result =& $oMaxDalMaintenance->getZonesForecastsForAllZones();
     $this->assertEqual($result, $expected);
     // register forecast for the OI before, this should not affect current OI forecast
     $oDate =& $oServiceLocator->get('now');
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $currentOpIntID = OX_OperationInterval::convertDateToOperationIntervalID($aDates['start']);
     $this->_generateTestHistory(1, $aDates, 3700, 0);
     $this->_generateTestHistory(2, $aDates, 300, 0);
     $this->_generateTestHistory(3, $aDates, 500, 0);
     $result =& $oMaxDalMaintenance->getZonesForecastsForAllZones();
     $this->assertEqual($result, $expected);
     DataGenerator::cleanUp();
 }
 /**
  * A method to modify an array of history data so that it can be displayed in a format
  * compatible with the weekly breakdown template.
  *
  * @param array $aData    A reference to an array of arrays, containing the rows of data.
  * @param object $oCaller The calling object. Expected to have the the class variable
  *                        "statsBreakdown" set.
  */
 function prepareWeekBreakdown(&$aData, $oCaller)
 {
     // Only prepare the weekly breakdown if the statsBreakdown
     // in the caller is set to "week"
     if ($oCaller->statsBreakdown != 'week') {
         return;
     }
     $beginOfWeek = OA_Admin_DaySpan::getBeginOfWeek();
     $aWeekData = array();
     ksort($aData);
     foreach ($aData as $key => $aRowData) {
         // Get the date for this row's data
         $oDate = new Date($key);
         if ($beginOfWeek != 0) {
             // Need to change the date used for the data so
             // that the day appears in the correct week
             $daysToGoback = (int) (SECONDS_PER_DAY * $beginOfWeek);
             $oDate->subtractSeconds($daysToGoback);
         }
         // Get the week this date is in, in YYYY-MM format
         $week = sprintf('%04d-%02d', $oDate->getYear(), $oDate->getWeekOfYear());
         // Prepare the data array for this week, if not set, where
         // the week is in the "week" index, there is a "data" index
         // for all the rows that make up the week, and the array
         // has all the columns of an empty data row
         if (!isset($aWeekData[$week])) {
             $aWeekData[$week] = $oCaller->aEmptyRow;
             $aWeekData[$week]['week'] = $week;
             $aWeekData[$week]['data'] = array();
         }
         // Add the data from the row to the totals of the week
         foreach (array_keys($oCaller->aColumns) as $colKey) {
             $aWeekData[$week][$colKey] += $aRowData[$colKey];
         }
         // Store the row in the week
         $aWeekData[$week]['data'][$key] = $aRowData;
     }
     foreach (array_keys($aWeekData) as $week) {
         // Now that the totals are complete, fill any
         // remaining days in the week with empty data
         $days = count($aWeekData[$week]['data']);
         if ($days < 7) {
             // Locate the first day of the week in the days that make
             // up the week so far
             ksort($aWeekData[$week]['data']);
             $key = key($aWeekData[$week]['data']);
             $oDate = new Date($key);
             $firstDataDayOfWeek = $oDate->getDayOfWeek();
             // Is this after the start of the week?
             if ($firstDataDayOfWeek > $beginOfWeek) {
                 // Change the date to be the first day of this week
                 $daysToGoback = (int) (SECONDS_PER_DAY * ($firstDataDayOfWeek - $beginOfWeek));
                 $oDate->subtractSeconds($daysToGoback);
             }
             // Check each day in the week
             for ($counter = 0; $counter < 7; $counter++) {
                 if (is_null($aWeekData[$week]['data'][$oDate->format('%Y-%m-%d')])) {
                     // Set the day's data to the empty row, plus the "day" heading for the day
                     $aWeekData[$week]['data'][$oDate->format('%Y-%m-%d')] = $oCaller->aEmptyRow;
                     $aWeekData[$week]['data'][$oDate->format('%Y-%m-%d')]['day'] = $oDate->format($GLOBALS['date_format']);
                 } elseif (!is_null($aWeekData[$week]['data'][$oDate->format('%Y-%m-%d')]) && !array_key_exists('day', $aWeekData[$week]['data'][$oDate->format('%Y-%m-%d')])) {
                     $aWeekData[$week]['data'][$oDate->format('%Y-%m-%d')]['day'] = $oDate->format($GLOBALS['date_format']);
                 }
                 $oDate->addSeconds(SECONDS_PER_DAY);
             }
         }
         // Ensure the day data is sorted correctly
         ksort($aWeekData[$week]['data']);
         // Format all day rows
         foreach (array_keys($aWeekData[$week]['data']) as $key) {
             $oCaller->_formatStatsRowRecursive($aWeekData[$week]['data'][$key]);
         }
         // Calculate CTR and other columns, making sure that the method is available
         if (is_callable(array($oCaller, '_summarizeStats'))) {
             $oCaller->_summarizeStats($aWeekData[$week]);
         }
     }
     // Set the new weekly-formatted data as the new data array to use
     $aData = $aWeekData;
 }
 /**
  * Deletes users who are not linked with any sso account, never logged
  * in and their account was created before deleteUnverifiedUsersAfter days.
  * Where deleteUnverifiedUsersAfter is defined in config in
  * "authentication" section.
  *
  * @return boolean
  */
 function deleteUnverifiedUsers($deleteOlderThanSeconds = null)
 {
     if (empty($deleteOlderThanSeconds)) {
         // by default 28 days
         $deleteOlderThanSeconds = OA::getConfigOption('authentication', 'deleteUnverifiedUsersAfter', 2419200);
     }
     $monthAgo = new Date();
     $monthAgo->subtractSeconds($deleteOlderThanSeconds);
     $this->whereAdd('date_created < \'' . $this->formatDate($monthAgo) . '\'');
     $this->whereAdd('sso_user_id IS NULL');
     $this->whereAdd('date_last_login IS NULL');
     return $this->delete(DB_DATAOBJECT_WHEREADD_ONLY);
 }
 /**
  * Prune all entries where the ad_id is for a banner in a High Priority Campaign where:
  * The campaign has a booked number of lifetime target impressions and/or clicks and/or conversions AND the campaign is not active AND at least one of the booked lifetime target values has been reached.
  *
  */
 function testpruneDataSummaryAdZoneAssocTargetReached()
 {
     $oToday = new Date();
     $oExpire = new Date();
     $oExpire->subtractSeconds(999999);
     $today = $oToday->getDate();
     $expire = $oExpire->getDate();
     $oDal = new OA_Maintenance_Pruning();
     $doDSAZA = OA_Dal::factoryDO('data_summary_ad_zone_assoc');
     $doDIA = OA_Dal::factoryDO('data_intermediate_ad');
     $aDIAs = DataGenerator::generate($doDIA, 4);
     $doDIA = OA_Dal::staticGetDO('data_intermediate_ad', $aDIAs[0]);
     $doDIA->ad_id = $this->idBanner1;
     $doDIA->impressions = 1000;
     $doDIA->clicks = 0;
     $doDIA->conversions = 0;
     $doDIA->update();
     $doDIA = OA_Dal::staticGetDO('data_intermediate_ad', $aDIAs[1]);
     $doDIA->ad_id = $this->idBanner1;
     $doDIA->impressions = 100;
     $doDIA->clicks = 0;
     $doDIA->conversions = 0;
     $doDIA->update();
     $doDIA = OA_Dal::staticGetDO('data_intermediate_ad', $aDIAs[2]);
     $doDIA->ad_id = $this->idBanner1;
     $doDIA->impressions = 10;
     $doDIA->clicks = 0;
     $doDIA->conversions = 0;
     $doDIA->update();
     $doDIA = OA_Dal::staticGetDO('data_intermediate_ad', $aDIAs[3]);
     $doDIA->ad_id = $this->idBanner1;
     $doDIA->impressions = 1;
     $doDIA->clicks = 0;
     $doDIA->conversions = 0;
     $doDIA->update();
     // generate 2 summary ad_zone records for an active campaign ad_id
     $doDSAZA->ad_id = $this->idBanner1;
     $aIds = DataGenerator::generate($doDSAZA, 2);
     // generate 7 summary ad_zone records for an inactive campaign ad_id
     $doDSAZA->ad_id = $this->idBanner2;
     $aIds = DataGenerator::generate($doDSAZA, 7);
     // make sure 9 rows in table
     $this->assertEqual($this->_countRowsInDSAZA(), 9);
     // ad_id 1 => campaignid 1 => active, high priority, not expired, target impressions not reached
     $doCampaigns = OA_Dal::staticGetDO('campaigns', $this->idCampaign1);
     $doCampaigns->priority = 5;
     $doCampaigns->status = OA_ENTITY_STATUS_RUNNING;
     $doCampaigns->target_impression = 0;
     $doCampaigns->target_click = 0;
     $doCampaigns->target_conversion = 0;
     $doCampaigns->views = 100000;
     $doCampaigns->clicks = 1000;
     $doCampaigns->conversions = 100;
     $doCampaigns->update();
     $result = $oDal->_pruneDataSummaryAdZoneAssocInactiveTargetReached(1);
     // 0 records were deleted
     $this->assertEqual($result, 0);
     // 0 records remain
     $this->assertEqual($this->_countRowsInDSAZA(), 9);
     // ad_id 1 => campaignid 1 => not active, high priority, not expired, target impressions reached
     $doCampaigns = OA_Dal::staticGetDO('campaigns', $this->idCampaign1);
     $doCampaigns->priority = 5;
     $doCampaigns->status = OA_ENTITY_STATUS_EXPIRED;
     $doCampaigns->target_impression = 0;
     $doCampaigns->target_click = 0;
     $doCampaigns->target_conversion = 0;
     $doCampaigns->views = 1111;
     $doCampaigns->clicks = 111;
     $doCampaigns->conversions = 11;
     $doCampaigns->update();
     $result = $oDal->_pruneDataSummaryAdZoneAssocInactiveTargetReached(1);
     // 1 record deleted
     $this->assertEqual($result, 1);
     // 8 records remain
     $this->assertEqual($this->_countRowsInDSAZA(), 8);
     $result = $oDal->_pruneDataSummaryAdZoneAssocInactiveTargetReached(5);
     // 1 record was deleted
     $this->assertEqual($result, 1);
     // 7 records remain
     $this->assertEqual($this->_countRowsInDSAZA(), 7);
 }
 /**
  * A method to test the getDaysLeftString() method.
  */
 function testGetDaysLeftString()
 {
     /*
         	Possible cases for testing:
         	Case 1 -> Campaign without expiration date and without a estimated
         	          expiration date yet
         	Case 2 -> Campaign without expiration date and with a estimated
         	          expiration date
         	Case 3 -> Campaign with expiration date and without a estimated
         	          expiration date
         	Case 4 -> Campaign with expiration date reached
         	Case 5 -> Campaign with expiration date and with estimated
         	          expiration date minor than the expiration date
         	Case 6 -> Campaign with expiration date and with estimated
         	          expiration date equals to the expiration date
         	Case 7 -> Campaign with expiration date and with estimated
         	          expiration date higher than the expiration date
     */
     $GLOBALS['strExpirationDate'] = "Expiration date";
     $GLOBALS['strNoExpiration'] = "No expiration date set";
     $GLOBALS['strEstimated'] = "Estimated expiration date";
     $GLOBALS['strNoExpirationEstimation'] = "No expiration estimated yet";
     $GLOBALS['strCampaignStop'] = "Campaign stop";
     $GLOBALS['strDaysAgo'] = "days ago";
     $GLOBALS['strDaysLeft'] = "Days left";
     $GLOBALS['date_format'] = '%d.%m.%Y';
     // Case 1
     // Test an unlimited campaign without expiration date and without a
     // estimated expiration date yet
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->views = 0;
     $doCampaigns->clicks = 0;
     $doCampaigns->conversions = 0;
     $aData = array('reportlastdate' => array('2007-04-03 18:39:45'));
     $dg = new DataGenerator();
     $dg->setData('clients', $aData);
     $aCampaignIds = $dg->generate($doCampaigns, 1, true);
     $campaignId = $aCampaignIds[0];
     $expected = array('estimatedExpiration' => $GLOBALS['strEstimated'] . ": " . $GLOBALS['strNoExpirationEstimation'], 'campaignExpiration' => $GLOBALS['strNoExpiration']);
     $actual = $this->oDalCampaigns->getDaysLeftString($campaignId);
     $this->assertEqual($actual, $expected);
     // Case 2.1
     // Test a campaign (an impression limited campaign) without
     // expiration date and with a estimated expiration date
     $totalImpressions = 1000;
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->views = $totalImpressions;
     $doCampaigns->clicks = 0;
     $doCampaigns->conversions = 0;
     $aData = array('reportlastdate' => array('2007-04-03 18:39:45'));
     $dg = new DataGenerator();
     $dg->setData('clients', $aData);
     $aCampaignIds = $dg->generate($doCampaigns, 1, true);
     $campaignId = $aCampaignIds[0];
     // Link a banner to this campaign
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $campaignId;
     $doBanners->acls_updated = '2007-04-03 18:39:45';
     $bannerId = DataGenerator::generateOne($doBanners);
     // Insert impression delivery data occurring today
     $oDate = new Date();
     $impressions = 50;
     $clicks = 5;
     $conversions = 1;
     $doDSAH = OA_Dal::factoryDO('data_intermediate_ad');
     $doDSAH->day = $oDate->format('%Y-%m-%d');
     $doDSAH->hour = 10;
     $doDSAH->ad_id = $bannerId;
     $doDSAH->impressions = $impressions;
     $doDSAH->clicks = $clicks;
     $doDSAH->conversions = $conversions;
     $dsahId = DataGenerator::generateOne($doDSAH);
     // Delivered 50 impressions in 1 day. So, expect to take 19 days
     // to deliver remaining 950
     $daysLeft = 19;
     $oExpirationDate = new Date();
     $oExpirationDate->copy($oDate);
     $oExpirationDate->addSeconds($daysLeft * SECONDS_PER_DAY);
     $expected = array('estimatedExpiration' => $GLOBALS['strEstimated'] . ": " . $oExpirationDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")", 'campaignExpiration' => $GLOBALS['strNoExpiration']);
     $actual = $this->oDalCampaigns->getDaysLeftString($campaignId);
     $this->assertEqual($actual, $expected);
     // Case 2.2
     // Test a campaign (click limited campaign) without
     // expiration date and with a estimated expiration date
     $totalClicks = 500;
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->views = 0;
     $doCampaigns->clicks = $totalClicks;
     $doCampaigns->conversions = 0;
     $aData = array('reportlastdate' => array('2007-04-03 18:39:45'));
     $dg = new DataGenerator();
     $dg->setData('clients', $aData);
     $aCampaignIds = $dg->generate($doCampaigns, 1, true);
     $campaignId = $aCampaignIds[0];
     // Link a banner to this campaign
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $campaignId;
     $doBanners->acls_updated = '2007-04-03 18:39:45';
     $bannerId = DataGenerator::generateOne($doBanners);
     // Insert click delivery data occurring today
     $oDate = new Date();
     $impressions = 50;
     $clicks = 5;
     $conversions = 1;
     $doDSAH = OA_Dal::factoryDO('data_intermediate_ad');
     $doDSAH->day = $oDate->format('%Y-%m-%d');
     $doDSAH->hour = 10;
     $doDSAH->ad_id = $bannerId;
     $doDSAH->impressions = $impressions;
     $doDSAH->clicks = $clicks;
     $doDSAH->conversions = $conversions;
     $dsahId = DataGenerator::generateOne($doDSAH);
     // Delivered 5 clicks in 1 day. So, expect to take 99 days to deliver
     // remaining 495
     $daysLeft = 99;
     $oExpirationDate = new Date();
     $oExpirationDate->copy($oDate);
     $oExpirationDate->addSeconds($daysLeft * SECONDS_PER_DAY);
     $expected = array('estimatedExpiration' => $GLOBALS['strEstimated'] . ": " . $oExpirationDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")", 'campaignExpiration' => $GLOBALS['strNoExpiration']);
     $actual = $this->oDalCampaigns->getDaysLeftString($campaignId);
     $this->assertEqual($actual, $expected);
     // Case 2.3
     // Test a campaign (conversion limited campaign)
     // without expiration date and with a estimated expiration date
     $totalConversions = 10;
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->views = 0;
     $doCampaigns->clicks = 0;
     $doCampaigns->conversions = $totalConversions;
     $aData = array('reportlastdate' => array('2007-04-03 18:39:45'));
     $dg = new DataGenerator();
     $dg->setData('clients', $aData);
     $aCampaignIds = $dg->generate($doCampaigns, 1, true);
     $campaignId = $aCampaignIds[0];
     // Link a banner to this campaign
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $campaignId;
     $doBanners->acls_updated = '2007-04-03 18:39:45';
     $bannerId = DataGenerator::generateOne($doBanners);
     // Insert conversion delivery data occurring today
     $oDate = new Date();
     $impressions = 50;
     $clicks = 5;
     $conversions = 1;
     $doDSAH = OA_Dal::factoryDO('data_intermediate_ad');
     $doDSAH->day = $oDate->format('%Y-%m-%d');
     $doDSAH->hour = 10;
     $doDSAH->ad_id = $bannerId;
     $doDSAH->impressions = $impressions;
     $doDSAH->clicks = $clicks;
     $doDSAH->conversions = $conversions;
     $dsahId = DataGenerator::generateOne($doDSAH);
     // Delivered 1 conversion in 1 day. So, expect to take 9 days to deliver remaining 9
     $daysLeft = 9;
     $oExpirationDate = new Date();
     $oExpirationDate->copy($oDate);
     $oExpirationDate->addSeconds($daysLeft * SECONDS_PER_DAY);
     $expected = array('estimatedExpiration' => $GLOBALS['strEstimated'] . ": " . $oExpirationDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")", 'campaignExpiration' => $GLOBALS['strNoExpiration']);
     $actual = $this->oDalCampaigns->getDaysLeftString($campaignId);
     $this->assertEqual($actual, $expected);
     // Case 2.4
     // Test a triple limited campaign without expiration date
     // and with a estimated expiration date
     $totalImpressions = 1000;
     $totalClicks = 500;
     $totalConversions = 10;
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->views = $totalImpressions;
     $doCampaigns->clicks = $totalClicks;
     $doCampaigns->conversions = $totalConversions;
     $aData = array('reportlastdate' => array('2007-04-03 18:39:45'));
     $dg = new DataGenerator();
     $dg->setData('clients', $aData);
     $aCampaignIds = $dg->generate($doCampaigns, 1, true);
     $campaignId = $aCampaignIds[0];
     // Link a banner to this campaign
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $campaignId;
     $doBanners->acls_updated = '2007-04-03 18:39:45';
     $bannerId = DataGenerator::generateOne($doBanners);
     // Insert conversion delivery data occurring today
     $oDate = new Date();
     $impressions = 50;
     $clicks = 5;
     $conversions = 1;
     $doDSAH = OA_Dal::factoryDO('data_intermediate_ad');
     $doDSAH->day = $oDate->format('%Y-%m-%d');
     $doDSAH->hour = 10;
     $doDSAH->ad_id = $bannerId;
     $doDSAH->impressions = $impressions;
     $doDSAH->clicks = $clicks;
     $doDSAH->conversions = $conversions;
     $dsahId = DataGenerator::generateOne($doDSAH);
     // Delivered 50 impressions in 1 day. So, expect to take 19 days to
     // deliver remaining 950
     // Delivered 5 clicks in 1 day. So, expect to take 99 days to deliver
     // remaining 495
     // Delivered 1 conversion in 1 day. So, expect to take 9 days to deliver
     // remaining 9
     // The estimated expiration will be calucalated based on impression targets
     // or based on click targets or based on conversion targets (following this order).
     $daysLeft = 19;
     $oExpirationDate = new Date();
     $oExpirationDate->copy($oDate);
     $oExpirationDate->addSeconds($daysLeft * SECONDS_PER_DAY);
     $expected = array('estimatedExpiration' => $GLOBALS['strEstimated'] . ": " . $oExpirationDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")", 'campaignExpiration' => $GLOBALS['strNoExpiration']);
     $actual = $this->oDalCampaigns->getDaysLeftString($campaignId);
     $this->assertEqual($actual, $expected);
     // Case 3
     // Test a campaign with expiration date and without a estimated expiration date
     // Prepare a date 10 days in the future
     $daysLeft = 10;
     $oDate = new Date();
     $oDate->setHour(23);
     $oDate->setMinute(59);
     $oDate->setSecond(59);
     $oDate->addSeconds($daysLeft * SECONDS_PER_DAY);
     $oDate->toUTC();
     // Test an unlimited campaign which expires 10 days in the future
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->views = 0;
     $doCampaigns->clicks = 0;
     $doCampaigns->conversions = 0;
     $doCampaigns->expire_time = $oDate->getDate(DATE_FORMAT_ISO);
     $aData = array('reportlastdate' => array('2007-04-03 18:39:45'));
     $dg = new DataGenerator();
     $dg->setData('clients', $aData);
     $aCampaignIds = $dg->generate($doCampaigns, 1, true);
     $campaignId = $aCampaignIds[0];
     // Link a banner to this campaign
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $campaignId;
     $doBanners->acls_updated = '2007-04-03 18:39:45';
     $bannerId = DataGenerator::generateOne($doBanners);
     $expected = array('estimatedExpiration' => $GLOBALS['strEstimated'] . ": " . $GLOBALS['strNoExpirationEstimation'], 'campaignExpiration' => $GLOBALS['strExpirationDate'] . ": " . $oDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")");
     $actual = $this->oDalCampaigns->getDaysLeftString($campaignId);
     $this->assertEqual($actual, $expected);
     // Case 4
     // Campaign with expiration date reached
     // Prepare a campaign with expiration date reached
     $daysExpired = 5;
     $oDate = new Date();
     $oDate->setHour(23);
     $oDate->setMinute(59);
     $oDate->setSecond(59);
     $oDate->subtractSeconds($daysExpired * SECONDS_PER_DAY);
     $oDate->toUTC();
     // Test an unlimited campaign which expired 5 days ago
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->views = 0;
     $doCampaigns->clicks = 0;
     $doCampaigns->conversions = 0;
     $doCampaigns->expire_time = $oDate->getDate(DATE_FORMAT_ISO);
     $aData = array('reportlastdate' => array('2007-04-03 18:39:45'));
     $dg = new DataGenerator();
     $dg->setData('clients', $aData);
     $aCampaignIds = $dg->generate($doCampaigns, 1, true);
     $campaignId = $aCampaignIds[0];
     // Link a banner to this campaign
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $campaignId;
     $doBanners->acls_updated = '2007-04-03 18:39:45';
     $bannerId = DataGenerator::generateOne($doBanners);
     $expected = array('estimatedExpiration' => '', 'campaignExpiration' => $GLOBALS['strCampaignStop'] . ": " . $oDate->format('%d.%m.%Y') . " (" . $daysExpired . " " . $GLOBALS['strDaysAgo'] . ")");
     $actual = $this->oDalCampaigns->getDaysLeftString($campaignId);
     $this->assertEqual($actual, $expected);
     // Case 5
     // Campaign with expiration date and with estimated
     // expiration date minor than the expiration date
     // Prepare a date 25 days in the future
     $daysLeft = 25;
     $oDate = new Date();
     $oDate->setHour(23);
     $oDate->setMinute(59);
     $oDate->setSecond(59);
     $oDate->addSeconds($daysLeft * SECONDS_PER_DAY);
     $oDate->toUTC();
     $campaignExpiration = $GLOBALS['strExpirationDate'] . ": " . $oDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")";
     $totalImpressions = 1000;
     $totalClicks = 500;
     $totalConversions = 10;
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->expire_time = $oDate->getDate(DATE_FORMAT_ISO);
     $doCampaigns->views = $totalImpressions;
     $doCampaigns->clicks = $totalClicks;
     $doCampaigns->conversions = $totalConversions;
     $aData = array('reportlastdate' => array('2007-04-03 18:39:45'));
     $dg = new DataGenerator();
     $dg->setData('clients', $aData);
     $aCampaignIds = $dg->generate($doCampaigns, 1, true);
     $campaignId = $aCampaignIds[0];
     // Link a banner to this campaign
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $campaignId;
     $doBanners->acls_updated = '2007-04-03 18:39:45';
     $bannerId = DataGenerator::generateOne($doBanners);
     // Insert conversion delivery data occurring today
     $oDate = new Date();
     $impressions = 50;
     $clicks = 5;
     $conversions = 1;
     $doDSAH = OA_Dal::factoryDO('data_intermediate_ad');
     $doDSAH->day = $oDate->format('%Y-%m-%d');
     $doDSAH->hour = 10;
     $doDSAH->ad_id = $bannerId;
     $doDSAH->impressions = $impressions;
     $doDSAH->clicks = $clicks;
     $doDSAH->conversions = $conversions;
     $dsahId = DataGenerator::generateOne($doDSAH);
     // Delivered 50 impressions in 1 day. So, expect to take 19 days to
     // deliver remaining 950
     // Delivered 5 clicks in 1 day. So, expect to take 99 days to deliver
     // remaining 495
     // Delivered 1 conversion in 1 day. So, expect to take 9 days to deliver
     // remaining 9
     // The estimated expiration will be calucalated based onimpression targets
     // or based on click targets or based on conversion targets (following this order).
     $daysLeft = 19;
     $oExpirationDate = new Date();
     $oExpirationDate->copy($oDate);
     $oExpirationDate->addSeconds($daysLeft * SECONDS_PER_DAY);
     $expected = array('estimatedExpiration' => $GLOBALS['strEstimated'] . ": " . $oExpirationDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")", 'campaignExpiration' => $campaignExpiration);
     $actual = $this->oDalCampaigns->getDaysLeftString($campaignId);
     $this->assertEqual($actual, $expected);
     // Case 6
     // Campaign with expiration date and with estimated
     // expiration date equals to the expiration date
     // Prepare a date 19 days in the future
     $daysLeft = 19;
     $oDate = new Date();
     $oDate->setHour(23);
     $oDate->setMinute(59);
     $oDate->setSecond(59);
     $oDate->addSeconds($daysLeft * SECONDS_PER_DAY);
     $oDate->toUTC();
     $campaignExpiration = $GLOBALS['strExpirationDate'] . ": " . $oDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")";
     $totalImpressions = 1000;
     $totalClicks = 500;
     $totalConversions = 10;
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->expire_time = $oDate->getDate(DATE_FORMAT_ISO);
     $doCampaigns->views = $totalImpressions;
     $doCampaigns->clicks = $totalClicks;
     $doCampaigns->conversions = $totalConversions;
     $aData = array('reportlastdate' => array('2007-04-03 18:39:45'));
     $dg = new DataGenerator();
     $dg->setData('clients', $aData);
     $aCampaignIds = $dg->generate($doCampaigns, 1, true);
     $campaignId = $aCampaignIds[0];
     // Link a banner to this campaign
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $campaignId;
     $doBanners->acls_updated = '2007-04-03 18:39:45';
     $bannerId = DataGenerator::generateOne($doBanners);
     // Insert conversion delivery data occurring today
     $oDate = new Date();
     $impressions = 50;
     $clicks = 5;
     $conversions = 1;
     $doDSAH = OA_Dal::factoryDO('data_intermediate_ad');
     $doDSAH->day = $oDate->format('%Y-%m-%d');
     $doDSAH->hour = 10;
     $doDSAH->ad_id = $bannerId;
     $doDSAH->impressions = $impressions;
     $doDSAH->clicks = $clicks;
     $doDSAH->conversions = $conversions;
     $dsahId = DataGenerator::generateOne($doDSAH);
     // Delivered 50 impressions in 1 day. So, expect to take 19 days to
     // deliver remaining 950
     // Delivered 5 clicks in 1 day. So, expect to take 99 days to deliver
     // remaining 495
     // Delivered 1 conversion in 1 day. So, expect to take 9 days to
     // deliver remaining 9
     // The estimated expiration will be calucalated based on impression targets
     // or based on click targets or based on conversion targets (following this order).
     $daysLeft = 19;
     $oExpirationDate = new Date();
     $oExpirationDate->copy($oDate);
     $oExpirationDate->addSeconds($daysLeft * SECONDS_PER_DAY);
     $expected = array('estimatedExpiration' => $GLOBALS['strEstimated'] . ": " . $oExpirationDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")", 'campaignExpiration' => $campaignExpiration);
     $actual = $this->oDalCampaigns->getDaysLeftString($campaignId);
     $this->assertEqual($actual, $expected);
     // Case 7
     // Campaign with expiration date and with estimated
     // expiration date higher than the expiration date
     // Prepare a date 10 days in the future
     $daysLeft = 10;
     $oDate = new Date();
     $oDate->setHour(23);
     $oDate->setMinute(59);
     $oDate->setSecond(59);
     $oDate->addSeconds($daysLeft * SECONDS_PER_DAY);
     $oDate->toUTC();
     // Test a triple limited campaign with an expiration date 10 days
     // in the future
     $totalImpressions = 1000;
     $totalClicks = 500;
     $totalConversions = 10;
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->views = $totalImpressions;
     $doCampaigns->clicks = $totalClicks;
     $doCampaigns->conversions = $totalConversions;
     $doCampaigns->expire_time = $oDate->getDate(DATE_FORMAT_ISO);
     $aData = array('reportlastdate' => array('2007-04-03 18:39:45'));
     $dg = new DataGenerator();
     $dg->setData('clients', $aData);
     $aCampaignIds = $dg->generate($doCampaigns, 1, true);
     $campaignId = $aCampaignIds[0];
     $campaignExpiration = $GLOBALS['strExpirationDate'] . ": " . $oDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")";
     // Link a banner to this campaign
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $campaignId;
     $doBanners->acls_updated = '2007-04-03 18:39:45';
     $bannerId = DataGenerator::generateOne($doBanners);
     // Insert conversion delivery data occurring today
     $oDate = new Date();
     $impressions = 50;
     $clicks = 5;
     $conversions = 1;
     $doDSAH = OA_Dal::factoryDO('data_intermediate_ad');
     $doDSAH->day = $oDate->format('%Y-%m-%d');
     $doDSAH->hour = 10;
     $doDSAH->ad_id = $bannerId;
     $doDSAH->impressions = $impressions;
     $doDSAH->clicks = $clicks;
     $doDSAH->conversions = $conversions;
     $dsahId = DataGenerator::generateOne($doDSAH);
     // Expiration date is in 10 days
     // Delivered 50 impressions in 1 day. So, expect to take 19 days to
     // deliver remaining 950
     // Delivered 5 clicks in 1 day. So, expect to take 99 days to
     // deliver remaining 495
     // Delivered 1 conversion in 1 day. So, expect to take 9 days to
     // deliver remaining 9
     // The estimated expiration will be calucalated based on impression targets
     // or based on click targets or based on conversion targets (following this order)
     $estimatedDaysLeft = 19;
     $oExpirationDate = new Date();
     $oExpirationDate->copy($oDate);
     $oExpirationDate->addSeconds($estimatedDaysLeft * SECONDS_PER_DAY);
     // The extimated expiration is higher than the expiration set by the user
     // so the value of the extimated expiration will be null because is not a
     // relevant estimation because the campaign will expire before this estimation.
     $expected = array('estimatedExpiration' => '', 'campaignExpiration' => $campaignExpiration);
     $actual = $this->oDalCampaigns->getDaysLeftString($campaignId);
     $this->assertEqual($actual, $expected);
 }
function transferFormerFinishedTransactions($account)
{
    global $us;
    if ($us->getProperty('autoExpandPlannedTransactions') == false) {
        return;
    }
    $now = new Date();
    $now->setHour(0);
    $now->setMinute(0);
    $now->setSecond(0);
    $account->setType('planned');
    $account->setFilter(array(array('key' => 'beginDate', 'op' => 'le', 'val' => $now)));
    try {
        $lastInsertDate = $us->getProperty('Account_' . $account->getId() . '_LastTransferFormerFinishedTransactions');
    } catch (BadgerException $ex) {
        $lastInsertDate = new Date('1000-01-01');
    }
    $us->setProperty('Account_' . $account->getId() . '_LastTransferFormerFinishedTransactions', $now);
    if (!$lastInsertDate->before($now)) {
        return;
    }
    while ($currentTransaction = $account->getNextPlannedTransaction()) {
        $date = new Date($currentTransaction->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 = $currentTransaction->getEndDate()) ? new Date('9999-12-31') : $tmp)) {
            if ($date->after($lastInsertDate)) {
                $account->addFinishedTransaction($currentTransaction->getAmount(), $currentTransaction->getTitle(), $currentTransaction->getDescription(), new Date($date), $currentTransaction->getTransactionPartner(), $currentTransaction->getCategory(), $currentTransaction->getOutsideCapital(), false, true);
            }
            //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;
            }
        }
    }
}