/**
  * @return DatabaseBase
  */
 function getMasterDB()
 {
     if (!isset($this->dbConn)) {
         $this->dbConn = DatabaseBase::factory($this->dbType, array('host' => $this->dbServer, 'user' => $this->dbUser, 'password' => $this->dbPassword, 'dbname' => $this->dbName, 'flags' => $this->dbFlags, 'tablePrefix' => $this->tablePrefix));
     }
     return $this->dbConn;
 }
示例#2
0
 /**
  * Get the Query database connection (read-only)
  * @return DatabaseBase
  */
 protected function getDB()
 {
     if (is_null($this->mDb)) {
         global $wgMetricsDBserver, $wgMetricsDBname, $wgMetricsDBuser, $wgMetricsDBpassword, $wgMetricsDBtype, $wgMetricsDBprefix, $wgDebugDumpSql;
         $this->mDb = DatabaseBase::factory($wgMetricsDBtype, array('host' => $wgMetricsDBserver, 'user' => $wgMetricsDBuser, 'password' => $wgMetricsDBpassword, 'dbname' => $wgMetricsDBname, 'tablePrefix' => $wgMetricsDBprefix, 'flags' => ($wgDebugDumpSql ? DBO_DEBUG : 0) | DBO_DEFAULT));
         //$this->mDb->query( "SET names utf8" );
     }
     return $this->mDb;
 }
 /**
  * @return DatabaseBase
  */
 protected function getDB()
 {
     if (is_null($this->db)) {
         global $wgMetricsDBserver, $wgMetricsDBname, $wgMetricsDBuser, $wgMetricsDBpassword, $wgMetricsDBtype, $wgMetricsDBprefix;
         $this->db = DatabaseBase::factory($wgMetricsDBtype, array('host' => $wgMetricsDBserver, 'user' => $wgMetricsDBuser, 'password' => $wgMetricsDBpassword, 'dbname' => $wgMetricsDBname, 'tablePrefix' => $wgMetricsDBprefix));
         //$this->db->query( "SET names utf8" );
     }
     return $this->db;
 }
示例#4
0
 function __construct()
 {
     $this->dbr = wfGetDB(DB_SLAVE);
     $this->dbw = DatabaseBase::factory('mysql');
     $this->dbw->open(WH_DATABASE_BACKUP, WH_DATABASE_MAINTENANCE_USER, WH_DATABASE_MAINTENANCE_PASSWORD, self::STU_DATABASE);
     $this->pagesProcessed = 0;
     $this->errors = false;
     $this->warnings = false;
     $this->dryRun = false;
 }
示例#5
0
 private function getDBR()
 {
     global $wgDBname;
     if (strpos(@$_SERVER['HOSTNAME'], 'wikidiy.com') !== false) {
         define(WAP_DB_HOST, WH_DATABASE_MASTER);
     } else {
         define(WAP_DB_HOST, WH_DATABASE_BACKUP);
     }
     $db = DatabaseBase::factory('mysql');
     $db->open(WAP_DB_HOST, WH_DATABASE_MAINTENANCE_USER, WH_DATABASE_MAINTENANCE_PASSWORD, $wgDBname);
     return $db;
 }
 function updateRemote()
 {
     global $wgUser, $wgVanillaDB;
     try {
         $db = DatabaseBase::factory('mysql');
         $db->open($wgVanillaDB['host'], $wgVanillaDB['user'], $wgVanillaDB['password'], $wgVanillaDB['dbname']);
         $oldignore = $db->ignoreErrors(true);
         // get vanilla user id
         $vid = $db->selectField('GDN_UserAuthentication', array('UserID'), array('ForeignUserKey' => $wgUser->getID()));
         if (!$vid) {
             return true;
         }
         $photo = Avatar::getAvatarURL($wgUser->getName());
         $updates = array("Photo" => $photo, "Email" => $wgUser->getEmail());
         if (in_array('bureaucrat', $wgUser->getGroups())) {
             $updates["Admin"] = 1;
         } else {
             $updates["Admin"] = 0;
         }
         $opts = array('UserID' => $vid);
         $db->update('GDN_User', $updates, $opts);
         if (self::isUserBlocked()) {
             $db->update('GDN_UserRole', array('RoleID = 1'), $opts);
         } else {
             if (in_array('bureaucrat', $wgUser->getGroups())) {
                 $db->update('GDN_UserRole', array('RoleID = 16'), $opts);
             } else {
                 if (in_array('sysop', $wgUser->getGroups())) {
                     $db->update("GDN_User", array('Permissions' => 'a:14:{i:0;s:19:"Garden.SignIn.Allow";i:1;s:22:"Garden.Activity.Delete";i:2;s:25:"Vanilla.Categories.Manage";i:3;s:19:"Vanilla.Spam.Manage";s:24:"Vanilla.Discussions.View";a:6:{i:0;s:1:"1";i:1;s:1:"4";i:2;s:1:"5";i:3;s:1:"7";i:4;s:1:"8";i:5;s:1:"9";}s:23:"Vanilla.Discussions.Add";a:6:{i:0;s:1:"1";i:1;s:1:"4";i:2;s:1:"5";i:3;s:1:"7";i:4;s:1:"8";i:5;s:1:"9";}s:24:"Vanilla.Discussions.Edit";a:6:{i:0;s:1:"1";i:1;s:1:"4";i:2;s:1:"5";i:3;s:1:"7";i:4;s:1:"8";i:5;s:1:"9";}s:28:"Vanilla.Discussions.Announce";a:6:{i:0;s:1:"1";i:1;s:1:"4";i:2;s:1:"5";i:3;s:1:"7";i:4;s:1:"8";i:5;s:1:"9";}s:24:"Vanilla.Discussions.Sink";a:6:{i:0;s:1:"1";i:1;s:1:"4";i:2;s:1:"5";i:3;s:1:"7";i:4;s:1:"8";i:5;s:1:"9";}s:25:"Vanilla.Discussions.Close";a:6:{i:0;s:1:"1";i:1;s:1:"4";i:2;s:1:"5";i:3;s:1:"7";i:4;s:1:"8";i:5;s:1:"9";}s:26:"Vanilla.Discussions.Delete";a:6:{i:0;s:1:"1";i:1;s:1:"4";i:2;s:1:"5";i:3;s:1:"7";i:4;s:1:"8";i:5;s:1:"9";}s:20:"Vanilla.Comments.Add";a:6:{i:0;s:1:"1";i:1;s:1:"4";i:2;s:1:"5";i:3;s:1:"7";i:4;s:1:"8";i:5;s:1:"9";}s:21:"Vanilla.Comments.Edit";a:6:{i:0;s:1:"1";i:1;s:1:"4";i:2;s:1:"5";i:3;s:1:"7";i:4;s:1:"8";i:5;s:1:"9";}s:23:"Vanilla.Comments.Delete";a:6:{i:0;s:1:"1";i:1;s:1:"4";i:2;s:1:"5";i:3;s:1:"7";i:4;s:1:"8";i:5;s:1:"9";}}'), $opts);
                     $db->update('GDN_UserRole', array('RoleID = 32'), $opts);
                 } else {
                     $db->update("GDN_User", array('Permissions' => 'a:4:{i:0;s:19:"Garden.SignIn.Allow";s:24:"Vanilla.Discussions.View";a:6:{i:0;s:1:"1";i:1;s:1:"4";i:2;s:1:"5";i:3;s:1:"7";i:4;s:1:"8";i:5;s:1:"9";}s:23:"Vanilla.Discussions.Add";a:6:{i:0;s:1:"1";i:1;s:1:"4";i:2;s:1:"5";i:3;s:1:"7";i:4;s:1:"8";i:5;s:1:"9";}s:20:"Vanilla.Comments.Add";a:6:{i:0;s:1:"1";i:1;s:1:"4";i:2;s:1:"5";i:3;s:1:"7";i:4;s:1:"8";i:5;s:1:"9";}}'), $opts);
                     $db->update('GDN_UserRole', array('RoleID = 8'), $opts);
                     print $db->lastQuery();
                 }
             }
         }
         $db->ignoreErrors($oldignore);
     } catch (Exception $e) {
         print "oops {$e->getMessage()}\n";
     }
     return true;
 }
示例#7
0
 public static function setAvatar($user)
 {
     global $wgVanillaDB;
     $fname = "Vanilla::setAvatar";
     wfProfileIn($fname);
     $db = DatabaseBase::factory('mysql');
     $db->open($wgVanillaDB['host'], $wgVanillaDB['user'], $wgVanillaDB['password'], $wgVanillaDB['dbname']);
     // get vanilla user id
     $vid = $db->selectField('GDN_UserAuthentication', array('UserID'), array('ForeignUserKey' => $user->getID()));
     if (!$vid) {
         return false;
     }
     $updates = array("Photo" => Avatar::getAvatarURL($user->getName()));
     $opts = array('UserID' => $vid);
     $db->update('GDN_User', $updates, $opts);
     wfDebug("Vanilla: Updating avatar " . print_r($updates, true) . print_r($opts, true) . "\n");
     wfProfileOut($fname);
     return true;
 }
示例#8
0
 /**
  * Get a connection to the specified database
  *
  * @param int $serverIndex
  * @return DatabaseBase
  * @throws MWException
  */
 protected function getDB($serverIndex)
 {
     global $wgDebugDBTransactions;
     if (!isset($this->conns[$serverIndex])) {
         if ($serverIndex >= $this->numServers) {
             throw new MWException(__METHOD__ . ": Invalid server index \"{$serverIndex}\"");
         }
         # Don't keep timing out trying to connect for each call if the DB is down
         if (isset($this->connFailureErrors[$serverIndex]) && time() - $this->connFailureTimes[$serverIndex] < 60) {
             throw $this->connFailureErrors[$serverIndex];
         }
         # If server connection info was given, use that
         if ($this->serverInfos) {
             if ($wgDebugDBTransactions) {
                 $this->logger->debug("Using provided serverInfo for SqlBagOStuff");
             }
             $info = $this->serverInfos[$serverIndex];
             $type = isset($info['type']) ? $info['type'] : 'mysql';
             $host = isset($info['host']) ? $info['host'] : '[unknown]';
             $this->logger->debug(__CLASS__ . ": connecting to {$host}");
             // Use a blank trx profiler to ignore expections as this is a cache
             $info['trxProfiler'] = new TransactionProfiler();
             $db = DatabaseBase::factory($type, $info);
             $db->clearFlag(DBO_TRX);
         } else {
             /*
              * We must keep a separate connection to MySQL in order to avoid deadlocks
              * However, SQLite has an opposite behavior. And PostgreSQL needs to know
              * if we are in transaction or no
              */
             $index = $this->slaveOnly ? DB_SLAVE : DB_MASTER;
             if (wfGetDB($index)->getType() == 'mysql') {
                 $this->lb = wfGetLBFactory()->newMainLB();
                 $db = $this->lb->getConnection($index);
                 $db->clearFlag(DBO_TRX);
                 // auto-commit mode
             } else {
                 $db = wfGetDB($index);
             }
         }
         if ($wgDebugDBTransactions) {
             $this->logger->debug(sprintf("Connection %s will be used for SqlBagOStuff", $db));
         }
         $this->conns[$serverIndex] = $db;
     }
     return $this->conns[$serverIndex];
 }
示例#9
0
 /**
  * Open a PG connection with given parameters
  * @param string $user User name
  * @param string $password Password
  * @param string $dbName Database name
  * @param string $schema Database schema
  * @return Status
  */
 protected function openConnectionWithParams($user, $password, $dbName, $schema)
 {
     $status = Status::newGood();
     try {
         $db = DatabaseBase::factory('postgres', array('host' => $this->getVar('wgDBserver'), 'user' => $user, 'password' => $password, 'dbname' => $dbName, 'schema' => $schema));
         $status->value = $db;
     } catch (DBConnectionError $e) {
         $status->fatal('config-connection-error', $e->getMessage());
     }
     return $status;
 }
示例#10
0
    /**
     * @return Status
     */
    public function setupDatabase()
    {
        $dir = $this->getVar('wgSQLiteDataDir');
        # Sanity check. We checked this before but maybe someone deleted the
        # data dir between then and now
        $dir_status = self::dataDirOKmaybeCreate($dir, false);
        if (!$dir_status->isOK()) {
            return $dir_status;
        }
        $db = $this->getVar('wgDBname');
        # Make the main and cache stub DB files
        $status = Status::newGood();
        $status->merge($this->makeStubDBFile($dir, $db));
        $status->merge($this->makeStubDBFile($dir, "wikicache"));
        if (!$status->isOK()) {
            return $status;
        }
        # Nuke the unused settings for clarity
        $this->setVar('wgDBserver', '');
        $this->setVar('wgDBuser', '');
        $this->setVar('wgDBpassword', '');
        $this->setupSchemaVars();
        # Create the global cache DB
        try {
            global $wgSQLiteDataDir;
            # @todo FIXME: setting globals kind of sucks
            $wgSQLiteDataDir = $dir;
            $conn = DatabaseBase::factory('sqlite', array('dbname' => "wikicache"));
            # @todo: don't duplicate objectcache definition, though it's very simple
            $sql = <<<EOT
\tCREATE TABLE IF NOT EXISTS objectcache (
\t  keyname BLOB NOT NULL default '' PRIMARY KEY,
\t  value BLOB,
\t  exptime TEXT
\t)
EOT;
            $conn->query($sql);
            $conn->query("CREATE INDEX IF NOT EXISTS exptime ON objectcache (exptime)");
            $conn->query("PRAGMA journal_mode=WAL");
            // this is permanent
            $conn->close();
        } catch (DBConnectionError $e) {
            return Status::newFatal('config-sqlite-connection-error', $e->getMessage());
        }
        # Open the main DB
        return $this->getConnection();
    }
示例#11
0
 /**
  * Really opens a connection. Uncached.
  * Returns a Database object whether or not the connection was successful.
  * @access private
  *
  * @param array $server
  * @param bool $dbNameOverride
  * @throws MWException
  * @return DatabaseBase
  */
 protected function reallyOpenConnection($server, $dbNameOverride = false)
 {
     if (!is_array($server)) {
         throw new MWException('You must update your load-balancing configuration. ' . 'See DefaultSettings.php entry for $wgDBservers.');
     }
     if ($dbNameOverride !== false) {
         $server['dbname'] = $dbNameOverride;
     }
     // Log when many connection are made on requests
     if (++$this->connsOpened >= self::CONN_HELD_WARN_THRESHOLD) {
         $masterAddr = $this->getServerName(0);
         wfDebugLog('DBPerformance', __METHOD__ . ": " . "{$this->connsOpened}+ connections made (master={$masterAddr})\n" . wfBacktrace(true));
     }
     # Create object
     try {
         $db = DatabaseBase::factory($server['type'], $server);
     } catch (DBConnectionError $e) {
         // FIXME: This is probably the ugliest thing I have ever done to
         // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
         $db = $e->db;
     }
     $db->setLBInfo($server);
     if (isset($server['fakeSlaveLag'])) {
         $db->setFakeSlaveLag($server['fakeSlaveLag']);
     }
     if (isset($server['fakeMaster'])) {
         $db->setFakeMaster(true);
     }
     return $db;
 }
示例#12
0
 /**
  * Get (or reuse) a connection to a lock DB
  *
  * @param string $lockDb
  * @return IDatabase
  * @throws DBError
  */
 protected function getConnection($lockDb)
 {
     if (!isset($this->conns[$lockDb])) {
         $db = null;
         if ($lockDb === 'localDBMaster') {
             $lb = wfGetLBFactory()->getMainLB($this->domain);
             $db = $lb->getConnection(DB_MASTER, array(), $this->domain);
         } elseif (isset($this->dbServers[$lockDb])) {
             $config = $this->dbServers[$lockDb];
             $db = DatabaseBase::factory($config['type'], $config);
         }
         if (!$db) {
             return null;
             // config error?
         }
         $this->conns[$lockDb] = $db;
         $this->conns[$lockDb]->clearFlag(DBO_TRX);
         # If the connection drops, try to avoid letting the DB rollback
         # and release the locks before the file operations are finished.
         # This won't handle the case of DB server restarts however.
         $options = array();
         if ($this->lockExpiry > 0) {
             $options['connTimeout'] = $this->lockExpiry;
         }
         $this->conns[$lockDb]->setSessionOptions($options);
         $this->initConnection($lockDb, $this->conns[$lockDb]);
     }
     if (!$this->conns[$lockDb]->trxLevel()) {
         $this->conns[$lockDb]->begin(__METHOD__);
         // start transaction
     }
     return $this->conns[$lockDb];
 }
 public function openConnectionToAnyDB($user, $password)
 {
     $dbs = array('template1', 'postgres');
     if (!in_array($this->getVar('wgDBname'), $dbs)) {
         array_unshift($dbs, $this->getVar('wgDBname'));
     }
     $conn = false;
     $status = Status::newGood();
     foreach ($dbs as $db) {
         try {
             $p = array('host' => $this->getVar('wgDBserver'), 'user' => $user, 'password' => $password, 'dbname' => $db);
             $conn = DatabaseBase::factory('postgres', $p);
         } catch (DBConnectionError $error) {
             $conn = false;
             $status->fatal('config-pg-test-error', $db, $error->getMessage());
         }
         if ($conn !== false) {
             break;
         }
     }
     if ($conn !== false) {
         return Status::newGood($conn);
     } else {
         return $status;
     }
 }
示例#14
0
 /**
  * @param string $filename
  * @param array $p Options map; supports:
  *   - flags       : (same as __construct counterpart)
  *   - trxMode     : (same as __construct counterpart)
  *   - dbDirectory : (same as __construct counterpart)
  * @return DatabaseSqlite
  * @since 1.25
  */
 public static function newStandaloneInstance($filename, array $p = array())
 {
     $p['dbFilePath'] = $filename;
     $p['schema'] = false;
     $p['tablePrefix'] = '';
     return DatabaseBase::factory('sqlite', $p);
 }
示例#15
0
 /**
  * Really opens a connection. Uncached.
  * Returns a Database object whether or not the connection was successful.
  * @access private
  *
  * @return DatabaseBase
  */
 function reallyOpenConnection($server, $dbNameOverride = false)
 {
     if (!is_array($server)) {
         throw new MWException('You must update your load-balancing configuration. ' . 'See DefaultSettings.php entry for $wgDBservers.');
     }
     $host = $server['host'];
     $dbname = $server['dbname'];
     if ($dbNameOverride !== false) {
         $server['dbname'] = $dbname = $dbNameOverride;
     }
     # Create object
     wfDebug("Connecting to {$host} {$dbname}...\n");
     try {
         $db = DatabaseBase::factory($server['type'], $server);
     } catch (DBConnectionError $e) {
         // FIXME: This is probably the ugliest thing I have ever done to
         // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
         $db = $e->db;
     }
     if ($db->isOpen()) {
         wfDebug("Connected to {$host} {$dbname}.\n");
     } else {
         wfDebug("Connection failed to {$host} {$dbname}.\n");
     }
     $db->setLBInfo($server);
     if (isset($server['fakeSlaveLag'])) {
         $db->setFakeSlaveLag($server['fakeSlaveLag']);
     }
     if (isset($server['fakeMaster'])) {
         $db->setFakeMaster(true);
     }
     return $db;
 }
示例#16
0
 /**
  * Really opens a connection. Uncached.
  * Returns a Database object whether or not the connection was successful.
  * @access private
  *
  * @param $server
  * @param $dbNameOverride bool
  * @return DatabaseBase
  */
 function reallyOpenConnection($server, $dbNameOverride = false)
 {
     if (!is_array($server)) {
         throw new MWException('You must update your load-balancing configuration. ' . 'See DefaultSettings.php entry for $wgDBservers.');
     }
     $host = $server['host'];
     $dbname = $server['dbname'];
     if ($dbNameOverride !== false) {
         $server['dbname'] = $dbname = $dbNameOverride;
     }
     # Create object
     wfDebug("Connecting to {$host} {$dbname}...\n");
     try {
         $db = DatabaseBase::factory($server['type'], $server);
     } catch (DBConnectionError $e) {
         // FIXME: This is probably the ugliest thing I have ever done to
         // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
         $db = $e->db;
     }
     $db->setLBInfo($server);
     if (isset($server['fakeSlaveLag'])) {
         $db->setFakeSlaveLag($server['fakeSlaveLag']);
     }
     if (isset($server['fakeMaster'])) {
         $db->setFakeMaster(true);
     }
     // Wikia change - begin
     if ($db->getSampler()->shouldSample()) {
         $db->getWikiaLogger()->info("LoadBalancer::reallyOpenConnection", ['caller' => wfGetCallerClassMethod(__CLASS__), 'host' => $server['hostName'], 'dbname' => $dbname]);
     }
     // Wikia change - end
     return $db;
 }
示例#17
0
 /**
  * @return Closure
  */
 protected function getDBFactory()
 {
     return function ($index) {
         return DatabaseBase::factory($this->dbType, array('host' => $this->dbServer, 'user' => $this->dbUser, 'password' => $this->dbPassword, 'dbname' => $this->dbName, 'flags' => $this->dbFlags, 'tablePrefix' => $this->tablePrefix, 'foreign' => true));
     };
 }
示例#18
0
 public function execute()
 {
     if ($this->getVar('_ExistingDBSettings')) {
         return 'skip';
     }
     $r = $this->parent->request;
     if ($r->wasPosted()) {
         $status = $this->submit();
         if ($status->isGood()) {
             $this->setVar('_UpgradeDone', false);
             return 'continue';
         } else {
             $this->parent->showStatusBox($status);
         }
     }
     $this->startForm();
     $types = "<ul class=\"config-settings-block\">\n";
     $settings = '';
     $defaultType = $this->getVar('wgDBtype');
     $dbSupport = '';
     foreach ($this->parent->getDBTypes() as $type) {
         $link = DatabaseBase::factory($type)->getSoftwareLink();
         $dbSupport .= wfMsgNoTrans("config-support-{$type}", $link) . "\n";
     }
     $this->addHTML($this->parent->getInfoBox(wfMsg('config-support-info', $dbSupport)));
     foreach ($this->parent->getVar('_CompiledDBs') as $type) {
         $installer = $this->parent->getDBInstaller($type);
         $types .= '<li>' . Xml::radioLabel($installer->getReadableName(), 'DBType', $type, "DBType_{$type}", $type == $defaultType, array('class' => 'dbRadio', 'rel' => "DB_wrapper_{$type}")) . "</li>\n";
         $settings .= Html::openElement('div', array('id' => 'DB_wrapper_' . $type, 'class' => 'dbWrapper')) . Html::element('h3', array(), wfMsg('config-header-' . $type)) . $installer->getConnectForm() . "</div>\n";
     }
     $types .= "</ul><br clear=\"left\"/>\n";
     $this->addHTML($this->parent->label('config-db-type', false, $types) . $settings);
     $this->endForm();
 }
示例#19
0
 static function getDBData($dbID, $from, $columns, $where, $options)
 {
     global $edgDBServerType;
     global $edgDBServer;
     global $edgDBName;
     global $edgDBUser;
     global $edgDBPass;
     global $edgDBFlags;
     global $edgDBTablePrefix;
     // Mandatory parameters
     if (!array_key_exists($dbID, $edgDBServerType) || !array_key_exists($dbID, $edgDBServer) || !array_key_exists($dbID, $edgDBName) || !array_key_exists($dbID, $edgDBUser) || !array_key_exists($dbID, $edgDBPass)) {
         echo wfMsgExt("externaldata-db-incomplete-information", array('parse', 'escape'));
         return;
     }
     $db_type = $edgDBServerType[$dbID];
     $db_server = $edgDBServer[$dbID];
     $db_name = $edgDBName[$dbID];
     $db_username = $edgDBUser[$dbID];
     $db_password = $edgDBPass[$dbID];
     // Optional parameters
     if (array_key_exists($dbID, $edgDBFlags)) {
         $db_flags = $edgDBFlags[$dbID];
     } else {
         $db_flags = DBO_DEFAULT;
     }
     if (array_key_exists($dbID, $edgDBTablePrefix)) {
         $db_tableprefix = $edgDBTablePrefix[$dbID];
     } else {
         $db_tableprefix = '';
     }
     // DatabaseBase::newFromType() was added in MW 1.17 - it was
     // then replaced by DatabaseBase::factory() in MW 1.18
     $factorFunction = array('DatabaseBase', 'factory');
     $newFromTypeFunction = array('DatabaseBase', 'newFromType');
     if (is_callable($factorFunction)) {
         $db = DatabaseBase::factory($db_type, array('host' => $db_server, 'user' => $db_username, 'password' => $db_password, 'dbname' => $db_name, 'dbName' => $db_name, 'flags' => $db_flags, 'tablePrefix' => $db_tableprefix));
     } elseif (is_callable($newFromTypeFunction)) {
         $db = DatabaseBase::newFromType($db_type, array('host' => $db_server, 'user' => $db_username, 'password' => $db_password, 'dbname' => $db_name, 'flags' => $db_flags, 'tableprefix' => $db_tableprefix));
     } else {
         if ($db_flags !== DBO_DEFAULT || $db_tableprefix !== '') {
             print wfMsg("externaldata-db-option-unsupported", '<code>$edgDBFlags</code>', '<code>$edgDBTablePrefix</code>');
             return;
         }
         if ($db_type == "mysql") {
             $db = new Database($db_server, $db_username, $db_password, $db_name);
         } elseif ($db_type == "postgres") {
             $db = new DatabasePostgres($db_server, $db_username, $db_password, $db_name);
         } elseif ($db_type == "mssql") {
             $db = new DatabaseMssql($db_server, $db_username, $db_password, $db_name);
         } elseif ($db_type == "oracle") {
             $db = new DatabaseOracle($db_server, $db_username, $db_password, $db_name);
         } else {
             $db = null;
         }
     }
     if ($db == null) {
         echo wfMsgExt("externaldata-db-unknown-type", array('parse', 'escape'));
         return;
     }
     if (!$db->isOpen()) {
         echo wfMsgExt("externaldata-db-could-not-connect", array('parse', 'escape'));
         return;
     }
     if (count($columns) == 0) {
         echo wfMsgExt("externaldata-db-no-return-values", array('parse', 'escape'));
         return;
     }
     $rows = self::searchDB($db, $from, $columns, $where, $options);
     $db->close();
     $values = array();
     foreach ($rows as $row) {
         foreach ($columns as $column) {
             $values[$column][] = $row[$column];
         }
     }
     return $values;
 }
示例#20
0
 public static function newInstance(array $p = array())
 {
     $p['dbFilePath'] = ':memory:';
     $p['schema'] = false;
     return DatabaseBase::factory('SqliteMock', $p);
 }
示例#21
0
 /**
  * @return Closure
  */
 protected function getDBFactory()
 {
     $type = $this->dbType;
     $params = ['host' => $this->dbServer, 'user' => $this->dbUser, 'password' => $this->dbPassword, 'dbname' => $this->dbName, 'flags' => $this->dbFlags, 'tablePrefix' => $this->tablePrefix, 'foreign' => true];
     return function ($index) use($type, $params) {
         return DatabaseBase::factory($type, $params);
     };
 }
示例#22
0
 private function getDb()
 {
     global $wgExternalAuthConf;
     return DatabaseBase::factory('mysql', array('host' => $wgExternalAuthConf['server'], 'user' => $wgExternalAuthConf['username'], 'password' => $wgExternalAuthConf['password'], 'dbname' => $wgExternalAuthConf['dbname'], 'tablePrefix' => $wgExternalAuthConf['tablePrefix']));
 }
示例#23
0
 /**
  * Really opens a connection. Uncached.
  * Returns a Database object whether or not the connection was successful.
  * @access private
  *
  * @param array $server
  * @param bool $dbNameOverride
  * @throws MWException
  * @return DatabaseBase
  */
 protected function reallyOpenConnection($server, $dbNameOverride = false)
 {
     if (!is_array($server)) {
         throw new MWException('You must update your load-balancing configuration. ' . 'See DefaultSettings.php entry for $wgDBservers.');
     }
     if ($dbNameOverride !== false) {
         $server['dbname'] = $dbNameOverride;
     }
     // Let the handle know what the cluster master is (e.g. "db1052")
     $masterName = $this->getServerName(0);
     $server['clusterMasterHost'] = $masterName;
     // Log when many connection are made on requests
     if (++$this->connsOpened >= self::CONN_HELD_WARN_THRESHOLD) {
         wfDebugLog('DBPerformance', __METHOD__ . ": " . "{$this->connsOpened}+ connections made (master={$masterName})\n" . wfBacktrace(true));
     }
     # Create object
     try {
         $db = DatabaseBase::factory($server['type'], $server);
     } catch (DBConnectionError $e) {
         // FIXME: This is probably the ugliest thing I have ever done to
         // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
         $db = $e->db;
     }
     $db->setLBInfo($server);
     $db->setLazyMasterHandle($this->getLazyConnectionRef(DB_MASTER, array(), $db->getWikiID()));
     $db->setTransactionProfiler($this->trxProfiler);
     return $db;
 }
示例#24
0
 public function execute()
 {
     if ($this->getVar('_ExistingDBSettings')) {
         return 'skip';
     }
     $r = $this->parent->request;
     if ($r->wasPosted()) {
         $status = $this->submit();
         if ($status->isGood()) {
             $this->setVar('_UpgradeDone', false);
             return 'continue';
         } else {
             $this->parent->showStatusBox($status);
         }
     }
     $this->startForm();
     $types = "<ul class=\"config-settings-block\">\n";
     $settings = '';
     $defaultType = $this->getVar('wgDBtype');
     // Give grep a chance to find the usages:
     // config-support-mysql, config-support-postgres, config-support-oracle, config-support-sqlite
     $dbSupport = '';
     foreach ($this->parent->getDBTypes() as $type) {
         $link = DatabaseBase::factory($type)->getSoftwareLink();
         $dbSupport .= wfMessage("config-support-{$type}", $link)->plain() . "\n";
     }
     $this->addHTML($this->parent->getInfoBox(wfMessage('config-support-info', trim($dbSupport))->text()));
     // It's possible that the library for the default DB type is not compiled in.
     // In that case, instead select the first supported DB type in the list.
     $compiledDBs = $this->parent->getVar('_CompiledDBs');
     if (!in_array($defaultType, $compiledDBs)) {
         $defaultType = $compiledDBs[0];
     }
     foreach ($compiledDBs as $type) {
         $installer = $this->parent->getDBInstaller($type);
         $types .= '<li>' . Xml::radioLabel($installer->getReadableName(), 'DBType', $type, "DBType_{$type}", $type == $defaultType, array('class' => 'dbRadio', 'rel' => "DB_wrapper_{$type}")) . "</li>\n";
         // Give grep a chance to find the usages:
         // config-header-mysql, config-header-postgres, config-header-oracle, config-header-sqlite
         $settings .= Html::openElement('div', array('id' => 'DB_wrapper_' . $type, 'class' => 'dbWrapper')) . Html::element('h3', array(), wfMessage('config-header-' . $type)->text()) . $installer->getConnectForm() . "</div>\n";
     }
     $types .= "</ul><br style=\"clear: left\"/>\n";
     $this->addHTML($this->parent->label('config-db-type', false, $types) . $settings);
     $this->endForm();
 }
 /**
  * @return Status
  */
 public function setupUser()
 {
     $dbUser = $this->getVar('wgDBuser');
     if ($dbUser == $this->getVar('_InstallUser')) {
         return Status::newGood();
     }
     $status = $this->getConnection();
     if (!$status->isOK()) {
         return $status;
     }
     $this->setupSchemaVars();
     $dbName = $this->getVar('wgDBname');
     $this->db->selectDB($dbName);
     $server = $this->getVar('wgDBserver');
     $password = $this->getVar('wgDBpassword');
     $grantableNames = array();
     if ($this->getVar('_CreateDBAccount')) {
         // Before we blindly try to create a user that already has access,
         try {
             // first attempt to connect to the database
             DatabaseBase::factory('mysql', array('host' => $server, 'user' => $dbUser, 'password' => $password, 'dbname' => false, 'flags' => 0, 'tablePrefix' => $this->getVar('wgDBprefix')));
             $grantableNames[] = $this->buildFullUserName($dbUser, $server);
             $tryToCreate = false;
         } catch (DBConnectionError $e) {
             $tryToCreate = true;
         }
     } else {
         $grantableNames[] = $this->buildFullUserName($dbUser, $server);
         $tryToCreate = false;
     }
     if ($tryToCreate) {
         $createHostList = array($server, 'localhost', 'localhost.localdomain', '%');
         $createHostList = array_unique($createHostList);
         $escPass = $this->db->addQuotes($password);
         foreach ($createHostList as $host) {
             $fullName = $this->buildFullUserName($dbUser, $host);
             if (!$this->userDefinitelyExists($dbUser, $host)) {
                 try {
                     $this->db->begin(__METHOD__);
                     $this->db->query("CREATE USER {$fullName} IDENTIFIED BY {$escPass}", __METHOD__);
                     $this->db->commit(__METHOD__);
                     $grantableNames[] = $fullName;
                 } catch (DBQueryError $dqe) {
                     if ($this->db->lastErrno() == 1396) {
                         // User (probably) already exists
                         $this->db->rollback(__METHOD__);
                         $status->warning('config-install-user-alreadyexists', $dbUser);
                         $grantableNames[] = $fullName;
                         break;
                     } else {
                         // If we couldn't create for some bizzare reason and the
                         // user probably doesn't exist, skip the grant
                         $this->db->rollback(__METHOD__);
                         $status->warning('config-install-user-create-failed', $dbUser, $dqe->getText());
                     }
                 }
             } else {
                 $status->warning('config-install-user-alreadyexists', $dbUser);
                 $grantableNames[] = $fullName;
                 break;
             }
         }
     }
     // Try to grant to all the users we know exist or we were able to create
     $dbAllTables = $this->db->addIdentifierQuotes($dbName) . '.*';
     foreach ($grantableNames as $name) {
         try {
             $this->db->begin(__METHOD__);
             $this->db->query("GRANT ALL PRIVILEGES ON {$dbAllTables} TO {$name}", __METHOD__);
             $this->db->commit(__METHOD__);
         } catch (DBQueryError $dqe) {
             $this->db->rollback(__METHOD__);
             $status->fatal('config-install-user-grant-failed', $dbUser, $dqe->getText());
         }
     }
     return $status;
 }
示例#26
0
 /**
  * @param $cond array
  * @return bool
  */
 private function initFromCond($cond)
 {
     global $wgExternalAuthConf;
     $this->mDb = DatabaseBase::factory($wgExternalAuthConf['DBtype'], array('host' => $wgExternalAuthConf['DBserver'], 'user' => $wgExternalAuthConf['DBuser'], 'password' => $wgExternalAuthConf['DBpassword'], 'dbname' => $wgExternalAuthConf['DBname'], 'tablePrefix' => $wgExternalAuthConf['DBprefix']));
     $row = $this->mDb->selectRow('user', array('user_name', 'user_id', 'user_password', 'user_email', 'user_email_authenticated'), $cond, __METHOD__);
     if (!$row) {
         return false;
     }
     $this->mRow = $row;
     return true;
 }
示例#27
0
 /**
  * @return Status
  */
 public function submitSettingsForm()
 {
     $this->setVarsFromRequest(array('wgDBuser', 'wgDBpassword', '_SameAccount', '_CreateDBAccount', '_WebWindowsAuthentication'));
     if ($this->getVar('_SameAccount')) {
         $this->setVar('_WebWindowsAuthentication', $this->getVar('_InstallWindowsAuthentication'));
         $this->setVar('wgDBuser', $this->getVar('_InstallUser'));
         $this->setVar('wgDBpassword', $this->getVar('_InstallPassword'));
     }
     if ($this->getVar('_WebWindowsAuthentication') == 'windowsauth') {
         $this->setVar('wgDBuser', '');
         $this->setVar('wgDBpassword', '');
         $this->setVar('wgDBWindowsAuthentication', true);
     } else {
         $this->setVar('wgDBWindowsAuthentication', false);
     }
     if ($this->getVar('_CreateDBAccount') && $this->getVar('_WebWindowsAuthentication') == 'sqlauth' && strval($this->getVar('wgDBpassword')) == '') {
         return Status::newFatal('config-db-password-empty', $this->getVar('wgDBuser'));
     }
     // Validate the create checkbox
     $canCreate = $this->canCreateAccounts();
     if (!$canCreate) {
         $this->setVar('_CreateDBAccount', false);
         $create = false;
     } else {
         $create = $this->getVar('_CreateDBAccount');
     }
     if (!$create) {
         // Test the web account
         $user = $this->getVar('wgDBuser');
         $password = $this->getVar('wgDBpassword');
         if ($this->getVar('_WebWindowsAuthentication') == 'windowsauth') {
             $user = '******';
             $password = '******';
         }
         try {
             DatabaseBase::factory('mssql', array('host' => $this->getVar('wgDBserver'), 'user' => $user, 'password' => $password, 'dbname' => false, 'flags' => 0, 'tablePrefix' => $this->getVar('wgDBprefix'), 'schema' => $this->getVar('wgDBmwschema')));
         } catch (DBConnectionError $e) {
             return Status::newFatal('config-connection-error', $e->getMessage());
         }
     }
     return Status::newGood();
 }
示例#28
0
 static function getDBData($dbID, $from, $columns, $where, $options)
 {
     global $edgDBServerType;
     global $edgDBServer;
     global $edgDBDirectory;
     global $edgDBName;
     global $edgDBUser;
     global $edgDBPass;
     global $edgDBFlags;
     global $edgDBTablePrefix;
     // Get all possible parameters
     $db_type = self::getArrayValue($edgDBServerType, $dbID);
     $db_server = self::getArrayValue($edgDBServer, $dbID);
     $db_directory = self::getArrayValue($edgDBDirectory, $dbID);
     $db_name = self::getArrayValue($edgDBName, $dbID);
     $db_username = self::getArrayValue($edgDBUser, $dbID);
     $db_password = self::getArrayValue($edgDBPass, $dbID);
     $db_flags = self::getArrayValue($edgDBFlags, $dbID);
     $db_tableprefix = self::getArrayValue($edgDBTablePrefix, $dbID);
     // Validate parameters
     if ($db_type == '') {
         echo wfMsgExt("externaldata-db-incomplete-information", array('parse', 'escape'));
         return;
     } elseif ($db_type == 'sqlite') {
         if ($db_directory == '' || $db_name == '') {
             echo wfMsgExt("externaldata-db-incomplete-information", array('parse', 'escape'));
             return;
         }
     } else {
         if ($db_server == '' || $db_name == '' || $db_username == '' || $db_password == '') {
             echo wfMsgExt("externaldata-db-incomplete-information", array('parse', 'escape'));
             return;
         }
     }
     // Additional settings
     if ($db_type == 'sqlite') {
         global $wgSQLiteDataDir;
         $oldDataDir = $wgSQLiteDataDir;
         $wgSQLiteDataDir = $db_directory;
     }
     if ($db_flags == '') {
         $db_flags = DBO_DEFAULT;
     }
     // DatabaseBase::newFromType() was added in MW 1.17 - it was
     // then replaced by DatabaseBase::factory() in MW 1.18
     $factoryFunction = array('DatabaseBase', 'factory');
     $newFromTypeFunction = array('DatabaseBase', 'newFromType');
     if (is_callable($factoryFunction)) {
         $db = DatabaseBase::factory($db_type, array('host' => $db_server, 'user' => $db_username, 'password' => $db_password, 'dbname' => $db_name, 'dbName' => $db_name, 'flags' => $db_flags, 'tablePrefix' => $db_tableprefix));
     } elseif (is_callable($newFromTypeFunction)) {
         $db = DatabaseBase::newFromType($db_type, array('host' => $db_server, 'user' => $db_username, 'password' => $db_password, 'dbname' => $db_name, 'flags' => $db_flags, 'tableprefix' => $db_tableprefix));
     } else {
         if ($db_flags !== DBO_DEFAULT || $db_tableprefix !== '') {
             print wfMsg("externaldata-db-option-unsupported", '<code>$edgDBFlags</code>', '<code>$edgDBTablePrefix</code>');
             return;
         }
         if ($db_type == "mysql") {
             $db = new Database($db_server, $db_username, $db_password, $db_name);
         } elseif ($db_type == "postgres") {
             $db = new DatabasePostgres($db_server, $db_username, $db_password, $db_name);
         } elseif ($db_type == "mssql") {
             $db = new DatabaseMssql($db_server, $db_username, $db_password, $db_name);
         } elseif ($db_type == "oracle") {
             $db = new DatabaseOracle($db_server, $db_username, $db_password, $db_name);
         } elseif ($db_type == "sqlite") {
             $db = new DatabaseSqlite($db_server, $db_username, $db_password, $db_name);
         } elseif ($db_type == "db2") {
             $db = new DatabaseIbm_db2($db_server, $db_username, $db_password, $db_name);
         } else {
             $db = null;
         }
     }
     if ($db == null) {
         echo wfMsgExt("externaldata-db-unknown-type", array('parse', 'escape'));
         return;
     }
     if (!$db->isOpen()) {
         echo wfMsgExt("externaldata-db-could-not-connect", array('parse', 'escape'));
         return;
     }
     if (count($columns) == 0) {
         echo wfMsgExt("externaldata-db-no-return-values", array('parse', 'escape'));
         return;
     }
     $rows = self::searchDB($db, $from, $columns, $where, $options);
     $db->close();
     if ($db_type == 'sqlite') {
         // Reset global variable back to its original value.
         global $wgSQLiteDataDir;
         $wgSQLiteDataDir = $oldDataDir;
     }
     $values = array();
     foreach ($rows as $row) {
         foreach ($columns as $column) {
             $values[$column][] = $row[$column];
         }
     }
     return $values;
 }
<?php

require_once 'commandLine.inc';
require_once "{$IP}/extensions/wikihow/titus/Titus.class.php";
require_once "{$IP}/extensions/wikihow/DatabaseHelper.class.php";
$dbw = DatabaseBase::factory('mysql');
$dbw->open(TITUS_DB_HOST, WH_DATABASE_MAINTENANCE_USER, WH_DATABASE_MAINTENANCE_PASSWORD, TitusDB::getDBName());
$rows = DatabaseHelper::batchSelect('titus_intl', 'ti_page_id', array('ti_language_code' => $wgLanguageCode), __METHOD__, array(), 2000, $dbw);
$deletedPageIds = array();
foreach ($rows as $row) {
    $t = Title::newFromId($row->ti_page_id);
    if (!($t && $t->exists() && $t->getNamespace() == NS_MAIN)) {
        $deletedPageIds[] = $row->ti_page_id;
    }
}
$chunks = array_chunk($deletedPageIds, 500);
foreach ($chunks as $chunk) {
    $aids = "(" . implode(",", $chunk) . ")";
    $sql = "DELETE FROM titus_intl where ti_page_id IN {$aids} AND ti_language_code='{$wgLanguageCode}'";
    var_dump($sql);
    $dbw->query($sql);
}
示例#30
0
 /**
  * Get connection to the wiki database 
  */
 private function getWikiDB()
 {
     global $wgDBname;
     if (is_null($this->wikiDB) || !$this->wikiDB->ping()) {
         $this->wikiDB = DatabaseBase::factory('mysql');
         $this->wikiDB->open(TITUS_DB_HOST, WH_DATABASE_MAINTENANCE_USER, WH_DATABASE_MAINTENANCE_PASSWORD, $wgDBname);
     }
     return $this->wikiDB;
 }