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 call_user_func_array( [ $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() )
136 // Image-specific checks
137 if ( $this->oldTitle
->inNamespace( NS_FILE
) ) {
138 $status->merge( $this->isValidFileMove() );
141 if ( $this->newTitle
->inNamespace( NS_FILE
) && !$this->oldTitle
->inNamespace( NS_FILE
) ) {
142 $status->fatal( 'nonfile-cannot-move-to-file' );
145 // Hook for extensions to say a title can't be moved for technical reasons
146 Hooks
::run( 'MovePageIsValidMove', [ $this->oldTitle
, $this->newTitle
, $status ] );
152 * Sanity checks for when a file is being moved
156 protected function isValidFileMove() {
157 $status = new Status();
158 $file = wfLocalFile( $this->oldTitle
);
159 $file->load( File
::READ_LATEST
);
160 if ( $file->exists() ) {
161 if ( $this->newTitle
->getText() != wfStripIllegalFilenameChars( $this->newTitle
->getText() ) ) {
162 $status->fatal( 'imageinvalidfilename' );
164 if ( !File
::checkExtensionCompatibility( $file, $this->newTitle
->getDBkey() ) ) {
165 $status->fatal( 'imagetypemismatch' );
169 if ( !$this->newTitle
->inNamespace( NS_FILE
) ) {
170 $status->fatal( 'imagenocrossnamespace' );
177 * Checks if $this can be moved to a given Title
178 * - Selects for update, so don't call it unless you mean business
183 protected function isValidMoveTarget() {
184 # Is it an existing file?
185 if ( $this->newTitle
->inNamespace( NS_FILE
) ) {
186 $file = wfLocalFile( $this->newTitle
);
187 $file->load( File
::READ_LATEST
);
188 if ( $file->exists() ) {
189 wfDebug( __METHOD__
. ": file exists\n" );
193 # Is it a redirect with no history?
194 if ( !$this->newTitle
->isSingleRevRedirect() ) {
195 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
198 # Get the article text
199 $rev = Revision
::newFromTitle( $this->newTitle
, false, Revision
::READ_LATEST
);
200 if ( !is_object( $rev ) ) {
203 $content = $rev->getContent();
204 # Does the redirect point to the source?
205 # Or is it a broken self-redirect, usually caused by namespace collisions?
206 $redirTitle = $content ?
$content->getRedirectTarget() : null;
209 if ( $redirTitle->getPrefixedDBkey() !== $this->oldTitle
->getPrefixedDBkey() &&
210 $redirTitle->getPrefixedDBkey() !== $this->newTitle
->getPrefixedDBkey() ) {
211 wfDebug( __METHOD__
. ": redirect points to other page\n" );
217 # Fail safe (not a redirect after all. strange.)
218 wfDebug( __METHOD__
. ": failsafe: database says " . $this->newTitle
->getPrefixedDBkey() .
219 " is a redirect, but it doesn't contain a valid redirect.\n" );
226 * @param string $reason
227 * @param bool $createRedirect
230 public function move( User
$user, $reason, $createRedirect ) {
231 global $wgCategoryCollation;
233 Hooks
::run( 'TitleMove', [ $this->oldTitle
, $this->newTitle
, $user ] );
235 // If it is a file, move it first.
236 // It is done before all other moving stuff is done because it's hard to revert.
237 $dbw = wfGetDB( DB_MASTER
);
238 if ( $this->oldTitle
->getNamespace() == NS_FILE
) {
239 $file = wfLocalFile( $this->oldTitle
);
240 $file->load( File
::READ_LATEST
);
241 if ( $file->exists() ) {
242 $status = $file->move( $this->newTitle
);
243 if ( !$status->isOK() ) {
247 // Clear RepoGroup process cache
248 RepoGroup
::singleton()->clearCache( $this->oldTitle
);
249 RepoGroup
::singleton()->clearCache( $this->newTitle
); # clear false negative cache
252 $dbw->startAtomic( __METHOD__
);
254 Hooks
::run( 'TitleMoveStarting', [ $this->oldTitle
, $this->newTitle
, $user ] );
256 $pageid = $this->oldTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
257 $protected = $this->oldTitle
->isProtected();
259 // Do the actual move
260 $nullRevision = $this->moveToInternal( $user, $this->newTitle
, $reason, $createRedirect );
262 // Refresh the sortkey for this row. Be careful to avoid resetting
263 // cl_timestamp, which may disturb time-based lists on some sites.
264 // @todo This block should be killed, it's duplicating code
265 // from LinksUpdate::getCategoryInsertions() and friends.
266 $prefixes = $dbw->select(
268 [ 'cl_sortkey_prefix', 'cl_to' ],
269 [ 'cl_from' => $pageid ],
272 if ( $this->newTitle
->getNamespace() == NS_CATEGORY
) {
274 } elseif ( $this->newTitle
->getNamespace() == NS_FILE
) {
279 foreach ( $prefixes as $prefixRow ) {
280 $prefix = $prefixRow->cl_sortkey_prefix
;
281 $catTo = $prefixRow->cl_to
;
282 $dbw->update( 'categorylinks',
284 'cl_sortkey' => Collation
::singleton()->getSortKey(
285 $this->newTitle
->getCategorySortkey( $prefix ) ),
286 'cl_collation' => $wgCategoryCollation,
288 'cl_timestamp=cl_timestamp' ],
290 'cl_from' => $pageid,
296 $redirid = $this->oldTitle
->getArticleID();
299 # Protect the redirect title as the title used to be...
300 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
302 'pr_page' => $redirid,
303 'pr_type' => 'pr_type',
304 'pr_level' => 'pr_level',
305 'pr_cascade' => 'pr_cascade',
306 'pr_user' => 'pr_user',
307 'pr_expiry' => 'pr_expiry'
309 [ 'pr_page' => $pageid ],
314 // Build comment for log
315 $comment = wfMessage(
317 $this->oldTitle
->getPrefixedText(),
318 $this->newTitle
->getPrefixedText()
319 )->inContentLanguage()->text();
321 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
324 // reread inserted pr_ids for log relation
325 $insertedPrIds = $dbw->select(
328 [ 'pr_page' => $redirid ],
331 $logRelationsValues = [];
332 foreach ( $insertedPrIds as $prid ) {
333 $logRelationsValues[] = $prid->pr_id
;
336 // Update the protection log
337 $logEntry = new ManualLogEntry( 'protect', 'move_prot' );
338 $logEntry->setTarget( $this->newTitle
);
339 $logEntry->setComment( $comment );
340 $logEntry->setPerformer( $user );
341 $logEntry->setParameters( [
342 '4::oldtitle' => $this->oldTitle
->getPrefixedText(),
344 $logEntry->setRelations( [ 'pr_id' => $logRelationsValues ] );
345 $logId = $logEntry->insert();
346 $logEntry->publish( $logId );
349 // Update *_from_namespace fields as needed
350 if ( $this->oldTitle
->getNamespace() != $this->newTitle
->getNamespace() ) {
351 $dbw->update( 'pagelinks',
352 [ 'pl_from_namespace' => $this->newTitle
->getNamespace() ],
353 [ 'pl_from' => $pageid ],
356 $dbw->update( 'templatelinks',
357 [ 'tl_from_namespace' => $this->newTitle
->getNamespace() ],
358 [ 'tl_from' => $pageid ],
361 $dbw->update( 'imagelinks',
362 [ 'il_from_namespace' => $this->newTitle
->getNamespace() ],
363 [ 'il_from' => $pageid ],
369 $oldtitle = $this->oldTitle
->getDBkey();
370 $newtitle = $this->newTitle
->getDBkey();
371 $oldsnamespace = MWNamespace
::getSubject( $this->oldTitle
->getNamespace() );
372 $newsnamespace = MWNamespace
::getSubject( $this->newTitle
->getNamespace() );
373 if ( $oldsnamespace != $newsnamespace ||
$oldtitle != $newtitle ) {
374 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
375 $store->duplicateAllAssociatedEntries( $this->oldTitle
, $this->newTitle
);
379 'TitleMoveCompleting',
380 [ $this->oldTitle
, $this->newTitle
,
381 $user, $pageid, $redirid, $reason, $nullRevision ]
384 $dbw->endAtomic( __METHOD__
);
395 $dbw->onTransactionIdle( function () use ( $params, $dbw ) {
396 // Keep each single hook handler atomic
397 $dbw->setFlag( DBO_TRX
); // flag is automatically reset by DB layer
398 Hooks
::run( 'TitleMoveComplete', $params );
401 return Status
::newGood();
405 * Move page to a title which is either a redirect to the
406 * source page or nonexistent
408 * @fixme This was basically directly moved from Title, it should be split into smaller functions
409 * @param User $user the User doing the move
410 * @param Title $nt The page to move to, which should be a redirect or nonexistent
411 * @param string $reason The reason for the move
412 * @param bool $createRedirect Whether to leave a redirect at the old title. Does not check
413 * if the user has the suppressredirect right
414 * @return Revision the revision created by the move
415 * @throws MWException
417 private function moveToInternal( User
$user, &$nt, $reason = '', $createRedirect = true ) {
420 if ( $nt->exists() ) {
421 $moveOverRedirect = true;
422 $logType = 'move_redir';
424 $moveOverRedirect = false;
428 if ( $createRedirect ) {
429 if ( $this->oldTitle
->getNamespace() == NS_CATEGORY
430 && !wfMessage( 'category-move-redirect-override' )->inContentLanguage()->isDisabled()
432 $redirectContent = new WikitextContent(
433 wfMessage( 'category-move-redirect-override' )
434 ->params( $nt->getPrefixedText() )->inContentLanguage()->plain() );
436 $contentHandler = ContentHandler
::getForTitle( $this->oldTitle
);
437 $redirectContent = $contentHandler->makeRedirectContent( $nt,
438 wfMessage( 'move-redirect-text' )->inContentLanguage()->plain() );
441 // NOTE: If this page's content model does not support redirects, $redirectContent will be null.
443 $redirectContent = null;
446 // Figure out whether the content model is no longer the default
447 $oldDefault = ContentHandler
::getDefaultModelFor( $this->oldTitle
);
448 $contentModel = $this->oldTitle
->getContentModel();
449 $newDefault = ContentHandler
::getDefaultModelFor( $nt );
450 $defaultContentModelChanging = ( $oldDefault !== $newDefault
451 && $oldDefault === $contentModel );
453 // bug 57084: log_page should be the ID of the *moved* page
454 $oldid = $this->oldTitle
->getArticleID();
455 $logTitle = clone $this->oldTitle
;
457 $logEntry = new ManualLogEntry( 'move', $logType );
458 $logEntry->setPerformer( $user );
459 $logEntry->setTarget( $logTitle );
460 $logEntry->setComment( $reason );
461 $logEntry->setParameters( [
462 '4::target' => $nt->getPrefixedText(),
463 '5::noredir' => $redirectContent ?
'0': '1',
466 $formatter = LogFormatter
::newFromEntry( $logEntry );
467 $formatter->setContext( RequestContext
::newExtraneousContext( $this->oldTitle
) );
468 $comment = $formatter->getPlainActionText();
470 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
472 # Truncate for whole multibyte characters.
473 $comment = $wgContLang->truncate( $comment, 255 );
475 $dbw = wfGetDB( DB_MASTER
);
477 $oldpage = WikiPage
::factory( $this->oldTitle
);
478 $oldcountable = $oldpage->isCountable();
480 $newpage = WikiPage
::factory( $nt );
482 if ( $moveOverRedirect ) {
483 $newid = $nt->getArticleID();
484 $newcontent = $newpage->getContent();
486 # Delete the old redirect. We don't save it to history since
487 # by definition if we've got here it's rather uninteresting.
488 # We have to remove it so that the next step doesn't trigger
489 # a conflict on the unique namespace+title index...
490 $dbw->delete( 'page', [ 'page_id' => $newid ], __METHOD__
);
492 $newpage->doDeleteUpdates( $newid, $newcontent );
495 # Save a null revision in the page's history notifying of the move
496 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true, $user );
497 if ( !is_object( $nullRevision ) ) {
498 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
501 $nullRevision->insertOn( $dbw );
503 # Change the name of the target page:
504 $dbw->update( 'page',
506 'page_namespace' => $nt->getNamespace(),
507 'page_title' => $nt->getDBkey(),
509 /* WHERE */ [ 'page_id' => $oldid ],
513 // clean up the old title before reset article id - bug 45348
514 if ( !$redirectContent ) {
515 WikiPage
::onArticleDelete( $this->oldTitle
);
518 $this->oldTitle
->resetArticleID( 0 ); // 0 == non existing
519 $nt->resetArticleID( $oldid );
520 $newpage->loadPageData( WikiPage
::READ_LOCKING
); // bug 46397
522 $newpage->updateRevisionOn( $dbw, $nullRevision );
524 Hooks
::run( 'NewRevisionFromEditComplete',
525 [ $newpage, $nullRevision, $nullRevision->getParentId(), $user ] );
527 $newpage->doEditUpdates( $nullRevision, $user,
528 [ 'changed' => false, 'moved' => true, 'oldcountable' => $oldcountable ] );
530 // If the default content model changes, we need to populate rev_content_model
531 if ( $defaultContentModelChanging ) {
534 [ 'rev_content_model' => $contentModel ],
535 [ 'rev_page' => $nt->getArticleID(), 'rev_content_model IS NULL' ],
540 if ( !$moveOverRedirect ) {
541 WikiPage
::onArticleCreate( $nt );
544 # Recreate the redirect, this time in the other direction.
545 if ( $redirectContent ) {
546 $redirectArticle = WikiPage
::factory( $this->oldTitle
);
547 $redirectArticle->loadFromRow( false, WikiPage
::READ_LOCKING
); // bug 46397
548 $newid = $redirectArticle->insertOn( $dbw );
549 if ( $newid ) { // sanity
550 $this->oldTitle
->resetArticleID( $newid );
551 $redirectRevision = new Revision( [
552 'title' => $this->oldTitle
, // for determining the default content model
554 'user_text' => $user->getName(),
555 'user' => $user->getId(),
556 'comment' => $comment,
557 'content' => $redirectContent ] );
558 $redirectRevision->insertOn( $dbw );
559 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
561 Hooks
::run( 'NewRevisionFromEditComplete',
562 [ $redirectArticle, $redirectRevision, false, $user ] );
564 $redirectArticle->doEditUpdates( $redirectRevision, $user, [ 'created' => true ] );
569 $logid = $logEntry->insert();
570 $logEntry->publish( $logid );
572 return $nullRevision;