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
;
25 * Handles the backend logic of moving a page from one title
42 public function __construct( Title
$oldTitle, Title
$newTitle ) {
43 $this->oldTitle
= $oldTitle;
44 $this->newTitle
= $newTitle;
47 public function checkPermissions( User
$user, $reason ) {
48 $status = new Status();
50 $errors = wfMergeErrorArrays(
51 $this->oldTitle
->getUserPermissionsErrors( 'move', $user ),
52 $this->oldTitle
->getUserPermissionsErrors( 'edit', $user ),
53 $this->newTitle
->getUserPermissionsErrors( 'move-target', $user ),
54 $this->newTitle
->getUserPermissionsErrors( 'edit', $user )
57 // Convert into a Status object
59 foreach ( $errors as $error ) {
60 $status->fatal( ...$error );
64 if ( EditPage
::matchSummarySpamRegex( $reason ) !== false ) {
65 // This is kind of lame, won't display nice
66 $status->fatal( 'spamprotectiontext' );
69 $tp = $this->newTitle
->getTitleProtection();
70 if ( $tp !== false && !$user->isAllowed( $tp['permission'] ) ) {
71 $status->fatal( 'cantmove-titleprotected' );
74 Hooks
::run( 'MovePageCheckPermissions',
75 [ $this->oldTitle
, $this->newTitle
, $user, $reason, $status ]
82 * Does various sanity checks that the move is
83 * valid. Only things based on the two titles
84 * should be checked here.
88 public function isValidMove() {
89 global $wgContentHandlerUseDB;
90 $status = new Status();
92 if ( $this->oldTitle
->equals( $this->newTitle
) ) {
93 $status->fatal( 'selfmove' );
95 if ( !$this->oldTitle
->isMovable() ) {
96 $status->fatal( 'immobile-source-namespace', $this->oldTitle
->getNsText() );
98 if ( $this->newTitle
->isExternal() ) {
99 $status->fatal( 'immobile-target-namespace-iw' );
101 if ( !$this->newTitle
->isMovable() ) {
102 $status->fatal( 'immobile-target-namespace', $this->newTitle
->getNsText() );
105 $oldid = $this->oldTitle
->getArticleID();
107 if ( strlen( $this->newTitle
->getDBkey() ) < 1 ) {
108 $status->fatal( 'articleexists' );
111 ( $this->oldTitle
->getDBkey() == '' ) ||
113 ( $this->newTitle
->getDBkey() == '' )
115 $status->fatal( 'badarticleerror' );
118 # The move is allowed only if (1) the target doesn't exist, or
119 # (2) the target is a redirect to the source, and has no history
120 # (so we can undo bad moves right after they're done).
121 if ( $this->newTitle
->getArticleID() && !$this->isValidMoveTarget() ) {
122 $status->fatal( 'articleexists' );
125 // Content model checks
126 if ( !$wgContentHandlerUseDB &&
127 $this->oldTitle
->getContentModel() !== $this->newTitle
->getContentModel() ) {
128 // can't move a page if that would change the page's content model
131 ContentHandler
::getLocalizedName( $this->oldTitle
->getContentModel() ),
132 ContentHandler
::getLocalizedName( $this->newTitle
->getContentModel() )
135 !ContentHandler
::getForTitle( $this->oldTitle
)->canBeUsedOn( $this->newTitle
)
138 'content-not-allowed-here',
139 ContentHandler
::getLocalizedName( $this->oldTitle
->getContentModel() ),
140 $this->newTitle
->getPrefixedText()
144 // Image-specific checks
145 if ( $this->oldTitle
->inNamespace( NS_FILE
) ) {
146 $status->merge( $this->isValidFileMove() );
149 if ( $this->newTitle
->inNamespace( NS_FILE
) && !$this->oldTitle
->inNamespace( NS_FILE
) ) {
150 $status->fatal( 'nonfile-cannot-move-to-file' );
153 // Hook for extensions to say a title can't be moved for technical reasons
154 Hooks
::run( 'MovePageIsValidMove', [ $this->oldTitle
, $this->newTitle
, $status ] );
160 * Sanity checks for when a file is being moved
164 protected function isValidFileMove() {
165 $status = new Status();
166 $file = wfLocalFile( $this->oldTitle
);
167 $file->load( File
::READ_LATEST
);
168 if ( $file->exists() ) {
169 if ( $this->newTitle
->getText() != wfStripIllegalFilenameChars( $this->newTitle
->getText() ) ) {
170 $status->fatal( 'imageinvalidfilename' );
172 if ( !File
::checkExtensionCompatibility( $file, $this->newTitle
->getDBkey() ) ) {
173 $status->fatal( 'imagetypemismatch' );
177 if ( !$this->newTitle
->inNamespace( NS_FILE
) ) {
178 $status->fatal( 'imagenocrossnamespace' );
185 * Checks if $this can be moved to a given Title
186 * - Selects for update, so don't call it unless you mean business
191 protected function isValidMoveTarget() {
192 # Is it an existing file?
193 if ( $this->newTitle
->inNamespace( NS_FILE
) ) {
194 $file = wfLocalFile( $this->newTitle
);
195 $file->load( File
::READ_LATEST
);
196 if ( $file->exists() ) {
197 wfDebug( __METHOD__
. ": file exists\n" );
201 # Is it a redirect with no history?
202 if ( !$this->newTitle
->isSingleRevRedirect() ) {
203 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
206 # Get the article text
207 $rev = Revision
::newFromTitle( $this->newTitle
, false, Revision
::READ_LATEST
);
208 if ( !is_object( $rev ) ) {
211 $content = $rev->getContent();
212 # Does the redirect point to the source?
213 # Or is it a broken self-redirect, usually caused by namespace collisions?
214 $redirTitle = $content ?
$content->getRedirectTarget() : null;
217 if ( $redirTitle->getPrefixedDBkey() !== $this->oldTitle
->getPrefixedDBkey() &&
218 $redirTitle->getPrefixedDBkey() !== $this->newTitle
->getPrefixedDBkey() ) {
219 wfDebug( __METHOD__
. ": redirect points to other page\n" );
225 # Fail safe (not a redirect after all. strange.)
226 wfDebug( __METHOD__
. ": failsafe: database says " . $this->newTitle
->getPrefixedDBkey() .
227 " is a redirect, but it doesn't contain a valid redirect.\n" );
234 * @param string $reason
235 * @param bool $createRedirect
236 * @param string[] $changeTags Change tags to apply to the entry in the move log. Caller
237 * should perform permission checks with ChangeTags::canAddTagsAccompanyingChange
240 public function move( User
$user, $reason, $createRedirect, array $changeTags = [] ) {
241 global $wgCategoryCollation;
243 Hooks
::run( 'TitleMove', [ $this->oldTitle
, $this->newTitle
, $user ] );
245 // If it is a file, move it first.
246 // It is done before all other moving stuff is done because it's hard to revert.
247 $dbw = wfGetDB( DB_MASTER
);
248 if ( $this->oldTitle
->getNamespace() == NS_FILE
) {
249 $file = wfLocalFile( $this->oldTitle
);
250 $file->load( File
::READ_LATEST
);
251 if ( $file->exists() ) {
252 $status = $file->move( $this->newTitle
);
253 if ( !$status->isOK() ) {
257 // Clear RepoGroup process cache
258 RepoGroup
::singleton()->clearCache( $this->oldTitle
);
259 RepoGroup
::singleton()->clearCache( $this->newTitle
); # clear false negative cache
262 $dbw->startAtomic( __METHOD__
);
264 Hooks
::run( 'TitleMoveStarting', [ $this->oldTitle
, $this->newTitle
, $user ] );
266 $pageid = $this->oldTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
267 $protected = $this->oldTitle
->isProtected();
269 // Do the actual move; if this fails, it will throw an MWException(!)
270 $nullRevision = $this->moveToInternal( $user, $this->newTitle
, $reason, $createRedirect,
273 // Refresh the sortkey for this row. Be careful to avoid resetting
274 // cl_timestamp, which may disturb time-based lists on some sites.
275 // @todo This block should be killed, it's duplicating code
276 // from LinksUpdate::getCategoryInsertions() and friends.
277 $prefixes = $dbw->select(
279 [ 'cl_sortkey_prefix', 'cl_to' ],
280 [ 'cl_from' => $pageid ],
283 $type = MWNamespace
::getCategoryLinkType( $this->newTitle
->getNamespace() );
284 foreach ( $prefixes as $prefixRow ) {
285 $prefix = $prefixRow->cl_sortkey_prefix
;
286 $catTo = $prefixRow->cl_to
;
287 $dbw->update( 'categorylinks',
289 'cl_sortkey' => Collation
::singleton()->getSortKey(
290 $this->newTitle
->getCategorySortkey( $prefix ) ),
291 'cl_collation' => $wgCategoryCollation,
293 'cl_timestamp=cl_timestamp' ],
295 'cl_from' => $pageid,
301 $redirid = $this->oldTitle
->getArticleID();
304 # Protect the redirect title as the title used to be...
307 [ 'pr_type', 'pr_level', 'pr_cascade', 'pr_user', 'pr_expiry' ],
308 [ 'pr_page' => $pageid ],
313 foreach ( $res as $row ) {
315 'pr_page' => $redirid,
316 'pr_type' => $row->pr_type
,
317 'pr_level' => $row->pr_level
,
318 'pr_cascade' => $row->pr_cascade
,
319 'pr_user' => $row->pr_user
,
320 'pr_expiry' => $row->pr_expiry
323 $dbw->insert( 'page_restrictions', $rowsInsert, __METHOD__
, [ 'IGNORE' ] );
325 // Build comment for log
326 $comment = wfMessage(
328 $this->oldTitle
->getPrefixedText(),
329 $this->newTitle
->getPrefixedText()
330 )->inContentLanguage()->text();
332 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
335 // reread inserted pr_ids for log relation
336 $insertedPrIds = $dbw->select(
339 [ 'pr_page' => $redirid ],
342 $logRelationsValues = [];
343 foreach ( $insertedPrIds as $prid ) {
344 $logRelationsValues[] = $prid->pr_id
;
347 // Update the protection log
348 $logEntry = new ManualLogEntry( 'protect', 'move_prot' );
349 $logEntry->setTarget( $this->newTitle
);
350 $logEntry->setComment( $comment );
351 $logEntry->setPerformer( $user );
352 $logEntry->setParameters( [
353 '4::oldtitle' => $this->oldTitle
->getPrefixedText(),
355 $logEntry->setRelations( [ 'pr_id' => $logRelationsValues ] );
356 $logEntry->setTags( $changeTags );
357 $logId = $logEntry->insert();
358 $logEntry->publish( $logId );
361 // Update *_from_namespace fields as needed
362 if ( $this->oldTitle
->getNamespace() != $this->newTitle
->getNamespace() ) {
363 $dbw->update( 'pagelinks',
364 [ 'pl_from_namespace' => $this->newTitle
->getNamespace() ],
365 [ 'pl_from' => $pageid ],
368 $dbw->update( 'templatelinks',
369 [ 'tl_from_namespace' => $this->newTitle
->getNamespace() ],
370 [ 'tl_from' => $pageid ],
373 $dbw->update( 'imagelinks',
374 [ 'il_from_namespace' => $this->newTitle
->getNamespace() ],
375 [ 'il_from' => $pageid ],
381 $oldtitle = $this->oldTitle
->getDBkey();
382 $newtitle = $this->newTitle
->getDBkey();
383 $oldsnamespace = MWNamespace
::getSubject( $this->oldTitle
->getNamespace() );
384 $newsnamespace = MWNamespace
::getSubject( $this->newTitle
->getNamespace() );
385 if ( $oldsnamespace != $newsnamespace ||
$oldtitle != $newtitle ) {
386 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
387 $store->duplicateAllAssociatedEntries( $this->oldTitle
, $this->newTitle
);
391 'TitleMoveCompleting',
392 [ $this->oldTitle
, $this->newTitle
,
393 $user, $pageid, $redirid, $reason, $nullRevision ]
396 $dbw->endAtomic( __METHOD__
);
407 // Keep each single hook handler atomic
408 DeferredUpdates
::addUpdate(
409 new AtomicSectionUpdate(
412 // Hold onto $user to avoid HHVM bug where it no longer
413 // becomes a reference (T118683)
414 function () use ( $params, &$user ) {
415 Hooks
::run( 'TitleMoveComplete', $params );
420 return Status
::newGood();
424 * Move page to a title which is either a redirect to the
425 * source page or nonexistent
427 * @todo This was basically directly moved from Title, it should be split into
429 * @param User $user the User doing the move
430 * @param Title $nt The page to move to, which should be a redirect or non-existent
431 * @param string $reason The reason for the move
432 * @param bool $createRedirect Whether to leave a redirect at the old title. Does not check
433 * if the user has the suppressredirect right
434 * @param string[] $changeTags Change tags to apply to the entry in the move log
435 * @return Revision the revision created by the move
436 * @throws MWException
438 private function moveToInternal( User
$user, &$nt, $reason = '', $createRedirect = true,
439 array $changeTags = []
441 if ( $nt->exists() ) {
442 $moveOverRedirect = true;
443 $logType = 'move_redir';
445 $moveOverRedirect = false;
449 if ( $moveOverRedirect ) {
450 $overwriteMessage = wfMessage(
451 'delete_and_move_reason',
452 $this->oldTitle
->getPrefixedText()
453 )->inContentLanguage()->text();
454 $newpage = WikiPage
::factory( $nt );
456 $status = $newpage->doDeleteArticleReal(
458 /* $suppress */ false,
467 if ( !$status->isGood() ) {
468 throw new MWException( 'Failed to delete page-move revision: ' . $status );
471 $nt->resetArticleID( false );
474 if ( $createRedirect ) {
475 if ( $this->oldTitle
->getNamespace() == NS_CATEGORY
476 && !wfMessage( 'category-move-redirect-override' )->inContentLanguage()->isDisabled()
478 $redirectContent = new WikitextContent(
479 wfMessage( 'category-move-redirect-override' )
480 ->params( $nt->getPrefixedText() )->inContentLanguage()->plain() );
482 $contentHandler = ContentHandler
::getForTitle( $this->oldTitle
);
483 $redirectContent = $contentHandler->makeRedirectContent( $nt,
484 wfMessage( 'move-redirect-text' )->inContentLanguage()->plain() );
487 // NOTE: If this page's content model does not support redirects, $redirectContent will be null.
489 $redirectContent = null;
492 // Figure out whether the content model is no longer the default
493 $oldDefault = ContentHandler
::getDefaultModelFor( $this->oldTitle
);
494 $contentModel = $this->oldTitle
->getContentModel();
495 $newDefault = ContentHandler
::getDefaultModelFor( $nt );
496 $defaultContentModelChanging = ( $oldDefault !== $newDefault
497 && $oldDefault === $contentModel );
499 // T59084: log_page should be the ID of the *moved* page
500 $oldid = $this->oldTitle
->getArticleID();
501 $logTitle = clone $this->oldTitle
;
503 $logEntry = new ManualLogEntry( 'move', $logType );
504 $logEntry->setPerformer( $user );
505 $logEntry->setTarget( $logTitle );
506 $logEntry->setComment( $reason );
507 $logEntry->setParameters( [
508 '4::target' => $nt->getPrefixedText(),
509 '5::noredir' => $redirectContent ?
'0' : '1',
512 $formatter = LogFormatter
::newFromEntry( $logEntry );
513 $formatter->setContext( RequestContext
::newExtraneousContext( $this->oldTitle
) );
514 $comment = $formatter->getPlainActionText();
516 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
519 $dbw = wfGetDB( DB_MASTER
);
521 $oldpage = WikiPage
::factory( $this->oldTitle
);
522 $oldcountable = $oldpage->isCountable();
524 $newpage = WikiPage
::factory( $nt );
526 # Change the name of the target page:
527 $dbw->update( 'page',
529 'page_namespace' => $nt->getNamespace(),
530 'page_title' => $nt->getDBkey(),
532 /* WHERE */ [ 'page_id' => $oldid ],
536 # Save a null revision in the page's history notifying of the move
537 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true, $user );
538 if ( !is_object( $nullRevision ) ) {
539 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
542 $nullRevId = $nullRevision->insertOn( $dbw );
543 $logEntry->setAssociatedRevId( $nullRevId );
545 if ( !$redirectContent ) {
546 // Clean up the old title *before* reset article id - T47348
547 WikiPage
::onArticleDelete( $this->oldTitle
);
550 $this->oldTitle
->resetArticleID( 0 ); // 0 == non existing
551 $nt->resetArticleID( $oldid );
552 $newpage->loadPageData( WikiPage
::READ_LOCKING
); // T48397
554 $newpage->updateRevisionOn( $dbw, $nullRevision );
556 Hooks
::run( 'NewRevisionFromEditComplete',
557 [ $newpage, $nullRevision, $nullRevision->getParentId(), $user ] );
559 $newpage->doEditUpdates( $nullRevision, $user,
560 [ 'changed' => false, 'moved' => true, 'oldcountable' => $oldcountable ] );
562 // If the default content model changes, we need to populate rev_content_model
563 if ( $defaultContentModelChanging ) {
566 [ 'rev_content_model' => $contentModel ],
567 [ 'rev_page' => $nt->getArticleID(), 'rev_content_model IS NULL' ],
572 WikiPage
::onArticleCreate( $nt );
574 # Recreate the redirect, this time in the other direction.
575 if ( $redirectContent ) {
576 $redirectArticle = WikiPage
::factory( $this->oldTitle
);
577 $redirectArticle->loadFromRow( false, WikiPage
::READ_LOCKING
); // T48397
578 $newid = $redirectArticle->insertOn( $dbw );
579 if ( $newid ) { // sanity
580 $this->oldTitle
->resetArticleID( $newid );
581 $redirectRevision = new Revision( [
582 'title' => $this->oldTitle
, // for determining the default content model
584 'user_text' => $user->getName(),
585 'user' => $user->getId(),
586 'comment' => $comment,
587 'content' => $redirectContent ] );
588 $redirectRevId = $redirectRevision->insertOn( $dbw );
589 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
591 Hooks
::run( 'NewRevisionFromEditComplete',
592 [ $redirectArticle, $redirectRevision, false, $user ] );
594 $redirectArticle->doEditUpdates( $redirectRevision, $user, [ 'created' => true ] );
596 // make a copy because of log entry below
597 $redirectTags = $changeTags;
598 if ( in_array( 'mw-new-redirect', ChangeTags
::getSoftwareTags() ) ) {
599 $redirectTags[] = 'mw-new-redirect';
601 ChangeTags
::addTags( $redirectTags, null, $redirectRevId, null );
606 $logid = $logEntry->insert();
608 $logEntry->setTags( $changeTags );
609 $logEntry->publish( $logid );
611 return $nullRevision;