示例#1
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;
 }
 /**
  * A method that uses the getAllCampaigns() method to obtain all campaigns
  * that meet the requirements of this class. That is:
  *
  * - The campaign has an expiration date (that is not already passed); and
  * - As a result of the above, the campaign must have an activation date that has
  *   passed, or has the default fake activation date; and
  * - The campaign is active, and has a priority of at least 1; and
  * - The campaign has inventory requirements for the duration of its activation.
  *
  * @access private
  * @return array An array of {@link OX_Maintenance_Priority_Campaign} objects.
  */
 function _getValidCampaigns()
 {
     $conf = $GLOBALS['_MAX']['CONF'];
     // Get current date
     $oDate = new Date($this->_getDate());
     $oDate->toUTC();
     $dateYMD = $oDate->getDate(DATE_FORMAT_ISO);
     $oDbh = OA_DB::singleton();
     $table = $oDbh->quoteIdentifier($conf['table']['prefix'] . $conf['table']['campaigns'], true);
     $aWheres = array(array("{$table}.priority >= 1", 'AND'), array("{$table}.status = " . OA_ENTITY_STATUS_RUNNING, 'AND'), array("{$table}.expire_time >= '{$dateYMD}'", 'AND'), array("({$table}.views > 0 OR {$table}.clicks > 0 OR {$table}.conversions > 0)", 'AND'));
     return $this->_getAllCampaigns($aWheres);
 }
示例#3
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;
 }
 /**
  * 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);
 }
/**
 * Processes submit values of campaign form
 *
 * @param OA_Admin_UI_Component_Form $form form to process
 * @return An array of Pear::Error objects if any
 */
function processCampaignForm($form, &$oComponent = null)
{
    $aFields = $form->exportValues();
    if (!empty($aFields['start'])) {
        $oDate = new Date(date('Y-m-d 00:00:00', strtotime($aFields['start'])));
        $oDate->toUTC();
        $activate = $oDate->getDate();
    } else {
        $oDate = new Date(date('Y-m-d 00:00:00'));
        $oDate->toUTC();
        $activate = $oDate->getDate();
    }
    if (!empty($aFields['end'])) {
        $oDate = new Date(date('Y-m-d 23:59:59', strtotime($aFields['end'])));
        $oDate->toUTC();
        $expire = $oDate->getDate();
    } else {
        $expire = null;
    }
    if (empty($aFields['campaignid'])) {
        // The form is submitting a new campaign, so, the ID is not set;
        // set the ID to the string "null" so that the table auto_increment
        // or sequence will be used when the campaign is created
        $aFields['campaignid'] = "null";
    } else {
        // The form is submitting a campaign modification; need to test
        // if any of the banners in the campaign are linked to an email zone,
        // and if so, if the link(s) would still be valid if the change(s)
        // to the campaign were made...
        $dalCampaigns = OA_Dal::factoryDAL('campaigns');
        $aCurrentLinkedEmalZoneIds = $dalCampaigns->getLinkedEmailZoneIds($aFields['campaignid']);
        if (PEAR::isError($aCurrentLinkedEmalZoneIds)) {
            OX::disableErrorHandling();
            $errors[] = PEAR::raiseError($GLOBALS['strErrorDBPlain']);
            OX::enableErrorHandling();
        }
        $errors = array();
        foreach ($aCurrentLinkedEmalZoneIds as $zoneId) {
            $thisLink = Admin_DA::_checkEmailZoneAdAssoc($zoneId, $aFields['campaignid'], $activate, $expire);
            if (PEAR::isError($thisLink)) {
                $errors[] = $thisLink;
                break;
            }
        }
    }
    //correct and check revenue and ecpm
    correctAdnCheckNumericFormField($aFields, $errors, 'revenue', $GLOBALS['strErrorEditingCampaignRevenue']);
    correctAdnCheckNumericFormField($aFields, $errors, 'ecpm', $GLOBALS['strErrorEditingCampaignECPM']);
    if (empty($errors)) {
        //check booked limits values
        // If this is a remnant, ecpm or exclusive campaign with an expiry date, set the target's to unlimited
        if (!empty($expire) && ($aFields['campaign_type'] == OX_CAMPAIGN_TYPE_REMNANT || $aFields['campaign_type'] == OX_CAMPAIGN_TYPE_ECPM || $aFields['campaign_type'] == OX_CAMPAIGN_TYPE_CONTRACT_EXCLUSIVE)) {
            $aFields['impressions'] = $aFields['clicks'] = $aFields['conversions'] = -1;
        } else {
            if (!empty($aFields['impr_unlimited']) && $aFields['impr_unlimited'] == 't') {
                $aFields['impressions'] = -1;
            } else {
                if (empty($aFields['impressions']) || $aFields['impressions'] == '-') {
                    $aFields['impressions'] = 0;
                }
            }
            if (!empty($aFields['click_unlimited']) && $aFields['click_unlimited'] == 't') {
                $aFields['clicks'] = -1;
            } else {
                if (empty($aFields['clicks']) || $aFields['clicks'] == '-') {
                    $aFields['clicks'] = 0;
                }
            }
            if (!empty($aFields['conv_unlimited']) && $aFields['conv_unlimited'] == 't') {
                $aFields['conversions'] = -1;
            } else {
                if (empty($aFields['conversions']) || $aFields['conversions'] == '-') {
                    $aFields['conversions'] = 0;
                }
            }
        }
        //pricing model - reset fields not applicable to model to 0,
        //note that in new flow MAX_FINANCE_CPA allows all limits to be set
        if ($aFields['revenue_type'] == MAX_FINANCE_CPM) {
            $aFields['clicks'] = -1;
            $aFields['conversions'] = -1;
        } else {
            if ($aFields['revenue_type'] == MAX_FINANCE_CPC) {
                $aFields['conversions'] = -1;
            } else {
                if ($aFields['revenue_type'] == MAX_FINANCE_MT) {
                    $aFields['impressions'] = -1;
                    $aFields['clicks'] = -1;
                    $aFields['conversions'] = -1;
                }
            }
        }
        //check type and set priority
        if ($aFields['campaign_type'] == OX_CAMPAIGN_TYPE_REMNANT) {
            $aFields['priority'] = 0;
            //low
        } else {
            if ($aFields['campaign_type'] == OX_CAMPAIGN_TYPE_CONTRACT_NORMAL) {
                $aFields['priority'] = isset($aFields['high_priority_value']) ? $aFields['high_priority_value'] : 5;
                //high
            } else {
                if ($aFields['campaign_type'] == OX_CAMPAIGN_TYPE_CONTRACT_EXCLUSIVE) {
                    $aFields['priority'] = -1;
                    //exclusive
                } else {
                    if ($aFields['campaign_type'] == OX_CAMPAIGN_TYPE_ECPM) {
                        $aFields['priority'] = -2;
                        //ecpm
                    }
                }
            }
        }
        // Set target
        $target_impression = 0;
        $target_click = 0;
        $target_conversion = 0;
        if ($aFields['priority'] > 0) {
            // Daily targets need to be set only if the campaign doesn't have both expiration and lifetime targets
            $hasExpiration = !empty($expire);
            $hasLifetimeTargets = $aFields['impressions'] != -1 || $aFields['clicks'] != -1 || $aFields['conversions'] != -1;
            if (!($hasExpiration && $hasLifetimeTargets) && isset($aFields['target_value']) && $aFields['target_value'] != '-') {
                switch ($aFields['target_type']) {
                    case 'target_impression':
                        $target_impression = $aFields['target_value'];
                        break;
                    case 'target_click':
                        $target_click = $aFields['target_value'];
                        break;
                    case 'target_conversion':
                        $target_conversion = $aFields['target_value'];
                        break;
                }
            }
            $aFields['weight'] = 0;
        } else {
            // Set weight
            if (!isset($aFields['weight']) || $aFields['weight'] == '-' || $aFields['weight'] == '') {
                $aFields['weight'] = 0;
            }
        }
        if ($aFields['anonymous'] != 't') {
            $aFields['anonymous'] = 'f';
        }
        if ($aFields['companion'] != 1) {
            $aFields['companion'] = 0;
        }
        if ($aFields['show_capped_no_cookie'] != 1) {
            $aFields['show_capped_no_cookie'] = 0;
        }
        $new_campaign = $aFields['campaignid'] == 'null';
        if (empty($aFields['revenue']) || $aFields['revenue'] <= 0) {
            // No revenue information, set to null
            $aFields['revenue'] = OX_DATAOBJECT_NULL;
        }
        if (empty($aFields['ecpm']) || $aFields['ecpm'] <= 0) {
            // No ecpm information, set to null
            $aFields['ecpm'] = OX_DATAOBJECT_NULL;
        }
        // Get the capping variables
        $block = _initCappingVariables($aFields['time'], $aFields['capping'], $aFields['session_capping']);
        $doCampaigns = OA_Dal::factoryDO('campaigns');
        $doCampaigns->campaignname = $aFields['campaignname'];
        $doCampaigns->clientid = $aFields['clientid'];
        $doCampaigns->views = $aFields['impressions'];
        $doCampaigns->clicks = $aFields['clicks'];
        $doCampaigns->conversions = $aFields['conversions'];
        $doCampaigns->priority = $aFields['priority'];
        $doCampaigns->weight = $aFields['weight'];
        $doCampaigns->target_impression = $target_impression;
        $doCampaigns->target_click = $target_click;
        $doCampaigns->target_conversion = $target_conversion;
        $doCampaigns->min_impressions = $aFields['min_impressions'];
        $doCampaigns->ecpm = $aFields['ecpm'];
        $doCampaigns->anonymous = $aFields['anonymous'];
        $doCampaigns->companion = $aFields['companion'];
        $doCampaigns->show_capped_no_cookie = $aFields['show_capped_no_cookie'];
        $doCampaigns->comments = $aFields['comments'];
        $doCampaigns->revenue = $aFields['revenue'];
        $doCampaigns->revenue_type = $aFields['revenue_type'];
        $doCampaigns->block = $block;
        $doCampaigns->capping = $aFields['capping'];
        $doCampaigns->session_capping = $aFields['session_capping'];
        // Activation and expiration
        $doCampaigns->activate_time = isset($activate) ? $activate : OX_DATAOBJECT_NULL;
        $doCampaigns->expire_time = isset($expire) ? $expire : OX_DATAOBJECT_NULL;
        if (!empty($aFields['campaignid']) && $aFields['campaignid'] != "null") {
            $doCampaigns->campaignid = $aFields['campaignid'];
            $doCampaigns->setEcpmEnabled();
            $doCampaigns->update();
        } else {
            $doCampaigns->setEcpmEnabled();
            $aFields['campaignid'] = $doCampaigns->insert();
        }
        if ($oComponent) {
            $oComponent->processCampaignForm($aFields);
        }
        // Recalculate priority only when editing a campaign
        // or moving banners into a newly created, and when:
        //
        // - campaign changes status (activated or deactivated) or
        // - the campaign is active and target/weight are changed
        //
        if (!$new_campaign) {
            $doCampaigns = OA_Dal::staticGetDO('campaigns', $aFields['campaignid']);
            $status = $doCampaigns->status;
            switch (true) {
                case (bool) $status != (bool) $aFields['status_old']:
                    // Run the Maintenance Priority Engine process
                    OA_Maintenance_Priority::scheduleRun();
                    break;
                case $status == OA_ENTITY_STATUS_RUNNING:
                    if (!empty($aFields['target_type']) && ${$aFields['target_type']} != $aFields['target_old'] || !empty($aFields['target_type']) && $aFields['target_type_old'] != $aFields['target_type'] || $aFields['weight'] != $aFields['weight_old'] || $aFields['clicks'] != $aFields['previousclicks'] || $aFields['conversions'] != $aFields['previousconversions'] || $aFields['impressions'] != $aFields['previousimpressions']) {
                        // Run the Maintenance Priority Engine process
                        OA_Maintenance_Priority::scheduleRun();
                    }
                    break;
            }
        }
        // Rebuild cache
        // include_once MAX_PATH . '/lib/max/deliverycache/cache-'.$conf['delivery']['cache'].'.inc.php';
        // phpAds_cacheDelete();
        // Delete channel forecasting cache
        include_once 'Cache/Lite.php';
        $options = array('cacheDir' => MAX_CACHE);
        $cache = new Cache_Lite($options);
        $group = 'campaign_' . $aFields['campaignid'];
        $cache->clean($group);
        $translation = new OX_Translation();
        if ($new_campaign) {
            // Queue confirmation message
            $translated_message = $translation->translate($GLOBALS['strCampaignHasBeenAdded'], array(MAX::constructURL(MAX_URL_ADMIN, 'campaign-edit.php?clientid=' . $aFields['clientid'] . '&campaignid=' . $aFields['campaignid']), htmlspecialchars($aFields['campaignname']), MAX::constructURL(MAX_URL_ADMIN, 'banner-edit.php?clientid=' . $aFields['clientid'] . '&campaignid=' . $aFields['campaignid'])));
            OA_Admin_UI::queueMessage($translated_message, 'local', 'confirm', 0);
            OX_Admin_Redirect::redirect("advertiser-campaigns.php?clientid=" . $aFields['clientid']);
        } else {
            $translated_message = $translation->translate($GLOBALS['strCampaignHasBeenUpdated'], array(MAX::constructURL(MAX_URL_ADMIN, 'campaign-edit.php?clientid=' . $aFields['clientid'] . '&campaignid=' . $aFields['campaignid']), htmlspecialchars($aFields['campaignname'])));
            OA_Admin_UI::queueMessage($translated_message, 'local', 'confirm', 0);
            OX_Admin_Redirect::redirect("campaign-edit.php?clientid=" . $aFields['clientid'] . "&campaignid=" . $aFields['campaignid']);
        }
    }
    //return processing errors
    return $errors;
}
示例#6
0
 /**
  * A method to get the details of the total number of advertisements
  * delivered, today, for a specified placement.
  *
  * @param integer $id The placement ID.
  * @param string $today A "CCYY-MM-DD" formatted representation of today's date.
  * @return array An array of arrays, with each containing the "placement_id",
  *               "sum_requests", "sum_views", "sum_clicks" and "sum_conversions"
  *               for that placement.
  */
 function getCampaignDeliveryToday($id, $today)
 {
     $tz = $this->getTimezoneForCampaign($id);
     $oStartDate = new Date($today);
     $oStartDate->setTZ($tz);
     $oStartDate->setHour(0);
     $oStartDate->setMinute(0);
     $oStartDate->setSecond(0);
     $oStartDate->toUTC();
     $oEndDate = new Date($today);
     $oEndDate->setTZ($tz);
     $oEndDate->setHour(23);
     $oEndDate->setMinute(59);
     $oEndDate->setSecond(59);
     $oEndDate->toUTC();
     $aConf = $GLOBALS['_MAX']['CONF'];
     $query = array();
     $table = $this->_getTablenameUnquoted('campaigns');
     $joinTable1 = $this->_getTablenameUnquoted('banners');
     $joinTable2 = $this->_getTablenameUnquoted('data_intermediate_ad');
     $query['table'] = $table;
     $query['fields'] = array("SUM({$joinTable2}.requests) AS sum_requests", "SUM({$joinTable2}.impressions) AS sum_views", "SUM({$joinTable2}.clicks) AS sum_clicks", "SUM({$joinTable2}.conversions) AS sum_conversions", "{$table}.campaignid AS placement_id");
     $query['wheres'] = array(array("{$table}.campaignid = {$id}", 'AND'));
     $query['joins'] = array(array($joinTable1, "{$table}.campaignid = {$joinTable1}.campaignid"), array($joinTable2, "{$joinTable1}.bannerid = {$joinTable2}.ad_id AND {$joinTable2}.date_time >= '" . $oStartDate->format('%Y-%m-%d %H:%M:%S') . "' AND {$joinTable2}.date_time <= '" . $oEndDate->format('%Y-%m-%d %H:%M:%S') . "'"));
     $query['group'] = "placement_id";
     return $this->_get($query);
 }
 /**
  * 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);
 }
示例#8
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']);
                         }
                     }
                 }
             }
         }
     }
 }
 // Connection was changed to conversion (or conversion was changed to connection)
 $aConVariables = Admin_DA::fromCache('getConnectionVariables', $conversionId);
 // Sum up basket values
 $basketValue = 0;
 $numItems = 0;
 foreach ($aConVariables as $conVariable) {
     if ($conVariable['purpose'] == 'basket_value') {
         $basketValue += $conVariable['value'];
     } elseif ($conVariable['purpose'] == 'num_items') {
         $numItems += $conVariable['value'];
     }
 }
 // Get day, $hour and operation interval
 $dateTime = $aConversions[$conversionId]['date_time'];
 $oConnectionDate = new Date($dateTime);
 $oConnectionDate->toUTC();
 $optIntID = OX_OperationInterval::convertDateToOperationIntervalID($oConnectionDate);
 $opDay = $oConnectionDate->format('%Y-%m-%d');
 $opHour = $oConnectionDate->format('%H');
 // Get ad_id, creative_id and zone_id
 $ad_id = $aConversions[$conversionId]['ad_id'];
 $creative_id = $aConversions[$conversionId]['creative_id'];
 $zone_id = $aConversions[$conversionId]['zone_id'];
 $operation = null;
 // If conversion was changed to connection
 if ($aConversions[$conversionId]['connection_status'] == MAX_CONNECTION_STATUS_APPROVED) {
     // Substract conversion from "data_intermediate_ad" and from "data_summary_ad_hourly"
     // and remove $connectionBasketValue from total_basket_value
     $operation = '-';
 }
 // If connection was changed to conversion
示例#10
0
 /**
  * A method to check if the campaign is expired
  *
  * @return bool
  */
 function _isExpired()
 {
     static $oServiceLocator;
     if (!empty($this->expire_time) && $this->expire_time != OX_DATAOBJECT_NULL) {
         if (!isset($oServiceLocator)) {
             $oServiceLocator =& OA_ServiceLocator::instance();
         }
         if (!($oNow = $oServiceLocator->get('now'))) {
             $oNow = new Date();
         }
         $oNow->toUTC();
         $oExpire = new Date($this->expire_time);
         $oExpire->setTZbyID('UTC');
         if ($oNow->after($oExpire)) {
             return true;
         }
     }
     return false;
 }
示例#11
0
 /**
  * Add the fields needed for conversions stats
  *
  * @param array Row of stats
  * @param string Invocated method
  * @param array Parameter array
  * @param array Empty row
  */
 function mergeConversions(&$aRows, $method, $aParams, $emptyRow)
 {
     $conf = $GLOBALS['_MAX']['CONF'];
     $aParams['include'] = isset($aParams['include']) ? array_flip($aParams['include']) : array();
     $aParams['exclude'] = isset($aParams['exclude']) ? array_flip($aParams['exclude']) : array();
     // Primary key
     if ($method == 'getEntitiesStats') {
         if (!isset($aParams['exclude']['ad_id']) && !isset($aParams['exclude']['zone_id'])) {
             $aFields[] = "CONCAT(diac.ad_id, '_', diac.zone_id) AS pkey";
         } elseif (!isset($aParams['exclude']['ad_id'])) {
             $aFields[] = "diac.ad_id AS pkey";
         } else {
             $aFields[] = "diac.zone_id AS pkey";
         }
     } else {
         $aParams['exclude']['ad_id'] = true;
         $aParams['exclude']['zone_id'] = true;
         if ($method == 'getDayHistory') {
             $tzMethod = 'format';
             $tzArgs = array('%Y-%m-%d');
         } elseif ($method == 'getMonthHistory') {
             $tzMethod = 'format';
             $tzArgs = array('%Y-%m');
         } elseif ($method == 'getDayOfWeekHistory') {
             $tzMethod = 'getDayOfWeek';
             $tzArgs = array();
         } elseif ($method == 'getHourHistory') {
             $tzMethod = 'getHour';
             $tzArgs = array();
         }
         $aFields[] = "DATE_FORMAT(diac.tracker_date_time, '%Y-%m-%d %H:00:00') AS day_and_hour";
         $aGroupBy = array('day_and_hour');
     }
     $aFrom = array("{$conf['table']['prefix']}{$conf['table']['data_intermediate_ad_connection']} diac");
     $aWhere = array("diac.inside_window = 1");
     $aFields[] = "SUM(IF(diac.connection_status = " . MAX_CONNECTION_STATUS_APPROVED . " AND diac.connection_action = " . MAX_CONNECTION_AD_IMPRESSION . ",1,0)) AS sum_conversions_" . MAX_CONNECTION_AD_IMPRESSION;
     $aFields[] = "SUM(IF(diac.connection_status = " . MAX_CONNECTION_STATUS_APPROVED . " AND diac.connection_action = " . MAX_CONNECTION_AD_CLICK . ",1,0)) AS sum_conversions_" . MAX_CONNECTION_AD_CLICK;
     $aFields[] = "SUM(IF(diac.connection_status = " . MAX_CONNECTION_STATUS_APPROVED . " AND diac.connection_action = " . MAX_CONNECTION_AD_ARRIVAL . ",1,0)) AS sum_conversions_" . MAX_CONNECTION_AD_ARRIVAL;
     $aFields[] = "SUM(IF(diac.connection_status = " . MAX_CONNECTION_STATUS_APPROVED . " AND diac.connection_action = " . MAX_CONNECTION_MANUAL . ",1,0)) AS sum_conversions_" . MAX_CONNECTION_MANUAL;
     $aFields[] = "SUM(IF(diac.connection_status = " . MAX_CONNECTION_STATUS_APPROVED . ",1,0)) AS sum_conversions";
     $aFields[] = "SUM(IF(diac.connection_status = " . MAX_CONNECTION_STATUS_PENDING . ",1,0)) AS sum_conversions_pending";
     if (!empty($aParams['day_begin']) && !empty($aParams['day_end'])) {
         $oStartDate = new Date("{$aParams['day_begin']} 00:00:00");
         $oEndDate = new Date("{$aParams['day_end']} 23:59:59");
         $oStartDate->toUTC();
         $oEndDate->toUTC();
         $aWhere[] = "diac.tracker_date_time BETWEEN '" . $oStartDate->format('%Y-%m-%d %H:%M:%S') . "'" . " AND '" . $oEndDate->format('%Y-%m-%d %H:%M:%S') . "'";
     }
     if (!empty($aParams['agency_id'])) {
         $aFrom['b'] = "JOIN {$conf['table']['prefix']}{$conf['table']['banners']} b ON (b.bannerid = diac.ad_id)";
         $aFrom['m'] = "JOIN {$conf['table']['prefix']}{$conf['table']['campaigns']} m ON (m.campaignid = b.campaignid)";
         $aFrom['c'] = "JOIN {$conf['table']['prefix']}{$conf['table']['clients']} c ON (c.clientid = m.clientid)";
         $aFrom['z'] = "LEFT JOIN {$conf['table']['prefix']}{$conf['table']['zones']} z ON (z.zoneid = diac.zone_id)";
         $aFrom['p'] = "LEFT JOIN {$conf['table']['prefix']}{$conf['table']['affiliates']} p ON (p.affiliateid = z.affiliateid AND p.agencyid = '{$aParams['agency_id']}')";
         $aWhere[] = "c.agencyid = '{$aParams['agency_id']}'";
     }
     if (!empty($aParams['advertiser_id']) || isset($aParams['include']['advertiser_id'])) {
         $aFrom['b'] = "JOIN {$conf['table']['prefix']}{$conf['table']['banners']} b ON (b.bannerid = diac.ad_id)";
         $aFrom['m'] = "JOIN {$conf['table']['prefix']}{$conf['table']['campaigns']} m ON (m.campaignid = b.campaignid)";
         if (!empty($aParams['advertiser_id'])) {
             $aWhere[] = "m.clientid = '{$aParams['advertiser_id']}'";
         }
         if (isset($aParams['include']['advertiser_id']) && !isset($aParams['exclude']['advertiser_id'])) {
             $aFields[] = "m.clientid AS advertiser_id";
             $aGroupBy[] = "advertiser_id";
         }
     }
     if (!empty($aParams['placement_id']) || isset($aParams['include']['placement_id'])) {
         $aFrom['b'] = "JOIN {$conf['table']['prefix']}{$conf['table']['banners']} b ON (b.bannerid = diac.ad_id)";
         if (!empty($aParams['placement_id'])) {
             $aWhere[] = "b.campaignid = '{$aParams['placement_id']}'";
         }
         if (isset($aParams['include']['placement_id']) && !isset($aParams['exclude']['placement_id'])) {
             $aFields[] = "b.campaignid AS placement_id";
             $aGroupBy[] = "placement_id";
         }
     }
     if (!empty($aParams['publisher_id']) || isset($aParams['include']['publisher_id'])) {
         $aFrom['z'] = "JOIN {$conf['table']['prefix']}{$conf['table']['zones']} z ON (z.zoneid = diac.zone_id)";
         if (!empty($aParams['publisher_id'])) {
             $aWhere[] = "z.affiliateid = '{$aParams['publisher_id']}'";
         }
         if (isset($aParams['include']['publisher_id']) && !isset($aParams['exclude']['publisher_id'])) {
             $aFields[] = "z.affiliateid AS publisher_id";
             $aGroupBy[] = "publisher_id";
         }
     }
     if (!empty($aParams['ad_id'])) {
         $aWhere[] = "diac.ad_id = '{$aParams['ad_id']}'";
     }
     if (!isset($aParams['exclude']['ad_id'])) {
         $aFields[] = "diac.ad_id AS ad_id";
         $aGroupBy[] = "ad_id";
     }
     // Using isset: zone_id could be 0 in case of direct selection
     if (isset($aParams['zone_id'])) {
         $aWhere[] = "diac.zone_id = '{$aParams['zone_id']}'";
     }
     if (!isset($aParams['exclude']['zone_id'])) {
         $aFields[] = "diac.zone_id AS zone_id";
         $aGroupBy[] = "zone_id";
     }
     $sFields = count($aFields) ? join(', ', $aFields) : '';
     $sFrom = count($aFrom) ? join(' ', $aFrom) : '';
     $sWhere = count($aWhere) ? 'WHERE ' . join(' AND ', $aWhere) : '';
     $sGroupBy = count($aGroupBy) ? 'GROUP BY ' . join(', ', $aGroupBy) : '';
     $query = "SELECT " . $sFields . " FROM " . $sFrom . " " . $sWhere . " " . $sGroupBy;
     $oDbh = OA_DB::singleton();
     $key = $method == 'getEntitiesStats' ? 'pkey' : 'day_and_hour';
     $oRes = $oDbh->query($query);
     $aResult = array();
     if (!PEAR::isError($oRes)) {
         while ($row = $oRes->fetchRow()) {
             $aResult[$row[$key]] = $row;
             unset($aResult[$row[$key]][$key]);
         }
     }
     if ($method != 'getEntitiesStats') {
         $aResult = Admin_DA::_convertStatsArrayToTz($aResult, $aParams, null, $tzMethod, $tzArgs);
     }
     foreach ($aResult as $k => $row) {
         if (!isset($aRows[$k])) {
             $aRows[$k] = $emptyRow;
         }
         foreach ($row as $field => $value) {
             if (!isset($aRows[$k][$field])) {
                 $aRows[$k][$field] = $value;
             }
         }
     }
 }
 function test_getAuditLogForAuditWidget()
 {
     $dllAuditPartialMock = new PartialMockOA_Dll_Audit($this);
     $oSpanDay = new Date_Span('1-0-0-0');
     $oDate = new Date(OA::getNow());
     $oDate->toUTC();
     $oDate->subtractSpan(new Date_Span('8-0-0-0'));
     // add 1 hour to make sure that the test passes even if it takes some time
     $oDate->addSpan(new Date_Span('0-1-0-0'));
     // record 1 - more than 7 days old so should not be returned
     $oAudit = OA_Dal::factoryDO('audit');
     $oAudit->account_id = 1;
     $oAudit->context = 'campaigns';
     $oAudit->contextid = 1;
     $oAudit->parentid = null;
     $oAudit->username = '******';
     $oAudit->actionid = OA_AUDIT_ACTION_UPDATE;
     $oAudit->updated = $oDate->getDate();
     $aDetails['campaignname'] = 'Campaign 1';
     $aDetails['status'] = OA_ENTITY_STATUS_EXPIRED;
     $oAudit->details = serialize($aDetails);
     $oAudit->insert();
     // record 2
     $oDate->addSpan($oSpanDay);
     $oAudit->updated = $oDate->getDate();
     $oAudit->username = '******';
     $aDetails['status'] = OA_ENTITY_STATUS_RUNNING;
     $oAudit->details = serialize($aDetails);
     $idAudit = $oAudit->insert();
     $aExpect[$idAudit] = $oAudit->toArray();
     $aExpect[$idAudit]['details'] = $aDetails;
     // record 3
     $oDate->addSpan($oSpanDay);
     $oAudit->updated = $oDate->getDate();
     $oAudit->username = '******';
     $aDetails['status'] = OA_ENTITY_STATUS_PAUSED;
     $oAudit->details = serialize($aDetails);
     $idAudit = $oAudit->insert();
     $aExpect[$idAudit] = $oAudit->toArray();
     $aExpect[$idAudit]['details'] = $aDetails;
     // record 4
     $oDate->addSpan($oSpanDay);
     $oAudit->contextid = 2;
     $oAudit->updated = $oDate->getDate();
     $aDetails['campaignname'] = 'Campaign 2';
     $aDetails['status'] = OA_ENTITY_STATUS_RUNNING;
     $oAudit->details = serialize($aDetails);
     $idAudit = $oAudit->insert();
     $aExpect[$idAudit] = $oAudit->toArray();
     $aExpect[$idAudit]['details'] = $aDetails;
     // record 5
     $oDate->addSpan($oSpanDay);
     $oAudit->updated = $oDate->getDate();
     $oAudit->username = '******';
     $aDetails['status'] = OA_ENTITY_STATUS_EXPIRED;
     $oAudit->details = serialize($aDetails);
     $idAudit = $oAudit->insert();
     $aExpect[$idAudit] = $oAudit->toArray();
     $aExpect[$idAudit]['details'] = $aDetails;
     // record 6
     $oDate->addSpan($oSpanDay);
     $oAudit->account_id = 2;
     $oAudit->contextid = 3;
     $oAudit->username = '******';
     $oAudit->updated = $oDate->getDate();
     $aDetails['campaignname'] = 'Campaign 3';
     $aDetails['status'] = OA_ENTITY_STATUS_RUNNING;
     $oAudit->details = serialize($aDetails);
     $idAudit = $oAudit->insert();
     $aExpect[$idAudit] = $oAudit->toArray();
     $aExpect[$idAudit]['details'] = $aDetails;
     // record 7 - is a maintenance audit rec so should not be returned
     $oDate->addSpan($oSpanDay);
     $oAudit->username = '******';
     $oAudit->contextid = 1;
     $oAudit->updated = $oDate->getDate();
     $aDetails['campaignname'] = 'Campaign 1';
     $aDetails['status'] = OA_ENTITY_STATUS_RUNNING;
     $oAudit->details = serialize($aDetails);
     $oAudit->insert();
     $aParams = array();
     $aResults = $dllAuditPartialMock->getAuditLogForAuditWidget($aParams);
     $this->assertIsA($aResults, 'array');
     $this->assertEqual(count($aResults), 5);
     foreach ($aResults as $i => $aResRow) {
         $aExpRow = $aExpect[$aResRow['auditid']];
         $this->assertEqual($aResRow['auditid'], $aExpRow['auditid']);
         $this->assertEqual($aResRow['actionid'], $aExpRow['actionid']);
         $this->assertEqual($aResRow['context'], $dllAuditPartialMock->getContextDescription($aExpRow['context']));
         $this->assertEqual($aResRow['contextid'], $aExpRow['contextid']);
         $this->assertEqual($aResRow['parentid'], $aExpRow['parentid']);
         $this->assertEqual($aResRow['username'], $aExpRow['username']);
         $this->assertEqual($aResRow['details']['campaignname'], $aExpRow['details']['campaignname']);
         $this->assertEqual($aResRow['details']['status'], $aExpRow['details']['status']);
         $oDate = new Date($aResRow['updated']);
         $oDate->toUTC();
         $this->assertEqual($oDate->getDate(), $aExpRow['updated']);
     }
     // Check that the account_id filter is working
     $aParams = array('account_id' => 2);
     $aResults = $dllAuditPartialMock->getAuditLogForAuditWidget($aParams);
     $this->assertIsA($aResults, 'array');
     $this->assertEqual(count($aResults), 1);
 }
 function _convertDate($date, $tz, $end)
 {
     if (empty($date) || $date == '0000-00-00') {
         return null;
     }
     $oDate = new Date($date);
     $oDate->setTZByID($tz);
     if ($end) {
         $oDate->setHour(23);
         $oDate->setMinute(59);
         $oDate->setSecond(59);
     }
     $oDate->toUTC();
     return $oDate->getDate(DATE_FORMAT_ISO);
 }
示例#14
0
 /**
  * Returns the data used by the weekly report.
  *
  * @access  public
  * @param   string $usr_id The ID of the user this report is for.
  * @param   string The start date of this report.
  * @param   string The end date of this report.
  * @param   boolean If closed issues should be separated from other issues.
  * @return  array An array of data containing all the elements of the weekly report.
  */
 function getWeeklyReport($usr_id, $start, $end, $separate_closed = false)
 {
     $usr_id = Misc::escapeInteger($usr_id);
     // figure out timezone
     $user_prefs = Prefs::get($usr_id);
     $tz = @$user_prefs["timezone"];
     $start_dt = new Date();
     $end_dt = new Date();
     // set timezone to that of user.
     $start_dt->setTZById($tz);
     $end_dt->setTZById($tz);
     // set the dates in the users time zone
     $start_dt->setDate($start . " 00:00:00");
     $end_dt->setDate($end . " 23:59:59");
     // convert time to GMT
     $start_dt->toUTC();
     $end_dt->toUTC();
     $start_ts = $start_dt->getDate();
     $end_ts = $end_dt->getDate();
     $time_tracking = Time_Tracking::getSummaryByUser($usr_id, $start_ts, $end_ts);
     // replace spaces in index with _ and calculate total time
     $total_time = 0;
     foreach ($time_tracking as $category => $data) {
         unset($time_tracking[$category]);
         $time_tracking[str_replace(" ", "_", $category)] = $data;
         $total_time += $data["total_time"];
     }
     // get count of issues assigned in week of report.
     $stmt = "SELECT\n                    COUNT(*)\n                 FROM\n                    " . APP_DEFAULT_DB . "." . APP_TABLE_PREFIX . "issue,\n                    " . APP_DEFAULT_DB . "." . APP_TABLE_PREFIX . "issue_user,\n                    " . APP_DEFAULT_DB . "." . APP_TABLE_PREFIX . "status\n                 WHERE\n                    iss_id = isu_iss_id AND\n                    iss_sta_id = sta_id AND\n                    isu_usr_id = {$usr_id} AND\n                    isu_assigned_date BETWEEN '{$start_ts}' AND '{$end_ts}'";
     $newly_assigned = $GLOBALS["db_api"]->dbh->getOne($stmt);
     if (PEAR::isError($newly_assigned)) {
         Error_Handler::logError(array($newly_assigned->getMessage(), $newly_assigned->getDebugInfo()), __FILE__, __LINE__);
     }
     $email_count = array("associated" => Support::getSentEmailCountByUser($usr_id, $start_ts, $end_ts, true), "other" => Support::getSentEmailCountByUser($usr_id, $start_ts, $end_ts, false));
     $data = array("start" => str_replace('-', '.', $start), "end" => str_replace('-', '.', $end), "user" => User::getDetails($usr_id), "group_name" => Group::getName(User::getGroupID($usr_id)), "issues" => History::getTouchedIssuesByUser($usr_id, $start_ts, $end_ts, $separate_closed), "status_counts" => History::getTouchedIssueCountByStatus($usr_id, $start_ts, $end_ts), "new_assigned_count" => $newly_assigned, "time_tracking" => $time_tracking, "email_count" => $email_count, "phone_count" => Phone_Support::getCountByUser($usr_id, $start_ts, $end_ts), "note_count" => Note::getCountByUser($usr_id, $start_ts, $end_ts), "total_time" => Misc::getFormattedTime($total_time, false));
     return $data;
 }
示例#15
0
 /**
  * requires permission checks
  *
  * @param array $aParam
  * @return array
  */
 function getAuditLogForAuditWidget($aParam = array())
 {
     $oAudit = OA_Dal::factoryDO('audit');
     // Apply account level filters
     if (!empty($aParam['account_id'])) {
         $oAudit->account_id = $aParam['account_id'];
     }
     if (!empty($aParam['advertiser_account_id'])) {
         $oAudit->advertiser_account_id = $aParam['advertiser_account_id'];
     }
     if (!empty($aParam['website_account_id'])) {
         $oAudit->website_account_id = $aParam['website_account_id'];
     }
     $oDate = new Date();
     $oDate->toUTC();
     $oDate->subtractSpan(new Date_Span('7-0-0-0'));
     $oAudit->whereAdd("username <> 'Maintenance'");
     $oAudit->whereAdd('parentid IS NULL');
     $oAudit->whereAdd("updated >= " . DBC::makeLiteral($oDate->format('%Y-%m-%d %H:%M:%S')));
     $oAudit->orderBy('auditid DESC');
     $oAudit->limit(0, 5);
     $numRows = $oAudit->find();
     $oNow = new Date();
     $aResult = array();
     while ($oAudit->fetch()) {
         $aAudit = $oAudit->toArray();
         $oDate = new Date($aAudit['updated']);
         $oDate->setTZbyID('UTC');
         $oDate->convertTZ($oNow->tz);
         $aAudit['updated'] = $oDate->format('%Y-%m-%d %H:%M:%S');
         $aAudit['details'] = unserialize($aAudit['details']);
         $aAudit['context'] = $this->getContextDescription($aAudit['context']);
         $aResult[] = $aAudit;
     }
     return $aResult;
 }
 /**
  * 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'));
 }
示例#17
0
 /**
  * A private method to prepare the statistics part of the body of an
  * advertiser's "campaign delivery" report email.
  *
  * @access private
  * @param integer    $advertiserId The advertiser's ID.
  * @param Date $oStartDate   The start date of the report, inclusive.
  * @param Date $oEndDate     The end date of the report, inclusive.
  * @param string     $type         One of "impressions", "clicks" or "conversions".
  * @param string     $adTextPrint  An sprintf compatible formatting string for use
  *                                 with the $strTotalThisPeriod global string.
  * @return an array with
  *      'body'      => string The ad statistics part of the report.
  *      'adviews'   => int    Adviews in this period
  */
 function _prepareCampaignDeliveryEmailBodyStats($adId, $oStartDate, $oEndDate, $type, $adTextPrint)
 {
     $oDbh =& OA_DB::singleton();
     // Obtain the required date format
     global $date_format;
     // Obtain the impressions, clicks and conversions string, and prepare
     // these strings for use, including formatting strings
     global $strNoViewLoggedInInterval, $strNoClickLoggedInInterval, $strNoConversionLoggedInInterval, $strTotalThisPeriod;
     if ($type == 'impressions') {
         $nothingLogged = $strNoViewLoggedInInterval;
     } else {
         if ($type == 'clicks') {
             $nothingLogged = $strNoClickLoggedInInterval;
         } else {
             if ($type == 'conversions') {
                 $nothingLogged = $strNoConversionLoggedInInterval;
             } else {
                 return array('body' => '', 'adviews' => 0);
             }
         }
     }
     // Prepare the result
     $emailBodyStats = '';
     $total = 0;
     // Fetch the ad's stats for the report period, grouped by day
     $doDataSummaryAdHourly = OA_Dal::factoryDO('data_summary_ad_hourly');
     $doDataSummaryAdHourly->selectAdd();
     $doDataSummaryAdHourly->selectAdd("date_time");
     $doDataSummaryAdHourly->selectAdd("SUM({$type}) as quantity");
     $doDataSummaryAdHourly->ad_id = $adId;
     $doDataSummaryAdHourly->whereAdd("impressions > 0");
     if (!is_null($oStartDate)) {
         $oDate = new Date($oStartDate);
         $oDate->toUTC();
         $doDataSummaryAdHourly->whereAdd('date_time >= ' . $oDbh->quote($oDate->format('%Y-%m-%d %H:%M:%S'), 'timestamp'));
     }
     $oDate = new Date($oEndDate);
     $oDate->toUTC();
     $doDataSummaryAdHourly->whereAdd('date_time <= ' . $oDbh->quote($oDate->format('%Y-%m-%d %H:%M:%S'), 'timestamp'));
     $doDataSummaryAdHourly->groupBy('date_time');
     $doDataSummaryAdHourly->orderBy('date_time DESC');
     $doDataSummaryAdHourly->find();
     if ($doDataSummaryAdHourly->getRowCount() > 0) {
         // The ad has statistics this period, perform time zone conversion and summarize
         $aAdQuantity = array();
         while ($doDataSummaryAdHourly->fetch()) {
             $v = $doDataSummaryAdHourly->toArray();
             $oDate = new Date($v['date_time']);
             $oDate->setTZbyID('UTC');
             $oDate->convertTZ($oEndDate->tz);
             $k = $oDate->format($date_format);
             if (!isset($aAdQuantity[$k])) {
                 $aAdQuantity[$k] = 0;
             }
             $aAdQuantity[$k] += $v['quantity'];
         }
         foreach ($aAdQuantity as $day => $quantity) {
             // Add this day
             $emailBodyStats .= sprintf($adTextPrint, $day) . ': ';
             $emailBodyStats .= sprintf('%15s', phpAds_formatNumber($quantity)) . "\n";
             $total += $quantity;
         }
         // Add the total statistics for the period
         $emailBodyStats .= sprintf($adTextPrint, $strTotalThisPeriod) . ': ';
         $emailBodyStats .= sprintf('%15s', phpAds_formatNumber($total)) . "\n";
     } else {
         // Simply note that there were no statistics this period
         $emailBodyStats .= '  ' . $nothingLogged . "\n";
     }
     // Return the result for the ad's stats
     return array('body' => $emailBodyStats, 'adviews' => $total);
 }
示例#18
0
 /**
  * A method to get the number of operation intervals in a given
  * start & end date range must be valid OI start & end date range
  *
  * @static
  * @param object $oStartDate PEAR::Date object
  * @param object $oEndDate PEAR::Date object
  * @return integer number of operation intervals remaining
  */
 function getIntervalsRemaining($oStartDate, $oEndDate)
 {
     $operationIntervalSeconds = OX_OperationInterval::getOperationInterval() * 60;
     // Convert to UTC
     $oStartCopy = new Date($oStartDate);
     $oStartCopy->toUTC();
     $oEndCopy = new Date($oEndDate);
     $oEndCopy->toUTC();
     // Get timestamp of start date/time - in seconds
     $startDateSeconds = mktime($oStartCopy->getHour(), $oStartCopy->getMinute(), $oStartCopy->getSecond(), $oStartCopy->getMonth(), $oStartCopy->getDay(), $oStartCopy->getYear());
     // Get timestamp of end date/time - in seconds
     $endDateSeconds = mktime($oEndCopy->getHour(), $oEndCopy->getMinute(), $oEndCopy->getSecond(), $oEndCopy->getMonth(), $oEndCopy->getDay(), $oEndCopy->getYear());
     // calculate interval length in seconds
     $interval = $endDateSeconds - $startDateSeconds;
     // find number of operation intervals during interval
     return $interval <= 0 ? 0 : round($interval / $operationIntervalSeconds);
 }
示例#19
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;
 }
示例#20
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;
     }
 }
示例#21
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');
 }
示例#22
0
 /**
  * A method to activate/deactivate campaigns, based on the date and/or the inventory
  * requirements (impressions, clicks and/or conversions). Also sends email reports
  * for any campaigns that are activated/deactivated, as well as sending email reports
  * for any campaigns that are likely to expire in the near future.
  *
  * @param Date $oDate The current date/time.
  * @return string Report on the campaigns activated/deactivated.
  */
 function manageCampaigns($oDate)
 {
     $aConf = $GLOBALS['_MAX']['CONF'];
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oEmail =& $oServiceLocator->get('OA_Email');
     if ($oEmail === false) {
         $oEmail = new OA_Email();
         $oServiceLocator->register('OA_Email', $oEmail);
     }
     $report = "\n";
     // Select all campaigns in the system, where:
     //    The campaign is ACTIVE and:
     //    - The end date stored for the campaign is not null; or
     //    - The campaign has a lifetime impression, click or conversion
     //      target set.
     //
     //    That is:
     //    - It is possible for the active campaign to be automatically
     //      stopped, as it has a valid end date. (No limitations are
     //      applied to those campaigns tested, as the ME may not have
     //      run for a while, and if so, even campaigns with an end date
     //      of many, many weeks ago should be tested to ensure they are
     //      [belatedly] halted.)
     //    - It is possible for the active campaign to be automatically
     //      stopped, as it has at leaast one lifetime target that could
     //      have been reached.
     //
     //    The campaign is INACTIVE and:
     //    - The start date stored for the campaign is not null; and
     //    - The weight is greater than zero; and
     //    - The end date stored for the campaign is either null, or is
     //      greater than "today" less one day.
     //
     //    That is:
     //    - It is possible for the inactive campaign to be automatically
     //      started, as it has a valid start date. (No limitations are
     //      applied to those campaigns tested, as the ME may not have run
     //      for a while, and if so, even campaigns with an activation date
     //      of many, many weeks ago should be tested to ensure they are
     //      [belatedy] enabled.)
     //    - The campaign is not in a permanently inactive state, as a
     //      result of the weight being less then one, which means that
     //      it cannot be activated.
     //    - The test to start the campaign is unlikely to fail on account
     //      of the end date.
     $prefix = $this->getTablePrefix();
     $oNowDate = new Date($oDate);
     $oNowDate->toUTC();
     $query = "\n            SELECT\n                cl.clientid AS advertiser_id,\n                cl.account_id AS advertiser_account_id,\n                cl.agencyid AS agency_id,\n                cl.contact AS contact,\n                cl.email AS email,\n                cl.reportdeactivate AS send_activate_deactivate_email,\n                ca.campaignid AS campaign_id,\n                ca.campaignname AS campaign_name,\n                ca.views AS targetimpressions,\n                ca.clicks AS targetclicks,\n                ca.conversions AS targetconversions,\n                ca.status AS status,\n                ca.activate_time AS start,\n                ca.expire_time AS end\n            FROM\n                {$prefix}campaigns AS ca,\n                {$prefix}clients AS cl\n            WHERE\n                ca.clientid = cl.clientid\n                AND\n                ((\n                    ca.status = " . $this->oDbh->quote(OA_ENTITY_STATUS_RUNNING, 'integer') . " AND\n                    (\n                        ca.expire_time IS NOT NULL\n                        OR\n                        (\n                            ca.views > 0\n                            OR\n                            ca.clicks > 0\n                            OR\n                            ca.conversions > 0\n                        )\n                    )\n                ) OR (\n                    ca.status = " . $this->oDbh->quote(OA_ENTITY_STATUS_AWAITING, 'integer') . " AND\n                    (\n                        ca.activate_time <= " . $this->oDbh->quote($oNowDate->getDate(DATE_FORMAT_ISO), 'timestamp') . "\n                        AND\n                        (\n                            ca.weight > 0\n                            OR\n                            ca.priority > 0\n                        )\n                        AND\n                        (\n                            ca.expire_time >= " . $this->oDbh->quote($oNowDate->getDate(DATE_FORMAT_ISO), 'timestamp') . "\n                            OR\n                            ca.expire_time IS NULL\n                        )\n                    )\n                ))\n            ORDER BY\n                advertiser_id";
     OA::debug('- Requesting campaigns to test for activation/deactivation', PEAR_LOG_DEBUG);
     $rsResult = $this->oDbh->query($query);
     if (PEAR::isError($rsResult)) {
         return MAX::raiseError($rsResult, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
     }
     OA::debug('- Found ' . $rsResult->numRows() . ' campaigns to test for activation/deactivation', PEAR_LOG_DEBUG);
     while ($aCampaign = $rsResult->fetchRow()) {
         if ($aCampaign['status'] == OA_ENTITY_STATUS_RUNNING) {
             // The campaign is currently running, look at the campaign
             $disableReason = 0;
             $canExpireSoon = false;
             if ($aCampaign['targetimpressions'] > 0 || $aCampaign['targetclicks'] > 0 || $aCampaign['targetconversions'] > 0) {
                 OA::debug('  - Selecting impressions, clicks and conversions for this running campaign ID = ' . $aCampaign['campaign_id'], PEAR_LOG_DEBUG);
                 // The campaign has an impression, click and/or conversion target,
                 // so get the sum total statistics for the campaign
                 $query = "\n                        SELECT\n                            SUM(dia.impressions) AS impressions,\n                            SUM(dia.clicks) AS clicks,\n                            SUM(dia.conversions) AS conversions\n                        FROM\n                            " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['data_intermediate_ad'], true) . " AS dia,\n                            " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['banners'], true) . " AS b\n                        WHERE\n                            dia.ad_id = b.bannerid\n                            AND b.campaignid = {$aCampaign['campaign_id']}";
                 $rsResultInner = $this->oDbh->query($query);
                 $valuesRow = $rsResultInner->fetchRow();
                 if (isset($valuesRow['impressions']) || !is_null($valuesRow['clicks']) || !is_null($valuesRow['conversions'])) {
                     // There were impressions, clicks and/or conversions for this
                     // campaign, so find out if campaign targets have been passed
                     if (!isset($valuesRow['impressions'])) {
                         // No impressions
                         $valuesRow['impressions'] = 0;
                     }
                     if (!isset($valuesRow['clicks'])) {
                         // No clicks
                         $valuesRow['clicks'] = 0;
                     }
                     if (!isset($valuesRow['conversions'])) {
                         // No conversions
                         $valuesRow['conversions'] = 0;
                     }
                     if ($aCampaign['targetimpressions'] > 0) {
                         if ($aCampaign['targetimpressions'] <= $valuesRow['impressions']) {
                             // The campaign has an impressions target, and this has been
                             // passed, so update and disable the campaign
                             $disableReason |= OX_CAMPAIGN_DISABLED_IMPRESSIONS;
                         }
                     }
                     if ($aCampaign['targetclicks'] > 0) {
                         if ($aCampaign['targetclicks'] <= $valuesRow['clicks']) {
                             // The campaign has a click target, and this has been
                             // passed, so update and disable the campaign
                             $disableReason |= OX_CAMPAIGN_DISABLED_CLICKS;
                         }
                     }
                     if ($aCampaign['targetconversions'] > 0) {
                         if ($aCampaign['targetconversions'] <= $valuesRow['conversions']) {
                             // The campaign has a target limitation, and this has been
                             // passed, so update and disable the campaign
                             $disableReason |= OX_CAMPAIGN_DISABLED_CONVERSIONS;
                         }
                     }
                     if ($disableReason) {
                         // One of the campaign targets was exceeded, so disable
                         $message = '  - Exceeded a campaign quota: Deactivating campaign ID ' . "{$aCampaign['campaign_id']}: {$aCampaign['campaign_name']}";
                         OA::debug($message, PEAR_LOG_INFO);
                         $report .= $message . "\n";
                         $doCampaigns = OA_Dal::factoryDO('campaigns');
                         $doCampaigns->campaignid = $aCampaign['campaign_id'];
                         $doCampaigns->find();
                         $doCampaigns->fetch();
                         $doCampaigns->status = OA_ENTITY_STATUS_EXPIRED;
                         $result = $doCampaigns->update();
                         if ($result == false) {
                             return MAX::raiseError($rows, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
                         }
                         phpAds_userlogSetUser(phpAds_userMaintenance);
                         phpAds_userlogAdd(phpAds_actionDeactiveCampaign, $aCampaign['campaign_id']);
                     } else {
                         // The campaign didn't have a diable reason,
                         // it *might* possibly be diabled "soon"...
                         $canExpireSoon = true;
                     }
                 }
             }
             // Does the campaign need to be disabled due to the date?
             if (!empty($aCampaign['end'])) {
                 // The campaign has a valid end date, stored in in UTC
                 $oEndDate = new Date($aCampaign['end']);
                 $oEndDate->setTZByID('UTC');
                 if ($oDate->after($oEndDate)) {
                     // The end date has been passed; disable the campaign
                     $disableReason |= OX_CAMPAIGN_DISABLED_DATE;
                     $message = "  - Passed campaign end time of '" . $oEndDate->getDate() . " UTC" . "': Deactivating campaign ID {$aCampaign['campaign_id']}: {$aCampaign['campaign_name']}";
                     OA::debug($message, PEAR_LOG_INFO);
                     $report .= $message . "\n";
                     $doCampaigns = OA_Dal::factoryDO('campaigns');
                     $doCampaigns->campaignid = $aCampaign['campaign_id'];
                     $doCampaigns->find();
                     $doCampaigns->fetch();
                     $doCampaigns->status = OA_ENTITY_STATUS_EXPIRED;
                     $result = $doCampaigns->update();
                     if ($result == false) {
                         return MAX::raiseError($rows, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
                     }
                     phpAds_userlogSetUser(phpAds_userMaintenance);
                     phpAds_userlogAdd(phpAds_actionDeactiveCampaign, $aCampaign['campaign_id']);
                 } else {
                     // The campaign wasn't disabled based on the end
                     // date, to it *might* possibly be disabled "soon"...
                     $canExpireSoon = true;
                 }
             }
             if ($disableReason) {
                 // The campaign was disabled, so send the appropriate
                 // message to the campaign's contact
                 $query = "\n                        SELECT\n                            bannerid AS advertisement_id,\n                            description AS description,\n                            alt AS alt,\n                            url AS url\n                        FROM\n                            " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['banners'], true) . "\n                        WHERE\n                            campaignid = {$aCampaign['campaign_id']}";
                 OA::debug("  - Getting the advertisements for campaign ID {$aCampaign['campaign_id']}", PEAR_LOG_DEBUG);
                 $rsResultAdvertisement = $this->oDbh->query($query);
                 if (PEAR::isError($rsResultAdvertisement)) {
                     return MAX::raiseError($rsResultAdvertisement, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
                 }
                 while ($advertisementRow = $rsResultAdvertisement->fetchRow()) {
                     $advertisements[$advertisementRow['advertisement_id']] = array($advertisementRow['description'], $advertisementRow['alt'], $advertisementRow['url']);
                 }
                 if ($aCampaign['send_activate_deactivate_email'] == 't') {
                     OA::debug("  - Sending campaign deactivated email ", PEAR_LOG_DEBUG);
                     $oEmail->sendCampaignActivatedDeactivatedEmail($aCampaign['campaign_id'], $disableReason);
                     // Also send campaignDeliveryEmail for the campaign we just deactivated.
                     $doClients = OA_Dal::staticGetDO('clients', $aCampaign['advertiser_id']);
                     $aAdvertiser = $doClients->toArray();
                     OA::debug("  - Sending campaign delivery email ", PEAR_LOG_DEBUG);
                     $oStart = new Date($aAdvertiser['reportlastdate']);
                     $oEnd = new Date($oDate);
                     // Set end date to tomorrow so we get stats for today.
                     $oEnd->addSpan(new Date_Span('1-0-0-0'));
                     $oEmail->sendCampaignDeliveryEmail($aAdvertiser, $oStart, $oEnd, $aCampaign['campaign_id']);
                 }
             } else {
                 if ($canExpireSoon) {
                     // The campaign has NOT been deactivated - test to see if it will
                     // be deactivated "soon", and send email(s) warning of this as required
                     OA::debug("  - Sending campaign 'soon deactivated' email ", PEAR_LOG_DEBUG);
                     $oEmail->sendCampaignImpendingExpiryEmail($oDate, $aCampaign['campaign_id']);
                 }
             }
         } elseif (!empty($aCampaign['start'])) {
             // The campaign is awaiting activation and has a valid start date, stored in UTC
             $oStartDate = new Date($aCampaign['start']);
             $oStartDate->setTZByID('UTC');
             // Find out if there are any impression, click or conversion targets for
             // the campaign (i.e. if the target values are > 0)
             $remainingImpressions = 0;
             $remainingClicks = 0;
             $remainingConversions = 0;
             if ($aCampaign['targetimpressions'] > 0 || $aCampaign['targetclicks'] > 0 || $aCampaign['targetconversions'] > 0) {
                 OA::debug("  - The campaign ID " . $aCampaign['campaign_id'] . " has an impression, click and/or conversion target, requesting impressions so far", PEAR_LOG_DEBUG);
                 $query = "\n                        SELECT\n                            SUM(dia.impressions) AS impressions,\n                            SUM(dia.clicks) AS clicks,\n                            SUM(dia.conversions) AS conversions\n                        FROM\n                            " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['data_intermediate_ad'], true) . " AS dia,\n                            " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['banners'], true) . " AS b\n                        WHERE\n                            dia.ad_id = b.bannerid\n                            AND b.campaignid = {$aCampaign['campaign_id']}";
                 $rsResultInner = $this->oDbh->query($query);
                 $valuesRow = $rsResultInner->fetchRow();
                 // Set the remaining impressions, clicks and conversions for the campaign
                 $remainingImpressions = $aCampaign['targetimpressions'] - $valuesRow['impressions'];
                 $remainingClicks = $aCampaign['targetclicks'] - $valuesRow['clicks'];
                 $remainingConversions = $aCampaign['targetconversions'] - $valuesRow['conversions'];
             }
             // In order for the campaign to be activated, need to test:
             // 1) That there is no impression target (<= 0), or, if there is an impression target (> 0),
             //    then there must be remaining impressions to deliver (> 0); and
             // 2) That there is no click target (<= 0), or, if there is a click target (> 0),
             //    then there must be remaining clicks to deliver (> 0); and
             // 3) That there is no conversion target (<= 0), or, if there is a conversion target (> 0),
             //    then there must be remaining conversions to deliver (> 0)
             if (($aCampaign['targetimpressions'] <= 0 || $aCampaign['targetimpressions'] > 0 && $remainingImpressions > 0) && ($aCampaign['targetclicks'] <= 0 || $aCampaign['targetclicks'] > 0 && $remainingClicks > 0) && ($aCampaign['targetconversions'] <= 0 || $aCampaign['targetconversions'] > 0 && $remainingConversions > 0)) {
                 $message = "- Passed campaign start time of '" . $oStartDate->getDate() . " UTC" . "': Activating campaign ID {$aCampaign['campaign_id']}: {$aCampaign['campaign_name']}";
                 OA::debug($message, PEAR_LOG_INFO);
                 $report .= $message . "\n";
                 $doCampaigns = OA_Dal::factoryDO('campaigns');
                 $doCampaigns->campaignid = $aCampaign['campaign_id'];
                 $doCampaigns->find();
                 $doCampaigns->fetch();
                 $doCampaigns->status = OA_ENTITY_STATUS_RUNNING;
                 $result = $doCampaigns->update();
                 if ($result == false) {
                     return MAX::raiseError($rows, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
                 }
                 phpAds_userlogSetUser(phpAds_userMaintenance);
                 phpAds_userlogAdd(phpAds_actionActiveCampaign, $aCampaign['campaign_id']);
                 if ($aCampaign['send_activate_deactivate_email'] == 't') {
                     OA::debug("  - Sending activation email for campaign ID " . $aCampaign['campaign_id'], PEAR_LOG_DEBUG);
                     $oEmail->sendCampaignActivatedDeactivatedEmail($aCampaign['campaign_id']);
                 }
             }
         }
     }
 }
示例#23
0
 /**
  * Method used to convert the user date (that might be in a
  * specific timezone) to a GMT date.
  *
  * @access  public
  * @param   string $date The user based date
  * @return  string The date in the GMT timezone
  */
 function getDateGMT($date)
 {
     $dt = new Date($date);
     $dt->setTZbyID(Date_API::getPreferredTimezone());
     $dt->toUTC();
     return $dt->format('%Y-%m-%d %H:%M:%S');
 }
 /**
  * A method to test the activation of campaigns does NOT occur in the
  * event that the campaigns have previously been deactivated within
  * the manageCampaigns() method.
  */
 function testManageCampaignsNoRestart()
 {
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oServiceLocator->register('now', new Date('2005-12-07 10:01:00'));
     $oFactory = new OX_Dal_Maintenance_Statistics_Factory();
     $oDalMaintenanceStatistics = $oFactory->factory();
     // Create the required accounts & set the various ID values
     $aValues = $this->_createAccounts();
     $adminAccountId = $aValues['adminAccount'];
     $managerAccountId = $aValues['managerAccount'];
     $advertiserClientId = $aValues['advertiserClient'];
     /******************************************************************************/
     /* Prepare Campaign and Banner Data for Test                                  */
     /******************************************************************************/
     // Campaign 1:
     // - Owned by Advertiser 1
     // - Lifetime target of 10 impressions
     // - Start date of 2005-12-07
     // - End date of 2005-12-09
     // - Campaign currently running, will be expired after we insert stats
     $aData = array('campaignname' => 'Test Campaign 1', 'clientid' => $advertiserClientId, 'views' => 10, 'clicks' => -1, 'conversions' => -1, 'activate_time' => '2005-12-06 14:00:00', 'expire_time' => '2005-12-09 13:59:59', 'status' => OA_ENTITY_STATUS_RUNNING);
     $idCampaign1 = $this->_insertPlacement($aData);
     // Banner 1
     // - In Campaign 1
     $aData = array('campaignid' => $idCampaign1);
     $idBanner1 = $this->_insertAd($aData);
     // 100 Impressions for Banner 1 occuring after the
     // start date of Campaign 1, and before the end date
     // of Campaign 1, when the campaign start/end dates
     // are converted into UTC
     $aData = array('operation_interval_id' => 25, 'interval_start' => '2005-12-07 10:00:00', 'interval_end' => '2005-12-07 10:59:59', 'hour' => 10, 'ad_id' => $idBanner1, 'impressions' => 100, 'clicks' => 1, 'conversions' => 0);
     $idDIA1 = $this->_insertDataIntermediateAd($aData);
     // Make sure that campaign 1 is expired
     $doCampaigns = OA_Dal::staticGetDO('campaigns', $idCampaign1);
     $doCampaigns->status = OA_ENTITY_STATUS_RUNNING;
     $doCampaigns->update();
     /******************************************************************************/
     // Test 1: Prepare a date for the manageCampaigns() method to run at in UTC;
     //         2005-12-07 11:01:00 UTC is 2005-12-07 22:01:00 Australia/Sydney
     $oDate = new Date();
     $oDate->toUTC();
     $oDate->setDate('2005-12-07 11:01:00');
     $oServiceLocator->register('now', $oDate);
     // Test 1: Run the method, and ensure that, although the date in UTC
     //         is after the start date of Campaign 1 and before the end
     //         date of Campaign 1, the campaign is NOT enabled, due to
     //         past expiration of the campaign
     $report = $oDalMaintenanceStatistics->manageCampaigns($oDate);
     $this->_testCampaignByCampaignId($idCampaign1, 10, -1, -1, '2005-12-06 14:00:00', '2005-12-09 13:59:59', OA_ENTITY_STATUS_EXPIRED);
     /******************************************************************************/
     DataGenerator::cleanUp();
 }
示例#25
0
 /**
  * A method to return the end day of the span in UTC (ISO
  *
  * @param string $format An optional PEAR::Date compatible format string.
  * @return string The end day of the span.
  */
 function getEndDateStringUTC($format = '%Y-%m-%d')
 {
     $oDate = new Date($this->oEndDate);
     $oDate->toUTC();
     return $oDate->getDate(DATE_FORMAT_ISO);
 }
示例#26
0
 protected function getDateTimeInUtc($date)
 {
     $dateInUTC = new Date($date);
     $dateInUTC->toUTC();
     return $dateInUTC->format('%Y-%m-%d %H:%M:%S');
 }
示例#27
0
 /**
  * Sets the span from the elapsed time between two dates
  *
  * The time span is unsigned, so the date's order is not important.
  *
  * @param object $date1 first Date
  * @param object $date2 second Date
  *
  * @return   bool       true on success
  * @access   public
  * @see      Date_Span::set()
  */
 function setFromDateDiff($date1, $date2)
 {
     if (!is_a($date1, 'date') or !is_a($date2, 'date')) {
         return false;
     }
     // create a local copy of instance, in order avoid changes the object
     // reference when its object has converted to UTC due PHP5 is always
     // passed the object by reference.
     $tdate1 = new Date($date1);
     $tdate2 = new Date($date2);
     // convert to UTC
     $tdate1->toUTC();
     $tdate2->toUTC();
     if ($tdate1->after($tdate2)) {
         list($tdate1, $tdate2) = array($tdate2, $tdate1);
     }
     $days = Date_Calc::dateDiff($tdate1->getDay(), $tdate1->getMonth(), $tdate1->getYear(), $tdate2->getDay(), $tdate2->getMonth(), $tdate2->getYear());
     $hours = $tdate2->getHour() - $tdate1->getHour();
     $mins = $tdate2->getMinute() - $tdate1->getMinute();
     $secs = $tdate2->getSecond() - $tdate1->getSecond();
     $this->setFromSeconds($days * 86400 + $hours * 3600 + $mins * 60 + $secs);
     return true;
 }