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