SECURITY: rate-limit and prevent blocked users from changing email
[lhc/web/wiklou.git] / includes / MovePage.php
1 <?php
2
3 /**
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 * http://www.gnu.org/copyleft/gpl.html
18 *
19 * @file
20 */
21
22 use MediaWiki\MediaWikiServices;
23 use MediaWiki\Revision\SlotRecord;
24 use Wikimedia\Rdbms\IDatabase;
25
26 /**
27 * Handles the backend logic of moving a page from one title
28 * to another.
29 *
30 * @since 1.24
31 */
32 class MovePage {
33
34 /**
35 * @var Title
36 */
37 protected $oldTitle;
38
39 /**
40 * @var Title
41 */
42 protected $newTitle;
43
44 public function __construct( Title $oldTitle, Title $newTitle ) {
45 $this->oldTitle = $oldTitle;
46 $this->newTitle = $newTitle;
47 }
48
49 /**
50 * Check if the user is allowed to perform the move.
51 *
52 * @param User $user
53 * @param string|null $reason To check against summary spam regex. Set to null to skip the check,
54 * for instance to display errors preemptively before the user has filled in a summary.
55 * @return Status
56 */
57 public function checkPermissions( User $user, $reason ) {
58 $status = new Status();
59
60 $errors = wfMergeErrorArrays(
61 $this->oldTitle->getUserPermissionsErrors( 'move', $user ),
62 $this->oldTitle->getUserPermissionsErrors( 'edit', $user ),
63 $this->newTitle->getUserPermissionsErrors( 'move-target', $user ),
64 $this->newTitle->getUserPermissionsErrors( 'edit', $user )
65 );
66
67 // Convert into a Status object
68 if ( $errors ) {
69 foreach ( $errors as $error ) {
70 $status->fatal( ...$error );
71 }
72 }
73
74 if ( $reason !== null && EditPage::matchSummarySpamRegex( $reason ) !== false ) {
75 // This is kind of lame, won't display nice
76 $status->fatal( 'spamprotectiontext' );
77 }
78
79 $tp = $this->newTitle->getTitleProtection();
80 if ( $tp !== false && !$user->isAllowed( $tp['permission'] ) ) {
81 $status->fatal( 'cantmove-titleprotected' );
82 }
83
84 Hooks::run( 'MovePageCheckPermissions',
85 [ $this->oldTitle, $this->newTitle, $user, $reason, $status ]
86 );
87
88 return $status;
89 }
90
91 /**
92 * Does various sanity checks that the move is
93 * valid. Only things based on the two titles
94 * should be checked here.
95 *
96 * @return Status
97 */
98 public function isValidMove() {
99 global $wgContentHandlerUseDB;
100 $status = new Status();
101
102 if ( $this->oldTitle->equals( $this->newTitle ) ) {
103 $status->fatal( 'selfmove' );
104 }
105 if ( !$this->oldTitle->isMovable() ) {
106 $status->fatal( 'immobile-source-namespace', $this->oldTitle->getNsText() );
107 }
108 if ( $this->newTitle->isExternal() ) {
109 $status->fatal( 'immobile-target-namespace-iw' );
110 }
111 if ( !$this->newTitle->isMovable() ) {
112 $status->fatal( 'immobile-target-namespace', $this->newTitle->getNsText() );
113 }
114
115 $oldid = $this->oldTitle->getArticleID();
116
117 if ( $this->newTitle->getDBkey() === '' ) {
118 $status->fatal( 'articleexists' );
119 }
120 if (
121 ( $this->oldTitle->getDBkey() == '' ) ||
122 ( !$oldid ) ||
123 ( $this->newTitle->getDBkey() == '' )
124 ) {
125 $status->fatal( 'badarticleerror' );
126 }
127
128 # The move is allowed only if (1) the target doesn't exist, or
129 # (2) the target is a redirect to the source, and has no history
130 # (so we can undo bad moves right after they're done).
131 if ( $this->newTitle->getArticleID() && !$this->isValidMoveTarget() ) {
132 $status->fatal( 'articleexists' );
133 }
134
135 // Content model checks
136 if ( !$wgContentHandlerUseDB &&
137 $this->oldTitle->getContentModel() !== $this->newTitle->getContentModel() ) {
138 // can't move a page if that would change the page's content model
139 $status->fatal(
140 'bad-target-model',
141 ContentHandler::getLocalizedName( $this->oldTitle->getContentModel() ),
142 ContentHandler::getLocalizedName( $this->newTitle->getContentModel() )
143 );
144 } elseif (
145 !ContentHandler::getForTitle( $this->oldTitle )->canBeUsedOn( $this->newTitle )
146 ) {
147 $status->fatal(
148 'content-not-allowed-here',
149 ContentHandler::getLocalizedName( $this->oldTitle->getContentModel() ),
150 $this->newTitle->getPrefixedText(),
151 SlotRecord::MAIN
152 );
153 }
154
155 // Image-specific checks
156 if ( $this->oldTitle->inNamespace( NS_FILE ) ) {
157 $status->merge( $this->isValidFileMove() );
158 }
159
160 if ( $this->newTitle->inNamespace( NS_FILE ) && !$this->oldTitle->inNamespace( NS_FILE ) ) {
161 $status->fatal( 'nonfile-cannot-move-to-file' );
162 }
163
164 // Hook for extensions to say a title can't be moved for technical reasons
165 Hooks::run( 'MovePageIsValidMove', [ $this->oldTitle, $this->newTitle, $status ] );
166
167 return $status;
168 }
169
170 /**
171 * Sanity checks for when a file is being moved
172 *
173 * @return Status
174 */
175 protected function isValidFileMove() {
176 $status = new Status();
177 $file = wfLocalFile( $this->oldTitle );
178 $file->load( File::READ_LATEST );
179 if ( $file->exists() ) {
180 if ( $this->newTitle->getText() != wfStripIllegalFilenameChars( $this->newTitle->getText() ) ) {
181 $status->fatal( 'imageinvalidfilename' );
182 }
183 if ( !File::checkExtensionCompatibility( $file, $this->newTitle->getDBkey() ) ) {
184 $status->fatal( 'imagetypemismatch' );
185 }
186 }
187
188 if ( !$this->newTitle->inNamespace( NS_FILE ) ) {
189 $status->fatal( 'imagenocrossnamespace' );
190 }
191
192 return $status;
193 }
194
195 /**
196 * Checks if $this can be moved to a given Title
197 * - Selects for update, so don't call it unless you mean business
198 *
199 * @since 1.25
200 * @return bool
201 */
202 protected function isValidMoveTarget() {
203 # Is it an existing file?
204 if ( $this->newTitle->inNamespace( NS_FILE ) ) {
205 $file = wfLocalFile( $this->newTitle );
206 $file->load( File::READ_LATEST );
207 if ( $file->exists() ) {
208 wfDebug( __METHOD__ . ": file exists\n" );
209 return false;
210 }
211 }
212 # Is it a redirect with no history?
213 if ( !$this->newTitle->isSingleRevRedirect() ) {
214 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
215 return false;
216 }
217 # Get the article text
218 $rev = Revision::newFromTitle( $this->newTitle, false, Revision::READ_LATEST );
219 if ( !is_object( $rev ) ) {
220 return false;
221 }
222 $content = $rev->getContent();
223 # Does the redirect point to the source?
224 # Or is it a broken self-redirect, usually caused by namespace collisions?
225 $redirTitle = $content ? $content->getRedirectTarget() : null;
226
227 if ( $redirTitle ) {
228 if ( $redirTitle->getPrefixedDBkey() !== $this->oldTitle->getPrefixedDBkey() &&
229 $redirTitle->getPrefixedDBkey() !== $this->newTitle->getPrefixedDBkey() ) {
230 wfDebug( __METHOD__ . ": redirect points to other page\n" );
231 return false;
232 } else {
233 return true;
234 }
235 } else {
236 # Fail safe (not a redirect after all. strange.)
237 wfDebug( __METHOD__ . ": failsafe: database says " . $this->newTitle->getPrefixedDBkey() .
238 " is a redirect, but it doesn't contain a valid redirect.\n" );
239 return false;
240 }
241 }
242
243 /**
244 * Move a page without taking user permissions into account. Only checks if the move is itself
245 * invalid, e.g., trying to move a special page or trying to move a page onto one that already
246 * exists.
247 *
248 * @param User $user
249 * @param string|null $reason
250 * @param bool|null $createRedirect
251 * @param string[] $changeTags Change tags to apply to the entry in the move log
252 * @return Status
253 */
254 public function move(
255 User $user, $reason = null, $createRedirect = true, array $changeTags = []
256 ) {
257 $status = $this->isValidMove();
258 if ( !$status->isOK() ) {
259 return $status;
260 }
261
262 return $this->moveUnsafe( $user, $reason, $createRedirect, $changeTags );
263 }
264
265 /**
266 * Same as move(), but with permissions checks.
267 *
268 * @param User $user
269 * @param string|null $reason
270 * @param bool|null $createRedirect Ignored if user doesn't have suppressredirect permission
271 * @param string[] $changeTags Change tags to apply to the entry in the move log
272 * @return Status
273 */
274 public function moveIfAllowed(
275 User $user, $reason = null, $createRedirect = true, array $changeTags = []
276 ) {
277 $status = $this->isValidMove();
278 $status->merge( $this->checkPermissions( $user, $reason ) );
279 if ( $changeTags ) {
280 $status->merge( ChangeTags::canAddTagsAccompanyingChange( $changeTags, $user ) );
281 }
282
283 if ( !$status->isOK() ) {
284 // Auto-block user's IP if the account was "hard" blocked
285 $user->spreadAnyEditBlock();
286 return $status;
287 }
288
289 // Check suppressredirect permission
290 if ( !$user->isAllowed( 'suppressredirect' ) ) {
291 $createRedirect = true;
292 }
293
294 return $this->moveUnsafe( $user, $reason, $createRedirect, $changeTags );
295 }
296
297 /**
298 * Move the source page's subpages to be subpages of the target page, without checking user
299 * permissions. The caller is responsible for moving the source page itself. We will still not
300 * do moves that are inherently not allowed, nor will we move more than $wgMaximumMovedPages.
301 *
302 * @param User $user
303 * @param string|null $reason The reason for the move
304 * @param bool|null $createRedirect Whether to create redirects from the old subpages to
305 * the new ones
306 * @param string[] $changeTags Applied to entries in the move log and redirect page revision
307 * @return Status Good if no errors occurred. Ok if at least one page succeeded. The "value"
308 * of the top-level status is an array containing the per-title status for each page. For any
309 * move that succeeded, the "value" of the per-title status is the new page title.
310 */
311 public function moveSubpages(
312 User $user, $reason = null, $createRedirect = true, array $changeTags = []
313 ) {
314 return $this->moveSubpagesInternal( false, $user, $reason, $createRedirect, $changeTags );
315 }
316
317 /**
318 * Move the source page's subpages to be subpages of the target page, with user permission
319 * checks. The caller is responsible for moving the source page itself.
320 *
321 * @param User $user
322 * @param string|null $reason The reason for the move
323 * @param bool|null $createRedirect Whether to create redirects from the old subpages to
324 * the new ones. Ignored if the user doesn't have the 'suppressredirect' right.
325 * @param string[] $changeTags Applied to entries in the move log and redirect page revision
326 * @return Status Good if no errors occurred. Ok if at least one page succeeded. The "value"
327 * of the top-level status is an array containing the per-title status for each page. For any
328 * move that succeeded, the "value" of the per-title status is the new page title.
329 */
330 public function moveSubpagesIfAllowed(
331 User $user, $reason = null, $createRedirect = true, array $changeTags = []
332 ) {
333 return $this->moveSubpagesInternal( true, $user, $reason, $createRedirect, $changeTags );
334 }
335
336 /**
337 * @param bool $checkPermissions
338 * @param User $user
339 * @param string $reason
340 * @param bool $createRedirect
341 * @param array $changeTags
342 * @return Status
343 */
344 private function moveSubpagesInternal(
345 $checkPermissions, User $user, $reason, $createRedirect, array $changeTags
346 ) {
347 global $wgMaximumMovedPages;
348 $services = MediaWikiServices::getInstance();
349
350 if ( $checkPermissions ) {
351 if ( !$services->getPermissionManager()->userCan(
352 'move-subpages', $user, $this->oldTitle )
353 ) {
354 return Status::newFatal( 'cant-move-subpages' );
355 }
356 }
357
358 $nsInfo = $services->getNamespaceInfo();
359
360 // Do the source and target namespaces support subpages?
361 if ( !$nsInfo->hasSubpages( $this->oldTitle->getNamespace() ) ) {
362 return Status::newFatal( 'namespace-nosubpages',
363 $nsInfo->getCanonicalName( $this->oldTitle->getNamespace() ) );
364 }
365 if ( !$nsInfo->hasSubpages( $this->newTitle->getNamespace() ) ) {
366 return Status::newFatal( 'namespace-nosubpages',
367 $nsInfo->getCanonicalName( $this->newTitle->getNamespace() ) );
368 }
369
370 // Return a status for the overall result. Its value will be an array with per-title
371 // status for each subpage. Merge any errors from the per-title statuses into the
372 // top-level status without resetting the overall result.
373 $topStatus = Status::newGood();
374 $perTitleStatus = [];
375 $subpages = $this->oldTitle->getSubpages( $wgMaximumMovedPages + 1 );
376 $count = 0;
377 foreach ( $subpages as $oldSubpage ) {
378 $count++;
379 if ( $count > $wgMaximumMovedPages ) {
380 $status = Status::newFatal( 'movepage-max-pages', $wgMaximumMovedPages );
381 $perTitleStatus[$oldSubpage->getPrefixedText()] = $status;
382 $topStatus->merge( $status );
383 $topStatus->setOk( true );
384 break;
385 }
386
387 // We don't know whether this function was called before or after moving the root page,
388 // so check both titles
389 if ( $oldSubpage->getArticleID() == $this->oldTitle->getArticleID() ||
390 $oldSubpage->getArticleID() == $this->newTitle->getArticleID()
391 ) {
392 // When moving a page to a subpage of itself, don't move it twice
393 continue;
394 }
395 $newPageName = preg_replace(
396 '#^' . preg_quote( $this->oldTitle->getDBkey(), '#' ) . '#',
397 StringUtils::escapeRegexReplacement( $this->newTitle->getDBkey() ), # T23234
398 $oldSubpage->getDBkey() );
399 if ( $oldSubpage->isTalkPage() ) {
400 $newNs = $this->newTitle->getTalkPage()->getNamespace();
401 } else {
402 $newNs = $this->newTitle->getSubjectPage()->getNamespace();
403 }
404 // T16385: we need makeTitleSafe because the new page names may be longer than 255
405 // characters.
406 $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
407
408 $mp = new MovePage( $oldSubpage, $newSubpage );
409 $method = $checkPermissions ? 'moveIfAllowed' : 'move';
410 $status = $mp->$method( $user, $reason, $createRedirect, $changeTags );
411 if ( $status->isOK() ) {
412 $status->setResult( true, $newSubpage->getPrefixedText() );
413 }
414 $perTitleStatus[$oldSubpage->getPrefixedText()] = $status;
415 $topStatus->merge( $status );
416 $topStatus->setOk( true );
417 }
418
419 $topStatus->value = $perTitleStatus;
420 return $topStatus;
421 }
422
423 /**
424 * Moves *without* any sort of safety or sanity checks. Hooks can still fail the move, however.
425 *
426 * @param User $user
427 * @param string $reason
428 * @param bool $createRedirect
429 * @param string[] $changeTags Change tags to apply to the entry in the move log
430 * @return Status
431 */
432 private function moveUnsafe( User $user, $reason, $createRedirect, array $changeTags ) {
433 global $wgCategoryCollation;
434
435 $status = Status::newGood();
436 Hooks::run( 'TitleMove', [ $this->oldTitle, $this->newTitle, $user, $reason, &$status ] );
437 if ( !$status->isOK() ) {
438 // Move was aborted by the hook
439 return $status;
440 }
441
442 $dbw = wfGetDB( DB_MASTER );
443 $dbw->startAtomic( __METHOD__, IDatabase::ATOMIC_CANCELABLE );
444
445 Hooks::run( 'TitleMoveStarting', [ $this->oldTitle, $this->newTitle, $user ] );
446
447 $pageid = $this->oldTitle->getArticleID( Title::GAID_FOR_UPDATE );
448 $protected = $this->oldTitle->isProtected();
449
450 // Do the actual move; if this fails, it will throw an MWException(!)
451 $nullRevision = $this->moveToInternal( $user, $this->newTitle, $reason, $createRedirect,
452 $changeTags );
453
454 // Refresh the sortkey for this row. Be careful to avoid resetting
455 // cl_timestamp, which may disturb time-based lists on some sites.
456 // @todo This block should be killed, it's duplicating code
457 // from LinksUpdate::getCategoryInsertions() and friends.
458 $prefixes = $dbw->select(
459 'categorylinks',
460 [ 'cl_sortkey_prefix', 'cl_to' ],
461 [ 'cl_from' => $pageid ],
462 __METHOD__
463 );
464 $services = MediaWikiServices::getInstance();
465 $type = $services->getNamespaceInfo()->
466 getCategoryLinkType( $this->newTitle->getNamespace() );
467 foreach ( $prefixes as $prefixRow ) {
468 $prefix = $prefixRow->cl_sortkey_prefix;
469 $catTo = $prefixRow->cl_to;
470 $dbw->update( 'categorylinks',
471 [
472 'cl_sortkey' => Collation::singleton()->getSortKey(
473 $this->newTitle->getCategorySortkey( $prefix ) ),
474 'cl_collation' => $wgCategoryCollation,
475 'cl_type' => $type,
476 'cl_timestamp=cl_timestamp' ],
477 [
478 'cl_from' => $pageid,
479 'cl_to' => $catTo ],
480 __METHOD__
481 );
482 }
483
484 $redirid = $this->oldTitle->getArticleID();
485
486 if ( $protected ) {
487 # Protect the redirect title as the title used to be...
488 $res = $dbw->select(
489 'page_restrictions',
490 [ 'pr_type', 'pr_level', 'pr_cascade', 'pr_user', 'pr_expiry' ],
491 [ 'pr_page' => $pageid ],
492 __METHOD__,
493 'FOR UPDATE'
494 );
495 $rowsInsert = [];
496 foreach ( $res as $row ) {
497 $rowsInsert[] = [
498 'pr_page' => $redirid,
499 'pr_type' => $row->pr_type,
500 'pr_level' => $row->pr_level,
501 'pr_cascade' => $row->pr_cascade,
502 'pr_user' => $row->pr_user,
503 'pr_expiry' => $row->pr_expiry
504 ];
505 }
506 $dbw->insert( 'page_restrictions', $rowsInsert, __METHOD__, [ 'IGNORE' ] );
507
508 // Build comment for log
509 $comment = wfMessage(
510 'prot_1movedto2',
511 $this->oldTitle->getPrefixedText(),
512 $this->newTitle->getPrefixedText()
513 )->inContentLanguage()->text();
514 if ( $reason ) {
515 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
516 }
517
518 // reread inserted pr_ids for log relation
519 $insertedPrIds = $dbw->select(
520 'page_restrictions',
521 'pr_id',
522 [ 'pr_page' => $redirid ],
523 __METHOD__
524 );
525 $logRelationsValues = [];
526 foreach ( $insertedPrIds as $prid ) {
527 $logRelationsValues[] = $prid->pr_id;
528 }
529
530 // Update the protection log
531 $logEntry = new ManualLogEntry( 'protect', 'move_prot' );
532 $logEntry->setTarget( $this->newTitle );
533 $logEntry->setComment( $comment );
534 $logEntry->setPerformer( $user );
535 $logEntry->setParameters( [
536 '4::oldtitle' => $this->oldTitle->getPrefixedText(),
537 ] );
538 $logEntry->setRelations( [ 'pr_id' => $logRelationsValues ] );
539 $logEntry->setTags( $changeTags );
540 $logId = $logEntry->insert();
541 $logEntry->publish( $logId );
542 }
543
544 // Update *_from_namespace fields as needed
545 if ( $this->oldTitle->getNamespace() != $this->newTitle->getNamespace() ) {
546 $dbw->update( 'pagelinks',
547 [ 'pl_from_namespace' => $this->newTitle->getNamespace() ],
548 [ 'pl_from' => $pageid ],
549 __METHOD__
550 );
551 $dbw->update( 'templatelinks',
552 [ 'tl_from_namespace' => $this->newTitle->getNamespace() ],
553 [ 'tl_from' => $pageid ],
554 __METHOD__
555 );
556 $dbw->update( 'imagelinks',
557 [ 'il_from_namespace' => $this->newTitle->getNamespace() ],
558 [ 'il_from' => $pageid ],
559 __METHOD__
560 );
561 }
562
563 # Update watchlists
564 $oldtitle = $this->oldTitle->getDBkey();
565 $newtitle = $this->newTitle->getDBkey();
566 $oldsnamespace = $services->getNamespaceInfo()->
567 getSubject( $this->oldTitle->getNamespace() );
568 $newsnamespace = $services->getNamespaceInfo()->
569 getSubject( $this->newTitle->getNamespace() );
570 if ( $oldsnamespace != $newsnamespace || $oldtitle != $newtitle ) {
571 $services->getWatchedItemStore()->duplicateAllAssociatedEntries(
572 $this->oldTitle, $this->newTitle );
573 }
574
575 // If it is a file then move it last.
576 // This is done after all database changes so that file system errors cancel the transaction.
577 if ( $this->oldTitle->getNamespace() == NS_FILE ) {
578 $status = $this->moveFile( $this->oldTitle, $this->newTitle );
579 if ( !$status->isOK() ) {
580 $dbw->cancelAtomic( __METHOD__ );
581 return $status;
582 }
583 }
584
585 Hooks::run(
586 'TitleMoveCompleting',
587 [ $this->oldTitle, $this->newTitle,
588 $user, $pageid, $redirid, $reason, $nullRevision ]
589 );
590
591 $dbw->endAtomic( __METHOD__ );
592
593 $params = [
594 &$this->oldTitle,
595 &$this->newTitle,
596 &$user,
597 $pageid,
598 $redirid,
599 $reason,
600 $nullRevision
601 ];
602 // Keep each single hook handler atomic
603 DeferredUpdates::addUpdate(
604 new AtomicSectionUpdate(
605 $dbw,
606 __METHOD__,
607 // Hold onto $user to avoid HHVM bug where it no longer
608 // becomes a reference (T118683)
609 function () use ( $params, &$user ) {
610 Hooks::run( 'TitleMoveComplete', $params );
611 }
612 )
613 );
614
615 return Status::newGood();
616 }
617
618 /**
619 * Move a file associated with a page to a new location.
620 * Can also be used to revert after a DB failure.
621 *
622 * @private
623 * @param Title $oldTitle Old location to move the file from.
624 * @param Title $newTitle New location to move the file to.
625 * @return Status
626 */
627 private function moveFile( $oldTitle, $newTitle ) {
628 $status = Status::newFatal(
629 'cannotdelete',
630 $oldTitle->getPrefixedText()
631 );
632
633 $file = wfLocalFile( $oldTitle );
634 $file->load( File::READ_LATEST );
635 if ( $file->exists() ) {
636 $status = $file->move( $newTitle );
637 }
638
639 // Clear RepoGroup process cache
640 RepoGroup::singleton()->clearCache( $oldTitle );
641 RepoGroup::singleton()->clearCache( $newTitle ); # clear false negative cache
642 return $status;
643 }
644
645 /**
646 * Move page to a title which is either a redirect to the
647 * source page or nonexistent
648 *
649 * @todo This was basically directly moved from Title, it should be split into
650 * smaller functions
651 * @param User $user the User doing the move
652 * @param Title $nt The page to move to, which should be a redirect or non-existent
653 * @param string $reason The reason for the move
654 * @param bool $createRedirect Whether to leave a redirect at the old title. Does not check
655 * if the user has the suppressredirect right
656 * @param string[] $changeTags Change tags to apply to the entry in the move log
657 * @return Revision the revision created by the move
658 * @throws MWException
659 */
660 private function moveToInternal( User $user, &$nt, $reason = '', $createRedirect = true,
661 array $changeTags = []
662 ) {
663 if ( $nt->exists() ) {
664 $moveOverRedirect = true;
665 $logType = 'move_redir';
666 } else {
667 $moveOverRedirect = false;
668 $logType = 'move';
669 }
670
671 if ( $moveOverRedirect ) {
672 $overwriteMessage = wfMessage(
673 'delete_and_move_reason',
674 $this->oldTitle->getPrefixedText()
675 )->inContentLanguage()->text();
676 $newpage = WikiPage::factory( $nt );
677 $errs = [];
678 $status = $newpage->doDeleteArticleReal(
679 $overwriteMessage,
680 /* $suppress */ false,
681 $nt->getArticleID(),
682 /* $commit */ false,
683 $errs,
684 $user,
685 $changeTags,
686 'delete_redir'
687 );
688
689 if ( !$status->isGood() ) {
690 throw new MWException( 'Failed to delete page-move revision: '
691 . $status->getWikiText( false, false, 'en' ) );
692 }
693
694 $nt->resetArticleID( false );
695 }
696
697 if ( $createRedirect ) {
698 if ( $this->oldTitle->getNamespace() == NS_CATEGORY
699 && !wfMessage( 'category-move-redirect-override' )->inContentLanguage()->isDisabled()
700 ) {
701 $redirectContent = new WikitextContent(
702 wfMessage( 'category-move-redirect-override' )
703 ->params( $nt->getPrefixedText() )->inContentLanguage()->plain() );
704 } else {
705 $contentHandler = ContentHandler::getForTitle( $this->oldTitle );
706 $redirectContent = $contentHandler->makeRedirectContent( $nt,
707 wfMessage( 'move-redirect-text' )->inContentLanguage()->plain() );
708 }
709
710 // NOTE: If this page's content model does not support redirects, $redirectContent will be null.
711 } else {
712 $redirectContent = null;
713 }
714
715 // Figure out whether the content model is no longer the default
716 $oldDefault = ContentHandler::getDefaultModelFor( $this->oldTitle );
717 $contentModel = $this->oldTitle->getContentModel();
718 $newDefault = ContentHandler::getDefaultModelFor( $nt );
719 $defaultContentModelChanging = ( $oldDefault !== $newDefault
720 && $oldDefault === $contentModel );
721
722 // T59084: log_page should be the ID of the *moved* page
723 $oldid = $this->oldTitle->getArticleID();
724 $logTitle = clone $this->oldTitle;
725
726 $logEntry = new ManualLogEntry( 'move', $logType );
727 $logEntry->setPerformer( $user );
728 $logEntry->setTarget( $logTitle );
729 $logEntry->setComment( $reason );
730 $logEntry->setParameters( [
731 '4::target' => $nt->getPrefixedText(),
732 '5::noredir' => $redirectContent ? '0' : '1',
733 ] );
734
735 $formatter = LogFormatter::newFromEntry( $logEntry );
736 $formatter->setContext( RequestContext::newExtraneousContext( $this->oldTitle ) );
737 $comment = $formatter->getPlainActionText();
738 if ( $reason ) {
739 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
740 }
741
742 $dbw = wfGetDB( DB_MASTER );
743
744 $oldpage = WikiPage::factory( $this->oldTitle );
745 $oldcountable = $oldpage->isCountable();
746
747 $newpage = WikiPage::factory( $nt );
748
749 # Change the name of the target page:
750 $dbw->update( 'page',
751 /* SET */ [
752 'page_namespace' => $nt->getNamespace(),
753 'page_title' => $nt->getDBkey(),
754 ],
755 /* WHERE */ [ 'page_id' => $oldid ],
756 __METHOD__
757 );
758
759 # Save a null revision in the page's history notifying of the move
760 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true, $user );
761 if ( !is_object( $nullRevision ) ) {
762 throw new MWException( 'Failed to create null revision while moving page ID '
763 . $oldid . ' to ' . $nt->getPrefixedDBkey() );
764 }
765
766 $nullRevId = $nullRevision->insertOn( $dbw );
767 $logEntry->setAssociatedRevId( $nullRevId );
768
769 /**
770 * T163966
771 * Increment user_editcount during page moves
772 * Moved from SpecialMovepage.php per T195550
773 */
774 $user->incEditCount();
775
776 if ( !$redirectContent ) {
777 // Clean up the old title *before* reset article id - T47348
778 WikiPage::onArticleDelete( $this->oldTitle );
779 }
780
781 $this->oldTitle->resetArticleID( 0 ); // 0 == non existing
782 $nt->resetArticleID( $oldid );
783 $newpage->loadPageData( WikiPage::READ_LOCKING ); // T48397
784
785 $newpage->updateRevisionOn( $dbw, $nullRevision );
786
787 Hooks::run( 'NewRevisionFromEditComplete',
788 [ $newpage, $nullRevision, $nullRevision->getParentId(), $user ] );
789
790 $newpage->doEditUpdates( $nullRevision, $user,
791 [ 'changed' => false, 'moved' => true, 'oldcountable' => $oldcountable ] );
792
793 // If the default content model changes, we need to populate rev_content_model
794 if ( $defaultContentModelChanging ) {
795 $dbw->update(
796 'revision',
797 [ 'rev_content_model' => $contentModel ],
798 [ 'rev_page' => $nt->getArticleID(), 'rev_content_model IS NULL' ],
799 __METHOD__
800 );
801 }
802
803 WikiPage::onArticleCreate( $nt );
804
805 # Recreate the redirect, this time in the other direction.
806 if ( $redirectContent ) {
807 $redirectArticle = WikiPage::factory( $this->oldTitle );
808 $redirectArticle->loadFromRow( false, WikiPage::READ_LOCKING ); // T48397
809 $newid = $redirectArticle->insertOn( $dbw );
810 if ( $newid ) { // sanity
811 $this->oldTitle->resetArticleID( $newid );
812 $redirectRevision = new Revision( [
813 'title' => $this->oldTitle, // for determining the default content model
814 'page' => $newid,
815 'user_text' => $user->getName(),
816 'user' => $user->getId(),
817 'comment' => $comment,
818 'content' => $redirectContent ] );
819 $redirectRevId = $redirectRevision->insertOn( $dbw );
820 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
821
822 Hooks::run( 'NewRevisionFromEditComplete',
823 [ $redirectArticle, $redirectRevision, false, $user ] );
824
825 $redirectArticle->doEditUpdates( $redirectRevision, $user, [ 'created' => true ] );
826
827 // make a copy because of log entry below
828 $redirectTags = $changeTags;
829 if ( in_array( 'mw-new-redirect', ChangeTags::getSoftwareTags() ) ) {
830 $redirectTags[] = 'mw-new-redirect';
831 }
832 ChangeTags::addTags( $redirectTags, null, $redirectRevId, null );
833 }
834 }
835
836 # Log the move
837 $logid = $logEntry->insert();
838
839 $logEntry->setTags( $changeTags );
840 $logEntry->publish( $logid );
841
842 return $nullRevision;
843 }
844 }