예제 #1
0
 /**
  * Class constructor
  *
  * @param MDB2_Driver_Common $oDbh
  * @return OA_DB_Charset
  */
 function __construct(&$oDbh)
 {
     $aVersion = $oDbh->getServerVersion();
     if (version_compare($aVersion['native'], '4.1.2', '>=')) {
         parent::__construct($oDbh);
     }
 }
예제 #2
0
 /**
  * Class constructor
  *
  * @param MDB2_Driver_Common $oDbh
  * @return OA_DB_Charset
  */
 function OA_DB_Charset_mysql(&$oDbh)
 {
     $aVersion = $oDbh->getServerVersion();
     if (version_compare($aVersion['native'], '4.1.2', '>=')) {
         parent::OA_DB_Charset($oDbh);
     }
 }
예제 #3
0
 function rollback()
 {
     if ($this->hasTransactions) {
         $this->oDbh->rollback();
         return true;
     }
     return false;
 }
 /**
  * A method to test when there are no old format raw requests,
  * impressions and clicks.
  */
 function testNoData()
 {
     $aConf =& $GLOBALS['_MAX']['CONF'];
     $aConf['maintenance']['operationInterval'] = 60;
     // Prepare an array of the required tables used in testing
     $aTables = array($aConf['table']['prefix'] . $aConf['table']['data_raw_ad_request'] => $aConf['table']['prefix'] . 'data_bkt_r', $aConf['table']['prefix'] . $aConf['table']['data_raw_ad_impression'] => $aConf['table']['prefix'] . 'data_bkt_m', $aConf['table']['prefix'] . $aConf['table']['data_raw_ad_click'] => $aConf['table']['prefix'] . 'data_bkt_c');
     // Install the openXDeliveryLog plugin, which will create the
     // data bucket tables required for testing
     TestEnv::installPluginPackage('openXDeliveryLog', false);
     // Ensure that there are no old format raw data
     foreach ($aTables as $rawTable => $bucketTable) {
         $query = "\n                SELECT\n                    COUNT(*) AS count\n                FROM\n                    " . $this->oDbh->quoteIdentifier($rawTable, true);
         $rsResult = $this->oDbh->query($query);
         $this->assertNotA($rsReults, 'PEAR_Error');
         $rows = $rsResult->numRows();
         $this->assertEqual($rows, 1);
         $aRow = $rsResult->fetchRow();
         $this->assertEqual($aRow['count'], 0);
     }
     // Ensure that there are no new format bucket data
     foreach ($aTables as $rawTable => $bucketTable) {
         $query = "\n                SELECT\n                    COUNT(*) AS count\n                FROM\n                    " . $this->oDbh->quoteIdentifier($bucketTable, true);
         $rsResult = $this->oDbh->query($query);
         $this->assertNotA($rsReults, 'PEAR_Error');
         $rows = $rsResult->numRows();
         $this->assertEqual($rows, 1);
         $aRow = $rsResult->fetchRow();
         $this->assertEqual($aRow['count'], 0);
     }
     // Run the migration of raw data DAL code for a given OI
     $oStart = new Date('2009-01-09 12:00:00');
     $oEnd = new Date('2009-01-09 12:59:59');
     $this->oDal->migrateRawRequests($oStart, $oEnd);
     $this->oDal->migrateRawImpressions($oStart, $oEnd);
     $this->oDal->migrateRawClicks($oStart, $oEnd);
     // Re-test that there are still no new format bucket data
     foreach ($aTables as $rawTable => $bucketTable) {
         $query = "\n                SELECT\n                    COUNT(*) AS count\n                FROM\n                    " . $this->oDbh->quoteIdentifier($bucketTable, true);
         $rsResult = $this->oDbh->query($query);
         $this->assertNotA($rsReults, 'PEAR_Error');
         $rows = $rsResult->numRows();
         $this->assertEqual($rows, 1);
         $aRow = $rsResult->fetchRow();
         $this->assertEqual($aRow['count'], 0);
     }
     // Uninstall the installed plugin
     TestEnv::uninstallPluginPackage('openXDeliveryLog', false);
     // Restore the test environment configuration
     TestEnv::restoreConfig();
 }
예제 #5
0
    /**
     * Gets a recordset of tag dataobjects.
     *
     * @param SwatDBRange $range optional. Range of tags to retrieve. If not
     *                           specified, all tags are loaded.
     * @param string $order_by_clause optional. SQL order by clause of the tag
     *                                list.
     *
     * @return PinholeTagDataObjectWrapper
     */
    private function getSubTagDataObjects(SwatDBRange $range = null, $order_by_clause = null)
    {
        $args = func_get_args();
        $cache_key = $this->getCacheKey(__FUNCTION__, $args);
        $value = $this->app->getCacheRecordset($cache_key, 'PinholeTagDataObjectWrapper', 'photos');
        if ($value !== false) {
            return $value;
        }
        if ($order_by_clause === null) {
            $order_by_clause = 'PinholeTagDateView.first_modified desc';
        }
        $sql = sprintf('select PinholeTag.*,
				PinholeTagDateView.first_modified,
				PinholeTagDateView.last_modified
			from PinholeTag
			inner join PinholeTagDateView on
				PinholeTagDateView.tag = PinholeTag.id
			where %s
			order by %s', $this->getSubTagWhereClause(), $order_by_clause);
        if ($range !== null) {
            $this->db->setLimit($range->getLimit(), $range->getOffset());
        }
        $tag_data_objects = SwatDB::query($this->db, $sql, 'PinholeTagDataObjectWrapper');
        $this->app->addCacheRecordset($tag_data_objects, $cache_key, 'photos');
        return $tag_data_objects;
    }
예제 #6
0
파일: Sync.php 프로젝트: villos/tree_admin
 /**
  * Build global statistics array to be sent through Sync
  *
  * @return array
  */
 function buildStats()
 {
     $lastRun = OA_Dal_ApplicationVariables::get('sync_last_run');
     if ($lastRun) {
         $oStart = new Date($lastRun);
     } else {
         $oStart = new Date();
         $oStart->subtractSpan(new Date_Span('1-0-0-0'));
     }
     $oStart->setMinute(0);
     $oStart->setSecond(0);
     $oEnd = new Date();
     $oEnd->setMinute(0);
     $oEnd->setSecond(0);
     $doDsah = OA_Dal::factoryDO('data_summary_ad_hourly');
     $doDsah->selectAdd();
     $doDsah->selectAdd('date_time');
     $doDsah->selectAdd('SUM(impressions) AS total_impressions');
     $doDsah->selectAdd('SUM(clicks) AS total_clicks');
     $doDsah->whereAdd("date_time >= " . $this->oDbh->quote($oStart->format('%Y-%m-%d %H:%M:%S')));
     $doDsah->whereAdd("date_time < " . $this->oDbh->quote($oEnd->format('%Y-%m-%d %H:%M:%S')));
     $doDsah->groupBy('date_time');
     $doDsah->orderBy('date_time');
     $doDsah->find();
     $aStats = array();
     while ($doDsah->fetch()) {
         $row = $doDsah->toArray();
         $aStats[$row['date_time']] = array('impressions' => $row['total_impressions'], 'clicks' => $row['total_clicks']);
     }
     return $aStats;
 }
예제 #7
0
 function outdateSession()
 {
     $sessionId = SESSIONID;
     $prefix = OA_Dal::getTablePrefix();
     $table = $this->dbh->quoteIdentifier($prefix . 'session');
     $this->dbh->exec("UPDATE {$table} set lastused = '2005-01-01 01:00:00' WHERE sessionid = '{$sessionId}'");
 }
 function execute($aParams)
 {
     $this->oUpgrade =& $aParams[0];
     $this->oDbh =& OA_DB::singleton();
     $aConf = $GLOBALS['_MAX']['CONF']['table'];
     $this->prefix = $aConf['prefix'];
     $this->tblPreferences = $aConf['prefix'] . ($aConf['preferences'] ? $aConf['preferences'] : 'preferences');
     $query = "INSERT INTO " . $this->oDbh->quoteIdentifier($this->tblPreferences, true) . "\n                  (preference_name, account_type)\n                 VALUES('campaign_ecpm_enabled', 'MANAGER')";
     $ret = $this->oDbh->query($query);
     //check for error
     if (PEAR::isError($ret)) {
         $this->logError($ret->getUserInfo());
         return false;
     }
     $this->logOnly("Added 'campaign_ecpm_enabled' preference to 'MANAGER' account");
     return true;
 }
예제 #9
0
파일: Abstract.php 프로젝트: gauthierm/MDB2
 public function tableExists($table)
 {
     $this->db->loadModule('Manager', null, true);
     $tables = $this->db->manager->listTables();
     if (MDB2::isError($tables)) {
         //$this->fail('Cannot list tables: '. $tables->getUserInfo());
         return false;
     }
     return in_array(strtolower($table), array_map('strtolower', $tables));
 }
 function execute($aParams)
 {
     $this->oUpgrade =& $aParams[0];
     $this->oDbh =& OA_DB::singleton();
     $aConf = $GLOBALS['_MAX']['CONF']['table'];
     $prefix = $aConf['prefix'];
     $tblBanners = $prefix . ($aConf['banners'] ? $aConf['banners'] : 'banners');
     $tblAza = $prefix . ($aConf['ad_zone_assoc'] ? $aConf['ad_zone_assoc'] : 'ad_zone_assoc');
     $query = "\n            SELECT\n                bannerid,\n                0 AS zoneid,\n                " . MAX_AD_ZONE_LINK_DIRECT . " AS link_type\n            FROM\n                " . $this->oDbh->quoteIdentifier($tblBanners, true) . " b LEFT JOIN\n                " . $this->oDbh->quoteIdentifier($tblAza, true) . " aza ON (b.bannerid = aza.ad_id AND aza.zone_id = 0)\n            WHERE\n                aza.ad_id IS NULL\n            ";
     $query = "\n            INSERT INTO " . $this->oDbh->quoteIdentifier($tblAza, true) . "\n                (ad_id, zone_id, link_type)\n            " . $query;
     $ret = $this->oDbh->exec($query);
     //check for error
     if (PEAR::isError($ret)) {
         $this->logError($ret->getUserInfo());
         return false;
     }
     $this->logOnly("Added {$ret} missing banner links to zone 0");
     return true;
 }
예제 #11
0
파일: db.php 프로젝트: ryanshoover/core
 /**
  * Commit the database changes done during a transaction that is in progress
  * @return bool
  */
 public static function commit()
 {
     self::connect();
     if (!self::$inTransaction) {
         return false;
     }
     self::$connection->commit();
     self::$inTransaction = false;
     return true;
 }
 function getLinkedSequence($table, $field_name)
 {
     $query = "SELECT\n                    (SELECT substring(pg_get_expr(d.adbin, d.adrelid) for 128)\n                        FROM pg_attrdef d\n                        WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef) as default\n                    FROM pg_attribute a, pg_class c\n                    WHERE c.relname = " . $this->oDbh->quote($table, 'text') . "\n                        AND c.oid = a.attrelid\n                        AND NOT a.attisdropped\n                        AND a.attnum > 0\n                        AND a.attname = " . $this->oDbh->quote($field_name, 'text') . "\n                    ORDER BY a.attnum";
     $column = $this->oDbh->queryRow($query, null, MDB2_FETCHMODE_ASSOC);
     if (!PEAR::isError($column)) {
         if (preg_match('/nextval\\(\'(.*?)\'/', $column['default'], $m)) {
             return $m[1];
         }
     }
     return false;
 }
 function execute($aParams)
 {
     // Insert the required application variable flag to ensure that
     // when the maintenance script next runs, it will process all
     // raw data into the new bucket format, so that any raw data not
     // previously summarised will be accounted for
     $this->oUpgrade =& $aParams[0];
     $this->oDbh =& OA_DB::singleton();
     $aConf = $GLOBALS['_MAX']['CONF']['table'];
     $this->tblApplicationVariable = $aConf['prefix'] . ($aConf['application_variable'] ? $aConf['application_variable'] : 'application_variable');
     $query = "\n            INSERT INTO\n                " . $this->oDbh->quoteIdentifier($this->tblApplicationVariable, true) . "\n                (\n                    name,\n                    value\n                )\n            VALUES\n                (\n                    'mse_process_raw',\n                    '1'\n                )";
     $this->logOnly("Setting application variable flag to ensure ME processes old sytle raw data on next run...");
     $rs = $this->oDbh->exec($query);
     // Check for errors
     if (PEAR::isError($rs)) {
         $this->logError($rs->getUserInfo());
         return false;
     }
     $this->logOnly("Application variable flag to ensure ME processes old sytle raw data on next run correctly set.");
     return true;
 }
 function execute($aParams)
 {
     $this->oUpgrade =& $aParams[0];
     $this->oDbh =& OA_DB::singleton();
     $aConf = $GLOBALS['_MAX']['CONF']['table'];
     $prefix = $aConf['prefix'];
     foreach (array('tblAppVar' => 'application_variable', 'tblAccounts' => 'accounts', 'tblAgency' => 'agency', 'tblClients' => 'clients', 'tblCampaigns' => 'campaigns', 'tblBanners' => 'banners', 'tblAcls' => 'acls', 'tblPrefs' => 'preferences', 'tblAccPrefs' => 'account_preference_assoc') as $k => $v) {
         ${$k} = $this->oDbh->quoteIdentifier($prefix . ($aConf[$v] ? $aConf[$v] : $v), true);
     }
     // Get admin account ID
     $adminAccountId = (int) $this->oDbh->queryOne("SELECT value FROM {$tblAppVar} WHERE name = 'admin_account_id'");
     if (PEAR::isError($adminAccountId)) {
         $this->logError("No admin account ID");
         return false;
     }
     // Get preference ID for timezone
     $tzId = $this->oDbh->queryOne("SELECT preference_id FROM {$tblPrefs} WHERE preference_name = 'timezone'");
     if (empty($tzId) || PEAR::isError($tzId)) {
         // Upgrading from 2.4 maybe?
         $tzId = 0;
         $this->logOnly("No timezone preference available, using default server timezone");
         $adminTz = date_default_timezone_get();
         if (empty($adminTz)) {
             // C'mon you should have set the timezone in your php.ini!
             $this->logOnly("No default server timezone, using UTC");
             $adminTz = 'UTC';
         }
     } else {
         // Get admin timezone
         $adminTz = $this->oDbh->queryOne("SELECT value FROM {$tblAccPrefs} WHERE preference_id = {$tzId} AND account_id = {$adminAccountId}");
         if (empty($adminTz) || PEAR::isError($adminTz)) {
             $this->logOnly("No admin timezone, using UTC");
             $adminTz = 'UTC';
         }
     }
     $joinList = "{$tblBanners} b JOIN\n                    {$tblCampaigns} ca USING (campaignid) JOIN\n                    {$tblClients} cl USING (clientid) JOIN\n                    {$tblAgency} a USING (agencyid) LEFT JOIN\n                    {$tblAccPrefs} p ON (p.account_id = a.account_id AND p.preference_id = {$tzId})";
     $tzPart = "COALESCE(p.value, " . $this->oDbh->quote($adminTz) . ")";
     $wherePart = "\n                    ac.bannerid = b.bannerid AND\n                \tac.type LIKE 'deliveryLimitations:Time:%' AND\n                \tac.data NOT LIKE '%@%'\n        ";
     if ($this->oDbh->dbsyntax == 'pgsql') {
         $query = "\n                UPDATE\n                    {$tblAcls} ac\n                SET\n                    data = data || '@' || {$tzPart}\n                FROM\n                    {$joinList}\n                WHERE\n                    {$wherePart}\n            ";
     } else {
         $query = "\n                UPDATE\n                    {$tblAcls} ac,\n                    {$joinList}\n                SET\n                    ac.data = CONCAT(ac.data, '@', {$tzPart})\n                WHERE\n                    {$wherePart}\n            ";
     }
     $ret = $this->oDbh->exec($query);
     if (PEAR::isError($ret)) {
         $this->logError($ret->getUserInfo());
         return false;
     }
     // Rebuild ACLs
     $this->oUpgrade->addPostUpgradeTask('Recompile_Acls');
     // Also rebuild banner cache for OX-5184
     $this->oUpgrade->addPostUpgradeTask('Rebuild_Banner_Cache');
     $this->logOnly("Appended timezone information to {$ret} time based delivery limitations");
     return true;
 }
 /**
  * Update the "Administrator Account" account to "System Administrator", if
  * it still exists for the user, for improved understanding of the account
  * purpose
  */
 function _updateAdministratorAccountToSystemAdministrator()
 {
     $this->oDbh =& OA_DB::singleton();
     $aConf = $GLOBALS['_MAX']['CONF']['table'];
     $this->logOnly("Attempting to rename the 'Administrator Account' account to 'System Administrator' in the 'accounts' table");
     $tblAccounts = $aConf['prefix'] . ($aConf['accounts'] ? $aConf['accounts'] : 'accounts');
     $query = "UPDATE " . $this->oDbh->quoteIdentifier($tblAccounts, true) . " SET account_name = 'System Administrator' WHERE account_name = 'Administrator account'";
     $result = $this->oDbh->query($query);
     if (!PEAR::isError($result)) {
         $this->logOnly("Renamed the old 'Administrator Account' account in the 'accounts' table");
     } else {
         $this->logError("Failed to rename the old 'Administrator Account' account in the 'accounts' table");
     }
 }
예제 #16
0
 /**
  * @param string $fromTable
  * @param string $fromColumn
  * @param string $toTable
  * @param string $toColumn
  * @return boolean
  */
 function updateColumn($fromTable, $fromColumn, $toTable, $toColumn)
 {
     // ERROR: $this not initialised
     $prefix = $this->getPrefix();
     $statement = $this->aSQLStatements['table_update_col'];
     $query = sprintf($statement, $prefix . $toTable, $toColumn, $prefix . $fromTable, $fromColumn);
     $this->_log('select query prepared: ' . $query);
     $result = $this->oDBH->exec($query);
     if (PEAR::isError($result)) {
         $this->_logError('error executing statement: ' . $result->getUserInfo());
         return false;
     }
     $this->affectedRows = $result;
     $this->_log('update complete: ' . $this->affectedRows . ' rows affected');
     return true;
 }
예제 #17
0
 /**
  * Constructor
  */
 function __construct()
 {
     parent::__construct();
     $this->phptype = 'mysql';
     $this->dbsyntax = 'mysql';
     $this->supported['sequences'] = true;
     $this->supported['indexes'] = true;
     $this->supported['affected_rows'] = true;
     $this->supported['transactions'] = false;
     $this->supported['summary_functions'] = true;
     $this->supported['order_by_text'] = true;
     $this->supported['current_id'] = true;
     $this->supported['limit_queries'] = true;
     $this->supported['LOBs'] = true;
     $this->supported['replace'] = true;
     $this->supported['sub_selects'] = false;
     $this->supported['auto_increment'] = true;
     $this->options['default_table_type'] = null;
 }
예제 #18
0
 /**
  * Private method that will use MDB2_Driver_Common::query() for simple and
  * MDB2_Driver_Common::prepare() & MDB2_Statement_Common::execute() for complex
  * query specifications.
  *
  * @param mixed  $sql        A string or an array.
  * @param string $configPath The config path used for exception messages.
  *
  * @return MDB2_Result
  * @throws XML_Query2XML_DBException If a database related error occures.
  */
 private function _prepareAndExecute($sql, $configPath)
 {
     $preparedQuery = $sql['query'];
     if (isset($sql['limit'])) {
         $preparedQuery .= '; LIMIT:' . $sql['limit'];
         $preparedQuery .= '; OFFSET:' . $sql['offset'];
         $this->_db->setLimit($sql['limit'], $sql['offset']);
     }
     if (isset($this->_preparedQueries[$preparedQuery])) {
         $queryHandle = $this->_preparedQueries[$preparedQuery];
     } else {
         // PREPARE
         $queryHandle = $this->_db->prepare($sql['query']);
         if (PEAR::isError($queryHandle)) {
             /*
              * unit tests: (only if mysql or pgsql is used)
              *  MDB2/_prepareAndExecute/throwDBException_complexQuery.phpt
              */
             throw new XML_Query2XML_DBException($configPath . ': Could not prepare the following SQL query: ' . $sql['query'] . '; ' . $queryHandle->toString());
         }
         $this->_preparedQueries[$preparedQuery] =& $queryHandle;
     }
     // EXECUTE
     if (isset($sql['data'])) {
         $result = $queryHandle->execute($sql['data']);
     } else {
         $result = $queryHandle->execute();
     }
     if (PEAR::isError($result)) {
         /*
          * unit tests:
          *  if sqlite is used: MDB2/_prepareAndExecute/
          *   throwDBException_complexQuery.phpt
          *  if sqlite or mysql is sued: MDB2/getXML/
          *   throwDBException_nullResultSet_complexQuery_multipleRecords.phpt
          *   throwDBException_nullResultSet_complexQuery_singleRecord.phpt
          */
         throw new XML_Query2XML_DBException($configPath . ': Could not execute the following SQL query: ' . $sql['query'] . '; ' . $result->toString());
     }
     return $result;
 }
예제 #19
0
 /**
  * Gets the photos this tag applies to
  *
  * @param SwatDBRange $range optional. The database range of photos to
  *                            select.
  *
  * @return PinholePhotoWrapper the set of {@link PinholePhoto} objects that
  *                              this tag applies to.
  *
  * @see PinholeAbstractTag::getPhotoCount()
  */
 public function getPhotos(SwatDBRange $range = null)
 {
     if (!$this->photos_loaded) {
         $sql = 'select * from PinholePhoto';
         $join_clauses = implode(' ', $this->getJoinClauses());
         if ($join_clauses != '') {
             $sql .= ' ' . $join_clauses . ' ';
         }
         $where_clause = $this->getWhereClause();
         if ($where_clause != '') {
             $sql .= ' where ' . $where_clause;
         }
         if ($range !== null) {
             $this->db->setRange($range->getLimit(), $range->getOffset());
         }
         $wrapper = SwatDBClassMap::get('PinholePhotoWrapper');
         $this->photos = SwatDB::query($this->db, $sql, $wrapper);
         $this->photos_loaded = true;
     }
     return $this->photos;
 }
 /**
  * A private method to perform assertions on the contents of the
  * log_maintenance_priority table.
  *
  * @access private
  * @param integer    $id Optional row ID to test on, if not set, tests
  *                       that table is empty.
  * @param PEAR::Date $oBeforeUpdateDate The before date to test the row with.
  * @param PEAR::Date $oAfterUpdateDate The after date to test the row with.
  * @param integer    $oi The operation interval to test the row with.
  * @param integer    $runType The run type value to test the row with.
  * @param string     $updatedTo The updated to date to test the row with, if any.
  */
 function _assertLogMaintenance($id = null, $oBeforeUpdateDate = null, $oAfterUpdateDate = null, $oi = null, $runType = null, $updatedTo = null)
 {
     $aConf = $GLOBALS['_MAX']['CONF'];
     $tableName = $aConf['table']['prefix'] . 'log_maintenance_priority';
     $table = $this->oDbh->quoteIdentifier($tableName, true);
     $query = "\n            SELECT\n                start_run,\n                end_run,\n                operation_interval,\n                run_type,\n                updated_to\n            FROM\n                {$table}";
     if (!is_null($id)) {
         $query .= "\n            WHERE\n                log_maintenance_priority_id = {$id}";
     }
     $rc = $this->oDbh->query($query);
     $aRow = $rc->fetchRow();
     if (is_null($id)) {
         // Check there are no rows returned
         $this->assertNull($aRow);
     } else {
         // Check the returned row's values
         $oStartRunDate = new Date($aRow['start_run']);
         $oEndRunDate = new Date($aRow['end_run']);
         $result = $oBeforeUpdateDate->before($oStartRunDate);
         $this->assertTrue($result);
         $result = $oBeforeUpdateDate->before($oEndRunDate);
         $this->assertTrue($result);
         $result = $oAfterUpdateDate->after($oStartRunDate);
         $this->assertTrue($result);
         $result = $oAfterUpdateDate->after($oEndRunDate);
         $this->assertTrue($result);
         $result = $oStartRunDate->after($oEndRunDate);
         $this->assertFalse($result);
         $this->assertEqual($aRow['operation_interval'], $oi);
         $this->assertEqual($aRow['run_type'], $runType);
         if (!is_null($updatedTo)) {
             $this->assertEqual($aRow['updated_to'], $updatedTo);
         } else {
             $this->assertNull($aRow['updated_to']);
         }
     }
 }
 function execute($aParams)
 {
     $this->oUpgrade =& $aParams[0];
     // Recompile the delivery limitations to update the compiled limitations as well
     $this->oUpgrade->addPostUpgradeTask('Recompile_Acls');
     $this->oDbh =& OA_DB::singleton();
     $aConf = $GLOBALS['_MAX']['CONF']['table'];
     $this->prefix = $aConf['prefix'];
     $this->tblPreferences = $aConf['prefix'] . ($aConf['preferences'] ? $aConf['preferences'] : 'preferences');
     $this->tblAccountPreferenceAssoc = $aConf['prefix'] . ($aConf['account_preference_assoc'] ? $aConf['account_preference_assoc'] : 'account_preference_assoc');
     $query = "SELECT preference_id\n                  FROM " . $this->oDbh->quoteIdentifier($this->tblPreferences, true) . "\n                  WHERE preference_name = 'auto_alter_html_banners_for_click_tracking'";
     $rs = $this->oDbh->query($query);
     //check for error
     if (PEAR::isError($rs)) {
         $this->logError($rs->getUserInfo());
         return false;
     }
     $preferenceId = $rs->fetchRow(MDB2_FETCHMODE_ASSOC);
     $preferenceId = $preferenceId['preference_id'];
     if (!empty($preferenceId)) {
         $sql = "DELETE FROM " . $this->oDbh->quoteIdentifier($this->tblAccountPreferenceAssoc, true) . " WHERE preference_id = {$preferenceId}";
         $rs = $this->oDbh->exec($sql);
         //check for error
         if (PEAR::isError($rs)) {
             $this->logError($rs->getUserInfo());
             return false;
         }
         $this->logOnly("Removed entries in account_preferences_assoc table related to auto_alter_html_banners_for_click_tracking");
         $sql = "DELETE FROM " . $this->oDbh->quoteIdentifier($this->tblPreferences, true) . " WHERE preference_id = {$preferenceId}";
         $rs = $this->oDbh->exec($sql);
         //check for error
         if (PEAR::isError($rs)) {
             $this->logError($rs->getUserInfo());
             return false;
         }
         $this->logOnly("Removed auto_alter_html_banners_for_click_tracking preference in preferences table");
     }
     return true;
 }
예제 #22
0
    /**
     * Efficiently loads tags for a set of posts
     *
     * @param BlorgPostWrapper $posts the posts for which to efficiently load
     *                                 tags.
     */
    protected function loadPostTags(BlorgPostWrapper $posts)
    {
        $instance_id = $this->instance === null ? null : $this->instance->id;
        $wrapper = SwatDBClassMap::get('BlorgTagWrapper');
        // get post ids
        $post_ids = array();
        foreach ($posts as $post) {
            $post_ids[] = $post->id;
        }
        $post_ids = $this->db->implodeArray($post_ids, 'integer');
        // build SQL to select all tags
        $sql = sprintf('select BlorgTag.*, BlorgPostTagBinding.post
			from BlorgTag
				inner join BlorgPostTagBinding on
					BlorgTag.id = BlorgPostTagBinding.tag
			where post in (%s) and BlorgTag.instance %s %s
			order by post, createdate desc', $post_ids, SwatDB::equalityOperator($instance_id), $this->db->quote($instance_id, 'integer'));
        // get all tags
        $tags = SwatDB::query($this->db, $sql, $wrapper);
        // assign empty recordsets for all posts
        foreach ($posts as $post) {
            $recordset = new $wrapper();
            $post->setTags($recordset);
        }
        // assign tags to correct posts
        $current_post_id = null;
        $current_recordset = null;
        foreach ($tags as $tag) {
            $post_id = $tag->getInternalValue('post');
            if ($post_id !== $current_post_id) {
                $current_post_id = $post_id;
                $current_recordset = $posts[$post_id]->getTags();
            }
            $current_recordset->add($tag);
        }
    }
예제 #23
0
 /**
  * Create a new MDB2 connection object and connect to the specified
  * database
  *
  * IMPORTANT: In order for MDB2 to work properly it is necessary that
  * you make sure that you work with a reference of the original
  * object instead of a copy (this is a PHP4 quirk).
  *
  * For example:
  *     $mdb =& MDB2::connect($dsn);
  *          ^^
  * And not:
  *     $mdb = MDB2::connect($dsn);
  *          ^^
  *
  * @param   mixed   $dsn      'data source name', see the MDB2::parseDSN
  *                            method for a description of the dsn format.
  *                            Can also be specified as an array of the
  *                            format returned by MDB2::parseDSN.
  * @param   array   $options  An associative array of option names and
  *                            their values.
  * @return  mixed   a newly created MDB2 connection object, or a MDB2
  *                  error object on error
  * @access  public
  * @see     MDB2::parseDSN
  */
 function &connect($dsn, $options = false)
 {
     $dsninfo = MDB2::parseDSN($dsn);
     if (!isset($dsninfo['phptype'])) {
         $error =& MDB2_Driver_Common::raiseError(MDB2_ERROR_NOT_FOUND, null, null, 'no RDBMS driver specified');
         return $error;
     }
     $type = $dsninfo['phptype'];
     if (is_array($options) && isset($options['debug']) && $options['debug'] >= 2) {
         $debug = true;
     } else {
         $debug = false;
     }
     $db =& MDB2::factory($type, $debug);
     if (MDB2::isError($db)) {
         return $db;
     }
     $db->setDSN($dsninfo);
     $err = MDB2::setOptions($db, $options);
     if (MDB2::isError($err)) {
         $db->disconnect();
         return $err;
     }
     if (isset($dsninfo['database'])) {
         $err = $db->connect();
         if (MDB2::isError($err)) {
             $dsn = $db->getDSN();
             $err->addUserInfo($dsn);
             return $err;
         }
     }
     return $db;
 }
예제 #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;
 }
예제 #25
0
 /**
  * Returns a native connection
  *
  * @return  mixed   a valid MDB2 connection object,
  *                  or a MDB2 error object on error
  * @access  public
  */
 function getConnection()
 {
     $connection = parent::getConnection();
     if (PEAR::isError($connection)) {
         return $connection;
     }
     $fix_assoc_fields_names = $this->options['portability'] & MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES;
     if ($fix_assoc_fields_names !== $this->fix_assoc_fields_names) {
         @sqlite_query("PRAGMA short_column_names = {$fix_assoc_fields_names};", $connection);
         $this->fix_assoc_fields_names = $fix_assoc_fields_names;
     }
     return $connection;
 }
예제 #26
0
파일: sqlsrv.php 프로젝트: Dulciane/jaws
 /**
  * Log out and disconnect from the database.
  *
  * @param  boolean $force if the disconnect should be forced even if the
  *                        connection is opened persistently
  * @return mixed true on success, false if not connected and error
  *                object on error
  * @access public
  */
 function disconnect($force = true)
 {
     if (is_resource($this->connection)) {
         if ($this->in_transaction) {
             $dsn = $this->dsn;
             $database_name = $this->database_name;
             $persistent = $this->options['persistent'];
             $this->dsn = $this->connected_dsn;
             $this->database_name = $this->connected_database_name;
             $this->options['persistent'] = $this->opened_persistent;
             $this->rollback();
             $this->dsn = $dsn;
             $this->database_name = $database_name;
             $this->options['persistent'] = $persistent;
         }
         @sqlsrv_close($this->connection);
     }
     return parent::disconnect($force);
 }
예제 #27
0
파일: Base.php 프로젝트: gauthierm/MDB2
 /**
  * Drop a FUNCTION
  */
 public function dropFunction($name)
 {
     return $this->db->exec('DROP FUNCTION ' . $name);
 }
예제 #28
0
 /**
  * Prepares a query for multiple execution with execute().
  * With some database backends, this is emulated.
  * prepare() requires a generic query as string like
  * 'INSERT INTO numbers VALUES(?,?)' or
  * 'INSERT INTO numbers VALUES(:foo,:bar)'.
  * The ? and :[a-zA-Z] and  are placeholders which can be set using
  * bindParam() and the query can be send off using the execute() method.
  *
  * @param string $query the query to prepare
  * @param mixed   $types  array that contains the types of the placeholders
  * @param mixed   $result_types  array that contains the types of the columns in
  *                        the result set or MDB2_PREPARE_RESULT, if set to
  *                        MDB2_PREPARE_MANIP the query is handled as a manipulation query
  * @param mixed   $lobs   key (field) value (parameter) pair for all lob placeholders
  * @return mixed resource handle for the prepared query on success, a MDB2
  *        error on failure
  * @access public
  * @see bindParam, execute
  */
 function &prepare($query, $types = null, $result_types = null, $lobs = array())
 {
     if ($this->options['emulate_prepared'] || $this->supported['prepared_statements'] !== true) {
         $obj =& parent::prepare($query, $types, $result_types, $lobs);
         return $obj;
     }
     $is_manip = $result_types === MDB2_PREPARE_MANIP;
     $offset = $this->offset;
     $limit = $this->limit;
     $this->offset = $this->limit = 0;
     $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
     $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
     if ($result) {
         if (PEAR::isError($result)) {
             return $result;
         }
         $query = $result;
     }
     $placeholder_type_guess = $placeholder_type = null;
     $question = '?';
     $colon = ':';
     $positions = array();
     $position = 0;
     while ($position < strlen($query)) {
         $q_position = strpos($query, $question, $position);
         $c_position = strpos($query, $colon, $position);
         if ($q_position && $c_position) {
             $p_position = min($q_position, $c_position);
         } elseif ($q_position) {
             $p_position = $q_position;
         } elseif ($c_position) {
             $p_position = $c_position;
         } else {
             break;
         }
         if (is_null($placeholder_type)) {
             $placeholder_type_guess = $query[$p_position];
         }
         $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
         if (PEAR::isError($new_pos)) {
             return $new_pos;
         }
         if ($new_pos != $position) {
             $position = $new_pos;
             continue;
             //evaluate again starting from the new position
         }
         if ($query[$position] == $placeholder_type_guess) {
             if (is_null($placeholder_type)) {
                 $placeholder_type = $query[$p_position];
                 $question = $colon = $placeholder_type;
             }
             if ($placeholder_type == ':') {
                 //make sure this is not part of an user defined variable
                 $new_pos = $this->_skipUserDefinedVariable($query, $position);
                 if ($new_pos != $position) {
                     $position = $new_pos;
                     continue;
                     //evaluate again starting from the new position
                 }
                 $parameter = preg_replace('/^.{' . ($position + 1) . '}([a-z0-9_]+).*$/si', '\\1', $query);
                 if ($parameter === '') {
                     $err =& $this->raiseError(MDB2_ERROR_SYNTAX, null, null, 'named parameter with an empty name', __FUNCTION__);
                     return $err;
                 }
                 $positions[$p_position] = $parameter;
                 $query = substr_replace($query, '?', $position, strlen($parameter) + 1);
             } else {
                 $positions[$p_position] = count($positions);
             }
             $position = $p_position + 1;
         } else {
             $position = $p_position;
         }
     }
     $connection = $this->getConnection();
     if (PEAR::isError($connection)) {
         return $connection;
     }
     $statement_name = sprintf($this->options['statement_format'], $this->phptype, md5(time() + rand()));
     $query = "PREPARE {$statement_name} FROM " . $this->quote($query, 'text');
     $statement =& $this->_doQuery($query, true, $connection);
     if (PEAR::isError($statement)) {
         return $statement;
     }
     $class_name = 'MDB2_Statement_' . $this->phptype;
     $obj =& new $class_name($this, $statement_name, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
     $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
     return $obj;
 }
 /**
  * Tests that the MDB2::escape() method correctly escapes strings.
  */
 function test_escape()
 {
     $tmp = $this->db->string_quoting;
     $this->string_quoting['escape'] = '\\';
     $this->string_quoting['end'] = '"';
     $text = 'xxx"z"xxx';
     $this->assertEquals('xxx\\"z\\"xxx', MDB2_Driver_Common::escape($text), 'escape');
     $this->db->string_quoting = $tmp;
 }
예제 #30
0
 /**
  * Gets the available document type shortnames
  *
  * @param MDB2_Driver_Common $db the database driver to use to get the
  *                                available document type shortnames.
  *
  * @return array an array containing the available document type shortnames.
  *
  * @throws NateGoSearchDBException if a database error occurs.
  */
 public static function getDocumentTypes(MDB2_Driver_Common $db)
 {
     $sql = 'select shortname from NateGoSearchType';
     $values = $db->queryCol($sql, 'text');
     if (MDB2::isError($values)) {
         throw new NateGoSearchDBException($values);
     }
     return $values;
 }