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