Merge "Remove not used private member variable mParserWarnings from OutputPage"
[mediawiki.git] / includes / MovePage.php
blobfb0ca8c89a093f96d47263348e3f62c11a000abc
1 <?php
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.
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
19 * @file
22 /**
23 * Handles the backend logic of moving a page from one title
24 * to another.
26 * @since 1.24
28 class MovePage {
30 /**
31 * @var Title
33 protected $oldTitle;
35 /**
36 * @var Title
38 protected $newTitle;
40 public function __construct( Title $oldTitle, Title $newTitle ) {
41 $this->oldTitle = $oldTitle;
42 $this->newTitle = $newTitle;
45 public function checkPermissions( User $user, $reason ) {
46 $status = new Status();
48 $errors = wfMergeErrorArrays(
49 $this->oldTitle->getUserPermissionsErrors( 'move', $user ),
50 $this->oldTitle->getUserPermissionsErrors( 'edit', $user ),
51 $this->newTitle->getUserPermissionsErrors( 'move-target', $user ),
52 $this->newTitle->getUserPermissionsErrors( 'edit', $user )
55 // Convert into a Status object
56 if ( $errors ) {
57 foreach ( $errors as $error ) {
58 call_user_func_array( array( $status, 'fatal' ), $error );
62 if ( EditPage::matchSummarySpamRegex( $reason ) !== false ) {
63 // This is kind of lame, won't display nice
64 $status->fatal( 'spamprotectiontext' );
67 $tp = $this->newTitle->getTitleProtection();
68 if ( $tp !== false && !$user->isAllowed( $tp['permission'] ) ) {
69 $status->fatal( 'cantmove-titleprotected' );
72 Hooks::run( 'MovePageCheckPermissions',
73 array( $this->oldTitle, $this->newTitle, $user, $reason, $status )
76 return $status;
79 /**
80 * Does various sanity checks that the move is
81 * valid. Only things based on the two titles
82 * should be checked here.
84 * @return Status
86 public function isValidMove() {
87 global $wgContentHandlerUseDB;
88 $status = new Status();
90 if ( $this->oldTitle->equals( $this->newTitle ) ) {
91 $status->fatal( 'selfmove' );
93 if ( !$this->oldTitle->isMovable() ) {
94 $status->fatal( 'immobile-source-namespace', $this->oldTitle->getNsText() );
96 if ( $this->newTitle->isExternal() ) {
97 $status->fatal( 'immobile-target-namespace-iw' );
99 if ( !$this->newTitle->isMovable() ) {
100 $status->fatal( 'immobile-target-namespace', $this->newTitle->getNsText() );
103 $oldid = $this->oldTitle->getArticleID();
105 if ( strlen( $this->newTitle->getDBkey() ) < 1 ) {
106 $status->fatal( 'articleexists' );
108 if (
109 ( $this->oldTitle->getDBkey() == '' ) ||
110 ( !$oldid ) ||
111 ( $this->newTitle->getDBkey() == '' )
113 $status->fatal( 'badarticleerror' );
116 # The move is allowed only if (1) the target doesn't exist, or
117 # (2) the target is a redirect to the source, and has no history
118 # (so we can undo bad moves right after they're done).
119 if ( $this->newTitle->getArticleID() && !$this->isValidMoveTarget() ) {
120 $status->fatal( 'articleexists' );
123 // Content model checks
124 if ( !$wgContentHandlerUseDB &&
125 $this->oldTitle->getContentModel() !== $this->newTitle->getContentModel() ) {
126 // can't move a page if that would change the page's content model
127 $status->fatal(
128 'bad-target-model',
129 ContentHandler::getLocalizedName( $this->oldTitle->getContentModel() ),
130 ContentHandler::getLocalizedName( $this->newTitle->getContentModel() )
134 // Image-specific checks
135 if ( $this->oldTitle->inNamespace( NS_FILE ) ) {
136 $status->merge( $this->isValidFileMove() );
139 if ( $this->newTitle->inNamespace( NS_FILE ) && !$this->oldTitle->inNamespace( NS_FILE ) ) {
140 $status->fatal( 'nonfile-cannot-move-to-file' );
143 // Hook for extensions to say a title can't be moved for technical reasons
144 Hooks::run( 'MovePageIsValidMove', array( $this->oldTitle, $this->newTitle, $status ) );
146 return $status;
150 * Sanity checks for when a file is being moved
152 * @return Status
154 protected function isValidFileMove() {
155 $status = new Status();
156 $file = wfLocalFile( $this->oldTitle );
157 $file->load( File::READ_LATEST );
158 if ( $file->exists() ) {
159 if ( $this->newTitle->getText() != wfStripIllegalFilenameChars( $this->newTitle->getText() ) ) {
160 $status->fatal( 'imageinvalidfilename' );
162 if ( !File::checkExtensionCompatibility( $file, $this->newTitle->getDBkey() ) ) {
163 $status->fatal( 'imagetypemismatch' );
167 if ( !$this->newTitle->inNamespace( NS_FILE ) ) {
168 $status->fatal( 'imagenocrossnamespace' );
171 return $status;
175 * Checks if $this can be moved to a given Title
176 * - Selects for update, so don't call it unless you mean business
178 * @since 1.25
179 * @return bool
181 protected function isValidMoveTarget() {
182 # Is it an existing file?
183 if ( $this->newTitle->inNamespace( NS_FILE ) ) {
184 $file = wfLocalFile( $this->newTitle );
185 $file->load( File::READ_LATEST );
186 if ( $file->exists() ) {
187 wfDebug( __METHOD__ . ": file exists\n" );
188 return false;
191 # Is it a redirect with no history?
192 if ( !$this->newTitle->isSingleRevRedirect() ) {
193 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
194 return false;
196 # Get the article text
197 $rev = Revision::newFromTitle( $this->newTitle, false, Revision::READ_LATEST );
198 if ( !is_object( $rev ) ) {
199 return false;
201 $content = $rev->getContent();
202 # Does the redirect point to the source?
203 # Or is it a broken self-redirect, usually caused by namespace collisions?
204 $redirTitle = $content ? $content->getRedirectTarget() : null;
206 if ( $redirTitle ) {
207 if ( $redirTitle->getPrefixedDBkey() !== $this->oldTitle->getPrefixedDBkey() &&
208 $redirTitle->getPrefixedDBkey() !== $this->newTitle->getPrefixedDBkey() ) {
209 wfDebug( __METHOD__ . ": redirect points to other page\n" );
210 return false;
211 } else {
212 return true;
214 } else {
215 # Fail safe (not a redirect after all. strange.)
216 wfDebug( __METHOD__ . ": failsafe: database says " . $this->newTitle->getPrefixedDBkey() .
217 " is a redirect, but it doesn't contain a valid redirect.\n" );
218 return false;
223 * @param User $user
224 * @param string $reason
225 * @param bool $createRedirect
226 * @return Status
228 public function move( User $user, $reason, $createRedirect ) {
229 global $wgCategoryCollation;
231 Hooks::run( 'TitleMove', array( $this->oldTitle, $this->newTitle, $user ) );
233 // If it is a file, move it first.
234 // It is done before all other moving stuff is done because it's hard to revert.
235 $dbw = wfGetDB( DB_MASTER );
236 if ( $this->oldTitle->getNamespace() == NS_FILE ) {
237 $file = wfLocalFile( $this->oldTitle );
238 $file->load( File::READ_LATEST );
239 if ( $file->exists() ) {
240 $status = $file->move( $this->newTitle );
241 if ( !$status->isOk() ) {
242 return $status;
245 // Clear RepoGroup process cache
246 RepoGroup::singleton()->clearCache( $this->oldTitle );
247 RepoGroup::singleton()->clearCache( $this->newTitle ); # clear false negative cache
250 $dbw->startAtomic( __METHOD__ );
251 $pageid = $this->oldTitle->getArticleID( Title::GAID_FOR_UPDATE );
252 $protected = $this->oldTitle->isProtected();
254 // Do the actual move
255 $nullRevision = $this->moveToInternal( $user, $this->newTitle, $reason, $createRedirect );
257 // Refresh the sortkey for this row. Be careful to avoid resetting
258 // cl_timestamp, which may disturb time-based lists on some sites.
259 // @todo This block should be killed, it's duplicating code
260 // from LinksUpdate::getCategoryInsertions() and friends.
261 $prefixes = $dbw->select(
262 'categorylinks',
263 array( 'cl_sortkey_prefix', 'cl_to' ),
264 array( 'cl_from' => $pageid ),
265 __METHOD__
267 if ( $this->newTitle->getNamespace() == NS_CATEGORY ) {
268 $type = 'subcat';
269 } elseif ( $this->newTitle->getNamespace() == NS_FILE ) {
270 $type = 'file';
271 } else {
272 $type = 'page';
274 foreach ( $prefixes as $prefixRow ) {
275 $prefix = $prefixRow->cl_sortkey_prefix;
276 $catTo = $prefixRow->cl_to;
277 $dbw->update( 'categorylinks',
278 array(
279 'cl_sortkey' => Collation::singleton()->getSortKey(
280 $this->newTitle->getCategorySortkey( $prefix ) ),
281 'cl_collation' => $wgCategoryCollation,
282 'cl_type' => $type,
283 'cl_timestamp=cl_timestamp' ),
284 array(
285 'cl_from' => $pageid,
286 'cl_to' => $catTo ),
287 __METHOD__
291 $redirid = $this->oldTitle->getArticleID();
293 if ( $protected ) {
294 # Protect the redirect title as the title used to be...
295 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
296 array(
297 'pr_page' => $redirid,
298 'pr_type' => 'pr_type',
299 'pr_level' => 'pr_level',
300 'pr_cascade' => 'pr_cascade',
301 'pr_user' => 'pr_user',
302 'pr_expiry' => 'pr_expiry'
304 array( 'pr_page' => $pageid ),
305 __METHOD__,
306 array( 'IGNORE' )
309 // Build comment for log
310 $comment = wfMessage(
311 'prot_1movedto2',
312 $this->oldTitle->getPrefixedText(),
313 $this->newTitle->getPrefixedText()
314 )->inContentLanguage()->text();
315 if ( $reason ) {
316 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
319 // reread inserted pr_ids for log relation
320 $insertedPrIds = $dbw->select(
321 'page_restrictions',
322 'pr_id',
323 array( 'pr_page' => $redirid ),
324 __METHOD__
326 $logRelationsValues = array();
327 foreach ( $insertedPrIds as $prid ) {
328 $logRelationsValues[] = $prid->pr_id;
331 // Update the protection log
332 $logEntry = new ManualLogEntry( 'protect', 'move_prot' );
333 $logEntry->setTarget( $this->newTitle );
334 $logEntry->setComment( $comment );
335 $logEntry->setPerformer( $user );
336 $logEntry->setParameters( array(
337 '4::oldtitle' => $this->oldTitle->getPrefixedText(),
338 ) );
339 $logEntry->setRelations( array( 'pr_id' => $logRelationsValues ) );
340 $logId = $logEntry->insert();
341 $logEntry->publish( $logId );
344 // Update *_from_namespace fields as needed
345 if ( $this->oldTitle->getNamespace() != $this->newTitle->getNamespace() ) {
346 $dbw->update( 'pagelinks',
347 array( 'pl_from_namespace' => $this->newTitle->getNamespace() ),
348 array( 'pl_from' => $pageid ),
349 __METHOD__
351 $dbw->update( 'templatelinks',
352 array( 'tl_from_namespace' => $this->newTitle->getNamespace() ),
353 array( 'tl_from' => $pageid ),
354 __METHOD__
356 $dbw->update( 'imagelinks',
357 array( 'il_from_namespace' => $this->newTitle->getNamespace() ),
358 array( 'il_from' => $pageid ),
359 __METHOD__
363 # Update watchlists
364 $oldtitle = $this->oldTitle->getDBkey();
365 $newtitle = $this->newTitle->getDBkey();
366 $oldsnamespace = MWNamespace::getSubject( $this->oldTitle->getNamespace() );
367 $newsnamespace = MWNamespace::getSubject( $this->newTitle->getNamespace() );
368 if ( $oldsnamespace != $newsnamespace || $oldtitle != $newtitle ) {
369 WatchedItem::duplicateEntries( $this->oldTitle, $this->newTitle );
372 Hooks::run(
373 'TitleMoveCompleting',
374 array( $this->oldTitle, $this->newTitle,
375 $user, $pageid, $redirid, $reason, $nullRevision )
378 $dbw->endAtomic( __METHOD__ );
380 $params = array(
381 &$this->oldTitle,
382 &$this->newTitle,
383 &$user,
384 $pageid,
385 $redirid,
386 $reason,
387 $nullRevision
389 $dbw->onTransactionIdle( function () use ( $params, $dbw ) {
390 // Keep each single hook handler atomic
391 $dbw->setFlag( DBO_TRX ); // flag is automatically reset by DB layer
392 Hooks::run( 'TitleMoveComplete', $params );
393 } );
395 return Status::newGood();
399 * Move page to a title which is either a redirect to the
400 * source page or nonexistent
402 * @fixme This was basically directly moved from Title, it should be split into smaller functions
403 * @param User $user the User doing the move
404 * @param Title $nt The page to move to, which should be a redirect or nonexistent
405 * @param string $reason The reason for the move
406 * @param bool $createRedirect Whether to leave a redirect at the old title. Does not check
407 * if the user has the suppressredirect right
408 * @return Revision the revision created by the move
409 * @throws MWException
411 private function moveToInternal( User $user, &$nt, $reason = '', $createRedirect = true ) {
412 global $wgContLang;
414 if ( $nt->exists() ) {
415 $moveOverRedirect = true;
416 $logType = 'move_redir';
417 } else {
418 $moveOverRedirect = false;
419 $logType = 'move';
422 if ( $createRedirect ) {
423 if ( $this->oldTitle->getNamespace() == NS_CATEGORY
424 && !wfMessage( 'category-move-redirect-override' )->inContentLanguage()->isDisabled()
426 $redirectContent = new WikitextContent(
427 wfMessage( 'category-move-redirect-override' )
428 ->params( $nt->getPrefixedText() )->inContentLanguage()->plain() );
429 } else {
430 $contentHandler = ContentHandler::getForTitle( $this->oldTitle );
431 $redirectContent = $contentHandler->makeRedirectContent( $nt,
432 wfMessage( 'move-redirect-text' )->inContentLanguage()->plain() );
435 // NOTE: If this page's content model does not support redirects, $redirectContent will be null.
436 } else {
437 $redirectContent = null;
440 // Figure out whether the content model is no longer the default
441 $oldDefault = ContentHandler::getDefaultModelFor( $this->oldTitle );
442 $contentModel = $this->oldTitle->getContentModel();
443 $newDefault = ContentHandler::getDefaultModelFor( $nt );
444 $defaultContentModelChanging = ( $oldDefault !== $newDefault
445 && $oldDefault === $contentModel );
447 // bug 57084: log_page should be the ID of the *moved* page
448 $oldid = $this->oldTitle->getArticleID();
449 $logTitle = clone $this->oldTitle;
451 $logEntry = new ManualLogEntry( 'move', $logType );
452 $logEntry->setPerformer( $user );
453 $logEntry->setTarget( $logTitle );
454 $logEntry->setComment( $reason );
455 $logEntry->setParameters( array(
456 '4::target' => $nt->getPrefixedText(),
457 '5::noredir' => $redirectContent ? '0': '1',
458 ) );
460 $formatter = LogFormatter::newFromEntry( $logEntry );
461 $formatter->setContext( RequestContext::newExtraneousContext( $this->oldTitle ) );
462 $comment = $formatter->getPlainActionText();
463 if ( $reason ) {
464 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
466 # Truncate for whole multibyte characters.
467 $comment = $wgContLang->truncate( $comment, 255 );
469 $dbw = wfGetDB( DB_MASTER );
471 $oldpage = WikiPage::factory( $this->oldTitle );
472 $oldcountable = $oldpage->isCountable();
474 $newpage = WikiPage::factory( $nt );
476 if ( $moveOverRedirect ) {
477 $newid = $nt->getArticleID();
478 $newcontent = $newpage->getContent();
480 # Delete the old redirect. We don't save it to history since
481 # by definition if we've got here it's rather uninteresting.
482 # We have to remove it so that the next step doesn't trigger
483 # a conflict on the unique namespace+title index...
484 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__ );
486 $newpage->doDeleteUpdates( $newid, $newcontent );
489 # Save a null revision in the page's history notifying of the move
490 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true, $user );
491 if ( !is_object( $nullRevision ) ) {
492 throw new MWException( 'No valid null revision produced in ' . __METHOD__ );
495 $nullRevision->insertOn( $dbw );
497 # Change the name of the target page:
498 $dbw->update( 'page',
499 /* SET */ array(
500 'page_namespace' => $nt->getNamespace(),
501 'page_title' => $nt->getDBkey(),
503 /* WHERE */ array( 'page_id' => $oldid ),
504 __METHOD__
507 // clean up the old title before reset article id - bug 45348
508 if ( !$redirectContent ) {
509 WikiPage::onArticleDelete( $this->oldTitle );
512 $this->oldTitle->resetArticleID( 0 ); // 0 == non existing
513 $nt->resetArticleID( $oldid );
514 $newpage->loadPageData( WikiPage::READ_LOCKING ); // bug 46397
516 $newpage->updateRevisionOn( $dbw, $nullRevision );
518 Hooks::run( 'NewRevisionFromEditComplete',
519 array( $newpage, $nullRevision, $nullRevision->getParentId(), $user ) );
521 $newpage->doEditUpdates( $nullRevision, $user,
522 array( 'changed' => false, 'moved' => true, 'oldcountable' => $oldcountable ) );
524 // If the default content model changes, we need to populate rev_content_model
525 if ( $defaultContentModelChanging ) {
526 $dbw->update(
527 'revision',
528 array( 'rev_content_model' => $contentModel ),
529 array( 'rev_page' => $nt->getArticleID(), 'rev_content_model IS NULL' ),
530 __METHOD__
534 if ( !$moveOverRedirect ) {
535 WikiPage::onArticleCreate( $nt );
538 # Recreate the redirect, this time in the other direction.
539 if ( $redirectContent ) {
540 $redirectArticle = WikiPage::factory( $this->oldTitle );
541 $redirectArticle->loadFromRow( false, WikiPage::READ_LOCKING ); // bug 46397
542 $newid = $redirectArticle->insertOn( $dbw );
543 if ( $newid ) { // sanity
544 $this->oldTitle->resetArticleID( $newid );
545 $redirectRevision = new Revision( array(
546 'title' => $this->oldTitle, // for determining the default content model
547 'page' => $newid,
548 'user_text' => $user->getName(),
549 'user' => $user->getId(),
550 'comment' => $comment,
551 'content' => $redirectContent ) );
552 $redirectRevision->insertOn( $dbw );
553 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
555 Hooks::run( 'NewRevisionFromEditComplete',
556 array( $redirectArticle, $redirectRevision, false, $user ) );
558 $redirectArticle->doEditUpdates( $redirectRevision, $user, array( 'created' => true ) );
562 # Log the move
563 $logid = $logEntry->insert();
564 $logEntry->publish( $logid );
566 return $nullRevision;