WikiPageDbTestBase.php 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522
  1. <?php
  2. use MediaWiki\Edit\PreparedEdit;
  3. use MediaWiki\MediaWikiServices;
  4. use MediaWiki\Storage\RevisionSlotsUpdate;
  5. use PHPUnit\Framework\MockObject\MockObject;
  6. use Wikimedia\TestingAccessWrapper;
  7. /**
  8. * @covers WikiPage
  9. */
  10. abstract class WikiPageDbTestBase extends MediaWikiLangTestCase {
  11. private $pagesToDelete;
  12. public function __construct( $name = null, array $data = [], $dataName = '' ) {
  13. parent::__construct( $name, $data, $dataName );
  14. $this->tablesUsed = array_merge(
  15. $this->tablesUsed,
  16. [ 'page',
  17. 'revision',
  18. 'redirect',
  19. 'archive',
  20. 'category',
  21. 'ip_changes',
  22. 'text',
  23. 'recentchanges',
  24. 'logging',
  25. 'page_props',
  26. 'pagelinks',
  27. 'categorylinks',
  28. 'langlinks',
  29. 'externallinks',
  30. 'imagelinks',
  31. 'templatelinks',
  32. 'iwlinks' ] );
  33. }
  34. protected function addCoreDBData() {
  35. // Blank out. This would fail with a modified schema, and we don't need it.
  36. }
  37. /**
  38. * @return int
  39. */
  40. abstract protected function getMcrMigrationStage();
  41. /**
  42. * @return string[]
  43. */
  44. abstract protected function getMcrTablesToReset();
  45. protected function setUp() {
  46. parent::setUp();
  47. $this->tablesUsed += $this->getMcrTablesToReset();
  48. $this->setMwGlobals( 'wgContentHandlerUseDB', $this->getContentHandlerUseDB() );
  49. $this->setMwGlobals(
  50. 'wgMultiContentRevisionSchemaMigrationStage',
  51. $this->getMcrMigrationStage()
  52. );
  53. $this->pagesToDelete = [];
  54. $this->overrideMwServices();
  55. }
  56. protected function tearDown() {
  57. foreach ( $this->pagesToDelete as $p ) {
  58. /* @var $p WikiPage */
  59. try {
  60. if ( $p->exists() ) {
  61. $p->doDeleteArticle( "testing done." );
  62. }
  63. } catch ( MWException $ex ) {
  64. // fail silently
  65. }
  66. }
  67. parent::tearDown();
  68. }
  69. abstract protected function getContentHandlerUseDB();
  70. /**
  71. * @param Title|string $title
  72. * @param string|null $model
  73. * @return WikiPage
  74. */
  75. private function newPage( $title, $model = null ) {
  76. if ( is_string( $title ) ) {
  77. $ns = $this->getDefaultWikitextNS();
  78. $title = Title::newFromText( $title, $ns );
  79. }
  80. $p = new WikiPage( $title );
  81. $this->pagesToDelete[] = $p;
  82. return $p;
  83. }
  84. /**
  85. * @param string|Title|WikiPage $page
  86. * @param string|Content|Content[] $content
  87. * @param int|null $model
  88. *
  89. * @return WikiPage
  90. */
  91. protected function createPage( $page, $content, $model = null, $user = null ) {
  92. if ( is_string( $page ) || $page instanceof Title ) {
  93. $page = $this->newPage( $page, $model );
  94. }
  95. if ( !$user ) {
  96. $user = $this->getTestUser()->getUser();
  97. }
  98. if ( is_string( $content ) ) {
  99. $content = ContentHandler::makeContent( $content, $page->getTitle(), $model );
  100. }
  101. if ( !is_array( $content ) ) {
  102. $content = [ 'main' => $content ];
  103. }
  104. $updater = $page->newPageUpdater( $user );
  105. foreach ( $content as $role => $cnt ) {
  106. $updater->setContent( $role, $cnt );
  107. }
  108. $updater->saveRevision( CommentStoreComment::newUnsavedComment( "testing" ) );
  109. return $page;
  110. }
  111. /**
  112. * @covers WikiPage::prepareContentForEdit
  113. */
  114. public function testPrepareContentForEdit() {
  115. $user = $this->getTestUser()->getUser();
  116. $sysop = $this->getTestUser( [ 'sysop' ] )->getUser();
  117. $page = $this->createPage( __METHOD__, __METHOD__, null, $user );
  118. $title = $page->getTitle();
  119. $content = ContentHandler::makeContent(
  120. "[[Lorem ipsum]] dolor sit amet, consetetur sadipscing elitr, sed diam "
  121. . " nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat.",
  122. $title,
  123. CONTENT_MODEL_WIKITEXT
  124. );
  125. $content2 = ContentHandler::makeContent(
  126. "At vero eos et accusam et justo duo [[dolores]] et ea rebum. "
  127. . "Stet clita kasd [[gubergren]], no sea takimata sanctus est. ~~~~",
  128. $title,
  129. CONTENT_MODEL_WIKITEXT
  130. );
  131. $edit = $page->prepareContentForEdit( $content, null, $user, null, false );
  132. $this->assertInstanceOf(
  133. ParserOptions::class,
  134. $edit->popts,
  135. "pops"
  136. );
  137. $this->assertContains( '</a>', $edit->output->getText(), "output" );
  138. $this->assertContains(
  139. 'consetetur sadipscing elitr',
  140. $edit->output->getText(),
  141. "output"
  142. );
  143. $this->assertTrue( $content->equals( $edit->newContent ), "newContent field" );
  144. $this->assertTrue( $content->equals( $edit->pstContent ), "pstContent field" );
  145. $this->assertSame( $edit->output, $edit->output, "output field" );
  146. $this->assertSame( $edit->popts, $edit->popts, "popts field" );
  147. $this->assertSame( null, $edit->revid, "revid field" );
  148. // Re-using the prepared info if possible
  149. $sameEdit = $page->prepareContentForEdit( $content, null, $user, null, false );
  150. $this->assertPreparedEditEquals( $edit, $sameEdit, 'equivalent PreparedEdit' );
  151. $this->assertSame( $edit->pstContent, $sameEdit->pstContent, 're-use output' );
  152. $this->assertSame( $edit->output, $sameEdit->output, 're-use output' );
  153. // Not re-using the same PreparedEdit if not possible
  154. $rev = $page->getRevision();
  155. $edit2 = $page->prepareContentForEdit( $content2, null, $user, null, false );
  156. $this->assertPreparedEditNotEquals( $edit, $edit2 );
  157. $this->assertContains( 'At vero eos', $edit2->pstContent->serialize(), "content" );
  158. // Check pre-safe transform
  159. $this->assertContains( '[[gubergren]]', $edit2->pstContent->serialize() );
  160. $this->assertNotContains( '~~~~', $edit2->pstContent->serialize() );
  161. $edit3 = $page->prepareContentForEdit( $content2, null, $sysop, null, false );
  162. $this->assertPreparedEditNotEquals( $edit2, $edit3 );
  163. // TODO: test with passing revision, then same without revision.
  164. }
  165. /**
  166. * @covers WikiPage::doEditUpdates
  167. */
  168. public function testDoEditUpdates() {
  169. $user = $this->getTestUser()->getUser();
  170. // NOTE: if site stats get out of whack and drop below 0,
  171. // that causes a DB error during tear-down. So bump the
  172. // numbers high enough to not drop below 0.
  173. $siteStatsUpdate = SiteStatsUpdate::factory(
  174. [ 'edits' => 1000, 'articles' => 1000, 'pages' => 1000 ]
  175. );
  176. $siteStatsUpdate->doUpdate();
  177. $page = $this->createPage( __METHOD__, __METHOD__ );
  178. $revision = new Revision(
  179. [
  180. 'id' => 9989,
  181. 'page' => $page->getId(),
  182. 'title' => $page->getTitle(),
  183. 'comment' => __METHOD__,
  184. 'minor_edit' => true,
  185. 'text' => __METHOD__ . ' [[|foo]][[bar]]', // PST turns [[|foo]] into [[foo]]
  186. 'user' => $user->getId(),
  187. 'user_text' => $user->getName(),
  188. 'timestamp' => '20170707040404',
  189. 'content_model' => CONTENT_MODEL_WIKITEXT,
  190. 'content_format' => CONTENT_FORMAT_WIKITEXT,
  191. ]
  192. );
  193. $page->doEditUpdates( $revision, $user );
  194. // TODO: test various options; needs temporary hooks
  195. $dbr = wfGetDB( DB_REPLICA );
  196. $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $page->getId() ] );
  197. $n = $res->numRows();
  198. $res->free();
  199. $this->assertEquals( 1, $n, 'pagelinks should contain only one link if PST was not applied' );
  200. }
  201. /**
  202. * @covers WikiPage::doEditContent
  203. * @covers WikiPage::prepareContentForEdit
  204. */
  205. public function testDoEditContent() {
  206. $this->setMwGlobals( 'wgPageCreationLog', true );
  207. $page = $this->newPage( __METHOD__ );
  208. $title = $page->getTitle();
  209. $user1 = $this->getTestUser()->getUser();
  210. // Use the confirmed group for user2 to make sure the user is different
  211. $user2 = $this->getTestUser( [ 'confirmed' ] )->getUser();
  212. $content = ContentHandler::makeContent(
  213. "[[Lorem ipsum]] dolor sit amet, consetetur sadipscing elitr, sed diam "
  214. . " nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat.",
  215. $title,
  216. CONTENT_MODEL_WIKITEXT
  217. );
  218. $preparedEditBefore = $page->prepareContentForEdit( $content, null, $user1 );
  219. $status = $page->doEditContent( $content, "[[testing]] 1", EDIT_NEW, false, $user1 );
  220. $this->assertTrue( $status->isOK(), 'OK' );
  221. $this->assertTrue( $status->value['new'], 'new' );
  222. $this->assertNotNull( $status->value['revision'], 'revision' );
  223. $this->assertSame( $status->value['revision']->getId(), $page->getRevision()->getId() );
  224. $this->assertSame( $status->value['revision']->getSha1(), $page->getRevision()->getSha1() );
  225. $this->assertTrue( $status->value['revision']->getContent()->equals( $content ), 'equals' );
  226. $rev = $page->getRevision();
  227. $preparedEditAfter = $page->prepareContentForEdit( $content, $rev, $user1 );
  228. $this->assertNotNull( $rev->getRecentChange() );
  229. $this->assertSame( $rev->getId(), (int)$rev->getRecentChange()->getAttribute( 'rc_this_oldid' ) );
  230. // make sure that cached ParserOutput gets re-used throughout
  231. $this->assertSame( $preparedEditBefore->output, $preparedEditAfter->output );
  232. $id = $page->getId();
  233. // Test page creation logging
  234. $this->assertSelect(
  235. 'logging',
  236. [ 'log_type', 'log_action' ],
  237. [ 'log_page' => $id ],
  238. [ [ 'create', 'create' ] ]
  239. );
  240. $this->assertTrue( $title->getArticleID() > 0, "Title object should have new page id" );
  241. $this->assertTrue( $id > 0, "WikiPage should have new page id" );
  242. $this->assertTrue( $title->exists(), "Title object should indicate that the page now exists" );
  243. $this->assertTrue( $page->exists(), "WikiPage object should indicate that the page now exists" );
  244. # ------------------------
  245. $dbr = wfGetDB( DB_REPLICA );
  246. $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
  247. $n = $res->numRows();
  248. $res->free();
  249. $this->assertEquals( 1, $n, 'pagelinks should contain one link from the page' );
  250. # ------------------------
  251. $page = new WikiPage( $title );
  252. $retrieved = $page->getContent();
  253. $this->assertTrue( $content->equals( $retrieved ), 'retrieved content doesn\'t equal original' );
  254. # ------------------------
  255. $page = new WikiPage( $title );
  256. // try null edit, with a different user
  257. $status = $page->doEditContent( $content, 'This changes nothing', EDIT_UPDATE, false, $user2 );
  258. $this->assertTrue( $status->isOK(), 'OK' );
  259. $this->assertFalse( $status->value['new'], 'new' );
  260. $this->assertNull( $status->value['revision'], 'revision' );
  261. $this->assertNotNull( $page->getRevision() );
  262. $this->assertTrue( $page->getRevision()->getContent()->equals( $content ), 'equals' );
  263. # ------------------------
  264. $content = ContentHandler::makeContent(
  265. "At vero eos et accusam et justo duo [[dolores]] et ea rebum. "
  266. . "Stet clita kasd [[gubergren]], no sea takimata sanctus est. ~~~~",
  267. $title,
  268. CONTENT_MODEL_WIKITEXT
  269. );
  270. $status = $page->doEditContent( $content, "testing 2", EDIT_UPDATE );
  271. $this->assertTrue( $status->isOK(), 'OK' );
  272. $this->assertFalse( $status->value['new'], 'new' );
  273. $this->assertNotNull( $status->value['revision'], 'revision' );
  274. $this->assertSame( $status->value['revision']->getId(), $page->getRevision()->getId() );
  275. $this->assertSame( $status->value['revision']->getSha1(), $page->getRevision()->getSha1() );
  276. $this->assertFalse(
  277. $status->value['revision']->getContent()->equals( $content ),
  278. 'not equals (PST must substitute signature)'
  279. );
  280. $rev = $page->getRevision();
  281. $this->assertNotNull( $rev->getRecentChange() );
  282. $this->assertSame( $rev->getId(), (int)$rev->getRecentChange()->getAttribute( 'rc_this_oldid' ) );
  283. # ------------------------
  284. $page = new WikiPage( $title );
  285. $retrieved = $page->getContent();
  286. $newText = $retrieved->serialize();
  287. $this->assertContains( '[[gubergren]]', $newText, 'New text must replace old text.' );
  288. $this->assertNotContains( '~~~~', $newText, 'PST must substitute signature.' );
  289. # ------------------------
  290. $dbr = wfGetDB( DB_REPLICA );
  291. $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
  292. $n = $res->numRows();
  293. $res->free();
  294. $this->assertEquals( 2, $n, 'pagelinks should contain two links from the page' );
  295. }
  296. /**
  297. * @covers WikiPage::doEditContent
  298. */
  299. public function testDoEditContent_twice() {
  300. $title = Title::newFromText( __METHOD__ );
  301. $page = WikiPage::factory( $title );
  302. $content = ContentHandler::makeContent( '$1 van $2', $title );
  303. // Make sure we can do the exact same save twice.
  304. // This tests checks that internal caches are reset as appropriate.
  305. $status1 = $page->doEditContent( $content, __METHOD__ );
  306. $status2 = $page->doEditContent( $content, __METHOD__ );
  307. $this->assertTrue( $status1->isOK(), 'OK' );
  308. $this->assertTrue( $status2->isOK(), 'OK' );
  309. $this->assertTrue( isset( $status1->value['revision'] ), 'OK' );
  310. $this->assertFalse( isset( $status2->value['revision'] ), 'OK' );
  311. }
  312. /**
  313. * Undeletion is covered in PageArchiveTest::testUndeleteRevisions()
  314. * TODO: Revision deletion
  315. *
  316. * @covers WikiPage::doDeleteArticle
  317. * @covers WikiPage::doDeleteArticleReal
  318. */
  319. public function testDoDeleteArticle() {
  320. $page = $this->createPage(
  321. __METHOD__,
  322. "[[original text]] foo",
  323. CONTENT_MODEL_WIKITEXT
  324. );
  325. $id = $page->getId();
  326. $page->doDeleteArticle( "testing deletion" );
  327. $this->assertFalse(
  328. $page->getTitle()->getArticleID() > 0,
  329. "Title object should now have page id 0"
  330. );
  331. $this->assertFalse( $page->getId() > 0, "WikiPage should now have page id 0" );
  332. $this->assertFalse(
  333. $page->exists(),
  334. "WikiPage::exists should return false after page was deleted"
  335. );
  336. $this->assertNull(
  337. $page->getContent(),
  338. "WikiPage::getContent should return null after page was deleted"
  339. );
  340. $t = Title::newFromText( $page->getTitle()->getPrefixedText() );
  341. $this->assertFalse(
  342. $t->exists(),
  343. "Title::exists should return false after page was deleted"
  344. );
  345. // Run the job queue
  346. JobQueueGroup::destroySingletons();
  347. $jobs = new RunJobs;
  348. $jobs->loadParamsAndArgs( null, [ 'quiet' => true ], null );
  349. $jobs->execute();
  350. # ------------------------
  351. $dbr = wfGetDB( DB_REPLICA );
  352. $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
  353. $n = $res->numRows();
  354. $res->free();
  355. $this->assertEquals( 0, $n, 'pagelinks should contain no more links from the page' );
  356. }
  357. /**
  358. * @covers WikiPage::doDeleteArticleReal
  359. */
  360. public function testDoDeleteArticleReal_user0() {
  361. $page = $this->createPage(
  362. __METHOD__,
  363. "[[original text]] foo",
  364. CONTENT_MODEL_WIKITEXT
  365. );
  366. $id = $page->getId();
  367. $errorStack = '';
  368. $status = $page->doDeleteArticleReal(
  369. /* reason */ "testing user 0 deletion",
  370. /* suppress */ false,
  371. /* unused 1 */ null,
  372. /* unused 2 */ null,
  373. /* errorStack */ $errorStack,
  374. null
  375. );
  376. $logId = $status->getValue();
  377. $actorQuery = ActorMigration::newMigration()->getJoin( 'log_user' );
  378. $this->assertSelect(
  379. [ 'logging' ] + $actorQuery['tables'], /* table */
  380. [
  381. 'log_type',
  382. 'log_action',
  383. 'log_comment',
  384. 'log_user' => $actorQuery['fields']['log_user'],
  385. 'log_user_text' => $actorQuery['fields']['log_user_text'],
  386. 'log_namespace',
  387. 'log_title',
  388. ],
  389. [ 'log_id' => $logId ],
  390. [ [
  391. 'delete',
  392. 'delete',
  393. 'testing user 0 deletion',
  394. '0',
  395. '127.0.0.1',
  396. (string)$page->getTitle()->getNamespace(),
  397. $page->getTitle()->getDBkey(),
  398. ] ],
  399. [],
  400. $actorQuery['joins']
  401. );
  402. }
  403. /**
  404. * @covers WikiPage::doDeleteArticleReal
  405. */
  406. public function testDoDeleteArticleReal_userSysop() {
  407. $page = $this->createPage(
  408. __METHOD__,
  409. "[[original text]] foo",
  410. CONTENT_MODEL_WIKITEXT
  411. );
  412. $id = $page->getId();
  413. $user = $this->getTestSysop()->getUser();
  414. $errorStack = '';
  415. $status = $page->doDeleteArticleReal(
  416. /* reason */ "testing sysop deletion",
  417. /* suppress */ false,
  418. /* unused 1 */ null,
  419. /* unused 2 */ null,
  420. /* errorStack */ $errorStack,
  421. $user
  422. );
  423. $logId = $status->getValue();
  424. $actorQuery = ActorMigration::newMigration()->getJoin( 'log_user' );
  425. $this->assertSelect(
  426. [ 'logging' ] + $actorQuery['tables'], /* table */
  427. [
  428. 'log_type',
  429. 'log_action',
  430. 'log_comment',
  431. 'log_user' => $actorQuery['fields']['log_user'],
  432. 'log_user_text' => $actorQuery['fields']['log_user_text'],
  433. 'log_namespace',
  434. 'log_title',
  435. ],
  436. [ 'log_id' => $logId ],
  437. [ [
  438. 'delete',
  439. 'delete',
  440. 'testing sysop deletion',
  441. (string)$user->getId(),
  442. $user->getName(),
  443. (string)$page->getTitle()->getNamespace(),
  444. $page->getTitle()->getDBkey(),
  445. ] ],
  446. [],
  447. $actorQuery['joins']
  448. );
  449. }
  450. /**
  451. * TODO: Test more stuff about suppression.
  452. *
  453. * @covers WikiPage::doDeleteArticleReal
  454. */
  455. public function testDoDeleteArticleReal_suppress() {
  456. $page = $this->createPage(
  457. __METHOD__,
  458. "[[original text]] foo",
  459. CONTENT_MODEL_WIKITEXT
  460. );
  461. $id = $page->getId();
  462. $user = $this->getTestSysop()->getUser();
  463. $errorStack = '';
  464. $status = $page->doDeleteArticleReal(
  465. /* reason */ "testing deletion",
  466. /* suppress */ true,
  467. /* unused 1 */ null,
  468. /* unused 2 */ null,
  469. /* errorStack */ $errorStack,
  470. $user
  471. );
  472. $logId = $status->getValue();
  473. $actorQuery = ActorMigration::newMigration()->getJoin( 'log_user' );
  474. $this->assertSelect(
  475. [ 'logging' ] + $actorQuery['tables'], /* table */
  476. [
  477. 'log_type',
  478. 'log_action',
  479. 'log_comment',
  480. 'log_user' => $actorQuery['fields']['log_user'],
  481. 'log_user_text' => $actorQuery['fields']['log_user_text'],
  482. 'log_namespace',
  483. 'log_title',
  484. ],
  485. [ 'log_id' => $logId ],
  486. [ [
  487. 'suppress',
  488. 'delete',
  489. 'testing deletion',
  490. (string)$user->getId(),
  491. $user->getName(),
  492. (string)$page->getTitle()->getNamespace(),
  493. $page->getTitle()->getDBkey(),
  494. ] ],
  495. [],
  496. $actorQuery['joins']
  497. );
  498. $this->assertNull(
  499. $page->getContent( Revision::FOR_PUBLIC ),
  500. "WikiPage::getContent should return null after the page was suppressed for general users"
  501. );
  502. $this->assertNull(
  503. $page->getContent( Revision::FOR_THIS_USER, null ),
  504. "WikiPage::getContent should return null after the page was suppressed for user zero"
  505. );
  506. $this->assertNull(
  507. $page->getContent( Revision::FOR_THIS_USER, $user ),
  508. "WikiPage::getContent should return null after the page was suppressed even for a sysop"
  509. );
  510. }
  511. /**
  512. * @covers WikiPage::doDeleteUpdates
  513. */
  514. public function testDoDeleteUpdates() {
  515. $user = $this->getTestUser()->getUser();
  516. $page = $this->createPage(
  517. __METHOD__,
  518. "[[original text]] foo",
  519. CONTENT_MODEL_WIKITEXT
  520. );
  521. $id = $page->getId();
  522. $page->loadPageData(); // make sure the current revision is cached.
  523. // Similar to MovePage logic
  524. wfGetDB( DB_MASTER )->delete( 'page', [ 'page_id' => $id ], __METHOD__ );
  525. $page->doDeleteUpdates( $page->getId(), $page->getContent(), $page->getRevision(), $user );
  526. // Run the job queue
  527. JobQueueGroup::destroySingletons();
  528. $jobs = new RunJobs;
  529. $jobs->loadParamsAndArgs( null, [ 'quiet' => true ], null );
  530. $jobs->execute();
  531. # ------------------------
  532. $dbr = wfGetDB( DB_REPLICA );
  533. $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
  534. $n = $res->numRows();
  535. $res->free();
  536. $this->assertEquals( 0, $n, 'pagelinks should contain no more links from the page' );
  537. }
  538. /**
  539. * @param string $name
  540. *
  541. * @return ContentHandler
  542. */
  543. protected function defineMockContentModelForUpdateTesting( $name ) {
  544. /** @var ContentHandler|MockObject $handler */
  545. $handler = $this->getMockBuilder( TextContentHandler::class )
  546. ->setConstructorArgs( [ $name ] )
  547. ->setMethods(
  548. [ 'getSecondaryDataUpdates', 'getDeletionUpdates', 'unserializeContent' ]
  549. )
  550. ->getMock();
  551. $dataUpdate = new MWCallableUpdate( 'time' );
  552. $dataUpdate->_name = "$name data update";
  553. $deletionUpdate = new MWCallableUpdate( 'time' );
  554. $deletionUpdate->_name = "$name deletion update";
  555. $handler->method( 'getSecondaryDataUpdates' )->willReturn( [ $dataUpdate ] );
  556. $handler->method( 'getDeletionUpdates' )->willReturn( [ $deletionUpdate ] );
  557. $handler->method( 'unserializeContent' )->willReturnCallback(
  558. function ( $text ) use ( $handler ) {
  559. return $this->createMockContent( $handler, $text );
  560. }
  561. );
  562. $this->mergeMwGlobalArrayValue(
  563. 'wgContentHandlers', [
  564. $name => function () use ( $handler ){
  565. return $handler;
  566. }
  567. ]
  568. );
  569. return $handler;
  570. }
  571. /**
  572. * @param ContentHandler $handler
  573. * @param string $text
  574. *
  575. * @return Content
  576. */
  577. protected function createMockContent( ContentHandler $handler, $text ) {
  578. /** @var Content|MockObject $content */
  579. $content = $this->getMockBuilder( TextContent::class )
  580. ->setConstructorArgs( [ $text ] )
  581. ->setMethods( [ 'getModel', 'getContentHandler' ] )
  582. ->getMock();
  583. $content->method( 'getModel' )->willReturn( $handler->getModelID() );
  584. $content->method( 'getContentHandler' )->willReturn( $handler );
  585. return $content;
  586. }
  587. public function testGetDeletionUpdates() {
  588. $m1 = $this->defineMockContentModelForUpdateTesting( 'M1' );
  589. $mainContent1 = $this->createMockContent( $m1, 'main 1' );
  590. $page = new WikiPage( Title::newFromText( __METHOD__ ) );
  591. $page = $this->createPage(
  592. $page,
  593. [ 'main' => $mainContent1 ]
  594. );
  595. $dataUpdates = $page->getDeletionUpdates( $page->getRevisionRecord() );
  596. $this->assertNotEmpty( $dataUpdates );
  597. $updateNames = array_map( function ( $du ) {
  598. return isset( $du->_name ) ? $du->_name : get_class( $du );
  599. }, $dataUpdates );
  600. $this->assertContains( LinksDeletionUpdate::class, $updateNames );
  601. $this->assertContains( 'M1 deletion update', $updateNames );
  602. }
  603. /**
  604. * @covers WikiPage::getRevision
  605. */
  606. public function testGetRevision() {
  607. $page = $this->newPage( __METHOD__ );
  608. $rev = $page->getRevision();
  609. $this->assertNull( $rev );
  610. # -----------------
  611. $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT );
  612. $rev = $page->getRevision();
  613. $this->assertEquals( $page->getLatest(), $rev->getId() );
  614. $this->assertEquals( "some text", $rev->getContent()->getNativeData() );
  615. }
  616. /**
  617. * @covers WikiPage::getContent
  618. */
  619. public function testGetContent() {
  620. $page = $this->newPage( __METHOD__ );
  621. $content = $page->getContent();
  622. $this->assertNull( $content );
  623. # -----------------
  624. $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT );
  625. $content = $page->getContent();
  626. $this->assertEquals( "some text", $content->getNativeData() );
  627. }
  628. /**
  629. * @covers WikiPage::exists
  630. */
  631. public function testExists() {
  632. $page = $this->newPage( __METHOD__ );
  633. $this->assertFalse( $page->exists() );
  634. # -----------------
  635. $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT );
  636. $this->assertTrue( $page->exists() );
  637. $page = new WikiPage( $page->getTitle() );
  638. $this->assertTrue( $page->exists() );
  639. # -----------------
  640. $page->doDeleteArticle( "done testing" );
  641. $this->assertFalse( $page->exists() );
  642. $page = new WikiPage( $page->getTitle() );
  643. $this->assertFalse( $page->exists() );
  644. }
  645. public function provideHasViewableContent() {
  646. return [
  647. [ 'WikiPageTest_testHasViewableContent', false, true ],
  648. [ 'Special:WikiPageTest_testHasViewableContent', false ],
  649. [ 'MediaWiki:WikiPageTest_testHasViewableContent', false ],
  650. [ 'Special:Userlogin', true ],
  651. [ 'MediaWiki:help', true ],
  652. ];
  653. }
  654. /**
  655. * @dataProvider provideHasViewableContent
  656. * @covers WikiPage::hasViewableContent
  657. */
  658. public function testHasViewableContent( $title, $viewable, $create = false ) {
  659. $page = $this->newPage( $title );
  660. $this->assertEquals( $viewable, $page->hasViewableContent() );
  661. if ( $create ) {
  662. $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT );
  663. $this->assertTrue( $page->hasViewableContent() );
  664. $page = new WikiPage( $page->getTitle() );
  665. $this->assertTrue( $page->hasViewableContent() );
  666. }
  667. }
  668. public function provideGetRedirectTarget() {
  669. return [
  670. [ 'WikiPageTest_testGetRedirectTarget_1', CONTENT_MODEL_WIKITEXT, "hello world", null ],
  671. [
  672. 'WikiPageTest_testGetRedirectTarget_2',
  673. CONTENT_MODEL_WIKITEXT,
  674. "#REDIRECT [[hello world]]",
  675. "Hello world"
  676. ],
  677. ];
  678. }
  679. /**
  680. * @dataProvider provideGetRedirectTarget
  681. * @covers WikiPage::getRedirectTarget
  682. */
  683. public function testGetRedirectTarget( $title, $model, $text, $target ) {
  684. $this->setMwGlobals( [
  685. 'wgCapitalLinks' => true,
  686. ] );
  687. $page = $this->createPage( $title, $text, $model );
  688. # sanity check, because this test seems to fail for no reason for some people.
  689. $c = $page->getContent();
  690. $this->assertEquals( WikitextContent::class, get_class( $c ) );
  691. # now, test the actual redirect
  692. $t = $page->getRedirectTarget();
  693. $this->assertEquals( $target, is_null( $t ) ? null : $t->getPrefixedText() );
  694. }
  695. /**
  696. * @dataProvider provideGetRedirectTarget
  697. * @covers WikiPage::isRedirect
  698. */
  699. public function testIsRedirect( $title, $model, $text, $target ) {
  700. $page = $this->createPage( $title, $text, $model );
  701. $this->assertEquals( !is_null( $target ), $page->isRedirect() );
  702. }
  703. public function provideIsCountable() {
  704. return [
  705. // any
  706. [ 'WikiPageTest_testIsCountable',
  707. CONTENT_MODEL_WIKITEXT,
  708. '',
  709. 'any',
  710. true
  711. ],
  712. [ 'WikiPageTest_testIsCountable',
  713. CONTENT_MODEL_WIKITEXT,
  714. 'Foo',
  715. 'any',
  716. true
  717. ],
  718. // link
  719. [ 'WikiPageTest_testIsCountable',
  720. CONTENT_MODEL_WIKITEXT,
  721. 'Foo',
  722. 'link',
  723. false
  724. ],
  725. [ 'WikiPageTest_testIsCountable',
  726. CONTENT_MODEL_WIKITEXT,
  727. 'Foo [[bar]]',
  728. 'link',
  729. true
  730. ],
  731. // redirects
  732. [ 'WikiPageTest_testIsCountable',
  733. CONTENT_MODEL_WIKITEXT,
  734. '#REDIRECT [[bar]]',
  735. 'any',
  736. false
  737. ],
  738. [ 'WikiPageTest_testIsCountable',
  739. CONTENT_MODEL_WIKITEXT,
  740. '#REDIRECT [[bar]]',
  741. 'link',
  742. false
  743. ],
  744. // not a content namespace
  745. [ 'Talk:WikiPageTest_testIsCountable',
  746. CONTENT_MODEL_WIKITEXT,
  747. 'Foo',
  748. 'any',
  749. false
  750. ],
  751. [ 'Talk:WikiPageTest_testIsCountable',
  752. CONTENT_MODEL_WIKITEXT,
  753. 'Foo [[bar]]',
  754. 'link',
  755. false
  756. ],
  757. // not a content namespace, different model
  758. [ 'MediaWiki:WikiPageTest_testIsCountable.js',
  759. null,
  760. 'Foo',
  761. 'any',
  762. false
  763. ],
  764. [ 'MediaWiki:WikiPageTest_testIsCountable.js',
  765. null,
  766. 'Foo [[bar]]',
  767. 'link',
  768. false
  769. ],
  770. ];
  771. }
  772. /**
  773. * @dataProvider provideIsCountable
  774. * @covers WikiPage::isCountable
  775. */
  776. public function testIsCountable( $title, $model, $text, $mode, $expected ) {
  777. global $wgContentHandlerUseDB;
  778. $this->setMwGlobals( 'wgArticleCountMethod', $mode );
  779. $title = Title::newFromText( $title );
  780. if ( !$wgContentHandlerUseDB
  781. && $model
  782. && ContentHandler::getDefaultModelFor( $title ) != $model
  783. ) {
  784. $this->markTestSkipped( "Can not use non-default content model $model for "
  785. . $title->getPrefixedDBkey() . " with \$wgContentHandlerUseDB disabled." );
  786. }
  787. $page = $this->createPage( $title, $text, $model );
  788. $editInfo = $page->prepareContentForEdit( $page->getContent() );
  789. $v = $page->isCountable();
  790. $w = $page->isCountable( $editInfo );
  791. $this->assertEquals(
  792. $expected,
  793. $v,
  794. "isCountable( null ) returned unexpected value " . var_export( $v, true )
  795. . " instead of " . var_export( $expected, true )
  796. . " in mode `$mode` for text \"$text\""
  797. );
  798. $this->assertEquals(
  799. $expected,
  800. $w,
  801. "isCountable( \$editInfo ) returned unexpected value " . var_export( $v, true )
  802. . " instead of " . var_export( $expected, true )
  803. . " in mode `$mode` for text \"$text\""
  804. );
  805. }
  806. public function provideGetParserOutput() {
  807. return [
  808. [
  809. CONTENT_MODEL_WIKITEXT,
  810. "hello ''world''\n",
  811. "<div class=\"mw-parser-output\"><p>hello <i>world</i></p></div>"
  812. ],
  813. // @todo more...?
  814. ];
  815. }
  816. /**
  817. * @dataProvider provideGetParserOutput
  818. * @covers WikiPage::getParserOutput
  819. */
  820. public function testGetParserOutput( $model, $text, $expectedHtml ) {
  821. $page = $this->createPage( __METHOD__, $text, $model );
  822. $opt = $page->makeParserOptions( 'canonical' );
  823. $po = $page->getParserOutput( $opt );
  824. $text = $po->getText();
  825. $text = trim( preg_replace( '/<!--.*?-->/sm', '', $text ) ); # strip injected comments
  826. $text = preg_replace( '!\s*(</p>|</div>)!sm', '\1', $text ); # don't let tidy confuse us
  827. $this->assertEquals( $expectedHtml, $text );
  828. return $po;
  829. }
  830. /**
  831. * @covers WikiPage::getParserOutput
  832. */
  833. public function testGetParserOutput_nonexisting() {
  834. $page = new WikiPage( Title::newFromText( __METHOD__ ) );
  835. $opt = new ParserOptions();
  836. $po = $page->getParserOutput( $opt );
  837. $this->assertFalse( $po, "getParserOutput() shall return false for non-existing pages." );
  838. }
  839. /**
  840. * @covers WikiPage::getParserOutput
  841. */
  842. public function testGetParserOutput_badrev() {
  843. $page = $this->createPage( __METHOD__, 'dummy', CONTENT_MODEL_WIKITEXT );
  844. $opt = new ParserOptions();
  845. $po = $page->getParserOutput( $opt, $page->getLatest() + 1234 );
  846. // @todo would be neat to also test deleted revision
  847. $this->assertFalse( $po, "getParserOutput() shall return false for non-existing revisions." );
  848. }
  849. public static $sections =
  850. "Intro
  851. == stuff ==
  852. hello world
  853. == test ==
  854. just a test
  855. == foo ==
  856. more stuff
  857. ";
  858. public function dataReplaceSection() {
  859. // NOTE: assume the Help namespace to contain wikitext
  860. return [
  861. [ 'Help:WikiPageTest_testReplaceSection',
  862. CONTENT_MODEL_WIKITEXT,
  863. self::$sections,
  864. "0",
  865. "No more",
  866. null,
  867. trim( preg_replace( '/^Intro/sm', 'No more', self::$sections ) )
  868. ],
  869. [ 'Help:WikiPageTest_testReplaceSection',
  870. CONTENT_MODEL_WIKITEXT,
  871. self::$sections,
  872. "",
  873. "No more",
  874. null,
  875. "No more"
  876. ],
  877. [ 'Help:WikiPageTest_testReplaceSection',
  878. CONTENT_MODEL_WIKITEXT,
  879. self::$sections,
  880. "2",
  881. "== TEST ==\nmore fun",
  882. null,
  883. trim( preg_replace( '/^== test ==.*== foo ==/sm',
  884. "== TEST ==\nmore fun\n\n== foo ==",
  885. self::$sections ) )
  886. ],
  887. [ 'Help:WikiPageTest_testReplaceSection',
  888. CONTENT_MODEL_WIKITEXT,
  889. self::$sections,
  890. "8",
  891. "No more",
  892. null,
  893. trim( self::$sections )
  894. ],
  895. [ 'Help:WikiPageTest_testReplaceSection',
  896. CONTENT_MODEL_WIKITEXT,
  897. self::$sections,
  898. "new",
  899. "No more",
  900. "New",
  901. trim( self::$sections ) . "\n\n== New ==\n\nNo more"
  902. ],
  903. ];
  904. }
  905. /**
  906. * @dataProvider dataReplaceSection
  907. * @covers WikiPage::replaceSectionContent
  908. */
  909. public function testReplaceSectionContent( $title, $model, $text, $section,
  910. $with, $sectionTitle, $expected
  911. ) {
  912. $page = $this->createPage( $title, $text, $model );
  913. $content = ContentHandler::makeContent( $with, $page->getTitle(), $page->getContentModel() );
  914. $c = $page->replaceSectionContent( $section, $content, $sectionTitle );
  915. $this->assertEquals( $expected, is_null( $c ) ? null : trim( $c->getNativeData() ) );
  916. }
  917. /**
  918. * @dataProvider dataReplaceSection
  919. * @covers WikiPage::replaceSectionAtRev
  920. */
  921. public function testReplaceSectionAtRev( $title, $model, $text, $section,
  922. $with, $sectionTitle, $expected
  923. ) {
  924. $page = $this->createPage( $title, $text, $model );
  925. $baseRevId = $page->getLatest();
  926. $content = ContentHandler::makeContent( $with, $page->getTitle(), $page->getContentModel() );
  927. $c = $page->replaceSectionAtRev( $section, $content, $sectionTitle, $baseRevId );
  928. $this->assertEquals( $expected, is_null( $c ) ? null : trim( $c->getNativeData() ) );
  929. }
  930. /**
  931. * @covers WikiPage::getOldestRevision
  932. */
  933. public function testGetOldestRevision() {
  934. $page = $this->newPage( __METHOD__ );
  935. $page->doEditContent(
  936. new WikitextContent( 'one' ),
  937. "first edit",
  938. EDIT_NEW
  939. );
  940. $rev1 = $page->getRevision();
  941. $page = new WikiPage( $page->getTitle() );
  942. $page->doEditContent(
  943. new WikitextContent( 'two' ),
  944. "second edit",
  945. EDIT_UPDATE
  946. );
  947. $page = new WikiPage( $page->getTitle() );
  948. $page->doEditContent(
  949. new WikitextContent( 'three' ),
  950. "third edit",
  951. EDIT_UPDATE
  952. );
  953. // sanity check
  954. $this->assertNotEquals(
  955. $rev1->getId(),
  956. $page->getRevision()->getId(),
  957. '$page->getRevision()->getId()'
  958. );
  959. // actual test
  960. $this->assertEquals(
  961. $rev1->getId(),
  962. $page->getOldestRevision()->getId(),
  963. '$page->getOldestRevision()->getId()'
  964. );
  965. }
  966. /**
  967. * @covers WikiPage::doRollback
  968. * @covers WikiPage::commitRollback
  969. */
  970. public function testDoRollback() {
  971. // FIXME: fails under postgres
  972. $this->markTestSkippedIfDbType( 'postgres' );
  973. $admin = $this->getTestSysop()->getUser();
  974. $user1 = $this->getTestUser()->getUser();
  975. // Use the confirmed group for user2 to make sure the user is different
  976. $user2 = $this->getTestUser( [ 'confirmed' ] )->getUser();
  977. // make sure we can test autopatrolling
  978. $this->setMwGlobals( 'wgUseRCPatrol', true );
  979. // TODO: MCR: test rollback of multiple slots!
  980. $page = $this->newPage( __METHOD__ );
  981. // Make some edits
  982. $text = "one";
  983. $status1 = $page->doEditContent( ContentHandler::makeContent( $text, $page->getTitle() ),
  984. "section one", EDIT_NEW, false, $admin );
  985. $text .= "\n\ntwo";
  986. $status2 = $page->doEditContent( ContentHandler::makeContent( $text, $page->getTitle() ),
  987. "adding section two", 0, false, $user1 );
  988. $text .= "\n\nthree";
  989. $status3 = $page->doEditContent( ContentHandler::makeContent( $text, $page->getTitle() ),
  990. "adding section three", 0, false, $user2 );
  991. /** @var Revision $rev1 */
  992. /** @var Revision $rev2 */
  993. /** @var Revision $rev3 */
  994. $rev1 = $status1->getValue()['revision'];
  995. $rev2 = $status2->getValue()['revision'];
  996. $rev3 = $status3->getValue()['revision'];
  997. /**
  998. * We are having issues with doRollback spuriously failing. Apparently
  999. * the last revision somehow goes missing or not committed under some
  1000. * circumstances. So, make sure the revisions have the correct usernames.
  1001. */
  1002. $this->assertEquals( 3, Revision::countByPageId( wfGetDB( DB_REPLICA ), $page->getId() ) );
  1003. $this->assertEquals( $admin->getName(), $rev1->getUserText() );
  1004. $this->assertEquals( $user1->getName(), $rev2->getUserText() );
  1005. $this->assertEquals( $user2->getName(), $rev3->getUserText() );
  1006. // Now, try the actual rollback
  1007. $token = $admin->getEditToken( 'rollback' );
  1008. $rollbackErrors = $page->doRollback(
  1009. $user2->getName(),
  1010. "testing rollback",
  1011. $token,
  1012. false,
  1013. $resultDetails,
  1014. $admin
  1015. );
  1016. if ( $rollbackErrors ) {
  1017. $this->fail(
  1018. "Rollback failed:\n" .
  1019. print_r( $rollbackErrors, true ) . ";\n" .
  1020. print_r( $resultDetails, true )
  1021. );
  1022. }
  1023. $page = new WikiPage( $page->getTitle() );
  1024. $this->assertEquals( $rev2->getSha1(), $page->getRevision()->getSha1(),
  1025. "rollback did not revert to the correct revision" );
  1026. $this->assertEquals( "one\n\ntwo", $page->getContent()->getNativeData() );
  1027. $rc = MediaWikiServices::getInstance()->getRevisionStore()->getRecentChange(
  1028. $page->getRevision()->getRevisionRecord()
  1029. );
  1030. $this->assertNotNull( $rc, 'RecentChanges entry' );
  1031. $this->assertEquals(
  1032. RecentChange::PRC_AUTOPATROLLED,
  1033. $rc->getAttribute( 'rc_patrolled' ),
  1034. 'rc_patrolled'
  1035. );
  1036. // TODO: MCR: assert origin once we write slot data
  1037. // $mainSlot = $page->getRevision()->getRevisionRecord()->getSlot( 'main' );
  1038. // $this->assertTrue( $mainSlot->isInherited(), 'isInherited' );
  1039. // $this->assertSame( $rev2->getId(), $mainSlot->getOrigin(), 'getOrigin' );
  1040. }
  1041. /**
  1042. * @covers WikiPage::doRollback
  1043. * @covers WikiPage::commitRollback
  1044. */
  1045. public function testDoRollbackFailureSameContent() {
  1046. $admin = $this->getTestSysop()->getUser();
  1047. $text = "one";
  1048. $page = $this->newPage( __METHOD__ );
  1049. $page->doEditContent(
  1050. ContentHandler::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT ),
  1051. "section one",
  1052. EDIT_NEW,
  1053. false,
  1054. $admin
  1055. );
  1056. $rev1 = $page->getRevision();
  1057. $user1 = $this->getTestUser( [ 'sysop' ] )->getUser();
  1058. $text .= "\n\ntwo";
  1059. $page = new WikiPage( $page->getTitle() );
  1060. $page->doEditContent(
  1061. ContentHandler::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT ),
  1062. "adding section two",
  1063. 0,
  1064. false,
  1065. $user1
  1066. );
  1067. # now, do a the rollback from the same user was doing the edit before
  1068. $resultDetails = [];
  1069. $token = $user1->getEditToken( 'rollback' );
  1070. $errors = $page->doRollback(
  1071. $user1->getName(),
  1072. "testing revert same user",
  1073. $token,
  1074. false,
  1075. $resultDetails,
  1076. $admin
  1077. );
  1078. $this->assertEquals( [], $errors, "Rollback failed same user" );
  1079. # now, try the rollback
  1080. $resultDetails = [];
  1081. $token = $admin->getEditToken( 'rollback' );
  1082. $errors = $page->doRollback(
  1083. $user1->getName(),
  1084. "testing revert",
  1085. $token,
  1086. false,
  1087. $resultDetails,
  1088. $admin
  1089. );
  1090. $this->assertEquals(
  1091. [
  1092. [
  1093. 'alreadyrolled',
  1094. __METHOD__,
  1095. $user1->getName(),
  1096. $admin->getName(),
  1097. ],
  1098. ],
  1099. $errors,
  1100. "Rollback not failed"
  1101. );
  1102. $page = new WikiPage( $page->getTitle() );
  1103. $this->assertEquals( $rev1->getSha1(), $page->getRevision()->getSha1(),
  1104. "rollback did not revert to the correct revision" );
  1105. $this->assertEquals( "one", $page->getContent()->getNativeData() );
  1106. }
  1107. /**
  1108. * Tests tagging for edits that do rollback action
  1109. * @covers WikiPage::doRollback
  1110. */
  1111. public function testDoRollbackTagging() {
  1112. if ( !in_array( 'mw-rollback', ChangeTags::getSoftwareTags() ) ) {
  1113. $this->markTestSkipped( 'Rollback tag deactivated, skipped the test.' );
  1114. }
  1115. $admin = new User();
  1116. $admin->setName( 'Administrator' );
  1117. $admin->addToDatabase();
  1118. $text = 'First line';
  1119. $page = $this->newPage( 'WikiPageTest_testDoRollbackTagging' );
  1120. $page->doEditContent(
  1121. ContentHandler::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT ),
  1122. 'Added first line',
  1123. EDIT_NEW,
  1124. false,
  1125. $admin
  1126. );
  1127. $secondUser = new User();
  1128. $secondUser->setName( '92.65.217.32' );
  1129. $text .= '\n\nSecond line';
  1130. $page = new WikiPage( $page->getTitle() );
  1131. $page->doEditContent(
  1132. ContentHandler::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT ),
  1133. 'Adding second line',
  1134. 0,
  1135. false,
  1136. $secondUser
  1137. );
  1138. // Now, try the rollback
  1139. $admin->addGroup( 'sysop' ); // Make the test user a sysop
  1140. $token = $admin->getEditToken( 'rollback' );
  1141. $errors = $page->doRollback(
  1142. $secondUser->getName(),
  1143. 'testing rollback',
  1144. $token,
  1145. false,
  1146. $resultDetails,
  1147. $admin
  1148. );
  1149. // If doRollback completed without errors
  1150. if ( $errors === [] ) {
  1151. $tags = $resultDetails[ 'tags' ];
  1152. $this->assertContains( 'mw-rollback', $tags );
  1153. }
  1154. }
  1155. public function provideGetAutoDeleteReason() {
  1156. return [
  1157. [
  1158. [],
  1159. false,
  1160. false
  1161. ],
  1162. [
  1163. [
  1164. [ "first edit", null ],
  1165. ],
  1166. "/first edit.*only contributor/",
  1167. false
  1168. ],
  1169. [
  1170. [
  1171. [ "first edit", null ],
  1172. [ "second edit", null ],
  1173. ],
  1174. "/second edit.*only contributor/",
  1175. true
  1176. ],
  1177. [
  1178. [
  1179. [ "first edit", "127.0.2.22" ],
  1180. [ "second edit", "127.0.3.33" ],
  1181. ],
  1182. "/second edit/",
  1183. true
  1184. ],
  1185. [
  1186. [
  1187. [
  1188. "first edit: "
  1189. . "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam "
  1190. . " nonumy eirmod tempor invidunt ut labore et dolore magna "
  1191. . "aliquyam erat, sed diam voluptua. At vero eos et accusam "
  1192. . "et justo duo dolores et ea rebum. Stet clita kasd gubergren, "
  1193. . "no sea takimata sanctus est Lorem ipsum dolor sit amet.'",
  1194. null
  1195. ],
  1196. ],
  1197. '/first edit:.*\.\.\."/',
  1198. false
  1199. ],
  1200. [
  1201. [
  1202. [ "first edit", "127.0.2.22" ],
  1203. [ "", "127.0.3.33" ],
  1204. ],
  1205. "/before blanking.*first edit/",
  1206. true
  1207. ],
  1208. ];
  1209. }
  1210. /**
  1211. * @dataProvider provideGetAutoDeleteReason
  1212. * @covers WikiPage::getAutoDeleteReason
  1213. */
  1214. public function testGetAutoDeleteReason( $edits, $expectedResult, $expectedHistory ) {
  1215. global $wgUser;
  1216. // NOTE: assume Help namespace to contain wikitext
  1217. $page = $this->newPage( "Help:WikiPageTest_testGetAutoDeleteReason" );
  1218. $c = 1;
  1219. foreach ( $edits as $edit ) {
  1220. $user = new User();
  1221. if ( !empty( $edit[1] ) ) {
  1222. $user->setName( $edit[1] );
  1223. } else {
  1224. $user = $wgUser;
  1225. }
  1226. $content = ContentHandler::makeContent( $edit[0], $page->getTitle(), $page->getContentModel() );
  1227. $page->doEditContent( $content, "test edit $c", $c < 2 ? EDIT_NEW : 0, false, $user );
  1228. $c += 1;
  1229. }
  1230. $reason = $page->getAutoDeleteReason( $hasHistory );
  1231. if ( is_bool( $expectedResult ) || is_null( $expectedResult ) ) {
  1232. $this->assertEquals( $expectedResult, $reason );
  1233. } else {
  1234. $this->assertTrue( (bool)preg_match( $expectedResult, $reason ),
  1235. "Autosummary didn't match expected pattern $expectedResult: $reason" );
  1236. }
  1237. $this->assertEquals( $expectedHistory, $hasHistory,
  1238. "expected \$hasHistory to be " . var_export( $expectedHistory, true ) );
  1239. $page->doDeleteArticle( "done" );
  1240. }
  1241. public function providePreSaveTransform() {
  1242. return [
  1243. [ 'hello this is ~~~',
  1244. "hello this is [[Special:Contributions/127.0.0.1|127.0.0.1]]",
  1245. ],
  1246. [ 'hello \'\'this\'\' is <nowiki>~~~</nowiki>',
  1247. 'hello \'\'this\'\' is <nowiki>~~~</nowiki>',
  1248. ],
  1249. ];
  1250. }
  1251. /**
  1252. * @covers WikiPage::factory
  1253. */
  1254. public function testWikiPageFactory() {
  1255. $title = Title::makeTitle( NS_FILE, 'Someimage.png' );
  1256. $page = WikiPage::factory( $title );
  1257. $this->assertEquals( WikiFilePage::class, get_class( $page ) );
  1258. $title = Title::makeTitle( NS_CATEGORY, 'SomeCategory' );
  1259. $page = WikiPage::factory( $title );
  1260. $this->assertEquals( WikiCategoryPage::class, get_class( $page ) );
  1261. $title = Title::makeTitle( NS_MAIN, 'SomePage' );
  1262. $page = WikiPage::factory( $title );
  1263. $this->assertEquals( WikiPage::class, get_class( $page ) );
  1264. }
  1265. /**
  1266. * @covers WikiPage::loadPageData
  1267. * @covers WikiPage::wasLoadedFrom
  1268. */
  1269. public function testLoadPageData() {
  1270. $title = Title::makeTitle( NS_MAIN, 'SomePage' );
  1271. $page = WikiPage::factory( $title );
  1272. $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject::READ_NORMAL ) );
  1273. $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject::READ_LATEST ) );
  1274. $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject::READ_LOCKING ) );
  1275. $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject::READ_EXCLUSIVE ) );
  1276. $page->loadPageData( IDBAccessObject::READ_NORMAL );
  1277. $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_NORMAL ) );
  1278. $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject::READ_LATEST ) );
  1279. $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject::READ_LOCKING ) );
  1280. $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject::READ_EXCLUSIVE ) );
  1281. $page->loadPageData( IDBAccessObject::READ_LATEST );
  1282. $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_NORMAL ) );
  1283. $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_LATEST ) );
  1284. $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject::READ_LOCKING ) );
  1285. $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject::READ_EXCLUSIVE ) );
  1286. $page->loadPageData( IDBAccessObject::READ_LOCKING );
  1287. $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_NORMAL ) );
  1288. $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_LATEST ) );
  1289. $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_LOCKING ) );
  1290. $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject::READ_EXCLUSIVE ) );
  1291. $page->loadPageData( IDBAccessObject::READ_EXCLUSIVE );
  1292. $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_NORMAL ) );
  1293. $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_LATEST ) );
  1294. $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_LOCKING ) );
  1295. $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_EXCLUSIVE ) );
  1296. }
  1297. /**
  1298. * @dataProvider provideCommentMigrationOnDeletion
  1299. *
  1300. * @param int $writeStage
  1301. * @param int $readStage
  1302. */
  1303. public function testCommentMigrationOnDeletion( $writeStage, $readStage ) {
  1304. $this->setMwGlobals( 'wgCommentTableSchemaMigrationStage', $writeStage );
  1305. $this->overrideMwServices();
  1306. $dbr = wfGetDB( DB_REPLICA );
  1307. $page = $this->createPage(
  1308. __METHOD__,
  1309. "foo",
  1310. CONTENT_MODEL_WIKITEXT
  1311. );
  1312. $revid = $page->getLatest();
  1313. if ( $writeStage > MIGRATION_OLD ) {
  1314. $comment_id = $dbr->selectField(
  1315. 'revision_comment_temp',
  1316. 'revcomment_comment_id',
  1317. [ 'revcomment_rev' => $revid ],
  1318. __METHOD__
  1319. );
  1320. }
  1321. $this->setMwGlobals( 'wgCommentTableSchemaMigrationStage', $readStage );
  1322. $this->overrideMwServices();
  1323. $page->doDeleteArticle( "testing deletion" );
  1324. if ( $readStage > MIGRATION_OLD ) {
  1325. // Didn't leave behind any 'revision_comment_temp' rows
  1326. $n = $dbr->selectField(
  1327. 'revision_comment_temp', 'COUNT(*)', [ 'revcomment_rev' => $revid ], __METHOD__
  1328. );
  1329. $this->assertEquals( 0, $n, 'no entry in revision_comment_temp after deletion' );
  1330. // Copied or upgraded the comment_id, as applicable
  1331. $ar_comment_id = $dbr->selectField(
  1332. 'archive',
  1333. 'ar_comment_id',
  1334. [ 'ar_rev_id' => $revid ],
  1335. __METHOD__
  1336. );
  1337. if ( $writeStage > MIGRATION_OLD ) {
  1338. $this->assertSame( $comment_id, $ar_comment_id );
  1339. } else {
  1340. $this->assertNotEquals( 0, $ar_comment_id );
  1341. }
  1342. }
  1343. // Copied rev_comment, if applicable
  1344. if ( $readStage <= MIGRATION_WRITE_BOTH && $writeStage <= MIGRATION_WRITE_BOTH ) {
  1345. $ar_comment = $dbr->selectField(
  1346. 'archive',
  1347. 'ar_comment',
  1348. [ 'ar_rev_id' => $revid ],
  1349. __METHOD__
  1350. );
  1351. $this->assertSame( 'testing', $ar_comment );
  1352. }
  1353. }
  1354. public function provideCommentMigrationOnDeletion() {
  1355. return [
  1356. [ MIGRATION_OLD, MIGRATION_OLD ],
  1357. [ MIGRATION_OLD, MIGRATION_WRITE_BOTH ],
  1358. [ MIGRATION_OLD, MIGRATION_WRITE_NEW ],
  1359. [ MIGRATION_WRITE_BOTH, MIGRATION_OLD ],
  1360. [ MIGRATION_WRITE_BOTH, MIGRATION_WRITE_BOTH ],
  1361. [ MIGRATION_WRITE_BOTH, MIGRATION_WRITE_NEW ],
  1362. [ MIGRATION_WRITE_BOTH, MIGRATION_NEW ],
  1363. [ MIGRATION_WRITE_NEW, MIGRATION_WRITE_BOTH ],
  1364. [ MIGRATION_WRITE_NEW, MIGRATION_WRITE_NEW ],
  1365. [ MIGRATION_WRITE_NEW, MIGRATION_NEW ],
  1366. [ MIGRATION_NEW, MIGRATION_WRITE_BOTH ],
  1367. [ MIGRATION_NEW, MIGRATION_WRITE_NEW ],
  1368. [ MIGRATION_NEW, MIGRATION_NEW ],
  1369. ];
  1370. }
  1371. /**
  1372. * @covers WikiPage::updateCategoryCounts
  1373. */
  1374. public function testUpdateCategoryCounts() {
  1375. $page = new WikiPage( Title::newFromText( __METHOD__ ) );
  1376. // Add an initial category
  1377. $page->updateCategoryCounts( [ 'A' ], [], 0 );
  1378. $this->assertEquals( 1, Category::newFromName( 'A' )->getPageCount() );
  1379. $this->assertEquals( 0, Category::newFromName( 'B' )->getPageCount() );
  1380. $this->assertEquals( 0, Category::newFromName( 'C' )->getPageCount() );
  1381. // Add a new category
  1382. $page->updateCategoryCounts( [ 'B' ], [], 0 );
  1383. $this->assertEquals( 1, Category::newFromName( 'A' )->getPageCount() );
  1384. $this->assertEquals( 1, Category::newFromName( 'B' )->getPageCount() );
  1385. $this->assertEquals( 0, Category::newFromName( 'C' )->getPageCount() );
  1386. // Add and remove a category
  1387. $page->updateCategoryCounts( [ 'C' ], [ 'A' ], 0 );
  1388. $this->assertEquals( 0, Category::newFromName( 'A' )->getPageCount() );
  1389. $this->assertEquals( 1, Category::newFromName( 'B' )->getPageCount() );
  1390. $this->assertEquals( 1, Category::newFromName( 'C' )->getPageCount() );
  1391. }
  1392. public function provideUpdateRedirectOn() {
  1393. yield [ '#REDIRECT [[Foo]]', true, null, true, true, 0 ];
  1394. yield [ '#REDIRECT [[Foo]]', true, 'Foo', true, false, 1 ];
  1395. yield [ 'SomeText', false, null, false, true, 0 ];
  1396. yield [ 'SomeText', false, 'Foo', false, false, 1 ];
  1397. }
  1398. /**
  1399. * @dataProvider provideUpdateRedirectOn
  1400. * @covers WikiPage::updateRedirectOn
  1401. *
  1402. * @param string $initialText
  1403. * @param bool $initialRedirectState
  1404. * @param string|null $redirectTitle
  1405. * @param bool|null $lastRevIsRedirect
  1406. * @param bool $expectedSuccess
  1407. * @param int $expectedRowCount
  1408. */
  1409. public function testUpdateRedirectOn(
  1410. $initialText,
  1411. $initialRedirectState,
  1412. $redirectTitle,
  1413. $lastRevIsRedirect,
  1414. $expectedSuccess,
  1415. $expectedRowCount
  1416. ) {
  1417. // FIXME: fails under sqlite and postgres
  1418. $this->markTestSkippedIfDbType( 'sqlite' );
  1419. $this->markTestSkippedIfDbType( 'postgres' );
  1420. static $pageCounter = 0;
  1421. $pageCounter++;
  1422. $page = $this->createPage( Title::newFromText( __METHOD__ . $pageCounter ), $initialText );
  1423. $this->assertSame( $initialRedirectState, $page->isRedirect() );
  1424. $redirectTitle = is_string( $redirectTitle )
  1425. ? Title::newFromText( $redirectTitle )
  1426. : $redirectTitle;
  1427. $success = $page->updateRedirectOn( $this->db, $redirectTitle, $lastRevIsRedirect );
  1428. $this->assertSame( $expectedSuccess, $success, 'Success assertion' );
  1429. /**
  1430. * updateRedirectOn explicitly updates the redirect table (and not the page table).
  1431. * Most of core checks the page table for redirect status, so we have to be ugly and
  1432. * assert a select from the table here.
  1433. */
  1434. $this->assertRedirectTableCountForPageId( $page->getId(), $expectedRowCount );
  1435. }
  1436. private function assertRedirectTableCountForPageId( $pageId, $expected ) {
  1437. $this->assertSelect(
  1438. 'redirect',
  1439. 'COUNT(*)',
  1440. [ 'rd_from' => $pageId ],
  1441. [ [ strval( $expected ) ] ]
  1442. );
  1443. }
  1444. /**
  1445. * @covers WikiPage::insertRedirectEntry
  1446. */
  1447. public function testInsertRedirectEntry_insertsRedirectEntry() {
  1448. $page = $this->createPage( Title::newFromText( __METHOD__ ), 'A' );
  1449. $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
  1450. $targetTitle = Title::newFromText( 'SomeTarget#Frag' );
  1451. $targetTitle->mInterwiki = 'eninter';
  1452. $page->insertRedirectEntry( $targetTitle, null );
  1453. $this->assertSelect(
  1454. 'redirect',
  1455. [ 'rd_from', 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
  1456. [ 'rd_from' => $page->getId() ],
  1457. [ [
  1458. strval( $page->getId() ),
  1459. strval( $targetTitle->getNamespace() ),
  1460. strval( $targetTitle->getDBkey() ),
  1461. strval( $targetTitle->getFragment() ),
  1462. strval( $targetTitle->getInterwiki() ),
  1463. ] ]
  1464. );
  1465. }
  1466. /**
  1467. * @covers WikiPage::insertRedirectEntry
  1468. */
  1469. public function testInsertRedirectEntry_insertsRedirectEntryWithPageLatest() {
  1470. $page = $this->createPage( Title::newFromText( __METHOD__ ), 'A' );
  1471. $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
  1472. $targetTitle = Title::newFromText( 'SomeTarget#Frag' );
  1473. $targetTitle->mInterwiki = 'eninter';
  1474. $page->insertRedirectEntry( $targetTitle, $page->getLatest() );
  1475. $this->assertSelect(
  1476. 'redirect',
  1477. [ 'rd_from', 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
  1478. [ 'rd_from' => $page->getId() ],
  1479. [ [
  1480. strval( $page->getId() ),
  1481. strval( $targetTitle->getNamespace() ),
  1482. strval( $targetTitle->getDBkey() ),
  1483. strval( $targetTitle->getFragment() ),
  1484. strval( $targetTitle->getInterwiki() ),
  1485. ] ]
  1486. );
  1487. }
  1488. /**
  1489. * @covers WikiPage::insertRedirectEntry
  1490. */
  1491. public function testInsertRedirectEntry_doesNotInsertIfPageLatestIncorrect() {
  1492. $page = $this->createPage( Title::newFromText( __METHOD__ ), 'A' );
  1493. $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
  1494. $targetTitle = Title::newFromText( 'SomeTarget#Frag' );
  1495. $targetTitle->mInterwiki = 'eninter';
  1496. $page->insertRedirectEntry( $targetTitle, 215251 );
  1497. $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
  1498. }
  1499. private function getRow( array $overrides = [] ) {
  1500. $row = [
  1501. 'page_id' => '44',
  1502. 'page_len' => '76',
  1503. 'page_is_redirect' => '1',
  1504. 'page_latest' => '99',
  1505. 'page_namespace' => '3',
  1506. 'page_title' => 'JaJaTitle',
  1507. 'page_restrictions' => 'edit=autoconfirmed,sysop:move=sysop',
  1508. 'page_touched' => '20120101020202',
  1509. 'page_links_updated' => '20140101020202',
  1510. ];
  1511. foreach ( $overrides as $key => $value ) {
  1512. $row[$key] = $value;
  1513. }
  1514. return (object)$row;
  1515. }
  1516. public function provideNewFromRowSuccess() {
  1517. yield 'basic row' => [
  1518. $this->getRow(),
  1519. function ( WikiPage $wikiPage, self $test ) {
  1520. $test->assertSame( 44, $wikiPage->getId() );
  1521. $test->assertSame( 76, $wikiPage->getTitle()->getLength() );
  1522. $test->assertTrue( $wikiPage->isRedirect() );
  1523. $test->assertSame( 99, $wikiPage->getLatest() );
  1524. $test->assertSame( 3, $wikiPage->getTitle()->getNamespace() );
  1525. $test->assertSame( 'JaJaTitle', $wikiPage->getTitle()->getDBkey() );
  1526. $test->assertSame(
  1527. [
  1528. 'edit' => [ 'autoconfirmed', 'sysop' ],
  1529. 'move' => [ 'sysop' ],
  1530. ],
  1531. $wikiPage->getTitle()->getAllRestrictions()
  1532. );
  1533. $test->assertSame( '20120101020202', $wikiPage->getTouched() );
  1534. $test->assertSame( '20140101020202', $wikiPage->getLinksTimestamp() );
  1535. }
  1536. ];
  1537. yield 'different timestamp formats' => [
  1538. $this->getRow( [
  1539. 'page_touched' => '2012-01-01 02:02:02',
  1540. 'page_links_updated' => '2014-01-01 02:02:02',
  1541. ] ),
  1542. function ( WikiPage $wikiPage, self $test ) {
  1543. $test->assertSame( '20120101020202', $wikiPage->getTouched() );
  1544. $test->assertSame( '20140101020202', $wikiPage->getLinksTimestamp() );
  1545. }
  1546. ];
  1547. yield 'no restrictions' => [
  1548. $this->getRow( [
  1549. 'page_restrictions' => '',
  1550. ] ),
  1551. function ( WikiPage $wikiPage, self $test ) {
  1552. $test->assertSame(
  1553. [
  1554. 'edit' => [],
  1555. 'move' => [],
  1556. ],
  1557. $wikiPage->getTitle()->getAllRestrictions()
  1558. );
  1559. }
  1560. ];
  1561. yield 'not redirect' => [
  1562. $this->getRow( [
  1563. 'page_is_redirect' => '0',
  1564. ] ),
  1565. function ( WikiPage $wikiPage, self $test ) {
  1566. $test->assertFalse( $wikiPage->isRedirect() );
  1567. }
  1568. ];
  1569. }
  1570. /**
  1571. * @covers WikiPage::newFromRow
  1572. * @covers WikiPage::loadFromRow
  1573. * @dataProvider provideNewFromRowSuccess
  1574. *
  1575. * @param object $row
  1576. * @param callable $assertions
  1577. */
  1578. public function testNewFromRow( $row, $assertions ) {
  1579. $page = WikiPage::newFromRow( $row, 'fromdb' );
  1580. $assertions( $page, $this );
  1581. }
  1582. public function provideTestNewFromId_returnsNullOnBadPageId() {
  1583. yield[ 0 ];
  1584. yield[ -11 ];
  1585. }
  1586. /**
  1587. * @covers WikiPage::newFromID
  1588. * @dataProvider provideTestNewFromId_returnsNullOnBadPageId
  1589. */
  1590. public function testNewFromId_returnsNullOnBadPageId( $pageId ) {
  1591. $this->assertNull( WikiPage::newFromID( $pageId ) );
  1592. }
  1593. /**
  1594. * @covers WikiPage::newFromID
  1595. */
  1596. public function testNewFromId_appearsToFetchCorrectRow() {
  1597. $createdPage = $this->createPage( __METHOD__, 'Xsfaij09' );
  1598. $fetchedPage = WikiPage::newFromID( $createdPage->getId() );
  1599. $this->assertSame( $createdPage->getId(), $fetchedPage->getId() );
  1600. $this->assertEquals(
  1601. $createdPage->getContent()->getNativeData(),
  1602. $fetchedPage->getContent()->getNativeData()
  1603. );
  1604. }
  1605. /**
  1606. * @covers WikiPage::newFromID
  1607. */
  1608. public function testNewFromId_returnsNullOnNonExistingId() {
  1609. $this->assertNull( WikiPage::newFromID( 2147483647 ) );
  1610. }
  1611. public function provideTestInsertProtectNullRevision() {
  1612. // phpcs:disable Generic.Files.LineLength
  1613. yield [
  1614. 'goat-message-key',
  1615. [ 'edit' => 'sysop' ],
  1616. [ 'edit' => '20200101040404' ],
  1617. false,
  1618. 'Goat Reason',
  1619. true,
  1620. '(goat-message-key: WikiPageDbTestBase::testInsertProtectNullRevision, UTSysop)(colon-separator)Goat Reason(word-separator)(parentheses: (protect-summary-desc: (restriction-edit), (protect-level-sysop), (protect-expiring: 04:04, 1 (january) 2020, 1 (january) 2020, 04:04)))'
  1621. ];
  1622. yield [
  1623. 'goat-key',
  1624. [ 'edit' => 'sysop', 'move' => 'something' ],
  1625. [ 'edit' => '20200101040404', 'move' => '20210101050505' ],
  1626. false,
  1627. 'Goat Goat',
  1628. true,
  1629. '(goat-key: WikiPageDbTestBase::testInsertProtectNullRevision, UTSysop)(colon-separator)Goat Goat(word-separator)(parentheses: (protect-summary-desc: (restriction-edit), (protect-level-sysop), (protect-expiring: 04:04, 1 (january) 2020, 1 (january) 2020, 04:04))(word-separator)(protect-summary-desc: (restriction-move), (protect-level-something), (protect-expiring: 05:05, 1 (january) 2021, 1 (january) 2021, 05:05)))'
  1630. ];
  1631. // phpcs:enable
  1632. }
  1633. /**
  1634. * @dataProvider provideTestInsertProtectNullRevision
  1635. * @covers WikiPage::insertProtectNullRevision
  1636. * @covers WikiPage::protectDescription
  1637. *
  1638. * @param string $revCommentMsg
  1639. * @param array $limit
  1640. * @param array $expiry
  1641. * @param bool $cascade
  1642. * @param string $reason
  1643. * @param bool|null $user true if the test sysop should be used, or null
  1644. * @param string $expectedComment
  1645. */
  1646. public function testInsertProtectNullRevision(
  1647. $revCommentMsg,
  1648. array $limit,
  1649. array $expiry,
  1650. $cascade,
  1651. $reason,
  1652. $user,
  1653. $expectedComment
  1654. ) {
  1655. $this->setContentLang( 'qqx' );
  1656. $page = $this->createPage( __METHOD__, 'Goat' );
  1657. $user = $user === null ? $user : $this->getTestSysop()->getUser();
  1658. $result = $page->insertProtectNullRevision(
  1659. $revCommentMsg,
  1660. $limit,
  1661. $expiry,
  1662. $cascade,
  1663. $reason,
  1664. $user
  1665. );
  1666. $this->assertTrue( $result instanceof Revision );
  1667. $this->assertSame( $expectedComment, $result->getComment( Revision::RAW ) );
  1668. }
  1669. /**
  1670. * @covers WikiPage::updateRevisionOn
  1671. */
  1672. public function testUpdateRevisionOn_existingPage() {
  1673. $user = $this->getTestSysop()->getUser();
  1674. $page = $this->createPage( __METHOD__, 'StartText' );
  1675. $revision = new Revision(
  1676. [
  1677. 'id' => 9989,
  1678. 'page' => $page->getId(),
  1679. 'title' => $page->getTitle(),
  1680. 'comment' => __METHOD__,
  1681. 'minor_edit' => true,
  1682. 'text' => __METHOD__ . '-text',
  1683. 'len' => strlen( __METHOD__ . '-text' ),
  1684. 'user' => $user->getId(),
  1685. 'user_text' => $user->getName(),
  1686. 'timestamp' => '20170707040404',
  1687. 'content_model' => CONTENT_MODEL_WIKITEXT,
  1688. 'content_format' => CONTENT_FORMAT_WIKITEXT,
  1689. ]
  1690. );
  1691. $result = $page->updateRevisionOn( $this->db, $revision );
  1692. $this->assertTrue( $result );
  1693. $this->assertSame( 9989, $page->getLatest() );
  1694. $this->assertEquals( $revision, $page->getRevision() );
  1695. }
  1696. /**
  1697. * @covers WikiPage::updateRevisionOn
  1698. */
  1699. public function testUpdateRevisionOn_NonExistingPage() {
  1700. $user = $this->getTestSysop()->getUser();
  1701. $page = $this->createPage( __METHOD__, 'StartText' );
  1702. $page->doDeleteArticle( 'reason' );
  1703. $revision = new Revision(
  1704. [
  1705. 'id' => 9989,
  1706. 'page' => $page->getId(),
  1707. 'title' => $page->getTitle(),
  1708. 'comment' => __METHOD__,
  1709. 'minor_edit' => true,
  1710. 'text' => __METHOD__ . '-text',
  1711. 'len' => strlen( __METHOD__ . '-text' ),
  1712. 'user' => $user->getId(),
  1713. 'user_text' => $user->getName(),
  1714. 'timestamp' => '20170707040404',
  1715. 'content_model' => CONTENT_MODEL_WIKITEXT,
  1716. 'content_format' => CONTENT_FORMAT_WIKITEXT,
  1717. ]
  1718. );
  1719. $result = $page->updateRevisionOn( $this->db, $revision );
  1720. $this->assertFalse( $result );
  1721. }
  1722. /**
  1723. * @covers WikiPage::updateIfNewerOn
  1724. */
  1725. public function testUpdateIfNewerOn_olderRevision() {
  1726. $user = $this->getTestSysop()->getUser();
  1727. $page = $this->createPage( __METHOD__, 'StartText' );
  1728. $initialRevision = $page->getRevision();
  1729. $olderTimeStamp = wfTimestamp(
  1730. TS_MW,
  1731. wfTimestamp( TS_UNIX, $initialRevision->getTimestamp() ) - 1
  1732. );
  1733. $olderRevison = new Revision(
  1734. [
  1735. 'id' => 9989,
  1736. 'page' => $page->getId(),
  1737. 'title' => $page->getTitle(),
  1738. 'comment' => __METHOD__,
  1739. 'minor_edit' => true,
  1740. 'text' => __METHOD__ . '-text',
  1741. 'len' => strlen( __METHOD__ . '-text' ),
  1742. 'user' => $user->getId(),
  1743. 'user_text' => $user->getName(),
  1744. 'timestamp' => $olderTimeStamp,
  1745. 'content_model' => CONTENT_MODEL_WIKITEXT,
  1746. 'content_format' => CONTENT_FORMAT_WIKITEXT,
  1747. ]
  1748. );
  1749. $result = $page->updateIfNewerOn( $this->db, $olderRevison );
  1750. $this->assertFalse( $result );
  1751. }
  1752. /**
  1753. * @covers WikiPage::updateIfNewerOn
  1754. */
  1755. public function testUpdateIfNewerOn_newerRevision() {
  1756. $user = $this->getTestSysop()->getUser();
  1757. $page = $this->createPage( __METHOD__, 'StartText' );
  1758. $initialRevision = $page->getRevision();
  1759. $newerTimeStamp = wfTimestamp(
  1760. TS_MW,
  1761. wfTimestamp( TS_UNIX, $initialRevision->getTimestamp() ) + 1
  1762. );
  1763. $newerRevision = new Revision(
  1764. [
  1765. 'id' => 9989,
  1766. 'page' => $page->getId(),
  1767. 'title' => $page->getTitle(),
  1768. 'comment' => __METHOD__,
  1769. 'minor_edit' => true,
  1770. 'text' => __METHOD__ . '-text',
  1771. 'len' => strlen( __METHOD__ . '-text' ),
  1772. 'user' => $user->getId(),
  1773. 'user_text' => $user->getName(),
  1774. 'timestamp' => $newerTimeStamp,
  1775. 'content_model' => CONTENT_MODEL_WIKITEXT,
  1776. 'content_format' => CONTENT_FORMAT_WIKITEXT,
  1777. ]
  1778. );
  1779. $result = $page->updateIfNewerOn( $this->db, $newerRevision );
  1780. $this->assertTrue( $result );
  1781. }
  1782. /**
  1783. * @covers WikiPage::insertOn
  1784. */
  1785. public function testInsertOn() {
  1786. $title = Title::newFromText( __METHOD__ );
  1787. $page = new WikiPage( $title );
  1788. $startTimeStamp = wfTimestampNow();
  1789. $result = $page->insertOn( $this->db );
  1790. $endTimeStamp = wfTimestampNow();
  1791. $this->assertInternalType( 'int', $result );
  1792. $this->assertTrue( $result > 0 );
  1793. $condition = [ 'page_id' => $result ];
  1794. // Check the default fields have been filled
  1795. $this->assertSelect(
  1796. 'page',
  1797. [
  1798. 'page_namespace',
  1799. 'page_title',
  1800. 'page_restrictions',
  1801. 'page_is_redirect',
  1802. 'page_is_new',
  1803. 'page_latest',
  1804. 'page_len',
  1805. ],
  1806. $condition,
  1807. [ [
  1808. '0',
  1809. __METHOD__,
  1810. '',
  1811. '0',
  1812. '1',
  1813. '0',
  1814. '0',
  1815. ] ]
  1816. );
  1817. // Check the page_random field has been filled
  1818. $pageRandom = $this->db->selectField( 'page', 'page_random', $condition );
  1819. $this->assertTrue( (float)$pageRandom < 1 && (float)$pageRandom > 0 );
  1820. // Assert the touched timestamp in the DB is roughly when we inserted the page
  1821. $pageTouched = $this->db->selectField( 'page', 'page_touched', $condition );
  1822. $this->assertTrue(
  1823. wfTimestamp( TS_UNIX, $startTimeStamp )
  1824. <= wfTimestamp( TS_UNIX, $pageTouched )
  1825. );
  1826. $this->assertTrue(
  1827. wfTimestamp( TS_UNIX, $endTimeStamp )
  1828. >= wfTimestamp( TS_UNIX, $pageTouched )
  1829. );
  1830. // Try inserting the same page again and checking the result is false (no change)
  1831. $result = $page->insertOn( $this->db );
  1832. $this->assertFalse( $result );
  1833. }
  1834. /**
  1835. * @covers WikiPage::insertOn
  1836. */
  1837. public function testInsertOn_idSpecified() {
  1838. $title = Title::newFromText( __METHOD__ );
  1839. $page = new WikiPage( $title );
  1840. $id = 1478952189;
  1841. $result = $page->insertOn( $this->db, $id );
  1842. $this->assertSame( $id, $result );
  1843. $condition = [ 'page_id' => $result ];
  1844. // Check there is actually a row in the db
  1845. $this->assertSelect(
  1846. 'page',
  1847. [ 'page_title' ],
  1848. $condition,
  1849. [ [ __METHOD__ ] ]
  1850. );
  1851. }
  1852. public function provideTestDoUpdateRestrictions_setBasicRestrictions() {
  1853. // Note: Once the current dates passes the date in these tests they will fail.
  1854. yield 'move something' => [
  1855. true,
  1856. [ 'move' => 'something' ],
  1857. [],
  1858. [ 'edit' => [], 'move' => [ 'something' ] ],
  1859. [],
  1860. ];
  1861. yield 'move something, edit blank' => [
  1862. true,
  1863. [ 'move' => 'something', 'edit' => '' ],
  1864. [],
  1865. [ 'edit' => [], 'move' => [ 'something' ] ],
  1866. [],
  1867. ];
  1868. yield 'edit sysop, with expiry' => [
  1869. true,
  1870. [ 'edit' => 'sysop' ],
  1871. [ 'edit' => '21330101020202' ],
  1872. [ 'edit' => [ 'sysop' ], 'move' => [] ],
  1873. [ 'edit' => '21330101020202' ],
  1874. ];
  1875. yield 'move and edit, move with expiry' => [
  1876. true,
  1877. [ 'move' => 'something', 'edit' => 'another' ],
  1878. [ 'move' => '22220202010101' ],
  1879. [ 'edit' => [ 'another' ], 'move' => [ 'something' ] ],
  1880. [ 'move' => '22220202010101' ],
  1881. ];
  1882. yield 'move and edit, edit with infinity expiry' => [
  1883. true,
  1884. [ 'move' => 'something', 'edit' => 'another' ],
  1885. [ 'edit' => 'infinity' ],
  1886. [ 'edit' => [ 'another' ], 'move' => [ 'something' ] ],
  1887. [ 'edit' => 'infinity' ],
  1888. ];
  1889. yield 'non existing, create something' => [
  1890. false,
  1891. [ 'create' => 'something' ],
  1892. [],
  1893. [ 'create' => [ 'something' ] ],
  1894. [],
  1895. ];
  1896. yield 'non existing, create something with expiry' => [
  1897. false,
  1898. [ 'create' => 'something' ],
  1899. [ 'create' => '23451212112233' ],
  1900. [ 'create' => [ 'something' ] ],
  1901. [ 'create' => '23451212112233' ],
  1902. ];
  1903. }
  1904. /**
  1905. * @dataProvider provideTestDoUpdateRestrictions_setBasicRestrictions
  1906. * @covers WikiPage::doUpdateRestrictions
  1907. */
  1908. public function testDoUpdateRestrictions_setBasicRestrictions(
  1909. $pageExists,
  1910. array $limit,
  1911. array $expiry,
  1912. array $expectedRestrictions,
  1913. array $expectedRestrictionExpiries
  1914. ) {
  1915. if ( $pageExists ) {
  1916. $page = $this->createPage( __METHOD__, 'ABC' );
  1917. } else {
  1918. $page = new WikiPage( Title::newFromText( __METHOD__ . '-nonexist' ) );
  1919. }
  1920. $user = $this->getTestSysop()->getUser();
  1921. $cascade = false;
  1922. $status = $page->doUpdateRestrictions( $limit, $expiry, $cascade, 'aReason', $user, [] );
  1923. $logId = $status->getValue();
  1924. $allRestrictions = $page->getTitle()->getAllRestrictions();
  1925. $this->assertTrue( $status->isGood() );
  1926. $this->assertInternalType( 'int', $logId );
  1927. $this->assertSame( $expectedRestrictions, $allRestrictions );
  1928. foreach ( $expectedRestrictionExpiries as $key => $value ) {
  1929. $this->assertSame( $value, $page->getTitle()->getRestrictionExpiry( $key ) );
  1930. }
  1931. // Make sure the log entry looks good
  1932. // log_params is not checked here
  1933. $actorQuery = ActorMigration::newMigration()->getJoin( 'log_user' );
  1934. $this->assertSelect(
  1935. [ 'logging' ] + $actorQuery['tables'],
  1936. [
  1937. 'log_comment',
  1938. 'log_user' => $actorQuery['fields']['log_user'],
  1939. 'log_user_text' => $actorQuery['fields']['log_user_text'],
  1940. 'log_namespace',
  1941. 'log_title',
  1942. ],
  1943. [ 'log_id' => $logId ],
  1944. [ [
  1945. 'aReason',
  1946. (string)$user->getId(),
  1947. $user->getName(),
  1948. (string)$page->getTitle()->getNamespace(),
  1949. $page->getTitle()->getDBkey(),
  1950. ] ],
  1951. [],
  1952. $actorQuery['joins']
  1953. );
  1954. }
  1955. /**
  1956. * @covers WikiPage::doUpdateRestrictions
  1957. */
  1958. public function testDoUpdateRestrictions_failsOnReadOnly() {
  1959. $page = $this->createPage( __METHOD__, 'ABC' );
  1960. $user = $this->getTestSysop()->getUser();
  1961. $cascade = false;
  1962. // Set read only
  1963. $readOnly = $this->getMockBuilder( ReadOnlyMode::class )
  1964. ->disableOriginalConstructor()
  1965. ->setMethods( [ 'isReadOnly', 'getReason' ] )
  1966. ->getMock();
  1967. $readOnly->expects( $this->once() )
  1968. ->method( 'isReadOnly' )
  1969. ->will( $this->returnValue( true ) );
  1970. $readOnly->expects( $this->once() )
  1971. ->method( 'getReason' )
  1972. ->will( $this->returnValue( 'Some Read Only Reason' ) );
  1973. $this->setService( 'ReadOnlyMode', $readOnly );
  1974. $status = $page->doUpdateRestrictions( [], [], $cascade, 'aReason', $user, [] );
  1975. $this->assertFalse( $status->isOK() );
  1976. $this->assertSame( 'readonlytext', $status->getMessage()->getKey() );
  1977. }
  1978. /**
  1979. * @covers WikiPage::doUpdateRestrictions
  1980. */
  1981. public function testDoUpdateRestrictions_returnsGoodIfNothingChanged() {
  1982. $page = $this->createPage( __METHOD__, 'ABC' );
  1983. $user = $this->getTestSysop()->getUser();
  1984. $cascade = false;
  1985. $limit = [ 'edit' => 'sysop' ];
  1986. $status = $page->doUpdateRestrictions(
  1987. $limit,
  1988. [],
  1989. $cascade,
  1990. 'aReason',
  1991. $user,
  1992. []
  1993. );
  1994. // The first entry should have a logId as it did something
  1995. $this->assertTrue( $status->isGood() );
  1996. $this->assertInternalType( 'int', $status->getValue() );
  1997. $status = $page->doUpdateRestrictions(
  1998. $limit,
  1999. [],
  2000. $cascade,
  2001. 'aReason',
  2002. $user,
  2003. []
  2004. );
  2005. // The second entry should not have a logId as nothing changed
  2006. $this->assertTrue( $status->isGood() );
  2007. $this->assertNull( $status->getValue() );
  2008. }
  2009. /**
  2010. * @covers WikiPage::doUpdateRestrictions
  2011. */
  2012. public function testDoUpdateRestrictions_logEntryTypeAndAction() {
  2013. $page = $this->createPage( __METHOD__, 'ABC' );
  2014. $user = $this->getTestSysop()->getUser();
  2015. $cascade = false;
  2016. // Protect the page
  2017. $status = $page->doUpdateRestrictions(
  2018. [ 'edit' => 'sysop' ],
  2019. [],
  2020. $cascade,
  2021. 'aReason',
  2022. $user,
  2023. []
  2024. );
  2025. $this->assertTrue( $status->isGood() );
  2026. $this->assertInternalType( 'int', $status->getValue() );
  2027. $this->assertSelect(
  2028. 'logging',
  2029. [ 'log_type', 'log_action' ],
  2030. [ 'log_id' => $status->getValue() ],
  2031. [ [ 'protect', 'protect' ] ]
  2032. );
  2033. // Modify the protection
  2034. $status = $page->doUpdateRestrictions(
  2035. [ 'edit' => 'somethingElse' ],
  2036. [],
  2037. $cascade,
  2038. 'aReason',
  2039. $user,
  2040. []
  2041. );
  2042. $this->assertTrue( $status->isGood() );
  2043. $this->assertInternalType( 'int', $status->getValue() );
  2044. $this->assertSelect(
  2045. 'logging',
  2046. [ 'log_type', 'log_action' ],
  2047. [ 'log_id' => $status->getValue() ],
  2048. [ [ 'protect', 'modify' ] ]
  2049. );
  2050. // Remove the protection
  2051. $status = $page->doUpdateRestrictions(
  2052. [],
  2053. [],
  2054. $cascade,
  2055. 'aReason',
  2056. $user,
  2057. []
  2058. );
  2059. $this->assertTrue( $status->isGood() );
  2060. $this->assertInternalType( 'int', $status->getValue() );
  2061. $this->assertSelect(
  2062. 'logging',
  2063. [ 'log_type', 'log_action' ],
  2064. [ 'log_id' => $status->getValue() ],
  2065. [ [ 'protect', 'unprotect' ] ]
  2066. );
  2067. }
  2068. /**
  2069. * @covers WikiPage::newPageUpdater
  2070. * @covers WikiPage::getDerivedDataUpdater
  2071. */
  2072. public function testNewPageUpdater() {
  2073. $user = $this->getTestUser()->getUser();
  2074. $page = $this->newPage( __METHOD__, __METHOD__ );
  2075. /** @var Content $content */
  2076. $content = $this->getMockBuilder( WikitextContent::class )
  2077. ->setConstructorArgs( [ 'Hello World' ] )
  2078. ->setMethods( [ 'getParserOutput' ] )
  2079. ->getMock();
  2080. $content->expects( $this->once() )
  2081. ->method( 'getParserOutput' )
  2082. ->willReturn( new ParserOutput( 'HTML' ) );
  2083. $preparedEditBefore = $page->prepareContentForEdit( $content, null, $user );
  2084. // provide context, so the cache can be kept in place
  2085. $slotsUpdate = new revisionSlotsUpdate();
  2086. $slotsUpdate->modifyContent( 'main', $content );
  2087. $updater = $page->newPageUpdater( $user, $slotsUpdate );
  2088. $updater->setContent( 'main', $content );
  2089. $revision = $updater->saveRevision(
  2090. CommentStoreComment::newUnsavedComment( 'test' ),
  2091. EDIT_NEW
  2092. );
  2093. $preparedEditAfter = $page->prepareContentForEdit( $content, $revision, $user );
  2094. $this->assertSame( $revision->getId(), $page->getLatest() );
  2095. // Parsed output must remain cached throughout.
  2096. $this->assertSame( $preparedEditBefore->output, $preparedEditAfter->output );
  2097. }
  2098. /**
  2099. * @covers WikiPage::newPageUpdater
  2100. * @covers WikiPage::getDerivedDataUpdater
  2101. */
  2102. public function testGetDerivedDataUpdater() {
  2103. $admin = $this->getTestSysop()->getUser();
  2104. /** @var object $page */
  2105. $page = $this->createPage( __METHOD__, __METHOD__ );
  2106. $page = TestingAccessWrapper::newFromObject( $page );
  2107. $revision = $page->getRevision()->getRevisionRecord();
  2108. $user = $revision->getUser();
  2109. $slotsUpdate = new RevisionSlotsUpdate();
  2110. $slotsUpdate->modifyContent( 'main', new WikitextContent( 'Hello World' ) );
  2111. // get a virgin updater
  2112. $updater1 = $page->getDerivedDataUpdater( $user );
  2113. $this->assertFalse( $updater1->isUpdatePrepared() );
  2114. $updater1->prepareUpdate( $revision );
  2115. // Re-use updater with same revision or content, even if base changed
  2116. $this->assertSame( $updater1, $page->getDerivedDataUpdater( $user, $revision ) );
  2117. $slotsUpdate = RevisionSlotsUpdate::newFromContent(
  2118. [ 'main' => $revision->getContent( 'main' ) ]
  2119. );
  2120. $this->assertSame( $updater1, $page->getDerivedDataUpdater( $user, null, $slotsUpdate ) );
  2121. // Don't re-use for edit if base revision ID changed
  2122. $this->assertNotSame(
  2123. $updater1,
  2124. $page->getDerivedDataUpdater( $user, null, $slotsUpdate, true )
  2125. );
  2126. // Don't re-use with different user
  2127. $updater2a = $page->getDerivedDataUpdater( $admin, null, $slotsUpdate );
  2128. $updater2a->prepareContent( $admin, $slotsUpdate, false );
  2129. $updater2b = $page->getDerivedDataUpdater( $user, null, $slotsUpdate );
  2130. $updater2b->prepareContent( $user, $slotsUpdate, false );
  2131. $this->assertNotSame( $updater2a, $updater2b );
  2132. // Don't re-use with different content
  2133. $updater3 = $page->getDerivedDataUpdater( $admin, null, $slotsUpdate );
  2134. $updater3->prepareUpdate( $revision );
  2135. $this->assertNotSame( $updater2b, $updater3 );
  2136. // Don't re-use if no context given
  2137. $updater4 = $page->getDerivedDataUpdater( $admin );
  2138. $updater4->prepareUpdate( $revision );
  2139. $this->assertNotSame( $updater3, $updater4 );
  2140. // Don't re-use if AGAIN no context given
  2141. $updater5 = $page->getDerivedDataUpdater( $admin );
  2142. $this->assertNotSame( $updater4, $updater5 );
  2143. // Don't re-use cached "virgin" unprepared updater
  2144. $updater6 = $page->getDerivedDataUpdater( $admin, $revision );
  2145. $this->assertNotSame( $updater5, $updater6 );
  2146. }
  2147. protected function assertPreparedEditEquals(
  2148. PreparedEdit $edit, PreparedEdit $edit2, $message = ''
  2149. ) {
  2150. // suppress differences caused by a clock tick between generating the two PreparedEdits
  2151. if ( abs( $edit->timestamp - $edit2->timestamp ) < 3 ) {
  2152. $edit2 = clone $edit2;
  2153. $edit2->timestamp = $edit->timestamp;
  2154. }
  2155. $this->assertEquals( $edit, $edit2, $message );
  2156. }
  2157. protected function assertPreparedEditNotEquals(
  2158. PreparedEdit $edit, PreparedEdit $edit2, $message = ''
  2159. ) {
  2160. if ( abs( $edit->timestamp - $edit2->timestamp ) < 3 ) {
  2161. $edit2 = clone $edit2;
  2162. $edit2->timestamp = $edit->timestamp;
  2163. }
  2164. $this->assertNotEquals( $edit, $edit2, $message );
  2165. }
  2166. }