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