7use Psr\Log\LoggerInterface;
11use Wikimedia\TestingAccessWrapper;
18 use MediaWikiCoversValidator;
19 use PHPUnit4And6Compat;
148 parent::__construct(
$name, $data, $dataName );
150 $this->backupGlobals =
false;
151 $this->backupStaticAttributes =
false;
157 if ( isset( $this->called[
'setUp'] ) && !isset( $this->called[
'tearDown'] ) ) {
158 throw new MWException( static::class .
"::tearDown() must call parent::tearDown()" );
163 parent::setUpBeforeClass();
166 if ( !self::$originalServices ) {
167 self::$originalServices = MediaWikiServices::getInstance();
180 return TestUserRegistry::getImmutableTestUser( $groups );
192 return TestUserRegistry::getMutableTestUser( __CLASS__, $groups );
204 return self::getTestUser( [
'sysop',
'bureaucrat' ] );
221 throw new MWException(
'When testing which pages, the test cases\'s needsDB()' .
222 ' method should return true. Use @group Database or $this->tablesUsed.' );
227 $page = WikiPage::factory(
$title );
229 if ( !$page->exists() ) {
230 $user = self::getTestSysop()->getUser();
231 $page->doEditContent(
257 throw new MWException(
'When testing which pages, the test cases\'s needsDB()' .
258 ' method should return true. Use @group Database or $this->tablesUsed.' );
263 $page = WikiPage::factory(
$title );
265 if ( $page->exists() ) {
266 $page->doDeleteArticle(
'Testing' );
288 Config $baseConfig =
null,
289 Config $customOverrides =
null
293 if ( !$baseConfig ) {
294 $baseConfig = self::$originalServices->getBootstrapConfig();
301 $hashCache = [
'class' => HashBagOStuff::class,
'reportDupes' =>
false ];
307 'apcu' => $hashCache,
308 'wincache' => $hashCache,
309 ] + $baseConfig->get(
'ObjectCaches' );
311 $defaultOverrides->set(
'ObjectCaches', $objectCaches );
312 $defaultOverrides->set(
'MainCacheType',
CACHE_NONE );
313 $defaultOverrides->set(
'JobTypeConf', [
'default' => [
'class' => JobQueueMemory::class ] ] );
316 $defaultOverrides->set(
'PasswordDefault',
'A' );
318 $testConfig = $customOverrides
319 ?
new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
320 :
new MultiConfig( [ $defaultOverrides, $baseConfig ] );
333 array $configurations
339 $namesToClone = array_diff(
341 array_keys( $configurations )
344 foreach ( $namesToClone
as $name ) {
348 foreach ( $configurations
as $name => $config ) {
349 $factory->register(
$name, $config );
364 JobQueueGroup::singleton()->get(
$type )->delete();
366 JobQueueGroup::destroySingletons();
368 ObjectCache::clear();
370 DeferredUpdates::clearPendingUpdates();
373 RequestContext::resetMain();
374 if ( session_id() !==
'' ) {
375 session_write_close();
380 MediaWiki\Session\SessionManager::resetCache();
383 public function run( PHPUnit_Framework_TestResult
$result =
null ) {
385 $this->cliArgs =
$result->getMediaWikiCliArgs();
391 get_class( $this ) .
' apparently needsDB but is not in the Database group'
395 $needsResetDB =
false;
396 if ( !self::$dbSetup || $this->
needsDB() ) {
399 self::$useTemporaryTables = !$this->
getCliArg(
'use-normal-tables' );
400 self::$reuseDB = $this->
getCliArg(
'reuse-db' );
406 if ( !self::$dbSetup ) {
416 $this->
resetDB( $this->db, $this->tablesUsed );
421 $needsResetDB =
true;
427 $this->overriddenServices = [];
429 if ( $needsResetDB ) {
430 $this->
resetDB( $this->db, $this->tablesUsed );
433 self::restoreMwServices();
434 $this->localServices =
null;
444 $class = static::class;
446 $first = !isset( $this->db->_hasDataForTestClass )
447 || $this->db->_hasDataForTestClass !== $class;
449 $this->db->_hasDataForTestClass = $class;
459 return self::$useTemporaryTables;
472 $fileName = tempnam(
wfTempDir(),
'MW_PHPUnit_' . static::class .
'_' );
473 $this->tmpFiles[] = $fileName;
503 $this->called[
'setUp'] =
true;
505 $this->phpErrorLevel = intval( ini_get(
'error_reporting' ) );
507 $this->overriddenServices = [];
510 foreach ( $this->tmpFiles
as $fileName ) {
511 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
513 } elseif ( is_dir( $fileName ) ) {
518 if ( $this->
needsDB() && $this->db ) {
520 while ( $this->db->trxLevel() > 0 ) {
521 $this->db->rollback( __METHOD__,
'flush' );
524 if ( $this->db->getType() ===
'mysql' ) {
525 $this->db->query(
"SET sql_mode = 'STRICT_ALL_TABLES'", __METHOD__ );
530 self::resetNonServiceCaches();
534 $lbFactory = $this->localServices->getDBLoadBalancerFactory();
537 ob_start(
'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
541 $this->tmpFiles = array_merge( $this->tmpFiles, (
array)$files );
548 if ( isset(
$status[
'name'] ) &&
549 $status[
'name'] ===
'MediaWikiTestCase::wfResetOutputBuffersBarrier'
554 $this->called[
'tearDown'] =
true;
556 foreach ( $this->tmpFiles
as $fileName ) {
557 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
559 } elseif ( is_dir( $fileName ) ) {
564 if ( $this->
needsDB() && $this->db ) {
566 while ( $this->db->trxLevel() > 0 ) {
567 $this->db->rollback( __METHOD__,
'flush' );
569 if ( $this->db->getType() ===
'mysql' ) {
570 $this->db->query(
"SET sql_mode = " . $this->db->addQuotes(
$wgSQLMode ),
578 foreach ( $this->mwGlobals
as $key =>
$value ) {
581 foreach ( $this->mwGlobalsToUnset
as $value ) {
588 array_key_exists(
'wgExtraNamespaces', $this->mwGlobals ) ||
589 in_array(
'wgExtraNamespaces', $this->mwGlobalsToUnset )
593 $this->mwGlobals = [];
594 $this->mwGlobalsToUnset = [];
598 RequestContext::resetMain();
599 if ( session_id() !==
'' ) {
600 session_write_close();
604 MediaWiki\Session\SessionManager::resetCache();
605 MediaWiki\Auth\AuthManager::resetCache();
610 ini_set(
'error_reporting', $this->phpErrorLevel );
612 $oldHex = strtoupper( dechex( $this->phpErrorLevel ) );
614 $message =
"PHP error_reporting setting was left dirty: "
615 .
"was 0x$oldHex before test, 0x$newHex after test!";
617 $this->fail( $message );
632 $this->assertArrayHasKey(
'setUp', $this->called,
633 static::class .
'::setUp() must call parent::setUp()'
647 if ( !$this->localServices ) {
648 throw new Exception( __METHOD__ .
' must be called after MediaWikiTestCase::run()' );
651 if ( $this->localServices !== MediaWikiServices::getInstance() ) {
652 throw new Exception( __METHOD__ .
' will not work because the global MediaWikiServices '
653 .
'instance has been replaced by test code.' );
656 $this->overriddenServices[] =
$name;
658 $this->localServices->disableService(
$name );
659 $this->localServices->redefineService(
661 function ()
use ( $object ) {
666 if (
$name ===
'ContentLanguage' ) {
707 if ( is_string( $pairs ) ) {
708 $pairs = [ $pairs =>
$value ];
711 if ( isset( $pairs[
'wgContLang'] ) ) {
713 'No setting $wgContLang, use setContentLang() or setService( \'ContentLanguage\' )'
727 foreach ( $pairs
as $key =>
$value ) {
731 if ( array_key_exists(
'wgExtraNamespaces', $pairs ) ) {
743 $original = ini_get(
$name );
744 $this->iniSettings[
$name] = $original;
753 if ( !$this->localServices ) {
754 throw new Exception( __METHOD__ .
' must be called after MediaWikiTestCase::run()' );
757 if ( $this->localServices !== MediaWikiServices::getInstance() ) {
758 throw new Exception( __METHOD__ .
' will not work because the global MediaWikiServices '
759 .
'instance has been replaced by test code.' );
762 MWNamespace::clearCaches();
763 Language::clearCaches();
767 $this->localServices->resetServiceForTesting(
'TitleFormatter' );
768 $this->localServices->resetServiceForTesting(
'TitleParser' );
769 $this->localServices->resetServiceForTesting(
'_MediaWikiTitleCodec' );
784 if ( is_array(
$value ) ) {
786 if ( !is_scalar( $subValue ) && $subValue !==
null ) {
819 if ( is_string( $globalKeys ) ) {
820 $globalKeys = [ $globalKeys ];
823 foreach ( $globalKeys
as $globalKey ) {
828 !array_key_exists( $globalKey, $this->mwGlobals ) &&
829 !array_key_exists( $globalKey, $this->mwGlobalsToUnset )
831 if ( !array_key_exists( $globalKey,
$GLOBALS ) ) {
832 $this->mwGlobalsToUnset[$globalKey] = $globalKey;
838 if ( self::canShallowCopy(
$GLOBALS[$globalKey] ) ) {
839 $this->mwGlobals[$globalKey] =
$GLOBALS[$globalKey];
847 $this->mwGlobals[$globalKey] = clone
$GLOBALS[$globalKey];
852 $this->mwGlobals[$globalKey] =
$GLOBALS[$globalKey];
856 }
catch ( Exception
$e ) {
857 $this->mwGlobals[$globalKey] =
$GLOBALS[$globalKey];
871 if ( $var instanceof Closure ) {
874 if ( !is_array( $var ) || $maxDepth === 0 ) {
906 throw new MWException(
"MW global $name is not an array." );
911 foreach ( $values
as $k => $v ) {
937 if ( $this->overriddenServices ) {
939 'The following services were set and are now being unset by overrideMwServices: ' .
940 implode(
', ', $this->overriddenServices )
943 $newInstance = self::installMockMwServices( $configOverrides );
945 if ( $this->localServices ) {
946 $this->localServices->destroy();
949 $this->localServices = $newInstance;
952 $newInstance->redefineService(
$name, $callback );
977 if ( !self::$originalServices ) {
978 self::$originalServices = MediaWikiServices::getInstance();
981 if ( !$configOverrides ) {
985 $oldConfigFactory = self::$originalServices->getConfigFactory();
986 $oldLoadBalancerFactory = self::$originalServices->getDBLoadBalancerFactory();
988 $testConfig = self::makeTestConfig(
null, $configOverrides );
993 $wiringFiles = $testConfig->get(
'ServiceWiringFiles' );
994 $newServices->loadWiringFiles( $wiringFiles );
997 Hooks::run(
'MediaWikiServices', [ $newServices ] );
1001 $bootstrapConfig = $newServices->getBootstrapConfig();
1002 $newServices->resetServiceForTesting(
'ConfigFactory' );
1003 $newServices->redefineService(
1005 self::makeTestConfigFactoryInstantiator(
1007 [
'main' => $bootstrapConfig ]
1010 $newServices->resetServiceForTesting(
'DBLoadBalancerFactory' );
1011 $newServices->redefineService(
1012 'DBLoadBalancerFactory',
1014 return $oldLoadBalancerFactory;
1018 MediaWikiServices::forceGlobalInstance( $newServices );
1019 return $newServices;
1034 if ( !self::$originalServices ) {
1038 $currentServices = MediaWikiServices::getInstance();
1040 if ( self::$originalServices === $currentServices ) {
1044 MediaWikiServices::forceGlobalInstance( self::$originalServices );
1045 $currentServices->destroy();
1055 RequestContext::getMain()->setLanguage(
$lang );
1056 $this->
setMwGlobals(
'wgLang', RequestContext::getMain()->getLanguage() );
1072 $services = MediaWikiServices::getInstance();
1073 $services->resetServiceForTesting(
'ContentLanguage' );
1095 if ( is_string( $newPerms ) ) {
1096 $newPerms = [ $newPerms => [ $newKey => $newValue ] ];
1100 foreach ( $newPerms
as $group => $permissions ) {
1101 foreach ( $permissions
as $key =>
$value ) {
1102 $newPermissions[$group][$key] =
$value;
1106 $this->
setMwGlobals(
'wgGroupPermissions', $newPermissions );
1115 protected function setLogger( $channel, LoggerInterface $logger ) {
1119 $provider = LoggerFactory::getProvider();
1120 $wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
1121 $singletons = $wrappedProvider->singletons;
1123 if ( !isset( $this->loggers[$channel] ) ) {
1124 $this->loggers[$channel] = $singletons[
'loggers'][$channel] ??
null;
1126 $singletons[
'loggers'][$channel] = $logger;
1127 } elseif ( $provider instanceof
LegacySpi ) {
1128 if ( !isset( $this->loggers[$channel] ) ) {
1129 $this->loggers[$channel] = $singletons[$channel] ??
null;
1131 $singletons[$channel] = $logger;
1133 throw new LogicException( __METHOD__ .
': setting a logger for ' . get_class( $provider )
1134 .
' is not implemented' );
1136 $wrappedProvider->singletons = $singletons;
1144 $provider = LoggerFactory::getProvider();
1145 $wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
1146 $singletons = $wrappedProvider->singletons;
1147 foreach ( $this->loggers
as $channel => $logger ) {
1149 if ( $logger ===
null ) {
1150 unset( $singletons[
'loggers'][$channel] );
1152 $singletons[
'loggers'][$channel] = $logger;
1154 } elseif ( $provider instanceof
LegacySpi ) {
1155 if ( $logger ===
null ) {
1156 unset( $singletons[$channel] );
1158 $singletons[$channel] = $logger;
1162 $wrappedProvider->singletons = $singletons;
1163 $this->loggers = [];
1171 return self::getTestPrefixFor( $this->db );
1180 return $db->
getType() ==
'oracle' ? self::ORA_DB_PREFIX : self::DB_PREFIX;
1199 $rc =
new ReflectionClass( $this );
1200 return (
bool)preg_match(
'/@group +Database/im', $rc->getDocComment() );
1221 $text =
'Sample page for unit test.',
1226 throw new MWException(
'When testing which pages, the test cases\'s needsDB()' .
1227 ' method should return true. Use @group Database or $this->tablesUsed.' );
1230 if ( is_string( $pageName ) ) {
1231 $title = Title::newFromText( $pageName, $namespace );
1237 $user = static::getTestSysop()->getUser();
1239 $comment = __METHOD__ .
': Sample page for unit test.';
1241 $page = WikiPage::factory(
$title );
1242 $page->doEditContent( ContentHandler::makeContent( $text,
$title ), $comment, 0,
false,
$user );
1246 'id' => $page->getId(),
1284 if ( $this->db->getType() ==
'oracle' ) {
1285 # Insert 0 user to prevent FK violations
1287 if ( !$this->db->selectField(
'user',
'1', [
'user_id' => 0 ] ) ) {
1288 $this->db->insert(
'user', [
1290 'user_name' =>
'Anonymous' ], __METHOD__, [
'IGNORE' ] );
1293 # Insert 0 page to prevent FK violations
1295 if ( !$this->db->selectField(
'page',
'1', [
'page_id' => 0 ] ) ) {
1296 $this->db->insert(
'page', [
1298 'page_namespace' => 0,
1299 'page_title' =>
' ',
1300 'page_restrictions' =>
null,
1301 'page_is_redirect' => 0,
1304 'page_touched' => $this->db->timestamp(),
1306 'page_len' => 0 ], __METHOD__, [
'IGNORE' ] );
1315 $user = static::getTestSysop()->getUser();
1318 $page = WikiPage::factory( Title::newFromText(
'UTPage' ) );
1319 if ( $page->getId() == 0 ) {
1320 $page->doEditContent(
1329 JobQueueGroup::singleton()->get(
'htmlCacheUpdate' )->delete();
1331 JobQueueGroup::singleton()->get(
'recentChangesUpdate' )->delete();
1335 if ( session_id() !==
'' ) {
1336 session_write_close();
1354 if ( !self::$dbSetup ) {
1358 Hooks::run(
'UnitTestsBeforeDatabaseTeardown' );
1362 JobQueueGroup::singleton()->get(
$type )->delete();
1367 self::$oldTablePrefix =
false;
1368 self::$dbSetup =
false;
1386 if ( $prefix ===
null ) {
1387 $prefix = self::getTestPrefixFor( $db );
1390 if ( ( $db->
getType() ==
'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
1395 if ( !isset( $db->_originalTablePrefix ) ) {
1398 if ( $oldPrefix === $prefix ) {
1400 $oldPrefix = self::$oldTablePrefix;
1404 $tablesCloned = self::listTables( $db );
1405 $dbClone =
new CloneDatabase( $db, $tablesCloned, $prefix, $oldPrefix );
1406 $dbClone->useTemporaryTables( self::$useTemporaryTables );
1408 $dbClone->cloneTableStructure();
1411 $db->_originalTablePrefix = $oldPrefix;
1428 self::setupTestDB( $this->db, $testPrefix );
1430 if ( self::isUsingExternalStoreDB() ) {
1431 self::setupExternalStoreTestDBs( $testPrefix );
1461 if ( self::$dbSetup ) {
1467 'Cannot run unit tests, the database prefix is already "' . $prefix .
'"' );
1473 self::$dbSetup =
true;
1475 if ( !self::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1481 if ( $db->
getType() ==
'oracle' ) {
1482 $db->
query(
'BEGIN FILL_WIKI_INFO; END;', __METHOD__ );
1485 Hooks::run(
'UnitTestsAfterDatabaseSetup', [ $db, $prefix ] );
1495 $connections = self::getExternalStoreDatabaseConnections();
1496 foreach ( $connections
as $dbw ) {
1497 self::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1511 $externalStoreDB = ExternalStore::getStoreObject(
'DB' );
1514 foreach ( $defaultArray
as $url ) {
1515 if ( strpos( $url,
'DB://' ) === 0 ) {
1516 list( $proto, $cluster ) = explode(
'://', $url, 2 );
1519 $dbws[] = $externalStoreDB->getMaster( $cluster );
1538 foreach ( $defaultArray
as $url ) {
1539 if ( strpos( $url,
'DB://' ) === 0 ) {
1555 throw new LogicException(
1556 'Trying to delete mock tables, but table prefix does not indicate a mock database.'
1596 $oldOverrides = $oldOverrides + self::$schemaOverrideDefaults;
1600 $tablesToDrop = array_merge( $oldOverrides[
'create'], $oldOverrides[
'alter'] );
1604 $tablesToRestore = array_merge( $tablesToDrop, $oldOverrides[
'drop'] );
1605 $tablesToRestore = array_intersect( $originalTables, $tablesToRestore );
1607 if ( $tablesToDrop ) {
1611 if ( $tablesToRestore ) {
1623 $oldOverrides = $db->_schemaOverrides ?? self::$schemaOverrideDefaults;
1625 if ( $oldOverrides[
'alter'] || $oldOverrides[
'create'] || $oldOverrides[
'drop'] ) {
1632 $extraKeys = array_diff(
1633 array_keys( $overrides ),
1634 array_keys( self::$schemaOverrideDefaults )
1638 throw new InvalidArgumentException(
1639 'Schema override contains extra keys: ' . var_export( $extraKeys,
true )
1643 if ( !$overrides[
'scripts'] ) {
1648 if ( !$overrides[
'create'] && !$overrides[
'drop'] && !$overrides[
'alter'] ) {
1649 throw new InvalidArgumentException(
1650 'Schema override scripts given, but no tables are declared to be '
1651 .
'created, dropped or altered.'
1659 $tablesToDrop = array_intersect( $originalTables, $overrides[
'create'] );
1661 if ( $tablesToDrop ) {
1666 foreach ( $overrides[
'scripts']
as $script ) {
1678 $db->_schemaOverrides = $overrides;
1682 return self::$useTemporaryTables
1683 ? preg_replace(
'/\bCREATE\s+TABLE\b/i',
'CREATE TEMPORARY TABLE', $cmd )
1698 $db->
query(
"DROP TABLE IF EXISTS $tbl", __METHOD__ );
1710 if ( !isset( $db->_originalTablePrefix ) ) {
1711 throw new LogicException(
'No original table prefix know, cannot list tables!' );
1714 $originalTables = $db->
listTables( $db->_originalTablePrefix, __METHOD__ );
1715 if ( $prefix ===
'unprefixed' ) {
1716 $originalPrefixRegex =
'/^' . preg_quote( $db->_originalTablePrefix,
'/' ) .
'/';
1717 $originalTables = array_map(
1718 function ( $pt )
use ( $originalPrefixRegex ) {
1719 return preg_replace( $originalPrefixRegex,
'', $pt );
1725 return $originalTables;
1739 if ( !isset( $db->_originalTablePrefix ) ) {
1740 throw new LogicException(
'No original table prefix know, cannot restore tables!' );
1747 $dbClone->useTemporaryTables( self::$useTemporaryTables );
1749 $dbClone->cloneTableStructure();
1760 $userTables = [
'user',
'user_groups',
'user_properties',
'actor' ];
1762 'page',
'revision',
'ip_changes',
'revision_comment_temp',
'comment',
'archive',
1763 'revision_actor_temp',
'slots',
'content',
'content_models',
'slot_roles',
1765 $coreDBDataTables = array_merge( $userTables, $pageTables );
1768 if ( array_intersect(
$tablesUsed, $userTables ) ) {
1770 TestUserRegistry::clear();
1772 if ( array_intersect(
$tablesUsed, $pageTables ) ) {
1793 if ( array_intersect(
$tablesUsed, $coreDBDataTables ) ) {
1819 $truncate = in_array(
$db->
getType(), [
'oracle',
'mysql' ] );
1824 $db->
delete( $tableName,
'*', __METHOD__ );
1827 if (
$db instanceof DatabasePostgres ||
$db instanceof DatabaseSqlite ) {
1829 $db->resetSequenceForTable( $tableName, __METHOD__ );
1833 if ( $tableName ===
'site_stats' ) {
1839 $tableName = substr( $tableName, strlen( $prefix ) );
1843 return strpos( $table, self::DB_PREFIX ) !== 0;
1857 if ( $db->
getType() ===
'mysql' ) {
1858 static $viewListCache =
null;
1859 if ( $viewListCache ===
null ) {
1860 $viewListCache = $db->
listViews(
null, __METHOD__ );
1865 array_walk(
$tables, [ __CLASS__,
'unprefixTable' ], $prefix );
1868 $tables = array_filter(
$tables, [ __CLASS__,
'isNotUnittest' ] );
1870 if ( $db->
getType() ==
'sqlite' ) {
1873 unset(
$tables[
'searchindex_content'] );
1874 unset(
$tables[
'searchindex_segdir'] );
1875 unset(
$tables[
'searchindex_segments'] );
1894 $res =
$source->select( $table,
'*', [], __METHOD__ );
1897 foreach (
$res as $row ) {
1898 $allRows[] = (
array)$row;
1901 $target->
insert( $table, $allRows, __METHOD__, [
'IGNORE' ] );
1910 if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
1911 throw new MWException( $this->db->getType() .
" is not currently supported for unit testing." );
1921 return $this->cliArgs[$offset] ??
null;
1930 $this->cliArgs[$offset] =
$value;
1941 Wikimedia\suppressWarnings();
1943 Wikimedia\restoreWarnings();
1970 throw new MWException(
'When testing database state, the test cases\'s needDB()' .
1971 ' method should return true. Use @group Database or $this->tablesUsed.' );
1981 $options + [
'ORDER BY' => $fields ],
1988 foreach ( $expectedRows
as $expected ) {
1989 $r =
$res->fetchRow();
1990 self::stripStringKeys( $r );
1993 $this->assertNotEmpty( $r,
"row #$i missing" );
1995 $this->assertEquals( $expected, $r,
"row #$i mismatches" );
1998 $r =
$res->fetchRow();
1999 self::stripStringKeys( $r );
2001 $this->assertFalse( $r,
"found extra row (after #$i)" );
2017 function ( $element ) {
2018 return [ $element ];
2037 $ordered =
false, $named =
false
2045 $expected = array_values( $expected );
2046 $actual = array_values( $actual );
2049 call_user_func_array(
2050 [ $this,
'assertEquals' ],
2051 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
2068 $expected = str_replace(
'>',
">\n", $expected );
2069 $actual = str_replace(
'>',
">\n", $actual );
2071 $this->assertEquals( $expected, $actual, $msg );
2084 function ( $a, $b ) {
2100 if ( !is_array( $r ) ) {
2104 foreach ( $r
as $k => $v ) {
2105 if ( is_string( $k ) ) {
2125 if ( $actual ===
$value ) {
2126 $this->assertTrue(
true, $message );
2144 if ( class_exists(
$type ) || interface_exists(
$type ) ) {
2145 $this->assertInstanceOf(
$type, $actual, $message );
2147 $this->assertInternalType(
$type, $actual, $message );
2180 static $wikitextNS =
null;
2181 if ( $wikitextNS !==
null ) {
2192 MWNamespace::getContentNamespaces(),
2194 MWNamespace::getValidNamespaces()
2201 $talk = array_filter(
$namespaces,
function ( $ns ) {
2202 return MWNamespace::isTalk( $ns );
2223 throw new MWException(
"No namespace defaults to wikitext!" );
2235 # This check may also protect against code injection in
2236 # case of broken installations.
2237 Wikimedia\suppressWarnings();
2239 Wikimedia\restoreWarnings();
2241 if ( !$haveDiff3 ) {
2242 $this->markTestSkipped(
"Skip test, since diff3 is not configured" );
2255 $loaded = extension_loaded( $extName );
2257 $this->markTestSkipped(
"PHP extension '$extName' is not loaded, skipping." );
2270 if ( $this->db->getType() ===
$type ) {
2271 $this->markTestSkipped(
"The $type database type isn't supported for this test" );
2307 $createIfMissing =
false,
2310 if ( $createIfMissing ) {
2311 if ( !file_exists( $fileName ) ) {
2312 file_put_contents( $fileName, $actualData );
2313 $this->markTestSkipped(
'Data file $fileName does not exist' );
2316 self::assertFileExists( $fileName );
2318 self::assertEquals( file_get_contents( $fileName ), $actualData, $msg );
2335 throw new MWException(
'When testing which pages, the test cases\'s needsDB()' .
2336 ' method should return true. Use @group Database or $this->tablesUsed.' );
2339 $title = Title::newFromText( $pageName, $defaultNs );
2340 $page = WikiPage::factory(
$title );
2342 return $page->doEditContent( ContentHandler::makeContent( $text,
$title ), $summary );
2356 if ( is_int(
$rev ) ) {
2360 'revision', RequestContext::getMain(),
$rev->getTitle(), [
$rev->getId() ]
2363 'comment' => $comment,
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.
$wgGroupPermissions
Permission keys given to users in each group.
$wgJobClasses
Maps jobs to their handlers; 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.
WebRequest clone which takes values from a provided array.
static destroySingleton()
Destroy the singleton instance.
A Config instance which stores all settings as a member variable.
Internationalisation code.
static setLBFactoryTriggers(LBFactory $LBFactory, Config $config)
Provides a fallback sequence for Config objects.
static createList( $typeName, IContextSource $context, Title $title, array $ids)
Instantiate the appropriate list class for a given list of IDs.
static newFromId( $id, $flags=0)
Load a page revision from a given revision ID number.
static doPlaceholderInit()
Insert a dummy row with all zeroes if no row is present.
Wraps the user object, so we can also retain full access to properties like password if we log in via...
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
static resetIdByNameCache()
Reset the cache used in idFromName().
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
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
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. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. '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. 'LanguageGetMagic':DEPRECATED since 1.16! 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: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
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
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
namespace and then decline to actually register it file or subcat img or subcat $title
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 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
Allows to change the fields on the form that will be generated $name
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
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
processing should stop and the error should be shown to the user * false
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
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
Interface for configuration instances.
Advanced database interface for IDatabase handles that include maintenance methods.
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.
sourceFile( $filename, callable $lineCallback=null, callable $resultCallback=null, $fname=false, callable $inputCallback=null)
Read and execute SQL commands from a file.
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))
if(!isset( $args[0])) $lang