<exclude-pattern>*/maintenance/storage/recompressTracked\.php</exclude-pattern>
<exclude-pattern>*/maintenance/storage/trackBlobs\.php</exclude-pattern>
<!-- Skip violations in some tests for now -->
+ <exclude-pattern>*/tests/phpunit/unit/includes/GlobalFunctions/*\.php</exclude-pattern>
<exclude-pattern>*/tests/phpunit/includes/GlobalFunctions/*\.php</exclude-pattern>
<exclude-pattern>*/tests/phpunit/maintenance/*\.php</exclude-pattern>
<exclude-pattern>*/tests/phpunit/integration/includes/GlobalFunctions/*\.php</exclude-pattern>
* $wgWikiDiff2MovedParagraphDetectionCutoff — If you still want a custom change
size threshold, please specify in php.ini, using the configuration variable
wikidiff2.moved_paragraph_detection_cutoff.
+* $wgDebugPrintHttpHeaders - The default of including HTTP headers in the
+ debug log channel is no longer configurable. The debug log itself remains
+ configurable via $wgDebugLogFile.
=== New user-facing features in 1.34 ===
* Special:Mute has been added as a quick way for users to block unwanted emails
specified, deprecated in 1.30, have been removed.
* BufferingStatsdDataFactory::getBuffer(), deprecated in 1.30, has been removed.
* The constant DB_SLAVE, deprecated in 1.28, has been removed. Use DB_REPLICA.
+* The constants NS_IMAGE and NS_IMAGE_TALK, deprecated in 1.14, have been
+ removed. Use NS_FILE and NS_FILE_TALK respectively.
* Replacer, DoubleReplacer, HashtableReplacer and RegexlikeReplacer
(deprecated in 1.32) have been removed. Closures should be used instead.
* OutputPage::addWikiText(), ::addWikiTextWithTitle(), ::addWikiTextTitleTidy(),
0..(numRows-1).
* The ChangePasswordForm hook, deprecated in 1.27, has been removed. Use the
AuthChangeFormFields hook or security levels instead.
+* WikiMap::getWikiIdFromDomain(), deprecated in 1.33, has been removed.
+ Use WikiMap::getWikiIdFromDbDomain() instead.
+* The config variables $wgHtml5, $wgJsMimeType, and $wgXhtmlDefaultNamespace,
+ which were deprecated and ignored by core since 1.22, are no longer set to any
+ value, and SkinTemplate no longer emits a 'jsmimetype' key. Any extensions not
+ updated since 2013 to cope with this deprecation may now break.
* …
=== Deprecations in 1.34 ===
"SkinOOUIThemes": {
"type": "object"
},
+ "OOUIThemePaths": {
+ "type": "object",
+ "description": "Map of custom OOUI theme names to paths to load them from. Same format as ResourceLoaderOOUIModule::$builtinThemePaths.",
+ "patternProperties": {
+ "^[A-Za-z]+$": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "scripts": {
+ "type": "string",
+ "description": "Path to script file."
+ },
+ "styles": {
+ "type": "string",
+ "description": "Path to style files. '{module}' will be replaced with the module's name."
+ },
+ "images": {
+ "type": [ "string", "null" ],
+ "description": "Path to images (optional). '{module}' will be replaced with the module's name."
+ }
+ }
+ }
+ }
+ },
"PasswordPolicy": {
"type": "object",
"description": "Password policies"
"type": "object",
"description": "Map of skin names to OOUI themes to use. Same format as ResourceLoaderOOUIModule::$builtinSkinThemeMap."
},
+ "OOUIThemePaths": {
+ "type": "object",
+ "description": "Map of custom OOUI theme names to paths to load them from. Same format as ResourceLoaderOOUIModule::$builtinThemePaths.",
+ "patternProperties": {
+ "^[A-Za-z]+$": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "scripts": {
+ "type": "string",
+ "description": "Path to script file."
+ },
+ "styles": {
+ "type": "string",
+ "description": "Path to style files. '{module}' will be replaced with the module's name."
+ },
+ "images": {
+ "type": [ "string", "null" ],
+ "description": "Path to images (optional). '{module}' will be replaced with the module's name."
+ }
+ }
+ }
+ }
+ },
"PasswordPolicy": {
"type": "object",
"description": "Password policies"
*/
$wgMimeType = 'text/html';
-/**
- * Previously used as content type in HTML script tags. This is now ignored since
- * HTML5 doesn't require a MIME type for script tags (javascript is the default).
- * It was also previously used by RawAction to determine the ctype query parameter
- * value that will result in a javascript response.
- * @deprecated since 1.22
- */
-$wgJsMimeType = null;
-
-/**
- * The default xmlns attribute. The option to define this has been removed.
- * The value of this variable is no longer used by core and is set to a fixed
- * value in Setup.php for compatibility with extensions that depend on the value
- * of this variable being set. Such a dependency however is deprecated.
- * @deprecated since 1.22
- */
-$wgXhtmlDefaultNamespace = null;
-
-/**
- * Previously used to determine if we should output an HTML5 doctype.
- * This is no longer used as we always output HTML5 now. For compatibility with
- * extensions that still check the value of this config it's value is now forced
- * to true by Setup.php.
- * @deprecated since 1.22
- */
-$wgHtml5 = true;
-
/**
* Defines the value of the version attribute in the <html> tag, if any.
*
*/
$wgDebugTimestamps = false;
-/**
- * Print HTTP headers for every request in the debug information.
- */
-$wgDebugPrintHttpHeaders = true;
-
/**
* Show the contents of $wgHooks in Special:Version
*/
*/
$wgPageInfoTransclusionLimit = 50;
-/**
- * Set this to an integer to only do synchronous site_stats updates
- * one every *this many* updates. The other requests go into pending
- * delta values in $wgMemc. Make sure that $wgMemc is a global cache.
- * If set to -1, updates *only* go to $wgMemc (useful for daemons).
- */
-$wgSiteStatsAsyncFactor = false;
-
/**
* Parser test suite files to be run by parserTests.php when no specific
* filename is passed to it.
define( 'NS_HELP_TALK', 13 );
define( 'NS_CATEGORY', 14 );
define( 'NS_CATEGORY_TALK', 15 );
-
-/**
- * NS_IMAGE and NS_IMAGE_TALK are the pre-v1.14 names for NS_FILE and
- * NS_FILE_TALK respectively, and are kept for compatibility.
- *
- * When writing code that should be compatible with older MediaWiki
- * versions, either stick to the old names or define the new constants
- * yourself, if they're not defined already.
- *
- * @deprecated since 1.14
- */
-define( 'NS_IMAGE', NS_FILE );
-/**
- * @deprecated since 1.14
- */
-define( 'NS_IMAGE_TALK', NS_FILE_TALK );
/**@}*/
/**@{
*/
public function insertRevisionOn( RevisionRecord $rev, IDatabase $dbw ) {
// TODO: pass in a DBTransactionContext instead of a database connection.
- $this->checkDatabaseWikiId( $dbw );
+ $this->checkDatabaseDomain( $dbw );
$slotRoles = $rev->getSlotRoles();
$minor,
User $user
) {
- $this->checkDatabaseWikiId( $dbw );
+ $this->checkDatabaseDomain( $dbw );
$pageId = $title->getArticleID();
* @param IDatabase $db
* @throws MWException
*/
- private function checkDatabaseWikiId( IDatabase $db ) {
- $storeWiki = $this->dbDomain;
- $dbWiki = $db->getDomainID();
-
- if ( $dbWiki === $storeWiki ) {
- return;
- }
-
- $storeWiki = $storeWiki ?: $this->loadBalancer->getLocalDomainID();
- // @FIXME: when would getDomainID() be false here?
- $dbWiki = $dbWiki ?: wfWikiID();
-
- if ( $dbWiki === $storeWiki ) {
- return;
- }
-
- // HACK: counteract encoding imposed by DatabaseDomain
- $storeWiki = str_replace( '?h', '-', $storeWiki );
- $dbWiki = str_replace( '?h', '-', $dbWiki );
-
- if ( $dbWiki === $storeWiki ) {
+ private function checkDatabaseDomain( IDatabase $db ) {
+ $dbDomain = $db->getDomainID();
+ $storeDomain = $this->loadBalancer->resolveDomainID( $this->dbDomain );
+ if ( $dbDomain === $storeDomain ) {
return;
}
- throw new MWException( "RevisionStore for $storeWiki "
- . "cannot be used with a DB connection for $dbWiki" );
+ throw new MWException( "DB connection domain '$dbDomain' does not match '$storeDomain'" );
}
/**
* @return object|false data row as a raw object
*/
private function fetchRevisionRowFromConds( IDatabase $db, $conditions, $flags = 0 ) {
- $this->checkDatabaseWikiId( $db );
+ $this->checkDatabaseDomain( $db );
$revQuery = $this->getQueryInfo( [ 'page', 'user' ] );
$options = [];
* of the corresponding revision.
*/
public function listRevisionSizes( IDatabase $db, array $revIds ) {
- $this->checkDatabaseWikiId( $db );
+ $this->checkDatabaseDomain( $db );
$revLens = [];
if ( !$revIds ) {
* @return int
*/
private function getPreviousRevisionId( IDatabase $db, RevisionRecord $rev ) {
- $this->checkDatabaseWikiId( $db );
+ $this->checkDatabaseDomain( $db );
if ( $rev->getPageId() === null ) {
return 0;
* @return int
*/
public function countRevisionsByPageId( IDatabase $db, $id ) {
- $this->checkDatabaseWikiId( $db );
+ $this->checkDatabaseDomain( $db );
$row = $db->selectRow( 'revision',
[ 'revCount' => 'COUNT(*)' ],
* @return bool True if the given user was the only one to edit since the given timestamp
*/
public function userWasLastToEdit( IDatabase $db, $pageId, $userId, $since ) {
- $this->checkDatabaseWikiId( $db );
+ $this->checkDatabaseDomain( $db );
if ( !$userId ) {
return false;
$wgDebugToolbar = false;
}
-// We always output HTML5 since 1.22, overriding these is no longer supported
-// we set them here for extensions that depend on its value.
-$wgHtml5 = true;
-$wgXhtmlDefaultNamespace = 'http://www.w3.org/1999/xhtml';
-$wgJsMimeType = 'text/javascript';
-
// Blacklisted file extensions shouldn't appear on the "allowed" list
$wgFileExtensions = array_values( array_diff( $wgFileExtensions, $wgFileBlacklist ) );
}
} else {
$debug = "\n\nStart request {$wgRequest->getMethod()} {$wgRequest->getRequestURL()}\n";
-
- if ( $wgDebugPrintHttpHeaders ) {
- $debug .= "HTTP HEADERS:\n";
-
- foreach ( $wgRequest->getAllHeaders() as $name => $value ) {
- $debug .= "$name: $value\n";
- }
+ $debug .= "HTTP HEADERS:\n";
+ foreach ( $wgRequest->getAllHeaders() as $name => $value ) {
+ $debug .= "$name: $value\n";
}
wfDebug( $debug );
}
$config = MediaWikiServices::getInstance()->getMainConfig();
$lb = self::getLB();
- $dbr = $lb->getConnection( DB_REPLICA );
+ $dbr = $lb->getConnectionRef( DB_REPLICA );
wfDebug( __METHOD__ . ": reading site_stats from replica DB\n" );
$row = self::doLoadFromDB( $dbr );
if ( !self::isRowSane( $row ) && $lb->hasOrMadeRecentMasterChanges() ) {
// Might have just been initialized during this request? Underflow?
wfDebug( __METHOD__ . ": site_stats damaged or missing on replica DB\n" );
- $row = self::doLoadFromDB( $lb->getConnection( DB_MASTER ) );
+ $row = self::doLoadFromDB( $lb->getConnectionRef( DB_MASTER ) );
}
if ( !self::isRowSane( $row ) ) {
SiteStatsInit::doAllAndCommit( $dbr );
}
- $row = self::doLoadFromDB( $lb->getConnection( DB_MASTER ) );
+ $row = self::doLoadFromDB( $lb->getConnectionRef( DB_MASTER ) );
}
if ( !self::isRowSane( $row ) ) {
$cache->makeKey( 'SiteStats', 'groupcounts', $group ),
$cache::TTL_HOUR,
function ( $oldValue, &$ttl, array &$setOpts ) use ( $group, $fname ) {
- $dbr = self::getLB()->getConnection( DB_REPLICA );
+ $dbr = self::getLB()->getConnectionRef( DB_REPLICA );
$setOpts += Database::getCacheSetOptions( $dbr );
return (int)$dbr->selectField(
$cache->makeKey( 'SiteStats', 'page-in-namespace', $ns ),
$cache::TTL_HOUR,
function ( $oldValue, &$ttl, array &$setOpts ) use ( $ns, $fname ) {
- $dbr = self::getLB()->getConnection( DB_REPLICA );
+ $dbr = self::getLB()->getConnectionRef( DB_REPLICA );
$setOpts += Database::getCacheSetOptions( $dbr );
return (int)$dbr->selectField(
// the stash request finishes parsing. For the lock acquisition below, there is not much
// need to duplicate parsing of the same content/user/summary bundle, so try to avoid
// blocking at all here.
- $dbw = $this->lb->getConnection( DB_MASTER );
+ $dbw = $this->lb->getConnectionRef( DB_MASTER );
if ( !$dbw->lock( $key, $fname, 0 ) ) {
// De-duplicate requests on the same key
return self::ERROR_BUSY;
* @return string|null TS_MW timestamp or null
*/
private function lastEditTime( User $user ) {
- $db = $this->lb->getConnection( DB_REPLICA );
+ $db = $this->lb->getConnectionRef( DB_REPLICA );
+
$actorQuery = ActorMigration::newMigration()->getWhere( $db, 'rc_user', $user, false );
$time = $db->selectField(
[ 'recentchanges' ] + $actorQuery['tables'],
if (
!MediaWikiServices::getInstance()->getNamespaceInfo()->
hasSubpages( $this->mNamespace )
+ || strtok( $this->getText(), '/' ) === false
) {
return $this->getText();
}
* @since 1.20
*/
public function getSubpage( $text ) {
- return self::makeTitleSafe( $this->mNamespace, $this->getText() . '/' . $text );
+ return self::makeTitleSafe(
+ $this->mNamespace,
+ $this->getText() . '/' . $text,
+ '',
+ $this->mInterwiki
+ );
}
/**
: (string)$domain->getDatabase();
}
- /**
- * @param string $domain
- * @return string
- * @deprecated Since 1.33; use getWikiIdFromDbDomain()
- */
- public static function getWikiIdFromDomain( $domain ) {
- return self::getWikiIdFromDbDomain( $domain );
- }
-
/**
* @return DatabaseDomain Database domain of the current wiki
* @since 1.33
* @since 1.33
*/
public static function isCurrentWikiDbDomain( $domain ) {
- return self::getCurrentWikiDbDomain()->equals( DatabaseDomain::newFromId( $domain ) );
+ return self::getCurrentWikiDbDomain()->equals( $domain );
}
/**
"Kenjiraw",
"Framawiki",
"Epok",
- "Derugon"
+ "Derugon",
+ "Lucas Werkmeister (WMDE)"
]
},
"apihelp-main-extended-description": "<div class=\"hlist plainlinks api-main-links\">\n* [[mw:Special:MyLanguage/API:Main_page|Documentation]]\n* [[mw:Special:MyLanguage/API:FAQ|FAQ]]\n* [https://lists.wikimedia.org/mailman/listinfo/mediawiki-api Liste de diffusion]\n* [https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce Annonces de l’API]\n* [https://phabricator.wikimedia.org/maniphest/query/GebfyV4uCaLd/#R Bogues et demandes]\n</div>\n<strong>État :</strong> L’API MediaWiki est une interface stable et mature qui est supportée et améliorée de façon active. Bien que nous essayions de l’éviter, nous pouvons avoir parfois besoin de faire des modifications impactantes ; inscrivez-vous à [https://lists.wikimedia.org/pipermail/mediawiki-api-announce/ la liste de diffusion mediawiki-api-announce] pour être informé des mises à jour.\n\n<strong>Requêtes erronées :</strong> Si des requêtes erronées sont envoyées à l’API, un entête HTTP sera renvoyé avec la clé « MediaWiki-API-Error ». La valeur de cet entête et le code d’erreur renvoyé prendront la même valeur. Pour plus d’information, voyez [[mw:Special:MyLanguage/API:Errors_and_warnings|API:Errors and warnings]].\n\n<p class=\"mw-apisandbox-link\"><strong>Test :</strong> Pour faciliter le test des requêtes à l’API, voyez [[Special:ApiSandbox]].</p>",
"apihelp-query+languageinfo-paramvalue-prop-code": "Le code de langue (ce code est spécifique à MédiaWiki, bien qu’il y ait des recouvrements avec d’autres standards).",
"apihelp-query+languageinfo-paramvalue-prop-bcp47": "Le code de langue BCP-47.",
"apihelp-query+languageinfo-paramvalue-prop-dir": "La direction d’écriture de la langue (<code>ltr</code> ou <code>rtl</code>).",
- "apihelp-query+languageinfo-paramvalue-prop-autonym": "L’autonyme d'une langue, c’est-à-dire son nom dans cette langue.",
+ "apihelp-query+languageinfo-paramvalue-prop-autonym": "L’autonyme d’une langue, c’est-à-dire son nom dans cette langue.",
"apihelp-query+languageinfo-paramvalue-prop-name": "Le nom de la langue dans la langue spécifiée par le paramètre <var>lilang</var>, avec application des langues de secours si besoin.",
"apihelp-query+languageinfo-paramvalue-prop-fallbacks": "Les codes de langue des langues de secours configurées pour cette langue. Le secours implicite final en 'en' n’est pas inclus (mais certaines langues peuvent avoir 'en' en secours explicitement).",
"apihelp-query+languageinfo-paramvalue-prop-variants": "Les codes de langue des variantes supportées par cette langue.",
"apihelp-main-param-uselang": "Јазик за преведување на пораките. <kbd>[[Special:ApiHelp/query+siteinfo|action=query&meta=siteinfo]]</kbd> со <kbd>siprop=languages</kbd> дава список на јазични кодови, или укажете <kbd>user</kbd> за да го користите тековно зададениот јазик корисникот, или пак укажете <kbd>content</kbd> за да го користите јазикот на содржината на ова вики.",
"apihelp-block-summary": "Блокирај корисник.",
"apihelp-block-param-user": "Корисничко име, IP-адреса или IP-опсег ако сакате да блокирате. Не може да се користи заедно со <var>$1userid</var>",
- "apihelp-block-param-expiry": "Време на истек. Може да биде релативно (на пр. <kbd>5 months</kbd> или „2 недели“) или пак апсолутно (на пр. <kbd>2014-09-18T12:34:56Z</kbd>). Ако го зададете <kbd>infinite</kbd>, <kbd>indefinite</kbd> или <kbd>never</kbd>, блокот ќе трае засекогаш.",
+ "apihelp-block-param-expiry": "Време на истек. Може да биде релативно (на пр. <kbd>5 months</kbd> или <kbd>2 weeks</kbd>) или пак апсолутно (на пр. <kbd>2014-09-18T12:34:56Z</kbd>). Ако го зададете <kbd>infinite</kbd>, <kbd>indefinite</kbd> или <kbd>never</kbd>, блокот ќе трае засекогаш.",
"apihelp-block-param-reason": "Причина за блокирање.",
"apihelp-block-param-anononly": "Блокирај само анонимни корисници (т.е. оневозможи анонимно уредување од оваа IP-адреса).",
"apihelp-block-param-nocreate": "Оневозможи создавање кориснички сметки.",
"apihelp-opensearch-param-search": "Низа за пребарување.",
"apihelp-opensearch-param-limit": "Највеќе ставки за прикажување.",
"apihelp-opensearch-param-namespace": "Именски простори за пребарување.",
- "apihelp-opensearch-param-suggest": "Не прави ништо ако <var>[[mw:Manual:$wgEnableOpenSearchSuggest|$wgEnableOpenSearchSuggest]]</var> е неточно.",
+ "apihelp-opensearch-param-suggest": "Не прави ништо ако <var>[[mw:Special:MyLanguage/Manual:$wgEnableOpenSearchSuggest|$wgEnableOpenSearchSuggest]]</var> е неточно.",
"apihelp-opensearch-param-redirects": "Како да се работи со пренасочувања:\n;return: Дај го самото пренасочување.\n;resolve: Дај ја целната страница. Може да даде помалку од $1limit ставки.\nОд историски причини, по основно е „return“ за $1format=json и „resolve“ за други формати.",
"apihelp-opensearch-param-format": "Формат на изводот.",
"apihelp-opensearch-example-te": "Најди страници што почнуваат со <kbd>Те</kbd>.",
"apihelp-options-param-resetkinds": "Сисок на типови можности за повраток кога е зададена можноста <var>$1reset</var>.",
"apihelp-options-param-change": "Список на промени во форматот name=value (на пр. skin=vector). Вредностите не треба да содржат исправени црти. Ако не зададете вредност (дури ни знак за равенство), на пр., можност|другаможност|..., ќе биде зададена вредноста на можноста по основно.",
"apihelp-options-param-optionname": "Назив на можноста што треба да ѝ се зададе на вредноста дадена од <var>$1optionvalue</var>.",
- "apihelp-options-param-optionvalue": "Вредноста на можноста укажана од <var>$1optionname</var>. Може да содржи исправени црти.",
+ "apihelp-options-param-optionvalue": "Вредноста на можноста укажана од <var>$1optionname</var>.",
"apihelp-options-example-reset": "Врати ги сите поставки по основно",
"apihelp-options-example-change": "Смени ги поставките <kbd>skin</kbd и <kbd>hideminor</kbd>.",
"apihelp-options-example-complex": "Врати ги сите нагодувања по основно, а потоа задај ги <kbd>skin</kbd> и <kbd>nickname</kbd>.",
"apihelp-paraminfo-summary": "Набави информации за извршнички (API) модули.",
- "apihelp-paraminfo-param-modules": "Список на називи на модули (вредности на параметрите <var>action</var> и <var>format</var>, или пак <kbd>main</kbd>). Може да се укажат подмодули со <kbd>+</kbd>.",
+ "apihelp-paraminfo-param-modules": "Список на називи на модули (вредности на параметрите <var>action</var> и <var>format</var>, или пак <kbd>main</kbd>). Може да се укажат подмодули со <kbd>+</kbd>, или сите подмодули <kbd>+*</kbd>, или сите подмодули рекурзивно со <kbd>+**</kbd>.",
"apihelp-paraminfo-param-helpformat": "Формат на помошните низи.",
"apihelp-paraminfo-param-querymodules": "Список на називи на модули за барања (вредност на параметарот <var>prop</var>, <var>meta</var> или <var>list</var>). Користете го <kbd>$1modules=query+foo</kbd> наместо <kbd>$1querymodules=foo</kbd>.",
"apihelp-paraminfo-param-mainmodule": "Добави информации и за главниот (врховен) модул. Користете го <kbd>$1modules=main</kbd> наместо тоа.",
"apihelp-paraminfo-param-pagesetmodule": "Дај ги сите информации и за модулот на збирот страници (укажувајќи titles= и сродни).",
"apihelp-paraminfo-param-formatmodules": "Список на називи на форматни модули (вредностза параметарот <var>format</var>). Наместо тоа, користете го <var>$1modules</var>.",
+ "apihelp-paraminfo-example-1": "Прикажи информации за <kbd>[[Special:ApiHelp/parse|action=parse]]</kbd>, <kbd>[[Special:ApiHelp/jsonfm|format=jsonfm]]</kbd>, <kbd>[[Special:ApiHelp/query+allpages|action=query&list=allpages]]</kbd> и <kbd>[[Special:ApiHelp/query+siteinfo|action=query&meta=siteinfo]]</kbd>.",
+ "apihelp-paraminfo-example-2": "Прикажи информации за сите подмодули на <kbd>[[Special:ApiHelp/query|action=query]]</kbd>.",
"apihelp-parse-param-summary": "Опис за расчленување.",
"apihelp-parse-param-preview": "Расчлени во прегледен режим.",
"apihelp-parse-param-sectionpreview": "Расчлени во прегледен режим на поднасловот (го овозможува и прегледниот режим).",
"apihelp-patrol-summary": "Испатролирај страница или преработка.",
"apihelp-patrol-param-rcid": "Назнака на спорешните промени за патролирање.",
"apihelp-patrol-param-revid": "Назнака на преработката за патролирање.",
+ "apihelp-patrol-param-tags": "Ознаки за примена врз ставката во дневникот на патролирања.",
"apihelp-patrol-example-rcid": "Испатролирај скорешна промена",
"apihelp-patrol-example-revid": "Патролирај праработка",
"apihelp-protect-summary": "Смени го степенот на заштита на страница.",
"apihelp-protect-param-title": "Наслов на страница што се (од)заштитува. Не може да се користи заедно со $1pageid.",
"apihelp-protect-param-pageid": "Назнака на страница што се (од)заштитува. Не може да се користи заедно со $1title.",
"apihelp-protect-param-reason": "Причиина за (од)заштитување",
+ "apihelp-protect-param-tags": "Ознаки за примена врз ставката во дневникот на заштита.",
"apihelp-protect-example-protect": "Заштити страница",
"apihelp-purge-param-forcelinkupdate": "Поднови ги табелите со врски.",
"apihelp-purge-example-simple": "Превчитај ги <kbd>Main Page</kbd> и <kbd>API</kbd>.",
"apihelp-query+allcategories-param-from": "Од која категорија да почне набројувањето.",
"apihelp-query+allcategories-param-to": "На која категорија да запре набројувањето.",
"apihelp-query+allcategories-param-dir": "Насока на подредувањето.",
+ "apihelp-query+allcategories-param-limit": "Колку категории да се дадат.",
"apihelp-query+allcategories-param-prop": "Кои својства да се дадат:",
"apihelp-query+alldeletedrevisions-param-from": "Почни го исписот од овој наслов.",
"apihelp-query+alldeletedrevisions-param-to": "Запри го исписот на овој наслов.",
"WhitePhosphorus",
"科劳",
"SolidBlock",
- "神樂坂秀吉"
+ "神樂坂秀吉",
+ "94rain"
]
},
"apihelp-main-extended-description": "<div class=\"hlist plainlinks api-main-links\">\n* [[mw:Special:MyLanguage/API:Main_page|文档]]\n* [[mw:Special:MyLanguage/API:FAQ|常见问题]]\n* [https://lists.wikimedia.org/mailman/listinfo/mediawiki-api 邮件列表]\n* [https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce API公告]\n* [https://phabricator.wikimedia.org/maniphest/query/GebfyV4uCaLd/#R 程序错误与功能请求]\n</div>\n<strong>状态信息:</strong>MediaWiki API是一个成熟稳定的,不断受到支持和改进的界面。尽管我们尽力避免,但偶尔也需要作出重大更新;请订阅[https://lists.wikimedia.org/pipermail/mediawiki-api-announce/ mediawiki-api-announce 邮件列表]以便获得更新通知。\n\n<strong>错误请求:</strong>当API收到错误请求时,HTTP header将会返回一个包含\"MediaWiki-API-Error\"的值,随后header的值与error code将会送回并设置为相同的值。详细信息请参阅[[mw:Special:MyLanguage/API:Errors_and_warnings|API:错误与警告]]。\n\n<p class=\"mw-apisandbox-link\"><strong>测试中:</strong>测试API请求的易用性,请参见[[Special:ApiSandbox]]。</p>",
"apihelp-upload-param-comment": "上传注释。如果没有指定<var>$1text</var>,那么它也被用于新文件的初始页面文本。",
"apihelp-upload-param-tags": "更改标签以应用于上传日志记录和文件页面修订中。",
"apihelp-upload-param-text": "用于新文件的初始页面文本。",
- "apihelp-upload-param-watch": "关注页面。",
+ "apihelp-upload-param-watch": "监视页面。",
"apihelp-upload-param-watchlist": "无条件地将页面加入至当前用户的监视列表或将其移除,使用设置或不更改监视。",
"apihelp-upload-param-ignorewarnings": "忽略任何警告。",
"apihelp-upload-param-file": "文件内容。",
return [];
}
- $db = $db ?: $this->loadBalancer->getConnection( DB_REPLICA );
+ $db = $db ?: $this->loadBalancer->getConnectionRef( DB_REPLICA );
$result = $db->select(
[ 'ipblocks_restrictions', 'page' ],
return false;
}
- $dbw = $this->loadBalancer->getConnection( DB_MASTER );
+ $dbw = $this->loadBalancer->getConnectionRef( DB_MASTER );
$dbw->insert(
'ipblocks_restrictions',
* @return bool
*/
public function update( array $restrictions ) {
- $dbw = $this->loadBalancer->getConnection( DB_MASTER );
+ $dbw = $this->loadBalancer->getConnectionRef( DB_MASTER );
$dbw->startAtomic( __METHOD__ );
$parentBlockId = (int)$parentBlockId;
- $db = $this->loadBalancer->getConnection( DB_MASTER );
+ $db = $this->loadBalancer->getConnectionRef( DB_MASTER );
$db->startAtomic( __METHOD__ );
* @return bool
*/
public function delete( array $restrictions ) {
- $dbw = $this->loadBalancer->getConnection( DB_MASTER );
+ $dbw = $this->loadBalancer->getConnectionRef( DB_MASTER );
$result = true;
foreach ( $restrictions as $restriction ) {
if ( !$restriction instanceof Restriction ) {
* @return bool
*/
public function deleteByBlockId( $blockId ) {
- $dbw = $this->loadBalancer->getConnection( DB_MASTER );
+ $dbw = $this->loadBalancer->getConnectionRef( DB_MASTER );
return $dbw->delete(
'ipblocks_restrictions',
[ 'ir_ipb_id' => $blockId ],
* @return bool
*/
public function deleteByParentBlockId( $parentBlockId ) {
- $dbw = $this->loadBalancer->getConnection( DB_MASTER );
+ $dbw = $this->loadBalancer->getConnectionRef( DB_MASTER );
return $dbw->deleteJoin(
'ipblocks_restrictions',
'ipblocks',
* Class for handling updates to the site_stats table
*/
class SiteStatsUpdate implements DeferrableUpdate, MergeableUpdate {
- /** @var BagOStuff */
- protected $stash;
/** @var int */
protected $edits = 0;
/** @var int */
/** @var int */
protected $images = 0;
- private static $counters = [ 'edits', 'pages', 'articles', 'users', 'images' ];
+ /** @var string[] Map of (table column => counter type) */
+ private static $counters = [
+ 'ss_total_edits' => 'edits',
+ 'ss_total_pages' => 'pages',
+ 'ss_good_articles' => 'articles',
+ 'ss_users' => 'users',
+ 'ss_images' => 'images'
+ ];
// @todo deprecate this constructor
function __construct( $views, $edits, $good, $pages = 0, $users = 0 ) {
$this->articles = $good;
$this->pages = $pages;
$this->users = $users;
-
- $this->stash = MediaWikiServices::getInstance()->getMainObjectStash();
}
public function merge( MergeableUpdate $update ) {
}
/**
- * @param array $deltas
+ * @param int[] $deltas Map of (counter type => integer delta)
* @return SiteStatsUpdate
+ * @throws UnexpectedValueException
*/
public static function factory( array $deltas ) {
$update = new self( 0, 0, 0 );
}
foreach ( self::$counters as $field ) {
- if ( isset( $deltas[$field] ) && $deltas[$field] ) {
- $update->$field = $deltas[$field];
- }
+ $update->$field = $deltas[$field] ?? 0;
}
return $update;
}
public function doUpdate() {
- $this->doUpdateContextStats();
-
- $rate = MediaWikiServices::getInstance()->getMainConfig()->get( 'SiteStatsAsyncFactor' );
- // If set to do so, only do actual DB updates 1 every $rate times.
- // The other times, just update "pending delta" values in memcached.
- if ( $rate && ( $rate < 0 || mt_rand( 0, $rate - 1 ) != 0 ) ) {
- $this->doUpdatePendingDeltas();
- } else {
- // Need a separate transaction because this a global lock
- DeferredUpdates::addCallableUpdate( [ $this, 'tryDBUpdateInternal' ] );
- }
- }
-
- /**
- * Do not call this outside of SiteStatsUpdate
- */
- public function tryDBUpdateInternal() {
$services = MediaWikiServices::getInstance();
- $config = $services->getMainConfig();
-
- $dbw = $services->getDBLoadBalancer()->getConnection( DB_MASTER );
- $lockKey = $dbw->getDomainID() . ':site_stats'; // prepend wiki ID
- $pd = [];
- if ( $config->get( 'SiteStatsAsyncFactor' ) ) {
- // Lock the table so we don't have double DB/memcached updates
- if ( !$dbw->lock( $lockKey, __METHOD__, 0 ) ) {
- $this->doUpdatePendingDeltas();
+ $stats = $services->getStatsdDataFactory();
- return;
+ $deltaByType = [];
+ foreach ( self::$counters as $type ) {
+ $delta = $this->$type;
+ if ( $delta !== 0 ) {
+ $stats->updateCount( "site.$type", $delta );
}
- $pd = $this->getPendingDeltas();
- // Piggy-back the async deltas onto those of this stats update....
- $this->edits += ( $pd['ss_total_edits']['+'] - $pd['ss_total_edits']['-'] );
- $this->articles += ( $pd['ss_good_articles']['+'] - $pd['ss_good_articles']['-'] );
- $this->pages += ( $pd['ss_total_pages']['+'] - $pd['ss_total_pages']['-'] );
- $this->users += ( $pd['ss_users']['+'] - $pd['ss_users']['-'] );
- $this->images += ( $pd['ss_images']['+'] - $pd['ss_images']['-'] );
- }
-
- // Build up an SQL query of deltas and apply them...
- $updates = '';
- $this->appendUpdate( $updates, 'ss_total_edits', $this->edits );
- $this->appendUpdate( $updates, 'ss_good_articles', $this->articles );
- $this->appendUpdate( $updates, 'ss_total_pages', $this->pages );
- $this->appendUpdate( $updates, 'ss_users', $this->users );
- $this->appendUpdate( $updates, 'ss_images', $this->images );
- if ( $updates != '' ) {
- $dbw->update( 'site_stats', [ $updates ], [], __METHOD__ );
+ $deltaByType[$type] = $delta;
}
- if ( $config->get( 'SiteStatsAsyncFactor' ) ) {
- // Decrement the async deltas now that we applied them
- $this->removePendingDeltas( $pd );
- // Commit the updates and unlock the table
- $dbw->unlock( $lockKey, __METHOD__ );
- }
+ ( new AutoCommitUpdate(
+ $services->getDBLoadBalancer()->getConnectionRef( DB_MASTER ),
+ __METHOD__,
+ function ( IDatabase $dbw, $fname ) use ( $deltaByType ) {
+ $set = [];
+ foreach ( self::$counters as $column => $type ) {
+ $delta = (int)$deltaByType[$type];
+ if ( $delta > 0 ) {
+ $set[] = "$column=$column+" . abs( $delta );
+ } elseif ( $delta < 0 ) {
+ $set[] = "$column=$column-" . abs( $delta );
+ }
+ }
+
+ if ( $set ) {
+ $dbw->update( 'site_stats', $set, [ 'ss_row_id' => 1 ], $fname );
+ }
+ }
+ ) )->doUpdate();
- // Invalid cache used by parser functions
+ // Invalidate cache used by parser functions
SiteStats::unload();
}
$services = MediaWikiServices::getInstance();
$config = $services->getMainConfig();
- $dbr = $services->getDBLoadBalancer()->getConnection( DB_REPLICA, 'vslow' );
+ $dbr = $services->getDBLoadBalancer()->getConnectionRef( DB_REPLICA, 'vslow' );
# Get non-bot users than did some recent action other than making accounts.
# If account creation is included, the number gets inflated ~20+ fold on enwiki.
$rcQuery = RecentChange::getQueryInfo();
return $activeUsers;
}
-
- protected function doUpdateContextStats() {
- $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
- foreach ( [ 'edits', 'articles', 'pages', 'users', 'images' ] as $type ) {
- $delta = $this->$type;
- if ( $delta !== 0 ) {
- $stats->updateCount( "site.$type", $delta );
- }
- }
- }
-
- protected function doUpdatePendingDeltas() {
- $this->adjustPending( 'ss_total_edits', $this->edits );
- $this->adjustPending( 'ss_good_articles', $this->articles );
- $this->adjustPending( 'ss_total_pages', $this->pages );
- $this->adjustPending( 'ss_users', $this->users );
- $this->adjustPending( 'ss_images', $this->images );
- }
-
- /**
- * @param string &$sql
- * @param string $field
- * @param int $delta
- */
- protected function appendUpdate( &$sql, $field, $delta ) {
- if ( $delta ) {
- if ( $sql ) {
- $sql .= ',';
- }
- if ( $delta < 0 ) {
- $sql .= "$field=$field-" . abs( $delta );
- } else {
- $sql .= "$field=$field+" . abs( $delta );
- }
- }
- }
-
- /**
- * @param BagOStuff $stash
- * @param string $type
- * @param string $sign ('+' or '-')
- * @return string
- */
- private function getTypeCacheKey( BagOStuff $stash, $type, $sign ) {
- return $stash->makeKey( 'sitestatsupdate', 'pendingdelta', $type, $sign );
- }
-
- /**
- * Adjust the pending deltas for a stat type.
- * Each stat type has two pending counters, one for increments and decrements
- * @param string $type
- * @param int $delta Delta (positive or negative)
- */
- protected function adjustPending( $type, $delta ) {
- if ( $delta < 0 ) { // decrement
- $key = $this->getTypeCacheKey( $this->stash, $type, '-' );
- } else { // increment
- $key = $this->getTypeCacheKey( $this->stash, $type, '+' );
- }
-
- $magnitude = abs( $delta );
- $this->stash->incrWithInit( $key, 0, $magnitude, $magnitude );
- }
-
- /**
- * Get pending delta counters for each stat type
- * @return array Positive and negative deltas for each type
- */
- protected function getPendingDeltas() {
- $pending = [];
- foreach ( [ 'ss_total_edits',
- 'ss_good_articles', 'ss_total_pages', 'ss_users', 'ss_images' ] as $type
- ) {
- // Get pending increments and pending decrements
- $flg = BagOStuff::READ_LATEST;
- $pending[$type]['+'] = (int)$this->stash->get(
- $this->getTypeCacheKey( $this->stash, $type, '+' ),
- $flg
- );
- $pending[$type]['-'] = (int)$this->stash->get(
- $this->getTypeCacheKey( $this->stash, $type, '-' ),
- $flg
- );
- }
-
- return $pending;
- }
-
- /**
- * Reduce pending delta counters after updates have been applied
- * @param array $pd Result of getPendingDeltas(), used for DB update
- */
- protected function removePendingDeltas( array $pd ) {
- foreach ( $pd as $type => $deltas ) {
- foreach ( $deltas as $sign => $magnitude ) {
- // Lower the pending counter now that we applied these changes
- $key = $this->getTypeCacheKey( $this->stash, $type, $sign );
- $this->stash->decr( $key, $magnitude );
- }
- }
- }
}
*/
public function doUpdate() {
$lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
- $dbw = $lb->getConnection( DB_MASTER );
+ $dbw = $lb->getConnectionRef( DB_MASTER );
$fname = __METHOD__;
( new AutoCommitUpdate( $dbw, __METHOD__, function () use ( $lb, $dbw, $fname ) {
// The user_editcount is probably NULL (e.g. not initialized).
// Since this update runs after the new revisions were committed,
// wait for the replica DB to catch up so they will be counted.
- $dbr = $lb->getConnection( DB_REPLICA );
- // If $dbr is actually the master DB, then clearing the snapshot is
+ $dbr = $lb->getConnectionRef( DB_REPLICA );
+ // If $dbr is actually the master DB, then clearing the snapshot
// is harmless and waitForMasterPos() will just no-op.
$dbr->flushSnapshot( $fname );
$lb->waitForMasterPos( $dbr );
"config-sidebar": "* [https://www.mediawiki.org Хатняя старонка MediaWiki]\n* [https://www.mediawiki.org/wiki/Special:MyLanguage/Help:Contents Даведка для ўдзельнікаў]\n* [https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:Contents Даведка для адміністратараў]\n* [https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:FAQ Адказы на частыя пытаньні]",
"config-sidebar-readme": "Прачытай мяне",
"config-sidebar-relnotes": "Заўвагі да выпуску",
+ "config-sidebar-license": "Капіяваньне",
+ "config-sidebar-upgrade": "Абнаўленьне",
"config-env-good": "Асяродзьдзе было праверанае.\nВы можаце ўсталёўваць MediaWiki.",
"config-env-bad": "Асяродзьдзе было праверанае.\nУсталяваньне MediaWiki немагчымае.",
"config-env-php": "Усталяваны PHP $1.",
"config-sidebar": "* [https://www.mediawiki.org Pagina principale MediaWiki]\n* [https://www.mediawiki.org/Special:MyLanguage/Help:Contents Guida ai contenuti per utenti]\n* [https://www.mediawiki.org/Special:MyLanguage/Manual:Contents Guida ai contenuti per admin]\n* [https://www.mediawiki.org/Special:MyLanguage/Manual:FAQ FAQ]",
"config-sidebar-readme": "Leggimi",
"config-sidebar-relnotes": "Note di versione",
- "config-sidebar-license": "copiando",
+ "config-sidebar-license": "Licenza",
"config-sidebar-upgrade": "Aggiornamento",
"config-env-good": "L'ambiente è stato controllato.\nÈ possibile installare MediaWiki.",
"config-env-bad": "L'ambiente è stato controllato.\nNon è possibile installare MediaWiki.",
"config-restart": "Ja, starta om",
"config-welcome": "=== Miljökontroller ===\nGrundläggande kontroller kommer nu att utföras för att se om denna miljö är lämplig för installation av MediaWiki.\nKom ihåg att ta med denna information om du söker stöd för hur du skall slutföra installationen.",
"config-copyright": "=== Upphovsrätt och Villkor ===\n\n$1\n\nDetta program är fri programvara; du kan vidaredistribuera den och/eller modifiera det enligt villkoren i GNU General Public License som publicerats av Free Software Foundation; antingen genom version 2 av licensen, eller (på ditt initiativ) någon senare version.\n\nDetta program är distribuerat i hopp om att det kommer att vara användbart, men '''utan någon garanti'''; utan att ens ha en underförstådd garanti om '''säljbarhet''' eller '''lämplighet för ett särskilt ändamål'''.\nSe GNU General Public License för mer detaljer.\n\nDu bör ha fått <doclink href=Copying>en kopia av GNU General Public License</doclink> tillsammans med detta program; om inte, skriv till Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA, eller [https://www.gnu.org/copyleft/gpl.html läs den online].",
- "config-sidebar": "* [https://www.mediawiki.org MediaWikis webbplats]\n* [https://www.mediawiki.org/wiki/Special:MyLanguage/Help:Contents Användarguide]\n* [https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:Contents Administratörguide]\n* [https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:FAQ Frågor och svar]\n----\n* <doclink href=Readme>Läs mig</doclink>\n* <doclink href=ReleaseNotes>Utgivningsanteckningar</doclink>\n* <doclink href=Copying>Kopiering</doclink>\n* <doclink href=UpgradeDoc>Uppgradering</doclink>",
+ "config-sidebar": "* [https://www.mediawiki.org MediaWikis webbplats]\n* [https://www.mediawiki.org/wiki/Special:MyLanguage/Help:Contents Användarguide]\n* [https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:Contents Administratörsguide]\n* [https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:FAQ Frågor och svar]",
+ "config-sidebar-readme": "Läs mig",
+ "config-sidebar-relnotes": "Utgivningsanteckningar",
+ "config-sidebar-license": "Kopierar",
+ "config-sidebar-upgrade": "Uppgradering",
"config-env-good": "Miljön har kontrollerats.\nDu kan installera MediaWiki.",
"config-env-bad": "Miljön har kontrollerats.\nDu kan inte installera MediaWiki.",
"config-env-php": "PHP $1 är installerat.",
"config-restart": "Так, перезапустити установку",
"config-welcome": "=== Перевірка оточення ===\nБудуть проведені базові перевірки, щоб виявити, чи можлива установка MediaWiki у даній системі.\nНе забудьте включити цю інформацію, якщо ви звернетеся по підтримку, як завершити установку.",
"config-copyright": "=== Авторське право і умови ===\n\n$1\n\nЦя програма є вільним програмним забезпеченням; Ви можете розповсюджувати та/або змінювати її під ліцензією GNU General Public License, опублікованою Фондом вільного програмного забезпечення; версією 2 цієї ліцензії або будь-якою пізнішою на Ваш вибір.\n\nЦя програма поширюється з надією на те, що вона буде корисною, однак '''без жодних гарантій'''; навіть без неявної гарантії '''комерційної цінності''' або '''придатності для певних цілей'''.\nДив. GNU General Public License для детальної інформації.\n\nВи повинні були отримати <doclink href=Copying>копію GNU General Public License</doclink> разом із цією програмою; якщо ж ні, зверніться до Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. або [https://www.gnu.org/copyleft/gpl.html ознайомтесь з нею онлайн].",
- "config-sidebar": "* [https://www.mediawiki.org Сайт MediaWiki]\n* [https://www.mediawiki.org/wiki/Special:MyLanguage/Help:Contents Посібник користувача]\n* [https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:Contents Посібник адміністратора]\n* [https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:FAQ FAQ]\n----\n* <doclink href=Readme>Read me</doclink>\n* <doclink href=ReleaseNotes>Інформація про випуск</doclink>\n* <doclink href=Copying>Ліцензія</doclink>\n* <doclink href=UpgradeDoc>Оновлення</doclink>",
+ "config-sidebar": "* [https://www.mediawiki.org Сайт MediaWiki]\n* [https://www.mediawiki.org/wiki/Special:MyLanguage/Help:Contents Посібник користувача]\n* [https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:Contents Посібник адміністратора]\n* [https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:FAQ FAQ]",
+ "config-sidebar-readme": "Прочитай мене",
+ "config-sidebar-relnotes": "Інформація про версію",
+ "config-sidebar-license": "Копіювання",
+ "config-sidebar-upgrade": "Оновлення",
"config-env-good": "Перевірку середовища успішно завершено.\nВи можете встановити MediaWiki.",
"config-env-bad": "Було проведено перевірку середовища. Ви не можете встановити MediaWiki.",
"config-env-php": "Встановлено версію PHP: $1.",
"config-env-hhvm": "HHVM $1 встановлено.",
- "config-unicode-using-intl": "Ð\92икоÑ\80иÑ\81Ñ\82овÑ\83ваÑ\82и [https://pecl.php.net/intl мÑ\96жнаÑ\80одне Ñ\80озÑ\88иÑ\80еннÑ\8f PECL] для нормалізації Юнікоду.",
- "config-unicode-pure-php-warning": "'''Увага''': [https://pecl.php.net/intl міжнародне розширення PECL] не може провести нормалізацію Юнікоду.\nЯкщо ваш сайт має високий трафік, вам варто почитати про [https://www.mediawiki.org/wiki/Special:MyLanguage/Unicode_normalization_considerations нормалізацію Юнікоду].",
+ "config-unicode-using-intl": "Ð\97а допомогоÑ\8e [https://php.net/manual/en/book.intl.php PHP-Ñ\80озÑ\88иÑ\80еннÑ\8f intl] для нормалізації Юнікоду.",
+ "config-unicode-pure-php-warning": "'''Увага''': [https://php.net/manual/en/book.intl.php PHP-розширення intl] не може провести нормалізацію Юнікоду.\nЯкщо ваш сайт має високий трафік, вам варто почитати про [https://www.mediawiki.org/wiki/Special:MyLanguage/Unicode_normalization_considerations нормалізацію Юнікоду].",
"config-unicode-update-warning": "'''Увага''': Встановлена версія обгортки нормалізації Юнікоду використовує стару версію бібліотеки [http://site.icu-project.org/ проекту ICU].\nВи маєте [https://www.mediawiki.org/wiki/Special:MyLanguage/Unicode_normalization_considerations оновити версію], якщо плануєте повноцінно використовувати Юнікод.",
"config-no-db": "Не вдалося знайти потрібний драйвер бази даних! Вам необхідно встановити драйвер бази даних для PHP. Підтримуються {{PLURAL:$2|такий тип|такі типи}} баз даних: $1.\n\nЯкщо ви скомпілювали PHP самостійно, переналаштуйте його з увімкненим клієнтом бази даних, наприклад за допомогою <code>./configure --with-mysqli</code>.\n\nЯкщо установлено PHP з пакетів Debian або Ubuntu, тоді ви також повинні встановити, наприклад, пакунок <code>php-mysql</code>.",
"config-outdated-sqlite": "<strong>Увага:</strong> у Вас встановлена версія SQLite $2, а це нижче, ніж мінімально необхідна версія $1. SQLite буде недоступним.",
"config-support-info": "MediaWiki підтримує такі системи баз даних:\n\n$1\n\nЯкщо Ви не бачите серед перерахованих систему баз даних, яку використовуєте, виконайте вказівки, вказані вище, щоб увімкнути підтримку.",
"config-dbsupport-mysql": "* [{{int:version-db-mariadb-url}} MariaDB] є основною ціллю для MediaWiki і найкраще підтримується. MediaWiki також працює з [{{int:version-db-mysql-url}} MySQL] та [{{int:version-db-percona-url}} Percona Server], які сумісні з MariaDB. ([https://www.php.net/manual/en/mysqli.installation.php Як зібрати PHP з підтримкою MySQL])",
"config-dbsupport-postgres": "* [{{int:version-db-postgres-url}} PostgreSQL] — популярна відкрита СУБД, альтернатива MySQL. ([https://www.php.net/manual/en/pgsql.installation.php як зібрати PHP з допомогою PostgreSQL]).",
- "config-dbsupport-sqlite": "* [{{int:version-db-sqlite-url}} SQLite] — легка система баз даних, яка дуже добре підтримується. ([http://www.php.net/manual/en/pdo.installation.php Як зібрати PHP з допомогою SQLite], що використовує PDO)",
- "config-dbsupport-oracle": "* [{{int:version-db-oracle-url}} Oracle] — комерційна база даних масштабу підприємства. ([http://www.php.net/manual/en/oci8.installation.php Як зібрати PHP з підтримкою OCI8])",
+ "config-dbsupport-sqlite": "* [{{int:version-db-sqlite-url}} SQLite] — легка система баз даних, яка дуже добре підтримується. ([http://www.php.net/manual/en/pdo.installation.php Як зібрати PHP з допомогою SQLite], використовує PDO)",
+ "config-dbsupport-oracle": "* [{{int:version-db-oracle-url}} Oracle] — комерційна база даних масштабу підприємства. ([http://www.php.net/manual/en/oci8.installation.php Як зібрати PHP з підтримкою OCI8])",
"config-dbsupport-mssql": "* [{{int:version-db-mssql-url}} Microsoft SQL Server] — це комерційна база даних для Windows масштабу підприємства. ([https://www.php.net/manual/en/sqlsrv.installation.php Як зібрати PHP з підтримкою SQLSRV])",
"config-header-mysql": "Налаштування MariaDB/MySQL",
"config-header-postgres": "Налаштування PostgreSQL",
"config-license-help": "Чимало загальнодоступних вікі публікують увесь свій вміст під [https://freedomdefined.org/Definition вільною ліцензією]. Це розвиває відчуття спільної власності і заохочує довготривалу участь. У загальному випадку для приватної чи корпоративної вікі у цьому немає необхідності.\n\nЯкщо Ви хочете мати змогу використовувати текст з Вікіпедії і дати Вікіпедії змогу використовувати текст, скопійований з Вашої вікі, вам необхідно обрати <strong>{{int:config-license-cc-by-sa}}</strong>.\n\nРаніше Вікіпедія використовувала GNU Free Documentation License.\nGFDL — допустима ліцензія, але у ній важко розібратися, а контент під GFDL важко використовувати повторно.",
"config-email-settings": "Налаштування електронної пошти",
"config-enable-email": "Увімкнути вихідну електронну пошту",
- "config-enable-email-help": "Якщо Ви хочете, що електронна пошта працювала, необхідно виставити коректні [Config-dbsupport-oracle/manual/en/mail.configuration.php налаштування пошти у PHP].\nЯкщо Вам не потрібні жодні можливості електронної пошти у вікі, можете тут їх відімкнути.",
+ "config-enable-email-help": "Якщо Ви хочете, що електронна пошта працювала, необхідно виставити коректні [https://www.php.net/manual/en/mail.configuration.php налаштування пошти у PHP].\nЯкщо Вам не потрібні жодні можливості електронної пошти у вікі, можете тут їх відімкнути.",
"config-email-user": "Увімкнути електронну пошту користувач-користувачеві",
"config-email-user-help": "Дозволити усім користувачам надсилати один одному електронну пошту, якщо вони увімкнули цю можливість у своїх налаштуваннях.",
"config-email-usertalk": "Увімкнути сповіщення про повідомлення на сторінці обговорення користувача",
/** @var StatsdDataFactoryInterface */
protected $stats;
- /** @var BagOStuff */
- protected $dupCache;
+ /** @var WANObjectCache */
+ protected $wanCache;
const QOS_ATOMIC = 1; // integer; "all-or-nothing" job insertions
/**
* @param array $params
+ * - type : A job type
+ * - domain : A DB domain ID
+ * - wanCache : An instance of WANObjectCache to use for caching [default: none]
+ * - stats : An instance of StatsdDataFactoryInterface [default: none]
+ * - claimTTL : Seconds a job can be claimed for exclusive execution [default: forever]
+ * - maxTries : Total times a job can be tried, assuming claims expire [default: 3]
+ * - order : Queue order, one of ("fifo", "timestamp", "random") [default: variable]
+ * - readOnlyReason : Mark the queue as read-only with this reason [default: false]
* @throws JobQueueError
*/
protected function __construct( array $params ) {
}
$this->readOnlyReason = $params['readOnlyReason'] ?? false;
$this->stats = $params['stats'] ?? new NullStatsdDataFactory();
- $this->dupCache = $params['stash'] ?? new EmptyBagOStuff();
+ $this->wanCache = $params['wanCache'] ?? WANObjectCache::newEmpty();
}
/**
* @return bool
*/
protected function doDeduplicateRootJob( IJobSpecification $job ) {
- if ( !$job->hasRootJobParams() ) {
+ $params = $job->hasRootJobParams() ? $job->getRootJobParams() : null;
+ if ( !$params ) {
throw new JobQueueError( "Cannot register root job; missing parameters." );
}
- $params = $job->getRootJobParams();
$key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
- // Callers should call JobQueueGroup::push() before this method so that if the insert
- // fails, the de-duplication registration will be aborted. Since the insert is
- // deferred till "transaction idle", do the same here, so that the ordering is
- // maintained. Having only the de-duplication registration succeed would cause
- // jobs to become no-ops without any actual jobs that made them redundant.
- $timestamp = $this->dupCache->get( $key ); // current last timestamp of this job
- if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
+ // Callers should call JobQueueGroup::push() before this method so that if the
+ // insert fails, the de-duplication registration will be aborted. Having only the
+ // de-duplication registration succeed would cause jobs to become no-ops without
+ // any actual jobs that made them redundant.
+ $timestamp = $this->wanCache->get( $key ); // last known timestamp of such a root job
+ if ( $timestamp !== false && $timestamp >= $params['rootJobTimestamp'] ) {
return true; // a newer version of this root job was enqueued
}
// Update the timestamp of the last root job started at the location...
- return $this->dupCache->set( $key, $params['rootJobTimestamp'], self::ROOTJOB_TTL );
+ return $this->wanCache->set( $key, $params['rootJobTimestamp'], self::ROOTJOB_TTL );
}
/**
if ( $job->getType() !== $this->type ) {
throw new JobQueueError( "Got '{$job->getType()}' job; expected '{$this->type}'." );
}
- $isDuplicate = $this->doIsRootJobOldDuplicate( $job );
- return $isDuplicate;
+ return $this->doIsRootJobOldDuplicate( $job );
}
/**
* @return bool
*/
protected function doIsRootJobOldDuplicate( IJobSpecification $job ) {
- if ( !$job->hasRootJobParams() ) {
+ $params = $job->hasRootJobParams() ? $job->getRootJobParams() : null;
+ if ( !$params ) {
return false; // job has no de-deplication info
}
- $params = $job->getRootJobParams();
$key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
// Get the last time this root job was enqueued
- $timestamp = $this->dupCache->get( $key );
+ $timestamp = $this->wanCache->get( $key );
+ if ( $timestamp === false || $params['rootJobTimestamp'] > $timestamp ) {
+ // Update the timestamp of the last known root job started at the location...
+ $this->wanCache->set( $key, $params['rootJobTimestamp'], self::ROOTJOB_TTL );
+ }
// Check if a new root job was started at the location after this one's...
return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
* @return string
*/
protected function getRootJobCacheKey( $signature ) {
- return $this->dupCache->makeGlobalKey(
+ return $this->wanCache->makeGlobalKey(
'jobqueue',
$this->domain,
$this->type,
use Wikimedia\Rdbms\DBConnectionError;
use Wikimedia\Rdbms\DBError;
use MediaWiki\MediaWikiServices;
+use Wikimedia\Rdbms\IMaintainableDatabase;
use Wikimedia\ScopedCallback;
/**
const MAX_JOB_RANDOM = 2147483647; // integer; 2^31 - 1, used for job_random
const MAX_OFFSET = 255; // integer; maximum number of rows to skip
- /** @var WANObjectCache */
- protected $cache;
- /** @var IDatabase|DBError|null */
+ /** @var IMaintainableDatabase|DBError|null */
protected $conn;
/** @var array|null Server configuration array */
* If not specified, the primary DB cluster for the wiki will be used.
* This can be overridden with a custom cluster so that DB handles will
* be retrieved via LBFactory::getExternalLB() and getConnection().
- * - wanCache : An instance of WANObjectCache to use for caching.
* @param array $params
*/
protected function __construct( array $params ) {
} elseif ( isset( $params['cluster'] ) && is_string( $params['cluster'] ) ) {
$this->cluster = $params['cluster'];
}
-
- $this->cache = $params['wanCache'] ?? WANObjectCache::newEmpty();
}
protected function supportedOrders() {
protected function doGetSize() {
$key = $this->getCacheKey( 'size' );
- $size = $this->cache->get( $key );
+ $size = $this->wanCache->get( $key );
if ( is_int( $size ) ) {
return $size;
}
} catch ( DBError $e ) {
throw $this->getDBException( $e );
}
- $this->cache->set( $key, $size, self::CACHE_TTL_SHORT );
+ $this->wanCache->set( $key, $size, self::CACHE_TTL_SHORT );
return $size;
}
$key = $this->getCacheKey( 'acquiredcount' );
- $count = $this->cache->get( $key );
+ $count = $this->wanCache->get( $key );
if ( is_int( $count ) ) {
return $count;
}
} catch ( DBError $e ) {
throw $this->getDBException( $e );
}
- $this->cache->set( $key, $count, self::CACHE_TTL_SHORT );
+ $this->wanCache->set( $key, $count, self::CACHE_TTL_SHORT );
return $count;
}
$key = $this->getCacheKey( 'abandonedcount' );
- $count = $this->cache->get( $key );
+ $count = $this->wanCache->get( $key );
if ( is_int( $count ) ) {
return $count;
}
throw $this->getDBException( $e );
}
- $this->cache->set( $key, $count, self::CACHE_TTL_SHORT );
+ $this->wanCache->set( $key, $count, self::CACHE_TTL_SHORT );
return $count;
}
/** @noinspection PhpUnusedLocalVariableInspection */
$scope = $this->getScopedNoTrxFlag( $dbw );
// Check cache to see if the queue has <= OFFSET items
- $tinyQueue = $this->cache->get( $this->getCacheKey( 'small' ) );
+ $tinyQueue = $this->wanCache->get( $this->getCacheKey( 'small' ) );
$invertedDirection = false; // whether one job_random direction was already scanned
// This uses a replication safe method for acquiring jobs. One could use UPDATE+LIMIT
);
if ( !$row ) {
$tinyQueue = true; // we know the queue must have <= MAX_OFFSET rows
- $this->cache->set( $this->getCacheKey( 'small' ), 1, 30 );
+ $this->wanCache->set( $this->getCacheKey( 'small' ), 1, 30 );
continue; // use job_random
}
}
* @return bool
*/
protected function doDeduplicateRootJob( IJobSpecification $job ) {
- $params = $job->getParams();
- if ( !isset( $params['rootJobSignature'] ) ) {
- throw new MWException( "Cannot register root job; missing 'rootJobSignature'." );
- } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
- throw new MWException( "Cannot register root job; missing 'rootJobTimestamp'." );
- }
- $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
- // Callers should call JobQueueGroup::push() before this method so that if the insert
- // fails, the de-duplication registration will be aborted. Since the insert is
- // deferred till "transaction idle", do the same here, so that the ordering is
+ // Callers should call JobQueueGroup::push() before this method so that if the
+ // insert fails, the de-duplication registration will be aborted. Since the insert
+ // is deferred till "transaction idle", do the same here, so that the ordering is
// maintained. Having only the de-duplication registration succeed would cause
// jobs to become no-ops without any actual jobs that made them redundant.
$dbw = $this->getMasterDB();
/** @noinspection PhpUnusedLocalVariableInspection */
$scope = $this->getScopedNoTrxFlag( $dbw );
-
- $cache = $this->dupCache;
$dbw->onTransactionCommitOrIdle(
- function () use ( $cache, $params, $key ) {
- $timestamp = $cache->get( $key ); // current last timestamp of this job
- if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
- return true; // a newer version of this root job was enqueued
- }
-
- // Update the timestamp of the last root job started at the location...
- return $cache->set( $key, $params['rootJobTimestamp'], JobQueueDB::ROOTJOB_TTL );
+ function () use ( $job ) {
+ parent::doDeduplicateRootJob( $job );
},
__METHOD__
);
*/
protected function doFlushCaches() {
foreach ( [ 'size', 'acquiredcount' ] as $type ) {
- $this->cache->delete( $this->getCacheKey( $type ) );
+ $this->wanCache->delete( $this->getCacheKey( $type ) );
}
}
/**
* @throws JobQueueConnectionError
- * @return IDatabase
+ * @return IMaintainableDatabase
*/
protected function getMasterDB() {
try {
/**
* @param int $index (DB_REPLICA/DB_MASTER)
- * @return IDatabase
+ * @return IMaintainableDatabase
*/
protected function getDB( $index ) {
if ( $this->server ) {
? $lbFactory->getExternalLB( $this->cluster )
: $lbFactory->getMainLB( $this->domain );
- return ( $lb->getServerType( $lb->getWriterIndex() ) !== 'sqlite' )
+ if ( $lb->getServerType( $lb->getWriterIndex() ) !== 'sqlite' ) {
// Keep a separate connection to avoid contention and deadlocks;
// However, SQLite has the opposite behavior due to DB-level locking.
- ? $lb->getConnectionRef( $index, [], $this->domain, $lb::CONN_TRX_AUTOCOMMIT )
+ $flags = $lb::CONN_TRX_AUTOCOMMIT;
+ } else {
// Jobs insertion will be defered until the PRESEND stage to reduce contention.
- : $lb->getConnectionRef( $index, [], $this->domain );
+ $flags = 0;
+ }
+
+ return $lb->getMaintenanceConnectionRef( $index, [], $this->domain, $flags );
}
}
private function getCacheKey( $property ) {
$cluster = is_string( $this->cluster ) ? $this->cluster : 'main';
- return $this->cache->makeGlobalKey(
+ return $this->wanCache->makeGlobalKey(
'jobqueue',
$this->domain,
$cluster,
$services = MediaWikiServices::getInstance();
$conf['stats'] = $services->getStatsdDataFactory();
$conf['wanCache'] = $services->getMainWANObjectCache();
- $conf['stash'] = $services->getMainObjectStash();
return JobQueue::factory( $conf );
}
protected static $data = [];
public function __construct( array $params ) {
- parent::__construct( $params );
+ $params['wanCache'] = new WANObjectCache( [ 'cache' => new HashBagOStuff() ] );
- $this->dupCache = new HashBagOStuff();
+ parent::__construct( $params );
}
/**
$conn = $this->getConnection();
try {
- $timestamp = $conn->get( $key ); // current last timestamp of this job
+ $timestamp = $conn->get( $key ); // last known timestamp of such a root job
if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
return true; // a newer version of this root job was enqueued
}
public function run() {
$lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
$lb = $lbFactory->getMainLB();
- $dbw = $lb->getConnection( DB_MASTER );
+ $dbw = $lb->getConnectionRef( DB_MASTER );
$this->ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__ );
}
// Cut down on the time spent in waitForMasterPos() in the critical section
- $dbr = $lb->getConnection( DB_REPLICA, [ 'recentchanges' ] );
+ $dbr = $lb->getConnectionRef( DB_REPLICA, [ 'recentchanges' ] );
if ( !$lb->waitForMasterPos( $dbr ) ) {
$this->setLastError( "Timed out while pre-waiting for replica DB to catch up" );
return false;
$batchSize = $wgUpdateRowsPerQuery;
$loadBalancer = MediaWikiServices::getInstance()->getDBLoadBalancer();
- $dbw = $loadBalancer->getConnection( DB_MASTER );
- $dbr = $loadBalancer->getConnection( DB_REPLICA, [ 'watchlist' ] );
+ $dbw = $loadBalancer->getConnectionRef( DB_MASTER );
+ $dbr = $loadBalancer->getConnectionRef( DB_REPLICA, [ 'watchlist' ] );
// Wait before lock to try to reduce time waiting in the lock.
if ( !$loadBalancer->waitForMasterPos( $dbr ) ) {
$lbFactory = $services->getDBLoadBalancerFactory();
$rowsPerQuery = $services->getMainConfig()->get( 'UpdateRowsPerQuery' );
- $dbw = $lbFactory->getMainLB()->getConnection( DB_MASTER );
+ $dbw = $lbFactory->getMainLB()->getConnectionRef( DB_MASTER );
$ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__ );
$timestamp = $this->params['timestamp'] ?? null;
if ( $timestamp === null ) {
// Serialize link update job by page ID so they see each others' changes.
// The page ID and latest revision ID will be queried again after the lock
// is acquired to bail if they are changed from that of loadPageData() above.
- $dbw = $lbFactory->getMainLB()->getConnection( DB_MASTER );
+ // Serialize links updates by page ID so they see each others' changes
+ $dbw = $lbFactory->getMainLB()->getConnectionRef( DB_MASTER );
+ /** @noinspection PhpUnusedLocalVariableInspection */
$scopedLock = LinksUpdate::acquirePageLock( $dbw, $page->getId(), 'job' );
if ( $scopedLock === null ) {
// Another job is already updating the page, likely for a prior revision (T170596)
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerInterface;
use Wikimedia\ScopedCallback;
+use Psr\Log\NullLogger;
/**
* @brief Base class for all file backend classes (including multi-write backends).
if ( !is_callable( $this->profiler ) ) {
$this->profiler = null;
}
- $this->logger = $config['logger'] ?? new \Psr\Log\NullLogger();
+ $this->logger = $config['logger'] ?? new NullLogger();
$this->statusWrapper = $config['statusWrapper'] ?? null;
$this->tmpDirectory = $config['tmpDirectory'] ?? null;
}
/** @var float */
protected $connTimeout = 10;
/** @var float */
- protected $reqTimeout = 300;
+ protected $reqTimeout = 900;
/** @var bool */
protected $usePipelining = false;
/** @var int */
* @ingroup FileBackend
*/
use Psr\Log\LoggerInterface;
+use Psr\Log\NullLogger;
use Wikimedia\WaitConditionLoop;
/**
}
$this->session = md5( implode( '-', $random ) );
- $this->logger = $config['logger'] ?? new \Psr\Log\NullLogger();
+ $this->logger = $config['logger'] ?? new NullLogger();
}
/**
*/
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerInterface;
+use Psr\Log\NullLogger;
/**
* Implements functions related to MIME types such as detection and mapping to file extension
$this->detectCallback = $params['detectCallback'] ?? null;
$this->guessCallback = $params['guessCallback'] ?? null;
$this->extCallback = $params['extCallback'] ?? null;
- $this->logger = $params['logger'] ?? new \Psr\Log\NullLogger();
+ $this->logger = $params['logger'] ?? new NullLogger();
$this->loadFiles();
}
/**
* Get an associative array containing the item for each of the keys that have items.
- * @param string[] $keys List of keys
+ * @param string[] $keys List of keys; can be a map of (unused => key) for convenience
* @param int $flags Bitfield; supports READ_LATEST [optional]
- * @return array Map of (key => value) for existing keys
+ * @return mixed[] Map of (key => value) for existing keys; preserves the order of $keys
*/
public function getMulti( array $keys, $flags = 0 ) {
- $valuesBykey = $this->doGetMulti( $keys, $flags );
- foreach ( $valuesBykey as $key => $value ) {
+ $foundByKey = $this->doGetMulti( $keys, $flags );
+
+ $res = [];
+ foreach ( $keys as $key ) {
// Resolve one blob at a time (avoids too much I/O at once)
- $valuesBykey[$key] = $this->resolveSegments( $key, $value );
+ if ( array_key_exists( $key, $foundByKey ) ) {
+ // A value should not appear in the key if a segment is missing
+ $value = $this->resolveSegments( $key, $foundByKey[$key] );
+ if ( $value !== false ) {
+ $res[$key] = $value;
+ }
+ }
}
- return $valuesBykey;
+ return $res;
}
/**
* Get an associative array containing the item for each of the keys that have items.
* @param string[] $keys List of keys
* @param int $flags Bitfield; supports READ_LATEST [optional]
- * @return array Map of (key => value) for existing keys
+ * @return mixed[] Map of (key => value) for existing keys
*/
protected function doGetMulti( array $keys, $flags = 0 ) {
$res = [];
* Type: Measure (in milliseconds).
* Variable `kClass`: The first part of your cache key.
+#### `wanobjectcache.{kClass}.regen_walltime`
+
+Upon cache miss, this measures the time spent in `WANObjectCache::getWithSetCallback()`
+from the start of the callback to right after the new value has been computed.
+
+* Type: Measure (in milliseconds).
+* Variable `kClass`: The first part of your cache key.
+
#### `wanobjectcache.{kClass}.ck_touch.{result}`
Call counter from `WANObjectCache::touchCheckKey()`.
if ( $ttl ) {
$result = $conn->setex( $key, $ttl, $this->serialize( $value ) );
} else {
- // No expiry, that is very different from zero expiry in Redis
$result = $conn->set( $key, $this->serialize( $value ) );
}
} catch ( RedisException $e ) {
$this->debug( "setMulti request to $server failed" );
continue;
}
- foreach ( $batchResult as $value ) {
- if ( $value === false ) {
- $result = false;
- }
- }
+ $result = $result && !in_array( false, $batchResult, true );
} catch ( RedisException $e ) {
$this->handleException( $conn, $e );
$result = false;
$this->debug( "deleteMulti request to $server failed" );
continue;
}
- foreach ( $batchResult as $value ) {
- if ( $value === false ) {
- $result = false;
- }
- }
+ $result = $result && !in_array( false, $batchResult, true );
} catch ( RedisException $e ) {
$this->handleException( $conn, $e );
$result = false;
if ( !$conn ) {
return false;
}
- $expiry = $this->convertToRelative( $expiry );
+
+ $ttl = $this->convertToRelative( $expiry );
try {
- if ( $expiry ) {
- $result = $conn->set(
- $key,
- $this->serialize( $value ),
- [ 'nx', 'ex' => $expiry ]
- );
- } else {
- $result = $conn->setnx( $key, $this->serialize( $value ) );
- }
+ $result = $conn->set(
+ $key,
+ $this->serialize( $value ),
+ $ttl ? [ 'nx', 'ex' => $ttl ] : [ 'nx' ]
+ );
} catch ( RedisException $e ) {
$result = false;
$this->handleException( $conn, $e );
}
$this->logRequest( 'add', $key, $server, $result );
+
return $result;
}
- /**
- * Non-atomic implementation of incr().
- *
- * Probably all callers actually want incr() to atomically initialise
- * values to zero if they don't exist, as provided by the Redis INCR
- * command. But we are constrained by the memcached-like interface to
- * return null in that case. Once the key exists, further increments are
- * atomic.
- * @param string $key Key to increase
- * @param int $value Value to add to $key (Default 1)
- * @return int|bool New value or false on failure
- */
public function incr( $key, $value = 1 ) {
list( $server, $conn ) = $this->getConnection( $key );
if ( !$conn ) {
return false;
}
+
try {
- if ( !$conn->exists( $key ) ) {
- return false;
+ $conn->watch( $key );
+ if ( $conn->exists( $key ) ) {
+ $conn->multi( Redis::MULTI );
+ $conn->incrBy( $key, $value );
+ $batchResult = $conn->exec();
+ if ( $batchResult === false ) {
+ $result = false;
+ } else {
+ $result = end( $batchResult );
+ }
+ } else {
+ $result = false;
+ $conn->unwatch();
}
- // @FIXME: on races, the key may have a 0 TTL
- $result = $conn->incrBy( $key, $value );
} catch ( RedisException $e ) {
+ try {
+ $conn->unwatch(); // sanity
+ } catch ( RedisException $ex ) {
+ // already errored
+ }
$result = false;
$this->handleException( $conn, $e );
}
$this->logRequest( 'incr', $key, $server, $result );
+
+ return $result;
+ }
+
+ public function incrWithInit( $key, $exptime, $value = 1, $init = 1 ) {
+ list( $server, $conn ) = $this->getConnection( $key );
+ if ( !$conn ) {
+ return false;
+ }
+
+ $ttl = $this->convertToRelative( $exptime );
+ $preIncrInit = $init - $value;
+ try {
+ $conn->multi( Redis::MULTI );
+ $conn->set( $key, $preIncrInit, $ttl ? [ 'nx', 'ex' => $ttl ] : [ 'nx' ] );
+ $conn->incrBy( $key, $value );
+ $batchResult = $conn->exec();
+ if ( $batchResult === false ) {
+ $result = false;
+ $this->debug( "incrWithInit request to $server failed" );
+ } else {
+ $result = end( $batchResult );
+ }
+ } catch ( RedisException $e ) {
+ $result = false;
+ $this->handleException( $conn, $e );
+ }
+
+ $this->logRequest( 'incr', $key, $server, $result );
+
return $result;
}
protected $asyncHandler;
/** @var float Unix timestamp of the oldest possible valid values */
protected $epoch;
+ /** @var string Stable secret used for hasing long strings into key components */
+ protected $secret;
/** @var int Callback stack depth for getWithSetCallback() */
private $callbackDepth = 0;
* is configured to interpret /<region>/<cluster>/ key prefixes as routes. This
* requires that "region" and "cluster" are both set above. [optional]
* - epoch: lowest UNIX timestamp a value/tombstone must have to be valid. [optional]
+ * - secret: stable secret used for hashing long strings into key components. [optional]
*/
public function __construct( array $params ) {
$this->cache = $params['cache'];
$this->cluster = $params['cluster'] ?? 'wan-main';
$this->mcrouterAware = !empty( $params['mcrouterAware'] );
$this->epoch = $params['epoch'] ?? self::EPOCH_UNIX_ONE_SECOND;
+ $this->secret = $params['secret'] ?? (string)$this->epoch;
$this->setLogger( $params['logger'] ?? new NullLogger() );
$this->stats = $params['stats'] ?? new NullStatsdDataFactory();
*
* @param string $key Cache key made from makeKey() or makeGlobalKey()
* @param mixed|null &$curTTL Approximate TTL left on the key if present/tombstoned [returned]
- * @param array $checkKeys List of "check" keys
+ * @param string[] $checkKeys The "check" keys used to validate the value
* @param mixed|null &$info Key info if WANObjectCache::PASS_BY_REF [returned]
* @return mixed Value of cache key or false on failure
*/
* Othwerwise, $info will transform into a map of (cache key => cached value timestamp).
* Only the cache keys listed in $keys that exists or are tombstoned will have an entry.
*
+ * $checkKeys holds the "check" keys used to validate values of applicable keys. The integer
+ * indexes hold "check" keys that apply to all of $keys while the string indexes hold "check"
+ * keys that only apply to the cache key with that name.
+ *
* @see WANObjectCache::get()
*
- * @param array $keys List of cache keys made from makeKey() or makeGlobalKey()
+ * @param string[] $keys List of cache keys made from makeKey() or makeGlobalKey()
* @param mixed|null &$curTTLs Map of (key => TTL left) for existing/tombstoned keys [returned]
- * @param array $checkKeys List of check keys to apply to all $keys. May also apply "check"
- * keys to specific cache keys only by using cache keys as keys in the $checkKeys array.
+ * @param string[]|string[][] $checkKeys Map of (integer or cache key => "check" key(s))
* @param mixed|null &$info Map of (key => info) if WANObjectCache::PASS_BY_REF [returned]
- * @return array Map of (key => value) for keys that exist and are not tombstoned
+ * @return mixed[] Map of (key => value) for existing values; order of $keys is preserved
*/
final public function getMulti(
array $keys,
/**
* @since 1.27
- * @param array $timeKeys List of prefixed time check keys
- * @param array $wrappedValues
+ * @param string[] $timeKeys List of prefixed time check keys
+ * @param mixed[] $wrappedValues
* @param float $now
- * @return array List of purge value arrays
+ * @return array[] List of purge value arrays
*/
private function processCheckKeys( array $timeKeys, array $wrappedValues, $now ) {
$purgeValues = [];
* @see WANObjectCache::getCheckKeyTime()
* @see WANObjectCache::getWithSetCallback()
*
- * @param array $keys
+ * @param string[] $keys
* @return float[] Map of (key => UNIX timestamp)
* @since 1.31
*/
) {
// How long it took to generate the value
$walltime = max( $postCallbackTime - $preCallbackTime, 0.0 );
+ $this->stats->timing( "wanobjectcache.$kClass.regen_walltime", 1e3 * $walltime );
// If the key is write-holed then use the (volatile) interim key as an alternative
if ( $isKeyTombstoned ) {
$this->setInterimValue( $key, $value, $lockTSE, $version, $walltime );
* // Map of cache keys to entity IDs
* $cache->makeMultiKeys(
* $this->fileVersionIds(),
- * function ( $id, WANObjectCache $cache ) {
+ * function ( $id ) use ( $cache ) {
* return $cache->makeKey( 'file-version', $id );
* }
* ),
* @param int $ttl Seconds to live for key updates
* @param callable $callback Callback the yields entity regeneration callbacks
* @param array $opts Options map
- * @return array Map of (cache key => value) in the same order as $keyedIds
+ * @return mixed[] Map of (cache key => value) in the same order as $keyedIds
* @since 1.28
*/
final public function getMultiWithSetCallback(
ArrayIterator $keyedIds, $ttl, callable $callback, array $opts = []
) {
- $valueKeys = array_keys( $keyedIds->getArrayCopy() );
-
// Load required keys into process cache in one go
$this->warmupCache = $this->getRawKeysForWarmup(
- $this->getNonProcessCachedKeys( $valueKeys, $opts ),
+ $this->getNonProcessCachedMultiKeys( $keyedIds, $opts ),
$opts['checkKeys'] ?? []
);
$this->warmupKeyMisses = 0;
* // Map of cache keys to entity IDs
* $cache->makeMultiKeys(
* $this->fileVersionIds(),
- * function ( $id, WANObjectCache $cache ) {
+ * function ( $id ) use ( $cache ) {
* return $cache->makeKey( 'file-version', $id );
* }
* ),
* @param int $ttl Seconds to live for key updates
* @param callable $callback Callback the yields entity regeneration callbacks
* @param array $opts Options map
- * @return array Map of (cache key => value) in the same order as $keyedIds
+ * @return mixed[] Map of (cache key => value) in the same order as $keyedIds
* @since 1.30
*/
final public function getMultiWithUnionSetCallback(
ArrayIterator $keyedIds, $ttl, callable $callback, array $opts = []
) {
- $idsByValueKey = $keyedIds->getArrayCopy();
- $valueKeys = array_keys( $idsByValueKey );
$checkKeys = $opts['checkKeys'] ?? [];
unset( $opts['lockTSE'] ); // incompatible
unset( $opts['busyValue'] ); // incompatible
// Load required keys into process cache in one go
- $keysGet = $this->getNonProcessCachedKeys( $valueKeys, $opts );
- $this->warmupCache = $this->getRawKeysForWarmup( $keysGet, $checkKeys );
+ $keysByIdGet = $this->getNonProcessCachedMultiKeys( $keyedIds, $opts );
+ $this->warmupCache = $this->getRawKeysForWarmup( $keysByIdGet, $checkKeys );
$this->warmupKeyMisses = 0;
// IDs of entities known to be in need of regeneration
// Find out which keys are missing/deleted/stale
$curTTLs = [];
$asOfs = [];
- $curByKey = $this->getMulti( $keysGet, $curTTLs, $checkKeys, $asOfs );
- foreach ( $keysGet as $key ) {
+ $curByKey = $this->getMulti( $keysByIdGet, $curTTLs, $checkKeys, $asOfs );
+ foreach ( $keysByIdGet as $id => $key ) {
if ( !array_key_exists( $key, $curByKey ) || $curTTLs[$key] < 0 ) {
- $idsRegen[] = $idsByValueKey[$key];
+ $idsRegen[] = $id;
}
}
// Run the cache-aside logic using warmupCache instead of persistent cache queries
$values = [];
- foreach ( $idsByValueKey as $key => $id ) { // preserve order
+ foreach ( $keyedIds as $key => $id ) { // preserve order
$values[$key] = $this->getWithSetCallback( $key, $ttl, $func, $opts );
}
}
/**
- * @param array $entities List of entity IDs
- * @param callable $keyFunc Callback yielding a key from (entity ID, this WANObjectCache)
- * @return ArrayIterator Iterator yielding (cache key => entity ID) in $entities order
+ * Hash a possibly long string into a suitable component for makeKey()/makeGlobalKey()
+ *
+ * @param string $component A raw component used in building a cache key
+ * @return string 64 character HMAC using a stable secret for public collision resistance
+ * @since 1.34
+ */
+ public function hash256( $component ) {
+ return hash_hmac( 'sha256', $component, $this->secret );
+ }
+
+ /**
+ * Get an iterator of (cache key => entity ID) for a list of entity IDs
+ *
+ * The callback takes an ID string and returns a key via makeKey()/makeGlobalKey().
+ * There should be no network nor filesystem I/O used in the callback. The entity
+ * ID/key mapping must be 1:1 or an exception will be thrown. If hashing is needed,
+ * then use the hash256() method.
+ *
+ * Example usage for the default keyspace:
+ * @code
+ * $keyedIds = $cache->makeMultiKeys(
+ * $modules,
+ * function ( $module ) use ( $cache ) {
+ * return $cache->makeKey( 'module-info', $module );
+ * }
+ * );
+ * @endcode
+ *
+ * Example usage for mixed default and global keyspace:
+ * @code
+ * $keyedIds = $cache->makeMultiKeys(
+ * $filters,
+ * function ( $filter ) use ( $cache ) {
+ * return ( strpos( $filter, 'central:' ) === 0 )
+ * ? $cache->makeGlobalKey( 'regex-filter', $filter )
+ * : $cache->makeKey( 'regex-filter', $filter )
+ * }
+ * );
+ * @endcode
+ *
+ * Example usage with hashing:
+ * @code
+ * $keyedIds = $cache->makeMultiKeys(
+ * $urls,
+ * function ( $url ) use ( $cache ) {
+ * return $cache->makeKey( 'url-info', $cache->hash256( $url ) );
+ * }
+ * );
+ * @endcode
+ *
+ * @see WANObjectCache::makeKey()
+ * @see WANObjectCache::makeGlobalKey()
+ * @see WANObjectCache::hash256()
+ *
+ * @param string[]|int[] $ids List of entity IDs
+ * @param callable $keyCallback Function returning makeKey()/makeGlobalKey() on the input ID
+ * @return ArrayIterator Iterator of (cache key => ID); order of $ids is preserved
+ * @throws UnexpectedValueException
* @since 1.28
*/
- final public function makeMultiKeys( array $entities, callable $keyFunc ) {
- $map = [];
- foreach ( $entities as $entity ) {
- $map[$keyFunc( $entity, $this )] = $entity;
+ final public function makeMultiKeys( array $ids, $keyCallback ) {
+ $idByKey = [];
+ foreach ( $ids as $id ) {
+ // Discourage triggering of automatic makeKey() hashing in some backends
+ if ( strlen( $id ) > 64 ) {
+ $this->logger->warning( __METHOD__ . ": long ID '$id'; use hash256()" );
+ }
+ $key = $keyCallback( $id, $this );
+ // Edge case: ignore key collisions due to duplicate $ids like "42" and 42
+ if ( !isset( $idByKey[$key] ) ) {
+ $idByKey[$key] = $id;
+ } elseif ( (string)$id !== (string)$idByKey[$key] ) {
+ throw new UnexpectedValueException(
+ "Cache key collision; IDs ('$id','{$idByKey[$key]}') map to '$key'"
+ );
+ }
+ }
+
+ return new ArrayIterator( $idByKey );
+ }
+
+ /**
+ * Get an (ID => value) map from (i) a non-unique list of entity IDs, and (ii) the list
+ * of corresponding entity values by first appearance of each ID in the entity ID list
+ *
+ * For use with getMultiWithSetCallback() and getMultiWithUnionSetCallback().
+ *
+ * *Only* use this method if the entity ID/key mapping is trivially 1:1 without exception.
+ * Key generation method must utitilize the *full* entity ID in the key (not a hash of it).
+ *
+ * Example usage:
+ * @code
+ * $poems = $cache->getMultiWithSetCallback(
+ * $cache->makeMultiKeys(
+ * $uuids,
+ * function ( $uuid ) use ( $cache ) {
+ * return $cache->makeKey( 'poem', $uuid );
+ * }
+ * ),
+ * $cache::TTL_DAY,
+ * function ( $uuid ) use ( $url ) {
+ * return $this->http->run( [ 'method' => 'GET', 'url' => "$url/$uuid" ] );
+ * }
+ * );
+ * $poemsByUUID = $cache->multiRemap( $uuids, $poems );
+ * @endcode
+ *
+ * @see WANObjectCache::makeMultiKeys()
+ * @see WANObjectCache::getMultiWithSetCallback()
+ * @see WANObjectCache::getMultiWithUnionSetCallback()
+ *
+ * @param string[]|int[] $ids Entity ID list makeMultiKeys()
+ * @param mixed[] $res Result of getMultiWithSetCallback()/getMultiWithUnionSetCallback()
+ * @return mixed[] Map of (ID => value); order of $ids is preserved
+ * @since 1.34
+ */
+ final public function multiRemap( array $ids, array $res ) {
+ if ( count( $ids ) !== count( $res ) ) {
+ // If makeMultiKeys() is called on a list of non-unique IDs, then the resulting
+ // ArrayIterator will have less entries due to "first appearance" de-duplication
+ $ids = array_keys( array_flip( $ids ) );
+ if ( count( $ids ) !== count( $res ) ) {
+ throw new UnexpectedValueException( "Multi-key result does not match ID list" );
+ }
}
- return new ArrayIterator( $map );
+ return array_combine( $ids, $res );
}
/**
}
/**
- * @param array $keys
+ * @param string[] $keys
* @param string $prefix
- * @return string[]
+ * @return string[] Prefix keys; the order of $keys is preserved
*/
protected static function prefixCacheKeys( array $keys, $prefix ) {
$res = [];
}
/**
- * @param array $keys
+ * @param ArrayIterator $keys
* @param array $opts
- * @return string[] List of keys
+ * @return string[] Map of (ID => cache key)
*/
- private function getNonProcessCachedKeys( array $keys, array $opts ) {
+ private function getNonProcessCachedMultiKeys( ArrayIterator $keys, array $opts ) {
$pcTTL = $opts['pcTTL'] ?? self::TTL_UNCACHEABLE;
- $keysFound = [];
+ $keysMissing = [];
if ( $pcTTL > 0 && $this->callbackDepth == 0 ) {
$version = $opts['version'] ?? null;
$pCache = $this->getProcessCache( $opts['pcGroup'] ?? self::PC_PRIMARY );
- foreach ( $keys as $key ) {
- if ( $pCache->has( $this->getProcessCacheKey( $key, $version ), $pcTTL ) ) {
- $keysFound[] = $key;
+ foreach ( $keys as $key => $id ) {
+ if ( !$pCache->has( $this->getProcessCacheKey( $key, $version ), $pcTTL ) ) {
+ $keysMissing[$id] = $key;
}
}
}
- return array_diff( $keys, $keysFound );
+ return $keysMissing;
}
/**
- * @param array $keys
- * @param array $checkKeys
- * @return array Map of (cache key => mixed)
+ * @param string[] $keys
+ * @param string[]|string[][] $checkKeys
+ * @return string[] List of cache keys
*/
private function getRawKeysForWarmup( array $keys, array $checkKeys ) {
if ( !$keys ) {
return $this->__call( __FUNCTION__, func_get_args() );
}
- public function setLBInfo( $name, $value = null ) {
+ public function setLBInfo( $nameOrArray, $value = null ) {
// Disallow things that might confuse the LoadBalancer tracking
throw new DBUnexpectedError( $this, "Changing LB info is disallowed to enable reuse." );
}
return null;
}
- public function setLBInfo( $name, $value = null ) {
- if ( is_null( $value ) ) {
- $this->lbInfo = $name;
+ public function setLBInfo( $nameOrArray, $value = null ) {
+ if ( is_array( $nameOrArray ) ) {
+ $this->lbInfo = $nameOrArray;
+ } elseif ( is_string( $nameOrArray ) ) {
+ if ( $value !== null ) {
+ $this->lbInfo[$nameOrArray] = $value;
+ } else {
+ unset( $this->lbInfo[$nameOrArray] );
+ }
} else {
- $this->lbInfo[$name] = $value;
+ throw new InvalidArgumentException( "Got non-string key" );
}
}
}
/**
+ * @param string $prefix Only show tables with this prefix, e.g. mw_
+ * @param string $fname Calling function name
+ * @return string[]
* @suppress SecurityCheck-SQLInjection array_map not recognized T204911
*/
- public function listTables( $prefix = null, $fname = __METHOD__ ) {
+ public function listTables( $prefix = '', $fname = __METHOD__ ) {
$eschemas = implode( ',', array_map( [ $this, 'addQuotes' ], $this->getCoreSchemas() ) );
$result = $this->query(
"SELECT DISTINCT tablename FROM pg_tables WHERE schemaname IN ($eschemas)", $fname );
foreach ( $result as $table ) {
$vars = get_object_vars( $table );
$table = array_pop( $vars );
- if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
+ if ( $prefix == '' || strpos( $table, $prefix ) === 0 ) {
$endArray[] = $table;
}
}
if ( self::$fulltextEnabled === null ) {
self::$fulltextEnabled = false;
$table = $this->tableName( 'searchindex' );
- $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__ );
+ $res = $this->query(
+ "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'",
+ __METHOD__,
+ self::QUERY_IGNORE_DBO_TRX
+ );
if ( $res ) {
$row = $res->fetchRow();
self::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
$file = is_string( $file ) ? $file : self::generateFileName( $this->dbDir, $name );
$encFile = $this->addQuotes( $file );
- return $this->query( "ATTACH DATABASE $encFile AS $name", $fname );
+ return $this->query(
+ "ATTACH DATABASE $encFile AS $name",
+ $fname,
+ self::QUERY_IGNORE_DBO_TRX
+ );
}
protected function isWriteQuery( $sql ) {
$encTable = $this->addQuotes( $tableRaw );
$res = $this->query(
- "SELECT 1 FROM sqlite_master WHERE type='table' AND name=$encTable" );
+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name=$encTable",
+ __METHOD__,
+ self::QUERY_IGNORE_DBO_TRX
+ );
return $res->numRows() ? true : false;
}
*/
function indexInfo( $table, $index, $fname = __METHOD__ ) {
$sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
- $res = $this->query( $sql, $fname );
+ $res = $this->query( $sql, $fname, self::QUERY_IGNORE_DBO_TRX );
if ( !$res || $res->numRows() == 0 ) {
return false;
}
function fieldInfo( $table, $field ) {
$tableName = $this->tableName( $table );
$sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
- $res = $this->query( $sql, __METHOD__ );
+ $res = $this->query( $sql, __METHOD__, self::QUERY_IGNORE_DBO_TRX );
foreach ( $res as $row ) {
if ( $row->name == $field ) {
return new SQLiteField( $row, $tableName );
}
$sql = "DROP TABLE " . $this->tableName( $tableName );
- return $this->query( $sql, $fName );
+ return $this->query( $sql, $fName, self::QUERY_IGNORE_DBO_TRX );
}
public function setTableAliases( array $aliases ) {
public function resetSequenceForTable( $table, $fname = __METHOD__ ) {
$encTable = $this->addIdentifierQuotes( 'sqlite_sequence' );
$encName = $this->addQuotes( $this->tableName( $table, 'raw' ) );
- $this->query( "DELETE FROM $encTable WHERE name = $encName", $fname );
+ $this->query(
+ "DELETE FROM $encTable WHERE name = $encName",
+ $fname,
+ self::QUERY_IGNORE_DBO_TRX
+ );
}
public function databasesAreIndependent() {
public function getLBInfo( $name = null );
/**
- * Set the LB info array, or a member of it. If called with one parameter,
- * the LB info array is set to that parameter. If it is called with two
- * parameters, the member with the given name is set to the given value.
+ * Set the entire array or a particular key of the managing load balancer info array
*
- * @param array|string $name
- * @param array|null $value
+ * @param array|string $nameOrArray The new array or the name of a key to set
+ * @param array|null $value If $nameOrArray is a string, the new key value (null to unset)
*/
- public function setLBInfo( $name, $value = null );
+ public function setLBInfo( $nameOrArray, $value = null );
/**
* Set a lazy-connecting DB handle to the master DB (for replication status purposes)
/**
* Change the current database
*
- * This should not be called outside LoadBalancer for connections managed by a LoadBalancer
+ * This should only be called by a load balancer or if the handle is not attached to one
*
* @param string $db
* @return bool True unless an exception was thrown
/**
* Set the current domain (database, schema, and table prefix)
*
- * This will throw an error for some database types if the database unspecified
+ * This will throw an error for some database types if the database is unspecified
*
- * This should not be called outside LoadBalancer for connections managed by a LoadBalancer
+ * This should only be called by a load balancer or if the handle is not attached to one
*
* @param string|DatabaseDomain $domain
* @since 1.32
}
if ( $conn->getFlag( $conn::DBO_TRX ) ) {
- $conn->setLBInfo( 'trxRoundId', false );
+ $conn->setLBInfo( 'trxRoundId', null ); // remove the round ID
}
if ( $conn->getFlag( $conn::DBO_DEFAULT ) ) {
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerInterface;
+use Psr\Log\NullLogger;
/**
* Helper class to manage Redis connections.
__CLASS__ . ' requires a Redis client library. ' .
'See https://www.mediawiki.org/wiki/Redis#Setup' );
}
- $this->logger = $options['logger'] ?? new \Psr\Log\NullLogger();
+ $this->logger = $options['logger'] ?? new NullLogger();
$this->connectTimeout = $options['connectTimeout'];
$this->readTimeout = $options['readTimeout'];
$this->persistent = $options['persistent'];
* @throws UnexpectedValueException
*/
public static function newWANCacheFromParams( array $params ) {
- global $wgCommandLineMode;
+ global $wgCommandLineMode, $wgSecretKey;
$services = MediaWikiServices::getInstance();
$params['cache'] = self::newFromParams( $params['store'] );
// Let pre-emptive refreshes happen post-send on HTTP requests
$params['asyncHandler'] = [ DeferredUpdates::class, 'addCallableUpdate' ];
}
+ $params['secret'] = $params['secret'] ?? $wgSecretKey;
$class = $params['class'];
return new $class( $params );
* @deprecated Since 1.28 Use MediaWikiServices::getInstance()->getMainWANObjectCache()
*/
public static function getMainWANInstance() {
+ wfDeprecated( __METHOD__, '1.28' );
return MediaWikiServices::getInstance()->getMainWANObjectCache();
}
* @throws MWException
*/
protected function getDB( $serverIndex ) {
- if ( !isset( $this->conns[$serverIndex] ) ) {
- if ( $serverIndex >= $this->numServers ) {
- throw new MWException( __METHOD__ . ": Invalid server index \"$serverIndex\"" );
- }
+ if ( $serverIndex >= $this->numServers ) {
+ throw new MWException( __METHOD__ . ": Invalid server index \"$serverIndex\"" );
+ }
- # Don't keep timing out trying to connect for each call if the DB is down
- if ( isset( $this->connFailureErrors[$serverIndex] )
- && ( time() - $this->connFailureTimes[$serverIndex] ) < 60
- ) {
- throw $this->connFailureErrors[$serverIndex];
- }
+ # Don't keep timing out trying to connect for each call if the DB is down
+ if (
+ isset( $this->connFailureErrors[$serverIndex] ) &&
+ ( time() - $this->connFailureTimes[$serverIndex] ) < 60
+ ) {
+ throw $this->connFailureErrors[$serverIndex];
+ }
- if ( $this->serverInfos ) {
+ if ( $this->serverInfos ) {
+ if ( !isset( $this->conns[$serverIndex] ) ) {
// Use custom database defined by server connection info
$info = $this->serverInfos[$serverIndex];
$type = $info['type'] ?? 'mysql';
$this->logger->debug( __CLASS__ . ": connecting to $host" );
$db = Database::factory( $type, $info );
$db->clearFlag( DBO_TRX ); // auto-commit mode
+ $this->conns[$serverIndex] = $db;
+ }
+ $db = $this->conns[$serverIndex];
+ } else {
+ // Use the main LB database
+ $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
+ $index = $this->replicaOnly ? DB_REPLICA : DB_MASTER;
+ if ( $lb->getServerType( $lb->getWriterIndex() ) !== 'sqlite' ) {
+ // Keep a separate connection to avoid contention and deadlocks
+ $db = $lb->getConnection( $index, [], false, $lb::CONN_TRX_AUTOCOMMIT );
} else {
- // Use the main LB database
- $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
- $index = $this->replicaOnly ? DB_REPLICA : DB_MASTER;
- if ( $lb->getServerType( $lb->getWriterIndex() ) !== 'sqlite' ) {
- // Keep a separate connection to avoid contention and deadlocks
- $db = $lb->getConnection( $index, [], false, $lb::CONN_TRX_AUTOCOMMIT );
- } else {
- // However, SQLite has the opposite behavior due to DB-level locking.
- // Stock sqlite MediaWiki installs use a separate sqlite cache DB instead.
- $db = $lb->getConnection( $index );
- }
+ // However, SQLite has the opposite behavior due to DB-level locking.
+ // Stock sqlite MediaWiki installs use a separate sqlite cache DB instead.
+ $db = $lb->getConnection( $index );
}
-
- $this->logger->debug( sprintf( "Connection %s will be used for SqlBagOStuff", $db ) );
- $this->conns[$serverIndex] = $db;
}
- return $this->conns[$serverIndex];
+ $this->logger->debug( sprintf( "Connection %s will be used for SqlBagOStuff", $db ) );
+
+ return $db;
}
/**
# Show delete and move logs if there were any such events.
# The logging query can DOS the site when bots/crawlers cause 404 floods,
# so be careful showing this. 404 pages must be cheap as they are hard to cache.
- $cache = $services->getMainObjectStash();
- $key = $cache->makeKey( 'page-recent-delete', md5( $title->getPrefixedText() ) );
+ $dbCache = ObjectCache::getInstance( 'db-replicated' );
+ $key = $dbCache->makeKey( 'page-recent-delete', md5( $title->getPrefixedText() ) );
$loggedIn = $this->getContext()->getUser()->isLoggedIn();
$sessionExists = $this->getContext()->getRequest()->getSession()->isPersistent();
- if ( $loggedIn || $cache->get( $key ) || $sessionExists ) {
+ if ( $loggedIn || $dbCache->get( $key ) || $sessionExists ) {
$logTypes = [ 'delete', 'move', 'protect' ];
$dbr = wfGetDB( DB_REPLICA );
$baseRevId = null;
if ( $edittime && $sectionId !== 'new' ) {
$lb = $this->getDBLoadBalancer();
- $dbr = $lb->getConnection( DB_REPLICA );
+ $dbr = $lb->getConnectionRef( DB_REPLICA );
$rev = Revision::loadFromTimestamp( $dbr, $this->mTitle, $edittime );
// Try the master if this thread may have just added it.
// This could be abstracted into a Revision method, but we don't want
&& $lb->getServerCount() > 1
&& $lb->hasOrMadeRecentMasterChanges()
) {
- $dbw = $lb->getConnection( DB_MASTER );
+ $dbw = $lb->getConnectionRef( DB_MASTER );
$rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
}
if ( $rev ) {
$status->value = $logid;
// Show log excerpt on 404 pages rather than just a link
- $cache = MediaWikiServices::getInstance()->getMainObjectStash();
- $key = $cache->makeKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
- $cache->set( $key, 1, $cache::TTL_DAY );
+ $dbCache = ObjectCache::getInstance( 'db-replicated' );
+ $key = $dbCache->makeKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
+ $dbCache->set( $key, 1, $dbCache::TTL_DAY );
}
return $status;
protected $type = 'generic';
/** @var bool */
protected $cacheable = false; // does this override getCachedWork() ?
+ /** @var PoolCounter */
+ private $poolCounter;
/**
* @param string $type The class of actions to limit concurrency for (task type)
'ResourceFileModulePaths',
'ResourceModules',
'ResourceModuleSkinStyles',
+ 'OOUIThemePaths',
'QUnitTestModule',
'ExtensionMessagesFiles',
'MessagesDirs',
}
}
- foreach ( [ 'ResourceModules', 'ResourceModuleSkinStyles' ] as $setting ) {
+ foreach ( [ 'ResourceModules', 'ResourceModuleSkinStyles', 'OOUIThemePaths' ] as $setting ) {
if ( isset( $info[$setting] ) ) {
foreach ( $info[$setting] as $name => $data ) {
if ( isset( $data['localBasePath'] ) ) {
if ( $defaultPaths ) {
$data += $defaultPaths;
}
- $this->globals["wg$setting"][$name] = $data;
+ if ( $setting === 'OOUIThemePaths' ) {
+ $this->attributes[$setting][$name] = $data;
+ } else {
+ $this->globals["wg$setting"][$name] = $data;
+ }
}
}
}
case 'debugScripts':
case 'styles':
case 'packageFiles':
- $this->{$member} = (array)$option;
+ $this->{$member} = is_array( $option ) ? $option : [ $option ];
break;
case 'templates':
$hasTemplates = true;
- $this->{$member} = (array)$option;
+ $this->{$member} = is_array( $option ) ? $option : [ $option ];
break;
// Collated lists of file paths
case 'languageScripts':
"'$key' given, string expected."
);
}
- $this->{$member}[$key] = (array)$value;
+ $this->{$member}[$key] = is_array( $value ) ? $value : [ $value ];
}
break;
case 'deprecated':
// Ensure relevant template compiler module gets loaded
foreach ( $this->templates as $alias => $templatePath ) {
if ( is_int( $alias ) ) {
- $alias = $templatePath;
+ $alias = $this->getPath( $templatePath );
}
$suffix = explode( '.', $alias );
$suffix = end( $suffix );
return $summary;
}
+ /**
+ * @param string|ResourceLoaderFilePath $path
+ * @return string
+ */
+ protected function getPath( $path ) {
+ if ( $path instanceof ResourceLoaderFilePath ) {
+ return $path->getPath();
+ }
+
+ return $path;
+ }
+
/**
* @param string|ResourceLoaderFilePath $path
* @return string
foreach ( $this->templates as $alias => $templatePath ) {
// Alias is optional
if ( is_int( $alias ) ) {
- $alias = $templatePath;
+ $alias = $this->getPath( $templatePath );
}
$localPath = $this->getLocalPath( $templatePath );
if ( file_exists( $localPath ) ) {
return "{$this->remoteBasePath}/{$this->path}";
}
+ /**
+ * @return string
+ */
+ public function getLocalBasePath() {
+ return $this->localBasePath;
+ }
+
+ /**
+ * @return string
+ */
+ public function getRemoteBasePath() {
+ return $this->remoteBasePath;
+ }
+
/**
* @return string
*/
// Ensure that all files have common extension.
$extensions = [];
- $descriptor = (array)$this->descriptor;
+ $descriptor = is_array( $this->descriptor ) ? $this->descriptor : [ $this->descriptor ];
array_walk_recursive( $descriptor, function ( $path ) use ( &$extensions ) {
- $extensions[] = pathinfo( $path, PATHINFO_EXTENSION );
+ $extensions[] = pathinfo( $this->getLocalPath( $path ), PATHINFO_EXTENSION );
} );
$extensions = array_unique( $extensions );
if ( count( $extensions ) !== 1 ) {
*/
public function getPath( ResourceLoaderContext $context ) {
$desc = $this->descriptor;
- if ( is_string( $desc ) ) {
- return $this->basePath . '/' . $desc;
+ if ( !is_array( $desc ) ) {
+ return $this->getLocalPath( $desc );
}
if ( isset( $desc['lang'] ) ) {
$contextLang = $context->getLanguage();
if ( isset( $desc['lang'][$contextLang] ) ) {
- return $this->basePath . '/' . $desc['lang'][$contextLang];
+ return $this->getLocalPath( $desc['lang'][$contextLang] );
}
$fallbacks = Language::getFallbacksFor( $contextLang, Language::STRICT_FALLBACKS );
foreach ( $fallbacks as $lang ) {
if ( isset( $desc['lang'][$lang] ) ) {
- return $this->basePath . '/' . $desc['lang'][$lang];
+ return $this->getLocalPath( $desc['lang'][$lang] );
}
}
}
if ( isset( $desc[$context->getDirection()] ) ) {
- return $this->basePath . '/' . $desc[$context->getDirection()];
+ return $this->getLocalPath( $desc[$context->getDirection()] );
}
if ( isset( $desc['default'] ) ) {
- return $this->basePath . '/' . $desc['default'];
+ return $this->getLocalPath( $desc['default'] );
} else {
throw new MWException( 'No matching path found' );
}
}
+ /**
+ * @param string|ResourceLoaderFilePath $path
+ * @return string
+ */
+ protected function getLocalPath( $path ) {
+ if ( $path instanceof ResourceLoaderFilePath ) {
+ return $path->getLocalPath();
+ }
+
+ return "{$this->basePath}/$path";
+ }
+
/**
* Get the extension of the image.
*
$this->definition = null;
if ( isset( $options['data'] ) ) {
- $dataPath = $this->localBasePath . '/' . $options['data'];
+ $dataPath = $this->getLocalPath( $options['data'] );
$data = json_decode( file_get_contents( $dataPath ), true );
$options = array_merge( $data, $options );
}
$this->images[$skin] = $this->images['default'] ?? [];
}
foreach ( $this->images[$skin] as $name => $options ) {
- $fileDescriptor = is_string( $options ) ? $options : $options['file'];
+ $fileDescriptor = is_array( $options ) ? $options['file'] : $options;
$allowedVariants = array_merge(
( is_array( $options ) && isset( $options['variants'] ) ) ? $options['variants'] : [],
return array_map( [ __CLASS__, 'safeFileHash' ], $files );
}
+ /**
+ * @param string|ResourceLoaderFilePath $path
+ * @return string
+ */
+ protected function getLocalPath( $path ) {
+ if ( $path instanceof ResourceLoaderFilePath ) {
+ return $path->getLocalPath();
+ }
+
+ return "{$this->localBasePath}/$path";
+ }
+
/**
* Extract a local base path from module definition information.
*
// Find the path to the JSON file which contains the actual image definitions for this theme
if ( $module ) {
$dataPath = $this->getThemeImagesPath( $theme, $module );
+ if ( !$dataPath ) {
+ return false;
+ }
} else {
// Backwards-compatibility for things that probably shouldn't have used this class...
$dataPath =
* @return array|false
*/
protected function readJSONFile( $dataPath ) {
- $localDataPath = $this->localBasePath . '/' . $dataPath;
+ $localDataPath = $this->getLocalPath( $dataPath );
if ( !file_exists( $localDataPath ) ) {
return false;
// Expand the paths to images (since they are relative to the JSON file that defines them, not
// our base directory)
$fixPath = function ( &$path ) use ( $dataPath ) {
- $path = dirname( $dataPath ) . '/' . $path;
+ if ( $dataPath instanceof ResourceLoaderFilePath ) {
+ $path = new ResourceLoaderFilePath(
+ dirname( $dataPath->getPath() ) . '/' . $path,
+ $dataPath->getLocalBasePath(),
+ $dataPath->getRemoteBasePath()
+ );
+ } else {
+ $path = dirname( $dataPath ) . '/' . $path;
+ }
};
array_walk( $data['images'], function ( &$value ) use ( $fixPath ) {
if ( is_string( $value['file'] ) ) {
* Return a map of theme names to lists of paths from which a given theme should be loaded.
*
* Keys are theme names, values are associative arrays. Keys of the inner array are 'scripts',
- * 'styles', or 'images', and values are string paths.
+ * 'styles', or 'images', and values are paths. Paths may be strings or ResourceLoaderFilePaths.
*
* Additionally, the string '{module}' in paths represents the name of the module to load.
*
*/
protected static function getThemePaths() {
$themePaths = self::$builtinThemePaths;
+ $themePaths += ExtensionRegistry::getInstance()->getAttribute( 'OOUIThemePaths' );
+
+ list( $defaultLocalBasePath, $defaultRemoteBasePath ) =
+ ResourceLoaderFileModule::extractBasePaths();
+
+ // Allow custom themes' paths to be relative to the skin/extension that defines them,
+ // like with ResourceModuleSkinStyles
+ foreach ( $themePaths as $theme => &$paths ) {
+ list( $localBasePath, $remoteBasePath ) =
+ ResourceLoaderFileModule::extractBasePaths( $paths );
+ if ( $localBasePath !== $defaultLocalBasePath || $remoteBasePath !== $defaultRemoteBasePath ) {
+ foreach ( $paths as &$path ) {
+ $path = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
+ }
+ }
+ }
+
return $themePaths;
}
/**
* Return a path to load given module of given theme from.
*
+ * The file at this path may not exist. This should be handled by the caller (throwing an error or
+ * falling back to default theme).
+ *
* @param string $theme OOUI theme name, for example 'WikimediaUI' or 'Apex'
* @param string $kind Kind of the module: 'scripts', 'styles', or 'images'
* @param string $module Module name, for valid values see $knownScriptsModules,
* $knownStylesModules, $knownImagesModules
- * @return string
+ * @return string|ResourceLoaderFilePath
*/
protected function getThemePath( $theme, $kind, $module ) {
$paths = self::getThemePaths();
$path = $paths[$theme][$kind];
- $path = str_replace( '{module}', $module, $path );
+ if ( $path instanceof ResourceLoaderFilePath ) {
+ $path = new ResourceLoaderFilePath(
+ str_replace( '{module}', $module, $path->getPath() ),
+ $path->getLocalBasePath(),
+ $path->getRemoteBasePath()
+ );
+ } else {
+ $path = str_replace( '{module}', $module, $path );
+ }
return $path;
}
/**
* @param string $theme See getThemePath()
* @param string $module See getThemePath()
- * @return string
+ * @return string|ResourceLoaderFilePath
*/
protected function getThemeScriptsPath( $theme, $module ) {
if ( !in_array( $module, self::$knownScriptsModules ) ) {
/**
* @param string $theme See getThemePath()
* @param string $module See getThemePath()
- * @return string
+ * @return string|ResourceLoaderFilePath
*/
protected function getThemeStylesPath( $theme, $module ) {
if ( !in_array( $module, self::$knownStylesModules ) ) {
/**
* @param string $theme See getThemePath()
* @param string $module See getThemePath()
- * @return string
+ * @return string|ResourceLoaderFilePath
*/
protected function getThemeImagesPath( $theme, $module ) {
if ( !in_array( $module, self::$knownImagesModules ) ) {
* @param string $text
*/
function update( $id, $title, $text ) {
- $dbw = $this->lb->getConnection( DB_MASTER );
+ $dbw = $this->lb->getMaintenanceConnectionRef( DB_MASTER );
$dbw->replace( 'searchindex',
[ 'si_page' ],
[
* Whether fulltext search is supported by current schema
* @return bool
*/
- function fulltextSearchSupported() {
+ private function fulltextSearchSupported() {
+ // Avoid getConnectionRef() in order to get DatabaseSqlite specifically
/** @var DatabaseSqlite $dbr */
$dbr = $this->lb->getConnection( DB_REPLICA );
-
- return $dbr->checkForEnabledSearch();
+ try {
+ return $dbr->checkForEnabledSearch();
+ } finally {
+ $this->lb->reuseConnection( $dbr );
+ }
}
/**
* @param string $title
* @param string $text
*/
- function update( $id, $title, $text ) {
+ public function update( $id, $title, $text ) {
if ( !$this->fulltextSearchSupported() ) {
return;
}
* @param int $id
* @param string $title
*/
- function updateTitle( $id, $title ) {
+ public function updateTitle( $id, $title ) {
if ( !$this->fulltextSearchSupported() ) {
return;
}
use Psr\Log\LoggerInterface;
use BagOStuff;
+use Psr\Log\NullLogger;
/**
* Adapter for PHP's session handling
}
// Anything deleted in $_SESSION and unchanged in Session should be deleted too
// (but not if $_SESSION can't represent it at all)
- \Wikimedia\PhpSessionSerializer::setLogger( new \Psr\Log\NullLogger() );
+ \Wikimedia\PhpSessionSerializer::setLogger( new NullLogger() );
foreach ( $cache as $key => $value ) {
if ( !array_key_exists( $key, $data ) && $session->exists( $key ) &&
\Wikimedia\PhpSessionSerializer::encode( [ $key => true ] )
protected function loadSites() {
$this->sites = new SiteList();
- $dbr = $this->dbLoadBalancer->getConnection( DB_REPLICA );
+ $dbr = $this->dbLoadBalancer->getConnectionRef( DB_REPLICA );
$res = $dbr->select(
'sites',
return true;
}
- $dbw = $this->dbLoadBalancer->getConnection( DB_MASTER );
+ $dbw = $this->dbLoadBalancer->getConnectionRef( DB_MASTER );
$dbw->startAtomic( __METHOD__ );
* @return bool Success
*/
public function clear() {
- $dbw = $this->dbLoadBalancer->getConnection( DB_MASTER );
+ $dbw = $this->dbLoadBalancer->getConnectionRef( DB_MASTER );
$dbw->startAtomic( __METHOD__ );
$ok = $dbw->delete( 'sites', '*', __METHOD__ );
* @return QuickTemplate The template to be executed by outputPage
*/
protected function prepareQuickTemplate() {
- global $wgScript, $wgStylePath, $wgMimeType, $wgJsMimeType,
+ global $wgScript, $wgStylePath, $wgMimeType,
$wgSitename, $wgLogo, $wgMaxCredits,
$wgShowCreditsIfMax, $wgArticlePath,
$wgScriptPath, $wgServer;
}
$tpl->set( 'mimetype', $wgMimeType );
- $tpl->set( 'jsmimetype', $wgJsMimeType );
$tpl->set( 'charset', 'UTF-8' );
$tpl->set( 'wgScript', $wgScript );
$tpl->set( 'skinname', $this->skinname );
throw new PermissionsError( 'viewmyprivateinfo' );
}
- if ( $user->isBlockedFromEmailuser() ) {
- throw new UserBlockedError( $user->getBlock() );
- }
-
parent::checkExecutePermissions( $user );
}
* @file
* @ingroup Upload
*/
-use MediaWiki\MediaWikiServices;
use MediaWiki\Shell\Shell;
/**
protected $mTempPath;
/** @var TempFSFile|null Wrapper to handle deleting the temp file */
protected $tempFileObj;
-
- protected $mDesiredDestName, $mDestName, $mRemoveTempFile, $mSourceType;
- protected $mTitle = false, $mTitleError = 0;
- protected $mFilteredName, $mFinalExtension;
- protected $mLocalFile, $mStashFile, $mFileSize, $mFileProps;
+ /** @var string|null */
+ protected $mDesiredDestName;
+ /** @var string|null */
+ protected $mDestName;
+ /** @var string|null */
+ protected $mRemoveTempFile;
+ /** @var string|null */
+ protected $mSourceType;
+ /** @var Title|bool */
+ protected $mTitle = false;
+ /** @var int */
+ protected $mTitleError = 0;
+ /** @var string|null */
+ protected $mFilteredName;
+ /** @var string|null */
+ protected $mFinalExtension;
+ /** @var LocalFile */
+ protected $mLocalFile;
+ /** @var UploadStashFile */
+ protected $mStashFile;
+ /** @var int|null */
+ protected $mFileSize;
+ /** @var array|null */
+ protected $mFileProps;
+ /** @var string[] */
protected $mBlackListedExtensions;
- protected $mJavaDetected, $mSVGNSError;
+ /** @var bool|null */
+ protected $mJavaDetected;
+ /** @var string|null */
+ protected $mSVGNSError;
protected static $safeXmlEncodings = [
'UTF-8',
* @todo Replace this with a whitelist filter!
* @param string $element
* @param array $attribs
- * @param array|null $data
+ * @param string|null $data
* @return bool|array
*/
public function checkSvgScriptCallback( $element, $attribs, $data = null ) {
* @return Status[]|bool
*/
public static function getSessionStatus( User $user, $statusKey ) {
- $cache = MediaWikiServices::getInstance()->getMainObjectStash();
- $key = $cache->makeKey( 'uploadstatus', $user->getId() ?: md5( $user->getName() ), $statusKey );
+ $store = self::getUploadSessionStore();
+ $key = self::getUploadSessionKey( $store, $user, $statusKey );
- return $cache->get( $key );
+ return $store->get( $key );
}
/**
*
* The value will be set in cache for 1 day
*
+ * Avoid triggering this method on HTTP GET/HEAD requests
+ *
* @param User $user
* @param string $statusKey
* @param array|bool $value
* @return void
*/
public static function setSessionStatus( User $user, $statusKey, $value ) {
- $cache = MediaWikiServices::getInstance()->getMainObjectStash();
- $key = $cache->makeKey( 'uploadstatus', $user->getId() ?: md5( $user->getName() ), $statusKey );
+ $store = self::getUploadSessionStore();
+ $key = self::getUploadSessionKey( $store, $user, $statusKey );
if ( $value === false ) {
- $cache->delete( $key );
+ $store->delete( $key );
} else {
- $cache->set( $key, $value, $cache::TTL_DAY );
+ $store->set( $key, $value, $store::TTL_DAY );
}
}
+
+ /**
+ * @param BagOStuff $store
+ * @param User $user
+ * @param string $statusKey
+ * @return string
+ */
+ private static function getUploadSessionKey( BagOStuff $store, User $user, $statusKey ) {
+ return $store->makeKey(
+ 'uploadstatus',
+ $user->getId() ?: md5( $user->getName() ),
+ $statusKey
+ );
+ }
+
+ /**
+ * @return BagOStuff
+ */
+ private static function getUploadSessionStore() {
+ return ObjectCache::getInstance( 'db-replicated' );
+ }
}
* @author Michael Dale
*/
class UploadFromChunks extends UploadFromFile {
+ /** @var LocalRepo */
+ private $repo;
+ /** @var UploadStash */
+ public $stash;
+ /** @var User */
+ public $user;
+
protected $mOffset;
protected $mChunkIndex;
protected $mFileKey;
protected $mVirtualTempPath;
- /** @var LocalRepo */
- private $repo;
+
+ /** @noinspection PhpMissingParentConstructorInspection */
/**
* Setup local pointers to stash, repo and user (similar to UploadFromStash)
if ( $mode === 'refresh' ) {
$cache->delete( $key, 1 ); // low tombstone/"hold-off" TTL
} else {
- $lb->getConnection( DB_MASTER )->onTransactionPreCommitOrIdle(
+ $lb->getConnectionRef( DB_MASTER )->onTransactionPreCommitOrIdle(
function () use ( $cache, $key ) {
$cache->delete( $key );
},
$lbFactory = $services->getDBLoadBalancerFactory();
$ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__ );
- $dbw = $services->getDBLoadBalancer()->getConnection( DB_MASTER );
+ $dbw = $services->getDBLoadBalancer()->getConnectionRef( DB_MASTER );
$lockKey = "{$dbw->getDomainID()}:UserGroupMembership:purge"; // per-wiki
$scopedLock = $dbw->getScopedLockAndFlush( $lockKey, __METHOD__, 0 );
'〇周后' => '〇周後',
'〇只' => '〇隻',
'〇余' => '〇餘',
+'》里' => '》裡',
'“' => '「',
'”' => '」',
'‘' => '『',
'包准' => '包準',
'包谷' => '包穀',
'包扎' => '包紮',
+'包制' => '包製',
'匏系' => '匏繫',
'北山索面' => '北山索麵',
'北仑河' => '北崙河',
'后安路' => '后安路',
'后平路' => '后平路',
'后庄' => '后庄',
-'后座' => '后座',
'后母戊' => '后母戊',
'后海湾' => '后海灣',
'后海灣' => '后海灣',
'方便面' => '方便麵',
'方向' => '方向',
'方法里' => '方法裡',
+'于吉林' => '於吉林',
'于震中' => '於震中',
'于震前' => '於震前',
'于震后' => '於震後',
'松口镇' => '松口鎮',
'松山庄' => '松山庄',
'松溪县' => '松谿縣',
+'松开始' => '松開始',
'板荡' => '板蕩',
'林宏岳' => '林宏嶽',
'林杰樑' => '林杰樑',
'片里' => '片裡',
'片言只语' => '片言隻語',
'版图里' => '版圖裡',
+'版本里' => '版本裡',
'牙签' => '牙籤',
'牛只' => '牛隻',
'物欲' => '物慾',
'理次发' => '理次髮',
'理发动' => '理發動',
'理发展' => '理發展',
+'理发放' => '理發放',
'理发现' => '理發現',
'理发生' => '理發生',
'理发表' => '理發表',
'空蒙' => '空濛',
'空荡' => '空蕩',
'空荡荡' => '空蕩蕩',
+'空里' => '空裡',
'空钟' => '空鐘',
'空余' => '空餘',
'窒欲' => '窒慾',
'制成' => '製成',
'制毒' => '製毒',
'制法' => '製法',
+'制汉字' => '製漢字',
'制浆' => '製漿',
'制片' => '製片',
'制版' => '製版',
'托交' => '託交',
'托付' => '託付',
'托克逊' => '託克遜',
-'托儿' => '託兒',
'托古讽今' => '託古諷今',
'托名' => '託名',
'托命' => '託命',
'这只比' => '這只比',
'这只用' => '這只用',
'这只能' => '這只能',
+'这只要' => '這只要',
'这只限' => '這只限',
'这只需' => '這只需',
'这只须' => '這只須',
'那只比' => '那只比',
'那只用' => '那只用',
'那只能' => '那只能',
+'那只要' => '那只要',
'那只限' => '那只限',
'那只需' => '那只需',
'那只须' => '那只須',
'厘革' => '釐革',
'金仆姑' => '金僕姑',
'金城里' => '金城里',
+'金发放' => '金發放',
'金范' => '金範',
'金圣叹' => '金聖歎',
'金表情' => '金表情',
'闯荡' => '闖蕩',
'闯炼' => '闖鍊',
'关系' => '關係',
+'关注:' => '關注:',
+'關注:' => '關注:',
'关系列' => '關系列',
'关系所' => '關系所',
'关系科' => '關系科',
'島' => '岛',
'峽' => '峡',
'崍' => '崃',
-'崑' => '昆',
'崗' => '岗',
'崙' => '仑',
'崢' => '峥',
'昇汞' => '升汞',
'陞用' => '升用',
'陞補' => '升补',
+'昇起' => '升起',
'陞遷' => '升迁',
'昇降' => '升降',
'卓著' => '卓著',
'旋乾转坤' => '旋乾转坤',
'無言不讎' => '无言不雠',
'曠若發矇' => '旷若发矇',
+'崑崙' => '昆仑',
+'崑岡' => '昆冈',
+'崑劇' => '昆剧',
+'崑山' => '昆山',
+'崑嵛' => '昆嵛',
+'崑承湖' => '昆承湖',
+'崑曲' => '昆曲',
+'崑腔' => '昆腔',
+'崑蘇' => '昆苏',
+'崑調' => '昆调',
'易·乾' => '易·乾',
'易經·乾' => '易经·乾',
'易经·乾' => '易经·乾',
'瀋液' => '渖液',
'满拚自尽' => '满拚自尽',
'滿拚自盡' => '满拚自尽',
+'靈崑' => '灵昆',
'薰習' => '熏习',
'薰心' => '熏心',
'薰沐' => '熏沐',
'老么' => '老幺',
'肉乾乾' => '肉干干',
'肘手鍊足' => '肘手链足',
+'蘇崑' => '苏昆',
'甦醒' => '苏醒',
'苧烯' => '苧烯',
'薴烯' => '苧烯',
'蔡孝乾' => '蔡孝乾',
'蔡絛' => '蔡絛',
'行餘' => '行馀',
+'西崑' => '西昆',
'覆蓋' => '覆盖',
'見微知著' => '见微知著',
'見著' => '见著',
'局域网' => '區域網',
'局域网络' => '區域網路',
'十杆' => '十桿',
-'特立尼达和托巴哥' => '千里達托貝哥',
-'特立尼達和多巴哥' => '千里達托貝哥',
+'特立尼达和托巴哥' => '千里達及托巴哥',
+'特立尼達和多巴哥' => '千里達及托巴哥',
'不列颠哥伦比亚省' => '卑詩省',
'南朝鲜' => '南韓',
'卡斯特罗' => '卡斯楚',
'塞维利亚' => '塞維亞',
'西維爾' => '塞維亞',
'塞黑' => '塞蒙',
+'塔希提' => '大溪地',
'共和联邦' => '大英國協',
'英联邦' => '大英國協',
'英聯邦' => '大英國協',
'尼日尔' => '尼日',
'尼日爾' => '尼日',
'雅马哈' => '山葉',
-'巴厘岛' => '峇里島',
+'巴厘' => '峇里',
'特朗普' => '川普',
'机床' => '工具機',
'機床' => '工具機',
'萌島' => '曼島',
'马恩岛' => '曼島',
'木杆' => '木桿',
+'尾班車' => '末班車',
'列奥纳多' => '李奧納多',
'杜塞尔多夫' => '杜塞道夫',
'杜塞爾多夫' => '杜塞道夫',
'圣基茨和尼维斯' => '聖克里斯多福及尼維斯',
'聖吉斯納域斯' => '聖克里斯多福及尼維斯',
'聖佐治' => '聖喬治',
+'圣多美和普林西比' => '聖多美普林西比',
+'聖多美和普林西比' => '聖多美普林西比',
'圣文森特和格林纳丁斯' => '聖文森及格瑞那丁',
'聖文森特和格林納丁斯' => '聖文森及格瑞那丁',
'圣赫勒拿' => '聖赫倫那',
'扎伊爾' => '薩伊',
'素檀' => '蘇丹',
'苏里南' => '蘇利南',
+'蘇里南' => '蘇利南',
'浮罗交怡' => '蘭卡威',
'浮羅交怡' => '蘭卡威',
'劳拉' => '蘿拉',
'香煙' => '香菸',
'馬里共和國' => '馬利共和國',
'马里共和国' => '馬利共和國',
+'馬拉維' => '馬拉威',
'马拉维' => '馬拉威',
'馬勒當拿' => '馬拉度納',
'马拉多纳' => '馬拉度納',
'IP地址' => 'IP位址',
'·威尔士' => '·威爾士',
'·威爾士' => '·威爾士',
+'》里' => '》裏',
'一地里' => '一地裏',
'三十六著' => '三十六着',
'三極體' => '三極管',
'夢著述' => '夢著述',
'夢著錄' => '夢著錄',
'梦里' => '夢裏',
+'塔希提' => '大溪地',
'天里' => '天裏',
'宇航员' => '太空人',
'夾著' => '夾着',
'山里的' => '山裏的',
'甘比亞' => '岡比亞',
'岸裡' => '岸裡',
-'巴厘岛' => '峇里島',
+'巴厘' => '峇里',
'工作台' => '工作枱',
'已占' => '已佔',
'巴塞罗那' => '巴塞隆拿',
'爭著錄' => '爭著錄',
'墙里' => '牆裏',
'版图里' => '版圖裏',
+'版本里' => '版本裏',
'版权信息' => '版權資訊',
-'千里達托貝哥' => '特立尼達和多巴哥',
+'千里達及托巴哥' => '特立尼達和多巴哥',
'牽著' => '牽着',
'牽著作' => '牽著作',
'牽著名' => '牽著名',
'空著者' => '空著者',
'空著述' => '空著述',
'空著錄' => '空著錄',
+'空里' => '空裏',
'太空梭' => '穿梭機',
'航天飞机' => '穿梭機',
'穿著' => '穿着',
'聖喬治' => '聖佐治',
'圣基茨和尼维斯' => '聖吉斯納域斯',
'聖克里斯多福及尼維斯' => '聖吉斯納域斯',
+'聖多美普林西比' => '聖多美和普林西比',
'聖文森及格瑞那丁' => '聖文森特和格林納丁斯',
'聖露西亞' => '聖盧西亞',
'聖馬利諾' => '聖馬力諾',
'藏著者' => '藏著者',
'藏著述' => '藏著述',
'藏著錄' => '藏著錄',
+'蘇利南' => '蘇里南',
'蘊涵著' => '蘊涵着',
'蘸著' => '蘸着',
'蘸著作' => '蘸著作',
'馬拉度納' => '馬勒當拿',
'马拉多纳' => '馬勒當拿',
'马拉特·萨芬' => '馬拉特·沙芬',
+'馬拉威' => '馬拉維',
'馬斯垂克' => '馬斯特里赫特',
'馬爾地夫' => '馬爾代夫',
'馬利共和國' => '馬里共和國',
'駕著者' => '駕著者',
'駕著述' => '駕著述',
'駕著錄' => '駕著錄',
+'駛著' => '駛着',
'騎著' => '騎着',
'騎著作' => '騎著作',
'騎著名' => '騎著名',
'騙著者' => '騙著者',
'騙著述' => '騙著述',
'騙著錄' => '騙著錄',
-'驶著' => '驶着',
'体里' => '體裏',
'高畫質' => '高清',
'高著' => '高着',
'全球資訊網' => '万维网',
'三十六著' => '三十六着',
'三極體' => '三极管',
+'上落客' => '上下客',
'下著' => '下着',
'下著作' => '下著作',
'下著名' => '下著名',
'下著稱' => '下著称',
'下著者' => '下著者',
'下著述' => '下著述',
+'落車' => '下车',
'卑詩省' => '不列颠哥伦比亚省',
'不著' => '不着',
'不著書' => '不著书',
'聖露西亞' => '圣卢西亚',
'聖克里斯多福及尼維斯' => '圣基茨和尼维斯',
'聖吉斯納域斯' => '圣基茨和尼维斯',
+'聖多美普林西比' => '圣多美和普林西比',
'聖文森及格瑞那丁' => '圣文森特和格林纳丁斯',
'聖馬利諾' => '圣马力诺',
'蓋亞那' => '圭亚那',
'朝著稱' => '朝著称',
'朝著者' => '朝著者',
'朝著述' => '朝著述',
+'尾班車' => '末班车',
'賓·拉登' => '本·拉登',
'本份' => '本分',
'賓拉登' => '本拉登',
'牽著述' => '牵著述',
'千里達' => '特立尼达',
'千里達及托巴哥' => '特立尼达和多巴哥',
-'千里達托貝哥' => '特立尼达和托巴哥',
'德蕾莎·梅伊' => '特蕾莎·梅',
'文翠珊' => '特蕾莎·梅',
'狗隻' => '犬只',
"actionfailed": "Дзеяньне ня выкананае",
"deletedtext": "«$1» была выдаленая.\nЗапісы пра выдаленыя старонкі зьмяшчаюцца ў $2.",
"dellogpage": "Журнал выдаленьняў",
- "dellogpagetext": "Сьпіс апошніх выдаленьняў.",
+ "dellogpagetext": "Ð\9dÑ\96жÑ\8dй знаÑ\85одзÑ\96Ñ\86Ñ\86а Ñ\81ьпіс апошніх выдаленьняў.",
"deletionlog": "журнал выдаленьняў",
"log-name-create": "Журнал стварэньня старонак",
"log-description-create": "Ніжэй знаходзіцца сьпіс апошніх стварэньняў старонак.",
"history": "История",
"history_short": "История",
"history_small": "история",
- "updatedmarker": "пÑ\80оменено оÑ\82 поÑ\81ледноÑ\82о ми посещение",
+ "updatedmarker": "пÑ\80оменено оÑ\82 поÑ\81ледноÑ\82о Ð\92и посещение",
"printableversion": "Версия за печат",
"permalink": "Постоянна препратка",
"print": "Печат",
"deleteprotected": "Не можете да изтриете страницата, защото е защитена.",
"deleting-backlinks-warning": "<strong>Внимание:</strong> [[Special:WhatLinksHere/{{FULLPAGENAME}}|Други страници]] сочат към или включват като шаблон страницата, която се опитвате да изтриете.",
"rollback": "Отмяна на промените",
+ "rollback-confirmation-confirm": "Моля потвърдете:",
+ "rollback-confirmation-yes": "Отмяна",
"rollback-confirmation-no": "Отказ",
"rollbacklink": "отмяна",
"rollbacklinkcount": "отмяна на $1 {{PLURAL:$1|редакция|редакции}}",
"blocklist-userblocks": "Скриване блокирането на потребителски сметки",
"blocklist-tempblocks": "Скриване на временни блокирания",
"blocklist-addressblocks": "Скриване на отделни блокирания на IP адреси",
+ "blocklist-type-opt-sitewide": "За всички уикита",
+ "blocklist-type-opt-partial": "Частично",
"blocklist-rangeblocks": "Скриване на блокиранията по IP диапазон",
"blocklist-timestamp": "Дата и час",
"blocklist-target": "Цел",
"watchlistedit-clear-titles": "Заглавия:",
"watchlistedit-clear-submit": "Изчистване на списъка за наблюдение (Необратимо!)",
"watchlistedit-clear-done": "Списъкът за наблюдение беше изчистен.",
+ "watchlistedit-clear-jobqueue": "Вашият списък за наблюдение се изчиства. Това може да отнеме известно време!",
"watchlistedit-clear-removed": "{{PLURAL:$1|1 заглавие беше премахнато|$1 заглавия бяха премахнати}}:",
"watchlistedit-too-many": "Има твърде много страници за показване.",
"watchlisttools-clear": "Изчистване на списъка за наблюдение",
"redirect-file": "Име на файл",
"redirect-logid": "Номер на записа",
"redirect-not-exists": "Стойността не е намерена",
+ "redirect-not-numeric": "Стойността не е числова",
"fileduplicatesearch": "Търсене на повтарящи се файлове",
"fileduplicatesearch-summary": "Търсене на повтарящи се файлове на база хеш стойности.",
"fileduplicatesearch-filename": "Име на файл:",
"tag-mw-contentmodelchange": "промяна на модела на съдържание",
"tag-mw-new-redirect": "Ново пренасочване",
"tag-mw-removed-redirect": "Премахнато пренасочване",
+ "tag-mw-changed-redirect-target": "Промяна целта на пренасочване",
+ "tag-mw-changed-redirect-target-description": "Редакции, променящи целта на пренасочване",
"tag-mw-blank": "Изтриване на съдържанието",
"tag-mw-replace": "Заменено",
+ "tag-mw-replace-description": "Редакции, премахващи над 90% от съдържанието на страница",
"tag-mw-rollback": "Отмяна",
"tag-mw-undo": "Отмяна",
"tags-title": "Етикети",
"powersearch-togglelabel": "تاوتوێ بکە:",
"powersearch-toggleall": "ھەموویان",
"powersearch-togglenone": "ھیچیان",
- "powersearch-remember": "ھەڵبژاردەکانت بۆ گەڕانەکانی تر لە بیر بێت",
+ "powersearch-remember": "بەبیرھێناوەی ھەڵبژاردەکان بۆ گەڕانەکانی داھاتوو",
"search-external": "گەڕانی دەرەکی",
"searchdisabled": "گەڕانی {{SITENAME}} ئێستە کار ناکات.\nدەتوانی بۆ ئێستا لە گەڕانی گووگڵ کەڵک وەرگری.\nلەیادت بێت لەوانەیە پێرستەکانیان بۆ گەڕانی ناو {{SITENAME}}، کاتبەسەرچوو بێت.",
"preferences": "ھەڵبژاردەکان",
"navigation": "Navigazione",
"and": " è",
"actions": "Azzione",
+ "namespaces": "Spazii",
"variants": "Variante",
+ "navigation-heading": "Navigazione",
"errorpagetitle": "Errore",
"returnto": "Vultà à $1.",
"tagline": "À prupositu di {{SITENAME}}",
"specialpage": "Pagina speciale",
"personaltools": "Strumenti persunali",
"talk": "Discussione",
+ "views": "Viste sfarenti",
"toolbox": "Stuvigli",
"mediawikipage": "Vede i missaghji",
"templatepage": "Vede a pagina di mudellu",
"categorypage": "Vede a pagina di categuria",
"viewtalkpage": "Vede a discussione",
"otherlanguages": "In altre lingue",
+ "redirectedfrom": "(Reindirizzamentu da $1)",
"redirectpagesub": "Pagina di reindirizzamentu",
"redirectto": "Reindirizzamentu à:",
- "lastmodifiedat": "Ultima mudifica di sta pagina u $1 à e $2.",
+ "lastmodifiedat": "Ùltima mudìfica di sta pàgina u $1 à e $2.",
"protectedpage": "Pagina prutetta",
"jumpto": "Andà à:",
"jumptonavigation": "navigazione",
"loginlanguagelabel": "Lingua: $1",
"pt-login": "Cunnessione",
"pt-login-button": "Cunnessione",
+ "pt-createaccount": "Registramentu",
"pt-userlogout": "Scunnessione",
"retypenew": "Scrive torna a nova parulla secreta:",
"resetpass-submit-cancel": "Cancillà",
"currentrev": "Ultima revisione",
"currentrev-asof": "Versione attuale di e $1",
"revisionasof": "Versione di e $1",
- "revision-info": "Versione di e $4 à e $5 di $2",
+ "revision-info": "Versione di e $4 à e $5 da {{GENDER:$6|$2}}$7",
"previousrevision": "← Versione menu ricente",
"nextrevision": "Versione più nova →",
"currentrevisionlink": "Ultima revisione",
"searchprofile-everything": "Tuttu",
"searchprofile-advanced": "Avanzatu",
"searchprofile-articles-tooltip": "Circà in $1",
+ "searchprofile-images-tooltip": "Circà schedarii",
"searchprofile-everything-tooltip": "Circà dapertuttu (incluse e pagine di discussione)",
"search-result-size": "$1 ({{PLURAL:$2|1 parolla|$2 parolle}})",
"search-redirect": "(Reindirizzamentu da $1)",
"hide": "piattà",
"show": "mustrà",
"minoreditletter": "m",
+ "newpageletter": "N",
"boteditletter": "b",
"rc-enhanced-hide": "Nasconde i dittagli",
"recentchangeslinked": "Mudifiche assuciate",
"file-anchor-link": "Schedariu",
"filehist": "Cronolugia di l'imagine",
"filehist-deleteone": "supprimà",
+ "filehist-current": "attuale",
+ "filehist-datetime": "Data/Óra",
+ "filehist-thumb": "Previsualizzazione",
+ "filehist-thumbtext": "Previsualizzazione di a versione di",
"filehist-user": "Cuntributore",
"filehist-dimensions": "Dimensione",
"filehist-comment": "Cummentu",
"watchlistfor2": "Per $1 ($2)",
"watch": "Suvità",
"unwatch": "Ùn suvità micca",
- "wlshowlast": "Mustrà l'ultime $1 ore $2 ghjorni",
+ "wlshowlast": "Mustrà l'ùltime $1 ore $2 ghjorni",
"enotif_reset": "Marcà tutte e pagine visitate",
"created": "creatu",
"changed": "cambiatu",
"import-logentry-upload-detail": "$1 {{PLURAL:$1|revisione|revisione}}",
"tooltip-pt-userpage": "{{GENDER:|A to}} pàgina di cuntributore",
"tooltip-pt-mytalk": "{{GENDER:|A to}} pàgina di discussione",
- "tooltip-pt-preferences": "{{GENDER:|E to}}} preferenze",
+ "tooltip-pt-preferences": "{{GENDER:|E to}} preferenze",
"tooltip-pt-watchlist": "Lista di e pagine ch'è tù suviti",
"tooltip-pt-mycontris": "Lista di {{GENDER:|e to}} cuntribuzioni",
"tooltip-pt-login": "U registramentu hè suggeritu, micca ubligatoriu",
"tooltip-pt-logout": "Esce da a sessione",
"tooltip-ca-talk": "Vede e discussione relative à sta pagina",
- "tooltip-ca-edit": "Pò mudificà 'ssa pagina. Per piacè improda l'ozzione di previsualisazzione prima di salvà",
+ "tooltip-ca-edit": "Mudificà 'ssa pagina",
"tooltip-ca-addsection": "Cumincià una nova sezzione",
"tooltip-ca-viewsource": "Sta pagina hè prutetta, ma si pò vede u so codice surghjente",
"tooltip-ca-history": "Versione precedente di sta pagina",
"tooltip-t-whatlinkshere": "Listinu di tutte e pagine chì sò ligate à quessa",
"tooltip-t-recentchangeslinked": "Versione di l'ultime mudifiche à e pagine legate à quessa",
"tooltip-t-contributions": "Listinu di e mudifiche {{GENDER:$1|di 'ssu cuntributore}}",
+ "tooltip-t-upload": "Incaricà un schedariu",
"tooltip-t-specialpages": "Listinu di tutte e pagine spiciale",
"tooltip-t-print": "Versione stampevule di 'ssa pagina",
"tooltip-t-permalink": "Ligame permanente à e revisione di sta pagina",
"tooltip-ca-nstab-user": "Vede a pagina di cuntributore",
"tooltip-ca-nstab-special": "Questa hè una pàgina particulare chi ùn si pó micca esse mudificata",
"tooltip-ca-nstab-project": "Vede a pagina di u prugettu",
+ "tooltip-ca-nstab-image": "Vede pàgina di schedariu",
"tooltip-ca-nstab-template": "Vede u mudellu",
"tooltip-ca-nstab-category": "Vede a pagina di categuria",
"tooltip-minoredit": "Signalà com'è mudifica minore",
"noimages": "Nulla da vede.",
"ilsubmit": "Ricerca",
"bydate": "per data",
+ "namespacesall": "tutti",
"monthsall": "tutti",
"confirm_purge_button": "D'accordu",
"table_pager_next": "Pagina seguente",
"logentry-move-move": "$1 {{GENDER:$2|hà spustatu}} a pagina $3 à $4",
"logentry-newusers-create": "U participante $3 hè statu creatu da $1",
"rightsnone": "(nessunu)",
- "searchsuggest-search": "Ricerca",
+ "searchsuggest-search": "Circà in {{SITENAME}}",
"expand_templates_output": "Risultatu"
}
"Weblars",
"Kranix",
"Psl85",
- "Dipsacus fullonum"
+ "Dipsacus fullonum",
+ "Fugithora"
]
},
"tog-underline": "Understreg link:",
"history": "Sidehistorik",
"history_short": "Historik",
"history_small": "historik",
- "updatedmarker": "opdateret siden seneste besøg",
+ "updatedmarker": "opdateret siden dit seneste besøg",
"printableversion": "Udskriftsvenlig udgave",
"permalink": "Permanent link",
"print": "Udskriv",
"virus-scanfailed": "scan fejlede (fejlkode $1)",
"virus-unknownscanner": "ukendt antivirus:",
"logouttext": "<strong>Du er nu logget af.</strong>\n\nBemærk, at nogle sider stadigvæk kan vises som om du var logget på, indtil du tømmer din browsers cache.",
+ "logging-out-notify": "Du bliver logget ud, vent venligst.",
+ "logout-failed": "Kan ikke logge ud nu: $1",
"cannotlogoutnow-title": "Kan ikke logge af på nuværende tidspunkt",
"cannotlogoutnow-text": "Det er ikke muligt at logge af når du bruger $1.",
"welcomeuser": "Velkommen, $1!",
"Macofe",
"Matma Rex",
"Fitoschido",
- "Vlad5250"
+ "Vlad5250",
+ "J budissin"
]
},
"tog-underline": "Wótkaze pódšmarnuś:",
"nstab-template": "Pśedłoga",
"nstab-help": "Pomoc",
"nstab-category": "Kategorija",
+ "mainpage-nstab": "Głowny bok",
"nosuchaction": "Toś tu akciju njedajo",
"nosuchactiontext": "Akcija, kótaruž URL pódawa, jo njepłaśiwa.\nSy se snaź zapisał pśi zapódaśu URL abo sy slědował wopacnemu wótkazoju.\nTo by mógło teke programěrowańska zmólka w {{GRAMMAR:lokatiw|{{SITENAME}}}} byś.",
"nosuchspecialpage": "Toś ten specialny bok njeeksistěrujo",
"currentevents": "אקטואליה",
"currentevents-url": "Project:אקטואליה",
"disclaimers": "הבהרות משפטיות",
- "disclaimerpage": "Project:×\94×\91×\94ר×\94 ×\9eשפ×\98×\99ת",
+ "disclaimerpage": "Project:×\94×\91×\94ר×\95ת ×\9eשפ×\98×\99×\95ת",
"edithelp": "עזרה בעריכה",
"helppage-top-gethelp": "עזרה",
"mainpage": "עמוד ראשי",
"pt-createaccount": "יצירת חשבון",
"pt-userlogout": "יציאה מהחשבון",
"php-mail-error-unknown": "שגיאה לא ידועה בפונקציה mail() של PHP.",
- "user-mail-no-addy": "×\94ת×\91צע × ×\99ס×\99×\95×\9f ×\9cש×\9c×\99×\97ת ×\94×\95×\93×¢×\94 ×\9c×\9c×\90 ×\9bת×\95×\91ת ×\93×\95×\90×´ל.",
- "user-mail-no-body": "× ×\99ס×\99×\95×\9f ×\9cש×\9c×\95×\97 דוא\"ל עם תוכן ריק או קצר מאוד.",
+ "user-mail-no-addy": "×\94ת×\91צע × ×\99ס×\99×\95×\9f ×\9cש×\9c×\99×\97ת ×\94×\95×\93עת ×\93×\95×\90\"×\9c ×\9c×\9c×\90 ×\9bת×\95×\91ת ×\93×\95×\90\"ל.",
+ "user-mail-no-body": "×\94ת×\91צע × ×\99ס×\99×\95×\9f ×\9cש×\9c×\99×\97ת ×\94×\95×\93עת דוא\"ל עם תוכן ריק או קצר מאוד.",
"changepassword": "שינוי סיסמה",
"resetpass_announce": "כדי לסיים את הכניסה לחשבון, יש להגדיר סיסמה חדשה.",
"resetpass_text": "<!-- יש להוסיף טקסט כאן -->",
"autoblockedtext": "כתובת ה־IP שלך נחסמה באופן אוטומטי כיוון שמשתמש אחר, שנחסם על־ידי $1, השתמש בה.\nהסיבה שניתנה לחסימה היא:\n\n:<em>$2</em>\n\n* תחילת החסימה: $8\n* פקיעת החסימה: $6\n* החסימה שבוצעה: $7\n\nבאפשרותך ליצור קשר עם $1 או עם כל אחד מ[[{{MediaWiki:Grouppage-sysop}}|מפעילי המערכת]] האחרים כדי לדון בחסימה.\n\nכמו־כן, באפשרותך להשתמש בתכונת \"{{int:emailuser}}\", אלא אם לא ציינת כתובת דוא\"ל תקפה ב[[Special:Preferences|העדפות המשתמש שלך]] או אם נחסמת משליחת דוא\"ל.\n\nכתובת ה־IP הנוכחית שלך היא $3, ומספר החסימה שלך הוא #$5.\nיש לציין את כל הפרטים הללו בכל פנייה לבירור החסימה.",
"systemblockedtext": "שם המשתמש או כתובת ה־IP שלך נחסמו באופן אוטומטי על־ידי תוכנת מדיה־ויקי.\nהסיבה שניתנה לחסימה היא:\n\n:<em>$2</em>\n\n* תחילת החסימה: $8\n* פקיעת החסימה: $6\n* החסימה שבוצעה: $7\n\nכתובת ה־IP הנוכחית שלך היא $3.\nיש לציין את כל הפרטים הללו בכל פנייה לבירור החסימה.",
"blockednoreason": "לא ניתנה סיבה",
- "blockedtext-composite": "<strong>ש×\9d ×\94×\9eשת×\9eש ×\90×\95 ×\9bת×\95×\91ת ×\94Ö¾IP ש×\9c×\9b×\9d × ×\97ס×\9e×\95 ×\9eער×\99×\9b×\94.</strong>\n\n×\94ס×\99×\91×\94 ×©× ×\99×ª× ×\94 ×\94×\99×\90:\n\n:<em>$2</em>.\n\n* ת×\97×\99×\9cת ×\94×\97ס×\99×\9e×\94: $8\n* פק×\99עת ×\94×\97ס×\99×\9e×\94 ×\94×\90ר×\95×\9b×\94 ×\91×\99×\95תר: $6\n\n×\9bת×\95×\91ת ×\94Ö¾IP ×\94× ×\95×\9b×\97×\99ת ש×\9c×\9a ×\94×\99×\90 $3.\n×\99ש ×\9cספק ×\90ת ×\9b×\9c ×\94×\9e×\99×\93×¢ ×\94× \"×\9c ×¢×\91×\95ר ×\9b×\9c ×\94ש×\90×\99×\9cת×\95ת ש×\90ת×\9d ×\9e×\91צע×\99×\9d.",
- "blockedtext-composite-reason": "×\99×©× ×\9f ×\9eספר ×\97ס×\99×\9e×\95ת ×¢×\9c ×\94×\97ש×\91×\95×\9f ש×\9c×\9a ×\95/×\90×\95 ×\9bת×\95×\91ת ×\94Ö¾IP ש×\9c×\9a",
+ "blockedtext-composite": "<strong>ש×\9d ×\94×\9eשת×\9eש ×\90×\95 ×\9bת×\95×\91ת ×\94Ö¾IP ש×\9c×\9a × ×\97ס×\9e×\95.</strong>\n\n×\94ס×\99×\91×\94 ×©× ×\99×ª× ×\94 ×\9c×\9b×\9a ×\94×\99×\90:\n\n:<em>$2</em>.\n\n* ת×\97×\99×\9cת ×\94×\97ס×\99×\9e×\94: $8\n* פק×\99עת ×\94×\97ס×\99×\9e×\94 ×\94×\90ר×\95×\9b×\94 ×\91×\99×\95תר: $6\n\n×\9bת×\95×\91ת ×\94Ö¾IP ×\94× ×\95×\9b×\97×\99ת ש×\9c×\9a ×\94×\99×\90 $3.\n×\99ש ×\9cצ×\99×\99×\9f ×\90ת ×\9b×\9c ×\94פר×\98×\99×\9d ×\94×\9c×\9c×\95 ×\91×\9b×\9c ×¤× ×\99×\99×\94 ×\9c×\91×\99ר×\95ר ×\94×\97ס×\99×\9e×\94.",
+ "blockedtext-composite-reason": "×\94×\95פע×\9c×\95 ×\9eספר ×\97ס×\99×\9e×\95ת ×¢×\9c ×\97ש×\91×\95×\9f ×\94×\9eשת×\9eש ש×\9c×\9a ×\90×\95 ×¢×\9c ×\9bת×\95×\91ת ×\94Ö¾IP ש×\9c×\9a (×\90×\95 ×¢×\9c ×©× ×\99×\94×\9d)",
"whitelistedittext": "נדרשת $1 כדי לערוך דפים.",
"confirmedittext": "יש לאמת את כתובת הדוא\"ל לפני עריכת דפים.\nנא להגדיר ולאמת את כתובת הדוא\"ל שלך באמצעות [[Special:Preferences|העדפות המשתמש]] שלך.",
"nosuchsectiontitle": "הפסקה לא נמצאה",
"gender-male": "הוא עורך דפים בוויקי",
"gender-female": "היא עורכת דפים בוויקי",
"prefs-help-gender": "לא חובה למלא העדפה זו.\nהמערכת משתמשת במידע הזה כדי לפנות אליך/אלייך ולציין את שם המשתמש שלך במין הדקדוקי הנכון.\nהמידע יהיה ציבורי.",
- "email": "דוא״ל",
+ "email": "דוא\"ל",
"prefs-help-realname": "לא חובה למלא את השם האמיתי.\nאם סופק, הוא עשוי לשמש כדי לייחס לך את עבודתך.",
"prefs-help-email": "כתובת דואר אלקטרוני היא אופציונלית, אבל היא חיונית לאיפוס הסיסמה במקרה ש{{GENDER:|תשכח|תשכחי}} אותה.",
"prefs-help-email-others": "באפשרותך גם לאפשר למשתמשים ליצור איתך קשר באמצעות דוא\"ל דרך קישור בדף המשתמש או בדף השיחה שלך.\nכתובת הדוא\"ל שלך לא תיחשף כשמשתמשים יצרו איתך קשר.",
"mw-widgets-abandonedit-discard": "ביטול העריכות",
"mw-widgets-abandonedit-keep": "המשך עריכה",
"mw-widgets-abandonedit-title": "בטוח?",
- "mw-widgets-copytextlayout-copy": "העתק",
+ "mw-widgets-copytextlayout-copy": "העתקה",
"mw-widgets-copytextlayout-copy-fail": "ההעתקה ללוח נכשלה.",
"mw-widgets-copytextlayout-copy-success": "הועתק ללוח.",
"mw-widgets-dateinput-no-date": "לא נבחר תאריך",
"edit-error-short": "שגיאה: $1",
"edit-error-long": "שגיאות:\n\n$1",
"specialmute": "השתקה",
- "specialmute-success": "העדפות ההשתקה שלך עודכנו. ר' את כל המשתמשים המושתקים ב[[Special:Preferences|העדפות שלך]].",
+ "specialmute-success": "העדפות ההשתקה שלך עודכנו. רשימת כל המשתמשים המושתקים זמינה ב[[Special:Preferences|העדפות שלך]].",
"specialmute-submit": "אישור",
- "specialmute-label-mute-email": "×\9c×\94שת×\99ק דואר אלקטרוני מהמשתמש הזה",
- "specialmute-header": "× ×\90 ×\9c×\91×\97×\95ר ×\90ת העדפות ההשתקה שלך עבור {{BIDI:[[User:$1]]}}.",
+ "specialmute-label-mute-email": "×\94שתקת ×\94×\95×\93×¢×\95ת דואר אלקטרוני מהמשתמש הזה",
+ "specialmute-header": "×\91×\97×\99ר×\95ת העדפות ההשתקה שלך עבור {{BIDI:[[User:$1]]}}.",
"specialmute-error-invalid-user": "שם המשתמש המבוקש לא נמצא.",
- "specialmute-error-email-blacklist-disabled": "השתקת משתמשים משליחת דואר אלקטרוני אליך אינה מופעלת.",
+ "specialmute-error-email-blacklist-disabled": "×\94×\90פשר×\95ת ×\9c×\94שתקת ×\9eשת×\9eש×\99×\9d ×\9eש×\9c×\99×\97ת ×\93×\95×\90ר ×\90×\9cק×\98ר×\95× ×\99 ×\90×\9c×\99×\9a ×\90×\99× ×\94 ×\9e×\95פע×\9cת.",
"specialmute-error-email-preferences": "יש לאמת את כתובת הדואר האלקטרוני שלך לפני שתהיה לך אפשרות להשתיק משתמש. אפשר לעשות זאת מהדף [[Special:Preferences]].",
- "specialmute-email-footer": "×\9b×\93×\99 ×\9c× ×\94×\9c ×\90ת ×\94×\94×¢×\93פ×\95ת ×¢×\91×\95ר {{BIDI:$2}} × ×\90 לבקר בדף <$1>.",
- "specialmute-login-required": "× ×\90 ×\9c×\94×\99×\9b× ×¡ ×\9c×\97ש×\91×\95×\9f ×\9b×\93×\99 ×\9cש×\91ות את העדפות ההשתקה שלך.",
+ "specialmute-email-footer": "×\9b×\93×\99 ×\9c× ×\94×\9c ×\90ת ×\94×¢×\93פ×\95ת ק×\91×\9cת ×\94×\93×\95×\90ר ×\94×\90×\9cק×\98ר×\95× ×\99 ×©× ×©×\9c×\97 ×¢×\9cÖ¾×\99×\93×\99 {{BIDI:$2}}, ×\91×\90פשר×\95ת×\9a לבקר בדף <$1>.",
+ "specialmute-login-required": "× ×\93רשת ×\9b× ×\99ס×\94 ×\9c×\97ש×\91×\95×\9f ×\9b×\93×\99 ×\9c×©× ות את העדפות ההשתקה שלך.",
"revid": "גרסה $1",
"pageid": "מזהה דף $1",
"interfaceadmin-info": "$1\n\nההרשאות לעריכת קובצי CSS/JS/JSON של האתר כולו הופרדו לאחרונה מההרשאה <code>editinterface</code>. אם לא ברור לך מדוע קיבלת את הודעת השגיאה הזאת, ר' [[mw:MediaWiki_1.32/interface-admin]].",
"logentry-partialblock-block-ns": "{{PLURAL:$1|名前空間}} $2",
"logentry-partialblock-block": "$1 が {{GENDER:$4|$3}} に対して $7 からの編集を $5 {{GENDER:$2||ブロックしました}} $6",
"logentry-partialblock-reblock": "$1 が {{GENDER:$4|$3}} に対する $7 のブロックの期限を $5 に{{GENDER:$2|変更しました}} $6",
+ "logentry-non-editing-block-block": "$1 が {{GENDER:$4|$3}} に対して編集以外の処理を $5 $6 で{{GENDER:$2||ブロックしました}}",
+ "logentry-non-editing-block-reblock": "$1 が {{GENDER:$4|$3}} に対する特定の編集以外の処理のブロックの期限を $5 $6 に{{GENDER:$2|変更しました}}",
"logentry-suppress-block": "$1 が {{GENDER:$4|$3}} を$5で{{GENDER:$2|ブロックしました}} $6",
"logentry-suppress-reblock": "$1 が {{GENDER:$4|$3}} のブロックの期限を$5に{{GENDER:$2|変更しました}} $6",
"logentry-import-upload": "$1 がファイルをアップロードして $3 を{{GENDER:$2|インポートしました}}",
"edit-error-short": "エラー: $1",
"edit-error-long": "エラー:\n\n\n\n$1",
"specialmute": "ミュート",
+ "specialmute-success": "ミュートの個人設定が更新されました。[[Special:Preferences|ご自分の個人設定ページ]]でミューとした利用者の一覧を確認できます。",
+ "specialmute-submit": "確定",
"specialmute-label-mute-email": "この利用者からのウィキメールをミュートする",
+ "specialmute-header": "{{BIDI:[[User:$1]]}}さんに対するミュートを個人設定で選択してください。",
"specialmute-error-invalid-user": "あなたが要求した利用者名は見つかりませんでした。",
+ "specialmute-error-email-blacklist-disabled": "利用者からメールを受け取らないようにするミュートは設定されていません。",
+ "specialmute-error-email-preferences": "発信者をミューとする準備として、ご自分のeメールアドレスの認証が必要です。手続きは[[Special:Preferences|個人設定]]のページで行います。",
+ "specialmute-email-footer": "{{BIDI:$2}}のeメール発信者の個人設定を変更するには<$1>を開いてください。",
+ "specialmute-login-required": "ミュートの個人設定を変更するにはログインしてください。",
"revid": "版 $1",
"pageid": "ページID $1",
"interfaceadmin-info": "$1\n\nサイト全体のCSS/JavaScriptの編集権限は、最近<code>editinterface</code> 権限から分離されました。なぜこのエラーが表示されたのかわからない場合は、[[mw:MediaWiki_1.32/interface-admin]]をご覧ください。",
"Delim",
"Comjun04",
"Son77391",
- "Jango"
+ "Jango",
+ "D6283"
]
},
"tog-underline": "링크에 밑줄 긋기:",
"logentry-block-block": "$1님이 {{GENDER:$4|$3}}님을 $5 {{GENDER:$2|차단했습니다}} $6",
"logentry-block-unblock": "$1님이 {{GENDER:$4|$3}}님의 {{GENDER:$2|차단을 해제했습니다}}",
"logentry-block-reblock": "$1 님이 {{GENDER:$4|$3}} 님의 차단 기간을 $5(으)로 {{GENDER:$2|바꾸었습니다}} $6",
- "logentry-partialblock-block": "$1님이 {{GENDER:$4|$3}}님을 $7 {{PLURAL:$8|문서를|문서들을}} 편집하지 못하도록 $5 {{GENDER:$2|차단}}했습니다. $6",
+ "logentry-partialblock-block": "$1님이 {{GENDER:$4|$3}}님을 $7 편집하지 못하도록 $5 {{GENDER:$2|차단}}했습니다. $6",
"logentry-suppress-block": "$1님이 {{GENDER:$4|$3}} 사용자를 $5 {{GENDER:$2|차단했습니다}} $6",
"logentry-suppress-reblock": "$1 님이 {{GENDER:$4|$3}} 님의 차단 기간을 $5(으)로 {{GENDER:$2|바꾸었습니다}} $6",
"logentry-import-upload": "$1님이 $3 문서를 파일 올리기로 {{GENDER:$2|가져왔습니다}}",
"edit-error-short": "오류: $1",
"edit-error-long": "오류:\n\n$1",
"specialmute": "알림 미표시",
- "specialmute-success": "ì\95\8c림 미í\91\9cì\8b\9c í\99\98ê²½ ì\84¤ì \95ì\9d´ ì\84±ê³µì \81ì\9c¼ë¡\9c ì\97\85ë\8d°ì\9d´í\8a¸ë\90\98ì\97\88ì\8aµë\8b\88ë\8b¤. [[Special:Preferences]]에서 알림이 표시되지 않는 모든 사용자를 확인하십시오.",
+ "specialmute-success": "ì\95\8c림 미í\91\9cì\8b\9c í\99\98ê²½ ì\84¤ì \95ì\9d´ ì\97\85ë\8d°ì\9d´í\8a¸ë\90\98ì\97\88ì\8aµë\8b\88ë\8b¤. [[Special:Preferences|í\99\98ê²½ ì\84¤ì \95]]에서 알림이 표시되지 않는 모든 사용자를 확인하십시오.",
"specialmute-submit": "확인",
"specialmute-label-mute-email": "이 사용자의 이메일 알림을 표시하지 않습니다",
"specialmute-header": "{{BIDI:[[User:$1]]}}의 알림 미표시 환경 설정을 선택해 주십시오.",
"versionrequired": "Dibutuahan MediaWiki versi $1",
"versionrequiredtext": "MediaWiki versi $1 dibutuahan untuak manggunoan laman ko. Caliak [[Special:Version|versi laman]]",
"ok": "OK",
- "pagetitle": "$1 - {{SITENAME}} bahaso Minang",
+ "pagetitle": "$1 - {{SITENAME}} Minangkabau",
"pagetitle-view-mainpage": "{{SITENAME}} bahaso Minang",
"backlinksubtitle": "← $1",
"retrievedfrom": "Didapek dari \"$1\"",
"minoredit": "Chisto è nu cagnamiénto piccerillo",
"watchthis": "Tiene d'uocchio sta paggena",
"savearticle": "Sarva 'a paggena",
- "savechanges": "Sarva 'e cagnamiénte",
+ "savechanges": "Sarva",
"publishpage": "Pubbreca paggena",
"publishchanges": "Pubbreca 'e cagnamiente",
"savearticle-start": "Sarva 'a paggena...",
"search-filter-title-prefix": "ߞߐߜߍ ߡߍ߲ ߠߎ߬ ߞߎ߲߬ߕߐ߮ ߦߋ߫ ߘߊߡߌ߬ߣߊ߬ ߟߊ߫ \"$1\" ߡߊ߬ ߏ߬ ߟߎ߫ ߟߋ߬ ߘߐߙߐ߲߫ ߢߌߣߌ߲ ߦߴߌ ߘߐ߫.",
"search-filter-title-prefix-reset": "ߞߐߜߍ ߓߍ߯ ߢߌߣߌ߲߫",
"searchresults-title": "ߣߌ߲߬ \"$1\" ߢߌߣߌ߲ߠߌ߲ ߞߐߝߟߌ",
+ "titlematches": "ߞߐߜߍ ߞߎ߲߬ߕߐ߮ ߓߍ߲߬ߢߐ߲߰ߡߊ߬ߣߍ߲߫",
"prevn": "ߕߊ߬ߡߌ߲߬ߣߍ߲ ߠߎ߬ {{PLURAL:$1|$1}}",
"nextn": "ߟߊߕߎ߲߰ߠߊ {{PLURAL:$1|$1}}",
"prev-page": "ߞߐߜߍ ߢߍߕߊ",
"right-editmyuserjs": "ߌ ߖߘߍ߬ߞߊ߬ߣߌ߲߬ JavaScript ߞߐߕߐ߮ ߟߎ߬ ߡߊߦߟߍ߬ߡߊ߲߫",
"right-viewmywatchlist": "ߌ ߖߘߍ߬ߞߊ߬ߣߌ߲߬ ߜߋ߬ߟߎ߲߬ߠߌ߲߬ ߛߙߍߘߍ ߦߋ߫",
"right-editmyoptions": "ߌ ߖߘߍ߬ߞߊ߬ߣߌ߲߬ ߟߊߝߌߛߦߊߟߌ ߡߊߦߟߍ߬ߡߊ߲߫",
+ "right-import": "ߞߐߜߍ ߟߎ߬ ߟߊߛߣߍ߫ ߞߊ߬ ߓߐ߫ ߥߞߌ ߕߐ߭ ߟߎ߬ ߘߐ߫",
+ "right-importupload": "ߞߐߜߍ ߟߎ߬ ߟߊߛߣߍ߫ ߞߊ߬ ߓߐ߫ ߞߐߕߐ߯ ߟߊߦߟߍ߬ߣߍ߲ ߠߎ߬ ߘߐ߫",
+ "right-patrol": "ߟߊ߬ߓߊ߰ߙߊ߬ߟߊ ߘߏ ߟߎ߬ ߟߊ߫ ߓߍ߬ߙߍ߲߬ߓߍ߬ߙߍ߲߬ߣߍ߲ ߠߎ߬ ߣߐ߬ߣߐ߬.",
+ "right-autopatrol": "ߒ ߖߍ߬ߘߍ ߟߊ߫ ߡߊ߬ߦߟߍ߬ߡߊ߲߬ߣߍ߲ ߠߎ߬ ߞߍ߫ ߓߍ߬ߙߍ߲߬ߓߍ߬ߙߍ߲߬ߣߍ߲ ߘߌ߫ ߞߍ߲ߒߖߘߍߦߋ߫ ߓߟߏߡߊ߬",
+ "right-patrolmarks": "ߡߊ߬ߦߟߍ߬ߡߊ߲߬ߠߌ߲߬ ߞߎߘߊ ߟߎ߬ ߦߋ߫ ߓߍ߬ߙߍ߲߬ߓߍ߬ߙߍ߲߬ߠߌ߲߫ ߣߐ߬ߣߐ߬ߣߍ߲ ߘߌ߫",
"right-unwatchedpages": "ߞߐߜߍ߫ ߜߋ߬ߟߎ߲߬ߓߊߟߌ ߟߎ߬ ߛߙߍߘߍ ߦߋ߫",
"right-mergehistory": "ߞߐߜߍ ߟߊ߫ ߘߐ߬ߝߐ ߟߎ߬ ߞߍߢߐ߲߮ߞߊ߲߬",
"right-userrights": "ߟߊ߬ߓߊ߰ߙߊ߬ߟߊ ߤߊߞߍ ߓߍ߯ ߡߊߦߟߍ߬ߡߊ߲߫",
"rcfilters-filterlist-feedbacklink": "ߌ ߤߊߞߟߌߣߊ߲ ߝߐ߫ ߊ߲ ߧߋ߫ ߞߊ߬ ߓߍ߲߬ ߛߍ߲ߛߍ߲ߟߊ߲ ߖߐ߯ߙߊ߲ ߠߊ߫ ߞߏ ߡߊ߬.",
"rcfilters-highlightbutton-title": "ߞߐߝߟߌ߫ ߡߊߦߋߙߋ߲ߣߍ߲ ߠߎ߬",
"rcfilters-highlightmenu-title": "ߞߐ߬ߟߐ ߘߏ߫ ߓߊߓߌ߬ߟߊ߬",
+ "rcfilters-filterlist-noresults": "ߛߍ߲ߛߍ߲ߟߊ߲߫ ߡߊ߫ ߛߐ߬ߘߐ߲߬",
"rcfilters-filter-editsbyself-label": "ߡߍ߲ ߠߎ߬ ߡߊߦߟߍ߬ߡߊ߲߬ߣߍ߲߬ ߌ ߓߟߏ߫",
"rcfilters-filter-editsbyself-description": "ߌ ߖߘߍ߬ߞߊ߬ߣߌ߲߬ ߓߟߏߓߌߟߊߢߐ߲߯ߞߊ߲.",
"rcfilters-filter-editsbyother-label": "ߘߏ ߟߎ߬ ߟߊ߫ ߡߊ߬ߦߟߍ߬ߡߊ߲߬ߠߌ߲ ߠߎ߬",
"filedelete-reason-dropdown": "* ߖߏ߰ߛߌ߬ߟߌ ߟߎ߬ ߝߊ߲߬ߓߊ ߞߎ߲߭\n** ߓߊߦߟߍߡߊ߲ ߤߊߞߍ ߕߌߢߍߟߌ\n** ߞߐߕߐ߯ ߓߊߟߌߣߍ߲ ߠߎ߬",
"filedelete-edit-reasonlist": "ߖߏ߰ߛߌ߬ߟߌ ߞߎ߲߭ ߡߊߦߟߍ߬ߡߊ߲߫",
"filedelete-maintenance-title": "ߞߐߕߐ߮ ߕߍ߫ ߛߐ߲߬ ߖߏ߰ߛߌ߬ ߟߊ߫",
+ "mimetype": "MIME ߛߎ߮ߦߊ:",
+ "download": "ߟߊ߬ߖߌ߰ߒ߬ߞߎ߲߬ߠߌ߲",
+ "unwatchedpages": "ߞߐߜߍ߫ ߜߋ߬ߟߎ߲߬ߓߊߟߌ ߟߎ߬",
+ "listredirects": "ߟߊ߬ߞߎ߲߬ߛߌ߲߬ߠߌ߲ ߛߙߍߘߍ ߟߎ߬",
+ "listduplicatedfiles": "ߞߐߕߐ߯ ߓߊߟߌߣߍ߲ ߠߎ߬ ߛߙߍߘߍ",
+ "listduplicatedfiles-entry": "[[:File:$1|$1]] ߓߘߊ߫ [[$3|{{PLURAL:$2|ߓߊߟߌ߫|ߟߎ߬ ߓߊߟߌߣߍ߲߫}}]]",
+ "unusedtemplates": "ߞߙߊߞߏ߫ ߟߊߓߊ߯ߙߊߓߊߟߌ ߟߎ߬",
"unusedtemplateswlh": "ߛߘߌ߬ߜߋ߲ ߜߘߍ ߟߎ߬",
"randompage": "ߞߎ߲߬ߝߍ߬ ߞߐߜߍ",
+ "randompage-nopages": "ߞߐߕߐ߯ ߛߌ߫ ߕߍ߫ ߢߌ߲߬ ߠߎ߬ ߘߐ߫ \n{{PLURAL:$2|ߕߐ߯ߛߓߍ ߞߣߍ|ߕߐ߯ߛߓߍ߫ ߞߣߍ ߟߎ߬}}: $1.",
"randomincategory": "ߓߍ߲߬ߛߋ߲߬ߡߊ߬ ߞߐߜߍ ߦߌߟߡߊ ߘߐ߫",
+ "randomincategory-invalidcategory": "$1 ߕߍ߫ ߦߌߟߡߊ߫ ߕߐ߯ ߓߍ߲߬ߣߍ߲߬ ߘߌ߫.",
"randomincategory-nopages": "ߞߐߜߍ߫ ߛߌ߫ ߕߍ߫ [[:Category:$1|$1]] ߘߌ߫ ߦߌߟߡߊ",
"randomincategory-category": "ߦߌߟߡߊ",
"randomincategory-legend": "ߓߍ߲߬ߛߋ߲߬ߡߊ߬ ߞߐߜߍ ߦߌߟߡߊ ߘߐ߫",
"statistics-pages": "ߞߐߜߍ ߟߎ߬",
"statistics-pages-desc": "ߞߐߜߍ ߡߍ߲ ߓߍ߯ ߦߋ߫ ߥߞߌ ߞߊ߲߬߸ ߦߏ߫ ߞߎߡߊߢߐ߲߯ߦߊ߫ ߞߐߜߍ߸ ߟߊ߬ߞߎ߲߬ߛߌ߲߬ߠߌ߲߸ ߊ߬ ߣߌ߫.",
"statistics-files": "ߞߐߕߐ߮ ߟߊߦߟߍ߬ߣߍ߲ ߠߎ߬",
+ "statistics-edits-average": "ߡߊ߬ߦߟߍ߬ߡߊ߲߬ߠߌ߲ ߡߎ߰ߡߍ ߡߍ߲ ߞߍߣߍ߲߫ ߞߐߜߍ ߡߊ߬",
+ "statistics-users": "ߟߊߓߊ߯ߙߊߓߊ߯ ߛߙߍߘߍߦߊߣߍ߲ ߠߎ߬",
+ "statistics-users-active-desc": "ߟߊ߬ߓߊ߰ߙߊ߬ߟߊ ߡߍ߲ ߠߎ߬ ߝߊߘߌ߲ߧߊ߫ ߘߊ߫ ߞߏ߫ ߘߏ߫ ߞߍ {{PLURAL:$1|ߕߟߋ߬|$1 ߕߋ߬ߟߋ}} ߟߎ߬ ߞߘߐ߫.",
"pageswithprop-submit": "ߕߊ߯",
"double-redirect-fixer": "ߟߊ߬ߞߎ߲߬ߛߌ߲߬ߠߌ߲ ߘߐߓߍ߲߬ߟߊ߲",
"brokenredirects-edit": "ߊ߬ ߡߊߦߟߍ߬ߡߊ߲߬",
"apisandbox-dynamic-parameters-add-label": "ߟߊ߬ߓߍ߲߬ߢߐ߲߰ߡߊ ߟߊߘߏ߲߬",
"apisandbox-dynamic-parameters-add-placeholder": "ߟߊ߬ߓߍ߲߬ߢߐ߲߰ߡߊ ߕߐ߮",
"apisandbox-dynamic-error-exists": "ߟߊ߬ߓߍ߲߬ߢߐ߲߰ߡߊ ߕߐ߮ \"$1\" ߦߋ߫ ߦߋ߲߬ ߞߘߐ߬ߡߊ߲߬.",
+ "apisandbox-fetch-token": "ߖߐߟߐ߲ߞߐ ߞߍߒߖߘߍߦߋ߫ ߟߝߊߟߌ",
"apisandbox-add-multi": "ߟߊ߬ߘߏ߲߬ߠߌ߲",
"apisandbox-results": "ߞߐߖߋߓߌ ߟߎ߬",
"apisandbox-sending-request": "API ߡߊ߬ߢߌ߬ߣߌ߲߬ߞߊ߬ߟߌ ߗߋߟߌ ߦߴߌ ߘߐ߫...",
"allpagessubmit": "ߥߊ߫",
"allpages-hide-redirects": "ߟߊ߬ߞߎ߲߬ߛߌ߲߬ߠߌ߲ ߢߡߊߘߏ߲߰",
"categories": "ߦߌߟߡߊ ߟߎ߬",
+ "categoriesfrom": "ߦߌߟߡߊ ߟߎ߬ ߦߌ߬ߘߊ߬ߟߌ ߟߊߝߟߐ߫ ߣߌ߲߬ ߡߊ߬:",
+ "deletedcontributions": "ߟߊ߬ߓߊ߰ߙߊ߬ߟߊ ߟߊ߫ ߓߟߏߡߊߜߍ߲ ߠߎ߬ ߓߘߊ߫ ߖߏ߬ߛߌ߬",
+ "deletedcontributions-title": "ߟߊ߬ߓߊ߰ߙߊ߬ߟߊ ߟߊ߫ ߓߟߏߡߊߜߍ߲ ߓߘߊ߫ ߓߊ߲߫ ߖߏ߬ߛߌ߬ ߟߊ߫",
+ "sp-deletedcontributions-contribs": "ߓߟߏߓߌߟߊߢߐ߲߯ߞߊ߲ ߠߎ߬",
"linksearch": "ߞߐߞߊ߲ߠߊ ߛߘߌ߬ߜߋ߲ ߢߌߣߌ߲ߠߌ߲",
+ "linksearch-ns": "ߕߐ߯ߛߓߍ ߞߣߍ:",
+ "linksearch-ok": "ߢߌߣߌ߲ߠߌ߲",
+ "linksearch-line": "$1 ߦߋ߫ ߛߘߌ߬ߜߋ߲ ߠߋ߬ ߘߌ߫ ߞߊ߬ ߓߐ߫ $2",
+ "listusersfrom": "ߟߊ߬ߓߊ߰ߙߊ߬ߟߊ ߟߎ߬ ߦߌ߬ߘߊ߬ߟߌ ߟߊߝߟߐ߫ ߣߌ߲߬ ߡߊ߬:",
+ "listusers-submit": "ߦߌ߬ߘߊ߬ߟߌ",
+ "listusers-noresult": "ߟߊ߬ߓߊ߰ߙߊ߬ߟߊ ߕߴߦߋ߲߬",
"activeusers-noresult": "ߟߊ߬ߓߊ߰ߙߊ߬ߟߊ ߕߴߦߋ߲߬",
"listgrouprights-members": "(ߛߌ߲߬ߝߏ߲ ߠߎ߫ ߛߙߍߘߍ)",
"emailuser": "ߗߋߛߓߍ ߗߋ߫ ߣߌ߲߬ ߕߌ߭ ߡߊ߬",
索羅門群島 所罗门群岛
汶萊 文莱
史瓦濟蘭 斯威士兰
+史瓦帝尼 斯威士兰
斯洛維尼亞 斯洛文尼亚
紐西蘭 新西兰
格瑞那達 格林纳达
波士尼亞與赫塞哥維納 波斯尼亚和黑塞哥维那
辛巴威 津巴布韦
宏都拉斯 洪都拉斯
-千里達托貝哥 特立尼达和托巴哥
萬那杜 瓦努阿图
溫納圖 瓦努阿图
葛摩 科摩罗
電視影集 电视系列剧
原子筆 圆珠笔
智慧卡 智能卡
+尾班車 末班车
+落車 下车
+上落客 上下客
鐵達尼號 泰坦尼克号
轉殖 克隆
空中巴士 空中客车
卑詩省 不列颠哥伦比亚省
丹帕沙 登巴萨
峇里 巴厘
-史瓦帝尼 斯威士兰
皮特肯 皮特凯恩
安地卡 安提瓜
撒拉威阿拉伯 阿拉伯撒哈拉
格瑞那丁 格林纳丁斯
普立茲獎 普利策奖
富比士 福布斯
+聖多美普林西比 圣多美和普林西比
公寓里 公寓裏
窝里斗 窩裏鬥
镇里 鎮裏
+》里 》裏
+空里 空裏
+版本里 版本裏
苑裡 苑裡
霄裡 霄裡
岸裡 岸裡
寫著 寫着
遇著 遇着
殺著 殺着
-驶è\91\97 驶着
+é§\9bè\91\97 é§\9b着
著筆 着筆
著鞭 着鞭
著法 着法
厄瓜多尔 厄瓜多爾
厄瓜多爾 厄瓜多爾
厄瓜多 厄瓜多爾
+馬拉威 馬拉維
百慕大 百慕達
厄利垂亞 厄立特里亞
吉布地 吉布堤
索羅門群島 所羅門群島
文莱 汶萊
史瓦濟蘭 斯威士蘭
+史瓦帝尼 斯威士蘭
斯洛維尼亞 斯洛文尼亞
紐西蘭 新西蘭
格瑞那達 格林納達
沙烏地阿拉伯 沙特阿拉伯
辛巴威 津巴布韋
宏都拉斯 洪都拉斯
-千里達托貝哥 特立尼達和多巴哥
+千里達及托巴哥 特立尼達和多巴哥
萬那杜 瓦努阿圖
葛摩 科摩羅
寮國 老撾
北朝鲜 北韓
寮語 老撾語
寮人民民主共和國 老撾人民民主共和國
+蘇利南 蘇里南
莱特湾 雷伊泰灣
萊特灣 雷伊泰灣
蘭卡威 浮羅交怡
帕拉林匹克 殘疾人奧林匹克
不列颠哥伦比亚省 卑詩省
丹帕沙 登巴薩
-巴厘岛 峇里島
-史瓦帝尼 斯威士蘭
+巴厘 峇里
皮特凯恩 皮特肯
安地卡 安提瓜
撒拉威阿拉伯 阿拉伯撒哈拉
疯牛病 瘋牛症
狂牛症 瘋牛症
普利策奖 普立茲獎
+聖多美普林西比 聖多美和普林西比
+塔希提 大溪地
剖釐 剖厘
一釐 一厘
昇平 升平
+昇起 升起
飛昇 飞升
提昇 提升
高昇 高升
滿拚自盡 满拚自尽
拚生尽死 拚生尽死
拚生盡死 拚生尽死
+崑劇 昆剧
+崑山 昆山
+崑岡 昆冈
+崑崙 昆仑
+崑嵛 昆嵛
+崑曲 昆曲
+崑腔 昆腔
+崑蘇 昆苏
+崑調 昆调
+蘇崑 苏昆
+西崑 西昆
+靈崑 灵昆
+崑承湖 昆承湖
所罗门群岛 索羅門群島
所羅門群島 索羅門群島
文莱 汶萊
-斯威士兰 史瓦濟蘭
-斯威士蘭 史瓦濟蘭
+斯威士兰 史瓦帝尼
+斯威士蘭 史瓦帝尼
斯洛文尼亚 斯洛維尼亞
斯洛文尼亞 斯洛維尼亞
新西兰 紐西蘭
津巴布韦 辛巴威
津巴布韋 辛巴威
洪都拉斯 宏都拉斯
-特立尼达和托巴哥 千里達托貝哥
-特立尼達和多巴哥 千里達托貝哥
+特立尼达和托巴哥 千里達及托巴哥
+特立尼達和多巴哥 千里達及托巴哥
瑙鲁 諾魯
瑙魯 諾魯
瓦努阿图 萬那杜
内罗毕 奈洛比
內羅畢 奈洛比
苏里南 蘇利南
+蘇里南 蘇利南
莫桑比克 莫三比克
莱索托 賴索托
萊索托 賴索托
金沙薩 金夏沙
达累斯萨拉姆 三蘭港
马拉维 馬拉威
+馬拉維 馬拉威
留尼汪 留尼旺
布隆方丹 布隆泉
厄瓜多 厄瓜多
东南亚国家联盟 東南亞國家協會
東南亞國家聯盟 東南亞國家協會
哥特式 哥德式
+尾班車 末班車
落車 下車
上落客 上下客
集装箱 貨櫃
不列颠哥伦比亚省 卑詩省
登巴萨 丹帕沙
登巴薩 丹帕沙
-巴厘岛 峇里島
-斯威士兰 史瓦帝尼
-斯威士蘭 史瓦帝尼
+巴厘 峇里
皮特凯恩 皮特肯
安提瓜 安地卡
阿拉伯撒哈拉 撒拉威阿拉伯
格林納丁斯 格瑞那丁
空中客车 空中巴士
普利策奖 普立茲獎
+圣多美和普林西比 聖多美普林西比
+聖多美和普林西比 聖多美普林西比
+塔希提 大溪地
黄岩县 黃巖縣
黄岩区 黃巖區
北仑河 北崙河
+昆剧 崑劇
+昆山 崑山
+昆冈 崑岡
+昆仑 崑崙
昆嵛 崑嵛
-昆承湖 崑承湖
+昆曲 崑曲
+昆腔 崑腔
+昆苏 崑蘇
+昆调 崑調
+苏昆 蘇崑
+西昆 西崑
灵昆 靈崑
+昆承湖 崑承湖
龙岩 龍巖
扑冬 撲鼕
冬冬鼓 鼕鼕鼓
U+05C6D屭|U+05C43屃|
U+05C85岅|U+05742坂|
U+05CDD峝|U+05CD2峒|
-U+05D11崑|U+06606昆|
U+05D19崙|U+04ED1仑|
U+05D57嵗|U+05C81岁|
U+05D7D嵽|U+2BD87𫶇|
這只比
這只限
這只應
+這只要
這只不過
這只包括
那只能
那只比
那只限
那只應
+那只要
那只不過
那只包括
多只能
黑奴籲天錄
林郁方
讚歌
-崑山
-崑曲
-崑腔
-崑調
-崑劇
-崑蘇
-蘇崑
一干家中
星期後
依依不捨
于禁
于敏中
註:# 不作“注:”
+關注:
劃為# 不作“划為”
一個# 避免“個裡”的錯誤
兩個
殿裡
隊裡
詞裡
+》裡
+空裡
+版本裡
裏白 #植物常用名
烏蘇里 #分詞用
夸脫
于丹
于冕
于吉
+於吉林
于堅
于姓
于氏
米瀋
拾瀋
姦污
-託兒
同人誌
文學誌
衝着
燉製
煮製
熬製
+包製
+製漢字 #和製漢字等
遏制 #以下分詞用
管制
抑制
胎發生
結發育
結發表
+金發放
+理發放
古人有云
昔人有云
云敞
哈囉喂
松口鎮
岩松了
+松開始
沙瑯
琺瑯
菜餚
關系統
關系所
關系科
-崑崙
-崑山
-崑劇
-崑曲
-崑腔
-崑蘇
-崑調
-崑岡
-西崑
-蘇崑
銹病
嚐糞
@colorButtonTextHighlight: @colorGray4;
@colorButtonTextActive: @colorGray1;
@colorDisabledText: @colorGray7;
-@colorErrorText: #d33;
-@colorWarningText: #705000;
+
+// Messages
+// Messages: Error
+@backgroundColorError: #fee7e6;
+// Use only for inlined messages, boxed messages require `@colorTextEmphasized` for
+// minimum contrast ratio.
+@colorError: #d33;
+@borderColorError: @colorError;
+// Messages: Warning
+@backgroundColorWarning: #fef6e7;
+@colorWarning: @colorTextEmphasized;
+@borderColorWarning: #fc3;
+// Messages: Success
+@backgroundColorSuccess: #d5fdf4;
+@colorSuccess: #14866d;
+@borderColorSuccess: @colorSuccess;
+
+// FIXME: Remove after a few weeks, when extensions got updated
+@colorErrorText: @colorError;
+@colorWarningText: @colorWarning;
// UI colors
@backgroundColorInputBinaryChecked: @colorProgressive;
// Form input sizes, equal to OOUI at 14px base font-size
@sizeInputBinary: 1.5625em;
-
-// Messages
-@backgroundColorError: #fee7e6;
-@borderColorError: #d33;
-@backgroundColorWarning: #fef6e7;
-@borderColorWarning: #fc3;
/**
* @inheritdoc
+ * @param {string} subject Section title.
+ * @param {string} body Message body, as wikitext. Signature code will automatically be added unless the message already contains the string ~~~.
+ * @param {Object} [options] Message options:
+ * @param {string} [options.tags] [Change tags](https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:Tags) to add to the message's revision, pipe-separated.
*/
- WikitextMessagePoster.prototype.post = function ( subject, body ) {
- mw.messagePoster.WikitextMessagePoster.parent.prototype.post.call( this, subject, body );
+ WikitextMessagePoster.prototype.post = function ( subject, body, options ) {
+ var additionalParams;
+ options = options || {};
+ mw.messagePoster.WikitextMessagePoster.parent.prototype.post.call( this, subject, body, options );
// Add signature if needed
if ( body.indexOf( '~~~' ) === -1 ) {
body += '\n\n~~~~';
}
+ additionalParams = { redirect: true };
+ if ( options.tags !== undefined ) {
+ additionalParams.tags = options.tags;
+ }
return this.api.newSection(
this.title,
subject,
body,
- { redirect: true }
+ additionalParams
).then( function ( resp, jqXHR ) {
if ( resp.edit.result === 'Success' ) {
return $.Deferred().resolve( resp, jqXHR );
* @param {string} body Body, as wikitext. Signature code will automatically be added
* by MessagePosters that require one, unless the message already contains the string
* ~~~.
+ * @param {Object} [options] Message options. See MessagePoster implementations for details.
* @return {jQuery.Promise} Promise completing when the post succeeds or fails.
* For failure, will be rejected with three arguments:
*
public static function applyInitialConfig() {
global $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType, $wgMainWANCache;
global $wgMainStash;
+ global $wgObjectCaches;
global $wgLanguageConverterCacheType, $wgUseDatabaseMessages;
global $wgLocaltimezone, $wgLocalisationCacheConf;
global $wgSearchType;
$wgLanguageConverterCacheType = 'hash';
// Uses db-replicated in DefaultSettings
$wgMainStash = 'hash';
+ // Use hash instead of db
+ $wgObjectCaches['db-replicated'] = $wgObjectCaches['hash'];
// Use memory job queue
$wgJobTypeConf = [
'default' => [ 'class' => JobQueueMemory::class, 'order' => 'fifo' ],
$setup['wgNoFollowDomainExceptions'] = [ 'no-nofollow.org' ];
$setup['wgExternalLinkTarget'] = false;
$setup['wgLocaltimezone'] = 'UTC';
- $setup['wgHtml5'] = true;
$setup['wgDisableLangConversion'] = false;
$setup['wgDisableTitleConversion'] = false;
// Wipe WANObjectCache process cache, which is invalidated by article insertion
// due to T144706
- ObjectCache::getMainWANInstance()->clearProcessCache();
+ MediaWikiServices::getInstance()->getMainWANObjectCache()->clearProcessCache();
$this->executeSetupSnippets( $teardown );
}
wfRequireOnceInGlobalScope( "$IP/tests/common/TestsAutoLoader.php" );
wfRequireOnceInGlobalScope( "$IP/includes/Defines.php" );
wfRequireOnceInGlobalScope( "$IP/includes/DefaultSettings.php" );
+wfRequireOnceInGlobalScope( "$IP/includes/GlobalFunctions.php" );
// Load extensions/skins present in filesystem so that classes can be discovered.
$directoryToJsonMap = [
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><title>eye</title><path d="M10 7.5a2.5 2.5 0 1 0 2.5 2.5A2.5 2.5 0 0 0 10 7.5zm0 7a4.5 4.5 0 1 1 4.5-4.5 4.5 4.5 0 0 1-4.5 4.5zM10 3C3 3 0 10 0 10s3 7 10 7 10-7 10-7-3-7-10-7z"/></svg>
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><title>flag</title><path d="M17 6L3 1v18h2v-6.87L17 6z"/></svg>
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><title>flag</title><path d="M3 6l14-5v18h-2v-6.87L3 6z"/></svg>
\ No newline at end of file
--- /dev/null
+mw.test();
--- /dev/null
+body {
+ color: red;
+}
--- /dev/null
+body {
+ color: black;
+}
--- /dev/null
+<div></div>
+++ /dev/null
-<?php
-
-/**
- * @group GlobalFunctions
- * @covers ::wfAppendQuery
- */
-class WfAppendQueryTest extends MediaWikiTestCase {
- /**
- * @dataProvider provideAppendQuery
- */
- public function testAppendQuery( $url, $query, $expected, $message = null ) {
- $this->assertEquals( $expected, wfAppendQuery( $url, $query ), $message );
- }
-
- public static function provideAppendQuery() {
- return [
- [
- 'http://www.example.org/index.php',
- '',
- 'http://www.example.org/index.php',
- 'No query'
- ],
- [
- 'http://www.example.org/index.php',
- [ 'foo' => 'bar' ],
- 'http://www.example.org/index.php?foo=bar',
- 'Set query array'
- ],
- [
- 'http://www.example.org/index.php?foz=baz',
- 'foo=bar',
- 'http://www.example.org/index.php?foz=baz&foo=bar',
- 'Set query string'
- ],
- [
- 'http://www.example.org/index.php?foo=bar',
- '',
- 'http://www.example.org/index.php?foo=bar',
- 'Empty string with query'
- ],
- [
- 'http://www.example.org/index.php?foo=bar',
- [ 'baz' => 'quux' ],
- 'http://www.example.org/index.php?foo=bar&baz=quux',
- 'Add query array'
- ],
- [
- 'http://www.example.org/index.php?foo=bar',
- 'baz=quux',
- 'http://www.example.org/index.php?foo=bar&baz=quux',
- 'Add query string'
- ],
- [
- 'http://www.example.org/index.php?foo=bar',
- [ 'baz' => 'quux', 'foo' => 'baz' ],
- 'http://www.example.org/index.php?foo=bar&baz=quux&foo=baz',
- 'Modify query array'
- ],
- [
- 'http://www.example.org/index.php?foo=bar',
- 'baz=quux&foo=baz',
- 'http://www.example.org/index.php?foo=bar&baz=quux&foo=baz',
- 'Modify query string'
- ],
- [
- 'http://www.example.org/index.php#baz',
- 'foo=bar',
- 'http://www.example.org/index.php?foo=bar#baz',
- 'URL with fragment'
- ],
- [
- 'http://www.example.org/index.php?foo=bar#baz',
- 'quux=blah',
- 'http://www.example.org/index.php?foo=bar&quux=blah#baz',
- 'URL with query string and fragment'
- ]
- ];
- }
-}
+++ /dev/null
-<?php
-/**
- * @group GlobalFunctions
- * @covers ::wfArrayPlus2d
- */
-class WfArrayPlus2dTest extends MediaWikiTestCase {
- /**
- * @dataProvider provideArrays
- */
- public function testWfArrayPlus2d( $baseArray, $newValues, $expected, $testName ) {
- $this->assertEquals(
- $expected,
- wfArrayPlus2d( $baseArray, $newValues ),
- $testName
- );
- }
-
- /**
- * Provider for testing wfArrayPlus2d
- *
- * @return array
- */
- public static function provideArrays() {
- return [
- // target array, new values array, expected result
- [
- [ 0 => '1dArray' ],
- [ 1 => '1dArray' ],
- [ 0 => '1dArray', 1 => '1dArray' ],
- "Test simple union of two arrays with different keys",
- ],
- [
- [
- 0 => [ 0 => '2dArray' ],
- ],
- [
- 0 => [ 1 => '2dArray' ],
- ],
- [
- 0 => [ 0 => '2dArray', 1 => '2dArray' ],
- ],
- "Test union of 2d arrays with different keys in the value array",
- ],
- [
- [
- 0 => [ 0 => '2dArray' ],
- ],
- [
- 0 => [ 0 => '1dArray' ],
- ],
- [
- 0 => [ 0 => '2dArray' ],
- ],
- "Test union of 2d arrays with same keys in the value array",
- ],
- [
- [
- 0 => [ 0 => [ 0 => '3dArray' ] ],
- ],
- [
- 0 => [ 0 => [ 1 => '2dArray' ] ],
- ],
- [
- 0 => [ 0 => [ 0 => '3dArray' ] ],
- ],
- "Test union of 3d array with different keys",
- ],
- [
- [
- 0 => [ 0 => [ 0 => '3dArray' ] ],
- ],
- [
- 0 => [ 1 => [ 0 => '2dArray' ] ],
- ],
- [
- 0 => [ 0 => [ 0 => '3dArray' ], 1 => [ 0 => '2dArray' ] ],
- ],
- "Test union of 3d array with different keys in the value array",
- ],
- [
- [
- 0 => [ 0 => [ 0 => '3dArray' ] ],
- ],
- [
- 0 => [ 0 => [ 0 => '2dArray' ] ],
- ],
- [
- 0 => [ 0 => [ 0 => '3dArray' ] ],
- ],
- "Test union of 3d array with same keys in the value array",
- ],
- ];
- }
-}
+++ /dev/null
-<?php
-/**
- * @group GlobalFunctions
- * @covers ::wfAssembleUrl
- */
-class WfAssembleUrlTest extends MediaWikiTestCase {
- /**
- * @dataProvider provideURLParts
- */
- public function testWfAssembleUrl( $parts, $output ) {
- $partsDump = print_r( $parts, true );
- $this->assertEquals(
- $output,
- wfAssembleUrl( $parts ),
- "Testing $partsDump assembles to $output"
- );
- }
-
- /**
- * Provider of URL parts for testing wfAssembleUrl()
- *
- * @return array
- */
- public static function provideURLParts() {
- $schemes = [
- '' => [],
- '//' => [
- 'delimiter' => '//',
- ],
- 'http://' => [
- 'scheme' => 'http',
- 'delimiter' => '://',
- ],
- ];
-
- $hosts = [
- '' => [],
- 'example.com' => [
- 'host' => 'example.com',
- ],
- 'example.com:123' => [
- 'host' => 'example.com',
- 'port' => 123,
- ],
- 'id@example.com' => [
- 'user' => 'id',
- 'host' => 'example.com',
- ],
- 'id@example.com:123' => [
- 'user' => 'id',
- 'host' => 'example.com',
- 'port' => 123,
- ],
- 'id:key@example.com' => [
- 'user' => 'id',
- 'pass' => 'key',
- 'host' => 'example.com',
- ],
- 'id:key@example.com:123' => [
- 'user' => 'id',
- 'pass' => 'key',
- 'host' => 'example.com',
- 'port' => 123,
- ],
- ];
-
- $cases = [];
- foreach ( $schemes as $scheme => $schemeParts ) {
- foreach ( $hosts as $host => $hostParts ) {
- foreach ( [ '', '/path' ] as $path ) {
- foreach ( [ '', 'query' ] as $query ) {
- foreach ( [ '', 'fragment' ] as $fragment ) {
- $parts = array_merge(
- $schemeParts,
- $hostParts
- );
- $url = $scheme .
- $host .
- $path;
-
- if ( $path ) {
- $parts['path'] = $path;
- }
- if ( $query ) {
- $parts['query'] = $query;
- $url .= '?' . $query;
- }
- if ( $fragment ) {
- $parts['fragment'] = $fragment;
- $url .= '#' . $fragment;
- }
-
- $cases[] = [
- $parts,
- $url,
- ];
- }
- }
- }
- }
- }
-
- $complexURL = 'http://id:key@example.org:321' .
- '/over/there?name=ferret&foo=bar#nose';
- $cases[] = [
- wfParseUrl( $complexURL ),
- $complexURL,
- ];
-
- return $cases;
- }
-}
+++ /dev/null
-<?php
-/**
- * @group GlobalFunctions
- * @covers ::wfBaseName
- */
-class WfBaseNameTest extends MediaWikiTestCase {
- /**
- * @dataProvider providePaths
- */
- public function testBaseName( $fullpath, $basename ) {
- $this->assertEquals( $basename, wfBaseName( $fullpath ),
- "wfBaseName('$fullpath') => '$basename'" );
- }
-
- public static function providePaths() {
- return [
- [ '', '' ],
- [ '/', '' ],
- [ '\\', '' ],
- [ '//', '' ],
- [ '\\\\', '' ],
- [ 'a', 'a' ],
- [ 'aaaa', 'aaaa' ],
- [ '/a', 'a' ],
- [ '\\a', 'a' ],
- [ '/aaaa', 'aaaa' ],
- [ '\\aaaa', 'aaaa' ],
- [ '/aaaa/', 'aaaa' ],
- [ '\\aaaa\\', 'aaaa' ],
- [ '\\aaaa\\', 'aaaa' ],
- [
- '/mnt/upload3/wikipedia/en/thumb/8/8b/'
- . 'Zork_Grand_Inquisitor_box_cover.jpg/93px-Zork_Grand_Inquisitor_box_cover.jpg',
- '93px-Zork_Grand_Inquisitor_box_cover.jpg'
- ],
- [ 'C:\\Progra~1\\Wikime~1\\Wikipe~1\\VIEWER.EXE', 'VIEWER.EXE' ],
- [ 'Östergötland_coat_of_arms.png', 'Östergötland_coat_of_arms.png' ],
- ];
- }
-}
+++ /dev/null
-<?php
-
-/**
- * @group GlobalFunctions
- * @covers ::wfEscapeShellArg
- */
-class WfEscapeShellArgTest extends MediaWikiTestCase {
- public function testSingleInput() {
- if ( wfIsWindows() ) {
- $expected = '"blah"';
- } else {
- $expected = "'blah'";
- }
-
- $actual = wfEscapeShellArg( 'blah' );
-
- $this->assertEquals( $expected, $actual );
- }
-
- public function testMultipleArgs() {
- if ( wfIsWindows() ) {
- $expected = '"foo" "bar" "baz"';
- } else {
- $expected = "'foo' 'bar' 'baz'";
- }
-
- $actual = wfEscapeShellArg( 'foo', 'bar', 'baz' );
-
- $this->assertEquals( $expected, $actual );
- }
-
- public function testMultipleArgsAsArray() {
- if ( wfIsWindows() ) {
- $expected = '"foo" "bar" "baz"';
- } else {
- $expected = "'foo' 'bar' 'baz'";
- }
-
- $actual = wfEscapeShellArg( [ 'foo', 'bar', 'baz' ] );
-
- $this->assertEquals( $expected, $actual );
- }
-}
+++ /dev/null
-<?php
-
-/**
- * @group GlobalFunctions
- * @covers ::wfGetCaller
- */
-class WfGetCallerTest extends MediaWikiTestCase {
- public function testZero() {
- $this->assertEquals( 'WfGetCallerTest->testZero', wfGetCaller( 1 ) );
- }
-
- function callerOne() {
- return wfGetCaller();
- }
-
- public function testOne() {
- $this->assertEquals( 'WfGetCallerTest->testOne', self::callerOne() );
- }
-
- static function intermediateFunction( $level = 2, $n = 0 ) {
- if ( $n > 0 ) {
- return self::intermediateFunction( $level, $n - 1 );
- }
-
- return wfGetCaller( $level );
- }
-
- public function testTwo() {
- $this->assertEquals( 'WfGetCallerTest->testTwo', self::intermediateFunction() );
- }
-
- public function testN() {
- $this->assertEquals( 'WfGetCallerTest->testN', self::intermediateFunction( 2, 0 ) );
- $this->assertEquals(
- 'WfGetCallerTest::intermediateFunction',
- self::intermediateFunction( 1, 0 )
- );
-
- for ( $i = 0; $i < 10; $i++ ) {
- $this->assertEquals(
- 'WfGetCallerTest::intermediateFunction',
- self::intermediateFunction( $i + 1, $i )
- );
- }
- }
-}
+++ /dev/null
-<?php
-
-/**
- * @group GlobalFunctions
- * @covers ::wfRemoveDotSegments
- */
-class WfRemoveDotSegmentsTest extends MediaWikiTestCase {
- /**
- * @dataProvider providePaths
- */
- public function testWfRemoveDotSegments( $inputPath, $outputPath ) {
- $this->assertEquals(
- $outputPath,
- wfRemoveDotSegments( $inputPath ),
- "Testing $inputPath expands to $outputPath"
- );
- }
-
- /**
- * Provider of URL paths for testing wfRemoveDotSegments()
- *
- * @return array
- */
- public static function providePaths() {
- return [
- [ '/a/b/c/./../../g', '/a/g' ],
- [ 'mid/content=5/../6', 'mid/6' ],
- [ '/a//../b', '/a/b' ],
- [ '/.../a', '/.../a' ],
- [ '.../a', '.../a' ],
- [ '', '' ],
- [ '/', '/' ],
- [ '//', '//' ],
- [ '.', '' ],
- [ '..', '' ],
- [ '...', '...' ],
- [ '/.', '/' ],
- [ '/..', '/' ],
- [ './', '' ],
- [ '../', '' ],
- [ './a', 'a' ],
- [ '../a', 'a' ],
- [ '../../a', 'a' ],
- [ '.././a', 'a' ],
- [ './../a', 'a' ],
- [ '././a', 'a' ],
- [ '../../', '' ],
- [ '.././', '' ],
- [ './../', '' ],
- [ '././', '' ],
- [ '../..', '' ],
- [ '../.', '' ],
- [ './..', '' ],
- [ './.', '' ],
- [ '/../../a', '/a' ],
- [ '/.././a', '/a' ],
- [ '/./../a', '/a' ],
- [ '/././a', '/a' ],
- [ '/../../', '/' ],
- [ '/.././', '/' ],
- [ '/./../', '/' ],
- [ '/././', '/' ],
- [ '/../..', '/' ],
- [ '/../.', '/' ],
- [ '/./..', '/' ],
- [ '/./.', '/' ],
- [ 'b/../../a', '/a' ],
- [ 'b/.././a', '/a' ],
- [ 'b/./../a', '/a' ],
- [ 'b/././a', 'b/a' ],
- [ 'b/../../', '/' ],
- [ 'b/.././', '/' ],
- [ 'b/./../', '/' ],
- [ 'b/././', 'b/' ],
- [ 'b/../..', '/' ],
- [ 'b/../.', '/' ],
- [ 'b/./..', '/' ],
- [ 'b/./.', 'b/' ],
- [ '/b/../../a', '/a' ],
- [ '/b/.././a', '/a' ],
- [ '/b/./../a', '/a' ],
- [ '/b/././a', '/b/a' ],
- [ '/b/../../', '/' ],
- [ '/b/.././', '/' ],
- [ '/b/./../', '/' ],
- [ '/b/././', '/b/' ],
- [ '/b/../..', '/' ],
- [ '/b/../.', '/' ],
- [ '/b/./..', '/' ],
- [ '/b/./.', '/b/' ],
- ];
- }
-}
+++ /dev/null
-<?php
-
-/**
- * @group GlobalFunctions
- * @covers ::wfShorthandToInteger
- */
-class WfShorthandToIntegerTest extends MediaWikiTestCase {
- /**
- * @dataProvider provideABunchOfShorthands
- */
- public function testWfShorthandToInteger( $input, $output, $description ) {
- $this->assertEquals(
- wfShorthandToInteger( $input ),
- $output,
- $description
- );
- }
-
- public static function provideABunchOfShorthands() {
- return [
- [ '', -1, 'Empty string' ],
- [ ' ', -1, 'String of spaces' ],
- [ '1G', 1024 * 1024 * 1024, 'One gig uppercased' ],
- [ '1g', 1024 * 1024 * 1024, 'One gig lowercased' ],
- [ '1M', 1024 * 1024, 'One meg uppercased' ],
- [ '1m', 1024 * 1024, 'One meg lowercased' ],
- [ '1K', 1024, 'One kb uppercased' ],
- [ '1k', 1024, 'One kb lowercased' ],
- ];
- }
-}
+++ /dev/null
-<?php
-
-/**
- * @group GlobalFunctions
- * @covers ::wfStringToBool
- */
-class WfStringToBoolTest extends MediaWikiTestCase {
-
- public function getTestCases() {
- return [
- [ 'true', true ],
- [ 'on', true ],
- [ 'yes', true ],
- [ 'TRUE', true ],
- [ 'YeS', true ],
- [ 'On', true ],
- [ '1', true ],
- [ '+1', true ],
- [ '01', true ],
- [ '-001', true ],
- [ ' 1', true ],
- [ '-1 ', true ],
- [ '', false ],
- [ '0', false ],
- [ 'false', false ],
- [ 'NO', false ],
- [ 'NOT', false ],
- [ 'never', false ],
- [ '!&', false ],
- [ '-0', false ],
- [ '+0', false ],
- [ 'forget about it', false ],
- [ ' on', false ],
- [ 'true ', false ],
- ];
- }
-
- /**
- * @dataProvider getTestCases
- * @param string $str
- * @param bool $bool
- */
- public function testStr2Bool( $str, $bool ) {
- if ( $bool ) {
- $this->assertTrue( wfStringToBool( $str ) );
- } else {
- $this->assertFalse( wfStringToBool( $str ) );
- }
- }
-
-}
+++ /dev/null
-<?php
-
-/**
- * @group GlobalFunctions
- * @covers ::wfTimestamp
- */
-class WfTimestampTest extends MediaWikiTestCase {
- /**
- * @dataProvider provideNormalTimestamps
- */
- public function testNormalTimestamps( $input, $format, $output, $desc ) {
- $this->assertEquals( $output, wfTimestamp( $format, $input ), $desc );
- }
-
- public static function provideNormalTimestamps() {
- $t = gmmktime( 12, 34, 56, 1, 15, 2001 );
-
- return [
- // TS_UNIX
- [ $t, TS_MW, '20010115123456', 'TS_UNIX to TS_MW' ],
- [ -30281104, TS_MW, '19690115123456', 'Negative TS_UNIX to TS_MW' ],
- [ $t, TS_UNIX, 979562096, 'TS_UNIX to TS_UNIX' ],
- [ $t, TS_DB, '2001-01-15 12:34:56', 'TS_UNIX to TS_DB' ],
- [ $t + 0.01, TS_MW, '20010115123456', 'TS_UNIX float to TS_MW' ],
-
- [ $t, TS_ISO_8601_BASIC, '20010115T123456Z', 'TS_ISO_8601_BASIC to TS_DB' ],
-
- // TS_MW
- [ '20010115123456', TS_MW, '20010115123456', 'TS_MW to TS_MW' ],
- [ '20010115123456', TS_UNIX, 979562096, 'TS_MW to TS_UNIX' ],
- [ '20010115123456', TS_DB, '2001-01-15 12:34:56', 'TS_MW to TS_DB' ],
- [ '20010115123456', TS_ISO_8601_BASIC, '20010115T123456Z', 'TS_MW to TS_ISO_8601_BASIC' ],
-
- // TS_DB
- [ '2001-01-15 12:34:56', TS_MW, '20010115123456', 'TS_DB to TS_MW' ],
- [ '2001-01-15 12:34:56', TS_UNIX, 979562096, 'TS_DB to TS_UNIX' ],
- [ '2001-01-15 12:34:56', TS_DB, '2001-01-15 12:34:56', 'TS_DB to TS_DB' ],
- [
- '2001-01-15 12:34:56',
- TS_ISO_8601_BASIC,
- '20010115T123456Z',
- 'TS_DB to TS_ISO_8601_BASIC'
- ],
-
- # rfc2822 section 3.3
- [ '20010115123456', TS_RFC2822, 'Mon, 15 Jan 2001 12:34:56 GMT', 'TS_MW to TS_RFC2822' ],
- [ 'Mon, 15 Jan 2001 12:34:56 GMT', TS_MW, '20010115123456', 'TS_RFC2822 to TS_MW' ],
- [
- ' Mon, 15 Jan 2001 12:34:56 GMT',
- TS_MW,
- '20010115123456',
- 'TS_RFC2822 with leading space to TS_MW'
- ],
- [
- '15 Jan 2001 12:34:56 GMT',
- TS_MW,
- '20010115123456',
- 'TS_RFC2822 without optional day-of-week to TS_MW'
- ],
-
- # FWS = ([*WSP CRLF] 1*WSP) / obs-FWS ; Folding white space
- # obs-FWS = 1*WSP *(CRLF 1*WSP) ; Section 4.2
- [ 'Mon, 15 Jan 2001 12:34:56 GMT', TS_MW, '20010115123456', 'TS_RFC2822 to TS_MW' ],
-
- # WSP = SP / HTAB ; rfc2234
- [
- "Mon, 15 Jan\x092001 12:34:56 GMT",
- TS_MW,
- '20010115123456',
- 'TS_RFC2822 with HTAB to TS_MW'
- ],
- [
- "Mon, 15 Jan\x09 \x09 2001 12:34:56 GMT",
- TS_MW,
- '20010115123456',
- 'TS_RFC2822 with HTAB and SP to TS_MW'
- ],
- [
- 'Sun, 6 Nov 94 08:49:37 GMT',
- TS_MW,
- '19941106084937',
- 'TS_RFC2822 with obsolete year to TS_MW'
- ],
- ];
- }
-
- /**
- * This test checks wfTimestamp() with values outside.
- * It needs PHP 64 bits or PHP > 5.1.
- * See r74778 and T27451
- * @dataProvider provideOldTimestamps
- */
- public function testOldTimestamps( $input, $outputType, $output, $message ) {
- $timestamp = wfTimestamp( $outputType, $input );
- if ( substr( $output, 0, 1 ) === '/' ) {
- // T66946: Day of the week calculations for very old
- // timestamps varies from system to system.
- $this->assertRegExp( $output, $timestamp, $message );
- } else {
- $this->assertEquals( $output, $timestamp, $message );
- }
- }
-
- public static function provideOldTimestamps() {
- return [
- [
- '19011213204554',
- TS_RFC2822,
- 'Fri, 13 Dec 1901 20:45:54 GMT',
- 'Earliest time according to PHP documentation'
- ],
- [ '20380119031407', TS_RFC2822, 'Tue, 19 Jan 2038 03:14:07 GMT', 'Latest 32 bit time' ],
- [ '19011213204552', TS_UNIX, '-2147483648', 'Earliest 32 bit unix time' ],
- [ '20380119031407', TS_UNIX, '2147483647', 'Latest 32 bit unix time' ],
- [ '19011213204552', TS_RFC2822, 'Fri, 13 Dec 1901 20:45:52 GMT', 'Earliest 32 bit time' ],
- [
- '19011213204551',
- TS_RFC2822,
- 'Fri, 13 Dec 1901 20:45:51 GMT', 'Earliest 32 bit time - 1'
- ],
- [ '20380119031408', TS_RFC2822, 'Tue, 19 Jan 2038 03:14:08 GMT', 'Latest 32 bit time + 1' ],
- [ '19011212000000', TS_MW, '19011212000000', 'Convert to itself r74778#c10645' ],
- [ '19011213204551', TS_UNIX, '-2147483649', 'Earliest 32 bit unix time - 1' ],
- [ '20380119031408', TS_UNIX, '2147483648', 'Latest 32 bit unix time + 1' ],
- [ '-2147483649', TS_MW, '19011213204551', '1901 negative unix time to MediaWiki' ],
- [ '-5331871504', TS_MW, '18010115123456', '1801 negative unix time to MediaWiki' ],
- [
- '0117-08-09 12:34:56',
- TS_RFC2822,
- '/, 09 Aug 0117 12:34:56 GMT$/',
- 'Death of Roman Emperor [[Trajan]]'
- ],
-
- /* @todo FIXME: 00 to 101 years are taken as being in [1970-2069] */
- [ '-58979923200', TS_RFC2822, '/, 01 Jan 0101 00:00:00 GMT$/', '1/1/101' ],
- [ '-62135596800', TS_RFC2822, 'Mon, 01 Jan 0001 00:00:00 GMT', 'Year 1' ],
-
- /* It is not clear if we should generate a year 0 or not
- * We are completely off RFC2822 requirement of year being
- * 1900 or later.
- */
- [
- '-62142076800',
- TS_RFC2822,
- 'Wed, 18 Oct 0000 00:00:00 GMT',
- 'ISO 8601:2004 [[year 0]], also called [[1 BC]]'
- ],
- ];
- }
-
- /**
- * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1
- * @dataProvider provideHttpDates
- */
- public function testHttpDate( $input, $output, $desc ) {
- $this->assertEquals( $output, wfTimestamp( TS_MW, $input ), $desc );
- }
-
- public static function provideHttpDates() {
- return [
- [ 'Sun, 06 Nov 1994 08:49:37 GMT', '19941106084937', 'RFC 822 date' ],
- [ 'Sunday, 06-Nov-94 08:49:37 GMT', '19941106084937', 'RFC 850 date' ],
- [ 'Sun Nov 6 08:49:37 1994', '19941106084937', "ANSI C's asctime() format" ],
- // See http://www.squid-cache.org/mail-archive/squid-users/200307/0122.html and r77171
- [
- 'Mon, 22 Nov 2010 14:12:42 GMT; length=52626',
- '20101122141242',
- 'Netscape extension to HTTP/1.0'
- ],
- ];
- }
-
- /**
- * There are a number of assumptions in our codebase where wfTimestamp()
- * should give the current date but it is not given a 0 there. See r71751 CR
- */
- public function testTimestampParameter() {
- $now = wfTimestamp( TS_UNIX );
- // We check that wfTimestamp doesn't return false (error) and use a LessThan assert
- // for the cases where the test is run in a second boundary.
-
- $zero = wfTimestamp( TS_UNIX, 0 );
- $this->assertNotEquals( false, $zero );
- $this->assertLessThan( 5, $zero - $now );
-
- $empty = wfTimestamp( TS_UNIX, '' );
- $this->assertNotEquals( false, $empty );
- $this->assertLessThan( 5, $empty - $now );
-
- $null = wfTimestamp( TS_UNIX, null );
- $this->assertNotEquals( false, $null );
- $this->assertLessThan( 5, $null - $now );
- }
-}
+++ /dev/null
-<?php
-
-/**
- * The function only need a string parameter and might react to IIS7.0
- *
- * @group GlobalFunctions
- * @covers ::wfUrlencode
- */
-class WfUrlencodeTest extends MediaWikiTestCase {
- # ### TESTS ##############################################################
-
- /**
- * @dataProvider provideURLS
- */
- public function testEncodingUrlWith( $input, $expected ) {
- $this->verifyEncodingFor( 'Apache', $input, $expected );
- }
-
- /**
- * @dataProvider provideURLS
- */
- public function testEncodingUrlWithMicrosoftIis7( $input, $expected ) {
- $this->verifyEncodingFor( 'Microsoft-IIS/7', $input, $expected );
- }
-
- # ### HELPERS #############################################################
-
- /**
- * Internal helper that actually run the test.
- * Called by the public methods testEncodingUrlWith...()
- */
- private function verifyEncodingFor( $server, $input, $expectations ) {
- $expected = $this->extractExpect( $server, $expectations );
-
- // save up global
- $old = $_SERVER['SERVER_SOFTWARE'] ?? null;
- $_SERVER['SERVER_SOFTWARE'] = $server;
- wfUrlencode( null );
-
- // do the requested test
- $this->assertEquals(
- $expected,
- wfUrlencode( $input ),
- "Encoding '$input' for server '$server' should be '$expected'"
- );
-
- // restore global
- if ( $old === null ) {
- unset( $_SERVER['SERVER_SOFTWARE'] );
- } else {
- $_SERVER['SERVER_SOFTWARE'] = $old;
- }
- wfUrlencode( null );
- }
-
- /**
- * Interprets the provider array. Return expected value depending
- * the HTTP server name.
- */
- private function extractExpect( $server, $expectations ) {
- if ( is_string( $expectations ) ) {
- return $expectations;
- } elseif ( is_array( $expectations ) ) {
- if ( !array_key_exists( $server, $expectations ) ) {
- throw new MWException( __METHOD__ . " expectation does not have any "
- . "value for server name $server. Check the provider array.\n" );
- } else {
- return $expectations[$server];
- }
- } else {
- throw new MWException( __METHOD__ . " given invalid expectation for "
- . "'$server'. Should be a string or an array [ <http server name> => <string> ].\n" );
- }
- }
-
- # ### PROVIDERS ###########################################################
-
- /**
- * Format is either:
- * [ 'input', 'expected' ];
- * Or:
- * [ 'input',
- * [ 'Apache', 'expected' ],
- * [ 'Microsoft-IIS/7', 'expected' ],
- * ],
- * If you want to add other HTTP server name, you will have to add a new
- * testing method much like the testEncodingUrlWith() method above.
- */
- public static function provideURLS() {
- return [
- # ## RFC 1738 chars
- // + is not safe
- [ '+', '%2B' ],
- // & and = not safe in queries
- [ '&', '%26' ],
- [ '=', '%3D' ],
-
- [ ':', [
- 'Apache' => ':',
- 'Microsoft-IIS/7' => '%3A',
- ] ],
-
- // remaining chars do not need encoding
- [
- ';@$-_.!*',
- ';@$-_.!*',
- ],
-
- # ## Other tests
- // slash remain unchanged. %2F seems to break things
- [ '/', '/' ],
- // T105265
- [ '~', '~' ],
-
- // Other 'funnies' chars
- [ '[]', '%5B%5D' ],
- [ '<>', '%3C%3E' ],
-
- // Apostrophe is encoded
- [ '\'', '%27' ],
- ];
- }
-}
$rl = $out->getResourceLoader();
$rl->setMessageBlobStore( $this->createMock( MessageBlobStore::class ) );
$rl->register( [
- 'test.foo' => new ResourceLoaderTestModule( [
+ 'test.foo' => [
+ 'class' => ResourceLoaderTestModule::class,
'script' => 'mw.test.foo( { a: true } );',
'styles' => '.mw-test-foo { content: "style"; }',
- ] ),
- 'test.bar' => new ResourceLoaderTestModule( [
+ ],
+ 'test.bar' => [
+ 'class' => ResourceLoaderTestModule::class,
'script' => 'mw.test.bar( { a: true } );',
'styles' => '.mw-test-bar { content: "style"; }',
- ] ),
- 'test.baz' => new ResourceLoaderTestModule( [
+ ],
+ 'test.baz' => [
+ 'class' => ResourceLoaderTestModule::class,
'script' => 'mw.test.baz( { a: true } );',
'styles' => '.mw-test-baz { content: "style"; }',
- ] ),
- 'test.quux' => new ResourceLoaderTestModule( [
+ ],
+ 'test.quux' => [
+ 'class' => ResourceLoaderTestModule::class,
'script' => 'mw.test.baz( { token: 123 } );',
'styles' => '/* pref-animate=off */ .mw-icon { transition: none; }',
'group' => 'private',
- ] ),
- 'test.noscript' => new ResourceLoaderTestModule( [
+ ],
+ 'test.noscript' => [
+ 'class' => ResourceLoaderTestModule::class,
'styles' => '.stuff { color: red; }',
'group' => 'noscript',
- ] ),
- 'test.group.foo' => new ResourceLoaderTestModule( [
+ ],
+ 'test.group.foo' => [
+ 'class' => ResourceLoaderTestModule::class,
'script' => 'mw.doStuff( "foo" );',
'group' => 'foo',
- ] ),
- 'test.group.bar' => new ResourceLoaderTestModule( [
+ ],
+ 'test.group.bar' => [
+ 'class' => ResourceLoaderTestModule::class,
'script' => 'mw.doStuff( "bar" );',
'group' => 'bar',
- ] ),
+ ],
] );
$links = $method->invokeArgs( $out, $args );
$actualHtml = strval( $links );
->setConstructorArgs( [ $ctx ] )
->setMethods( [ 'buildCssLinksArray' ] )
->getMock();
- $op->expects( $this->any() )
- ->method( 'buildCssLinksArray' )
+ $op->method( 'buildCssLinksArray' )
->willReturn( [] );
$rl = $op->getResourceLoader();
$rl->setMessageBlobStore( $this->createMock( MessageBlobStore::class ) );
// Register custom modules
$rl->register( [
- 'example.site.a' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
- 'example.site.b' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
- 'example.user' => new ResourceLoaderTestModule( [ 'group' => 'user' ] ),
+ 'example.site.a' => [ 'class' => ResourceLoaderTestModule::class, 'group' => 'site' ],
+ 'example.site.b' => [ 'class' => ResourceLoaderTestModule::class, 'group' => 'site' ],
+ 'example.user' => [ 'class' => ResourceLoaderTestModule::class, 'group' => 'user' ],
] );
$op = TestingAccessWrapper::newFromObject( $op );
+++ /dev/null
-<?php
-
-/**
- * Tests for the PathRouter parsing.
- *
- * @covers PathRouter
- */
-class PathRouterTest extends MediaWikiTestCase {
-
- /**
- * @var PathRouter
- */
- protected $basicRouter;
-
- protected function setUp() {
- parent::setUp();
- $router = new PathRouter;
- $router->add( "/wiki/$1" );
- $this->basicRouter = $router;
- }
-
- public static function provideParse() {
- $tests = [
- // Basic path parsing
- 'Basic path parsing' => [
- "/wiki/$1",
- "/wiki/Foo",
- [ 'title' => "Foo" ]
- ],
- //
- 'Loose path auto-$1: /$1' => [
- "/",
- "/Foo",
- [ 'title' => "Foo" ]
- ],
- 'Loose path auto-$1: /wiki' => [
- "/wiki",
- "/wiki/Foo",
- [ 'title' => "Foo" ]
- ],
- 'Loose path auto-$1: /wiki/' => [
- "/wiki/",
- "/wiki/Foo",
- [ 'title' => "Foo" ]
- ],
- // Ensure that path is based on specificity, not order
- 'Order, /$1 added first' => [
- [ "/$1", "/a/$1", "/b/$1" ],
- "/a/Foo",
- [ 'title' => "Foo" ]
- ],
- 'Order, /$1 added last' => [
- [ "/b/$1", "/a/$1", "/$1" ],
- "/a/Foo",
- [ 'title' => "Foo" ]
- ],
- // Handling of key based arrays with a url parameter
- 'Key based array' => [
- [ [
- 'path' => [ 'edit' => "/edit/$1" ],
- 'params' => [ 'action' => '$key' ],
- ] ],
- "/edit/Foo",
- [ 'title' => "Foo", 'action' => 'edit' ]
- ],
- // Additional parameter
- 'Basic $2' => [
- [ [
- 'path' => '/$2/$1',
- 'params' => [ 'test' => '$2' ]
- ] ],
- "/asdf/Foo",
- [ 'title' => "Foo", 'test' => 'asdf' ]
- ],
- ];
- // Shared patterns for restricted value parameter tests
- $restrictedPatterns = [
- [
- 'path' => '/$2/$1',
- 'params' => [ 'test' => '$2' ],
- 'options' => [ '$2' => [ 'a', 'b' ] ]
- ],
- [
- 'path' => '/$2/$1',
- 'params' => [ 'test2' => '$2' ],
- 'options' => [ '$2' => 'c' ]
- ],
- '/$1'
- ];
- $tests += [
- // Restricted value parameter tests
- 'Restricted 1' => [
- $restrictedPatterns,
- "/asdf/Foo",
- [ 'title' => "asdf/Foo" ]
- ],
- 'Restricted 2' => [
- $restrictedPatterns,
- "/a/Foo",
- [ 'title' => "Foo", 'test' => 'a' ]
- ],
- 'Restricted 3' => [
- $restrictedPatterns,
- "/c/Foo",
- [ 'title' => "Foo", 'test2' => 'c' ]
- ],
-
- // Callback test
- 'Callback' => [
- [ [
- 'path' => "/$1",
- 'params' => [ 'a' => 'b', 'data:foo' => 'bar' ],
- 'options' => [ 'callback' => [ __CLASS__, 'callbackForTest' ] ]
- ] ],
- '/Foo',
- [
- 'title' => "Foo",
- 'x' => 'Foo',
- 'a' => 'b',
- 'foo' => 'bar'
- ]
- ],
-
- // Test to ensure that matches are not made if a parameter expects nonexistent input
- 'Fail' => [
- [ [
- 'path' => "/wiki/$1",
- 'params' => [ 'title' => "$1$2" ],
- ] ],
- "/wiki/A",
- []
- ],
-
- // Make sure the router handles titles like Special:Recentchanges correctly
- 'Special title' => [
- "/wiki/$1",
- "/wiki/Special:Recentchanges",
- [ 'title' => "Special:Recentchanges" ]
- ],
-
- // Make sure the router decodes urlencoding properly
- 'URL encoding' => [
- "/wiki/$1",
- "/wiki/Title_With%20Space",
- [ 'title' => "Title_With Space" ]
- ],
-
- // Double slash and dot expansion
- 'Double slash in prefix' => [
- '/wiki/$1',
- '//wiki/Foo',
- [ 'title' => 'Foo' ]
- ],
- 'Double slash at start of $1' => [
- '/wiki/$1',
- '/wiki//Foo',
- [ 'title' => '/Foo' ]
- ],
- 'Double slash in middle of $1' => [
- '/wiki/$1',
- '/wiki/.hack//SIGN',
- [ 'title' => '.hack//SIGN' ]
- ],
- 'Dots removed 1' => [
- '/wiki/$1',
- '/x/../wiki/Foo',
- [ 'title' => 'Foo' ]
- ],
- 'Dots removed 2' => [
- '/wiki/$1',
- '/./wiki/Foo',
- [ 'title' => 'Foo' ]
- ],
- 'Dots retained 1' => [
- '/wiki/$1',
- '/wiki/../wiki/Foo',
- [ 'title' => '../wiki/Foo' ]
- ],
- 'Dots retained 2' => [
- '/wiki/$1',
- '/wiki/./Foo',
- [ 'title' => './Foo' ]
- ],
- 'Triple slash' => [
- '/wiki/$1',
- '///wiki/Foo',
- [ 'title' => 'Foo' ]
- ],
- // '..' only traverses one slash, see e.g. RFC 3986
- 'Dots traversing double slash 1' => [
- '/wiki/$1',
- '/a//b/../../wiki/Foo',
- []
- ],
- 'Dots traversing double slash 2' => [
- '/wiki/$1',
- '/a//b/../../../wiki/Foo',
- [ 'title' => 'Foo' ]
- ],
- ];
-
- // Make sure the router doesn't break on special characters like $ used in regexp replacements
- foreach ( [ "$", "$1", "\\", "\\$1" ] as $char ) {
- $tests["Regexp character $char"] = [
- "/wiki/$1",
- "/wiki/$char",
- [ 'title' => "$char" ]
- ];
- }
-
- $tests += [
- // Make sure the router handles characters like +&() properly
- "Special characters" => [
- "/wiki/$1",
- "/wiki/Plus+And&Dollar\\Stuff();[]{}*",
- [ 'title' => "Plus+And&Dollar\\Stuff();[]{}*" ],
- ],
-
- // Make sure the router handles unicode characters correctly
- "Unicode 1" => [
- "/wiki/$1",
- "/wiki/Spécial:Modifications_récentes" ,
- [ 'title' => "Spécial:Modifications_récentes" ],
- ],
-
- "Unicode 2" => [
- "/wiki/$1",
- "/wiki/Sp%C3%A9cial:Modifications_r%C3%A9centes",
- [ 'title' => "Spécial:Modifications_récentes" ],
- ]
- ];
-
- // Ensure the router doesn't choke on long paths.
- $lorem = "Lorem_ipsum_dolor_sit_amet,_consectetur_adipisicing_elit,_sed_do_eiusmod_" .
- "tempor_incididunt_ut_labore_et_dolore_magna_aliqua._Ut_enim_ad_minim_veniam,_quis_" .
- "nostrud_exercitation_ullamco_laboris_nisi_ut_aliquip_ex_ea_commodo_consequat._" .
- "Duis_aute_irure_dolor_in_reprehenderit_in_voluptate_velit_esse_cillum_dolore_" .
- "eu_fugiat_nulla_pariatur._Excepteur_sint_occaecat_cupidatat_non_proident,_sunt_" .
- "in_culpa_qui_officia_deserunt_mollit_anim_id_est_laborum.";
-
- $tests += [
- "Long path" => [
- "/wiki/$1",
- "/wiki/$lorem",
- [ 'title' => $lorem ]
- ],
-
- // Ensure that the php passed site of parameter values are not urldecoded
- "Pattern urlencoding" => [
- [ [ 'path' => "/wiki/$1", 'params' => [ 'title' => '%20:$1' ] ] ],
- "/wiki/Foo",
- [ 'title' => '%20:Foo' ]
- ],
-
- // Ensure that raw parameter values do not have any variable replacements or urldecoding
- "Raw param value" => [
- [ [ 'path' => "/wiki/$1", 'params' => [ 'title' => [ 'value' => 'bar%20$1' ] ] ] ],
- "/wiki/Foo",
- [ 'title' => 'bar%20$1' ]
- ]
- ];
-
- return $tests;
- }
-
- /**
- * Test path parsing
- * @dataProvider provideParse
- */
- public function testParse( $patterns, $path, $expected ) {
- $patterns = (array)$patterns;
-
- $router = new PathRouter;
- foreach ( $patterns as $pattern ) {
- if ( is_array( $pattern ) ) {
- $router->add( $pattern['path'], $pattern['params'] ?? [],
- $pattern['options'] ?? [] );
- } else {
- $router->add( $pattern );
- }
- }
- $matches = $router->parse( $path );
- $this->assertEquals( $matches, $expected );
- }
-
- public static function callbackForTest( &$matches, $data ) {
- $matches['x'] = $data['$1'];
- $matches['foo'] = $data['foo'];
- }
-
- public static function provideWeight() {
- return [
- [ '/Foo', [ 'title' => 'Foo' ] ],
- [ '/Bar', [ 'ping' => 'pong' ] ],
- [ '/Baz', [ 'marco' => 'polo' ] ],
- [ '/asdf-foo', [ 'title' => 'qwerty-foo' ] ],
- [ '/qwerty-bar', [ 'title' => 'asdf-bar' ] ],
- [ '/a/Foo', [ 'title' => 'Foo' ] ],
- [ '/asdf/Foo', [ 'title' => 'Foo' ] ],
- [ '/qwerty/Foo', [ 'title' => 'Foo', 'qwerty' => 'qwerty' ] ],
- [ '/baz/Foo', [ 'title' => 'Foo', 'unrestricted' => 'baz' ] ],
- [ '/y/Foo', [ 'title' => 'Foo', 'restricted-to-y' => 'y' ] ],
- ];
- }
-
- /**
- * Test to ensure weight of paths is handled correctly
- * @dataProvider provideWeight
- */
- public function testWeight( $path, $expected ) {
- $router = new PathRouter;
- $router->addStrict( "/Bar", [ 'ping' => 'pong' ] );
- $router->add( "/asdf-$1", [ 'title' => 'qwerty-$1' ] );
- $router->add( "/$1" );
- $router->add( "/qwerty-$1", [ 'title' => 'asdf-$1' ] );
- $router->addStrict( "/Baz", [ 'marco' => 'polo' ] );
- $router->add( "/a/$1" );
- $router->add( "/asdf/$1" );
- $router->add( "/$2/$1", [ 'unrestricted' => '$2' ] );
- $router->add( [ 'qwerty' => "/qwerty/$1" ], [ 'qwerty' => '$key' ] );
- $router->add( "/$2/$1", [ 'restricted-to-y' => '$2' ], [ '$2' => 'y' ] );
-
- $this->assertEquals( $router->parse( $path ), $expected );
- }
-}
+++ /dev/null
-<?php
-
-namespace MediaWiki\Tests\Rest;
-
-use ArrayIterator;
-use MediaWiki\Rest\HttpException;
-use MediaWiki\Rest\ResponseFactory;
-use MediaWikiTestCase;
-
-/** @covers \MediaWiki\Rest\ResponseFactory */
-class ResponseFactoryTest extends MediaWikiTestCase {
- public static function provideEncodeJson() {
- return [
- [ (object)[], '{}' ],
- [ '/', '"/"' ],
- [ '£', '"£"' ],
- [ [], '[]' ],
- ];
- }
-
- /** @dataProvider provideEncodeJson */
- public function testEncodeJson( $input, $expected ) {
- $rf = new ResponseFactory;
- $this->assertSame( $expected, $rf->encodeJson( $input ) );
- }
-
- public function testCreateJson() {
- $rf = new ResponseFactory;
- $response = $rf->createJson( [] );
- $response->getBody()->rewind();
- $this->assertSame( 'application/json', $response->getHeaderLine( 'Content-Type' ) );
- $this->assertSame( '[]', $response->getBody()->getContents() );
- // Make sure getSize() is functional, since testCreateNoContent() depends on it
- $this->assertSame( 2, $response->getBody()->getSize() );
- }
-
- public function testCreateNoContent() {
- $rf = new ResponseFactory;
- $response = $rf->createNoContent();
- $this->assertSame( [], $response->getHeader( 'Content-Type' ) );
- $this->assertSame( 0, $response->getBody()->getSize() );
- $this->assertSame( 204, $response->getStatusCode() );
- }
-
- public function testCreatePermanentRedirect() {
- $rf = new ResponseFactory;
- $response = $rf->createPermanentRedirect( 'http://www.example.com/' );
- $this->assertSame( [ 'http://www.example.com/' ], $response->getHeader( 'Location' ) );
- $this->assertSame( 301, $response->getStatusCode() );
- }
-
- public function testCreateLegacyTemporaryRedirect() {
- $rf = new ResponseFactory;
- $response = $rf->createLegacyTemporaryRedirect( 'http://www.example.com/' );
- $this->assertSame( [ 'http://www.example.com/' ], $response->getHeader( 'Location' ) );
- $this->assertSame( 302, $response->getStatusCode() );
- }
-
- public function testCreateTemporaryRedirect() {
- $rf = new ResponseFactory;
- $response = $rf->createTemporaryRedirect( 'http://www.example.com/' );
- $this->assertSame( [ 'http://www.example.com/' ], $response->getHeader( 'Location' ) );
- $this->assertSame( 307, $response->getStatusCode() );
- }
-
- public function testCreateSeeOther() {
- $rf = new ResponseFactory;
- $response = $rf->createSeeOther( 'http://www.example.com/' );
- $this->assertSame( [ 'http://www.example.com/' ], $response->getHeader( 'Location' ) );
- $this->assertSame( 303, $response->getStatusCode() );
- }
-
- public function testCreateNotModified() {
- $rf = new ResponseFactory;
- $response = $rf->createNotModified();
- $this->assertSame( 0, $response->getBody()->getSize() );
- $this->assertSame( 304, $response->getStatusCode() );
- }
-
- /** @expectedException \InvalidArgumentException */
- public function testCreateHttpErrorInvalid() {
- $rf = new ResponseFactory;
- $rf->createHttpError( 200 );
- }
-
- public function testCreateHttpError() {
- $rf = new ResponseFactory;
- $response = $rf->createHttpError( 415, [ 'message' => '...' ] );
- $this->assertSame( 415, $response->getStatusCode() );
- $body = $response->getBody();
- $body->rewind();
- $data = json_decode( $body->getContents(), true );
- $this->assertSame( 415, $data['httpCode'] );
- $this->assertSame( '...', $data['message'] );
- }
-
- public function testCreateFromExceptionUnlogged() {
- $rf = new ResponseFactory;
- $response = $rf->createFromException( new HttpException( 'hello', 415 ) );
- $this->assertSame( 415, $response->getStatusCode() );
- $body = $response->getBody();
- $body->rewind();
- $data = json_decode( $body->getContents(), true );
- $this->assertSame( 415, $data['httpCode'] );
- $this->assertSame( 'hello', $data['message'] );
- }
-
- public function testCreateFromExceptionLogged() {
- $rf = new ResponseFactory;
- $response = $rf->createFromException( new \Exception( "hello", 415 ) );
- $this->assertSame( 500, $response->getStatusCode() );
- $body = $response->getBody();
- $body->rewind();
- $data = json_decode( $body->getContents(), true );
- $this->assertSame( 500, $data['httpCode'] );
- $this->assertSame( 'Error: exception of type Exception', $data['message'] );
- }
-
- public static function provideCreateFromReturnValue() {
- return [
- [ 'hello', '{"value":"hello"}' ],
- [ true, '{"value":true}' ],
- [ [ 'x' => 'y' ], '{"x":"y"}' ],
- [ [ 'x', 'y' ], '["x","y"]' ],
- [ [ 'a', 'x' => 'y' ], '{"0":"a","x":"y"}' ],
- [ (object)[ 'a', 'x' => 'y' ], '{"0":"a","x":"y"}' ],
- [ [], '[]' ],
- [ (object)[], '{}' ],
- ];
- }
-
- /** @dataProvider provideCreateFromReturnValue */
- public function testCreateFromReturnValue( $input, $expected ) {
- $rf = new ResponseFactory;
- $response = $rf->createFromReturnValue( $input );
- $body = $response->getBody();
- $body->rewind();
- $this->assertSame( $expected, $body->getContents() );
- }
-
- /** @expectedException \InvalidArgumentException */
- public function testCreateFromReturnValueInvalid() {
- $rf = new ResponseFactory;
- $rf->createFromReturnValue( new ArrayIterator );
- }
-}
+++ /dev/null
-<?php
-
-namespace MediaWiki\Tests\Revision;
-
-use MediaWiki\Revision\MainSlotRoleHandler;
-use MediaWikiTestCase;
-use PHPUnit\Framework\MockObject\MockObject;
-use Title;
-
-/**
- * @covers \MediaWiki\Revision\MainSlotRoleHandler
- */
-class MainSlotRoleHandlerTest extends MediaWikiTestCase {
-
- private function makeTitleObject( $ns ) {
- /** @var Title|MockObject $title */
- $title = $this->getMockBuilder( Title::class )
- ->disableOriginalConstructor()
- ->getMock();
-
- $title->method( 'getNamespace' )
- ->willReturn( $ns );
-
- return $title;
- }
-
- /**
- * @covers \MediaWiki\Revision\MainSlotRoleHandler::__construct
- * @covers \MediaWiki\Revision\MainSlotRoleHandler::getRole()
- * @covers \MediaWiki\Revision\MainSlotRoleHandler::getNameMessageKey()
- * @covers \MediaWiki\Revision\MainSlotRoleHandler::getOutputLayoutHints()
- */
- public function testConstruction() {
- $handler = new MainSlotRoleHandler( [] );
- $this->assertSame( 'main', $handler->getRole() );
- $this->assertSame( 'slot-name-main', $handler->getNameMessageKey() );
-
- $hints = $handler->getOutputLayoutHints();
- $this->assertArrayHasKey( 'display', $hints );
- $this->assertArrayHasKey( 'region', $hints );
- $this->assertArrayHasKey( 'placement', $hints );
- }
-
- /**
- * @covers \MediaWiki\Revision\MainSlotRoleHandler::getDefaultModel()
- */
- public function testFetDefaultModel() {
- $handler = new MainSlotRoleHandler( [ 100 => CONTENT_MODEL_TEXT ] );
-
- // For the main handler, the namespace determins the default model
- $titleMain = $this->makeTitleObject( NS_MAIN );
- $this->assertSame( CONTENT_MODEL_WIKITEXT, $handler->getDefaultModel( $titleMain ) );
-
- $title100 = $this->makeTitleObject( 100 );
- $this->assertSame( CONTENT_MODEL_TEXT, $handler->getDefaultModel( $title100 ) );
- }
-
- /**
- * @covers \MediaWiki\Revision\MainSlotRoleHandler::isAllowedModel()
- */
- public function testIsAllowedModel() {
- $handler = new MainSlotRoleHandler( [] );
-
- // For the main handler, (nearly) all models are allowed
- $title = $this->makeTitleObject( NS_MAIN );
- $this->assertTrue( $handler->isAllowedModel( CONTENT_MODEL_WIKITEXT, $title ) );
- $this->assertTrue( $handler->isAllowedModel( CONTENT_MODEL_TEXT, $title ) );
- }
-
- /**
- * @covers \MediaWiki\Revision\MainSlotRoleHandler::supportsArticleCount()
- */
- public function testSupportsArticleCount() {
- $handler = new MainSlotRoleHandler( [] );
-
- $this->assertTrue( $handler->supportsArticleCount() );
- }
-
-}
/**
* @dataProvider provideDomainCheck
- * @covers \MediaWiki\Revision\RevisionStore::checkDatabaseWikiId
+ * @covers \MediaWiki\Revision\RevisionStore::checkDatabaseDomain
*/
public function testDomainCheck( $wikiId, $dbName, $dbPrefix ) {
$this->setMwGlobals(
+++ /dev/null
-<?php
-
-namespace MediaWiki\Tests\Revision;
-
-use InvalidArgumentException;
-use LogicException;
-use MediaWiki\Revision\IncompleteRevisionException;
-use MediaWiki\Revision\SlotRecord;
-use MediaWiki\Revision\SuppressedDataException;
-use MediaWikiTestCase;
-use WikitextContent;
-
-/**
- * @covers \MediaWiki\Revision\SlotRecord
- */
-class SlotRecordTest extends MediaWikiTestCase {
-
- private function makeRow( $data = [] ) {
- $data = $data + [
- 'slot_id' => 1234,
- 'slot_content_id' => 33,
- 'content_size' => '5',
- 'content_sha1' => 'someHash',
- 'content_address' => 'tt:456',
- 'model_name' => CONTENT_MODEL_WIKITEXT,
- 'format_name' => CONTENT_FORMAT_WIKITEXT,
- 'slot_revision_id' => '2',
- 'slot_origin' => '1',
- 'role_name' => 'myRole',
- ];
- return (object)$data;
- }
-
- public function testCompleteConstruction() {
- $row = $this->makeRow();
- $record = new SlotRecord( $row, new WikitextContent( 'A' ) );
-
- $this->assertTrue( $record->hasAddress() );
- $this->assertTrue( $record->hasContentId() );
- $this->assertTrue( $record->hasRevision() );
- $this->assertTrue( $record->isInherited() );
- $this->assertSame( 'A', $record->getContent()->getText() );
- $this->assertSame( 5, $record->getSize() );
- $this->assertSame( 'someHash', $record->getSha1() );
- $this->assertSame( CONTENT_MODEL_WIKITEXT, $record->getModel() );
- $this->assertSame( 2, $record->getRevision() );
- $this->assertSame( 1, $record->getOrigin() );
- $this->assertSame( 'tt:456', $record->getAddress() );
- $this->assertSame( 33, $record->getContentId() );
- $this->assertSame( CONTENT_FORMAT_WIKITEXT, $record->getFormat() );
- $this->assertSame( 'myRole', $record->getRole() );
- }
-
- public function testConstructionDeferred() {
- $row = $this->makeRow( [
- 'content_size' => null, // to be computed
- 'content_sha1' => null, // to be computed
- 'format_name' => function () {
- return CONTENT_FORMAT_WIKITEXT;
- },
- 'slot_revision_id' => '2',
- 'slot_origin' => '2',
- 'slot_content_id' => function () {
- return null;
- },
- ] );
-
- $content = function () {
- return new WikitextContent( 'A' );
- };
-
- $record = new SlotRecord( $row, $content );
-
- $this->assertTrue( $record->hasAddress() );
- $this->assertTrue( $record->hasRevision() );
- $this->assertFalse( $record->hasContentId() );
- $this->assertFalse( $record->isInherited() );
- $this->assertSame( 'A', $record->getContent()->getText() );
- $this->assertSame( 1, $record->getSize() );
- $this->assertNotEmpty( $record->getSha1() );
- $this->assertSame( CONTENT_MODEL_WIKITEXT, $record->getModel() );
- $this->assertSame( 2, $record->getRevision() );
- $this->assertSame( 2, $record->getRevision() );
- $this->assertSame( 'tt:456', $record->getAddress() );
- $this->assertSame( CONTENT_FORMAT_WIKITEXT, $record->getFormat() );
- $this->assertSame( 'myRole', $record->getRole() );
- }
-
- public function testNewUnsaved() {
- $record = SlotRecord::newUnsaved( 'myRole', new WikitextContent( 'A' ) );
-
- $this->assertFalse( $record->hasAddress() );
- $this->assertFalse( $record->hasContentId() );
- $this->assertFalse( $record->hasRevision() );
- $this->assertFalse( $record->isInherited() );
- $this->assertFalse( $record->hasOrigin() );
- $this->assertSame( 'A', $record->getContent()->getText() );
- $this->assertSame( 1, $record->getSize() );
- $this->assertNotEmpty( $record->getSha1() );
- $this->assertSame( CONTENT_MODEL_WIKITEXT, $record->getModel() );
- $this->assertSame( 'myRole', $record->getRole() );
- }
-
- public function provideInvalidConstruction() {
- yield 'both null' => [ null, null ];
- yield 'null row' => [ null, new WikitextContent( 'A' ) ];
- yield 'array row' => [ [], new WikitextContent( 'A' ) ];
- yield 'empty row' => [ (object)[], new WikitextContent( 'A' ) ];
- yield 'null content' => [ (object)[], null ];
- }
-
- /**
- * @dataProvider provideInvalidConstruction
- */
- public function testInvalidConstruction( $row, $content ) {
- $this->setExpectedException( InvalidArgumentException::class );
- new SlotRecord( $row, $content );
- }
-
- public function testGetContentId_fails() {
- $record = SlotRecord::newUnsaved( SlotRecord::MAIN, new WikitextContent( 'A' ) );
- $this->setExpectedException( IncompleteRevisionException::class );
-
- $record->getContentId();
- }
-
- public function testGetAddress_fails() {
- $record = SlotRecord::newUnsaved( SlotRecord::MAIN, new WikitextContent( 'A' ) );
- $this->setExpectedException( IncompleteRevisionException::class );
-
- $record->getAddress();
- }
-
- public function provideIncomplete() {
- $unsaved = SlotRecord::newUnsaved( SlotRecord::MAIN, new WikitextContent( 'A' ) );
- yield 'unsaved' => [ $unsaved ];
-
- $parent = new SlotRecord( $this->makeRow(), new WikitextContent( 'A' ) );
- $inherited = SlotRecord::newInherited( $parent );
- yield 'inherited' => [ $inherited ];
- }
-
- /**
- * @dataProvider provideIncomplete
- */
- public function testGetRevision_fails( SlotRecord $record ) {
- $record = SlotRecord::newUnsaved( SlotRecord::MAIN, new WikitextContent( 'A' ) );
- $this->setExpectedException( IncompleteRevisionException::class );
-
- $record->getRevision();
- }
-
- /**
- * @dataProvider provideIncomplete
- */
- public function testGetOrigin_fails( SlotRecord $record ) {
- $record = SlotRecord::newUnsaved( SlotRecord::MAIN, new WikitextContent( 'A' ) );
- $this->setExpectedException( IncompleteRevisionException::class );
-
- $record->getOrigin();
- }
-
- public function provideHashStability() {
- yield [ '', 'phoiac9h4m842xq45sp7s6u21eteeq1' ];
- yield [ 'Lorem ipsum', 'hcr5u40uxr81d3nx89nvwzclfz6r9c5' ];
- }
-
- /**
- * @dataProvider provideHashStability
- */
- public function testHashStability( $text, $hash ) {
- // Changing the output of the hash function will break things horribly!
-
- $this->assertSame( $hash, SlotRecord::base36Sha1( $text ) );
-
- $record = SlotRecord::newUnsaved( SlotRecord::MAIN, new WikitextContent( $text ) );
- $this->assertSame( $hash, $record->getSha1() );
- }
-
- public function testHashComputed() {
- $row = $this->makeRow();
- $row->content_sha1 = '';
-
- $rec = new SlotRecord( $row, new WikitextContent( 'A' ) );
- $this->assertNotEmpty( $rec->getSha1() );
- }
-
- public function testNewWithSuppressedContent() {
- $input = new SlotRecord( $this->makeRow(), new WikitextContent( 'A' ) );
- $output = SlotRecord::newWithSuppressedContent( $input );
-
- $this->setExpectedException( SuppressedDataException::class );
- $output->getContent();
- }
-
- public function testNewInherited() {
- $row = $this->makeRow( [ 'slot_revision_id' => 7, 'slot_origin' => 7 ] );
- $parent = new SlotRecord( $row, new WikitextContent( 'A' ) );
-
- // This would happen while doing an edit, before saving revision meta-data.
- $inherited = SlotRecord::newInherited( $parent );
-
- $this->assertSame( $parent->getContentId(), $inherited->getContentId() );
- $this->assertSame( $parent->getAddress(), $inherited->getAddress() );
- $this->assertSame( $parent->getContent(), $inherited->getContent() );
- $this->assertTrue( $inherited->isInherited() );
- $this->assertTrue( $inherited->hasOrigin() );
- $this->assertFalse( $inherited->hasRevision() );
-
- // make sure we didn't mess with the internal state of $parent
- $this->assertFalse( $parent->isInherited() );
- $this->assertSame( 7, $parent->getRevision() );
-
- // This would happen while doing an edit, after saving the revision meta-data
- // and content meta-data.
- $saved = SlotRecord::newSaved(
- 10,
- $inherited->getContentId(),
- $inherited->getAddress(),
- $inherited
- );
- $this->assertSame( $parent->getContentId(), $saved->getContentId() );
- $this->assertSame( $parent->getAddress(), $saved->getAddress() );
- $this->assertSame( $parent->getContent(), $saved->getContent() );
- $this->assertTrue( $saved->isInherited() );
- $this->assertTrue( $saved->hasRevision() );
- $this->assertSame( 10, $saved->getRevision() );
-
- // make sure we didn't mess with the internal state of $parent or $inherited
- $this->assertSame( 7, $parent->getRevision() );
- $this->assertFalse( $inherited->hasRevision() );
- }
-
- public function testNewSaved() {
- // This would happen while doing an edit, before saving revision meta-data.
- $unsaved = SlotRecord::newUnsaved( SlotRecord::MAIN, new WikitextContent( 'A' ) );
-
- // This would happen while doing an edit, after saving the revision meta-data
- // and content meta-data.
- $saved = SlotRecord::newSaved( 10, 20, 'theNewAddress', $unsaved );
- $this->assertFalse( $saved->isInherited() );
- $this->assertTrue( $saved->hasOrigin() );
- $this->assertTrue( $saved->hasRevision() );
- $this->assertTrue( $saved->hasAddress() );
- $this->assertTrue( $saved->hasContentId() );
- $this->assertSame( 'theNewAddress', $saved->getAddress() );
- $this->assertSame( 20, $saved->getContentId() );
- $this->assertSame( 'A', $saved->getContent()->getText() );
- $this->assertSame( 10, $saved->getRevision() );
- $this->assertSame( 10, $saved->getOrigin() );
-
- // make sure we didn't mess with the internal state of $unsaved
- $this->assertFalse( $unsaved->hasAddress() );
- $this->assertFalse( $unsaved->hasContentId() );
- $this->assertFalse( $unsaved->hasRevision() );
- }
-
- public function provideNewSaved_LogicException() {
- $freshRow = $this->makeRow( [
- 'content_id' => 10,
- 'content_address' => 'address:1',
- 'slot_origin' => 1,
- 'slot_revision_id' => 1,
- ] );
-
- $freshSlot = new SlotRecord( $freshRow, new WikitextContent( 'A' ) );
- yield 'mismatching address' => [ 1, 10, 'address:BAD', $freshSlot ];
- yield 'mismatching revision' => [ 5, 10, 'address:1', $freshSlot ];
- yield 'mismatching content ID' => [ 1, 17, 'address:1', $freshSlot ];
-
- $inheritedRow = $this->makeRow( [
- 'content_id' => null,
- 'content_address' => null,
- 'slot_origin' => 0,
- 'slot_revision_id' => 1,
- ] );
-
- $inheritedSlot = new SlotRecord( $inheritedRow, new WikitextContent( 'A' ) );
- yield 'inherited, but no address' => [ 1, 10, 'address:2', $inheritedSlot ];
- }
-
- /**
- * @dataProvider provideNewSaved_LogicException
- */
- public function testNewSaved_LogicException(
- $revisionId,
- $contentId,
- $contentAddress,
- SlotRecord $protoSlot
- ) {
- $this->setExpectedException( LogicException::class );
- SlotRecord::newSaved( $revisionId, $contentId, $contentAddress, $protoSlot );
- }
-
- public function provideNewSaved_InvalidArgumentException() {
- $unsaved = SlotRecord::newUnsaved( SlotRecord::MAIN, new WikitextContent( 'A' ) );
-
- yield 'bad revision id' => [ 'xyzzy', 5, 'address', $unsaved ];
- yield 'bad content id' => [ 7, 'xyzzy', 'address', $unsaved ];
- yield 'bad content address' => [ 7, 5, 77, $unsaved ];
- }
-
- /**
- * @dataProvider provideNewSaved_InvalidArgumentException
- */
- public function testNewSaved_InvalidArgumentException(
- $revisionId,
- $contentId,
- $contentAddress,
- SlotRecord $protoSlot
- ) {
- $this->setExpectedException( InvalidArgumentException::class );
- SlotRecord::newSaved( $revisionId, $contentId, $contentAddress, $protoSlot );
- }
-
- public function provideHasSameContent() {
- $fail = function () {
- self::fail( 'There should be no need to actually load the content.' );
- };
-
- $a100a1 = new SlotRecord(
- $this->makeRow(
- [
- 'model_name' => 'A',
- 'content_size' => 100,
- 'content_sha1' => 'hash-a',
- 'content_address' => 'xxx:a1',
- ]
- ),
- $fail
- );
- $a100a1b = new SlotRecord(
- $this->makeRow(
- [
- 'model_name' => 'A',
- 'content_size' => 100,
- 'content_sha1' => 'hash-a',
- 'content_address' => 'xxx:a1',
- ]
- ),
- $fail
- );
- $a100null = new SlotRecord(
- $this->makeRow(
- [
- 'model_name' => 'A',
- 'content_size' => 100,
- 'content_sha1' => 'hash-a',
- 'content_address' => null,
- ]
- ),
- $fail
- );
- $a100a2 = new SlotRecord(
- $this->makeRow(
- [
- 'model_name' => 'A',
- 'content_size' => 100,
- 'content_sha1' => 'hash-a',
- 'content_address' => 'xxx:a2',
- ]
- ),
- $fail
- );
- $b100a1 = new SlotRecord(
- $this->makeRow(
- [
- 'model_name' => 'B',
- 'content_size' => 100,
- 'content_sha1' => 'hash-a',
- 'content_address' => 'xxx:a1',
- ]
- ),
- $fail
- );
- $a200a1 = new SlotRecord(
- $this->makeRow(
- [
- 'model_name' => 'A',
- 'content_size' => 200,
- 'content_sha1' => 'hash-a',
- 'content_address' => 'xxx:a2',
- ]
- ),
- $fail
- );
- $a100x1 = new SlotRecord(
- $this->makeRow(
- [
- 'model_name' => 'A',
- 'content_size' => 100,
- 'content_sha1' => 'hash-x',
- 'content_address' => 'xxx:x1',
- ]
- ),
- $fail
- );
-
- yield 'same instance' => [ $a100a1, $a100a1, true ];
- yield 'no address' => [ $a100a1, $a100null, true ];
- yield 'same address' => [ $a100a1, $a100a1b, true ];
- yield 'different address' => [ $a100a1, $a100a2, true ];
- yield 'different model' => [ $a100a1, $b100a1, false ];
- yield 'different size' => [ $a100a1, $a200a1, false ];
- yield 'different hash' => [ $a100a1, $a100x1, false ];
- }
-
- /**
- * @dataProvider provideHasSameContent
- */
- public function testHasSameContent( SlotRecord $a, SlotRecord $b, $sameContent ) {
- $this->assertSame( $sameContent, $a->hasSameContent( $b ) );
- $this->assertSame( $sameContent, $b->hasSameContent( $a ) );
- }
-
-}
+++ /dev/null
-<?php
-
-/**
- * @author Addshore
- * @covers TitleArrayFromResult
- */
-class TitleArrayFromResultTest extends PHPUnit\Framework\TestCase {
-
- use MediaWikiCoversValidator;
-
- private function getMockResultWrapper( $row = null, $numRows = 1 ) {
- $resultWrapper = $this->getMockBuilder( Wikimedia\Rdbms\ResultWrapper::class )
- ->disableOriginalConstructor();
-
- $resultWrapper = $resultWrapper->getMock();
- $resultWrapper->expects( $this->atLeastOnce() )
- ->method( 'current' )
- ->will( $this->returnValue( $row ) );
- $resultWrapper->expects( $this->any() )
- ->method( 'numRows' )
- ->will( $this->returnValue( $numRows ) );
-
- return $resultWrapper;
- }
-
- private function getRowWithTitle( $namespace = 3, $title = 'foo' ) {
- $row = new stdClass();
- $row->page_namespace = $namespace;
- $row->page_title = $title;
- return $row;
- }
-
- /**
- * @covers TitleArrayFromResult::__construct
- */
- public function testConstructionWithFalseRow() {
- $row = false;
- $resultWrapper = $this->getMockResultWrapper( $row );
-
- $object = new TitleArrayFromResult( $resultWrapper );
-
- $this->assertEquals( $resultWrapper, $object->res );
- $this->assertSame( 0, $object->key );
- $this->assertEquals( $row, $object->current );
- }
-
- /**
- * @covers TitleArrayFromResult::__construct
- */
- public function testConstructionWithRow() {
- $namespace = 0;
- $title = 'foo';
- $row = $this->getRowWithTitle( $namespace, $title );
- $resultWrapper = $this->getMockResultWrapper( $row );
-
- $object = new TitleArrayFromResult( $resultWrapper );
-
- $this->assertEquals( $resultWrapper, $object->res );
- $this->assertSame( 0, $object->key );
- $this->assertInstanceOf( Title::class, $object->current );
- $this->assertEquals( $namespace, $object->current->mNamespace );
- $this->assertEquals( $title, $object->current->mTextform );
- }
-
- public static function provideNumberOfRows() {
- return [
- [ 0 ],
- [ 1 ],
- [ 122 ],
- ];
- }
-
- /**
- * @dataProvider provideNumberOfRows
- * @covers TitleArrayFromResult::count
- */
- public function testCountWithVaryingValues( $numRows ) {
- $object = new TitleArrayFromResult( $this->getMockResultWrapper(
- $this->getRowWithTitle(),
- $numRows
- ) );
- $this->assertEquals( $numRows, $object->count() );
- }
-
- /**
- * @covers TitleArrayFromResult::current
- */
- public function testCurrentAfterConstruction() {
- $namespace = 0;
- $title = 'foo';
- $row = $this->getRowWithTitle( $namespace, $title );
- $object = new TitleArrayFromResult( $this->getMockResultWrapper( $row ) );
- $this->assertInstanceOf( Title::class, $object->current() );
- $this->assertEquals( $namespace, $object->current->mNamespace );
- $this->assertEquals( $title, $object->current->mTextform );
- }
-
- public function provideTestValid() {
- return [
- [ $this->getRowWithTitle(), true ],
- [ false, false ],
- ];
- }
-
- /**
- * @dataProvider provideTestValid
- * @covers TitleArrayFromResult::valid
- */
- public function testValid( $input, $expected ) {
- $object = new TitleArrayFromResult( $this->getMockResultWrapper( $input ) );
- $this->assertEquals( $expected, $object->valid() );
- }
-
- // @todo unit test for key()
- // @todo unit test for next()
- // @todo unit test for rewind()
-}
<?php
+use MediaWiki\Interwiki\InterwikiLookup;
use MediaWiki\Linker\LinkTarget;
use MediaWiki\MediaWikiServices;
use Wikimedia\TestingAccessWrapper;
# Title, expected base, optional message
[ 'User:John_Doe/subOne/subTwo', 'John Doe' ],
[ 'User:Foo / Bar / Baz', 'Foo ' ],
+ [ 'Talk:////', '////' ],
+ [ 'Template:////', '////' ],
+ [ 'Template:Foo////', 'Foo' ],
+ [ 'Template:Foo////Bar', 'Foo' ],
];
}
];
}
+ public function provideSubpage() {
+ // NOTE: avoid constructing Title objects in the provider, since it may access the database.
+ return [
+ [ 'Foo', 'x', new TitleValue( NS_MAIN, 'Foo/x' ) ],
+ [ 'Foo#bar', 'x', new TitleValue( NS_MAIN, 'Foo/x' ) ],
+ [ 'User:Foo', 'x', new TitleValue( NS_USER, 'Foo/x' ) ],
+ [ 'wiki:User:Foo', 'x', new TitleValue( NS_MAIN, 'User:Foo/x', '', 'wiki' ) ],
+ ];
+ }
+
+ /**
+ * @dataProvider provideSubpage
+ * @covers Title::getSubpage
+ */
+ public function testSubpage( $title, $sub, LinkTarget $expected ) {
+ $interwikiLookup = $this->getMock( InterwikiLookup::class );
+ $interwikiLookup->expects( $this->any() )
+ ->method( 'isValidInterwiki' )
+ ->willReturnCallback(
+ function ( $prefix ) {
+ return $prefix == 'wiki';
+ }
+ );
+
+ $this->setService( 'InterwikiLookup', $interwikiLookup );
+
+ $title = Title::newFromText( $title );
+ $expected = Title::newFromLinkTarget( $expected );
+ $actual = $title->getSubpage( $sub );
+
+ // NOTE: convert to string for comparison
+ $this->assertSame( $expected->getPrefixedText(), $actual->getPrefixedText(), 'text form' );
+ $this->assertTrue( $expected->equals( $actual ), 'Title equality' );
+ }
+
public static function provideNewFromTitleValue() {
return [
[ new TitleValue( NS_MAIN, 'Foo' ) ],
$this->assertEquals( $wiki, WikiMap::getWikiFromUrl( $url ) );
}
- public function provideGetWikiIdFromDomain() {
+ public function provideGetWikiIdFromDbDomain() {
return [
[ 'db-prefix_', 'db-prefix_' ],
[ wfWikiID(), wfWikiID() ],
}
/**
- * @dataProvider provideGetWikiIdFromDomain
+ * @dataProvider provideGetWikiIdFromDbDomain
* @covers WikiMap::getWikiIdFromDbDomain()
*/
- public function testGetWikiIdFromDomain( $domain, $wikiId ) {
+ public function testGetWikiIdFromDbDomain( $domain, $wikiId ) {
$this->assertEquals( $wikiId, WikiMap::getWikiIdFromDbDomain( $domain ) );
}
+++ /dev/null
-<?php
-
-/**
- * @covers WikiReference
- */
-class WikiReferenceTest extends PHPUnit\Framework\TestCase {
-
- use MediaWikiCoversValidator;
-
- public function provideGetDisplayName() {
- return [
- 'http' => [ 'foo.bar', 'http://foo.bar' ],
- 'https' => [ 'foo.bar', 'http://foo.bar' ],
-
- // apparently, this is the expected behavior
- 'invalid' => [ 'purple kittens', 'purple kittens' ],
- ];
- }
-
- /**
- * @dataProvider provideGetDisplayName
- */
- public function testGetDisplayName( $expected, $canonicalServer ) {
- $reference = new WikiReference( $canonicalServer, '/wiki/$1' );
- $this->assertEquals( $expected, $reference->getDisplayName() );
- }
-
- public function testGetCanonicalServer() {
- $reference = new WikiReference( 'https://acme.com', '/wiki/$1', '//acme.com' );
- $this->assertEquals( 'https://acme.com', $reference->getCanonicalServer() );
- }
-
- public function provideGetCanonicalUrl() {
- return [
- 'no fragment' => [
- 'https://acme.com/wiki/Foo',
- 'https://acme.com',
- '//acme.com',
- '/wiki/$1',
- 'Foo',
- null
- ],
- 'empty fragment' => [
- 'https://acme.com/wiki/Foo',
- 'https://acme.com',
- '//acme.com',
- '/wiki/$1',
- 'Foo',
- ''
- ],
- 'fragment' => [
- 'https://acme.com/wiki/Foo#Bar',
- 'https://acme.com',
- '//acme.com',
- '/wiki/$1',
- 'Foo',
- 'Bar'
- ],
- 'double fragment' => [
- 'https://acme.com/wiki/Foo#Bar%23Xus',
- 'https://acme.com',
- '//acme.com',
- '/wiki/$1',
- 'Foo',
- 'Bar#Xus'
- ],
- 'escaped fragment' => [
- 'https://acme.com/wiki/Foo%23Bar',
- 'https://acme.com',
- '//acme.com',
- '/wiki/$1',
- 'Foo#Bar',
- null
- ],
- 'empty path' => [
- 'https://acme.com/Foo',
- 'https://acme.com',
- '//acme.com',
- '/$1',
- 'Foo',
- null
- ],
- ];
- }
-
- /**
- * @dataProvider provideGetCanonicalUrl
- */
- public function testGetCanonicalUrl(
- $expected, $canonicalServer, $server, $path, $page, $fragmentId
- ) {
- $reference = new WikiReference( $canonicalServer, $path, $server );
- $this->assertEquals( $expected, $reference->getCanonicalUrl( $page, $fragmentId ) );
- }
-
- /**
- * @dataProvider provideGetCanonicalUrl
- * @note getUrl is an alias for getCanonicalUrl
- */
- public function testGetUrl( $expected, $canonicalServer, $server, $path, $page, $fragmentId ) {
- $reference = new WikiReference( $canonicalServer, $path, $server );
- $this->assertEquals( $expected, $reference->getUrl( $page, $fragmentId ) );
- }
-
- public function provideGetFullUrl() {
- return [
- 'no fragment' => [
- '//acme.com/wiki/Foo',
- 'https://acme.com',
- '//acme.com',
- '/wiki/$1',
- 'Foo',
- null
- ],
- 'empty fragment' => [
- '//acme.com/wiki/Foo',
- 'https://acme.com',
- '//acme.com',
- '/wiki/$1',
- 'Foo',
- ''
- ],
- 'fragment' => [
- '//acme.com/wiki/Foo#Bar',
- 'https://acme.com',
- '//acme.com',
- '/wiki/$1',
- 'Foo',
- 'Bar'
- ],
- 'double fragment' => [
- '//acme.com/wiki/Foo#Bar%23Xus',
- 'https://acme.com',
- '//acme.com',
- '/wiki/$1',
- 'Foo',
- 'Bar#Xus'
- ],
- 'escaped fragment' => [
- '//acme.com/wiki/Foo%23Bar',
- 'https://acme.com',
- '//acme.com',
- '/wiki/$1',
- 'Foo#Bar',
- null
- ],
- 'empty path' => [
- '//acme.com/Foo',
- 'https://acme.com',
- '//acme.com',
- '/$1',
- 'Foo',
- null
- ],
- ];
- }
-
- /**
- * @dataProvider provideGetFullUrl
- */
- public function testGetFullUrl( $expected, $canonicalServer, $server, $path, $page, $fragmentId ) {
- $reference = new WikiReference( $canonicalServer, $path, $server );
- $this->assertEquals( $expected, $reference->getFullUrl( $page, $fragmentId ) );
- }
-
-}
new TitleValue( 1, 'ApiQueryWatchlistRawIntegrationTestPage1' ),
] );
- ObjectCache::getMainWANInstance()->clearProcessCache();
+ MediaWikiServices::getInstance()->getMainWANObjectCache()->clearProcessCache();
$result = $this->doListWatchlistRawRequest( [
'wrowner' => $otherUser->getName(),
'wrtoken' => '1234567890',
+++ /dev/null
-<?php
-
-namespace MediaWiki\Logger\Monolog;
-
-/**
- * Flay per https://phabricator.wikimedia.org/T218688.
- *
- * @group Broken
- * @covers \MediaWiki\Logger\Monolog\CeeFormatter
- */
-class CeeFormatterTest extends \PHPUnit\Framework\TestCase {
- public function testV1() {
- $ls_formatter = new LogstashFormatter( 'app', 'system', null, 'ctx_', LogstashFormatter::V1 );
- $cee_formatter = new CeeFormatter( 'app', 'system', null, 'ctx_', LogstashFormatter::V1 );
- $record = [ 'extra' => [ 'url' => 1 ], 'context' => [ 'url' => 2 ] ];
- $this->assertSame(
- $cee_formatter->format( $record ),
- "@cee: " . $ls_formatter->format( $record ) );
- }
-}
$fi = SiteStats::images();
$ai = SiteStats::articles();
+ $this->assertEquals( 0, DeferredUpdates::pendingUpdatesCount() );
+
$dbw->begin( __METHOD__ ); // block opportunistic updates
- $update = SiteStatsUpdate::factory( [ 'pages' => 2, 'images' => 1, 'edits' => 2 ] );
- $this->assertEquals( 0, DeferredUpdates::pendingUpdatesCount() );
- $update->doUpdate();
+ DeferredUpdates::addUpdate(
+ SiteStatsUpdate::factory( [ 'pages' => 2, 'images' => 1, 'edits' => 2 ] )
+ );
$this->assertEquals( 1, DeferredUpdates::pendingUpdatesCount() );
// Still the same
+++ /dev/null
-<?php
-
-/**
- * @covers DifferenceEngineSlotDiffRenderer
- */
-class DifferenceEngineSlotDiffRendererTest extends \PHPUnit\Framework\TestCase {
-
- public function testGetDiff() {
- $differenceEngine = new CustomDifferenceEngine();
- $slotDiffRenderer = new DifferenceEngineSlotDiffRenderer( $differenceEngine );
- $oldContent = ContentHandler::makeContent( 'xxx', null, CONTENT_MODEL_TEXT );
- $newContent = ContentHandler::makeContent( 'yyy', null, CONTENT_MODEL_TEXT );
-
- $diff = $slotDiffRenderer->getDiff( $oldContent, $newContent );
- $this->assertEquals( 'xxx|yyy', $diff );
-
- $diff = $slotDiffRenderer->getDiff( null, $newContent );
- $this->assertEquals( '|yyy', $diff );
-
- $diff = $slotDiffRenderer->getDiff( $oldContent, null );
- $this->assertEquals( 'xxx|', $diff );
- }
-
- public function testAddModules() {
- $output = $this->getMockBuilder( OutputPage::class )
- ->disableOriginalConstructor()
- ->setMethods( [ 'addModules' ] )
- ->getMock();
- $output->expects( $this->once() )
- ->method( 'addModules' )
- ->with( 'foo' );
- $differenceEngine = new CustomDifferenceEngine();
- $slotDiffRenderer = new DifferenceEngineSlotDiffRenderer( $differenceEngine );
- $slotDiffRenderer->addModules( $output );
- }
-
- public function testGetExtraCacheKeys() {
- $differenceEngine = new CustomDifferenceEngine();
- $slotDiffRenderer = new DifferenceEngineSlotDiffRenderer( $differenceEngine );
- $extraCacheKeys = $slotDiffRenderer->getExtraCacheKeys();
- $this->assertSame( [ 'foo' ], $extraCacheKeys );
- }
-
-}
+++ /dev/null
-<?php
-
-use Wikimedia\Assert\ParameterTypeException;
-use Wikimedia\TestingAccessWrapper;
-
-/**
- * @covers SlotDiffRenderer
- */
-class SlotDiffRendererTest extends \PHPUnit\Framework\TestCase {
-
- /**
- * @dataProvider provideNormalizeContents
- */
- public function testNormalizeContents(
- $oldContent, $newContent, $allowedClasses,
- $expectedOldContent, $expectedNewContent, $expectedExceptionClass
- ) {
- $slotDiffRenderer = $this->getMockBuilder( SlotDiffRenderer::class )
- ->getMock();
- try {
- // __call needs help deciding which parameter to take by reference
- call_user_func_array( [ TestingAccessWrapper::newFromObject( $slotDiffRenderer ),
- 'normalizeContents' ], [ &$oldContent, &$newContent, $allowedClasses ] );
- $this->assertEquals( $expectedOldContent, $oldContent );
- $this->assertEquals( $expectedNewContent, $newContent );
- } catch ( Exception $e ) {
- if ( !$expectedExceptionClass ) {
- throw $e;
- }
- $this->assertInstanceOf( $expectedExceptionClass, $e );
- }
- }
-
- public function provideNormalizeContents() {
- return [
- 'both null' => [ null, null, null, null, null, InvalidArgumentException::class ],
- 'left null' => [
- null, new WikitextContent( 'abc' ), null,
- new WikitextContent( '' ), new WikitextContent( 'abc' ), null,
- ],
- 'right null' => [
- new WikitextContent( 'def' ), null, null,
- new WikitextContent( 'def' ), new WikitextContent( '' ), null,
- ],
- 'type filter' => [
- new WikitextContent( 'abc' ), new WikitextContent( 'def' ), WikitextContent::class,
- new WikitextContent( 'abc' ), new WikitextContent( 'def' ), null,
- ],
- 'type filter (subclass)' => [
- new WikitextContent( 'abc' ), new WikitextContent( 'def' ), TextContent::class,
- new WikitextContent( 'abc' ), new WikitextContent( 'def' ), null,
- ],
- 'type filter (null)' => [
- new WikitextContent( 'abc' ), null, TextContent::class,
- new WikitextContent( 'abc' ), new WikitextContent( '' ), null,
- ],
- 'type filter failure (left)' => [
- new TextContent( 'abc' ), new WikitextContent( 'def' ), WikitextContent::class,
- null, null, ParameterTypeException::class,
- ],
- 'type filter failure (right)' => [
- new WikitextContent( 'abc' ), new TextContent( 'def' ), WikitextContent::class,
- null, null, ParameterTypeException::class,
- ],
- 'type filter (array syntax)' => [
- new WikitextContent( 'abc' ), new JsonContent( 'def' ),
- [ JsonContent::class, WikitextContent::class ],
- new WikitextContent( 'abc' ), new JsonContent( 'def' ), null,
- ],
- 'type filter failure (array syntax)' => [
- new WikitextContent( 'abc' ), new CssContent( 'def' ),
- [ JsonContent::class, WikitextContent::class ],
- null, null, ParameterTypeException::class,
- ],
- ];
- }
-
-}
+++ /dev/null
-<?php
-
-class FileBackendDBRepoWrapperTest extends MediaWikiTestCase {
- protected $backendName = 'foo-backend';
- protected $repoName = 'pureTestRepo';
-
- /**
- * @dataProvider getBackendPathsProvider
- * @covers FileBackendDBRepoWrapper::getBackendPaths
- */
- public function testGetBackendPaths(
- $mocks,
- $latest,
- $dbReadsExpected,
- $dbReturnValue,
- $originalPath,
- $expectedBackendPath,
- $message ) {
- list( $dbMock, $backendMock, $wrapperMock ) = $mocks;
-
- $dbMock->expects( $dbReadsExpected )
- ->method( 'selectField' )
- ->will( $this->returnValue( $dbReturnValue ) );
-
- $newPaths = $wrapperMock->getBackendPaths( [ $originalPath ], $latest );
-
- $this->assertEquals(
- $expectedBackendPath,
- $newPaths[0],
- $message );
- }
-
- public function getBackendPathsProvider() {
- $prefix = 'mwstore://' . $this->backendName . '/' . $this->repoName;
- $mocksForCaching = $this->getMocks();
-
- return [
- [
- $mocksForCaching,
- false,
- $this->once(),
- '96246614d75ba1703bdfd5d7660bb57407aaf5d9',
- $prefix . '-public/f/o/foobar.jpg',
- $prefix . '-original/9/6/2/96246614d75ba1703bdfd5d7660bb57407aaf5d9',
- 'Public path translated correctly',
- ],
- [
- $mocksForCaching,
- false,
- $this->never(),
- '96246614d75ba1703bdfd5d7660bb57407aaf5d9',
- $prefix . '-public/f/o/foobar.jpg',
- $prefix . '-original/9/6/2/96246614d75ba1703bdfd5d7660bb57407aaf5d9',
- 'LRU cache leveraged',
- ],
- [
- $this->getMocks(),
- true,
- $this->once(),
- '96246614d75ba1703bdfd5d7660bb57407aaf5d9',
- $prefix . '-public/f/o/foobar.jpg',
- $prefix . '-original/9/6/2/96246614d75ba1703bdfd5d7660bb57407aaf5d9',
- 'Latest obtained',
- ],
- [
- $this->getMocks(),
- true,
- $this->never(),
- '96246614d75ba1703bdfd5d7660bb57407aaf5d9',
- $prefix . '-deleted/f/o/foobar.jpg',
- $prefix . '-original/f/o/o/foobar',
- 'Deleted path translated correctly',
- ],
- [
- $this->getMocks(),
- true,
- $this->once(),
- null,
- $prefix . '-public/b/a/baz.jpg',
- $prefix . '-public/b/a/baz.jpg',
- 'Path left untouched if no sha1 can be found',
- ],
- ];
- }
-
- /**
- * @covers FileBackendDBRepoWrapper::getFileContentsMulti
- */
- public function testGetFileContentsMulti() {
- list( $dbMock, $backendMock, $wrapperMock ) = $this->getMocks();
-
- $sha1Path = 'mwstore://' . $this->backendName . '/' . $this->repoName
- . '-original/9/6/2/96246614d75ba1703bdfd5d7660bb57407aaf5d9';
- $filenamePath = 'mwstore://' . $this->backendName . '/' . $this->repoName
- . '-public/f/o/foobar.jpg';
-
- $dbMock->expects( $this->once() )
- ->method( 'selectField' )
- ->will( $this->returnValue( '96246614d75ba1703bdfd5d7660bb57407aaf5d9' ) );
-
- $backendMock->expects( $this->once() )
- ->method( 'getFileContentsMulti' )
- ->will( $this->returnValue( [ $sha1Path => 'foo' ] ) );
-
- $result = $wrapperMock->getFileContentsMulti( [ 'srcs' => [ $filenamePath ] ] );
-
- $this->assertEquals(
- [ $filenamePath => 'foo' ],
- $result,
- 'File contents paths translated properly'
- );
- }
-
- protected function getMocks() {
- $dbMock = $this->getMockBuilder( Wikimedia\Rdbms\IDatabase::class )
- ->disableOriginalClone()
- ->disableOriginalConstructor()
- ->getMock();
-
- $backendMock = $this->getMockBuilder( FSFileBackend::class )
- ->setConstructorArgs( [ [
- 'name' => $this->backendName,
- 'wikiId' => wfWikiID()
- ] ] )
- ->getMock();
-
- $wrapperMock = $this->getMockBuilder( FileBackendDBRepoWrapper::class )
- ->setMethods( [ 'getDB' ] )
- ->setConstructorArgs( [ [
- 'backend' => $backendMock,
- 'repoName' => $this->repoName,
- 'dbHandleFactory' => null
- ] ] )
- ->getMock();
-
- $wrapperMock->expects( $this->any() )->method( 'getDB' )->will( $this->returnValue( $dbMock ) );
-
- return [ $dbMock, $backendMock, $wrapperMock ];
- }
-}
+++ /dev/null
-<?php
-
-/** @covers ForeignDBFile */
-class ForeignDBFileTest extends \PHPUnit\Framework\TestCase {
-
- use PHPUnit4And6Compat;
-
- public function testShouldConstructCorrectInstanceFromTitle() {
- $title = Title::makeTitle( NS_FILE, 'Awesome_file' );
- $repoMock = $this->createMock( LocalRepo::class );
-
- $file = ForeignDBFile::newFromTitle( $title, $repoMock );
-
- $this->assertInstanceOf( ForeignDBFile::class, $file );
- }
-}
+++ /dev/null
-<?php
-
-/**
- * @covers HTMLCheckMatrix
- */
-class HTMLCheckMatrixTest extends MediaWikiTestCase {
- private static $defaultOptions = [
- 'rows' => [ 'r1', 'r2' ],
- 'columns' => [ 'c1', 'c2' ],
- 'fieldname' => 'test',
- ];
-
- public function testPlainInstantiation() {
- try {
- new HTMLCheckMatrix( [] );
- } catch ( MWException $e ) {
- $this->assertInstanceOf( HTMLFormFieldRequiredOptionsException::class, $e );
- return;
- }
-
- $this->fail( 'Expected MWException indicating missing parameters but none was thrown.' );
- }
-
- public function testInstantiationWithMinimumRequiredParameters() {
- new HTMLCheckMatrix( self::$defaultOptions );
- $this->assertTrue( true ); // form instantiation must throw exception on failure
- }
-
- public function testValidateCallsUserDefinedValidationCallback() {
- $called = false;
- $field = new HTMLCheckMatrix( self::$defaultOptions + [
- 'validation-callback' => function () use ( &$called ) {
- $called = true;
-
- return false;
- },
- ] );
- $this->assertEquals( false, $this->validate( $field, [] ) );
- $this->assertTrue( $called );
- }
-
- public function testValidateRequiresArrayInput() {
- $field = new HTMLCheckMatrix( self::$defaultOptions );
- $this->assertEquals( false, $this->validate( $field, null ) );
- $this->assertEquals( false, $this->validate( $field, true ) );
- $this->assertEquals( false, $this->validate( $field, 'abc' ) );
- $this->assertEquals( false, $this->validate( $field, new stdClass ) );
- $this->assertEquals( true, $this->validate( $field, [] ) );
- }
-
- public function testValidateAllowsOnlyKnownTags() {
- $field = new HTMLCheckMatrix( self::$defaultOptions );
- $this->assertInstanceOf( Message::class, $this->validate( $field, [ 'foo' ] ) );
- }
-
- public function testValidateAcceptsPartialTagList() {
- $field = new HTMLCheckMatrix( self::$defaultOptions );
- $this->assertTrue( $this->validate( $field, [] ) );
- $this->assertTrue( $this->validate( $field, [ 'c1-r1' ] ) );
- $this->assertTrue( $this->validate( $field, [ 'c1-r1', 'c1-r2', 'c2-r1', 'c2-r2' ] ) );
- }
-
- /**
- * This form object actually has no visibility into what happens later on, but essentially
- * if the data submitted by the user passes validate the following is run:
- * foreach ( $field->filterDataForSubmit( $data ) as $k => $v ) {
- * $user->setOption( $k, $v );
- * }
- */
- public function testValuesForcedOnRemainOn() {
- $field = new HTMLCheckMatrix( self::$defaultOptions + [
- 'force-options-on' => [ 'c2-r1' ],
- ] );
- $expected = [
- 'c1-r1' => false,
- 'c1-r2' => false,
- 'c2-r1' => true,
- 'c2-r2' => false,
- ];
- $this->assertEquals( $expected, $field->filterDataForSubmit( [] ) );
- }
-
- public function testValuesForcedOffRemainOff() {
- $field = new HTMLCheckMatrix( self::$defaultOptions + [
- 'force-options-off' => [ 'c1-r2', 'c2-r2' ],
- ] );
- $expected = [
- 'c1-r1' => true,
- 'c1-r2' => false,
- 'c2-r1' => true,
- 'c2-r2' => false,
- ];
- // array_keys on the result simulates submitting all fields checked
- $this->assertEquals( $expected, $field->filterDataForSubmit( array_keys( $expected ) ) );
- }
-
- protected function validate( HTMLFormField $field, $submitted ) {
- return $field->validate(
- $submitted,
- [ self::$defaultOptions['fieldname'] => $submitted ]
- );
- }
-
-}
*/
class HttpTest extends MediaWikiTestCase {
- /**
- * Test Http::isValidURI()
- * T29854 : Http::isValidURI is too lax
- * @dataProvider provideURI
- * @covers Http::isValidURI
- */
- public function testIsValidUri( $expect, $URI, $message = '' ) {
- $this->assertEquals(
- $expect,
- (bool)Http::isValidURI( $URI ),
- $message
- );
- }
-
/**
* @covers Http::getProxy
*/
);
}
- /**
- * Feeds URI to test a long regular expression in Http::isValidURI
- */
- public static function provideURI() {
- /** Format: 'boolean expectation', 'URI to test', 'Optional message' */
- return [
- [ false, '¿non sens before!! http://a', 'Allow anything before URI' ],
-
- # (http|https) - only two schemes allowed
- [ true, 'http://www.example.org/' ],
- [ true, 'https://www.example.org/' ],
- [ true, 'http://www.example.org', 'URI without directory' ],
- [ true, 'http://a', 'Short name' ],
- [ true, 'http://étoile', 'Allow UTF-8 in hostname' ], # 'étoile' is french for 'star'
- [ false, '\\host\directory', 'CIFS share' ],
- [ false, 'gopher://host/dir', 'Reject gopher scheme' ],
- [ false, 'telnet://host', 'Reject telnet scheme' ],
-
- # :\/\/ - double slashes
- [ false, 'http//example.org', 'Reject missing colon in protocol' ],
- [ false, 'http:/example.org', 'Reject missing slash in protocol' ],
- [ false, 'http:example.org', 'Must have two slashes' ],
- # Following fail since hostname can be made of anything
- [ false, 'http:///example.org', 'Must have exactly two slashes, not three' ],
-
- # (\w+:{0,1}\w*@)? - optional user:pass
- [ true, 'http://user@host', 'Username provided' ],
- [ true, 'http://user:@host', 'Username provided, no password' ],
- [ true, 'http://user:pass@host', 'Username and password provided' ],
-
- # (\S+) - host part is made of anything not whitespaces
- // commented these out in order to remove @group Broken
- // @todo are these valid tests? if so, fix Http::isValidURI so it can handle them
- // [ false, 'http://!"èèè¿¿¿~~\'', 'hostname is made of any non whitespace' ],
- // [ false, 'http://exam:ple.org/', 'hostname can not use colons!' ],
-
- # (:[0-9]+)? - port number
- [ true, 'http://example.org:80/' ],
- [ true, 'https://example.org:80/' ],
- [ true, 'http://example.org:443/' ],
- [ true, 'https://example.org:443/' ],
-
- # Part after the hostname is / or / with something else
- [ true, 'http://example/#' ],
- [ true, 'http://example/!' ],
- [ true, 'http://example/:' ],
- [ true, 'http://example/.' ],
- [ true, 'http://example/?' ],
- [ true, 'http://example/+' ],
- [ true, 'http://example/=' ],
- [ true, 'http://example/&' ],
- [ true, 'http://example/%' ],
- [ true, 'http://example/@' ],
- [ true, 'http://example/-' ],
- [ true, 'http://example//' ],
- [ true, 'http://example/&' ],
-
- # Fragment
- [ true, 'http://exam#ple.org', ], # This one is valid, really!
- [ true, 'http://example.org:80#anchor' ],
- [ true, 'http://example.org/?id#anchor' ],
- [ true, 'http://example.org/?#anchor' ],
-
- [ false, 'http://a ¿non !!sens after', 'Allow anything after URI' ],
- ];
- }
-
}
+++ /dev/null
-<?php
-
-/**
- * @covers FormatJson
- */
-class FormatJsonTest extends MediaWikiTestCase {
-
- /**
- * Test data for testParseTryFixing.
- *
- * Some PHP interpreters use json-c rather than the JSON.org canonical
- * parser to avoid being encumbered by the "shall be used for Good, not
- * Evil" clause of the JSON.org parser's license. By default, json-c
- * parses in a non-strict mode which allows trailing commas for array and
- * object delarations among other things, so our JSON_ERROR_SYNTAX rescue
- * block is not always triggered. It however isn't lenient in exactly the
- * same ways as our TRY_FIXING mode, so the assertions in this test are
- * a bit more complicated than they ideally would be:
- *
- * Optional third argument: true if json-c parses the value without
- * intervention, false otherwise. Defaults to true.
- *
- * Optional fourth argument: expected cannonical JSON serialization of
- * json-c parsed result. Defaults to the second argument's value.
- */
- public static function provideParseTryFixing() {
- return [
- [ "[,]", '[]', false ],
- [ "[ , ]", '[]', false ],
- [ "[ , }", false ],
- [ '[1],', false, true, '[1]' ],
- [ "[1,]", '[1]' ],
- [ "[1\n,]", '[1]' ],
- [ "[1,\n]", '[1]' ],
- [ "[1,]\n", '[1]' ],
- [ "[1\n,\n]\n", '[1]' ],
- [ '["a,",]', '["a,"]' ],
- [ "[[1,]\n,[2,\n],[3\n,]]", '[[1],[2],[3]]' ],
- // I wish we could parse this, but would need quote parsing
- [ '[[1,],[2,],[3,]]', false, true, '[[1],[2],[3]]' ],
- [ '[1,,]', false, false, '[1]' ],
- ];
- }
-
- /**
- * @dataProvider provideParseTryFixing
- * @param string $value
- * @param string|bool $expected Expected result with strict parser
- * @param bool $jsoncParses Will json-c parse this value without TRY_FIXING?
- * @param string|bool $expectedJsonc Expected result with lenient parser
- * if different from the strict expectation
- */
- public function testParseTryFixing(
- $value, $expected,
- $jsoncParses = true, $expectedJsonc = null
- ) {
- // PHP5 results are always expected to have isGood() === false
- $expectedGoodStatus = false;
-
- // Check to see if json parser allows trailing commas
- if ( json_decode( '[1,]' ) !== null ) {
- // Use json-c specific expected result if provided
- $expected = ( $expectedJsonc === null ) ? $expected : $expectedJsonc;
- // If json-c parses the value natively, expect isGood() === true
- $expectedGoodStatus = $jsoncParses;
- }
-
- $st = FormatJson::parse( $value, FormatJson::TRY_FIXING );
- $this->assertInstanceOf( Status::class, $st );
- if ( $expected === false ) {
- $this->assertFalse( $st->isOK(), 'Expected isOK() == false' );
- } else {
- $this->assertSame( $expectedGoodStatus, $st->isGood(),
- 'Expected isGood() == ' . ( $expectedGoodStatus ? 'true' : 'false' )
- );
- $this->assertTrue( $st->isOK(), 'Expected isOK == true' );
- $val = FormatJson::encode( $st->getValue(), false, FormatJson::ALL_OK );
- $this->assertEquals( $expected, $val );
- }
- }
-
-}
* @covers WANObjectCache::getWarmupKeyMisses
* @covers WANObjectCache::prefixCacheKeys
* @covers WANObjectCache::getProcessCache
- * @covers WANObjectCache::getNonProcessCachedKeys
+ * @covers WANObjectCache::getNonProcessCachedMultiKeys
* @covers WANObjectCache::getRawKeysForWarmup
* @covers WANObjectCache::getInterimValue
* @covers WANObjectCache::setInterimValue
$cache->set( $key2, $value2, 10 );
$curTTLs = [];
- $this->assertEquals(
+ $this->assertSame(
[ $key1 => $value1, $key2 => $value2 ],
$cache->getMulti( [ $key1, $key2, $key3 ], $curTTLs ),
'Result array populated'
$mockWallClock += 1;
$curTTLs = [];
- $this->assertEquals(
+ $this->assertSame(
[ $key1 => $value1, $key2 => $value2 ],
$cache->getMulti( [ $key1, $key2, $key3 ], $curTTLs, [ $cKey1, $cKey2 ] ),
"Result array populated even with new check keys"
'key2' => $check2,
'key3' => $check3,
] );
- $this->assertEquals(
+ $this->assertSame(
[ 'key1' => $value1, 'key2' => $value2 ],
$result,
'Initial values'
'key2' => $check2,
'key3' => $check3,
] );
- $this->assertEquals(
+ $this->assertSame(
[ 'key1' => $value1, 'key2' => $value2 ],
$result,
'key1 expired by check1, but value still provided'
$this->assertEquals( $class, $wanCache->determineKeyClassForStats( $key ) );
}
+
+ /**
+ * @covers WANObjectCache::makeMultiKeys
+ */
+ public function testMakeMultiKeys() {
+ $cache = $this->cache;
+
+ $ids = [ 1, 2, 3, 4, 4, 5, 6, 6, 7, 7 ];
+ $keyCallback = function ( $id, WANObjectCache $cache ) {
+ return $cache->makeKey( 'key', $id );
+ };
+ $keyedIds = $cache->makeMultiKeys( $ids, $keyCallback );
+
+ $expected = [
+ "local:key:1" => 1,
+ "local:key:2" => 2,
+ "local:key:3" => 3,
+ "local:key:4" => 4,
+ "local:key:5" => 5,
+ "local:key:6" => 6,
+ "local:key:7" => 7
+ ];
+ $this->assertSame( $expected, iterator_to_array( $keyedIds ) );
+
+ $ids = [ '1', '2', '3', '4', '4', '5', '6', '6', '7', '7' ];
+ $keyCallback = function ( $id, WANObjectCache $cache ) {
+ return $cache->makeGlobalKey( 'key', $id, 'a', $id, 'b' );
+ };
+ $keyedIds = $cache->makeMultiKeys( $ids, $keyCallback );
+
+ $expected = [
+ "global:key:1:a:1:b" => '1',
+ "global:key:2:a:2:b" => '2',
+ "global:key:3:a:3:b" => '3',
+ "global:key:4:a:4:b" => '4',
+ "global:key:5:a:5:b" => '5',
+ "global:key:6:a:6:b" => '6',
+ "global:key:7:a:7:b" => '7'
+ ];
+ $this->assertSame( $expected, iterator_to_array( $keyedIds ) );
+ }
+
+ /**
+ * @covers WANObjectCache::makeMultiKeys
+ */
+ public function testMakeMultiKeysIntString() {
+ $cache = $this->cache;
+ $ids = [ 1, 2, 3, 4, '4', 5, 6, 6, 7, '7' ];
+ $keyCallback = function ( $id, WANObjectCache $cache ) {
+ return $cache->makeGlobalKey( 'key', $id, 'a', $id, 'b' );
+ };
+
+ $keyedIds = $cache->makeMultiKeys( $ids, $keyCallback );
+
+ $expected = [
+ "global:key:1:a:1:b" => 1,
+ "global:key:2:a:2:b" => 2,
+ "global:key:3:a:3:b" => 3,
+ "global:key:4:a:4:b" => 4,
+ "global:key:5:a:5:b" => 5,
+ "global:key:6:a:6:b" => 6,
+ "global:key:7:a:7:b" => 7
+ ];
+ $this->assertSame( $expected, iterator_to_array( $keyedIds ) );
+ }
+
+ /**
+ * @covers WANObjectCache::makeMultiKeys
+ * @expectedException UnexpectedValueException
+ */
+ public function testMakeMultiKeysCollision() {
+ $ids = [ 1, 2, 3, 4, '4', 5, 6, 6, 7 ];
+
+ $this->cache->makeMultiKeys(
+ $ids,
+ function ( $id ) {
+ return "keymod:" . $id % 3;
+ }
+ );
+ }
+
+ /**
+ * @covers WANObjectCache::multiRemap
+ */
+ public function testMultiRemap() {
+ $a = [ 'a', 'b', 'c' ];
+ $res = [ 'keyA' => 1, 'keyB' => 2, 'keyC' => 3 ];
+
+ $this->assertEquals(
+ [ 'a' => 1, 'b' => 2, 'c' => 3 ],
+ $this->cache->multiRemap( $a, $res )
+ );
+
+ $a = [ 'a', 'b', 'c', 'c', 'd' ];
+ $res = [ 'keyA' => 1, 'keyB' => 2, 'keyC' => 3, 'keyD' => 4 ];
+
+ $this->assertEquals(
+ [ 'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4 ],
+ $this->cache->multiRemap( $a, $res )
+ );
+ }
+
+ /**
+ * @covers WANObjectCache::hash256
+ */
+ public function testHash256() {
+ $bag = new HashBagOStuff();
+ $cache = new WANObjectCache( [ 'cache' => $bag, 'epoch' => 5 ] );
+ $this->assertEquals(
+ 'f402bce76bfa1136adc705d8d5719911ce1fe61f0ad82ddf79a15f3c4de6ec4c',
+ $cache->hash256( 'x' )
+ );
+
+ $cache = new WANObjectCache( [ 'cache' => $bag, 'epoch' => 50 ] );
+ $this->assertEquals(
+ 'f79a126722f0a682c4c500509f1b61e836e56c4803f92edc89fc281da5caa54e',
+ $cache->hash256( 'x' )
+ );
+
+ $cache = new WANObjectCache( [ 'cache' => $bag, 'secret' => 'garden' ] );
+ $this->assertEquals(
+ '48cd57016ffe29981a1114c45e5daef327d30fc6206cb73edc3cb94b4d8fe093',
+ $cache->hash256( 'x' )
+ );
+
+ $cache = new WANObjectCache( [ 'cache' => $bag, 'secret' => 'garden', 'epoch' => 3 ] );
+ $this->assertEquals(
+ '48cd57016ffe29981a1114c45e5daef327d30fc6206cb73edc3cb94b4d8fe093',
+ $cache->hash256( 'x' )
+ );
+ }
}
class NearExpiringWANObjectCache extends WANObjectCache {
$this->assertSame( $oldDomain, $this->db->getDomainId() );
}
+ /**
+ * @covers Wikimedia\Rdbms\Database::getLBInfo
+ * @covers Wikimedia\Rdbms\Database::setLBInfo
+ */
+ public function testGetSetLBInfo() {
+ $db = $this->getMockDB();
+
+ $this->assertEquals( [], $db->getLBInfo() );
+ $this->assertNull( $db->getLBInfo( 'pringles' ) );
+
+ $db->setLBInfo( 'soda', 'water' );
+ $this->assertEquals( [ 'soda' => 'water' ], $db->getLBInfo() );
+ $this->assertNull( $db->getLBInfo( 'pringles' ) );
+ $this->assertEquals( 'water', $db->getLBInfo( 'soda' ) );
+
+ $db->setLBInfo( 'basketball', 'Lebron' );
+ $this->assertEquals( [ 'soda' => 'water', 'basketball' => 'Lebron' ], $db->getLBInfo() );
+ $this->assertEquals( 'water', $db->getLBInfo( 'soda' ) );
+ $this->assertEquals( 'Lebron', $db->getLBInfo( 'basketball' ) );
+
+ $db->setLBInfo( 'soda', null );
+ $this->assertEquals( [ 'basketball' => 'Lebron' ], $db->getLBInfo() );
+
+ $db->setLBInfo( [ 'King' => 'James' ] );
+ $this->assertNull( $db->getLBInfo( 'basketball' ) );
+ $this->assertEquals( [ 'King' => 'James' ], $db->getLBInfo() );
+ }
}
}
public function testGetLinkClasses() {
- $wanCache = ObjectCache::getMainWANInstance();
- $titleFormatter = MediaWikiServices::getInstance()->getTitleFormatter();
- $nsInfo = MediaWikiServices::getInstance()->getNamespaceInfo();
+ $services = MediaWikiServices::getInstance();
+ $wanCache = $services->getMainWANObjectCache();
+ $titleFormatter = $services->getTitleFormatter();
+ $nsInfo = $services->getNamespaceInfo();
$linkCache = new LinkCache( $titleFormatter, $wanCache, $nsInfo );
$foobarTitle = new TitleValue( NS_MAIN, 'FooBar' );
$redirectTitle = new TitleValue( NS_MAIN, 'Redirect' );
+++ /dev/null
-<?php
-/**
- * @todo Could use a test of extended XMP segments. Hard to find programs that
- * create example files, and creating my own in vim propbably wouldn't
- * serve as a very good "test". (Adobe photoshop probably creates such files
- * but it costs money). The implementation of it currently in MediaWiki is based
- * solely on reading the standard, without any real world test files.
- *
- * @group Media
- * @covers JpegMetadataExtractor
- */
-class JpegMetadataExtractorTest extends MediaWikiTestCase {
-
- protected $filePath;
-
- protected function setUp() {
- parent::setUp();
-
- $this->filePath = __DIR__ . '/../../data/media/';
- }
-
- /**
- * We also use this test to test padding bytes don't
- * screw stuff up
- *
- * @param string $file Filename
- *
- * @dataProvider provideUtf8Comment
- */
- public function testUtf8Comment( $file ) {
- $res = JpegMetadataExtractor::segmentSplitter( $this->filePath . $file );
- $this->assertEquals( [ 'UTF-8 JPEG Comment — ¼' ], $res['COM'] );
- }
-
- public static function provideUtf8Comment() {
- return [
- [ 'jpeg-comment-utf.jpg' ],
- [ 'jpeg-padding-even.jpg' ],
- [ 'jpeg-padding-odd.jpg' ],
- ];
- }
-
- /** The file is iso-8859-1, but it should get auto converted */
- public function testIso88591Comment() {
- $res = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'jpeg-comment-iso8859-1.jpg' );
- $this->assertEquals( [ 'ISO-8859-1 JPEG Comment - ¼' ], $res['COM'] );
- }
-
- /** Comment values that are non-textual (random binary junk) should not be shown.
- * The example test file has a comment with a 0x5 byte in it which is a control character
- * and considered binary junk for our purposes.
- */
- public function testBinaryCommentStripped() {
- $res = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'jpeg-comment-binary.jpg' );
- $this->assertEmpty( $res['COM'] );
- }
-
- /* Very rarely a file can have multiple comments.
- * Order of comments is based on order inside the file.
- */
- public function testMultipleComment() {
- $res = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'jpeg-comment-multiple.jpg' );
- $this->assertEquals( [ 'foo', 'bar' ], $res['COM'] );
- }
-
- public function testXMPExtraction() {
- $res = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'jpeg-xmp-psir.jpg' );
- $expected = file_get_contents( $this->filePath . 'jpeg-xmp-psir.xmp' );
- $this->assertEquals( $expected, $res['XMP'] );
- }
-
- public function testPSIRExtraction() {
- $res = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'jpeg-xmp-psir.jpg' );
- $expected = '50686f746f73686f7020332e30003842494d04040000000'
- . '000181c02190004746573741c02190003666f6f1c020000020004';
- $this->assertEquals( $expected, bin2hex( $res['PSIR'][0] ) );
- }
-
- public function testXMPExtractionAltAppId() {
- $res = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'jpeg-xmp-alt.jpg' );
- $expected = file_get_contents( $this->filePath . 'jpeg-xmp-psir.xmp' );
- $this->assertEquals( $expected, $res['XMP'] );
- }
-
- public function testIPTCHashComparisionNoHash() {
- $segments = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'jpeg-xmp-psir.jpg' );
- $res = JpegMetadataExtractor::doPSIR( $segments['PSIR'][0] );
-
- $this->assertEquals( 'iptc-no-hash', $res );
- }
-
- public function testIPTCHashComparisionBadHash() {
- $segments = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'jpeg-iptc-bad-hash.jpg' );
- $res = JpegMetadataExtractor::doPSIR( $segments['PSIR'][0] );
-
- $this->assertEquals( 'iptc-bad-hash', $res );
- }
-
- public function testIPTCHashComparisionGoodHash() {
- $segments = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'jpeg-iptc-good-hash.jpg' );
- $res = JpegMetadataExtractor::doPSIR( $segments['PSIR'][0] );
-
- $this->assertEquals( 'iptc-good-hash', $res );
- }
-
- public function testExifByteOrder() {
- $res = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'exif-user-comment.jpg' );
- $expected = 'BE';
- $this->assertEquals( $expected, $res['byteOrder'] );
- }
-
- public function testInfiniteRead() {
- // test file truncated right after a segment, which previously
- // caused an infinite loop looking for the next segment byte.
- // Should get past infinite loop and throw in wfUnpack()
- $this->setExpectedException( 'MWException' );
- $res = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'jpeg-segment-loop1.jpg' );
- }
-
- public function testInfiniteRead2() {
- // test file truncated after a segment's marker and size, which
- // would cause a seek past end of file. Seek past end of file
- // doesn't actually fail, but prevents further reading and was
- // devolving into the previous case (testInfiniteRead).
- $this->setExpectedException( 'MWException' );
- $res = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'jpeg-segment-loop2.jpg' );
- }
-}
+++ /dev/null
-<?php
-
-class ArticleTest extends MediaWikiTestCase {
-
- /**
- * @var Title
- */
- private $title;
- /**
- * @var Article
- */
- private $article;
-
- /** creates a title object and its article object */
- protected function setUp() {
- parent::setUp();
- $this->title = Title::makeTitle( NS_MAIN, 'SomePage' );
- $this->article = new Article( $this->title );
- }
-
- /** cleanup title object and its article object */
- protected function tearDown() {
- parent::tearDown();
- $this->title = null;
- $this->article = null;
- }
-
- /**
- * @covers Article::__get
- */
- public function testImplementsGetMagic() {
- $this->assertEquals( false, $this->article->mLatest, "Article __get magic" );
- }
-
- /**
- * @depends testImplementsGetMagic
- * @covers Article::__set
- */
- public function testImplementsSetMagic() {
- $this->article->mLatest = 2;
- $this->assertEquals( 2, $this->article->mLatest, "Article __set magic" );
- }
-
- /**
- * @covers Article::__get
- * @covers Article::__set
- */
- public function testGetOrSetOnNewProperty() {
- $this->article->ext_someNewProperty = 12;
- $this->assertEquals( 12, $this->article->ext_someNewProperty,
- "Article get/set magic on new field" );
-
- $this->article->ext_someNewProperty = -8;
- $this->assertEquals( -8, $this->article->ext_someNewProperty,
- "Article get/set magic on update to new field" );
- }
-}
);
}
+ /**
+ * Test reading files from elsewhere than localBasePath using ResourceLoaderFilePath.
+ *
+ * This mimics modules modified by skins using 'ResourceModuleSkinStyles' and 'OOUIThemePaths'
+ * skin attributes.
+ *
+ * @covers ResourceLoaderFilePath::getLocalBasePath
+ * @covers ResourceLoaderFilePath::getRemoteBasePath
+ */
+ public function testResourceLoaderFilePath() {
+ $basePath = __DIR__ . '/../../data/blahblah';
+ $filePath = __DIR__ . '/../../data/rlfilepath';
+ $testModule = new ResourceLoaderFileModule( [
+ 'localBasePath' => $basePath,
+ 'remoteBasePath' => 'blahblah',
+ 'styles' => new ResourceLoaderFilePath( 'style.css', $filePath, 'rlfilepath' ),
+ 'skinStyles' => [
+ 'vector' => new ResourceLoaderFilePath( 'skinStyle.css', $filePath, 'rlfilepath' ),
+ ],
+ 'scripts' => new ResourceLoaderFilePath( 'script.js', $filePath, 'rlfilepath' ),
+ 'templates' => new ResourceLoaderFilePath( 'template.html', $filePath, 'rlfilepath' ),
+ ] );
+ $expectedModule = new ResourceLoaderFileModule( [
+ 'localBasePath' => $filePath,
+ 'remoteBasePath' => 'rlfilepath',
+ 'styles' => 'style.css',
+ 'skinStyles' => [
+ 'vector' => 'skinStyle.css',
+ ],
+ 'scripts' => 'script.js',
+ 'templates' => 'template.html',
+ ] );
+
+ $context = $this->getResourceLoaderContext();
+ $this->assertEquals(
+ $expectedModule->getModuleContent( $context ),
+ $testModule->getModuleContent( $context ),
+ "Using ResourceLoaderFilePath works correctly"
+ );
+ }
+
public static function providerGetTemplates() {
$modules = self::getModules();
--- /dev/null
+<?php
+
+class ResourceLoaderFilePathTest extends PHPUnit\Framework\TestCase {
+ /**
+ * @covers ResourceLoaderFilePath::__construct
+ */
+ public function testConstructor() {
+ $resourceLoaderFilePath = new ResourceLoaderFilePath(
+ 'dummy/path', 'localBasePath', 'remoteBasePath'
+ );
+
+ $this->assertInstanceOf( ResourceLoaderFilePath::class, $resourceLoaderFilePath );
+ }
+
+ /**
+ * @covers ResourceLoaderFilePath::getLocalPath
+ */
+ public function testGetLocalPath() {
+ $resourceLoaderFilePath = new ResourceLoaderFilePath(
+ 'dummy/path', 'localBasePath', 'remoteBasePath'
+ );
+
+ $this->assertSame(
+ 'localBasePath/dummy/path', $resourceLoaderFilePath->getLocalPath()
+ );
+ }
+
+ /**
+ * @covers ResourceLoaderFilePath::getRemotePath
+ */
+ public function testGetRemotePath() {
+ $resourceLoaderFilePath = new ResourceLoaderFilePath(
+ 'dummy/path', 'localBasePath', 'remoteBasePath'
+ );
+
+ $this->assertSame(
+ 'remoteBasePath/dummy/path', $resourceLoaderFilePath->getRemotePath()
+ );
+ }
+
+ /**
+ * @covers ResourceLoaderFilePath::getPath
+ */
+ public function testGetPath() {
+ $resourceLoaderFilePath = new ResourceLoaderFilePath(
+ 'dummy/path', 'localBasePath', 'remoteBasePath'
+ );
+
+ $this->assertSame(
+ 'dummy/path', $resourceLoaderFilePath->getPath()
+ );
+ }
+}
];
}
+ /**
+ * Test reading files from elsewhere than localBasePath using ResourceLoaderFilePath.
+ *
+ * This mimics modules modified by skins using 'ResourceModuleSkinStyles' and 'OOUIThemePaths'
+ * skin attributes.
+ *
+ * @covers ResourceLoaderFilePath::getLocalBasePath
+ * @covers ResourceLoaderFilePath::getRemoteBasePath
+ */
+ public function testResourceLoaderFilePath() {
+ $basePath = __DIR__ . '/../../data/blahblah';
+ $filePath = __DIR__ . '/../../data/rlfilepath';
+ $testModule = new ResourceLoaderImageModule( [
+ 'localBasePath' => $basePath,
+ 'remoteBasePath' => 'blahblah',
+ 'prefix' => 'foo',
+ 'images' => [
+ 'eye' => new ResourceLoaderFilePath( 'eye.svg', $filePath, 'rlfilepath' ),
+ 'flag' => [
+ 'file' => [
+ 'ltr' => new ResourceLoaderFilePath( 'flag-ltr.svg', $filePath, 'rlfilepath' ),
+ 'rtl' => new ResourceLoaderFilePath( 'flag-rtl.svg', $filePath, 'rlfilepath' ),
+ ],
+ ],
+ ],
+ ] );
+ $expectedModule = new ResourceLoaderImageModule( [
+ 'localBasePath' => $filePath,
+ 'remoteBasePath' => 'rlfilepath',
+ 'prefix' => 'foo',
+ 'images' => [
+ 'eye' => 'eye.svg',
+ 'flag' => [
+ 'file' => [
+ 'ltr' => 'flag-ltr.svg',
+ 'rtl' => 'flag-rtl.svg',
+ ],
+ ],
+ ],
+ ] );
+
+ $context = $this->getResourceLoaderContext();
+ $this->assertEquals(
+ $expectedModule->getModuleContent( $context ),
+ $testModule->getModuleContent( $context ),
+ "Using ResourceLoaderFilePath works correctly"
+ );
+ }
+
/**
* @dataProvider providerGetModules
* @covers ResourceLoaderImageModule::getStyles
*/
class SessionTest extends MediaWikiTestCase {
- public function testConstructor() {
- $backend = TestUtils::getDummySessionBackend();
- TestingAccessWrapper::newFromObject( $backend )->requests = [ -1 => 'dummy' ];
- TestingAccessWrapper::newFromObject( $backend )->id = new SessionId( 'abc' );
-
- $session = new Session( $backend, 42, new \TestLogger );
- $priv = TestingAccessWrapper::newFromObject( $session );
- $this->assertSame( $backend, $priv->backend );
- $this->assertSame( 42, $priv->index );
-
- $request = new \FauxRequest();
- $priv2 = TestingAccessWrapper::newFromObject( $session->sessionWithRequest( $request ) );
- $this->assertSame( $backend, $priv2->backend );
- $this->assertNotSame( $priv->index, $priv2->index );
- $this->assertSame( $request, $priv2->getRequest() );
- }
-
- /**
- * @dataProvider provideMethods
- * @param string $m Method to test
- * @param array $args Arguments to pass to the method
- * @param bool $index Whether the backend method gets passed the index
- * @param bool $ret Whether the method returns a value
- */
- public function testMethods( $m, $args, $index, $ret ) {
- $mock = $this->getMockBuilder( DummySessionBackend::class )
- ->setMethods( [ $m, 'deregisterSession' ] )
- ->getMock();
- $mock->expects( $this->once() )->method( 'deregisterSession' )
- ->with( $this->identicalTo( 42 ) );
-
- $tmp = $mock->expects( $this->once() )->method( $m );
- $expectArgs = [];
- if ( $index ) {
- $expectArgs[] = $this->identicalTo( 42 );
- }
- foreach ( $args as $arg ) {
- $expectArgs[] = $this->identicalTo( $arg );
- }
- $tmp = call_user_func_array( [ $tmp, 'with' ], $expectArgs );
-
- $retval = new \stdClass;
- $tmp->will( $this->returnValue( $retval ) );
-
- $session = TestUtils::getDummySession( $mock, 42 );
-
- if ( $ret ) {
- $this->assertSame( $retval, call_user_func_array( [ $session, $m ], $args ) );
- } else {
- $this->assertNull( call_user_func_array( [ $session, $m ], $args ) );
- }
-
- // Trigger Session destructor
- $session = null;
- }
-
- public static function provideMethods() {
- return [
- [ 'getId', [], false, true ],
- [ 'getSessionId', [], false, true ],
- [ 'resetId', [], false, true ],
- [ 'getProvider', [], false, true ],
- [ 'isPersistent', [], false, true ],
- [ 'persist', [], false, false ],
- [ 'unpersist', [], false, false ],
- [ 'shouldRememberUser', [], false, true ],
- [ 'setRememberUser', [ true ], false, false ],
- [ 'getRequest', [], true, true ],
- [ 'getUser', [], false, true ],
- [ 'getAllowedUserRights', [], false, true ],
- [ 'canSetUser', [], false, true ],
- [ 'setUser', [ new \stdClass ], false, false ],
- [ 'suggestLoginUsername', [], true, true ],
- [ 'shouldForceHTTPS', [], false, true ],
- [ 'setForceHTTPS', [ true ], false, false ],
- [ 'getLoggedOutTimestamp', [], false, true ],
- [ 'setLoggedOutTimestamp', [ 123 ], false, false ],
- [ 'getProviderMetadata', [], false, true ],
- [ 'save', [], false, false ],
- [ 'delaySave', [], false, true ],
- [ 'renew', [], false, false ],
- ];
- }
-
- public function testDataAccess() {
- $session = TestUtils::getDummySession();
- $backend = TestingAccessWrapper::newFromObject( $session )->backend;
-
- $this->assertEquals( 1, $session->get( 'foo' ) );
- $this->assertEquals( 'zero', $session->get( 0 ) );
- $this->assertFalse( $backend->dirty );
-
- $this->assertEquals( null, $session->get( 'null' ) );
- $this->assertEquals( 'default', $session->get( 'null', 'default' ) );
- $this->assertFalse( $backend->dirty );
-
- $session->set( 'foo', 55 );
- $this->assertEquals( 55, $backend->data['foo'] );
- $this->assertTrue( $backend->dirty );
- $backend->dirty = false;
-
- $session->set( 1, 'one' );
- $this->assertEquals( 'one', $backend->data[1] );
- $this->assertTrue( $backend->dirty );
- $backend->dirty = false;
-
- $session->set( 1, 'one' );
- $this->assertFalse( $backend->dirty );
-
- $this->assertTrue( $session->exists( 'foo' ) );
- $this->assertTrue( $session->exists( 1 ) );
- $this->assertFalse( $session->exists( 'null' ) );
- $this->assertFalse( $session->exists( 100 ) );
- $this->assertFalse( $backend->dirty );
-
- $session->remove( 'foo' );
- $this->assertArrayNotHasKey( 'foo', $backend->data );
- $this->assertTrue( $backend->dirty );
- $backend->dirty = false;
- $session->remove( 1 );
- $this->assertArrayNotHasKey( 1, $backend->data );
- $this->assertTrue( $backend->dirty );
- $backend->dirty = false;
-
- $session->remove( 101 );
- $this->assertFalse( $backend->dirty );
-
- $backend->data = [ 'a', 'b', '?' => 'c' ];
- $this->assertSame( 3, $session->count() );
- $this->assertSame( 3, count( $session ) );
- $this->assertFalse( $backend->dirty );
-
- $data = [];
- foreach ( $session as $key => $value ) {
- $data[$key] = $value;
- }
- $this->assertEquals( $backend->data, $data );
- $this->assertFalse( $backend->dirty );
-
- $this->assertEquals( $backend->data, iterator_to_array( $session ) );
- $this->assertFalse( $backend->dirty );
- }
-
- public function testArrayAccess() {
- $logger = new \TestLogger;
- $session = TestUtils::getDummySession( null, -1, $logger );
- $backend = TestingAccessWrapper::newFromObject( $session )->backend;
-
- $this->assertEquals( 1, $session['foo'] );
- $this->assertEquals( 'zero', $session[0] );
- $this->assertFalse( $backend->dirty );
-
- $logger->setCollect( true );
- $this->assertEquals( null, $session['null'] );
- $logger->setCollect( false );
- $this->assertFalse( $backend->dirty );
- $this->assertSame( [
- [ LogLevel::DEBUG, 'Undefined index (auto-adds to session with a null value): null' ]
- ], $logger->getBuffer() );
- $logger->clearBuffer();
-
- $session['foo'] = 55;
- $this->assertEquals( 55, $backend->data['foo'] );
- $this->assertTrue( $backend->dirty );
- $backend->dirty = false;
-
- $session[1] = 'one';
- $this->assertEquals( 'one', $backend->data[1] );
- $this->assertTrue( $backend->dirty );
- $backend->dirty = false;
-
- $session[1] = 'one';
- $this->assertFalse( $backend->dirty );
-
- $session['bar'] = [ 'baz' => [] ];
- $session['bar']['baz']['quux'] = 2;
- $this->assertEquals( [ 'baz' => [ 'quux' => 2 ] ], $backend->data['bar'] );
-
- $logger->setCollect( true );
- $session['bar2']['baz']['quux'] = 3;
- $logger->setCollect( false );
- $this->assertEquals( [ 'baz' => [ 'quux' => 3 ] ], $backend->data['bar2'] );
- $this->assertSame( [
- [ LogLevel::DEBUG, 'Undefined index (auto-adds to session with a null value): bar2' ]
- ], $logger->getBuffer() );
- $logger->clearBuffer();
-
- $backend->dirty = false;
- $this->assertTrue( isset( $session['foo'] ) );
- $this->assertTrue( isset( $session[1] ) );
- $this->assertFalse( isset( $session['null'] ) );
- $this->assertFalse( isset( $session['missing'] ) );
- $this->assertFalse( isset( $session[100] ) );
- $this->assertFalse( $backend->dirty );
-
- unset( $session['foo'] );
- $this->assertArrayNotHasKey( 'foo', $backend->data );
- $this->assertTrue( $backend->dirty );
- $backend->dirty = false;
- unset( $session[1] );
- $this->assertArrayNotHasKey( 1, $backend->data );
- $this->assertTrue( $backend->dirty );
- $backend->dirty = false;
-
- unset( $session[101] );
- $this->assertFalse( $backend->dirty );
- }
-
public function testClear() {
$session = TestUtils::getDummySession();
$priv = TestingAccessWrapper::newFromObject( $session );
$this->assertTrue( $backend->dirty );
}
- public function testTokens() {
- $session = TestUtils::getDummySession();
- $priv = TestingAccessWrapper::newFromObject( $session );
- $backend = $priv->backend;
-
- $token = TestingAccessWrapper::newFromObject( $session->getToken() );
- $this->assertArrayHasKey( 'wsTokenSecrets', $backend->data );
- $this->assertArrayHasKey( 'default', $backend->data['wsTokenSecrets'] );
- $secret = $backend->data['wsTokenSecrets']['default'];
- $this->assertSame( $secret, $token->secret );
- $this->assertSame( '', $token->salt );
- $this->assertTrue( $token->wasNew() );
-
- $token = TestingAccessWrapper::newFromObject( $session->getToken( 'foo' ) );
- $this->assertSame( $secret, $token->secret );
- $this->assertSame( 'foo', $token->salt );
- $this->assertFalse( $token->wasNew() );
-
- $backend->data['wsTokenSecrets']['secret'] = 'sekret';
- $token = TestingAccessWrapper::newFromObject(
- $session->getToken( [ 'bar', 'baz' ], 'secret' )
- );
- $this->assertSame( 'sekret', $token->secret );
- $this->assertSame( 'bar|baz', $token->salt );
- $this->assertFalse( $token->wasNew() );
-
- $session->resetToken( 'secret' );
- $this->assertArrayHasKey( 'wsTokenSecrets', $backend->data );
- $this->assertArrayHasKey( 'default', $backend->data['wsTokenSecrets'] );
- $this->assertArrayNotHasKey( 'secret', $backend->data['wsTokenSecrets'] );
-
- $session->resetAllTokens();
- $this->assertArrayNotHasKey( 'wsTokenSecrets', $backend->data );
- }
-
- /**
- * @dataProvider provideSecretsRoundTripping
- * @param mixed $data
- */
- public function testSecretsRoundTripping( $data ) {
- $session = TestUtils::getDummySession();
-
- // Simple round-trip
- $session->setSecret( 'secret', $data );
- $this->assertNotEquals( $data, $session->get( 'secret' ) );
- $this->assertEquals( $data, $session->getSecret( 'secret', 'defaulted' ) );
- }
-
- public static function provideSecretsRoundTripping() {
- return [
- [ 'Foobar' ],
- [ 42 ],
- [ [ 'foo', 'bar' => 'baz', 'subarray' => [ 1, 2, 3 ] ] ],
- [ (object)[ 'foo', 'bar' => 'baz', 'subarray' => [ 1, 2, 3 ] ] ],
- [ true ],
- [ false ],
- [ null ],
- ];
- }
-
public function testSecrets() {
$logger = new \TestLogger;
$session = TestUtils::getDummySession( null, -1, $logger );
\Wikimedia\restoreWarnings();
}
+ /**
+ * @dataProvider provideSecretsRoundTripping
+ * @param mixed $data
+ */
+ public function testSecretsRoundTripping( $data ) {
+ $session = TestUtils::getDummySession();
+
+ // Simple round-trip
+ $session->setSecret( 'secret', $data );
+ $this->assertNotEquals( $data, $session->get( 'secret' ) );
+ $this->assertEquals( $data, $session->getSecret( 'secret', 'defaulted' ) );
+ }
+
+ public static function provideSecretsRoundTripping() {
+ return [
+ [ 'Foobar' ],
+ [ 42 ],
+ [ [ 'foo', 'bar' => 'baz', 'subarray' => [ 1, 2, 3 ] ] ],
+ [ (object)[ 'foo', 'bar' => 'baz', 'subarray' => [ 1, 2, 3 ] ] ],
+ [ true ],
+ [ false ],
+ [ null ],
+ ];
+ }
+
}
+++ /dev/null
-<?php
-
-namespace MediaWiki\Session;
-
-use MediaWikiTestCase;
-use Wikimedia\TestingAccessWrapper;
-
-/**
- * @group Session
- * @covers MediaWiki\Session\Token
- */
-class TokenTest extends MediaWikiTestCase {
-
- public function testBasics() {
- $token = $this->getMockBuilder( Token::class )
- ->setMethods( [ 'toStringAtTimestamp' ] )
- ->setConstructorArgs( [ 'sekret', 'salty', true ] )
- ->getMock();
- $token->expects( $this->any() )->method( 'toStringAtTimestamp' )
- ->will( $this->returnValue( 'faketoken+\\' ) );
-
- $this->assertSame( 'faketoken+\\', $token->toString() );
- $this->assertSame( 'faketoken+\\', (string)$token );
- $this->assertTrue( $token->wasNew() );
-
- $token = new Token( 'sekret', 'salty', false );
- $this->assertFalse( $token->wasNew() );
- }
-
- public function testToStringAtTimestamp() {
- $token = TestingAccessWrapper::newFromObject( new Token( 'sekret', 'salty', false ) );
-
- $this->assertSame(
- 'd9ade0c7d4349e9df9094e61c33a5a0d5644fde2+\\',
- $token->toStringAtTimestamp( 1447362018 )
- );
- $this->assertSame(
- 'ee2f7a2488dea9176c224cfb400d43be5644fdea+\\',
- $token->toStringAtTimestamp( 1447362026 )
- );
- }
-
- public function testGetTimestamp() {
- $this->assertSame(
- 1447362018, Token::getTimestamp( 'd9ade0c7d4349e9df9094e61c33a5a0d5644fde2+\\' )
- );
- $this->assertSame(
- 1447362026, Token::getTimestamp( 'ee2f7a2488dea9176c224cfb400d43be5644fdea+\\' )
- );
- $this->assertNull( Token::getTimestamp( 'ee2f7a2488dea9176c224cfb400d43be5644fdea-\\' ) );
- $this->assertNull( Token::getTimestamp( 'ee2f7a2488dea9176c224cfb400d43be+\\' ) );
-
- $this->assertNull( Token::getTimestamp( 'ee2f7a2488dea9x76c224cfb400d43be5644fdea+\\' ) );
- }
-
- public function testMatch() {
- $token = TestingAccessWrapper::newFromObject( new Token( 'sekret', 'salty', false ) );
-
- $test = $token->toStringAtTimestamp( time() - 10 );
- $this->assertTrue( $token->match( $test ) );
- $this->assertTrue( $token->match( $test, 12 ) );
- $this->assertFalse( $token->match( $test, 8 ) );
-
- $this->assertFalse( $token->match( 'ee2f7a2488dea9176c224cfb400d43be5644fdea-\\' ) );
- }
-
-}
+++ /dev/null
-<?php
-
-/**
- * Copyright (C) 2017 Kunal Mehta <legoktm@member.fsf.org>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License along
- * with this program; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- */
-
-use MediaWiki\Shell\FirejailCommand;
-use MediaWiki\Shell\Shell;
-use Wikimedia\TestingAccessWrapper;
-
-class FirejailCommandTest extends PHPUnit\Framework\TestCase {
-
- use MediaWikiCoversValidator;
-
- public function provideBuildFinalCommand() {
- global $IP;
- // phpcs:ignore Generic.Files.LineLength
- $env = "'MW_INCLUDE_STDERR=;MW_CPU_LIMIT=180; MW_CGROUP='\'''\''; MW_MEM_LIMIT=307200; MW_FILE_SIZE_LIMIT=102400; MW_WALL_CLOCK_LIMIT=180; MW_USE_LOG_PIPE=yes'";
- $limit = "/bin/bash '$IP/includes/shell/limit.sh'";
- $profile = "--profile=$IP/includes/shell/firejail.profile";
- $blacklist = '--blacklist=' . realpath( MW_CONFIG_FILE );
- $default = "$blacklist --noroot --seccomp --private-dev";
- return [
- [
- 'No restrictions',
- 'ls', 0, "$limit ''\''ls'\''' $env"
- ],
- [
- 'default restriction',
- 'ls', Shell::RESTRICT_DEFAULT,
- "$limit 'firejail --quiet $profile $default -- '\''ls'\''' $env"
- ],
- [
- 'no network',
- 'ls', Shell::NO_NETWORK,
- "$limit 'firejail --quiet $profile --net=none -- '\''ls'\''' $env"
- ],
- [
- 'default restriction & no network',
- 'ls', Shell::RESTRICT_DEFAULT | Shell::NO_NETWORK,
- "$limit 'firejail --quiet $profile $default --net=none -- '\''ls'\''' $env"
- ],
- [
- 'seccomp',
- 'ls', Shell::SECCOMP,
- "$limit 'firejail --quiet $profile --seccomp -- '\''ls'\''' $env"
- ],
- [
- 'seccomp & no execve',
- 'ls', Shell::SECCOMP | Shell::NO_EXECVE,
- "$limit 'firejail --quiet $profile --shell=none --seccomp=execve -- '\''ls'\''' $env"
- ],
- ];
- }
-
- /**
- * @covers \MediaWiki\Shell\FirejailCommand::buildFinalCommand()
- * @dataProvider provideBuildFinalCommand
- */
- public function testBuildFinalCommand( $desc, $params, $flags, $expected ) {
- $command = new FirejailCommand( 'firejail' );
- $command
- ->params( $params )
- ->restrict( $flags );
- $wrapper = TestingAccessWrapper::newFromObject( $command );
- $output = $wrapper->buildFinalCommand( $wrapper->command );
- $this->assertEquals( $expected, $output[0], $desc );
- }
-
-}
+++ /dev/null
-<?php
-
-use MediaWiki\Site\MediaWikiPageNameNormalizer;
-
-/**
- * @covers MediaWiki\Site\MediaWikiPageNameNormalizer
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License along
- * with this program; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- * http://www.gnu.org/copyleft/gpl.html
- *
- * @since 1.27
- *
- * @group Site
- * @group medium
- *
- * @author Marius Hoch
- */
-class MediaWikiPageNameNormalizerTest extends PHPUnit\Framework\TestCase {
-
- use MediaWikiCoversValidator;
-
- /**
- * @dataProvider normalizePageTitleProvider
- */
- public function testNormalizePageTitle( $expected, $pageName, $getResponse ) {
- MediaWikiPageNameNormalizerTestMockHttp::$response = $getResponse;
-
- $normalizer = new MediaWikiPageNameNormalizer(
- new MediaWikiPageNameNormalizerTestMockHttp()
- );
-
- $this->assertSame(
- $expected,
- $normalizer->normalizePageName( $pageName, 'https://www.wikidata.org/w/api.php' )
- );
- }
-
- public function normalizePageTitleProvider() {
- // Response are taken from wikidata and kkwiki using the following API request
- // api.php?action=query&prop=info&redirects=1&converttitles=1&format=json&titles=…
- return [
- 'universe (Q1)' => [
- 'Q1',
- 'Q1',
- '{"batchcomplete":"","query":{"pages":{"129":{"pageid":129,"ns":0,'
- . '"title":"Q1","contentmodel":"wikibase-item","pagelanguage":"en",'
- . '"pagelanguagehtmlcode":"en","pagelanguagedir":"ltr",'
- . '"touched":"2016-06-23T05:11:21Z","lastrevid":350004448,"length":58001}}}}'
- ],
- 'Q404 redirects to Q395' => [
- 'Q395',
- 'Q404',
- '{"batchcomplete":"","query":{"redirects":[{"from":"Q404","to":"Q395"}],"pages"'
- . ':{"601":{"pageid":601,"ns":0,"title":"Q395","contentmodel":"wikibase-item",'
- . '"pagelanguage":"en","pagelanguagehtmlcode":"en","pagelanguagedir":"ltr",'
- . '"touched":"2016-06-23T08:00:20Z","lastrevid":350021914,"length":60108}}}}'
- ],
- 'D converted to Д (Latin to Cyrillic) (taken from kkwiki)' => [
- 'Д',
- 'D',
- '{"batchcomplete":"","query":{"converted":[{"from":"D","to":"\u0414"}],'
- . '"pages":{"510541":{"pageid":510541,"ns":0,"title":"\u0414",'
- . '"contentmodel":"wikitext","pagelanguage":"kk","pagelanguagehtmlcode":"kk",'
- . '"pagelanguagedir":"ltr","touched":"2015-11-22T09:16:18Z",'
- . '"lastrevid":2373618,"length":3501}}}}'
- ],
- 'there is no Q0' => [
- false,
- 'Q0',
- '{"batchcomplete":"","query":{"pages":{"-1":{"ns":0,"title":"Q0",'
- . '"missing":"","contentmodel":"wikibase-item","pagelanguage":"en",'
- . '"pagelanguagehtmlcode":"en","pagelanguagedir":"ltr"}}}}'
- ],
- 'invalid title' => [
- false,
- '{{',
- '{"batchcomplete":"","query":{"pages":{"-1":{"title":"{{",'
- . '"invalidreason":"The requested page title contains invalid '
- . 'characters: \"{\".","invalid":""}}}}'
- ],
- 'error on get' => [ false, 'ABC', false ]
- ];
- }
-
-}
-
-/**
- * @private
- * @see Http
- */
-class MediaWikiPageNameNormalizerTestMockHttp extends Http {
-
- /**
- * @var mixed
- */
- public static $response;
-
- public static function get( $url, array $options = [], $caller = __METHOD__ ) {
- PHPUnit_Framework_Assert::assertInternalType( 'string', $url );
- PHPUnit_Framework_Assert::assertInternalType( 'string', $caller );
-
- return self::$response;
- }
-}
$this->db->delete( 'actor', [ 'actor_user' => $id ], __METHOD__ );
User::purge( $domain, $id );
// Because WANObjectCache->delete() stupidly doesn't delete from the process cache.
- ObjectCache::getMainWANInstance()->clearProcessCache();
+
+ MediaWikiServices::getInstance()->getMainWANObjectCache()->clearProcessCache();
$user = User::newFromId( $id );
$this->assertFalse( $user->getActorId() > 0, 'No Actor ID by default if none in database' );
+++ /dev/null
-<?php
-
-/**
- * @covers ZipDirectoryReader
- * NOTE: this test is more like an integration test than a unit test
- */
-class ZipDirectoryReaderTest extends PHPUnit\Framework\TestCase {
-
- use MediaWikiCoversValidator;
-
- protected $zipDir;
- protected $entries;
-
- protected function setUp() {
- parent::setUp();
- $this->zipDir = __DIR__ . '/../../data/zip';
- }
-
- function zipCallback( $entry ) {
- $this->entries[] = $entry;
- }
-
- function readZipAssertError( $file, $error, $assertMessage ) {
- $this->entries = [];
- $status = ZipDirectoryReader::read( "{$this->zipDir}/$file", [ $this, 'zipCallback' ] );
- $this->assertTrue( $status->hasMessage( $error ), $assertMessage );
- }
-
- function readZipAssertSuccess( $file, $assertMessage ) {
- $this->entries = [];
- $status = ZipDirectoryReader::read( "{$this->zipDir}/$file", [ $this, 'zipCallback' ] );
- $this->assertTrue( $status->isOK(), $assertMessage );
- }
-
- public function testEmpty() {
- $this->readZipAssertSuccess( 'empty.zip', 'Empty zip' );
- }
-
- public function testMultiDisk0() {
- $this->readZipAssertError( 'split.zip', 'zip-unsupported',
- 'Split zip error' );
- }
-
- public function testNoSignature() {
- $this->readZipAssertError( 'nosig.zip', 'zip-wrong-format',
- 'No signature should give "wrong format" error' );
- }
-
- public function testSimple() {
- $this->readZipAssertSuccess( 'class.zip', 'Simple ZIP' );
- $this->assertEquals( $this->entries, [ [
- 'name' => 'Class.class',
- 'mtime' => '20010115000000',
- 'size' => 1,
- ] ] );
- }
-
- public function testBadCentralEntrySignature() {
- $this->readZipAssertError( 'wrong-central-entry-sig.zip', 'zip-bad',
- 'Bad central entry error' );
- }
-
- public function testTrailingBytes() {
- // Due to T40432 this is now zip-wrong-format instead of zip-bad
- $this->readZipAssertError( 'trail.zip', 'zip-wrong-format',
- 'Trailing bytes error' );
- }
-
- public function testWrongCDStart() {
- $this->readZipAssertError( 'wrong-cd-start-disk.zip', 'zip-unsupported',
- 'Wrong CD start disk error' );
- }
-
- public function testCentralDirectoryGap() {
- $this->readZipAssertError( 'cd-gap.zip', 'zip-bad',
- 'CD gap error' );
- }
-
- public function testCentralDirectoryTruncated() {
- $this->readZipAssertError( 'cd-truncated.zip', 'zip-bad',
- 'CD truncated error (should hit unpack() overrun)' );
- }
-
- public function testLooksLikeZip64() {
- $this->readZipAssertError( 'looks-like-zip64.zip', 'zip-unsupported',
- 'A file which looks like ZIP64 but isn\'t, should give error' );
- }
-}
}
/**
- * Verify that nothing depends on "startup".
+ * Verify that all modules specified as dependencies of other modules actually
+ * exist and are not illegal.
*
- * Depending on it is unsupported as it cannot be loaded by the client.
- *
- * @todo Modules can dynamically choose dependencies based on context. This method does not
- * test such dependencies. The same goes for testMissingDependencies() and
- * testUnsatisfiableDependencies().
+ * @todo Modules can dynamically choose dependencies based on context. This method
+ * does not find all such variations. The same applies to testUnsatisfiableDependencies().
*/
- public function testIllegalDependencies() {
+ public function testValidDependencies() {
$data = self::getAllModules();
-
- $illegalDeps = [];
- foreach ( $data['modules'] as $moduleName => $module ) {
- if ( $module instanceof ResourceLoaderStartUpModule ) {
- $illegalDeps[] = $moduleName;
- }
- }
-
- /** @var ResourceLoaderModule $module */
- foreach ( $data['modules'] as $moduleName => $module ) {
- foreach ( $illegalDeps as $illegalDep ) {
- $this->assertNotContains(
- $illegalDep,
- $module->getDependencies( $data['context'] ),
- "Module '$moduleName' must not depend on '$illegalDep'"
- );
- }
- }
- }
-
- /**
- * Verify that all modules specified as dependencies of other modules actually exist.
- */
- public function testMissingDependencies() {
- $data = self::getAllModules();
- $validDeps = array_keys( $data['modules'] );
+ $knownDeps = array_keys( $data['modules'] );
+ $illegalDeps = [ 'startup' ];
+
+ // Avoid an assert for each module to keep the test fast.
+ // Instead, perform a single assertion against everything at once.
+ // When all is good, actual/expected are both empty arrays.
+ // When we find issues, add the violations to 'actual' and add an empty
+ // key to 'expected'. These keys in expected are because the PHPUnit diff
+ // (as of 6.5) only goes one level deep.
+ $actualUnknown = [];
+ $expectedUnknown = [];
+ $actualIllegal = [];
+ $expectedIllegal = [];
/** @var ResourceLoaderModule $module */
foreach ( $data['modules'] as $moduleName => $module ) {
foreach ( $module->getDependencies( $data['context'] ) as $dep ) {
- $this->assertContains(
- $dep,
- $validDeps,
- "The module '$dep' required by '$moduleName' must exist"
- );
+ if ( !in_array( $dep, $knownDeps, true ) ) {
+ $actualUnknown[$moduleName][] = $dep;
+ $expectedUnknown[$moduleName] = [];
+ }
+ if ( in_array( $dep, $illegalDeps, true ) ) {
+ $actualIllegal[$moduleName][] = $dep;
+ $expectedIllegal[$moduleName] = [];
+ }
}
}
+ $this->assertEquals( $expectedUnknown, $actualUnknown, 'Dependencies that do not exist' );
+ $this->assertEquals( $expectedIllegal, $actualIllegal, 'Dependencies that are not legal' );
}
/**
--- /dev/null
+<?php
+
+/**
+ * @group GlobalFunctions
+ * @covers ::wfAppendQuery
+ */
+class WfAppendQueryTest extends MediaWikiUnitTestCase {
+ /**
+ * @dataProvider provideAppendQuery
+ */
+ public function testAppendQuery( $url, $query, $expected, $message = null ) {
+ $this->assertEquals( $expected, wfAppendQuery( $url, $query ), $message );
+ }
+
+ public static function provideAppendQuery() {
+ return [
+ [
+ 'http://www.example.org/index.php',
+ '',
+ 'http://www.example.org/index.php',
+ 'No query'
+ ],
+ [
+ 'http://www.example.org/index.php',
+ [ 'foo' => 'bar' ],
+ 'http://www.example.org/index.php?foo=bar',
+ 'Set query array'
+ ],
+ [
+ 'http://www.example.org/index.php?foz=baz',
+ 'foo=bar',
+ 'http://www.example.org/index.php?foz=baz&foo=bar',
+ 'Set query string'
+ ],
+ [
+ 'http://www.example.org/index.php?foo=bar',
+ '',
+ 'http://www.example.org/index.php?foo=bar',
+ 'Empty string with query'
+ ],
+ [
+ 'http://www.example.org/index.php?foo=bar',
+ [ 'baz' => 'quux' ],
+ 'http://www.example.org/index.php?foo=bar&baz=quux',
+ 'Add query array'
+ ],
+ [
+ 'http://www.example.org/index.php?foo=bar',
+ 'baz=quux',
+ 'http://www.example.org/index.php?foo=bar&baz=quux',
+ 'Add query string'
+ ],
+ [
+ 'http://www.example.org/index.php?foo=bar',
+ [ 'baz' => 'quux', 'foo' => 'baz' ],
+ 'http://www.example.org/index.php?foo=bar&baz=quux&foo=baz',
+ 'Modify query array'
+ ],
+ [
+ 'http://www.example.org/index.php?foo=bar',
+ 'baz=quux&foo=baz',
+ 'http://www.example.org/index.php?foo=bar&baz=quux&foo=baz',
+ 'Modify query string'
+ ],
+ [
+ 'http://www.example.org/index.php#baz',
+ 'foo=bar',
+ 'http://www.example.org/index.php?foo=bar#baz',
+ 'URL with fragment'
+ ],
+ [
+ 'http://www.example.org/index.php?foo=bar#baz',
+ 'quux=blah',
+ 'http://www.example.org/index.php?foo=bar&quux=blah#baz',
+ 'URL with query string and fragment'
+ ]
+ ];
+ }
+}
--- /dev/null
+<?php
+/**
+ * @group GlobalFunctions
+ * @covers ::wfArrayPlus2d
+ */
+class WfArrayPlus2dTest extends MediaWikiUnitTestCase {
+ /**
+ * @dataProvider provideArrays
+ */
+ public function testWfArrayPlus2d( $baseArray, $newValues, $expected, $testName ) {
+ $this->assertEquals(
+ $expected,
+ wfArrayPlus2d( $baseArray, $newValues ),
+ $testName
+ );
+ }
+
+ /**
+ * Provider for testing wfArrayPlus2d
+ *
+ * @return array
+ */
+ public static function provideArrays() {
+ return [
+ // target array, new values array, expected result
+ [
+ [ 0 => '1dArray' ],
+ [ 1 => '1dArray' ],
+ [ 0 => '1dArray', 1 => '1dArray' ],
+ "Test simple union of two arrays with different keys",
+ ],
+ [
+ [
+ 0 => [ 0 => '2dArray' ],
+ ],
+ [
+ 0 => [ 1 => '2dArray' ],
+ ],
+ [
+ 0 => [ 0 => '2dArray', 1 => '2dArray' ],
+ ],
+ "Test union of 2d arrays with different keys in the value array",
+ ],
+ [
+ [
+ 0 => [ 0 => '2dArray' ],
+ ],
+ [
+ 0 => [ 0 => '1dArray' ],
+ ],
+ [
+ 0 => [ 0 => '2dArray' ],
+ ],
+ "Test union of 2d arrays with same keys in the value array",
+ ],
+ [
+ [
+ 0 => [ 0 => [ 0 => '3dArray' ] ],
+ ],
+ [
+ 0 => [ 0 => [ 1 => '2dArray' ] ],
+ ],
+ [
+ 0 => [ 0 => [ 0 => '3dArray' ] ],
+ ],
+ "Test union of 3d array with different keys",
+ ],
+ [
+ [
+ 0 => [ 0 => [ 0 => '3dArray' ] ],
+ ],
+ [
+ 0 => [ 1 => [ 0 => '2dArray' ] ],
+ ],
+ [
+ 0 => [ 0 => [ 0 => '3dArray' ], 1 => [ 0 => '2dArray' ] ],
+ ],
+ "Test union of 3d array with different keys in the value array",
+ ],
+ [
+ [
+ 0 => [ 0 => [ 0 => '3dArray' ] ],
+ ],
+ [
+ 0 => [ 0 => [ 0 => '2dArray' ] ],
+ ],
+ [
+ 0 => [ 0 => [ 0 => '3dArray' ] ],
+ ],
+ "Test union of 3d array with same keys in the value array",
+ ],
+ ];
+ }
+}
--- /dev/null
+<?php
+/**
+ * @group GlobalFunctions
+ * @covers ::wfAssembleUrl
+ */
+class WfAssembleUrlTest extends MediaWikiUnitTestCase {
+ /**
+ * @dataProvider provideURLParts
+ */
+ public function testWfAssembleUrl( $parts, $output ) {
+ $partsDump = print_r( $parts, true );
+ $this->assertEquals(
+ $output,
+ wfAssembleUrl( $parts ),
+ "Testing $partsDump assembles to $output"
+ );
+ }
+
+ /**
+ * Provider of URL parts for testing wfAssembleUrl()
+ *
+ * @return array
+ */
+ public static function provideURLParts() {
+ $schemes = [
+ '' => [],
+ '//' => [
+ 'delimiter' => '//',
+ ],
+ 'http://' => [
+ 'scheme' => 'http',
+ 'delimiter' => '://',
+ ],
+ ];
+
+ $hosts = [
+ '' => [],
+ 'example.com' => [
+ 'host' => 'example.com',
+ ],
+ 'example.com:123' => [
+ 'host' => 'example.com',
+ 'port' => 123,
+ ],
+ 'id@example.com' => [
+ 'user' => 'id',
+ 'host' => 'example.com',
+ ],
+ 'id@example.com:123' => [
+ 'user' => 'id',
+ 'host' => 'example.com',
+ 'port' => 123,
+ ],
+ 'id:key@example.com' => [
+ 'user' => 'id',
+ 'pass' => 'key',
+ 'host' => 'example.com',
+ ],
+ 'id:key@example.com:123' => [
+ 'user' => 'id',
+ 'pass' => 'key',
+ 'host' => 'example.com',
+ 'port' => 123,
+ ],
+ ];
+
+ $cases = [];
+ foreach ( $schemes as $scheme => $schemeParts ) {
+ foreach ( $hosts as $host => $hostParts ) {
+ foreach ( [ '', '/path' ] as $path ) {
+ foreach ( [ '', 'query' ] as $query ) {
+ foreach ( [ '', 'fragment' ] as $fragment ) {
+ $parts = array_merge(
+ $schemeParts,
+ $hostParts
+ );
+ $url = $scheme .
+ $host .
+ $path;
+
+ if ( $path ) {
+ $parts['path'] = $path;
+ }
+ if ( $query ) {
+ $parts['query'] = $query;
+ $url .= '?' . $query;
+ }
+ if ( $fragment ) {
+ $parts['fragment'] = $fragment;
+ $url .= '#' . $fragment;
+ }
+
+ $cases[] = [
+ $parts,
+ $url,
+ ];
+ }
+ }
+ }
+ }
+ }
+
+ $complexURL = 'http://id:key@example.org:321' .
+ '/over/there?name=ferret&foo=bar#nose';
+ $cases[] = [
+ wfParseUrl( $complexURL ),
+ $complexURL,
+ ];
+
+ return $cases;
+ }
+}
--- /dev/null
+<?php
+/**
+ * @group GlobalFunctions
+ * @covers ::wfBaseName
+ */
+class WfBaseNameTest extends MediaWikiUnitTestCase {
+ /**
+ * @dataProvider providePaths
+ */
+ public function testBaseName( $fullpath, $basename ) {
+ $this->assertEquals( $basename, wfBaseName( $fullpath ),
+ "wfBaseName('$fullpath') => '$basename'" );
+ }
+
+ public static function providePaths() {
+ return [
+ [ '', '' ],
+ [ '/', '' ],
+ [ '\\', '' ],
+ [ '//', '' ],
+ [ '\\\\', '' ],
+ [ 'a', 'a' ],
+ [ 'aaaa', 'aaaa' ],
+ [ '/a', 'a' ],
+ [ '\\a', 'a' ],
+ [ '/aaaa', 'aaaa' ],
+ [ '\\aaaa', 'aaaa' ],
+ [ '/aaaa/', 'aaaa' ],
+ [ '\\aaaa\\', 'aaaa' ],
+ [ '\\aaaa\\', 'aaaa' ],
+ [
+ '/mnt/upload3/wikipedia/en/thumb/8/8b/'
+ . 'Zork_Grand_Inquisitor_box_cover.jpg/93px-Zork_Grand_Inquisitor_box_cover.jpg',
+ '93px-Zork_Grand_Inquisitor_box_cover.jpg'
+ ],
+ [ 'C:\\Progra~1\\Wikime~1\\Wikipe~1\\VIEWER.EXE', 'VIEWER.EXE' ],
+ [ 'Östergötland_coat_of_arms.png', 'Östergötland_coat_of_arms.png' ],
+ ];
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * @group GlobalFunctions
+ * @covers ::wfEscapeShellArg
+ */
+class WfEscapeShellArgTest extends MediaWikiUnitTestCase {
+ public function testSingleInput() {
+ if ( wfIsWindows() ) {
+ $expected = '"blah"';
+ } else {
+ $expected = "'blah'";
+ }
+
+ $actual = wfEscapeShellArg( 'blah' );
+
+ $this->assertEquals( $expected, $actual );
+ }
+
+ public function testMultipleArgs() {
+ if ( wfIsWindows() ) {
+ $expected = '"foo" "bar" "baz"';
+ } else {
+ $expected = "'foo' 'bar' 'baz'";
+ }
+
+ $actual = wfEscapeShellArg( 'foo', 'bar', 'baz' );
+
+ $this->assertEquals( $expected, $actual );
+ }
+
+ public function testMultipleArgsAsArray() {
+ if ( wfIsWindows() ) {
+ $expected = '"foo" "bar" "baz"';
+ } else {
+ $expected = "'foo' 'bar' 'baz'";
+ }
+
+ $actual = wfEscapeShellArg( [ 'foo', 'bar', 'baz' ] );
+
+ $this->assertEquals( $expected, $actual );
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * @group GlobalFunctions
+ * @covers ::wfGetCaller
+ */
+class WfGetCallerTest extends MediaWikiUnitTestCase {
+ public function testZero() {
+ $this->assertEquals( 'WfGetCallerTest->testZero', wfGetCaller( 1 ) );
+ }
+
+ function callerOne() {
+ return wfGetCaller();
+ }
+
+ public function testOne() {
+ $this->assertEquals( 'WfGetCallerTest->testOne', self::callerOne() );
+ }
+
+ static function intermediateFunction( $level = 2, $n = 0 ) {
+ if ( $n > 0 ) {
+ return self::intermediateFunction( $level, $n - 1 );
+ }
+
+ return wfGetCaller( $level );
+ }
+
+ public function testTwo() {
+ $this->assertEquals( 'WfGetCallerTest->testTwo', self::intermediateFunction() );
+ }
+
+ public function testN() {
+ $this->assertEquals( 'WfGetCallerTest->testN', self::intermediateFunction( 2, 0 ) );
+ $this->assertEquals(
+ 'WfGetCallerTest::intermediateFunction',
+ self::intermediateFunction( 1, 0 )
+ );
+
+ for ( $i = 0; $i < 10; $i++ ) {
+ $this->assertEquals(
+ 'WfGetCallerTest::intermediateFunction',
+ self::intermediateFunction( $i + 1, $i )
+ );
+ }
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * @group GlobalFunctions
+ * @covers ::wfRemoveDotSegments
+ */
+class WfRemoveDotSegmentsTest extends MediaWikiUnitTestCase {
+ /**
+ * @dataProvider providePaths
+ */
+ public function testWfRemoveDotSegments( $inputPath, $outputPath ) {
+ $this->assertEquals(
+ $outputPath,
+ wfRemoveDotSegments( $inputPath ),
+ "Testing $inputPath expands to $outputPath"
+ );
+ }
+
+ /**
+ * Provider of URL paths for testing wfRemoveDotSegments()
+ *
+ * @return array
+ */
+ public static function providePaths() {
+ return [
+ [ '/a/b/c/./../../g', '/a/g' ],
+ [ 'mid/content=5/../6', 'mid/6' ],
+ [ '/a//../b', '/a/b' ],
+ [ '/.../a', '/.../a' ],
+ [ '.../a', '.../a' ],
+ [ '', '' ],
+ [ '/', '/' ],
+ [ '//', '//' ],
+ [ '.', '' ],
+ [ '..', '' ],
+ [ '...', '...' ],
+ [ '/.', '/' ],
+ [ '/..', '/' ],
+ [ './', '' ],
+ [ '../', '' ],
+ [ './a', 'a' ],
+ [ '../a', 'a' ],
+ [ '../../a', 'a' ],
+ [ '.././a', 'a' ],
+ [ './../a', 'a' ],
+ [ '././a', 'a' ],
+ [ '../../', '' ],
+ [ '.././', '' ],
+ [ './../', '' ],
+ [ '././', '' ],
+ [ '../..', '' ],
+ [ '../.', '' ],
+ [ './..', '' ],
+ [ './.', '' ],
+ [ '/../../a', '/a' ],
+ [ '/.././a', '/a' ],
+ [ '/./../a', '/a' ],
+ [ '/././a', '/a' ],
+ [ '/../../', '/' ],
+ [ '/.././', '/' ],
+ [ '/./../', '/' ],
+ [ '/././', '/' ],
+ [ '/../..', '/' ],
+ [ '/../.', '/' ],
+ [ '/./..', '/' ],
+ [ '/./.', '/' ],
+ [ 'b/../../a', '/a' ],
+ [ 'b/.././a', '/a' ],
+ [ 'b/./../a', '/a' ],
+ [ 'b/././a', 'b/a' ],
+ [ 'b/../../', '/' ],
+ [ 'b/.././', '/' ],
+ [ 'b/./../', '/' ],
+ [ 'b/././', 'b/' ],
+ [ 'b/../..', '/' ],
+ [ 'b/../.', '/' ],
+ [ 'b/./..', '/' ],
+ [ 'b/./.', 'b/' ],
+ [ '/b/../../a', '/a' ],
+ [ '/b/.././a', '/a' ],
+ [ '/b/./../a', '/a' ],
+ [ '/b/././a', '/b/a' ],
+ [ '/b/../../', '/' ],
+ [ '/b/.././', '/' ],
+ [ '/b/./../', '/' ],
+ [ '/b/././', '/b/' ],
+ [ '/b/../..', '/' ],
+ [ '/b/../.', '/' ],
+ [ '/b/./..', '/' ],
+ [ '/b/./.', '/b/' ],
+ ];
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * @group GlobalFunctions
+ * @covers ::wfShorthandToInteger
+ */
+class WfShorthandToIntegerTest extends MediaWikiUnitTestCase {
+ /**
+ * @dataProvider provideABunchOfShorthands
+ */
+ public function testWfShorthandToInteger( $input, $output, $description ) {
+ $this->assertEquals(
+ wfShorthandToInteger( $input ),
+ $output,
+ $description
+ );
+ }
+
+ public static function provideABunchOfShorthands() {
+ return [
+ [ '', -1, 'Empty string' ],
+ [ ' ', -1, 'String of spaces' ],
+ [ '1G', 1024 * 1024 * 1024, 'One gig uppercased' ],
+ [ '1g', 1024 * 1024 * 1024, 'One gig lowercased' ],
+ [ '1M', 1024 * 1024, 'One meg uppercased' ],
+ [ '1m', 1024 * 1024, 'One meg lowercased' ],
+ [ '1K', 1024, 'One kb uppercased' ],
+ [ '1k', 1024, 'One kb lowercased' ],
+ ];
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * @group GlobalFunctions
+ * @covers ::wfStringToBool
+ */
+class WfStringToBoolTest extends MediaWikiUnitTestCase {
+
+ public function getTestCases() {
+ return [
+ [ 'true', true ],
+ [ 'on', true ],
+ [ 'yes', true ],
+ [ 'TRUE', true ],
+ [ 'YeS', true ],
+ [ 'On', true ],
+ [ '1', true ],
+ [ '+1', true ],
+ [ '01', true ],
+ [ '-001', true ],
+ [ ' 1', true ],
+ [ '-1 ', true ],
+ [ '', false ],
+ [ '0', false ],
+ [ 'false', false ],
+ [ 'NO', false ],
+ [ 'NOT', false ],
+ [ 'never', false ],
+ [ '!&', false ],
+ [ '-0', false ],
+ [ '+0', false ],
+ [ 'forget about it', false ],
+ [ ' on', false ],
+ [ 'true ', false ],
+ ];
+ }
+
+ /**
+ * @dataProvider getTestCases
+ * @param string $str
+ * @param bool $bool
+ */
+ public function testStr2Bool( $str, $bool ) {
+ if ( $bool ) {
+ $this->assertTrue( wfStringToBool( $str ) );
+ } else {
+ $this->assertFalse( wfStringToBool( $str ) );
+ }
+ }
+
+}
--- /dev/null
+<?php
+
+/**
+ * @group GlobalFunctions
+ * @covers ::wfTimestamp
+ */
+class WfTimestampTest extends MediaWikiUnitTestCase {
+ /**
+ * @dataProvider provideNormalTimestamps
+ */
+ public function testNormalTimestamps( $input, $format, $output, $desc ) {
+ $this->assertEquals( $output, wfTimestamp( $format, $input ), $desc );
+ }
+
+ public static function provideNormalTimestamps() {
+ $t = gmmktime( 12, 34, 56, 1, 15, 2001 );
+
+ return [
+ // TS_UNIX
+ [ $t, TS_MW, '20010115123456', 'TS_UNIX to TS_MW' ],
+ [ -30281104, TS_MW, '19690115123456', 'Negative TS_UNIX to TS_MW' ],
+ [ $t, TS_UNIX, 979562096, 'TS_UNIX to TS_UNIX' ],
+ [ $t, TS_DB, '2001-01-15 12:34:56', 'TS_UNIX to TS_DB' ],
+ [ $t + 0.01, TS_MW, '20010115123456', 'TS_UNIX float to TS_MW' ],
+
+ [ $t, TS_ISO_8601_BASIC, '20010115T123456Z', 'TS_ISO_8601_BASIC to TS_DB' ],
+
+ // TS_MW
+ [ '20010115123456', TS_MW, '20010115123456', 'TS_MW to TS_MW' ],
+ [ '20010115123456', TS_UNIX, 979562096, 'TS_MW to TS_UNIX' ],
+ [ '20010115123456', TS_DB, '2001-01-15 12:34:56', 'TS_MW to TS_DB' ],
+ [ '20010115123456', TS_ISO_8601_BASIC, '20010115T123456Z', 'TS_MW to TS_ISO_8601_BASIC' ],
+
+ // TS_DB
+ [ '2001-01-15 12:34:56', TS_MW, '20010115123456', 'TS_DB to TS_MW' ],
+ [ '2001-01-15 12:34:56', TS_UNIX, 979562096, 'TS_DB to TS_UNIX' ],
+ [ '2001-01-15 12:34:56', TS_DB, '2001-01-15 12:34:56', 'TS_DB to TS_DB' ],
+ [
+ '2001-01-15 12:34:56',
+ TS_ISO_8601_BASIC,
+ '20010115T123456Z',
+ 'TS_DB to TS_ISO_8601_BASIC'
+ ],
+
+ # rfc2822 section 3.3
+ [ '20010115123456', TS_RFC2822, 'Mon, 15 Jan 2001 12:34:56 GMT', 'TS_MW to TS_RFC2822' ],
+ [ 'Mon, 15 Jan 2001 12:34:56 GMT', TS_MW, '20010115123456', 'TS_RFC2822 to TS_MW' ],
+ [
+ ' Mon, 15 Jan 2001 12:34:56 GMT',
+ TS_MW,
+ '20010115123456',
+ 'TS_RFC2822 with leading space to TS_MW'
+ ],
+ [
+ '15 Jan 2001 12:34:56 GMT',
+ TS_MW,
+ '20010115123456',
+ 'TS_RFC2822 without optional day-of-week to TS_MW'
+ ],
+
+ # FWS = ([*WSP CRLF] 1*WSP) / obs-FWS ; Folding white space
+ # obs-FWS = 1*WSP *(CRLF 1*WSP) ; Section 4.2
+ [ 'Mon, 15 Jan 2001 12:34:56 GMT', TS_MW, '20010115123456', 'TS_RFC2822 to TS_MW' ],
+
+ # WSP = SP / HTAB ; rfc2234
+ [
+ "Mon, 15 Jan\x092001 12:34:56 GMT",
+ TS_MW,
+ '20010115123456',
+ 'TS_RFC2822 with HTAB to TS_MW'
+ ],
+ [
+ "Mon, 15 Jan\x09 \x09 2001 12:34:56 GMT",
+ TS_MW,
+ '20010115123456',
+ 'TS_RFC2822 with HTAB and SP to TS_MW'
+ ],
+ [
+ 'Sun, 6 Nov 94 08:49:37 GMT',
+ TS_MW,
+ '19941106084937',
+ 'TS_RFC2822 with obsolete year to TS_MW'
+ ],
+ ];
+ }
+
+ /**
+ * This test checks wfTimestamp() with values outside.
+ * It needs PHP 64 bits or PHP > 5.1.
+ * See r74778 and T27451
+ * @dataProvider provideOldTimestamps
+ */
+ public function testOldTimestamps( $input, $outputType, $output, $message ) {
+ $timestamp = wfTimestamp( $outputType, $input );
+ if ( substr( $output, 0, 1 ) === '/' ) {
+ // T66946: Day of the week calculations for very old
+ // timestamps varies from system to system.
+ $this->assertRegExp( $output, $timestamp, $message );
+ } else {
+ $this->assertEquals( $output, $timestamp, $message );
+ }
+ }
+
+ public static function provideOldTimestamps() {
+ return [
+ [
+ '19011213204554',
+ TS_RFC2822,
+ 'Fri, 13 Dec 1901 20:45:54 GMT',
+ 'Earliest time according to PHP documentation'
+ ],
+ [ '20380119031407', TS_RFC2822, 'Tue, 19 Jan 2038 03:14:07 GMT', 'Latest 32 bit time' ],
+ [ '19011213204552', TS_UNIX, '-2147483648', 'Earliest 32 bit unix time' ],
+ [ '20380119031407', TS_UNIX, '2147483647', 'Latest 32 bit unix time' ],
+ [ '19011213204552', TS_RFC2822, 'Fri, 13 Dec 1901 20:45:52 GMT', 'Earliest 32 bit time' ],
+ [
+ '19011213204551',
+ TS_RFC2822,
+ 'Fri, 13 Dec 1901 20:45:51 GMT', 'Earliest 32 bit time - 1'
+ ],
+ [ '20380119031408', TS_RFC2822, 'Tue, 19 Jan 2038 03:14:08 GMT', 'Latest 32 bit time + 1' ],
+ [ '19011212000000', TS_MW, '19011212000000', 'Convert to itself r74778#c10645' ],
+ [ '19011213204551', TS_UNIX, '-2147483649', 'Earliest 32 bit unix time - 1' ],
+ [ '20380119031408', TS_UNIX, '2147483648', 'Latest 32 bit unix time + 1' ],
+ [ '-2147483649', TS_MW, '19011213204551', '1901 negative unix time to MediaWiki' ],
+ [ '-5331871504', TS_MW, '18010115123456', '1801 negative unix time to MediaWiki' ],
+ [
+ '0117-08-09 12:34:56',
+ TS_RFC2822,
+ '/, 09 Aug 0117 12:34:56 GMT$/',
+ 'Death of Roman Emperor [[Trajan]]'
+ ],
+
+ /* @todo FIXME: 00 to 101 years are taken as being in [1970-2069] */
+ [ '-58979923200', TS_RFC2822, '/, 01 Jan 0101 00:00:00 GMT$/', '1/1/101' ],
+ [ '-62135596800', TS_RFC2822, 'Mon, 01 Jan 0001 00:00:00 GMT', 'Year 1' ],
+
+ /* It is not clear if we should generate a year 0 or not
+ * We are completely off RFC2822 requirement of year being
+ * 1900 or later.
+ */
+ [
+ '-62142076800',
+ TS_RFC2822,
+ 'Wed, 18 Oct 0000 00:00:00 GMT',
+ 'ISO 8601:2004 [[year 0]], also called [[1 BC]]'
+ ],
+ ];
+ }
+
+ /**
+ * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1
+ * @dataProvider provideHttpDates
+ */
+ public function testHttpDate( $input, $output, $desc ) {
+ $this->assertEquals( $output, wfTimestamp( TS_MW, $input ), $desc );
+ }
+
+ public static function provideHttpDates() {
+ return [
+ [ 'Sun, 06 Nov 1994 08:49:37 GMT', '19941106084937', 'RFC 822 date' ],
+ [ 'Sunday, 06-Nov-94 08:49:37 GMT', '19941106084937', 'RFC 850 date' ],
+ [ 'Sun Nov 6 08:49:37 1994', '19941106084937', "ANSI C's asctime() format" ],
+ // See http://www.squid-cache.org/mail-archive/squid-users/200307/0122.html and r77171
+ [
+ 'Mon, 22 Nov 2010 14:12:42 GMT; length=52626',
+ '20101122141242',
+ 'Netscape extension to HTTP/1.0'
+ ],
+ ];
+ }
+
+ /**
+ * There are a number of assumptions in our codebase where wfTimestamp()
+ * should give the current date but it is not given a 0 there. See r71751 CR
+ */
+ public function testTimestampParameter() {
+ $now = wfTimestamp( TS_UNIX );
+ // We check that wfTimestamp doesn't return false (error) and use a LessThan assert
+ // for the cases where the test is run in a second boundary.
+
+ $zero = wfTimestamp( TS_UNIX, 0 );
+ $this->assertNotEquals( false, $zero );
+ $this->assertLessThan( 5, $zero - $now );
+
+ $empty = wfTimestamp( TS_UNIX, '' );
+ $this->assertNotEquals( false, $empty );
+ $this->assertLessThan( 5, $empty - $now );
+
+ $null = wfTimestamp( TS_UNIX, null );
+ $this->assertNotEquals( false, $null );
+ $this->assertLessThan( 5, $null - $now );
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * The function only need a string parameter and might react to IIS7.0
+ *
+ * @group GlobalFunctions
+ * @covers ::wfUrlencode
+ */
+class WfUrlencodeTest extends MediaWikiUnitTestCase {
+ # ### TESTS ##############################################################
+
+ /**
+ * @dataProvider provideURLS
+ */
+ public function testEncodingUrlWith( $input, $expected ) {
+ $this->verifyEncodingFor( 'Apache', $input, $expected );
+ }
+
+ /**
+ * @dataProvider provideURLS
+ */
+ public function testEncodingUrlWithMicrosoftIis7( $input, $expected ) {
+ $this->verifyEncodingFor( 'Microsoft-IIS/7', $input, $expected );
+ }
+
+ # ### HELPERS #############################################################
+
+ /**
+ * Internal helper that actually run the test.
+ * Called by the public methods testEncodingUrlWith...()
+ */
+ private function verifyEncodingFor( $server, $input, $expectations ) {
+ $expected = $this->extractExpect( $server, $expectations );
+
+ // save up global
+ $old = $_SERVER['SERVER_SOFTWARE'] ?? null;
+ $_SERVER['SERVER_SOFTWARE'] = $server;
+ wfUrlencode( null );
+
+ // do the requested test
+ $this->assertEquals(
+ $expected,
+ wfUrlencode( $input ),
+ "Encoding '$input' for server '$server' should be '$expected'"
+ );
+
+ // restore global
+ if ( $old === null ) {
+ unset( $_SERVER['SERVER_SOFTWARE'] );
+ } else {
+ $_SERVER['SERVER_SOFTWARE'] = $old;
+ }
+ wfUrlencode( null );
+ }
+
+ /**
+ * Interprets the provider array. Return expected value depending
+ * the HTTP server name.
+ */
+ private function extractExpect( $server, $expectations ) {
+ if ( is_string( $expectations ) ) {
+ return $expectations;
+ } elseif ( is_array( $expectations ) ) {
+ if ( !array_key_exists( $server, $expectations ) ) {
+ throw new MWException( __METHOD__ . " expectation does not have any "
+ . "value for server name $server. Check the provider array.\n" );
+ } else {
+ return $expectations[$server];
+ }
+ } else {
+ throw new MWException( __METHOD__ . " given invalid expectation for "
+ . "'$server'. Should be a string or an array [ <http server name> => <string> ].\n" );
+ }
+ }
+
+ # ### PROVIDERS ###########################################################
+
+ /**
+ * Format is either:
+ * [ 'input', 'expected' ];
+ * Or:
+ * [ 'input',
+ * [ 'Apache', 'expected' ],
+ * [ 'Microsoft-IIS/7', 'expected' ],
+ * ],
+ * If you want to add other HTTP server name, you will have to add a new
+ * testing method much like the testEncodingUrlWith() method above.
+ */
+ public static function provideURLS() {
+ return [
+ # ## RFC 1738 chars
+ // + is not safe
+ [ '+', '%2B' ],
+ // & and = not safe in queries
+ [ '&', '%26' ],
+ [ '=', '%3D' ],
+
+ [ ':', [
+ 'Apache' => ':',
+ 'Microsoft-IIS/7' => '%3A',
+ ] ],
+
+ // remaining chars do not need encoding
+ [
+ ';@$-_.!*',
+ ';@$-_.!*',
+ ],
+
+ # ## Other tests
+ // slash remain unchanged. %2F seems to break things
+ [ '/', '/' ],
+ // T105265
+ [ '~', '~' ],
+
+ // Other 'funnies' chars
+ [ '[]', '%5B%5D' ],
+ [ '<>', '%3C%3E' ],
+
+ // Apostrophe is encoded
+ [ '\'', '%27' ],
+ ];
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Tests for the PathRouter parsing.
+ *
+ * @covers PathRouter
+ */
+class PathRouterTest extends MediaWikiUnitTestCase {
+
+ /**
+ * @var PathRouter
+ */
+ protected $basicRouter;
+
+ protected function setUp() {
+ parent::setUp();
+ $router = new PathRouter;
+ $router->add( "/wiki/$1" );
+ $this->basicRouter = $router;
+ }
+
+ public static function provideParse() {
+ $tests = [
+ // Basic path parsing
+ 'Basic path parsing' => [
+ "/wiki/$1",
+ "/wiki/Foo",
+ [ 'title' => "Foo" ]
+ ],
+ //
+ 'Loose path auto-$1: /$1' => [
+ "/",
+ "/Foo",
+ [ 'title' => "Foo" ]
+ ],
+ 'Loose path auto-$1: /wiki' => [
+ "/wiki",
+ "/wiki/Foo",
+ [ 'title' => "Foo" ]
+ ],
+ 'Loose path auto-$1: /wiki/' => [
+ "/wiki/",
+ "/wiki/Foo",
+ [ 'title' => "Foo" ]
+ ],
+ // Ensure that path is based on specificity, not order
+ 'Order, /$1 added first' => [
+ [ "/$1", "/a/$1", "/b/$1" ],
+ "/a/Foo",
+ [ 'title' => "Foo" ]
+ ],
+ 'Order, /$1 added last' => [
+ [ "/b/$1", "/a/$1", "/$1" ],
+ "/a/Foo",
+ [ 'title' => "Foo" ]
+ ],
+ // Handling of key based arrays with a url parameter
+ 'Key based array' => [
+ [ [
+ 'path' => [ 'edit' => "/edit/$1" ],
+ 'params' => [ 'action' => '$key' ],
+ ] ],
+ "/edit/Foo",
+ [ 'title' => "Foo", 'action' => 'edit' ]
+ ],
+ // Additional parameter
+ 'Basic $2' => [
+ [ [
+ 'path' => '/$2/$1',
+ 'params' => [ 'test' => '$2' ]
+ ] ],
+ "/asdf/Foo",
+ [ 'title' => "Foo", 'test' => 'asdf' ]
+ ],
+ ];
+ // Shared patterns for restricted value parameter tests
+ $restrictedPatterns = [
+ [
+ 'path' => '/$2/$1',
+ 'params' => [ 'test' => '$2' ],
+ 'options' => [ '$2' => [ 'a', 'b' ] ]
+ ],
+ [
+ 'path' => '/$2/$1',
+ 'params' => [ 'test2' => '$2' ],
+ 'options' => [ '$2' => 'c' ]
+ ],
+ '/$1'
+ ];
+ $tests += [
+ // Restricted value parameter tests
+ 'Restricted 1' => [
+ $restrictedPatterns,
+ "/asdf/Foo",
+ [ 'title' => "asdf/Foo" ]
+ ],
+ 'Restricted 2' => [
+ $restrictedPatterns,
+ "/a/Foo",
+ [ 'title' => "Foo", 'test' => 'a' ]
+ ],
+ 'Restricted 3' => [
+ $restrictedPatterns,
+ "/c/Foo",
+ [ 'title' => "Foo", 'test2' => 'c' ]
+ ],
+
+ // Callback test
+ 'Callback' => [
+ [ [
+ 'path' => "/$1",
+ 'params' => [ 'a' => 'b', 'data:foo' => 'bar' ],
+ 'options' => [ 'callback' => [ __CLASS__, 'callbackForTest' ] ]
+ ] ],
+ '/Foo',
+ [
+ 'title' => "Foo",
+ 'x' => 'Foo',
+ 'a' => 'b',
+ 'foo' => 'bar'
+ ]
+ ],
+
+ // Test to ensure that matches are not made if a parameter expects nonexistent input
+ 'Fail' => [
+ [ [
+ 'path' => "/wiki/$1",
+ 'params' => [ 'title' => "$1$2" ],
+ ] ],
+ "/wiki/A",
+ []
+ ],
+
+ // Make sure the router handles titles like Special:Recentchanges correctly
+ 'Special title' => [
+ "/wiki/$1",
+ "/wiki/Special:Recentchanges",
+ [ 'title' => "Special:Recentchanges" ]
+ ],
+
+ // Make sure the router decodes urlencoding properly
+ 'URL encoding' => [
+ "/wiki/$1",
+ "/wiki/Title_With%20Space",
+ [ 'title' => "Title_With Space" ]
+ ],
+
+ // Double slash and dot expansion
+ 'Double slash in prefix' => [
+ '/wiki/$1',
+ '//wiki/Foo',
+ [ 'title' => 'Foo' ]
+ ],
+ 'Double slash at start of $1' => [
+ '/wiki/$1',
+ '/wiki//Foo',
+ [ 'title' => '/Foo' ]
+ ],
+ 'Double slash in middle of $1' => [
+ '/wiki/$1',
+ '/wiki/.hack//SIGN',
+ [ 'title' => '.hack//SIGN' ]
+ ],
+ 'Dots removed 1' => [
+ '/wiki/$1',
+ '/x/../wiki/Foo',
+ [ 'title' => 'Foo' ]
+ ],
+ 'Dots removed 2' => [
+ '/wiki/$1',
+ '/./wiki/Foo',
+ [ 'title' => 'Foo' ]
+ ],
+ 'Dots retained 1' => [
+ '/wiki/$1',
+ '/wiki/../wiki/Foo',
+ [ 'title' => '../wiki/Foo' ]
+ ],
+ 'Dots retained 2' => [
+ '/wiki/$1',
+ '/wiki/./Foo',
+ [ 'title' => './Foo' ]
+ ],
+ 'Triple slash' => [
+ '/wiki/$1',
+ '///wiki/Foo',
+ [ 'title' => 'Foo' ]
+ ],
+ // '..' only traverses one slash, see e.g. RFC 3986
+ 'Dots traversing double slash 1' => [
+ '/wiki/$1',
+ '/a//b/../../wiki/Foo',
+ []
+ ],
+ 'Dots traversing double slash 2' => [
+ '/wiki/$1',
+ '/a//b/../../../wiki/Foo',
+ [ 'title' => 'Foo' ]
+ ],
+ ];
+
+ // Make sure the router doesn't break on special characters like $ used in regexp replacements
+ foreach ( [ "$", "$1", "\\", "\\$1" ] as $char ) {
+ $tests["Regexp character $char"] = [
+ "/wiki/$1",
+ "/wiki/$char",
+ [ 'title' => "$char" ]
+ ];
+ }
+
+ $tests += [
+ // Make sure the router handles characters like +&() properly
+ "Special characters" => [
+ "/wiki/$1",
+ "/wiki/Plus+And&Dollar\\Stuff();[]{}*",
+ [ 'title' => "Plus+And&Dollar\\Stuff();[]{}*" ],
+ ],
+
+ // Make sure the router handles unicode characters correctly
+ "Unicode 1" => [
+ "/wiki/$1",
+ "/wiki/Spécial:Modifications_récentes" ,
+ [ 'title' => "Spécial:Modifications_récentes" ],
+ ],
+
+ "Unicode 2" => [
+ "/wiki/$1",
+ "/wiki/Sp%C3%A9cial:Modifications_r%C3%A9centes",
+ [ 'title' => "Spécial:Modifications_récentes" ],
+ ]
+ ];
+
+ // Ensure the router doesn't choke on long paths.
+ $lorem = "Lorem_ipsum_dolor_sit_amet,_consectetur_adipisicing_elit,_sed_do_eiusmod_" .
+ "tempor_incididunt_ut_labore_et_dolore_magna_aliqua._Ut_enim_ad_minim_veniam,_quis_" .
+ "nostrud_exercitation_ullamco_laboris_nisi_ut_aliquip_ex_ea_commodo_consequat._" .
+ "Duis_aute_irure_dolor_in_reprehenderit_in_voluptate_velit_esse_cillum_dolore_" .
+ "eu_fugiat_nulla_pariatur._Excepteur_sint_occaecat_cupidatat_non_proident,_sunt_" .
+ "in_culpa_qui_officia_deserunt_mollit_anim_id_est_laborum.";
+
+ $tests += [
+ "Long path" => [
+ "/wiki/$1",
+ "/wiki/$lorem",
+ [ 'title' => $lorem ]
+ ],
+
+ // Ensure that the php passed site of parameter values are not urldecoded
+ "Pattern urlencoding" => [
+ [ [ 'path' => "/wiki/$1", 'params' => [ 'title' => '%20:$1' ] ] ],
+ "/wiki/Foo",
+ [ 'title' => '%20:Foo' ]
+ ],
+
+ // Ensure that raw parameter values do not have any variable replacements or urldecoding
+ "Raw param value" => [
+ [ [ 'path' => "/wiki/$1", 'params' => [ 'title' => [ 'value' => 'bar%20$1' ] ] ] ],
+ "/wiki/Foo",
+ [ 'title' => 'bar%20$1' ]
+ ]
+ ];
+
+ return $tests;
+ }
+
+ /**
+ * Test path parsing
+ * @dataProvider provideParse
+ */
+ public function testParse( $patterns, $path, $expected ) {
+ $patterns = (array)$patterns;
+
+ $router = new PathRouter;
+ foreach ( $patterns as $pattern ) {
+ if ( is_array( $pattern ) ) {
+ $router->add( $pattern['path'], $pattern['params'] ?? [],
+ $pattern['options'] ?? [] );
+ } else {
+ $router->add( $pattern );
+ }
+ }
+ $matches = $router->parse( $path );
+ $this->assertEquals( $matches, $expected );
+ }
+
+ public static function callbackForTest( &$matches, $data ) {
+ $matches['x'] = $data['$1'];
+ $matches['foo'] = $data['foo'];
+ }
+
+ public static function provideWeight() {
+ return [
+ [ '/Foo', [ 'title' => 'Foo' ] ],
+ [ '/Bar', [ 'ping' => 'pong' ] ],
+ [ '/Baz', [ 'marco' => 'polo' ] ],
+ [ '/asdf-foo', [ 'title' => 'qwerty-foo' ] ],
+ [ '/qwerty-bar', [ 'title' => 'asdf-bar' ] ],
+ [ '/a/Foo', [ 'title' => 'Foo' ] ],
+ [ '/asdf/Foo', [ 'title' => 'Foo' ] ],
+ [ '/qwerty/Foo', [ 'title' => 'Foo', 'qwerty' => 'qwerty' ] ],
+ [ '/baz/Foo', [ 'title' => 'Foo', 'unrestricted' => 'baz' ] ],
+ [ '/y/Foo', [ 'title' => 'Foo', 'restricted-to-y' => 'y' ] ],
+ ];
+ }
+
+ /**
+ * Test to ensure weight of paths is handled correctly
+ * @dataProvider provideWeight
+ */
+ public function testWeight( $path, $expected ) {
+ $router = new PathRouter;
+ $router->addStrict( "/Bar", [ 'ping' => 'pong' ] );
+ $router->add( "/asdf-$1", [ 'title' => 'qwerty-$1' ] );
+ $router->add( "/$1" );
+ $router->add( "/qwerty-$1", [ 'title' => 'asdf-$1' ] );
+ $router->addStrict( "/Baz", [ 'marco' => 'polo' ] );
+ $router->add( "/a/$1" );
+ $router->add( "/asdf/$1" );
+ $router->add( "/$2/$1", [ 'unrestricted' => '$2' ] );
+ $router->add( [ 'qwerty' => "/qwerty/$1" ], [ 'qwerty' => '$key' ] );
+ $router->add( "/$2/$1", [ 'restricted-to-y' => '$2' ], [ '$2' => 'y' ] );
+
+ $this->assertEquals( $router->parse( $path ), $expected );
+ }
+}
--- /dev/null
+<?php
+
+namespace MediaWiki\Tests\Rest;
+
+use ArrayIterator;
+use MediaWiki\Rest\HttpException;
+use MediaWiki\Rest\ResponseFactory;
+use MediaWikiUnitTestCase;
+
+/** @covers \MediaWiki\Rest\ResponseFactory */
+class ResponseFactoryTest extends MediaWikiUnitTestCase {
+ public static function provideEncodeJson() {
+ return [
+ [ (object)[], '{}' ],
+ [ '/', '"/"' ],
+ [ '£', '"£"' ],
+ [ [], '[]' ],
+ ];
+ }
+
+ /** @dataProvider provideEncodeJson */
+ public function testEncodeJson( $input, $expected ) {
+ $rf = new ResponseFactory;
+ $this->assertSame( $expected, $rf->encodeJson( $input ) );
+ }
+
+ public function testCreateJson() {
+ $rf = new ResponseFactory;
+ $response = $rf->createJson( [] );
+ $response->getBody()->rewind();
+ $this->assertSame( 'application/json', $response->getHeaderLine( 'Content-Type' ) );
+ $this->assertSame( '[]', $response->getBody()->getContents() );
+ // Make sure getSize() is functional, since testCreateNoContent() depends on it
+ $this->assertSame( 2, $response->getBody()->getSize() );
+ }
+
+ public function testCreateNoContent() {
+ $rf = new ResponseFactory;
+ $response = $rf->createNoContent();
+ $this->assertSame( [], $response->getHeader( 'Content-Type' ) );
+ $this->assertSame( 0, $response->getBody()->getSize() );
+ $this->assertSame( 204, $response->getStatusCode() );
+ }
+
+ public function testCreatePermanentRedirect() {
+ $rf = new ResponseFactory;
+ $response = $rf->createPermanentRedirect( 'http://www.example.com/' );
+ $this->assertSame( [ 'http://www.example.com/' ], $response->getHeader( 'Location' ) );
+ $this->assertSame( 301, $response->getStatusCode() );
+ }
+
+ public function testCreateLegacyTemporaryRedirect() {
+ $rf = new ResponseFactory;
+ $response = $rf->createLegacyTemporaryRedirect( 'http://www.example.com/' );
+ $this->assertSame( [ 'http://www.example.com/' ], $response->getHeader( 'Location' ) );
+ $this->assertSame( 302, $response->getStatusCode() );
+ }
+
+ public function testCreateTemporaryRedirect() {
+ $rf = new ResponseFactory;
+ $response = $rf->createTemporaryRedirect( 'http://www.example.com/' );
+ $this->assertSame( [ 'http://www.example.com/' ], $response->getHeader( 'Location' ) );
+ $this->assertSame( 307, $response->getStatusCode() );
+ }
+
+ public function testCreateSeeOther() {
+ $rf = new ResponseFactory;
+ $response = $rf->createSeeOther( 'http://www.example.com/' );
+ $this->assertSame( [ 'http://www.example.com/' ], $response->getHeader( 'Location' ) );
+ $this->assertSame( 303, $response->getStatusCode() );
+ }
+
+ public function testCreateNotModified() {
+ $rf = new ResponseFactory;
+ $response = $rf->createNotModified();
+ $this->assertSame( 0, $response->getBody()->getSize() );
+ $this->assertSame( 304, $response->getStatusCode() );
+ }
+
+ /** @expectedException \InvalidArgumentException */
+ public function testCreateHttpErrorInvalid() {
+ $rf = new ResponseFactory;
+ $rf->createHttpError( 200 );
+ }
+
+ public function testCreateHttpError() {
+ $rf = new ResponseFactory;
+ $response = $rf->createHttpError( 415, [ 'message' => '...' ] );
+ $this->assertSame( 415, $response->getStatusCode() );
+ $body = $response->getBody();
+ $body->rewind();
+ $data = json_decode( $body->getContents(), true );
+ $this->assertSame( 415, $data['httpCode'] );
+ $this->assertSame( '...', $data['message'] );
+ }
+
+ public function testCreateFromExceptionUnlogged() {
+ $rf = new ResponseFactory;
+ $response = $rf->createFromException( new HttpException( 'hello', 415 ) );
+ $this->assertSame( 415, $response->getStatusCode() );
+ $body = $response->getBody();
+ $body->rewind();
+ $data = json_decode( $body->getContents(), true );
+ $this->assertSame( 415, $data['httpCode'] );
+ $this->assertSame( 'hello', $data['message'] );
+ }
+
+ public function testCreateFromExceptionLogged() {
+ $rf = new ResponseFactory;
+ $response = $rf->createFromException( new \Exception( "hello", 415 ) );
+ $this->assertSame( 500, $response->getStatusCode() );
+ $body = $response->getBody();
+ $body->rewind();
+ $data = json_decode( $body->getContents(), true );
+ $this->assertSame( 500, $data['httpCode'] );
+ $this->assertSame( 'Error: exception of type Exception', $data['message'] );
+ }
+
+ public static function provideCreateFromReturnValue() {
+ return [
+ [ 'hello', '{"value":"hello"}' ],
+ [ true, '{"value":true}' ],
+ [ [ 'x' => 'y' ], '{"x":"y"}' ],
+ [ [ 'x', 'y' ], '["x","y"]' ],
+ [ [ 'a', 'x' => 'y' ], '{"0":"a","x":"y"}' ],
+ [ (object)[ 'a', 'x' => 'y' ], '{"0":"a","x":"y"}' ],
+ [ [], '[]' ],
+ [ (object)[], '{}' ],
+ ];
+ }
+
+ /** @dataProvider provideCreateFromReturnValue */
+ public function testCreateFromReturnValue( $input, $expected ) {
+ $rf = new ResponseFactory;
+ $response = $rf->createFromReturnValue( $input );
+ $body = $response->getBody();
+ $body->rewind();
+ $this->assertSame( $expected, $body->getContents() );
+ }
+
+ /** @expectedException \InvalidArgumentException */
+ public function testCreateFromReturnValueInvalid() {
+ $rf = new ResponseFactory;
+ $rf->createFromReturnValue( new ArrayIterator );
+ }
+}
--- /dev/null
+<?php
+
+namespace MediaWiki\Tests\Revision;
+
+use MediaWiki\Revision\MainSlotRoleHandler;
+use MediaWikiUnitTestCase;
+use PHPUnit\Framework\MockObject\MockObject;
+use Title;
+
+/**
+ * @covers \MediaWiki\Revision\MainSlotRoleHandler
+ */
+class MainSlotRoleHandlerTest extends MediaWikiUnitTestCase {
+
+ private function makeTitleObject( $ns ) {
+ /** @var Title|MockObject $title */
+ $title = $this->getMockBuilder( Title::class )
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $title->method( 'getNamespace' )
+ ->willReturn( $ns );
+
+ return $title;
+ }
+
+ /**
+ * @covers \MediaWiki\Revision\MainSlotRoleHandler::__construct
+ * @covers \MediaWiki\Revision\MainSlotRoleHandler::getRole()
+ * @covers \MediaWiki\Revision\MainSlotRoleHandler::getNameMessageKey()
+ * @covers \MediaWiki\Revision\MainSlotRoleHandler::getOutputLayoutHints()
+ */
+ public function testConstruction() {
+ $handler = new MainSlotRoleHandler( [] );
+ $this->assertSame( 'main', $handler->getRole() );
+ $this->assertSame( 'slot-name-main', $handler->getNameMessageKey() );
+
+ $hints = $handler->getOutputLayoutHints();
+ $this->assertArrayHasKey( 'display', $hints );
+ $this->assertArrayHasKey( 'region', $hints );
+ $this->assertArrayHasKey( 'placement', $hints );
+ }
+
+ /**
+ * @covers \MediaWiki\Revision\MainSlotRoleHandler::getDefaultModel()
+ */
+ public function testFetDefaultModel() {
+ $handler = new MainSlotRoleHandler( [ 100 => CONTENT_MODEL_TEXT ] );
+
+ // For the main handler, the namespace determins the default model
+ $titleMain = $this->makeTitleObject( NS_MAIN );
+ $this->assertSame( CONTENT_MODEL_WIKITEXT, $handler->getDefaultModel( $titleMain ) );
+
+ $title100 = $this->makeTitleObject( 100 );
+ $this->assertSame( CONTENT_MODEL_TEXT, $handler->getDefaultModel( $title100 ) );
+ }
+
+ /**
+ * @covers \MediaWiki\Revision\MainSlotRoleHandler::isAllowedModel()
+ */
+ public function testIsAllowedModel() {
+ $handler = new MainSlotRoleHandler( [] );
+
+ // For the main handler, (nearly) all models are allowed
+ $title = $this->makeTitleObject( NS_MAIN );
+ $this->assertTrue( $handler->isAllowedModel( CONTENT_MODEL_WIKITEXT, $title ) );
+ $this->assertTrue( $handler->isAllowedModel( CONTENT_MODEL_TEXT, $title ) );
+ }
+
+ /**
+ * @covers \MediaWiki\Revision\MainSlotRoleHandler::supportsArticleCount()
+ */
+ public function testSupportsArticleCount() {
+ $handler = new MainSlotRoleHandler( [] );
+
+ $this->assertTrue( $handler->supportsArticleCount() );
+ }
+
+}
--- /dev/null
+<?php
+
+namespace MediaWiki\Tests\Revision;
+
+use InvalidArgumentException;
+use LogicException;
+use MediaWiki\Revision\IncompleteRevisionException;
+use MediaWiki\Revision\SlotRecord;
+use MediaWiki\Revision\SuppressedDataException;
+use MediaWikiUnitTestCase;
+use WikitextContent;
+
+/**
+ * @covers \MediaWiki\Revision\SlotRecord
+ */
+class SlotRecordTest extends MediaWikiUnitTestCase {
+
+ private function makeRow( $data = [] ) {
+ $data = $data + [
+ 'slot_id' => 1234,
+ 'slot_content_id' => 33,
+ 'content_size' => '5',
+ 'content_sha1' => 'someHash',
+ 'content_address' => 'tt:456',
+ 'model_name' => CONTENT_MODEL_WIKITEXT,
+ 'format_name' => CONTENT_FORMAT_WIKITEXT,
+ 'slot_revision_id' => '2',
+ 'slot_origin' => '1',
+ 'role_name' => 'myRole',
+ ];
+ return (object)$data;
+ }
+
+ public function testCompleteConstruction() {
+ $row = $this->makeRow();
+ $record = new SlotRecord( $row, new WikitextContent( 'A' ) );
+
+ $this->assertTrue( $record->hasAddress() );
+ $this->assertTrue( $record->hasContentId() );
+ $this->assertTrue( $record->hasRevision() );
+ $this->assertTrue( $record->isInherited() );
+ $this->assertSame( 'A', $record->getContent()->getText() );
+ $this->assertSame( 5, $record->getSize() );
+ $this->assertSame( 'someHash', $record->getSha1() );
+ $this->assertSame( CONTENT_MODEL_WIKITEXT, $record->getModel() );
+ $this->assertSame( 2, $record->getRevision() );
+ $this->assertSame( 1, $record->getOrigin() );
+ $this->assertSame( 'tt:456', $record->getAddress() );
+ $this->assertSame( 33, $record->getContentId() );
+ $this->assertSame( CONTENT_FORMAT_WIKITEXT, $record->getFormat() );
+ $this->assertSame( 'myRole', $record->getRole() );
+ }
+
+ public function testConstructionDeferred() {
+ $row = $this->makeRow( [
+ 'content_size' => null, // to be computed
+ 'content_sha1' => null, // to be computed
+ 'format_name' => function () {
+ return CONTENT_FORMAT_WIKITEXT;
+ },
+ 'slot_revision_id' => '2',
+ 'slot_origin' => '2',
+ 'slot_content_id' => function () {
+ return null;
+ },
+ ] );
+
+ $content = function () {
+ return new WikitextContent( 'A' );
+ };
+
+ $record = new SlotRecord( $row, $content );
+
+ $this->assertTrue( $record->hasAddress() );
+ $this->assertTrue( $record->hasRevision() );
+ $this->assertFalse( $record->hasContentId() );
+ $this->assertFalse( $record->isInherited() );
+ $this->assertSame( 'A', $record->getContent()->getText() );
+ $this->assertSame( 1, $record->getSize() );
+ $this->assertNotEmpty( $record->getSha1() );
+ $this->assertSame( CONTENT_MODEL_WIKITEXT, $record->getModel() );
+ $this->assertSame( 2, $record->getRevision() );
+ $this->assertSame( 2, $record->getRevision() );
+ $this->assertSame( 'tt:456', $record->getAddress() );
+ $this->assertSame( CONTENT_FORMAT_WIKITEXT, $record->getFormat() );
+ $this->assertSame( 'myRole', $record->getRole() );
+ }
+
+ public function testNewUnsaved() {
+ $record = SlotRecord::newUnsaved( 'myRole', new WikitextContent( 'A' ) );
+
+ $this->assertFalse( $record->hasAddress() );
+ $this->assertFalse( $record->hasContentId() );
+ $this->assertFalse( $record->hasRevision() );
+ $this->assertFalse( $record->isInherited() );
+ $this->assertFalse( $record->hasOrigin() );
+ $this->assertSame( 'A', $record->getContent()->getText() );
+ $this->assertSame( 1, $record->getSize() );
+ $this->assertNotEmpty( $record->getSha1() );
+ $this->assertSame( CONTENT_MODEL_WIKITEXT, $record->getModel() );
+ $this->assertSame( 'myRole', $record->getRole() );
+ }
+
+ public function provideInvalidConstruction() {
+ yield 'both null' => [ null, null ];
+ yield 'null row' => [ null, new WikitextContent( 'A' ) ];
+ yield 'array row' => [ [], new WikitextContent( 'A' ) ];
+ yield 'empty row' => [ (object)[], new WikitextContent( 'A' ) ];
+ yield 'null content' => [ (object)[], null ];
+ }
+
+ /**
+ * @dataProvider provideInvalidConstruction
+ */
+ public function testInvalidConstruction( $row, $content ) {
+ $this->setExpectedException( InvalidArgumentException::class );
+ new SlotRecord( $row, $content );
+ }
+
+ public function testGetContentId_fails() {
+ $record = SlotRecord::newUnsaved( SlotRecord::MAIN, new WikitextContent( 'A' ) );
+ $this->setExpectedException( IncompleteRevisionException::class );
+
+ $record->getContentId();
+ }
+
+ public function testGetAddress_fails() {
+ $record = SlotRecord::newUnsaved( SlotRecord::MAIN, new WikitextContent( 'A' ) );
+ $this->setExpectedException( IncompleteRevisionException::class );
+
+ $record->getAddress();
+ }
+
+ public function provideIncomplete() {
+ $unsaved = SlotRecord::newUnsaved( SlotRecord::MAIN, new WikitextContent( 'A' ) );
+ yield 'unsaved' => [ $unsaved ];
+
+ $parent = new SlotRecord( $this->makeRow(), new WikitextContent( 'A' ) );
+ $inherited = SlotRecord::newInherited( $parent );
+ yield 'inherited' => [ $inherited ];
+ }
+
+ /**
+ * @dataProvider provideIncomplete
+ */
+ public function testGetRevision_fails( SlotRecord $record ) {
+ $record = SlotRecord::newUnsaved( SlotRecord::MAIN, new WikitextContent( 'A' ) );
+ $this->setExpectedException( IncompleteRevisionException::class );
+
+ $record->getRevision();
+ }
+
+ /**
+ * @dataProvider provideIncomplete
+ */
+ public function testGetOrigin_fails( SlotRecord $record ) {
+ $record = SlotRecord::newUnsaved( SlotRecord::MAIN, new WikitextContent( 'A' ) );
+ $this->setExpectedException( IncompleteRevisionException::class );
+
+ $record->getOrigin();
+ }
+
+ public function provideHashStability() {
+ yield [ '', 'phoiac9h4m842xq45sp7s6u21eteeq1' ];
+ yield [ 'Lorem ipsum', 'hcr5u40uxr81d3nx89nvwzclfz6r9c5' ];
+ }
+
+ /**
+ * @dataProvider provideHashStability
+ */
+ public function testHashStability( $text, $hash ) {
+ // Changing the output of the hash function will break things horribly!
+
+ $this->assertSame( $hash, SlotRecord::base36Sha1( $text ) );
+
+ $record = SlotRecord::newUnsaved( SlotRecord::MAIN, new WikitextContent( $text ) );
+ $this->assertSame( $hash, $record->getSha1() );
+ }
+
+ public function testHashComputed() {
+ $row = $this->makeRow();
+ $row->content_sha1 = '';
+
+ $rec = new SlotRecord( $row, new WikitextContent( 'A' ) );
+ $this->assertNotEmpty( $rec->getSha1() );
+ }
+
+ public function testNewWithSuppressedContent() {
+ $input = new SlotRecord( $this->makeRow(), new WikitextContent( 'A' ) );
+ $output = SlotRecord::newWithSuppressedContent( $input );
+
+ $this->setExpectedException( SuppressedDataException::class );
+ $output->getContent();
+ }
+
+ public function testNewInherited() {
+ $row = $this->makeRow( [ 'slot_revision_id' => 7, 'slot_origin' => 7 ] );
+ $parent = new SlotRecord( $row, new WikitextContent( 'A' ) );
+
+ // This would happen while doing an edit, before saving revision meta-data.
+ $inherited = SlotRecord::newInherited( $parent );
+
+ $this->assertSame( $parent->getContentId(), $inherited->getContentId() );
+ $this->assertSame( $parent->getAddress(), $inherited->getAddress() );
+ $this->assertSame( $parent->getContent(), $inherited->getContent() );
+ $this->assertTrue( $inherited->isInherited() );
+ $this->assertTrue( $inherited->hasOrigin() );
+ $this->assertFalse( $inherited->hasRevision() );
+
+ // make sure we didn't mess with the internal state of $parent
+ $this->assertFalse( $parent->isInherited() );
+ $this->assertSame( 7, $parent->getRevision() );
+
+ // This would happen while doing an edit, after saving the revision meta-data
+ // and content meta-data.
+ $saved = SlotRecord::newSaved(
+ 10,
+ $inherited->getContentId(),
+ $inherited->getAddress(),
+ $inherited
+ );
+ $this->assertSame( $parent->getContentId(), $saved->getContentId() );
+ $this->assertSame( $parent->getAddress(), $saved->getAddress() );
+ $this->assertSame( $parent->getContent(), $saved->getContent() );
+ $this->assertTrue( $saved->isInherited() );
+ $this->assertTrue( $saved->hasRevision() );
+ $this->assertSame( 10, $saved->getRevision() );
+
+ // make sure we didn't mess with the internal state of $parent or $inherited
+ $this->assertSame( 7, $parent->getRevision() );
+ $this->assertFalse( $inherited->hasRevision() );
+ }
+
+ public function testNewSaved() {
+ // This would happen while doing an edit, before saving revision meta-data.
+ $unsaved = SlotRecord::newUnsaved( SlotRecord::MAIN, new WikitextContent( 'A' ) );
+
+ // This would happen while doing an edit, after saving the revision meta-data
+ // and content meta-data.
+ $saved = SlotRecord::newSaved( 10, 20, 'theNewAddress', $unsaved );
+ $this->assertFalse( $saved->isInherited() );
+ $this->assertTrue( $saved->hasOrigin() );
+ $this->assertTrue( $saved->hasRevision() );
+ $this->assertTrue( $saved->hasAddress() );
+ $this->assertTrue( $saved->hasContentId() );
+ $this->assertSame( 'theNewAddress', $saved->getAddress() );
+ $this->assertSame( 20, $saved->getContentId() );
+ $this->assertSame( 'A', $saved->getContent()->getText() );
+ $this->assertSame( 10, $saved->getRevision() );
+ $this->assertSame( 10, $saved->getOrigin() );
+
+ // make sure we didn't mess with the internal state of $unsaved
+ $this->assertFalse( $unsaved->hasAddress() );
+ $this->assertFalse( $unsaved->hasContentId() );
+ $this->assertFalse( $unsaved->hasRevision() );
+ }
+
+ public function provideNewSaved_LogicException() {
+ $freshRow = $this->makeRow( [
+ 'content_id' => 10,
+ 'content_address' => 'address:1',
+ 'slot_origin' => 1,
+ 'slot_revision_id' => 1,
+ ] );
+
+ $freshSlot = new SlotRecord( $freshRow, new WikitextContent( 'A' ) );
+ yield 'mismatching address' => [ 1, 10, 'address:BAD', $freshSlot ];
+ yield 'mismatching revision' => [ 5, 10, 'address:1', $freshSlot ];
+ yield 'mismatching content ID' => [ 1, 17, 'address:1', $freshSlot ];
+
+ $inheritedRow = $this->makeRow( [
+ 'content_id' => null,
+ 'content_address' => null,
+ 'slot_origin' => 0,
+ 'slot_revision_id' => 1,
+ ] );
+
+ $inheritedSlot = new SlotRecord( $inheritedRow, new WikitextContent( 'A' ) );
+ yield 'inherited, but no address' => [ 1, 10, 'address:2', $inheritedSlot ];
+ }
+
+ /**
+ * @dataProvider provideNewSaved_LogicException
+ */
+ public function testNewSaved_LogicException(
+ $revisionId,
+ $contentId,
+ $contentAddress,
+ SlotRecord $protoSlot
+ ) {
+ $this->setExpectedException( LogicException::class );
+ SlotRecord::newSaved( $revisionId, $contentId, $contentAddress, $protoSlot );
+ }
+
+ public function provideNewSaved_InvalidArgumentException() {
+ $unsaved = SlotRecord::newUnsaved( SlotRecord::MAIN, new WikitextContent( 'A' ) );
+
+ yield 'bad revision id' => [ 'xyzzy', 5, 'address', $unsaved ];
+ yield 'bad content id' => [ 7, 'xyzzy', 'address', $unsaved ];
+ yield 'bad content address' => [ 7, 5, 77, $unsaved ];
+ }
+
+ /**
+ * @dataProvider provideNewSaved_InvalidArgumentException
+ */
+ public function testNewSaved_InvalidArgumentException(
+ $revisionId,
+ $contentId,
+ $contentAddress,
+ SlotRecord $protoSlot
+ ) {
+ $this->setExpectedException( InvalidArgumentException::class );
+ SlotRecord::newSaved( $revisionId, $contentId, $contentAddress, $protoSlot );
+ }
+
+ public function provideHasSameContent() {
+ $fail = function () {
+ self::fail( 'There should be no need to actually load the content.' );
+ };
+
+ $a100a1 = new SlotRecord(
+ $this->makeRow(
+ [
+ 'model_name' => 'A',
+ 'content_size' => 100,
+ 'content_sha1' => 'hash-a',
+ 'content_address' => 'xxx:a1',
+ ]
+ ),
+ $fail
+ );
+ $a100a1b = new SlotRecord(
+ $this->makeRow(
+ [
+ 'model_name' => 'A',
+ 'content_size' => 100,
+ 'content_sha1' => 'hash-a',
+ 'content_address' => 'xxx:a1',
+ ]
+ ),
+ $fail
+ );
+ $a100null = new SlotRecord(
+ $this->makeRow(
+ [
+ 'model_name' => 'A',
+ 'content_size' => 100,
+ 'content_sha1' => 'hash-a',
+ 'content_address' => null,
+ ]
+ ),
+ $fail
+ );
+ $a100a2 = new SlotRecord(
+ $this->makeRow(
+ [
+ 'model_name' => 'A',
+ 'content_size' => 100,
+ 'content_sha1' => 'hash-a',
+ 'content_address' => 'xxx:a2',
+ ]
+ ),
+ $fail
+ );
+ $b100a1 = new SlotRecord(
+ $this->makeRow(
+ [
+ 'model_name' => 'B',
+ 'content_size' => 100,
+ 'content_sha1' => 'hash-a',
+ 'content_address' => 'xxx:a1',
+ ]
+ ),
+ $fail
+ );
+ $a200a1 = new SlotRecord(
+ $this->makeRow(
+ [
+ 'model_name' => 'A',
+ 'content_size' => 200,
+ 'content_sha1' => 'hash-a',
+ 'content_address' => 'xxx:a2',
+ ]
+ ),
+ $fail
+ );
+ $a100x1 = new SlotRecord(
+ $this->makeRow(
+ [
+ 'model_name' => 'A',
+ 'content_size' => 100,
+ 'content_sha1' => 'hash-x',
+ 'content_address' => 'xxx:x1',
+ ]
+ ),
+ $fail
+ );
+
+ yield 'same instance' => [ $a100a1, $a100a1, true ];
+ yield 'no address' => [ $a100a1, $a100null, true ];
+ yield 'same address' => [ $a100a1, $a100a1b, true ];
+ yield 'different address' => [ $a100a1, $a100a2, true ];
+ yield 'different model' => [ $a100a1, $b100a1, false ];
+ yield 'different size' => [ $a100a1, $a200a1, false ];
+ yield 'different hash' => [ $a100a1, $a100x1, false ];
+ }
+
+ /**
+ * @dataProvider provideHasSameContent
+ */
+ public function testHasSameContent( SlotRecord $a, SlotRecord $b, $sameContent ) {
+ $this->assertSame( $sameContent, $a->hasSameContent( $b ) );
+ $this->assertSame( $sameContent, $b->hasSameContent( $a ) );
+ }
+
+}
--- /dev/null
+<?php
+
+/**
+ * @author Addshore
+ * @covers TitleArrayFromResult
+ */
+class TitleArrayFromResultTest extends MediaWikiUnitTestCase {
+
+ private function getMockResultWrapper( $row = null, $numRows = 1 ) {
+ $resultWrapper = $this->getMockBuilder( Wikimedia\Rdbms\ResultWrapper::class )
+ ->disableOriginalConstructor();
+
+ $resultWrapper = $resultWrapper->getMock();
+ $resultWrapper->expects( $this->atLeastOnce() )
+ ->method( 'current' )
+ ->will( $this->returnValue( $row ) );
+ $resultWrapper->expects( $this->any() )
+ ->method( 'numRows' )
+ ->will( $this->returnValue( $numRows ) );
+
+ return $resultWrapper;
+ }
+
+ private function getRowWithTitle( $namespace = 3, $title = 'foo' ) {
+ $row = new stdClass();
+ $row->page_namespace = $namespace;
+ $row->page_title = $title;
+ return $row;
+ }
+
+ /**
+ * @covers TitleArrayFromResult::__construct
+ */
+ public function testConstructionWithFalseRow() {
+ $row = false;
+ $resultWrapper = $this->getMockResultWrapper( $row );
+
+ $object = new TitleArrayFromResult( $resultWrapper );
+
+ $this->assertEquals( $resultWrapper, $object->res );
+ $this->assertSame( 0, $object->key );
+ $this->assertEquals( $row, $object->current );
+ }
+
+ /**
+ * @covers TitleArrayFromResult::__construct
+ */
+ public function testConstructionWithRow() {
+ $namespace = 0;
+ $title = 'foo';
+ $row = $this->getRowWithTitle( $namespace, $title );
+ $resultWrapper = $this->getMockResultWrapper( $row );
+
+ $object = new TitleArrayFromResult( $resultWrapper );
+
+ $this->assertEquals( $resultWrapper, $object->res );
+ $this->assertSame( 0, $object->key );
+ $this->assertInstanceOf( Title::class, $object->current );
+ $this->assertEquals( $namespace, $object->current->mNamespace );
+ $this->assertEquals( $title, $object->current->mTextform );
+ }
+
+ public static function provideNumberOfRows() {
+ return [
+ [ 0 ],
+ [ 1 ],
+ [ 122 ],
+ ];
+ }
+
+ /**
+ * @dataProvider provideNumberOfRows
+ * @covers TitleArrayFromResult::count
+ */
+ public function testCountWithVaryingValues( $numRows ) {
+ $object = new TitleArrayFromResult( $this->getMockResultWrapper(
+ $this->getRowWithTitle(),
+ $numRows
+ ) );
+ $this->assertEquals( $numRows, $object->count() );
+ }
+
+ /**
+ * @covers TitleArrayFromResult::current
+ */
+ public function testCurrentAfterConstruction() {
+ $namespace = 0;
+ $title = 'foo';
+ $row = $this->getRowWithTitle( $namespace, $title );
+ $object = new TitleArrayFromResult( $this->getMockResultWrapper( $row ) );
+ $this->assertInstanceOf( Title::class, $object->current() );
+ $this->assertEquals( $namespace, $object->current->mNamespace );
+ $this->assertEquals( $title, $object->current->mTextform );
+ }
+
+ public function provideTestValid() {
+ return [
+ [ $this->getRowWithTitle(), true ],
+ [ false, false ],
+ ];
+ }
+
+ /**
+ * @dataProvider provideTestValid
+ * @covers TitleArrayFromResult::valid
+ */
+ public function testValid( $input, $expected ) {
+ $object = new TitleArrayFromResult( $this->getMockResultWrapper( $input ) );
+ $this->assertEquals( $expected, $object->valid() );
+ }
+
+ // @todo unit test for key()
+ // @todo unit test for next()
+ // @todo unit test for rewind()
+}
--- /dev/null
+<?php
+
+/**
+ * @covers WikiReference
+ */
+class WikiReferenceTest extends MediaWikiUnitTestCase {
+
+ public function provideGetDisplayName() {
+ return [
+ 'http' => [ 'foo.bar', 'http://foo.bar' ],
+ 'https' => [ 'foo.bar', 'http://foo.bar' ],
+
+ // apparently, this is the expected behavior
+ 'invalid' => [ 'purple kittens', 'purple kittens' ],
+ ];
+ }
+
+ /**
+ * @dataProvider provideGetDisplayName
+ */
+ public function testGetDisplayName( $expected, $canonicalServer ) {
+ $reference = new WikiReference( $canonicalServer, '/wiki/$1' );
+ $this->assertEquals( $expected, $reference->getDisplayName() );
+ }
+
+ public function testGetCanonicalServer() {
+ $reference = new WikiReference( 'https://acme.com', '/wiki/$1', '//acme.com' );
+ $this->assertEquals( 'https://acme.com', $reference->getCanonicalServer() );
+ }
+
+ public function provideGetCanonicalUrl() {
+ return [
+ 'no fragment' => [
+ 'https://acme.com/wiki/Foo',
+ 'https://acme.com',
+ '//acme.com',
+ '/wiki/$1',
+ 'Foo',
+ null
+ ],
+ 'empty fragment' => [
+ 'https://acme.com/wiki/Foo',
+ 'https://acme.com',
+ '//acme.com',
+ '/wiki/$1',
+ 'Foo',
+ ''
+ ],
+ 'fragment' => [
+ 'https://acme.com/wiki/Foo#Bar',
+ 'https://acme.com',
+ '//acme.com',
+ '/wiki/$1',
+ 'Foo',
+ 'Bar'
+ ],
+ 'double fragment' => [
+ 'https://acme.com/wiki/Foo#Bar%23Xus',
+ 'https://acme.com',
+ '//acme.com',
+ '/wiki/$1',
+ 'Foo',
+ 'Bar#Xus'
+ ],
+ 'escaped fragment' => [
+ 'https://acme.com/wiki/Foo%23Bar',
+ 'https://acme.com',
+ '//acme.com',
+ '/wiki/$1',
+ 'Foo#Bar',
+ null
+ ],
+ 'empty path' => [
+ 'https://acme.com/Foo',
+ 'https://acme.com',
+ '//acme.com',
+ '/$1',
+ 'Foo',
+ null
+ ],
+ ];
+ }
+
+ /**
+ * @dataProvider provideGetCanonicalUrl
+ */
+ public function testGetCanonicalUrl(
+ $expected, $canonicalServer, $server, $path, $page, $fragmentId
+ ) {
+ $reference = new WikiReference( $canonicalServer, $path, $server );
+ $this->assertEquals( $expected, $reference->getCanonicalUrl( $page, $fragmentId ) );
+ }
+
+ /**
+ * @dataProvider provideGetCanonicalUrl
+ * @note getUrl is an alias for getCanonicalUrl
+ */
+ public function testGetUrl( $expected, $canonicalServer, $server, $path, $page, $fragmentId ) {
+ $reference = new WikiReference( $canonicalServer, $path, $server );
+ $this->assertEquals( $expected, $reference->getUrl( $page, $fragmentId ) );
+ }
+
+ public function provideGetFullUrl() {
+ return [
+ 'no fragment' => [
+ '//acme.com/wiki/Foo',
+ 'https://acme.com',
+ '//acme.com',
+ '/wiki/$1',
+ 'Foo',
+ null
+ ],
+ 'empty fragment' => [
+ '//acme.com/wiki/Foo',
+ 'https://acme.com',
+ '//acme.com',
+ '/wiki/$1',
+ 'Foo',
+ ''
+ ],
+ 'fragment' => [
+ '//acme.com/wiki/Foo#Bar',
+ 'https://acme.com',
+ '//acme.com',
+ '/wiki/$1',
+ 'Foo',
+ 'Bar'
+ ],
+ 'double fragment' => [
+ '//acme.com/wiki/Foo#Bar%23Xus',
+ 'https://acme.com',
+ '//acme.com',
+ '/wiki/$1',
+ 'Foo',
+ 'Bar#Xus'
+ ],
+ 'escaped fragment' => [
+ '//acme.com/wiki/Foo%23Bar',
+ 'https://acme.com',
+ '//acme.com',
+ '/wiki/$1',
+ 'Foo#Bar',
+ null
+ ],
+ 'empty path' => [
+ '//acme.com/Foo',
+ 'https://acme.com',
+ '//acme.com',
+ '/$1',
+ 'Foo',
+ null
+ ],
+ ];
+ }
+
+ /**
+ * @dataProvider provideGetFullUrl
+ */
+ public function testGetFullUrl( $expected, $canonicalServer, $server, $path, $page, $fragmentId ) {
+ $reference = new WikiReference( $canonicalServer, $path, $server );
+ $this->assertEquals( $expected, $reference->getFullUrl( $page, $fragmentId ) );
+ }
+
+}
--- /dev/null
+<?php
+
+namespace MediaWiki\Logger\Monolog;
+
+/**
+ * Flay per https://phabricator.wikimedia.org/T218688.
+ *
+ * @group Broken
+ * @covers \MediaWiki\Logger\Monolog\CeeFormatter
+ */
+class CeeFormatterTest extends \MediaWikiUnitTestCase {
+ public function testV1() {
+ $ls_formatter = new LogstashFormatter( 'app', 'system', null, 'ctx_', LogstashFormatter::V1 );
+ $cee_formatter = new CeeFormatter( 'app', 'system', null, 'ctx_', LogstashFormatter::V1 );
+ $record = [ 'extra' => [ 'url' => 1 ], 'context' => [ 'url' => 2 ] ];
+ $this->assertSame(
+ $cee_formatter->format( $record ),
+ "@cee: " . $ls_formatter->format( $record ) );
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * @covers DifferenceEngineSlotDiffRenderer
+ */
+class DifferenceEngineSlotDiffRendererTest extends \MediaWikiUnitTestCase {
+
+ public function testGetDiff() {
+ $differenceEngine = new CustomDifferenceEngine();
+ $slotDiffRenderer = new DifferenceEngineSlotDiffRenderer( $differenceEngine );
+ $oldContent = ContentHandler::makeContent( 'xxx', null, CONTENT_MODEL_TEXT );
+ $newContent = ContentHandler::makeContent( 'yyy', null, CONTENT_MODEL_TEXT );
+
+ $diff = $slotDiffRenderer->getDiff( $oldContent, $newContent );
+ $this->assertEquals( 'xxx|yyy', $diff );
+
+ $diff = $slotDiffRenderer->getDiff( null, $newContent );
+ $this->assertEquals( '|yyy', $diff );
+
+ $diff = $slotDiffRenderer->getDiff( $oldContent, null );
+ $this->assertEquals( 'xxx|', $diff );
+ }
+
+ public function testAddModules() {
+ $output = $this->getMockBuilder( OutputPage::class )
+ ->disableOriginalConstructor()
+ ->setMethods( [ 'addModules' ] )
+ ->getMock();
+ $output->expects( $this->once() )
+ ->method( 'addModules' )
+ ->with( 'foo' );
+ $differenceEngine = new CustomDifferenceEngine();
+ $slotDiffRenderer = new DifferenceEngineSlotDiffRenderer( $differenceEngine );
+ $slotDiffRenderer->addModules( $output );
+ }
+
+ public function testGetExtraCacheKeys() {
+ $differenceEngine = new CustomDifferenceEngine();
+ $slotDiffRenderer = new DifferenceEngineSlotDiffRenderer( $differenceEngine );
+ $extraCacheKeys = $slotDiffRenderer->getExtraCacheKeys();
+ $this->assertSame( [ 'foo' ], $extraCacheKeys );
+ }
+
+}
--- /dev/null
+<?php
+
+use Wikimedia\Assert\ParameterTypeException;
+use Wikimedia\TestingAccessWrapper;
+
+/**
+ * @covers SlotDiffRenderer
+ */
+class SlotDiffRendererTest extends \MediaWikiUnitTestCase {
+
+ /**
+ * @dataProvider provideNormalizeContents
+ */
+ public function testNormalizeContents(
+ $oldContent, $newContent, $allowedClasses,
+ $expectedOldContent, $expectedNewContent, $expectedExceptionClass
+ ) {
+ $slotDiffRenderer = $this->getMockBuilder( SlotDiffRenderer::class )
+ ->getMock();
+ try {
+ // __call needs help deciding which parameter to take by reference
+ call_user_func_array( [ TestingAccessWrapper::newFromObject( $slotDiffRenderer ),
+ 'normalizeContents' ], [ &$oldContent, &$newContent, $allowedClasses ] );
+ $this->assertEquals( $expectedOldContent, $oldContent );
+ $this->assertEquals( $expectedNewContent, $newContent );
+ } catch ( Exception $e ) {
+ if ( !$expectedExceptionClass ) {
+ throw $e;
+ }
+ $this->assertInstanceOf( $expectedExceptionClass, $e );
+ }
+ }
+
+ public function provideNormalizeContents() {
+ return [
+ 'both null' => [ null, null, null, null, null, InvalidArgumentException::class ],
+ 'left null' => [
+ null, new WikitextContent( 'abc' ), null,
+ new WikitextContent( '' ), new WikitextContent( 'abc' ), null,
+ ],
+ 'right null' => [
+ new WikitextContent( 'def' ), null, null,
+ new WikitextContent( 'def' ), new WikitextContent( '' ), null,
+ ],
+ 'type filter' => [
+ new WikitextContent( 'abc' ), new WikitextContent( 'def' ), WikitextContent::class,
+ new WikitextContent( 'abc' ), new WikitextContent( 'def' ), null,
+ ],
+ 'type filter (subclass)' => [
+ new WikitextContent( 'abc' ), new WikitextContent( 'def' ), TextContent::class,
+ new WikitextContent( 'abc' ), new WikitextContent( 'def' ), null,
+ ],
+ 'type filter (null)' => [
+ new WikitextContent( 'abc' ), null, TextContent::class,
+ new WikitextContent( 'abc' ), new WikitextContent( '' ), null,
+ ],
+ 'type filter failure (left)' => [
+ new TextContent( 'abc' ), new WikitextContent( 'def' ), WikitextContent::class,
+ null, null, ParameterTypeException::class,
+ ],
+ 'type filter failure (right)' => [
+ new WikitextContent( 'abc' ), new TextContent( 'def' ), WikitextContent::class,
+ null, null, ParameterTypeException::class,
+ ],
+ 'type filter (array syntax)' => [
+ new WikitextContent( 'abc' ), new JsonContent( 'def' ),
+ [ JsonContent::class, WikitextContent::class ],
+ new WikitextContent( 'abc' ), new JsonContent( 'def' ), null,
+ ],
+ 'type filter failure (array syntax)' => [
+ new WikitextContent( 'abc' ), new CssContent( 'def' ),
+ [ JsonContent::class, WikitextContent::class ],
+ null, null, ParameterTypeException::class,
+ ],
+ ];
+ }
+
+}
--- /dev/null
+<?php
+
+class FileBackendDBRepoWrapperTest extends MediaWikiUnitTestCase {
+ protected $backendName = 'foo-backend';
+ protected $repoName = 'pureTestRepo';
+
+ /**
+ * @dataProvider getBackendPathsProvider
+ * @covers FileBackendDBRepoWrapper::getBackendPaths
+ */
+ public function testGetBackendPaths(
+ $mocks,
+ $latest,
+ $dbReadsExpected,
+ $dbReturnValue,
+ $originalPath,
+ $expectedBackendPath,
+ $message ) {
+ list( $dbMock, $backendMock, $wrapperMock ) = $mocks;
+
+ $dbMock->expects( $dbReadsExpected )
+ ->method( 'selectField' )
+ ->will( $this->returnValue( $dbReturnValue ) );
+
+ $newPaths = $wrapperMock->getBackendPaths( [ $originalPath ], $latest );
+
+ $this->assertEquals(
+ $expectedBackendPath,
+ $newPaths[0],
+ $message );
+ }
+
+ public function getBackendPathsProvider() {
+ $prefix = 'mwstore://' . $this->backendName . '/' . $this->repoName;
+ $mocksForCaching = $this->getMocks();
+
+ return [
+ [
+ $mocksForCaching,
+ false,
+ $this->once(),
+ '96246614d75ba1703bdfd5d7660bb57407aaf5d9',
+ $prefix . '-public/f/o/foobar.jpg',
+ $prefix . '-original/9/6/2/96246614d75ba1703bdfd5d7660bb57407aaf5d9',
+ 'Public path translated correctly',
+ ],
+ [
+ $mocksForCaching,
+ false,
+ $this->never(),
+ '96246614d75ba1703bdfd5d7660bb57407aaf5d9',
+ $prefix . '-public/f/o/foobar.jpg',
+ $prefix . '-original/9/6/2/96246614d75ba1703bdfd5d7660bb57407aaf5d9',
+ 'LRU cache leveraged',
+ ],
+ [
+ $this->getMocks(),
+ true,
+ $this->once(),
+ '96246614d75ba1703bdfd5d7660bb57407aaf5d9',
+ $prefix . '-public/f/o/foobar.jpg',
+ $prefix . '-original/9/6/2/96246614d75ba1703bdfd5d7660bb57407aaf5d9',
+ 'Latest obtained',
+ ],
+ [
+ $this->getMocks(),
+ true,
+ $this->never(),
+ '96246614d75ba1703bdfd5d7660bb57407aaf5d9',
+ $prefix . '-deleted/f/o/foobar.jpg',
+ $prefix . '-original/f/o/o/foobar',
+ 'Deleted path translated correctly',
+ ],
+ [
+ $this->getMocks(),
+ true,
+ $this->once(),
+ null,
+ $prefix . '-public/b/a/baz.jpg',
+ $prefix . '-public/b/a/baz.jpg',
+ 'Path left untouched if no sha1 can be found',
+ ],
+ ];
+ }
+
+ /**
+ * @covers FileBackendDBRepoWrapper::getFileContentsMulti
+ */
+ public function testGetFileContentsMulti() {
+ list( $dbMock, $backendMock, $wrapperMock ) = $this->getMocks();
+
+ $sha1Path = 'mwstore://' . $this->backendName . '/' . $this->repoName
+ . '-original/9/6/2/96246614d75ba1703bdfd5d7660bb57407aaf5d9';
+ $filenamePath = 'mwstore://' . $this->backendName . '/' . $this->repoName
+ . '-public/f/o/foobar.jpg';
+
+ $dbMock->expects( $this->once() )
+ ->method( 'selectField' )
+ ->will( $this->returnValue( '96246614d75ba1703bdfd5d7660bb57407aaf5d9' ) );
+
+ $backendMock->expects( $this->once() )
+ ->method( 'getFileContentsMulti' )
+ ->will( $this->returnValue( [ $sha1Path => 'foo' ] ) );
+
+ $result = $wrapperMock->getFileContentsMulti( [ 'srcs' => [ $filenamePath ] ] );
+
+ $this->assertEquals(
+ [ $filenamePath => 'foo' ],
+ $result,
+ 'File contents paths translated properly'
+ );
+ }
+
+ protected function getMocks() {
+ $dbMock = $this->getMockBuilder( Wikimedia\Rdbms\IDatabase::class )
+ ->disableOriginalClone()
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $backendMock = $this->getMockBuilder( FSFileBackend::class )
+ ->setConstructorArgs( [ [
+ 'name' => $this->backendName,
+ 'wikiId' => wfWikiID()
+ ] ] )
+ ->getMock();
+
+ $wrapperMock = $this->getMockBuilder( FileBackendDBRepoWrapper::class )
+ ->setMethods( [ 'getDB' ] )
+ ->setConstructorArgs( [ [
+ 'backend' => $backendMock,
+ 'repoName' => $this->repoName,
+ 'dbHandleFactory' => null
+ ] ] )
+ ->getMock();
+
+ $wrapperMock->expects( $this->any() )->method( 'getDB' )->will( $this->returnValue( $dbMock ) );
+
+ return [ $dbMock, $backendMock, $wrapperMock ];
+ }
+}
--- /dev/null
+<?php
+
+/** @covers ForeignDBFile */
+class ForeignDBFileTest extends \MediaWikiUnitTestCase {
+
+ public function testShouldConstructCorrectInstanceFromTitle() {
+ $title = Title::makeTitle( NS_FILE, 'Awesome_file' );
+ $repoMock = $this->createMock( LocalRepo::class );
+
+ $file = ForeignDBFile::newFromTitle( $title, $repoMock );
+
+ $this->assertInstanceOf( ForeignDBFile::class, $file );
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * @covers HTMLCheckMatrix
+ */
+class HTMLCheckMatrixTest extends MediaWikiUnitTestCase {
+ private static $defaultOptions = [
+ 'rows' => [ 'r1', 'r2' ],
+ 'columns' => [ 'c1', 'c2' ],
+ 'fieldname' => 'test',
+ ];
+
+ public function testPlainInstantiation() {
+ try {
+ new HTMLCheckMatrix( [] );
+ } catch ( MWException $e ) {
+ $this->assertInstanceOf( HTMLFormFieldRequiredOptionsException::class, $e );
+ return;
+ }
+
+ $this->fail( 'Expected MWException indicating missing parameters but none was thrown.' );
+ }
+
+ public function testInstantiationWithMinimumRequiredParameters() {
+ new HTMLCheckMatrix( self::$defaultOptions );
+ $this->assertTrue( true ); // form instantiation must throw exception on failure
+ }
+
+ public function testValidateCallsUserDefinedValidationCallback() {
+ $called = false;
+ $field = new HTMLCheckMatrix( self::$defaultOptions + [
+ 'validation-callback' => function () use ( &$called ) {
+ $called = true;
+
+ return false;
+ },
+ ] );
+ $this->assertEquals( false, $this->validate( $field, [] ) );
+ $this->assertTrue( $called );
+ }
+
+ public function testValidateRequiresArrayInput() {
+ $field = new HTMLCheckMatrix( self::$defaultOptions );
+ $this->assertEquals( false, $this->validate( $field, null ) );
+ $this->assertEquals( false, $this->validate( $field, true ) );
+ $this->assertEquals( false, $this->validate( $field, 'abc' ) );
+ $this->assertEquals( false, $this->validate( $field, new stdClass ) );
+ $this->assertEquals( true, $this->validate( $field, [] ) );
+ }
+
+ public function testValidateAllowsOnlyKnownTags() {
+ $field = new HTMLCheckMatrix( self::$defaultOptions );
+ $this->assertInstanceOf( Message::class, $this->validate( $field, [ 'foo' ] ) );
+ }
+
+ public function testValidateAcceptsPartialTagList() {
+ $field = new HTMLCheckMatrix( self::$defaultOptions );
+ $this->assertTrue( $this->validate( $field, [] ) );
+ $this->assertTrue( $this->validate( $field, [ 'c1-r1' ] ) );
+ $this->assertTrue( $this->validate( $field, [ 'c1-r1', 'c1-r2', 'c2-r1', 'c2-r2' ] ) );
+ }
+
+ /**
+ * This form object actually has no visibility into what happens later on, but essentially
+ * if the data submitted by the user passes validate the following is run:
+ * foreach ( $field->filterDataForSubmit( $data ) as $k => $v ) {
+ * $user->setOption( $k, $v );
+ * }
+ */
+ public function testValuesForcedOnRemainOn() {
+ $field = new HTMLCheckMatrix( self::$defaultOptions + [
+ 'force-options-on' => [ 'c2-r1' ],
+ ] );
+ $expected = [
+ 'c1-r1' => false,
+ 'c1-r2' => false,
+ 'c2-r1' => true,
+ 'c2-r2' => false,
+ ];
+ $this->assertEquals( $expected, $field->filterDataForSubmit( [] ) );
+ }
+
+ public function testValuesForcedOffRemainOff() {
+ $field = new HTMLCheckMatrix( self::$defaultOptions + [
+ 'force-options-off' => [ 'c1-r2', 'c2-r2' ],
+ ] );
+ $expected = [
+ 'c1-r1' => true,
+ 'c1-r2' => false,
+ 'c2-r1' => true,
+ 'c2-r2' => false,
+ ];
+ // array_keys on the result simulates submitting all fields checked
+ $this->assertEquals( $expected, $field->filterDataForSubmit( array_keys( $expected ) ) );
+ }
+
+ protected function validate( HTMLFormField $field, $submitted ) {
+ return $field->validate(
+ $submitted,
+ [ self::$defaultOptions['fieldname'] => $submitted ]
+ );
+ }
+
+}
--- /dev/null
+<?php
+
+/**
+ * @covers Http
+ * @group Http
+ * @group small
+ */
+class HttpUnitTest extends MediaWikiUnitTestCase {
+
+ /**
+ * Test Http::isValidURI()
+ * T29854 : Http::isValidURI is too lax
+ * @dataProvider provideURI
+ * @covers Http::isValidURI
+ */
+ public function testIsValidUri( $expect, $URI, $message = '' ) {
+ $this->assertEquals(
+ $expect,
+ (bool)Http::isValidURI( $URI ),
+ $message
+ );
+ }
+
+ /**
+ * Feeds URI to test a long regular expression in Http::isValidURI
+ */
+ public static function provideURI() {
+ /** Format: 'boolean expectation', 'URI to test', 'Optional message' */
+ return [
+ [ false, '¿non sens before!! http://a', 'Allow anything before URI' ],
+
+ # (http|https) - only two schemes allowed
+ [ true, 'http://www.example.org/' ],
+ [ true, 'https://www.example.org/' ],
+ [ true, 'http://www.example.org', 'URI without directory' ],
+ [ true, 'http://a', 'Short name' ],
+ [ true, 'http://étoile', 'Allow UTF-8 in hostname' ], # 'étoile' is french for 'star'
+ [ false, '\\host\directory', 'CIFS share' ],
+ [ false, 'gopher://host/dir', 'Reject gopher scheme' ],
+ [ false, 'telnet://host', 'Reject telnet scheme' ],
+
+ # :\/\/ - double slashes
+ [ false, 'http//example.org', 'Reject missing colon in protocol' ],
+ [ false, 'http:/example.org', 'Reject missing slash in protocol' ],
+ [ false, 'http:example.org', 'Must have two slashes' ],
+ # Following fail since hostname can be made of anything
+ [ false, 'http:///example.org', 'Must have exactly two slashes, not three' ],
+
+ # (\w+:{0,1}\w*@)? - optional user:pass
+ [ true, 'http://user@host', 'Username provided' ],
+ [ true, 'http://user:@host', 'Username provided, no password' ],
+ [ true, 'http://user:pass@host', 'Username and password provided' ],
+
+ # (\S+) - host part is made of anything not whitespaces
+ // commented these out in order to remove @group Broken
+ // @todo are these valid tests? if so, fix Http::isValidURI so it can handle them
+ // [ false, 'http://!"èèè¿¿¿~~\'', 'hostname is made of any non whitespace' ],
+ // [ false, 'http://exam:ple.org/', 'hostname can not use colons!' ],
+
+ # (:[0-9]+)? - port number
+ [ true, 'http://example.org:80/' ],
+ [ true, 'https://example.org:80/' ],
+ [ true, 'http://example.org:443/' ],
+ [ true, 'https://example.org:443/' ],
+
+ # Part after the hostname is / or / with something else
+ [ true, 'http://example/#' ],
+ [ true, 'http://example/!' ],
+ [ true, 'http://example/:' ],
+ [ true, 'http://example/.' ],
+ [ true, 'http://example/?' ],
+ [ true, 'http://example/+' ],
+ [ true, 'http://example/=' ],
+ [ true, 'http://example/&' ],
+ [ true, 'http://example/%' ],
+ [ true, 'http://example/@' ],
+ [ true, 'http://example/-' ],
+ [ true, 'http://example//' ],
+ [ true, 'http://example/&' ],
+
+ # Fragment
+ [ true, 'http://exam#ple.org', ], # This one is valid, really!
+ [ true, 'http://example.org:80#anchor' ],
+ [ true, 'http://example.org/?id#anchor' ],
+ [ true, 'http://example.org/?#anchor' ],
+
+ [ false, 'http://a ¿non !!sens after', 'Allow anything after URI' ],
+ ];
+ }
+
+}
--- /dev/null
+<?php
+
+/**
+ * @covers FormatJson
+ */
+class FormatJsonTest extends MediaWikiUnitTestCase {
+
+ /**
+ * Test data for testParseTryFixing.
+ *
+ * Some PHP interpreters use json-c rather than the JSON.org canonical
+ * parser to avoid being encumbered by the "shall be used for Good, not
+ * Evil" clause of the JSON.org parser's license. By default, json-c
+ * parses in a non-strict mode which allows trailing commas for array and
+ * object delarations among other things, so our JSON_ERROR_SYNTAX rescue
+ * block is not always triggered. It however isn't lenient in exactly the
+ * same ways as our TRY_FIXING mode, so the assertions in this test are
+ * a bit more complicated than they ideally would be:
+ *
+ * Optional third argument: true if json-c parses the value without
+ * intervention, false otherwise. Defaults to true.
+ *
+ * Optional fourth argument: expected cannonical JSON serialization of
+ * json-c parsed result. Defaults to the second argument's value.
+ */
+ public static function provideParseTryFixing() {
+ return [
+ [ "[,]", '[]', false ],
+ [ "[ , ]", '[]', false ],
+ [ "[ , }", false ],
+ [ '[1],', false, true, '[1]' ],
+ [ "[1,]", '[1]' ],
+ [ "[1\n,]", '[1]' ],
+ [ "[1,\n]", '[1]' ],
+ [ "[1,]\n", '[1]' ],
+ [ "[1\n,\n]\n", '[1]' ],
+ [ '["a,",]', '["a,"]' ],
+ [ "[[1,]\n,[2,\n],[3\n,]]", '[[1],[2],[3]]' ],
+ // I wish we could parse this, but would need quote parsing
+ [ '[[1,],[2,],[3,]]', false, true, '[[1],[2],[3]]' ],
+ [ '[1,,]', false, false, '[1]' ],
+ ];
+ }
+
+ /**
+ * @dataProvider provideParseTryFixing
+ * @param string $value
+ * @param string|bool $expected Expected result with strict parser
+ * @param bool $jsoncParses Will json-c parse this value without TRY_FIXING?
+ * @param string|bool $expectedJsonc Expected result with lenient parser
+ * if different from the strict expectation
+ */
+ public function testParseTryFixing(
+ $value, $expected,
+ $jsoncParses = true, $expectedJsonc = null
+ ) {
+ // PHP5 results are always expected to have isGood() === false
+ $expectedGoodStatus = false;
+
+ // Check to see if json parser allows trailing commas
+ if ( json_decode( '[1,]' ) !== null ) {
+ // Use json-c specific expected result if provided
+ $expected = ( $expectedJsonc === null ) ? $expected : $expectedJsonc;
+ // If json-c parses the value natively, expect isGood() === true
+ $expectedGoodStatus = $jsoncParses;
+ }
+
+ $st = FormatJson::parse( $value, FormatJson::TRY_FIXING );
+ $this->assertInstanceOf( Status::class, $st );
+ if ( $expected === false ) {
+ $this->assertFalse( $st->isOK(), 'Expected isOK() == false' );
+ } else {
+ $this->assertSame( $expectedGoodStatus, $st->isGood(),
+ 'Expected isGood() == ' . ( $expectedGoodStatus ? 'true' : 'false' )
+ );
+ $this->assertTrue( $st->isOK(), 'Expected isOK == true' );
+ $val = FormatJson::encode( $st->getValue(), false, FormatJson::ALL_OK );
+ $this->assertEquals( $expected, $val );
+ }
+ }
+
+}
--- /dev/null
+<?php
+
+/**
+ * @covers LanguageCode
+ * @group Language
+ *
+ * @author Thiemo Kreuz
+ */
+class LanguageCodeTest extends MediaWikiUnitTestCase {
+
+ public function testConstructor() {
+ $instance = new LanguageCode();
+
+ $this->assertInstanceOf( LanguageCode::class, $instance );
+ }
+
+ public function testGetDeprecatedCodeMapping() {
+ $map = LanguageCode::getDeprecatedCodeMapping();
+
+ $this->assertInternalType( 'array', $map );
+ $this->assertContainsOnly( 'string', array_keys( $map ) );
+ $this->assertArrayNotHasKey( '', $map );
+ $this->assertContainsOnly( 'string', $map );
+ $this->assertNotContains( '', $map );
+
+ // Codes special to MediaWiki should never appear in a map of "deprecated" codes
+ $this->assertArrayNotHasKey( 'qqq', $map, 'documentation' );
+ $this->assertNotContains( 'qqq', $map, 'documentation' );
+ $this->assertArrayNotHasKey( 'qqx', $map, 'debug code' );
+ $this->assertNotContains( 'qqx', $map, 'debug code' );
+
+ // Valid language codes that are currently not "deprecated"
+ $this->assertArrayNotHasKey( 'bh', $map, 'family of Bihari languages' );
+ $this->assertArrayNotHasKey( 'no', $map, 'family of Norwegian languages' );
+ $this->assertArrayNotHasKey( 'simple', $map );
+ }
+
+ public function testReplaceDeprecatedCodes() {
+ $this->assertEquals( 'gsw', LanguageCode::replaceDeprecatedCodes( 'als' ) );
+ $this->assertEquals( 'gsw', LanguageCode::replaceDeprecatedCodes( 'gsw' ) );
+ $this->assertEquals( null, LanguageCode::replaceDeprecatedCodes( null ) );
+ }
+
+ /**
+ * test @see LanguageCode::bcp47().
+ * Please note the BCP 47 explicitly state that language codes are case
+ * insensitive, there are some exceptions to the rule :)
+ * This test is used to verify our formatting against all lower and
+ * all upper cases language code.
+ *
+ * @see https://tools.ietf.org/html/bcp47
+ * @dataProvider provideLanguageCodes()
+ */
+ public function testBcp47( $code, $expected ) {
+ $this->assertEquals( $expected, LanguageCode::bcp47( $code ),
+ "Applying BCP 47 standard to '$code'"
+ );
+
+ $code = strtolower( $code );
+ $this->assertEquals( $expected, LanguageCode::bcp47( $code ),
+ "Applying BCP 47 standard to lower case '$code'"
+ );
+
+ $code = strtoupper( $code );
+ $this->assertEquals( $expected, LanguageCode::bcp47( $code ),
+ "Applying BCP 47 standard to upper case '$code'"
+ );
+ }
+
+ /**
+ * Array format is ($code, $expected)
+ */
+ public static function provideLanguageCodes() {
+ return [
+ // Extracted from BCP 47 (list not exhaustive)
+ # 2.1.1
+ [ 'en-ca-x-ca', 'en-CA-x-ca' ],
+ [ 'sgn-be-fr', 'sgn-BE-FR' ],
+ [ 'az-latn-x-latn', 'az-Latn-x-latn' ],
+ # 2.2
+ [ 'sr-Latn-RS', 'sr-Latn-RS' ],
+ [ 'az-arab-ir', 'az-Arab-IR' ],
+
+ # 2.2.5
+ [ 'sl-nedis', 'sl-nedis' ],
+ [ 'de-ch-1996', 'de-CH-1996' ],
+
+ # 2.2.6
+ [
+ 'en-latn-gb-boont-r-extended-sequence-x-private',
+ 'en-Latn-GB-boont-r-extended-sequence-x-private'
+ ],
+
+ // Examples from BCP 47 Appendix A
+ # Simple language subtag:
+ [ 'DE', 'de' ],
+ [ 'fR', 'fr' ],
+ [ 'ja', 'ja' ],
+
+ # Language subtag plus script subtag:
+ [ 'zh-hans', 'zh-Hans' ],
+ [ 'sr-cyrl', 'sr-Cyrl' ],
+ [ 'sr-latn', 'sr-Latn' ],
+
+ # Extended language subtags and their primary language subtag
+ # counterparts:
+ [ 'zh-cmn-hans-cn', 'zh-cmn-Hans-CN' ],
+ [ 'cmn-hans-cn', 'cmn-Hans-CN' ],
+ [ 'zh-yue-hk', 'zh-yue-HK' ],
+ [ 'yue-hk', 'yue-HK' ],
+
+ # Language-Script-Region:
+ [ 'zh-hans-cn', 'zh-Hans-CN' ],
+ [ 'sr-latn-RS', 'sr-Latn-RS' ],
+
+ # Language-Variant:
+ [ 'sl-rozaj', 'sl-rozaj' ],
+ [ 'sl-rozaj-biske', 'sl-rozaj-biske' ],
+ [ 'sl-nedis', 'sl-nedis' ],
+
+ # Language-Region-Variant:
+ [ 'de-ch-1901', 'de-CH-1901' ],
+ [ 'sl-it-nedis', 'sl-IT-nedis' ],
+
+ # Language-Script-Region-Variant:
+ [ 'hy-latn-it-arevela', 'hy-Latn-IT-arevela' ],
+
+ # Language-Region:
+ [ 'de-de', 'de-DE' ],
+ [ 'en-us', 'en-US' ],
+ [ 'es-419', 'es-419' ],
+
+ # Private use subtags:
+ [ 'de-ch-x-phonebk', 'de-CH-x-phonebk' ],
+ [ 'az-arab-x-aze-derbend', 'az-Arab-x-aze-derbend' ],
+ /**
+ * Previous test does not reflect the BCP 47 which states:
+ * az-Arab-x-AZE-derbend
+ * AZE being private, it should be lower case, hence the test above
+ * should probably be:
+ * [ 'az-arab-x-aze-derbend', 'az-Arab-x-AZE-derbend' ],
+ */
+
+ # Private use registry values:
+ [ 'x-whatever', 'x-whatever' ],
+ [ 'qaa-qaaa-qm-x-southern', 'qaa-Qaaa-QM-x-southern' ],
+ [ 'de-qaaa', 'de-Qaaa' ],
+ [ 'sr-latn-qm', 'sr-Latn-QM' ],
+ [ 'sr-qaaa-rs', 'sr-Qaaa-RS' ],
+
+ # Tags that use extensions
+ [ 'en-us-u-islamcal', 'en-US-u-islamcal' ],
+ [ 'zh-cn-a-myext-x-private', 'zh-CN-a-myext-x-private' ],
+ [ 'en-a-myext-b-another', 'en-a-myext-b-another' ],
+
+ # Invalid:
+ // de-419-DE
+ // a-DE
+ // ar-a-aaa-b-bbb-a-ccc
+
+ # Non-standard and deprecated language codes used by MediaWiki
+ [ 'als', 'gsw' ],
+ [ 'bat-smg', 'sgs' ],
+ [ 'be-x-old', 'be-tarask' ],
+ [ 'fiu-vro', 'vro' ],
+ [ 'roa-rup', 'rup' ],
+ [ 'zh-classical', 'lzh' ],
+ [ 'zh-min-nan', 'nan' ],
+ [ 'zh-yue', 'yue' ],
+ [ 'cbk-zam', 'cbk' ],
+ [ 'de-formal', 'de-x-formal' ],
+ [ 'eml', 'egl' ],
+ [ 'en-rtl', 'en-x-rtl' ],
+ [ 'es-formal', 'es-x-formal' ],
+ [ 'hu-formal', 'hu-x-formal' ],
+ [ 'kk-Arab', 'kk-Arab' ],
+ [ 'kk-Cyrl', 'kk-Cyrl' ],
+ [ 'kk-Latn', 'kk-Latn' ],
+ [ 'map-bms', 'jv-x-bms' ],
+ [ 'mo', 'ro-Cyrl-MD' ],
+ [ 'nrm', 'nrf' ],
+ [ 'nl-informal', 'nl-x-informal' ],
+ [ 'roa-tara', 'nap-x-tara' ],
+ [ 'simple', 'en-simple' ],
+ [ 'sr-ec', 'sr-Cyrl' ],
+ [ 'sr-el', 'sr-Latn' ],
+ [ 'zh-cn', 'zh-Hans-CN' ],
+ [ 'zh-sg', 'zh-Hans-SG' ],
+ [ 'zh-my', 'zh-Hans-MY' ],
+ [ 'zh-tw', 'zh-Hant-TW' ],
+ [ 'zh-hk', 'zh-Hant-HK' ],
+ [ 'zh-mo', 'zh-Hant-MO' ],
+ [ 'zh-hans', 'zh-Hans' ],
+ [ 'zh-hant', 'zh-Hant' ],
+ ];
+ }
+
+}
--- /dev/null
+<?php
+
+/**
+ * Verifies that special page aliases are valid, with no slashes.
+ *
+ * @group Language
+ * @group SpecialPageAliases
+ * @group SystemTest
+ * @group medium
+ * @todo This should be a structure test
+ *
+ * @author Katie Filbert < aude.wiki@gmail.com >
+ */
+class SpecialPageAliasTest extends \MediaWikiUnitTestCase {
+
+ /**
+ * @coversNothing
+ * @dataProvider validSpecialPageAliasesProvider
+ */
+ public function testValidSpecialPageAliases( $code, $specialPageAliases ) {
+ foreach ( $specialPageAliases as $specialPage => $aliases ) {
+ foreach ( $aliases as $alias ) {
+ $msg = "$specialPage alias '$alias' in $code is valid with no slashes";
+ $this->assertRegExp( '/^[^\/]*$/', $msg );
+ }
+ }
+ }
+
+ public function validSpecialPageAliasesProvider() {
+ $codes = array_keys( Language::fetchLanguageNames( null, 'mwfile' ) );
+
+ $data = [];
+
+ foreach ( $codes as $code ) {
+ $specialPageAliases = $this->getSpecialPageAliases( $code );
+
+ if ( $specialPageAliases !== [] ) {
+ $data[] = [ $code, $specialPageAliases ];
+ }
+ }
+
+ return $data;
+ }
+
+ /**
+ * @param string $code
+ *
+ * @return array
+ */
+ protected function getSpecialPageAliases( $code ) {
+ $file = Language::getMessagesFileName( $code );
+
+ if ( is_readable( $file ) ) {
+ include $file;
+
+ if ( isset( $specialPageAliases ) && $specialPageAliases !== null ) {
+ return $specialPageAliases;
+ }
+ }
+
+ return [];
+ }
+
+}
--- /dev/null
+<?php
+/**
+ * @todo Could use a test of extended XMP segments. Hard to find programs that
+ * create example files, and creating my own in vim propbably wouldn't
+ * serve as a very good "test". (Adobe photoshop probably creates such files
+ * but it costs money). The implementation of it currently in MediaWiki is based
+ * solely on reading the standard, without any real world test files.
+ *
+ * @group Media
+ * @covers JpegMetadataExtractor
+ */
+class JpegMetadataExtractorTest extends MediaWikiUnitTestCase {
+
+ protected $filePath;
+
+ protected function setUp() {
+ parent::setUp();
+
+ $this->filePath = __DIR__ . '/../../../data/media/';
+ }
+
+ /**
+ * We also use this test to test padding bytes don't
+ * screw stuff up
+ *
+ * @param string $file Filename
+ *
+ * @dataProvider provideUtf8Comment
+ */
+ public function testUtf8Comment( $file ) {
+ $res = JpegMetadataExtractor::segmentSplitter( $this->filePath . $file );
+ $this->assertEquals( [ 'UTF-8 JPEG Comment — ¼' ], $res['COM'] );
+ }
+
+ public static function provideUtf8Comment() {
+ return [
+ [ 'jpeg-comment-utf.jpg' ],
+ [ 'jpeg-padding-even.jpg' ],
+ [ 'jpeg-padding-odd.jpg' ],
+ ];
+ }
+
+ /** The file is iso-8859-1, but it should get auto converted */
+ public function testIso88591Comment() {
+ $res = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'jpeg-comment-iso8859-1.jpg' );
+ $this->assertEquals( [ 'ISO-8859-1 JPEG Comment - ¼' ], $res['COM'] );
+ }
+
+ /** Comment values that are non-textual (random binary junk) should not be shown.
+ * The example test file has a comment with a 0x5 byte in it which is a control character
+ * and considered binary junk for our purposes.
+ */
+ public function testBinaryCommentStripped() {
+ $res = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'jpeg-comment-binary.jpg' );
+ $this->assertEmpty( $res['COM'] );
+ }
+
+ /* Very rarely a file can have multiple comments.
+ * Order of comments is based on order inside the file.
+ */
+ public function testMultipleComment() {
+ $res = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'jpeg-comment-multiple.jpg' );
+ $this->assertEquals( [ 'foo', 'bar' ], $res['COM'] );
+ }
+
+ public function testXMPExtraction() {
+ $res = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'jpeg-xmp-psir.jpg' );
+ $expected = file_get_contents( $this->filePath . 'jpeg-xmp-psir.xmp' );
+ $this->assertEquals( $expected, $res['XMP'] );
+ }
+
+ public function testPSIRExtraction() {
+ $res = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'jpeg-xmp-psir.jpg' );
+ $expected = '50686f746f73686f7020332e30003842494d04040000000'
+ . '000181c02190004746573741c02190003666f6f1c020000020004';
+ $this->assertEquals( $expected, bin2hex( $res['PSIR'][0] ) );
+ }
+
+ public function testXMPExtractionAltAppId() {
+ $res = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'jpeg-xmp-alt.jpg' );
+ $expected = file_get_contents( $this->filePath . 'jpeg-xmp-psir.xmp' );
+ $this->assertEquals( $expected, $res['XMP'] );
+ }
+
+ public function testIPTCHashComparisionNoHash() {
+ $segments = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'jpeg-xmp-psir.jpg' );
+ $res = JpegMetadataExtractor::doPSIR( $segments['PSIR'][0] );
+
+ $this->assertEquals( 'iptc-no-hash', $res );
+ }
+
+ public function testIPTCHashComparisionBadHash() {
+ $segments = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'jpeg-iptc-bad-hash.jpg' );
+ $res = JpegMetadataExtractor::doPSIR( $segments['PSIR'][0] );
+
+ $this->assertEquals( 'iptc-bad-hash', $res );
+ }
+
+ public function testIPTCHashComparisionGoodHash() {
+ $segments = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'jpeg-iptc-good-hash.jpg' );
+ $res = JpegMetadataExtractor::doPSIR( $segments['PSIR'][0] );
+
+ $this->assertEquals( 'iptc-good-hash', $res );
+ }
+
+ public function testExifByteOrder() {
+ $res = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'exif-user-comment.jpg' );
+ $expected = 'BE';
+ $this->assertEquals( $expected, $res['byteOrder'] );
+ }
+
+ public function testInfiniteRead() {
+ // test file truncated right after a segment, which previously
+ // caused an infinite loop looking for the next segment byte.
+ // Should get past infinite loop and throw in wfUnpack()
+ $this->setExpectedException( 'MWException' );
+ $res = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'jpeg-segment-loop1.jpg' );
+ }
+
+ public function testInfiniteRead2() {
+ // test file truncated after a segment's marker and size, which
+ // would cause a seek past end of file. Seek past end of file
+ // doesn't actually fail, but prevents further reading and was
+ // devolving into the previous case (testInfiniteRead).
+ $this->setExpectedException( 'MWException' );
+ $res = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'jpeg-segment-loop2.jpg' );
+ }
+}
--- /dev/null
+<?php
+
+class ArticleTest extends MediaWikiUnitTestCase {
+
+ /**
+ * @var Title
+ */
+ private $title;
+ /**
+ * @var Article
+ */
+ private $article;
+
+ /** creates a title object and its article object */
+ protected function setUp() {
+ parent::setUp();
+ $this->title = Title::makeTitle( NS_MAIN, 'SomePage' );
+ $this->article = new Article( $this->title );
+ }
+
+ /** cleanup title object and its article object */
+ protected function tearDown() {
+ parent::tearDown();
+ $this->title = null;
+ $this->article = null;
+ }
+
+ /**
+ * @covers Article::__get
+ */
+ public function testImplementsGetMagic() {
+ $this->assertEquals( false, $this->article->mLatest, "Article __get magic" );
+ }
+
+ /**
+ * @depends testImplementsGetMagic
+ * @covers Article::__set
+ */
+ public function testImplementsSetMagic() {
+ $this->article->mLatest = 2;
+ $this->assertEquals( 2, $this->article->mLatest, "Article __set magic" );
+ }
+
+ /**
+ * @covers Article::__get
+ * @covers Article::__set
+ */
+ public function testGetOrSetOnNewProperty() {
+ $this->article->ext_someNewProperty = 12;
+ $this->assertEquals( 12, $this->article->ext_someNewProperty,
+ "Article get/set magic on new field" );
+
+ $this->article->ext_someNewProperty = -8;
+ $this->assertEquals( -8, $this->article->ext_someNewProperty,
+ "Article get/set magic on update to new field" );
+ }
+}
--- /dev/null
+<?php
+
+namespace MediaWiki\Session;
+
+use Psr\Log\LogLevel;
+use MediaWikiUnitTestCase;
+use Wikimedia\TestingAccessWrapper;
+
+/**
+ * @group Session
+ * @covers MediaWiki\Session\Session
+ */
+class SessionUnitTest extends MediaWikiUnitTestCase {
+
+ public function testConstructor() {
+ $backend = TestUtils::getDummySessionBackend();
+ TestingAccessWrapper::newFromObject( $backend )->requests = [ -1 => 'dummy' ];
+ TestingAccessWrapper::newFromObject( $backend )->id = new SessionId( 'abc' );
+
+ $session = new Session( $backend, 42, new \TestLogger );
+ $priv = TestingAccessWrapper::newFromObject( $session );
+ $this->assertSame( $backend, $priv->backend );
+ $this->assertSame( 42, $priv->index );
+
+ $request = new \FauxRequest();
+ $priv2 = TestingAccessWrapper::newFromObject( $session->sessionWithRequest( $request ) );
+ $this->assertSame( $backend, $priv2->backend );
+ $this->assertNotSame( $priv->index, $priv2->index );
+ $this->assertSame( $request, $priv2->getRequest() );
+ }
+
+ /**
+ * @dataProvider provideMethods
+ * @param string $m Method to test
+ * @param array $args Arguments to pass to the method
+ * @param bool $index Whether the backend method gets passed the index
+ * @param bool $ret Whether the method returns a value
+ */
+ public function testMethods( $m, $args, $index, $ret ) {
+ $mock = $this->getMockBuilder( DummySessionBackend::class )
+ ->setMethods( [ $m, 'deregisterSession' ] )
+ ->getMock();
+ $mock->expects( $this->once() )->method( 'deregisterSession' )
+ ->with( $this->identicalTo( 42 ) );
+
+ $tmp = $mock->expects( $this->once() )->method( $m );
+ $expectArgs = [];
+ if ( $index ) {
+ $expectArgs[] = $this->identicalTo( 42 );
+ }
+ foreach ( $args as $arg ) {
+ $expectArgs[] = $this->identicalTo( $arg );
+ }
+ $tmp = call_user_func_array( [ $tmp, 'with' ], $expectArgs );
+
+ $retval = new \stdClass;
+ $tmp->will( $this->returnValue( $retval ) );
+
+ $session = TestUtils::getDummySession( $mock, 42 );
+
+ if ( $ret ) {
+ $this->assertSame( $retval, call_user_func_array( [ $session, $m ], $args ) );
+ } else {
+ $this->assertNull( call_user_func_array( [ $session, $m ], $args ) );
+ }
+
+ // Trigger Session destructor
+ $session = null;
+ }
+
+ public static function provideMethods() {
+ return [
+ [ 'getId', [], false, true ],
+ [ 'getSessionId', [], false, true ],
+ [ 'resetId', [], false, true ],
+ [ 'getProvider', [], false, true ],
+ [ 'isPersistent', [], false, true ],
+ [ 'persist', [], false, false ],
+ [ 'unpersist', [], false, false ],
+ [ 'shouldRememberUser', [], false, true ],
+ [ 'setRememberUser', [ true ], false, false ],
+ [ 'getRequest', [], true, true ],
+ [ 'getUser', [], false, true ],
+ [ 'getAllowedUserRights', [], false, true ],
+ [ 'canSetUser', [], false, true ],
+ [ 'setUser', [ new \stdClass ], false, false ],
+ [ 'suggestLoginUsername', [], true, true ],
+ [ 'shouldForceHTTPS', [], false, true ],
+ [ 'setForceHTTPS', [ true ], false, false ],
+ [ 'getLoggedOutTimestamp', [], false, true ],
+ [ 'setLoggedOutTimestamp', [ 123 ], false, false ],
+ [ 'getProviderMetadata', [], false, true ],
+ [ 'save', [], false, false ],
+ [ 'delaySave', [], false, true ],
+ [ 'renew', [], false, false ],
+ ];
+ }
+
+ public function testDataAccess() {
+ $session = TestUtils::getDummySession();
+ $backend = TestingAccessWrapper::newFromObject( $session )->backend;
+
+ $this->assertEquals( 1, $session->get( 'foo' ) );
+ $this->assertEquals( 'zero', $session->get( 0 ) );
+ $this->assertFalse( $backend->dirty );
+
+ $this->assertEquals( null, $session->get( 'null' ) );
+ $this->assertEquals( 'default', $session->get( 'null', 'default' ) );
+ $this->assertFalse( $backend->dirty );
+
+ $session->set( 'foo', 55 );
+ $this->assertEquals( 55, $backend->data['foo'] );
+ $this->assertTrue( $backend->dirty );
+ $backend->dirty = false;
+
+ $session->set( 1, 'one' );
+ $this->assertEquals( 'one', $backend->data[1] );
+ $this->assertTrue( $backend->dirty );
+ $backend->dirty = false;
+
+ $session->set( 1, 'one' );
+ $this->assertFalse( $backend->dirty );
+
+ $this->assertTrue( $session->exists( 'foo' ) );
+ $this->assertTrue( $session->exists( 1 ) );
+ $this->assertFalse( $session->exists( 'null' ) );
+ $this->assertFalse( $session->exists( 100 ) );
+ $this->assertFalse( $backend->dirty );
+
+ $session->remove( 'foo' );
+ $this->assertArrayNotHasKey( 'foo', $backend->data );
+ $this->assertTrue( $backend->dirty );
+ $backend->dirty = false;
+ $session->remove( 1 );
+ $this->assertArrayNotHasKey( 1, $backend->data );
+ $this->assertTrue( $backend->dirty );
+ $backend->dirty = false;
+
+ $session->remove( 101 );
+ $this->assertFalse( $backend->dirty );
+
+ $backend->data = [ 'a', 'b', '?' => 'c' ];
+ $this->assertSame( 3, $session->count() );
+ $this->assertSame( 3, count( $session ) );
+ $this->assertFalse( $backend->dirty );
+
+ $data = [];
+ foreach ( $session as $key => $value ) {
+ $data[$key] = $value;
+ }
+ $this->assertEquals( $backend->data, $data );
+ $this->assertFalse( $backend->dirty );
+
+ $this->assertEquals( $backend->data, iterator_to_array( $session ) );
+ $this->assertFalse( $backend->dirty );
+ }
+
+ public function testArrayAccess() {
+ $logger = new \TestLogger;
+ $session = TestUtils::getDummySession( null, -1, $logger );
+ $backend = TestingAccessWrapper::newFromObject( $session )->backend;
+
+ $this->assertEquals( 1, $session['foo'] );
+ $this->assertEquals( 'zero', $session[0] );
+ $this->assertFalse( $backend->dirty );
+
+ $logger->setCollect( true );
+ $this->assertEquals( null, $session['null'] );
+ $logger->setCollect( false );
+ $this->assertFalse( $backend->dirty );
+ $this->assertSame( [
+ [ LogLevel::DEBUG, 'Undefined index (auto-adds to session with a null value): null' ]
+ ], $logger->getBuffer() );
+ $logger->clearBuffer();
+
+ $session['foo'] = 55;
+ $this->assertEquals( 55, $backend->data['foo'] );
+ $this->assertTrue( $backend->dirty );
+ $backend->dirty = false;
+
+ $session[1] = 'one';
+ $this->assertEquals( 'one', $backend->data[1] );
+ $this->assertTrue( $backend->dirty );
+ $backend->dirty = false;
+
+ $session[1] = 'one';
+ $this->assertFalse( $backend->dirty );
+
+ $session['bar'] = [ 'baz' => [] ];
+ $session['bar']['baz']['quux'] = 2;
+ $this->assertEquals( [ 'baz' => [ 'quux' => 2 ] ], $backend->data['bar'] );
+
+ $logger->setCollect( true );
+ $session['bar2']['baz']['quux'] = 3;
+ $logger->setCollect( false );
+ $this->assertEquals( [ 'baz' => [ 'quux' => 3 ] ], $backend->data['bar2'] );
+ $this->assertSame( [
+ [ LogLevel::DEBUG, 'Undefined index (auto-adds to session with a null value): bar2' ]
+ ], $logger->getBuffer() );
+ $logger->clearBuffer();
+
+ $backend->dirty = false;
+ $this->assertTrue( isset( $session['foo'] ) );
+ $this->assertTrue( isset( $session[1] ) );
+ $this->assertFalse( isset( $session['null'] ) );
+ $this->assertFalse( isset( $session['missing'] ) );
+ $this->assertFalse( isset( $session[100] ) );
+ $this->assertFalse( $backend->dirty );
+
+ unset( $session['foo'] );
+ $this->assertArrayNotHasKey( 'foo', $backend->data );
+ $this->assertTrue( $backend->dirty );
+ $backend->dirty = false;
+ unset( $session[1] );
+ $this->assertArrayNotHasKey( 1, $backend->data );
+ $this->assertTrue( $backend->dirty );
+ $backend->dirty = false;
+
+ unset( $session[101] );
+ $this->assertFalse( $backend->dirty );
+ }
+
+ public function testTokens() {
+ $session = TestUtils::getDummySession();
+ $priv = TestingAccessWrapper::newFromObject( $session );
+ $backend = $priv->backend;
+
+ $token = TestingAccessWrapper::newFromObject( $session->getToken() );
+ $this->assertArrayHasKey( 'wsTokenSecrets', $backend->data );
+ $this->assertArrayHasKey( 'default', $backend->data['wsTokenSecrets'] );
+ $secret = $backend->data['wsTokenSecrets']['default'];
+ $this->assertSame( $secret, $token->secret );
+ $this->assertSame( '', $token->salt );
+ $this->assertTrue( $token->wasNew() );
+
+ $token = TestingAccessWrapper::newFromObject( $session->getToken( 'foo' ) );
+ $this->assertSame( $secret, $token->secret );
+ $this->assertSame( 'foo', $token->salt );
+ $this->assertFalse( $token->wasNew() );
+
+ $backend->data['wsTokenSecrets']['secret'] = 'sekret';
+ $token = TestingAccessWrapper::newFromObject(
+ $session->getToken( [ 'bar', 'baz' ], 'secret' )
+ );
+ $this->assertSame( 'sekret', $token->secret );
+ $this->assertSame( 'bar|baz', $token->salt );
+ $this->assertFalse( $token->wasNew() );
+
+ $session->resetToken( 'secret' );
+ $this->assertArrayHasKey( 'wsTokenSecrets', $backend->data );
+ $this->assertArrayHasKey( 'default', $backend->data['wsTokenSecrets'] );
+ $this->assertArrayNotHasKey( 'secret', $backend->data['wsTokenSecrets'] );
+
+ $session->resetAllTokens();
+ $this->assertArrayNotHasKey( 'wsTokenSecrets', $backend->data );
+ }
+
+}
--- /dev/null
+<?php
+
+namespace MediaWiki\Session;
+
+use MediaWikiUnitTestCase;
+use Wikimedia\TestingAccessWrapper;
+
+/**
+ * @group Session
+ * @covers MediaWiki\Session\Token
+ */
+class TokenTest extends MediaWikiUnitTestCase {
+
+ public function testBasics() {
+ $token = $this->getMockBuilder( Token::class )
+ ->setMethods( [ 'toStringAtTimestamp' ] )
+ ->setConstructorArgs( [ 'sekret', 'salty', true ] )
+ ->getMock();
+ $token->expects( $this->any() )->method( 'toStringAtTimestamp' )
+ ->will( $this->returnValue( 'faketoken+\\' ) );
+
+ $this->assertSame( 'faketoken+\\', $token->toString() );
+ $this->assertSame( 'faketoken+\\', (string)$token );
+ $this->assertTrue( $token->wasNew() );
+
+ $token = new Token( 'sekret', 'salty', false );
+ $this->assertFalse( $token->wasNew() );
+ }
+
+ public function testToStringAtTimestamp() {
+ $token = TestingAccessWrapper::newFromObject( new Token( 'sekret', 'salty', false ) );
+
+ $this->assertSame(
+ 'd9ade0c7d4349e9df9094e61c33a5a0d5644fde2+\\',
+ $token->toStringAtTimestamp( 1447362018 )
+ );
+ $this->assertSame(
+ 'ee2f7a2488dea9176c224cfb400d43be5644fdea+\\',
+ $token->toStringAtTimestamp( 1447362026 )
+ );
+ }
+
+ public function testGetTimestamp() {
+ $this->assertSame(
+ 1447362018, Token::getTimestamp( 'd9ade0c7d4349e9df9094e61c33a5a0d5644fde2+\\' )
+ );
+ $this->assertSame(
+ 1447362026, Token::getTimestamp( 'ee2f7a2488dea9176c224cfb400d43be5644fdea+\\' )
+ );
+ $this->assertNull( Token::getTimestamp( 'ee2f7a2488dea9176c224cfb400d43be5644fdea-\\' ) );
+ $this->assertNull( Token::getTimestamp( 'ee2f7a2488dea9176c224cfb400d43be+\\' ) );
+
+ $this->assertNull( Token::getTimestamp( 'ee2f7a2488dea9x76c224cfb400d43be5644fdea+\\' ) );
+ }
+
+ public function testMatch() {
+ $token = TestingAccessWrapper::newFromObject( new Token( 'sekret', 'salty', false ) );
+
+ $test = $token->toStringAtTimestamp( time() - 10 );
+ $this->assertTrue( $token->match( $test ) );
+ $this->assertTrue( $token->match( $test, 12 ) );
+ $this->assertFalse( $token->match( $test, 8 ) );
+
+ $this->assertFalse( $token->match( 'ee2f7a2488dea9176c224cfb400d43be5644fdea-\\' ) );
+ }
+
+}
--- /dev/null
+<?php
+
+/**
+ * Copyright (C) 2017 Kunal Mehta <legoktm@member.fsf.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ */
+
+use MediaWiki\Shell\FirejailCommand;
+use MediaWiki\Shell\Shell;
+use Wikimedia\TestingAccessWrapper;
+
+class FirejailCommandTest extends MediaWikiUnitTestCase {
+
+ public function provideBuildFinalCommand() {
+ global $IP;
+ // phpcs:ignore Generic.Files.LineLength
+ $env = "'MW_INCLUDE_STDERR=;MW_CPU_LIMIT=180; MW_CGROUP='\'''\''; MW_MEM_LIMIT=307200; MW_FILE_SIZE_LIMIT=102400; MW_WALL_CLOCK_LIMIT=180; MW_USE_LOG_PIPE=yes'";
+ $limit = "/bin/bash '$IP/includes/shell/limit.sh'";
+ $profile = "--profile=$IP/includes/shell/firejail.profile";
+ $blacklist = '--blacklist=' . realpath( MW_CONFIG_FILE );
+ $default = "$blacklist --noroot --seccomp --private-dev";
+ return [
+ [
+ 'No restrictions',
+ 'ls', 0, "$limit ''\''ls'\''' $env"
+ ],
+ [
+ 'default restriction',
+ 'ls', Shell::RESTRICT_DEFAULT,
+ "$limit 'firejail --quiet $profile $default -- '\''ls'\''' $env"
+ ],
+ [
+ 'no network',
+ 'ls', Shell::NO_NETWORK,
+ "$limit 'firejail --quiet $profile --net=none -- '\''ls'\''' $env"
+ ],
+ [
+ 'default restriction & no network',
+ 'ls', Shell::RESTRICT_DEFAULT | Shell::NO_NETWORK,
+ "$limit 'firejail --quiet $profile $default --net=none -- '\''ls'\''' $env"
+ ],
+ [
+ 'seccomp',
+ 'ls', Shell::SECCOMP,
+ "$limit 'firejail --quiet $profile --seccomp -- '\''ls'\''' $env"
+ ],
+ [
+ 'seccomp & no execve',
+ 'ls', Shell::SECCOMP | Shell::NO_EXECVE,
+ "$limit 'firejail --quiet $profile --shell=none --seccomp=execve -- '\''ls'\''' $env"
+ ],
+ ];
+ }
+
+ /**
+ * @covers \MediaWiki\Shell\FirejailCommand::buildFinalCommand()
+ * @dataProvider provideBuildFinalCommand
+ */
+ public function testBuildFinalCommand( $desc, $params, $flags, $expected ) {
+ $command = new FirejailCommand( 'firejail' );
+ $command
+ ->params( $params )
+ ->restrict( $flags );
+ $wrapper = TestingAccessWrapper::newFromObject( $command );
+ $output = $wrapper->buildFinalCommand( $wrapper->command );
+ $this->assertEquals( $expected, $output[0], $desc );
+ }
+
+}
--- /dev/null
+<?php
+
+use MediaWiki\Site\MediaWikiPageNameNormalizer;
+
+/**
+ * @covers MediaWiki\Site\MediaWikiPageNameNormalizer
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
+ * @since 1.27
+ *
+ * @group Site
+ * @group medium
+ *
+ * @author Marius Hoch
+ */
+class MediaWikiPageNameNormalizerTest extends MediaWikiUnitTestCase {
+
+ /**
+ * @dataProvider normalizePageTitleProvider
+ */
+ public function testNormalizePageTitle( $expected, $pageName, $getResponse ) {
+ MediaWikiPageNameNormalizerTestMockHttp::$response = $getResponse;
+
+ $normalizer = new MediaWikiPageNameNormalizer(
+ new MediaWikiPageNameNormalizerTestMockHttp()
+ );
+
+ $this->assertSame(
+ $expected,
+ $normalizer->normalizePageName( $pageName, 'https://www.wikidata.org/w/api.php' )
+ );
+ }
+
+ public function normalizePageTitleProvider() {
+ // Response are taken from wikidata and kkwiki using the following API request
+ // api.php?action=query&prop=info&redirects=1&converttitles=1&format=json&titles=…
+ return [
+ 'universe (Q1)' => [
+ 'Q1',
+ 'Q1',
+ '{"batchcomplete":"","query":{"pages":{"129":{"pageid":129,"ns":0,'
+ . '"title":"Q1","contentmodel":"wikibase-item","pagelanguage":"en",'
+ . '"pagelanguagehtmlcode":"en","pagelanguagedir":"ltr",'
+ . '"touched":"2016-06-23T05:11:21Z","lastrevid":350004448,"length":58001}}}}'
+ ],
+ 'Q404 redirects to Q395' => [
+ 'Q395',
+ 'Q404',
+ '{"batchcomplete":"","query":{"redirects":[{"from":"Q404","to":"Q395"}],"pages"'
+ . ':{"601":{"pageid":601,"ns":0,"title":"Q395","contentmodel":"wikibase-item",'
+ . '"pagelanguage":"en","pagelanguagehtmlcode":"en","pagelanguagedir":"ltr",'
+ . '"touched":"2016-06-23T08:00:20Z","lastrevid":350021914,"length":60108}}}}'
+ ],
+ 'D converted to Д (Latin to Cyrillic) (taken from kkwiki)' => [
+ 'Д',
+ 'D',
+ '{"batchcomplete":"","query":{"converted":[{"from":"D","to":"\u0414"}],'
+ . '"pages":{"510541":{"pageid":510541,"ns":0,"title":"\u0414",'
+ . '"contentmodel":"wikitext","pagelanguage":"kk","pagelanguagehtmlcode":"kk",'
+ . '"pagelanguagedir":"ltr","touched":"2015-11-22T09:16:18Z",'
+ . '"lastrevid":2373618,"length":3501}}}}'
+ ],
+ 'there is no Q0' => [
+ false,
+ 'Q0',
+ '{"batchcomplete":"","query":{"pages":{"-1":{"ns":0,"title":"Q0",'
+ . '"missing":"","contentmodel":"wikibase-item","pagelanguage":"en",'
+ . '"pagelanguagehtmlcode":"en","pagelanguagedir":"ltr"}}}}'
+ ],
+ 'invalid title' => [
+ false,
+ '{{',
+ '{"batchcomplete":"","query":{"pages":{"-1":{"title":"{{",'
+ . '"invalidreason":"The requested page title contains invalid '
+ . 'characters: \"{\".","invalid":""}}}}'
+ ],
+ 'error on get' => [ false, 'ABC', false ]
+ ];
+ }
+
+}
+
+/**
+ * @private
+ * @see Http
+ */
+class MediaWikiPageNameNormalizerTestMockHttp extends Http {
+
+ /**
+ * @var mixed
+ */
+ public static $response;
+
+ public static function get( $url, array $options = [], $caller = __METHOD__ ) {
+ PHPUnit_Framework_Assert::assertInternalType( 'string', $url );
+ PHPUnit_Framework_Assert::assertInternalType( 'string', $caller );
+
+ return self::$response;
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * @covers ZipDirectoryReader
+ * NOTE: this test is more like an integration test than a unit test
+ */
+class ZipDirectoryReaderTest extends MediaWikiUnitTestCase {
+
+ protected $zipDir;
+ protected $entries;
+
+ protected function setUp() {
+ parent::setUp();
+ $this->zipDir = __DIR__ . '/../../../data/zip';
+ }
+
+ function zipCallback( $entry ) {
+ $this->entries[] = $entry;
+ }
+
+ function readZipAssertError( $file, $error, $assertMessage ) {
+ $this->entries = [];
+ $status = ZipDirectoryReader::read( "{$this->zipDir}/$file", [ $this, 'zipCallback' ] );
+ $this->assertTrue( $status->hasMessage( $error ), $assertMessage );
+ }
+
+ function readZipAssertSuccess( $file, $assertMessage ) {
+ $this->entries = [];
+ $status = ZipDirectoryReader::read( "{$this->zipDir}/$file", [ $this, 'zipCallback' ] );
+ $this->assertTrue( $status->isOK(), $assertMessage );
+ }
+
+ public function testEmpty() {
+ $this->readZipAssertSuccess( 'empty.zip', 'Empty zip' );
+ }
+
+ public function testMultiDisk0() {
+ $this->readZipAssertError( 'split.zip', 'zip-unsupported',
+ 'Split zip error' );
+ }
+
+ public function testNoSignature() {
+ $this->readZipAssertError( 'nosig.zip', 'zip-wrong-format',
+ 'No signature should give "wrong format" error' );
+ }
+
+ public function testSimple() {
+ $this->readZipAssertSuccess( 'class.zip', 'Simple ZIP' );
+ $this->assertEquals( $this->entries, [ [
+ 'name' => 'Class.class',
+ 'mtime' => '20010115000000',
+ 'size' => 1,
+ ] ] );
+ }
+
+ public function testBadCentralEntrySignature() {
+ $this->readZipAssertError( 'wrong-central-entry-sig.zip', 'zip-bad',
+ 'Bad central entry error' );
+ }
+
+ public function testTrailingBytes() {
+ // Due to T40432 this is now zip-wrong-format instead of zip-bad
+ $this->readZipAssertError( 'trail.zip', 'zip-wrong-format',
+ 'Trailing bytes error' );
+ }
+
+ public function testWrongCDStart() {
+ $this->readZipAssertError( 'wrong-cd-start-disk.zip', 'zip-unsupported',
+ 'Wrong CD start disk error' );
+ }
+
+ public function testCentralDirectoryGap() {
+ $this->readZipAssertError( 'cd-gap.zip', 'zip-bad',
+ 'CD gap error' );
+ }
+
+ public function testCentralDirectoryTruncated() {
+ $this->readZipAssertError( 'cd-truncated.zip', 'zip-bad',
+ 'CD truncated error (should hit unpack() overrun)' );
+ }
+
+ public function testLooksLikeZip64() {
+ $this->readZipAssertError( 'looks-like-zip64.zip', 'zip-unsupported',
+ 'A file which looks like ZIP64 but isn\'t, should give error' );
+ }
+}
+++ /dev/null
-<?php
-
-/**
- * @covers LanguageCode
- * @group Language
- *
- * @author Thiemo Kreuz
- */
-class LanguageCodeTest extends MediaWikiUnitTestCase {
-
- public function testConstructor() {
- $instance = new LanguageCode();
-
- $this->assertInstanceOf( LanguageCode::class, $instance );
- }
-
- public function testGetDeprecatedCodeMapping() {
- $map = LanguageCode::getDeprecatedCodeMapping();
-
- $this->assertInternalType( 'array', $map );
- $this->assertContainsOnly( 'string', array_keys( $map ) );
- $this->assertArrayNotHasKey( '', $map );
- $this->assertContainsOnly( 'string', $map );
- $this->assertNotContains( '', $map );
-
- // Codes special to MediaWiki should never appear in a map of "deprecated" codes
- $this->assertArrayNotHasKey( 'qqq', $map, 'documentation' );
- $this->assertNotContains( 'qqq', $map, 'documentation' );
- $this->assertArrayNotHasKey( 'qqx', $map, 'debug code' );
- $this->assertNotContains( 'qqx', $map, 'debug code' );
-
- // Valid language codes that are currently not "deprecated"
- $this->assertArrayNotHasKey( 'bh', $map, 'family of Bihari languages' );
- $this->assertArrayNotHasKey( 'no', $map, 'family of Norwegian languages' );
- $this->assertArrayNotHasKey( 'simple', $map );
- }
-
- public function testReplaceDeprecatedCodes() {
- $this->assertEquals( 'gsw', LanguageCode::replaceDeprecatedCodes( 'als' ) );
- $this->assertEquals( 'gsw', LanguageCode::replaceDeprecatedCodes( 'gsw' ) );
- $this->assertEquals( null, LanguageCode::replaceDeprecatedCodes( null ) );
- }
-
- /**
- * test @see LanguageCode::bcp47().
- * Please note the BCP 47 explicitly state that language codes are case
- * insensitive, there are some exceptions to the rule :)
- * This test is used to verify our formatting against all lower and
- * all upper cases language code.
- *
- * @see https://tools.ietf.org/html/bcp47
- * @dataProvider provideLanguageCodes()
- */
- public function testBcp47( $code, $expected ) {
- $this->assertEquals( $expected, LanguageCode::bcp47( $code ),
- "Applying BCP 47 standard to '$code'"
- );
-
- $code = strtolower( $code );
- $this->assertEquals( $expected, LanguageCode::bcp47( $code ),
- "Applying BCP 47 standard to lower case '$code'"
- );
-
- $code = strtoupper( $code );
- $this->assertEquals( $expected, LanguageCode::bcp47( $code ),
- "Applying BCP 47 standard to upper case '$code'"
- );
- }
-
- /**
- * Array format is ($code, $expected)
- */
- public static function provideLanguageCodes() {
- return [
- // Extracted from BCP 47 (list not exhaustive)
- # 2.1.1
- [ 'en-ca-x-ca', 'en-CA-x-ca' ],
- [ 'sgn-be-fr', 'sgn-BE-FR' ],
- [ 'az-latn-x-latn', 'az-Latn-x-latn' ],
- # 2.2
- [ 'sr-Latn-RS', 'sr-Latn-RS' ],
- [ 'az-arab-ir', 'az-Arab-IR' ],
-
- # 2.2.5
- [ 'sl-nedis', 'sl-nedis' ],
- [ 'de-ch-1996', 'de-CH-1996' ],
-
- # 2.2.6
- [
- 'en-latn-gb-boont-r-extended-sequence-x-private',
- 'en-Latn-GB-boont-r-extended-sequence-x-private'
- ],
-
- // Examples from BCP 47 Appendix A
- # Simple language subtag:
- [ 'DE', 'de' ],
- [ 'fR', 'fr' ],
- [ 'ja', 'ja' ],
-
- # Language subtag plus script subtag:
- [ 'zh-hans', 'zh-Hans' ],
- [ 'sr-cyrl', 'sr-Cyrl' ],
- [ 'sr-latn', 'sr-Latn' ],
-
- # Extended language subtags and their primary language subtag
- # counterparts:
- [ 'zh-cmn-hans-cn', 'zh-cmn-Hans-CN' ],
- [ 'cmn-hans-cn', 'cmn-Hans-CN' ],
- [ 'zh-yue-hk', 'zh-yue-HK' ],
- [ 'yue-hk', 'yue-HK' ],
-
- # Language-Script-Region:
- [ 'zh-hans-cn', 'zh-Hans-CN' ],
- [ 'sr-latn-RS', 'sr-Latn-RS' ],
-
- # Language-Variant:
- [ 'sl-rozaj', 'sl-rozaj' ],
- [ 'sl-rozaj-biske', 'sl-rozaj-biske' ],
- [ 'sl-nedis', 'sl-nedis' ],
-
- # Language-Region-Variant:
- [ 'de-ch-1901', 'de-CH-1901' ],
- [ 'sl-it-nedis', 'sl-IT-nedis' ],
-
- # Language-Script-Region-Variant:
- [ 'hy-latn-it-arevela', 'hy-Latn-IT-arevela' ],
-
- # Language-Region:
- [ 'de-de', 'de-DE' ],
- [ 'en-us', 'en-US' ],
- [ 'es-419', 'es-419' ],
-
- # Private use subtags:
- [ 'de-ch-x-phonebk', 'de-CH-x-phonebk' ],
- [ 'az-arab-x-aze-derbend', 'az-Arab-x-aze-derbend' ],
- /**
- * Previous test does not reflect the BCP 47 which states:
- * az-Arab-x-AZE-derbend
- * AZE being private, it should be lower case, hence the test above
- * should probably be:
- * [ 'az-arab-x-aze-derbend', 'az-Arab-x-AZE-derbend' ],
- */
-
- # Private use registry values:
- [ 'x-whatever', 'x-whatever' ],
- [ 'qaa-qaaa-qm-x-southern', 'qaa-Qaaa-QM-x-southern' ],
- [ 'de-qaaa', 'de-Qaaa' ],
- [ 'sr-latn-qm', 'sr-Latn-QM' ],
- [ 'sr-qaaa-rs', 'sr-Qaaa-RS' ],
-
- # Tags that use extensions
- [ 'en-us-u-islamcal', 'en-US-u-islamcal' ],
- [ 'zh-cn-a-myext-x-private', 'zh-CN-a-myext-x-private' ],
- [ 'en-a-myext-b-another', 'en-a-myext-b-another' ],
-
- # Invalid:
- // de-419-DE
- // a-DE
- // ar-a-aaa-b-bbb-a-ccc
-
- # Non-standard and deprecated language codes used by MediaWiki
- [ 'als', 'gsw' ],
- [ 'bat-smg', 'sgs' ],
- [ 'be-x-old', 'be-tarask' ],
- [ 'fiu-vro', 'vro' ],
- [ 'roa-rup', 'rup' ],
- [ 'zh-classical', 'lzh' ],
- [ 'zh-min-nan', 'nan' ],
- [ 'zh-yue', 'yue' ],
- [ 'cbk-zam', 'cbk' ],
- [ 'de-formal', 'de-x-formal' ],
- [ 'eml', 'egl' ],
- [ 'en-rtl', 'en-x-rtl' ],
- [ 'es-formal', 'es-x-formal' ],
- [ 'hu-formal', 'hu-x-formal' ],
- [ 'kk-Arab', 'kk-Arab' ],
- [ 'kk-Cyrl', 'kk-Cyrl' ],
- [ 'kk-Latn', 'kk-Latn' ],
- [ 'map-bms', 'jv-x-bms' ],
- [ 'mo', 'ro-Cyrl-MD' ],
- [ 'nrm', 'nrf' ],
- [ 'nl-informal', 'nl-x-informal' ],
- [ 'roa-tara', 'nap-x-tara' ],
- [ 'simple', 'en-simple' ],
- [ 'sr-ec', 'sr-Cyrl' ],
- [ 'sr-el', 'sr-Latn' ],
- [ 'zh-cn', 'zh-Hans-CN' ],
- [ 'zh-sg', 'zh-Hans-SG' ],
- [ 'zh-my', 'zh-Hans-MY' ],
- [ 'zh-tw', 'zh-Hant-TW' ],
- [ 'zh-hk', 'zh-Hant-HK' ],
- [ 'zh-mo', 'zh-Hant-MO' ],
- [ 'zh-hans', 'zh-Hans' ],
- [ 'zh-hant', 'zh-Hant' ],
- ];
- }
-
-}
+++ /dev/null
-<?php
-
-/**
- * Verifies that special page aliases are valid, with no slashes.
- *
- * @group Language
- * @group SpecialPageAliases
- * @group SystemTest
- * @group medium
- * @todo This should be a structure test
- *
- * @author Katie Filbert < aude.wiki@gmail.com >
- */
-class SpecialPageAliasTest extends \MediaWikiUnitTestCase {
-
- /**
- * @coversNothing
- * @dataProvider validSpecialPageAliasesProvider
- */
- public function testValidSpecialPageAliases( $code, $specialPageAliases ) {
- foreach ( $specialPageAliases as $specialPage => $aliases ) {
- foreach ( $aliases as $alias ) {
- $msg = "$specialPage alias '$alias' in $code is valid with no slashes";
- $this->assertRegExp( '/^[^\/]*$/', $msg );
- }
- }
- }
-
- public function validSpecialPageAliasesProvider() {
- $codes = array_keys( Language::fetchLanguageNames( null, 'mwfile' ) );
-
- $data = [];
-
- foreach ( $codes as $code ) {
- $specialPageAliases = $this->getSpecialPageAliases( $code );
-
- if ( $specialPageAliases !== [] ) {
- $data[] = [ $code, $specialPageAliases ];
- }
- }
-
- return $data;
- }
-
- /**
- * @param string $code
- *
- * @return array
- */
- protected function getSpecialPageAliases( $code ) {
- $file = Language::getMessagesFileName( $code );
-
- if ( is_readable( $file ) ) {
- include $file;
-
- if ( isset( $specialPageAliases ) && $specialPageAliases !== null ) {
- return $specialPageAliases;
- }
- }
-
- return [];
- }
-
-}