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.
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.
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
22 use MediaWiki\MediaWikiServices
;
23 use MediaWiki\Revision\SlotRecord
;
26 * Handles the backend logic of moving a page from one title
43 public function __construct( Title
$oldTitle, Title
$newTitle ) {
44 $this->oldTitle
= $oldTitle;
45 $this->newTitle
= $newTitle;
48 public function checkPermissions( User
$user, $reason ) {
49 $status = new Status();
51 $errors = wfMergeErrorArrays(
52 $this->oldTitle
->getUserPermissionsErrors( 'move', $user ),
53 $this->oldTitle
->getUserPermissionsErrors( 'edit', $user ),
54 $this->newTitle
->getUserPermissionsErrors( 'move-target', $user ),
55 $this->newTitle
->getUserPermissionsErrors( 'edit', $user )
58 // Convert into a Status object
60 foreach ( $errors as $error ) {
61 $status->fatal( ...$error );
65 if ( EditPage
::matchSummarySpamRegex( $reason ) !== false ) {
66 // This is kind of lame, won't display nice
67 $status->fatal( 'spamprotectiontext' );
70 $tp = $this->newTitle
->getTitleProtection();
71 if ( $tp !== false && !$user->isAllowed( $tp['permission'] ) ) {
72 $status->fatal( 'cantmove-titleprotected' );
75 Hooks
::run( 'MovePageCheckPermissions',
76 [ $this->oldTitle
, $this->newTitle
, $user, $reason, $status ]
83 * Does various sanity checks that the move is
84 * valid. Only things based on the two titles
85 * should be checked here.
89 public function isValidMove() {
90 global $wgContentHandlerUseDB;
91 $status = new Status();
93 if ( $this->oldTitle
->equals( $this->newTitle
) ) {
94 $status->fatal( 'selfmove' );
96 if ( !$this->oldTitle
->isMovable() ) {
97 $status->fatal( 'immobile-source-namespace', $this->oldTitle
->getNsText() );
99 if ( $this->newTitle
->isExternal() ) {
100 $status->fatal( 'immobile-target-namespace-iw' );
102 if ( !$this->newTitle
->isMovable() ) {
103 $status->fatal( 'immobile-target-namespace', $this->newTitle
->getNsText() );
106 $oldid = $this->oldTitle
->getArticleID();
108 if ( strlen( $this->newTitle
->getDBkey() ) < 1 ) {
109 $status->fatal( 'articleexists' );
112 ( $this->oldTitle
->getDBkey() == '' ) ||
114 ( $this->newTitle
->getDBkey() == '' )
116 $status->fatal( 'badarticleerror' );
119 # The move is allowed only if (1) the target doesn't exist, or
120 # (2) the target is a redirect to the source, and has no history
121 # (so we can undo bad moves right after they're done).
122 if ( $this->newTitle
->getArticleID() && !$this->isValidMoveTarget() ) {
123 $status->fatal( 'articleexists' );
126 // Content model checks
127 if ( !$wgContentHandlerUseDB &&
128 $this->oldTitle
->getContentModel() !== $this->newTitle
->getContentModel() ) {
129 // can't move a page if that would change the page's content model
132 ContentHandler
::getLocalizedName( $this->oldTitle
->getContentModel() ),
133 ContentHandler
::getLocalizedName( $this->newTitle
->getContentModel() )
136 !ContentHandler
::getForTitle( $this->oldTitle
)->canBeUsedOn( $this->newTitle
)
139 'content-not-allowed-here',
140 ContentHandler
::getLocalizedName( $this->oldTitle
->getContentModel() ),
141 $this->newTitle
->getPrefixedText(),
146 // Image-specific checks
147 if ( $this->oldTitle
->inNamespace( NS_FILE
) ) {
148 $status->merge( $this->isValidFileMove() );
151 if ( $this->newTitle
->inNamespace( NS_FILE
) && !$this->oldTitle
->inNamespace( NS_FILE
) ) {
152 $status->fatal( 'nonfile-cannot-move-to-file' );
155 // Hook for extensions to say a title can't be moved for technical reasons
156 Hooks
::run( 'MovePageIsValidMove', [ $this->oldTitle
, $this->newTitle
, $status ] );
162 * Sanity checks for when a file is being moved
166 protected function isValidFileMove() {
167 $status = new Status();
168 $file = wfLocalFile( $this->oldTitle
);
169 $file->load( File
::READ_LATEST
);
170 if ( $file->exists() ) {
171 if ( $this->newTitle
->getText() != wfStripIllegalFilenameChars( $this->newTitle
->getText() ) ) {
172 $status->fatal( 'imageinvalidfilename' );
174 if ( !File
::checkExtensionCompatibility( $file, $this->newTitle
->getDBkey() ) ) {
175 $status->fatal( 'imagetypemismatch' );
179 if ( !$this->newTitle
->inNamespace( NS_FILE
) ) {
180 $status->fatal( 'imagenocrossnamespace' );
187 * Checks if $this can be moved to a given Title
188 * - Selects for update, so don't call it unless you mean business
193 protected function isValidMoveTarget() {
194 # Is it an existing file?
195 if ( $this->newTitle
->inNamespace( NS_FILE
) ) {
196 $file = wfLocalFile( $this->newTitle
);
197 $file->load( File
::READ_LATEST
);
198 if ( $file->exists() ) {
199 wfDebug( __METHOD__
. ": file exists\n" );
203 # Is it a redirect with no history?
204 if ( !$this->newTitle
->isSingleRevRedirect() ) {
205 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
208 # Get the article text
209 $rev = Revision
::newFromTitle( $this->newTitle
, false, Revision
::READ_LATEST
);
210 if ( !is_object( $rev ) ) {
213 $content = $rev->getContent();
214 # Does the redirect point to the source?
215 # Or is it a broken self-redirect, usually caused by namespace collisions?
216 $redirTitle = $content ?
$content->getRedirectTarget() : null;
219 if ( $redirTitle->getPrefixedDBkey() !== $this->oldTitle
->getPrefixedDBkey() &&
220 $redirTitle->getPrefixedDBkey() !== $this->newTitle
->getPrefixedDBkey() ) {
221 wfDebug( __METHOD__
. ": redirect points to other page\n" );
227 # Fail safe (not a redirect after all. strange.)
228 wfDebug( __METHOD__
. ": failsafe: database says " . $this->newTitle
->getPrefixedDBkey() .
229 " is a redirect, but it doesn't contain a valid redirect.\n" );
236 * @param string $reason
237 * @param bool $createRedirect
238 * @param string[] $changeTags Change tags to apply to the entry in the move log. Caller
239 * should perform permission checks with ChangeTags::canAddTagsAccompanyingChange
242 public function move( User
$user, $reason, $createRedirect, array $changeTags = [] ) {
243 global $wgCategoryCollation;
245 $status = Status
::newGood();
246 Hooks
::run( 'TitleMove', [ $this->oldTitle
, $this->newTitle
, $user, $reason, &$status ] );
247 if ( !$status->isOK() ) {
248 // Move was aborted by the hook
252 $dbw = wfGetDB( DB_MASTER
);
253 $dbw->startAtomic( __METHOD__
);
255 Hooks
::run( 'TitleMoveStarting', [ $this->oldTitle
, $this->newTitle
, $user ] );
257 $pageid = $this->oldTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
258 $protected = $this->oldTitle
->isProtected();
260 // Do the actual move; if this fails, it will throw an MWException(!)
261 $nullRevision = $this->moveToInternal( $user, $this->newTitle
, $reason, $createRedirect,
264 // Refresh the sortkey for this row. Be careful to avoid resetting
265 // cl_timestamp, which may disturb time-based lists on some sites.
266 // @todo This block should be killed, it's duplicating code
267 // from LinksUpdate::getCategoryInsertions() and friends.
268 $prefixes = $dbw->select(
270 [ 'cl_sortkey_prefix', 'cl_to' ],
271 [ 'cl_from' => $pageid ],
274 $type = MWNamespace
::getCategoryLinkType( $this->newTitle
->getNamespace() );
275 foreach ( $prefixes as $prefixRow ) {
276 $prefix = $prefixRow->cl_sortkey_prefix
;
277 $catTo = $prefixRow->cl_to
;
278 $dbw->update( 'categorylinks',
280 'cl_sortkey' => Collation
::singleton()->getSortKey(
281 $this->newTitle
->getCategorySortkey( $prefix ) ),
282 'cl_collation' => $wgCategoryCollation,
284 'cl_timestamp=cl_timestamp' ],
286 'cl_from' => $pageid,
292 $redirid = $this->oldTitle
->getArticleID();
295 # Protect the redirect title as the title used to be...
298 [ 'pr_type', 'pr_level', 'pr_cascade', 'pr_user', 'pr_expiry' ],
299 [ 'pr_page' => $pageid ],
304 foreach ( $res as $row ) {
306 'pr_page' => $redirid,
307 'pr_type' => $row->pr_type
,
308 'pr_level' => $row->pr_level
,
309 'pr_cascade' => $row->pr_cascade
,
310 'pr_user' => $row->pr_user
,
311 'pr_expiry' => $row->pr_expiry
314 $dbw->insert( 'page_restrictions', $rowsInsert, __METHOD__
, [ 'IGNORE' ] );
316 // Build comment for log
317 $comment = wfMessage(
319 $this->oldTitle
->getPrefixedText(),
320 $this->newTitle
->getPrefixedText()
321 )->inContentLanguage()->text();
323 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
326 // reread inserted pr_ids for log relation
327 $insertedPrIds = $dbw->select(
330 [ 'pr_page' => $redirid ],
333 $logRelationsValues = [];
334 foreach ( $insertedPrIds as $prid ) {
335 $logRelationsValues[] = $prid->pr_id
;
338 // Update the protection log
339 $logEntry = new ManualLogEntry( 'protect', 'move_prot' );
340 $logEntry->setTarget( $this->newTitle
);
341 $logEntry->setComment( $comment );
342 $logEntry->setPerformer( $user );
343 $logEntry->setParameters( [
344 '4::oldtitle' => $this->oldTitle
->getPrefixedText(),
346 $logEntry->setRelations( [ 'pr_id' => $logRelationsValues ] );
347 $logEntry->setTags( $changeTags );
348 $logId = $logEntry->insert();
349 $logEntry->publish( $logId );
352 // Update *_from_namespace fields as needed
353 if ( $this->oldTitle
->getNamespace() != $this->newTitle
->getNamespace() ) {
354 $dbw->update( 'pagelinks',
355 [ 'pl_from_namespace' => $this->newTitle
->getNamespace() ],
356 [ 'pl_from' => $pageid ],
359 $dbw->update( 'templatelinks',
360 [ 'tl_from_namespace' => $this->newTitle
->getNamespace() ],
361 [ 'tl_from' => $pageid ],
364 $dbw->update( 'imagelinks',
365 [ 'il_from_namespace' => $this->newTitle
->getNamespace() ],
366 [ 'il_from' => $pageid ],
372 $oldtitle = $this->oldTitle
->getDBkey();
373 $newtitle = $this->newTitle
->getDBkey();
374 $oldsnamespace = MWNamespace
::getSubject( $this->oldTitle
->getNamespace() );
375 $newsnamespace = MWNamespace
::getSubject( $this->newTitle
->getNamespace() );
376 if ( $oldsnamespace != $newsnamespace ||
$oldtitle != $newtitle ) {
377 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
378 $store->duplicateAllAssociatedEntries( $this->oldTitle
, $this->newTitle
);
381 // If it is a file then move it last.
382 // This is done after all database changes so that file system errors cancel the transaction.
383 if ( $this->oldTitle
->getNamespace() == NS_FILE
) {
384 $status = $this->moveFile( $this->oldTitle
, $this->newTitle
);
385 if ( !$status->isOK() ) {
386 $dbw->cancelAtomic( __METHOD__
);
392 'TitleMoveCompleting',
393 [ $this->oldTitle
, $this->newTitle
,
394 $user, $pageid, $redirid, $reason, $nullRevision ]
397 $dbw->endAtomic( __METHOD__
);
408 // Keep each single hook handler atomic
409 DeferredUpdates
::addUpdate(
410 new AtomicSectionUpdate(
413 // Hold onto $user to avoid HHVM bug where it no longer
414 // becomes a reference (T118683)
415 function () use ( $params, &$user ) {
416 Hooks
::run( 'TitleMoveComplete', $params );
421 return Status
::newGood();
425 * Move a file associated with a page to a new location.
426 * Can also be used to revert after a DB failure.
429 * @param Title Old location to move the file from.
430 * @param Title New location to move the file to.
433 private function moveFile( $oldTitle, $newTitle ) {
434 $status = Status
::newFatal(
436 $oldTitle->getPrefixedText()
439 $file = wfLocalFile( $oldTitle );
440 $file->load( File
::READ_LATEST
);
441 if ( $file->exists() ) {
442 $status = $file->move( $newTitle );
445 // Clear RepoGroup process cache
446 RepoGroup
::singleton()->clearCache( $oldTitle );
447 RepoGroup
::singleton()->clearCache( $newTitle ); # clear false negative cache
452 * Move page to a title which is either a redirect to the
453 * source page or nonexistent
455 * @todo This was basically directly moved from Title, it should be split into
457 * @param User $user the User doing the move
458 * @param Title $nt The page to move to, which should be a redirect or non-existent
459 * @param string $reason The reason for the move
460 * @param bool $createRedirect Whether to leave a redirect at the old title. Does not check
461 * if the user has the suppressredirect right
462 * @param string[] $changeTags Change tags to apply to the entry in the move log
463 * @return Revision the revision created by the move
464 * @throws MWException
466 private function moveToInternal( User
$user, &$nt, $reason = '', $createRedirect = true,
467 array $changeTags = []
469 if ( $nt->exists() ) {
470 $moveOverRedirect = true;
471 $logType = 'move_redir';
473 $moveOverRedirect = false;
477 if ( $moveOverRedirect ) {
478 $overwriteMessage = wfMessage(
479 'delete_and_move_reason',
480 $this->oldTitle
->getPrefixedText()
481 )->inContentLanguage()->text();
482 $newpage = WikiPage
::factory( $nt );
484 $status = $newpage->doDeleteArticleReal(
486 /* $suppress */ false,
495 if ( !$status->isGood() ) {
496 throw new MWException( 'Failed to delete page-move revision: ' . $status );
499 $nt->resetArticleID( false );
502 if ( $createRedirect ) {
503 if ( $this->oldTitle
->getNamespace() == NS_CATEGORY
504 && !wfMessage( 'category-move-redirect-override' )->inContentLanguage()->isDisabled()
506 $redirectContent = new WikitextContent(
507 wfMessage( 'category-move-redirect-override' )
508 ->params( $nt->getPrefixedText() )->inContentLanguage()->plain() );
510 $contentHandler = ContentHandler
::getForTitle( $this->oldTitle
);
511 $redirectContent = $contentHandler->makeRedirectContent( $nt,
512 wfMessage( 'move-redirect-text' )->inContentLanguage()->plain() );
515 // NOTE: If this page's content model does not support redirects, $redirectContent will be null.
517 $redirectContent = null;
520 // Figure out whether the content model is no longer the default
521 $oldDefault = ContentHandler
::getDefaultModelFor( $this->oldTitle
);
522 $contentModel = $this->oldTitle
->getContentModel();
523 $newDefault = ContentHandler
::getDefaultModelFor( $nt );
524 $defaultContentModelChanging = ( $oldDefault !== $newDefault
525 && $oldDefault === $contentModel );
527 // T59084: log_page should be the ID of the *moved* page
528 $oldid = $this->oldTitle
->getArticleID();
529 $logTitle = clone $this->oldTitle
;
531 $logEntry = new ManualLogEntry( 'move', $logType );
532 $logEntry->setPerformer( $user );
533 $logEntry->setTarget( $logTitle );
534 $logEntry->setComment( $reason );
535 $logEntry->setParameters( [
536 '4::target' => $nt->getPrefixedText(),
537 '5::noredir' => $redirectContent ?
'0' : '1',
540 $formatter = LogFormatter
::newFromEntry( $logEntry );
541 $formatter->setContext( RequestContext
::newExtraneousContext( $this->oldTitle
) );
542 $comment = $formatter->getPlainActionText();
544 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
547 $dbw = wfGetDB( DB_MASTER
);
549 $oldpage = WikiPage
::factory( $this->oldTitle
);
550 $oldcountable = $oldpage->isCountable();
552 $newpage = WikiPage
::factory( $nt );
554 # Change the name of the target page:
555 $dbw->update( 'page',
557 'page_namespace' => $nt->getNamespace(),
558 'page_title' => $nt->getDBkey(),
560 /* WHERE */ [ 'page_id' => $oldid ],
564 # Save a null revision in the page's history notifying of the move
565 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true, $user );
566 if ( !is_object( $nullRevision ) ) {
567 throw new MWException( 'Failed to create null revision while moving page ID '
568 . $oldid . ' to ' . $nt->getPrefixedDBkey() );
571 $nullRevId = $nullRevision->insertOn( $dbw );
572 $logEntry->setAssociatedRevId( $nullRevId );
576 * Increment user_editcount during page moves
577 * Moved from SpecialMovepage.php per T195550
579 $user->incEditCount();
581 if ( !$redirectContent ) {
582 // Clean up the old title *before* reset article id - T47348
583 WikiPage
::onArticleDelete( $this->oldTitle
);
586 $this->oldTitle
->resetArticleID( 0 ); // 0 == non existing
587 $nt->resetArticleID( $oldid );
588 $newpage->loadPageData( WikiPage
::READ_LOCKING
); // T48397
590 $newpage->updateRevisionOn( $dbw, $nullRevision );
592 Hooks
::run( 'NewRevisionFromEditComplete',
593 [ $newpage, $nullRevision, $nullRevision->getParentId(), $user ] );
595 $newpage->doEditUpdates( $nullRevision, $user,
596 [ 'changed' => false, 'moved' => true, 'oldcountable' => $oldcountable ] );
598 // If the default content model changes, we need to populate rev_content_model
599 if ( $defaultContentModelChanging ) {
602 [ 'rev_content_model' => $contentModel ],
603 [ 'rev_page' => $nt->getArticleID(), 'rev_content_model IS NULL' ],
608 WikiPage
::onArticleCreate( $nt );
610 # Recreate the redirect, this time in the other direction.
611 if ( $redirectContent ) {
612 $redirectArticle = WikiPage
::factory( $this->oldTitle
);
613 $redirectArticle->loadFromRow( false, WikiPage
::READ_LOCKING
); // T48397
614 $newid = $redirectArticle->insertOn( $dbw );
615 if ( $newid ) { // sanity
616 $this->oldTitle
->resetArticleID( $newid );
617 $redirectRevision = new Revision( [
618 'title' => $this->oldTitle
, // for determining the default content model
620 'user_text' => $user->getName(),
621 'user' => $user->getId(),
622 'comment' => $comment,
623 'content' => $redirectContent ] );
624 $redirectRevId = $redirectRevision->insertOn( $dbw );
625 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
627 Hooks
::run( 'NewRevisionFromEditComplete',
628 [ $redirectArticle, $redirectRevision, false, $user ] );
630 $redirectArticle->doEditUpdates( $redirectRevision, $user, [ 'created' => true ] );
632 // make a copy because of log entry below
633 $redirectTags = $changeTags;
634 if ( in_array( 'mw-new-redirect', ChangeTags
::getSoftwareTags() ) ) {
635 $redirectTags[] = 'mw-new-redirect';
637 ChangeTags
::addTags( $redirectTags, null, $redirectRevId, null );
642 $logid = $logEntry->insert();
644 $logEntry->setTags( $changeTags );
645 $logEntry->publish( $logid );
647 return $nullRevision;