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 // If it is a file, move it first.
253 // It is done before all other moving stuff is done because it's hard to revert.
254 $dbw = wfGetDB( DB_MASTER
);
255 if ( $this->oldTitle
->getNamespace() == NS_FILE
) {
256 $file = wfLocalFile( $this->oldTitle
);
257 $file->load( File
::READ_LATEST
);
258 if ( $file->exists() ) {
259 $status = $file->move( $this->newTitle
);
260 if ( !$status->isOK() ) {
264 // Clear RepoGroup process cache
265 RepoGroup
::singleton()->clearCache( $this->oldTitle
);
266 RepoGroup
::singleton()->clearCache( $this->newTitle
); # clear false negative cache
269 $dbw->startAtomic( __METHOD__
);
271 Hooks
::run( 'TitleMoveStarting', [ $this->oldTitle
, $this->newTitle
, $user ] );
273 $pageid = $this->oldTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
274 $protected = $this->oldTitle
->isProtected();
276 // Do the actual move; if this fails, it will throw an MWException(!)
277 $nullRevision = $this->moveToInternal( $user, $this->newTitle
, $reason, $createRedirect,
280 // Refresh the sortkey for this row. Be careful to avoid resetting
281 // cl_timestamp, which may disturb time-based lists on some sites.
282 // @todo This block should be killed, it's duplicating code
283 // from LinksUpdate::getCategoryInsertions() and friends.
284 $prefixes = $dbw->select(
286 [ 'cl_sortkey_prefix', 'cl_to' ],
287 [ 'cl_from' => $pageid ],
290 $type = MWNamespace
::getCategoryLinkType( $this->newTitle
->getNamespace() );
291 foreach ( $prefixes as $prefixRow ) {
292 $prefix = $prefixRow->cl_sortkey_prefix
;
293 $catTo = $prefixRow->cl_to
;
294 $dbw->update( 'categorylinks',
296 'cl_sortkey' => Collation
::singleton()->getSortKey(
297 $this->newTitle
->getCategorySortkey( $prefix ) ),
298 'cl_collation' => $wgCategoryCollation,
300 'cl_timestamp=cl_timestamp' ],
302 'cl_from' => $pageid,
308 $redirid = $this->oldTitle
->getArticleID();
311 # Protect the redirect title as the title used to be...
314 [ 'pr_type', 'pr_level', 'pr_cascade', 'pr_user', 'pr_expiry' ],
315 [ 'pr_page' => $pageid ],
320 foreach ( $res as $row ) {
322 'pr_page' => $redirid,
323 'pr_type' => $row->pr_type
,
324 'pr_level' => $row->pr_level
,
325 'pr_cascade' => $row->pr_cascade
,
326 'pr_user' => $row->pr_user
,
327 'pr_expiry' => $row->pr_expiry
330 $dbw->insert( 'page_restrictions', $rowsInsert, __METHOD__
, [ 'IGNORE' ] );
332 // Build comment for log
333 $comment = wfMessage(
335 $this->oldTitle
->getPrefixedText(),
336 $this->newTitle
->getPrefixedText()
337 )->inContentLanguage()->text();
339 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
342 // reread inserted pr_ids for log relation
343 $insertedPrIds = $dbw->select(
346 [ 'pr_page' => $redirid ],
349 $logRelationsValues = [];
350 foreach ( $insertedPrIds as $prid ) {
351 $logRelationsValues[] = $prid->pr_id
;
354 // Update the protection log
355 $logEntry = new ManualLogEntry( 'protect', 'move_prot' );
356 $logEntry->setTarget( $this->newTitle
);
357 $logEntry->setComment( $comment );
358 $logEntry->setPerformer( $user );
359 $logEntry->setParameters( [
360 '4::oldtitle' => $this->oldTitle
->getPrefixedText(),
362 $logEntry->setRelations( [ 'pr_id' => $logRelationsValues ] );
363 $logEntry->setTags( $changeTags );
364 $logId = $logEntry->insert();
365 $logEntry->publish( $logId );
368 // Update *_from_namespace fields as needed
369 if ( $this->oldTitle
->getNamespace() != $this->newTitle
->getNamespace() ) {
370 $dbw->update( 'pagelinks',
371 [ 'pl_from_namespace' => $this->newTitle
->getNamespace() ],
372 [ 'pl_from' => $pageid ],
375 $dbw->update( 'templatelinks',
376 [ 'tl_from_namespace' => $this->newTitle
->getNamespace() ],
377 [ 'tl_from' => $pageid ],
380 $dbw->update( 'imagelinks',
381 [ 'il_from_namespace' => $this->newTitle
->getNamespace() ],
382 [ 'il_from' => $pageid ],
388 $oldtitle = $this->oldTitle
->getDBkey();
389 $newtitle = $this->newTitle
->getDBkey();
390 $oldsnamespace = MWNamespace
::getSubject( $this->oldTitle
->getNamespace() );
391 $newsnamespace = MWNamespace
::getSubject( $this->newTitle
->getNamespace() );
392 if ( $oldsnamespace != $newsnamespace ||
$oldtitle != $newtitle ) {
393 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
394 $store->duplicateAllAssociatedEntries( $this->oldTitle
, $this->newTitle
);
398 'TitleMoveCompleting',
399 [ $this->oldTitle
, $this->newTitle
,
400 $user, $pageid, $redirid, $reason, $nullRevision ]
403 $dbw->endAtomic( __METHOD__
);
414 // Keep each single hook handler atomic
415 DeferredUpdates
::addUpdate(
416 new AtomicSectionUpdate(
419 // Hold onto $user to avoid HHVM bug where it no longer
420 // becomes a reference (T118683)
421 function () use ( $params, &$user ) {
422 Hooks
::run( 'TitleMoveComplete', $params );
427 return Status
::newGood();
431 * Move page to a title which is either a redirect to the
432 * source page or nonexistent
434 * @todo This was basically directly moved from Title, it should be split into
436 * @param User $user the User doing the move
437 * @param Title $nt The page to move to, which should be a redirect or non-existent
438 * @param string $reason The reason for the move
439 * @param bool $createRedirect Whether to leave a redirect at the old title. Does not check
440 * if the user has the suppressredirect right
441 * @param string[] $changeTags Change tags to apply to the entry in the move log
442 * @return Revision the revision created by the move
443 * @throws MWException
445 private function moveToInternal( User
$user, &$nt, $reason = '', $createRedirect = true,
446 array $changeTags = []
448 if ( $nt->exists() ) {
449 $moveOverRedirect = true;
450 $logType = 'move_redir';
452 $moveOverRedirect = false;
456 if ( $moveOverRedirect ) {
457 $overwriteMessage = wfMessage(
458 'delete_and_move_reason',
459 $this->oldTitle
->getPrefixedText()
460 )->inContentLanguage()->text();
461 $newpage = WikiPage
::factory( $nt );
463 $status = $newpage->doDeleteArticleReal(
465 /* $suppress */ false,
474 if ( !$status->isGood() ) {
475 throw new MWException( 'Failed to delete page-move revision: ' . $status );
478 $nt->resetArticleID( false );
481 if ( $createRedirect ) {
482 if ( $this->oldTitle
->getNamespace() == NS_CATEGORY
483 && !wfMessage( 'category-move-redirect-override' )->inContentLanguage()->isDisabled()
485 $redirectContent = new WikitextContent(
486 wfMessage( 'category-move-redirect-override' )
487 ->params( $nt->getPrefixedText() )->inContentLanguage()->plain() );
489 $contentHandler = ContentHandler
::getForTitle( $this->oldTitle
);
490 $redirectContent = $contentHandler->makeRedirectContent( $nt,
491 wfMessage( 'move-redirect-text' )->inContentLanguage()->plain() );
494 // NOTE: If this page's content model does not support redirects, $redirectContent will be null.
496 $redirectContent = null;
499 // Figure out whether the content model is no longer the default
500 $oldDefault = ContentHandler
::getDefaultModelFor( $this->oldTitle
);
501 $contentModel = $this->oldTitle
->getContentModel();
502 $newDefault = ContentHandler
::getDefaultModelFor( $nt );
503 $defaultContentModelChanging = ( $oldDefault !== $newDefault
504 && $oldDefault === $contentModel );
506 // T59084: log_page should be the ID of the *moved* page
507 $oldid = $this->oldTitle
->getArticleID();
508 $logTitle = clone $this->oldTitle
;
510 $logEntry = new ManualLogEntry( 'move', $logType );
511 $logEntry->setPerformer( $user );
512 $logEntry->setTarget( $logTitle );
513 $logEntry->setComment( $reason );
514 $logEntry->setParameters( [
515 '4::target' => $nt->getPrefixedText(),
516 '5::noredir' => $redirectContent ?
'0' : '1',
519 $formatter = LogFormatter
::newFromEntry( $logEntry );
520 $formatter->setContext( RequestContext
::newExtraneousContext( $this->oldTitle
) );
521 $comment = $formatter->getPlainActionText();
523 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
526 $dbw = wfGetDB( DB_MASTER
);
528 $oldpage = WikiPage
::factory( $this->oldTitle
);
529 $oldcountable = $oldpage->isCountable();
531 $newpage = WikiPage
::factory( $nt );
533 # Change the name of the target page:
534 $dbw->update( 'page',
536 'page_namespace' => $nt->getNamespace(),
537 'page_title' => $nt->getDBkey(),
539 /* WHERE */ [ 'page_id' => $oldid ],
543 # Save a null revision in the page's history notifying of the move
544 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true, $user );
545 if ( !is_object( $nullRevision ) ) {
546 throw new MWException( 'Failed to create null revision while moving page ID '
547 . $oldid . ' to ' . $nt->getPrefixedDBkey() );
550 $nullRevId = $nullRevision->insertOn( $dbw );
551 $logEntry->setAssociatedRevId( $nullRevId );
555 * Increment user_editcount during page moves
556 * Moved from SpecialMovepage.php per T195550
558 $user->incEditCount();
560 if ( !$redirectContent ) {
561 // Clean up the old title *before* reset article id - T47348
562 WikiPage
::onArticleDelete( $this->oldTitle
);
565 $this->oldTitle
->resetArticleID( 0 ); // 0 == non existing
566 $nt->resetArticleID( $oldid );
567 $newpage->loadPageData( WikiPage
::READ_LOCKING
); // T48397
569 $newpage->updateRevisionOn( $dbw, $nullRevision );
571 Hooks
::run( 'NewRevisionFromEditComplete',
572 [ $newpage, $nullRevision, $nullRevision->getParentId(), $user ] );
574 $newpage->doEditUpdates( $nullRevision, $user,
575 [ 'changed' => false, 'moved' => true, 'oldcountable' => $oldcountable ] );
577 // If the default content model changes, we need to populate rev_content_model
578 if ( $defaultContentModelChanging ) {
581 [ 'rev_content_model' => $contentModel ],
582 [ 'rev_page' => $nt->getArticleID(), 'rev_content_model IS NULL' ],
587 WikiPage
::onArticleCreate( $nt );
589 # Recreate the redirect, this time in the other direction.
590 if ( $redirectContent ) {
591 $redirectArticle = WikiPage
::factory( $this->oldTitle
);
592 $redirectArticle->loadFromRow( false, WikiPage
::READ_LOCKING
); // T48397
593 $newid = $redirectArticle->insertOn( $dbw );
594 if ( $newid ) { // sanity
595 $this->oldTitle
->resetArticleID( $newid );
596 $redirectRevision = new Revision( [
597 'title' => $this->oldTitle
, // for determining the default content model
599 'user_text' => $user->getName(),
600 'user' => $user->getId(),
601 'comment' => $comment,
602 'content' => $redirectContent ] );
603 $redirectRevId = $redirectRevision->insertOn( $dbw );
604 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
606 Hooks
::run( 'NewRevisionFromEditComplete',
607 [ $redirectArticle, $redirectRevision, false, $user ] );
609 $redirectArticle->doEditUpdates( $redirectRevision, $user, [ 'created' => true ] );
611 // make a copy because of log entry below
612 $redirectTags = $changeTags;
613 if ( in_array( 'mw-new-redirect', ChangeTags
::getSoftwareTags() ) ) {
614 $redirectTags[] = 'mw-new-redirect';
616 ChangeTags
::addTags( $redirectTags, null, $redirectRevId, null );
621 $logid = $logEntry->insert();
623 $logEntry->setTags( $changeTags );
624 $logEntry->publish( $logid );
626 return $nullRevision;