Example #1
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']);
                         }
                     }
                 }
             }
         }
     }
 }
        // Disable if a null profile was supplied
        $phpAds_config['autotarget_factor'] = -1;
        $report .= "skipped: supplied profile is null\n\n";
    } else {
        $report .= "skipped: already set\n\n";
    }
    $report .= "--------------------------------------------------\n";
    $report .= "Smoothing factor:               " . sprintf('%.2f', $phpAds_config['autotarget_factor']) . "\n";
    $report .= "Today dow:                      " . phpAds_DowToday . "\n";
    $report .= "Today profile value:            " . $profile[phpAds_DowToday] . "\n";
    if ($phpAds_config['autotarget_factor'] != -1) {
        // Targets should not be fully satisfied if using plain autotargeting
        // Smoothing the view profile for later use
        $profile = phpAds_AutoTargetingSmoothProfile($profile, $phpAds_config['autotarget_factor']);
        $report .= "Today smoothed profile value:   " . $profile[phpAds_DowToday] . "\n";
    }
    $report .= "--------------------------------------------------\n\n";
    while ($row = phpAds_dbFetchArray($res)) {
        $target = phpAds_AutoTargetingGetTarget($profile, $row['views'], $row['expire'], $phpAds_config['autotarget_factor']);
        if (is_array($target)) {
            list($target, $debuglog) = $target;
        } else {
            $debuglog = 'no debug info available';
        }
        phpAds_dbQuery("\n\t\t\tUPDATE\n\t\t\t\t" . $phpAds_config['tbl_clients'] . "\n\t\t\tSET\n\t\t\t\ttarget = " . $target . "\n\t\t\tWHERE\n\t\t\t\tclientid = " . $row['clientid'] . "\n\t\t");
        $report .= "\n<b>{$row['clientname']} [id{$row['clientid']}]:</b> {$target} {$debuglog}\n\n";
    }
}
if ($report != '' && $phpAds_config['userlog_priority']) {
    phpAds_userlogAdd(phpAds_actionPriorityAutoTargeting, 0, $report);
}
Example #3
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']);
                 }
             }
         }
     }
 }
Example #4
0
 function sendCampaignActivatedDeactivatedEmail($campaignId, $reason = null)
 {
     $aConf = $GLOBALS['_MAX']['CONF'];
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doClient = OA_Dal::factoryDO('clients');
     $doCampaigns->joinAdd($doClient);
     $doCampaigns->get('campaignid', $campaignId);
     $aLinkedUsers = $this->getUsersLinkedToAccount('clients', $doCampaigns->clientid);
     $aAdvertiser = $this->_loadAdvertiser($doCampaigns->clientid);
     // Add the advertiser to the linked users if there isn't any linked user with the advertiser's email address
     $aLinkedUsers = $this->_addAdvertiser($aAdvertiser, $aLinkedUsers);
     $copiesSent = 0;
     if (!empty($aLinkedUsers) && is_array($aLinkedUsers)) {
         if ($aConf['email']['useManagerDetails']) {
             $aFromDetails = $this->_getAgencyFromDetails($aAdvertiser['agencyid']);
         }
         foreach ($aLinkedUsers as $aUser) {
             $aEmail = $this->prepareCampaignActivatedDeactivatedEmail($aUser, $doCampaigns->campaignid, $reason);
             if ($aEmail !== false) {
                 if ($this->sendMail($aEmail['subject'], $aEmail['contents'], $aUser['email_address'], $aUser['contact_name'], $aFromDetails)) {
                     $copiesSent++;
                     if ($aConf['email']['logOutgoing']) {
                         phpAds_userlogSetUser(phpAds_userMaintenance);
                         phpAds_userlogAdd(is_null($reason) ? phpAds_actionActivationMailed : phpAds_actionDeactivationMailed, $doPlacement->campaignid, "{$aEmail['subject']}\n\n\n                                 {$aUser['contact_name']}({$aUser['email_address']})\n\n\n                                 {$aEmail['contents']}");
                     }
                 }
             }
         }
         // Restore the default language strings
         Language_Loader::load('default');
     }
     return $copiesSent;
 }
<?php

// $Revision: 3830 $
/************************************************************************/
/* Openads 2.0                                                          */
/* ===========                                                          */
/*                                                                      */
/* Copyright (c) 2000-2007 by the Openads developers                    */
/* For more information visit: http://www.openads.org                   */
/*                                                                      */
/* This program is free software. You can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 2 of the License.       */
/************************************************************************/
// Prevent full path disclosure
if (!defined('phpAds_path')) {
    die;
}
// Include required files
require phpAds_path . "/libraries/lib-cleantables.inc.php";
$report = '';
if ($phpAds_config['auto_clean_tables']) {
    $report .= phpAds_cleanTables($phpAds_config['auto_clean_tables_interval'], true);
}
if ($phpAds_config['auto_clean_userlog']) {
    $report .= phpAds_cleanTables($phpAds_config['auto_clean_userlog_interval'], false);
}
if ($report != '' && $phpAds_config['userlog_autoclean']) {
    phpAds_userlogAdd(phpAds_actionAutoClean, 0, $report);
}
function phpAds_logExpire($clientid, $type = 0)
{
    global $phpAds_config;
    // Get campaign information
    $campaignresult = phpAds_dbQuery("SELECT *, UNIX_TIMESTAMP(expire) AS expire_st, UNIX_TIMESTAMP(activate) AS activate_st FROM " . $phpAds_config['tbl_clients'] . " WHERE clientid = '" . $clientid . "'");
    if ($campaign = phpAds_dbFetchArray($campaignresult)) {
        // Decrement views
        if ($type == phpAds_Views && $campaign['views'] > 0) {
            phpAds_dbQuery("UPDATE " . $phpAds_config['tbl_clients'] . " SET views = views - 1 WHERE clientid = '" . $clientid . "'");
            $campaign['views']--;
            // Mail warning - preset is reached
            if ($campaign['views'] == $phpAds_config['warn_limit'] && ($phpAds_config['warn_admin'] || $phpAds_config['warn_client'])) {
                // Include warning library
                if (!defined('LIBWARNING_INCLUDED')) {
                    require phpAds_path . '/libraries/lib-warnings.inc.php';
                }
                if (!defined('LIBMAIL_INCLUDED')) {
                    require phpAds_path . '/libraries/lib-mail.inc.php';
                }
                if (!defined('LIBUSERLOG_INCLUDED')) {
                    require phpAds_path . '/libraries/lib-userlog.inc.php';
                }
                phpAds_userlogSetUser(phpAds_userDeliveryEngine);
                phpAds_warningMail($campaign);
            }
        }
        // Decrement clicks
        if ($type == phpAds_Clicks && $campaign['clicks'] > 0) {
            phpAds_dbQuery("UPDATE " . $phpAds_config['tbl_clients'] . " SET clicks = clicks - 1 WHERE clientid='" . $clientid . "'");
            $campaign['clicks']--;
        }
        // Check activation status
        $active = "t";
        if ($campaign["clicks"] == 0 || $campaign["views"] == 0 || time() < $campaign["activate_st"] || time() > $campaign["expire_st"] && $campaign["expire_st"] != 0) {
            $active = "f";
        }
        if ($campaign["active"] != $active) {
            if (!defined('LIBUSERLOG_INCLUDED')) {
                require phpAds_path . '/libraries/lib-userlog.inc.php';
            }
            // Log deactivation
            phpAds_userlogSetUser(phpAds_userDeliveryEngine);
            phpAds_userlogAdd(phpAds_actionDeactiveCampaign, $campaign['clientid']);
            // Deactivate campaign
            phpAds_dbQuery("UPDATE " . $phpAds_config['tbl_clients'] . " SET active='" . $active . "' WHERE clientid='" . $clientid . "'");
            // Send deactivation warning
            if ($active == 'f') {
                // Rebuild priorities
                if (!defined('LIBPRIORITY_INCLUDED')) {
                    require phpAds_path . '/libraries/lib-priority.inc.php';
                }
                phpAds_PriorityCalculate();
                // Recalculate cache
                if (!defined('LIBVIEWCACHE_INCLUDED')) {
                    include phpAds_path . '/libraries/deliverycache/cache-' . $phpAds_config['delivery_caching'] . '.inc.php';
                }
                phpAds_cacheDelete();
                // Include warning library
                if (!defined('LIBWARNING_INCLUDED')) {
                    require phpAds_path . '/libraries/lib-warnings.inc.php';
                }
                if (!defined('LIBMAIL_INCLUDED')) {
                    require phpAds_path . '/libraries/lib-mail.inc.php';
                }
                phpAds_deactivateMail($campaign);
            }
        }
    }
}
<?php

// $Revision: 3830 $
/************************************************************************/
/* Openads 2.0                                                          */
/* ===========                                                          */
/*                                                                      */
/* Copyright (c) 2000-2007 by the Openads developers                    */
/* For more information visit: http://www.openads.org                   */
/*                                                                      */
/* This program is free software. You can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 2 of the License.       */
/************************************************************************/
// Prevent full path disclosure
if (!defined('phpAds_path')) {
    die;
}
if ($phpAds_config['updates_enabled']) {
    include phpAds_path . '/libraries/lib-openadssync.inc.php';
    $res = phpAds_checkForUpdates(0, true);
    if ($res[0] != 0 && $res[0] != 800) {
        phpAds_userlogAdd(phpAds_actionOpenadsSync, "Openads Sync error ({$res['0']}): {$res['1']}");
    }
}
function phpAds_SendMaintenanceReport($clientid, $first_unixtimestamp, $last_unixtimestamp, $update = true)
{
    global $phpAds_config, $phpAds_CharSet, $date_format, $strBanner, $strCampaign, $strViews, $strClicks, $strConversions, $strLinkedTo, $strMailSubject, $strMailHeader, $strMailBannerStats, $strMailFooter, $strMailReportPeriod, $strMailReportPeriodAll, $strLogErrorBanners, $strLogErrorClients, $strLogErrorViews, $strLogErrorClicks, $strLogErrorConversions, $strNoStatsForCampaign, $strNoViewLoggedInInterval, $strNoClickLoggedInInterval, $strNoCampaignLoggedInInterval, $strTotal, $strTotalThisPeriod;
    // Convert timestamps to SQL format
    $last_sqltimestamp = date("YmdHis", $last_unixtimestamp);
    $first_sqltimestamp = date("YmdHis", $first_unixtimestamp);
    // Get Client information
    $res_client = phpAds_dbQuery("SELECT" . " clientid" . ",clientname" . ",contact" . ",email" . ",language" . ",report" . ",reportinterval" . ",reportlastdate" . ",UNIX_TIMESTAMP(reportlastdate) AS reportlastdate_t" . " FROM " . $phpAds_config['tbl_clients'] . " WHERE clientid=" . $clientid);
    if (phpAds_dbNumRows($res_client) > 0) {
        $client = phpAds_dbFetchArray($res_client);
        // Load client language strings
        @(include phpAds_path . '/language/english/default.lang.php');
        if ($client['language'] != '') {
            $phpAds_config['language'] = $client['language'];
        }
        if ($phpAds_config['language'] != 'english' && file_exists(phpAds_path . '/language/' . $phpAds_config['language'] . '/default.lang.php')) {
            @(include phpAds_path . '/language/' . $phpAds_config['language'] . '/default.lang.php');
        }
        $active_campaigns = false;
        $log = "";
        // Fetch all campaigns belonging to client
        $res_campaigns = phpAds_dbQuery("SELECT" . " campaignid" . ",campaignname" . ",views" . ",clicks" . ",conversions" . ",expire" . ",UNIX_TIMESTAMP(expire) as expire_st" . ",activate" . ",UNIX_TIMESTAMP(activate) as activate_st" . ",active" . " FROM " . $phpAds_config['tbl_campaigns'] . " WHERE clientid=" . $client['clientid']) or die($strLogErrorClients);
        while ($campaign = phpAds_dbFetchArray($res_campaigns)) {
            // Fetch all banners belonging to campaign
            $res_banners = phpAds_dbQuery("SELECT" . " bannerid" . ",campaignid" . ",URL" . ",active" . ",description" . ",alt" . " FROM " . $phpAds_config['tbl_banners'] . " WHERE campaignid=" . $campaign['campaignid']) or die($strLogErrorBanners);
            $active_banners = false;
            $log .= "\n" . $strCampaign . "  " . strip_tags(phpAds_buildName($campaign['campaignid'], $campaign['campaignname'])) . "\n";
            $log .= "=======================================================\n\n";
            while ($row_banners = phpAds_dbFetchArray($res_banners)) {
                $adviews = phpAds_totalViews($row_banners["bannerid"]);
                $client["views_used"] = $adviews;
                $adclicks = phpAds_totalClicks($row_banners["bannerid"]);
                $campaign["clicks_used"] = $adclicks;
                $adconversions = phpAds_totalConversions($row_banners["bannerid"]);
                $campaign["conversions_used"] = $adconversions;
                if ($adviews > 0 || $adclicks > 0 || $adconversions > 0) {
                    $log .= $strBanner . "  " . strip_tags(phpAds_buildBannerName($row_banners['bannerid'], $row_banners['description'], $row_banners['alt'])) . "\n";
                    $log .= $strLinkedTo . ": " . $row_banners['URL'] . "\n";
                    $log .= "-------------------------------------------------------\n";
                    $active_banner_stats = false;
                    if ($adviews > 0) {
                        $log .= $strViews . " (" . $strTotal . "):    " . $adviews . "\n";
                        // Fetch all adviews belonging to banner belonging to client, grouped by day
                        $res_adviews = phpAds_dbQuery("SELECT" . " SUM(views) as qnt" . ",DATE_FORMAT(day, '{$date_format}') as t_stamp_f" . ",TO_DAYS(day) AS the_day" . " FROM " . $phpAds_config['tbl_adstats'] . " WHERE bannerid=" . $row_banners['bannerid'] . " AND views>0" . " AND UNIX_TIMESTAMP(day)>=" . $first_unixtimestamp . " AND UNIX_TIMESTAMP(day)<" . $last_unixtimestamp . " GROUP BY day" . " ORDER BY day DESC") or die($strLogErrorViews . " " . phpAds_dbError());
                        if (phpAds_dbNumRows($res_adviews)) {
                            $total = 0;
                            while ($row_adviews = phpAds_dbFetchArray($res_adviews)) {
                                $log .= "      " . $row_adviews['t_stamp_f'] . ":   " . $row_adviews['qnt'] . "\n";
                                $total += $row_adviews['qnt'];
                            }
                            $log .= $strTotalThisPeriod . ": " . $total . "\n";
                            $active_banner_stats = true;
                        } else {
                            $log .= "      " . $strNoViewLoggedInInterval . "\n";
                        }
                    }
                    if ($adclicks > 0) {
                        // Total adclicks
                        $log .= "\n" . $strClicks . " (" . $strTotal . "):   " . $adclicks . "\n";
                        // Fetch all adclicks belonging to banner belonging to client, grouped by day
                        $res_adclicks = phpAds_dbQuery("SELECT" . " SUM(clicks) as qnt" . ",DATE_FORMAT(day, '{$date_format}') as t_stamp_f" . ",TO_DAYS(day) AS the_day" . " FROM " . $phpAds_config['tbl_adstats'] . " WHERE bannerid = " . $row_banners['bannerid'] . " AND clicks>0" . " AND UNIX_TIMESTAMP(day)>=" . $first_unixtimestamp . " AND UNIX_TIMESTAMP(day)<" . $last_unixtimestamp . " GROUP BY day" . " ORDER BY day DESC") or die($strLogErrorClicks . " " . phpAds_dbError());
                        if (phpAds_dbNumRows($res_adclicks)) {
                            $total = 0;
                            while ($row_adclicks = phpAds_dbFetchArray($res_adclicks)) {
                                $log .= "      " . $row_adclicks['t_stamp_f'] . ":   " . $row_adclicks['qnt'] . "\n";
                                $total += $row_adclicks['qnt'];
                            }
                            $log .= $strTotalThisPeriod . ": " . $total . "\n";
                            $active_banner_stats = true;
                        } else {
                            $log .= "      " . $strNoClickLoggedInInterval . "\n";
                        }
                    }
                    if ($adconversions > 0) {
                        // Total adconversions
                        $log .= "\n" . $strConversions . " (" . $strTotal . "):   " . $adconversions . "\n";
                        // Fetch all adclicks belonging to banner belonging to client, grouped by day
                        $res_adconversions = phpAds_dbQuery("SELECT" . " SUM(conversions) as qnt" . ",DATE_FORMAT(day, '{$date_format}') as t_stamp_f" . ",TO_DAYS(day) AS the_day" . " FROM " . $phpAds_config['tbl_adstats'] . " WHERE bannerid = " . $row_banners['bannerid'] . " AND conversions>0" . " AND UNIX_TIMESTAMP(day)>=" . $first_unixtimestamp . " AND UNIX_TIMESTAMP(day)<" . $last_unixtimestamp . " GROUP BY day" . " ORDER BY day DESC") or die($strLogErrorConversions . " " . phpAds_dbError());
                        if (phpAds_dbNumRows($res_adconversions)) {
                            $total = 0;
                            while ($row_adconversions = phpAds_dbFetchArray($res_adconversions)) {
                                $log .= "      " . $row_adcconversions['t_stamp_f'] . ":   " . $row_adconversions['qnt'] . "\n";
                                $total += $row_adconversions['qnt'];
                            }
                            $log .= $strTotalThisPeriod . ": " . $total . "\n";
                            $active_banner_stats = true;
                        } else {
                            $log .= "      " . $strNoConversionLoggedInInterval . "\n";
                        }
                    }
                    $log .= "\n\n";
                    if ($active_banner_stats == true || $active_banner_stats == false && $campaign['active'] == 't') {
                        $active_banners = true;
                    }
                }
            }
            if ($active_banners == true) {
                $active_campaigns = true;
            } else {
                $log .= $strNoStatsForCampaign . "\n\n\n";
            }
        }
        // E-mail Stats to active clients
        if ($client["email"] != '' && $active_campaigns == true) {
            $Subject = $strMailSubject . ": " . $client["clientname"];
            $Body = "{$strMailHeader}\n";
            $Body .= "{$strMailBannerStats}\n";
            if ($first_unixtimestamp == 0) {
                $Body .= "{$strMailReportPeriodAll}\n\n";
            } else {
                $Body .= "{$strMailReportPeriod}\n\n";
            }
            $Body .= "{$log}\n";
            $Body .= "{$strMailFooter}";
            $Body = str_replace("{clientname}", $client['clientname'], $Body);
            $Body = str_replace("{contact}", $client['contact'], $Body);
            $Body = str_replace("{adminfullname}", $phpAds_config['admin_fullname'], $Body);
            $Body = str_replace("{startdate}", date(str_replace('%', '', $date_format), $first_unixtimestamp), $Body);
            $Body = str_replace("{enddate}", date(str_replace('%', '', $date_format), $last_unixtimestamp), $Body);
            if ($phpAds_config['userlog_email']) {
                phpAds_userlogAdd(phpAds_actionAdvertiserReportMailed, $client['clientid'], $Subject . "\n\n" . $Body);
            }
            if (phpAds_sendMail($client['email'], $client['contact'], $Subject, $Body)) {
                // Update last run
                if ($update == true) {
                    $res_update = phpAds_dbQuery("UPDATE " . $phpAds_config['tbl_clients'] . " SET reportlastdate=NOW() WHERE clientid=" . $client['clientid']);
                }
                return true;
            }
        }
    }
    return false;
}
// $Revision: 2.0 $
/************************************************************************/
/* phpAdsNew 2                                                          */
/* ===========                                                          */
/*                                                                      */
/* Copyright (c) 2000-2002 by the phpAdsNew developers                  */
/* For more information visit: http://www.phpadsnew.com                 */
/*                                                                      */
/* This program is free software. You can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 2 of the License.       */
/************************************************************************/
// Include required files
require "config.php";
require "lib-statistics.inc.php";
require "../libraries/lib-priority.inc.php";
// Security check
phpAds_checkAccess(phpAds_Admin);
/*********************************************************/
/* Main code                                             */
/*********************************************************/
$report = phpAds_PriorityCalculate();
if ($report != '' && $phpAds_config['userlog_priority']) {
    phpAds_userlogAdd(phpAds_actionPriorityCalculation, 0, $report);
}
// Rebuild cache
if (!defined('LIBVIEWCACHE_INCLUDED')) {
    include phpAds_path . '/libraries/deliverycache/cache-' . $phpAds_config['delivery_caching'] . '.inc.php';
}
phpAds_cacheDelete();
Header("Location: maintenance-priority.php");
function phpAds_deactivateMail($campaign)
{
    global $phpAds_config;
    global $strMailSubjectDeleted, $strMailHeader, $strMailClientDeactivated;
    global $strNoMoreClicks, $strNoMoreViews, $strBeforeActivate, $strAfterExpire;
    global $strBanner, $strMailNothingLeft, $strMailFooter, $strUntitled;
    $clientresult = phpAds_dbQuery("SELECT *" . " FROM " . $phpAds_config['tbl_clients'] . " WHERE clientid=" . $campaign['clientid']);
    if ($client = phpAds_dbFetchArray($clientresult)) {
        if ($client["email"] != '' && $client["reportdeactivate"] == 't') {
            // Load config from the database
            if (!defined('LIBDBCONFIG_INCLUDED')) {
                include phpAds_path . '/libraries/lib-dbconfig.inc.php';
                phpAds_LoadDbConfig();
            }
            // Load client language strings
            @(include phpAds_path . '/language/english/default.lang.php');
            if ($client['language'] != '') {
                $phpAds_config['language'] = $client['language'];
            }
            if ($phpAds_config['language'] != 'english' && file_exists(phpAds_path . '/language/' . $phpAds_config['language'] . '/default.lang.php')) {
                @(include phpAds_path . '/language/' . $phpAds_config['language'] . '/default.lang.php');
            }
            // Build email
            $Subject = $strMailSubjectDeleted . ": " . $campaign['campaignname'];
            $Body = $strMailHeader . "\n";
            $Body .= $strMailClientDeactivated;
            if ($campaign['clicks'] == 0) {
                $Body .= ", {$strNoMoreClicks}";
            }
            if ($campaign['views'] == 0) {
                $Body .= ", {$strNoMoreViews}";
            }
            if (time() < $campaign["activate_st"]) {
                $Body .= ", {$strBeforeActivate}";
            }
            if (time() > $campaign["expire_st"] && $campaign["expire_st"] != 0) {
                $Body .= ", {$strAfterExpire}";
            }
            $Body .= ".\n\n";
            $res_banners = phpAds_dbQuery("SELECT" . " bannerid" . ",url" . ",description" . ",alt" . " FROM " . $phpAds_config['tbl_banners'] . " WHERE campaignid=" . $campaign['campaignid']);
            if (phpAds_dbNumRows($res_banners) > 0) {
                $Body .= "-------------------------------------------------------\n";
                while ($row_banners = phpAds_dbFetchArray($res_banners)) {
                    $name = "[id" . $row_banners['bannerid'] . "] ";
                    if ($row_banners['description'] != "") {
                        $name .= $row_banners['description'];
                    } elseif ($row_banners['alt'] != "") {
                        $name .= $row_banners['alt'];
                    } else {
                        $name .= $strUntitled;
                    }
                    $Body .= $strBanner . "  " . $name . "\n";
                    $Body .= "linked to: " . $row_banners['url'] . "\n";
                    $Body .= "-------------------------------------------------------\n";
                }
            }
            $Body .= "\n";
            $Body .= "{$strMailNothingLeft}\n\n";
            $Body .= "{$strMailFooter}";
            $Body = str_replace("{clientname}", $client["clientname"], $Body);
            $Body = str_replace("{contact}", $client["contact"], $Body);
            $Body = str_replace("{adminfullname}", $phpAds_config['admin_fullname'], $Body);
            // Send email
            phpAds_sendMail($client['email'], $client['contact'], $Subject, $Body);
            if ($phpAds_config['userlog_email']) {
                phpAds_userlogAdd(phpAds_actionDeactivationMailed, $campaign['campaignid'], $Subject . "\n\n" . $Body);
            }
        }
    }
}
                phpAds_processStats($begin_timestamp, $end_timestamp, $day, $hour, $report);
            } else {
                $report .= "Statistics already exist for hour " . $hour . " on " . $day . ".  Please delete the statistics if you would like to regenerate.\n";
            }
            // Now that everything is done, update the stats generation date/time.
            phpAds_logStatsDate($end_timestamp);
        } else {
            $done = true;
        }
    } else {
        $done = true;
    }
}
$report .= "No more statistics to compile.\n";
// Write the output to the user log.
phpAds_userlogAdd(phpAds_actionBatchStatistics, 0, $report);
function phpAds_processStats($begin_timestamp, $end_timestamp, $day, $hour)
{
    global $report;
    // If we are rebuilding a particular hour,
    // then increment back any inventory to campaigns and delete the stats for this hour
    $regen = false;
    // Will build later...
    if ($regen) {
        $report .= "\t REGENERATING!!/n/n";
        phpAds_undoInventory($day, $hour);
        phpAds_deleteCompactStats($day, $hour);
    }
    // Count the total views for this hour
    phpAds_countViews($begin_timestamp, $end_timestamp, $day, $hour);
    // Count the total clicks for this hour
    }
    // Send Query
    $res_campaigns = phpAds_dbQuery("\n\t\tSELECT\n\t\t\tclientid,\n\t\t\tclientname,\n\t\t\tparent,\n\t\t\tviews,\n\t\t\tclicks,\n\t\t\texpire,\n\t\t\tUNIX_TIMESTAMP(expire) as expire_st,\n\t\t\tactivate,\n\t\t\tUNIX_TIMESTAMP(activate) as activate_st,\n\t\t\tactive\n\t\tFROM\n\t\t\t" . $phpAds_config['tbl_clients'] . "\n\t\tWHERE\n\t\t\tparent = " . $client['clientid'] . "\n\t\t") or die($GLOBALS['strLogErrorClients']);
    while ($campaign = phpAds_dbFetchArray($res_campaigns)) {
        $active = "t";
        if ($campaign["clicks"] == 0 || $campaign["views"] == 0) {
            $active = "f";
        }
        if (time() < $campaign["activate_st"]) {
            $active = "f";
        }
        if (time() > $campaign["expire_st"] && $campaign["expire_st"] != 0) {
            $active = "f";
        }
        if ($campaign["active"] != $active) {
            if ($active == "t") {
                phpAds_userlogAdd(phpAds_actionActiveCampaign, $campaign['clientid']);
            } else {
                phpAds_userlogAdd(phpAds_actionDeactiveCampaign, $campaign['clientid']);
                phpAds_deactivateMail($campaign);
            }
            phpAds_dbQuery("UPDATE " . $phpAds_config['tbl_clients'] . " SET active='{$active}' WHERE clientid=" . $campaign['clientid']);
        }
        if ($active == "t" && ($phpAds_config['warn_admin'] || $phpAds_config['warn_client'])) {
            $days_left = round(($campaign["expire_st"] - phpAds_LastMidnight) / (60 * 60 * 24));
            if ($days_left == $phpAds_config['warn_limit_days']) {
                phpAds_warningMail($campaign, $campaign["expire_st"]);
            }
        }
    }
}
// $Revision: 3830 $
/************************************************************************/
/* Openads 2.0                                                          */
/* ===========                                                          */
/*                                                                      */
/* Copyright (c) 2000-2007 by the Openads developers                    */
/* For more information visit: http://www.openads.org                   */
/*                                                                      */
/* This program is free software. You can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 2 of the License.       */
/************************************************************************/
// Prevent full path disclosure
if (!defined('phpAds_path')) {
    die;
}
// Recreate geotargeting configuration
if ($phpAds_config['geotracking_type'] && phpAds_isConfigWritable()) {
    include phpAds_path . '/libraries/geotargeting/geo-' . $phpAds_config['geotracking_type'] . '.inc.php';
    if (function_exists('phpAds_' . $phpAds_geoPluginID . '_getConf')) {
        $geoconf = call_user_func('phpAds_' . $phpAds_geoPluginID . '_getConf', $phpAds_config['geotracking_location']);
    } else {
        $geoconf = '';
    }
    if ($geoconf != $phpAds_config['geotracking_conf']) {
        phpAds_SettingsWriteAdd('geotracking_conf', $geoconf);
        phpAds_SettingsWriteFlush();
        phpAds_userlogAdd(phpAds_actionGeotargeting, 0);
    }
}
function phpAds_SendMaintenanceReport($clientid, $first_unixtimestamp, $last_unixtimestamp, $update = true)
{
    global $phpAds_config;
    global $date_format;
    global $strMailSubject, $strMailHeader, $strMailBannerStats, $strMailFooter, $strMailReportPeriod;
    global $strLogErrorClients, $strLogErrorBanners, $strLogErrorViews, $strNoStatsForCampaign;
    global $strLogErrorClicks, $strNoClickLoggedInInterval, $strNoViewLoggedInInterval;
    global $strTotal, $strTotalThisPeriod;
    global $strCampaign, $strBanner, $strLinkedTo, $strViews, $strClicks, $strMailReportPeriodAll;
    global $phpAds_CharSet;
    // Convert timestamps to SQL format
    $last_sqltimestamp = date("YmdHis", $last_unixtimestamp);
    $first_sqltimestamp = date("YmdHis", $first_unixtimestamp);
    // Get Client information
    $res_client = phpAds_dbQuery("\n\t\tSELECT\n\t\t\tclientid,\n\t\t\tclientname,\n\t\t\tcontact,\n\t\t\temail,\n\t\t\tlanguage,\n\t\t\treport,\n\t\t\treportinterval,\n\t\t\treportlastdate,\n\t\t\tUNIX_TIMESTAMP(reportlastdate) AS reportlastdate_t\n\t\tFROM\n\t\t\t" . $phpAds_config['tbl_clients'] . "\n\t\tWHERE\n\t\t\tclientid='" . $clientid . "'\n\t\t");
    if (phpAds_dbNumRows($res_client) > 0) {
        $client = phpAds_dbFetchArray($res_client);
        // Load client language strings
        @(include phpAds_path . '/language/english/default.lang.php');
        if ($client['language'] != '') {
            $phpAds_config['language'] = $client['language'];
        }
        if ($phpAds_config['language'] != 'english' && file_exists(phpAds_path . '/language/' . $phpAds_config['language'] . '/default.lang.php')) {
            @(include phpAds_path . '/language/' . $phpAds_config['language'] . '/default.lang.php');
        }
        $active_campaigns = false;
        $log = "";
        // Fetch all campaings belonging to client
        $res_campaigns = phpAds_dbQuery("\n\t\t\tSELECT\n\t\t\t\tclientid,\n\t\t\t\tclientname,\n\t\t\t\tviews,\n\t\t\t\tclicks,\n\t\t\t\texpire,\n\t\t\t\tUNIX_TIMESTAMP(expire) as expire_st,\n\t\t\t\tactivate,\n\t\t\t\tUNIX_TIMESTAMP(activate) as activate_st,\n\t\t\t\tactive\n\t\t\tFROM\n\t\t\t\t" . $phpAds_config['tbl_clients'] . "\n\t\t\tWHERE\n\t\t\t\tparent = " . $client['clientid'] . "\n\t\t\n\t\t") or die($strLogErrorClients);
        while ($campaign = phpAds_dbFetchArray($res_campaigns)) {
            $current_log = '';
            // Fetch all banners belonging to campaign
            $res_banners = phpAds_dbQuery("\n\t\t\t\tSELECT\n\t\t\t\t\tbannerid,\n\t\t\t\t\tclientid,\n\t\t\t\t\turl,\n\t\t\t\t\tactive,\n\t\t\t\t\tdescription,\n\t\t\t\t\talt\n\t\t\t\tFROM\n\t\t\t\t\t" . $phpAds_config['tbl_banners'] . "\n\t\t\t\tWHERE\n\t\t\t\t\tclientid = " . $campaign['clientid'] . "\n\t\t\t\t") or die($strLogErrorBanners);
            $active_banners = false;
            $current_log .= "\n" . $strCampaign . "  " . phpAds_buildClientName($campaign['clientid'], $campaign['clientname'], false) . "\n";
            $current_log .= "=======================================================\n\n";
            while ($row_banners = phpAds_dbFetchArray($res_banners)) {
                $adviews = phpAds_totalViews($row_banners["bannerid"]);
                $client["views_used"] = $adviews;
                $adclicks = phpAds_totalClicks($row_banners["bannerid"]);
                $campaign["clicks_used"] = $adclicks;
                $current_log .= $strBanner . "  " . phpAds_buildBannerName($row_banners['bannerid'], $row_banners['description'], $row_banners['alt'], 0, false) . "\n";
                $current_log .= $strLinkedTo . ": " . $row_banners['url'] . "\n";
                $current_log .= "-------------------------------------------------------\n";
                $active_banner_stats = false;
                if ($adviews > 0) {
                    $current_log .= $strViews . " (" . $strTotal . "):    " . $adviews . "\n";
                    // Fetch all adviews belonging to banner belonging to client, grouped by day
                    if ($phpAds_config['compact_stats']) {
                        $res_adviews = phpAds_dbQuery("\n\t\t\t\t\t\t\tSELECT\n\t\t\t\t\t\t\t\tSUM(views) as qnt,\n\t\t\t\t\t\t\t\tDATE_FORMAT(day, '{$date_format}') as t_stamp_f,\n\t\t\t\t\t\t\t\tTO_DAYS(day) AS the_day\n\t\t\t\t\t\t\tFROM\n\t\t\t\t\t\t\t\t" . $phpAds_config['tbl_adstats'] . "\n\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\tbannerid = " . $row_banners['bannerid'] . " AND\n\t\t\t\t\t\t\t\tviews > 0 AND\n\t\t\t\t\t\t\t\tUNIX_TIMESTAMP(day) >= {$first_unixtimestamp} AND\n\t\t\t\t\t\t\t\tUNIX_TIMESTAMP(day) < {$last_unixtimestamp}\n\t\t\t\t\t\t\tGROUP BY\n\t\t\t\t\t\t\t\tday\n\t\t\t\t\t\t\tORDER BY\n\t\t\t\t\t\t\t\tday DESC\n\t\t\t\t\t\t\t") or die("{$strLogErrorViews} " . phpAds_dbError());
                    } else {
                        $res_adviews = phpAds_dbQuery("\n\t\t\t\t\t\t\tSELECT\n\t\t\t\t\t\t\t\t*,\n\t\t\t\t\t\t\t\tcount(*) as qnt,\n\t\t\t\t\t\t\t\tDATE_FORMAT(t_stamp, '{$date_format}') as t_stamp_f,\n\t\t\t\t\t\t\t\tTO_DAYS(t_stamp) AS the_day\n\t\t\t\t\t\t\tFROM\n\t\t\t\t\t\t\t\t" . $phpAds_config['tbl_adviews'] . "\n\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\tbannerid = " . $row_banners['bannerid'] . " AND\n\t\t\t\t\t\t\t\tt_stamp >= {$first_sqltimestamp} AND\n\t\t\t\t\t\t\t\tt_stamp < {$last_sqltimestamp}\n\t\t\t\t\t\t\tGROUP BY\n\t\t\t\t\t\t\t\tthe_day\n\t\t\t\t\t\t\tORDER BY\n\t\t\t\t\t\t\t\tthe_day DESC\n\t\t\t\t\t\t\t") or die("{$strLogErrorViews} " . phpAds_dbError());
                    }
                    if (phpAds_dbNumRows($res_adviews)) {
                        $total = 0;
                        while ($row_adviews = phpAds_dbFetchArray($res_adviews)) {
                            $current_log .= "      " . $row_adviews['t_stamp_f'] . ":   " . $row_adviews['qnt'] . "\n";
                            $total += $row_adviews['qnt'];
                        }
                        $current_log .= $strTotalThisPeriod . ": " . $total . "\n";
                        $active_banner_stats = true;
                    } else {
                        $current_log .= "      " . $strNoViewLoggedInInterval . "\n";
                    }
                }
                if ($adclicks > 0) {
                    // Total adclicks
                    $current_log .= "\n" . $strClicks . " (" . $strTotal . "):   " . $adclicks . "\n";
                    // Fetch all adclicks belonging to banner belonging to client, grouped by day
                    if ($phpAds_config['compact_stats']) {
                        $res_adclicks = phpAds_dbQuery("\n\t\t\t\t\t\t\tSELECT\n\t\t\t\t\t\t\t\tSUM(clicks) as qnt,\n\t\t\t\t\t\t\t\tDATE_FORMAT(day, '{$date_format}') as t_stamp_f,\n\t\t\t\t\t\t\t\tTO_DAYS(day) AS the_day\n\t\t\t\t\t\t\tFROM\n\t\t\t\t\t\t\t\t" . $phpAds_config['tbl_adstats'] . "\n\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\tbannerid = " . $row_banners['bannerid'] . " AND\n\t\t\t\t\t\t\t\tclicks > 0 AND\n\t\t\t\t\t\t\t\tUNIX_TIMESTAMP(day) >= {$first_unixtimestamp} AND\n\t\t\t\t\t\t\t\tUNIX_TIMESTAMP(day) < {$last_unixtimestamp}\n\t\t\t\t\t\t\tGROUP BY\n\t\t\t\t\t\t\t\tday\n\t\t\t\t\t\t\tORDER BY\n\t\t\t\t\t\t\t\tday DESC\n\t\t\t\t\t\t\t") or die("{$strLogErrorClicks} " . phpAds_dbError());
                    } else {
                        $res_adclicks = phpAds_dbQuery("\n\t\t\t\t\t\t\tSELECT\n\t\t\t\t\t\t\t\tcount(*) as qnt,\n\t\t\t\t\t\t\t\tDATE_FORMAT(t_stamp, '{$date_format}') as t_stamp_f,\n\t\t\t\t\t\t\t\tTO_DAYS(t_stamp) AS the_day\n\t\t\t\t\t\t\tFROM\n\t\t\t\t\t\t\t\t" . $phpAds_config['tbl_adclicks'] . "\n\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\tbannerid = " . $row_banners['bannerid'] . " AND\n\t\t\t\t\t\t\t\tt_stamp >= {$first_sqltimestamp} AND\n\t\t\t\t\t\t\t\tt_stamp < {$last_sqltimestamp}\n\t\t\t\t\t\t\tGROUP BY\n\t\t\t\t\t\t\t\tthe_day\n\t\t\t\t\t\t\tORDER BY\n\t\t\t\t\t\t\t\tthe_day DESC\n\t\t\t\t\t\t\t") or die("{$strLogErrorClicks} " . phpAds_dbError());
                    }
                    if (phpAds_dbNumRows($res_adclicks)) {
                        $total = 0;
                        while ($row_adclicks = phpAds_dbFetchArray($res_adclicks)) {
                            $current_log .= "      " . $row_adclicks['t_stamp_f'] . ":   " . $row_adclicks['qnt'] . "\n";
                            $total += $row_adclicks['qnt'];
                        }
                        $current_log .= $strTotalThisPeriod . ": " . $total . "\n";
                        $active_banner_stats = true;
                    } else {
                        $current_log .= "      " . $strNoClickLoggedInInterval . "\n";
                    }
                }
                if ($adclicks == 0 && $adviews == 0) {
                    $current_log .= "      " . $strNoStatsForCampaign . "\n";
                }
                $current_log .= "\n\n";
                if ($campaign['active'] == 't' || $active_banner_stats == true) {
                    $active_banners = true;
                }
            }
            if ($active_banners == true) {
                $active_campaigns = true;
                $log .= $current_log;
            }
        }
        // E-mail Stats to active clients
        if ($client["email"] != '' && $active_campaigns == true) {
            $Subject = $strMailSubject . ": " . $client["clientname"];
            $Body = "{$strMailHeader}\n";
            $Body .= "{$strMailBannerStats}\n";
            if ($first_unixtimestamp == 0) {
                $Body .= "{$strMailReportPeriodAll}\n\n";
            } else {
                $Body .= "{$strMailReportPeriod}\n\n";
            }
            $Body .= "{$log}\n";
            $Body .= "{$strMailFooter}";
            $Body = str_replace("{clientname}", $client['clientname'], $Body);
            $Body = str_replace("{contact}", $client['contact'], $Body);
            $Body = str_replace("{adminfullname}", $phpAds_config['admin_fullname'], $Body);
            $Body = str_replace("{startdate}", date(str_replace('%', '', $date_format), $first_unixtimestamp), $Body);
            $Body = str_replace("{enddate}", date(str_replace('%', '', $date_format), $last_unixtimestamp), $Body);
            if ($phpAds_config['userlog_email']) {
                phpAds_userlogAdd(phpAds_actionAdvertiserReportMailed, $client['clientid'], $Subject . "\n\n" . $Body);
            }
            phpAds_sendMail($client['email'], $client['contact'], $Subject, $Body);
            // Update last run
            if ($update == true) {
                $res_update = phpAds_dbQuery("UPDATE " . $phpAds_config['tbl_clients'] . " SET reportlastdate=NOW() WHERE clientid=" . $client['clientid']);
            }
            return true;
        }
    }
    return false;
}