Sets a global, maintaining a stashed version of the previous global to be restored in tearDown.
Sets a global, maintaining a stashed version of the previous global to be restored in tearDownThe key is added to the array of globals that will be reset afterwards in the tearDown().
use Psr\Log\LoggerInterface;
private static $serviceLocator = null;
private $called = [];
public static $users;
protected $db;
protected $tablesUsed = [];
private static $useTemporaryTables = true;
private static $reuseDB = false;
private static $dbSetup = false;
private static $oldTablePrefix = '';
private $phpErrorLevel;
private $tmpFiles = [];
private $mwGlobals = [];
private $loggers = [];
const DB_PREFIX = 'unittest_';
const ORA_DB_PREFIX = 'ut_';
protected $supportedDBs = [
'mysql',
'sqlite',
'postgres',
'oracle'
];
public function __construct(
$name =
null,
array $data = [], $dataName =
'' ) {
parent::__construct(
$name, $data, $dataName );
$this->backupGlobals = false;
$this->backupStaticAttributes = false;
}
public function __destruct() {
if ( isset( $this->called['setUp'] ) && !isset( $this->called['tearDown'] ) ) {
throw new MWException( static::class .
"::tearDown() must call parent::tearDown()" );
}
}
public static function setUpBeforeClass() {
parent::setUpBeforeClass();
}
public static function getTestUser( $groups = [] ) {
}
public static function getMutableTestUser( $groups = [] ) {
}
public static function getTestSysop() {
return self::getTestUser( [ 'sysop', 'bureaucrat' ] );
}
public static function prepareServices(
Config $bootstrapConfig ) {
$services = self::resetGlobalServices( $bootstrapConfig );
}
}
protected static function resetGlobalServices(
Config $bootstrapConfig =
null ) {
$oldServices = MediaWikiServices::getInstance();
$oldConfigFactory = $oldServices->getConfigFactory();
$testConfig = self::makeTestConfig( $bootstrapConfig );
MediaWikiServices::resetGlobalInstance( $testConfig );
$serviceLocator = MediaWikiServices::getInstance();
self::installTestServices(
$oldConfigFactory,
$serviceLocator
);
return $serviceLocator;
}
private static function makeTestConfig(
Config $customOverrides =
null
) {
if ( !$baseConfig ) {
$baseConfig = MediaWikiServices::getInstance()->getBootstrapConfig();
}
$hashCache = [
'class' =>
'HashBagOStuff',
'reportDupes' =>
false ];
$objectCaches = [
'apc' => $hashCache,
'xcache' => $hashCache,
'wincache' => $hashCache,
] + $baseConfig->get( 'ObjectCaches' );
$defaultOverrides->set( 'ObjectCaches', $objectCaches );
$defaultOverrides->set(
'MainCacheType',
CACHE_NONE );
$defaultOverrides->set( 'JobTypeConf', [ 'default' => [ 'class' => 'JobQueueMemory' ] ] );
$defaultOverrides->set( 'PasswordDefault', 'A' );
$testConfig = $customOverrides
?
new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
:
new MultiConfig( [ $defaultOverrides, $baseConfig ] );
return $testConfig;
}
private static function installTestServices(
) {
$bootstrapConfig = $newServices->getBootstrapConfig();
$newServices->resetServiceForTesting( 'ConfigFactory' );
$newServices->redefineService(
'ConfigFactory',
self::makeTestConfigFactoryInstantiator(
$oldConfigFactory,
[ 'main' => $bootstrapConfig ]
)
);
}
private static function makeTestConfigFactoryInstantiator(
) {
$namesToClone = array_diff(
array_keys( $configurations )
);
foreach ( $namesToClone
as $name ) {
}
foreach ( $configurations
as $name => $config ) {
$factory->register(
$name, $config );
}
return $factory;
};
}
private function doLightweightServiceReset() {
ObjectCache::clear();
$services = MediaWikiServices::getInstance();
$services->resetServiceForTesting(
'MainObjectStash' );
$services->resetServiceForTesting(
'LocalServerObjectCache' );
$services->getMainWANObjectCache()->clearProcessCache();
if ( session_id() !== '' ) {
session_write_close();
session_id( '' );
}
MediaWiki\Session\SessionManager::resetCache();
}
public function run( PHPUnit_Framework_TestResult
$result =
null ) {
$this->doLightweightServiceReset();
$needsResetDB = false;
if ( !self::$dbSetup || $this->needsDB() ) {
self::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
self::$reuseDB = $this->getCliArg( 'reuse-db' );
$this->checkDbIsSupported();
if ( !self::$dbSetup ) {
$this->setupAllTestDBs();
$this->addCoreDBData();
if ( ( $this->db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
$this->resetDB( $this->db, $this->tablesUsed );
}
}
if ( $this->oncePerClass() ) {
$this->addDBDataOnce();
}
$this->addDBData();
$needsResetDB = true;
}
if ( $needsResetDB ) {
$this->resetDB( $this->db, $this->tablesUsed );
}
}
private function oncePerClass() {
$class = static::class;
$first = !isset( $this->db->_hasDataForTestClass )
|| $this->db->_hasDataForTestClass !== $class;
$this->db->_hasDataForTestClass = $class;
return $first;
}
public function usesTemporaryTables() {
return self::$useTemporaryTables;
}
protected function getNewTempFile() {
$fileName = tempnam(
wfTempDir(),
'MW_PHPUnit_' . get_class( $this ) .
'_' );
$this->tmpFiles[] = $fileName;
return $fileName;
}
protected function getNewTempDirectory() {
$fileName = $this->getNewTempFile();
unlink( $fileName );
return $fileName;
}
protected function setUp() {
parent::setUp();
$this->called['setUp'] = true;
$this->phpErrorLevel = intval( ini_get( 'error_reporting' ) );
foreach ( $this->tmpFiles
as $fileName ) {
if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
unlink( $fileName );
} elseif ( is_dir( $fileName ) ) {
}
}
if ( $this->needsDB() && $this->db ) {
while ( $this->db->trxLevel() > 0 ) {
$this->db->rollback( __METHOD__, 'flush' );
}
if ( $this->db->getType() === 'mysql' ) {
$this->db->query( "SET sql_mode = 'STRICT_ALL_TABLES'" );
}
}
DeferredUpdates::clearPendingUpdates();
ObjectCache::getMainWANInstance()->clearProcessCache();
$lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
}
protected function addTmpFiles(
$files ) {
$this->tmpFiles = array_merge( $this->tmpFiles, (
array)
$files );
}
protected function tearDown() {
$status[
'name'] ===
'MediaWikiTestCase::wfResetOutputBuffersBarrier'
) {
ob_end_flush();
}
$this->called['tearDown'] = true;
foreach ( $this->tmpFiles
as $fileName ) {
if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
unlink( $fileName );
} elseif ( is_dir( $fileName ) ) {
}
}
if ( $this->needsDB() && $this->db ) {
while ( $this->db->trxLevel() > 0 ) {
$this->db->rollback( __METHOD__, 'flush' );
}
if ( $this->db->getType() === 'mysql' ) {
$this->db->query(
"SET sql_mode = " . $this->db->addQuotes(
$wgSQLMode ) );
}
}
foreach ( $this->mwGlobals
as $key =>
$value ) {
}
$this->mwGlobals = [];
$this->restoreLoggers();
if ( self::$serviceLocator && MediaWikiServices::getInstance() !== self::$serviceLocator ) {
MediaWikiServices::forceGlobalInstance( self::$serviceLocator );
}
if ( session_id() !== '' ) {
session_write_close();
session_id( '' );
}
MediaWiki\Session\SessionManager::resetCache();
MediaWiki\Auth\AuthManager::resetCache();
$phpErrorLevel = intval( ini_get( 'error_reporting' ) );
if ( $phpErrorLevel !== $this->phpErrorLevel ) {
ini_set( 'error_reporting', $this->phpErrorLevel );
$oldHex = strtoupper( dechex( $this->phpErrorLevel ) );
$newHex = strtoupper( dechex( $phpErrorLevel ) );
$message = "PHP error_reporting setting was left dirty: "
. "was 0x$oldHex before test, 0x$newHex after test!";
$this->fail( $message );
}
parent::tearDown();
}
final public function testMediaWikiTestCaseParentSetupCalled() {
$this->assertArrayHasKey( 'setUp', $this->called,
static::class . '::setUp() must call parent::setUp()'
);
}
protected function setService(
$name, $object ) {
if ( MediaWikiServices::getInstance() === self::$serviceLocator ) {
$this->overrideMwServices();
}
MediaWikiServices::getInstance()->disableService(
$name );
MediaWikiServices::getInstance()->redefineService(
function ()
use ( $object ) {
return $object;
}
);
}
protected function setMwGlobals( $pairs,
$value =
null ) {
if ( is_string( $pairs ) ) {
$pairs = [ $pairs =>
$value ];
}
$this->stashMwGlobals( array_keys( $pairs ) );
}
}
private static function canShallowCopy(
$value ) {
return true;
}
if ( !is_scalar( $subValue ) && $subValue !== null ) {
return false;
}
}
return true;
}
return false;
}
protected function stashMwGlobals( $globalKeys ) {
if ( is_string( $globalKeys ) ) {
$globalKeys = [ $globalKeys ];
}
foreach ( $globalKeys
as $globalKey ) {
if ( !array_key_exists( $globalKey, $this->mwGlobals ) ) {
if ( !array_key_exists( $globalKey,
$GLOBALS ) ) {
throw new Exception( "Global with key {$globalKey} doesn't exist and cant be stashed" );
}
if ( self::canShallowCopy(
$GLOBALS[$globalKey] ) ) {
$this->mwGlobals[$globalKey] =
$GLOBALS[$globalKey];
} elseif (
) {
$this->mwGlobals[$globalKey] = clone
$GLOBALS[$globalKey];
} else {
try {
}
catch ( Exception
$e ) {
$this->mwGlobals[$globalKey] =
$GLOBALS[$globalKey];
}
}
}
}
}
protected function mergeMwGlobalArrayValue(
$name, $values ) {
$merged = $values;
} else {
throw new MWException(
"MW global $name is not an array." );
}
foreach ( $values
as $k => $v ) {
$merged[$k] = $v;
}
}
$this->setMwGlobals(
$name, $merged );
}
if ( !$configOverrides ) {
}
$oldInstance = MediaWikiServices::getInstance();
$oldConfigFactory = $oldInstance->getConfigFactory();
$testConfig = self::makeTestConfig( null, $configOverrides );
$wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
$newInstance->loadWiringFiles( $wiringFiles );
Hooks::run( 'MediaWikiServices', [ $newInstance ] );
$newInstance->redefineService(
$name, $callback );
}
self::installTestServices(
$oldConfigFactory,
$newInstance
);
MediaWikiServices::forceGlobalInstance( $newInstance );
return $newInstance;
}
public function setUserLang(
$lang ) {
}
public function setContentLang(
$lang ) {
$langCode =
$lang->getCode();
} else {
$langObj = Language::factory( $langCode );
}
$this->setMwGlobals( [
'wgLanguageCode' => $langCode,
'wgContLang' => $langObj,
] );
}
protected function setLogger( $channel, LoggerInterface $logger ) {
$provider = LoggerFactory::getProvider();
$wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
$singletons = $wrappedProvider->singletons;
if ( !isset( $this->loggers[$channel] ) ) {
$this->loggers[$channel] = isset( $singletons['loggers'][$channel] )
? $singletons['loggers'][$channel] : null;
}
$singletons['loggers'][$channel] = $logger;
} elseif ( $provider instanceof
LegacySpi ) {
if ( !isset( $this->loggers[$channel] ) ) {
$this->loggers[$channel] = isset( $singletons[$channel] ) ? $singletons[$channel] : null;
}
$singletons[$channel] = $logger;
} else {
throw new LogicException( __METHOD__ . ': setting a logger for ' . get_class( $provider )
. ' is not implemented' );
}
$wrappedProvider->singletons = $singletons;
}
private function restoreLoggers() {
$provider = LoggerFactory::getProvider();
$wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
$singletons = $wrappedProvider->singletons;
foreach ( $this->loggers
as $channel => $logger ) {
if ( $logger === null ) {
unset( $singletons['loggers'][$channel] );
} else {
$singletons['loggers'][$channel] = $logger;
}
} elseif ( $provider instanceof
LegacySpi ) {
if ( $logger === null ) {
unset( $singletons[$channel] );
} else {
$singletons[$channel] = $logger;
}
}
}
$wrappedProvider->singletons = $singletons;
$this->loggers = [];
}
public function dbPrefix() {
return $this->db->getType() == 'oracle' ? self::ORA_DB_PREFIX : self::DB_PREFIX;
}
public function needsDB() {
# if the test says it uses database tables, it needs the database
if ( $this->tablesUsed ) {
return true;
}
# if the test says it belongs to the Database group, it needs the database
$rc = new ReflectionClass( $this );
if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
return true;
}
return false;
}
protected function insertPage(
$pageName,
$text = 'Sample page for unit test.',
$namespace = null
) {
if ( is_string( $pageName ) ) {
$title = Title::newFromText( $pageName, $namespace );
} else {
}
$user = static::getTestSysop()->getUser();
$comment = __METHOD__ .
': Sample page for unit test.';
return [
];
}
public function addDBDataOnce() {
}
public function addDBData() {
}
private function addCoreDBData() {
if ( $this->db->getType() == 'oracle' ) {
# Insert 0 user to prevent FK violations
# Anonymous user
if ( !$this->db->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
$this->db->insert( 'user', [
'user_id' => 0,
'user_name' => 'Anonymous' ], __METHOD__, [ 'IGNORE' ] );
}
# Insert 0 page to prevent FK violations
# Blank page
if ( !$this->db->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
$this->db->insert( 'page', [
'page_id' => 0,
'page_namespace' => 0,
'page_title' => ' ',
'page_restrictions' => null,
'page_is_redirect' => 0,
'page_is_new' => 0,
'page_random' => 0,
'page_touched' => $this->db->timestamp(),
'page_latest' => 0,
'page_len' => 0 ], __METHOD__, [ 'IGNORE' ] );
}
}
User::resetIdByNameCache();
$user = static::getTestSysop()->getUser();
if (
$page->getId() == 0 ) {
'UTPageSummary',
false,
);
if ( session_id() !== '' ) {
session_write_close();
session_id( '' );
}
}
}
public static function teardownTestDB() {
if ( !self::$dbSetup ) {
return;
}
}
self::$oldTablePrefix = false;
self::$dbSetup = false;
}
protected static function setupDatabaseWithTestPrefix(
Database $db, $prefix ) {
$tablesCloned = self::listTables( $db );
$dbClone->useTemporaryTables( self::$useTemporaryTables );
if ( ( $db->
getType() ==
'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
return false;
} else {
$dbClone->cloneTableStructure();
return true;
}
}
public function setupAllTestDBs() {
$testPrefix = $this->dbPrefix();
self::setupTestDB( $this->db, $testPrefix );
if ( self::isUsingExternalStoreDB() ) {
self::setupExternalStoreTestDBs( $testPrefix );
}
}
public static function setupTestDB(
Database $db, $prefix ) {
if ( self::$dbSetup ) {
return;
}
'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
}
self::$dbSetup = true;
if ( !self::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
return;
}
if ( $db->
getType() ==
'oracle' ) {
$db->
query(
'BEGIN FILL_WIKI_INFO; END;' );
}
}
protected static function setupExternalStoreTestDBs( $testPrefix ) {
$connections = self::getExternalStoreDatabaseConnections();
foreach ( $connections
as $dbw ) {
$dbw->tablePrefix( self::$oldTablePrefix );
self::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
}
}
protected static function getExternalStoreDatabaseConnections() {
$dbws = [];
foreach ( $defaultArray
as $url ) {
if ( strpos( $url, 'DB://' ) === 0 ) {
list( $proto, $cluster ) = explode(
'://', $url, 2 );
$lb = $externalStoreDB->getLoadBalancer( $cluster );
$dbws[] = $dbw;
}
}
return $dbws;
}
protected static function isUsingExternalStoreDB() {
return false;
}
foreach ( $defaultArray
as $url ) {
if ( strpos( $url, 'DB://' ) === 0 ) {
return true;
}
}
return false;
}
private function resetDB( $db, $tablesUsed ) {
if ( $db ) {
$userTables = [ 'user', 'user_groups', 'user_properties' ];
$coreDBDataTables = array_merge( $userTables, [ 'page', 'revision' ] );
if ( array_intersect( $tablesUsed, $userTables ) ) {
$tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
}
$truncate = in_array( $db->
getType(), [
'oracle',
'mysql' ] );
foreach ( $tablesUsed
as $tbl ) {
if ( $tbl == 'interwiki' ) {
continue;
}
if ( $truncate ) {
} else {
$db->
delete( $tbl,
'*', __METHOD__ );
}
if ( $tbl === 'page' ) {
LinkCache::singleton()->clear();
}
}
if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
$this->addCoreDBData();
}
}
}
public function __call( $func,
$args ) {
static $compatibility = [
'assertEmpty' => 'assertEmpty2',
];
if ( isset( $compatibility[$func] ) ) {
return call_user_func_array( [ $this, $compatibility[$func] ],
$args );
} else {
throw new MWException(
"Called non-existent $func method on "
. get_class( $this ) );
}
}
private function assertEmpty2(
$value, $msg ) {
$this->assertTrue(
$value ==
'', $msg );
}
private static function unprefixTable( &$tableName, $ind, $prefix ) {
$tableName = substr( $tableName, strlen( $prefix ) );
}
private static function isNotUnittest( $table ) {
return strpos( $table, 'unittest_' ) !== 0;
}
public static function listTables(
Database $db ) {
if ( $db->
getType() ===
'mysql' ) {
static $viewListCache = null;
if ( $viewListCache === null ) {
$viewListCache = $db->
listViews(
null, __METHOD__ );
}
}
array_walk(
$tables, [ __CLASS__,
'unprefixTable' ], $prefix );
if ( $db->
getType() ==
'sqlite' ) {
unset(
$tables[
'searchindex_content'] );
unset(
$tables[
'searchindex_segdir'] );
unset(
$tables[
'searchindex_segments'] );
}
}
protected function checkDbIsSupported() {
if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
throw new MWException( $this->db->getType() .
" is not currently supported for unit testing." );
}
}
public function getCliArg( $offset ) {
}
}
public function setCliArg( $offset,
$value ) {
}
public function hideDeprecated( $function ) {
MediaWiki\suppressWarnings();
MediaWiki\restoreWarnings();
}
protected function assertSelect( $table, $fields, $condition,
array $expectedRows ) {
if ( !$this->needsDB() ) {
throw new MWException(
'When testing database state, the test cases\'s needDB()' .
' method should return true. Use @group Database or $this->tablesUsed.' );
}
$this->assertNotEmpty(
$res,
"query failed: " . $db->
lastError() );
$i = 0;
foreach ( $expectedRows
as $expected ) {
self::stripStringKeys( $r );
$i += 1;
$this->assertNotEmpty( $r, "row #$i missing" );
$this->assertEquals( $expected, $r, "row #$i mismatches" );
}
self::stripStringKeys( $r );
$this->assertFalse( $r, "found extra row (after #$i)" );
}
protected function arrayWrap(
array $elements ) {
return array_map(
function ( $element ) {
return [ $element ];
},
$elements
);
}
protected function assertArrayEquals(
array $expected,
array $actual,
$ordered = false, $named = false
) {
if ( !$ordered ) {
$this->objectAssociativeSort( $expected );
$this->objectAssociativeSort( $actual );
}
if ( !$named ) {
$expected = array_values( $expected );
$actual = array_values( $actual );
}
call_user_func_array(
[ $this, 'assertEquals' ],
array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
);
}
protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
$expected = str_replace( '>', ">\n", $expected );
$actual = str_replace( '>', ">\n", $actual );
$this->assertEquals( $expected, $actual, $msg );
}
protected function objectAssociativeSort(
array &$array ) {
uasort(
$array,
function ( $a, $b ) {
}
);
}
protected static function stripStringKeys( &$r ) {
if ( !is_array( $r ) ) {
return;
}
foreach ( $r
as $k => $v ) {
if ( is_string( $k ) ) {
unset( $r[$k] );
}
}
}
protected function assertTypeOrValue(
$type, $actual,
$value =
false, $message =
'' ) {
$this->assertTrue( true, $message );
} else {
$this->assertType(
$type, $actual, $message );
}
}
protected function assertType(
$type, $actual, $message =
'' ) {
if ( class_exists(
$type ) || interface_exists(
$type ) ) {
$this->assertInstanceOf(
$type, $actual, $message );
} else {
$this->assertInternalType(
$type, $actual, $message );
}
}
protected function isWikitextNS( $ns ) {
}
return true;
}
protected function getDefaultWikitextNS() {
static $wikitextNS = null;
if ( $wikitextNS !== null ) {
return $wikitextNS;
}
}
MWNamespace::getContentNamespaces(),
MWNamespace::getValidNamespaces()
) );
] );
return MWNamespace::isTalk( $ns );
} );
) {
$wikitextNS = $ns;
return $wikitextNS;
}
}
throw new MWException(
"No namespace defaults to wikitext!" );
}
protected function markTestSkippedIfNoDiff3() {
# This check may also protect against code injection in
# case of broken installations.
MediaWiki\suppressWarnings();
MediaWiki\restoreWarnings();
if ( !$haveDiff3 ) {
$this->markTestSkipped( "Skip test, since diff3 is not configured" );
}
}
protected function checkPHPExtension( $extName ) {
$loaded = extension_loaded( $extName );
if ( !$loaded ) {
$this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
}
return $loaded;
}
protected function assertValidHtmlSnippet(
$html ) {
$html =
'<!DOCTYPE html><html><head><title>test</title></head><body>' .
$html .
'</body></html>';
$this->assertValidHtmlDocument(
$html );
}
protected function assertValidHtmlDocument(
$html ) {
$this->markTestSkipped( 'Tidy extension not installed' );
}
$errorBuffer = '';
$allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
$errors = preg_grep(
'/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
$allErrors, PREG_GREP_INVERT
);
$this->assertEmpty( $errors, implode( "\n", $errors ) );
}
private static function tagMatch( $matcher, $actual, $isHtml = true ) {
$dom = PHPUnit_Util_XML::load( $actual, $isHtml );
$tags = PHPUnit_Util_XML::findNodes( $dom, $matcher, $isHtml );
return count( $tags ) > 0 && $tags[0] instanceof DOMNode;
}
public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
self::assertTrue( self::tagMatch( $matcher, $actual, $isHtml ), $message );
}
public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
self::assertFalse( self::tagMatch( $matcher, $actual, $isHtml ), $message );
}
public static function wfResetOutputBuffersBarrier(
$buffer ) {
}
protected function setTemporaryHook( $hookName,
$handler ) {
$this->mergeMwGlobalArrayValue(
'wgHooks', [ $hookName => [
$handler ] ] );
}
}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
unserialize( $serialized)
$wgDBprefix
Table name prefix.
$wgSQLMode
SQL Mode - default is turning off all modes, including strict, if set.
array $wgDefaultExternalStore
The place to put new revisions, false to put them in the local text table.
$wgDiff3
Path to the GNU diff3 utility.
$wgJobClasses
Maps jobs to their handling classes; extensions can add to this to provide custom jobs.
$wgNamespaceContentModels
Associative array mapping namespace IDs to the name of the content model pages in that namespace shou...
wfTempDir()
Tries to get the system directory for temporary files.
wfRecursiveRemoveDir( $dir)
Remove a directory and all its content.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfGetCaller( $level=2)
Get the name of the function which called this function wfGetCaller( 1 ) is the function with the wfG...
wfMkdirParents( $dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
if(! $wgDBerrorLogTZ) $wgRequest
static changePrefix( $prefix)
Change the table prefix on all open DB connections/.
Factory class to create Config objects.
makeConfig( $name)
Create a given Config using the registered callback for $name.
static makeContent( $text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
Relational database abstraction object.
delete( $table, $conds, $fname=__METHOD__)
DELETE query wrapper.
tablePrefix( $prefix=null)
Get/set the table prefix.
select( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Execute a SELECT query constructed using the various parameters provided.
query( $sql, $fname=__METHOD__, $tempIgnore=false)
Run an SQL query and return the result.
tableName( $name, $format='quoted')
Format a table name ready for use in constructing an SQL query.
listViews( $prefix=null, $fname=__METHOD__)
Lists all the VIEWs in the database.
listTables( $prefix=null, $fname=__METHOD__)
List all tables on the database.
static getStoreObject( $proto, array $params=[])
Get an external store object of the given type, with the given parameters.
WebRequest clone which takes values from a provided array.
static destroySingleton()
Destroy the singleton instance.
Accesses configuration settings from $GLOBALS.
A Config instance which stores all settings as a member variable.
static destroySingletons()
Destroy the singleton instances.
static singleton( $wiki=false)
Internationalisation code.
static checkErrors( $text, &$errorStr=null)
Check HTML for errors, used if $wgValidateAllHtml = true.
static setLBFactoryTriggers(LBFactory $LBFactory)
Provides a fallback sequence for Config objects.
static $additionalOptions
static resetMain()
Resets singleton returned by getMain().
static getMain()
Static methods.
static clear()
Clear the registry.
static getMutableTestUser( $testName, $groups=[])
Get a TestUser object that the caller may modify.
static getImmutableTestUser( $groups=[])
Get a TestUser object that the caller may not modify.
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Content object for wiki text pages.
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
when a variable name is used in a it is silently declared as a new local masking the global
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
const CONTENT_MODEL_WIKITEXT
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
the array() calling protocol came about after MediaWiki 1.4rc1.
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
namespace are movable Hooks may change this value to override the return value of MWNamespace::isMovable(). 'NewDifferenceEngine' do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached one of or reset my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist & $tables
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Associative array mapping language codes to prefixed links of the form "language:title". & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
namespace and then decline to actually register it & $namespaces
namespace and then decline to actually register it file or subcat img or subcat $title
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title after the basic globals have been set but before ordinary actions take place or wrap services the preferred way to define a new service is the $wgServiceWiringFiles array $services
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses & $html
Allows to change the fields on the form that will be generated $name
namespace are movable Hooks may change this value to override the return value of MWNamespace::isMovable(). 'NewDifferenceEngine' do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached $page
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check set to true or false to override the $wgMaxImageArea check result gives extension the possibility to transform it themselves $handler
processing should stop and the error should be shown to the user * false
returning false will NOT prevent logging $e
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Interface for configuration instances.
lastError()
Get a description of the last error.
getType()
Get the type of the DBMS, as it appears in $wgDBtype.
MediaWiki Logger LegacySpi
MediaWiki Logger MonologSpi
if(!isset( $args[0])) $lang