MediaWiki  master
ApiErrorFormatterTest.php
Go to the documentation of this file.
1 <?php
2 
4 
9 
13  public function testErrorFormatterBasics() {
14  $result = new ApiResult( 8388608 );
15  $formatter = new ApiErrorFormatter( $result, Language::factory( 'de' ), 'wikitext', false );
16  $this->assertSame( 'de', $formatter->getLanguage()->getCode() );
17  $this->assertSame( 'wikitext', $formatter->getFormat() );
18 
19  $formatter->addMessagesFromStatus( null, Status::newGood() );
20  $this->assertSame(
21  [ ApiResult::META_TYPE => 'assoc' ],
22  $result->getResultData()
23  );
24 
25  $this->assertSame( [], $formatter->arrayFromStatus( Status::newGood() ) );
26 
27  $wrappedFormatter = TestingAccessWrapper::newFromObject( $formatter );
28  $this->assertSame(
29  'Blah "kbd" <X> 😊',
30  $wrappedFormatter->stripMarkup( 'Blah <kbd>kbd</kbd> <b>&lt;X&gt;</b> &#x1f60a;' ),
31  'stripMarkup'
32  );
33  }
34 
39  public function testNewWithFormat() {
40  $result = new ApiResult( 8388608 );
41  $formatter = new ApiErrorFormatter( $result, Language::factory( 'de' ), 'wikitext', false );
42  $formatter2 = $formatter->newWithFormat( 'html' );
43 
44  $this->assertSame( $formatter->getLanguage(), $formatter2->getLanguage() );
45  $this->assertSame( 'html', $formatter2->getFormat() );
46 
47  $formatter3 = new ApiErrorFormatter_BackCompat( $result );
48  $formatter4 = $formatter3->newWithFormat( 'html' );
49  $this->assertNotInstanceOf( ApiErrorFormatter_BackCompat::class, $formatter4 );
50  $this->assertSame( $formatter3->getLanguage(), $formatter4->getLanguage() );
51  $this->assertSame( 'html', $formatter4->getFormat() );
52  }
53 
58  public function testErrorFormatter( $format, $lang, $useDB,
59  $expect1, $expect2, $expect3
60  ) {
61  $result = new ApiResult( 8388608 );
62  $formatter = new ApiErrorFormatter( $result, Language::factory( $lang ), $format, $useDB );
63 
64  // Add default type
65  $expect1[ApiResult::META_TYPE] = 'assoc';
66  $expect2[ApiResult::META_TYPE] = 'assoc';
67  $expect3[ApiResult::META_TYPE] = 'assoc';
68 
69  $formatter->addWarning( 'string', 'mainpage' );
70  $formatter->addError( 'err', 'mainpage' );
71  $this->assertEquals( $expect1, $result->getResultData(), 'Simple test' );
72 
73  $result->reset();
74  $formatter->addWarning( 'foo', 'mainpage' );
75  $formatter->addWarning( 'foo', 'mainpage' );
76  $formatter->addWarning( 'foo', [ 'parentheses', 'foobar' ] );
77  $msg1 = wfMessage( 'mainpage' );
78  $formatter->addWarning( 'message', $msg1 );
79  $msg2 = new ApiMessage( 'mainpage', 'overriddenCode', [ 'overriddenData' => true ] );
80  $formatter->addWarning( 'messageWithData', $msg2 );
81  $formatter->addError( 'errWithData', $msg2 );
82  $this->assertSame( $expect2, $result->getResultData(), 'Complex test' );
83 
84  $this->assertEquals(
85  $this->removeModuleTag( $expect2['warnings'][2] ),
86  $formatter->formatMessage( $msg1 ),
87  'formatMessage test 1'
88  );
89  $this->assertEquals(
90  $this->removeModuleTag( $expect2['warnings'][3] ),
91  $formatter->formatMessage( $msg2 ),
92  'formatMessage test 2'
93  );
94 
95  $result->reset();
97  $status->warning( 'mainpage' );
98  $status->warning( 'parentheses', 'foobar' );
99  $status->warning( $msg1 );
100  $status->warning( $msg2 );
101  $status->error( 'mainpage' );
102  $status->error( 'parentheses', 'foobar' );
103  $formatter->addMessagesFromStatus( 'status', $status );
104  $this->assertSame( $expect3, $result->getResultData(), 'Status test' );
105 
106  $this->assertSame(
107  array_map( [ $this, 'removeModuleTag' ], $expect3['errors'] ),
108  $formatter->arrayFromStatus( $status, 'error' ),
109  'arrayFromStatus test for error'
110  );
111  $this->assertSame(
112  array_map( [ $this, 'removeModuleTag' ], $expect3['warnings'] ),
113  $formatter->arrayFromStatus( $status, 'warning' ),
114  'arrayFromStatus test for warning'
115  );
116  }
117 
118  private function removeModuleTag( $s ) {
119  if ( is_array( $s ) ) {
120  unset( $s['module'] );
121  }
122  return $s;
123  }
124 
125  public static function provideErrorFormatter() {
126  $mainpageText = wfMessage( 'mainpage' )->inLanguage( 'de' )->useDatabase( false )->text();
127  $parensText = wfMessage( 'parentheses', 'foobar' )->inLanguage( 'de' )
128  ->useDatabase( false )->text();
129  $mainpageHTML = wfMessage( 'mainpage' )->inLanguage( 'en' )->parse();
130  $parensHTML = wfMessage( 'parentheses', 'foobar' )->inLanguage( 'en' )->parse();
133  $overriddenData = [ 'overriddenData' => true, ApiResult::META_TYPE => 'assoc' ];
134 
135  return [
136  $tmp = [ 'wikitext', 'de', false,
137  [
138  'errors' => [
139  [ 'code' => 'mainpage', 'text' => $mainpageText, 'module' => 'err', $C => 'text' ],
140  $I => 'error',
141  ],
142  'warnings' => [
143  [ 'code' => 'mainpage', 'text' => $mainpageText, 'module' => 'string', $C => 'text' ],
144  $I => 'warning',
145  ],
146  ],
147  [
148  'errors' => [
149  [ 'code' => 'overriddenCode', 'text' => $mainpageText,
150  'data' => $overriddenData, 'module' => 'errWithData', $C => 'text' ],
151  $I => 'error',
152  ],
153  'warnings' => [
154  [ 'code' => 'mainpage', 'text' => $mainpageText, 'module' => 'foo', $C => 'text' ],
155  [ 'code' => 'parentheses', 'text' => $parensText, 'module' => 'foo', $C => 'text' ],
156  [ 'code' => 'mainpage', 'text' => $mainpageText, 'module' => 'message', $C => 'text' ],
157  [ 'code' => 'overriddenCode', 'text' => $mainpageText,
158  'data' => $overriddenData, 'module' => 'messageWithData', $C => 'text' ],
159  $I => 'warning',
160  ],
161  ],
162  [
163  'errors' => [
164  [ 'code' => 'mainpage', 'text' => $mainpageText, 'module' => 'status', $C => 'text' ],
165  [ 'code' => 'parentheses', 'text' => $parensText, 'module' => 'status', $C => 'text' ],
166  $I => 'error',
167  ],
168  'warnings' => [
169  [ 'code' => 'mainpage', 'text' => $mainpageText, 'module' => 'status', $C => 'text' ],
170  [ 'code' => 'parentheses', 'text' => $parensText, 'module' => 'status', $C => 'text' ],
171  [ 'code' => 'overriddenCode', 'text' => $mainpageText,
172  'data' => $overriddenData, 'module' => 'status', $C => 'text' ],
173  $I => 'warning',
174  ],
175  ],
176  ],
177  [ 'plaintext' ] + $tmp, // For these messages, plaintext and wikitext are the same
178  [ 'html', 'en', true,
179  [
180  'errors' => [
181  [ 'code' => 'mainpage', 'html' => $mainpageHTML, 'module' => 'err', $C => 'html' ],
182  $I => 'error',
183  ],
184  'warnings' => [
185  [ 'code' => 'mainpage', 'html' => $mainpageHTML, 'module' => 'string', $C => 'html' ],
186  $I => 'warning',
187  ],
188  ],
189  [
190  'errors' => [
191  [ 'code' => 'overriddenCode', 'html' => $mainpageHTML,
192  'data' => $overriddenData, 'module' => 'errWithData', $C => 'html' ],
193  $I => 'error',
194  ],
195  'warnings' => [
196  [ 'code' => 'mainpage', 'html' => $mainpageHTML, 'module' => 'foo', $C => 'html' ],
197  [ 'code' => 'parentheses', 'html' => $parensHTML, 'module' => 'foo', $C => 'html' ],
198  [ 'code' => 'mainpage', 'html' => $mainpageHTML, 'module' => 'message', $C => 'html' ],
199  [ 'code' => 'overriddenCode', 'html' => $mainpageHTML,
200  'data' => $overriddenData, 'module' => 'messageWithData', $C => 'html' ],
201  $I => 'warning',
202  ],
203  ],
204  [
205  'errors' => [
206  [ 'code' => 'mainpage', 'html' => $mainpageHTML, 'module' => 'status', $C => 'html' ],
207  [ 'code' => 'parentheses', 'html' => $parensHTML, 'module' => 'status', $C => 'html' ],
208  $I => 'error',
209  ],
210  'warnings' => [
211  [ 'code' => 'mainpage', 'html' => $mainpageHTML, 'module' => 'status', $C => 'html' ],
212  [ 'code' => 'parentheses', 'html' => $parensHTML, 'module' => 'status', $C => 'html' ],
213  [ 'code' => 'overriddenCode', 'html' => $mainpageHTML,
214  'data' => $overriddenData, 'module' => 'status', $C => 'html' ],
215  $I => 'warning',
216  ],
217  ],
218  ],
219  [ 'raw', 'fr', true,
220  [
221  'errors' => [
222  [
223  'code' => 'mainpage',
224  'key' => 'mainpage',
225  'params' => [ $I => 'param' ],
226  'module' => 'err',
227  ],
228  $I => 'error',
229  ],
230  'warnings' => [
231  [
232  'code' => 'mainpage',
233  'key' => 'mainpage',
234  'params' => [ $I => 'param' ],
235  'module' => 'string',
236  ],
237  $I => 'warning',
238  ],
239  ],
240  [
241  'errors' => [
242  [
243  'code' => 'overriddenCode',
244  'key' => 'mainpage',
245  'params' => [ $I => 'param' ],
246  'data' => $overriddenData,
247  'module' => 'errWithData',
248  ],
249  $I => 'error',
250  ],
251  'warnings' => [
252  [
253  'code' => 'mainpage',
254  'key' => 'mainpage',
255  'params' => [ $I => 'param' ],
256  'module' => 'foo',
257  ],
258  [
259  'code' => 'parentheses',
260  'key' => 'parentheses',
261  'params' => [ 'foobar', $I => 'param' ],
262  'module' => 'foo',
263  ],
264  [
265  'code' => 'mainpage',
266  'key' => 'mainpage',
267  'params' => [ $I => 'param' ],
268  'module' => 'message',
269  ],
270  [
271  'code' => 'overriddenCode',
272  'key' => 'mainpage',
273  'params' => [ $I => 'param' ],
274  'data' => $overriddenData,
275  'module' => 'messageWithData',
276  ],
277  $I => 'warning',
278  ],
279  ],
280  [
281  'errors' => [
282  [
283  'code' => 'mainpage',
284  'key' => 'mainpage',
285  'params' => [ $I => 'param' ],
286  'module' => 'status',
287  ],
288  [
289  'code' => 'parentheses',
290  'key' => 'parentheses',
291  'params' => [ 'foobar', $I => 'param' ],
292  'module' => 'status',
293  ],
294  $I => 'error',
295  ],
296  'warnings' => [
297  [
298  'code' => 'mainpage',
299  'key' => 'mainpage',
300  'params' => [ $I => 'param' ],
301  'module' => 'status',
302  ],
303  [
304  'code' => 'parentheses',
305  'key' => 'parentheses',
306  'params' => [ 'foobar', $I => 'param' ],
307  'module' => 'status',
308  ],
309  [
310  'code' => 'overriddenCode',
311  'key' => 'mainpage',
312  'params' => [ $I => 'param' ],
313  'data' => $overriddenData,
314  'module' => 'status',
315  ],
316  $I => 'warning',
317  ],
318  ],
319  ],
320  [ 'none', 'fr', true,
321  [
322  'errors' => [
323  [ 'code' => 'mainpage', 'module' => 'err' ],
324  $I => 'error',
325  ],
326  'warnings' => [
327  [ 'code' => 'mainpage', 'module' => 'string' ],
328  $I => 'warning',
329  ],
330  ],
331  [
332  'errors' => [
333  [ 'code' => 'overriddenCode', 'data' => $overriddenData,
334  'module' => 'errWithData' ],
335  $I => 'error',
336  ],
337  'warnings' => [
338  [ 'code' => 'mainpage', 'module' => 'foo' ],
339  [ 'code' => 'parentheses', 'module' => 'foo' ],
340  [ 'code' => 'mainpage', 'module' => 'message' ],
341  [ 'code' => 'overriddenCode', 'data' => $overriddenData,
342  'module' => 'messageWithData' ],
343  $I => 'warning',
344  ],
345  ],
346  [
347  'errors' => [
348  [ 'code' => 'mainpage', 'module' => 'status' ],
349  [ 'code' => 'parentheses', 'module' => 'status' ],
350  $I => 'error',
351  ],
352  'warnings' => [
353  [ 'code' => 'mainpage', 'module' => 'status' ],
354  [ 'code' => 'parentheses', 'module' => 'status' ],
355  [ 'code' => 'overriddenCode', 'data' => $overriddenData, 'module' => 'status' ],
356  $I => 'warning',
357  ],
358  ],
359  ],
360  ];
361  }
362 
366  public function testErrorFormatterBC() {
367  $mainpagePlain = wfMessage( 'mainpage' )->useDatabase( false )->plain();
368  $parensPlain = wfMessage( 'parentheses', 'foobar' )->useDatabase( false )->plain();
369 
370  $result = new ApiResult( 8388608 );
371  $formatter = new ApiErrorFormatter_BackCompat( $result );
372 
373  $this->assertSame( 'en', $formatter->getLanguage()->getCode() );
374  $this->assertSame( 'bc', $formatter->getFormat() );
375 
376  $this->assertSame( [], $formatter->arrayFromStatus( Status::newGood() ) );
377 
378  $formatter->addWarning( 'string', 'mainpage' );
379  $formatter->addWarning( 'raw',
380  new RawMessage( 'Blah <kbd>kbd</kbd> <b>&lt;X&gt;</b> &#x1f61e;' )
381  );
382  $formatter->addError( 'err', 'mainpage' );
383  $this->assertSame( [
384  'error' => [
385  'code' => 'mainpage',
386  'info' => $mainpagePlain,
387  ],
388  'warnings' => [
389  'raw' => [
390  'warnings' => 'Blah "kbd" <X> 😞',
391  ApiResult::META_CONTENT => 'warnings',
392  ],
393  'string' => [
394  'warnings' => $mainpagePlain,
395  ApiResult::META_CONTENT => 'warnings',
396  ],
397  ],
398  ApiResult::META_TYPE => 'assoc',
399  ], $result->getResultData(), 'Simple test' );
400 
401  $result->reset();
402  $formatter->addWarning( 'foo', 'mainpage' );
403  $formatter->addWarning( 'foo', 'mainpage' );
404  $formatter->addWarning( 'xxx+foo', [ 'parentheses', 'foobar' ] );
405  $msg1 = wfMessage( 'mainpage' );
406  $formatter->addWarning( 'message', $msg1 );
407  $msg2 = new ApiMessage( 'mainpage', 'overriddenCode', [ 'overriddenData' => true ] );
408  $formatter->addWarning( 'messageWithData', $msg2 );
409  $formatter->addError( 'errWithData', $msg2 );
410  $formatter->addWarning( null, 'mainpage' );
411  $this->assertSame( [
412  'error' => [
413  'code' => 'overriddenCode',
414  'info' => $mainpagePlain,
415  'overriddenData' => true,
416  ],
417  'warnings' => [
418  'unknown' => [
419  'warnings' => $mainpagePlain,
420  ApiResult::META_CONTENT => 'warnings',
421  ],
422  'messageWithData' => [
423  'warnings' => $mainpagePlain,
424  ApiResult::META_CONTENT => 'warnings',
425  ],
426  'message' => [
427  'warnings' => $mainpagePlain,
428  ApiResult::META_CONTENT => 'warnings',
429  ],
430  'foo' => [
431  'warnings' => "$mainpagePlain\n$parensPlain",
432  ApiResult::META_CONTENT => 'warnings',
433  ],
434  ],
435  ApiResult::META_TYPE => 'assoc',
436  ], $result->getResultData(), 'Complex test' );
437 
438  $this->assertSame(
439  [
440  'code' => 'mainpage',
441  'info' => 'Main Page',
442  ],
443  $formatter->formatMessage( $msg1 )
444  );
445  $this->assertSame(
446  [
447  'code' => 'overriddenCode',
448  'info' => 'Main Page',
449  'overriddenData' => true,
450  ],
451  $formatter->formatMessage( $msg2 )
452  );
453 
454  $result->reset();
456  $status->warning( 'mainpage' );
457  $status->warning( 'parentheses', 'foobar' );
458  $status->warning( $msg1 );
459  $status->warning( $msg2 );
460  $status->error( 'mainpage' );
461  $status->error( 'parentheses', 'foobar' );
462  $formatter->addMessagesFromStatus( 'status', $status );
463  $this->assertSame( [
464  'error' => [
465  'code' => 'mainpage',
466  'info' => $mainpagePlain,
467  ],
468  'warnings' => [
469  'status' => [
470  'warnings' => "$mainpagePlain\n$parensPlain",
471  ApiResult::META_CONTENT => 'warnings',
472  ],
473  ],
474  ApiResult::META_TYPE => 'assoc',
475  ], $result->getResultData(), 'Status test' );
476 
478  $this->assertSame(
479  [
480  [
481  'message' => 'mainpage',
482  'params' => [ $I => 'param' ],
483  'code' => 'mainpage',
484  'type' => 'error',
485  ],
486  [
487  'message' => 'parentheses',
488  'params' => [ 'foobar', $I => 'param' ],
489  'code' => 'parentheses',
490  'type' => 'error',
491  ],
492  $I => 'error',
493  ],
494  $formatter->arrayFromStatus( $status, 'error' ),
495  'arrayFromStatus test for error'
496  );
497  $this->assertSame(
498  [
499  [
500  'message' => 'mainpage',
501  'params' => [ $I => 'param' ],
502  'code' => 'mainpage',
503  'type' => 'warning',
504  ],
505  [
506  'message' => 'parentheses',
507  'params' => [ 'foobar', $I => 'param' ],
508  'code' => 'parentheses',
509  'type' => 'warning',
510  ],
511  [
512  'message' => 'mainpage',
513  'params' => [ $I => 'param' ],
514  'code' => 'mainpage',
515  'type' => 'warning',
516  ],
517  [
518  'message' => 'mainpage',
519  'params' => [ $I => 'param' ],
520  'code' => 'overriddenCode',
521  'type' => 'warning',
522  ],
523  $I => 'warning',
524  ],
525  $formatter->arrayFromStatus( $status, 'warning' ),
526  'arrayFromStatus test for warning'
527  );
528 
529  $result->reset();
530  $result->addValue( null, 'error', [ 'bogus' ] );
531  $formatter->addError( 'err', 'mainpage' );
532  $this->assertSame( [
533  'error' => [
534  'code' => 'mainpage',
535  'info' => $mainpagePlain,
536  ],
537  ApiResult::META_TYPE => 'assoc',
538  ], $result->getResultData(), 'Overwrites bogus "error" value with real error' );
539  }
540 
549  public function testGetMessageFromException( $exception, $options, $expect ) {
550  $result = new ApiResult( 8388608 );
551  $formatter = new ApiErrorFormatter( $result, Language::factory( 'en' ), 'html', false );
552 
553  $msg = $formatter->getMessageFromException( $exception, $options );
554  $this->assertInstanceOf( Message::class, $msg );
555  $this->assertInstanceOf( IApiMessage::class, $msg );
556  $this->assertSame( $expect, [
557  'text' => $msg->parse(),
558  'code' => $msg->getApiCode(),
559  'data' => $msg->getApiData(),
560  ] );
561 
562  $expectFormatted = $formatter->formatMessage( $msg );
563  $formatted = $formatter->formatException( $exception, $options );
564  $this->assertSame( $expectFormatted, $formatted );
565  }
566 
574  public function testGetMessageFromException_BC( $exception, $options, $expect ) {
575  $result = new ApiResult( 8388608 );
576  $formatter = new ApiErrorFormatter_BackCompat( $result );
577 
578  $msg = $formatter->getMessageFromException( $exception, $options );
579  $this->assertInstanceOf( Message::class, $msg );
580  $this->assertInstanceOf( IApiMessage::class, $msg );
581  $this->assertSame( $expect, [
582  'text' => $msg->parse(),
583  'code' => $msg->getApiCode(),
584  'data' => $msg->getApiData(),
585  ] );
586 
587  $expectFormatted = $formatter->formatMessage( $msg );
588  $formatted = $formatter->formatException( $exception, $options );
589  $this->assertSame( $expectFormatted, $formatted );
590  $formatted = $formatter->formatException( $exception, $options + [ 'bc' => true ] );
591  $this->assertSame( $expectFormatted['info'], $formatted );
592  }
593 
594  public static function provideGetMessageFromException() {
595  return [
596  'Normal exception' => [
597  new RuntimeException( '<b>Something broke!</b>' ),
598  [],
599  [
600  'text' => '&#60;b&#62;Something broke!&#60;/b&#62;',
601  'code' => 'internal_api_error_RuntimeException',
602  'data' => [
603  'errorclass' => 'RuntimeException',
604  ],
605  ]
606  ],
607  'Normal exception, wrapped' => [
608  new RuntimeException( '<b>Something broke!</b>' ),
609  [ 'wrap' => 'parentheses', 'code' => 'some-code', 'data' => [ 'foo' => 'bar', 'baz' => 42 ] ],
610  [
611  'text' => '(&#60;b&#62;Something broke!&#60;/b&#62;)',
612  'code' => 'some-code',
613  'data' => [ 'foo' => 'bar', 'baz' => 42 ],
614  ]
615  ],
616  'LocalizedException' => [
617  new LocalizedException( [ 'returnto', '<b>FooBar</b>' ] ),
618  [],
619  [
620  'text' => 'Return to <b>FooBar</b>.',
621  'code' => 'returnto',
622  'data' => [],
623  ]
624  ],
625  'LocalizedException, wrapped' => [
626  new LocalizedException( [ 'returnto', '<b>FooBar</b>' ] ),
627  [ 'wrap' => 'parentheses', 'code' => 'some-code', 'data' => [ 'foo' => 'bar', 'baz' => 42 ] ],
628  [
629  'text' => 'Return to <b>FooBar</b>.',
630  'code' => 'some-code',
631  'data' => [ 'foo' => 'bar', 'baz' => 42 ],
632  ]
633  ],
634  ];
635  }
636 
643  $result = new ApiResult( 8388608 );
644  $formatter = new ApiErrorFormatter( $result, Language::factory( 'qqx' ), 'plaintext', false );
645 
647  $status->warning( 'mainpage' );
648  $status->warning( 'parentheses', 'foobar' );
649  $status->warning( wfMessage( 'mainpage' ) );
650  $status->error( 'mainpage' );
651  $status->error( 'parentheses', 'foobaz' );
652  $formatter->addMessagesFromStatus( 'status', $status, [ 'warning', 'error' ], [ 'mainpage' ] );
653  $this->assertSame( [
654  'errors' => [
655  [
656  'code' => 'parentheses',
657  'text' => '(parentheses: foobaz)',
658  'module' => 'status',
659  ApiResult::META_CONTENT => 'text',
660  ],
662  ],
663  'warnings' => [
664  [
665  'code' => 'parentheses',
666  'text' => '(parentheses: foobar)',
667  'module' => 'status',
668  ApiResult::META_CONTENT => 'text',
669  ],
671  ],
672  ApiResult::META_TYPE => 'assoc',
673  ], $result->getResultData() );
674  }
675 
682  public function testIsValidApiCode( $code, $expect ) {
683  $this->assertSame( $expect, ApiErrorFormatter::isValidApiCode( $code ) );
684  }
685 
686  public static function provideIsValidApiCode() {
687  return [
688  [ 'foo-bar_Baz123', true ],
689  [ 'foo bar', false ],
690  [ 'foo\\bar', false ],
691  [ 'internal_api_error_foo\\bar baz', true ],
692  ];
693  }
694 
695 }
Formats errors and warnings for the API, and add them to the associated ApiResult.
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
if(!isset( $args[0])) $lang
static isValidApiCode( $code)
Test whether a code is a valid API error code.
testIsValidApiCode( $code, $expect)
provideIsValidApiCode ApiErrorFormatter::isValidApiCode
const META_TYPE
Key for the &#39;type&#39; metadata item.
Definition: ApiResult.php:110
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1980
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:1982
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action, or null $user:User who performed the tagging when the tagging is subsequent to the action, or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy:boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
Definition: hooks.txt:1263
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt
Basic localized exception.
testAddMessagesFromStatus_filter()
ApiErrorFormatter::addMessagesFromStatus ApiErrorFormatter::addWarningOrError ApiErrorFormatter::form...
testErrorFormatter( $format, $lang, $useDB, $expect1, $expect2, $expect3)
ApiErrorFormatter provideErrorFormatter.
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:81
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:1982
testGetMessageFromException( $exception, $options, $expect)
provideGetMessageFromException ApiErrorFormatter::getMessageFromException ApiErrorFormatter::formatEx...
Extension of Message implementing IApiMessage.
Definition: ApiMessage.php:26
Format errors and warnings in the old style, for backwards compatibility.
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:780
static factory( $code)
Get a cached or new language object for a given language code.
Definition: Language.php:215
This class represents the result of the API operations.
Definition: ApiResult.php:35
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
Definition: hooks.txt:780
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
const META_INDEXED_TAG_NAME
Key for the &#39;indexed tag name&#39; metadata item.
Definition: ApiResult.php:72
testErrorFormatterBC()
ApiErrorFormatter_BackCompat.
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
Variant of the Message class.
Definition: RawMessage.php:34
testErrorFormatterBasics()
ApiErrorFormatter.
testNewWithFormat()
ApiErrorFormatter ApiErrorFormatter_BackCompat.
testGetMessageFromException_BC( $exception, $options, $expect)
provideGetMessageFromException ApiErrorFormatter_BackCompat::formatException
const META_CONTENT
Key for the &#39;content&#39; metadata item.
Definition: ApiResult.php:90