Exemplo 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');
     }
 }
Exemplo n.º 2
0
 /**
  * A private method used to return a copy of a Date object after altering its time. It can work using
  * either UTC or the current TZ and eventually converting the result back to UTC.
  *
  * @param Date $oDate
  * @param bool $localTZ
  * @param int $hour
  * @param int $minute
  * @param int $second
  * @return Date
  */
 private function setTimeAndReturnUTC($oDate, $localTZ = false, $hour = 0, $minute = 0, $second = 0)
 {
     $oTz = $this->getTimeZone($localTZ);
     $oDateCopy = new Date($oDate);
     $oDateCopy->setHour($hour);
     $oDateCopy->setMinute($minute);
     $oDateCopy->setSecond($second);
     $oDateCopy->setTZ($oTz);
     $oDateCopy->toUTC();
     return $oDateCopy;
 }
Exemplo n.º 3
0
  static public function create($year=0, $month=0, $day=0, $hour=0, $minute=0, $second=0)
  {
    $d = new Date();

    $d->setYear($year);
    $d->setMonth($month);
    $d->setDay($day);
    $d->setHour($hour);
    $d->setMinute($minute);
    $d->setSecond($second);

    return $d;
  }
Exemplo n.º 4
0
 function getStats()
 {
     // Set time zone to local
     OA_setTimeZoneLocal();
     $oEnd = new Date();
     $oEnd->setHour(0);
     $oEnd->setMinute(0);
     $oEnd->setSecond(0);
     $oEnd->toUTC();
     $oStart = new Date($oEnd);
     $oStart->subtractSpan(new Date_Span('7-0-0-0'));
     $oStart->toUTC();
     $doDsah = OA_Dal::factoryDO('data_summary_ad_hourly');
     $doDsah->selectAdd();
     $doDsah->selectAdd("DATE_FORMAT(date_time, '%Y-%m-%d') AS day");
     $doDsah->selectAdd('SUM(' . $doDsah->tableName() . '.impressions) AS total_impressions');
     $doDsah->selectAdd('SUM(' . $doDsah->tableName() . '.clicks) AS total_clicks');
     $doDsah->whereAdd("date_time >= '" . $doDsah->escape($oStart->format('%Y-%m-%d %H:%M:%S')) . "'");
     $doDsah->whereAdd("date_time < '" . $doDsah->escape($oEnd->format('%Y-%m-%d %H:%M:%S')) . "'");
     if (OA_Permission::isAccount(OA_ACCOUNT_MANAGER)) {
         $doBanners = OA_Dal::factoryDO('banners');
         $doCampaigns = OA_Dal::factoryDO('campaigns');
         $doClients = OA_Dal::factoryDO('clients');
         $doClients->agencyid = OA_Permission::getEntityId();
         $doCampaigns->joinAdd($doClients);
         $doBanners->joinAdd($doCampaigns);
         $doBanners->selectAdd();
         $doBanners->selectAdd("bannerid");
         $doBanners->find();
         $ad_ids = array();
         while ($doBanners->fetch()) {
             $ad_ids[] = $doBanners->bannerid;
         }
         if (empty($ad_ids)) {
             return array();
         }
         $doDsah->whereAdd("ad_id IN (" . implode(",", $ad_ids) . ")");
     }
     $doDsah->groupBy('day');
     $doDsah->orderBy('day');
     $doDsah->find();
     $aStats = array();
     while ($doDsah->fetch()) {
         $row = $doDsah->toArray();
         $aStats[0][date('D', strtotime($row['day']))] = $row['total_impressions'];
         $aStats[1][date('D', strtotime($row['day']))] = $row['total_clicks'];
     }
     return $aStats;
 }
Exemplo n.º 5
0
 /**
  * Check start/end dates - note that check is the reverse of normal check:
  * if the operation interval is <= 60, must be start/end of an hour, to
  * make sure we update all the operation intervals in the hour, and if
  * the operation interval > 60, must be the start/end of an operation
  * interval, to make sure we update all the hours in the operation interval.
  *
  * @static
  * @param Date $oStartDate
  * @param Date $oEndDate
  * @return boolean
  */
 function checkDates($oStartDate, $oEndDate)
 {
     $aConf = $GLOBALS['_MAX']['CONF'];
     $operationInterval = $aConf['maintenance']['operation_interval'];
     if ($operationInterval <= 60) {
         // Must ensure that only one hour is being summarised
         if (!OX_OperationInterval::checkDatesInSameHour($oStartDate, $oEndDate)) {
             return false;
         }
         // Now check that the start and end dates are match the start and
         // end of the hour
         $oHourStart = new Date();
         $oHourStart->setYear($oStartDate->getYear());
         $oHourStart->setMonth($oStartDate->getMonth());
         $oHourStart->setDay($oStartDate->getDay());
         $oHourStart->setHour($oStartDate->getHour());
         $oHourStart->setMinute('00');
         $oHourStart->setSecond('00');
         $oHourEnd = new Date();
         $oHourEnd->setYear($oEndDate->getYear());
         $oHourEnd->setMonth($oEndDate->getMonth());
         $oHourEnd->setDay($oEndDate->getDay());
         $oHourEnd->setHour($oEndDate->getHour());
         $oHourEnd->setMinute('59');
         $oHourEnd->setSecond('59');
         if (!$oStartDate->equals($oHourStart)) {
             return false;
         }
         if (!$oEndDate->equals($oHourEnd)) {
             return false;
         }
     } else {
         // Must ensure that only one operation interval is being summarised
         $operationIntervalID = OX_OperationInterval::convertDaySpanToOperationIntervalID($oStartDate, $oEndDate, $operationInterval);
         if (is_bool($operationIntervalID) && !$operationIntervalID) {
             return false;
         }
         // Now check that the start and end dates match the start and end
         // of the operation interval
         list($oOperationIntervalStart, $oOperationIntervalEnd) = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oStartDate, $operationInterval);
         if (!$oStartDate->equals($oOperationIntervalStart)) {
             return false;
         }
         if (!$oEndDate->equals($oOperationIntervalEnd)) {
             return false;
         }
     }
     return true;
 }
 protected function _setPeriodFilter($request)
 {
     $locale = Limb::toolkit()->getLocale();
     $start_date = new Date();
     $start_date->setHour(0);
     $start_date->setMinute(0);
     $start_date->setSecond(0);
     if ($stats_start_date = $request->get('stats_start_date')) {
         $start_date->setByLocaleString($locale, $stats_start_date, $locale->getShortDateTimeFormat());
     }
     $finish_date = new Date();
     if ($stats_finish_date = $request->get('stats_finish_date')) {
         $finish_date->setByLocaleString($locale, $stats_finish_date, $locale->getShortDateTimeFormat());
     }
     $finish_date->setHour(23);
     $finish_date->setMinute(59);
     $finish_date->setSecond(59);
     $this->_stats_report->setPeriodFilter($start_date, $finish_date);
 }
 function process(&$sql)
 {
     $toolkit =& Limb::toolkit();
     $request =& $toolkit->getRequest();
     $start_date = new Date();
     $start_date->setHour(0);
     $start_date->setMinute(0);
     $start_date->setSecond(0);
     if ($stats_start_date = $request->get('start_date')) {
         $start_date->setByString($stats_start_date);
     }
     $finish_date = new Date();
     if ($stats_finish_date = $request->get('finish_date')) {
         $finish_date->setByString($stats_finish_date);
     }
     $finish_date->setHour(23);
     $finish_date->setMinute(59);
     $finish_date->setSecond(59);
     $start_stamp = $start_date->getStamp();
     $finish_stamp = $finish_date->getStamp();
     $sql->addCondition("master.time BETWEEN {$start_stamp} AND {$finish_stamp}");
 }
Exemplo n.º 8
0
 /**
  * This method modifies an existing campaign. Undefined fields do not change
  * and defined fields with a NULL value also remain unchanged.
  *
  * @access public
  *
  * @param OA_Dll_CampaignInfo &$oCampaign <br />
  *          <b>For adding</b><br />
  *          <b>Required properties:</b> advertiserId<br />
  *          <b>Optional properties:</b> campaignName, startDate, endDate, impressions, clicks, priority, weight<br />
  *
  *          <b>For modify</b><br />
  *          <b>Required properties:</b> campaignId<br />
  *          <b>Optional properties:</b> advertiserId, campaignName, startDate, endDate, impressions, clicks, priority, weight, viewWindow, clickWindow<br />
  *
  * @return boolean  True if the operation was successful
  *
  */
 function modify(&$oCampaign)
 {
     if (!isset($oCampaign->campaignId)) {
         // Add
         $oCampaign->setDefaultForAdd();
         if (!$this->checkPermissions(array(OA_ACCOUNT_ADMIN, OA_ACCOUNT_MANAGER), 'clients', $oCampaign->advertiserId)) {
             return false;
         }
     } else {
         // Edit
         if (!$this->checkPermissions(array(OA_ACCOUNT_ADMIN, OA_ACCOUNT_MANAGER), 'campaigns', $oCampaign->campaignId)) {
             return false;
         }
     }
     $oStartDate = $oCampaign->startDate;
     $oEndDate = $oCampaign->endDate;
     $campaignData = (array) $oCampaign;
     $campaignData['campaignid'] = $oCampaign->campaignId;
     $campaignData['campaignname'] = $oCampaign->campaignName;
     $campaignData['clientid'] = $oCampaign->advertiserId;
     $oNow = new Date();
     if (is_object($oStartDate)) {
         $oDate = new Date($oStartDate);
         $oDate->setTZ($oNow->tz);
         $oDate->setHour(0);
         $oDate->setMinute(0);
         $oDate->setSecond(0);
         $oDate->toUTC();
         $campaignData['activate_time'] = $oDate->getDate(DATE_FORMAT_ISO);
     }
     if (is_object($oEndDate)) {
         $oDate = new Date($oEndDate);
         $oDate->setTZ($oNow->tz);
         $oDate->setHour(23);
         $oDate->setMinute(59);
         $oDate->setSecond(59);
         $oDate->toUTC();
         $campaignData['expire_time'] = $oDate->getDate(DATE_FORMAT_ISO);
     }
     $campaignData['views'] = $oCampaign->impressions;
     $campaignData['target_impression'] = $oCampaign->targetImpressions;
     $campaignData['target_click'] = $oCampaign->targetClicks;
     $campaignData['target_conversion'] = $oCampaign->targetConversions;
     $campaignData['revenue_type'] = $oCampaign->revenueType;
     $campaignData['capping'] = $oCampaign->capping > 0 ? $oCampaign->capping : 0;
     $campaignData['session_capping'] = $oCampaign->sessionCapping > 0 ? $oCampaign->sessionCapping : 0;
     $campaignData['block'] = $oCampaign->block > 0 ? $oCampaign->block : 0;
     $campaignData['viewwindow'] = $oCampaign->viewWindow;
     $campaignData['clickwindow'] = $oCampaign->clickWindow;
     if ($this->_validate($oCampaign)) {
         $doCampaign = OA_Dal::factoryDO('campaigns');
         if (!isset($oCampaign->campaignId)) {
             $doCampaign->setFrom($campaignData);
             $oCampaign->campaignId = $doCampaign->insert();
         } else {
             $doCampaign->get($campaignData['campaignid']);
             $doCampaign->setFrom($campaignData);
             $doCampaign->update();
         }
         return true;
     } else {
         return false;
     }
 }
Exemplo n.º 9
0
 /**
  * A method to check if midnight tasks should run
  *
  * @param Date $oLastRun
  * @return boolean
  */
 function isMidnightMaintenance($oLastRun)
 {
     global $serverTimezone;
     if (empty($oLastRun)) {
         return true;
     }
     $oServiceLocator =& OA_ServiceLocator::instance();
     $lastMidnight = new Date($oServiceLocator->get('now'));
     if (!empty($serverTimezone)) {
         $lastMidnight->convertTZbyID($serverTimezone);
     }
     $lastMidnight->setHour(0);
     $lastMidnight->setMinute(0);
     $lastMidnight->setSecond(0);
     $oLastRunCopy = new Date($oLastRun);
     return $oLastRunCopy->before($lastMidnight);
 }
Exemplo n.º 10
0
 /**
  * Tests that an e-mail reporting on impending campaign expiration
  * is able to be generated correctly.
  */
 function testSendAndPrepareCampaignImpendingExpiryEmail()
 {
     $adminContact = 'Andrew Hill';
     $adminName = 'OpenX Limited';
     $adminMail = '*****@*****.**';
     $adminCompany = 'Admin company name';
     $adminAccountId = 100;
     $agencyName = 'Agency Ltd.';
     $agencyContact = 'Mr. Foo Bar Agency';
     $agencyMail = '*****@*****.**';
     $advertiserName = 'Foo Client';
     $advertiserMail = '*****@*****.**';
     $advertiserUsername = '******';
     $aConf =& $GLOBALS['_MAX']['CONF'];
     $aConf['webpath']['admin'] = 'example.com';
     $aConf['email']['fromAddress'] = $adminMail;
     $aConf['email']['fromName'] = $adminName;
     $aConf['email']['fromCompany'] = $adminCompany;
     $aConf['email']['useManagerDetails'] = true;
     $aConf['email']['logOutgoing'] = true;
     $mockName = uniqid('PartialMockOA_Email_');
     Mock::generatePartial('OA_Email', $mockName, array('sendMail'));
     $oEmail = new $mockName();
     $oEmail->setReturnValue('sendMail', true);
     // Prepare valid test data
     $dateReason = 'date';
     $dateValue = '2007-05-15';
     $impReason = 'impressions';
     $impValue = 100;
     // The tests below assume that the number of days before a campaign expires when the
     $oCampaignDate = new Date($dateValue);
     $oCampaignDate->setHour(23);
     $oCampaignDate->setMinute(59);
     $oCampaignDate->setSecond(59);
     $oCampaignDate->toUTC();
     $oTwoDaysPriorDate = new Date($dateValue);
     $oTwoDaysPriorDate->subtractSeconds(2 * 24 * 60 * 60 - 10);
     $oNowDate = new Date($dateValue);
     // Prepare an admin user
     // Create the admin account
     $doAccounts = OA_Dal::factoryDO('accounts');
     $doAccounts->account_name = 'System Administrator';
     $doAccounts->account_type = OA_ACCOUNT_ADMIN;
     $adminAccountId = DataGenerator::generateOne($doAccounts);
     // Setup the admin account id
     $doAppVar = OA_Dal::factoryDO('application_variable');
     $doAppVar->name = 'admin_account_id';
     $doAppVar->value = $adminAccountId;
     // Create an user
     $doAdminUser = OA_Dal::factoryDO('users');
     $doAdminUser->contact_name = $adminContact;
     $doAdminUser->email_address = $adminMail;
     $doAdminUser->username = $adminName;
     $doAdminUser->password = md5('password');
     $doAdminUser->language = 'en';
     $doAdminUser->default_account_id = $adminAccountId;
     $adminUserId = DataGenerator::generateOne($doAdminUser);
     $doAdminUser = OA_Dal::staticGetDO('users', $adminUserId);
     $aAdminUser = $doAdminUser->toArray();
     // Create admin account-user association
     $doAUA = OA_Dal::factoryDO('account_user_assoc');
     $doAUA->account_id = $adminAccountId;
     $doAUA->user_id = $adminUserId;
     $doAUA->insert();
     // Prepare an agency
     $doAgency = OA_Dal::factoryDO('agency');
     $doAgency->name = $agencyName;
     $doAgency->contact = $agencyContact;
     $doAgency->email = $agencyMail;
     $agencyId = DataGenerator::generateOne($doAgency);
     $doAgency = OA_Dal::staticGetDO('agency', $agencyId);
     //get('agencyid', $agencyId);
     $agencyAccountId = $doAgency->account_id;
     // Prepare an agency user
     $doUser = OA_Dal::factoryDO('users');
     $doUser->contact_name = $agencyContact;
     $doUser->email_address = $agencyMail;
     $doUser->username = $agencyName;
     $doUser->language = 'en';
     $agencyUserId = DataGenerator::generateOne($doUser);
     $doAgencyUser = OA_Dal::staticGetDO('users', $agencyUserId);
     $aAgencyUser = $doAgencyUser->toArray();
     $oUserAccess = new OA_Admin_UI_UserAccess();
     // Agency user
     $oUserAccess->linkUserToAccount($agencyUserId, $doAgency->account_id, array(), array());
     // Generate an advertiser owned by the agency with no email adddress,
     // but no placements, and ensure false is returned
     $doClients = OA_Dal::factoryDO('clients');
     $doClients->agencyid = $agencyId;
     $doClients->clientname = $advertiserName;
     $doClients->email = '';
     $advertiserId1 = DataGenerator::generateOne($doClients);
     $doClients = OA_Dal::staticGetDO('clients', 'clientid', $advertiserId1);
     // ->get('clientid', $advertiserId1);
     $advertiserAccountId = $doClients->account_id;
     // Create an advertiser user
     $doUser = OA_Dal::factoryDO('users');
     $doUser->contact_name = $advertiserName;
     $doUser->email_address = $advertiserMail;
     $doUser->username = $advertiserUsername;
     $doUser->language = 'en';
     $userId = DataGenerator::generateOne($doUser);
     $doAdvertiserUser = OA_Dal::staticGetDO('users', $userId);
     $aAdvertiserUser = $doAdvertiserUser->toArray();
     // Link the advertiser user
     $oUserAccess->linkUserToAccount($userId, $doClients->account_id, array(), array());
     // Create a campaign
     $doPlacements = OA_Dal::factoryDO('campaigns');
     $doPlacements->clientid = $advertiserId1;
     $doPlacements->campaignname = 'Default Campaign';
     $doPlacements->views = 50;
     $doPlacements->expire_time = $oCampaignDate->getDate(DATE_FORMAT_ISO);
     $placementId = DataGenerator::generateOne($doPlacements);
     $doPlacements = OA_Dal::staticGetDO('campaigns', $placementId);
     $aCampaign = $doPlacements->toArray();
     $result = $oEmail->sendCampaignImpendingExpiryEmail($oNowDate, $placementId);
     // No emails should be sent yet because the preferences weren't set
     $this->assertEqual($result, 0);
     // No entries in userlog
     $doUserLog = OA_Dal::factoryDO('userlog');
     $doUserLog->find();
     $this->assertFalse($doUserLog->fetch());
     // Create the preference
     $doPreferences = OA_Dal::factoryDO('preferences');
     $doPreferences->preference_name = 'warn_email_admin';
     $doPreferences->account_type = OA_ACCOUNT_ADMIN;
     $warnEmailAdminPreferenceId = DataGenerator::generateOne($doPreferences);
     // Set the admin preference
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $adminAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailAdminPreferenceId;
     $doAccount_Preference_Assoc->value = 1;
     DataGenerator::generateOne($doAccount_Preference_Assoc);
     // Create the admin threshold preference
     $doPreferences = OA_Dal::factoryDO('preferences');
     $doPreferences->preference_name = 'warn_email_admin_impression_limit';
     $doPreferences->account_type = OA_ACCOUNT_ADMIN;
     $warnEmailAdminImpLimitPreferenceId = DataGenerator::generateOne($doPreferences);
     // Set the admin preference
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $adminAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailAdminImpLimitPreferenceId;
     $doAccount_Preference_Assoc->value = 100;
     DataGenerator::generateOne($doAccount_Preference_Assoc);
     // Create the admin day warning
     $doPreferences = OA_Dal::factoryDO('preferences');
     $doPreferences->preference_name = 'warn_email_admin_day_limit';
     $doPreferences->account_type = OA_ACCOUNT_ADMIN;
     $warnEmailAdminDayLimitPreferenceId = DataGenerator::generateOne($doPreferences);
     // Set the admin preference
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $adminAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailAdminDayLimitPreferenceId;
     $doAccount_Preference_Assoc->value = 2;
     DataGenerator::generateOne($doAccount_Preference_Assoc);
     // Set the agency preferences
     $doPreferences = OA_Dal::factoryDO('preferences');
     $doPreferences->preference_name = 'warn_email_manager';
     $doPreferences->account_type = OA_ACCOUNT_MANAGER;
     $warnEmailManagerPreferenceId = DataGenerator::generateOne($doPreferences);
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $agencyAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailManagerPreferenceId;
     $doAccount_Preference_Assoc->value = 0;
     DataGenerator::generateOne($doAccount_Preference_Assoc);
     $doPreferences = OA_Dal::factoryDO('preferences');
     $doPreferences->preference_name = 'warn_email_manager_impression_limit';
     $doPreferences->account_type = OA_ACCOUNT_MANAGER;
     $warnEmailManagerImpLimitPreferenceId = DataGenerator::generateOne($doPreferences);
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $agencyAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailManagerImpLimitPreferenceId;
     $doAccount_Preference_Assoc->value = 100;
     DataGenerator::generateOne($doAccount_Preference_Assoc);
     $doPreferences = OA_Dal::factoryDO('preferences');
     $doPreferences->preference_name = 'warn_email_manager_day_limit';
     $doPreferences->account_type = OA_ACCOUNT_MANAGER;
     $warnEmailManagerDayLimitPreferenceId = DataGenerator::generateOne($doPreferences);
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $agencyAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailManagerDayLimitPreferenceId;
     $doAccount_Preference_Assoc->value = 2;
     DataGenerator::generateOne($doAccount_Preference_Assoc);
     // Set the advertiser preferences
     $doPreferences = OA_Dal::factoryDO('preferences');
     $doPreferences->preference_name = 'warn_email_advertiser';
     $doPreferences->account_type = OA_ACCOUNT_ADVERTISER;
     $warnEmailAdvertiserPreferenceId = DataGenerator::generateOne($doPreferences);
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $advertiserAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailAdvertiserPreferenceId;
     $doAccount_Preference_Assoc->value = 0;
     DataGenerator::generateOne($doAccount_Preference_Assoc);
     $doPreferences = OA_Dal::factoryDO('preferences');
     $doPreferences->preference_name = 'warn_email_advertiser_impression_limit';
     $doPreferences->account_type = OA_ACCOUNT_ADVERTISER;
     $warnEmailAdvertiserImpLimitPreferenceId = DataGenerator::generateOne($doPreferences);
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $advertiserAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailAdvertiserImpLimitPreferenceId;
     $doAccount_Preference_Assoc->value = 100;
     DataGenerator::generateOne($doAccount_Preference_Assoc);
     $doPreferences = OA_Dal::factoryDO('preferences');
     $doPreferences->preference_name = 'warn_email_advertiser_day_limit';
     $doPreferences->account_type = OA_ACCOUNT_ADVERTISER;
     $warnEmailAdvertiserDayLimitPreferenceId = DataGenerator::generateOne($doPreferences);
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $advertiserAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailAdvertiserDayLimitPreferenceId;
     $doAccount_Preference_Assoc->value = 2;
     DataGenerator::generateOne($doAccount_Preference_Assoc);
     // Create another user linked to the advertiser account and ensure that an additional email is sent
     $doUser = OA_Dal::factoryDO('users');
     $doUser->contact_name = '2_' . $advertiserName;
     $doUser->email_address = '2_' . $advertiserMail;
     $doUser->username = '******' . $clientName;
     $doUser->language = 'de';
     $advertiserUserId2 = DataGenerator::generateOne($doUser);
     $doAdvertiserUser2 = OA_Dal::staticGetDO('users', $advertiserUserId2);
     $aAdvertiserUser2 = $doAdvertiserUser2->toArray();
     // Link the advertiser user
     $oUserAccess->linkUserToAccount($advertiserUserId2, $doClients->account_id, array(), array());
     // If the advertiser preference is off, then the advertiser should not be sent emails
     // even if the admin/manager preference is on
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $advertiserAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailAdvertiserPreferenceId;
     $doAccount_Preference_Assoc->value = 0;
     $doAccount_Preference_Assoc->update();
     // And turning off the manager preference should leave just agency emails (2)
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $agencyAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailManagerPreferenceId;
     $doAccount_Preference_Assoc->value = 0;
     $doAccount_Preference_Assoc->update();
     // -- The above sets up the environment for the tests below -- //
     // Check the body when passing in the admin user:
     $expectedSubject = "Impending campaign expiration: {$advertiserName}";
     $expectedContents = "Dear {$adminContact},\n\n";
     $expectedContents .= "The campaign belonging to {$advertiserName} shown below is due to end on {$dateValue}.\n\n";
     $expectedContents .= "As a result, the campaign will soon be automatically disabled, and the\n";
     $expectedContents .= "following banners in the campaign will also be disabled:\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "-------------------------------------------------------\n\n";
     $expectedContents .= " There are currently no banners defined for this campaign.\n\n";
     $expectedContents .= "-------------------------------------------------------\n\n\n";
     $expectedContents .= "Regards,\n   {$adminName}, {$adminCompany}";
     // Clear cache
     $oEmail->clearCache();
     Language_Loader::load('default', $aAdminUser['language']);
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oTwoDaysPriorDate, $placementId);
     $aResult = $oEmail->prepareCampaignImpendingExpiryEmail($aAdminUser, $advertiserId1, $placementId, $dateReason, $dateValue, 'admin');
     $this->assertEqual($numSent, 1);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     // One entry in userlog
     $doUserLog = OA_Dal::factoryDO('userlog');
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 1);
     $this->assertEqual($aUserLog[0]['action'], phpAds_actionWarningMailed);
     // Turn off email logging and send mail again
     $aConf['email']['logOutgoing'] = false;
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oTwoDaysPriorDate, $placementId);
     $this->assertEqual($numSent, 1);
     // Still one entry in userlog
     $doUserLog = OA_Dal::factoryDO('userlog');
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 1);
     // Set email logging back to true
     $aConf['email']['logOutgoing'] = true;
     // Manager user
     $expectedSubject = "Impending campaign expiration: {$advertiserName}";
     $expectedContents = "Dear {$aAgencyUser['contact_name']},\n\n";
     $expectedContents .= "The campaign belonging to {$advertiserName} shown below is due to end on {$dateValue}.\n\n";
     $expectedContents .= "As a result, the campaign will soon be automatically disabled, and the\n";
     $expectedContents .= "following banners in the campaign will also be disabled:\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "-------------------------------------------------------\n\n";
     $expectedContents .= " There are currently no banners defined for this campaign.\n\n";
     $expectedContents .= "-------------------------------------------------------\n\n\n";
     $expectedContents .= "Regards,\n   " . $aConf['email']['fromName'] . ", " . $aConf['email']['fromCompany'];
     Language_Loader::load('default', $aAgencyUser['language']);
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oTwoDaysPriorDate, $placementId);
     $aResult = $oEmail->prepareCampaignImpendingExpiryEmail($aAgencyUser, $advertiserId1, $placementId, $dateReason, $dateValue, 'manager');
     $this->assertEqual($numSent, 1);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     // Should create another entry in userlog
     $doUserLog = OA_Dal::factoryDO('userlog');
     $doUserLog->action = phpAds_actionWarningMailed;
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 2);
     // Use email from details instead of the owning account's details
     $aConf['email']['useManagerDetails'] = false;
     // Manager user
     $expectedSubject = "Impending campaign expiration: {$advertiserName}";
     $expectedContents = "Dear {$aAgencyUser['contact_name']},\n\n";
     $expectedContents .= "The campaign belonging to {$advertiserName} shown below is due to end on {$dateValue}.\n\n";
     $expectedContents .= "As a result, the campaign will soon be automatically disabled, and the\n";
     $expectedContents .= "following banners in the campaign will also be disabled:\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "-------------------------------------------------------\n\n";
     $expectedContents .= " There are currently no banners defined for this campaign.\n\n";
     $expectedContents .= "-------------------------------------------------------\n\n\n";
     $expectedContents .= "Regards,\n   " . $aConf['email']['fromName'] . ", " . $aConf['email']['fromCompany'];
     Language_Loader::load('default', $aAgencyUser['language']);
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oTwoDaysPriorDate, $placementId);
     $aResult = $oEmail->prepareCampaignImpendingExpiryEmail($aAgencyUser, $advertiserId1, $placementId, $dateReason, $dateValue, 'manager');
     $this->assertEqual($numSent, 1);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     // Use email from empty details and test that not Regards are added
     $aConf['email']['fromAddress'] = '';
     $aConf['email']['fromName'] = '';
     $aConf['email']['fromCompany'] = '';
     // Manager user
     $expectedSubject = "Impending campaign expiration: {$advertiserName}";
     $expectedContents = "Dear {$aAgencyUser['contact_name']},\n\n";
     $expectedContents .= "The campaign belonging to {$advertiserName} shown below is due to end on {$dateValue}.\n\n";
     $expectedContents .= "As a result, the campaign will soon be automatically disabled, and the\n";
     $expectedContents .= "following banners in the campaign will also be disabled:\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "-------------------------------------------------------\n\n";
     $expectedContents .= " There are currently no banners defined for this campaign.\n\n";
     $expectedContents .= "-------------------------------------------------------\n\n\n";
     Language_Loader::load('default', $aAgencyUser['language']);
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oTwoDaysPriorDate, $placementId);
     $aResult = $oEmail->prepareCampaignImpendingExpiryEmail($aAgencyUser, $advertiserId1, $placementId, $dateReason, $dateValue, 'manager');
     $this->assertEqual($numSent, 1);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     $aConf['email']['useManagerDetails'] = true;
     $aConf['email']['fromAddress'] = $adminMail;
     $aConf['email']['fromName'] = $adminName;
     $aConf['email']['fromCompany'] = $adminCompany;
     // Should create another entry in userlog
     $doUserLog = OA_Dal::factoryDO('userlog');
     $doUserLog->action = phpAds_actionWarningMailed;
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 4);
     // The following should never be sent because a campaign without banners should never deliver (and therefore never reach the "remaining" threshold)
     $expectedSubject = "Impending campaign expiration: {$advertiserName}";
     $expectedContents = "Dear {$aAdminUser['contact_name']},\n\n";
     $expectedContents .= "The campaign belonging to {$advertiserName} shown below has less than {$impValue} impressions remaining.\n\n";
     $expectedContents .= "As a result, the campaign will soon be automatically disabled, and the\n";
     $expectedContents .= "following banners in the campaign will also be disabled:\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "-------------------------------------------------------\n\n";
     $expectedContents .= " There are currently no banners defined for this campaign.\n\n";
     $expectedContents .= "-------------------------------------------------------\n\n\n";
     $expectedContents .= "Regards,\n   {$adminName}, {$adminCompany}";
     Language_Loader::load('default', $aAdminUser['language']);
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oNowDate, $placementId);
     $aResult = $oEmail->prepareCampaignImpendingExpiryEmail($aAdminUser, $advertiserId1, $placementId, $impReason, $impValue, 'admin');
     $this->assertEqual($numSent, 0);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     $expectedSubject = "Impending campaign expiration: {$advertiserName}";
     $expectedContents = "Dear {$aAgencyUser['contact_name']},\n\n";
     $expectedContents .= "The campaign belonging to {$advertiserName} shown below has less than {$impValue} impressions remaining.\n\n";
     $expectedContents .= "As a result, the campaign will soon be automatically disabled, and the\n";
     $expectedContents .= "following banners in the campaign will also be disabled:\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "-------------------------------------------------------\n\n";
     $expectedContents .= " There are currently no banners defined for this campaign.\n\n";
     $expectedContents .= "-------------------------------------------------------\n\n\n";
     $expectedContents .= "Regards,\n   " . $aConf['email']['fromName'] . ", " . $aConf['email']['fromCompany'];
     Language_Loader::load('default', $aAgencyUser['language']);
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oNowDate, $placementId);
     $aResult = $oEmail->prepareCampaignImpendingExpiryEmail($aAgencyUser, $advertiserId1, $placementId, $impReason, $impValue, 'manager');
     $this->assertEqual($numSent, 0);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     // Emails not sent, nothing new in userlog
     $doUserLog = OA_Dal::factoryDO('userlog');
     $doUserLog->action = phpAds_actionWarningMailed;
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 4);
     // Add some banners and retest
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $placementId;
     $doBanners->description = 'Test Banner';
     $doBanners->url = '';
     $bannerId1 = DataGenerator::generateOne($doBanners);
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $placementId;
     $doBanners->description = 'Test Banner';
     $doBanners->url = 'http://www.fornax.net/';
     $bannerId2 = DataGenerator::generateOne($doBanners);
     $expectedSubject = "Impending campaign expiration: {$advertiserName}";
     $expectedContents = "Dear {$aAdminUser['contact_name']},\n\n";
     $expectedContents .= "The campaign belonging to {$advertiserName} shown below is due to end on {$dateValue}.\n\n";
     $expectedContents .= "As a result, the campaign will soon be automatically disabled, and the\n";
     $expectedContents .= "following banners in the campaign will also be disabled:\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "-------------------------------------------------------\n\n";
     $expectedContents .= " Banner [id{$bannerId1}] Test Banner\n\n";
     $expectedContents .= " Banner [id{$bannerId2}] Test Banner\n";
     $expectedContents .= "  linked to: http://www.fornax.net/\n\n";
     $expectedContents .= "-------------------------------------------------------\n\n\n";
     $expectedContents .= "Regards,\n   {$adminName}, {$adminCompany}";
     Language_Loader::load('default', $aAdminUser['language']);
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oTwoDaysPriorDate, $placementId);
     $aResult = $oEmail->prepareCampaignImpendingExpiryEmail($aAdminUser, $advertiserId1, $placementId1, $dateReason, $dateValue, 'admin');
     $this->assertEqual($numSent, 1);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     $doUserLog = OA_Dal::factoryDO('userlog');
     $doUserLog->action = phpAds_actionWarningMailed;
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 5);
     $expectedSubject = "Impending campaign expiration: {$advertiserName}";
     $expectedContents = "Dear {$aAdvertiserUser['contact_name']},\n\n";
     $expectedContents .= "Your campaign shown below is due to end on {$dateValue}.\n\n";
     $expectedContents .= "As a result, the campaign will soon be automatically disabled, and the\n";
     $expectedContents .= "following banners in the campaign will also be disabled:\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "-------------------------------------------------------\n\n";
     $expectedContents .= " Banner [id{$bannerId1}] Test Banner\n\n";
     $expectedContents .= " Banner [id{$bannerId2}] Test Banner\n";
     $expectedContents .= "  linked to: http://www.fornax.net/\n\n";
     $expectedContents .= "-------------------------------------------------------\n\n\n";
     $expectedContents .= "Regards,\n   {$agencyContact}, {$agencyName}";
     Language_Loader::load('default', $aAdvertiserUser['language']);
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oTwoDaysPriorDate, $placementId);
     $aResult = $oEmail->prepareCampaignImpendingExpiryEmail($aAdvertiserUser, $advertiserId1, $placementId, $dateReason, $dateValue, 'advertiser');
     $this->assertEqual($numSent, 1);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     $doUserLog = OA_Dal::factoryDO('userlog');
     $doUserLog->action = phpAds_actionWarningMailed;
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 6);
     // Clear userlog table
     $doUserLog = OA_Dal::factoryDO('userlog');
     $doUserLog->whereAdd('1=1');
     $doUserLog->delete(DB_DATAOBJECT_WHEREADD_ONLY);
     // Enable the warn_email_advertiser preference and retest
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $advertiserAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailAdvertiserPreferenceId;
     $doAccount_Preference_Assoc->value = 1;
     $doAccount_Preference_Assoc->update();
     // Clear cache
     $oEmail->clearCache();
     // So should now send 1 admin and 2 advertiser emails
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oTwoDaysPriorDate, $placementId);
     $this->assertEqual($numSent, 3);
     $doUserLog = OA_Dal::factoryDO('userlog');
     $doUserLog->action = phpAds_actionWarningMailed;
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 3);
     $expectedSubject = "Impending campaign expiration: {$advertiserName}";
     $expectedContents = "Dear {$adminContact},\n\n";
     $expectedContents .= "The campaign belonging to {$advertiserName} shown below has less than {$impValue} impressions remaining.\n\n";
     $expectedContents .= "As a result, the campaign will soon be automatically disabled, and the\n";
     $expectedContents .= "following banners in the campaign will also be disabled:\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "-------------------------------------------------------\n\n";
     $expectedContents .= " Banner [id{$bannerId1}] Test Banner\n\n";
     $expectedContents .= " Banner [id{$bannerId2}] Test Banner\n";
     $expectedContents .= "  linked to: http://www.fornax.net/\n\n";
     $expectedContents .= "-------------------------------------------------------\n\n\n";
     $expectedContents .= "Regards,\n   {$adminName}, {$adminCompany}";
     $aResult = $oEmail->prepareCampaignImpendingExpiryEmail($aAdminUser, $advertiserId1, $placementId, $impReason, $impValue, 'admin');
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oTwoDaysPriorDate, $placementId);
     $this->assertEqual($numSent, 3);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     $doUserLog = OA_Dal::factoryDO('userlog');
     $doUserLog->action = phpAds_actionWarningMailed;
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 6);
     // Clear cache
     $oEmail->clearCache();
     // Enable the warn_email_manager preference and retest
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $agencyAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailManagerPreferenceId;
     $doAccount_Preference_Assoc->value = 1;
     $doAccount_Preference_Assoc->update();
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oTwoDaysPriorDate, $placementId);
     $this->assertEqual($numSent, 4);
     $doUserLog = OA_Dal::factoryDO('userlog');
     $doUserLog->action = phpAds_actionWarningMailed;
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 10);
     // Turn off email logging and send mail again
     $aConf['email']['logOutgoing'] = false;
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oTwoDaysPriorDate, $placementId);
     $this->assertEqual($numSent, 4);
     // No new entries in user log
     $doUserLog = OA_Dal::factoryDO('userlog');
     $doUserLog->action = phpAds_actionWarningMailed;
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 10);
     // Set email logging back to true
     $aConf['email']['logOutgoing'] = true;
     $expectedSubject = "Impending campaign expiration: {$advertiserName}";
     $expectedContents = "Dear {$aAdvertiserUser['contact_name']},\n\n";
     $expectedContents .= "Your campaign shown below has less than {$impValue} impressions remaining.\n\n";
     $expectedContents .= "As a result, the campaign will soon be automatically disabled, and the\n";
     $expectedContents .= "following banners in the campaign will also be disabled:\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "-------------------------------------------------------\n\n";
     $expectedContents .= " Banner [id{$bannerId1}] Test Banner\n\n";
     $expectedContents .= " Banner [id{$bannerId2}] Test Banner\n";
     $expectedContents .= "  linked to: http://www.fornax.net/\n\n";
     $expectedContents .= "-------------------------------------------------------\n\n\n";
     $expectedContents .= "Regards,\n   {$agencyContact}, {$agencyName}";
     $aResult = $oEmail->prepareCampaignImpendingExpiryEmail($aAdvertiserUser, $advertiserId1, $placementId, $impReason, $impValue, 'advertiser');
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     // Check that advertiser2's email is send in their desired language (german)
     $expectedSubject = "Bevorstehende Deaktivierung der Kampagne: {$advertiserName}";
     $expectedContents = "Sehr geehrte(r) {$aAdvertiserUser2['contact_name']},\n\n";
     $expectedContents .= "Unten angegebene Ihre Kampagne hat weniger als {$impValue} Impressions übrig.\n\n";
     $expectedContents .= "Auf Grund dessen wird die Kampagne bald deaktiviert und weiter unten angegebene Banner aus dieser Kampagne werden deaktiviert:\n";
     $expectedContents .= "\nKampagne [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "-------------------------------------------------------\n\n";
     $expectedContents .= " Banner [id{$bannerId1}] Test Banner\n\n";
     $expectedContents .= " Banner [id{$bannerId2}] Test Banner\n";
     $expectedContents .= "  verknüpft mit: http://www.fornax.net/\n\n";
     $expectedContents .= "-------------------------------------------------------\n\n\n";
     $expectedContents .= "Mit freundlichem Gruß\n   {$agencyContact}, {$agencyName}";
     $aResult = $oEmail->prepareCampaignImpendingExpiryEmail($aAdvertiserUser2, $advertiserId1, $placementId, $impReason, $impValue, 'advertiser');
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     DataGenerator::cleanUp(array('accounts', 'account_user_assoc'));
 }
Exemplo n.º 11
0
 /**
  * A method to check that two Dates represent either the start and end
  * of an operation interval, if the operation interval is less than an
  * hour, or the start and end of an hour otherwise.
  *
  * @static
  * @param Date $oStart The interval start date.
  * @param Date $oEnd The interval end date.
  * @param integer $operationInterval The operation interval in minutes.
  * @return bool Returns true if the dates are correct interval
  *              start/end dates, false otherwise.
  */
 function checkIntervalDates($oStart, $oEnd, $operationInterval = 0)
 {
     if ($operationInterval < 1) {
         $operationInterval = OX_OperationInterval::getOperationInterval();
     }
     if ($operationInterval <= 60) {
         // Must ensure that only one operation interval is being summarised
         $operationIntervalID = OX_OperationInterval::convertDateRangeToOperationIntervalID($oStart, $oEnd, $operationInterval);
         if (is_bool($operationIntervalID) && !$operationIntervalID) {
             return false;
         }
         // Now check that the start and end dates match the start and end
         // of the operation interval
         $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oStart, $operationInterval);
         if (!$oStart->equals($aDates['start'])) {
             return false;
         }
         if (!$oEnd->equals($aDates['end'])) {
             return false;
         }
     } else {
         // Must ensure that only one hour is being summarised
         if (!OX_OperationInterval::checkDatesInSameHour($oStart, $oEnd)) {
             return false;
         }
         // Now check that the start and end dates are match the start and
         // end of the hour
         $oHourStart = new Date();
         $oHourStart->copy($oStart);
         $oHourStart->setMinute('00');
         $oHourStart->setSecond('00');
         $oHourEnd = new Date();
         $oHourEnd->copy($oEnd);
         $oHourEnd->setMinute('59');
         $oHourEnd->setSecond('59');
         if (!$oStart->equals($oHourStart)) {
             return false;
         }
         if (!$oEnd->equals($oHourEnd)) {
             return false;
         }
     }
     return true;
 }
Exemplo n.º 12
0
 function _midnight($date)
 {
     $processed_date = new Date($date);
     $processed_date->setHour(0);
     $processed_date->setMinute(0);
     $processed_date->setSecond(0);
     return $processed_date;
 }
Exemplo n.º 13
0
 function _dayToDateTime($day, $begin = true)
 {
     $oDate = new Date($day);
     if (!$begin) {
         $oDate->setHour(23);
         $oDate->setMinute(59);
         $oDate->setSecond(59);
     }
     $oDate->toUTC();
     return $oDate->format('%Y-%m-%d %H:%M:%S');
 }
Exemplo n.º 14
0
 /**
  * A method to test the getDaysLeftString() method.
  */
 function testGetDaysLeftString()
 {
     /*
         	Possible cases for testing:
         	Case 1 -> Campaign without expiration date and without a estimated
         	          expiration date yet
         	Case 2 -> Campaign without expiration date and with a estimated
         	          expiration date
         	Case 3 -> Campaign with expiration date and without a estimated
         	          expiration date
         	Case 4 -> Campaign with expiration date reached
         	Case 5 -> Campaign with expiration date and with estimated
         	          expiration date minor than the expiration date
         	Case 6 -> Campaign with expiration date and with estimated
         	          expiration date equals to the expiration date
         	Case 7 -> Campaign with expiration date and with estimated
         	          expiration date higher than the expiration date
     */
     $GLOBALS['strExpirationDate'] = "Expiration date";
     $GLOBALS['strNoExpiration'] = "No expiration date set";
     $GLOBALS['strEstimated'] = "Estimated expiration date";
     $GLOBALS['strNoExpirationEstimation'] = "No expiration estimated yet";
     $GLOBALS['strCampaignStop'] = "Campaign stop";
     $GLOBALS['strDaysAgo'] = "days ago";
     $GLOBALS['strDaysLeft'] = "Days left";
     $GLOBALS['date_format'] = '%d.%m.%Y';
     // Case 1
     // Test an unlimited campaign without expiration date and without a
     // estimated expiration date yet
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->views = 0;
     $doCampaigns->clicks = 0;
     $doCampaigns->conversions = 0;
     $aData = array('reportlastdate' => array('2007-04-03 18:39:45'));
     $dg = new DataGenerator();
     $dg->setData('clients', $aData);
     $aCampaignIds = $dg->generate($doCampaigns, 1, true);
     $campaignId = $aCampaignIds[0];
     $expected = array('estimatedExpiration' => $GLOBALS['strEstimated'] . ": " . $GLOBALS['strNoExpirationEstimation'], 'campaignExpiration' => $GLOBALS['strNoExpiration']);
     $actual = $this->oDalCampaigns->getDaysLeftString($campaignId);
     $this->assertEqual($actual, $expected);
     // Case 2.1
     // Test a campaign (an impression limited campaign) without
     // expiration date and with a estimated expiration date
     $totalImpressions = 1000;
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->views = $totalImpressions;
     $doCampaigns->clicks = 0;
     $doCampaigns->conversions = 0;
     $aData = array('reportlastdate' => array('2007-04-03 18:39:45'));
     $dg = new DataGenerator();
     $dg->setData('clients', $aData);
     $aCampaignIds = $dg->generate($doCampaigns, 1, true);
     $campaignId = $aCampaignIds[0];
     // Link a banner to this campaign
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $campaignId;
     $doBanners->acls_updated = '2007-04-03 18:39:45';
     $bannerId = DataGenerator::generateOne($doBanners);
     // Insert impression delivery data occurring today
     $oDate = new Date();
     $impressions = 50;
     $clicks = 5;
     $conversions = 1;
     $doDSAH = OA_Dal::factoryDO('data_intermediate_ad');
     $doDSAH->day = $oDate->format('%Y-%m-%d');
     $doDSAH->hour = 10;
     $doDSAH->ad_id = $bannerId;
     $doDSAH->impressions = $impressions;
     $doDSAH->clicks = $clicks;
     $doDSAH->conversions = $conversions;
     $dsahId = DataGenerator::generateOne($doDSAH);
     // Delivered 50 impressions in 1 day. So, expect to take 19 days
     // to deliver remaining 950
     $daysLeft = 19;
     $oExpirationDate = new Date();
     $oExpirationDate->copy($oDate);
     $oExpirationDate->addSeconds($daysLeft * SECONDS_PER_DAY);
     $expected = array('estimatedExpiration' => $GLOBALS['strEstimated'] . ": " . $oExpirationDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")", 'campaignExpiration' => $GLOBALS['strNoExpiration']);
     $actual = $this->oDalCampaigns->getDaysLeftString($campaignId);
     $this->assertEqual($actual, $expected);
     // Case 2.2
     // Test a campaign (click limited campaign) without
     // expiration date and with a estimated expiration date
     $totalClicks = 500;
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->views = 0;
     $doCampaigns->clicks = $totalClicks;
     $doCampaigns->conversions = 0;
     $aData = array('reportlastdate' => array('2007-04-03 18:39:45'));
     $dg = new DataGenerator();
     $dg->setData('clients', $aData);
     $aCampaignIds = $dg->generate($doCampaigns, 1, true);
     $campaignId = $aCampaignIds[0];
     // Link a banner to this campaign
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $campaignId;
     $doBanners->acls_updated = '2007-04-03 18:39:45';
     $bannerId = DataGenerator::generateOne($doBanners);
     // Insert click delivery data occurring today
     $oDate = new Date();
     $impressions = 50;
     $clicks = 5;
     $conversions = 1;
     $doDSAH = OA_Dal::factoryDO('data_intermediate_ad');
     $doDSAH->day = $oDate->format('%Y-%m-%d');
     $doDSAH->hour = 10;
     $doDSAH->ad_id = $bannerId;
     $doDSAH->impressions = $impressions;
     $doDSAH->clicks = $clicks;
     $doDSAH->conversions = $conversions;
     $dsahId = DataGenerator::generateOne($doDSAH);
     // Delivered 5 clicks in 1 day. So, expect to take 99 days to deliver
     // remaining 495
     $daysLeft = 99;
     $oExpirationDate = new Date();
     $oExpirationDate->copy($oDate);
     $oExpirationDate->addSeconds($daysLeft * SECONDS_PER_DAY);
     $expected = array('estimatedExpiration' => $GLOBALS['strEstimated'] . ": " . $oExpirationDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")", 'campaignExpiration' => $GLOBALS['strNoExpiration']);
     $actual = $this->oDalCampaigns->getDaysLeftString($campaignId);
     $this->assertEqual($actual, $expected);
     // Case 2.3
     // Test a campaign (conversion limited campaign)
     // without expiration date and with a estimated expiration date
     $totalConversions = 10;
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->views = 0;
     $doCampaigns->clicks = 0;
     $doCampaigns->conversions = $totalConversions;
     $aData = array('reportlastdate' => array('2007-04-03 18:39:45'));
     $dg = new DataGenerator();
     $dg->setData('clients', $aData);
     $aCampaignIds = $dg->generate($doCampaigns, 1, true);
     $campaignId = $aCampaignIds[0];
     // Link a banner to this campaign
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $campaignId;
     $doBanners->acls_updated = '2007-04-03 18:39:45';
     $bannerId = DataGenerator::generateOne($doBanners);
     // Insert conversion delivery data occurring today
     $oDate = new Date();
     $impressions = 50;
     $clicks = 5;
     $conversions = 1;
     $doDSAH = OA_Dal::factoryDO('data_intermediate_ad');
     $doDSAH->day = $oDate->format('%Y-%m-%d');
     $doDSAH->hour = 10;
     $doDSAH->ad_id = $bannerId;
     $doDSAH->impressions = $impressions;
     $doDSAH->clicks = $clicks;
     $doDSAH->conversions = $conversions;
     $dsahId = DataGenerator::generateOne($doDSAH);
     // Delivered 1 conversion in 1 day. So, expect to take 9 days to deliver remaining 9
     $daysLeft = 9;
     $oExpirationDate = new Date();
     $oExpirationDate->copy($oDate);
     $oExpirationDate->addSeconds($daysLeft * SECONDS_PER_DAY);
     $expected = array('estimatedExpiration' => $GLOBALS['strEstimated'] . ": " . $oExpirationDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")", 'campaignExpiration' => $GLOBALS['strNoExpiration']);
     $actual = $this->oDalCampaigns->getDaysLeftString($campaignId);
     $this->assertEqual($actual, $expected);
     // Case 2.4
     // Test a triple limited campaign without expiration date
     // and with a estimated expiration date
     $totalImpressions = 1000;
     $totalClicks = 500;
     $totalConversions = 10;
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->views = $totalImpressions;
     $doCampaigns->clicks = $totalClicks;
     $doCampaigns->conversions = $totalConversions;
     $aData = array('reportlastdate' => array('2007-04-03 18:39:45'));
     $dg = new DataGenerator();
     $dg->setData('clients', $aData);
     $aCampaignIds = $dg->generate($doCampaigns, 1, true);
     $campaignId = $aCampaignIds[0];
     // Link a banner to this campaign
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $campaignId;
     $doBanners->acls_updated = '2007-04-03 18:39:45';
     $bannerId = DataGenerator::generateOne($doBanners);
     // Insert conversion delivery data occurring today
     $oDate = new Date();
     $impressions = 50;
     $clicks = 5;
     $conversions = 1;
     $doDSAH = OA_Dal::factoryDO('data_intermediate_ad');
     $doDSAH->day = $oDate->format('%Y-%m-%d');
     $doDSAH->hour = 10;
     $doDSAH->ad_id = $bannerId;
     $doDSAH->impressions = $impressions;
     $doDSAH->clicks = $clicks;
     $doDSAH->conversions = $conversions;
     $dsahId = DataGenerator::generateOne($doDSAH);
     // Delivered 50 impressions in 1 day. So, expect to take 19 days to
     // deliver remaining 950
     // Delivered 5 clicks in 1 day. So, expect to take 99 days to deliver
     // remaining 495
     // Delivered 1 conversion in 1 day. So, expect to take 9 days to deliver
     // remaining 9
     // The estimated expiration will be calucalated based on impression targets
     // or based on click targets or based on conversion targets (following this order).
     $daysLeft = 19;
     $oExpirationDate = new Date();
     $oExpirationDate->copy($oDate);
     $oExpirationDate->addSeconds($daysLeft * SECONDS_PER_DAY);
     $expected = array('estimatedExpiration' => $GLOBALS['strEstimated'] . ": " . $oExpirationDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")", 'campaignExpiration' => $GLOBALS['strNoExpiration']);
     $actual = $this->oDalCampaigns->getDaysLeftString($campaignId);
     $this->assertEqual($actual, $expected);
     // Case 3
     // Test a campaign with expiration date and without a estimated expiration date
     // Prepare a date 10 days in the future
     $daysLeft = 10;
     $oDate = new Date();
     $oDate->setHour(23);
     $oDate->setMinute(59);
     $oDate->setSecond(59);
     $oDate->addSeconds($daysLeft * SECONDS_PER_DAY);
     $oDate->toUTC();
     // Test an unlimited campaign which expires 10 days in the future
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->views = 0;
     $doCampaigns->clicks = 0;
     $doCampaigns->conversions = 0;
     $doCampaigns->expire_time = $oDate->getDate(DATE_FORMAT_ISO);
     $aData = array('reportlastdate' => array('2007-04-03 18:39:45'));
     $dg = new DataGenerator();
     $dg->setData('clients', $aData);
     $aCampaignIds = $dg->generate($doCampaigns, 1, true);
     $campaignId = $aCampaignIds[0];
     // Link a banner to this campaign
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $campaignId;
     $doBanners->acls_updated = '2007-04-03 18:39:45';
     $bannerId = DataGenerator::generateOne($doBanners);
     $expected = array('estimatedExpiration' => $GLOBALS['strEstimated'] . ": " . $GLOBALS['strNoExpirationEstimation'], 'campaignExpiration' => $GLOBALS['strExpirationDate'] . ": " . $oDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")");
     $actual = $this->oDalCampaigns->getDaysLeftString($campaignId);
     $this->assertEqual($actual, $expected);
     // Case 4
     // Campaign with expiration date reached
     // Prepare a campaign with expiration date reached
     $daysExpired = 5;
     $oDate = new Date();
     $oDate->setHour(23);
     $oDate->setMinute(59);
     $oDate->setSecond(59);
     $oDate->subtractSeconds($daysExpired * SECONDS_PER_DAY);
     $oDate->toUTC();
     // Test an unlimited campaign which expired 5 days ago
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->views = 0;
     $doCampaigns->clicks = 0;
     $doCampaigns->conversions = 0;
     $doCampaigns->expire_time = $oDate->getDate(DATE_FORMAT_ISO);
     $aData = array('reportlastdate' => array('2007-04-03 18:39:45'));
     $dg = new DataGenerator();
     $dg->setData('clients', $aData);
     $aCampaignIds = $dg->generate($doCampaigns, 1, true);
     $campaignId = $aCampaignIds[0];
     // Link a banner to this campaign
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $campaignId;
     $doBanners->acls_updated = '2007-04-03 18:39:45';
     $bannerId = DataGenerator::generateOne($doBanners);
     $expected = array('estimatedExpiration' => '', 'campaignExpiration' => $GLOBALS['strCampaignStop'] . ": " . $oDate->format('%d.%m.%Y') . " (" . $daysExpired . " " . $GLOBALS['strDaysAgo'] . ")");
     $actual = $this->oDalCampaigns->getDaysLeftString($campaignId);
     $this->assertEqual($actual, $expected);
     // Case 5
     // Campaign with expiration date and with estimated
     // expiration date minor than the expiration date
     // Prepare a date 25 days in the future
     $daysLeft = 25;
     $oDate = new Date();
     $oDate->setHour(23);
     $oDate->setMinute(59);
     $oDate->setSecond(59);
     $oDate->addSeconds($daysLeft * SECONDS_PER_DAY);
     $oDate->toUTC();
     $campaignExpiration = $GLOBALS['strExpirationDate'] . ": " . $oDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")";
     $totalImpressions = 1000;
     $totalClicks = 500;
     $totalConversions = 10;
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->expire_time = $oDate->getDate(DATE_FORMAT_ISO);
     $doCampaigns->views = $totalImpressions;
     $doCampaigns->clicks = $totalClicks;
     $doCampaigns->conversions = $totalConversions;
     $aData = array('reportlastdate' => array('2007-04-03 18:39:45'));
     $dg = new DataGenerator();
     $dg->setData('clients', $aData);
     $aCampaignIds = $dg->generate($doCampaigns, 1, true);
     $campaignId = $aCampaignIds[0];
     // Link a banner to this campaign
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $campaignId;
     $doBanners->acls_updated = '2007-04-03 18:39:45';
     $bannerId = DataGenerator::generateOne($doBanners);
     // Insert conversion delivery data occurring today
     $oDate = new Date();
     $impressions = 50;
     $clicks = 5;
     $conversions = 1;
     $doDSAH = OA_Dal::factoryDO('data_intermediate_ad');
     $doDSAH->day = $oDate->format('%Y-%m-%d');
     $doDSAH->hour = 10;
     $doDSAH->ad_id = $bannerId;
     $doDSAH->impressions = $impressions;
     $doDSAH->clicks = $clicks;
     $doDSAH->conversions = $conversions;
     $dsahId = DataGenerator::generateOne($doDSAH);
     // Delivered 50 impressions in 1 day. So, expect to take 19 days to
     // deliver remaining 950
     // Delivered 5 clicks in 1 day. So, expect to take 99 days to deliver
     // remaining 495
     // Delivered 1 conversion in 1 day. So, expect to take 9 days to deliver
     // remaining 9
     // The estimated expiration will be calucalated based onimpression targets
     // or based on click targets or based on conversion targets (following this order).
     $daysLeft = 19;
     $oExpirationDate = new Date();
     $oExpirationDate->copy($oDate);
     $oExpirationDate->addSeconds($daysLeft * SECONDS_PER_DAY);
     $expected = array('estimatedExpiration' => $GLOBALS['strEstimated'] . ": " . $oExpirationDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")", 'campaignExpiration' => $campaignExpiration);
     $actual = $this->oDalCampaigns->getDaysLeftString($campaignId);
     $this->assertEqual($actual, $expected);
     // Case 6
     // Campaign with expiration date and with estimated
     // expiration date equals to the expiration date
     // Prepare a date 19 days in the future
     $daysLeft = 19;
     $oDate = new Date();
     $oDate->setHour(23);
     $oDate->setMinute(59);
     $oDate->setSecond(59);
     $oDate->addSeconds($daysLeft * SECONDS_PER_DAY);
     $oDate->toUTC();
     $campaignExpiration = $GLOBALS['strExpirationDate'] . ": " . $oDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")";
     $totalImpressions = 1000;
     $totalClicks = 500;
     $totalConversions = 10;
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->expire_time = $oDate->getDate(DATE_FORMAT_ISO);
     $doCampaigns->views = $totalImpressions;
     $doCampaigns->clicks = $totalClicks;
     $doCampaigns->conversions = $totalConversions;
     $aData = array('reportlastdate' => array('2007-04-03 18:39:45'));
     $dg = new DataGenerator();
     $dg->setData('clients', $aData);
     $aCampaignIds = $dg->generate($doCampaigns, 1, true);
     $campaignId = $aCampaignIds[0];
     // Link a banner to this campaign
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $campaignId;
     $doBanners->acls_updated = '2007-04-03 18:39:45';
     $bannerId = DataGenerator::generateOne($doBanners);
     // Insert conversion delivery data occurring today
     $oDate = new Date();
     $impressions = 50;
     $clicks = 5;
     $conversions = 1;
     $doDSAH = OA_Dal::factoryDO('data_intermediate_ad');
     $doDSAH->day = $oDate->format('%Y-%m-%d');
     $doDSAH->hour = 10;
     $doDSAH->ad_id = $bannerId;
     $doDSAH->impressions = $impressions;
     $doDSAH->clicks = $clicks;
     $doDSAH->conversions = $conversions;
     $dsahId = DataGenerator::generateOne($doDSAH);
     // Delivered 50 impressions in 1 day. So, expect to take 19 days to
     // deliver remaining 950
     // Delivered 5 clicks in 1 day. So, expect to take 99 days to deliver
     // remaining 495
     // Delivered 1 conversion in 1 day. So, expect to take 9 days to
     // deliver remaining 9
     // The estimated expiration will be calucalated based on impression targets
     // or based on click targets or based on conversion targets (following this order).
     $daysLeft = 19;
     $oExpirationDate = new Date();
     $oExpirationDate->copy($oDate);
     $oExpirationDate->addSeconds($daysLeft * SECONDS_PER_DAY);
     $expected = array('estimatedExpiration' => $GLOBALS['strEstimated'] . ": " . $oExpirationDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")", 'campaignExpiration' => $campaignExpiration);
     $actual = $this->oDalCampaigns->getDaysLeftString($campaignId);
     $this->assertEqual($actual, $expected);
     // Case 7
     // Campaign with expiration date and with estimated
     // expiration date higher than the expiration date
     // Prepare a date 10 days in the future
     $daysLeft = 10;
     $oDate = new Date();
     $oDate->setHour(23);
     $oDate->setMinute(59);
     $oDate->setSecond(59);
     $oDate->addSeconds($daysLeft * SECONDS_PER_DAY);
     $oDate->toUTC();
     // Test a triple limited campaign with an expiration date 10 days
     // in the future
     $totalImpressions = 1000;
     $totalClicks = 500;
     $totalConversions = 10;
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->views = $totalImpressions;
     $doCampaigns->clicks = $totalClicks;
     $doCampaigns->conversions = $totalConversions;
     $doCampaigns->expire_time = $oDate->getDate(DATE_FORMAT_ISO);
     $aData = array('reportlastdate' => array('2007-04-03 18:39:45'));
     $dg = new DataGenerator();
     $dg->setData('clients', $aData);
     $aCampaignIds = $dg->generate($doCampaigns, 1, true);
     $campaignId = $aCampaignIds[0];
     $campaignExpiration = $GLOBALS['strExpirationDate'] . ": " . $oDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")";
     // Link a banner to this campaign
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $campaignId;
     $doBanners->acls_updated = '2007-04-03 18:39:45';
     $bannerId = DataGenerator::generateOne($doBanners);
     // Insert conversion delivery data occurring today
     $oDate = new Date();
     $impressions = 50;
     $clicks = 5;
     $conversions = 1;
     $doDSAH = OA_Dal::factoryDO('data_intermediate_ad');
     $doDSAH->day = $oDate->format('%Y-%m-%d');
     $doDSAH->hour = 10;
     $doDSAH->ad_id = $bannerId;
     $doDSAH->impressions = $impressions;
     $doDSAH->clicks = $clicks;
     $doDSAH->conversions = $conversions;
     $dsahId = DataGenerator::generateOne($doDSAH);
     // Expiration date is in 10 days
     // Delivered 50 impressions in 1 day. So, expect to take 19 days to
     // deliver remaining 950
     // Delivered 5 clicks in 1 day. So, expect to take 99 days to
     // deliver remaining 495
     // Delivered 1 conversion in 1 day. So, expect to take 9 days to
     // deliver remaining 9
     // The estimated expiration will be calucalated based on impression targets
     // or based on click targets or based on conversion targets (following this order)
     $estimatedDaysLeft = 19;
     $oExpirationDate = new Date();
     $oExpirationDate->copy($oDate);
     $oExpirationDate->addSeconds($estimatedDaysLeft * SECONDS_PER_DAY);
     // The extimated expiration is higher than the expiration set by the user
     // so the value of the extimated expiration will be null because is not a
     // relevant estimation because the campaign will expire before this estimation.
     $expected = array('estimatedExpiration' => '', 'campaignExpiration' => $campaignExpiration);
     $actual = $this->oDalCampaigns->getDaysLeftString($campaignId);
     $this->assertEqual($actual, $expected);
 }
Exemplo n.º 15
0
function create_conference() {
  global $log, $spUser,$_POST,$data; 
  $msgs = array(); 
  // check the title
  if (!$_POST[conference_name] ) { 
    $msgs[] = "Conference must have a title";
    return $msgs  ; 
  } 

  // validate the date ... 
  if (($conference_uts = strtotime($_POST[conference_date]))===false )  { 
    $msgs[] = "Conference date is an Invalid date.";
    return $msgs  ; 
  } 
  list ($m,$d,$y) = split('-',$_POST[conference_date]);

  // Make date objects...
  $confDate = new Date(); 
  $confDate->setMonth($m); 
  $confDate->setYear($y); 
  $confDate->setDay($d); 
  $confDate->setHour(0); 
  $confDate->setMinute(0); 
  $confDate->setSecond(0); 
  $beginTime = $confDate; 
  $endTime = $confDate; 

  list ($beginHour,$beginMinute) = split(':', $_POST[begin_time] ); 
  list ($endHour,$endMinute) = split(':', $_POST[end_time] ); 

  $beginTime->setHour($beginHour); 
  $beginTime->setMinute($beginMinute); 
  $endTime->setHour($endHour); 
  $endTime->setMinute($endMinute); 

  // see if it's the past
  if ($endTime->isPast() ){ 
    $msgs[] = "Conference date is in the Past.";
    return $msgs ; 
  }   

  // Make sure the end time is not less than the begin time
  if (Date::compare($endTime, $beginTime) != 1     ){ 
    $msgs[] = "Start time must be before end time.";
    return $msgs ; 
  }   
  
  // create a new Conference object

  $conference = new Conference($data->db, $spUser->username,$spUser->domain); 

  // get the user's company Id and load the companies constraints
  $conference->getCompanyId(); 
  $conference->loadConstraints() ; 
  // set the date objects.
  $conference->conferenceDate = $confDate; 
  $conference->beginTime = $beginTime; 
  $conference->endTime = $endTime; 
  $conference->conferenceName = $_POST[conference_name] ; 

  // Is the conference too long
  if (!$conference->isMaxTime()) {
    $msgs[] = "Your conference exceeds the maximum amount of minutes.";
    return $msgs  ; 
  } 
  
  // Are there other conferences scheduled for this time.
  if (!$conference->isMaxConcurrent()) {
    $msgs[] = "Your company has other conferences scheduled for this time.";
    return $msgs  ; 
  } 
  $error = "nay!"; 
  if ($conference->create($error) ) { 
    $msgs[] = "Conference created id = " . $conference->conferenceId;
    Header("Location: conference.php?msg=Conference created ") ;
  } else {
    $msgs[] = "Failed to create conference. ";
     $msgs[] = "$error";
  } 
  $owner = new Invitee($data->db, $conference->conferenceId);
  $owner->domain = $spUser->domain;
  $owner->username = $spUser->username;
  $owner->companyId = $conference->companyId; 
  $owner->inviteeEmail = $spUser->dbFields[email_address] ; 
  $owner->ownerFlag =  1; 
  $owner->inviteeName = $spUser->dbFields[first_name] . " " . $spUser->dbFields[last_name] ; 
  // genereate that unique code
  $owner->generateInviteeCode();   
  $owner->create();   
  $owner->sendNotify();   
  
  return $msgs  ; 


}
Exemplo n.º 16
0
function update1_0beta2To1_0beta3()
{
    global $badgerDb;
    $log = '';
    $log .= "&rarr; Adding page settings table.\n";
    $log .= doQuery("CREATE TABLE IF NOT EXISTS `page_settings` (\r\n\t\t`page_name` VARCHAR(255) NOT NULL,\r\n\t\t`setting_name` VARCHAR(255) NOT NULL,\r\n\t\t`setting` TEXT NULL,\r\n\t\tPRIMARY KEY (`page_name`, `setting_name`)\r\n\t\t)", array(-1));
    $log .= "&rarr; Adding new columns to account table.\n";
    $log .= doQuery("ALTER TABLE `account` ADD `last_calc_date` DATE NOT NULL DEFAULT '1000-01-01',\r\n\t\tADD `csv_parser` VARCHAR( 100 ) NULL,\r\n\t\tADD `delete_old_planned_transactions` BOOL NULL", array(-1));
    $log .= "&rarr; Adding new columns to category table.\n";
    $log .= doQuery("ALTER TABLE `category` ADD `keywords` TEXT NULL,\r\n\t\tADD `expense` BOOL NULL", array(-1));
    $log .= "&rarr; Adding new datagrid handler.\n";
    $log .= doQuery("REPLACE datagrid_handler SET handler_name = 'MultipleAccounts', file_path = '/modules/statistics2/MultipleAccounts.class.php', class_name = 'MultipleAccounts'");
    $log .= "&rarr; Adding new columns to finished transaction table.\n";
    $log .= doQuery("ALTER TABLE `finished_transaction` ADD `transferal_transaction_id` INT NULL,\r\n\t\tADD `transferal_source` BOOL NULL", array(-1));
    $log .= "&rarr; Adding new columns to planned transaction table.\n";
    $log .= doQuery("ALTER TABLE `planned_transaction` ADD `transferal_transaction_id` INT NULL,\r\n\t\tADD `transferal_source` BOOL NULL", array(-1));
    $log .= "&rarr; Deleting unused translation entries.\n";
    $log .= doQuery("DELETE FROM i18n WHERE page_id = 'accountCategory' AND id = 'pageTitle'");
    $log .= doQuery("DELETE FROM i18n WHERE page_id = 'csv' AND id = 'title'");
    $log .= doQuery("DELETE FROM i18n WHERE page_id = 'csv' AND id = 'legend'");
    $log .= "&rarr; Adding new translation entries.\n";
    $log .= doQuery("REPLACE i18n SET page_id = 'accountCategory', id = 'pageTitleEdit', en = 'Edit Category', de = 'Kategorie bearbeiten'");
    $log .= doQuery("REPLACE i18n SET page_id = 'dataGrid', id = 'gotoToday', en = 'Today', de = 'Heute'");
    $log .= doQuery("REPLACE i18n SET page_id = 'accountCategory', id = 'pageTitleEdit', en = 'Edit Category', de = 'Kategorie bearbeiten'");
    $log .= doQuery("REPLACE i18n SET page_id = 'importCsv', id = 'legend', en = 'Properties', de = 'Eigenschaften'");
    $log .= doQuery("REPLACE i18n SET page_id = 'dataGrid', id = 'filterLegend', en = 'Filter', de = 'Filter'");
    $log .= doQuery("REPLACE i18n SET page_id = 'dataGrid', id = 'setFilter', en = 'Set Filter', de = 'Filtern'");
    $log .= doQuery("REPLACE i18n SET page_id = 'dataGrid', id = 'resetFilter', en = 'Reset', de = 'Reset'");
    $log .= doQuery("REPLACE i18n SET page_id = 'common', id = 'gpcFieldUndefined', en = 'GET/POST/COOKIE field undefined', de = 'GET/POST/COOKIE-Feld nicht definiert'");
    $log .= doQuery("REPLACE i18n SET page_id = 'accountCategory', id = 'pageTitleNew', en = 'Create new Catagory', de = 'Neue Kategorie erstellen'");
    $log .= doQuery("REPLACE i18n SET page_id = 'DataGridHandler', id = 'illegalFieldSelected', en = 'The following field is not known to this DataGridHandler:', de = 'Das folgende Feld ist diesem DataGridHandler nicht bekannt:'");
    $log .= doQuery("REPLACE i18n SET page_id = 'MultipleAccounts', id = 'invalidFieldName', en = 'An unknown field was used with MultipleAccounts.', de = 'Es wurde ein unbekanntes Feld mit MultipleAccounts verwendet.'");
    $log .= doQuery("REPLACE i18n SET page_id = 'accountAccount', id = 'deleteOldPlannedTransactions', en = 'Auto-insert recurring transactions:', de = 'Wiederkehrende Transaktionen automatisch eintragen:'");
    $log .= doQuery("REPLACE i18n SET page_id = 'accountAccount', id = 'csvParser', en = 'CSV parser:', de = 'CSV-Parser:'");
    $log .= doQuery("REPLACE i18n SET page_id = 'accountAccount', id = 'deleteOldPlannedTransactionsDescription', en = 'If this option is checked, every occuring instance of a recurring transaction is automatically inserted as an single transaction. Uncheck this if you import your transactions from a CSV file on a regular basis.', de = 'Wenn diese Option ausgewählt wurde, werden eintretende Instanzen einer wiederkehrenden Transaktion automatisch als einmalige Transaktionen eingetragen. Wählen Sie die Option nicht aus, wenn Sie Ihre Transaktionen regelmäßig aus einer CSV-Datei importieren.'");
    $log .= doQuery("REPLACE i18n SET page_id = 'accountTransaction', id = 'range', en = 'Apply to', de = 'Anwenden auf'");
    $log .= doQuery("REPLACE i18n SET page_id = 'accountTransaction', id = 'rangeAll', en = 'all', de = 'alle'");
    $log .= doQuery("REPLACE i18n SET page_id = 'accountTransaction', id = 'rangeThis', en = 'this', de = 'diese'");
    $log .= doQuery("REPLACE i18n SET page_id = 'accountTransaction', id = 'rangePrevious', en = 'this and previous', de = 'diese und vorherige'");
    $log .= doQuery("REPLACE i18n SET page_id = 'accountTransaction', id = 'rangeFollowing', en = 'this and following', de = 'diese und folgende'");
    $log .= doQuery("REPLACE i18n SET page_id = 'accountTransaction', id = 'rangeUnit', en = 'instances', de = 'Ausprägungen'");
    $log .= doQuery("REPLACE i18n SET page_id = 'plannedTransaction', id = 'afterTitle', en = 'after', de = 'nach'");
    $log .= doQuery("REPLACE i18n SET page_id = 'plannedTransaction', id = 'beforeTitle', en = 'before', de = 'vor'");
    $log .= doQuery("REPLACE i18n SET page_id = 'AccountManager', id = 'UnknownFinishedTransactionId', en = 'An unknown single transaction id was used.', de = 'Es wurde eine unbekannte ID einer einmaligen Transaktion verwendet.'");
    $log .= doQuery("REPLACE i18n SET page_id = 'AccountManager', id = 'UnknownPlannedTransactionId', en = 'An unknown recurring transaction id was used.', de = 'Es wurde eine unbekannte ID einer wiederkehrenden Transaktion verwendet.'");
    $log .= doQuery("REPLACE i18n SET page_id = 'accountTransaction', id = 'transferalEnabled', en = 'Add transferal transaction', de = 'Gegenbuchung hinzufügen'");
    $log .= doQuery("REPLACE i18n SET page_id = 'accountTransaction', id = 'transferalAccount', en = 'Target account', de = 'Zielkonto'");
    $log .= doQuery("REPLACE i18n SET page_id = 'accountTransaction', id = 'transferalAmount', en = 'Amount on target Account', de = 'Betrag auf Zielkonto'");
    $log .= doQuery("REPLACE i18n SET page_id = 'Account', id = 'FinishedTransferalSourceTransaction', en = 'Source of single transferal transaction', de = 'Quelle einer Einmaligen Gegenbuchung'");
    $log .= doQuery("REPLACE i18n SET page_id = 'Account', id = 'FinishedTransferalTargetTransaction', en = 'Target of single transferal transaction', de = 'Ziel einer Einmaligen Gegenbuchung'");
    $log .= doQuery("REPLACE i18n SET page_id = 'Account', id = 'PlannedTransferalSourceTransaction', en = 'Source of recurring transferal transaction', de = 'Quelle einer Wiederkehrenden Gegenbuchung'");
    $log .= doQuery("REPLACE i18n SET page_id = 'Account', id = 'PlannedTransferalTargetTransaction', en = 'Target of recurring transferal transaction', de = 'Ziel einer Wiederkehrenden Gegenbuchung'");
    $log .= doQuery("REPLACE i18n SET page_id = 'accountCommon', id = 'includeSubCategories', en = '(including sub-categories)', de = '(Unterkategorien eingeschlossen)'");
    $log .= doQuery("REPLACE i18n SET page_id = 'widgetEngine', id = 'noImage', en = 'An image file cannot be found in the current theme or the Standard theme.', de = 'Eine Bilddatei kann weder im aktuellen noch im Standardtheme gefunden werden.'");
    $log .= doQuery("REPLACE i18n SET page_id = 'NavigationFromDB', id = 'noIcon', en = 'An navigation icon cannot be found in the current theme or the Standard theme.', de = 'Ein Navigationsicon kann weder im aktuellen noch im Standardtheme gefunden werden.'");
    $log .= doQuery("REPLACE i18n SET page_id = 'accountCategory', id = 'keywordsLabel', en = 'Keywords', de = 'Schlüsselwörter'");
    $log .= doQuery("REPLACE i18n SET page_id = 'accountCategory', id = 'keywordsDescription', en = 'If an imported transaction contains one of these keywords, this category will be pre-selected for this transaction. Use one line per keyword.', de = 'Wenn eine importierte Transaktion eines dieser Schlüsselwörter enthält, wird diese Kategorie vor-ausgewählt. Geben Sie pro Schlüsselwort eine neue Zeile ein.'");
    $log .= doQuery("REPLACE i18n SET page_id = 'UserSettingsAdmin', id = 'matchingDateDeltaLabel', en = 'Max. difference in days:', de = 'Max. Differenz in Tagen'");
    $log .= doQuery("REPLACE i18n SET page_id = 'UserSettingsAdmin', id = 'matchingDateDeltaDescription', en = 'Only transactions that differ at most this amount of days from the imported transaction are considered for comparison.', de = 'Nur Transaktionen, die maximal diese Anzahl an Tagen von der importierten Transaktion abweichen, werden zum Vergleich herangezogen.'");
    $log .= doQuery("REPLACE i18n SET page_id = 'UserSettingsAdmin', id = 'matchingAmountDeltaLabel', en = 'Max. difference of amount (%)', de = 'Max. Abweichung des Betrags (%)'");
    $log .= doQuery("REPLACE i18n SET page_id = 'UserSettingsAdmin', id = 'matchingAmountDeltaDescription', en = 'Only transactions that differ at most this percentage in amount from the imported transaction are considered for comparison.', de = 'Nur Transaktionen, deren Betrag maximal diesen Prozentsatz von der importierten Transaktion abweichen, werden zum Vergleich herangezogen.'");
    $log .= doQuery("REPLACE i18n SET page_id = 'UserSettingsAdmin', id = 'matchingTextSimilarityLabel', en = 'Min. text similarity (%)', de = 'Mind. Textähnlichkeit (%)'");
    $log .= doQuery("REPLACE i18n SET page_id = 'UserSettingsAdmin', id = 'matchingTextSimilarityDescription', en = 'Only transactions that are similar to the imported transaction by this percentage are considered for comparison.', de = 'Nur Transaktionen, die mindestens diesen Prozentsatz an Ähnlichkeit zur importierten Transaktion aufweisen, werden zum Vergleich herangezogen.'");
    $log .= doQuery("REPLACE i18n SET page_id = 'UserSettingsAdmin', id = 'matchingHeading', en = 'CSV Import Matching', de = 'Abgleich beim CSV-Import'");
    $log .= doQuery("REPLACE i18n SET page_id = 'importCsv', id = 'matchingHeader', en = 'Similar Transactions', de = 'Ähnliche Transaktionen'");
    $log .= doQuery("REPLACE i18n SET page_id = 'importCsv', id = 'matchingToolTip', en = 'If you choose a transaction here, it will be replaced by the imported data.', de = 'Wenn Sie hier eine Transaktion auswählen, wird sie durch die importierten Daten ersetzt.'");
    $log .= doQuery("REPLACE i18n SET page_id = 'importCsv', id = 'dontMatchTransaction', en = '&lt;Import as new&gt;', de = '&lt;Neu importieren&gt;'");
    $log .= doQuery("REPLACE i18n SET page_id = 'importCsv', id = 'descriptionFieldImportedPartner', en = 'Imported transaction partner: ', de = 'Importierter Transaktionspartner: '");
    $log .= doQuery("REPLACE i18n SET page_id = 'importCsv', id = 'descriptionFieldOrigValutaDate', en = 'Original valuta date: ', de = 'Original-Buchungsdatum: '");
    $log .= doQuery("REPLACE i18n SET page_id = 'importCsv', id = 'descriptionFieldOrigAmount', en = 'Original amount: ', de = 'Original-Betrag: '");
    $log .= doQuery("REPLACE i18n SET page_id = 'accountOverview', id = 'colBalance', en = 'Balance', de = 'Kontostand'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'colAccountName', en = 'Account', de = 'Konto'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'pageTitle', en = 'Advanced Statistics', de = 'Erweiterte Statistik'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'titleFilter', en = 'Title is ', de = 'Titel ist '");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'descriptionFilter', en = 'Description is ', de = 'Beschreibung ist '");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'valutaDateFilter', en = 'Valuta date is ', de = 'Buchungsdatum ist '");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'valutaDateBetweenFilter', en = 'Valuta date is between ', de = 'Buchungsdatum ist zwischen '");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'valutaDateBetweenFilterConj', en = ' and ', de = ' und '");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'valutaDateBetweenFilterInclusive', en = ' (both inclusive)', de = ' (beide inklusive)'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'valutaDateAgoFilter', en = 'Valuta within the last ', de = 'Buchungsdatum innerhalb der letzten '");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'valutaDateAgoFilterDaysAgo', en = ' days', de = ' Tage'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'amountFilter', en = 'Amount is ', de = 'Betrag ist '");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'outsideCapitalFilter', en = 'Source is ', de = 'Quelle ist '");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'outsideCapitalFilterOutside', en = 'outside capital', de = 'Fremdkapital'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'outsideCapitalFilterInside', en = 'inside capital', de = 'Eigenkapital'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'transactionPartnerFilter', en = 'Transaction partner is ', de = 'Transaktionspartner ist '");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'categoryFilter', en = 'Category ', de = 'Kategorie '");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'categoryFilterIs', en = 'is', de = 'ist'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'categoryFilterIsNot', en = 'is not', de = 'ist nicht'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'exceptionalFilter', en = 'Transaction is ', de = 'Transaktion ist '");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'exceptionalFilterExceptional', en = 'exceptional', de = 'außergewöhnlich'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'exceptionalFilterNotExceptional', en = 'not exceptional', de = 'nicht außergewöhnlich'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'periodicalFilter', en = 'Transaction is ', de = 'Transaktion ist '");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'periodicalFilterPeriodical', en = 'periodical', de = 'regelmäßig'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'periodicalFilterNotPeriodical', en = 'not periodical', de = 'unregelmäßig'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'availableFiltersUnselected', en = 'Please choose a filter', de = 'Bitte wählen Sie einen Filter'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'availableFiltersTitle', en = 'Title', de = 'Titel'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'availableFiltersDescription', en = 'Description', de = 'Beschreibung'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'availableFiltersValutaDate', en = 'Valuta date', de = 'Buchungsdatum'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'availableFiltersValutaDateBetween', en = 'Valuta date between', de = 'Buchungsdatum zwischen'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'availableFiltersValutaDateAgo', en = 'Valuta date last days', de = 'Buchungsdatum vergangene Tage'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'availableFiltersAmount', en = 'Amount', de = 'Betrag'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'availableFiltersOutsideCapital', en = 'Outside capital', de = 'Fremdkapital'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'availableFiltersTransactionPartner', en = 'Transaction partner', de = 'Transaktionspartner'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'availableFiltersCategory', en = 'Category', de = 'Kategorie'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'availableFiltersExceptional', en = 'Exceptional', de = 'Außergewöhnlich'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'availableFiltersPeriodical', en = 'Periodical', de = 'Regelmäßig'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'availableFiltersDelete', en = '&lt;Delete Filter&gt;', de = '&lt;Filter löschen&gt;'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'filterCaption', en = 'Filters', de = 'Filter'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'twistieCaptionInput', en = 'Input Values', de = 'Eingabewerte'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'outputSelectionTrendStartValue', en = 'Start Value', de = 'Startwert'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'outputSelectionTrendStartValueZero', en = '0 (zero)', de = '0 (null)'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'outputSelectionTrendStartValueBalance', en = 'Account Balance', de = 'Kontostand'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'outputSelectionTrendTickLabels', en = 'Tick labels', de = 'Tickmarken'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'outputSelectionTrendTickLabelsShow', en = 'Show', de = 'Anzeigen'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'outputSelectionTrendTickLabelsHide', en = 'Hide', de = 'Verbergen'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'outputSelectionCategoryType', en = 'Category Type', de = 'Kategorietyp'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'outputSelectionCategoryTypeInput', en = 'Income', de = 'Einnahmen'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'outputSelectionCategoryTypeOutput', en = 'Spending', de = 'Ausgaben'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'outputSelectionCategorySubCategories', en = 'Sub-Categories', de = 'Unterkategorien'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'outputSelectionCategorySubCategoriesSummarize', en = 'Summarize sub-categories', de = 'Unterkategorien zusammenfassen'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'outputSelectionCategorySubCategoriesNoSummarize', en = 'Do not summarize sub-categories', de = 'Unterkategorien einzeln aufführen'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'outputSelectionTimespanType', en = 'Type', de = 'Typ'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'outputSelectionTimespanTypeWeek', en = 'Week', de = 'Woche'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'outputSelectionTimespanTypeMonth', en = 'Month', de = 'Monat'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'outputSelectionTimespanTypeQuarter', en = 'Quarter', de = 'Quartal'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'outputSelectionTimespanTypeYear', en = 'Year', de = 'Jahr'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'outputSelectionGraphType', en = 'Graph Type', de = 'Graphtyp'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'outputSelectionGraphTypeTrend', en = 'Trend', de = 'Verlauf'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'outputSelectionGraphTypeCategory', en = 'Category', de = 'Kategorie'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'outputSelectionGraphTypeTimespan', en = 'Timespan', de = 'Zeitvergleich'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'twistieCaptionOutputSelection', en = 'Output Selection', de = 'Ausgabeauswahl'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'analyzeButton', en = 'Analyse', de = 'Analysieren'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'twistieCaptionGraph', en = 'Graph', de = 'Graph'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'twistieCaptionOutput', en = 'Output', de = 'Ausgabe'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'addFilterButton', en = 'Add Filter', de = 'Filter hinzufügen'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2Graph', id = 'noMatchingTransactions', en = 'No transactions match your criteria.', de = 'Keine Transaktionen entsprechen Ihren Kriterien.'");
    $log .= doQuery("REPLACE i18n SET page_id = 'dataGridFilter', id = 'beginsWith', en = 'begins with', de = 'fängt an mit'");
    $log .= doQuery("REPLACE i18n SET page_id = 'dataGridFilter', id = 'endsWith', en = 'ends with', de = 'hört auf mit'");
    $log .= doQuery("REPLACE i18n SET page_id = 'dataGridFilter', id = 'contains', en = 'contains', de = 'enthält'");
    $log .= doQuery("REPLACE i18n SET page_id = 'dataGridFilter', id = 'dateEqualTo', en = 'equal to', de = 'gleich'");
    $log .= doQuery("REPLACE i18n SET page_id = 'dataGridFilter', id = 'dateBefore', en = 'before', de = 'vor'");
    $log .= doQuery("REPLACE i18n SET page_id = 'dataGridFilter', id = 'dateBeforeEqual', en = 'before or equal to', de = 'vor oder gleich'");
    $log .= doQuery("REPLACE i18n SET page_id = 'dataGridFilter', id = 'dateAfter', en = 'after', de = 'nach'");
    $log .= doQuery("REPLACE i18n SET page_id = 'dataGridFilter', id = 'dateAfterEqual', en = 'after or equal to', de = 'nach oder gleich'");
    $log .= doQuery("REPLACE i18n SET page_id = 'dataGridFilter', id = 'dateNotEqual', en = 'not equal to', de = 'ungleich'");
    $log .= doQuery("REPLACE i18n SET page_id = 'Navigation', id = 'Statistics2', en = 'Advanced Statistics', de = 'Erweiterte Statistik'");
    $log .= doQuery("REPLACE i18n SET page_id = 'accountAccount', id = 'csvNoParser', en = '&lt;No parser&gt;', de = '&lt;Kein Parser&gt;'");
    $log .= doQuery("REPLACE i18n SET page_id = 'PageSettings', id = 'SQLError', en = 'An SQL error occured attempting to fetch the PageSettings data from the database.', de = 'Beim Abrufen der PageSettings-Daten aus der Datenbank trat ein SQL-Fehler auf.'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'pageSettingSave', en = 'Save Settings', de = 'Einstellungen speichern'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'pageSettingDelete', en = 'Delete Setting', de = 'Einstellung löschen'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'pageSettingsTwistieTitle', en = 'Settings', de = 'Einstellungen'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'pageSettingNewNamePrompt', en = 'Please enter the name for the setting:', de = 'Bitte geben Sie den Namen für die Einstellung ein:'");
    $log .= doQuery("REPLACE i18n SET page_id = 'accountCategory', id = 'expenseRowLabel', en = 'Standard direction:', de = 'Standardgeldfluss:'");
    $log .= doQuery("REPLACE i18n SET page_id = 'accountCategory', id = 'expenseIncome', en = 'Income', de = 'Einnahme'");
    $log .= doQuery("REPLACE i18n SET page_id = 'accountCategory', id = 'expenseExpense', en = 'Expense', de = 'Ausgabe'");
    $log .= doQuery("REPLACE i18n SET page_id = 'accountTransaction', id = 'categoryExpenseWarning', en = 'The selected category is marked as expense, but your amount is positive.', de = 'Die ausgewählte Kategorie ist als Ausgabe markiert, jedoch ist Ihr Betrag positiv.'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2', id = 'miscCategories', en = '(Miscellaneous)', de = '(Verbleibende)'");
    $log .= doQuery("REPLACE i18n SET page_id = 'importCsv', id = 'uploadTitle', en = 'File Uploaded and Analyzed', de = 'Datei hochgeladen und analysiert'");
    $log .= doQuery("REPLACE i18n SET page_id = 'importCsv', id = 'submitTitle', en = 'CSV Data Imported', de = 'CSV-Daten importiert'");
    $log .= doQuery("REPLACE i18n SET page_id = 'importCsv', id = 'pageHeading', en = 'CSV Import', de = 'CSV-Import'");
    $log .= doQuery("REPLACE i18n SET page_id = 'Account', id = 'textday', en = 'day', de = 'Tag'");
    $log .= doQuery("REPLACE i18n SET page_id = 'Account', id = 'textmonth', en = 'month', de = 'Monat'");
    $log .= doQuery("REPLACE i18n SET page_id = 'Account', id = 'textweek', en = 'week', de = 'Woche'");
    $log .= doQuery("REPLACE i18n SET page_id = 'Account', id = 'textyear', en = 'year', de = 'Jahr'");
    $log .= doQuery("REPLACE i18n SET page_id = 'Account', id = 'unknownOrdinalisationLanguage', en = 'An unknown language was passed to Account::ordinal().', de = 'An Account::ordinal wurde eine unbekannte Sprache übergeben.'");
    $log .= doQuery("REPLACE i18n SET page_id = 'accountOverviewPlanned', id = 'colRepeatText', en = 'Repetition', de = 'Wiederholung'");
    $log .= doQuery("REPLACE i18n SET page_id = 'statistics2Graph', id = 'only1transaction', en = 'Your criteria resulted in only one transaction, of which no line graph can be drawn.', de = 'Ihre Kriterien ergaben nur eine Transaktion, woraus kein Liniendiagramm gezeichnet werden kann.'");
    $log .= doQuery("REPLACE i18n SET page_id = 'dataGridFilter', id = 'stringEqualTo', en = 'equals', de = 'gleich'");
    $log .= doQuery("REPLACE i18n SET page_id = 'dataGridFilter', id = 'stringNotEqual', en = 'not equal', de = 'ungleich'");
    $log .= "&rarr; Changing translation entries.\n";
    $log .= doQuery("REPLACE i18n SET page_id = 'importCsv', id = 'successfullyWritten', en = 'transaction(s) successfully written to the following accounts:', de = 'Transaktion(en) erfolgreich in die folgenden Konten geschrieben:'");
    $log .= doQuery("REPLACE i18n SET page_id = 'importCsv', id = 'noTransactionSelected', en = 'No transactions selected.', de = 'Keine Transaktionen ausgewählt.'");
    $log .= doQuery("REPLACE i18n SET page_id = 'accountCategory', id = 'pageTitleOverview', en = 'Transaction Categories', de = 'Transaktionskategorien'");
    $log .= doQuery("REPLACE i18n SET page_id = 'accountAccount', id = 'pageTitleOverview', en = 'Account Overview', de = 'Kontenübersicht'");
    $log .= doQuery("REPLACE i18n SET page_id = 'CategoryManager', id = 'no_parent', en = '&lt;No parent category&gt;', de = '&lt;Keine Elternkategorie&gt;'");
    $log .= doQuery("REPLACE i18n SET page_id = 'dataGrid', id = 'NoRowSelectedMsg', en = 'Please, select a row to edit', de = 'Bitte selektieren sie eine Zeile, die sie bearbeiten wollen.'");
    $sql = "SELECT count(navi_id) FROM navi WHERE item_name = 'Statistics2'";
    $result =& $badgerDb->query($sql);
    $arr = array();
    $result->fetchInto($arr, DB_FETCHMODE_ORDERED);
    if ($arr[0] == 0) {
        $log .= "&rarr; Inserting new menu entry for advanced statistics.\n";
        $log .= doQuery("SELECT @max_navi_id := max(navi_id) FROM navi;");
        $log .= doQuery("INSERT INTO navi(navi_id, parent_id, menu_order, item_type, item_name, tooltip, icon_url, command) VALUES (@max_navi_id + 1, 30, 5, 'i', 'Statistics2', '', 'statistics.gif', '{BADGER_ROOT}/modules/statistics2/statistics2.php')");
        $log .= "&rarr; Updating max id to navigation sequence table.\n";
        $log .= doQuery("UPDATE navi_ids_seq SET id = ((SELECT MAX(navi_id) FROM navi) + 1)");
        $log .= "&rarr; Updating menu order of forecast.\n";
        $log .= doQuery("UPDATE navi SET menu_order = 6 WHERE item_name = 'Forecast'");
    }
    $log .= "&rarr; Applying new recurring transaction mode.\n";
    $accountManager = new AccountManager($badgerDb);
    $now = new Date();
    $now->setHour(0);
    $now->setMinute(0);
    $now->setSecond(0);
    while ($currentAccount = $accountManager->getNextAccount()) {
        $currentAccount->expandPlannedTransactions($now);
    }
    $log .= "&rarr; Updating database version to 1.0 beta 3.\n";
    $log .= doQuery("REPLACE user_settings SET prop_key = 'badgerDbVersion', prop_value = 's:10:\"1.0 beta 3\";'");
    $log .= "\n&rarr;&rarr; Update to version 1.0 beta 3 finished. &larr;&larr;\n\n";
    return $log;
}
Exemplo n.º 17
0
 /**
  * A method to check if the campaign is expired
  *
  * @return bool
  */
 function _isExpired()
 {
     static $oServiceLocator;
     // MySQL null date hardcoded for optimisation
     if (!empty($this->expire) && $this->expire != '0000-00-00') {
         if (!isset($oServiceLocator)) {
             $oServiceLocator =& OA_ServiceLocator::instance();
         }
         if (!($oNow = $oServiceLocator->get('now'))) {
             $oNow = new Date();
         }
         $oExpire = new Date($this->expire);
         $oExpire->setHour(23);
         $oExpire->setMinute(59);
         $oExpire->setSecond(59);
         if (!empty($this->clientid)) {
             // Set timezone
             $aAccounts = $this->getOwningAccountIds();
             $aPrefs = OA_Preferences::loadAccountPreferences($aAccounts[OA_ACCOUNT_ADVERTISER], true);
             if (isset($aPrefs['timezone'])) {
                 $oExpire->setTZbyID($aPrefs['timezone']);
             }
         }
         if ($oNow->after($oExpire)) {
             return true;
         }
     }
     return false;
 }
 /**
  * A method to distribute the calculated required campaign impressions between the campaign's
  * children advertisements. Impression allocation takes in to account ad weight, and the number
  * of operations intervals the ad will be active in given date/time delivery limitations, and
  * the pattern of available impressions for the zone(s) the advertisements are linked to.
  *
  * The calculated ad impressions are written to the temporary table tmp_ad_required_impression
  * for later analysis by the {@link OA_Maintenance_Priority_AdServer_Task_AllocateZoneImpressions}
  * class.
  *
  * @param array $aCampaigns An array of {@link OX_Maintenance_Priority_Campaign} objects which require
  *                          that their total required impressions be distributed between the
  *                          component advertisements.
  */
 function distributeCampaignImpressions($aCampaigns)
 {
     // Create an array for storing required ad impressions
     $aRequiredAdImpressions = array();
     // Get the current operation interval start/end dates
     $aCurrentOperationIntervalDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($this->_getDate());
     // For each campaign
     foreach ($aCampaigns as $oCampaign) {
         OA::debug('  - Distributing impression inventory requirements for campaign ID: ' . $oCampaign->id, PEAR_LOG_DEBUG);
         $adsCount = count($oCampaign->aAds);
         OA::debug("    - Campaign has {$adsCount} ads.", PEAR_LOG_DEBUG);
         // Get date object to represent campaign expiration date
         if ($oCampaign->impressionTargetDaily > 0 || $oCampaign->clickTargetDaily > 0 || $oCampaign->conversionTargetDaily > 0) {
             // The campaign has a daily target to meet, so treat the
             // campaign as if it expires at the end of "today", regardless
             // of the existance of any activation or expiration dates that
             // may (or may not) be set for the campaign
             $oCampaignExpiryDate = new Date($this->_getDate());
             $oCampaignExpiryDate->setTZ($this->currentTz);
             $oCampaignExpiryDate->setHour(23);
             $oCampaignExpiryDate->setMinute(59);
             $oCampaignExpiryDate->setSecond(59);
             $oCampaignExpiryDate->toUTC();
             // Unless the campaign has an expiry date and it happens before the end of today
             if (!empty($oCampaign->expireTime)) {
                 if ($oCampaignExpiryDate->after($this->_getDate($oCampaign->expireTime))) {
                     $oCampaignExpiryDate = $this->_getDate($oCampaign->expireTime);
                 }
             }
         } else {
             if (!empty($oCampaign->expireTime) && ($oCampaign->impressionTargetTotal > 0 || $oCampaign->clickTargetTotal > 0 || $oCampaign->conversionTargetTotal > 0)) {
                 // The campaign has an expiration date, and has some kind of
                 // (total) inventory requirement, so treat the campaign as if
                 // it expires at the expiration date/time
                 $oCampaignExpiryDate = $this->_getDate($oCampaign->expireTime);
             } else {
                 // Error! There should not be any other kind of high-priority
                 // campaign in terms of activation/expiration dates and
                 // either (total) inventory requirements or daily targets
                 $message = "- Error calculating the end date for Campaign ID {$oCampaign->id}";
                 OA::debug($message, PEAR_LOG_ERR);
                 continue;
             }
         }
         // Determine number of remaining operation intervals for campaign
         $message = "    - Calculating campaign remaining operation intervals.";
         OA::debug($message, PEAR_LOG_DEBUG);
         $campaignRemainingOperationIntervals = OX_OperationInterval::getIntervalsRemaining($aCurrentOperationIntervalDates['start'], $oCampaignExpiryDate);
         // For all ads in the campaign, determine:
         // - If the ad is capable of delivery in the current operation
         //   interval, or not, based on if it is linked to any zones, and,
         //   if so:
         // - If the ad is capable of delivery in the current operation
         //   interval, or not, based on delivery limitation(s), and if so;
         // - The result of the weight of the ad multiplied by the
         //   number of operation intervals remaining in which the ad
         //   is capable of delivering
         $aAdZones = array();
         $aAdDeliveryLimitations = array();
         $aAdBlockedForCurrentOI = array();
         $aAdWeightRemainingOperationIntervals = array();
         $aInvalidAdIds = array();
         reset($oCampaign->aAds);
         while (list($key, $oAd) = each($oCampaign->aAds)) {
             // Only calculate values for active ads
             if ($oAd->active && $oAd->weight > 0) {
                 $message = "    - Calculating remaining operation intervals for ad ID: {$oAd->id}";
                 OA::debug($message, PEAR_LOG_DEBUG);
                 // Get all zones associated with the ad
                 $aAdsZones = $this->oDal->getAdZoneAssociationsByAds(array($oAd->id));
                 $aAdZones[$oAd->id] = @$aAdsZones[$oAd->id];
                 if (is_null($aAdZones[$oAd->id])) {
                     $aInvalidAdIds[] = $oAd->id;
                     $message = "      - Ad ID {$oAd->id} has no linked zones, will skip...";
                     OA::debug($message, PEAR_LOG_ERR);
                     continue;
                 }
                 // Prepare a delivery limitation object for the ad
                 $aAdDeliveryLimitations[$oAd->id] = new OA_Maintenance_Priority_DeliveryLimitation($oAd->getDeliveryLimitations());
                 // Is the ad blocked from delivering in the current operation interval?
                 $aAdBlockedForCurrentOI[$oAd->id] = $aAdDeliveryLimitations[$oAd->id]->deliveryBlocked($aCurrentOperationIntervalDates['start']);
                 // Determine how many operation intervals remain that the ad can deliver in
                 $adRemainingOperationIntervals = $aAdDeliveryLimitations[$oAd->id]->getActiveAdOperationIntervals($campaignRemainingOperationIntervals, $aCurrentOperationIntervalDates['start'], $oCampaignExpiryDate);
                 // Determine the value of the ad weight multiplied by the number
                 // of operation intervals remaining that the ad can deliver in
                 if ($oAd->weight > 0) {
                     $aAdWeightRemainingOperationIntervals[$oAd->id] = $oAd->weight * $adRemainingOperationIntervals;
                 } else {
                     $aAdWeightRemainingOperationIntervals[$oAd->id] = 0;
                 }
             }
         }
         // Get the total sum of the ad weight * remaining OI values
         $sumAdWeightRemainingOperationIntervals = array_sum($aAdWeightRemainingOperationIntervals);
         // For each (active) ad that is capable of delivering in the current
         // operation interval, determine how many of the campaign's required
         // impressions should be alloced as the ad's required impressions
         // For each advertisement
         reset($oCampaign->aAds);
         while (list($key, $oAd) = each($oCampaign->aAds)) {
             if (in_array($oAd->id, $aInvalidAdIds)) {
                 OA::debug('       - Skipping ad ID: ' . $oAd->id, PEAR_LOG_DEBUG);
                 continue;
             }
             OA::debug('     - Calculating required impressions for ad ID: ' . $oAd->id, PEAR_LOG_DEBUG);
             // Get impressions required
             $totalRequiredAdImpressions = 0;
             if ($oAd->active && $oAd->weight > 0 && $aAdBlockedForCurrentOI[$oAd->id] !== true) {
                 $totalRequiredAdImpressions = $oCampaign->requiredImpressions * ($aAdWeightRemainingOperationIntervals[$oAd->id] / $sumAdWeightRemainingOperationIntervals);
             }
             if ($totalRequiredAdImpressions <= 0) {
                 OA::debug('       - No required impressions for ad ID: ' . $oAd->id, PEAR_LOG_DEBUG);
                 continue;
             }
             // Based on the average zone pattern of the zones the ad is
             // linked to, calculate how many of these impressions should
             // be delivered in the next operation interval
             OA::debug('       - Calculating next OI required impressions for ad ID: ' . $oAd->id, PEAR_LOG_DEBUG);
             $oAd->requiredImpressions = $this->_getAdImpressions($oAd, $totalRequiredAdImpressions, $aCurrentOperationIntervalDates['start'], $oCampaignExpiryDate, $aAdDeliveryLimitations[$oAd->id], $aAdZones[$oAd->id]);
             $aRequiredAdImpressions[] = array('ad_id' => $oAd->id, 'required_impressions' => $oAd->requiredImpressions);
         }
     }
     // Save the required impressions into the temporary database table
     OA::setTempDebugPrefix('- ');
     // Check if table exists
     if (!isset($GLOBALS['_OA']['DB_TABLES']['tmp_ad_required_impression'])) {
         if ($this->oTable->createTable('tmp_ad_required_impression', null, true) !== false) {
             // Remember that table was created
             $GLOBALS['_OA']['DB_TABLES']['tmp_ad_required_impression'] = true;
         }
     }
     $this->oDal->saveRequiredAdImpressions($aRequiredAdImpressions);
 }
Exemplo n.º 19
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;
 }
Exemplo n.º 20
0
 /**
  * A method for obtaining the targeting statistics of an ad or placement
  * for a single day, where the data is summarised by operation interval.
  *
  * @param integer    $id    The ad or placement ID.
  * @param string     $type  Either "ad" or "placement".
  * @param PEAR::Date $oDate A date representing the day required.
  *
  * @return mixed Returns false in the event of incorrect input, or in the case
  *               of being unable to connect to the database, otherwise, returns
  *               an array of arrays:
  *
  *
  * array(
  *     [$operationIntervalId] => array(
  *                                  ['interval_start']             => PEAR::Date
  *                                  ['interval_end']               => PEAR::Date
  *                                  ['ad_required_impressions']    => integer
  *                                  ['ad_requested_impressions']   => integer
  *                                  ['ad_actual_impressions']      => integer
  *                                  ['zones_forecast_impressions'] => integer
  *                                  ['zones_actual_impressions']   => integer
  *                                  ['average']                    => integer
  *                               )
  *      .
  *      .
  *      .
  * )
  *
  * or:
  *
  * array(
  *     [$operationIntervalId] => array(
  *                                  ['interval_start']                  => PEAR::Date
  *                                  ['interval_end']                    => PEAR::Date
  *                                  ['placement_required_impressions']  => integer
  *                                  ['placement_requested_impressions'] => integer
  *                                  ['placement_actual_impressions']    => integer
  *                                  ['zones_forecast_impressions']      => integer
  *                                  ['zones_actual_impressions']        => integer
  *                                  ['average']                         => integer
  *                               )
  *      .
  *      .
  *      .
  * )
  *
  * For the ad or placement and day specified, returns an array for each
  * operation interval in the day, consisting of the operation interval start
  * and end dates, and the total number of impressions requested by the ad, or
  * all ads in the placement (for all zones the ads are linked to), as well as
  * the total number of impressions actually delivered by the ad, or all ads
  * in the placement (for all zones the ads are linked to).
  *
  * The individual ad/zone impressions requested values may need to be
  * calculated as an "averge" value, in the event that there are multiple,
  * differing values for an ad in a zone for an operation interval -- in
  * much the same way as is done in
  * OA_Dal_Maintenance_Priority::getPreviousAdDeliveryInfo() -- before
  * the total impressions requested value can be calculated.
  */
 function getDailyTargetingStatistics($id, $type, $oDate)
 {
     if (!$this->_testGetTargetingStatisticsDayParameters($id, $type, $oDate)) {
         return false;
     }
     // Ensure that, if a placement, the placement has advertisements
     $aAdIds = $this->_testGetTargetingStatisticsSpanPlacement($id, $type);
     if ($aAdIds === false) {
         return false;
     }
     // Prepare the results array
     $aResult = array();
     // Get a date for the start of the day
     $oStartDate = new Date();
     $oStartDate->copy($oDate);
     $oStartDate->setHour(0);
     $oStartDate->setMinute(0);
     $oStartDate->setSecond(0);
     // Get a date for the end of the day
     $oEndOfDayDate = new Date();
     $oEndOfDayDate->copy($oDate);
     $oEndOfDayDate->setHour(23);
     $oEndOfDayDate->setMinute(59);
     $oEndOfDayDate->setSecond(59);
     // Get the first operation interval of the day
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oStartDate);
     // Get dates to be used in date comparisons
     $oCompareDate = new Date();
     $oCompareDate->copy($aDates['start']);
     $oCompareEndDate = new Date();
     $oCompareEndDate->copy($oEndOfDayDate);
     while ($oCompareDate->before($oEndOfDayDate)) {
         // Get the operation interval ID
         $operationIntervalId = OX_OperationInterval::convertDateToOperationIntervalID($aDates['start']);
         // Get the results for this operation interval
         $aResult[$operationIntervalId] = $this->getOperationIntervalTargetingStatistics($aAdIds, $type, $aDates['start'], $aDates['end']);
         if ($aResult[$operationIntervalId] === false) {
             return false;
         }
         // Get the next operation interval dates
         $aDates = OX_OperationInterval::convertDateToNextOperationIntervalStartAndEndDates($aDates['start']);
         // Update the comparison dates
         $oCompareDate = new Date();
         $oCompareDate->copy($aDates['start']);
         $oCompareEndDate = new Date();
         $oCompareEndDate->copy($oEndOfDayDate);
     }
     return $aResult;
 }
Exemplo n.º 21
0
 /**
  * A method to determine if the delivery limitation stored will prevent an
  * ad from delivering or not, given a time/date.
  *
  * @abstract
  * @param object $oDate PEAR:Date, represeting the time/date to test if the ACL would
  *                      block delivery at that point in time.
  * @return mixed A boolean (true if the ad is BLOCKED (i.e. will NOT deliver), false
  *               if the ad is NOT BLOCKED (i.e. WILL deliver), or a PEAR::Error.
  */
 function deliveryBlocked($oDate)
 {
     if (!is_a($oDate, 'Date')) {
         return MAX::raiseError('Parameter passed to OA_Maintenance_Priority_DeliveryLimitation_Date is not a PEAR::Date object', MAX_ERROR_INVALIDARGS);
     }
     // Clone the date
     $oCloneDate = new Date();
     $oCloneDate->copy($oDate);
     // Reset time part of date
     $oCloneDate->setHour(0);
     $oCloneDate->setMinute(0);
     $oCloneDate->setSecond(0);
     //  0 if the dates are equal;
     // -1 if $oCloneDate is before $this->date;
     //  1 if $oCloneDate is after $this->date
     $val = Date::compare($oCloneDate, $this->date);
     switch ($this->comparison) {
         case '==':
             return $val == 0;
             break;
         case '!=':
             return $val != 0;
             break;
         case '<=':
             return $val == -1 || $val == 0;
             break;
         case '>=':
             return $val == 1 || $val == 0;
             break;
         case '<':
             return $val == -1;
             break;
         case '>':
             return $val == 1;
             break;
     }
     return 0;
 }
Exemplo n.º 22
0
 function convertStartEndDate(&$oStartDate, &$oEndDate, $oTimezone)
 {
     if (isset($oStartDate)) {
         $oStartTz = new Date($oStartDate);
         $oStartTz->convertTZ($oTimezone);
         $oStartTz->setHour(0);
         $oStartTz->setMinute(0);
         $oStartTz->setSecond(0);
         if ($oStartTz->after($oStartDate)) {
             $oStartTz->subtractSpan(new Date_Span('1-0-0-0'));
         }
     } else {
         $oStartTz = null;
     }
     if (!isset($oEndDate)) {
         $oEndDate = new Date();
     }
     $oEndTz = new Date($oEndDate);
     $oEndTz->convertTZ($oTimezone);
     $oEndTz->setHour(0);
     $oEndTz->setMinute(0);
     $oEndTz->setSecond(0);
     $oEndTz->subtractSeconds(1);
     if ($oEndTz->after($oEndDate)) {
         $oEndTz->subtractSpan(new Date_Span('1-0-0-0'));
     }
     $oStartDate = $oStartTz;
     $oEndDate = $oEndTz;
 }
Exemplo n.º 23
0
 /**
  * A method to get the hourly revenuo of a monthly tenancy campaign
  *
  * Monthly tenancy calculation sponsored by www.admost.nl
  *
  * @param array $aInfo The finance information, as returned by _saveSummaryGetAdFinanceInfo
  * @param Date $oStartDate
  * @param Date $oEndDate
  * @param string $table
  * @return double
  */
 function getMtRevenue($aInfo, $oStartDate, $oEndDate, $table)
 {
     OA::debug(sprintf("  - Calculating MT revenue for banner [id%d] between %s and %s:", $aInfo['ad_id'], $oStartDate->format('%Y-%m-%d %H:%M:%S %Z'), $oEndDate->format('%Y-%m-%d %H:%M:%S %Z')), PEAR_LOG_DEBUG);
     $aConf = $GLOBALS['_MAX']['CONF'];
     $oMonthStart = new Date($oStartDate);
     // Set timezone
     if (!empty($aInfo['advertiser_id'])) {
         $doClient = OA_Dal::staticGetDO('clients', $aInfo['advertiser_id']);
         $aAdvertiserPrefs = OA_Preferences::loadAccountPreferences($doClient->account_id, true);
         if (!empty($aAdvertiserPrefs['timezone'])) {
             $oMonthStart->convertTZbyID($aAdvertiserPrefs['timezone']);
         }
     }
     // Get ad/zone combinations for the campaign
     if (!isset($this->aMtRevenueCache[$aInfo['campaign_id']])) {
         $query = "\n                SELECT\n                    COUNT(*) as cnt\n                FROM\n                    " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table'][$table], true) . " d JOIN\n                    " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['banners'], true) . " a ON (a.bannerid = d.ad_id)\n                WHERE\n                    a.campaignid = {$aInfo['campaign_id']}\n                    AND d.date_time >= " . $this->oDbh->quote($oStartDate->format('%Y-%m-%d %H:%M:%S'), 'timestamp') . "\n                    AND d.date_time <= " . $this->oDbh->quote($oEndDate->format('%Y-%m-%d %H:%M:%S'), 'timestamp');
         $this->aMtRevenueCache[$aInfo['campaign_id']] = $this->oDbh->query($query)->fetchOne();
     }
     $oMonthStart->setDay(1);
     $oMonthStart->setHour(0);
     $oMonthStart->setMinute(0);
     $oMonthStart->setSecond(0);
     OA::debug(sprintf("    - Month start: %s", $oMonthStart->format('%Y-%m-%d %H:%M:%S %Z')), PEAR_LOG_DEBUG);
     $daysInMonth = $oMonthStart->getDaysInMonth();
     OA::debug(sprintf("    - Days in month: %d", $daysInMonth), PEAR_LOG_DEBUG);
     $oMonthEnd = new Date($oMonthStart);
     $oMonthEnd->setDay($daysInMonth);
     $oMonthEnd = $oMonthEnd->getNextDay();
     $oMonthEnd->setTZ($oMonthStart->tz);
     OA::debug(sprintf("    - Month end: %s", $oMonthEnd->format('%Y-%m-%d %H:%M:%S %Z')), PEAR_LOG_DEBUG);
     $oDiff = new Date_Span();
     $oDiff->setFromDateDiff($oMonthEnd, $oMonthStart);
     $hoursPerMonth = ceil($oDiff->toHours());
     OA::debug(sprintf("    - Hours per month: %d", $hoursPerMonth), PEAR_LOG_DEBUG);
     $oDiff = new Date_Span();
     $oDiff->setFromDateDiff($oEndDate, $oStartDate);
     $hoursPerInterval = ceil($oDiff->toHours());
     OA::debug(sprintf("    - Hours per interval: %d", $hoursPerInterval), PEAR_LOG_DEBUG);
     $adZoneCombinations = $this->aMtRevenueCache[$aInfo['campaign_id']];
     OA::debug(sprintf("    - Ad/zone/OI combinations for campaign [id%d]: %d", $aInfo['campaign_id'], $this->aMtRevenueCache[$aInfo['campaign_id']]), PEAR_LOG_DEBUG);
     $result = $aInfo['revenue'] / $hoursPerMonth * $hoursPerInterval / $adZoneCombinations;
     OA::debug(sprintf("    - Result: %0.4f", $result), PEAR_LOG_DEBUG);
     return $result;
 }
Exemplo n.º 24
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;
 }
 /**
  * A method to obtain the sum of the zone forecast impression value, for all the zones
  * an advertisement is linked to, cloned out over the advertisement's entire remaining
  * lifetime in the campaign, with any blocked operation intervals removed.
  *
  * Requires that the getActiveAdOperationIntervals() method have previously been
  * called to function correctly.
  *
  * @param PEAR::Date $oNowDate The current date.
  * @param PEAR::Date $oEndDate The end date of the campaign. Note that if the end
  *                             date supplied is not at the end of a day, it will be
  *                             converted to be treated as such.
  * @param array $aCumulativeZoneForecast The cumulative forecast impressions, indexed
  *                                       by operation interval ID, of all the zones the
  *                                       advertisement is linked to.
  *                  array(
  *                      [operation_interval_id] => forecast_impressions,
  *                      [operation_interval_id] => forecast_impressions
  *                                  .
  *                                  .
  *                                  .
  *                  )
  * @return integer The ad's total remaining zone impression forecast for all zone for
  *                 the remaining life of the ad.
  */
 function getAdLifetimeZoneImpressionsRemaining($oNowDate, $oEndDate, $aCumulativeZoneForecast)
 {
     $totalAdLifetimeZoneImpressionsRemaining = 0;
     // Test the parameters, if invalid, return zero
     if (!is_a($oNowDate, 'date') || !is_a($oEndDate, 'date') || !is_array($aCumulativeZoneForecast) || count($aCumulativeZoneForecast) != OX_OperationInterval::operationIntervalsPerWeek()) {
         OA::debug('  - Invalid parameters to getAdLifetimeZoneImpressionsRemaining, returning 0', PEAR_LOG_ERR);
         return $totalAdLifetimeZoneImpressionsRemaining;
     }
     // Ensure that the end of campaign date is at the end of the day
     $oEndDateCopy = new Date($oEndDate);
     $oEndDateCopy->setHour(23);
     $oEndDateCopy->setMinute(59);
     $oEndDateCopy->setSecond(59);
     // Ensure that the $aCumulativeZoneForecast array is sorted by key, so that it can
     // be accessed by array_slice, regardless of the order that the forecast data was added
     // to the array
     ksort($aCumulativeZoneForecast);
     // Step 1: Calculate the sum of the forecast values from "now" until the end of "today"
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oNowDate);
     $oEndOfToday = new Date($aDates['start']);
     $oEndOfToday->setTZ($oEndDate->tz);
     $oEndOfToday->setHour(23);
     $oEndOfToday->setMinute(59);
     $oEndOfToday->setSecond(59);
     $oStart = $aDates['start'];
     while ($oStart->before($oEndOfToday)) {
         // Find the Operation Interval ID for this Operation Interval
         $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oStart);
         // As iteration over every OI is required anyway, test to see if
         // the ad is blocked in this OI; if not, add the forecast values to the
         // running total
         if (empty($this->aBlockedOperationIntervalDates[$oStart->format('%Y-%m-%d %H:%M:%S')])) {
             $totalAdLifetimeZoneImpressionsRemaining += $aCumulativeZoneForecast[$operationIntervalID];
         }
         // Go to the next operation interval in "today"
         $oStart = OX_OperationInterval::addOperationIntervalTimeSpan($oStart);
     }
     // Step 2: Calculate how many times each day of the week occurs between the end of
     //         "today" (i.e. starting "tomorrow morning") and the last day the ad can run
     $aDays = array();
     $oStartOfTomorrow = new Date($oEndOfToday);
     $oStartOfTomorrow->addSeconds(1);
     $oTempDate = new Date();
     $oTempDate->copy($oStartOfTomorrow);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oTempDate);
     while ($aDates['start']->before($oEndDateCopy)) {
         // Increase the count for this day of the week
         $aDays[$aDates['start']->getDayOfWeek()]++;
         // Go to the next day
         $oTempDate->addSeconds(SECONDS_PER_DAY);
         $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oTempDate);
     }
     // Step 3: For every possible day of the week (assuming that day of the week is in the
     //         ad's remaining lifetime), calculate the sum of the forecast values for every
     //         operation interval in that day
     if (!empty($aDays)) {
         $operationIntervalsPerDay = OX_OperationInterval::operationIntervalsPerDay();
         $oTempDate = new Date($oStartOfTomorrow);
         $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oTempDate);
         for ($counter = 0; $counter < 7; $counter++) {
             // Are there any instances of this day in the campaign?
             if ($aDays[$oTempDate->getDayOfWeek()] > 0) {
                 // Calculate the sum of the zone forecasts for this day of week
                 $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oTempDate);
                 $dayStartOperationIntervalId = OX_OperationInterval::convertDateToOperationIntervalID($aDates['start']);
                 $aDayCumulativeZoneForecast = array_slice($aCumulativeZoneForecast, $dayStartOperationIntervalId, $operationIntervalsPerDay);
                 $forecastSum = array_sum($aDayCumulativeZoneForecast);
                 // Multiply this day's forecast sum value by the number of times this
                 // day of week appears in the remainder of the campaign and add the
                 // value to the running total
                 $totalAdLifetimeZoneImpressionsRemaining += $forecastSum * $aDays[$oTempDate->getDayOfWeek()];
             }
             // Go to the next day
             $oTempDate->addSeconds(SECONDS_PER_DAY);
         }
     }
     // Step 4: Subtract any blocked interval values
     if ($this->blockedOperationIntervalCount > 0) {
         OA::debug("      - Subtracting {$this->blockedOperationIntervalCount} blocked intervals", PEAR_LOG_DEBUG);
         foreach ($this->aBlockedOperationIntervalDates as $aDates) {
             if ($aDates['start']->after($oEndOfToday)) {
                 $blockedOperationInvervalID = OX_OperationInterval::convertDateToOperationIntervalID($aDates['start']);
                 $totalAdLifetimeZoneImpressionsRemaining -= $aCumulativeZoneForecast[$blockedOperationInvervalID];
             }
         }
     }
     // Return the calculated value
     return $totalAdLifetimeZoneImpressionsRemaining;
 }
Exemplo n.º 26
0
function showTrendData()
{
    global $badgerDb;
    global $logger;
    $logger->log('statistics::showTrendData: REQUEST_URI: ' . $_SERVER['REQUEST_URI']);
    if (!isset($_GET['accounts']) || !isset($_GET['startDate']) || !isset($_GET['endDate'])) {
        throw new BadgerException('statistics', 'missingParameter');
    }
    $accountIds = explode(';', $_GET['accounts']);
    foreach ($accountIds as $key => $val) {
        settype($accountIds[$key], 'integer');
    }
    $startDate = new Date($_GET['startDate']);
    $endDate = new Date($_GET['endDate']);
    $now = new Date();
    $now->setHour(0);
    $now->setMinute(0);
    $now->setSecond(0);
    if ($endDate->after($now)) {
        $endDate = $now;
    }
    $accountManager = new AccountManager($badgerDb);
    $totals = array();
    $accounts = array();
    $currentAccountIndex = 0;
    foreach ($accountIds as $currentAccountId) {
        $currentAccount = $accountManager->getAccountById($currentAccountId);
        $accounts[$currentAccountIndex][0] = $currentAccount->getTitle();
        $currentBalances = getDailyAmount($currentAccount, $startDate, $endDate);
        foreach ($currentBalances as $balanceKey => $balanceVal) {
            if (isset($totals[$balanceKey])) {
                $totals[$balanceKey]->add($balanceVal);
            } else {
                $totals[$balanceKey] = $balanceVal;
            }
            $accounts[$currentAccountIndex][] = $balanceVal->get();
        }
        $currentAccountIndex++;
    }
    $numDates = count($totals);
    $chart = array();
    //for documentation for the following code see: http://www.maani.us/charts/index.php?menu=Reference
    $chart['chart_type'] = "line";
    $chart['axis_category'] = array('skip' => $numDates / 12, 'font' => "Arial", 'bold' => false, 'size' => 10, 'color' => "000000", 'alpha' => 100, 'orientation' => "horizontal");
    $chart['axis_ticks'] = array('value_ticks' => true, 'category_ticks' => true, 'position' => "centered", 'major_thickness' => 2, 'major_color' => "000000", 'minor_thickness' => 1, 'minor_color' => "000000", 'minor_count' => 4);
    $chart['axis_value'] = array('min' => 0, 'max' => 0, 'steps' => 10, 'prefix' => "", 'suffix' => "", 'decimals' => 0, 'decimal_char' => ".", 'separator' => "", 'show_min' => true, 'font' => "Arial", 'bold' => false, 'size' => 10, 'color' => "000000", 'alpha' => 75, 'orientation' => "horizontal");
    $chart['chart_border'] = array('top_thickness' => 1, 'bottom_thickness' => 1, 'left_thickness' => 1, 'right_thickness' => 1, 'color' => "000000");
    $chart['chart_pref'] = array('line_thickness' => 1, 'point_shape' => "none", 'fill_shape' => false);
    $chart['chart_grid_h'] = array('thickness' => 1, 'color' => "000000", 'alpha' => 15, 'type' => "solid");
    $chart['chart_grid_v'] = array('thickness' => 1, 'color' => "000000", 'alpha' => 5, 'type' => "dashed");
    $chart['chart_rect'] = array('x' => 50, 'y' => 50, 'width' => 700, 'height' => 300, 'positive_color' => "ffffff", 'negative_color' => "000000", 'positive_alpha' => 100, 'negative_alpha' => 10);
    $chart['chart_value'] = array('prefix' => "", 'suffix' => "", 'decimals' => 0, 'decimal_char' => ".", 'separator' => "", 'position' => "cursor", 'hide_zero' => true, 'as_percentage' => false, 'font' => "Arial", 'bold' => false, 'size' => 10, 'color' => "000000", 'alpha' => 90);
    $chart['chart_transition'] = array('type' => "none", 'delay' => 1, 'duration' => 1, 'order' => "all");
    $chart['legend_rect'] = array('x' => 50, 'y' => 5, 'width' => 700, 'height' => 5, 'margin' => 5, 'fill_color' => "FFFFFF", 'fill_alpha' => 100, 'line_color' => "000000", 'line_alpha' => 100, 'line_thickness' => 1);
    $chart['legend_label'] = array('layout' => "horizontal", 'bullet' => "circle", 'font' => "Arial", 'bold' => false, 'size' => 11, 'color' => "000000", 'alpha' => 90);
    $chart['legend_transition'] = array('type' => "none", 'delay' => 1, 'duration' => 1);
    $chart['series_color'] = array("FF0000", "00FF00", "0000FF", "FF8000", "404040", "800040");
    $chart['chart_data'] = array();
    $chart['chart_data'][0][0] = '';
    if (count($accounts) > 1) {
        $chart['chart_data'][1][0] = getBadgerTranslation2('statistics', 'trendTotal');
    } else {
        $chart['chart_data'][1][0] = utf8_encode($accounts[0][0]);
    }
    foreach ($totals as $key => $val) {
        $tmp = new Date($key);
        $chart['chart_data'][0][] = $tmp->getFormatted();
        $chart['chart_data'][1][] = $val->get();
    }
    if (count($accounts) > 1) {
        foreach ($accounts as $val) {
            $chart['chart_data'][] = $val;
        }
    }
    SendChartData($chart);
}
Exemplo n.º 27
0
 /**
  * Prune all entries where the ad_id is for a banner in a High Priority Campaign where:
  * The campaign does not have any booked lifetime target values AND the capaign has an end date AND the end date has been passed AND the campaign is not active.
  *
  */
 function testpruneDataSummaryAdZoneAssocInactiveExpired()
 {
     $oToday = new Date();
     $oToday->setHour(23);
     $oToday->setMinute(59);
     $oToday->setSecond(59);
     $oExpire = new Date($oToday);
     $oExpire->subtractSpan(new Date_Span('10-0-0-0'));
     $today = $oToday->getDate(DATE_FORMAT_ISO);
     $expire = $oExpire->getDate(DATE_FORMAT_ISO);
     $oDal = new OA_Maintenance_Pruning();
     $doDSAZA = OA_Dal::factoryDO('data_summary_ad_zone_assoc');
     // generate 2 summary ad_zone records for an active campaign ad_id
     $doDSAZA->ad_id = $this->idBanner1;
     $aIds = DataGenerator::generate($doDSAZA, 2);
     // generate 7 summary ad_zone records for an inactive campaign ad_id
     $doDSAZA->ad_id = $this->idBanner2;
     $aIds = DataGenerator::generate($doDSAZA, 7);
     // make sure 9 rows in table
     $this->assertEqual($this->_countRowsInDSAZA(), 9);
     // ad_id 1 => campaignid 1 => active, high priority, not expired
     $doCampaigns = OA_Dal::staticGetDO('campaigns', $this->idCampaign1);
     $doCampaigns->priority = 5;
     $doCampaigns->status = OA_ENTITY_STATUS_RUNNING;
     $doCampaigns->target_impression = 0;
     $doCampaigns->target_click = 0;
     $doCampaigns->target_conversion = 0;
     $doCampaigns->views = 0;
     $doCampaigns->clicks = 0;
     $doCampaigns->conversions = 0;
     $doCampaigns->update();
     // ad_id 2 => campaignid 2 => not active, high priority, expired
     $doCampaigns = OA_Dal::staticGetDO('campaigns', $this->idCampaign2);
     $doCampaigns->priority = 5;
     $doCampaigns->status = OA_ENTITY_STATUS_EXPIRED;
     $doCampaigns->target_impression = 0;
     $doCampaigns->target_click = 0;
     $doCampaigns->target_conversion = 0;
     $doCampaigns->views = 0;
     $doCampaigns->clicks = 0;
     $doCampaigns->conversions = 0;
     $doCampaigns->expire_time = $expire;
     $doCampaigns->update();
     $result = $oDal->_pruneDataSummaryAdZoneAssocInactiveExpired();
     // 7 records were deleted
     $this->assertEqual($result, 7);
     // 2 records remain
     $this->assertEqual($this->_countRowsInDSAZA(), 2);
     // ad_id 1 => campaignid 1 => not active, override (low priority)
     $doCampaigns = OA_Dal::staticGetDO('campaigns', $this->idCampaign1);
     $doCampaigns->priority = -1;
     $doCampaigns->status = OA_ENTITY_STATUS_EXPIRED;
     $doCampaigns->target_impression = 0;
     $doCampaigns->target_click = 0;
     $doCampaigns->target_conversion = 0;
     $doCampaigns->views = 0;
     $doCampaigns->clicks = 0;
     $doCampaigns->conversions = 0;
     $doCampaigns->expire_time = $expire;
     $doCampaigns->update();
     $result = $oDal->_pruneDataSummaryAdZoneAssocInactiveExpired();
     // 0 records were deleted
     $this->assertEqual($result, 0);
     // 2 records remain
     $this->assertEqual($this->_countRowsInDSAZA(), 2);
     // ad_id 1 => campaignid 1 => not active, high priority, not expired
     $doCampaigns = OA_Dal::staticGetDO('campaigns', $this->idCampaign1);
     $doCampaigns->priority = 5;
     $doCampaigns->status = OA_ENTITY_STATUS_EXPIRED;
     $doCampaigns->target_impression = 0;
     $doCampaigns->target_click = 0;
     $doCampaigns->target_conversion = 0;
     $doCampaigns->views = 0;
     $doCampaigns->clicks = 0;
     $doCampaigns->conversions = 0;
     $doCampaigns->expire_time = OX_DATAOBJECT_NULL;
     $doCampaigns->update();
     $result = $oDal->_pruneDataSummaryAdZoneAssocInactiveExpired();
     // 0 records were deleted
     $this->assertEqual($result, 0);
     // 2 records remain
     $this->assertEqual($this->_countRowsInDSAZA(), 2);
     // ad_id 1 => campaignid 1 => not active, high priority, expired
     $doCampaigns = OA_Dal::staticGetDO('campaigns', $this->idCampaign1);
     $doCampaigns->priority = 5;
     $doCampaigns->status = OA_ENTITY_STATUS_EXPIRED;
     $doCampaigns->target_impression = 0;
     $doCampaigns->target_click = 0;
     $doCampaigns->target_conversion = 0;
     $doCampaigns->views = 0;
     $doCampaigns->clicks = 0;
     $doCampaigns->conversions = 0;
     $doCampaigns->expire_time = $expire;
     $doCampaigns->update();
     $result = $oDal->_pruneDataSummaryAdZoneAssocInactiveExpired();
     // 2 records were deleted
     $this->assertEqual($result, 2);
     // 0 records remain
     $this->assertEqual($this->_countRowsInDSAZA(), 0);
     // generate 2 summary ad_zone records for an active campaign that expires today
     $doDSAZA->ad_id = 1;
     $aIds = DataGenerator::generate($doDSAZA, 2);
     $this->assertEqual($this->_countRowsInDSAZA(), 2);
     // ad_id 1 => campaignid 1 => active, high priority, expires today
     $doCampaigns = OA_Dal::staticGetDO('campaigns', $this->idCampaign1);
     $doCampaigns->priority = 5;
     $doCampaigns->status = OA_ENTITY_STATUS_RUNNING;
     $doCampaigns->target_impression = 0;
     $doCampaigns->target_click = 0;
     $doCampaigns->target_conversion = 0;
     $doCampaigns->views = 0;
     $doCampaigns->clicks = 0;
     $doCampaigns->conversions = 0;
     $doCampaigns->expire_time = $today;
     $doCampaigns->update();
     $result = $oDal->_pruneDataSummaryAdZoneAssocInactiveExpired();
     // 0 records were deleted
     $this->assertEqual($result, 0);
     // 2 records remain
     $this->assertEqual($this->_countRowsInDSAZA(), 2);
     // ad_id 1 => campaignid 1 => active, high priority, expired
     $doCampaigns = OA_Dal::staticGetDO('campaigns', $this->idCampaign1);
     $doCampaigns->priority = 5;
     $doCampaigns->status = OA_ENTITY_STATUS_EXPIRED;
     $doCampaigns->target_impression = 0;
     $doCampaigns->target_click = 0;
     $doCampaigns->target_conversion = 0;
     $doCampaigns->views = 0;
     $doCampaigns->clicks = 0;
     $doCampaigns->conversions = 0;
     $doCampaigns->expire_time = $expire;
     $doCampaigns->update();
     $result = $oDal->_pruneDataSummaryAdZoneAssocInactiveExpired();
     // 2 records were deleted
     $this->assertEqual($result, 2);
     // 0 records remain
     $this->assertEqual($this->_countRowsInDSAZA(), 0);
 }
Exemplo n.º 28
0
 /**
  * Returns an array of conversions.
  *
  * @param array $aParams
  * @return array
  */
 function getConversions($aParams)
 {
     $conf = $GLOBALS['_MAX']['CONF'];
     $oDbh =& OA_DB::singleton();
     $where = '';
     if (!empty($aParams['day'])) {
         $aParams['day_begin'] = $aParams['day_end'] = $aParams['day'];
     }
     if (!empty($aParams['day_begin'])) {
         $oStart = new Date($aParams['day_begin']);
         $oStart->setHour(0);
         $oStart->setMinute(0);
         $oStart->setSecond(0);
         $oStart->toUTC();
         $where .= ' AND ac.tracker_date_time >= ' . $oDbh->quote($oStart->format('%Y-%m-%d %H:%M:%S'), 'timestamp');
     }
     if (!empty($aParams['day_end'])) {
         $oEnd = new Date($aParams['day_end']);
         $oEnd->setHour(23);
         $oEnd->setMinute(59);
         $oEnd->setSecond(59);
         $oEnd->toUTC();
         $where .= ' AND ac.tracker_date_time <= ' . $oDbh->quote($oEnd->format('%Y-%m-%d %H:%M:%S'), 'timestamp');
     }
     if (!empty($aParams['month'])) {
         $oStart = new Date("{$aParams['month']}-01");
         $oStart->setHour(0);
         $oStart->setMinute(0);
         $oStart->setSecond(0);
         $oEnd = new Date(Date_Calc::beginOfNextMonth($oStart->getDay(), $oStart->getMonth, $oStart->getYear(), '%Y-%m-%d'));
         $oEnd->setHour(0);
         $oEnd->setMinute(0);
         $oEnd->setSecond(0);
         $oEnd->subtractSeconds(1);
         $oStart->toUTC();
         $oEnd->toUTC();
         $where .= ' AND ac.tracker_date_time >= ' . $oDbh->quote($oStart->format('%Y-%m-%d %H:%M:%S'), 'timestamp');
         $where .= ' AND ac.tracker_date_time <= ' . $oDbh->quote($oEnd->format('%Y-%m-%d %H:%M:%S'), 'timestamp');
     }
     if (!empty($aParams['day_hour'])) {
         $oStart = new Date("{$aParams['day_hour']}:00:00");
         $oStart->setMinute(0);
         $oStart->setSecond(0);
         $oEnd = new Date($oStart);
         $oStart->setMinute(59);
         $oStart->setSecond(59);
         $where .= ' AND ac.tracker_date_time >= ' . $oDbh->quote($oStart->format('%Y-%m-%d %H:%M:%S'), 'timestamp');
         $where .= ' AND ac.tracker_date_time <= ' . $oDbh->quote($oEnd->format('%Y-%m-%d %H:%M:%S'), 'timestamp');
     }
     if (!empty($aParams['agency_id'])) {
         $where .= ' AND c.agencyid=' . $oDbh->quote($aParams['agency_id'], 'integer');
     }
     if (!empty($aParams['clientid'])) {
         $where .= ' AND c.clientid=' . $oDbh->quote($aParams['clientid'], 'integer');
     }
     if (isset($aParams['zonesIds'])) {
         $where .= ' AND ac.zone_id IN (' . $oDbh->escape(implode(',', $aParams['zonesIds'])) . ")";
     }
     if (!empty($aParams['campaignid'])) {
         $where .= ' AND m.campaignid=' . $oDbh->quote($aParams['campaignid'], 'integer');
     }
     if (!empty($aParams['bannerid'])) {
         $where .= ' AND d.bannerid=' . $oDbh->quote($aParams['bannerid'], 'integer');
     }
     if (!empty($aParams['statuses'])) {
         $where .= ' AND ac.connection_status IN (' . $oDbh->escape(implode(',', $aParams['statuses'])) . ')';
     }
     if (isset($aParams['startRecord']) && is_numeric($aParams['startRecord']) && is_numeric($aParams['perPage'])) {
         $limit = ' LIMIT ' . $oDbh->quote($aParams['perPage'], 'text', false) . ' OFFSET ' . $oDbh->quote($aParams['startRecord'], 'text', false);
     } elseif (!empty($aParams['perPage'])) {
         $limit = ' LIMIT ' . $oDbh->quote($aParams['perPage'], 'integer', false) . ' OFFSET 0';
     } else {
         $limit = '';
     }
     $query = "SELECT\n            ac.data_intermediate_ad_connection_id as connection_id,\n            c.clientid,\n            m.campaignid,\n            m.campaignname AS campaignname,\n            ac.tracker_id as tracker_id,\n            ac.connection_status,\n            ac.connection_date_time AS connection_date_time,\n            ac.tracker_date_time as date_time,\n            t.trackername,\n            ac.tracker_ip_address,\n            ac.tracker_country,\n            ac.connection_action,\n            t.type AS connection_type,\n            ac.tracker_country,\n            ac.ad_id,\n            ac.creative_id,\n            ac.zone_id,\n            ac.comments\n        FROM\n            {$conf['table']['prefix']}{$conf['table']['clients']} AS c,\n            {$conf['table']['prefix']}{$conf['table']['data_intermediate_ad_connection']} AS ac,\n            {$conf['table']['prefix']}{$conf['table']['banners']} AS d,\n            {$conf['table']['prefix']}{$conf['table']['campaigns']} AS m,\n            {$conf['table']['prefix']}{$conf['table']['trackers']} AS t\n        WHERE\n            c.clientid=m.clientid\n            AND m.campaignid=d.campaignid\n            AND d.bannerid=ac.ad_id\n            AND t.trackerid=ac.tracker_id\n            AND ac.inside_window = 1\n            " . $where . "\n        ORDER BY\n            ac.tracker_date_time\n        {$limit}";
     $aStats = $oDbh->queryAll($query, null, MDB2_FETCHMODE_DEFAULT, true);
     $oNow = new Date();
     foreach (array_keys($aStats) as $k) {
         $oDate = new Date($aStats[$k]['date_time']);
         $oDate->setTZbyID('UTC');
         $oDate->convertTZ($oNow->tz);
         $aStats[$k]['date_time'] = $oDate->format('%Y-%m-%d %H:%M:%S');
         $oDate = new Date($aStats[$k]['connection_date_time']);
         $oDate->setTZbyID('UTC');
         $oDate->convertTZ($oNow->tz);
         $aStats[$k]['connection_date_time'] = $oDate->format('%Y-%m-%d %H:%M:%S');
     }
     return $aStats;
 }
Exemplo n.º 29
0
 public function getNextRunTime($date)
 {
     // check if $date is a timestamp...
     if ($date instanceof Date == false && is_integer($date)) {
         $date = new Date($date);
     }
     // assume now $date IS instanceof Date
     $cSecond = $date->getSecond();
     $cMinute = $date->getMinute();
     $cHour = $date->getHour();
     $cDay = $date->getDay();
     $cMonth = $date->getMonth();
     $cYear = $date->getYear();
     // required to check the number of days in the month
     $found = false;
     while ($found === false) {
         while ($found === false) {
             // iterate months...
             $cMonth = $this->findNextInArray($cMonth, $this->monthArray);
             if ($cMonth === null) {
                 break;
             }
             // find the day now
             while ($found === false) {
                 $cDay = $this->findNextInArray($cDay, $this->dayArray);
                 if ($cDay === null) {
                     break;
                 }
                 // here dayOfWeek and number of days in month should be checked!
                 $date = new Date();
                 $date->setYear($cYear);
                 $date->setMonth($cMonth);
                 $numberOfDaysInMonth = $date->getDaysInMonth();
                 if ($cDay > $numberOfDaysInMonth) {
                     break;
                 }
                 if ($this->dayOfWeekArray !== null) {
                     // get day of the week
                     $date->setDay($cDay);
                     $dayOfWeek = $date->getDayOfWeek();
                     if (!in_array($dayOfWeek, $this->dayOfWeekArray)) {
                         $cDay++;
                         continue;
                     }
                 }
                 while ($found === false) {
                     if ($cHour == 24) {
                         break;
                     }
                     $cHour = $this->findNextInArray($cHour, $this->hourArray);
                     if ($cHour === null) {
                         break;
                     }
                     while ($found === false) {
                         if ($cMinute == 60) {
                             break;
                         }
                         $cMinute = $this->findNextInArray($cMinute, $this->minuteArray);
                         if ($cMinute === null) {
                             break;
                         }
                         while ($found === false) {
                             if ($cSecond == 60) {
                                 break;
                             }
                             $cSecond = $this->findNextInArray($cSecond, $this->secondArray);
                             if ($cSecond === null) {
                                 break;
                             } else {
                                 // FOUND IT!!! WOOOO!
                                 // create Date object
                                 $date = new Date();
                                 $date->setYear($cYear);
                                 $date->setMonth($cMonth);
                                 $date->setDay($cDay);
                                 $date->setHour($cHour);
                                 $date->setMinute($cMinute);
                                 $date->setSecond($cSecond);
                                 return $date;
                             }
                         }
                         $cMinute++;
                         $cSecond = 0;
                     }
                     $cHour++;
                     $cMinute = 0;
                     $cSecond = 0;
                 }
                 $cDay++;
                 $cHour = 0;
                 $cMinute = 0;
                 $cSecond = 0;
             }
             $cMonth++;
             $cDay = 0;
             $cHour = 0;
             $cMinute = 0;
             $cSecond = 0;
         }
         $cYear++;
         $cMonth = 0;
         $cDay = 0;
         $cHour = 0;
         $cMinute = 0;
         $cSecond = 0;
     }
 }
Exemplo n.º 30
0
 /**
  * Expands the planned transactions.
  * 
  * All occurences of planned transactions between now and the targetFutureCalcDate will be inserted
  * in finishedTransactions. For distinction the planned transactions will have a 'p' as first character
  * in their id.
  * 
  * @throws BadgerException If an illegal repeat unit is used.
  */
 public function expandPlannedTransactions()
 {
     $now = new Date();
     $now->setHour(0);
     $now->setMinute(0);
     $now->setSecond(0);
     foreach ($this->plannedTransactions as $currentTransaction) {
         $date = new Date($currentTransaction->getBeginDate());
         $dayOfMonth = $date->getDay();
         //While we have not reached targetFutureCalcDate
         while ($this->targetFutureCalcDate->after($date) && !$date->after(is_null($tmp = $currentTransaction->getEndDate()) ? new Date('9999-12-31') : $tmp)) {
             $inRange = true;
             //Check if there is one or more valutaDate filter and apply them
             foreach ($this->filter as $currentFilter) {
                 if ($currentFilter['key'] == 'valutaDate') {
                     switch ($currentFilter['op']) {
                         case 'eq':
                             if (Date::compare($date, $currentFilter['val']) != 0) {
                                 $inRange = false;
                             }
                             break;
                         case 'lt':
                             if (Date::compare($date, $currentFilter['val']) >= 0) {
                                 $inRange = false;
                             }
                             break;
                         case 'le':
                             if (Date::compare($date, $currentFilter['val']) > 0) {
                                 $inRange = false;
                             }
                             break;
                         case 'gt':
                             if (Date::compare($date, $currentFilter['val']) <= 0) {
                                 $inRange = false;
                             }
                             break;
                         case 'ge':
                             if (Date::compare($date, $currentFilter['val']) < 0) {
                                 $inRange = false;
                             }
                             break;
                         case 'ne':
                             if (Date::compare($date, $currentFilter['val']) == 0) {
                                 $inRange = false;
                             }
                             break;
                         case 'bw':
                         case 'ew':
                         case 'ct':
                             if (strncasecmp($date->getFormatted(), $currentFilter['val']->getFormatted(), 9999) != 0) {
                                 $inRange = false;
                             }
                             break;
                     }
                     if (!$inRange) {
                         break;
                     }
                 }
             }
             if (!$date->before($now) && $inRange) {
                 $this->finishedTransactions[] = new FinishedTransaction($this->badgerDb, $this, 'p' . $currentTransaction->getId() . '_' . $date->getDate(), $currentTransaction->getTitle(), $currentTransaction->getAmount(), $currentTransaction->getDescription(), new Date($date), $currentTransaction->getTransactionPartner(), $currentTransaction->getCategory(), $currentTransaction->getOutsideCapital(), false, true, $currentTransaction, 'PlannedTransaction');
             }
             //do the date calculation
             switch ($currentTransaction->getRepeatUnit()) {
                 case 'day':
                     $date->addSeconds($currentTransaction->getRepeatFrequency() * 24 * 60 * 60);
                     break;
                 case 'week':
                     $date->addSeconds($currentTransaction->getRepeatFrequency() * 7 * 24 * 60 * 60);
                     break;
                 case 'month':
                     //Set the month
                     $date = new Date(Date_Calc::endOfMonthBySpan($currentTransaction->getRepeatFrequency(), $date->getMonth(), $date->getYear(), '%Y-%m-%d'));
                     //And count back as far as the last valid day of this month
                     while ($date->getDay() > $dayOfMonth) {
                         $date->subtractSeconds(24 * 60 * 60);
                     }
                     break;
                 case 'year':
                     $newYear = $date->getYear() + $currentTransaction->getRepeatFrequency();
                     if ($dayOfMonth == 29 && $date->getMonth() == 2 && !Date_Calc::isLeapYear($newYear)) {
                         $date->setDay(28);
                     } else {
                         $date->setDay($dayOfMonth);
                     }
                     $date->setYear($newYear);
                     break;
                 default:
                     throw new BadgerException('Account', 'IllegalRepeatUnit', $currentTransaction->getRepeatUnit());
                     exit;
             }
         }
     }
 }