/**
  * A method to detect the available SSL enabling extensions
  *
  * @return mixed An array of the available extensions, or false if none is present
  */
 public static function getAvailableSSLExtensions($forceReload = false)
 {
     if ($forceReload || !isset(self::$sslExtensions)) {
         self::$sslExtensions = OA::getAvailableSSLExtensions();
     }
     return self::$sslExtensions;
 }
 /**
  * A method to determine the day/hour that a placement first became active,
  * based on the first record of its children ads delivering.
  *
  * @param integer $placementId The placement ID.
  * @return mixed PEAR:Error on database error, null on no result, or a
  *               PEAR::Date object representing the time the placement started
  *               delivery, or, if not yet active, the current date/time.
  */
 function getPlacementFirstStatsDate($placementId)
 {
     // Test the input values
     if (!is_numeric($placementId)) {
         return null;
     }
     // Get the required data
     $conf = $GLOBALS['_MAX']['CONF'];
     $adTable = $this->oDbh->quoteIdentifier($conf['table']['prefix'] . $conf['table']['banners'], true);
     $dsahTable = $this->oDbh->quoteIdentifier($conf['table']['prefix'] . $conf['table']['data_summary_ad_hourly'], true);
     $query = "\n            SELECT\n                DATE_FORMAT(dsah.date_time, '%Y-%m-%d') AS day,\n                HOUR(dsah.date_time) AS hour\n            FROM\n                {$adTable} AS a,\n                {$dsahTable} AS dsah\n            WHERE\n                a.campaignid = " . $this->oDbh->quote($placementId, 'integer') . "\n                AND\n                a.bannerid = dsah.ad_id\n            ORDER BY\n                day ASC, hour ASC\n            LIMIT 1";
     $message = "Finding start date of placement ID {$placementId} based on delivery statistics.";
     OA::debug($message, PEAR_LOG_DEBUG);
     $rc = $this->oDbh->query($query);
     if (PEAR::isError($rc)) {
         return $rc;
     }
     // Was a result found?
     if ($rc->numRows() == 0) {
         // Return the current time
         $oDate = new Date();
     } else {
         // Store the results
         $aRow = $rc->fetchRow();
         $oDate = new Date($aRow['day'] . ' ' . $aRow['hour'] . ':00:00');
     }
     return $oDate;
 }
Exemple #3
0
 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 defaultData()
 {
     $oManager = new OX_Plugin_ComponentGroupManager();
     if (!array_key_exists('testPlugin', $GLOBALS['_MAX']['CONF']['pluginGroupComponents'])) {
         $oManager->disableComponentGroup('testPlugin');
     }
     $this->oManager->enableComponentGroup('testPlugin');
     $oTestPluginTable = OA_Dal::factoryDO('testplugin_table');
     if (!$oTestPluginTable) {
         OA::debug('Failed to instantiate DataObject for testplugin_table');
         return false;
     }
     $oTestPluginTable->myplugin_desc = 'Hello World';
     $aSettings[0]['data'] = $oTestPluginTable->insert();
     $aSettings[0]['section'] = 'myPlugin';
     $aSettings[0]['key'] = 'english';
     $oTestPluginTable->myplugin_desc = 'Hola Mundo';
     $aSettings[1]['data'] = $oTestPluginTable->insert();
     $aSettings[1]['section'] = 'myPlugin';
     $aSettings[1]['key'] = 'spanish';
     $oTestPluginTable->myplugin_desc = 'Look Simon, you\'re just making it up now';
     $aSettings[2]['data'] = $oTestPluginTable->insert();
     $aSettings[2]['section'] = 'myPlugin';
     $aSettings[2]['key'] = 'russian';
     $oManager->_registerSettings($aSettings);
     $oManager->disableComponentGroup('testPlugin');
     return true;
 }
Exemple #5
0
 /**
  * A method to launch and display the widget
  *
  * @param array $aParams The parameters array, usually $_REQUEST
  */
 function display()
 {
     if (!$this->oTpl->is_cached()) {
         OA::disableErrorHandling();
         $oRss = new XML_RSS($this->url);
         $result = $oRss->parse();
         OA::enableErrorHandling();
         // ignore bad character error which could appear if rss is using invalid characters
         if (PEAR::isError($result)) {
             if (!strstr($result->getMessage(), 'Invalid character')) {
                 PEAR::raiseError($result);
                 // rethrow
                 $this->oTpl->caching = false;
             }
         }
         $aPost = array_slice($oRss->getItems(), 0, $this->posts);
         foreach ($aPost as $key => $aValue) {
             $aPost[$key]['origTitle'] = $aValue['title'];
             if (strlen($aValue['title']) > 38) {
                 $aPost[$key]['title'] = substr($aValue['title'], 0, 38) . '...';
             }
         }
         $this->oTpl->assign('title', $this->title);
         $this->oTpl->assign('feed', $aPost);
         $this->oTpl->assign('siteTitle', $this->siteTitle);
         $this->oTpl->assign('siteUrl', $this->siteUrl);
     }
     $this->oTpl->display();
 }
 function execute($aParams)
 {
     $this->oUpgrade =& $aParams[0];
     $this->oDbh =& OA_DB::singleton();
     $prefix = $GLOBALS['_MAX']['CONF']['table']['prefix'];
     if ($this->oDbh->dbsyntax == 'pgsql') {
         $oTable =& $this->oUpgrade->oDBUpgrader->oTable;
         foreach ($oTable->aDefinition['tables'] as $tableName => $aTable) {
             foreach ($aTable['fields'] as $fieldName => $aField) {
                 if (!empty($aField['autoincrement'])) {
                     // Check actual sequence name
                     $oldSequenceName = $this->getLinkedSequence($prefix . $tableName, $fieldName);
                     if ($oldSequenceName) {
                         $newSequenceName = OA_DB::getSequenceName($this->oDbh, $tableName, $fieldName);
                         if ($oldSequenceName != $newSequenceName) {
                             $this->logOnly("Non standard sequence name found: " . $oldSequenceName);
                             $qTable = $this->oDbh->quoteIdentifier($prefix . $tableName, true);
                             $qField = $this->oDbh->quoteIdentifier($fieldName, true);
                             $qOldSequence = $this->oDbh->quoteIdentifier($oldSequenceName, true);
                             $qNewSequence = $this->oDbh->quoteIdentifier($newSequenceName, true);
                             OA::disableErrorHandling();
                             $result = $this->oDbh->exec("ALTER TABLE {$qOldSequence} RENAME TO {$qNewSequence}");
                             if (PEAR::isError($result)) {
                                 if ($result->getCode() == MDB2_ERROR_ALREADY_EXISTS) {
                                     $result = $this->oDbh->exec("DROP SEQUENCE {$qNewSequence}");
                                     if (PEAR::isError($result)) {
                                         $this->logError("Could not drop existing sequence {$newSequenceName}: " . $result->getUserInfo());
                                         return false;
                                     }
                                     $result = $this->oDbh->exec("ALTER TABLE {$qOldSequence} RENAME TO {$qNewSequence}");
                                 }
                             }
                             if (PEAR::isError($result)) {
                                 $this->logError("Could not rename {$oldSequenceName} to {$newSequenceName}: " . $result->getUserInfo());
                                 return false;
                             }
                             $result = $this->oDbh->exec("ALTER TABLE {$qTable} ALTER {$qField} SET DEFAULT nextval(" . $this->oDbh->quote($qNewSequence) . ")");
                             if (PEAR::isError($result)) {
                                 $this->logError("Could not set column default to sequence {$newSequenceName}: " . $result->getUserInfo());
                                 return false;
                             }
                             OA::enableErrorHandling();
                             $result = $oTable->resetSequenceByData($tableName, $fieldName);
                             if (PEAR::isError($result)) {
                                 $this->logError("Could not reset sequence value for {$newSequenceName}: " . $result->getUserInfo());
                                 return false;
                             }
                             $this->logOnly("Successfully renamed {$oldSequenceName} to {$newSequenceName}");
                         }
                     } else {
                         $this->logOnly("No sequence found for {$tableName}.{$fieldName}");
                     }
                 }
             }
         }
     }
     return true;
 }
 function __construct($path, $server, $port = 0, $proxy = '', $proxy_port = 0, $proxy_user = '', $proxy_pass = '')
 {
     if ($aExtensions = OA::getAvailableSSLExtensions()) {
         $this->hasCurl = in_array('curl', $aExtensions);
         $this->hasOpenssl = in_array('openssl', $aExtensions);
     }
     $this->verifyPeer = false;
     $this->caFile = MAX_PATH . '/etc/curl-ca-bundle.crt';
     parent::__construct($path, $server, $port);
 }
 /**
  * A private method for summarising data into the final tables when
  * at least one hour is complete.
  *
  * @access private
  * @param PEAR::Date $oStartDate The start date of the complete hour(s).
  * @param PEAR::Date $oEndDate The end date of the complete hour(s).
  */
 function _saveSummary($oStartDate, $oEndDate)
 {
     $message = '- Updating the data_summary_ad_hourly table for data after ' . $oStartDate->format('%Y-%m-%d %H:%M:%S') . ' ' . $oStartDate->tz->getShortName();
     $this->oController->report .= $message . ".\n";
     OA::debug($message, PEAR_LOG_DEBUG);
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oDal =& $oServiceLocator->get('OX_Dal_Maintenance_Statistics');
     $aTypes = array('types' => array(0 => 'request', 1 => 'impression', 2 => 'click'), 'connections' => array(1 => MAX_CONNECTION_AD_IMPRESSION, 2 => MAX_CONNECTION_AD_CLICK));
     $oDal->saveSummary($oStartDate, $oEndDate, $aTypes, 'data_intermediate_ad', 'data_summary_ad_hourly');
 }
Exemple #9
0
 /**
  * A method to run the run() method of each task in the collection,
  * in the registered order.
  *
  * @todo We should really make OA_Task::run return a boolean we can check.
  */
 function runTasks()
 {
     // Remove tasks from the queue and unset them when done to prevent
     // useless memory consumption
     while ($oTask = array_shift($this->aTasks)) {
         OA::debug('Task begin: ' . get_class($oTask), PEAR_LOG_INFO);
         $oTask->run();
         OA::debug('Task complete: ' . get_class($oTask), PEAR_LOG_INFO);
         unset($oTask);
     }
 }
 /**
  * The implementation of the OA_Task::run() method that performs
  * the required task of activating/deactivating campaigns.
  */
 function run()
 {
     if ($this->oController->updateIntermediate) {
         $oServiceLocator =& OA_ServiceLocator::instance();
         $oDate =& $oServiceLocator->get('now');
         $oDal =& $oServiceLocator->get('OX_Dal_Maintenance_Statistics');
         $message = '- Managing (activating/deactivating) campaigns';
         $this->oController->report .= "{$message}.\n";
         OA::debug($message);
         $this->report .= $oDal->manageCampaigns($oDate);
     }
 }
Exemple #11
0
 function OA_XML_RPC_Client($path, $server, $port = 0, $proxy = '', $proxy_port = 0, $proxy_user = '', $proxy_pass = '')
 {
     if ($aExtensions = OA::getAvailableSSLExtensions()) {
         $this->hasCurl = in_array('curl', $aExtensions);
         $this->hasOpenssl = in_array('openssl', $aExtensions);
     }
     $this->verifyPeer = false;
     // This CA file is reused in openXMarket plugin
     // to setup curl in Zend_Http_Client_Adapter_Curl in same way as here
     $this->caFile = MAX_PATH . '/etc/curl-ca-bundle.crt';
     parent::XML_RPC_Client($path, $server, $port);
 }
Exemple #12
0
 /**
  * A method to derive the class name to instantiate.
  *
  * @return string The name of the class object to create.
  */
 function deriveClassName()
 {
     $aConf = $GLOBALS['_MAX']['CONF'];
     $filename = ucfirst(strtolower($aConf['database']['type']));
     $classname = 'OX_Dal_Maintenance_Statistics_' . $filename;
     $includeFile = LIB_PATH . "/Dal/Maintenance/Statistics/{$filename}.php";
     require_once $includeFile;
     if (!class_exists($classname)) {
         // Unable to include the specified class file - raise error and halt
         OA::debug('Unable to find the "' . $classname . '" class in the "' . $includeFile . '" file.', PEAR_LOG_ERR);
         OA::debug('Aborting script execution', PEAR_LOG_ERR);
         exit;
     }
     return $classname;
 }
 /**
  * A method to prune a bucket of all records up to and
  * including the timestamp given.
  *
  * @param Date $oEnd   Prune until this interval_start (inclusive).
  * @param Date $oStart Only prune before this interval_start date (inclusive)
  *                     as well. Optional.
  * @return mixed Either the number of rows pruned, or an MDB2_Error objet.
  */
 public function pruneBucket($oBucket, $oEnd, $oStart = null)
 {
     $sTableName = $oBucket->getBucketTableName();
     if (!is_null($oStart)) {
         OA::debug('  - Pruning the ' . $sTableName . ' table for data with operation interval start between ' . $oStart->format('%Y-%m-%d %H:%M:%S') . ' ' . $oStart->tz->getShortName() . ' and ' . $oEnd->format('%Y-%m-%d %H:%M:%S') . ' ' . $oEnd->tz->getShortName(), PEAR_LOG_DEBUG);
     } else {
         OA::debug('  - Pruning the ' . $sTableName . ' table for all data with operation interval start equal to or before ' . $oEnd->format('%Y-%m-%d %H:%M:%S') . ' ' . $oEnd->tz->getShortName(), PEAR_LOG_DEBUG);
     }
     $query = "\n            DELETE FROM\n                {$sTableName}\n            WHERE\n                interval_start <= " . DBC::makeLiteral($oEnd->format('%Y-%m-%d %H:%M:%S'));
     if (!is_null($oStart)) {
         $query .= "\n                AND\n                interval_start >= " . DBC::makeLiteral($oStart->format('%Y-%m-%d %H:%M:%S'));
     }
     $oDbh = OA_DB::singleton();
     return $oDbh->exec($query);
 }
Exemple #14
0
 /**
  * A method to invoke errors.
  *
  * @static
  * @param mixed $message A string error message, or a {@link PEAR_Error} object.
  * @param integer $type A custom message code - see the {@link setupConstants()} function.
  * @param integer $behaviour Optional behaviour (i.e. PEAR_ERROR_DIE to halt on this error).
  * @return PEAR_Error $error A (@link PEAR_Error} object.
  */
 function raiseError($message, $type = null, $behaviour = null)
 {
     // If fatal
     if ($behaviour == PEAR_ERROR_DIE) {
         // Log fatal message here as execution will stop
         $errorType = MAX::errorConstantToString($type);
         if (!is_string($message)) {
             $message = print_r($message, true);
         }
         OA::debug($type . ' :: ' . $message, PEAR_LOG_EMERG);
         exit;
     }
     $error = PEAR::raiseError($message, $type, $behaviour);
     return $error;
 }
 /**
  * A method to test the checkOperationIntervalValue() method.
  *
  */
 function testCheckOperationIntervalValue()
 {
     OA::disableErrorHandling();
     for ($i = -1; $i <= 61; $i++) {
         $result = OX_OperationInterval::checkOperationIntervalValue($i);
         if ($i == 1 || $i == 2 || $i == 3 || $i == 4 || $i == 5 || $i == 6 || $i == 10 || $i == 12 || $i == 15 || $i == 20 || $i == 30 || $i == 60) {
             $this->assertTrue($result);
         } else {
             $this->assertTrue(PEAR::isError($result));
         }
         $result = OX_OperationInterval::checkOperationIntervalValue(120);
         $this->assertTrue(PEAR::isError($result));
     }
     OA::enableErrorHandling();
 }
 /**
  * A method to run distributed maintenance.
  */
 function run()
 {
     if (empty($GLOBALS['_MAX']['CONF']['lb']['enabled'])) {
         OA::debug('Distributed stats disabled, not running Maintenance Distributed Engine', PEAR_LOG_INFO);
         return;
     }
     if (!empty($GLOBALS['_MAX']['CONF']['rawDatabase'])) {
         $GLOBALS['_MAX']['CONF']['database'] = $GLOBALS['_MAX']['CONF']['rawDatabase'] + $GLOBALS['_MAX']['CONF']['database'];
         OA::debug('rawDatabase functionality is being used, switching settings', PEAR_LOG_INFO);
     }
     $oLock =& OA_DB_AdvisoryLock::factory();
     if (!$oLock->get(OA_DB_ADVISORYLOCK_DISTRIBUTED)) {
         OA::debug('Maintenance Distributed Engine Already Running', PEAR_LOG_INFO);
         return;
     }
     OA::debug('Running Maintenance Distributed Engine', PEAR_LOG_INFO);
     // Attempt to increase PHP memory
     OX_increaseMemoryLimit(OX_getMinimumRequiredMemory('maintenance'));
     // Ensure the current time is registered with the OA_ServiceLocator
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oNow =& $oServiceLocator->get('now');
     if (!$oNow) {
         // Record the current time, and register with the OA_ServiceLocator
         $oNow = new Date();
         $oServiceLocator->register('now', $oNow);
     }
     OA::debug(' - Current time is ' . $oNow->format('%Y-%m-%d %H:%M:%S') . ' ' . $oNow->tz->getShortName(), PEAR_LOG_DEBUG);
     // Get the components of the deliveryLog extension
     $aBuckets = OX_Component::getComponents('deliveryLog');
     // Copy buckets' records with "interval_start" up to and including previous OI start,
     // and then prune the data processed
     $aPreviousOperationIntervalDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oNow);
     OA::debug(' - Will process data for all operation intervals before and up to start', PEAR_LOG_DEBUG);
     OA::debug('   time of ' . $aPreviousOperationIntervalDates['start']->format('%Y-%m-%d %H:%M:%S') . ' ' . $aPreviousOperationIntervalDates['start']->tz->getShortName(), PEAR_LOG_DEBUG);
     foreach ($aBuckets as $sBucketName => $oBucketClass) {
         if ($oBucketClass->testStatisticsMigration($oBucketClass->getStatisticsMigration())) {
             $oBucketClass->processBucket($aPreviousOperationIntervalDates['start']);
             $oBucketClass->pruneBucket($aPreviousOperationIntervalDates['start']);
         } else {
             OA::debug('  - Skipping ' . $sBucketName, PEAR_LOG_DEBUG);
         }
     }
     $oLock->release();
     OA::debug('Maintenance Distributed Engine Completed', PEAR_LOG_INFO);
 }
Exemple #17
0
 /**
  * Returns phpAdsNew style config version.
  *
  * The OpenX version "number" is converted to an int using the following table:
  *
  * 'beta-rc' => 0.1
  * 'beta'    => 0.2
  * 'rc'      => 0.3
  * ''        => 0.4
  *
  * i.e.
  * v0.3.29-beta-rc10 becomes:
  *  0   *   1000 +
  *  3   *    100 +
  * 29   *      1 +    // Cannot exceed 100 patch releases!
  *  0.1          +
  * 10   /   1000 =
  * -------------
  *        3293.1
  */
 function getConfigVersion($version)
 {
     $a = array('dev' => -0.001, 'beta-rc' => 0.1, 'beta' => 0.2, 'rc' => 0.3, 'stable' => 0.4);
     $version = OA::stripVersion($version, array('dev', 'stable'));
     if (preg_match('/^v/', $version)) {
         $v = preg_split('/[.-]/', substr($version, 1));
     } else {
         $v = preg_split('/[.-]/', $version);
     }
     if (count($v) < 3) {
         return false;
     }
     // Prepare value from the first 3 items
     $returnValue = $v[0] * 1000 + $v[1] * 100 + $v[2];
     // How many items were there?
     if (count($v) == 5) {
         // Check that it is a beta-rc release
         if (!$v[3] == 'beta' || !preg_match('/^rc(\\d+)/', $v[4], $aMatches)) {
             return false;
         }
         // Add the beta-rc
         $returnValue += $a['beta-rc'] + $aMatches[1] / 1000;
         return $returnValue;
     } else {
         if (count($v) == 4) {
             // Check that it is a tag or rc numer
             if (isset($a[$v[3]])) {
                 // Add the beta
                 $returnValue += $a[$v[3]];
                 return $returnValue;
             } else {
                 if (preg_match('/^rc(\\d+)/', $v[3], $aMatches)) {
                     // Add the rc
                     $returnValue += $a['rc'] + $aMatches[1] / 1000;
                     return $returnValue;
                 }
             }
             return false;
         }
     }
     // Stable release
     $returnValue += $a['stable'];
     return $returnValue;
 }
 /**
  * Generate and save a recovery ID for a user
  *
  * @param int user ID
  * @return array generated recovery ID
  */
 function generateRecoveryId($userId)
 {
     $doPwdRecovery = OA_Dal::factoryDO('password_recovery');
     // Make sure that recoveryId is unique in password_recovery table
     do {
         $recoveryId = strtoupper(md5(uniqid('', true)));
         $recoveryId = substr(chunk_split($recoveryId, 8, '-'), -23, 22);
         $doPwdRecovery->recovery_id = $recoveryId;
     } while ($doPwdRecovery->find() > 0);
     $doPwdRecovery = OA_Dal::factoryDO('password_recovery');
     $doPwdRecovery->whereAdd('user_id = ' . DBC::makeLiteral($userId));
     $doPwdRecovery->delete(true);
     $doPwdRecovery = OA_Dal::factoryDO('password_recovery');
     $doPwdRecovery->user_type = 'user';
     $doPwdRecovery->user_id = $userId;
     $doPwdRecovery->recovery_id = $recoveryId;
     $doPwdRecovery->updated = OA::getNowUTC();
     $doPwdRecovery->insert();
     return $recoveryId;
 }
Exemple #19
0
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;
}
Exemple #20
0
 /**
  * Returns authentication plugin
  *
  * @static
  * @param string $authType
  * @return Plugins_Authentication
  */
 static function staticGetAuthPlugin()
 {
     static $authPlugin;
     static $authPluginType;
     if (!isset($authPlugin) || $authPluginType != $authType) {
         $aConf = $GLOBALS['_MAX']['CONF'];
         if (!empty($aConf['authentication']['type'])) {
             $authType = $aConf['authentication']['type'];
             $authPlugin = OX_Component::factoryByComponentIdentifier($authType);
         }
         if (!$authPlugin) {
             // Fall back to internal
             $authType = 'none';
             $authPlugin = new Plugins_Authentication();
         }
         if (!$authPlugin) {
             OA::debug('Error while including authentication plugin and unable to fallback', PEAR_LOG_ERR);
         }
         $authPluginType = $authType;
     }
     return $authPlugin;
 }
 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());
 }
Exemple #24
0
 /**
  * Connect to OpenX Sync to check for updates
  *
  * @param float $already_seen Only check for updates newer than this value.
  * @return array An array of two items:
  *
  *               Item 0 is the XML-RPC error code. Meanings:
  *                      -2  => The admin user has disabled update checking
  *                      -1  => No response from the server
  *                  0 - 799 => XML-RPC library error codes
  *                       0  => No error
  *                     800  => No updates
  *                     801+ => Error codes from the remote XML-RPC server
  *
  *               Item 1 is either the error message (item 1 != 0), or an array containing update info
  */
 function checkForUpdates($already_seen = 0)
 {
     global $XML_RPC_erruser;
     if (!$this->aConf['sync']['checkForUpdates']) {
         // Checking for updates has been disabled by the admin user,
         // so do not communicate with the server that provides the
         // details of what upgrades are available - just return an
         // 800 "error"
         $aReturn = array(-2, 'Check for updates has been disabled by the administrator.');
         return $aReturn;
     }
     // Create the XML-RPC client object
     $client = OA_Central::getXmlRpcClient($this->_conf);
     // Prepare the installation's platform hash
     $platform_hash = OA_Dal_ApplicationVariables::get('platform_hash');
     if (!$platform_hash) {
         // The installation does not have a platform hash; generate one,
         // and save it to the database for later use
         OA::debug("Generating a new platform_hash for the installation", PEAR_LOG_INFO);
         $platform_hash = OA_Dal_ApplicationVariables::generatePlatformHash();
         if (!OA_Dal_ApplicationVariables::set('platform_hash', $platform_hash)) {
             OA::debug("Could not save the new platform_hash to the database", PEAR_LOG_ERR);
             unset($platform_hash);
             OA::debug("Sync process proceeding without a platform_hash", PEAR_LOG_INFO);
         }
     }
     // Prepare the parameters required for the XML-RPC call to
     // obtain if an update is available for this installation
     $params = array(new XML_RPC_Value(PRODUCT_NAME, 'string'), new XML_RPC_Value($this->getConfigVersion(OA_Dal_ApplicationVariables::get('oa_version')), 'string'), new XML_RPC_Value($already_seen, 'string'), new XML_RPC_Value($platform_hash, 'string'));
     // Has the Revive Adserver admin user kindly agreed to share the
     // technology stack that it is running on, to help the community?
     $aTechStack = array('data' => false);
     if ($this->aConf['sync']['shareStack']) {
         // Thanks, admin user! You're a star! Prepare the technology stack
         // data and add it to the XML-RPC call
         if ($this->oDbh->dbsyntax == 'mysql') {
             $dbms = 'MySQL';
         } else {
             if ($this->oDbh->dbsyntax == 'pgsql') {
                 $dbms = 'PostgreSQL';
             } else {
                 $dbms = 'UnknownSQL';
             }
         }
         $aTechStack = array('os_type' => php_uname('s'), 'os_version' => php_uname('r'), 'webserver_type' => isset($_SERVER['SERVER_SOFTWARE']) ? preg_replace('#^(.*?)/.*$#', '$1', $_SERVER['SERVER_SOFTWARE']) : '', 'webserver_version' => isset($_SERVER['SERVER_SOFTWARE']) ? preg_replace('#^.*?/(.*?)(?: .*)?$#', '$1', $_SERVER['SERVER_SOFTWARE']) : '', 'db_type' => $dbms, 'db_version' => $this->oDbh->queryOne("SELECT VERSION()"), 'php_version' => phpversion(), 'php_sapi' => ucfirst(php_sapi_name()), 'php_extensions' => get_loaded_extensions(), 'php_register_globals' => (bool) ini_get('register_globals'), 'php_magic_quotes_gpc' => (bool) ini_get('magic_quotes_gpc'), 'php_safe_mode' => (bool) ini_get('safe_mode'), 'php_open_basedir' => (bool) strlen(ini_get('open_basedir')), 'php_upload_tmp_readable' => (bool) is_readable(ini_get('upload_tmp_dir') . DIRECTORY_SEPARATOR));
     }
     $params[] = XML_RPC_Encode($aTechStack);
     // Add the registered email address
     $params[] = new XML_RPC_Value(OA_Dal_ApplicationVariables::get('sync_registered_email'), 'string');
     // Create the XML-RPC request message
     $msg = new XML_RPC_Message("Revive.Sync", $params);
     // Send the XML-RPC request message
     if ($response = $client->send($msg, 10)) {
         // XML-RPC server found, now checking for errors
         if (!$response->faultCode()) {
             // No fault! Woo! Get the response and return it!
             $aReturn = array(0, XML_RPC_Decode($response->value()));
             // Prepare cache
             $cache = $aReturn[1];
             // Update last run
             OA_Dal_ApplicationVariables::set('sync_last_run', date('Y-m-d H:i:s'));
             // Also write to the debug log
             OA::debug("Sync: updates found!", PEAR_LOG_INFO);
         } else {
             // Boo! An error! (Well, maybe - if it's 800, yay!)
             $aReturn = array($response->faultCode(), $response->faultString());
             // Prepare cache
             $cache = false;
             // Update last run
             if ($response->faultCode() == 800) {
                 // Update last run
                 OA_Dal_ApplicationVariables::set('sync_last_run', date('Y-m-d H:i:s'));
                 // Also write to the debug log
                 OA::debug("Sync: {$aReturn[1]}", PEAR_LOG_INFO);
             } else {
                 // Write to the debug log
                 OA::debug("Sync: {$aReturn[1]} (code: {$aReturn[0]}", PEAR_LOG_ERR);
                 // Return immediately without writing to cache
                 return $aReturn;
             }
         }
         OA_Dal_ApplicationVariables::set('sync_cache', serialize($cache));
         OA_Dal_ApplicationVariables::set('sync_timestamp', time());
         return $aReturn;
     }
     $aReturn = array(-1, 'No response from the remote XML-RPC server.');
     // Also write to the debug log
     OA::debug("Sync: {$aReturn[1]}", PEAR_LOG_ERR);
     return $aReturn;
 }
Exemple #25
0
 /**
  * Performs a batch insert using either LOAD DATA INFILE or COPY FROM, eventually
  * falling back to batchInsertPlain (plain INSERTs) on failure. On MySQL LOAD DATA
  * INFILE is 20x faster than plain single inserts
  *
  * @param string $tableName The unquoted table name
  * @param array  $aFields   The array of unquoted field names
  * @param array  $aValues   The array of data to be inserted
  * @param bool $replace Should the data be UPDATEd when the primary key or unique key is already present in the table?
  *
  * @return int   The number of rows inserted or PEAR_Error on failure
  */
 function batchInsert($tableName, $aFields, $aValues, $replace = false, $primaryKey = array())
 {
     if (!is_array($aFields) || !is_array($aValues)) {
         return MAX::raiseError('$aFields and $aValues must be arrays', PEAR_ERROR_RETURN);
     }
     $oDbh = OA_DB::singleton();
     // Quote table name
     $qTableName = $oDbh->quoteIdentifier($tableName);
     // Quote fields list
     $fieldList = '(' . join(',', array_map(array($oDbh, 'quoteIdentifier'), $aFields)) . ')';
     // Database custom stuff
     if ($oDbh->dbsyntax == 'mysql') {
         $result = self::_batchInsertMySQL($qTableName, $fieldList, $aValues, $replace);
     } else {
         $result = self::_batchInsertPgSQL($qTableName, $fieldList, $aValues, $replace, $primaryKey);
     }
     if (PEAR::isError($result)) {
         OA::debug('LOAD DATA INFILE / COPY failed or not supported, falling back to INSERTing data by looping over each record...', PEAR_LOG_INFO);
         $result = self::batchInsertPlain($tableName, $aFields, $aValues);
     }
     return $result;
 }
Exemple #26
0
 /**
  * A method to validate table name
  *
  * @param string $name
  * @return true if valid PEAR error otherwise
  */
 static function validateTableName($name)
 {
     /*if ( !preg_match( '/^([a-zA-z_])([a-zA-z0-9_])*$/', $name) )
       {
           $result = false;
       }
       else if (preg_match( '/(\\\\|\/|\"|\\\'| |\(|\)|\:|\;|\`|\[|\]|\^)/', $name))
       {
           $result = false;
       }*/
     $result = true;
     OA::disableErrorHandling();
     $pattern = '/(?P<found>[\\x00-\\x23]|[\\x25-\\x29]|[\\x2a-\\x2f]|[\\x3a-\\x3f]|[\\x40]|[\\x5b-\\x5e]|[\\x60]|[\\x7b-\\x7e]|[\\x9c]|[\\xff])/U';
     if (preg_match($pattern, $name, $aMatches)) {
         $msg = 'Illegal character in table name ' . $aMatches['found'] . ' chr(' . ord($aMatches['found']) . ')';
         $result = PEAR::raiseError($msg);
     }
     if (PEAR::isError($result)) {
         OA::enableErrorHandling();
         $msg = 'Table names may not contain any of ! " # % & \' ( ) * + , - . \\/ : ; < = > ? @ [ \\ ] ^ ` { | } ~ £ nor any non-printing characters';
         return $result;
     }
     $oDbh = OA_DB::singleton();
     if (PEAR::isError($oDbh)) {
         OA::enableErrorHandling();
         return $oDbh;
     }
     $result = $oDbh->manager->validateTableName($name);
     OA::enableErrorHandling();
     if (PEAR::isError($result)) {
         return $result;
     }
     return true;
 }
Exemple #27
0
/**
 * This function check if the click logging for an add is blocked
 * when the block logging is active
 *
 * @param integer $adId              The add's id of the add that the function checks
 *                                   if is blocked for click logging
 * @param array $aBlockLoggingClick  And array with the timestamps of the last click logged
 *                                   for every add that has been clicked
 * @return boolean                   Returns true when the click block logging window for
 *                                   and add hasn't expired yet
 */
function MAX_Delivery_log_isClickBlocked($adId, $aBlockLoggingClick)
{
    if (isset($GLOBALS['conf']['logging']['blockAdClicksWindow']) && $GLOBALS['conf']['logging']['blockAdClicksWindow'] != 0) {
        if (isset($aBlockLoggingClick[$adId])) {
            $endBlock = MAX_commonUnCompressInt($aBlockLoggingClick[$adId]) + $GLOBALS['conf']['logging']['blockAdClicksWindow'];
            if ($endBlock >= MAX_commonGetTimeNow()) {
                ###START_STRIP_DELIVERY
                OA::debug('adID ' . $adId . ' click is still blocked by block logging window ');
                ###END_STRIP_DELIVERY
                return true;
            }
        }
    }
    return false;
}
 /**
  * Deletes users who are not linked with any sso account, never logged
  * in and their account was created before deleteUnverifiedUsersAfter days.
  * Where deleteUnverifiedUsersAfter is defined in config in
  * "authentication" section.
  *
  * @return boolean
  */
 function deleteUnverifiedUsers($deleteOlderThanSeconds = null)
 {
     if (empty($deleteOlderThanSeconds)) {
         // by default 28 days
         $deleteOlderThanSeconds = OA::getConfigOption('authentication', 'deleteUnverifiedUsersAfter', 2419200);
     }
     $monthAgo = new Date();
     $monthAgo->subtractSeconds($deleteOlderThanSeconds);
     $this->whereAdd('date_created < \'' . $this->formatDate($monthAgo) . '\'');
     $this->whereAdd('sso_user_id IS NULL');
     $this->whereAdd('date_last_login IS NULL');
     return $this->delete(DB_DATAOBJECT_WHEREADD_ONLY);
 }
Exemple #29
0
 function generateTags($zoneId, $codeType, $aParams = null)
 {
     // Backwards Compatibity Array for code types
     $aBackwardsCompatibityTypes = array('adframe' => 'invocationTags:oxInvocationTags:adframe', 'adjs' => 'invocationTags:oxInvocationTags:adjs', 'adlayer' => 'invocationTags:oxInvocationTags:adlayer', 'adview' => 'invocationTags:oxInvocationTags:adview', 'adviewnocookies' => 'invocationTags:oxInvocationTags:adviewnocookies', 'local' => 'invocationTags:oxInvocationTags:local', 'popup' => 'invocationTags:oxInvocationTags:popup', 'xmlrpc' => 'invocationTags:oxInvocationTags:xmlrpc');
     // Translate old code type to new Component Identifier
     if (array_key_exists($codeType, $aBackwardsCompatibityTypes)) {
         $codeType = $aBackwardsCompatibityTypes[$codeType];
     }
     if ($this->checkIdExistence('zones', $zoneId)) {
         $doZones = OA_Dal::staticGetDO('zones', $zoneId);
         if (!$this->checkPermissions(null, 'affiliates', $doZones->affiliateid, OA_PERM_ZONE_INVOCATION)) {
             return false;
         }
         $aAllowedTags = $this->getAllowedTags();
         if (!in_array($codeType, $aAllowedTags)) {
             $this->raiseError('Field \'codeType\' must be one of the enum: ' . join(', ', $aAllowedTags));
             return false;
         }
         if (!empty($codeType)) {
             require_once MAX_PATH . '/lib/max/Admin/Invocation.php';
             $maxInvocation = new MAX_Admin_Invocation();
             // factory plugin for this $codetype
             OA::disableErrorHandling();
             $invocationTag = OX_Component::factoryByComponentIdentifier($codeType);
             OA::enableErrorHandling();
             if ($invocationTag === false) {
                 $this->raiseError('Error while factory invocationTag plugin');
                 return false;
             }
             $invocationTag->setInvocation($maxInvocation);
             $aParams['zoneid'] = $zoneId;
             $aParams['codetype'] = $codeType;
             $buffer = $maxInvocation->generateInvocationCode($invocationTag, $aParams);
             return $buffer;
         } else {
             $this->raiseError('Parameter codeType wrong');
         }
     }
     return false;
 }
Exemple #30
0
 /**
  * Resets a (postgresql) sequence to 1
  * similar to OA_DB_Table::resetSequence()
  * DOESN'T SEEM TO WORK THO
  *
  * @param string $sequence the name of the sequence to reset
  * @return boolean true on success, false otherwise
  */
 function resetSequence($tableName)
 {
     $aConf = $GLOBALS['_MAX']['CONF'];
     $oDbh = OA_DB::singleton();
     if ($aConf['database']['type'] == 'pgsql') {
         OA_DB::setCaseSensitive();
         $aSequences = $oDbh->manager->listSequences();
         OA_DB::disableCaseSensitive();
         if (is_array($aSequences)) {
             OA::debug('Resetting sequence ' . $sequence, PEAR_LOG_DEBUG);
             OA::disableErrorHandling(null);
             $tableName = substr($aConf['table']['prefix'] . $tableName, 0, 29) . '_';
             foreach ($aSequences as $k => $sequence) {
                 if (strpos($sequence, $tableName) === 0) {
                     $sequence = $oDbh->quoteIdentifier($sequence . '_seq', true);
                     $result = $oDbh->exec("SELECT setval('{$sequence}', 1, false)");
                     break;
                 }
             }
             OA::enableErrorHandling();
             if (PEAR::isError($result)) {
                 OA::debug('Unable to reset sequence on table ' . $tableName, PEAR_LOG_ERR);
                 return false;
             }
         }
     } else {
         if ($aConf['database']['type'] == 'mysql') {
             $tableName = $aConf['table']['prefix'] . $tableName;
             OA::disableErrorHandling();
             $result = $oDbh->exec("ALTER TABLE {$tableName} AUTO_INCREMENT = 1");
             OA::enableErrorHandling();
             if (PEAR::isError($result)) {
                 OA::debug('Unable to reset sequence on table ' . $tableName, PEAR_LOG_ERR);
                 return false;
             }
         }
     }
     return true;
 }