MediaWiki  master
ApiQueryTest.php
Go to the documentation of this file.
1 <?php
2 
9 class ApiQueryTest extends ApiTestCase {
10  protected function setUp() {
11  parent::setUp();
12 
13  // Setup apiquerytestiw: as interwiki prefix
14  $this->setMwGlobals( 'wgHooks', [
15  'InterwikiLoadPrefix' => [
16  function ( $prefix, &$data ) {
17  if ( $prefix == 'apiquerytestiw' ) {
18  $data = [ 'iw_url' => 'wikipedia' ];
19  }
20  return false;
21  }
22  ]
23  ] );
24  }
25 
26  public function testTitlesGetNormalized() {
27  global $wgMetaNamespace;
28 
29  $this->setMwGlobals( [
30  'wgCapitalLinks' => true,
31  ] );
32 
33  $data = $this->doApiRequest( [
34  'action' => 'query',
35  'titles' => 'Project:articleA|article_B' ] );
36 
37  $this->assertArrayHasKey( 'query', $data[0] );
38  $this->assertArrayHasKey( 'normalized', $data[0]['query'] );
39 
40  // Forge a normalized title
41  $to = Title::newFromText( $wgMetaNamespace . ':ArticleA' );
42 
43  $this->assertEquals(
44  [
45  'fromencoded' => false,
46  'from' => 'Project:articleA',
47  'to' => $to->getPrefixedText(),
48  ],
49  $data[0]['query']['normalized'][0]
50  );
51 
52  $this->assertEquals(
53  [
54  'fromencoded' => false,
55  'from' => 'article_B',
56  'to' => 'Article B'
57  ],
58  $data[0]['query']['normalized'][1]
59  );
60  }
61 
62  public function testTitlesAreRejectedIfInvalid() {
63  $title = false;
64  while ( !$title || Title::newFromText( $title )->exists() ) {
65  $title = md5( mt_rand( 0, 100000 ) );
66  }
67 
68  $data = $this->doApiRequest( [
69  'action' => 'query',
70  'titles' => $title . '|Talk:' ] );
71 
72  $this->assertArrayHasKey( 'query', $data[0] );
73  $this->assertArrayHasKey( 'pages', $data[0]['query'] );
74  $this->assertEquals( 2, count( $data[0]['query']['pages'] ) );
75 
76  $this->assertArrayHasKey( -2, $data[0]['query']['pages'] );
77  $this->assertArrayHasKey( -1, $data[0]['query']['pages'] );
78 
79  $this->assertArrayHasKey( 'missing', $data[0]['query']['pages'][-2] );
80  $this->assertArrayHasKey( 'invalid', $data[0]['query']['pages'][-1] );
81  }
82 
83  public function testTitlesWithWhitespaces() {
84  $data = $this->doApiRequest( [
85  'action' => 'query',
86  'titles' => ' '
87  ] );
88 
89  $this->assertArrayHasKey( 'query', $data[0] );
90  $this->assertArrayHasKey( 'pages', $data[0]['query'] );
91  $this->assertEquals( 1, count( $data[0]['query']['pages'] ) );
92  $this->assertArrayHasKey( -1, $data[0]['query']['pages'] );
93  $this->assertArrayHasKey( 'invalid', $data[0]['query']['pages'][-1] );
94  }
95 
105  function testTitlePartToKey( $titlePart, $namespace, $expected, $expectException ) {
106  $this->setMwGlobals( [
107  'wgCapitalLinks' => true,
108  ] );
109 
110  $api = new MockApiQueryBase();
111  $exceptionCaught = false;
112  try {
113  $this->assertEquals( $expected, $api->titlePartToKey( $titlePart, $namespace ) );
114  } catch ( ApiUsageException $e ) {
115  $exceptionCaught = true;
116  }
117  $this->assertEquals( $expectException, $exceptionCaught,
118  'ApiUsageException thrown by titlePartToKey' );
119  }
120 
122  return [
123  [ 'a b c', NS_MAIN, 'A_b_c', false ],
124  [ 'x', NS_MAIN, 'X', false ],
125  [ 'y ', NS_MAIN, 'Y_', false ],
126  [ 'template:foo', NS_CATEGORY, 'Template:foo', false ],
127  [ 'apiquerytestiw:foo', NS_CATEGORY, 'Apiquerytestiw:foo', false ],
128  [ "\xF7", NS_MAIN, null, true ],
129  [ 'template:foo', NS_MAIN, null, true ],
130  [ 'apiquerytestiw:foo', NS_MAIN, null, true ],
131  ];
132  }
133 
137  public function testClassNamesInModuleManager() {
138  $api = new ApiMain(
139  new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] )
140  );
141  $queryApi = new ApiQuery( $api, 'query' );
142  $modules = $queryApi->getModuleManager()->getNamesWithClasses();
143 
144  foreach ( $modules as $name => $class ) {
145  $this->assertTrue(
146  class_exists( $class ),
147  'Class ' . $class . ' for api module ' . $name . ' does not exist (with exact case)'
148  );
149  }
150  }
151 
153  $title = Title::makeTitle( NS_MAIN, 'Test article' );
154  $this->insertPage( $title );
155 
156  $this->setTemporaryHook( 'getUserPermissionsErrors',
157  function ( Title $page, &$user, $action, &$result ) use ( $title ) {
158  if ( $page->equals( $title ) && $action === 'read' ) {
159  $result = false;
160  return false;
161  }
162  } );
163 
164  $data = $this->doApiRequest( [
165  'action' => 'query',
166  'titles' => $title->getPrefixedText(),
167  'export' => 1,
168  ] );
169 
170  $this->assertArrayHasKey( 'query', $data[0] );
171  $this->assertArrayHasKey( 'export', $data[0]['query'] );
172  // This response field contains an XML document even if no pages were exported
173  $this->assertNotContains( $title->getPrefixedText(), $data[0]['query']['export'] );
174  }
175 }
const NS_MAIN
Definition: Defines.php:60
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
equals(LinkTarget $title)
Compare with another title.
Definition: Title.php:4008
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2147
API Database medium ApiQuery.
Definition: ApiQueryTest.php:9
Exception used to abort API execution with an error.
doApiRequest(array $params, array $session=null, $appendModule=false, User $user=null, $tokenType=null)
Does the API request and returns the result.
Definition: ApiTestCase.php:62
$wgMetaNamespace
Name of the project namespace.
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\*-\*)") will be honored when streaming the file. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1970
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition: hooks.txt:1972
provideTestTitlePartToKey()
$modules
testTitlesAreRejectedIfInvalid()
testClassNamesInModuleManager()
Test if all classes in the query module manager exists.
const NS_CATEGORY
Definition: Defines.php:74
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:41
testTitlesWithWhitespaces()
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:767
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:912
This is the main query class.
Definition: ApiQuery.php:36
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
testShouldNotExportPagesThatUserCanNotRead()
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:592
testTitlePartToKey( $titlePart, $namespace, $expected, $expectException)
Test the ApiBase::titlePartToKey function.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
testTitlesGetNormalized()
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1454
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:322