MediaWiki REL1_32
PageArchiveTestBase.php
Go to the documentation of this file.
1<?php
4
8abstract class PageArchiveTestBase extends MediaWikiTestCase {
9
13 protected $pageId;
14
18 protected $archivedPage;
19
24 protected $ipEditor;
25
30 protected $firstRev;
31
36 protected $ipRev;
37
38 function __construct( $name = null, array $data = [], $dataName = '' ) {
39 parent::__construct( $name, $data, $dataName );
40
41 $this->tablesUsed = array_merge(
42 $this->tablesUsed,
43 [
44 'page',
45 'revision',
46 'ip_changes',
47 'text',
48 'archive',
49 'recentchanges',
50 'logging',
51 'page_props',
52 ]
53 );
54 }
55
56 protected function addCoreDBData() {
57 // Blank out to avoid failures when schema overrides imposed by subclasses
58 // affect revision storage.
59 }
60
64 abstract protected function getMcrMigrationStage();
65
69 abstract protected function getMcrTablesToReset();
70
74 protected function getContentHandlerUseDB() {
75 return true;
76 }
77
78 protected function setUp() {
79 parent::setUp();
80
81 $this->tablesUsed += $this->getMcrTablesToReset();
82
83 $this->setMwGlobals( 'wgCommentTableSchemaMigrationStage', MIGRATION_OLD );
84 $this->setMwGlobals( 'wgActorTableSchemaMigrationStage', SCHEMA_COMPAT_OLD );
85 $this->setMwGlobals( 'wgContentHandlerUseDB', $this->getContentHandlerUseDB() );
86 $this->setMwGlobals(
87 'wgMultiContentRevisionSchemaMigrationStage',
89 );
90 $this->overrideMwServices();
91
92 // First create our dummy page
93 $page = Title::newFromText( 'PageArchiveTest_thePage' );
94 $page = new WikiPage( $page );
95 $content = ContentHandler::makeContent(
96 'testing',
97 $page->getTitle(),
99 );
100
101 $user = $this->getTestUser()->getUser();
102 $page->doEditContent( $content, 'testing', EDIT_NEW, false, $user );
103
104 $this->pageId = $page->getId();
105 $this->firstRev = $page->getRevision()->getRevisionRecord();
106
107 // Insert IP revision
108 $this->ipEditor = '2001:db8::1';
109
110 $revisionStore = MediaWikiServices::getInstance()->getRevisionStore();
111
112 $ipTimestamp = wfTimestamp(
113 TS_MW,
114 wfTimestamp( TS_UNIX, $this->firstRev->getTimestamp() ) + 1
115 );
116
117 $rev = $revisionStore->newMutableRevisionFromArray( [
118 'text' => 'Lorem Ipsum',
119 'comment' => 'just a test',
120 'page' => $page->getId(),
121 'user_text' => $this->ipEditor,
122 'timestamp' => $ipTimestamp,
123 ] );
124
125 $dbw = wfGetDB( DB_MASTER );
126 $this->ipRev = $revisionStore->insertRevisionOn( $rev, $dbw );
127
128 // Delete the page
129 $page->doDeleteArticleReal( 'Just a test deletion' );
130
131 $this->archivedPage = new PageArchive( $page->getTitle() );
132 }
133
138 public function testUndeleteRevisions() {
139 // TODO: MCR: Test undeletion with multiple slots. Check that slots remain untouched.
140
141 // First make sure old revisions are archived
144 $row = $dbr->selectRow(
145 $arQuery['tables'],
146 $arQuery['fields'],
147 [ 'ar_rev_id' => $this->ipRev->getId() ],
148 __METHOD__,
149 [],
150 $arQuery['joins']
151 );
152 $this->assertEquals( $this->ipEditor, $row->ar_user_text );
153
154 // Should not be in revision
155 $row = $dbr->selectRow( 'revision', '1', [ 'rev_id' => $this->ipRev->getId() ] );
156 $this->assertFalse( $row );
157
158 // Should not be in ip_changes
159 $row = $dbr->selectRow( 'ip_changes', '1', [ 'ipc_rev_id' => $this->ipRev->getId() ] );
160 $this->assertFalse( $row );
161
162 // Restore the page
163 $this->archivedPage->undelete( [] );
164
165 // Should be back in revision
167 $row = $dbr->selectRow(
168 $revQuery['tables'],
169 $revQuery['fields'],
170 [ 'rev_id' => $this->ipRev->getId() ],
171 __METHOD__,
172 [],
173 $revQuery['joins']
174 );
175 $this->assertNotFalse( $row, 'row exists in revision table' );
176 $this->assertEquals( $this->ipEditor, $row->rev_user_text );
177
178 // Should be back in ip_changes
179 $row = $dbr->selectRow( 'ip_changes', [ 'ipc_hex' ], [ 'ipc_rev_id' => $this->ipRev->getId() ] );
180 $this->assertNotFalse( $row, 'row exists in ip_changes table' );
181 $this->assertEquals( IP::toHex( $this->ipEditor ), $row->ipc_hex );
182 }
183
184 abstract protected function getExpectedArchiveRows();
185
189 public function testListRevisions() {
190 $revisions = $this->archivedPage->listRevisions();
191 $this->assertEquals( 2, $revisions->numRows() );
192
193 // Get the rows as arrays
194 $row0 = (array)$revisions->current();
195 $row1 = (array)$revisions->next();
196
197 $expectedRows = $this->getExpectedArchiveRows();
198
199 $this->assertEquals(
200 $expectedRows[0],
201 $row0
202 );
203 $this->assertEquals(
204 $expectedRows[1],
205 $row1
206 );
207 }
208
212 public function testListPagesBySearch() {
213 $pages = PageArchive::listPagesBySearch( 'PageArchiveTest_thePage' );
214 $this->assertSame( 1, $pages->numRows() );
215
216 $page = (array)$pages->current();
217
218 $this->assertSame(
219 [
220 'ar_namespace' => '0',
221 'ar_title' => 'PageArchiveTest_thePage',
222 'count' => '2',
223 ],
224 $page
225 );
226 }
227
231 public function testListPagesByPrefix() {
232 $pages = PageArchive::listPagesByPrefix( 'PageArchiveTest' );
233 $this->assertSame( 1, $pages->numRows() );
234
235 $page = (array)$pages->current();
236
237 $this->assertSame(
238 [
239 'ar_namespace' => '0',
240 'ar_title' => 'PageArchiveTest_thePage',
241 'count' => '2',
242 ],
243 $page
244 );
245 }
246
248 yield 'missing ar_text_id field' => [ [] ];
249 yield 'ar_text_id is null' => [ [ 'ar_text_id' => null ] ];
250 yield 'ar_text_id is zero' => [ [ 'ar_text_id' => 0 ] ];
251 yield 'ar_text_id is "0"' => [ [ 'ar_text_id' => '0' ] ];
252 }
253
259 $this->hideDeprecated( PageArchive::class . '::getTextFromRow' );
260 $this->setExpectedException( InvalidArgumentException::class );
261
262 $this->archivedPage->getTextFromRow( (object)$row );
263 }
264
268 public function testGetLastRevisionText() {
269 $this->hideDeprecated( PageArchive::class . '::getLastRevisionText' );
270
271 $text = $this->archivedPage->getLastRevisionText();
272 $this->assertSame( 'Lorem Ipsum', $text );
273 }
274
278 public function testGetLastRevisionId() {
279 $id = $this->archivedPage->getLastRevisionId();
280 $this->assertSame( $this->ipRev->getId(), $id );
281 }
282
286 public function testIsDeleted() {
287 $this->assertTrue( $this->archivedPage->isDeleted() );
288 }
289
293 public function testGetRevision() {
294 $rev = $this->archivedPage->getRevision( $this->ipRev->getTimestamp() );
295 $this->assertNotNull( $rev );
296 $this->assertSame( $this->pageId, $rev->getPage() );
297
298 $rev = $this->archivedPage->getRevision( '22991212115555' );
299 $this->assertNull( $rev );
300 }
301
305 public function testGetArchivedRevision() {
306 $rev = $this->archivedPage->getArchivedRevision( $this->ipRev->getId() );
307 $this->assertNotNull( $rev );
308 $this->assertSame( $this->ipRev->getTimestamp(), $rev->getTimestamp() );
309 $this->assertSame( $this->pageId, $rev->getPage() );
310
311 $rev = $this->archivedPage->getArchivedRevision( 632546 );
312 $this->assertNull( $rev );
313 }
314
318 public function testGetPreviousRevision() {
319 $rev = $this->archivedPage->getPreviousRevision( $this->ipRev->getTimestamp() );
320 $this->assertNotNull( $rev );
321 $this->assertSame( $this->firstRev->getId(), $rev->getId() );
322
323 $rev = $this->archivedPage->getPreviousRevision( $this->firstRev->getTimestamp() );
324 $this->assertNull( $rev );
325
326 // Re-create our dummy page
327 $title = Title::newFromText( 'PageArchiveTest_thePage' );
328 $page = new WikiPage( $title );
329 $content = ContentHandler::makeContent(
330 'testing again',
331 $page->getTitle(),
333 );
334
335 $user = $this->getTestUser()->getUser();
336 $status = $page->doEditContent( $content, 'testing', EDIT_NEW, false, $user );
337
339 $newRev = $status->value['revision'];
340
341 // force the revision timestamp
342 $newTimestamp = wfTimestamp(
343 TS_MW,
344 wfTimestamp( TS_UNIX, $this->ipRev->getTimestamp() ) + 1
345 );
346
347 $this->db->update(
348 'revision',
349 [ 'rev_timestamp' => $this->db->timestamp( $newTimestamp ) ],
350 [ 'rev_id' => $newRev->getId() ]
351 );
352
353 // check that we don't get the existing revision too soon.
354 $rev = $this->archivedPage->getPreviousRevision( $newTimestamp );
355 $this->assertNotNull( $rev );
356 $this->assertSame( $this->ipRev->getId(), $rev->getId() );
357
358 // check that we do get the existing revision when appropriate.
359 $afterNewTimestamp = wfTimestamp(
360 TS_MW,
361 wfTimestamp( TS_UNIX, $newTimestamp ) + 1
362 );
363
364 $rev = $this->archivedPage->getPreviousRevision( $afterNewTimestamp );
365 $this->assertNotNull( $rev );
366 $this->assertSame( $newRev->getId(), $rev->getId() );
367 }
368
369}
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
overrideMwServices(Config $configOverrides=null, array $services=[])
Stashes the global instance of MediaWikiServices, and installs a new one, allowing test cases to over...
setMwGlobals( $pairs, $value=null)
Sets a global, maintaining a stashed version of the previous global to be restored in tearDown.
hideDeprecated( $function)
Don't throw a warning if $function is deprecated and called later.
static getTestUser( $groups=[])
Convenience method for getting an immutable test user.
MediaWikiServices is the service locator for the application scope of MediaWiki.
Page revision base class.
Base class for tests of PageArchive against different database schemas.
testGetLastRevisionText()
PageArchive::getLastRevisionText.
RevisionRecord $ipRev
Revision of the IP edit (the second edit)
__construct( $name=null, array $data=[], $dataName='')
RevisionRecord $firstRev
Revision of the first (initial) edit.
testListRevisions()
PageArchive::listRevisions.
testGetLastRevisionId()
PageArchive::getLastRevisionId.
testGetTextFromRowThrowsInvalidArgumentException(array $row)
provideGetTextFromRowThrowsInvalidArgumentException PageArchive::getTextFromRow
testGetRevision()
PageArchive::getRevision.
testListPagesByPrefix()
PageArchive::listPagesBySearch.
testUndeleteRevisions()
PageArchive::undelete PageArchive::undeleteRevisions.
testGetPreviousRevision()
PageArchive::getPreviousRevision.
$ipEditor
A logged out user who edited the page before it was archived.
testListPagesBySearch()
PageArchive::listPagesBySearch.
testIsDeleted()
PageArchive::isDeleted.
testGetArchivedRevision()
PageArchive::getRevision.
Used to show archived pages and eventually restore them.
static listPagesBySearch( $term)
List deleted pages recorded in the archive matching the given term, using search engine archive.
static listPagesByPrefix( $prefix)
List deleted pages recorded in the archive table matching the given title prefix.
static getArchiveQueryInfo()
Return the tables, fields, and join conditions to be selected to create a new archived revision objec...
Definition Revision.php:535
static getQueryInfo( $options=[])
Return the tables, fields, and join conditions to be selected to create a new revision object.
Definition Revision.php:521
Class representing a MediaWiki article and history.
Definition WikiPage.php:44
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action, or null $user:User who performed the tagging when the tagging is subsequent to the action, or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy: boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
Definition hooks.txt:1071
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:1818
const SCHEMA_COMPAT_OLD
Definition Defines.php:290
const CONTENT_MODEL_WIKITEXT
Definition Defines.php:235
const MIGRATION_OLD
Definition Defines.php:315
const EDIT_NEW
Definition Defines.php:152
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
$content
$newRev
const DB_REPLICA
Definition defines.php:25
const DB_MASTER
Definition defines.php:26