示例#1
0
 function __construct()
 {
     // Check auto-maintenance settings
     $aConf = $GLOBALS['_MAX']['CONF'];
     $this->isAutoMaintenanceEnabled = !empty($aConf['maintenance']['autoMaintenance']);
     // Get time 1 hour ago
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oNow = $oServiceLocator->get('now');
     if ($oNow) {
         $oOneHourAgo = new Date($oNow);
     } else {
         $oOneHourAgo = new Date();
     }
     $oOneHourAgo->subtractSpan(new Date_Span('0-1-0-0'));
     // Get last runs
     $oLastCronRun = OX_Maintenance::getLastScheduledRun();
     $oLastRun = OX_Maintenance::getLastRun();
     // Reset minutes and seconds
     if (isset($oLastCronRun)) {
         $oLastCronRun->setMinute(0);
         $oLastCronRun->setSecond(0);
     }
     if (isset($oLastRun)) {
         $oLastRun->setMinute(0);
         $oLastRun->setSecond(0);
     }
     // Check if any kind of maintenance was run
     if (isset($oLastCronRun) && !$oOneHourAgo->after($oLastCronRun)) {
         $this->isScheduledMaintenanceRunning = true;
     } elseif (isset($oLastRun) && !$oOneHourAgo->after($oLastRun)) {
         $this->isAutoMaintenanceRunning = true;
     }
 }
示例#2
0
 function after($when)
 {
     if (!is_object($when)) {
         $when = new CDate($when);
     }
     return parent::after($when);
 }
示例#3
0
 function after($date)
 {
     if (!$date instanceof parent) {
         $when = new CDate($date);
     } else {
         // copy the Date object to prevent changes propagation
         $when = new CDate();
         $when->copy($date);
     }
     return parent::after($when);
 }
示例#4
0
 public function getLinks()
 {
     $oDate = new Date($this->oStart);
     $oNow = new Date();
     $aLinks = array();
     $baseUrl = parent::getUrl(false);
     $year = $oDate->getYear();
     $aLinks['prev'] = array('label' => '< ' . ($year - 1), 'url' => $this->appendToUrl($baseUrl, 'year=' . ($year - 1)));
     $oDate->setYear($year + 1);
     $aLinks['next'] = array('label' => $year + 1 . ' >');
     if ($oNow->after($oDate)) {
         $aLinks['next']['url'] = $this->appendToUrl($baseUrl, 'year=' . ($year + 1));
     }
     return $aLinks;
 }
 /**
  * A method to test the getPlacementFirstStatsDate() method.
  *
  * Requirements:
  * Test 1: Test with an invalid placement ID, and ensure null is returned.
  * Test 2: Test with no data in the database, and ensure current date is returned.
  * Test 3: Test with single row in the database, and ensure correct date is
  *         returned.
  * Test 4: Test with multi rows in the database, and ensure correct date is
  *         returned.
  */
 function testGetPlacementFirstStatsDate()
 {
     $conf =& $GLOBALS['_MAX']['CONF'];
     $oDbh =& OA_DB::singleton();
     $oDalStatistics = new MAX_Dal_Statistics();
     // Test 1
     $placementId = 'foo';
     $oResult = $oDalStatistics->getPlacementFirstStatsDate($placementId);
     $this->assertNull($oResult);
     // Test 2
     $placementId = 1;
     $oBeforeDate = new Date();
     sleep(1);
     $oResult = $oDalStatistics->getPlacementFirstStatsDate($placementId);
     sleep(1);
     $oAfterDate = new Date();
     $this->assertTrue(is_a($oResult, 'Date'));
     $this->assertTrue($oBeforeDate->before($oResult));
     $this->assertTrue($oAfterDate->after($oResult));
     // Test 3
     $oNow = new Date();
     $aData = array('campaignid' => $placementId, 'active' => 't', 'updated' => $oNow->format('%Y-%m-%d %H:%M:%S'), 'acls_updated' => $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idBanner1 = $this->_insertBanner($aData);
     $aData = array('day' => '2006-10-30', 'hour' => 12, 'ad_id' => $idBanner1, 'updated' => $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDSAH1 = $this->_insertDataSummaryAdHourly($aData);
     $oResult = $oDalStatistics->getPlacementFirstStatsDate($placementId);
     $oExpectedDate = new Date('2006-10-30 12:00:00');
     $this->assertEqual($oResult, $oExpectedDate);
     // Test 4
     $aData = array('campaignid' => $placementId, 'active' => 't', 'updated' => $oNow->format('%Y-%m-%d %H:%M:%S'), 'acls_updated' => $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idBanner2 = $this->_insertBanner($aData);
     $aData = array('campaignid' => 999, 'active' => 't', 'updated' => $oNow->format('%Y-%m-%d %H:%M:%S'), 'acls_updated' => $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idBanner3 = $this->_insertBanner($aData);
     $aData = array('day' => '2006-10-29', 'hour' => 12, 'ad_id' => $idBanner2, 'updated' => $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDSAH1 = $this->_insertDataSummaryAdHourly($aData);
     $aData = array('day' => '2006-10-28', 'hour' => 12, 'ad_id' => $idBanner2, 'updated' => $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDSAH2 = $this->_insertDataSummaryAdHourly($aData);
     $aData = array('day' => '2006-10-27', 'hour' => 12, 'ad_id' => $idBanner2, 'updated' => $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDSAH3 = $this->_insertDataSummaryAdHourly($aData);
     $aData = array('day' => '2006-10-26', 'hour' => 12, 'ad_id' => 999, 'updated' => $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDSAH4 = $this->_insertDataSummaryAdHourly($aData);
     $oResult = $oDalStatistics->getPlacementFirstStatsDate($placementId);
     $oExpectedDate = new Date('2006-10-27 12:00:00');
     $this->assertEqual($oResult, $oExpectedDate);
     DataGenerator::cleanUp();
 }
示例#6
0
 public function getLinks()
 {
     $oDate = new Date($this->oStart);
     $oNow = new Date();
     $aLinks = array();
     $baseUrl = parent::getUrl(false);
     $date = $oDate->format('%Y-%m');
     $aLinks['up'] = array('label' => $date, 'url' => $this->appendToUrl($baseUrl, 'month=' . $date));
     $oDate->subtractSpan(new Date_Span('1-0-0-0'));
     $date = $oDate->format('%Y-%m-%d');
     $aLinks['prev'] = array('label' => '< ' . $date, 'url' => $this->appendToUrl($baseUrl, 'day=' . $date));
     $oDate->addSpan(new Date_Span('2-0-0-0'));
     $date = $oDate->format('%Y-%m-%d');
     $aLinks['next'] = array('label' => $date . ' >');
     if ($oNow->after($oDate)) {
         $aLinks['next']['url'] = $this->appendToUrl($baseUrl, 'day=' . $date);
     }
     return $aLinks;
 }
 /**
  * A method to calculate the number of operation intervals, from a given
  * date to the end date of the campaign, an advertisement will be blocked
  * from delivering in.
  *
  * @param PEAR::Date $oStartDate A Date object representing the start of the
  *                               current operation interval.
  * @param PEAR::Date $oEndDate A Date object representing the end date of the
  *                             campaign the advertisement is in.
  * @return integer The number of operation intervals in which the advertisement
  *                 will be blocked from delivering in.
  */
 function getBlockedOperationIntervalCount($oStartDate, $oEndDate)
 {
     // Ensure the campaign end date is at the END of the day
     $oCampaignEndDate = new Date();
     $oCampaignEndDate->copy($oEndDate);
     $oCampaignEndDate->setHour(23);
     $oCampaignEndDate->setMinute(59);
     $oCampaignEndDate->setSecond(59);
     // Copy the starting date to use in a loop
     $oLoopDate = new Date();
     $oLoopDate->copy($oStartDate);
     // Count the number of blocked operation intervals
     $blockedIntervals = 0;
     while (!$oLoopDate->after($oCampaignEndDate)) {
         if ($this->deliveryBlocked($oLoopDate)) {
             // Update the count of blocked intervals, but
             // also store the start/end dates of the blocked
             // interval for later use
             $blockedIntervals++;
             $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oLoopDate);
             $this->aBlockedOperationIntervalDates[$aDates['start']->format('%Y-%m-%d %H:%M:%S')] = $aDates;
         }
         $oLoopDate->addSeconds(OX_OperationInterval::secondsPerOperationInterval());
     }
     return $blockedIntervals;
 }
function showTrendData()
{
    global $badgerDb;
    global $logger;
    $logger->log('statistics::showTrendData: REQUEST_URI: ' . $_SERVER['REQUEST_URI']);
    if (!isset($_GET['accounts']) || !isset($_GET['startDate']) || !isset($_GET['endDate'])) {
        throw new BadgerException('statistics', 'missingParameter');
    }
    $accountIds = explode(';', $_GET['accounts']);
    foreach ($accountIds as $key => $val) {
        settype($accountIds[$key], 'integer');
    }
    $startDate = new Date($_GET['startDate']);
    $endDate = new Date($_GET['endDate']);
    $now = new Date();
    $now->setHour(0);
    $now->setMinute(0);
    $now->setSecond(0);
    if ($endDate->after($now)) {
        $endDate = $now;
    }
    $accountManager = new AccountManager($badgerDb);
    $totals = array();
    $accounts = array();
    $currentAccountIndex = 0;
    foreach ($accountIds as $currentAccountId) {
        $currentAccount = $accountManager->getAccountById($currentAccountId);
        $accounts[$currentAccountIndex][0] = $currentAccount->getTitle();
        $currentBalances = getDailyAmount($currentAccount, $startDate, $endDate);
        foreach ($currentBalances as $balanceKey => $balanceVal) {
            if (isset($totals[$balanceKey])) {
                $totals[$balanceKey]->add($balanceVal);
            } else {
                $totals[$balanceKey] = $balanceVal;
            }
            $accounts[$currentAccountIndex][] = $balanceVal->get();
        }
        $currentAccountIndex++;
    }
    $numDates = count($totals);
    $chart = array();
    //for documentation for the following code see: http://www.maani.us/charts/index.php?menu=Reference
    $chart['chart_type'] = "line";
    $chart['axis_category'] = array('skip' => $numDates / 12, 'font' => "Arial", 'bold' => false, 'size' => 10, 'color' => "000000", 'alpha' => 100, 'orientation' => "horizontal");
    $chart['axis_ticks'] = array('value_ticks' => true, 'category_ticks' => true, 'position' => "centered", 'major_thickness' => 2, 'major_color' => "000000", 'minor_thickness' => 1, 'minor_color' => "000000", 'minor_count' => 4);
    $chart['axis_value'] = array('min' => 0, 'max' => 0, 'steps' => 10, 'prefix' => "", 'suffix' => "", 'decimals' => 0, 'decimal_char' => ".", 'separator' => "", 'show_min' => true, 'font' => "Arial", 'bold' => false, 'size' => 10, 'color' => "000000", 'alpha' => 75, 'orientation' => "horizontal");
    $chart['chart_border'] = array('top_thickness' => 1, 'bottom_thickness' => 1, 'left_thickness' => 1, 'right_thickness' => 1, 'color' => "000000");
    $chart['chart_pref'] = array('line_thickness' => 1, 'point_shape' => "none", 'fill_shape' => false);
    $chart['chart_grid_h'] = array('thickness' => 1, 'color' => "000000", 'alpha' => 15, 'type' => "solid");
    $chart['chart_grid_v'] = array('thickness' => 1, 'color' => "000000", 'alpha' => 5, 'type' => "dashed");
    $chart['chart_rect'] = array('x' => 50, 'y' => 50, 'width' => 700, 'height' => 300, 'positive_color' => "ffffff", 'negative_color' => "000000", 'positive_alpha' => 100, 'negative_alpha' => 10);
    $chart['chart_value'] = array('prefix' => "", 'suffix' => "", 'decimals' => 0, 'decimal_char' => ".", 'separator' => "", 'position' => "cursor", 'hide_zero' => true, 'as_percentage' => false, 'font' => "Arial", 'bold' => false, 'size' => 10, 'color' => "000000", 'alpha' => 90);
    $chart['chart_transition'] = array('type' => "none", 'delay' => 1, 'duration' => 1, 'order' => "all");
    $chart['legend_rect'] = array('x' => 50, 'y' => 5, 'width' => 700, 'height' => 5, 'margin' => 5, 'fill_color' => "FFFFFF", 'fill_alpha' => 100, 'line_color' => "000000", 'line_alpha' => 100, 'line_thickness' => 1);
    $chart['legend_label'] = array('layout' => "horizontal", 'bullet' => "circle", 'font' => "Arial", 'bold' => false, 'size' => 11, 'color' => "000000", 'alpha' => 90);
    $chart['legend_transition'] = array('type' => "none", 'delay' => 1, 'duration' => 1);
    $chart['series_color'] = array("FF0000", "00FF00", "0000FF", "FF8000", "404040", "800040");
    $chart['chart_data'] = array();
    $chart['chart_data'][0][0] = '';
    if (count($accounts) > 1) {
        $chart['chart_data'][1][0] = getBadgerTranslation2('statistics', 'trendTotal');
    } else {
        $chart['chart_data'][1][0] = utf8_encode($accounts[0][0]);
    }
    foreach ($totals as $key => $val) {
        $tmp = new Date($key);
        $chart['chart_data'][0][] = $tmp->getFormatted();
        $chart['chart_data'][1][] = $val->get();
    }
    if (count($accounts) > 1) {
        foreach ($accounts as $val) {
            $chart['chart_data'][] = $val;
        }
    }
    SendChartData($chart);
}
示例#9
0
 function revenueInsertStats($bannerId, $aParams, $actionType)
 {
     $aZoneIds = $this->revenueGetLinkedZones($bannerId);
     $oSpan = new Date_Span('0-1-0-0');
     $oDate = new Date($aParams['start']);
     $i = 0;
     while (!$oDate->after(new Date($aParams['end']))) {
         foreach ($aZoneIds as $zoneId) {
             $doDsah = OA_Dal::factoryDO('data_summary_ad_hourly');
             $doDsah->date_time = $oDate->format('%Y-%m-%d %H:00:00');
             $doDsah->ad_id = $bannerId;
             $doDsah->zone_id = $zoneId;
             $doDsah->creative_id = 0;
             $doDsahClone = clone $doDsah;
             if (!$doDsah->count()) {
                 $doDsahClone->updated = OA::getNow();
                 if ($doDsahClone->insert()) {
                     $i++;
                 }
             }
         }
         $oDate->addSpan($oSpan);
     }
     return $i > 0;
 }
示例#10
0
 /**
  * A method to check if the campaign is expired
  *
  * @return bool
  */
 function _isExpired()
 {
     static $oServiceLocator;
     // MySQL null date hardcoded for optimisation
     if (!empty($this->expire) && $this->expire != '0000-00-00') {
         if (!isset($oServiceLocator)) {
             $oServiceLocator =& OA_ServiceLocator::instance();
         }
         if (!($oNow = $oServiceLocator->get('now'))) {
             $oNow = new Date();
         }
         $oExpire = new Date($this->expire);
         $oExpire->setHour(23);
         $oExpire->setMinute(59);
         $oExpire->setSecond(59);
         if (!empty($this->clientid)) {
             // Set timezone
             $aAccounts = $this->getOwningAccountIds();
             $aPrefs = OA_Preferences::loadAccountPreferences($aAccounts[OA_ACCOUNT_ADVERTISER], true);
             if (isset($aPrefs['timezone'])) {
                 $oExpire->setTZbyID($aPrefs['timezone']);
             }
         }
         if ($oNow->after($oExpire)) {
             return true;
         }
     }
     return false;
 }
 /**
  * A method to distribute the calculated required campaign impressions between the campaign's
  * children advertisements. Impression allocation takes in to account ad weight, and the number
  * of operations intervals the ad will be active in given date/time delivery limitations, and
  * the pattern of available impressions for the zone(s) the advertisements are linked to.
  *
  * The calculated ad impressions are written to the temporary table tmp_ad_required_impression
  * for later analysis by the {@link OA_Maintenance_Priority_AdServer_Task_AllocateZoneImpressions}
  * class.
  *
  * @param array $aCampaigns An array of {@link OX_Maintenance_Priority_Campaign} objects which require
  *                          that their total required impressions be distributed between the
  *                          component advertisements.
  */
 function distributeCampaignImpressions($aCampaigns)
 {
     // Create an array for storing required ad impressions
     $aRequiredAdImpressions = array();
     // Get the current operation interval start/end dates
     $aCurrentOperationIntervalDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($this->_getDate());
     // For each campaign
     foreach ($aCampaigns as $oCampaign) {
         OA::debug('  - Distributing impression inventory requirements for campaign ID: ' . $oCampaign->id, PEAR_LOG_DEBUG);
         $adsCount = count($oCampaign->aAds);
         OA::debug("    - Campaign has {$adsCount} ads.", PEAR_LOG_DEBUG);
         // Get date object to represent campaign expiration date
         if ($oCampaign->impressionTargetDaily > 0 || $oCampaign->clickTargetDaily > 0 || $oCampaign->conversionTargetDaily > 0) {
             // The campaign has a daily target to meet, so treat the
             // campaign as if it expires at the end of "today", regardless
             // of the existance of any activation or expiration dates that
             // may (or may not) be set for the campaign
             $oCampaignExpiryDate = new Date($this->_getDate());
             $oCampaignExpiryDate->setTZ($this->currentTz);
             $oCampaignExpiryDate->setHour(23);
             $oCampaignExpiryDate->setMinute(59);
             $oCampaignExpiryDate->setSecond(59);
             $oCampaignExpiryDate->toUTC();
             // Unless the campaign has an expiry date and it happens before the end of today
             if (!empty($oCampaign->expireTime)) {
                 if ($oCampaignExpiryDate->after($this->_getDate($oCampaign->expireTime))) {
                     $oCampaignExpiryDate = $this->_getDate($oCampaign->expireTime);
                 }
             }
         } else {
             if (!empty($oCampaign->expireTime) && ($oCampaign->impressionTargetTotal > 0 || $oCampaign->clickTargetTotal > 0 || $oCampaign->conversionTargetTotal > 0)) {
                 // The campaign has an expiration date, and has some kind of
                 // (total) inventory requirement, so treat the campaign as if
                 // it expires at the expiration date/time
                 $oCampaignExpiryDate = $this->_getDate($oCampaign->expireTime);
             } else {
                 // Error! There should not be any other kind of high-priority
                 // campaign in terms of activation/expiration dates and
                 // either (total) inventory requirements or daily targets
                 $message = "- Error calculating the end date for Campaign ID {$oCampaign->id}";
                 OA::debug($message, PEAR_LOG_ERR);
                 continue;
             }
         }
         // Determine number of remaining operation intervals for campaign
         $message = "    - Calculating campaign remaining operation intervals.";
         OA::debug($message, PEAR_LOG_DEBUG);
         $campaignRemainingOperationIntervals = OX_OperationInterval::getIntervalsRemaining($aCurrentOperationIntervalDates['start'], $oCampaignExpiryDate);
         // For all ads in the campaign, determine:
         // - If the ad is capable of delivery in the current operation
         //   interval, or not, based on if it is linked to any zones, and,
         //   if so:
         // - If the ad is capable of delivery in the current operation
         //   interval, or not, based on delivery limitation(s), and if so;
         // - The result of the weight of the ad multiplied by the
         //   number of operation intervals remaining in which the ad
         //   is capable of delivering
         $aAdZones = array();
         $aAdDeliveryLimitations = array();
         $aAdBlockedForCurrentOI = array();
         $aAdWeightRemainingOperationIntervals = array();
         $aInvalidAdIds = array();
         reset($oCampaign->aAds);
         while (list($key, $oAd) = each($oCampaign->aAds)) {
             // Only calculate values for active ads
             if ($oAd->active && $oAd->weight > 0) {
                 $message = "    - Calculating remaining operation intervals for ad ID: {$oAd->id}";
                 OA::debug($message, PEAR_LOG_DEBUG);
                 // Get all zones associated with the ad
                 $aAdsZones = $this->oDal->getAdZoneAssociationsByAds(array($oAd->id));
                 $aAdZones[$oAd->id] = @$aAdsZones[$oAd->id];
                 if (is_null($aAdZones[$oAd->id])) {
                     $aInvalidAdIds[] = $oAd->id;
                     $message = "      - Ad ID {$oAd->id} has no linked zones, will skip...";
                     OA::debug($message, PEAR_LOG_ERR);
                     continue;
                 }
                 // Prepare a delivery limitation object for the ad
                 $aAdDeliveryLimitations[$oAd->id] = new OA_Maintenance_Priority_DeliveryLimitation($oAd->getDeliveryLimitations());
                 // Is the ad blocked from delivering in the current operation interval?
                 $aAdBlockedForCurrentOI[$oAd->id] = $aAdDeliveryLimitations[$oAd->id]->deliveryBlocked($aCurrentOperationIntervalDates['start']);
                 // Determine how many operation intervals remain that the ad can deliver in
                 $adRemainingOperationIntervals = $aAdDeliveryLimitations[$oAd->id]->getActiveAdOperationIntervals($campaignRemainingOperationIntervals, $aCurrentOperationIntervalDates['start'], $oCampaignExpiryDate);
                 // Determine the value of the ad weight multiplied by the number
                 // of operation intervals remaining that the ad can deliver in
                 if ($oAd->weight > 0) {
                     $aAdWeightRemainingOperationIntervals[$oAd->id] = $oAd->weight * $adRemainingOperationIntervals;
                 } else {
                     $aAdWeightRemainingOperationIntervals[$oAd->id] = 0;
                 }
             }
         }
         // Get the total sum of the ad weight * remaining OI values
         $sumAdWeightRemainingOperationIntervals = array_sum($aAdWeightRemainingOperationIntervals);
         // For each (active) ad that is capable of delivering in the current
         // operation interval, determine how many of the campaign's required
         // impressions should be alloced as the ad's required impressions
         // For each advertisement
         reset($oCampaign->aAds);
         while (list($key, $oAd) = each($oCampaign->aAds)) {
             if (in_array($oAd->id, $aInvalidAdIds)) {
                 OA::debug('       - Skipping ad ID: ' . $oAd->id, PEAR_LOG_DEBUG);
                 continue;
             }
             OA::debug('     - Calculating required impressions for ad ID: ' . $oAd->id, PEAR_LOG_DEBUG);
             // Get impressions required
             $totalRequiredAdImpressions = 0;
             if ($oAd->active && $oAd->weight > 0 && $aAdBlockedForCurrentOI[$oAd->id] !== true) {
                 $totalRequiredAdImpressions = $oCampaign->requiredImpressions * ($aAdWeightRemainingOperationIntervals[$oAd->id] / $sumAdWeightRemainingOperationIntervals);
             }
             if ($totalRequiredAdImpressions <= 0) {
                 OA::debug('       - No required impressions for ad ID: ' . $oAd->id, PEAR_LOG_DEBUG);
                 continue;
             }
             // Based on the average zone pattern of the zones the ad is
             // linked to, calculate how many of these impressions should
             // be delivered in the next operation interval
             OA::debug('       - Calculating next OI required impressions for ad ID: ' . $oAd->id, PEAR_LOG_DEBUG);
             $oAd->requiredImpressions = $this->_getAdImpressions($oAd, $totalRequiredAdImpressions, $aCurrentOperationIntervalDates['start'], $oCampaignExpiryDate, $aAdDeliveryLimitations[$oAd->id], $aAdZones[$oAd->id]);
             $aRequiredAdImpressions[] = array('ad_id' => $oAd->id, 'required_impressions' => $oAd->requiredImpressions);
         }
     }
     // Save the required impressions into the temporary database table
     OA::setTempDebugPrefix('- ');
     // Check if table exists
     if (!isset($GLOBALS['_OA']['DB_TABLES']['tmp_ad_required_impression'])) {
         if ($this->oTable->createTable('tmp_ad_required_impression', null, true) !== false) {
             // Remember that table was created
             $GLOBALS['_OA']['DB_TABLES']['tmp_ad_required_impression'] = true;
         }
     }
     $this->oDal->saveRequiredAdImpressions($aRequiredAdImpressions);
 }
示例#12
0
 /**
  * A method to return an array containing the days in the span, including the start
  * and end days, where each day in the array is formatted as a string.
  *
  * @param string $format An optional PEAR::Date compatible format string.
  * @return array An array of the days in the span.
  */
 function getDayArray($format = '%Y-%m-%d')
 {
     $aDays = array();
     $oDate = new Date();
     $oDate->copy($this->oStartDate);
     while (!$oDate->after($this->oEndDate)) {
         $aDays[] = $oDate->format($format);
         $oDate->addSeconds(SECONDS_PER_DAY);
     }
     return $aDays;
 }
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;
            }
        }
    }
}
/**
 * Returns the Account balance for $account at the end of each day between $startDate and $endDate.
 * 
 * Considers the planned transactions of $account.
 * 
 * @param object $account The Account object for which the balance should be calculated. 
 * It should be 'fresh', i. e. no transactions of any type should have been fetched from it.
 * @param object $startDate The first date the balance should be calculated for as Date object.
 * @param object $endDate The last date the balance should be calculated for as Date object.
 * @return array Array of Amount objects corresponding to the balance of $account at each day between
 * $startDate and $endDate. The array keys are the dates as ISO-String (yyyy-mm-dd). 
 */
function getDailyAmount($account, $startDate, $endDate, $isoDates = true, $startWithBalance = false, $includePlannedTransactions = false)
{
    global $badgerDb;
    $account->setTargetFutureCalcDate($endDate);
    $account->setOrder(array(array('key' => 'valutaDate', 'dir' => 'asc')));
    if (!$includePlannedTransactions) {
        $account->setType('finished');
    }
    $result = array();
    $startDate->setHour(0);
    $startDate->setMinute(0);
    $startDate->setSecond(0);
    $endDate->setHour(0);
    $endDate->setMinute(0);
    $endDate->setSecond(0);
    $currentDate = new Date($startDate);
    $currentAmount = new Amount();
    $firstRun = true;
    //foreach transaction
    while ($currentTransaction = $account->getNextTransaction()) {
        if ($currentDate->after($endDate)) {
            //we reached $endDAte
            break;
        }
        if ($firstRun && $startWithBalance) {
            $currentAmount = new Amount($currentTransaction->getBalance());
            $currentAmount->sub($currentTransaction->getAmount());
            $firstRun = false;
        }
        //fill all dates between last and this transaction with the old amount
        while (is_null($tmp = $currentTransaction->getValutaDate()) ? false : $currentDate->before($tmp)) {
            if ($isoDates) {
                $key = $currentDate->getDate();
            } else {
                $key = $currentDate->getTime();
            }
            $result[$key] = new Amount($currentAmount);
            $currentDate->addSeconds(24 * 60 * 60);
            if ($currentDate->after($endDate)) {
                //we reached $endDAte
                break;
            }
        }
        $currentAmount->add($currentTransaction->getAmount());
    }
    if ($firstRun && $startWithBalance) {
        $newAccountManager = new AccountManager($badgerDb);
        $newAccount = $newAccountManager->getAccountById($account->getId());
        $newAccount->setOrder(array(array('key' => 'valutaDate', 'dir' => 'asc')));
        while ($newTransaction = $newAccount->getNextTransaction()) {
            $currentDate = $newTransaction->getValutaDate();
            if ($currentDate->after($startDate)) {
                //we reached $endDAte
                break;
            }
            $currentAmount = new Amount($newTransaction->getBalance());
        }
        $currentDate = new Date($startDate);
        if ($isoDates) {
            $key = $currentDate->getDate();
        } else {
            $key = $currentDate->getTime();
        }
        $result[$key] = new Amount($currentAmount);
    }
    //fill all dates after the last transaction with the newest amount
    while (Date::compare($currentDate, $endDate) <= 0) {
        if ($isoDates) {
            $key = $currentDate->getDate();
        } else {
            $key = $currentDate->getTime();
        }
        $result[$key] = new Amount($currentAmount);
        $currentDate->addSeconds(24 * 60 * 60);
    }
    return $result;
}
示例#15
0
 /**
  * A method to check if the campaign is expired
  *
  * @return bool
  */
 function _isExpired()
 {
     static $oServiceLocator;
     if (!empty($this->expire_time) && $this->expire_time != OX_DATAOBJECT_NULL) {
         if (!isset($oServiceLocator)) {
             $oServiceLocator =& OA_ServiceLocator::instance();
         }
         if (!($oNow = $oServiceLocator->get('now'))) {
             $oNow = new Date();
         }
         $oNow->toUTC();
         $oExpire = new Date($this->expire_time);
         $oExpire->setTZbyID('UTC');
         if ($oNow->after($oExpire)) {
             return true;
         }
     }
     return false;
 }
示例#16
0
 /**
  * A private method to check if the returned stats may be inaccurate
  * becuase of an upgrade from a non TZ-enabled version
  *
  */
 function _checkStatsAccuracy()
 {
     $utcUpdate = OA_Dal_ApplicationVariables::get('utc_update');
     if (!empty($utcUpdate)) {
         $oUpdate = new Date($utcUpdate);
         $oUpdate->setTZbyID('UTC');
         // Add 12 hours
         $oUpdate->addSeconds(3600 * 12);
         if (!empty($this->aDates['day_begin']) && !empty($this->aDates['day_end'])) {
             $startDate = new Date($this->aDates['day_begin']);
             $endDate = new Date($this->aDates['day_end']);
             if ($oUpdate->after($endDate) || $oUpdate->after($startDate)) {
                 $this->displayInaccurateStatsWarning = true;
             }
         } else {
             // All statistics
             $this->displayInaccurateStatsWarning = true;
         }
     }
 }
 private function updateExpandedDates($start, $end, $updateTransferal = true)
 {
     if ($this->beginDate->equals($this->originalBeginDate)) {
         return;
     }
     $accountManager = new AccountManager($this->badgerDb);
     $compareAccount = $accountManager->getAccountById($this->account->getId());
     $compareAccount->setFilter(array(array('key' => 'plannedTransactionId', 'op' => 'eq', 'val' => $this->id), array('key' => 'valutaDate', 'op' => 'ge', 'val' => new Date($start)), array('key' => 'valutaDate', 'op' => 'le', 'val' => new Date($end))));
     $compareAccount->setOrder(array(array('key' => 'valutaDate', 'dir' => 'asc')));
     $date = new Date($this->beginDate);
     $originalDate = new Date($this->originalBeginDate);
     $windowStart = $this->previousOccurence(new Date($originalDate), $this->originalBeginDate);
     $windowEnd = $this->nextOccurence(new Date($originalDate), $this->originalBeginDate);
     while (!$date->after($windowStart)) {
         $date = $this->nextOccurence($date);
     }
     while ($currentCompareTransaction = $compareAccount->getNextTransaction()) {
         while ($originalDate->before($currentCompareTransaction->getValutaDate())) {
             $originalDate = $this->nextOccurence($originalDate, $this->originalBeginDate);
             $date = $this->nextOccurence($date);
         }
         if ($originalDate->equals($currentCompareTransaction->getValutaDate())) {
             $currentCompareTransaction->setValutaDate(new Date($date));
         }
     }
     //while compareTransactions
     if ($updateTransferal && $this->transferalTransaction) {
         $this->transferalTransaction->updateExpandedDates($start, $end, false);
     }
 }
示例#18
0
 /**
  * Sets the span from the elapsed time between two dates
  *
  * The time span is unsigned, so the date's order is not important.
  *
  * @param object $date1 first Date
  * @param object $date2 second Date
  *
  * @return   bool       true on success
  * @access   public
  * @see      Date_Span::set()
  */
 function setFromDateDiff($date1, $date2)
 {
     if (!is_a($date1, 'date') or !is_a($date2, 'date')) {
         return false;
     }
     // create a local copy of instance, in order avoid changes the object
     // reference when its object has converted to UTC due PHP5 is always
     // passed the object by reference.
     $tdate1 = new Date($date1);
     $tdate2 = new Date($date2);
     // convert to UTC
     $tdate1->toUTC();
     $tdate2->toUTC();
     if ($tdate1->after($tdate2)) {
         list($tdate1, $tdate2) = array($tdate2, $tdate1);
     }
     $days = Date_Calc::dateDiff($tdate1->getDay(), $tdate1->getMonth(), $tdate1->getYear(), $tdate2->getDay(), $tdate2->getMonth(), $tdate2->getYear());
     $hours = $tdate2->getHour() - $tdate1->getHour();
     $mins = $tdate2->getMinute() - $tdate1->getMinute();
     $secs = $tdate2->getSecond() - $tdate1->getSecond();
     $this->setFromSeconds($days * 86400 + $hours * 3600 + $mins * 60 + $secs);
     return true;
 }
示例#19
0
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;
        }
    }
}
示例#20
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.
     $prefix = $this->getTablePrefix();
     $oNowDate = new Date($oDate);
     $oNowDate->toUTC();
     $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_time AS start,\n                ca.expire_time AS end\n            FROM\n                {$prefix}campaigns AS ca,\n                {$prefix}clients AS cl\n            WHERE\n                ca.clientid = cl.clientid\n                AND\n                ((\n                    ca.status = " . $this->oDbh->quote(OA_ENTITY_STATUS_RUNNING, 'integer') . " AND\n                    (\n                        ca.expire_time IS NOT NULL\n                        OR\n                        (\n                            ca.views > 0\n                            OR\n                            ca.clicks > 0\n                            OR\n                            ca.conversions > 0\n                        )\n                    )\n                ) OR (\n                    ca.status = " . $this->oDbh->quote(OA_ENTITY_STATUS_AWAITING, 'integer') . " AND\n                    (\n                        ca.activate_time <= " . $this->oDbh->quote($oNowDate->getDate(DATE_FORMAT_ISO), 'timestamp') . "\n                        AND\n                        (\n                            ca.weight > 0\n                            OR\n                            ca.priority > 0\n                        )\n                        AND\n                        (\n                            ca.expire_time >= " . $this->oDbh->quote($oNowDate->getDate(DATE_FORMAT_ISO), 'timestamp') . "\n                            OR\n                            ca.expire_time IS NULL\n                        )\n                    )\n                ))\n            ORDER BY\n                advertiser_id";
     OA::debug('- Requesting campaigns to test for activation/deactivation', PEAR_LOG_DEBUG);
     $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) {
                 OA::debug('  - Selecting impressions, clicks and conversions for this running campaign ID = ' . $aCampaign['campaign_id'], PEAR_LOG_DEBUG);
                 // 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 (isset($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 (!isset($valuesRow['impressions'])) {
                         // No impressions
                         $valuesRow['impressions'] = 0;
                     }
                     if (!isset($valuesRow['clicks'])) {
                         // No clicks
                         $valuesRow['clicks'] = 0;
                     }
                     if (!isset($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 (!empty($aCampaign['end'])) {
                 // The campaign has a valid end date, stored in in UTC
                 $oEndDate = new Date($aCampaign['end']);
                 $oEndDate->setTZByID('UTC');
                 if ($oDate->after($oEndDate)) {
                     // The end date has been passed; disable the campaign
                     $disableReason |= OX_CAMPAIGN_DISABLED_DATE;
                     $message = "  - Passed campaign end time of '" . $oEndDate->getDate() . " UTC" . "': 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') {
                     OA::debug("  - Sending campaign deactivated email ", PEAR_LOG_DEBUG);
                     $oEmail->sendCampaignActivatedDeactivatedEmail($aCampaign['campaign_id'], $disableReason);
                     // Also send campaignDeliveryEmail for the campaign we just deactivated.
                     $doClients = OA_Dal::staticGetDO('clients', $aCampaign['advertiser_id']);
                     $aAdvertiser = $doClients->toArray();
                     OA::debug("  - Sending campaign delivery email ", PEAR_LOG_DEBUG);
                     $oStart = new Date($aAdvertiser['reportlastdate']);
                     $oEnd = new Date($oDate);
                     // Set end date to tomorrow so we get stats for today.
                     $oEnd->addSpan(new Date_Span('1-0-0-0'));
                     $oEmail->sendCampaignDeliveryEmail($aAdvertiser, $oStart, $oEnd, $aCampaign['campaign_id']);
                 }
             } 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
                     OA::debug("  - Sending campaign 'soon deactivated' email ", PEAR_LOG_DEBUG);
                     $oEmail->sendCampaignImpendingExpiryEmail($oDate, $aCampaign['campaign_id']);
                 }
             }
         } elseif (!empty($aCampaign['start'])) {
             // The campaign is awaiting activation and has a valid start date, stored in UTC
             $oStartDate = new Date($aCampaign['start']);
             $oStartDate->setTZByID('UTC');
             // 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) {
                 OA::debug("  - The campaign ID " . $aCampaign['campaign_id'] . " has an impression, click and/or conversion target, requesting impressions so far", PEAR_LOG_DEBUG);
                 $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)
             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)) {
                 $message = "- Passed campaign start time of '" . $oStartDate->getDate() . " UTC" . "': 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']);
                 if ($aCampaign['send_activate_deactivate_email'] == 't') {
                     OA::debug("  - Sending activation email for campaign ID " . $aCampaign['campaign_id'], PEAR_LOG_DEBUG);
                     $oEmail->sendCampaignActivatedDeactivatedEmail($aCampaign['campaign_id']);
                 }
             }
         }
     }
 }
示例#21
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;
 }
示例#22
0
 /**
  * A private method to prepare the report range information from an
  * OA_Admin_DaySpan object.
  *
  * @access private
  * @param OA_Admin_DaySpan $oDaySpan The OA_Admin_DaySpan object to set
  *                                   the report range information from.
  */
 function _prepareReportRange($oDaySpan)
 {
     global $date_format;
     if (!empty($oDaySpan)) {
         $this->_oDaySpan = $oDaySpan;
         $this->_startDateString = $oDaySpan->getStartDateString($date_format);
         $this->_endDateString = $oDaySpan->getEndDateString($date_format);
     } else {
         $oDaySpan = new OA_Admin_DaySpan();
         // take as the start date the date when adds were serverd
         $aConf = $GLOBALS['_MAX']['CONF'];
         $oDbh = OA_DB::singleton();
         $query = "SELECT MIN(date_time) as min_datetime FROM " . $oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['data_summary_ad_hourly'], true) . " WHERE 1=1";
         $startDate = $oDbh->queryRow($query);
         $startDate = $startDate['min_datetime'];
         $oStartDate = new Date($startDate);
         $oEndDate = new Date();
         $oDaySpan->setSpanDays($oStartDate, $oEndDate);
         $this->_oDaySpan =& $oDaySpan;
         $this->_startDateString = MAX_Plugin_Translation::translate('Beginning', $this->module, $this->package);
         $this->_endDateString = $oDaySpan->getEndDateString($date_format);
     }
     $utcUpdate = OA_Dal_ApplicationVariables::get('utc_update');
     if (!empty($utcUpdate)) {
         $oUpdate = new Date($utcUpdate);
         $oUpdate->setTZbyID('UTC');
         // Add 12 hours
         $oUpdate->addSeconds(3600 * 12);
         $startDate = new Date($oDaySpan->oStartDate);
         $endDate = new Date($oDaySpan->oEndDate);
         if ($oUpdate->after($endDate) || $oUpdate->after($startDate)) {
             $this->_displayInaccurateStatsWarning = true;
         }
     }
 }
示例#23
0
 /**
  * ???
  *
  * @param integer $zoneId The ID of the zone to be tested.
  * @param unknown_type $campaignid ???
  * @param unknown_type $newStart ???
  * @param unknown_type $newEnd ???
  * @return unknown ???
  */
 function _checkEmailZoneAdAssoc($zoneId, $campaignid, $newStart = false, $newEnd = false)
 {
     // Suppress PEAR error handling for this method...
     PEAR::pushErrorHandling(null);
     require_once 'Date.php';
     // This is an email zone, so check all current linked ads for active date ranges
     $aOtherAds = Admin_DA::getAdZones(array('zone_id' => $zoneId));
     $campaignVariables = Admin_DA::getPlacement($campaignid);
     if ($newStart) {
         $campaignVariables['activate_time'] = $newStart;
     }
     if ($newEnd) {
         $campaignVariables['expire_time'] = $newEnd;
     }
     if (empty($campaignVariables['activate_time']) && empty($campaignVariables['expire_time'])) {
         return PEAR::raiseError($GLOBALS['strEmailNoDates'], MAX_ERROR_EMAILNODATES);
     }
     $campaignStart = new Date($campaignVariables['activate_time']);
     $campaignStart->setTZbyID('UTC');
     $campaignEnd = new Date($campaignVariables['expire_time']);
     $campaignEnd->setTZbyID('UTC');
     $okToLink = true;
     foreach ($aOtherAds as $azaID => $aAdVariables) {
         $aOtherAdVariables = Admin_DA::getAd($aAdVariables['ad_id']);
         if ($aOtherAdVariables['placement_id'] == $campaignid) {
             continue;
         }
         $otherCampaignVariables = Admin_DA::getPlacement($aOtherAdVariables['placement_id']);
         if (empty($otherCampaignVariables['activate_time']) || empty($otherCampaignVariables['expire_time'])) {
             $okToLink = false;
             break;
         }
         // Do not allow link if either start or end date is within another linked campaign dates
         $otherCampaignStart = new Date($otherCampaignVariables['activate_time']);
         $otherCampaignStart->setTZbyID('UTC');
         $otherCampaignEnd = new Date($otherCampaignVariables['expire_time']);
         $otherCampaignEnd->setTZbyID('UTC');
         if ($campaignStart->after($otherCampaignStart) && $campaignStart->before($otherCampaignEnd) || $campaignStart->equals($otherCampaignStart)) {
             $okToLink = false;
             break;
         }
         if ($campaignEnd->after($otherCampaignStart) && $campaignEnd->before($otherCampaignEnd) || $campaignEnd->equals($otherCampaignEnd)) {
             $okToLink = false;
             break;
         }
     }
     if (!$okToLink) {
         $link = "campaign-edit.php?clientid={$otherCampaignVariables['advertiser_id']}&campaignid={$otherCampaignVariables['placement_id']}";
         return PEAR::raiseError($GLOBALS['strDatesConflict'] . ": <a href='{$link}'>" . $otherCampaignVariables['name'] . "</a>", MAX_ERROR_EXISTINGCAMPAIGNFORDATES);
     }
     PEAR::popErrorHandling();
     return true;
 }