Remove hard deprecation of PasswordPolicyChecks::checkPopularPasswordBlacklist
[lhc/web/wiklou.git] / tests / phpunit / includes / MovePageTest.php
1 <?php
2
3 use MediaWiki\Config\ServiceOptions;
4 use MediaWiki\MediaWikiServices;
5 use MediaWiki\Page\MovePageFactory;
6 use MediaWiki\Permissions\PermissionManager;
7 use Wikimedia\Rdbms\IDatabase;
8 use Wikimedia\Rdbms\LoadBalancer;
9
10 /**
11 * @group Database
12 */
13 class MovePageTest extends MediaWikiTestCase {
14 /**
15 * @param string $class
16 * @return object A mock that throws on any method call
17 */
18 private function getNoOpMock( $class ) {
19 $mock = $this->createMock( $class );
20 $mock->expects( $this->never() )->method( $this->anythingBut( '__destruct' ) );
21 return $mock;
22 }
23
24 /**
25 * The only files that exist are 'File:Existent.jpg', 'File:Existent2.jpg', and
26 * 'File:Existent-file-no-page.jpg'. Calling unexpected methods causes a test failure.
27 *
28 * @return RepoGroup
29 */
30 private function getMockRepoGroup() : RepoGroup {
31 $mockExistentFile = $this->createMock( LocalFile::class );
32 $mockExistentFile->method( 'exists' )->willReturn( true );
33 $mockExistentFile->method( 'getMimeType' )->willReturn( 'image/jpeg' );
34 $mockExistentFile->expects( $this->never() )
35 ->method( $this->anythingBut( 'exists', 'load', 'getMimeType', '__destruct' ) );
36
37 $mockNonexistentFile = $this->createMock( LocalFile::class );
38 $mockNonexistentFile->method( 'exists' )->willReturn( false );
39 $mockNonexistentFile->expects( $this->never() )
40 ->method( $this->anythingBut( 'exists', 'load', '__destruct' ) );
41
42 $mockLocalRepo = $this->createMock( LocalRepo::class );
43 $mockLocalRepo->method( 'newFile' )->will( $this->returnCallback(
44 function ( Title $title ) use ( $mockExistentFile, $mockNonexistentFile ) {
45 if ( in_array( $title->getPrefixedText(),
46 [ 'File:Existent.jpg', 'File:Existent2.jpg', 'File:Existent-file-no-page.jpg' ]
47 ) ) {
48 return $mockExistentFile;
49 }
50 return $mockNonexistentFile;
51 }
52 ) );
53 $mockLocalRepo->expects( $this->never() )
54 ->method( $this->anythingBut( 'newFile', '__destruct' ) );
55
56 $mockRepoGroup = $this->createMock( RepoGroup::class );
57 $mockRepoGroup->method( 'getLocalRepo' )->willReturn( $mockLocalRepo );
58 $mockRepoGroup->expects( $this->never() )
59 ->method( $this->anythingBut( 'getLocalRepo', '__destruct' ) );
60
61 return $mockRepoGroup;
62 }
63
64 /**
65 * @param LinkTarget $old
66 * @param LinkTarget $new
67 * @param array $params Valid keys are: db, options, nsInfo, wiStore, repoGroup.
68 * options is an indexed array that will overwrite our defaults, not a ServiceOptions, so it
69 * need not contain all keys.
70 * @return MovePage
71 */
72 private function newMovePage( $old, $new, array $params = [] ) : MovePage {
73 $mockLB = $this->createMock( LoadBalancer::class );
74 $mockLB->method( 'getConnection' )
75 ->willReturn( $params['db'] ?? $this->getNoOpMock( IDatabase::class ) );
76 $mockLB->expects( $this->never() )
77 ->method( $this->anythingBut( 'getConnection', '__destruct' ) );
78
79 $mockNsInfo = $this->createMock( NamespaceInfo::class );
80 $mockNsInfo->method( 'isMovable' )->will( $this->returnCallback(
81 function ( $ns ) {
82 return $ns >= 0;
83 }
84 ) );
85 $mockNsInfo->expects( $this->never() )
86 ->method( $this->anythingBut( 'isMovable', '__destruct' ) );
87
88 return new MovePage(
89 $old,
90 $new,
91 new ServiceOptions(
92 MovePageFactory::$constructorOptions,
93 $params['options'] ?? [],
94 [
95 'CategoryCollation' => 'uppercase',
96 'ContentHandlerUseDB' => true,
97 ]
98 ),
99 $mockLB,
100 $params['nsInfo'] ?? $mockNsInfo,
101 $params['wiStore'] ?? $this->getNoOpMock( WatchedItemStore::class ),
102 $params['permMgr'] ?? $this->getNoOpMock( PermissionManager::class ),
103 $params['repoGroup'] ?? $this->getMockRepoGroup()
104 );
105 }
106
107 public function setUp() {
108 parent::setUp();
109
110 // Ensure we have some pages that are guaranteed to exist or not
111 $this->getExistingTestPage( 'Existent' );
112 $this->getExistingTestPage( 'Existent2' );
113 $this->getExistingTestPage( 'File:Existent.jpg' );
114 $this->getExistingTestPage( 'File:Existent2.jpg' );
115 $this->getExistingTestPage( 'MediaWiki:Existent.js' );
116 $this->getExistingTestPage( 'Hooked in place' );
117 $this->getNonExistingTestPage( 'Nonexistent' );
118 $this->getNonExistingTestPage( 'Nonexistent2' );
119 $this->getNonExistingTestPage( 'File:Nonexistent.jpg' );
120 $this->getNonExistingTestPage( 'File:Nonexistent.png' );
121 $this->getNonExistingTestPage( 'File:Existent-file-no-page.jpg' );
122 $this->getNonExistingTestPage( 'MediaWiki:Nonexistent' );
123 $this->getNonExistingTestPage( 'No content allowed' );
124
125 // Set a couple of hooks for specific pages
126 $this->setTemporaryHook( 'ContentModelCanBeUsedOn',
127 function ( $modelId, Title $title, &$ok ) {
128 if ( $title->getPrefixedText() === 'No content allowed' ) {
129 $ok = false;
130 }
131 }
132 );
133
134 $this->setTemporaryHook( 'TitleIsMovable',
135 function ( Title $title, &$result ) {
136 if ( strtolower( $title->getPrefixedText() ) === 'hooked in place' ) {
137 $result = false;
138 }
139 }
140 );
141
142 $this->tablesUsed[] = 'page';
143 $this->tablesUsed[] = 'revision';
144 $this->tablesUsed[] = 'comment';
145 }
146
147 /**
148 * @covers MovePage::__construct
149 */
150 public function testConstructorDefaults() {
151 $services = MediaWikiServices::getInstance();
152
153 $obj1 = new MovePage( Title::newFromText( 'A' ), Title::newFromText( 'B' ) );
154 $obj2 = new MovePage(
155 Title::newFromText( 'A' ),
156 Title::newFromText( 'B' ),
157 new ServiceOptions( MovePageFactory::$constructorOptions, $services->getMainConfig() ),
158 $services->getDBLoadBalancer(),
159 $services->getNamespaceInfo(),
160 $services->getWatchedItemStore(),
161 $services->getPermissionManager(),
162 $services->getRepoGroup(),
163 $services->getTitleFormatter()
164 );
165
166 $this->assertEquals( $obj2, $obj1 );
167 }
168
169 /**
170 * @dataProvider provideIsValidMove
171 * @covers MovePage::isValidMove
172 * @covers MovePage::isValidMoveTarget
173 * @covers MovePage::isValidFileMove
174 * @covers MovePage::__construct
175 * @covers Title::isValidMoveOperation
176 *
177 * @param string|Title $old
178 * @param string|Title $new
179 * @param array $expectedErrors
180 * @param array $extraOptions
181 */
182 public function testIsValidMove(
183 $old, $new, array $expectedErrors, array $extraOptions = []
184 ) {
185 if ( is_string( $old ) ) {
186 $old = Title::newFromText( $old );
187 }
188 if ( is_string( $new ) ) {
189 $new = Title::newFromText( $new );
190 }
191 // Can't test MovePage with a null target, only isValidMoveOperation
192 if ( $new ) {
193 $mp = $this->newMovePage( $old, $new, [ 'options' => $extraOptions ] );
194 $this->assertSame( $expectedErrors, $mp->isValidMove()->getErrorsArray() );
195 }
196
197 foreach ( $extraOptions as $key => $val ) {
198 $this->setMwGlobals( "wg$key", $val );
199 }
200 $this->overrideMwServices();
201 $this->setService( 'RepoGroup', $this->getMockRepoGroup() );
202 // This returns true instead of an array if there are no errors
203 $this->hideDeprecated( 'Title::isValidMoveOperation' );
204 $this->assertSame( $expectedErrors ?: true, $old->isValidMoveOperation( $new, false ) );
205 }
206
207 public static function provideIsValidMove() {
208 global $wgMultiContentRevisionSchemaMigrationStage;
209 $ret = [
210 'Self move' => [
211 'Existent',
212 'Existent',
213 [ [ 'selfmove' ] ],
214 ],
215 'Move to null' => [
216 'Existent',
217 null,
218 [ [ 'badtitletext' ] ],
219 ],
220 'Move from empty name' => [
221 Title::makeTitle( NS_MAIN, '' ),
222 'Nonexistent',
223 // @todo More specific error message, or make the move valid if the page actually
224 // exists somehow in the database
225 [ [ 'badarticleerror' ] ],
226 ],
227 'Move to empty name' => [
228 'Existent',
229 Title::makeTitle( NS_MAIN, '' ),
230 [ [ 'movepage-invalid-target-title' ] ],
231 ],
232 'Move to invalid name' => [
233 'Existent',
234 Title::makeTitle( NS_MAIN, '<' ),
235 [ [ 'movepage-invalid-target-title' ] ],
236 ],
237 'Move between invalid names' => [
238 Title::makeTitle( NS_MAIN, '<' ),
239 Title::makeTitle( NS_MAIN, '>' ),
240 // @todo First error message should be more specific, or maybe we should make moving
241 // such pages valid if they actually exist somehow in the database
242 [ [ 'movepage-source-doesnt-exist' ], [ 'movepage-invalid-target-title' ] ],
243 ],
244 'Move nonexistent' => [
245 'Nonexistent',
246 'Nonexistent2',
247 [ [ 'movepage-source-doesnt-exist' ] ],
248 ],
249 'Move over existing' => [
250 'Existent',
251 'Existent2',
252 [ [ 'articleexists' ] ],
253 ],
254 'Move from another wiki' => [
255 Title::makeTitle( NS_MAIN, 'Test', '', 'otherwiki' ),
256 'Nonexistent',
257 [ [ 'immobile-source-namespace-iw' ] ],
258 ],
259 'Move special page' => [
260 'Special:FooBar',
261 'Nonexistent',
262 [ [ 'immobile-source-namespace', 'Special' ] ],
263 ],
264 'Move to another wiki' => [
265 'Existent',
266 Title::makeTitle( NS_MAIN, 'Test', '', 'otherwiki' ),
267 [ [ 'immobile-target-namespace-iw' ] ],
268 ],
269 'Move to special page' =>
270 [ 'Existent', 'Special:FooBar', [ [ 'immobile-target-namespace', 'Special' ] ] ],
271 'Move to allowed content model' => [
272 'MediaWiki:Existent.js',
273 'MediaWiki:Nonexistent',
274 [],
275 ],
276 'Move to prohibited content model' => [
277 'Existent',
278 'No content allowed',
279 [ [ 'content-not-allowed-here', 'wikitext', 'No content allowed', 'main' ] ],
280 ],
281 'Aborted by hook' => [
282 'Hooked in place',
283 'Nonexistent',
284 // @todo Error is wrong
285 [ [ 'immobile-source-namespace', '' ] ],
286 ],
287 'Doubly aborted by hook' => [
288 'Hooked in place',
289 'Hooked In Place',
290 // @todo Both errors are wrong
291 [ [ 'immobile-source-namespace', '' ], [ 'immobile-target-namespace', '' ] ],
292 ],
293 'Non-file to file' =>
294 [ 'Existent', 'File:Nonexistent.jpg', [ [ 'nonfile-cannot-move-to-file' ] ] ],
295 'File to non-file' => [
296 'File:Existent.jpg',
297 'Nonexistent',
298 [ [ 'imagenocrossnamespace' ] ],
299 ],
300 'Existing file to non-existing file' => [
301 'File:Existent.jpg',
302 'File:Nonexistent.jpg',
303 [],
304 ],
305 'Existing file to existing file' => [
306 'File:Existent.jpg',
307 'File:Existent2.jpg',
308 [ [ 'articleexists' ] ],
309 ],
310 'Existing file to existing file with no page' => [
311 'File:Existent.jpg',
312 'File:Existent-file-no-page.jpg',
313 // @todo Is this correct? Moving over an existing file with no page should succeed?
314 [],
315 ],
316 'Existing file to name with slash' => [
317 'File:Existent.jpg',
318 'File:Existent/slashed.jpg',
319 [ [ 'imageinvalidfilename' ] ],
320 ],
321 'Mismatched file extension' => [
322 'File:Existent.jpg',
323 'File:Nonexistent.png',
324 [ [ 'imagetypemismatch' ] ],
325 ],
326 ];
327 if ( $wgMultiContentRevisionSchemaMigrationStage === SCHEMA_COMPAT_OLD ) {
328 // ContentHandlerUseDB = false only works with the old schema
329 $ret['Move to different content model (ContentHandlerUseDB false)'] = [
330 'MediaWiki:Existent.js',
331 'MediaWiki:Nonexistent',
332 [ [ 'bad-target-model', 'JavaScript', 'wikitext' ] ],
333 [ 'ContentHandlerUseDB' => false ],
334 ];
335 }
336 return $ret;
337 }
338
339 /**
340 * @dataProvider provideMove
341 * @covers MovePage::move
342 *
343 * @param string $old Old name
344 * @param string $new New name
345 * @param array $expectedErrors
346 * @param array $extraOptions
347 */
348 public function testMove( $old, $new, array $expectedErrors, array $extraOptions = [] ) {
349 if ( is_string( $old ) ) {
350 $old = Title::newFromText( $old );
351 }
352 if ( is_string( $new ) ) {
353 $new = Title::newFromText( $new );
354 }
355
356 $params = [ 'options' => $extraOptions ];
357 if ( $expectedErrors === [] ) {
358 $this->markTestIncomplete( 'Checking actual moves has not yet been implemented' );
359 }
360
361 $obj = $this->newMovePage( $old, $new, $params );
362 $status = $obj->move( $this->getTestUser()->getUser() );
363 $this->assertSame( $expectedErrors, $status->getErrorsArray() );
364 }
365
366 public static function provideMove() {
367 $ret = [];
368 foreach ( self::provideIsValidMove() as $name => $arr ) {
369 list( $old, $new, $expectedErrors, $extraOptions ) = array_pad( $arr, 4, [] );
370 if ( !$new ) {
371 // Not supported by testMove
372 continue;
373 }
374 $ret[$name] = $arr;
375 }
376 return $ret;
377 }
378
379 /**
380 * Integration test to catch regressions like T74870. Taken and modified
381 * from SemanticMediaWiki
382 *
383 * @covers Title::moveTo
384 * @covers MovePage::move
385 */
386 public function testTitleMoveCompleteIntegrationTest() {
387 $this->hideDeprecated( 'Title::moveTo' );
388
389 $oldTitle = Title::newFromText( 'Help:Some title' );
390 WikiPage::factory( $oldTitle )->doEditContent( new WikitextContent( 'foo' ), 'bar' );
391 $newTitle = Title::newFromText( 'Help:Some other title' );
392 $this->assertNull(
393 WikiPage::factory( $newTitle )->getRevision()
394 );
395
396 $this->assertTrue( $oldTitle->moveTo( $newTitle, false, 'test1', true ) );
397 $this->assertNotNull(
398 WikiPage::factory( $oldTitle )->getRevision()
399 );
400 $this->assertNotNull(
401 WikiPage::factory( $newTitle )->getRevision()
402 );
403 }
404
405 /**
406 * Test for the move operation being aborted via the TitleMove hook
407 * @covers MovePage::move
408 */
409 public function testMoveAbortedByTitleMoveHook() {
410 $error = 'Preventing move operation with TitleMove hook.';
411 $this->setTemporaryHook( 'TitleMove',
412 function ( $old, $new, $user, $reason, $status ) use ( $error ) {
413 $status->fatal( $error );
414 }
415 );
416
417 $oldTitle = Title::newFromText( 'Some old title' );
418 WikiPage::factory( $oldTitle )->doEditContent( new WikitextContent( 'foo' ), 'bar' );
419 $newTitle = Title::newFromText( 'A brand new title' );
420 $mp = $this->newMovePage( $oldTitle, $newTitle );
421 $user = User::newFromName( 'TitleMove tester' );
422 $status = $mp->move( $user, 'Reason', true );
423 $this->assertTrue( $status->hasMessage( $error ) );
424 }
425
426 /**
427 * Test moving subpages from one page to another
428 * @covers MovePage::moveSubpages
429 */
430 public function testMoveSubpages() {
431 $name = ucfirst( __FUNCTION__ );
432
433 $subPages = [ "Talk:$name/1", "Talk:$name/2" ];
434 $ids = [];
435 $pages = [
436 $name,
437 "Talk:$name",
438 "$name 2",
439 "Talk:$name 2",
440 ];
441 foreach ( array_merge( $pages, $subPages ) as $page ) {
442 $ids[$page] = $this->createPage( $page );
443 }
444
445 $oldTitle = Title::newFromText( "Talk:$name" );
446 $newTitle = Title::newFromText( "Talk:$name 2" );
447 $mp = new MovePage( $oldTitle, $newTitle );
448 $status = $mp->moveSubpages( $this->getTestUser()->getUser(), 'Reason', true );
449
450 $this->assertTrue( $status->isGood(),
451 "Moving subpages from Talk:{$name} to Talk:{$name} 2 was not completely successful." );
452 foreach ( $subPages as $page ) {
453 $this->assertMoved( $page, str_replace( $name, "$name 2", $page ), $ids[$page] );
454 }
455 }
456
457 /**
458 * Test moving subpages from one page to another
459 * @covers MovePage::moveSubpagesIfAllowed
460 */
461 public function testMoveSubpagesIfAllowed() {
462 $name = ucfirst( __FUNCTION__ );
463
464 $subPages = [ "Talk:$name/1", "Talk:$name/2" ];
465 $ids = [];
466 $pages = [
467 $name,
468 "Talk:$name",
469 "$name 2",
470 "Talk:$name 2",
471 ];
472 foreach ( array_merge( $pages, $subPages ) as $page ) {
473 $ids[$page] = $this->createPage( $page );
474 }
475
476 $oldTitle = Title::newFromText( "Talk:$name" );
477 $newTitle = Title::newFromText( "Talk:$name 2" );
478 $mp = new MovePage( $oldTitle, $newTitle );
479 $status = $mp->moveSubpagesIfAllowed( $this->getTestUser()->getUser(), 'Reason', true );
480
481 $this->assertTrue( $status->isGood(),
482 "Moving subpages from Talk:{$name} to Talk:{$name} 2 was not completely successful." );
483 foreach ( $subPages as $page ) {
484 $this->assertMoved( $page, str_replace( $name, "$name 2", $page ), $ids[$page] );
485 }
486 }
487
488 /**
489 * Shortcut function to create a page and return its id.
490 *
491 * @param string $name Page to create
492 * @return int ID of created page
493 */
494 protected function createPage( $name ) {
495 return $this->editPage( $name, 'Content' )->value['revision']->getPage();
496 }
497
498 /**
499 * @param string $from Prefixed name of source
500 * @param string $to Prefixed name of destination
501 * @param string $id Page id of the page to move
502 * @param array|string|null $opts Options: 'noredirect' to expect no redirect
503 */
504 protected function assertMoved( $from, $to, $id, $opts = null ) {
505 $opts = (array)$opts;
506
507 Title::clearCaches();
508 $fromTitle = Title::newFromText( $from );
509 $toTitle = Title::newFromText( $to );
510
511 $this->assertTrue( $toTitle->exists(),
512 "Destination {$toTitle->getPrefixedText()} does not exist" );
513
514 if ( in_array( 'noredirect', $opts ) ) {
515 $this->assertFalse( $fromTitle->exists(),
516 "Source {$fromTitle->getPrefixedText()} exists" );
517 } else {
518 $this->assertTrue( $fromTitle->exists(),
519 "Source {$fromTitle->getPrefixedText()} does not exist" );
520 $this->assertTrue( $fromTitle->isRedirect(),
521 "Source {$fromTitle->getPrefixedText()} is not a redirect" );
522
523 $target = Revision::newFromTitle( $fromTitle )->getContent()->getRedirectTarget();
524 $this->assertSame( $toTitle->getPrefixedText(), $target->getPrefixedText() );
525 }
526
527 $this->assertSame( $id, $toTitle->getArticleID() );
528 }
529 }