MediaWiki  1.28.1
WikiPageTest.php
Go to the documentation of this file.
1 <?php
2 
10 
11  protected $pages_to_delete;
12 
13  function __construct( $name = null, array $data = [], $dataName = '' ) {
14  parent::__construct( $name, $data, $dataName );
15 
16  $this->tablesUsed = array_merge(
17  $this->tablesUsed,
18  [ 'page',
19  'revision',
20  'text',
21 
22  'recentchanges',
23  'logging',
24 
25  'page_props',
26  'pagelinks',
27  'categorylinks',
28  'langlinks',
29  'externallinks',
30  'imagelinks',
31  'templatelinks',
32  'iwlinks' ] );
33  }
34 
35  protected function setUp() {
36  parent::setUp();
37  $this->pages_to_delete = [];
38 
39  LinkCache::singleton()->clear(); # avoid cached redirect status, etc
40  }
41 
42  protected function tearDown() {
43  foreach ( $this->pages_to_delete as $p ) {
44  /* @var $p WikiPage */
45 
46  try {
47  if ( $p->exists() ) {
48  $p->doDeleteArticle( "testing done." );
49  }
50  } catch ( MWException $ex ) {
51  // fail silently
52  }
53  }
54  parent::tearDown();
55  }
56 
62  protected function newPage( $title, $model = null ) {
63  if ( is_string( $title ) ) {
64  $ns = $this->getDefaultWikitextNS();
66  }
67 
68  $p = new WikiPage( $title );
69 
70  $this->pages_to_delete[] = $p;
71 
72  return $p;
73  }
74 
82  protected function createPage( $page, $text, $model = null ) {
83  if ( is_string( $page ) || $page instanceof Title ) {
84  $page = $this->newPage( $page, $model );
85  }
86 
87  $content = ContentHandler::makeContent( $text, $page->getTitle(), $model );
88  $page->doEditContent( $content, "testing", EDIT_NEW );
89 
90  return $page;
91  }
92 
99  public function testDoEditContent() {
100  $page = $this->newPage( "WikiPageTest_testDoEditContent" );
101  $title = $page->getTitle();
102 
104  "[[Lorem ipsum]] dolor sit amet, consetetur sadipscing elitr, sed diam "
105  . " nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat.",
106  $title,
108  );
109 
110  $page->doEditContent( $content, "[[testing]] 1" );
111 
112  $this->assertTrue( $title->getArticleID() > 0, "Title object should have new page id" );
113  $this->assertTrue( $page->getId() > 0, "WikiPage should have new page id" );
114  $this->assertTrue( $title->exists(), "Title object should indicate that the page now exists" );
115  $this->assertTrue( $page->exists(), "WikiPage object should indicate that the page now exists" );
116 
117  $id = $page->getId();
118 
119  # ------------------------
120  $dbr = wfGetDB( DB_SLAVE );
121  $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
122  $n = $res->numRows();
123  $res->free();
124 
125  $this->assertEquals( 1, $n, 'pagelinks should contain one link from the page' );
126 
127  # ------------------------
128  $page = new WikiPage( $title );
129 
130  $retrieved = $page->getContent();
131  $this->assertTrue( $content->equals( $retrieved ), 'retrieved content doesn\'t equal original' );
132 
133  # ------------------------
135  "At vero eos et accusam et justo duo [[dolores]] et ea rebum. "
136  . "Stet clita kasd [[gubergren]], no sea takimata sanctus est.",
137  $title,
139  );
140 
141  $page->doEditContent( $content, "testing 2" );
142 
143  # ------------------------
144  $page = new WikiPage( $title );
145 
146  $retrieved = $page->getContent();
147  $this->assertTrue( $content->equals( $retrieved ), 'retrieved content doesn\'t equal original' );
148 
149  # ------------------------
150  $dbr = wfGetDB( DB_SLAVE );
151  $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
152  $n = $res->numRows();
153  $res->free();
154 
155  $this->assertEquals( 2, $n, 'pagelinks should contain two links from the page' );
156  }
157 
162  public function testDoEdit() {
163  $this->hideDeprecated( "WikiPage::doEdit" );
164  $this->hideDeprecated( "WikiPage::getText" );
165  $this->hideDeprecated( "Revision::getText" );
166 
167  // NOTE: assume help namespace will default to wikitext
168  $title = Title::newFromText( "Help:WikiPageTest_testDoEdit" );
169 
170  $page = $this->newPage( $title );
171 
172  $text = "[[Lorem ipsum]] dolor sit amet, consetetur sadipscing elitr, sed diam "
173  . " nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat.";
174 
175  $page->doEdit( $text, "[[testing]] 1" );
176 
177  $this->assertTrue( $title->getArticleID() > 0, "Title object should have new page id" );
178  $this->assertTrue( $page->getId() > 0, "WikiPage should have new page id" );
179  $this->assertTrue( $title->exists(), "Title object should indicate that the page now exists" );
180  $this->assertTrue( $page->exists(), "WikiPage object should indicate that the page now exists" );
181 
182  $id = $page->getId();
183 
184  # ------------------------
185  $dbr = wfGetDB( DB_SLAVE );
186  $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
187  $n = $res->numRows();
188  $res->free();
189 
190  $this->assertEquals( 1, $n, 'pagelinks should contain one link from the page' );
191 
192  # ------------------------
193  $page = new WikiPage( $title );
194 
195  $retrieved = $page->getText();
196  $this->assertEquals( $text, $retrieved, 'retrieved text doesn\'t equal original' );
197 
198  # ------------------------
199  $text = "At vero eos et accusam et justo duo [[dolores]] et ea rebum. "
200  . "Stet clita kasd [[gubergren]], no sea takimata sanctus est.";
201 
202  $page->doEdit( $text, "testing 2" );
203 
204  # ------------------------
205  $page = new WikiPage( $title );
206 
207  $retrieved = $page->getText();
208  $this->assertEquals( $text, $retrieved, 'retrieved text doesn\'t equal original' );
209 
210  # ------------------------
211  $dbr = wfGetDB( DB_SLAVE );
212  $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
213  $n = $res->numRows();
214  $res->free();
215 
216  $this->assertEquals( 2, $n, 'pagelinks should contain two links from the page' );
217  }
218 
222  public function testDoDeleteArticle() {
223  $page = $this->createPage(
224  "WikiPageTest_testDoDeleteArticle",
225  "[[original text]] foo",
227  );
228  $id = $page->getId();
229 
230  $page->doDeleteArticle( "testing deletion" );
231 
232  $this->assertFalse(
233  $page->getTitle()->getArticleID() > 0,
234  "Title object should now have page id 0"
235  );
236  $this->assertFalse( $page->getId() > 0, "WikiPage should now have page id 0" );
237  $this->assertFalse(
238  $page->exists(),
239  "WikiPage::exists should return false after page was deleted"
240  );
241  $this->assertNull(
242  $page->getContent(),
243  "WikiPage::getContent should return null after page was deleted"
244  );
245  $this->assertFalse(
246  $page->getText(),
247  "WikiPage::getText should return false after page was deleted"
248  );
249 
250  $t = Title::newFromText( $page->getTitle()->getPrefixedText() );
251  $this->assertFalse(
252  $t->exists(),
253  "Title::exists should return false after page was deleted"
254  );
255 
256  // Run the job queue
258  $jobs = new RunJobs;
259  $jobs->loadParamsAndArgs( null, [ 'quiet' => true ], null );
260  $jobs->execute();
261 
262  # ------------------------
263  $dbr = wfGetDB( DB_SLAVE );
264  $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
265  $n = $res->numRows();
266  $res->free();
267 
268  $this->assertEquals( 0, $n, 'pagelinks should contain no more links from the page' );
269  }
270 
274  public function testDoDeleteUpdates() {
275  $page = $this->createPage(
276  "WikiPageTest_testDoDeleteArticle",
277  "[[original text]] foo",
279  );
280  $id = $page->getId();
281 
282  // Similar to MovePage logic
283  wfGetDB( DB_MASTER )->delete( 'page', [ 'page_id' => $id ], __METHOD__ );
284  $page->doDeleteUpdates( $id );
285 
286  // Run the job queue
288  $jobs = new RunJobs;
289  $jobs->loadParamsAndArgs( null, [ 'quiet' => true ], null );
290  $jobs->execute();
291 
292  # ------------------------
293  $dbr = wfGetDB( DB_SLAVE );
294  $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
295  $n = $res->numRows();
296  $res->free();
297 
298  $this->assertEquals( 0, $n, 'pagelinks should contain no more links from the page' );
299  }
300 
304  public function testGetRevision() {
305  $page = $this->newPage( "WikiPageTest_testGetRevision" );
306 
307  $rev = $page->getRevision();
308  $this->assertNull( $rev );
309 
310  # -----------------
311  $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT );
312 
313  $rev = $page->getRevision();
314 
315  $this->assertEquals( $page->getLatest(), $rev->getId() );
316  $this->assertEquals( "some text", $rev->getContent()->getNativeData() );
317  }
318 
322  public function testGetContent() {
323  $page = $this->newPage( "WikiPageTest_testGetContent" );
324 
325  $content = $page->getContent();
326  $this->assertNull( $content );
327 
328  # -----------------
329  $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT );
330 
331  $content = $page->getContent();
332  $this->assertEquals( "some text", $content->getNativeData() );
333  }
334 
338  public function testGetText() {
339  $this->hideDeprecated( "WikiPage::getText" );
340 
341  $page = $this->newPage( "WikiPageTest_testGetText" );
342 
343  $text = $page->getText();
344  $this->assertFalse( $text );
345 
346  # -----------------
347  $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT );
348 
349  $text = $page->getText();
350  $this->assertEquals( "some text", $text );
351  }
352 
356  public function testGetContentModel() {
357  global $wgContentHandlerUseDB;
358 
359  if ( !$wgContentHandlerUseDB ) {
360  $this->markTestSkipped( '$wgContentHandlerUseDB is disabled' );
361  }
362 
363  $page = $this->createPage(
364  "WikiPageTest_testGetContentModel",
365  "some text",
367  );
368 
369  $page = new WikiPage( $page->getTitle() );
370  $this->assertEquals( CONTENT_MODEL_JAVASCRIPT, $page->getContentModel() );
371  }
372 
376  public function testGetContentHandler() {
377  global $wgContentHandlerUseDB;
378 
379  if ( !$wgContentHandlerUseDB ) {
380  $this->markTestSkipped( '$wgContentHandlerUseDB is disabled' );
381  }
382 
383  $page = $this->createPage(
384  "WikiPageTest_testGetContentHandler",
385  "some text",
387  );
388 
389  $page = new WikiPage( $page->getTitle() );
390  $this->assertEquals( 'JavaScriptContentHandler', get_class( $page->getContentHandler() ) );
391  }
392 
396  public function testExists() {
397  $page = $this->newPage( "WikiPageTest_testExists" );
398  $this->assertFalse( $page->exists() );
399 
400  # -----------------
401  $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT );
402  $this->assertTrue( $page->exists() );
403 
404  $page = new WikiPage( $page->getTitle() );
405  $this->assertTrue( $page->exists() );
406 
407  # -----------------
408  $page->doDeleteArticle( "done testing" );
409  $this->assertFalse( $page->exists() );
410 
411  $page = new WikiPage( $page->getTitle() );
412  $this->assertFalse( $page->exists() );
413  }
414 
415  public static function provideHasViewableContent() {
416  return [
417  [ 'WikiPageTest_testHasViewableContent', false, true ],
418  [ 'Special:WikiPageTest_testHasViewableContent', false ],
419  [ 'MediaWiki:WikiPageTest_testHasViewableContent', false ],
420  [ 'Special:Userlogin', true ],
421  [ 'MediaWiki:help', true ],
422  ];
423  }
424 
429  public function testHasViewableContent( $title, $viewable, $create = false ) {
430  $page = $this->newPage( $title );
431  $this->assertEquals( $viewable, $page->hasViewableContent() );
432 
433  if ( $create ) {
434  $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT );
435  $this->assertTrue( $page->hasViewableContent() );
436 
437  $page = new WikiPage( $page->getTitle() );
438  $this->assertTrue( $page->hasViewableContent() );
439  }
440  }
441 
442  public static function provideGetRedirectTarget() {
443  return [
444  [ 'WikiPageTest_testGetRedirectTarget_1', CONTENT_MODEL_WIKITEXT, "hello world", null ],
445  [
446  'WikiPageTest_testGetRedirectTarget_2',
448  "#REDIRECT [[hello world]]",
449  "Hello world"
450  ],
451  ];
452  }
453 
458  public function testGetRedirectTarget( $title, $model, $text, $target ) {
459  $this->setMwGlobals( [
460  'wgCapitalLinks' => true,
461  ] );
462 
463  $page = $this->createPage( $title, $text, $model );
464 
465  # sanity check, because this test seems to fail for no reason for some people.
466  $c = $page->getContent();
467  $this->assertEquals( 'WikitextContent', get_class( $c ) );
468 
469  # now, test the actual redirect
470  $t = $page->getRedirectTarget();
471  $this->assertEquals( $target, is_null( $t ) ? null : $t->getPrefixedText() );
472  }
473 
478  public function testIsRedirect( $title, $model, $text, $target ) {
479  $page = $this->createPage( $title, $text, $model );
480  $this->assertEquals( !is_null( $target ), $page->isRedirect() );
481  }
482 
483  public static function provideIsCountable() {
484  return [
485 
486  // any
487  [ 'WikiPageTest_testIsCountable',
489  '',
490  'any',
491  true
492  ],
493  [ 'WikiPageTest_testIsCountable',
495  'Foo',
496  'any',
497  true
498  ],
499 
500  // comma
501  [ 'WikiPageTest_testIsCountable',
503  'Foo',
504  'comma',
505  false
506  ],
507  [ 'WikiPageTest_testIsCountable',
509  'Foo, bar',
510  'comma',
511  true
512  ],
513 
514  // link
515  [ 'WikiPageTest_testIsCountable',
517  'Foo',
518  'link',
519  false
520  ],
521  [ 'WikiPageTest_testIsCountable',
523  'Foo [[bar]]',
524  'link',
525  true
526  ],
527 
528  // redirects
529  [ 'WikiPageTest_testIsCountable',
531  '#REDIRECT [[bar]]',
532  'any',
533  false
534  ],
535  [ 'WikiPageTest_testIsCountable',
537  '#REDIRECT [[bar]]',
538  'comma',
539  false
540  ],
541  [ 'WikiPageTest_testIsCountable',
543  '#REDIRECT [[bar]]',
544  'link',
545  false
546  ],
547 
548  // not a content namespace
549  [ 'Talk:WikiPageTest_testIsCountable',
551  'Foo',
552  'any',
553  false
554  ],
555  [ 'Talk:WikiPageTest_testIsCountable',
557  'Foo, bar',
558  'comma',
559  false
560  ],
561  [ 'Talk:WikiPageTest_testIsCountable',
563  'Foo [[bar]]',
564  'link',
565  false
566  ],
567 
568  // not a content namespace, different model
569  [ 'MediaWiki:WikiPageTest_testIsCountable.js',
570  null,
571  'Foo',
572  'any',
573  false
574  ],
575  [ 'MediaWiki:WikiPageTest_testIsCountable.js',
576  null,
577  'Foo, bar',
578  'comma',
579  false
580  ],
581  [ 'MediaWiki:WikiPageTest_testIsCountable.js',
582  null,
583  'Foo [[bar]]',
584  'link',
585  false
586  ],
587  ];
588  }
589 
594  public function testIsCountable( $title, $model, $text, $mode, $expected ) {
595  global $wgContentHandlerUseDB;
596 
597  $this->setMwGlobals( 'wgArticleCountMethod', $mode );
598 
600 
601  if ( !$wgContentHandlerUseDB
602  && $model
604  ) {
605  $this->markTestSkipped( "Can not use non-default content model $model for "
606  . $title->getPrefixedDBkey() . " with \$wgContentHandlerUseDB disabled." );
607  }
608 
609  $page = $this->createPage( $title, $text, $model );
610 
611  $editInfo = $page->prepareContentForEdit( $page->getContent() );
612 
613  $v = $page->isCountable();
614  $w = $page->isCountable( $editInfo );
615 
616  $this->assertEquals(
617  $expected,
618  $v,
619  "isCountable( null ) returned unexpected value " . var_export( $v, true )
620  . " instead of " . var_export( $expected, true )
621  . " in mode `$mode` for text \"$text\""
622  );
623 
624  $this->assertEquals(
625  $expected,
626  $w,
627  "isCountable( \$editInfo ) returned unexpected value " . var_export( $v, true )
628  . " instead of " . var_export( $expected, true )
629  . " in mode `$mode` for text \"$text\""
630  );
631  }
632 
633  public static function provideGetParserOutput() {
634  return [
635  [ CONTENT_MODEL_WIKITEXT, "hello ''world''\n", "<p>hello <i>world</i></p>" ],
636  // @todo more...?
637  ];
638  }
639 
644  public function testGetParserOutput( $model, $text, $expectedHtml ) {
645  $page = $this->createPage( 'WikiPageTest_testGetParserOutput', $text, $model );
646 
647  $opt = $page->makeParserOptions( 'canonical' );
648  $po = $page->getParserOutput( $opt );
649  $text = $po->getText();
650 
651  $text = trim( preg_replace( '/<!--.*?-->/sm', '', $text ) ); # strip injected comments
652  $text = preg_replace( '!\s*(</p>)!sm', '\1', $text ); # don't let tidy confuse us
653 
654  $this->assertEquals( $expectedHtml, $text );
655 
656  return $po;
657  }
658 
662  public function testGetParserOutput_nonexisting() {
663  static $count = 0;
664  $count++;
665 
666  $page = new WikiPage( new Title( "WikiPageTest_testGetParserOutput_nonexisting_$count" ) );
667 
668  $opt = new ParserOptions();
669  $po = $page->getParserOutput( $opt );
670 
671  $this->assertFalse( $po, "getParserOutput() shall return false for non-existing pages." );
672  }
673 
677  public function testGetParserOutput_badrev() {
678  $page = $this->createPage( 'WikiPageTest_testGetParserOutput', "dummy", CONTENT_MODEL_WIKITEXT );
679 
680  $opt = new ParserOptions();
681  $po = $page->getParserOutput( $opt, $page->getLatest() + 1234 );
682 
683  // @todo would be neat to also test deleted revision
684 
685  $this->assertFalse( $po, "getParserOutput() shall return false for non-existing revisions." );
686  }
687 
688  public static $sections =
689 
690  "Intro
691 
692 == stuff ==
693 hello world
694 
695 == test ==
696 just a test
697 
698 == foo ==
699 more stuff
700 ";
701 
702  public function dataReplaceSection() {
703  // NOTE: assume the Help namespace to contain wikitext
704  return [
705  [ 'Help:WikiPageTest_testReplaceSection',
706  CONTENT_MODEL_WIKITEXT,
707  WikiPageTest::$sections,
708  "0",
709  "No more",
710  null,
711  trim( preg_replace( '/^Intro/sm', 'No more', WikiPageTest::$sections ) )
712  ],
713  [ 'Help:WikiPageTest_testReplaceSection',
714  CONTENT_MODEL_WIKITEXT,
715  WikiPageTest::$sections,
716  "",
717  "No more",
718  null,
719  "No more"
720  ],
721  [ 'Help:WikiPageTest_testReplaceSection',
722  CONTENT_MODEL_WIKITEXT,
723  WikiPageTest::$sections,
724  "2",
725  "== TEST ==\nmore fun",
726  null,
727  trim( preg_replace( '/^== test ==.*== foo ==/sm',
728  "== TEST ==\nmore fun\n\n== foo ==",
729  WikiPageTest::$sections ) )
730  ],
731  [ 'Help:WikiPageTest_testReplaceSection',
732  CONTENT_MODEL_WIKITEXT,
733  WikiPageTest::$sections,
734  "8",
735  "No more",
736  null,
737  trim( WikiPageTest::$sections )
738  ],
739  [ 'Help:WikiPageTest_testReplaceSection',
740  CONTENT_MODEL_WIKITEXT,
741  WikiPageTest::$sections,
742  "new",
743  "No more",
744  "New",
745  trim( WikiPageTest::$sections ) . "\n\n== New ==\n\nNo more"
746  ],
747  ];
748  }
749 
754  public function testReplaceSectionContent( $title, $model, $text, $section,
755  $with, $sectionTitle, $expected
756  ) {
757  $page = $this->createPage( $title, $text, $model );
758 
759  $content = ContentHandler::makeContent( $with, $page->getTitle(), $page->getContentModel() );
760  $c = $page->replaceSectionContent( $section, $content, $sectionTitle );
761 
762  $this->assertEquals( $expected, is_null( $c ) ? null : trim( $c->getNativeData() ) );
763  }
764 
769  public function testReplaceSectionAtRev( $title, $model, $text, $section,
770  $with, $sectionTitle, $expected
771  ) {
772  $page = $this->createPage( $title, $text, $model );
773  $baseRevId = $page->getLatest();
774 
775  $content = ContentHandler::makeContent( $with, $page->getTitle(), $page->getContentModel() );
776  $c = $page->replaceSectionAtRev( $section, $content, $sectionTitle, $baseRevId );
777 
778  $this->assertEquals( $expected, is_null( $c ) ? null : trim( $c->getNativeData() ) );
779  }
780 
781  /* @todo FIXME: fix this!
782  public function testGetUndoText() {
783  $this->markTestSkippedIfNoDiff3();
784 
785  $text = "one";
786  $page = $this->createPage( "WikiPageTest_testGetUndoText", $text );
787  $rev1 = $page->getRevision();
788 
789  $text .= "\n\ntwo";
790  $page->doEditContent(
791  ContentHandler::makeContent( $text, $page->getTitle() ),
792  "adding section two"
793  );
794  $rev2 = $page->getRevision();
795 
796  $text .= "\n\nthree";
797  $page->doEditContent(
798  ContentHandler::makeContent( $text, $page->getTitle() ),
799  "adding section three"
800  );
801  $rev3 = $page->getRevision();
802 
803  $text .= "\n\nfour";
804  $page->doEditContent(
805  ContentHandler::makeContent( $text, $page->getTitle() ),
806  "adding section four"
807  );
808  $rev4 = $page->getRevision();
809 
810  $text .= "\n\nfive";
811  $page->doEditContent(
812  ContentHandler::makeContent( $text, $page->getTitle() ),
813  "adding section five"
814  );
815  $rev5 = $page->getRevision();
816 
817  $text .= "\n\nsix";
818  $page->doEditContent(
819  ContentHandler::makeContent( $text, $page->getTitle() ),
820  "adding section six"
821  );
822  $rev6 = $page->getRevision();
823 
824  $undo6 = $page->getUndoText( $rev6 );
825  if ( $undo6 === false ) $this->fail( "getUndoText failed for rev6" );
826  $this->assertEquals( "one\n\ntwo\n\nthree\n\nfour\n\nfive", $undo6 );
827 
828  $undo3 = $page->getUndoText( $rev4, $rev2 );
829  if ( $undo3 === false ) $this->fail( "getUndoText failed for rev4..rev2" );
830  $this->assertEquals( "one\n\ntwo\n\nfive", $undo3 );
831 
832  $undo2 = $page->getUndoText( $rev2 );
833  if ( $undo2 === false ) $this->fail( "getUndoText failed for rev2" );
834  $this->assertEquals( "one\n\nfive", $undo2 );
835  }
836  */
837 
842  public function broken_testDoRollback() {
843  $admin = new User();
844  $admin->setName( "Admin" );
845 
846  $text = "one";
847  $page = $this->newPage( "WikiPageTest_testDoRollback" );
848  $page->doEditContent( ContentHandler::makeContent( $text, $page->getTitle() ),
849  "section one", EDIT_NEW, false, $admin );
850 
851  $user1 = new User();
852  $user1->setName( "127.0.1.11" );
853  $text .= "\n\ntwo";
854  $page = new WikiPage( $page->getTitle() );
855  $page->doEditContent( ContentHandler::makeContent( $text, $page->getTitle() ),
856  "adding section two", 0, false, $user1 );
857 
858  $user2 = new User();
859  $user2->setName( "127.0.2.13" );
860  $text .= "\n\nthree";
861  $page = new WikiPage( $page->getTitle() );
862  $page->doEditContent( ContentHandler::makeContent( $text, $page->getTitle() ),
863  "adding section three", 0, false, $user2 );
864 
865  # we are having issues with doRollback spuriously failing. Apparently
866  # the last revision somehow goes missing or not committed under some
867  # circumstances. So, make sure the last revision has the right user name.
868  $dbr = wfGetDB( DB_SLAVE );
869  $this->assertEquals( 3, Revision::countByPageId( $dbr, $page->getId() ) );
870 
871  $page = new WikiPage( $page->getTitle() );
872  $rev3 = $page->getRevision();
873  $this->assertEquals( '127.0.2.13', $rev3->getUserText() );
874 
875  $rev2 = $rev3->getPrevious();
876  $this->assertEquals( '127.0.1.11', $rev2->getUserText() );
877 
878  $rev1 = $rev2->getPrevious();
879  $this->assertEquals( 'Admin', $rev1->getUserText() );
880 
881  # now, try the actual rollback
882  $admin->addGroup( "sysop" ); # XXX: make the test user a sysop...
883  $token = $admin->getEditToken(
884  [ $page->getTitle()->getPrefixedText(), $user2->getName() ],
885  null
886  );
887  $errors = $page->doRollback(
888  $user2->getName(),
889  "testing revert",
890  $token,
891  false,
892  $details,
893  $admin
894  );
895 
896  if ( $errors ) {
897  $this->fail( "Rollback failed:\n" . print_r( $errors, true )
898  . ";\n" . print_r( $details, true ) );
899  }
900 
901  $page = new WikiPage( $page->getTitle() );
902  $this->assertEquals( $rev2->getSha1(), $page->getRevision()->getSha1(),
903  "rollback did not revert to the correct revision" );
904  $this->assertEquals( "one\n\ntwo", $page->getContent()->getNativeData() );
905  }
906 
911  public function testDoRollback() {
912  $admin = new User();
913  $admin->setName( "Admin" );
914 
915  $text = "one";
916  $page = $this->newPage( "WikiPageTest_testDoRollback" );
917  $page->doEditContent(
918  ContentHandler::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT ),
919  "section one",
920  EDIT_NEW,
921  false,
922  $admin
923  );
924  $rev1 = $page->getRevision();
925 
926  $user1 = new User();
927  $user1->setName( "127.0.1.11" );
928  $text .= "\n\ntwo";
929  $page = new WikiPage( $page->getTitle() );
930  $page->doEditContent(
931  ContentHandler::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT ),
932  "adding section two",
933  0,
934  false,
935  $user1
936  );
937 
938  # now, try the rollback
939  $admin->addGroup( "sysop" ); # XXX: make the test user a sysop...
940  $token = $admin->getEditToken(
941  [ $page->getTitle()->getPrefixedText(), $user1->getName() ],
942  null
943  );
944  $errors = $page->doRollback(
945  $user1->getName(),
946  "testing revert",
947  $token,
948  false,
949  $details,
950  $admin
951  );
952 
953  if ( $errors ) {
954  $this->fail( "Rollback failed:\n" . print_r( $errors, true )
955  . ";\n" . print_r( $details, true ) );
956  }
957 
958  $page = new WikiPage( $page->getTitle() );
959  $this->assertEquals( $rev1->getSha1(), $page->getRevision()->getSha1(),
960  "rollback did not revert to the correct revision" );
961  $this->assertEquals( "one", $page->getContent()->getNativeData() );
962  }
963 
967  public function testDoRollbackFailureSameContent() {
968  $admin = new User();
969  $admin->setName( "Admin" );
970  $admin->addGroup( "sysop" ); # XXX: make the test user a sysop...
971 
972  $text = "one";
973  $page = $this->newPage( "WikiPageTest_testDoRollback" );
974  $page->doEditContent(
975  ContentHandler::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT ),
976  "section one",
977  EDIT_NEW,
978  false,
979  $admin
980  );
981  $rev1 = $page->getRevision();
982 
983  $user1 = new User();
984  $user1->setName( "127.0.1.11" );
985  $user1->addGroup( "sysop" ); # XXX: make the test user a sysop...
986  $text .= "\n\ntwo";
987  $page = new WikiPage( $page->getTitle() );
988  $page->doEditContent(
989  ContentHandler::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT ),
990  "adding section two",
991  0,
992  false,
993  $user1
994  );
995 
996  # now, do a the rollback from the same user was doing the edit before
997  $resultDetails = [];
998  $token = $user1->getEditToken(
999  [ $page->getTitle()->getPrefixedText(), $user1->getName() ],
1000  null
1001  );
1002  $errors = $page->doRollback(
1003  $user1->getName(),
1004  "testing revert same user",
1005  $token,
1006  false,
1007  $resultDetails,
1008  $admin
1009  );
1010 
1011  $this->assertEquals( [], $errors, "Rollback failed same user" );
1012 
1013  # now, try the rollback
1014  $resultDetails = [];
1015  $token = $admin->getEditToken(
1016  [ $page->getTitle()->getPrefixedText(), $user1->getName() ],
1017  null
1018  );
1019  $errors = $page->doRollback(
1020  $user1->getName(),
1021  "testing revert",
1022  $token,
1023  false,
1024  $resultDetails,
1025  $admin
1026  );
1027 
1028  $this->assertEquals( [ [ 'alreadyrolled', 'WikiPageTest testDoRollback',
1029  '127.0.1.11', 'Admin' ] ], $errors, "Rollback not failed" );
1030 
1031  $page = new WikiPage( $page->getTitle() );
1032  $this->assertEquals( $rev1->getSha1(), $page->getRevision()->getSha1(),
1033  "rollback did not revert to the correct revision" );
1034  $this->assertEquals( "one", $page->getContent()->getNativeData() );
1035  }
1036 
1037  public static function provideGetAutosummary() {
1038  return [
1039  [
1040  'Hello there, world!',
1041  '#REDIRECT [[Foo]]',
1042  0,
1043  '/^Redirected page .*Foo/'
1044  ],
1045 
1046  [
1047  null,
1048  'Hello world!',
1049  EDIT_NEW,
1050  '/^Created page .*Hello/'
1051  ],
1052 
1053  [
1054  'Hello there, world!',
1055  '',
1056  0,
1057  '/^Blanked/'
1058  ],
1059 
1060  [
1061  'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy
1062  eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam
1063  voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet
1064  clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.',
1065  'Hello world!',
1066  0,
1067  '/^Replaced .*Hello/'
1068  ],
1069 
1070  [
1071  'foo',
1072  'bar',
1073  0,
1074  '/^$/'
1075  ],
1076  ];
1077  }
1078 
1083  public function testGetAutosummary( $old, $new, $flags, $expected ) {
1084  $this->hideDeprecated( "WikiPage::getAutosummary" );
1085 
1086  $page = $this->newPage( "WikiPageTest_testGetAutosummary" );
1087 
1088  $summary = $page->getAutosummary( $old, $new, $flags );
1089 
1090  $this->assertTrue( (bool)preg_match( $expected, $summary ),
1091  "Autosummary didn't match expected pattern $expected: $summary" );
1092  }
1093 
1094  public static function provideGetAutoDeleteReason() {
1095  return [
1096  [
1097  [],
1098  false,
1099  false
1100  ],
1101 
1102  [
1103  [
1104  [ "first edit", null ],
1105  ],
1106  "/first edit.*only contributor/",
1107  false
1108  ],
1109 
1110  [
1111  [
1112  [ "first edit", null ],
1113  [ "second edit", null ],
1114  ],
1115  "/second edit.*only contributor/",
1116  true
1117  ],
1118 
1119  [
1120  [
1121  [ "first edit", "127.0.2.22" ],
1122  [ "second edit", "127.0.3.33" ],
1123  ],
1124  "/second edit/",
1125  true
1126  ],
1127 
1128  [
1129  [
1130  [
1131  "first edit: "
1132  . "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam "
1133  . " nonumy eirmod tempor invidunt ut labore et dolore magna "
1134  . "aliquyam erat, sed diam voluptua. At vero eos et accusam "
1135  . "et justo duo dolores et ea rebum. Stet clita kasd gubergren, "
1136  . "no sea takimata sanctus est Lorem ipsum dolor sit amet.'",
1137  null
1138  ],
1139  ],
1140  '/first edit:.*\.\.\."/',
1141  false
1142  ],
1143 
1144  [
1145  [
1146  [ "first edit", "127.0.2.22" ],
1147  [ "", "127.0.3.33" ],
1148  ],
1149  "/before blanking.*first edit/",
1150  true
1151  ],
1152 
1153  ];
1154  }
1155 
1160  public function testGetAutoDeleteReason( $edits, $expectedResult, $expectedHistory ) {
1161  global $wgUser;
1162 
1163  // NOTE: assume Help namespace to contain wikitext
1164  $page = $this->newPage( "Help:WikiPageTest_testGetAutoDeleteReason" );
1165 
1166  $c = 1;
1167 
1168  foreach ( $edits as $edit ) {
1169  $user = new User();
1170 
1171  if ( !empty( $edit[1] ) ) {
1172  $user->setName( $edit[1] );
1173  } else {
1174  $user = $wgUser;
1175  }
1176 
1177  $content = ContentHandler::makeContent( $edit[0], $page->getTitle(), $page->getContentModel() );
1178 
1179  $page->doEditContent( $content, "test edit $c", $c < 2 ? EDIT_NEW : 0, false, $user );
1180 
1181  $c += 1;
1182  }
1183 
1184  $reason = $page->getAutoDeleteReason( $hasHistory );
1185 
1186  if ( is_bool( $expectedResult ) || is_null( $expectedResult ) ) {
1187  $this->assertEquals( $expectedResult, $reason );
1188  } else {
1189  $this->assertTrue( (bool)preg_match( $expectedResult, $reason ),
1190  "Autosummary didn't match expected pattern $expectedResult: $reason" );
1191  }
1192 
1193  $this->assertEquals( $expectedHistory, $hasHistory,
1194  "expected \$hasHistory to be " . var_export( $expectedHistory, true ) );
1195 
1196  $page->doDeleteArticle( "done" );
1197  }
1198 
1199  public static function providePreSaveTransform() {
1200  return [
1201  [ 'hello this is ~~~',
1202  "hello this is [[Special:Contributions/127.0.0.1|127.0.0.1]]",
1203  ],
1204  [ 'hello \'\'this\'\' is <nowiki>~~~</nowiki>',
1205  'hello \'\'this\'\' is <nowiki>~~~</nowiki>',
1206  ],
1207  ];
1208  }
1209 
1213  public function testWikiPageFactory() {
1214  $title = Title::makeTitle( NS_FILE, 'Someimage.png' );
1215  $page = WikiPage::factory( $title );
1216  $this->assertEquals( 'WikiFilePage', get_class( $page ) );
1217 
1218  $title = Title::makeTitle( NS_CATEGORY, 'SomeCategory' );
1219  $page = WikiPage::factory( $title );
1220  $this->assertEquals( 'WikiCategoryPage', get_class( $page ) );
1221 
1222  $title = Title::makeTitle( NS_MAIN, 'SomePage' );
1223  $page = WikiPage::factory( $title );
1224  $this->assertEquals( 'WikiPage', get_class( $page ) );
1225  }
1226 }
static provideIsCountable()
loadParamsAndArgs($self=null, $opts=null, $args=null)
Process command line arguments $mOptions becomes an array with keys set to the option names $mArgs be...
static provideGetRedirectTarget()
wfGetDB($db, $groups=[], $wiki=false)
Get a Database object.
the array() calling protocol came about after MediaWiki 1.4rc1.
const CONTENT_MODEL_WIKITEXT
Definition: Defines.php:239
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:189
testIsCountable($title, $model, $text, $mode, $expected)
provideIsCountable WikiPage::isCountable
static provideHasViewableContent()
We use the convention $dbr for read and $dbw for write to help you keep track of whether the database object is a the world will explode Or to be a subsequent write query which succeeded on the master may fail when replicated to the slave due to a unique key collision Replication on the slave will stop and it may take hours to repair the database and get it back online Setting read_only in my cnf on the slave will avoid this but given the dire we prefer to have as many checks as possible We provide a but the wrapper functions like please read the documentation for except in special pages derived from QueryPage It s a common pitfall for new developers to submit code containing SQL queries which examine huge numbers of rows Remember that COUNT * is(N), counting rows in atable is like counting beans in a bucket.------------------------------------------------------------------------Replication------------------------------------------------------------------------The largest installation of MediaWiki, Wikimedia, uses a large set ofslave MySQL servers replicating writes made to a master MySQL server.Itis important to understand the issues associated with this setup if youwant to write code destined for Wikipedia.It's often the case that the best algorithm to use for a given taskdepends on whether or not replication is in use.Due to our unabashedWikipedia-centrism, we often just use the replication-friendly version, but if you like, you can use wfGetLB() ->getServerCount() > 1 tocheck to see if replication is in use.===Lag===Lag primarily occurs when large write queries are sent to the master.Writes on the master are executed in parallel, but they are executed inserial when they are replicated to the slaves.The master writes thequery to the binlog when the transaction is committed.The slaves pollthe binlog and start executing the query as soon as it appears.They canservice reads while they are performing a write query, but will not readanything more from the binlog and thus will perform no more writes.Thismeans that if the write query runs for a long time, the slaves will lagbehind the master for the time it takes for the write query to complete.Lag can be exacerbated by high read load.MediaWiki's load balancer willstop sending reads to a slave when it is lagged by more than 30 seconds.If the load ratios are set incorrectly, or if there is too much loadgenerally, this may lead to a slave permanently hovering around 30seconds lag.If all slaves are lagged by more than 30 seconds, MediaWiki will stopwriting to the database.All edits and other write operations will berefused, with an error returned to the user.This gives the slaves achance to catch up.Before we had this mechanism, the slaves wouldregularly lag by several minutes, making review of recent editsdifficult.In addition to this, MediaWiki attempts to ensure that the user seesevents occurring on the wiki in chronological order.A few seconds of lagcan be tolerated, as long as the user sees a consistent picture fromsubsequent requests.This is done by saving the master binlog positionin the session, and then at the start of each request, waiting for theslave to catch up to that position before doing any reads from it.Ifthis wait times out, reads are allowed anyway, but the request isconsidered to be in"lagged slave mode".Lagged slave mode can bechecked by calling wfGetLB() ->getLaggedSlaveMode().The onlypractical consequence at present is a warning displayed in the pagefooter.===Lag avoidance===To avoid excessive lag, queries which write large numbers of rows shouldbe split up, generally to write one row at a time.Multi-row INSERT...SELECT queries are the worst offenders should be avoided altogether.Instead do the select first and then the insert.===Working with lag===Despite our best efforts, it's not practical to guarantee a low-lagenvironment.Lag will usually be less than one second, but mayoccasionally be up to 30 seconds.For scalability, it's very importantto keep load on the master low, so simply sending all your queries tothe master is not the answer.So when you have a genuine need forup-to-date data, the following approach is advised:1) Do a quick query to the master for a sequence number or timestamp 2) Run the full query on the slave and check if it matches the data you gotfrom the master 3) If it doesn't, run the full query on the masterTo avoid swamping the master every time the slaves lag, use of thisapproach should be kept to a minimum.In most cases you should just readfrom the slave and let the user deal with the delay.------------------------------------------------------------------------Lock contention------------------------------------------------------------------------Due to the high write rate on Wikipedia(and some other wikis), MediaWiki developers need to be very careful to structure their writesto avoid long-lasting locks.By default, MediaWiki opens a transactionat the first query, and commits it before the output is sent.Locks willbe held from the time when the query is done until the commit.So youcan reduce lock time by doing as much processing as possible before youdo your write queries.Often this approach is not good enough, and it becomes necessary toenclose small groups of queries in their own transaction.Use thefollowing syntax:$dbw=wfGetDB(DB_MASTER
static getDefaultModelFor(Title $title)
Returns the name of the default content model to be used for the page with the given title...
has been added to your &Future changes to this page and its associated Talk page will be listed there
testDoEditContent()
WikiPage::doEditContent WikiPage::doModify WikiPage::doCreate WikiPage::doEditUpdates.
static newFromText($text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:262
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
const DB_MASTER
Definition: defines.php:23
testGetText()
WikiPage::getText.
testGetRevision()
WikiPage::getRevision.
getDefaultWikitextNS()
Returns the ID of a namespace that defaults to Wikitext.
testGetContentModel()
WikiPage::getContentModel.
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:1936
static provideGetParserOutput()
static singleton()
Get an instance of this class.
Definition: LinkCache.php:64
__construct($name=null, array $data=[], $dataName= '')
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add etc
Definition: design.txt:12
$res
Definition: database.txt:21
$summary
doDeleteArticle($reason, $suppress=false, $u1=null, $u2=null, &$error= '', User $user=null)
Same as doDeleteArticleReal(), but returns a simple boolean.
Definition: WikiPage.php:2839
Base class that store and restore the Language objects.
Maintenance script that runs pending jobs.
Definition: runJobs.php:33
testGetContent()
WikiPage::getContent.
testIsRedirect($title, $model, $text, $target)
provideGetRedirectTarget WikiPage::isRedirect
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:953
hideDeprecated($function)
Don't throw a warning if $function is deprecated and called later.
newPage($title, $model=null)
static makeContent($text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
Definition: hooks.txt:1721
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
Special handling for file pages.
CONTENT_MODEL_JAVASCRIPT
Uploads have to be specially set up to be secure.
testGetRedirectTarget($title, $model, $text, $target)
provideGetRedirectTarget WikiPage::getRedirectTarget
testDoEdit()
WikiPage::doEdit.
Class representing a MediaWiki article and history.
Definition: WikiPage.php:32
testGetContentHandler()
WikiPage::getContentHandler.
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
testGetParserOutput($model, $text, $expectedHtml)
provideGetParserOutput WikiPage::getParserOutput
const EDIT_NEW
Definition: Defines.php:146
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content $content
Definition: hooks.txt:1046
ContentHandler Database ^— important, causes temporary tables to be used instead of the real databas...
Definition: WikiPageTest.php:9
This list may contain false positives That usually means there is additional text with links below the first Each row contains links to the first and second redirect
testDoDeleteUpdates()
WikiPage::doDeleteUpdates.
setMwGlobals($pairs, $value=null)
const DB_SLAVE
Definition: Defines.php:28
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached one of or reset my talk page
Definition: hooks.txt:2491
testDoDeleteArticle()
WikiPage::doDeleteArticle.
testHasViewableContent($title, $viewable, $create=false)
provideHasViewableContent WikiPage::hasViewableContent
Special handling for category pages.
testExists()
WikiPage::exists.
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached $page
Definition: hooks.txt:2491
static destroySingletons()
Destroy the singleton instances.
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:300
createPage($page, $text, $model=null)