Ejemplo n.º 1
0
 /**
  * A method that can be inherited and used by children classes to get the
  * required date span of a statistics page.
  *
  * @param object $oCaller      The calling object. Expected to have the
  *                             the following class variables:
  *                                  $oCaller->aPlugins    - An array of statistics fields plugins
  *                                  $oCaller->oStartDate  - Will be set by method
  *                                  $oCaller->spanDays    - Will be set by method
  *                                  $oCaller->spanWeeks   - Will be set by method
  *                                  $oCaller->spanMonths  - Will be set by method
  * @param array  $aParams      An array of query parameters for
  *                             {@link Admin_DA::fromCache()}.
  */
 function getSpan(&$oCaller, $aParams)
 {
     $oStartDate = new Date(date('Y-m-d'));
     $oStartDate->setHour(0);
     $oStartDate->setMinute(0);
     $oStartDate->setSecond(0);
     // Check span using all plugins
     foreach ($oCaller->aPlugins as $oPlugin) {
         $aPluginParams = call_user_func(array($oPlugin, 'getHistorySpanParams'));
         $aSpan = Admin_DA::fromCache('getHistorySpan', $aParams + $aPluginParams);
         if (!empty($aSpan['start_date'])) {
             $oDate = new Date($aSpan['start_date']);
             $oDate->setTZbyID('UTC');
             if ($oDate->before($oStartDate)) {
                 $oDate->convertTZ($oStartDate->tz);
                 $oStartDate = new Date($oDate);
             }
         }
     }
     $oStartDate->setHour(0);
     $oStartDate->setMinute(0);
     $oStartDate->setSecond(0);
     $oNow = new Date();
     $oSpan = new Date_Span(new Date($oStartDate), new Date($oNow->format('%Y-%m-%d')));
     // Store the span data required for stats display
     $oCaller->oStartDate = $oStartDate;
     $oCaller->spanDays = (int) ceil($oSpan->toDays());
     $oCaller->spanWeeks = (int) ceil($oCaller->spanDays / 7) + ($oCaller->spanDays % 7 ? 1 : 0);
     $oCaller->spanMonths = ($oNow->getYear() - $oStartDate->getYear()) * 12 + ($oNow->getMonth() - $oStartDate->getMonth()) + 1;
     // Set the caller's aDates span in the event that it's empty
     if (empty($oCaller->aDates)) {
         $oCaller->aDates['day_begin'] = $oStartDate->format('%Y-%m-%d');
         $oCaller->aDates['day_end'] = $oNow->format('%Y-%m-%d');
     }
 }
Ejemplo n.º 2
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;
 }
Ejemplo n.º 3
0
 /**
  * Method used to convert the user date (that might be in a
  * specific timezone) to a GMT date.
  *
  * @access  public
  * @param   string $date The user based date
  * @return  string The date in the GMT timezone
  */
 function getDateGMT($date)
 {
     $dt = new Date($date);
     $dt->setTZbyID(Date_API::getPreferredTimezone());
     $dt->toUTC();
     return $dt->format('%Y-%m-%d %H:%M:%S');
 }
Ejemplo n.º 4
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;
         }
     }
 }
Ejemplo n.º 5
0
 /**
  * Calculates the effective CPM (eCPM)
  *
  * @param int $revenueType revenue type (CPM, CPA, etc) as defined in constants.php.
  * @param double $revenue revenue amount, eg 1.55.  CPM, CPC, CPA: the rate. Tenancy: the total.
  * @param int $impressions the number of impressions.
  * @param int $clicks the number of clicks
  * @param int $conversions the number of conversions.
  * @param string $startDate start date of the campaign. Required for tenancy.
  * @param string $endDate end date of the campaign. Required for tenancy.
  * @param double defaultClickRatio click ratio to use when there are no impressions.
  *                                 If null, uses the value in the config file.
  * @param double defaultConversionRatio conversion ratio to use when there are no impressions.
  *                                 If null, uses the value in the config file.
  *
  * @return double the eCPM
  */
 public static function getEcpm($revenueType, $revenue, $impressions = 0, $clicks = 0, $conversions = 0, $startDate = null, $endDate = null, $defaultClickRatio = null, $defaultConversionRatio = null)
 {
     $ecpm = 0.0;
     switch ($revenueType) {
         case MAX_FINANCE_CPM:
             // eCPM = CPM
             return $revenue;
             break;
         case MAX_FINANCE_CPC:
             if ($impressions != 0) {
                 $ecpm = $revenue * $clicks / $impressions * 1000;
             } else {
                 if (!$defaultClickRatio) {
                     $defaultClickRatio = $GLOBALS['_MAX']['CONF']['priority']['defaultClickRatio'];
                 }
                 $ecpm = $defaultClickRatio * $revenue * 1000;
             }
             break;
         case MAX_FINANCE_CPA:
             if ($impressions != 0) {
                 $ecpm = $revenue * $conversions / $impressions * 1000;
             } else {
                 if (!$defaultConversionRatio) {
                     $defaultConversionRatio = $GLOBALS['_MAX']['CONF']['priority']['defaultConversionRatio'];
                 }
                 $ecpm = $defaultConversionRatio * $revenue * 1000;
             }
             break;
         case MAX_FINANCE_MT:
             if ($impressions != 0) {
                 if ($startDate && $endDate) {
                     $oStart = new Date($startDate);
                     $oStart->setTZbyID('UTC');
                     $oEnd = new Date($endDate);
                     $oEnd->setTZbyID('UTC');
                     $oNow = new Date(date('Y-m-d'));
                     $oNow->setTZbyID('UTC');
                     $daysInCampaign = new Date_Span();
                     $daysInCampaign->setFromDateDiff($oStart, $oEnd);
                     $daysInCampaign = ceil($daysInCampaign->toDays());
                     $daysSoFar = new Date_Span();
                     $daysSoFar->setFromDateDiff($oStart, $oNow);
                     $daysSoFar = ceil($daysSoFar->toDays());
                     $ecpm = $revenue / $daysInCampaign * $daysSoFar / $impressions * 1000;
                 } else {
                     // Not valid without start and end dates.
                     $ecpm = 0.0;
                 }
             } else {
                 $ecpm = 0.0;
             }
             break;
     }
     return $ecpm;
 }
Ejemplo n.º 6
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;
 }
 /**
  * Tests that an e-mail reporting on placement delivery is able to be
  * generated correctly.
  */
 function testPrepareCampaignDeliveryEmail()
 {
     $aConf =& $GLOBALS['_MAX']['CONF'];
     $aConf['webpath']['admin'] = 'example.com';
     $aConf['email']['fromAddress'] = '*****@*****.**';
     $aConf['email']['fromName'] = 'Miguel Correa';
     $aConf['email']['fromCompany'] = 'OpenX Limited';
     $aConf['email']['useManagerDetails'] = true;
     $mockName = uniqid('PartialMockOA_Email_');
     Mock::generatePartial('OA_Email', $mockName, array('sendMail'));
     $oEmail = new $mockName();
     $oEmail->setReturnValue('sendMail', true);
     // Prepare valid test data
     $advertiserId = 1;
     $oStartDate = new Date('2007-05-13 00:00:00');
     $oEndDate = new Date('2007-05-19 23:59:59');
     $email = '*****@*****.**';
     $user_name = 'Andrew Hill';
     $clientName = 'Foo Client';
     // Setup a User array, but with no data
     $aUser = array('username', 'contact_name', 'email_address');
     // Test with no advertiser data in the database, and ensure that
     // false is returned
     $result = $oEmail->prepareCampaignDeliveryEmail($aUser, $advertiserId, $oStartDate, $oEndDate);
     $this->assertFalse($result);
     // Generate an advertiser with reports disabled and test, ensuring
     // that false is returned
     $doClients = OA_Dal::factoryDO('clients');
     $doClients->clientname = $clientName;
     $doClients->email = '';
     $doClients->contact = '';
     $doClients->report = 'f';
     $advertiserId = DataGenerator::generateOne($doClients);
     $result = $oEmail->prepareCampaignDeliveryEmail($aUser, $advertiserId, $oStartDate, $oEndDate);
     $this->assertFalse($result);
     // Generate an advertiser with reports enabled, but no other data,
     // and test, ensuring that false is returned
     $doClients = OA_Dal::factoryDO('clients');
     $doClients->clientname = $clientName;
     $doClients->email = '';
     $doClients->contact = '';
     $doClients->report = 't';
     $advertiserId = DataGenerator::generateOne($doClients);
     $result = $oEmail->prepareCampaignDeliveryEmail($aUser, $advertiserId, $oStartDate, $oEndDate);
     $this->assertFalse($result);
     // Generate an advertiser with reports enabled, and a sigle placement,
     // but no ads, ensuring that false is returned
     $doClients = OA_Dal::factoryDO('clients');
     $doClients->clientname = $clientName;
     $doClients->email = '';
     $doClients->contact = '';
     $doClients->report = 't';
     $advertiserId = DataGenerator::generateOne($doClients);
     $doPlacements = OA_Dal::factoryDO('campaigns');
     $doPlacements->clientid = $advertiserId;
     $placementId = DataGenerator::generateOne($doPlacements);
     $result = $oEmail->prepareCampaignDeliveryEmail($aUser, $advertiserId, $oStartDate, $oEndDate);
     $this->assertFalse($result);
     // Generate an advertiser with reports enabled & an email address,
     // and a sigle placement, but no ads, ensuring that the correct report
     // is generated
     $doClients = OA_Dal::factoryDO('clients');
     $doClients->clientname = $clientName;
     $doClients->email = $email;
     $doClients->contact = $user_name;
     $doClients->report = 't';
     $advertiserId = DataGenerator::generateOne($doClients);
     // Create a user to link to this account
     $doUser = OA_Dal::factoryDO('users');
     $doUser->contact_name = $user_name;
     $doUser->email_address = $email;
     $doUser->language = 'en';
     $userId = DataGenerator::generateOne($doUser);
     $aUser = $doUser->toArray();
     // Link the user to the account
     $oUserAccess = new OA_Admin_UI_UserAccess();
     $oUserAccess->linkUserToAccount($userId, $advertiserId, array(), array());
     $doPlacements = OA_Dal::factoryDO('campaigns');
     $doPlacements->clientid = $advertiserId;
     $doPlacements->status = '0';
     $doPlacements->campaignname = 'Default Campaign';
     $placementId1 = DataGenerator::generateOne($doPlacements);
     Language_Loader::load('default', $doUser->language);
     $aResult = $oEmail->prepareCampaignDeliveryEmail($aUser, $advertiserId, $oStartDate, $oEndDate);
     $expectedSubject = "Advertiser report: {$clientName}";
     $expectedContents = "Dear {$user_name},\n\n";
     $expectedContents .= "Below you will find the banner statistics for {$clientName}:\n";
     global $date_format;
     $startDate = $oStartDate->format($date_format);
     $endDate = $oEndDate->format($date_format);
     $expectedContents .= "This report includes statistics from {$startDate} up to {$endDate}.\n\n";
     $expectedContents .= "\nCampaign [id{$placementId1}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId}&campaignid={$placementId1}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "=======================================================\n\n";
     $expectedContents .= "There are no statistics available for this campaign\n\n\n\n";
     $expectedContents .= "Regards,\n   Miguel Correa, OpenX Limited";
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 3);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     // Add another placement with no ads to the above advertiser, and test
     // that the correct report is generated
     $doPlacements = OA_Dal::factoryDO('campaigns');
     $doPlacements->clientid = $advertiserId;
     $doPlacements->campaignname = 'Default Campaign';
     $placementId2 = DataGenerator::generateOne($doPlacements);
     $aResult = $oEmail->prepareCampaignDeliveryEmail($aUser, $advertiserId, $oStartDate, $oEndDate);
     $expectedSubject = "Advertiser report: {$clientName}";
     $expectedContents = "Dear {$user_name},\n\n";
     $expectedContents .= "Below you will find the banner statistics for {$clientName}:\n";
     global $date_format;
     $startDate = $oStartDate->format($date_format);
     $endDate = $oEndDate->format($date_format);
     $expectedContents .= "This report includes statistics from {$startDate} up to {$endDate}.\n\n";
     $expectedContents .= "\nCampaign [id{$placementId1}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId}&campaignid={$placementId1}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "=======================================================\n\n";
     $expectedContents .= "There are no statistics available for this campaign\n\n\n";
     $expectedContents .= "\nCampaign [id{$placementId2}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId}&campaignid={$placementId2}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "=======================================================\n\n";
     $expectedContents .= "There are no statistics available for this campaign\n\n\n\n";
     $expectedContents .= "Regards,\n   Miguel Correa, OpenX Limited";
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 3);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     // Add an ad to the second placements, but with no delivery data, and
     // ensure the correct email is generated (no change to previous!)
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $placementId2;
     $doPlacements->campaignname = 'Default Campaign';
     $adId1 = DataGenerator::generateOne($doBanners);
     $aResult = $oEmail->prepareCampaignDeliveryEmail($aUser, $advertiserId, $oStartDate, $oEndDate);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 3);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     // Add an ad to the second placements, with delivery data outside
     // the current date range, and ensure the correct email is generated
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $placementId2;
     $doBanners->description = 'Test Banner';
     $adId2 = DataGenerator::generateOne($doBanners);
     $doDataSummaryAdHourly = OA_Dal::factoryDO('data_summary_ad_hourly');
     $doDataSummaryAdHourly->date_time = '2007-05-12 12:00:00';
     $doDataSummaryAdHourly->ad_id = $adId2;
     $doDataSummaryAdHourly->impressions = 5000;
     $doDataSummaryAdHourly->clicks = 0;
     $doDataSummaryAdHourly->conversions = 0;
     DataGenerator::generateOne($doDataSummaryAdHourly);
     $aResult = $oEmail->prepareCampaignDeliveryEmail($aUser, $advertiserId, $oStartDate, $oEndDate);
     $expectedSubject = "Advertiser report: {$clientName}";
     $expectedContents = "Dear {$user_name},\n\n";
     $expectedContents .= "Below you will find the banner statistics for {$clientName}:\n";
     global $date_format;
     $startDate = $oStartDate->format($date_format);
     $endDate = $oEndDate->format($date_format);
     $expectedContents .= "This report includes statistics from {$startDate} up to {$endDate}.\n\n";
     $expectedContents .= "\nCampaign [id{$placementId1}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId}&campaignid={$placementId1}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "=======================================================\n\n";
     $expectedContents .= "There are no statistics available for this campaign\n\n\n";
     $expectedContents .= "\nCampaign [id{$placementId2}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId}&campaignid={$placementId2}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "=======================================================\n\n";
     $expectedContents .= " Banner  [id{$adId2}] Test Banner\n";
     $expectedContents .= " ------------------------------------------------------\n";
     $expectedContents .= " Impressions (Total):           5,000\n";
     $expectedContents .= "  No Impressions were logged during the span of this report\n";
     $expectedContents .= "\n\n";
     $expectedContents .= "Regards,\n   Miguel Correa, OpenX Limited";
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 3);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     // Add an ad to the second placements, with delivery data in the
     // report range, and ensure the correct email is generated
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $placementId2;
     $doBanners->description = 'Test Banner';
     $adId3 = DataGenerator::generateOne($doBanners);
     $doDataSummaryAdHourly = OA_Dal::factoryDO('data_summary_ad_hourly');
     $doDataSummaryAdHourly->date_time = '2007-05-14 12:00:00';
     $doDataSummaryAdHourly->ad_id = $adId3;
     $doDataSummaryAdHourly->impressions = 5000;
     $doDataSummaryAdHourly->clicks = 0;
     $doDataSummaryAdHourly->conversions = 0;
     DataGenerator::generateOne($doDataSummaryAdHourly);
     $doDataSummaryAdHourly->date_time = '2007-05-14 13:00:00';
     $doDataSummaryAdHourly->ad_id = $adId3;
     $doDataSummaryAdHourly->impressions = 5000;
     $doDataSummaryAdHourly->clicks = 0;
     $doDataSummaryAdHourly->conversions = 0;
     DataGenerator::generateOne($doDataSummaryAdHourly);
     $doDataSummaryAdHourly->date_time = '2007-05-15 13:00:00';
     $doDataSummaryAdHourly->ad_id = $adId3;
     $doDataSummaryAdHourly->impressions = 5000;
     $doDataSummaryAdHourly->clicks = 0;
     $doDataSummaryAdHourly->conversions = 0;
     DataGenerator::generateOne($doDataSummaryAdHourly);
     $aResult = $oEmail->prepareCampaignDeliveryEmail($aUser, $advertiserId, $oStartDate, $oEndDate);
     $expectedSubject = "Advertiser report: {$clientName}";
     $expectedContents = "Dear {$user_name},\n\n";
     $expectedContents .= "Below you will find the banner statistics for {$clientName}:\n";
     global $date_format;
     $startDate = $oStartDate->format($date_format);
     $endDate = $oEndDate->format($date_format);
     $expectedContents .= "This report includes statistics from {$startDate} up to {$endDate}.\n\n";
     $expectedContents .= "\nCampaign [id{$placementId1}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId}&campaignid={$placementId1}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "=======================================================\n\n";
     $expectedContents .= "There are no statistics available for this campaign\n\n\n";
     $expectedContents .= "\nCampaign [id{$placementId2}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId}&campaignid={$placementId2}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "=======================================================\n\n";
     $expectedContents .= " Banner  [id{$adId2}] Test Banner\n";
     $expectedContents .= " ------------------------------------------------------\n";
     $expectedContents .= " Impressions (Total):           5,000\n";
     $expectedContents .= "  No Impressions were logged during the span of this report\n";
     $expectedContents .= "\n";
     $expectedContents .= " Banner  [id{$adId3}] Test Banner\n";
     $expectedContents .= " ------------------------------------------------------\n";
     $expectedContents .= " Impressions (Total):          15,000\n";
     $expectedContents .= "          15-05-2007:           5,000\n";
     $expectedContents .= "          14-05-2007:          10,000\n";
     $expectedContents .= "   Total this period:          15,000\n";
     $expectedContents .= "\n\n";
     $expectedContents .= "Regards,\n   Miguel Correa, OpenX Limited";
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 3);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     DataGenerator::cleanUp();
     $aConf['webpath']['admin'] = 'example.com';
     $aConf['email']['fromAddress'] = '*****@*****.**';
     $aConf['email']['fromName'] = 'Andrew Hill';
     $aConf['email']['fromCompany'] = 'OpenX Limited';
     $aConf['email']['useManagerDetails'] = true;
     // Test with no start date
     $doClients = OA_Dal::factoryDO('clients');
     $doClients->clientname = $clientName;
     $doClients->email = $email;
     $doClients->contact = $user_name;
     $doClients->report = 't';
     $advertiserId = DataGenerator::generateOne($doClients);
     $doPlacements = OA_Dal::factoryDO('campaigns');
     $doPlacements->clientid = $advertiserId;
     $doPlacements->campaignname = 'Default Campaign';
     $placementId1 = DataGenerator::generateOne($doPlacements);
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $placementId1;
     $doBanners->description = 'Test Banner';
     $adId1 = DataGenerator::generateOne($doBanners);
     $doDataSummaryAdHourly = OA_Dal::factoryDO('data_summary_ad_hourly');
     $doDataSummaryAdHourly->date_time = '2007-05-14 02:00:00';
     $doDataSummaryAdHourly->ad_id = $adId1;
     $doDataSummaryAdHourly->impressions = 5000;
     $doDataSummaryAdHourly->clicks = 0;
     $doDataSummaryAdHourly->conversions = 0;
     DataGenerator::generateOne($doDataSummaryAdHourly);
     $doDataSummaryAdHourly->date_time = '2007-05-14 03:00:00';
     $doDataSummaryAdHourly->ad_id = $adId1;
     $doDataSummaryAdHourly->impressions = 5000;
     $doDataSummaryAdHourly->clicks = 0;
     $doDataSummaryAdHourly->conversions = 0;
     DataGenerator::generateOne($doDataSummaryAdHourly);
     $doDataSummaryAdHourly->date_time = '2007-05-15 03:00:00';
     $doDataSummaryAdHourly->ad_id = $adId1;
     $doDataSummaryAdHourly->impressions = 5000;
     $doDataSummaryAdHourly->clicks = 0;
     $doDataSummaryAdHourly->conversions = 0;
     DataGenerator::generateOne($doDataSummaryAdHourly);
     $aResult = $oEmail->prepareCampaignDeliveryEmail($aUser, $advertiserId, null, $oEndDate);
     $expectedSubject = "Advertiser report: {$clientName}";
     $expectedContents = "Dear {$user_name},\n\n";
     $expectedContents .= "Below you will find the banner statistics for {$clientName}:\n";
     global $date_format;
     $startDate = $oStartDate->format($date_format);
     $endDate = $oEndDate->format($date_format);
     $expectedContents .= "This report includes all statistics up to {$endDate}.\n\n";
     $expectedContents .= "\nCampaign [id{$placementId1}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId}&campaignid={$placementId1}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "=======================================================\n\n";
     $expectedContents .= " Banner  [id{$adId1}] Test Banner\n";
     $expectedContents .= " ------------------------------------------------------\n";
     $expectedContents .= " Impressions (Total):          15,000\n";
     $expectedContents .= "          15-05-2007:           5,000\n";
     $expectedContents .= "          14-05-2007:          10,000\n";
     $expectedContents .= "   Total this period:          15,000\n";
     $expectedContents .= "\n\n";
     $expectedContents .= "Regards,\n   Andrew Hill, OpenX Limited";
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 3);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     // Retest with a different timezone, same interval
     $oStartDate = new Date('2007-05-10 00:00:00');
     $oEndDate = new Date('2007-05-19 23:59:00');
     $oStartDate->setTZbyID('PST');
     $oEndDate->setTZbyID('PST');
     $aResult = $oEmail->prepareCampaignDeliveryEmail($aUser, $advertiserId, $oStartDate, $oEndDate);
     $expectedSubject = "Advertiser report: {$clientName}";
     $expectedContents = "Dear {$user_name},\n\n";
     $expectedContents .= "Below you will find the banner statistics for {$clientName}:\n";
     global $date_format;
     $startDate = $oStartDate->format($date_format);
     $endDate = $oEndDate->format($date_format);
     $expectedContents .= "This report includes statistics from {$startDate} up to {$endDate}.\n\n";
     $expectedContents .= "\nCampaign [id{$placementId1}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId}&campaignid={$placementId1}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "=======================================================\n\n";
     $expectedContents .= " Banner  [id{$adId1}] Test Banner\n";
     $expectedContents .= " ------------------------------------------------------\n";
     $expectedContents .= " Impressions (Total):          15,000\n";
     $expectedContents .= "          14-05-2007:           5,000\n";
     $expectedContents .= "          13-05-2007:          10,000\n";
     $expectedContents .= "   Total this period:          15,000\n";
     $expectedContents .= "\n\n";
     $expectedContents .= "Regards,\n   Andrew Hill, OpenX Limited";
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 3);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     // Retest with a different timezone, shorter interval
     $oStartDate = new Date('2007-05-13 00:00:00');
     $oEndDate = new Date('2007-05-13 23:59:00');
     $oStartDate->setTZbyID('PST');
     $oEndDate->setTZbyID('PST');
     $aResult = $oEmail->prepareCampaignDeliveryEmail($aUser, $advertiserId, $oStartDate, $oEndDate);
     $expectedSubject = "Advertiser report: {$clientName}";
     $expectedContents = "Dear {$user_name},\n\n";
     $expectedContents .= "Below you will find the banner statistics for {$clientName}:\n";
     global $date_format;
     $startDate = $oStartDate->format($date_format);
     $endDate = $oEndDate->format($date_format);
     $expectedContents .= "This report includes statistics from {$startDate} up to {$endDate}.\n\n";
     $expectedContents .= "\nCampaign [id{$placementId1}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId}&campaignid={$placementId1}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "=======================================================\n\n";
     $expectedContents .= " Banner  [id{$adId1}] Test Banner\n";
     $expectedContents .= " ------------------------------------------------------\n";
     $expectedContents .= " Impressions (Total):          15,000\n";
     $expectedContents .= "          13-05-2007:          10,000\n";
     $expectedContents .= "   Total this period:          10,000\n";
     $expectedContents .= "\n\n";
     $expectedContents .= "Regards,\n   Andrew Hill, OpenX Limited";
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 3);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     DataGenerator::cleanUp(array('accounts', 'account_user_assoc'));
 }
Ejemplo n.º 8
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;
 }
Ejemplo n.º 9
0
 /**
  * requires permission checks
  *
  * @param array $aParam
  * @return array
  */
 function getAuditLogForAuditWidget($aParam = array())
 {
     $oAudit = OA_Dal::factoryDO('audit');
     // Apply account level filters
     if (!empty($aParam['account_id'])) {
         $oAudit->account_id = $aParam['account_id'];
     }
     if (!empty($aParam['advertiser_account_id'])) {
         $oAudit->advertiser_account_id = $aParam['advertiser_account_id'];
     }
     if (!empty($aParam['website_account_id'])) {
         $oAudit->website_account_id = $aParam['website_account_id'];
     }
     $oDate = new Date();
     $oDate->toUTC();
     $oDate->subtractSpan(new Date_Span('7-0-0-0'));
     $oAudit->whereAdd("username <> 'Maintenance'");
     $oAudit->whereAdd('parentid IS NULL');
     $oAudit->whereAdd("updated >= " . DBC::makeLiteral($oDate->format('%Y-%m-%d %H:%M:%S')));
     $oAudit->orderBy('auditid DESC');
     $oAudit->limit(0, 5);
     $numRows = $oAudit->find();
     $oNow = new Date();
     $aResult = array();
     while ($oAudit->fetch()) {
         $aAudit = $oAudit->toArray();
         $oDate = new Date($aAudit['updated']);
         $oDate->setTZbyID('UTC');
         $oDate->convertTZ($oNow->tz);
         $aAudit['updated'] = $oDate->format('%Y-%m-%d %H:%M:%S');
         $aAudit['details'] = unserialize($aAudit['details']);
         $aAudit['context'] = $this->getContextDescription($aAudit['context']);
         $aResult[] = $aAudit;
     }
     return $aResult;
 }
Ejemplo n.º 10
0
 function now($format = DATE_FORMAT_ISO)
 {
     // this will force to the server time regardless of whether date() is returning UTC time or not
     $dateobj = new Date(gmdate('Y-m-d H:i:s'));
     $dateobj->setTZbyID('UTC');
     if (is_int($format)) {
         $date = $dateobj->getDate($format);
     } else {
         if (is_string($format)) {
             $date = $dateobj->format($format);
         }
     }
     unset($dateobj);
     return $date;
 }
Ejemplo n.º 11
0
 function getContainerContent($page_id, $container_id, $page_content_id = null)
 {
     $page_model =& $this->getDefaultModel();
     $this->auto_render = false;
     $page_id = (int) $page_id;
     $container_id = (int) $container_id;
     if (!$page_id || !$container_id) {
         return null;
     }
     // instantiate the page content controller
     // TODO: put some methods into the page_content controller to do some of this.
     $page_content =& NController::factory('page_content');
     $page_content_model =& $page_content->getDefaultModel();
     $page_content_pk = $page_content_model->primaryKey();
     $asset_ctrl =& NController::singleton('cms_asset_template');
     if (SITE_WORKFLOW && $this->nterchange) {
         // get the users rights and bit compare them below
         $workflow =& NController::factory('workflow');
         $user_rights = $workflow->getWorkflowUserRights($page_model);
     }
     // load up the content
     $content = '';
     // set the time using a trusted source
     $now = new Date(gmdate('Y-m-d H:i:s'));
     $now->setTZbyID('UTC');
     if ($page_content_model->getContainerContent($page_id, $container_id, $this->nterchange, $page_content_id)) {
         $page_content->set('page_id', $page_id);
         while ($page_content_model->fetch()) {
             $page_content->set('page_content_id', $page_content_model->{$page_content_pk});
             $timed_start_obj = $page_content_model->timed_start && $page_content_model->timed_start != '0000-00-00 00:00:00' ? new Date($page_content_model->timed_start) : false;
             $timed_end_obj = $page_content_model->timed_end && $page_content_model->timed_end != '0000-00-00 00:00:00' ? new Date($page_content_model->timed_end) : false;
             if ($timed_start_obj) {
                 $timed_start_obj->setTZbyID('UTC');
             }
             if ($timed_end_obj) {
                 $timed_end_obj->setTZbyID('UTC');
             }
             // set cache lifetimes for the page
             if ($timed_start_obj) {
                 $time_diff = $timed_start_obj->getDate(DATE_FORMAT_UNIXTIME) - $now->getDate(DATE_FORMAT_UNIXTIME);
                 if ($time_diff > 0) {
                     $this->view_cache_lifetimes[] = $time_diff;
                 }
             }
             if ($timed_end_obj) {
                 $time_diff = $timed_end_obj->getDate(DATE_FORMAT_UNIXTIME) - $now->getDate(DATE_FORMAT_UNIXTIME);
                 if ($time_diff > 0) {
                     $this->view_cache_lifetimes[] = $time_diff;
                 }
             }
             if ($timed_end_obj && $timed_end_obj->before($now)) {
                 $timed_end_active = true;
             }
             // if the timed end is in the past then kill it and continue.
             if ($timed_end_obj && $now->after($timed_end_obj)) {
                 // remove the content, which also kills the page cache
                 $page_content_controller =& NController::factory('page_content');
                 $page_content_controller->_auth =& $this->_auth;
                 $page_content_controller->removeContent($page_content_model->{$page_content_pk}, false, true);
                 unset($page_content_controller);
                 continue;
             } else {
                 if ($this->nterchange || !$timed_start_obj || $timed_start_obj && $timed_start_obj->before($now)) {
                     $content_controller =& NController::factory($page_content_model->content_asset);
                     if ($content_controller && is_object($content_controller)) {
                         $content_model =& $content_controller->getDefaultModel();
                         $fields = $content_model->fields();
                         $pk = $content_model->primaryKey();
                         // if we're on the public site, don't grab workflow or draft inserts
                         $conditions = array();
                         if ($this->nterchange && in_array('cms_draft', $fields)) {
                             $conditions = '(cms_draft = 0 OR (cms_draft=1 AND cms_modified_by_user='******'))';
                         } else {
                             $content_model->cms_draft = 0;
                         }
                         $content_model->{$pk} = $page_content_model->content_asset_id;
                         if ($content_model->find(array('conditions' => $conditions), true)) {
                             // last modified
                             if (strtotime($content_model->cms_modified) > $this->page_last_modified) {
                                 $this->page_last_modified = strtotime($content_model->cms_modified);
                             }
                             $template = $asset_ctrl->getAssetTemplate($page_content_model->content_asset, $page_content_model->page_template_container_id);
                             if (SITE_DRAFTS && $this->nterchange) {
                                 $is_draft = false;
                                 $user_owned = false;
                                 $user_id = $this->_auth->currentUserId();
                                 $draft_model =& NModel::factory('cms_drafts');
                                 $draft_model->asset = $content_controller->name;
                                 $draft_model->asset_id = $content_model->{$pk};
                                 if ($draft_model->find(null, true)) {
                                     $is_draft = true;
                                     // fill the local model with the draft info
                                     $current_user_id = isset($this->_auth) && is_object($this->_auth) ? $this->_auth->currentUserID() : 0;
                                     if ($current_user_id == $draft_model->cms_modified_by_user) {
                                         $draft_content = unserialize($draft_model->draft);
                                         foreach ($draft_content as $field => $val) {
                                             $content_model->{$field} = $val;
                                         }
                                         $user_owned = true;
                                         $draft_msg = 'You have saved';
                                     } else {
                                         $user_model =& $this->loadModel('cms_auth');
                                         $user_model->get($draft_model->cms_modified_by_user);
                                         $draft_msg = $user_model->real_name . ' has saved';
                                         unset($user_model);
                                     }
                                 }
                                 unset($draft_model);
                             }
                             if (SITE_WORKFLOW && $this->nterchange) {
                                 if ($workflow_group_model =& $workflow->getWorkflowGroup($page_model)) {
                                     if ($current_workflow =& $workflow->getWorkflow($page_content_model->{$page_content_model->primaryKey()}, $workflow_group_model->{$workflow_group_model->primaryKey()}, $content_controller)) {
                                         $current_user_id = isset($this->_auth) && is_object($this->_auth) ? $this->_auth->currentUserID() : 0;
                                         $content_edit_allowed = $this->content_edit_allowed;
                                         $this->content_edit_allowed = !$current_workflow->submitted && $current_user_id == $current_workflow->cms_modified_by_user ? true : false;
                                         $workflow_draft = unserialize($current_workflow->draft);
                                         foreach ($workflow_draft as $field => $val) {
                                             $content_model->{$field} = $val;
                                         }
                                     }
                                 }
                             }
                             $values = $content_model->toArray();
                             $values['_EDIT_START_'] = '';
                             $values['_EDIT_END_'] = '';
                             if ($this->nterchange && $this->edit) {
                                 $values['_SURFTOEDIT_'] = true;
                             }
                             if ($this->edit) {
                                 if ($this->content_edit_allowed) {
                                     // $values['_EDIT_START_'] .= '<div class="pagecontent" id="pagecontent' . $page_content_model->$page_content_pk . '">' . "\n";
                                     $page_content->set(array('asset' => $content_controller->name, 'asset_id' => $content_model->{$pk}));
                                     $values['_EDIT_START_'] .= $page_content->render(array('action' => 'asset_edit', 'return' => true));
                                 }
                                 $page_content->set(array('asset' => $content_controller->name, 'asset_id' => $content_model->{$pk}, 'page_content_id' => $page_content_model->{$page_content_pk}, 'page_id' => $page_id));
                                 $values['_EDIT_START_'] .= '<div class="editable-region">' . "\n";
                                 if (SITE_WORKFLOW && isset($current_workflow) && $current_workflow) {
                                     if ($this->content_edit_allowed) {
                                         $values['_EDIT_START_'] .= '<div class="workflow">The following content is waiting to be submitted to workflow in the <a href="' . urlHelper::urlFor($dashboard =& NController::factory('dashboard'), null) . '">dashboard</a>.</div>' . "\n";
                                     } else {
                                         $values['_EDIT_START_'] .= '<div class="workflow">The following content is currently in workflow and cannot be edited.</div>' . "\n";
                                     }
                                 }
                                 $values['_EDIT_END_'] .= "</div>\n";
                                 if ($this->content_edit_allowed) {
                                     if (SITE_DRAFTS && $is_draft) {
                                         $values['_EDIT_START_'] .= '<div class="draft">' . $draft_msg . ' the following content as a draft.</div>' . "\n";
                                     }
                                     $values['_EDIT_END_'] .= "</div>\n";
                                 }
                             }
                             if ($this->nterchange && ($timed_start_obj && $timed_start_obj->after($now) || $timed_end_obj && $timed_end_obj->after($now))) {
                                 $format = '%a, %b %e, %Y @ %I:%M:%S %p';
                                 $values['_EDIT_START_'] .= '<div class="timedcontent">';
                                 $values['_EDIT_START_'] .= 'The following content is currently' . ($timed_start_obj && $timed_start_obj->after($now) ? ' NOT' : '') . ' visible (it is now ' . NDate::convertTimeToClient($now, $format) . ')';
                                 if ($timed_start_obj && $timed_start_obj->after($now)) {
                                     $values['_EDIT_START_'] .= '<br />It will appear: ' . NDate::convertTimeToClient($timed_start_obj, $format);
                                 }
                                 if ($timed_end_obj && $timed_end_obj->after($now)) {
                                     $values['_EDIT_START_'] .= '<br />It will be removed: ' . NDate::convertTimeToClient($timed_end_obj, $format);
                                 }
                                 $values['_EDIT_START_'] .= '</div>';
                             }
                             if (isset($content_edit_allowed)) {
                                 $this->content_edit_allowed = $content_edit_allowed;
                                 unset($content_edit_allowed);
                             }
                             // Remove extra whitespace/newlines
                             $values['_EDIT_START_'] = trim(preg_replace('/\\s+/', ' ', $values['_EDIT_START_']));
                             $values['_EDIT_END_'] = trim(preg_replace('/\\s+/', ' ', $values['_EDIT_END_']));
                             // Render the content
                             $content_controller->set($values);
                             $content .= $content_controller->render(array('action' => $template, 'return' => true));
                         }
                         unset($content_model);
                         unset($content_controller);
                     }
                 }
             }
         }
     }
     // free up some memory
     unset($page_content_model);
     unset($page_content);
     // return the content
     return $content;
 }
Ejemplo n.º 12
0
compare('-sixth', $date2->formatLikeSQL('NPSTZHspth'), 'NPSTZHspth (2)');
compare('0', $date2->formatLikeSQL('TZI'), 'TZI (2)');
compare('00', $date2->formatLikeSQL('TZM'), 'TZM (2)');
compare('0', $date2->formatLikeSQL('NPTZM'), 'NPTZM (2)');
compare('Central Standard Time', $date2->formatLikeSQL('TZN'), 'TZN (2)');
compare('-06:00', $date2->formatLikeSQL('TZO'), 'TZO (2)');
compare('-06:00', $date2->formatLikeSQL('NPTZO'), 'NPTZO (2)');
compare('21600', $date2->formatLikeSQL('TZS'), 'TZS (2)');
compare('-21600', $date2->formatLikeSQL('STZS'), 'STZS (2)');
compare('21600', $date2->formatLikeSQL('NPTZS'), 'NPTZS (2)');
compare('-21600', $date2->formatLikeSQL('NPSTZS'), 'NPSTZS (2)');
compare('TWENTY-ONE THOUSAND SIX HUNDRED', $date2->formatLikeSQL('TZSSP'), 'TZSSP (2)');
compare('MINUS TWENTY-ONE THOUSAND SIX HUNDRED', $date2->formatLikeSQL('NPSTZSSP'), 'NPSTZSSP (2)');
compare('America/Chicago', $date2->formatLikeSQL('TZR'), 'TZR (2)');
$date3 = new Date($date);
$date3->setTZbyID("UTC");
compare('UTC', $date3->formatLikeSQL('TZC'), 'TZC (formatLikeDate)');
compare('00', $date3->formatLikeSQL('TZH'), 'TZH (formatLikeDate)');
compare('+00', $date3->formatLikeSQL('STZH'), 'STZH (formatLikeDate)');
compare('0', $date3->formatLikeSQL('NPTZH'), 'NPTZH (formatLikeDate)');
compare('+0', $date3->formatLikeSQL('NPSTZH'), 'NPSTZH (formatLikeDate)');
compare('ZERO', $date3->formatLikeSQL('NPTZHSP'), 'NPTZHSP (formatLikeDate)');
compare('+ZEROTH', $date3->formatLikeSQL('NPSTZHSPTH'), 'NPSTZHSPTH (formatLikeDate)');
compare('0', $date3->formatLikeSQL('TZI'), 'TZI (formatLikeDate)');
compare('00', $date3->formatLikeSQL('TZM'), 'TZM (formatLikeDate)');
compare('0', $date3->formatLikeSQL('NPTZM'), 'NPTZM (formatLikeDate)');
compare('Coordinated Universal Time', $date3->formatLikeSQL('TZN'), 'TZN (formatLikeDate)');
compare('00000', $date3->formatLikeSQL('TZS'), 'TZS (formatLikeDate)');
compare(' 00000', $date3->formatLikeSQL('STZS'), 'STZS (formatLikeDate)');
compare('0', $date3->formatLikeSQL('NPTZS'), 'NPTZS (formatLikeDate)');
compare('0', $date3->formatLikeSQL('NPSTZS'), 'NPSTZS (formatLikeDate)');
Ejemplo n.º 13
0
 function _convertStatsArrayToTz($aStats, $aParams, $name, $method, $args = array(), $formatted = null)
 {
     $aResult = array();
     foreach ($aStats as $k => $v) {
         unset($v['date_time']);
         $oDate = new Date($k);
         $oDate->setTZbyID('UTC');
         $oDate->convertTZbyID($aParams['tz']);
         $key = call_user_func_array(array(&$oDate, $method), $args);
         if (!isset($aResult[$key])) {
             $v[$name] = $key;
             if ($formatted) {
                 $v['date_f'] = $oDate->format($formatted);
             }
             $aResult[$key] = $v;
         } else {
             foreach ($v as $kk => $vv) {
                 $aResult[$key][$kk] += $vv;
             }
         }
     }
     return $aResult;
 }
 /**
  * A private method for formatting date strings for the report.
  *
  * @access private
  * @param string $dateString The date in string format to format.
  * @return string The formatting date string for the report, or false if
  *                the date should not be shown.
  */
 function _formatDateForDisplay($dateString)
 {
     if (empty($dateString)) {
         return false;
     }
     global $date_format;
     $oDate = new Date($dateString);
     $oTz = $oDate->tz;
     $oDate->setTZbyID('UTC');
     $oDate->convertTZ($oTz);
     $formattedDate = $oDate->format($date_format);
     return $formattedDate;
 }
Ejemplo n.º 15
0
 $campaign['expire'] = $data['expire'];
 if (!empty($data['expire_time'])) {
     $oExpireDate = new Date($data['expire_time']);
     $oTz = $oExpireDate->tz;
     $oExpireDate->setTZbyID('UTC');
     $oExpireDate->convertTZ($oTz);
     $campaign['expire_f'] = $oExpireDate->format($date_format);
     $campaign['expire_date'] = $oExpireDate->format('%Y-%m-%d');
 }
 $campaign['status'] = $doCampaigns->status;
 $campaign['an_status'] = $doCampaigns->an_status;
 $campaign['as_reject_reason'] = $doCampaigns->as_reject_reason;
 if (!empty($data['activate_time'])) {
     $oActivateDate = new Date($data['activate_time']);
     $oTz = $oActivateDate->tz;
     $oActivateDate->setTZbyID('UTC');
     $oActivateDate->convertTZ($oTz);
     $campaign['activate_f'] = $oActivateDate->format($date_format);
     $campaign['activate_date'] = $oActivateDate->format('%Y-%m-%d');
 }
 $campaign['priority'] = $data['priority'];
 $campaign['weight'] = $data['weight'];
 $campaign['target_impression'] = $data['target_impression'];
 $campaign['target_click'] = $data['target_click'];
 $campaign['target_conversion'] = $data['target_conversion'];
 $campaign['min_impressions'] = $data['min_impressions'];
 $campaign['ecpm'] = OA_Admin_NumberFormat::formatNumber($data['ecpm'], 4);
 $campaign['anonymous'] = $data['anonymous'];
 $campaign['companion'] = $data['companion'];
 $campaign['show_capped_no_cookie'] = $data['show_capped_no_cookie'];
 $campaign['comments'] = $data['comments'];
Ejemplo n.º 16
0
            print_r($expect);
            echo "Actual:\n";
            print_r($actual);
        }
    } else {
        if ($expect !== $actual) {
            echo "'{$test_name}' failed.  Expect: '{$expect}'  Actual: '{$actual}'\n";
        }
    }
}
if (php_sapi_name() != 'cli') {
    echo "<pre>\n";
}
$date = new Date("1972-07-01 05:29:58.987654", true);
// count leap seconds
$date->setTZbyID("Asia/Calcutta");
$datetest = new Date($date);
$datetest->addSeconds(1, true);
compare("01/07/1972 05.29.59.98765", $datetest->formatLikeSQL("DD/MM/YYYY HH.MI.SS.FFFFF"), "1");
$datetest = new Date($date);
$datetest->addSeconds(2, true);
compare("01/07/1972 05.29.60.98765", $datetest->formatLikeSQL("DD/MM/YYYY HH.MI.SS.FFFFF"), "2");
// leap second
$datetest = new Date($date);
$datetest->addSeconds(3, true);
compare("01/07/1972 05.30.00.98765", $datetest->formatLikeSQL("DD/MM/YYYY HH.MI.SS.FFFFF"), "3");
$datetest = new Date($date);
$datetest->addSeconds(4, true);
compare("01/07/1972 05.30.01.98765", $datetest->formatLikeSQL("DD/MM/YYYY HH.MI.SS.FFFFF"), "4");
$datetest = new Date($date);
$datetest->addSeconds(5, true);
Ejemplo n.º 17
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;
         }
     }
 }
Ejemplo n.º 18
0
 /**
  * Fetch the history stats using the specified parameters
  *
  * @param array  $aParams Query parameters
  * @param string $link    Optional link for the leftmost column content
  */
 function getHistory($aParams, $link = '')
 {
     $oNow = new Date();
     $aParams['tz'] = $oNow->tz->getID();
     $method = $this->oHistory->setBreakdownInfo($this);
     // Add plugin aParams
     $pluginParams = array();
     foreach ($this->aPlugins as $oPlugin) {
         $oPlugin->addQueryParams($pluginParams);
     }
     $aStats = Admin_DA::fromCache($method, $aParams + $this->aDates + $pluginParams);
     // Merge plugin additional $oPlugin
     foreach ($this->aPlugins as $oPlugin) {
         $oPlugin->mergeData($aStats, $method, $aParams + $this->aDates, $this->aEmptyRow);
     }
     if (count($aStats) == 0) {
         $this->noStatsAvailable = true;
         return $aStats;
     }
     // Fill unused plugins columns
     foreach (array_keys($aStats) as $k) {
         $aStats[$k] += $this->aEmptyRow;
     }
     // Set some of the variables that used to be set by getSpan
     if (!empty($aStats)) {
         $dates = array_keys($aStats);
         // assumes first row has earliest date
         $firstDate = new Date($dates[0]);
         // Convert to current TZ
         $firstDate->setTZbyID('UTC');
         $firstDate->convertTZ($oNow->tz);
         $firstDate->setHour(0);
         $firstDate->setMinute(0);
         $firstDate->setSecond(0);
         if (empty($this->aDates)) {
             $this->aDates['day_begin'] = $firstDate->format('%Y-%m-%d');
             $this->aDates['day_end'] = $oNow->format('%Y-%m-%d');
         }
         $this->oStartDate = new Date($firstDate);
     }
     $aDates = $this->oHistory->getDatesArray($this->aDates, $this->statsBreakdown, $this->oStartDate);
     $this->oHistory->fillGapsAndLink($aStats, $aDates, $this, $link);
     if (!in_array($this->listOrderField, array_merge(array($this->statsBreakdown), array_keys($this->aColumns)))) {
         $this->listOrderField = $this->statsBreakdown;
         $this->listOrderDirection = $this->statsBreakdown == 'hour' || $this->statsBreakdown == 'dow' ? 'up' : 'down';
     }
     // If required, re-format the data in the weekly breakdown format
     if ($this->statsBreakdown == 'week') {
         $this->oHistory->prepareWeekBreakdown($aStats, $this);
     }
     MAX_sortArray($aStats, $this->listOrderField, $this->listOrderDirection == 'up');
     // Summarise the values into a the totals array, & format
     $this->_summariseTotalsAndFormat($aStats, true);
     return $aStats;
 }
Ejemplo n.º 19
0
 /**
  * @param $oDate
  * @param $campaignId
  * @return int Number of emails sent
  */
 function sendCampaignImpendingExpiryEmail($oDate, $campaignId)
 {
     $aConf = $GLOBALS['_MAX']['CONF'];
     global $date_format;
     $oPreference = new OA_Preferences();
     if (!isset($this->aAdminCache)) {
         // Get admin account ID
         $adminAccountId = OA_Dal_ApplicationVariables::get('admin_account_id');
         // Get admin prefs
         $adminPrefsNames = $this->_createPrefsListPerAccount(OA_ACCOUNT_ADMIN);
         $aAdminPrefs = $oPreference->loadAccountPreferences($adminAccountId, $adminPrefsNames, OA_ACCOUNT_ADMIN);
         // Get admin users
         $aAdminUsers = $this->getAdminUsersLinkedToAccount();
         // Store admin cache
         $this->aAdminCache = array($aAdminPrefs, $aAdminUsers);
     } else {
         // Retrieve admin cache
         list($aAdminPrefs, $aAdminUsers) = $this->aAdminCache;
     }
     $aPreviousOIDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $aPreviousOIDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aPreviousOIDates['start']);
     $doCampaigns = OA_Dal::staticGetDO('campaigns', $campaignId);
     if (!$doCampaigns) {
         return 0;
     }
     $aCampaign = $doCampaigns->toArray();
     if (!isset($this->aClientCache[$aCampaign['clientid']])) {
         $doClients = OA_Dal::staticGetDO('clients', $aCampaign['clientid']);
         // Add advertiser linked users
         $aLinkedUsers['advertiser'] = $this->getUsersLinkedToAccount('clients', $aCampaign['clientid']);
         // Add advertiser prefs
         $advertiserPrefsNames = $this->_createPrefsListPerAccount(OA_ACCOUNT_ADVERTISER);
         $aPrefs['advertiser'] = $oPreference->loadAccountPreferences($doClients->account_id, $advertiserPrefsNames, OA_ACCOUNT_ADVERTISER);
         if (!isset($aAgencyCache[$doClients->agencyid])) {
             // Add manager linked users
             $doAgency = OA_Dal::staticGetDO('agency', $doClients->agencyid);
             $aLinkedUsers['manager'] = $this->getUsersLinkedToAccount('agency', $doClients->agencyid);
             // Add manager preferences
             $managerPrefsNames = $this->_createPrefsListPerAccount(OA_ACCOUNT_MANAGER);
             $aPrefs['manager'] = $oPreference->loadAccountPreferences($doAgency->account_id, $managerPrefsNames, OA_ACCOUNT_MANAGER);
             // Get agency "From" details
             $aAgencyFromDetails = $this->_getAgencyFromDetails($doAgency->agencyid);
             // Store in the agency cache
             $this->aAgencyCache = array($doClients->agencyid => array($aLinkedUsers['manager'], $aPrefs['manager'], $aAgencyFromDetails));
         } else {
             // Retrieve agency cache
             list($aLinkedUsers['manager'], $aPrefs['manager'], $aAgencyFromDetails) = $this->aAgencyCache[$doClients->agencyid];
         }
         // Add admin linked users and preferences
         $aLinkedUsers['admin'] = $aAdminUsers;
         $aPrefs['admin'] = $aAdminPrefs;
         // Create a linked user 'special' for the advertiser that will take the admin preferences for advertiser
         $aLinkedUsers['special']['advertiser'] = $doClients->toArray();
         $aLinkedUsers['special']['advertiser']['contact_name'] = $aLinkedUsers['special']['advertiser']['contact'];
         $aLinkedUsers['special']['advertiser']['email_address'] = $aLinkedUsers['special']['advertiser']['email'];
         $aLinkedUsers['special']['advertiser']['language'] = '';
         $aLinkedUsers['special']['advertiser']['user_id'] = 0;
         // Check that every user is not going to receive more than one email if they
         // are linked to more than one account
         $aLinkedUsers = $this->_deleteDuplicatedUser($aLinkedUsers);
         // Create the linked special user preferences from the admin preferences
         // the special user is the client that doesn't have preferences in the database
         $aPrefs['special'] = $aPrefs['admin'];
         $aPrefs['special']['warn_email_special'] = $aPrefs['special']['warn_email_advertiser'];
         $aPrefs['special']['warn_email_special_day_limit'] = $aPrefs['special']['warn_email_advertiser_day_limit'];
         $aPrefs['special']['warn_email_special_impression_limit'] = $aPrefs['special']['warn_email_advertiser_impression_limit'];
         // Store in the client cache
         $this->aClientCache = array($aCampaign['clientid'] => array($aLinkedUsers, $aPrefs, $aAgencyFromDetails));
     } else {
         // Retrieve client cache
         list($aLinkedUsers, $aPrefs, $aAgencyFromDetails) = $this->aClientCache[$aCampaign['clientid']];
     }
     $copiesSent = 0;
     foreach ($aLinkedUsers as $accountType => $aUsers) {
         if ($accountType == 'special' || $accountType == 'advertiser') {
             // Get the agency details and use them for emailing advertisers
             $aFromDetails = $aAgencyFromDetails;
         } else {
             // Use the Admin details
             $aFromDetails = '';
         }
         if ($aPrefs[$accountType]['warn_email_' . $accountType]) {
             // Does the account type want warnings when the impressions are low?
             if ($aPrefs[$accountType]['warn_email_' . $accountType . '_impression_limit'] > 0 && $aCampaign['views'] > 0) {
                 // Test to see if the placements impressions remaining are less than the limit
                 $dalCampaigns = OA_Dal::factoryDAL('campaigns');
                 $remainingImpressions = $dalCampaigns->getAdImpressionsLeft($aCampaign['campaignid']);
                 if ($remainingImpressions < $aPrefs[$accountType]['warn_email_' . $accountType . '_impression_limit']) {
                     // Yes, the placement will expire soon! But did the placement just reach
                     // the point where it is about to expire, or did it happen a while ago?
                     $previousRemainingImpressions = $dalCampaigns->getAdImpressionsLeft($aCampaign['campaignid'], $aPreviousOIDates['end']);
                     if ($previousRemainingImpressions >= $aPrefs[$accountType]['warn_email_' . $accountType . '_impression_limit']) {
                         // Yes! This is the operation interval that the boundary
                         // was crossed to the point where it's about to expire,
                         // so send that email, baby!
                         foreach ($aUsers as $aUser) {
                             $aEmail = $this->prepareCampaignImpendingExpiryEmail($aUser, $aCampaign['clientid'], $aCampaign['campaignid'], 'impressions', $aPrefs[$accountType]['warn_email_' . $accountType . '_impression_limit'], $accountType);
                             if ($aEmail !== false) {
                                 if ($this->sendMail($aEmail['subject'], $aEmail['contents'], $aUser['email_address'], $aUser['contact_name'], $aFromDetails)) {
                                     $copiesSent++;
                                     if ($aConf['email']['logOutgoing']) {
                                         phpAds_userlogSetUser(phpAds_userMaintenance);
                                         phpAds_userlogAdd(phpAds_actionWarningMailed, $aPlacement['campaignid'], "{$aEmail['subject']}\n\n\n                                                 {$aUser['contact_name']}({$aUser['email_address']})\n\n\n                                                 {$aEmail['contents']}");
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
             // Does the account type want warnings when the days are low?
             if ($aPrefs[$accountType]['warn_email_' . $accountType . '_day_limit'] > 0 && !empty($aCampaign['expire_time'])) {
                 // Calculate the date that should be used to see if the warning needs to be sent
                 $warnSeconds = (int) ($aPrefs[$accountType]['warn_email_' . $accountType . '_day_limit'] + 1) * SECONDS_PER_DAY;
                 $oEndDate = new Date($aCampaign['expire_time']);
                 $oEndDate->setTZbyID('UTC');
                 $oTestDate = new Date();
                 $oTestDate->copy($oDate);
                 $oTestDate->addSeconds($warnSeconds);
                 // Test to see if the test date is after the placement's expiration date
                 if ($oTestDate->after($oEndDate)) {
                     // Yes, the placement will expire soon! But did the placement just reach
                     // the point where it is about to expire, or did it happen a while ago?
                     $oiSeconds = (int) $aConf['maintenance']['operationInterval'] * 60;
                     $oTestDate->subtractSeconds($oiSeconds);
                     if (!$oTestDate->after($oEndDate)) {
                         // Yes! This is the operation interval that the boundary
                         // was crossed to the point where it's about to expire,
                         // so send those emails, baby!
                         foreach ($aUsers as $aUser) {
                             $aEmail = $this->prepareCampaignImpendingExpiryEmail($aUser, $aCampaign['clientid'], $aCampaign['campaignid'], 'date', $oEndDate->format($date_format), $accountType);
                             if ($aEmail !== false) {
                                 if ($this->sendMail($aEmail['subject'], $aEmail['contents'], $aUser['email_address'], $aUser['contact_name'], $aFromDetails)) {
                                     $copiesSent++;
                                     if ($aConf['email']['logOutgoing']) {
                                         phpAds_userlogSetUser(phpAds_userMaintenance);
                                         phpAds_userlogAdd(phpAds_actionWarningMailed, $aPlacement['campaignid'], "{$aEmail['subject']}\n\n\n                                                 {$aUser['contact_name']}({$aUser['email_address']})\n\n\n                                                 {$aEmail['contents']}");
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     // Restore the default language strings
     Language_Loader::load('default');
     return $copiesSent;
 }
Ejemplo n.º 20
0
 /**
  * A method to convert a Date into an array containing the start
  * and end Dates of the operation interval that the date is in.
  *
  * @static
  * @param Date $oDate The date to convert.
  * @param integer $operation_interval Optional length of the operation interval
  *                                    in minutes. If not given, will use the
  *                                    currently defined operation interval.
  * @param boolean $cacheResult  If true the data should be cached
  * @return array An array of the start and end Dates of the operation interval.
  */
 function convertDateToOperationIntervalStartAndEndDates($oDate, $operationInterval = 0, $cacheResult = true)
 {
     // Convert to UTC
     $oDateCopy = new Date($oDate);
     $oDateCopy->toUTC();
     // Check cache
     static $aCache;
     if ($cacheResult && isset($aCache[$oDateCopy->getDate()][$operationInterval])) {
         $cachedDates = $aCache[$oDateCopy->getDate()][$operationInterval];
         $oStart = new Date($cachedDates['start']);
         $oStart->setTZbyID('UTC');
         $oEnd = new Date($cachedDates['end']);
         $oEnd->setTZbyID('UTC');
         return array('start' => $oStart, 'end' => $oEnd);
     }
     if ($operationInterval < 1) {
         $operationInterval = OX_OperationInterval::getOperationInterval();
     }
     // Get the date representing the start of the week
     $oStartOfWeek = new Date(Date_Calc::beginOfWeek($oDateCopy->getDay(), $oDateCopy->getMonth(), $oDateCopy->getYear(), '%Y-%m-%d 00:00:00'));
     $oStartOfWeek->setTZbyID('UTC');
     // Get the operation interval ID of the date
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDateCopy, $operationInterval);
     // The start of the operation interval is the start of the week plus the
     // operation interval ID multiplied by the operation interval
     $oStart = new Date();
     $oStart->copy($oStartOfWeek);
     $oStart->addSeconds($operationIntervalID * $operationInterval * 60);
     // The end of the operation interval is the start of the week plus the
     // operation interval ID + 1 multiplied by the operation interval
     $oEnd = new Date();
     $oEnd->copy($oStart);
     $oEnd->addSeconds($operationInterval * 60 - 1);
     // Cache result - cache as string to save memory
     if ($cacheResult) {
         $aCache[$oDate->getDate()][$operationInterval] = array('start' => $oStart->getDate(), 'end' => $oEnd->getDate());
     }
     // Return the result
     return array('start' => $oStart, 'end' => $oEnd);
 }
 /**
  * A private method to prepare an array of connections and variable values for the
  * report.
  *
  * @access private
  * @return array An array with the following format:
  *      array(
  *          $trackerId => array(
  *              'connections' => array(
  *                  $connectionId => array(
  *                      'data_intermediate_ad_connection_id' => Integer:   The conversion ID
  *                      'tracker_date_time'                  => Timestamp: The date/time of the conversion
  *                      'tracker_day'                        => String:    The day of the conversion in YYYY-MM-DD format
  *                      'connection_date_time'               => Timestamp: The date/time of the ad impression/click
  *                      'connection_status'                  => Integer:   The status of the connection
  *                      'connection_channel'                 => Integer:   The channel ID of the ad impression/click
  *                      'connection_action'                  => Integer:   If it was an ad impression or click
  *                      'connection_ip_address'              => String:    The IP address of the ad impression/click
  *                      'connection_country'                 => String:    The country of the ad impression/click
  *                      'connection_domain'                  => String:    The domain of the ad impression/click
  *                      'connection_language'                => String:    The language of the ad impression/click
  *                      'connection_os'                      => String:    The operating system of the ad impression/click
  *                      'connection_browser'                 => String:    The browser of the ad impression/click
  *                      'connection_comments'                => String:    Any comments associated with the connection
  *                      'advertiser_id'                      => Integer:   The advertiser ID of the ad impression/click
  *                      'advertiser_name'                    => String:    The name of the advertiser of the ad impression/click
  *                      'placement_id'                       => Integer:   The placement ID of the ad impression/click
  *                      'placement_name'                     => String:    The name of the placement of the ad impression/click
  *                      'ad_id'                              => Integer:   The ad ID of the ad impression/click
  *                      'ad_name'                            => String:    The name of the ad of the ad impression/click
  *                      'ad_alt'                             => String:    The alt. name of the ad of the ad impression/click
  *                      'publisher_id'                       => Integer:   The publisher ID of the ad impression/click
  *                      'publisher_name'                     => String:    The name of the publisher of the ad impression/click
  *                      'zone_id'                            => Integer:   The zone ID of the ad impression/click
  *                      'zone_name'                          => String:    The name of the zone of the ad impression/click
  *                      'tracker_id'                         => Integer:   The tracker ID for the conversion
  *                      'variables'                          => array(
  *                          $trackerVariableId => array(
  *                              tracker_variable_id    => Integer: The tracker variable ID
  *                              tracker_variable_value => Mixed:   The tracker variable value for the conversion
  *                          )
  *                      )
  *                  )
  *              )
  *          )
  *      )
  */
 function _prepareConnections()
 {
     $aConnections = array();
     $aConf = $GLOBALS['_MAX']['CONF'];
     // Prepare the start and end dates for the conversion range
     $oDaySpan = new OA_Admin_DaySpan();
     $oDaySpan->setSpanDays($this->_oDaySpan->oStartDate, $this->_oDaySpan->oEndDate);
     $oDaySpan->toUTC();
     $startDateString = $oDaySpan->getStartDateString('%Y-%m-%d %H:%M:%S');
     $endDateString = $oDaySpan->getEndDateString('%Y-%m-%d %H:%M:%S');
     // Prepare the agency/advertiser/publisher limitations
     $agencyId = $this->_oScope->getAgencyId();
     $advertiserId = $this->_oScope->getAdvertiserId();
     $publisherId = $this->_oScope->getPublisherId();
     // Prepare the query to select the required conversions and variable values
     $query = "\n            SELECT\n                diac.data_intermediate_ad_connection_id AS data_intermediate_ad_connection_id,\n                diac.tracker_date_time AS tracker_date_time,\n                diac.tracker_id AS tracker_id,\n                diac.connection_date_time AS connection_date_time,\n                diac.connection_status AS connection_status,\n                diac.connection_channel AS connection_channel,\n                diac.connection_action AS connection_action,\n                diac.tracker_ip_address AS connection_ip_address,\n                diac.tracker_country AS connection_country,\n                diac.tracker_domain AS connection_domain,\n                diac.tracker_language AS connection_language,\n                diac.tracker_os AS connection_os,\n                diac.tracker_browser AS connection_browser,\n                diac.comments AS connection_comments,\n                z.zoneid AS zone_id,\n                z.zonename AS zone_name,\n                p.affiliateid AS publisher_id,\n                p.name AS publisher_name,\n                a.clientid AS advertiser_id,\n                a.clientname AS advertiser_name,\n                c.campaignid AS placement_id,\n                c.campaignname AS campaign_name,\n                b.bannerid AS ad_id,\n                b.description AS ad_name,\n                b.alt AS ad_alt,\n                diavv.tracker_variable_id AS tracker_variable_id,\n                diavv.value AS tracker_variable_value\n            FROM\n                {$aConf['table']['prefix']}{$aConf['table']['data_intermediate_ad_connection']} AS diac\n            JOIN\n                {$aConf['table']['prefix']}{$aConf['table']['banners']} AS b\n            ON\n                (\n                    diac.ad_id = b.bannerid\n                )\n            JOIN\n                {$aConf['table']['prefix']}{$aConf['table']['campaigns']} AS c\n            ON\n                (\n                    b.campaignid = c.campaignid\n                )\n            JOIN\n                {$aConf['table']['prefix']}{$aConf['table']['clients']} AS a\n            ON\n                (\n                    c.clientid = a.clientid\n                )\n            LEFT JOIN\n                {$aConf['table']['prefix']}{$aConf['table']['zones']} AS z\n            ON\n                (\n                    diac.zone_id = z.zoneid\n                )\n            LEFT JOIN\n                {$aConf['table']['prefix']}{$aConf['table']['affiliates']} AS p\n            ON\n                (\n                    z.affiliateid = p.affiliateid\n                )\n            LEFT JOIN\n                {$aConf['table']['prefix']}{$aConf['table']['data_intermediate_ad_variable_value']} AS diavv\n            ON\n                (\n                    diac.data_intermediate_ad_connection_id = diavv.data_intermediate_ad_connection_id\n                )\n            WHERE\n                diac.tracker_date_time >= " . DBC::makeLiteral($startDateString, 'string') . "\n                AND\n                diac.tracker_date_time <= " . DBC::makeLiteral($endDateString, 'string') . "\n                AND\n                diac.inside_window = 1";
     if ($agencyId) {
         $query .= "\n                AND\n                a.agencyid = " . DBC::makeLiteral($agencyId, 'integer');
     }
     if ($advertiserId) {
         $query .= "\n                AND\n                a.clientid = " . DBC::makeLiteral($advertiserId, 'integer');
     }
     if ($publisherId) {
         $query .= "\n                AND\n                z.affiliateid = " . DBC::makeLiteral($publisherId, 'integer');
     }
     $query .= "\n            ORDER BY\n                tracker_id,\n                data_intermediate_ad_connection_id";
     // Select the conversions in the report
     $rsConversions = DBC::NewRecordSet($query);
     $rsConversions->find();
     while ($rsConversions->fetch()) {
         $aConversion = $rsConversions->toArray();
         $trackerId = $aConversion['tracker_id'];
         $connectionId = $aConversion['data_intermediate_ad_connection_id'];
         // Does this tracker/connection pair exist in the result array already?
         // It might, due to multiple attached variable values...
         if (!isset($aConnections[$trackerId]['connections'][$connectionId])) {
             // It's not set, store the connection details
             $oTrackerDate = new Date($aConversion['tracker_date_time']);
             $oTrackerDate->setTZbyID('UTC');
             $oTrackerDate->convertTZ($this->_oDaySpan->oStartDate->tz);
             $oConnectionDate = new Date($aConversion['connection_date_time']);
             $oConnectionDate->setTZbyID('UTC');
             $oConnectionDate->convertTZ($this->_oDaySpan->oStartDate->tz);
             $aConnections[$trackerId]['connections'][$connectionId] = array('data_intermediate_ad_connection_id' => $connectionId, 'tracker_date_time' => $oTrackerDate->format('%Y-%m-%d %H:%M:%S'), 'tracker_day' => $oTrackerDate->format('%Y-%m-%d'), 'connection_date_time' => $oConnectionDate->format('%Y-%m-%d %H:%M:%S'), 'connection_status' => $aConversion['connection_status'], 'connection_channel' => $aConversion['connection_channel'], 'connection_action' => $aConversion['connection_action'], 'connection_ip_address' => $aConversion['connection_ip_address'], 'connection_country' => $aConversion['connection_country'], 'connection_domain' => $aConversion['connection_domain'], 'connection_language' => $aConversion['connection_language'], 'connection_os' => $aConversion['connection_os'], 'connection_browser' => $aConversion['connection_browser'], 'connection_comments' => $aConversion['connection_comments'], 'advertiser_id' => $aConversion['advertiser_id'], 'advertiser_name' => $aConversion['advertiser_name'], 'placement_id' => $aConversion['placement_id'], 'placement_name' => $aConversion['placement_name'], 'ad_id' => $aConversion['ad_id'], 'ad_name' => $aConversion['ad_name'], 'ad_alt' => $aConversion['ad_alt'], 'publisher_id' => $aConversion['publisher_id'], 'publisher_name' => $aConversion['publisher_name'], 'zone_id' => $aConversion['zone_id'], 'zone_name' => $aConversion['zone_name'], 'tracker_id' => $aConversion['tracker_id']);
         }
         // Store the variable value associated with this connection, if one exists
         $trackerVariableId = $aConversion['tracker_variable_id'];
         if (!empty($trackerVariableId)) {
             $aConnections[$trackerId]['connections'][$connectionId]['variables'][$trackerVariableId] = array('tracker_variable_id' => $trackerVariableId, 'tracker_variable_value' => $aConversion['tracker_variable_value']);
         }
     }
     // Return the connections
     return $aConnections;
 }
Ejemplo n.º 22
0
 function testDateUnixtime4()
 {
     $temp = new Date();
     $temp->setTZbyID("Europe/London");
     $temp->setDate(strtotime("2003-10-04 14:03:24Z"));
     // Summer time in London
     $temp->setTZbyID("UTC");
     $this->assertEquals('2003-10-04 15:03:24', sprintf('%04d-%02d-%02d %02d:%02d:%02d', $temp->year, $temp->month, $temp->day, $temp->hour, $temp->minute, $temp->second));
 }
Ejemplo n.º 23
0
 /**
  * A method to determine how long it will be until a campaign "expires".
  *
  * Returns the earliest possible date from the following values:
  *  - The campaign's expiration date, if set.
  *  - The eStimated expiration date based on lifetime impression delivery
  *    rate, if applicable.
  *  - The eStimated expiration date based on lifetime click delivery rate
  *    if applicable.
  *  - The eStimated expiration date based on lifetime conversion rate,
  *    if applicable.
  *
  * Usage:
  *   $desc = $dalCampaigns->getDaysLeftString($campaignid);
  *
  * Where:
  *   $desc is a string to display giving how the expiration was calculated
  *     eg. "Estimated expiration", or that there is no expiration date
  *
  * @param integer $campaignId The campaign ID.
  * @return string
  */
 function getDaysLeftString($campaignId)
 {
     global $date_format, $strNoExpiration, $strDaysLeft, $strEstimated, $strExpirationDate, $strNoExpirationEstimation, $strDaysAgo, $strCampaignStop;
     $prefix = $this->getTablePrefix();
     // Define array to store possible expiration date results
     $aExpiration = array();
     // Get the campaign target info
     $now = OA::getNow('Y-m-d');
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->selectAdd("views AS impressions");
     $doCampaigns->get($campaignId);
     $aCampaignData = $doCampaigns->toArray();
     if (!empty($aCampaignData['expire_time'])) {
         $oNow = new Date($now);
         $oNow->setHour(0);
         $oNow->setMinute(0);
         $oNow->setSecond(0);
         $oDate = new Date($aCampaignData['expire_time']);
         $oDate->setTZbyID('UTC');
         $oDate->convertTZ($oNow->tz);
         $oDate->setHour(0);
         $oDate->setMinute(0);
         $oDate->setSecond(0);
         $oSpan = new Date_Span();
         $oSpan->setFromDateDiff($oNow, $oDate);
         $aCampaignData['expire_f'] = $oDate->format($date_format);
         $aCampaignData['days_left'] = $oSpan->toDays() * ($oDate->before($oNow) ? -1 : 1);
     }
     $oDbh = OA_DB::singleton();
     $tableB = $oDbh->quoteIdentifier($prefix . 'banners', true);
     $tableD = $oDbh->quoteIdentifier($prefix . 'data_intermediate_ad', true);
     // Define array to return the expiration dates (if they exist)
     $aReturn = array('estimatedExpiration' => '', 'campaignExpiration' => '');
     // Does the campaign have lifetime impression targets?
     // If yes, try to get a stimated expiration date
     if ($aCampaignData['impressions'] > 0) {
         $query = "\n        \t    SELECT\n        \t        SUM(dia.impressions) AS delivered,\n        \t        DATE_FORMAT(MIN(dia.date_time), '%Y-%m-%d') AS day_of_first\n        \t    FROM\n        \t        {$tableD} AS dia,\n        \t        {$tableB} AS b\n        \t    WHERE\n        \t        dia.ad_id = b.bannerid\n        \t        AND\n        \t        b.campaignid = " . DBC::makeLiteral($campaignId);
         $rsImpressions = DBC::FindRecord($query);
         if ($rsImpressions) {
             $aImpressions = $rsImpressions->toArray();
             // Get the number of days until the campaign will end
             // based on the impression target delivery data
             $aExpiration = $this->_calculateRemainingDays($aImpressions, $aCampaignData['impressions']);
         }
     } elseif ($aCampaignData['clicks'] > 0) {
         $query = "\n        \t    SELECT\n        \t        SUM(dia.clicks) AS delivered,\n        \t        DATE_FORMAT(MIN(dia.date_time), '%Y-%m-%d') AS day_of_first\n        \t    FROM\n        \t        {$tableD} AS dia,\n        \t        {$tableB} AS b\n        \t    WHERE\n        \t        dia.ad_id = b.bannerid\n        \t        AND\n        \t        b.campaignid = " . DBC::makeLiteral($campaignId);
         $rsClicks = DBC::FindRecord($query);
         if ($rsClicks) {
             $aClicks = $rsClicks->toArray();
             // Get the number of days until the campaign will end
             // based on the click target delivery data
             $aExpiration = $this->_calculateRemainingDays($aClicks, $aCampaignData['clicks']);
         }
     } elseif ($aCampaignData['conversions'] > 0) {
         $query = "\n        \t    SELECT\n        \t        SUM(dia.conversions) AS delivered,\n        \t        DATE_FORMAT(MIN(dia.date_time), '%Y-%m-%d') AS day_of_first\n        \t    FROM\n        \t        {$tableD} AS dia,\n        \t        {$tableB} AS b\n        \t    WHERE\n        \t        dia.ad_id = b.bannerid\n        \t        AND\n        \t        b.campaignid = " . DBC::makeLiteral($campaignId);
         $rsConversions = DBC::FindRecord($query);
         if ($rsConversions) {
             $aConversions = $rsConversions->toArray();
             // Get the number of days until the campaign will end
             // based on the conversion target delivery data
             $aExpiration = $this->_calculateRemainingDays($aConversions, $aCampaignData['conversions']);
         }
     }
     // flags to control if the campaign expiration date and
     // the estimated expiration date are going to be showed
     $existExpirationDate = false;
     $showEtimatedDate = false;
     // is there a expiration date?
     if (!empty($aCampaignData['expire_time'])) {
         $existExpirationDate = true;
     }
     if ($existExpirationDate) {
         // has the expiration date been reached?
         if ((int) $aCampaignData['days_left'] < 0) {
             $aReturn['campaignExpiration'] = $strCampaignStop . ": " . $aCampaignData['expire_f'];
             $aReturn['campaignExpiration'] = $aReturn['campaignExpiration'] . " (" . abs((int) round($aCampaignData['days_left'])) . " {$strDaysAgo})";
         } else {
             $aReturn['campaignExpiration'] = $strExpirationDate . ": " . $aCampaignData['expire_f'];
             $aReturn['campaignExpiration'] = $aReturn['campaignExpiration'] . " (" . $strDaysLeft . ": " . round($aCampaignData['days_left']) . ")";
         }
     } else {
         $aReturn['campaignExpiration'] = $strNoExpiration;
     }
     // There is a estimated expiration date?
     // If yes, check if the campaign expiration date is set up and compare
     // both expiration dates to show only relevant estimated expiration dates
     if (!empty($aExpiration)) {
         if ($existExpirationDate == true) {
             if (round($aCampaignData['days_left']) >= 0) {
                 $campaignExpirationDate = new Date($aCampaignData['expire_time']);
                 $aExpiration['date']->hour = 0;
                 $aExpiration['date']->minute = 0;
                 $aExpiration['date']->second = 0;
                 $aExpiration['date']->partsecond = 0;
                 $compareDate = Date::compare($aExpiration['date'], $campaignExpirationDate);
                 // the estimated expiration date is previous or equal to the
                 // campaign expiration date and hasn't the expiration date been reached?
                 if ($compareDate <= 0 && (int) $aCampaignData['days_left'] >= 0) {
                     $showEtimatedDate = true;
                 }
             }
         } else {
             $showEtimatedDate = true;
         }
     } elseif ($existExpirationDate && round($aCampaignData['days_left']) >= 0 || !$existExpirationDate) {
         $aReturn['estimatedExpiration'] = $strEstimated . ": " . $strNoExpirationEstimation;
     }
     if ($showEtimatedDate) {
         $aExpiration['daysLeft'] = phpAds_formatNumber($aExpiration['daysLeft']);
         $aReturn['estimatedExpiration'] = $strEstimated . ": " . $aExpiration['date_f'] . " (" . $strDaysLeft . ": " . $aExpiration['daysLeft'] . ")";
     }
     return $aReturn;
 }
 $aCampaign['impressions'] = phpAds_formatNumber($aCampaign['views']);
 $aCampaign['clicks'] = phpAds_formatNumber($aCampaign['clicks']);
 $aCampaign['conversions'] = phpAds_formatNumber($aCampaign['conversions']);
 if (!empty($aCampaign['activate_time'])) {
     $oActivateDate = new Date($aCampaign['activate_time']);
     $oTz = $oActivateDate->tz;
     $oActivateDate->setTZbyID('UTC');
     $oActivateDate->convertTZ($oTz);
     $aCampaign['activate'] = $oActivateDate->format($date_format);
 } else {
     $aCampaign['activate'] = '-';
 }
 if (!empty($aCampaign['expire_time'])) {
     $oExpireDate = new Date($aCampaign['expire_time']);
     $oTz = $oExpireDate->tz;
     $oExpireDate->setTZbyID('UTC');
     $oExpireDate->convertTZ($oTz);
     $aCampaign['expire'] = $oExpireDate->format($date_format);
 } else {
     $aCampaign['expire'] = '-';
 }
 if ($aCampaign['type'] == DataObjects_Campaigns::CAMPAIGN_TYPE_MARKET_CONTRACT) {
     $aCampaign['system'] = true;
     $aCampaign['type'] = OX_Util_Utils::getCampaignType($aCampaign['priority']);
 } else {
     $aCampaign['type'] = OX_Util_Utils::getCampaignType($aCampaign['priority']);
 }
 if ($aCampaign['priority'] == -1) {
     $aCampaign['priority'] = $strOverride;
 } elseif ($aCampaign['priority'] == -2) {
     $aCampaign['priority'] = $strCampaignECPM;
Ejemplo n.º 25
0
            print_r($expect);
            echo "Actual:\n";
            print_r($actual);
        }
    } else {
        if ($expect !== $actual) {
            echo "'{$test_name}' failed.  Expect: '{$expect}'  Actual: '{$actual}'\n";
        }
    }
}
if (php_sapi_name() != 'cli') {
    echo "<pre>\n";
}
$date = new Date("1972-07-01 00:59:58.987654", true);
// count leap seconds
$date->setTZbyID("Europe/London");
$datetest = new Date($date);
$datetest->addSeconds(1, true);
compare("01/07/1972 00.59.59.98765", $datetest->formatLikeSQL("DD/MM/YYYY HH.MI.SS.FFFFF"), "1");
$datetest = new Date($date);
$datetest->addSeconds(2, true);
compare("01/07/1972 00.59.60.98765", $datetest->formatLikeSQL("DD/MM/YYYY HH.MI.SS.FFFFF"), "2");
// leap second
$datetest = new Date($date);
$datetest->addSeconds(3, true);
compare("01/07/1972 01.00.00.98765", $datetest->formatLikeSQL("DD/MM/YYYY HH.MI.SS.FFFFF"), "3");
$datetest = new Date($date);
$datetest->addSeconds(4, true);
compare("01/07/1972 01.00.01.98765", $datetest->formatLikeSQL("DD/MM/YYYY HH.MI.SS.FFFFF"), "4");
$datetest = new Date($date);
$datetest->addSeconds(5, true);
Ejemplo n.º 26
0
            print_r($expect);
            echo "Actual:\n";
            print_r($actual);
        }
    } else {
        if ($expect !== $actual) {
            echo "'{$test_name}' failed.  Expect: '{$expect}'  Actual: '{$actual}'\n";
        }
    }
}
if (php_sapi_name() != 'cli') {
    echo "<pre>\n";
}
$date = new Date("1972-07-01 01:59:58.987654", true);
// count leap seconds
$date->setTZbyID("Europe/Paris");
$datetest = new Date($date);
$datetest->addSeconds(1, true);
compare("01/07/1972 01.59.59.98765", $datetest->formatLikeSQL("DD/MM/YYYY HH.MI.SS.FFFFF"), "1");
$datetest = new Date($date);
$datetest->addSeconds(2, true);
compare("01/07/1972 01.59.60.98765", $datetest->formatLikeSQL("DD/MM/YYYY HH.MI.SS.FFFFF"), "2");
// leap second
$datetest = new Date($date);
$datetest->addSeconds(3, true);
compare("01/07/1972 02.00.00.98765", $datetest->formatLikeSQL("DD/MM/YYYY HH.MI.SS.FFFFF"), "3");
$datetest = new Date($date);
$datetest->addSeconds(4, true);
compare("01/07/1972 02.00.01.98765", $datetest->formatLikeSQL("DD/MM/YYYY HH.MI.SS.FFFFF"), "4");
$datetest = new Date($date);
$datetest->addSeconds(5, true);
Ejemplo n.º 27
0
 /**
  * A private method to prepare the statistics part of the body of an
  * advertiser's "campaign delivery" report email.
  *
  * @access private
  * @param integer    $advertiserId The advertiser's ID.
  * @param Date $oStartDate   The start date of the report, inclusive.
  * @param Date $oEndDate     The end date of the report, inclusive.
  * @param string     $type         One of "impressions", "clicks" or "conversions".
  * @param string     $adTextPrint  An sprintf compatible formatting string for use
  *                                 with the $strTotalThisPeriod global string.
  * @return an array with
  *      'body'      => string The ad statistics part of the report.
  *      'adviews'   => int    Adviews in this period
  */
 function _prepareCampaignDeliveryEmailBodyStats($adId, $oStartDate, $oEndDate, $type, $adTextPrint)
 {
     $oDbh =& OA_DB::singleton();
     // Obtain the required date format
     global $date_format;
     // Obtain the impressions, clicks and conversions string, and prepare
     // these strings for use, including formatting strings
     global $strNoViewLoggedInInterval, $strNoClickLoggedInInterval, $strNoConversionLoggedInInterval, $strTotalThisPeriod;
     if ($type == 'impressions') {
         $nothingLogged = $strNoViewLoggedInInterval;
     } else {
         if ($type == 'clicks') {
             $nothingLogged = $strNoClickLoggedInInterval;
         } else {
             if ($type == 'conversions') {
                 $nothingLogged = $strNoConversionLoggedInInterval;
             } else {
                 return array('body' => '', 'adviews' => 0);
             }
         }
     }
     // Prepare the result
     $emailBodyStats = '';
     $total = 0;
     // Fetch the ad's stats for the report period, grouped by day
     $doDataSummaryAdHourly = OA_Dal::factoryDO('data_summary_ad_hourly');
     $doDataSummaryAdHourly->selectAdd();
     $doDataSummaryAdHourly->selectAdd("date_time");
     $doDataSummaryAdHourly->selectAdd("SUM({$type}) as quantity");
     $doDataSummaryAdHourly->ad_id = $adId;
     $doDataSummaryAdHourly->whereAdd("impressions > 0");
     if (!is_null($oStartDate)) {
         $oDate = new Date($oStartDate);
         $oDate->toUTC();
         $doDataSummaryAdHourly->whereAdd('date_time >= ' . $oDbh->quote($oDate->format('%Y-%m-%d %H:%M:%S'), 'timestamp'));
     }
     $oDate = new Date($oEndDate);
     $oDate->toUTC();
     $doDataSummaryAdHourly->whereAdd('date_time <= ' . $oDbh->quote($oDate->format('%Y-%m-%d %H:%M:%S'), 'timestamp'));
     $doDataSummaryAdHourly->groupBy('date_time');
     $doDataSummaryAdHourly->orderBy('date_time DESC');
     $doDataSummaryAdHourly->find();
     if ($doDataSummaryAdHourly->getRowCount() > 0) {
         // The ad has statistics this period, perform time zone conversion and summarize
         $aAdQuantity = array();
         while ($doDataSummaryAdHourly->fetch()) {
             $v = $doDataSummaryAdHourly->toArray();
             $oDate = new Date($v['date_time']);
             $oDate->setTZbyID('UTC');
             $oDate->convertTZ($oEndDate->tz);
             $k = $oDate->format($date_format);
             if (!isset($aAdQuantity[$k])) {
                 $aAdQuantity[$k] = 0;
             }
             $aAdQuantity[$k] += $v['quantity'];
         }
         foreach ($aAdQuantity as $day => $quantity) {
             // Add this day
             $emailBodyStats .= sprintf($adTextPrint, $day) . ': ';
             $emailBodyStats .= sprintf('%15s', phpAds_formatNumber($quantity)) . "\n";
             $total += $quantity;
         }
         // Add the total statistics for the period
         $emailBodyStats .= sprintf($adTextPrint, $strTotalThisPeriod) . ': ';
         $emailBodyStats .= sprintf('%15s', phpAds_formatNumber($total)) . "\n";
     } else {
         // Simply note that there were no statistics this period
         $emailBodyStats .= '  ' . $nothingLogged . "\n";
     }
     // Return the result for the ad's stats
     return array('body' => $emailBodyStats, 'adviews' => $total);
 }