Go to the documentation of this file.
8 use Psr\Log\LoggerInterface;
12 use Wikimedia\TestingAccessWrapper;
19 use MediaWikiCoversValidator;
20 use PHPUnit4And6Compat;
149 parent::__construct(
$name,
$data, $dataName );
151 $this->backupGlobals =
false;
152 $this->backupStaticAttributes =
false;
158 if ( isset( $this->called[
'setUp'] ) && !isset( $this->called[
'tearDown'] ) ) {
164 parent::setUpBeforeClass();
167 if ( !self::$originalServices ) {
168 self::$originalServices = MediaWikiServices::getInstance();
222 throw new MWException(
'When testing which pages, the test cases\'s needsDB()' .
223 ' method should return true. Use @group Database or $this->tablesUsed.' );
230 if ( !$page->exists() ) {
232 $page->doEditContent(
258 throw new MWException(
'When testing which pages, the test cases\'s needsDB()' .
259 ' method should return true. Use @group Database or $this->tablesUsed.' );
266 if ( $page->exists() ) {
267 $page->doDeleteArticle(
'Testing' );
289 Config $baseConfig =
null,
290 Config $customOverrides =
null
294 if ( !$baseConfig ) {
295 $baseConfig = self::$originalServices->getBootstrapConfig();
308 'apcu' => $hashCache,
309 'wincache' => $hashCache,
310 ] + $baseConfig->get(
'ObjectCaches' );
312 $defaultOverrides->set(
'ObjectCaches', $objectCaches );
313 $defaultOverrides->set(
'MainCacheType',
CACHE_NONE );
317 $defaultOverrides->set(
'PasswordDefault',
'A' );
319 $testConfig = $customOverrides
320 ?
new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
321 :
new MultiConfig( [ $defaultOverrides, $baseConfig ] );
334 array $configurations
340 $namesToClone = array_diff(
342 array_keys( $configurations )
345 foreach ( $namesToClone
as $name ) {
349 foreach ( $configurations
as $name => $config ) {
350 $factory->register(
$name, $config );
376 if ( session_id() !==
'' ) {
377 session_write_close();
385 public function run( PHPUnit_Framework_TestResult
$result =
null ) {
387 $this->cliArgs =
$result->getMediaWikiCliArgs();
393 get_class( $this ) .
' apparently needsDB but is not in the Database group'
397 $needsResetDB =
false;
398 if ( !self::$dbSetup || $this->
needsDB() ) {
401 self::$useTemporaryTables = !$this->
getCliArg(
'use-normal-tables' );
402 self::$reuseDB = $this->
getCliArg(
'reuse-db' );
404 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
405 $this->db = $lb->getConnection(
DB_MASTER );
409 if ( !self::$dbSetup ) {
419 $this->
resetDB( $this->db, $this->tablesUsed );
424 $needsResetDB =
true;
430 $this->overriddenServices = [];
432 if ( $needsResetDB ) {
433 $this->
resetDB( $this->db, $this->tablesUsed );
437 $this->localServices =
null;
449 $first = !isset( $this->db->_hasDataForTestClass )
450 || $this->db->_hasDataForTestClass !== $class;
452 $this->db->_hasDataForTestClass = $class;
476 $this->tmpFiles[] = $fileName;
506 $this->called[
'setUp'] =
true;
508 $this->phpErrorLevel = intval( ini_get(
'error_reporting' ) );
510 $this->overriddenServices = [];
513 foreach ( $this->tmpFiles
as $fileName ) {
514 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
516 } elseif ( is_dir( $fileName ) ) {
521 if ( $this->
needsDB() && $this->db ) {
523 while ( $this->db->trxLevel() > 0 ) {
524 $this->db->rollback( __METHOD__,
'flush' );
527 if ( $this->db->getType() ===
'mysql' ) {
528 $this->db->query(
"SET sql_mode = 'STRICT_ALL_TABLES'", __METHOD__ );
537 $lbFactory = $this->localServices->getDBLoadBalancerFactory();
540 ob_start(
'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
544 $this->tmpFiles = array_merge( $this->tmpFiles, (
array)$files );
551 if ( isset(
$status[
'name'] ) &&
552 $status[
'name'] ===
'MediaWikiTestCase::wfResetOutputBuffersBarrier'
557 $this->called[
'tearDown'] =
true;
559 foreach ( $this->tmpFiles
as $fileName ) {
560 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
562 } elseif ( is_dir( $fileName ) ) {
567 if ( $this->
needsDB() && $this->db ) {
569 while ( $this->db->trxLevel() > 0 ) {
570 $this->db->rollback( __METHOD__,
'flush' );
572 if ( $this->db->getType() ===
'mysql' ) {
573 $this->db->query(
"SET sql_mode = " . $this->db->addQuotes(
$wgSQLMode ),
581 foreach ( $this->mwGlobals
as $key =>
$value ) {
584 foreach ( $this->mwGlobalsToUnset
as $value ) {
591 array_key_exists(
'wgExtraNamespaces', $this->mwGlobals ) ||
592 in_array(
'wgExtraNamespaces', $this->mwGlobalsToUnset )
596 $this->mwGlobals = [];
597 $this->mwGlobalsToUnset = [];
602 if ( session_id() !==
'' ) {
603 session_write_close();
613 ini_set(
'error_reporting', $this->phpErrorLevel );
615 $oldHex = strtoupper( dechex( $this->phpErrorLevel ) );
617 $message =
"PHP error_reporting setting was left dirty: "
618 .
"was 0x$oldHex before test, 0x$newHex after test!";
620 $this->fail( $message );
635 $this->assertArrayHasKey(
'setUp', $this->called,
650 if ( !$this->localServices ) {
651 throw new Exception( __METHOD__ .
' must be called after MediaWikiTestCase::run()' );
654 if ( $this->localServices !== MediaWikiServices::getInstance() ) {
655 throw new Exception( __METHOD__ .
' will not work because the global MediaWikiServices '
656 .
'instance has been replaced by test code.' );
659 $this->overriddenServices[] =
$name;
661 $this->localServices->disableService(
$name );
662 $this->localServices->redefineService(
664 function ()
use ( $object ) {
669 if (
$name ===
'ContentLanguage' ) {
710 if ( is_string( $pairs ) ) {
711 $pairs = [ $pairs =>
$value ];
714 if ( isset( $pairs[
'wgContLang'] ) ) {
716 'No setting $wgContLang, use setContentLang() or setService( \'ContentLanguage\' )'
730 foreach ( $pairs
as $key =>
$value ) {
734 if ( array_key_exists(
'wgExtraNamespaces', $pairs ) ) {
746 $original = ini_get(
$name );
747 $this->iniSettings[
$name] = $original;
756 if ( !$this->localServices ) {
757 throw new Exception( __METHOD__ .
' must be called after MediaWikiTestCase::run()' );
760 if ( $this->localServices !== MediaWikiServices::getInstance() ) {
761 throw new Exception( __METHOD__ .
' will not work because the global MediaWikiServices '
762 .
'instance has been replaced by test code.' );
770 $this->localServices->resetServiceForTesting(
'TitleFormatter' );
771 $this->localServices->resetServiceForTesting(
'TitleParser' );
772 $this->localServices->resetServiceForTesting(
'_MediaWikiTitleCodec' );
787 if ( is_array(
$value ) ) {
789 if ( !is_scalar( $subValue ) && $subValue !==
null ) {
822 if ( is_string( $globalKeys ) ) {
823 $globalKeys = [ $globalKeys ];
826 foreach ( $globalKeys
as $globalKey ) {
831 !array_key_exists( $globalKey, $this->mwGlobals ) &&
832 !array_key_exists( $globalKey, $this->mwGlobalsToUnset )
834 if ( !array_key_exists( $globalKey,
$GLOBALS ) ) {
835 $this->mwGlobalsToUnset[$globalKey] = $globalKey;
841 if ( self::canShallowCopy(
$GLOBALS[$globalKey] ) ) {
842 $this->mwGlobals[$globalKey] =
$GLOBALS[$globalKey];
850 $this->mwGlobals[$globalKey] = clone
$GLOBALS[$globalKey];
855 $this->mwGlobals[$globalKey] =
$GLOBALS[$globalKey];
859 }
catch ( Exception
$e ) {
860 $this->mwGlobals[$globalKey] =
$GLOBALS[$globalKey];
874 if ( $var instanceof Closure ) {
877 if ( !is_array( $var ) || $maxDepth === 0 ) {
909 throw new MWException(
"MW global $name is not an array." );
914 foreach ( $values
as $k => $v ) {
940 if ( $this->overriddenServices ) {
942 'The following services were set and are now being unset by overrideMwServices: ' .
943 implode(
', ', $this->overriddenServices )
948 if ( $this->localServices ) {
949 $this->localServices->destroy();
952 $this->localServices = $newInstance;
955 $newInstance->redefineService(
$name, $callback );
980 if ( !self::$originalServices ) {
981 self::$originalServices = MediaWikiServices::getInstance();
984 if ( !$configOverrides ) {
988 $oldConfigFactory = self::$originalServices->getConfigFactory();
989 $oldLoadBalancerFactory = self::$originalServices->getDBLoadBalancerFactory();
996 $wiringFiles = $testConfig->get(
'ServiceWiringFiles' );
997 $newServices->loadWiringFiles( $wiringFiles );
1000 Hooks::run(
'MediaWikiServices', [ $newServices ] );
1004 $bootstrapConfig = $newServices->getBootstrapConfig();
1005 $newServices->resetServiceForTesting(
'ConfigFactory' );
1006 $newServices->redefineService(
1008 self::makeTestConfigFactoryInstantiator(
1010 [
'main' => $bootstrapConfig ]
1013 $newServices->resetServiceForTesting(
'DBLoadBalancerFactory' );
1014 $newServices->redefineService(
1015 'DBLoadBalancerFactory',
1017 return $oldLoadBalancerFactory;
1021 MediaWikiServices::forceGlobalInstance( $newServices );
1022 return $newServices;
1037 if ( !self::$originalServices ) {
1041 $currentServices = MediaWikiServices::getInstance();
1043 if ( self::$originalServices === $currentServices ) {
1047 MediaWikiServices::forceGlobalInstance( self::$originalServices );
1048 $currentServices->destroy();
1075 $services = MediaWikiServices::getInstance();
1076 $services->resetServiceForTesting(
'ContentLanguage' );
1098 if ( is_string( $newPerms ) ) {
1099 $newPerms = [ $newPerms => [ $newKey => $newValue ] ];
1103 foreach ( $newPerms
as $group => $permissions ) {
1104 foreach ( $permissions
as $key =>
$value ) {
1105 $newPermissions[$group][$key] =
$value;
1109 $this->
setMwGlobals(
'wgGroupPermissions', $newPermissions );
1118 protected function setLogger( $channel, LoggerInterface $logger ) {
1122 $provider = LoggerFactory::getProvider();
1123 $wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
1124 $singletons = $wrappedProvider->singletons;
1126 if ( !isset( $this->loggers[$channel] ) ) {
1127 $this->loggers[$channel] = $singletons[
'loggers'][$channel] ??
null;
1129 $singletons[
'loggers'][$channel] = $logger;
1131 if ( !isset( $this->loggers[$channel] ) ) {
1132 $this->loggers[$channel] = $singletons[$channel] ??
null;
1134 $singletons[$channel] = $logger;
1136 throw new LogicException( __METHOD__ .
': setting a logger for ' . get_class( $provider )
1137 .
' is not implemented' );
1139 $wrappedProvider->singletons = $singletons;
1147 $provider = LoggerFactory::getProvider();
1148 $wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
1149 $singletons = $wrappedProvider->singletons;
1150 foreach ( $this->loggers
as $channel => $logger ) {
1152 if ( $logger ===
null ) {
1153 unset( $singletons[
'loggers'][$channel] );
1155 $singletons[
'loggers'][$channel] = $logger;
1158 if ( $logger ===
null ) {
1159 unset( $singletons[$channel] );
1161 $singletons[$channel] = $logger;
1165 $wrappedProvider->singletons = $singletons;
1166 $this->loggers = [];
1202 $rc =
new ReflectionClass( $this );
1203 return (
bool)preg_match(
'/@group +Database/im', $rc->getDocComment() );
1224 $text =
'Sample page for unit test.',
1229 throw new MWException(
'When testing which pages, the test cases\'s needsDB()' .
1230 ' method should return true. Use @group Database or $this->tablesUsed.' );
1233 if ( is_string( $pageName ) ) {
1240 $user = static::getTestSysop()->getUser();
1242 $comment = __METHOD__ .
': Sample page for unit test.';
1249 'id' => $page->getId(),
1287 if ( $this->db->getType() ==
'oracle' ) {
1288 # Insert 0 user to prevent FK violations
1290 if ( !$this->db->selectField(
'user',
'1', [
'user_id' => 0 ] ) ) {
1291 $this->db->insert(
'user', [
1293 'user_name' =>
'Anonymous' ], __METHOD__, [
'IGNORE' ] );
1296 # Insert 0 page to prevent FK violations
1298 if ( !$this->db->selectField(
'page',
'1', [
'page_id' => 0 ] ) ) {
1299 $this->db->insert(
'page', [
1301 'page_namespace' => 0,
1302 'page_title' =>
' ',
1303 'page_restrictions' =>
null,
1304 'page_is_redirect' => 0,
1307 'page_touched' => $this->db->timestamp(),
1309 'page_len' => 0 ], __METHOD__, [
'IGNORE' ] );
1318 $user = static::getTestSysop()->getUser();
1322 if ( $page->getId() == 0 ) {
1323 $page->doEditContent(
1338 if ( session_id() !==
'' ) {
1339 session_write_close();
1357 if ( !self::$dbSetup ) {
1361 Hooks::run(
'UnitTestsBeforeDatabaseTeardown' );
1370 MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->closeAll();
1373 self::$oldTablePrefix =
false;
1374 self::$dbSetup =
false;
1392 if ( $prefix ===
null ) {
1401 if ( !isset(
$db->_originalTablePrefix ) ) {
1404 if ( $oldPrefix === $prefix ) {
1412 $dbClone->useTemporaryTables( self::$useTemporaryTables );
1414 $dbClone->cloneTableStructure();
1417 $db->_originalTablePrefix = $oldPrefix;
1436 if ( self::isUsingExternalStoreDB() ) {
1467 if ( self::$dbSetup ) {
1473 'Cannot run unit tests, the database prefix is already "' . $prefix .
'"' );
1479 self::$dbSetup =
true;
1481 if ( !self::setupDatabaseWithTestPrefix(
$db, $prefix ) ) {
1488 $db->
query(
'BEGIN FILL_WIKI_INFO; END;', __METHOD__ );
1491 Hooks::run(
'UnitTestsAfterDatabaseSetup', [
$db, $prefix ] );
1502 foreach ( $connections
as $dbw ) {
1520 foreach ( $defaultArray
as $url ) {
1521 if ( strpos( $url,
'DB://' ) === 0 ) {
1522 list( $proto, $cluster ) = explode(
'://', $url, 2 );
1525 $dbws[] = $externalStoreDB->getMaster( $cluster );
1544 foreach ( $defaultArray
as $url ) {
1545 if ( strpos( $url,
'DB://' ) === 0 ) {
1561 throw new LogicException(
1562 'Trying to delete mock tables, but table prefix does not indicate a mock database.'
1606 $tablesToDrop = array_merge( $oldOverrides[
'create'], $oldOverrides[
'alter'] );
1610 $tablesToRestore = array_merge( $tablesToDrop, $oldOverrides[
'drop'] );
1611 $tablesToRestore = array_intersect( $originalTables, $tablesToRestore );
1613 if ( $tablesToDrop ) {
1617 if ( $tablesToRestore ) {
1622 $this->
resetDB( $db, $tablesToRestore );
1635 if ( $oldOverrides[
'alter'] || $oldOverrides[
'create'] || $oldOverrides[
'drop'] ) {
1637 unset(
$db->_schemaOverrides );
1643 $extraKeys = array_diff(
1644 array_keys( $overrides ),
1645 array_keys( self::$schemaOverrideDefaults )
1649 throw new InvalidArgumentException(
1650 'Schema override contains extra keys: ' . var_export( $extraKeys,
true )
1654 if ( !$overrides[
'scripts'] ) {
1659 if ( !$overrides[
'create'] && !$overrides[
'drop'] && !$overrides[
'alter'] ) {
1660 throw new InvalidArgumentException(
1661 'Schema override scripts given, but no tables are declared to be '
1662 .
'created, dropped or altered.'
1670 $tablesToDrop = array_intersect( $originalTables, $overrides[
'create'] );
1672 if ( $tablesToDrop ) {
1677 foreach ( $overrides[
'scripts']
as $script ) {
1689 $db->_schemaOverrides = $overrides;
1693 return self::$useTemporaryTables
1694 ? preg_replace(
'/\bCREATE\s+TABLE\b/i',
'CREATE TEMPORARY TABLE', $cmd )
1709 $db->
query(
"DROP TABLE IF EXISTS $tbl", __METHOD__ );
1720 if ( !isset(
$db->_originalTablePrefix ) ) {
1721 throw new LogicException(
'No original table prefix know, cannot list tables!' );
1724 $originalTables =
$db->
listTables(
$db->_originalTablePrefix, __METHOD__ );
1726 $unittestPrefixRegex =
'/^' . preg_quote( $this->
dbPrefix(),
'/' ) .
'/';
1727 $originalPrefixRegex =
'/^' . preg_quote(
$db->_originalTablePrefix,
'/' ) .
'/';
1729 $originalTables = array_filter(
1731 function ( $pt )
use ( $unittestPrefixRegex ) {
1732 return !preg_match( $unittestPrefixRegex, $pt );
1736 $originalTables = array_map(
1737 function ( $pt )
use ( $originalPrefixRegex ) {
1738 return preg_replace( $originalPrefixRegex,
'', $pt );
1743 return array_unique( $originalTables );
1757 if ( !isset(
$db->_originalTablePrefix ) ) {
1758 throw new LogicException(
'No original table prefix know, cannot restore tables!' );
1767 $dbClone->cloneTableStructure();
1778 $userTables = [
'user',
'user_groups',
'user_properties',
'actor' ];
1780 'page',
'revision',
'ip_changes',
'revision_comment_temp',
'comment',
'archive',
1781 'revision_actor_temp',
'slots',
'content',
'content_models',
'slot_roles',
1783 $coreDBDataTables = array_merge( $userTables, $pageTables );
1786 if ( array_intersect(
$tablesUsed, $userTables ) ) {
1794 $wgUser->clearInstanceCache( $wgUser->mFrom );
1796 if ( array_intersect(
$tablesUsed, $pageTables ) ) {
1817 if ( array_intersect(
$tablesUsed, $coreDBDataTables ) ) {
1843 $truncate = in_array(
$db->
getType(), [
'oracle',
'mysql' ] );
1848 $db->
delete( $tableName,
'*', __METHOD__ );
1851 if (
$db instanceof DatabasePostgres ||
$db instanceof DatabaseSqlite ) {
1853 $db->resetSequenceForTable( $tableName, __METHOD__ );
1857 if ( $tableName ===
'site_stats' ) {
1863 $tableName = substr( $tableName, strlen( $prefix ) );
1867 return strpos( $table, self::DB_PREFIX ) !== 0;
1882 static $viewListCache =
null;
1883 if ( $viewListCache ===
null ) {
1889 array_walk(
$tables, [ __CLASS__,
'unprefixTable' ], $prefix );
1892 $tables = array_filter(
$tables, [ __CLASS__,
'isNotUnittest' ] );
1897 unset(
$tables[
'searchindex_content'] );
1898 unset(
$tables[
'searchindex_segdir'] );
1899 unset(
$tables[
'searchindex_segments'] );
1915 if ( $this->db->getType() ===
'sqlite' ) {
1919 throw new RuntimeException(
1920 'Setting up a secondary database connection with test data is currently not'
1921 .
'with SQLite. You may want to use markTestSkippedIfDbType() to bypass this issue.'
1928 $res =
$source->select( $table,
'*', [], __METHOD__ );
1931 foreach (
$res as $row ) {
1932 $allRows[] = (
array)$row;
1935 $target->
insert( $table, $allRows, __METHOD__, [
'IGNORE' ] );
1945 throw new MWException( $this->db->getType() .
" is not currently supported for unit testing." );
1955 return $this->cliArgs[$offset] ??
null;
1964 $this->cliArgs[$offset] =
$value;
1975 Wikimedia\suppressWarnings();
1977 Wikimedia\restoreWarnings();
2004 throw new MWException(
'When testing database state, the test cases\'s needDB()' .
2005 ' method should return true. Use @group Database or $this->tablesUsed.' );
2015 $options + [
'ORDER BY' => $fields ],
2022 foreach ( $expectedRows
as $expected ) {
2023 $r =
$res->fetchRow();
2027 $this->assertNotEmpty( $r,
"row #$i missing" );
2029 $this->assertEquals( $expected, $r,
"row #$i mismatches" );
2032 $r =
$res->fetchRow();
2035 $this->assertFalse( $r,
"found extra row (after #$i)" );
2051 function ( $element ) {
2052 return [ $element ];
2071 $ordered =
false, $named =
false
2079 $expected = array_values( $expected );
2080 $actual = array_values( $actual );
2083 call_user_func_array(
2084 [ $this,
'assertEquals' ],
2085 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
2102 $expected = str_replace(
'>',
">\n", $expected );
2103 $actual = str_replace(
'>',
">\n", $actual );
2105 $this->assertEquals( $expected, $actual, $msg );
2118 function ( $a, $b ) {
2134 if ( !is_array( $r ) ) {
2138 foreach ( $r
as $k => $v ) {
2139 if ( is_string( $k ) ) {
2159 if ( $actual ===
$value ) {
2160 $this->assertTrue(
true, $message );
2178 if ( class_exists(
$type ) || interface_exists(
$type ) ) {
2179 $this->assertInstanceOf(
$type, $actual, $message );
2181 $this->assertInternalType(
$type, $actual, $message );
2214 static $wikitextNS =
null;
2215 if ( $wikitextNS !==
null ) {
2235 $talk = array_filter(
$namespaces,
function ( $ns ) {
2257 throw new MWException(
"No namespace defaults to wikitext!" );
2269 # This check may also protect against code injection in
2270 # case of broken installations.
2271 Wikimedia\suppressWarnings();
2273 Wikimedia\restoreWarnings();
2275 if ( !$haveDiff3 ) {
2276 $this->markTestSkipped(
"Skip test, since diff3 is not configured" );
2289 $loaded = extension_loaded( $extName );
2291 $this->markTestSkipped(
"PHP extension '$extName' is not loaded, skipping." );
2304 if ( $this->db->getType() ===
$type ) {
2305 $this->markTestSkipped(
"The $type database type isn't supported for this test" );
2341 $createIfMissing =
false,
2344 if ( $createIfMissing ) {
2345 if ( !file_exists( $fileName ) ) {
2346 file_put_contents( $fileName, $actualData );
2347 $this->markTestSkipped(
'Data file $fileName does not exist' );
2350 self::assertFileExists( $fileName );
2352 self::assertEquals( file_get_contents( $fileName ), $actualData, $msg );
2369 throw new MWException(
'When testing which pages, the test cases\'s needsDB()' .
2370 ' method should return true. Use @group Database or $this->tablesUsed.' );
2390 if ( is_int(
$rev ) ) {
2397 'comment' => $comment,
static clear()
Clear all the cached instances.
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action, or null $user:User who performed the tagging when the tagging is subsequent to the action, or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy:boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
return true to allow those checks to and false if checking is done & $user
WebRequest clone which takes values from a provided array.
$wgNamespaceContentModels
Associative array mapping namespace IDs to the name of the content model pages in that namespace shou...
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
static clearCaches()
Intended for tests that may change configuration in a way that invalidates caches.
processing should stop and the error should be shown to the user * false
static getValidNamespaces()
Returns an array of the namespaces (by integer id) that exist on the wiki.
static resetGetDefaultOptionsForTestsOnly()
Reset the process cache of default user options.
static newFromId( $id, $flags=0)
Load a page revision from a given revision ID number.
static isTalk( $index)
Is the given namespace a talk namespace?
Provides a fallback sequence for Config objects.
wfMkdirParents( $dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
if(!isset( $args[0])) $lang
A Config instance which stores all settings as a member variable.
$wgDiff3
Path to the GNU diff3 utility.
static setLBFactoryTriggers(LBFactory $LBFactory, Config $config)
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 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name '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. '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 '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:Array with elements of the form "language:title" in the order that they will be output. & $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 since 1.28! 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
this hook is for auditing only RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist & $tables
static destroySingletons()
Destroy the singleton instances.
static clearPendingUpdates()
Clear all pending updates without performing them.
const CONTENT_MODEL_WIKITEXT
array $wgDefaultExternalStore
The place to put new revisions, false to put them in the local text table.
static getContentNamespaces()
Get a list of all namespace indices which are considered to contain content.
$wgDBprefix
Table name prefix.
$wgJobClasses['replaceText']
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
Wraps the user object, so we can also retain full access to properties like password if we log in via...
static destroySingleton()
Destroy the singleton instance.
static clearCaches()
Clear internal caches.
Interface for configuration instances.
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
namespace and then decline to actually register it file or subcat img or subcat $title
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password 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
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
static clearLog()
Clears internal log array and deprecation tracking.
Content object for wiki text pages.
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
static createList( $typeName, IContextSource $context, Title $title, array $ids)
Instantiate the appropriate list class for a given list of IDs.
and give any other recipients of the Program a copy of this License along with the Program You may charge a fee for the physical act of transferring a and you may at your option offer warranty protection in exchange for a fee You may modify your copy or copies of the Program or any portion of thus forming a work based on the and copy and distribute such modifications or work under the terms of Section provided that you also meet all of these that in whole or in part contains or is derived from the Program or any part to be licensed as a whole at no charge to all third parties under the terms of this License c If the modified program normally reads commands interactively when run
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
static makeContent( $text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Allows to change the fields on the form that will be generated $name
static resetMain()
Resets singleton returned by getMain().
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
MediaWiki Logger LegacySpi
makeConfig( $name)
Create a given Config using the registered callback for $name.
static getMain()
Get the RequestContext object associated with the main request.
useTemporaryTables( $u=true)
Set whether to use temporary tables or not.
unserialize( $serialized)
MediaWiki Logger MonologSpi
wfTempDir()
Tries to get the system directory for temporary files.
static getStoreObject( $proto, array $params=[])
Get an external store object of the given type, with the given parameters.
static singleton( $domain=false)
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 & $options
static changePrefix( $prefix)
Change the table prefix on all open DB connections.
static resetIdByNameCache()
Reset the cache used in idFromName().
wfRecursiveRemoveDir( $dir)
Remove a directory and all its content.
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
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
Factory class to create Config objects.
MediaWiki Logger LoggerFactory implements a PSR[0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method. MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances. The "Spi" in MediaWiki\Logger\Spi stands for "service provider interface". An SPI is an API intended to be implemented or extended by a third party. This software design pattern is intended to enable framework extension and replaceable components. It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki. The service provider interface allows the backend logging library to be implemented in multiple ways. The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime. This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance. Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
$wgGroupPermissions['sysop']['replacetext']
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
static getMutableTestUser( $testName, $groups=[])
Get a TestUser object that the caller may modify.
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response 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
if(! $wgDBerrorLogTZ) $wgRequest
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
static doPlaceholderInit()
Insert a dummy row with all zeroes if no row is present.
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 run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
wfGetCaller( $level=2)
Get the name of the function which called this function wfGetCaller( 1 ) is the function with the wfG...
Advanced database interface for IDatabase handles that include maintenance methods.
Internationalisation code.
$wgSQLMode
SQL Mode - default is turning off all modes, including strict, if set.
static clear()
Clear the registry.