function run() { // Make sure that the output is sent to the browser before // loading libraries and connecting to the db flush(); $aConf = $GLOBALS['_MAX']['CONF']; // Set longer time out, and ignore user abort if (!ini_get('safe_mode')) { @set_time_limit($aConf['maintenance']['timeLimitScripts']); @ignore_user_abort(true); } if (!defined('OA_VERSION')) { // If the code is executed inside delivery, the constants // need to be initialized require_once MAX_PATH . '/constants.php'; setupConstants(); } $oLock =& OA_DB_AdvisoryLock::factory(); if ($oLock->get(OA_DB_ADVISORYLOCK_MAINTENANCE)) { OA::debug('Running Automatic Maintenance Task', PEAR_LOG_INFO); OA_Preferences::loadAdminAccountPreferences(); require_once LIB_PATH . '/Maintenance.php'; $oMaint = new OX_Maintenance(); $oMaint->run(); $oLock->release(); OA::debug('Automatic Maintenance Task Completed', PEAR_LOG_INFO); } else { OA::debug('Automatic Maintenance Task not run: could not acquire lock', PEAR_LOG_INFO); } }
function OX_Maintenance() { $this->aConf = $GLOBALS['_MAX']['CONF']; OA_Preferences::loadAdminAccountPreferences(); $this->aPref = $GLOBALS['_MAX']['PREF']; // Get a connection to the datbase $this->oDbh =& OA_DB::singleton(); if (PEAR::isError($this->oDbh)) { // Unable to continue! MAX::raiseError($this->oDbh, null, PEAR_ERROR_DIE); } }
/** * This function recreates the data_summary_ad_hourly table rolls-up hourly stats to daily totals * The roll-up is done in accordance to the user's (currently) selected timezone * * @param PEAR_Date $oDate The date before which hourly stats should be rolled up */ function _rollUpHourlyStatsToDaily($oDate) { $sDate = $oDate->format('%Y-%m-%d 00:00:00'); $updated = OA::getNowUTC('Y-m-d h:i:s'); OA::debug("Beginning stats rollup for pre-{$sDate}", PEAR_LOG_INFO); // First create a temporary table with ad_id/offset pairs, this can then be joined in a (compled) INSERT INTO ... SELECT FROM statement $aTimezones = OX_Admin_Timezones::availableTimezones(false); $aAdminPreferences = OA_Preferences::loadAdminAccountPreferences(true); $aAdminTzOffset = $this->_getSqlOffsetFromString($aTimezones[$aAdminPreferences['timezone']]); // CREATE a timezone string => offset table (since the format we use in PHP is incompatible with the format used by MySQL) $this->oDbh->exec("DROP TABLE IF EXISTS {$this->prefix}tmp_tz_offset"); $this->oDbh->exec("CREATE TABLE `{$this->prefix}tmp_tz_offset`\n (`timezone` varchar(32) NOT NULL PRIMARY KEY, `offset` char(6) NOT NULL DEFAULT '+00:00') ENGINE={$this->conf['table']['type']}"); foreach ($aTimezones as $tzString => $tzData) { $tzData = $this->_getSqlOffsetFromString($tzData); $this->oDbh->exec("INSERT INTO {$this->prefix}tmp_tz_offset (timezone, offset) VALUES('{$tzString}', '{$tzData}')"); } OA::debug("Created timezone/offset mapping table", PEAR_LOG_DEBUG); // CREATE an ad_id => offset table $this->oDbh->exec("DROP TABLE IF EXISTS {$this->prefix}tmp_ad_offset"); $this->oDbh->exec("CREATE TABLE `{$this->prefix}tmp_ad_offset`\n (`ad_id` int(11) NOT NULL PRIMARY KEY, `offset` char(6) NOT NULL DEFAULT '+00:00') ENGINE={$this->conf['table']['type']}"); $this->oDbh->exec("INSERT INTO {$this->prefix}tmp_ad_offset SELECT bannerid, '{$aAdminTzOffset}' FROM {$this->prefix}banners AS b"); $this->oDbh->exec("UPDATE\n {$this->prefix}tmp_ad_offset AS ao,\n {$this->prefix}banners AS b,\n {$this->prefix}campaigns AS c,\n {$this->prefix}clients AS cl,\n {$this->prefix}agency AS ag,\n {$this->prefix}account_preference_assoc AS apa,\n {$this->prefix}preferences AS p,\n {$this->prefix}tmp_tz_offset AS tzo\n SET ao.offset = tzo.offset\n WHERE\n p.preference_name = 'timezone'\n AND apa.preference_id = p.preference_id\n AND apa.account_id = ag.account_id\n AND cl.agencyid=ag.agencyid\n AND ao.ad_id=b.bannerid\n AND c.campaignid=b.campaignid\n AND cl.clientid=c.clientid\n AND ag.agencyid=cl.agencyid\n AND apa.value = tzo.timezone;\n "); OA::debug("Created ad/offset mapping table", PEAR_LOG_DEBUG); // So, now we have a table tmp_ad_offset which contains every banner id, and the offset of the account it belongs to. // We can use this to do a complex GROUP BY to collapse data down into the user's timzone's midday $this->oDbh->exec("DROP TABLE IF EXISTS {$this->prefix}data_summary_ad_hourly_rolledup"); $this->oDbh->exec("DROP TABLE IF EXISTS {$this->prefix}data_summary_ad_hourly_backup"); // Create a new stats table, we do this because trying to delete a bunch of records from the existing table would just fragment the index $this->oDbh->exec("CREATE TABLE {$this->prefix}data_summary_ad_hourly_rolledup LIKE {$this->prefix}data_summary_ad_hourly;"); // Copy stats over from the existing table to the new table, rolling up according to each ad's offset OA::debug("Beginning rolled-up stats copy...", PEAR_LOG_DEBUG); $this->oDbh->exec("INSERT INTO {$this->prefix}data_summary_ad_hourly_rolledup (\n date_time, ad_id, creative_id, zone_id, requests, impressions, clicks, conversions,\n total_basket_value, total_num_items, total_revenue, total_cost, total_techcost, updated )\n SELECT\n CONVERT_TZ(DATE_FORMAT(CONVERT_TZ(dsah.date_time, '+00:00', ao.offset), '%Y-%m-%d 12:00:00'), ao.offset, '+00:00') AS tz_date_time,\n dsah.ad_id, dsah.creative_id, dsah.zone_id, SUM(dsah.requests), SUM(dsah.impressions), SUM(dsah.clicks), SUM(dsah.conversions),\n SUM(dsah.total_basket_value), SUM(dsah.total_num_items), SUM(dsah.total_revenue), SUM(dsah.total_cost), SUM(dsah.total_techcost), '{$updated}'\n FROM\n {$this->prefix}data_summary_ad_hourly AS dsah,\n {$this->prefix}tmp_ad_offset AS ao\n WHERE\n ao.ad_id=dsah.ad_id\n AND CONVERT_TZ(dsah.date_time, '+00:00', ao.offset) < '{$sDate}'\n GROUP BY\n tz_date_time, ad_id, creative_id, zone_id;\n "); OA::debug("Completed rolled-up stats copy...", PEAR_LOG_DEBUG); // Copy any un-rolled up stats records over into the new table OA::debug("Beginning *non* rolled-up stats copy...", PEAR_LOG_DEBUG); $this->oDbh->exec("INSERT INTO {$this->prefix}data_summary_ad_hourly_rolledup (\n date_time, ad_id, creative_id, zone_id, requests, impressions, clicks, conversions,\n total_basket_value, total_num_items, total_revenue, total_cost, total_techcost, updated)\n SELECT\n dsah.date_time AS tz_date_time, dsah.ad_id, dsah.creative_id, dsah.zone_id, dsah.requests, dsah.impressions, dsah.clicks, dsah.conversions,\n dsah.total_basket_value, dsah.total_num_items, dsah.total_revenue, dsah.total_cost, dsah.total_techcost, '{$updated}'\n FROM\n {$this->prefix}data_summary_ad_hourly AS dsah,\n {$this->prefix}tmp_ad_offset AS ao\n WHERE\n ao.ad_id=dsah.ad_id\n AND CONVERT_TZ(dsah.date_time, '+00:00', ao.offset) >= '{$sDate}'\n "); OA::debug("Completed *non* rolled-up stats copy...", PEAR_LOG_DEBUG); // Swap the old table with the new $this->oDbh->exec("RENAME TABLE {$this->prefix}data_summary_ad_hourly TO {$this->prefix}data_summary_ad_hourly_backup"); $this->oDbh->exec("RENAME TABLE {$this->prefix}data_summary_ad_hourly_rolledup TO {$this->prefix}data_summary_ad_hourly"); OA::debug("Swapped new table for old...", PEAR_LOG_DEBUG); // Cleanup $this->oDbh->exec("DROP TABLE {$this->prefix}tmp_ad_offset;"); $this->oDbh->exec("DROP TABLE {$this->prefix}tmp_tz_offset;"); OA::debug("Woo hoo stats rolled up for pre-{$sDate}", PEAR_LOG_INFO); }
$aElements[] = 'warn_email_admin'; $aCheckboxes['warn_email_admin'] = true; $aElements[] = 'warn_email_admin_impression_limit'; $aElements[] = 'warn_email_admin_day_limit'; // Manager email Warnings $aElements[] = 'warn_email_manager'; $aCheckboxes['warn_email_manager'] = true; $aElements[] = 'warn_email_manager_impression_limit'; $aElements[] = 'warn_email_manager_day_limit'; // Advertiser email Warnings $aElements[] = 'warn_email_advertiser'; $aCheckboxes['warn_email_advertiser'] = true; $aElements[] = 'warn_email_advertiser_impression_limit'; $aElements[] = 'warn_email_advertiser_day_limit'; // Save the preferences $result = OA_Preferences::processPreferencesFromForm($aElements, $aCheckboxes); if ($result) { // Queue confirmation message $setPref = $oOptions->getSettingsPreferences($prefSection); $title = $setPref[$prefSection]['name']; $translation = new OX_Translation(); $translated_message = $translation->translate($GLOBALS['strXPreferencesHaveBeenUpdated'], array(htmlspecialchars($title))); OA_Admin_UI::queueMessage($translated_message, 'local', 'confirm', 0); OX_Admin_Redirect::redirect(basename($_SERVER['PHP_SELF'])); } // Could not write the preferences to the database, store this // error message and continue $aErrormessage[0][] = $strUnableToWritePrefs; } // Set the correct section of the preference pages and display the drop-down menu $setPref = $oOptions->getSettingsPreferences($prefSection);
} } else { if (!$logging_trackerImpressions && $logging_trackerImpressionsCurrent) { // Conversion tracking has been turned off, need to update // account preferences to not display any of the conversion // tracking columns in statistics screens require_once MAX_PATH . '/lib/OA/Admin/Statistics/Fields/Delivery/Affiliates.php'; require_once MAX_PATH . '/lib/OA/Admin/Statistics/Fields/Delivery/Default.php'; $aStatisticsFieldsDelivery['affiliates'] = new OA_StatisticsFieldsDelivery_Affiliates(); $aStatisticsFieldsDelivery['default'] = new OA_StatisticsFieldsDelivery_Default(); foreach ($aStatisticsFieldsDelivery as $obj) { // Get all of the column preference names that relate to // conversion tracking $aPrefs = $obj->getConversionColumnPreferenceNames(); // Disable these preferences OA_Preferences::disableStatisticsColumns($aPrefs); } } } // The settings configuration file was written correctly, // go to the "next" settings page from here // Queue confirmation message $setPref = $oOptions->getSettingsPreferences($prefSection); $title = $setPref[$prefSection]['name']; $translation = new OX_Translation(); $translated_message = $translation->translate($GLOBALS['strXSettingsHaveBeenUpdated'], array(htmlspecialchars($title))); OA_Admin_UI::queueMessage($translated_message, 'local', 'confirm', 0); OX_Admin_Redirect::redirect(basename($_SERVER['SCRIPT_NAME'])); } // Could not write the settings configuration file, store this // error message and continue
/** * A method to check if the campaign is expired * * @return bool */ function _isExpired() { static $oServiceLocator; // MySQL null date hardcoded for optimisation if (!empty($this->expire) && $this->expire != '0000-00-00') { if (!isset($oServiceLocator)) { $oServiceLocator =& OA_ServiceLocator::instance(); } if (!($oNow = $oServiceLocator->get('now'))) { $oNow = new Date(); } $oExpire = new Date($this->expire); $oExpire->setHour(23); $oExpire->setMinute(59); $oExpire->setSecond(59); if (!empty($this->clientid)) { // Set timezone $aAccounts = $this->getOwningAccountIds(); $aPrefs = OA_Preferences::loadAccountPreferences($aAccounts[OA_ACCOUNT_ADVERTISER], true); if (isset($aPrefs['timezone'])) { $oExpire->setTZbyID($aPrefs['timezone']); } } if ($oNow->after($oExpire)) { return true; } } return false; }
* max_formattedNumberStringToFloat() function when the onSubmit() * event of the field occurs, so that you get un-formatted input * into your form submission script, if said script doesn't deal * with the formatted input. * * * @TODO Add support for dealing with exceeding the upper limit of * JS support for numbers. */ // Require the initialisation file require_once '../../../init.php'; // Required files require_once MAX_PATH . '/lib/max/language/Default.php'; require_once MAX_PATH . '/lib/OA/Preferences.php'; // Load the user preferences from the database $pref = OA_Preferences::loadAdminAccountPreferences(true); // Load the required language files Language_Default::load(); // Send content-type header header("Content-type: application/x-javascript"); // The largest possible integer in when using JavaScript's // default 4-octet storage for numbers define('MAX_JS_INTEGER_UPPER_LIMIT', 9007199254740992); ?> /** * A JavaScript function to take a number, either as a real number, or * as a formatted string represenation of a number, and return that * number as a string, correctly formatted with thousands and decimal * delimiters in the textual representation. *
function testPutAdmin() { $oUpgrade = new OA_Upgrade(); // Prepare test data $aAdmin = array('email' => '*****@*****.**', 'name' => 'testadmin', 'pword' => 'testpass', 'language' => 'es'); $aPrefs = array('timezone' => 'Europe/Madrid'); // there shouldn't be admin account $adminAccountId = OA_Dal_ApplicationVariables::get('admin_account_id'); $this->assertNull($adminAccountId); // create admin $result = $oUpgrade->putAdmin($aAdmin, $aPrefs); $this->assertTrue($result); // admin account is set $adminAccountId = OA_Dal_ApplicationVariables::get('admin_account_id'); $this->assertNotNull($adminAccountId); $doAccount = OA_Dal::factoryDO('accounts'); $doAccount->get($adminAccountId); $this->assertEqual($doAccount->account_type, OA_ACCOUNT_ADMIN); $this->assertEqual($doAccount->account_name, 'Administrator account'); // user exists $doUser = OA_Dal::factoryDO('users'); $doUserAssoc = OA_Dal::factoryDO('account_user_assoc'); $doUserAssoc->account_id = $adminAccountId; $doUser->joinAdd($doUserAssoc); $doUser->find(); $this->assertTrue($doUser->fetch()); $this->assertEqual($doUser->contact_name, 'Administrator'); $this->assertEqual($doUser->email_address, $aAdmin['email']); $this->assertEqual($doUser->username, $aAdmin['name']); $this->assertEqual($doUser->password, md5($aAdmin['pword'])); $this->assertEqual($doUser->language, $aAdmin['language']); // agency was created $doAgency = OA_Dal::factoryDO('agency'); $doAccount = OA_Dal::factoryDO('accounts'); $doAccount->account_id = $doUser->default_account_id; $doAgency->joinAdd($doAccount); $doAgency->find(); $this->assertTrue($doAgency->fetch()); $this->assertEqual($doAgency->name, 'Default manager'); $this->assertEqual($doAgency->email, $aAdmin['email']); $this->assertEqual($doAgency->active, 1); // Default preferences + custom timezone are set $oPreferences = new OA_Preferences(); $aDefPrefs = $oPreferences->getPreferenceDefaults(); $aExpected = array(); foreach ($aDefPrefs as $name => $values) { $aExpected[$name] = $values['default']; } $aExpected['timezone'] = $aPrefs['timezone']; $aExpected['language'] = 'en'; //added by get admin account preferences $aAdminPreferences = OA_Preferences::loadAdminAccountPreferences(true); $this->assertEqual($aExpected, $aAdminPreferences); // trunkate tables DataGenerator::cleanUp(array('account_preference_assoc', 'preferences', 'account_user_assoc', 'users', 'agency', 'accounts')); // remove admin_account_id from application variables OA_Dal_ApplicationVariables::delete('admin_account_id'); }
/** * A static method for processing preference values from a UI form, and * updating the preference values in the database. * * @static * @param array $aElementNames An array of HTML form element names, which * are also the preference value names. * @param array $aCheckboxes An array of the above HTML form element * names which are checkboxes, as these will not * be set in the form POST if unchecked, and * so need to be treated differently. * @return boolean True on success, false otherwise. */ function processPreferencesFromForm($aElementNames, $aCheckboxes) { phpAds_registerGlobalUnslashed('token'); if (!phpAds_SessionValidateToken($GLOBALS['token'])) { return false; } // Get all of the preference types that exist $aPreferenceTypes = array(); $doPreferences = OA_Dal::factoryDO('preferences'); $doPreferences->find(); if ($doPreferences->getRowCount() < 1) { return false; } while ($doPreferences->fetch()) { $aPreference = $doPreferences->toArray(); $aPreferenceTypes[$aPreference['preference_name']] = array('preference_id' => $aPreference['preference_id'], 'account_type' => $aPreference['account_type']); } // Are there any preference types in the system? if (empty($aPreferenceTypes)) { return false; } // Get the type of the current accout $currentAccountType = OA_Permission::getAccountType(); // Get the current account's ID $currentAccountId = OA_Permission::getAccountId(); // Get the parent account preferences $aParentPreferences = OA_Preferences::loadPreferences(false, true, true); // Prepare the preference values that should be saved or deleted $aSavePreferences = array(); $aDeletePreferences = array(); foreach ($aElementNames as $preferenceName) { // Ensure that the current account has permission to process // the preference type $access = OA_Preferences::hasAccess($currentAccountType, $aPreferenceTypes[$preferenceName]['account_type']); if ($access == false) { // Don't process this value continue; } // Register the HTML element value phpAds_registerGlobalUnslashed($preferenceName); // Is the HTML element value a checkbox, and unset? if (isset($aCheckboxes[$preferenceName]) && !isset($GLOBALS[$preferenceName])) { // Set the value of the element to the false string "" $GLOBALS[$preferenceName] = ''; } else { if (isset($aCheckboxes[$preferenceName]) && $GLOBALS[$preferenceName]) { // Set the value of the element to the true string "1" $GLOBALS[$preferenceName] = '1'; } } // Was the HTML element value set? if (isset($GLOBALS[$preferenceName])) { // Is the preference value different from the parent value? if (!isset($aParentPreferences[$preferenceName]) || $GLOBALS[$preferenceName] != $aParentPreferences[$preferenceName]) { // The preference value is different from the parent, so it // needs to be stored $aSavePreferences[$preferenceName] = $GLOBALS[$preferenceName]; } else { if ($currentAccountType != OA_ACCOUNT_ADMIN) { // The preference value is not different from the parent, so // it should be deleted if not the admin account (in case it // exists for the account, and so would not inherit correctly // if the admin account changes preferences) $aDeletePreferences[$preferenceName] = $GLOBALS[$preferenceName]; } } } } // Save the required preferences foreach ($aSavePreferences as $preferenceName => $preferenceValue) { $doAccount_preference_assoc = OA_Dal::factoryDO('account_preference_assoc'); $doAccount_preference_assoc->account_id = $currentAccountId; $doAccount_preference_assoc->preference_id = $aPreferenceTypes[$preferenceName]['preference_id']; $doAccount_preference_assoc->find(); if ($doAccount_preference_assoc->getRowCount() != 1) { // Insert the preference $doAccount_preference_assoc->value = $preferenceValue; $result = $doAccount_preference_assoc->insert(); if ($result === false) { return false; } } else { // Update the preference $doAccount_preference_assoc->fetch(); $doAccount_preference_assoc->value = $preferenceValue; $result = $doAccount_preference_assoc->update(); if ($result === false) { return false; } } } // Delete the required preferences foreach ($aDeletePreferences as $preferenceName => $preferenceValue) { $doAccount_preference_assoc = OA_Dal::factoryDO('account_preference_assoc'); $doAccount_preference_assoc->account_id = $currentAccountId; $doAccount_preference_assoc->preference_id = $aPreferenceTypes[$preferenceName]['preference_id']; $doAccount_preference_assoc->find(); if ($doAccount_preference_assoc->getRowCount() == 1) { // Delete the preference $result = $doAccount_preference_assoc->delete(); if ($result === false) { return false; } } } return true; }
function testLoadPreferencesByNameAndAccount() { // clean cache OA_Preferences::cachePreferences(null, array(), null, true); $prefs = OA_Preferences::loadPreferencesByNameAndAccount($accountId = 1, array('pref1'), 'ADMIN'); $this->assertEqual($prefs, array()); // add prefs $prefsNamesIds = array('pref1' => 1, 'pref2' => 2); $this->_createPreferences($prefsNamesIds); $this->_addPrefsToAccount(array(1 => 'pref1val'), $accountId); $prefs = OA_Preferences::loadPreferencesByNameAndAccount($accountId, array('pref1'), 'ADMIN'); $this->assertEqual($prefs, array('pref1' => 'pref1val')); $this->_addPrefsToAccount(array(2 => 'pref2val'), $accountId); $prefs = OA_Preferences::loadPreferencesByNameAndAccount($accountId, array('pref1', 'pref2'), 'ADMIN'); $this->assertEqual($prefs, array('pref1' => 'pref1val', 'pref2' => 'pref2val')); $prefs = OA_Preferences::loadPreferencesByNameAndAccount(2, array('pref1'), 'ADMIN'); $this->assertEqual($prefs, array()); }
$oDal = OA_Dal::factoryDAL('campaigns'); $agencyId = OA_Permission::getAgencyId(); $aCampaigns = $oDal->updateCampaignsPriorityByAgency($agencyId, $updateFrom, $updateTo); foreach ($aCampaigns as $campaignId => $aCampaign) { if ($aCampaign['status_changed'] && $aCampaign['status'] == OA_ENTITY_STATUS_INACTIVE) { // store without string indexes, to not to waste space in session $aInactivatedCampaignsIds[$campaignId] = array($campaignId, $aCampaign['clientid'], $aCampaign['campaignname']); } } $runMaintenance = true; } // We changed contract if ((bool) $_POST['contract_ecpm_enabled'] != (bool) $pref['contract_ecpm_enabled']) { // Reload the prefs we just changed into the global variable because // we use it when setting ecpm_enabled in the DO. OA_Preferences::loadPreferences(); $oDal = OA_Dal::factoryDAL('campaigns'); $agencyId = OA_Permission::getAgencyId(); $aCampaigns = $oDal->updateEcpmEnabledByAgency($agencyId); foreach ($aCampaigns as $campaignId => $aCampaign) { if ($aCampaign['status_changed'] && $aCampaign['status'] == OA_ENTITY_STATUS_INACTIVE) { // store without string indexes, to not to waste space in session $aInactivatedCampaignsIds[$campaignId] = array($campaignId, $aCampaign['clientid'], $aCampaign['campaignname']); } } $runMaintenance = true; } // store the list of inactivated campaigns in the session if (!empty($aInactivatedCampaignsIds)) { $session['aInactivatedCampaignsIds'] = $aInactivatedCampaignsIds; phpAds_SessionDataStore();
/** * A private method to load the preferences required when generating reports. * * @access private * @return array The loaded preference array. */ function _loadPrefs() { $aPref = $GLOBALS['_MAX']['PREF']; if (is_null($aPref)) { $aPref = OA_Preferences::loadAdminAccountPreferences(true); } return $aPref; }
/** * Post init session * */ function postInitSession() { global $session, $pref; global $affiliateid, $agencyid, $bannerid, $campaignid, $channelid; global $clientid, $day, $trackerid, $userlogid, $zoneid; // Overwrite certain preset preferences if (!empty($session['language']) && $session['language'] != $GLOBALS['pref']['language']) { $GLOBALS['_MAX']['CONF']['max']['language'] = $session['language']; } // Load the user preferences from the database OA_Preferences::loadPreferences(); // Load the required language files Language_Loader::load('default'); // Register variables phpAds_registerGlobalUnslashed('affiliateid', 'agencyid', 'bannerid', 'campaignid', 'channelid', 'clientid', 'day', 'trackerid', 'userlogid', 'zoneid'); if (!isset($affiliateid)) { $affiliateid = ''; } if (!isset($agencyid)) { $agencyid = OA_Permission::getAgencyId(); } if (!isset($bannerid)) { $bannerid = ''; } if (!isset($campaignid)) { $campaignid = ''; } if (!isset($channelid)) { $channelid = ''; } if (!isset($clientid)) { $clientid = ''; } if (!isset($day)) { $day = ''; } if (!isset($trackerid)) { $trackerid = ''; } if (!isset($userlogid)) { $userlogid = ''; } if (!isset($zoneid)) { $zoneid = ''; } }
/** * Return the timezone object that the campaign is suposed to be using * * @staticvar array $aCache * @param int $campaignId * @return Date_TimeZone */ public function getTimezoneForCampaign($campaignId) { static $aCache; $doAgency = OA_Dal::factoryDO('agency'); $doClients = OA_Dal::factoryDO('clients'); $doCampaigns = OA_Dal::factoryDO('campaigns'); $doCampaigns->campaignid = $campaignId; $doClients->joinAdd($doCampaigns); $doAgency->joinAdd($doClients); if ($doAgency->find()) { $doAgency->fetch(); if (!isset($aCache[$doAgency->account_id])) { $aPrefs = OA_Preferences::loadAccountPreferences($doAgency->account_id, true); $oTz = new Date_TimeZone(empty($aPrefs['timezone']) ? 'UTC' : $aPrefs['timezone']); $aCache[$doAgency->account_id] = $oTz; } else { $oTz = $aCache[$doAgency->account_id]; } } else { $oTz = new Date_TimeZone('UTC'); } return $oTz; }
/** * A method to get the hourly revenuo of a monthly tenancy campaign * * Monthly tenancy calculation sponsored by www.admost.nl * * @param array $aInfo The finance information, as returned by _saveSummaryGetAdFinanceInfo * @param Date $oStartDate * @param Date $oEndDate * @param string $table * @return double */ function getMtRevenue($aInfo, $oStartDate, $oEndDate, $table) { OA::debug(sprintf(" - Calculating MT revenue for banner [id%d] between %s and %s:", $aInfo['ad_id'], $oStartDate->format('%Y-%m-%d %H:%M:%S %Z'), $oEndDate->format('%Y-%m-%d %H:%M:%S %Z')), PEAR_LOG_DEBUG); $aConf = $GLOBALS['_MAX']['CONF']; $oMonthStart = new Date($oStartDate); // Set timezone if (!empty($aInfo['advertiser_id'])) { $doClient = OA_Dal::staticGetDO('clients', $aInfo['advertiser_id']); $aAdvertiserPrefs = OA_Preferences::loadAccountPreferences($doClient->account_id, true); if (!empty($aAdvertiserPrefs['timezone'])) { $oMonthStart->convertTZbyID($aAdvertiserPrefs['timezone']); } } // Get ad/zone combinations for the campaign if (!isset($this->aMtRevenueCache[$aInfo['campaign_id']])) { $query = "\n SELECT\n COUNT(*) as cnt\n FROM\n " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table'][$table], true) . " d JOIN\n " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['banners'], true) . " a ON (a.bannerid = d.ad_id)\n WHERE\n a.campaignid = {$aInfo['campaign_id']}\n AND d.date_time >= " . $this->oDbh->quote($oStartDate->format('%Y-%m-%d %H:%M:%S'), 'timestamp') . "\n AND d.date_time <= " . $this->oDbh->quote($oEndDate->format('%Y-%m-%d %H:%M:%S'), 'timestamp'); $this->aMtRevenueCache[$aInfo['campaign_id']] = $this->oDbh->query($query)->fetchOne(); } $oMonthStart->setDay(1); $oMonthStart->setHour(0); $oMonthStart->setMinute(0); $oMonthStart->setSecond(0); OA::debug(sprintf(" - Month start: %s", $oMonthStart->format('%Y-%m-%d %H:%M:%S %Z')), PEAR_LOG_DEBUG); $daysInMonth = $oMonthStart->getDaysInMonth(); OA::debug(sprintf(" - Days in month: %d", $daysInMonth), PEAR_LOG_DEBUG); $oMonthEnd = new Date($oMonthStart); $oMonthEnd->setDay($daysInMonth); $oMonthEnd = $oMonthEnd->getNextDay(); $oMonthEnd->setTZ($oMonthStart->tz); OA::debug(sprintf(" - Month end: %s", $oMonthEnd->format('%Y-%m-%d %H:%M:%S %Z')), PEAR_LOG_DEBUG); $oDiff = new Date_Span(); $oDiff->setFromDateDiff($oMonthEnd, $oMonthStart); $hoursPerMonth = ceil($oDiff->toHours()); OA::debug(sprintf(" - Hours per month: %d", $hoursPerMonth), PEAR_LOG_DEBUG); $oDiff = new Date_Span(); $oDiff->setFromDateDiff($oEndDate, $oStartDate); $hoursPerInterval = ceil($oDiff->toHours()); OA::debug(sprintf(" - Hours per interval: %d", $hoursPerInterval), PEAR_LOG_DEBUG); $adZoneCombinations = $this->aMtRevenueCache[$aInfo['campaign_id']]; OA::debug(sprintf(" - Ad/zone/OI combinations for campaign [id%d]: %d", $aInfo['campaign_id'], $this->aMtRevenueCache[$aInfo['campaign_id']]), PEAR_LOG_DEBUG); $result = $aInfo['revenue'] / $hoursPerMonth * $hoursPerInterval / $adZoneCombinations; OA::debug(sprintf(" - Result: %0.4f", $result), PEAR_LOG_DEBUG); return $result; }
/** * 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']); } } } } } } }
// Prepare an array of HTML elements to display for the form, and // output using the $oOption object $aPreferences[0]['text'] = $group . ' ' . $strPreferences; $count = count($aConfig['preferences']); $i = 0; foreach ($aConfig['preferences'] as $k => $v) { $aPreferences[0]['items'][] = array('type' => $v['type'], 'name' => $group . '_' . $v['name'], 'text' => $v['label'], 'req' => $v['required'], 'size' => $v['size'], 'value' => $v['value'], 'visible' => $v['visible']); //add break after a field excluding last $i++; if ($i < $count) { $aPreferences[0]['items'][] = array('type' => 'break'); } } $aPreferences[0]['items'][] = array('type' => 'hiddenfield', 'name' => 'plugin', 'value' => $plugin); $aPreferences[0]['items'][] = array('type' => 'hiddenfield', 'name' => 'group', 'value' => $group); $GLOBALS['_MAX']['PREF_EXTRA'] = OA_Preferences::loadPreferences(true, true); /*-------------------------------------------------------*/ /* HTML framework */ /*-------------------------------------------------------*/ phpAds_PageHeader("plugin-index", new OA_Admin_UI_Model_PageHeaderModel($GLOBALS['strPluginPreferences']), '', false, true); /*-------------------------------------------------------*/ /* Main code */ /*-------------------------------------------------------*/ //display back link $oTpl = new OA_Admin_Template('plugin-group-preferences.html'); $oTpl->assign('backURL', MAX::constructURL(MAX_URL_ADMIN, $backURL)); $oTpl->assign('plugin', $plugin); $oTpl->assign('group', $group); $oTpl->display(); //display options form $oOptions->show($aPreferences, $aErrormessage);
/** * A method to inser initialise the preferences table and insert the default prefs * * @param int $adminAccountId * @return bool */ function putDefaultPreferences($adminAccountId) { // Preferences handling $oPreferences = new OA_Preferences(); $aPrefs = $oPreferences->getPreferenceDefaults(); // Insert default prefs foreach ($aPrefs as $prefName => &$aPref) { $doPreferences = OA_Dal::factoryDO('preferences'); $doPreferences->preference_name = $prefName; $doPreferences->account_type = empty($aPref['account_type']) ? '' : $aPref['account_type']; $preferenceId = $doPreferences->insert(); if (!$preferenceId) { $this->oLogger->logError("error adding preference entry: {$prefName}"); return false; } $doAPA = OA_Dal::factoryDO('account_preference_assoc'); $doAPA->account_id = $adminAccountId; $doAPA->preference_id = $preferenceId; $doAPA->value = $aPref['default']; $result = $doAPA->insert(); if (!$result) { $this->oLogger->logError("error adding preference default for {$prefName}: '" . $aPref['default'] . "'"); return false; } } return true; }
/** * A private method to set the required options for column-based output * of option items. * * @access private * @param array $aItem The column option to display. * @param array $aValue An array of the column values. */ function _showStatsColumns($aItem, $aValue) { // Get all of the preference types that exist $aPreferenceTypes = array(); $doPreferences = OA_Dal::factoryDO('preferences'); $doPreferences->find(); if ($doPreferences->getRowCount() >= 1) { while ($doPreferences->fetch()) { $aPreference = $doPreferences->toArray(); $aPreferenceTypes[$aPreference['preference_name']] = array('preference_id' => $aPreference['preference_id'], 'account_type' => $aPreference['account_type']); } } // Get the type of the current accout $currentAccountType = OA_Permission::getAccountType(); global $tabindex; $aItem['tabindex'] = $tabindex++; foreach ($aItem['rows'] as $key => $aRow) { if (isset($aValue[$aRow['name']]['base'])) { $aItem['rows'][$key]['value'] = $aValue[$aRow['name']]['base']; } if (isset($aValue[$aRow['name']]['label'])) { $aItem['rows'][$key]['label_value'] = $aValue[$aRow['name']]['label']; } if (isset($aValue[$aRow['name']]['rank'])) { $aItem['rows'][$key]['rank_value'] = $aValue[$aRow['name']]['rank']; } // Has the current account got access to edit this preference? $access = OA_Preferences::hasAccess($currentAccountType, $aPreferenceTypes[$aRow['name']]['account_type']); if ($access == false) { $aItem['rows'][$key]['disabled'] = true; } } $this->aOption[] = array('statscolumns.html' => $aItem); // Update the global tab index for the number of stats column rows added $rows = count($aItem['rows']); $tabindex += $rows * 3; // Not an exact increment of the tab index, but close enough! }