public function testDateComparsion()
 {
     $date1 = Date::create(mktime(0, 0, 0, 1, 1, 2009));
     $date2 = Date::create(mktime(1, 0, 0, 1, 1, 2009));
     $this->assertEquals($date1, $date2);
     $this->assertEquals(Date::compare($date1, $date2), 0);
     return $this;
 }
/**
 * Returns the Account balance for $account at the end of each day between $startDate and $endDate.
 * 
 * Considers the planned transactions of $account.
 * 
 * @param object $account The Account object for which the balance should be calculated. 
 * It should be 'fresh', i. e. no transactions of any type should have been fetched from it.
 * @param object $startDate The first date the balance should be calculated for as Date object.
 * @param object $endDate The last date the balance should be calculated for as Date object.
 * @return array Array of Amount objects corresponding to the balance of $account at each day between
 * $startDate and $endDate. The array keys are the dates as ISO-String (yyyy-mm-dd). 
 */
function getDailyAmount($account, $startDate, $endDate)
{
    $account->setTargetFutureCalcDate($endDate);
    $account->setOrder(array(array('key' => 'valutaDate', 'dir' => 'asc')));
    $result = array();
    $startDate->setHour(0);
    $startDate->setMinute(0);
    $startDate->setSecond(0);
    $endDate->setHour(0);
    $endDate->setMinute(0);
    $endDate->setSecond(0);
    $currentDate = new Date($startDate);
    $currentAmount = new Amount();
    //foreach transaction
    while ($currentTransaction = $account->getNextTransaction()) {
        if ($currentDate->after($endDate)) {
            //we reached $endDAte
            break;
        }
        //fill all dates between last and this transaction with the old amount
        while (is_null($tmp = $currentTransaction->getValutaDate()) ? false : $currentDate->before($tmp)) {
            $result[$currentDate->getDate()] = new Amount($currentAmount);
            $currentDate->addSeconds(24 * 60 * 60);
            if ($currentDate->after($endDate)) {
                //we reached $endDAte
                break;
            }
        }
        $currentAmount->add($currentTransaction->getAmount());
    }
    //fill all dates after the last transaction with the newest amount
    while (Date::compare($currentDate, $endDate) <= 0) {
        $result[$currentDate->getDate()] = new Amount($currentAmount);
        $currentDate->addSeconds(24 * 60 * 60);
    }
    return $result;
}
示例#3
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;
 }
示例#4
0
 /**
  * Static helper function to sort an array of families by marriage date
  *
  * @param Family $x
  * @param Family $y
  *
  * @return int
  */
 public static function compareMarrDate(Family $x, Family $y)
 {
     return Date::compare($x->getMarriageDate(), $y->getMarriageDate());
 }
 /**
  * Retrieves the next assignee in the given project's round robin queue.
  *
  * @access  public
  * @param   integer $prj_id The project ID
  * @return  integer The assignee's user ID
  */
 function getNextAssignee($prj_id)
 {
     // get the full list of users for the given project
     list($blackout_start, $blackout_end, $users) = Round_Robin::getUsersByProject($prj_id);
     if (count($users) == 0) {
         return 0;
     } else {
         $user_ids = array_keys($users);
         $next_usr_id = 0;
         foreach ($users as $usr_id => $details) {
             if ($details['is_next']) {
                 $next_usr_id = $usr_id;
                 break;
             }
         }
         // if no user is currently set as the 'next' assignee,
         // then just get the first one in the list
         if (empty($next_usr_id)) {
             $next_usr_id = $user_ids[0];
         }
         // counter to keep the number of times we found an invalid user
         $ignored_users = 0;
         // check the blackout hours
         do {
             $user = new Date(Date_API::getCurrentUnixTimestampGMT());
             $user->convertTZById($users[$next_usr_id]['timezone']);
             list($today, $tomorrow) = Round_Robin::getBlackoutDates(&$user, $blackout_start, $blackout_end);
             $first = new Date($today . ' ' . $blackout_start);
             $first->setTZById($users[$next_usr_id]['timezone']);
             $second = new Date($tomorrow . ' ' . $blackout_end);
             $second->setTZById($users[$next_usr_id]['timezone']);
             if (Date::compare($first, $user) == -1 && Date::compare($user, $second) == -1) {
                 $ignored_users++;
                 $current_index = array_search($next_usr_id, $user_ids);
                 // if we reached the end of the list of users and none of them
                 // was a valid one, then just select the first one
                 // however, we want to complete at least one full iteration over the list of users
                 // that is, if we didn't start checking the users in the beginning of the list,
                 // then do another run over the users just in case
                 if ($ignored_users >= count($user_ids) && $current_index == count($user_ids) - 1) {
                     $assignee = $user_ids[0];
                     break;
                 }
                 // if we reached the end of the list, and we still didn't find an user,
                 // then go back to the beginning of the list one last time
                 if ($current_index == count($user_ids) - 1) {
                     $current_index = 0;
                     $next_usr_id = $user_ids[++$current_index];
                     $found = 0;
                     continue;
                 }
                 $next_usr_id = $user_ids[++$current_index];
                 $found = 0;
             } else {
                 $assignee = $next_usr_id;
                 $found = 1;
             }
         } while (!$found);
         // mark the next user in the list as the 'next' assignment
         $assignee_index = array_search($assignee, $user_ids);
         if ($assignee_index == count($user_ids) - 1) {
             $next_assignee = $user_ids[0];
         } else {
             $next_assignee = $user_ids[++$assignee_index];
         }
         Round_Robin::markNextAssignee($prj_id, $next_assignee);
         return $assignee;
     }
 }
示例#6
0
/**
* Sub-function to collect tasks within a period
*
* @param Date the starting date of the period
* @param Date the ending date of the period
* @param array by-ref an array of links to append new items to
* @param int the length to truncate entries by
* @param int the company id to filter by
* @author Andrew Eddie <*****@*****.**>
*/
function getTaskLinks($startPeriod, $endPeriod, &$links, $strMaxLen, $company_id = 0)
{
    global $a, $AppUI, $dPconfig;
    $tasks = CTask::getTasksForPeriod($startPeriod, $endPeriod, $company_id, $AppUI->user_id, true);
    $durnTypes = dPgetSysVal('TaskDurationType');
    $link = array();
    $sid = 3600 * 24;
    // assemble the links for the tasks
    foreach ($tasks as $row) {
        // the link
        $link['href'] = "?m=tasks&a=view&task_id=" . $row['task_id'];
        $link['alt'] = $row['project_name'] . ":\n" . $row['task_name'];
        // the link text
        if (strlen($row['task_name']) > $strMaxLen) {
            $row['task_name'] = substr($row['task_name'], 0, $strMaxLen) . '...';
        }
        $link['text'] = '<span style="color:' . bestColor($row['color']) . ';background-color:#' . $row['color'] . '">' . $row['task_name'] . '</span>';
        // determine which day(s) to display the task
        $start = new CDate($row['task_start_date']);
        $end = $row['task_end_date'] ? new CDate($row['task_end_date']) : null;
        $durn = $row['task_duration'];
        $durnType = $row['task_duration_type'];
        if (($start->after($startPeriod) || $start->equals($startPeriod)) && ($start->before($endPeriod) || $start->equals($endPeriod))) {
            $temp = $link;
            $temp['alt'] = "START [" . $row['task_duration'] . ' ' . $AppUI->_($durnTypes[$row['task_duration_type']]) . "]\n" . $link['alt'];
            if ($a != 'day_view') {
                $temp['text'] = dPshowImage(dPfindImage('block-start-16.png')) . $temp['text'];
            }
            $links[$start->format(FMT_TIMESTAMP_DATE)][] = $temp;
        }
        if ($end && $end->after($startPeriod) && $end->before($endPeriod) && $start->before($end)) {
            $temp = $link;
            $temp['alt'] = "FINISH\n" . $link['alt'];
            if ($a != 'day_view') {
                $temp['text'] .= dPshowImage(dPfindImage('block-end-16.png'));
            }
            $links[$end->format(FMT_TIMESTAMP_DATE)][] = $temp;
        }
        // convert duration to days
        if ($durnType < 24.0) {
            if ($durn > $dPconfig['daily_working_hours']) {
                $durn /= $dPconfig['daily_working_hours'];
            } else {
                $durn = 0.0;
            }
        } else {
            $durn *= $durnType / 24.0;
        }
        // fill in between start and finish based on duration
        // notes:
        // start date is not in a future month, must be this or past month
        // start date is counted as one days work
        // business days are not taken into account
        $target = $start;
        $target->addSeconds($durn * $sid);
        if (Date::compare($target, $startPeriod) < 0) {
            continue;
        }
        if (Date::compare($start, $startPeriod) > 0) {
            $temp = $start;
            $temp->addSeconds($sid);
        } else {
            $temp = $startPeriod;
        }
        // Optimised for speed, AJD.
        while (Date::compare($endPeriod, $temp) > 0 && Date::compare($target, $temp) > 0 && ($end == null || $temp->before($end))) {
            $links[$temp->format(FMT_TIMESTAMP_DATE)][] = $link;
            $temp->addSeconds($sid);
        }
    }
}
示例#7
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;
 }
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  ; 


}
require_once BADGER_ROOT . '/includes/fileHeaderBackEnd.inc.php';
require_once BADGER_ROOT . '/modules/account/accountCommon.php';
//include charts.php to access the InsertChart function
require_once BADGER_ROOT . "/includes/charts/charts.php";
header('Content-Type: text/xml');
echo "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
# validate if date is in future
$selectedDate = getGPC($_POST, 'endDate', 'DateFormatted');
$today = new Date();
$noFutureDates = NULL;
$noLowerLimit = NULL;
$noUpperLimit = NULL;
$noGraphChosen = NULL;
$insertChart = NULL;
//to avoid a date in the past or the same date as today
if ($today->compare($today, $selectedDate) != 1) {
    $selectedSavingTarget = getGPC($_POST, 'savingTarget', 'AmountFormatted');
    $savingTarget = $selectedSavingTarget->get();
    $endDate = $selectedDate->getDate();
    $account = getGPC($_POST, 'selectedAccount', 'int');
    //save selected account as standard account
    $us->setProperty('forecastStandardAccount', $account);
    $selectedPocketMoney1 = getGPC($_POST, 'pocketmoney1', 'AmountFormatted');
    $pocketMoney1 = $selectedPocketMoney1->get();
    $viewPocketMoney1 = $selectedPocketMoney1->getFormatted();
    $selectedPocketMoney2 = getGPC($_POST, 'pocketmoney2', 'AmountFormatted');
    $pocketMoney2 = $selectedPocketMoney2->get();
    $viewPocketMoney2 = $selectedPocketMoney2->getFormatted();
    $dailyPocketMoneyLabel = NULL;
    $dailyPocketMoneyValue = NULL;
    $dailyPocketMoneyToolTip = NULL;
示例#10
0
 /**
  * Takes a user's session identifier and session expiry
  * timestamp and checks to see if they represent a currently
  * active session.  Note: This method does not verify that
  * $session_id is a valid session identifier, but rather
  * expects these values to have come from a database source
  * and hence be validated prior to this method being called.
  * If the $session_id value is empty however, it will return
  * false.  Compares $expires against the current time to
  * determine if the session has expired or not.
  * 
  * @access	public
  * @param	string	$session_id
  * @param	integer	$expires
  * @return	boolean
  * 
  */
 function isActive($session_id, $expires)
 {
     if (empty($session_id)) {
         return false;
     }
     global $loader;
     $loader->import('saf.Date');
     if (Date::compare($expires, Date::toUnix()) >= 0) {
         return false;
     }
     return true;
 }
示例#11
0
 /**
  * Compares the given date and the current date.
  *
  * @return integer
  * @link http://www.php.net/manual/en/function.mktime.php
  */
 function _compareGivenDateAndCurrentDate()
 {
     $givenDate = new Date();
     $givenDate->setYear($this->_year);
     $givenDate->setMonth($this->_month);
     $givenDate->setDay($this->_day);
     $givenDate->setHour(0);
     $givenDate->setMinute(0);
     $givenDate->setSecond(0);
     $currentDate = new Date();
     $currentDate->setHour(0);
     $currentDate->setMinute(0);
     $currentDate->setSecond(0);
     return @Date::compare($givenDate, $currentDate);
 }
 static function date_greater_than_now($date)
 {
     $now = new Date(date('Y-m-d'), 'Ymd', 'Y-m-d');
     $date = new Date($date, 'dmY', 'Y-m-d');
     return $date->compare($now) > -1;
 }
示例#13
0
文件: date.php 项目: alencarmo/OCF
 function test()
 {
     $d = new Date("hjsgdf");
     echo "Invalid date:<br>";
     echo "<pre>" . print_r($d, TRUE) . "</pre>";
     $d = new Date();
     echo "Default date:<br>";
     echo "<pre>" . print_r($d, TRUE) . "</pre>";
     $d = new Date("now");
     echo "Current date:<br>";
     echo "<pre>" . print_r($d, TRUE) . "</pre>";
     $d = new Date('1960-02-10 01:02:03');
     echo "From string - '1960-02-10 01:02:03':<br>";
     echo "<pre>" . print_r($d, TRUE) . "</pre>";
     $d = new Date('Wed, 01/16/2008 07:20');
     echo "From string - 'Wed, 01/16/2008 07:20':<br>";
     echo "<pre>" . print_r($d, TRUE) . "</pre>";
     $d = new Date(1907, 1);
     echo "From 2 separate parameters:<br>";
     echo "<pre>" . print_r($d, TRUE) . "</pre>";
     $d = new Date(1907, 1, 15);
     echo "From 3 separate parameters:<br>";
     echo "<pre>" . print_r($d, TRUE) . "</pre>";
     $d = new Date(1907, 1, 15, 1);
     echo "From 4 separate parameters:<br>";
     echo "<pre>" . print_r($d, TRUE) . "</pre>";
     $d = new Date(1907, 1, 15, 1, 2);
     echo "From 5 separate parameters:<br>";
     echo "<pre>" . print_r($d, TRUE) . "</pre>";
     $d = new Date(1907, 1, 15, 1, 2, 3);
     echo "From 6 separate parameters:<br>";
     echo "<pre>" . print_r($d, TRUE) . "</pre>";
     $d = new Date(array("year" => 1, "month" => 2, "day" => 3, "hour" => 4, "minute" => 5, "second" => 6));
     echo "From array of 6:<br>";
     echo "<pre>" . print_r($d, TRUE) . "</pre>";
     $d = new Date(array("year" => 1, "month" => 2, "day" => 3, "hour" => 4, "minute" => 5));
     echo "From array of 5:<br>";
     echo "<pre>" . print_r($d, TRUE) . "</pre>";
     $d = new Date(array("year" => 1, "month" => 2, "day" => 3, "hour" => 4));
     echo "From array of 4:<br>";
     echo "<pre>" . print_r($d, TRUE) . "</pre>";
     $d = new Date(array("year" => 1, "month" => 2, "day" => 3));
     echo "From array of 3:<br>";
     echo "<pre>" . print_r($d, TRUE) . "</pre>";
     echo "<h3>Comparision test:</h3><br>";
     $d1 = new Date('1907-6-15 12:30:30');
     $d11 = new Date('1907-6-15 12:30:30');
     $d2 = new Date('1907-6-16 12:30:30');
     $d3 = new Date('1907-6-17 12:30:30');
     echo "{$d1}=={$d11}: " . ($d1->compare('==', $d11) ? 'ok' : '<font color=red>NOK</font>') . "<br>";
     echo "{$d1}!={$d11}: " . (!$d1->compare('!=', $d11) ? 'ok' : '<font color=red>NOK</font>') . "<br>";
     echo "{$d1}<{$d11}: " . (!$d1->compare('<', $d11) ? 'ok' : '<font color=red>NOK</font>') . "<br>";
     echo "{$d1}>{$d11}: " . (!$d1->compare('>', $d11) ? 'ok' : '<font color=red>NOK</font>') . "<br>";
     echo "{$d1}<={$d11}: " . ($d1->compare('<=', $d11) ? 'ok' : '<font color=red>NOK</font>') . "<br>";
     echo "{$d1}>={$d11}: " . ($d1->compare('>=', $d11) ? 'ok' : '<font color=red>NOK</font>') . "<br>";
     echo "{$d1}=={$d2}: " . (!$d1->compare('==', $d2) ? 'ok' : '<font color=red>NOK</font>') . "<br>";
     echo "{$d1}!={$d2}: " . ($d1->compare('!=', $d2) ? 'ok' : '<font color=red>NOK</font>') . "<br>";
     echo "{$d1}<{$d2}: " . ($d1->compare('<', $d2) ? 'ok' : '<font color=red>NOK</font>') . "<br>";
     echo "{$d1}>{$d2}: " . (!$d1->compare('>', $d2) ? 'ok' : '<font color=red>NOK</font>') . "<br>";
     echo "{$d1}<={$d2}: " . ($d1->compare('<=', $d2) ? 'ok' : '<font color=red>NOK</font>') . "<br>";
     echo "{$d1}>={$d2}: " . (!$d1->compare('>=', $d2) ? 'ok' : '<font color=red>NOK</font>') . "<br>";
     echo "{$d1}<{$d2}<{$d3}: " . ($d2->isBetween($d1, $d3) ? 'ok' : '<font color=red>NOK</font>') . "<br>";
     echo "{$d1}<={$d11}<{$d3}: " . ($d11->isBetween($d1, $d3, '<=>') ? 'ok' : '<font color=red>NOK</font>') . "<br>";
     echo "{$d1}<{$d2}: " . ($d1->isBefore($d2) ? 'ok' : '<font color=red>NOK</font>') . "<br>";
     echo "{$d3}>{$d2}: " . ($d3->isAfter($d2) ? 'ok' : '<font color=red>NOK</font>') . "<br>";
     echo "{$d1}=={$d2}(day): " . (!$d1->compare('==', $d2, Date_Day) ? 'ok' : '<font color=red>NOK</font>') . "<br>";
     echo "{$d1}!={$d2}(day): " . ($d1->compare('!=', $d2, Date_Day) ? 'ok' : '<font color=red>NOK</font>') . "<br>";
     echo "{$d1}<{$d2}(day): " . ($d1->compare('<', $d2, Date_Day) ? 'ok' : '<font color=red>NOK</font>') . "<br>";
     echo "{$d1}>{$d2}(day): " . (!$d1->compare('>', $d2, Date_Day) ? 'ok' : '<font color=red>NOK</font>') . "<br>";
     echo "{$d1}<={$d2}(day): " . ($d1->compare('<=', $d2, Date_Day) ? 'ok' : '<font color=red>NOK</font>') . "<br>";
     echo "{$d1}>={$d2}(day): " . (!$d1->compare('>=', $d2, Date_Day) ? 'ok' : '<font color=red>NOK</font>') . "<br>";
     echo "{$d1}=={$d2}(month): " . ($d1->compare('==', $d2, Date_Month) ? 'ok' : '<font color=red>NOK</font>') . "<br>";
     echo "{$d1}=={$d2}(year): " . ($d1->compare('==', $d2, Date_Year) ? 'ok' : '<font color=red>NOK</font>') . "<br>";
     echo "{$d1}=={$d2}(hour): " . (!$d1->compare('==', $d2, Date_Hour) ? 'ok' : '<font color=red>NOK</font>') . "<br>";
     echo "<h3>Diff test:</h3><br>";
     $d1 = new Date('1907-6-15 12:30:30');
     $d2 = new Date('1907-6-17 12:30:30');
     $d3 = new Date('1907-6-15 13:32:33');
     echo "Diff of {$d1} and {$d2}:<br>";
     echo "<pre>" . print_r($d1->getFullDiff($d2), TRUE) . "</pre>";
     echo "Diff of {$d1} and {$d3}:<br>";
     echo "<pre>" . print_r($d1->getFullDiff($d3), TRUE) . "</pre>";
     echo "Diff of {$d2} and {$d3}:<br>";
     echo "<pre>" . print_r($d2->getFullDiff($d3), TRUE) . "</pre>";
     echo "Diff of {$d1} and {$d1}:<br>";
     echo "<pre>" . print_r($d1->getFullDiff($d1), TRUE) . "</pre>";
     echo "Diff of {$d1} and {$d2}:<br>";
     echo "<pre>" . $d1->getHoursMinutesDiff($d2) . "</pre>";
     echo "Diff of {$d1} and {$d3}:<br>";
     echo "<pre>" . $d1->getHoursMinutesDiff($d3) . "</pre>";
     echo "Diff of {$d2} and {$d3}:<br>";
     echo "<pre>" . $d2->getHoursMinutesDiff($d3) . "</pre>";
     echo "Diff of {$d1} and {$d1}:<br>";
     echo "<pre>" . $d1->getHoursMinutesDiff($d1) . "</pre>";
     echo "firstSecondOfDay {$d1}:<br>";
     echo "<pre>" . $d1->firstSecondOfDay() . "</pre>";
     echo "firstSecondOfDay {$d1}:<br>";
     echo "<pre>" . Date::firstSecondOfDay($d1) . "</pre>";
     echo "firstSecondOfDay today:<br>";
     echo "<pre>" . Date::firstSecondOfDay() . "</pre>";
     echo "lastSecondOfDay {$d1}:<br>";
     echo "<pre>" . $d1->lastSecondOfDay() . "</pre>";
     echo "firstDayOfWeek {$d1}:<br>";
     echo "<pre>" . $d1->firstDayOfWeek() . "</pre>";
     echo "lastDayOfWeek {$d1}:<br>";
     echo "<pre>" . $d1->lastDayOfWeek() . "</pre>";
     echo "firstDayOfMonth {$d1}:<br>";
     echo "<pre>" . $d1->firstDayOfMonth() . "</pre>";
     echo "lastDayOfMonth {$d1}:<br>";
     echo "<pre>" . $d1->lastDayOfMonth() . "</pre>";
     echo "firstDayOfYear {$d1}:<br>";
     echo "<pre>" . $d1->firstDayOfYear() . "</pre>";
     echo "lastDayOfYear {$d1}:<br>";
     echo "<pre>" . $d1->lastDayOfYear() . "</pre>";
     echo "lastSecondOfWeek {$d1}:<br>";
     echo "<pre>" . $d1->lastSecondOfWeek() . "</pre>";
     echo "lastSecondOfMonth {$d1}:<br>";
     echo "<pre>" . $d1->lastSecondOfMonth() . "</pre>";
     echo "lastSecondOfYear {$d1}:<br>";
     echo "<pre>" . $d1->lastSecondOfYear() . "</pre>";
     echo "<h3>Datum aritmetika:</h3><br>";
     echo "{$d1} ->add( 1, Date_Second ):<br>";
     echo "<pre>" . $d1->add(1, Date_Second) . "</pre>";
     echo "{$d1} ->add( 1, Date_Minute ):<br>";
     echo "<pre>" . $d1->add(1, Date_Minute) . "</pre>";
     echo "{$d1} ->add( 1, Date_Hour ):<br>";
     echo "<pre>" . $d1->add(1, Date_Hour) . "</pre>";
     echo "{$d1} ->add( 1, Date_Day ):<br>";
     echo "<pre>" . $d1->add(1, Date_Day) . "</pre>";
     echo "{$d1} ->add( 1, Date_Week ):<br>";
     echo "<pre>" . $d1->add(1, Date_Week) . "</pre>";
     echo "{$d1} ->add( 1, Date_Month ):<br>";
     echo "<pre>" . $d1->add(1, Date_Month) . "</pre>";
     echo "{$d1} ->add( 1, Date_Year ):<br>";
     echo "<pre>" . $d1->add(1, Date_Year) . "</pre>";
     echo "1 nap mulva:<br>";
     echo "<pre>" . Date::add(1, Date_Day) . "</pre>";
     echo "1 honap mulva:<br>";
     echo "<pre>" . Date::add(1, Date_Month) . "</pre>";
     echo "1 ev mulva:<br>";
     echo "<pre>" . Date::add(1, Date_Year) . "</pre>";
     echo "1 nappal ezelott:<br>";
     echo "<pre>" . Date::subtract(1, Date_Day) . "</pre>";
     echo "1 honappal ezelott:<br>";
     echo "<pre>" . Date::subtract(1, Date_Month) . "</pre>";
     echo "1 evvel ezelott:<br>";
     echo "<pre>" . Date::subtract(1, Date_Year) . "</pre>";
 }
示例#14
0
 /**
  * Test if this date/time is exactly equal to a certain date/time
  *
  * @param object $when the Date object to test against
  *
  * @return   boolean    true if this date is exactly equal to $when
  * @access   public
  */
 function equals($when)
 {
     $hn_compare = Date::compare($this, $when);
     if (PEAR::isError($hn_compare)) {
         return $hn_compare;
     }
     if ($hn_compare == 0) {
         return true;
     } else {
         return false;
     }
 }
 /**
  * The implementation of the OA_Task::run() method that performs
  * the required task of determining what operation intervals
  * and/or hours, if any, need to be updated during the MSE run.
  */
 function run()
 {
     $aConf = $GLOBALS['_MAX']['CONF'];
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oNowDate =& $oServiceLocator->get('now');
     if (!$oNowDate) {
         $oNowDate = new Date();
     }
     $this->oController->report = "Maintenance Statistics Report\n";
     $this->oController->report .= "=====================================\n\n";
     $message = '- Maintenance start run time is ' . $oNowDate->format('%Y-%m-%d %H:%M:%S') . ' ' . $oNowDate->tz->getShortName();
     $this->oController->report .= $message . "\n";
     OA::debug($message, PEAR_LOG_DEBUG);
     // Don't update unless the time is right!
     $this->oController->updateIntermediate = false;
     $this->oController->updateFinal = false;
     // Test to see if a date for when the statistics were last updated
     // has been set in the service locator (for re-generation of stats)
     $oLastUpdatedDate =& $oServiceLocator->get('lastUpdatedDate');
     // Determine when the last intermediate table update happened
     if (is_a($oLastUpdatedDate, 'Date')) {
         $this->oController->oLastDateIntermediate = $oLastUpdatedDate;
     } else {
         $this->oController->oLastDateIntermediate = $this->_getMaintenanceStatisticsLastRunInfo(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_OI, $oNowDate);
         if (is_null($this->oController->oLastDateIntermediate)) {
             // The MSE has never run, look to see if delivery data exists
             $this->oController->oLastDateIntermediate = $this->_getEarliestLoggedDeliveryData(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_OI);
         }
     }
     if (is_null($this->oController->oLastDateIntermediate)) {
         // Could not find a last update date, so don't run MSE
         $message = '- Maintenance statistics has never been run before, and no logged delivery data was located in ';
         $this->oController->report .= $message . "\n";
         OA::debug($message, PEAR_LOG_DEBUG);
         $message = '  the database, so maintenance statistics will not be run for the intermediate tables';
         $this->oController->report .= $message . "\n\n";
         OA::debug($message, PEAR_LOG_DEBUG);
     } else {
         // Found a last update date
         $message = '- Maintenance statistics last updated intermediate table statistics to ' . $this->oController->oLastDateIntermediate->format('%Y-%m-%d %H:%M:%S') . ' ' . $this->oController->oLastDateIntermediate->tz->getShortName();
         $this->oController->report .= $message . ".\n";
         OA::debug($message, PEAR_LOG_DEBUG);
         // Does the last update date found occur on the end of an operation interval?
         $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($this->oController->oLastDateIntermediate);
         if (Date::compare($this->oController->oLastDateIntermediate, $aDates['end']) != 0) {
             $message = '- Last intermediate table updated to date of ' . $this->oController->oLastDateIntermediate->format('%Y-%m-%d %H:%M:%S') . ' ' . $this->oController->oLastDateIntermediate->tz->getShortName() . ' is not on the current operation interval boundary';
             $this->oController->report .= $message . "\n";
             OA::debug($message, PEAR_LOG_DEBUG);
             $message = '- OPERATION INTERVAL LENGTH CHANGE SINCE LAST RUN';
             $this->oController->report .= $message . "\n";
             OA::debug($message, PEAR_LOG_DEBUG);
             $message = '- Extending the time until next update';
             $this->oController->report .= $message . "\n";
             OA::debug($message, PEAR_LOG_DEBUG);
             $this->oController->sameOI = false;
         }
         // Calculate the date after which the next operation interval-based update can happen
         $oRequiredDate = new Date();
         if ($this->oController->sameOI) {
             $oRequiredDate->copy($this->oController->oLastDateIntermediate);
             $oRequiredDate->addSeconds($aConf['maintenance']['operationInterval'] * 60);
         } else {
             $oRequiredDate->copy($aDates['end']);
         }
         $message = '- Current time must be after ' . $oRequiredDate->format('%Y-%m-%d %H:%M:%S') . ' ' . $oRequiredDate->tz->getShortName() . ' for the next intermediate table update to happen';
         $this->oController->report .= $message . "\n";
         OA::debug($message, PEAR_LOG_DEBUG);
         if (Date::compare($oNowDate, $oRequiredDate) > 0) {
             $this->oController->updateIntermediate = true;
             // Update intermediate tables to the end of the previous (not current) operation interval
             $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oNowDate);
             $this->oController->oUpdateIntermediateToDate = new Date();
             $this->oController->oUpdateIntermediateToDate->copy($aDates['start']);
             $this->oController->oUpdateIntermediateToDate->subtractSeconds(1);
         } else {
             // An operation interval hasn't passed, so don't update
             $message = "- At least {$aConf['maintenance']['operationInterval']} minutes have " . 'not passed since the last operation interval update';
             $this->oController->report .= $message . "\n";
             OA::debug($message, PEAR_LOG_DEBUG);
         }
     }
     // Determine when the last final table update happened
     if ($oLastUpdatedDate !== false) {
         $this->oController->oLastDateFinal = $oLastUpdatedDate;
     } else {
         $this->oController->oLastDateFinal = $this->_getMaintenanceStatisticsLastRunInfo(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_HOUR, $oNowDate);
         if (is_null($this->oController->oLastDateFinal)) {
             // The MSE has never run, look to see if delivery data exists
             $this->oController->oLastDateFinal = $this->_getEarliestLoggedDeliveryData(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_HOUR);
         }
     }
     if (is_null($this->oController->oLastDateFinal)) {
         // Could not find a last update date, so don't run MSE
         $message = '- Maintenance statistics has never been run before, and no logged delivery data was located in ';
         $this->oController->report .= $message . "\n" . OA::debug($message, PEAR_LOG_DEBUG);
         $message = '  the database, so maintenance statistics will not be run for the final tables';
         $this->oController->report .= $message . "\n\n";
         OA::debug($message, PEAR_LOG_DEBUG);
     } else {
         // Found a last update date
         $message = '- Maintenance statistics last updated final table statistics to ' . $this->oController->oLastDateFinal->format('%Y-%m-%d %H:%M:%S') . ' ' . $this->oController->oLastDateFinal->tz->getShortName();
         $this->oController->report .= $message . ".\n";
         OA::debug($message, PEAR_LOG_DEBUG);
         // Calculate the date after which the next hour-based update can happen
         $oRequiredDate = new Date();
         $oRequiredDate->copy($this->oController->oLastDateFinal);
         $oRequiredDate->addSeconds(60 * 60);
         $message = '- Current time must be after ' . $oRequiredDate->format('%Y-%m-%d %H:%M:%S') . ' ' . $oRequiredDate->tz->getShortName() . ' for the next intermediate table update to happen';
         $this->oController->report .= $message . "\n";
         OA::debug($message, PEAR_LOG_DEBUG);
         if (Date::compare($oNowDate, $oRequiredDate) > 0) {
             $this->oController->updateFinal = true;
             // Update final tables to the end of the previous (not current) hour
             $this->oController->oUpdateFinalToDate = new Date($oNowDate->format('%Y-%m-%d %H:00:00'));
             $this->oController->oUpdateFinalToDate->subtractSeconds(1);
         } else {
             // An hour hasn't passed, so don't update
             $message = '- At least 60 minutes have NOT passed since the last final table update';
             $this->oController->report .= $message . "\n";
             OA::debug($message, PEAR_LOG_DEBUG);
         }
     }
     // Is an update of any type going to happen?
     if ($this->oController->updateIntermediate || $this->oController->updateFinal) {
         $message = "- Maintenance statistics will be run";
         $this->oController->report .= $message . ".\n";
         OA::debug($message, PEAR_LOG_INFO);
         if ($this->oController->updateIntermediate) {
             $message = '- The intermediate table statistics will be updated';
             $this->oController->report .= $message . ".\n";
             OA::debug($message, PEAR_LOG_INFO);
         }
         if ($this->oController->updateFinal) {
             $message = '- The final table statistics will be updated';
             $this->oController->report .= $message . ".\n";
             OA::debug($message, PEAR_LOG_INFO);
         }
         $this->oController->report .= "\n";
     } else {
         $message = "- Maintenance statistics will NOT be run";
         $this->oController->report .= $message . ".\n";
         OA::debug($message, PEAR_LOG_INFO);
         $this->oController->report .= "\n";
     }
 }
示例#16
0
 /**
  * A method to activate/deactivate campaigns, based on the date and/or the inventory
  * requirements (impressions, clicks and/or conversions). Also sends email reports
  * for any campaigns that are activated/deactivated, as well as sending email reports
  * for any campaigns that are likely to expire in the near future.
  *
  * @param Date $oDate The current date/time.
  * @return string Report on the campaigns activated/deactivated.
  */
 function manageCampaigns($oDate)
 {
     $aConf = $GLOBALS['_MAX']['CONF'];
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oEmail =& $oServiceLocator->get('OA_Email');
     if ($oEmail === false) {
         $oEmail = new OA_Email();
         $oServiceLocator->register('OA_Email', $oEmail);
     }
     $report = "\n";
     // Select all campaigns in the system, where:
     //    The campaign is ACTIVE and:
     //    - The end date stored for the campaign is not null; or
     //    - The campaign has a lifetime impression, click or conversion
     //      target set.
     //
     //    That is:
     //    - It is possible for the active campaign to be automatically
     //      stopped, as it has a valid end date. (No limitations are
     //      applied to those campaigns tested, as the ME may not have
     //      run for a while, and if so, even campaigns with an end date
     //      of many, many weeks ago should be tested to ensure they are
     //      [belatedly] halted.)
     //    - It is possible for the active campaign to be automatically
     //      stopped, as it has at leaast one lifetime target that could
     //      have been reached.
     //
     //    The campaign is INACTIVE and:
     //    - The start date stored for the campaign is not null; and
     //    - The weight is greater than zero; and
     //    - The end date stored for the campaign is either null, or is
     //      greater than "today" less one day.
     //
     //    That is:
     //    - It is possible for the inactive campaign to be automatically
     //      started, as it has a valid start date. (No limitations are
     //      applied to those campaigns tested, as the ME may not have run
     //      for a while, and if so, even campaigns with an activation date
     //      of many, many weeks ago should be tested to ensure they are
     //      [belatedy] enabled.)
     //    - The campaign is not in a permanently inactive state, as a
     //      result of the weight being less then one, which means that
     //      it cannot be activated.
     //    - The test to start the campaign is unlikely to fail on account
     //      of the end date. (Inactive campaigns with start dates may have
     //      passed the start date, but they may also have passed the end
     //      date - unfortunately, because the dates are not stored in UTC,
     //      it's not possible to know exactly which campaigns have passed
     //      the end date or not, until the values are converted to UTC based
     //      on the Advertiser Account timezone preference - so it's necessary
     //      to get some campaigns that might be passed the end date, and do
     //      the converstion to UTC and test to check.)
     $prefix = $this->getTablePrefix();
     $oYesterdayDate = new Date();
     $oYesterdayDate->copy($oDate);
     $oYesterdayDate->subtractSeconds(SECONDS_PER_DAY);
     $query = "\n            SELECT\n                cl.clientid AS advertiser_id,\n                cl.account_id AS advertiser_account_id,\n                cl.agencyid AS agency_id,\n                cl.contact AS contact,\n                cl.email AS email,\n                cl.reportdeactivate AS send_activate_deactivate_email,\n                ca.campaignid AS campaign_id,\n                ca.campaignname AS campaign_name,\n                ca.views AS targetimpressions,\n                ca.clicks AS targetclicks,\n                ca.conversions AS targetconversions,\n                ca.status AS status,\n                ca.activate AS start,\n                ca.expire AS end\n            FROM\n                {$prefix}campaigns AS ca,\n                {$prefix}clients AS cl\n            WHERE\n                ca.clientid = cl.clientid\n                AND\n                ca.status = " . $this->oDbh->quote(OA_ENTITY_STATUS_RUNNING, 'integer') . "\n                AND\n                (\n                    ca.expire " . OA_Dal::notEqualNoDateString() . "\n                    OR\n                    (\n                        ca.views > 0\n                        OR\n                        ca.clicks > 0\n                        OR\n                        ca.conversions > 0\n                    )\n                )\n            UNION ALL\n            SELECT\n                cl.clientid AS advertiser_id,\n                cl.account_id AS advertiser_account_id,\n                cl.agencyid AS agency_id,\n                cl.contact AS contact,\n                cl.email AS email,\n                cl.reportdeactivate AS send_activate_deactivate_email,\n                ca.campaignid AS campaign_id,\n                ca.campaignname AS campaign_name,\n                ca.views AS targetimpressions,\n                ca.clicks AS targetclicks,\n                ca.conversions AS targetconversions,\n                ca.status AS status,\n                ca.activate AS start,\n                ca.expire AS end\n            FROM\n                {$prefix}campaigns AS ca,\n                {$prefix}clients AS cl\n            WHERE\n                ca.clientid = cl.clientid\n                AND\n                ca.status != " . $this->oDbh->quote(OA_ENTITY_STATUS_RUNNING, 'integer') . "\n                AND\n                ca.activate " . OA_Dal::notEqualNoDateString() . "\n                AND\n                (\n                    ca.weight > 0\n                    OR\n                    ca.priority > 0\n                )\n                AND\n                (\n                    ca.expire >= " . $this->oDbh->quote($oYesterdayDate->format('%Y-%m-%d'), 'timestamp') . "\n                    OR\n                    ca.expire " . OA_Dal::equalNoDateString() . "\n                )\n            ORDER BY\n                advertiser_id";
     $rsResult = $this->oDbh->query($query);
     if (PEAR::isError($rsResult)) {
         return MAX::raiseError($rsResult, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
     }
     OA::debug('- Found ' . $rsResult->numRows() . ' campaigns to test for activation/deactivation', PEAR_LOG_DEBUG);
     while ($aCampaign = $rsResult->fetchRow()) {
         if ($aCampaign['status'] == OA_ENTITY_STATUS_RUNNING) {
             // The campaign is currently running, look at the campaign
             $disableReason = 0;
             $canExpireSoon = false;
             if ($aCampaign['targetimpressions'] > 0 || $aCampaign['targetclicks'] > 0 || $aCampaign['targetconversions'] > 0) {
                 // The campaign has an impression, click and/or conversion target,
                 // so get the sum total statistics for the campaign
                 $query = "\n                        SELECT\n                            SUM(dia.impressions) AS impressions,\n                            SUM(dia.clicks) AS clicks,\n                            SUM(dia.conversions) AS conversions\n                        FROM\n                            " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['data_intermediate_ad'], true) . " AS dia,\n                            " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['banners'], true) . " AS b\n                        WHERE\n                            dia.ad_id = b.bannerid\n                            AND b.campaignid = {$aCampaign['campaign_id']}";
                 $rsResultInner = $this->oDbh->query($query);
                 $valuesRow = $rsResultInner->fetchRow();
                 if (!is_null($valuesRow['impressions']) || !is_null($valuesRow['clicks']) || !is_null($valuesRow['conversions'])) {
                     // There were impressions, clicks and/or conversions for this
                     // campaign, so find out if campaign targets have been passed
                     if (is_null($valuesRow['impressions'])) {
                         // No impressions
                         $valuesRow['impressions'] = 0;
                     }
                     if (is_null($valuesRow['clicks'])) {
                         // No clicks
                         $valuesRow['clicks'] = 0;
                     }
                     if (is_null($valuesRow['conversions'])) {
                         // No conversions
                         $valuesRow['conversions'] = 0;
                     }
                     if ($aCampaign['targetimpressions'] > 0) {
                         if ($aCampaign['targetimpressions'] <= $valuesRow['impressions']) {
                             // The campaign has an impressions target, and this has been
                             // passed, so update and disable the campaign
                             $disableReason |= OX_CAMPAIGN_DISABLED_IMPRESSIONS;
                         }
                     }
                     if ($aCampaign['targetclicks'] > 0) {
                         if ($aCampaign['targetclicks'] <= $valuesRow['clicks']) {
                             // The campaign has a click target, and this has been
                             // passed, so update and disable the campaign
                             $disableReason |= OX_CAMPAIGN_DISABLED_CLICKS;
                         }
                     }
                     if ($aCampaign['targetconversions'] > 0) {
                         if ($aCampaign['targetconversions'] <= $valuesRow['conversions']) {
                             // The campaign has a target limitation, and this has been
                             // passed, so update and disable the campaign
                             $disableReason |= OX_CAMPAIGN_DISABLED_CONVERSIONS;
                         }
                     }
                     if ($disableReason) {
                         // One of the campaign targets was exceeded, so disable
                         $message = '- Exceeded a campaign quota: Deactivating campaign ID ' . "{$aCampaign['campaign_id']}: {$aCampaign['campaign_name']}";
                         OA::debug($message, PEAR_LOG_INFO);
                         $report .= $message . "\n";
                         $doCampaigns = OA_Dal::factoryDO('campaigns');
                         $doCampaigns->campaignid = $aCampaign['campaign_id'];
                         $doCampaigns->find();
                         $doCampaigns->fetch();
                         $doCampaigns->status = OA_ENTITY_STATUS_EXPIRED;
                         $result = $doCampaigns->update();
                         if ($result == false) {
                             return MAX::raiseError($rows, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
                         }
                         phpAds_userlogSetUser(phpAds_userMaintenance);
                         phpAds_userlogAdd(phpAds_actionDeactiveCampaign, $aCampaign['campaign_id']);
                     } else {
                         // The campaign didn't have a diable reason,
                         // it *might* possibly be diabled "soon"...
                         $canExpireSoon = true;
                     }
                 }
             }
             // Does the campaign need to be disabled due to the date?
             if ($aCampaign['end'] != OA_Dal::noDateValue()) {
                 // The campaign has a valid end date, stored in the timezone of the advertiser;
                 // create an end date in the advertiser's timezone, set the time, and then
                 // convert to UTC so that it can be compared with the MSE run time, which is
                 // in UTC
                 $aAdvertiserPrefs = OA_Preferences::loadAccountPreferences($aCampaign['advertiser_account_id'], true);
                 $oTimezone = new Date_Timezone($aAdvertiserPrefs['timezone']);
                 $oEndDate = new Date();
                 $oEndDate->convertTZ($oTimezone);
                 $oEndDate->setDate($aCampaign['end'] . ' 23:59:59');
                 // Campaigns end at the end of the day
                 $oEndDate->toUTC();
                 if ($oDate->after($oEndDate)) {
                     // The end date has been passed; disable the campaign
                     $disableReason |= OX_CAMPAIGN_DISABLED_DATE;
                     $message = "- Passed campaign end time of '{$aCampaign['end']} 23:59:59 {$aAdvertiserPrefs['timezone']} (" . $oEndDate->format('%Y-%m-%d %H:%M:%S') . ' ' . $oEndDate->tz->getShortName() . ")': Deactivating campaign ID {$aCampaign['campaign_id']}: {$aCampaign['campaign_name']}";
                     OA::debug($message, PEAR_LOG_INFO);
                     $report .= $message . "\n";
                     $doCampaigns = OA_Dal::factoryDO('campaigns');
                     $doCampaigns->campaignid = $aCampaign['campaign_id'];
                     $doCampaigns->find();
                     $doCampaigns->fetch();
                     $doCampaigns->status = OA_ENTITY_STATUS_EXPIRED;
                     $result = $doCampaigns->update();
                     if ($result == false) {
                         return MAX::raiseError($rows, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
                     }
                     phpAds_userlogSetUser(phpAds_userMaintenance);
                     phpAds_userlogAdd(phpAds_actionDeactiveCampaign, $aCampaign['campaign_id']);
                 } else {
                     // The campaign wasn't disabled based on the end
                     // date, to it *might* possibly be disabled "soon"...
                     $canExpireSoon = true;
                 }
             }
             if ($disableReason) {
                 // The campaign was disabled, so send the appropriate
                 // message to the campaign's contact
                 $query = "\n                        SELECT\n                            bannerid AS advertisement_id,\n                            description AS description,\n                            alt AS alt,\n                            url AS url\n                        FROM\n                            " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['banners'], true) . "\n                        WHERE\n                            campaignid = {$aCampaign['campaign_id']}";
                 OA::debug("- Getting the advertisements for campaign ID {$aCampaign['campaign_id']}", PEAR_LOG_DEBUG);
                 $rsResultAdvertisement = $this->oDbh->query($query);
                 if (PEAR::isError($rsResultAdvertisement)) {
                     return MAX::raiseError($rsResultAdvertisement, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
                 }
                 while ($advertisementRow = $rsResultAdvertisement->fetchRow()) {
                     $advertisements[$advertisementRow['advertisement_id']] = array($advertisementRow['description'], $advertisementRow['alt'], $advertisementRow['url']);
                 }
                 if ($aCampaign['send_activate_deactivate_email'] == 't') {
                     $oEmail->sendCampaignActivatedDeactivatedEmail($aCampaign['campaign_id'], $disableReason);
                 }
             } else {
                 if ($canExpireSoon) {
                     // The campaign has NOT been deactivated - test to see if it will
                     // be deactivated "soon", and send email(s) warning of this as required
                     $oEmail->sendCampaignImpendingExpiryEmail($oDate, $aCampaign['campaign_id']);
                 }
             }
         } else {
             // The campaign is not active - does it need to be enabled,
             // based on the campaign starting date?
             if ($aCampaign['start'] != OA_Dal::noDateValue()) {
                 // The campaign has a valid start date, stored in the timezone of the advertiser;
                 // create an end date in the advertiser's timezone, set the time, and then
                 // convert to UTC so that it can be compared with the MSE run time, which is
                 // in UTC
                 $aAdvertiserPrefs = OA_Preferences::loadAccountPreferences($aCampaign['advertiser_account_id'], true);
                 $oTimezone = new Date_Timezone($aAdvertiserPrefs['timezone']);
                 $oStartDate = new Date();
                 $oStartDate->convertTZ($oTimezone);
                 $oStartDate->setDate($aCampaign['start'] . ' 00:00:00');
                 // Campaigns start at the start of the day
                 $oStartDate->toUTC();
                 if ($aCampaign['end'] != OA_Dal::noDateValue()) {
                     // The campaign has a valid end date, stored in the timezone of the advertiser;
                     // create an end date in the advertiser's timezone, set the time, and then
                     // convert to UTC so that it can be compared with the MSE run time, which is
                     // in UTC
                     $oEndDate = new Date();
                     $oEndDate->convertTZ($oTimezone);
                     $oEndDate->setDate($aCampaign['end'] . ' 23:59:59');
                     // Campaign end at the end of the day
                     $oEndDate->toUTC();
                 } else {
                     $oEndDate = null;
                 }
                 if ($oDate->after($oStartDate)) {
                     // The start date has been passed; find out if there are any impression, click
                     // or conversion targets for the campaign (i.e. if the target values are > 0)
                     $remainingImpressions = 0;
                     $remainingClicks = 0;
                     $remainingConversions = 0;
                     if ($aCampaign['targetimpressions'] > 0 || $aCampaign['targetclicks'] > 0 || $aCampaign['targetconversions'] > 0) {
                         // The campaign has an impression, click and/or conversion target,
                         // so get the sum total statistics for the campaign so far
                         $query = "\n                                SELECT\n                                    SUM(dia.impressions) AS impressions,\n                                    SUM(dia.clicks) AS clicks,\n                                    SUM(dia.conversions) AS conversions\n                                FROM\n                                    " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['data_intermediate_ad'], true) . " AS dia,\n                                    " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['banners'], true) . " AS b\n                                WHERE\n                                    dia.ad_id = b.bannerid\n                                    AND b.campaignid = {$aCampaign['campaign_id']}";
                         $rsResultInner = $this->oDbh->query($query);
                         $valuesRow = $rsResultInner->fetchRow();
                         // Set the remaining impressions, clicks and conversions for the campaign
                         $remainingImpressions = $aCampaign['targetimpressions'] - $valuesRow['impressions'];
                         $remainingClicks = $aCampaign['targetclicks'] - $valuesRow['clicks'];
                         $remainingConversions = $aCampaign['targetconversions'] - $valuesRow['conversions'];
                     }
                     // In order for the campaign to be activated, need to test:
                     // 1) That there is no impression target (<= 0), or, if there is an impression target (> 0),
                     //    then there must be remaining impressions to deliver (> 0); and
                     // 2) That there is no click target (<= 0), or, if there is a click target (> 0),
                     //    then there must be remaining clicks to deliver (> 0); and
                     // 3) That there is no conversion target (<= 0), or, if there is a conversion target (> 0),
                     //    then there must be remaining conversions to deliver (> 0); and
                     // 4) Either there is no end date, or the end date has not been passed
                     if (($aCampaign['targetimpressions'] <= 0 || $aCampaign['targetimpressions'] > 0 && $remainingImpressions > 0) && ($aCampaign['targetclicks'] <= 0 || $aCampaign['targetclicks'] > 0 && $remainingClicks > 0) && ($aCampaign['targetconversions'] <= 0 || $aCampaign['targetconversions'] > 0 && $remainingConversions > 0) && (is_null($oEndDate) || $oEndDate->format('%Y-%m-%d') != OA_Dal::noDateValue() && Date::compare($oDate, $oEndDate) < 0)) {
                         $message = "- Passed campaign start time of '{$aCampaign['start']} 00:00:00 {$aAdvertiserPrefs['timezone']} (" . $oStartDate->format('%Y-%m-%d %H:%M:%S') . ' ' . $oStartDate->tz->getShortName() . ")': Activating campaign ID {$aCampaign['campaign_id']}: {$aCampaign['campaign_name']}";
                         OA::debug($message, PEAR_LOG_INFO);
                         $report .= $message . "\n";
                         $doCampaigns = OA_Dal::factoryDO('campaigns');
                         $doCampaigns->campaignid = $aCampaign['campaign_id'];
                         $doCampaigns->find();
                         $doCampaigns->fetch();
                         $doCampaigns->status = OA_ENTITY_STATUS_RUNNING;
                         $result = $doCampaigns->update();
                         if ($result == false) {
                             return MAX::raiseError($rows, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
                         }
                         phpAds_userlogSetUser(phpAds_userMaintenance);
                         phpAds_userlogAdd(phpAds_actionActiveCampaign, $aCampaign['campaign_id']);
                         // Get the advertisements associated with the campaign
                         $query = "\n                                SELECT\n                                    bannerid AS advertisement_id,\n                                    description AS description,\n                                    alt AS alt,\n                                    url AS url\n                                FROM\n                                    " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['banners'], true) . "\n                                WHERE\n                                    campaignid = {$aCampaign['campaign_id']}";
                         OA::debug("- Getting the advertisements for campaign ID {$aCampaign['campaign_id']}", PEAR_LOG_DEBUG);
                         $rsResultAdvertisement = $this->oDbh->query($query);
                         if (PEAR::isError($rsResultAdvertisement)) {
                             return MAX::raiseError($rsResultAdvertisement, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
                         }
                         while ($advertisementRow = $rsResultAdvertisement->fetchRow()) {
                             $advertisements[$advertisementRow['advertisement_id']] = array($advertisementRow['description'], $advertisementRow['alt'], $advertisementRow['url']);
                         }
                         if ($aCampaign['send_activate_deactivate_email'] == 't') {
                             $oEmail->sendCampaignActivatedDeactivatedEmail($aCampaign['campaign_id']);
                         }
                     }
                 }
             }
         }
     }
 }
 /**
  * The implementation of the OA_Task::run() method that performs
  * the required task of migrating bucket-based logged data to the
  * statistics table(s) specified by the appropriate plugin
  * components.
  */
 function run()
 {
     $aConf = $GLOBALS['_MAX']['CONF'];
     if ($this->oController->updateIntermediate) {
         // Locate all plugin components which may require bucket data to be
         // migrated from bucket tables to statistics tables
         $aSummariseComponents = $this->_locateComponents();
         // Are there any components that require data to be migrated?
         if (empty($aSummariseComponents)) {
             OA::debug('There are no installed plugins that require data migration', PEAR_LOG_DEBUG);
             return;
         }
         $message = '- Migrating bucket-based logged data to the statistics tables.';
         $this->oController->report .= $message . "\n";
         // Get the MSE DAL to perform the data migration
         $oServiceLocator =& OA_ServiceLocator::instance();
         $oDal =& $oServiceLocator->get('OX_Dal_Maintenance_Statistics');
         // Prepare the "now" date
         $oNowDate =& $oServiceLocator->get('now');
         if (!$oNowDate) {
             $oNowDate = new Date();
         }
         // Prepare an array of possible start and end dates for the migration, unless they have been set already
         if (empty($this->aRunDates)) {
             $this->aRunDates = array();
             $oStartDate = new Date();
             $oStartDate->copy($this->oController->oLastDateIntermediate);
             $oStartDate->addSeconds(1);
             while (Date::compare($oStartDate, $this->oController->oUpdateIntermediateToDate) < 0) {
                 // Calcuate the end of the operation interval
                 $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oStartDate);
                 $oEndDate = new Date();
                 $oEndDate->copy($aDates['end']);
                 // Store the dates
                 $oStoreStartDate = new Date();
                 $oStoreStartDate->copy($oStartDate);
                 $oStoreEndDate = new Date();
                 $oStoreEndDate->copy($oEndDate);
                 $this->aRunDates[] = array('start' => $oStoreStartDate, 'end' => $oStoreEndDate);
                 // Go to the next operation interval
                 $oStartDate->copy($oEndDate);
                 $oStartDate->addSeconds(1);
             }
         }
         // Check to see if any historical raw data needs to be migrated,
         // post-upgrade, and if so, migrate the data; requires that the
         // default openXDeliveryLog plugin is installed, so the migration
         // will not be called if it is not
         if (key_exists('openXDeliveryLog', $this->aPackages)) {
             $this->_postUpgrade();
         }
         // Prepare arrays of all of the migration maps of raw migrations
         $aRunComponents = $this->_prepareMaps($aSummariseComponents, 'raw');
         // Run each migration map separately, even if it's for the same table
         foreach ($aRunComponents as $statisticsTable => $aMaps) {
             foreach ($aMaps as $componentClassName => $aMigrationDetails) {
                 foreach ($this->aRunDates as $aDates) {
                     $message = "- Migrating raw bucket data from the '{$aMigrationDetails['bucketTable']}' bucket table";
                     OA::debug($message, PEAR_LOG_DEBUG);
                     $message = "  to the '{$statisticsTable}' table, for operation interval range";
                     OA::debug($message, PEAR_LOG_DEBUG);
                     $message = '  ' . $aDates['start']->format('%Y-%m-%d %H:%M:%S') . ' ' . $aDates['start']->tz->getShortName() . ' to ' . $aDates['end']->format('%Y-%m-%d %H:%M:%S') . ' ' . $aDates['end']->tz->getShortName();
                     OA::debug($message, PEAR_LOG_DEBUG);
                     $result = $oDal->summariseBucketsRaw($statisticsTable, $aMigrationDetails, $aDates);
                     if (PEAR::isError($result)) {
                         // Oh noz! The bucket data could not be migrated
                         // Tell the user all about it, but then just keep on truckin'...
                         $message = "   ERROR: Could not migrate raw bucket data from the '{$aMigrationDetails['bucketTable']}' bucket table";
                         OA::debug($message, PEAR_LOG_ERR);
                         $message = "   Error message was: {$result->message}";
                         OA::debug($message, PEAR_LOG_ERR);
                     } else {
                         $message = "  - Migrated {$result} row(s)";
                         OA::debug($message, PEAR_LOG_DEBUG);
                         $pruneResult = $aSummariseComponents[$statisticsTable][$componentClassName]->pruneBucket($aDates['end'], $aDates['start']);
                         if (PEAR::isError($pruneResult)) {
                             // Oh noz! The bucket data could not be pruned, and this is
                             // critical - if we can't prune the data, we'll end up double
                             // counting, so exit with a critical error...
                             $message = "   ERROR: Could not prune aggregate bucket data from the '" . $aSummariseComponents[$statisticsTable][$componentClassName]->getBucketName() . "' bucket table";
                             OA::debug($message, PEAR_LOG_CRIT);
                             $message = "   Error message was: {$pruneResult->message}";
                             OA::debug($message, PEAR_LOG_CRIT);
                             $message = "   Aborting maintenance execution";
                             OA::debug($message, PEAR_LOG_CRIT);
                             exit;
                         } else {
                             $message = "  - Pruned {$pruneResult} row(s)";
                             OA::debug($message, PEAR_LOG_DEBUG);
                         }
                     }
                 }
             }
         }
         // Prepare arrays of all of the migration maps of supplementary raw migrations
         $aRunComponents = $this->_prepareMaps($aSummariseComponents, 'rawSupplementary');
         // Run each migration map separately, even if it's for the same table
         foreach ($aRunComponents as $statisticsTable => $aMaps) {
             foreach ($aMaps as $componentClassName => $aMigrationDetails) {
                 foreach ($this->aRunDates as $aDates) {
                     $message = "- Migrating supplementary raw bucket data from the '{$aMigrationDetails['bucketTable']}' bucket table";
                     OA::debug($message, PEAR_LOG_DEBUG);
                     $message = "  to the '{$statisticsTable}' table, for operation interval range";
                     OA::debug($message, PEAR_LOG_DEBUG);
                     $message = '  ' . $aDates['start']->format('%Y-%m-%d %H:%M:%S') . ' ' . $aDates['start']->tz->getShortName() . ' to ' . $aDates['end']->format('%Y-%m-%d %H:%M:%S') . ' ' . $aDates['end']->tz->getShortName();
                     OA::debug($message, PEAR_LOG_DEBUG);
                     $result = $oDal->summariseBucketsRawSupplementary($statisticsTable, $aMigrationDetails, $aDates);
                     if (PEAR::isError($result)) {
                         // Oh noz! The bucket data could not be migrated
                         // Tell the user all about it, but then just keep on truckin'...
                         $message = "   ERROR: Could not migrate supplementary raw bucket data from the '{$aMigrationDetails['bucketTable']}' bucket table";
                         OA::debug($message, PEAR_LOG_ERR);
                         $message = "   Error message was: {$result->message}";
                         OA::debug($message, PEAR_LOG_ERR);
                     } else {
                         $message = "  - Migrated {$result} row(s)";
                         OA::debug($message, PEAR_LOG_DEBUG);
                         $pruneResult = $aSummariseComponents[$statisticsTable][$componentClassName]->pruneBucket($aDates['end'], $aDates['start']);
                         if (PEAR::isError($pruneResult)) {
                             // Oh noz! The bucket data could not be pruned, and this is
                             // critical - if we can't prune the data, we'll end up double
                             // counting, so exit with a critical error...
                             $message = "   ERROR: Could not prune aggregate bucket data from the '" . $aSummariseComponents[$statisticsTable][$componentClassName]->getBucketName() . "' bucket table";
                             OA::debug($message, PEAR_LOG_CRIT);
                             $message = "   Error message was: {$pruneResult->message}";
                             OA::debug($message, PEAR_LOG_CRIT);
                             $message = "   Aborting maintenance execution";
                             OA::debug($message, PEAR_LOG_CRIT);
                             exit;
                         } else {
                             $message = "  - Pruned {$pruneResult} row(s)";
                             OA::debug($message, PEAR_LOG_DEBUG);
                         }
                     }
                 }
             }
         }
         // Prepare arrays of all of the migration maps of aggregate migrations
         $aRunComponents = $this->_prepareMaps($aSummariseComponents, 'aggregate');
         // Run each migration map by statistics table
         foreach ($aRunComponents as $statisticsTable => $aMaps) {
             $aBucketTables = array();
             foreach ($aMaps as $aMap) {
                 $aBucketTables[] = $aMap['bucketTable'];
             }
             foreach ($this->aRunDates as $aDates) {
                 $aExtras = array();
                 // Is this the data_intermeidate_ad statistics table? It's special!
                 if ($statisticsTable == $aConf['table']['prefix'] . 'data_intermediate_ad') {
                     $aExtras = array('operation_interval' => $aConf['maintenance']['operationInterval'], 'operation_interval_id' => OX_OperationInterval::convertDateToOperationIntervalID($aDates['start']), 'interval_start' => $oDal->oDbh->quote($aDates['start']->format('%Y-%m-%d %H:%M:%S'), 'timestamp') . $oDal->timestampCastString, 'interval_end' => $oDal->oDbh->quote($aDates['end']->format('%Y-%m-%d %H:%M:%S'), 'timestamp') . $oDal->timestampCastString, 'creative_id' => 0, 'updated' => $oDal->oDbh->quote($oNowDate->format('%Y-%m-%d %H:%M:%S'), 'timestamp') . $oDal->timestampCastString);
                 }
                 $message = "- Migrating aggregate bucket data from the '" . implode("', '", $aBucketTables) . "' bucket table(s)";
                 OA::debug($message, PEAR_LOG_DEBUG);
                 $message = "  to the '{$statisticsTable}' table, for operation interval range";
                 OA::debug($message, PEAR_LOG_DEBUG);
                 $message = '  ' . $aDates['start']->format('%Y-%m-%d %H:%M:%S') . ' ' . $aDates['start']->tz->getShortName() . ' to ' . $aDates['end']->format('%Y-%m-%d %H:%M:%S') . ' ' . $aDates['end']->tz->getShortName();
                 OA::debug($message, PEAR_LOG_DEBUG);
                 $result = $oDal->summariseBucketsAggregate($statisticsTable, $aMaps, $aDates, $aExtras);
                 if (PEAR::isError($result)) {
                     // Oh noz! The bucket data could not be migrated
                     // Tell the user all about it, but then just keep on truckin'...
                     $message = "   ERROR: Could not migrate aggregate bucket data from the '" . implode("', '", $aBucketTables) . "' bucket table(s)";
                     OA::debug($message, PEAR_LOG_ERR);
                     $message = "   Error message was: {$result->message}";
                     OA::debug($message, PEAR_LOG_ERR);
                 } else {
                     $message = "  - Migrated {$result} row(s)";
                     OA::debug($message, PEAR_LOG_DEBUG);
                     foreach ($aMaps as $componentClassName => $aMap) {
                         $pruneResult = $aSummariseComponents[$statisticsTable][$componentClassName]->pruneBucket($aDates['end'], $aDates['start']);
                         if (PEAR::isError($pruneResult)) {
                             // Oh noz! The bucket data could not be pruned, and this is
                             // critical - if we can't prune the data, we'll end up double
                             // counting, so exit with a critical error...
                             $message = "   ERROR: Could not prune aggregate bucket data from the '" . $aSummariseComponents[$statisticsTable][$componentClassName]->getBucketName() . "' bucket table";
                             OA::debug($message, PEAR_LOG_CRIT);
                             $message = "   Error message was: {$pruneResult->message}";
                             OA::debug($message, PEAR_LOG_CRIT);
                             $message = "   Aborting maintenance execution";
                             OA::debug($message, PEAR_LOG_CRIT);
                             exit;
                         } else {
                             $message = "  - Pruned {$pruneResult} row(s)";
                             OA::debug($message, PEAR_LOG_DEBUG);
                         }
                     }
                 }
             }
         }
         // Prepare arrays of all of the migration maps of custom migrations
         // (If we refactor stats this will be the one and only method.)
         $aRunComponents = $this->_prepareMaps($aSummariseComponents, 'custom');
         // Run each migration map by statistics table
         foreach ($aRunComponents as $statisticsTable => $aMaps) {
             $aBucketTables = array();
             foreach ($aMaps as $aMap) {
                 $aBucketTables[] = $aMap['bucketTable'];
             }
             foreach ($this->aRunDates as $aDates) {
                 $aExtras = array();
                 $message = "- Migrating aggregate bucket data from the '" . implode("', '", $aBucketTables) . "' bucket table(s)";
                 OA::debug($message, PEAR_LOG_DEBUG);
                 $message = "  to the '{$statisticsTable}' table, for operation interval range";
                 OA::debug($message, PEAR_LOG_DEBUG);
                 $message = '  ' . $aDates['start']->format('%Y-%m%d %H:%M:%S') . ' ' . $aDates['start']->tz->getShortName() . ' to ' . $aDates['end']->format('%Y-%m%d %H:%M:%S') . ' ' . $aDates['end']->tz->getShortName();
                 OA::debug($message, PEAR_LOG_DEBUG);
                 // Call the components migrateStats method.
                 foreach ($aMaps as $componentClassName => $aMap) {
                     $result = $aSummariseComponents[$statisticsTable][$componentClassName]->migrateStatistics($aDates['end']);
                     if (PEAR::isError($result)) {
                         // Oh noz! The bucket data could not be migrated
                         // Tell the user all about it, but then just keep on truckin'...
                         $message = "   ERROR: Could not migrate aggregate bucket data from the '" . implode("', '", $aBucketTables) . "' bucket table(s)";
                         OA::debug($message, PEAR_LOG_ERR);
                         $message = "   Error message was: {$result->message}.";
                         OA::debug($message, PEAR_LOG_ERR);
                     } else {
                         // Only prune the bucket if we migrated the stats successfully.
                         $aSummariseComponents[$statisticsTable][$componentClassName]->pruneBucket($aDates['end'], $aDates['start']);
                     }
                 }
             }
         }
     }
     $this->aRunDates = array();
 }
示例#18
0
文件: Date.php 项目: mickdane/zidisha
 /**
  * Test if this date/time is exactly equal to a certian date/time
  *
  * Test if this date/time is exactly equal to a certian date/time
  *
  * @access public
  * @param object Date $when the date to test against
  * @return boolean true if this date is exactly equal to $when
  */
 function equals($when)
 {
     if (Date::compare($this, $when) == 0) {
         return true;
     } else {
         return false;
     }
 }
 /**
  * Compares two transactions according to $this->order.
  * 
  * For use with usort type of sort functions.
  * 
  * @param $aa object The first FinishedTransaction object.
  * @param $bb object The second FinishedTransaction object.
  * 
  * @return integer -1 if $aa is smaller than $bb, 0 if they are equal, 1 if $aa is bigger than $bb.
  */
 function transactionCompare($aa, $bb)
 {
     $tmp = 0;
     $default = 0;
     $repeatUnits = array('day' => 1, 'week' => 2, 'month' => 3, 'year' => 4);
     for ($run = 0; isset($this->order[$run]); $run++) {
         if ($this->order[$run]['dir'] == 'asc') {
             $a = $aa;
             $b = $bb;
             $default = -1;
         } else {
             $a = $bb;
             $b = $aa;
             $default = 1;
         }
         //echo "a: " . $a->getId() . "<br />";
         switch ($this->order[$run]['key']) {
             case 'transactionId':
             case 'plannedTransactionId':
             case 'finishedTransactionId':
                 $tmp = $a->getId() - $b->getId();
                 break;
             case 'type':
                 $tmp = strncasecmp($a->getType(), $b->getType(), 9999);
                 break;
             case 'title':
                 $tmp = strncasecmp($a->getTitle(), $b->getTitle(), 9999);
                 //echo $tmp;
                 break;
             case 'description':
                 $tmp = strncasecmp($a->getDescription(), $b->getDescription(), 9999);
                 break;
             case 'valutaDate':
                 if ($a->getValutaDate() && $b->getValutaDate()) {
                     $tmp = Date::compare($a->getValutaDate(), $b->getValutaDate());
                 } else {
                     if ($a->getValutaDate() && !$b->getValutaDate()) {
                         $tmp = 1;
                     } else {
                         if (!$a->getValutaDate() && $b->getValutaDate()) {
                             $tmp = -1;
                         }
                     }
                 }
                 break;
             case 'beginDate':
                 $tmp = Date::compare($a->getBeginDate(), $b->getBeginDate());
                 break;
             case 'endDate':
                 if ($a->getEndDate() && $b->getEndDate()) {
                     $tmp = Date::compare($a->getEndDate(), $b->getEndDate());
                 }
                 break;
             case 'amount':
                 $tmp = $a->getAmount()->compare($b->getAmount());
                 break;
             case 'outsideCapital':
                 $tmp = $a->getOutsideCapital()->sub($b->getOutsideCapital());
                 break;
             case 'transactionPartner':
                 $tmp = strncasecmp($a->getTransactionPartner(), $b->getTransactionPartner(), 9999);
                 break;
             case 'categoryId':
                 if ($a->getCategory() && $b->getCategory()) {
                     $tmp = $a->getCategory()->getId() - $b->getCategory()->getId();
                 } else {
                     if ($a->getCategory() && !$b->getCategory()) {
                         $tmp = -1;
                     } else {
                         if (!$a->getCategory() && $b->getCategory()) {
                             $tmp = 1;
                         }
                     }
                 }
                 break;
             case 'categoryTitle':
                 //echo "<pre>a: " . $a->getCategory() . " b: " . $b->getCategory();
                 if ($a->getCategory() && $b->getCategory()) {
                     $tmp = strncasecmp($a->getCategory()->getTitle(), $b->getCategory()->getTitle(), 9999);
                 } else {
                     if ($a->getCategory()) {
                         $tmp = -1;
                     } else {
                         if ($b->getCategory()) {
                             $tmp = 1;
                         }
                     }
                 }
                 //echo "tmp: $tmp</pre>";
                 break;
             case 'repeatUnit':
                 $tmp = $repeatUnits[$a->getRepeatUnit()] - $repeatUnits[$b->getRepeatUnit()];
                 break;
             case 'repeatFrequency':
                 $tmp = $a->getRepeatFrequency() - $b->getRepeatFrequency();
                 break;
             case 'sum':
                 $tmp = 0;
                 break;
         }
         if ($tmp != 0) {
             return $tmp;
         }
     }
     return $default;
 }
示例#20
0
    for ($i = 0, $xi = count(@$projects); $i < $xi; $i++) {
        //GT [BugFix]
        $p = $projects[$i];
        //GT
        $start = mb_substr($p['project_start_date'], 0, 10);
        $end = mb_substr($p['project_end_date'], 0, 10);
        $d_start->Date($start);
        $d_end->Date($end);
        if ($i == 0) {
            $min_d_start = $d_start;
            $max_d_end = $d_end;
        } else {
            if (Date::compare($min_d_start, $d_start) > 0) {
                $min_d_start = $d_start;
            }
            if (Date::compare($max_d_end, $d_end) < 0) {
                $max_d_end = $d_end;
            }
        }
    }
}
// check day_diff and modify Headers
$day_diff = $max_d_end->dateDiff($min_d_start);
if ($day_diff > 240) {
    //more than 240 days
    $graph->ShowHeaders(GANTT_HYEAR | GANTT_HMONTH);
} else {
    if ($day_diff > 90) {
        //more than 90 days and less of 241
        $graph->ShowHeaders(GANTT_HYEAR | GANTT_HMONTH | GANTT_HWEEK);
        $graph->scale->week->SetStyle(WEEKSTYLE_WNBR);
示例#21
0
 }
 //validar fechas
 if ($desde) {
     if (!contenido_estructura::isValidDate($desde)) {
         $errores[] = "INVALID_DESDE";
     }
 }
 if ($hasta) {
     if (!contenido_estructura::isValidDate($hasta)) {
         $errores[] = "INVALID_HASTA";
     }
 }
 if ($desde && $hasta) {
     //comparar las fechas desde y hasta
     //return int 0 if the dates are equal, -1 if d1 is before d2, 1 if d1 is after d2
     $res = Date::compare($desde, $hasta);
     if ($res == 1) {
         $errores[] = "INVALID_INTERVAL";
     }
 }
 if (count($errores) == 0) {
     $array_currencies = array();
     if ($values = $moneda->getChanges($desde, $hasta)) {
         //var_dump($values);
         $changes = array();
         $i = 0;
         foreach ($values as $v) {
             $changes[$i]['value'] = OOB_numeric::formatPrint($v['value']);
             $changes[$i]['date'] = $v['date'];
             $i++;
         }