/** * A method to prune the data_summary_ad_zone_assoc table * Pruning can be performed where zone_id = 0 (i.e. for direct selection) and where the entry is older than MAX_PREVIOUS_AD_DELIVERY_INFO_LIMIT minutes ago. * * @return integer : number of records deleted */ function _pruneDataSummaryAdZoneAssocOldData() { $doDSAZA = OA_Dal::factoryDO('data_summary_ad_zone_assoc'); $doDSAZA->whereAdd('zone_id=0', 'AND'); $doDSAZA->whereAdd('created < DATE_ADD(' . $this->oDbh->quote(OA::getNow()) . ', ' . OA_Dal::quoteInterval(-MAX_PREVIOUS_AD_DELIVERY_INFO_LIMIT, 'SECOND') . ')', 'AND'); return $doDSAZA->delete(true, false); }
function phpAds_userlogAdd($action, $object, $details = '') { $oDbh =& OA_DB::singleton(); $conf = $GLOBALS['_MAX']['CONF']; global $phpAds_Usertype; if ($phpAds_Usertype != 0) { $usertype = $phpAds_Usertype; $userid = 0; } else { $usertype = phpAds_userAdministrator; $userid = 0; } $now = strtotime(OA::getNow()); $query = "\n INSERT INTO\n " . $oDbh->quoteIdentifier($conf['table']['prefix'] . $conf['table']['userlog'], true) . "\n (\n timestamp,\n usertype,\n userid,\n action,\n object,\n details\n )\n VALUES\n (\n " . $oDbh->quote($now, 'integer') . ",\n " . $oDbh->quote($usertype, 'integer') . ",\n " . $oDbh->quote($userid, 'integer') . ",\n " . $oDbh->quote($action, 'integer') . ",\n " . $oDbh->quote($object, 'integer') . ",\n " . $oDbh->quote($details, 'text') . "\n )"; $res = $oDbh->exec($query); if (PEAR::isError($res)) { return $res; } return true; }
function sendCampaignDeliveryEmail($aAdvertiser, $oStartDate = null, $oEndDate = null, $campaignId = null) { $aConf = $GLOBALS['_MAX']['CONF']; $aAdvertiserPrefs = OA_Preferences::loadAccountPreferences($aAdvertiser['account_id'], true); $oTimezone = new Date_Timezone($aAdvertiserPrefs['timezone']); $this->convertStartEndDate($oStartDate, $oEndDate, $oTimezone); $aLinkedUsers = $this->getUsersLinkedToAccount('clients', $aAdvertiser['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->prepareCampaignDeliveryEmail($aUser, $aAdvertiser['clientid'], $oStartDate, $oEndDate, $campaignId); if ($aEmail !== false) { if (!isset($aEmail['hasAdviews']) || $aEmail['hasAdviews'] !== false) { if ($this->sendMail($aEmail['subject'], $aEmail['contents'], $aUser['email_address'], $aUser['contact_name'], $aFromDetails)) { $copiesSent++; if ($aConf['email']['logOutgoing']) { phpAds_userlogSetUser(phpAds_userMaintenance); phpAds_userlogAdd(phpAds_actionAdvertiserReportMailed, $aAdvertiser['clientid'], "{$aEmail['subject']}\n\n\n {$aUser['contact_name']}({$aUser['email_address']})\n\n\n {$aEmail['contents']}"); } } } } } } // Only update the last sent date if we actually sent out at least one copy of the email if ($copiesSent) { // Update the last run date to "today" OA::debug(' - Updating the date the report was last sent for advertiser ID ' . $aAdvertiser['clientid'] . '.', PEAR_LOG_DEBUG); $doUpdateClients = OA_Dal::factoryDO('clients'); $doUpdateClients->clientid = $aAdvertiser['clientid']; $doUpdateClients->reportlastdate = OA::getNow(); $doUpdateClients->update(); } return $copiesSent; }
function updateAuditAction($aParams = array()) { $id = isset($aParams['id']) ? $aParams['id'] : $this->getUpgradeActionId(); unset($aParams['id']); if (!$id) { $this->logError('upgrade_action_id is empty'); return false; } $aParams = $this->_escapeParams($aParams); $values = ''; foreach ($aParams as $k => $v) { $values .= "{$k}={$v},"; } $values .= "updated='" . OA::getNow() . "'"; $table = $this->getLogTableName(); $query = "UPDATE {$table} SET {$values} WHERE upgrade_action_id={$id}"; $result = $this->oDbh->exec($query); if ($this->isPearError($result, "error inserting {$this->prefix}{$this->logTable}")) { return false; } return true; }
/** * method for extending OA_Test_Data_DataObject */ function generateTestData() { if (!parent::init()) { return false; } // Disable Auditing while loading the test data: $GLOBALS['_MAX']['CONF']['audit']['enabled'] = false; parent::generateTestData(); for ($hour = 0; $hour < 24; $hour++) { $doDSAH = OA_Dal::factoryDO('data_summary_ad_hourly'); $doDSAH->date_time = sprintf('%s %02d:00:00', substr(OA::getNow(), 0, 10), $hour); $doDSAH->ad_id = $this->aIds['banners'][1]; $doDSAH->creative_id = rand(1, 999); $doDSAH->zone_id = $this->aIds['zones'][1]; $doDSAH->requests = rand(1, 999); $doDSAH->impressions = rand(1, 999); $doDSAH->clicks = rand(1, 999); $doDSAH->conversions = rand(1, 999); $doDSAH->total_basket_value = 0; $this->aIds['DSAH'][] = DataGenerator::generateOne($doDSAH); } return $this->aIds; }
function test_MAX_AclSave() { // insert a channel $doChannel = OA_Dal::factoryDO('channel'); $channelId = DataGenerator::generateOne($doChannel); $doChannel->channelid = $channelId; // insert a banner $doBanners = OA_Dal::factoryDO('banners'); $bannerId = DataGenerator::generateOne($doBanners); $doBanners->bannerid = $bannerId; $doBanners->acls_updated = OA::getNow(); $doBanners->update(); $updated1 = $doBanners->acls_updated; // save a banner limited by date/time $aAcls[1]['data'] = '0,1'; $aAcls[1]['logical'] = 'and'; $aAcls[1]['type'] = 'Dummy:Dummy'; $aAcls[1]['comparison'] = '=~'; $aAcls[1]['executionorder'] = 1; $sLimitation = "MAX_checkDummy_Dummy('0,1', '=~')"; $aEntities = array('bannerid' => $bannerId); $this->assertTrue(MAX_AclSave(array($aAcls[1]), $aEntities, 'banner-acl.php')); $doBanners = OA_Dal::staticGetDO('banners', $bannerId); $this->assertTrue($doBanners); $this->assertEqual($sLimitation, $doBanners->compiledlimitation); $doAcls = OA_Dal::factoryDO('acls'); $doAcls->whereAdd('bannerid = ' . $bannerId); $this->assertTrue($doAcls->find(true)); $this->assertEqual($doAcls->bannerid, $bannerId); $this->assertEqual($doAcls->logical, $aAcls[1]['logical']); $this->assertEqual($doAcls->type, $aAcls[1]['type']); $this->assertEqual($doAcls->comparison, $aAcls[1]['comparison']); $this->assertEqual($doAcls->data, $aAcls[1]['data']); $this->assertEqual($doAcls->executionorder, $aAcls[1]['executionorder']); $this->assertFalse($doAcls->fetch()); }
/** * A method to prune the data_summary_ad_zone_assoc table * Prune all entries where the ad_id is for a banner in a High Priority Campaign where: * The campaign does not have any booked lifetime target values AND the caMpaign has an end date AND the end date has been passed AND the campaign is not active. * * @return integer : number of records deleted */ function _pruneDataSummaryAdZoneAssocInactiveExpired() { $tblAssoc = $this->_getTablename('data_summary_ad_zone_assoc'); $tblBanners = $this->_getTablename('banners'); $tblCampaigns = $this->_getTablename('campaigns'); $queryEnd = '' . ' LEFT JOIN ' . $tblCampaigns . ' AS c ON b.campaignid = c.campaignid' . ' WHERE ( ( c.status <> ' . OA_ENTITY_STATUS_RUNNING . ') AND (c.priority > 0 )) ' . ' AND' . '(' . ' (' . ' (c.target_impression < 1)' . ' AND' . ' (c.target_click < 1)' . ' AND' . ' (c.target_conversion < 1)' . ' )' . ' AND' . ' (UNIX_TIMESTAMP(c.expire) > 0)' . ' AND' . ' (c.expire < ' . $this->oDbh->quote(OA::getNow('Y-m-d')) . ')' . ')'; if ($this->oDbh->dbsyntax == 'pgsql') { $query = 'DELETE FROM ' . $tblAssoc . ' WHERE data_summary_ad_zone_assoc_id IN (' . ' SELECT dsaza.data_summary_ad_zone_assoc_id FROM' . ' ' . $tblAssoc . ' AS dsaza' . ' LEFT JOIN ' . $tblBanners . ' AS b ON dsaza.ad_id = b.bannerid' . $queryEnd . ')'; } else { $query = 'DELETE FROM ' . $tblAssoc . ' USING ' . $tblAssoc . ' LEFT JOIN ' . $tblBanners . ' AS b ON ' . $tblAssoc . '.ad_id = b.bannerid' . $queryEnd; } return $this->oDbh->exec($query); }
function processForm($aAdvertiser, $form) { $aFields = $form->exportValues(); // Name if (OA_Permission::isAccount(OA_ACCOUNT_MANAGER)) { $aAdvertiser['clientname'] = $aFields['clientname']; } // Default fields $aAdvertiser['contact'] = $aFields['contact']; $aAdvertiser['email'] = $aFields['email']; $aAdvertiser['comments'] = $aFields['comments']; // Same advertiser limitation $aAdvertiser['advertiser_limitation'] = $aFields['advertiser_limitation'] == '1' ? 1 : 0; // Reports $aAdvertiser['report'] = $aFields['report'] == 't' ? 't' : 'f'; $aAdvertiser['reportdeactivate'] = $aFields['reportdeactivate'] == 't' ? 't' : 'f'; $aAdvertiser['reportinterval'] = (int) $aFields['reportinterval']; if ($aAdvertiser['reportinterval'] == 0) { $aAdvertiser['reportinterval'] = 1; } if ($aFields['reportlastdate'] == '' || $aFields['reportlastdate'] == '0000-00-00' || $aFields['reportprevious'] != $aAdvertiser['report']) { $aAdvertiser['reportlastdate'] = date("Y-m-d"); } if (empty($aAdvertiser['clientid'])) { // Set agency ID $aAdvertiser['agencyid'] = OA_Permission::getAgencyId(); $doClients = OA_Dal::factoryDO('clients'); $doClients->setFrom($aAdvertiser); $doClients->updated = OA::getNow(); // Insert $aAdvertiser['clientid'] = $doClients->insert(); // Queue confirmation message $translation = new OX_Translation(); $translated_message = $translation->translate($GLOBALS['strAdvertiserHasBeenAdded'], array(MAX::constructURL(MAX_URL_ADMIN, 'advertiser-edit.php?clientid=' . $aAdvertiser['clientid']), htmlspecialchars($aAdvertiser['clientname']), MAX::constructURL(MAX_URL_ADMIN, 'campaign-edit.php?clientid=' . $aAdvertiser['clientid']))); OA_Admin_UI::queueMessage($translated_message, 'local', 'confirm', 0); // Go to next page OX_Admin_Redirect::redirect("advertiser-index.php"); } else { $doClients = OA_Dal::factoryDO('clients'); $doClients->get($aAdvertiser['clientid']); $doClients->setFrom($aAdvertiser); $doClients->updated = OA::getNow(); $doClients->update(); // Queue confirmation message $translation = new OX_Translation(); $translated_message = $translation->translate($GLOBALS['strAdvertiserHasBeenUpdated'], array(MAX::constructURL(MAX_URL_ADMIN, 'advertiser-edit.php?clientid=' . $aAdvertiser['clientid']), htmlspecialchars($aAdvertiser['clientname']))); OA_Admin_UI::queueMessage($translated_message, 'local', 'confirm', 0); OX_Admin_Redirect::redirect('advertiser-edit.php?clientid=' . $aAdvertiser['clientid']); } exit; }
/** * Update "updated" status of entity (if necessesary) * * @param string $entity * @param array $aVariables */ function _updateEntityTimestamp($entity, &$aVariables) { if (in_array($entity, $GLOBALS['_MAX']['Admin_DA']['updateEntities'])) { $aVariables['updated'] = OA::getNow(); } }
function MAX_AclSave($acls, $aEntities, $page = false) { //$conf = $GLOBALS['_MAX']['CONF']; $oDbh =& OA_DB::singleton(); if ($page === false) { $page = basename($_SERVER['PHP_SELF']); } if ('banner-acl.php' == $page) { $table = 'banners'; $aclsTable = 'acls'; $fieldId = 'bannerid'; } else { if ('channel-acl.php' == $page) { $table = 'channel'; $aclsTable = 'acls_channel'; $fieldId = 'channelid'; } else { return false; } } $aclsObjectId = $aEntities[$fieldId]; $sLimitation = OA_aclGetSLimitationFromAAcls($acls); $doTable = OA_Dal::factoryDO($table); $doTable->{$fieldId} = $aclsObjectId; $found = $doTable->find(true); if ($sLimitation == $doTable->compiledlimitation) { return true; // No changes to the ACL } $doAcls = OA_Dal::factoryDO($aclsTable); $doAcls->whereAdd($fieldId . ' = ' . $aclsObjectId); $doAcls->delete(true); if (!empty($acls)) { foreach ($acls as $acl) { $deliveryLimitationPlugin =& OA_aclGetComponentFromRow($acl); $doAcls = OA_Dal::factoryDO($aclsTable); $doAcls->{$fieldId} = $aclsObjectId; $doAcls->logical = $acl['logical']; $doAcls->type = $acl['type']; $doAcls->comparison = $acl['comparison']; $doAcls->data = $deliveryLimitationPlugin->getData(); $doAcls->executionorder = $acl['executionorder']; $id = $doAcls->insert(); if (!$id) { return false; } } } $doTable->acl_plugins = MAX_AclGetPlugins($acls); $doTable->compiledlimitation = $sLimitation; $doTable->update(); // When a channel limitation changes - All banners with this channel must be re-learnt if ($page == 'channel-acl.php') { $affected_ads = array(); $table = modifyTableName('acls'); $query = "\n SELECT\n DISTINCT(bannerid)\n FROM\n {$table}\n WHERE\n type = 'Site:Channel'\n AND (data = '{$aclsObjectId}' OR data LIKE '%,{$aclsObjectId}' OR data LIKE '%,{$aclsObjectId},%' OR data LIKE '{$aclsObjectId},%')\n "; $res = $oDbh->query($query); if (PEAR::isError($res)) { return $res; } while ($row = $res->fetchRow()) { $doBanners = OA_Dal::staticGetDO('banners', $row['bannerid']); if ($doBanners->bannerid == $row['bannerid']) { $doBanners->acls_updated = OA::getNow(); $doBanners->update(); } } } return true; }
/** * A method to reject conversions which variables which are required to be * non-empty, but which are in reality, empty, between the supplied operation * interval start and end dates. * * @param PEAR::Date $oStart The start date/time of the operation interval. * @param PEAR::Date $oEnd The end date/time of the operation interval. */ function rejectEmptyVarConversions($oStart, $oEnd) { $aConf = $GLOBALS['_MAX']['CONF']; $query = "\n UPDATE\n {$aConf['table']['prefix']}{$aConf['table']['data_intermediate_ad_connection']} AS diac\n JOIN\n {$aConf['table']['prefix']}{$aConf['table']['variables']} AS v\n ON\n (\n diac.tracker_id = v.trackerid\n )\n LEFT JOIN\n {$aConf['table']['prefix']}{$aConf['table']['data_intermediate_ad_variable_value']} AS diavv\n ON\n (\n diac.data_intermediate_ad_connection_id = diavv.data_intermediate_ad_connection_id\n AND\n v.variableid = diavv.tracker_variable_id\n )\n SET\n diac.connection_status = " . MAX_CONNECTION_STATUS_DISAPPROVED . ",\n diac.updated = '" . OA::getNow() . "',\n diac.comments = CONCAT('Rejected because ', COALESCE(NULLIF(v.description, ''), v.name), ' is empty')\n WHERE\n diac.tracker_date_time >= " . $this->oDbh->quote($oStart->format('%Y-%m-%d %H:%M:%S'), 'timestamp') . "\n AND\n diac.tracker_date_time <= " . $this->oDbh->quote($oEnd->format('%Y-%m-%d %H:%M:%S'), 'timestamp') . "\n AND\n diac.inside_window = 1\n AND\n v.reject_if_empty = 1\n AND\n (diavv.value IS NULL OR diavv.value = '')\n "; $message = '- Rejecting conversions with empty required variables between ' . $oStart->format('%Y-%m-%d %H:%M:%S') . ' ' . $oStart->tz->getShortName() . ' and ' . $oEnd->format('%Y-%m-%d %H:%M:%S') . ' ' . $oEnd->tz->getShortName(); OA::debug($message, PEAR_LOG_DEBUG); $rows = $this->oDbh->exec($query); if (PEAR::isError($rows)) { return MAX::raiseError($rows, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE); } }
/** * A method to update maintenance last run information for * old maintenance code. */ function updateLastRun($bScheduled = false) { $sField = $bScheduled ? 'maintenance_cron_timestamp' : 'maintenance_timestamp'; OA_Dal_ApplicationVariables::set($sField, OA::getNow('U')); // Make sure that the maintenance delivery cache is regenerated MAX_cacheCheckIfMaintenanceShouldRun(false); }
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); }
// Initialise some parameters $pageName = basename($_SERVER['PHP_SELF']); $tabindex = 1; $aEntities = array('clientid' => $clientid, 'campaignid' => $campaignid, 'bannerid' => $bannerid); if (!empty($action)) { $acl = MAX_AclAdjust($acl, $action); } elseif (!empty($submit)) { $acl = isset($acl) ? $acl : array(); // Only save when inputs are valid if (OX_AclCheckInputsFields($acl, $pageName) === true) { $aBannerPrev = MAX_cacheGetAd($bannerid, false); MAX_AclSave($acl, $aEntities); $block = _initCappingVariables($time, $cap, $session_capping); $values = array(); $acls_updated = false; $now = OA::getNow(); if ($aBannerPrev['block_ad'] != $block) { $values['block'] = $block; $acls_updated = $block == 0 ? true : $acls_updated; } if ($aBannerPrev['cap_ad'] != $cap) { $values['capping'] = $cap; $acls_updated = $cap == 0 ? true : $acls_updated; } if ($aBannerPrev['session_cap_ad'] != $session_capping) { $values['session_capping'] = $session_capping; $acls_updated = $session_capping == 0 ? true : $acls_updated; } if ($acls_updated) { $values['acls_updated'] = $now; }
/** * TODO: Should we refactor this method in more general one? * (maybe by creating common abstract class for all summary tables?) * * @param string $operation Either + or - * @param int $basketValue * @param int $numItems * @param int $ad_id * @param int $creative_id * @param int $zone_id * @param strin $day * @param string $hour * @return unknown */ function addConversion($operation, $basketValue, $numItems, $ad_id, $creative_id, $zone_id, $day, $hour, $table = null) { $prefix = $this->getTablePrefix(); if ($operation != '-') { $operation = '+'; } if ($table == null) { $table = $this->table; } $oDbh = OA_DB::singleton(); $table = $oDbh->quoteIdentifier($prefix . $table, true); $query = ' UPDATE ' . $table . ' SET conversions=conversions' . $operation . '1 , total_basket_value=total_basket_value' . $operation . DBC::makeLiteral($basketValue) . ' , total_num_items=total_num_items' . $operation . DBC::makeLiteral($numItems) . ' , updated = \'' . OA::getNow() . '\' WHERE ad_id = ' . DBC::makeLiteral($ad_id) . ' AND creative_id = ' . DBC::makeLiteral($creative_id) . ' AND zone_id = ' . DBC::makeLiteral($zone_id) . ' AND date_time = ' . DBC::makeLiteral(sprintf("%s %02d:00:00", $day, $hour)); return DBC::execute($query); }
/** * create uniquely named copies of affected tables * audit each backup * * @return boolean */ function _backup() { if ($this->doBackups) { $aTables = $this->aChanges['affected_tables'][$this->timingStr]; $this->aDBTables = $this->_listTables(); if (!empty($aTables)) { $this->oAuditor->logAuditAction(array('info1' => 'BACKUP STARTED', 'action' => DB_UPGRADE_ACTION_BACKUP_STARTED)); // Create backup SQL functions if needed $result = OA_DB::createFunctions(true); if ($this->_isPearError($result, 'error creating backup SQL functions')) { $this->_halt(); $this->oAuditor->logAuditAction(array('info1' => 'BACKUP FAILED', 'info2' => 'creating backup SQL functions', 'action' => DB_UPGRADE_ACTION_BACKUP_FAILED)); return false; } // Backup tables foreach ($aTables as $k => &$table) { if (in_array($this->prefix . $table, $this->aDBTables)) { $string = $this->versionTo . $this->timingStr . $this->database . $this->prefix . $table . OA::getNow(); // Create the table name using a 64bit hex string (16 char) // Uniqueness is guaranteed using a second crc32 call with a // slightly modified string $table_bak = sprintf('z_%08x%08x', crc32($string), crc32("@" . $string)); $this->aMessages[] = "backing up table {$this->prefix}{$table} to table {$this->prefix}{$table_bak} "; $statement = $this->aSQLStatements['table_copy']; $query = sprintf($statement, $this->prefix . $table_bak, $this->prefix . $table); $result = $this->oSchema->db->exec($query); if ($this->_isPearError($result, 'error creating backup')) { $this->_halt(); $this->oAuditor->logAuditAction(array('info1' => 'BACKUP FAILED', 'info2' => 'creating backup table' . $table_bak, 'action' => DB_UPGRADE_ACTION_BACKUP_FAILED)); return false; } $aDef = $this->_getDefinitionFromDatabase($table); $aBakDef = $aDef['tables'][$table]; // keeping the restore array alive is no longer necessary after refactored recovery // $this->aRestoreTables[$table] = array( // 'bak'=>$table_bak, // 'def'=>$aBakDef // ); $this->oAuditor->logAuditAction(array('info1' => 'copied table', 'tablename' => $table, 'tablename_backup' => $table_bak, 'table_backup_schema' => serialize($aBakDef), 'action' => DB_UPGRADE_ACTION_BACKUP_TABLE_COPIED)); } else { $this->aAddedTables[$table] = true; } } $this->oAuditor->logAuditAction(array('info1' => 'BACKUP COMPLETE', 'action' => DB_UPGRADE_ACTION_BACKUP_SUCCEEDED)); } else { $this->oAuditor->logAuditAction(array('info1' => 'BACKUP UNNECESSARY', 'action' => DB_UPGRADE_ACTION_BACKUP_SUCCEEDED)); } } else { $this->oAuditor->logAuditAction(array('info1' => 'BACKUP IGNORED', 'action' => DB_UPGRADE_ACTION_BACKUP_IGNORED)); } return true; }
function delete($useWhere = false, $cascade = true, $parentid = null) { // Find acls which use this channels $dalAcls = OA_Dal::factoryDAL('acls'); $rsChannel = $dalAcls->getAclsByDataValueType($this->channelid, 'Site:Channel'); $rsChannel->reset(); while ($rsChannel->next()) { // Get the IDs of the banner that's using this channel $bannerId = $rsChannel->get('bannerid'); // Get the remaining channels the banner will use, if any $aChannelIds = explode(',', $rsChannel->get('data')); $aChannelIds = array_diff($aChannelIds, array($this->channelid)); // Prepare to update the banner's limitations in the "acls" table $doAcls = DB_DataObject::factory('acls'); $doAcls->init(); $doAcls->bannerid = $bannerId; $doAcls->executionorder = $rsChannel->get('executionorder'); if (!empty($aChannelIds)) { $doAcls->data = implode(',', $aChannelIds); $doAcls->update(); } else { $doAcls->delete(); } // Re-compile the banner's limitations $aAcls = array(); $doAcls = DB_DataObject::factory('acls'); $doAcls->init(); $doAcls->bannerid = $bannerId; $doAcls->orderBy('executionorder'); $doAcls->find(); while ($doAcls->fetch()) { $aData = $doAcls->toArray(); $deliveryLimitationPlugin = OX_Component::factoryByComponentIdentifier('deliveryLimitations:' . $aData['type']); if ($deliveryLimitationPlugin) { $deliveryLimitationPlugin->init($aData); if ($deliveryLimitationPlugin->isAllowed($page)) { $aAcls[$aData['executionorder']] = $aData; } } } $sLimitation = MAX_AclGetCompiled($aAcls, $page); // TODO: it should be done inside plugins instead, there is no need to slash the data $sLimitation = !get_magic_quotes_runtime() ? stripslashes($sLimitation) : $sLimitation; $doBanners = OA_Dal::factoryDO('banners'); $doBanners->bannerid = $bannerId; $doBanners->find(); $doBanners->fetch(); $doBanners->acl_plugins = MAX_AclGetPlugins($aAcls); $doBanners->acls_updated = OA::getNow(); $doBanners->compiledlimitation = $sLimitation; $doBanners->update(); } return parent::delete($useWhere, $cascade, $parentid); }
function insertTracker($index) { $doAffiliate = OA_Dal::factoryDO('affiliates'); $doAffiliate->agencyid = $this->agencyId; $doAffiliate->name = 'Default Publisher ' . $index; $doAffiliate->mnemonic = 'pub' . $index; $doAffiliate->comments = ''; $doAffiliate->contact = 'publisher' . $index; $doAffiliate->email = 'publisher' . $index . '@example.com'; $doAffiliate->website = 'http://www.example.com'; $doAffiliate->username = ''; $doAffiliate->password = ''; $doAffiliate->permissions = ''; $doAffiliate->language = ''; $doAffiliate->publiczones = 't'; //$doAffiliate->last_accepted_agency_agreement = ''; $doAffiliate->updated = OA::getNow(); $this->affiliateId = DataGenerator::generateOne($doAffiliate); }
/** * A method to set the basic financial information in a summary table, * on the basis of given ad financial information. * * @access private * @param array $aAdFinanceInfo An array of arrays, each with the ad_id, revenue and * revenue_type information for the ads that need updating. * @param PEAR::Date $oStartDate The start date of records that need updating. * @param PEAR::Date $oEndDate The end date of records that need updating. * @param string $table The name of the summary table to update with financial * information (e.g. 'data_summary_ad_hourly'). * * Note: The method looks for a special variable in the service locator, called * "aAdFinanceMappings". If found, and an array, the contents of the array * are used to determine the column name that should be used when calculating * the finance information in the SQL statement, for the appropriate revenue * type. If not found, the default mapping is used: * array( * MAX_FINANCE_CPM => impressions, * MAX_FINANCE_CPC => clicks, * MAX_FINANCE_CPA => conversions * ) * * Note: The method looks for a special variable in the service locator, called * "aAdFinanceLimitTypes". If found, and an array, the contents of the array * are tested to see if the revenue type set for the ad ID to be updated is * in the array. If it is not, then the finance information is not set for * the ad. * * @TODO Update to deal with monthly tenancy. */ function _saveSummaryUpdateAdsWithFinanceInfo($aAdFinanceInfo, $oStartDate, $oEndDate, $table) { $aConf = $GLOBALS['_MAX']['CONF']; if ($oStartDate->format('%H') != 0 || $oEndDate->format('%H') != 23) { if ($oStartDate->format('%Y-%m-%d') != $oEndDate->format('%Y-%m-%d')) { MAX::raiseError('_saveSummaryUpdateAdsWithFinanceInfo called with dates not on the same day.', null, PEAR_ERROR_DIE); } } $oServiceLocator =& OA_ServiceLocator::instance(); // Prepare the revenue type to column name mapping array $aAdFinanceMappings =& $oServiceLocator->get('aAdFinanceMappings'); if ($aAdFinanceMappings === false || !array($aAdFinanceMappings) || empty($aAdFinanceMappings)) { $aAdFinanceMappings = array(MAX_FINANCE_CPM => 'impressions', MAX_FINANCE_CPC => 'clicks', MAX_FINANCE_CPA => 'conversions'); } // Try to get the $aAdFinanceLimitTypes array $aAdFinanceLimitTypes =& $oServiceLocator->get('aAdFinanceLimitTypes'); foreach ($aAdFinanceInfo as $aInfo) { $query = ''; $setInfo = true; // Test to see if the finance information should NOT be set for this ad if ($aAdFinanceLimitTypes !== false) { if (is_array($aAdFinanceLimitTypes) && !empty($aAdFinanceLimitTypes)) { // Try to find the ad's revenue type in the array if (!in_array($aInfo['revenue_type'], $aAdFinanceLimitTypes)) { // It's not in the array, don't set the finance info $setInfo = false; } } } // Prepare the SQL query to set the revenue information, if required if ($setInfo) { switch ($aInfo['revenue_type']) { case MAX_FINANCE_CPM: $query = "\n UPDATE\n " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table'][$table], true) . "\n SET\n total_revenue = {$aAdFinanceMappings[MAX_FINANCE_CPM]} * {$aInfo['revenue']} / 1000,\n updated = '" . OA::getNow() . "'\n WHERE\n ad_id = {$aInfo['ad_id']}\n AND date_time >= " . $this->oDbh->quote($oStartDate->format('%Y-%m-%d %H:%M:%S'), 'timestamp') . "\n AND date_time <= " . $this->oDbh->quote($oEndDate->format('%Y-%m-%d %H:%M:%S'), 'timestamp'); break; case MAX_FINANCE_CPC: $query = "\n UPDATE\n " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table'][$table], true) . "\n SET\n total_revenue = {$aAdFinanceMappings[MAX_FINANCE_CPC]} * {$aInfo['revenue']},\n updated = '" . OA::getNow() . "'\n WHERE\n ad_id = {$aInfo['ad_id']}\n AND date_time >= " . $this->oDbh->quote($oStartDate->format('%Y-%m-%d %H:%M:%S'), 'timestamp') . "\n AND date_time <= " . $this->oDbh->quote($oEndDate->format('%Y-%m-%d %H:%M:%S'), 'timestamp'); break; case MAX_FINANCE_CPA: $query = "\n UPDATE\n " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table'][$table], true) . "\n SET\n total_revenue = {$aAdFinanceMappings[MAX_FINANCE_CPA]} * {$aInfo['revenue']},\n updated = '" . OA::getNow() . "'\n WHERE\n ad_id = {$aInfo['ad_id']}\n AND date_time >= " . $this->oDbh->quote($oStartDate->format('%Y-%m-%d %H:%M:%S'), 'timestamp') . "\n AND date_time <= " . $this->oDbh->quote($oEndDate->format('%Y-%m-%d %H:%M:%S'), 'timestamp'); break; } } if (!empty($query)) { $rows = $this->oDbh->exec($query); if (PEAR::isError($rows)) { return MAX::raiseError($rows, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE); } } } }
/** * A method to determine how long it will be until a campaign "expires". * * Returns the earliest possible date from the following values: * - The campaign's expiration date, if set. * - The eStimated expiration date based on lifetime impression delivery * rate, if applicable. * - The eStimated expiration date based on lifetime click delivery rate * if applicable. * - The eStimated expiration date based on lifetime conversion rate, * if applicable. * * Usage: * $desc = $dalCampaigns->getDaysLeftString($campaignid); * * Where: * $desc is a string to display giving how the expiration was calculated * eg. "Estimated expiration", or that there is no expiration date * * @param integer $campaignId The campaign ID. * @return string */ function getDaysLeftString($campaignId) { global $date_format, $strNoExpiration, $strDaysLeft, $strEstimated, $strExpirationDate, $strNoExpirationEstimation, $strDaysAgo, $strCampaignStop; $prefix = $this->getTablePrefix(); // Define array to store possible expiration date results $aExpiration = array(); // Get the campaign target info $now = OA::getNow('Y-m-d'); $doCampaigns = OA_Dal::factoryDO('campaigns'); $doCampaigns->selectAdd("views AS impressions"); $doCampaigns->get($campaignId); $aCampaignData = $doCampaigns->toArray(); if (!empty($aCampaignData['expire_time'])) { $oNow = new Date($now); $oNow->setHour(0); $oNow->setMinute(0); $oNow->setSecond(0); $oDate = new Date($aCampaignData['expire_time']); $oDate->setTZbyID('UTC'); $oDate->convertTZ($oNow->tz); $oDate->setHour(0); $oDate->setMinute(0); $oDate->setSecond(0); $oSpan = new Date_Span(); $oSpan->setFromDateDiff($oNow, $oDate); $aCampaignData['expire_f'] = $oDate->format($date_format); $aCampaignData['days_left'] = $oSpan->toDays() * ($oDate->before($oNow) ? -1 : 1); } $oDbh = OA_DB::singleton(); $tableB = $oDbh->quoteIdentifier($prefix . 'banners', true); $tableD = $oDbh->quoteIdentifier($prefix . 'data_intermediate_ad', true); // Define array to return the expiration dates (if they exist) $aReturn = array('estimatedExpiration' => '', 'campaignExpiration' => ''); // Does the campaign have lifetime impression targets? // If yes, try to get a stimated expiration date if ($aCampaignData['impressions'] > 0) { $query = "\n \t SELECT\n \t SUM(dia.impressions) AS delivered,\n \t DATE_FORMAT(MIN(dia.date_time), '%Y-%m-%d') AS day_of_first\n \t FROM\n \t {$tableD} AS dia,\n \t {$tableB} AS b\n \t WHERE\n \t dia.ad_id = b.bannerid\n \t AND\n \t b.campaignid = " . DBC::makeLiteral($campaignId); $rsImpressions = DBC::FindRecord($query); if ($rsImpressions) { $aImpressions = $rsImpressions->toArray(); // Get the number of days until the campaign will end // based on the impression target delivery data $aExpiration = $this->_calculateRemainingDays($aImpressions, $aCampaignData['impressions']); } } elseif ($aCampaignData['clicks'] > 0) { $query = "\n \t SELECT\n \t SUM(dia.clicks) AS delivered,\n \t DATE_FORMAT(MIN(dia.date_time), '%Y-%m-%d') AS day_of_first\n \t FROM\n \t {$tableD} AS dia,\n \t {$tableB} AS b\n \t WHERE\n \t dia.ad_id = b.bannerid\n \t AND\n \t b.campaignid = " . DBC::makeLiteral($campaignId); $rsClicks = DBC::FindRecord($query); if ($rsClicks) { $aClicks = $rsClicks->toArray(); // Get the number of days until the campaign will end // based on the click target delivery data $aExpiration = $this->_calculateRemainingDays($aClicks, $aCampaignData['clicks']); } } elseif ($aCampaignData['conversions'] > 0) { $query = "\n \t SELECT\n \t SUM(dia.conversions) AS delivered,\n \t DATE_FORMAT(MIN(dia.date_time), '%Y-%m-%d') AS day_of_first\n \t FROM\n \t {$tableD} AS dia,\n \t {$tableB} AS b\n \t WHERE\n \t dia.ad_id = b.bannerid\n \t AND\n \t b.campaignid = " . DBC::makeLiteral($campaignId); $rsConversions = DBC::FindRecord($query); if ($rsConversions) { $aConversions = $rsConversions->toArray(); // Get the number of days until the campaign will end // based on the conversion target delivery data $aExpiration = $this->_calculateRemainingDays($aConversions, $aCampaignData['conversions']); } } // flags to control if the campaign expiration date and // the estimated expiration date are going to be showed $existExpirationDate = false; $showEtimatedDate = false; // is there a expiration date? if (!empty($aCampaignData['expire_time'])) { $existExpirationDate = true; } if ($existExpirationDate) { // has the expiration date been reached? if ((int) $aCampaignData['days_left'] < 0) { $aReturn['campaignExpiration'] = $strCampaignStop . ": " . $aCampaignData['expire_f']; $aReturn['campaignExpiration'] = $aReturn['campaignExpiration'] . " (" . abs((int) round($aCampaignData['days_left'])) . " {$strDaysAgo})"; } else { $aReturn['campaignExpiration'] = $strExpirationDate . ": " . $aCampaignData['expire_f']; $aReturn['campaignExpiration'] = $aReturn['campaignExpiration'] . " (" . $strDaysLeft . ": " . round($aCampaignData['days_left']) . ")"; } } else { $aReturn['campaignExpiration'] = $strNoExpiration; } // There is a estimated expiration date? // If yes, check if the campaign expiration date is set up and compare // both expiration dates to show only relevant estimated expiration dates if (!empty($aExpiration)) { if ($existExpirationDate == true) { if (round($aCampaignData['days_left']) >= 0) { $campaignExpirationDate = new Date($aCampaignData['expire_time']); $aExpiration['date']->hour = 0; $aExpiration['date']->minute = 0; $aExpiration['date']->second = 0; $aExpiration['date']->partsecond = 0; $compareDate = Date::compare($aExpiration['date'], $campaignExpirationDate); // the estimated expiration date is previous or equal to the // campaign expiration date and hasn't the expiration date been reached? if ($compareDate <= 0 && (int) $aCampaignData['days_left'] >= 0) { $showEtimatedDate = true; } } } else { $showEtimatedDate = true; } } elseif ($existExpirationDate && round($aCampaignData['days_left']) >= 0 || !$existExpirationDate) { $aReturn['estimatedExpiration'] = $strEstimated . ": " . $strNoExpirationEstimation; } if ($showEtimatedDate) { $aExpiration['daysLeft'] = phpAds_formatNumber($aExpiration['daysLeft']); $aReturn['estimatedExpiration'] = $strEstimated . ": " . $aExpiration['date_f'] . " (" . $strDaysLeft . ": " . $aExpiration['daysLeft'] . ")"; } return $aReturn; }
/** * build a string for naming a logfile * should identify it's purpose * * @param string $timing -- not used currently * @return string */ function _getUpgradeLogFileName($timing = 'constructive') { if ($this->package_file == '') { $package = 'openads_upgrade_' . OA_VERSION; } else { $package = str_replace('.xml', '', $this->package_file); } return $package . '_' . OA::getNow('Y_m_d_h_i_s') . '.log'; }
function revenueUpdateStats($aStats) { foreach ($aStats as $key => $value) { $doDsah = OA_Dal::factoryDO('data_summary_ad_hourly'); $doDsah->get($key); $doDsah->total_revenue = $value; $doDsah->updated = OA::getNow(); $result = $doDsah->update(); if ($result === false) { return false; } } return true; }