Merge "DatabaseMssql: Don't duplicate body of makeList()"
[mediawiki.git] / includes / MovePage.php
blob065e18985784fca78756de82ba1595d982283386
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 # The move is allowed only if (1) the target doesn't exist, or
68 # (2) the target is a redirect to the source, and has no history
69 # (so we can undo bad moves right after they're done).
71 if ( $this->newTitle->getArticleID() ) { # Target exists; check for validity
72 if ( !$this->isValidMoveTarget() ) {
73 $status->fatal( 'articleexists' );
75 } else {
76 $tp = $this->newTitle->getTitleProtection();
77 if ( $tp !== false ) {
78 if ( !$user->isAllowed( $tp['permission'] ) ) {
79 $status->fatal( 'cantmove-titleprotected' );
84 Hooks::run( 'MovePageCheckPermissions',
85 array( $this->oldTitle, $this->newTitle, $user, $reason, $status )
88 return $status;
91 /**
92 * Does various sanity checks that the move is
93 * valid. Only things based on the two titles
94 * should be checked here.
96 * @return Status
98 public function isValidMove() {
99 global $wgContentHandlerUseDB;
100 $status = new Status();
102 if ( $this->oldTitle->equals( $this->newTitle ) ) {
103 $status->fatal( 'selfmove' );
105 if ( !$this->oldTitle->isMovable() ) {
106 $status->fatal( 'immobile-source-namespace', $this->oldTitle->getNsText() );
108 if ( $this->newTitle->isExternal() ) {
109 $status->fatal( 'immobile-target-namespace-iw' );
111 if ( !$this->newTitle->isMovable() ) {
112 $status->fatal( 'immobile-target-namespace', $this->newTitle->getNsText() );
115 $oldid = $this->oldTitle->getArticleID();
117 if ( strlen( $this->newTitle->getDBkey() ) < 1 ) {
118 $status->fatal( 'articleexists' );
120 if (
121 ( $this->oldTitle->getDBkey() == '' ) ||
122 ( !$oldid ) ||
123 ( $this->newTitle->getDBkey() == '' )
125 $status->fatal( 'badarticleerror' );
128 // Content model checks
129 if ( !$wgContentHandlerUseDB &&
130 $this->oldTitle->getContentModel() !== $this->newTitle->getContentModel() ) {
131 // can't move a page if that would change the page's content model
132 $status->fatal(
133 'bad-target-model',
134 ContentHandler::getLocalizedName( $this->oldTitle->getContentModel() ),
135 ContentHandler::getLocalizedName( $this->newTitle->getContentModel() )
139 // Image-specific checks
140 if ( $this->oldTitle->inNamespace( NS_FILE ) ) {
141 $status->merge( $this->isValidFileMove() );
144 if ( $this->newTitle->inNamespace( NS_FILE ) && !$this->oldTitle->inNamespace( NS_FILE ) ) {
145 $status->fatal( 'nonfile-cannot-move-to-file' );
148 // Hook for extensions to say a title can't be moved for technical reasons
149 Hooks::run( 'MovePageIsValidMove', array( $this->oldTitle, $this->newTitle, $status ) );
151 return $status;
155 * Sanity checks for when a file is being moved
157 * @return Status
159 protected function isValidFileMove() {
160 $status = new Status();
161 $file = wfLocalFile( $this->oldTitle );
162 if ( $file->exists() ) {
163 if ( $this->newTitle->getText() != wfStripIllegalFilenameChars( $this->newTitle->getText() ) ) {
164 $status->fatal( 'imageinvalidfilename' );
166 if ( !File::checkExtensionCompatibility( $file, $this->newTitle->getDBkey() ) ) {
167 $status->fatal( 'imagetypemismatch' );
171 if ( !$this->newTitle->inNamespace( NS_FILE ) ) {
172 $status->fatal( 'imagenocrossnamespace' );
175 return $status;
179 * Checks if $this can be moved to a given Title
180 * - Selects for update, so don't call it unless you mean business
182 * @since 1.25
183 * @return bool
185 protected function isValidMoveTarget() {
186 # Is it an existing file?
187 if ( $this->newTitle->inNamespace( NS_FILE ) ) {
188 $file = wfLocalFile( $this->newTitle );
189 if ( $file->exists() ) {
190 wfDebug( __METHOD__ . ": file exists\n" );
191 return false;
194 # Is it a redirect with no history?
195 if ( !$this->newTitle->isSingleRevRedirect() ) {
196 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
197 return false;
199 # Get the article text
200 $rev = Revision::newFromTitle( $this->newTitle, false, Revision::READ_LATEST );
201 if ( !is_object( $rev ) ) {
202 return false;
204 $content = $rev->getContent();
205 # Does the redirect point to the source?
206 # Or is it a broken self-redirect, usually caused by namespace collisions?
207 $redirTitle = $content ? $content->getRedirectTarget() : null;
209 if ( $redirTitle ) {
210 if ( $redirTitle->getPrefixedDBkey() !== $this->oldTitle->getPrefixedDBkey() &&
211 $redirTitle->getPrefixedDBkey() !== $this->newTitle->getPrefixedDBkey() ) {
212 wfDebug( __METHOD__ . ": redirect points to other page\n" );
213 return false;
214 } else {
215 return true;
217 } else {
218 # Fail safe (not a redirect after all. strange.)
219 wfDebug( __METHOD__ . ": failsafe: database says " . $this->newTitle->getPrefixedDBkey() .
220 " is a redirect, but it doesn't contain a valid redirect.\n" );
221 return false;
226 * @param User $user
227 * @param string $reason
228 * @param bool $createRedirect
229 * @return Status
231 public function move( User $user, $reason, $createRedirect ) {
232 global $wgCategoryCollation;
234 Hooks::run( 'TitleMove', array( $this->oldTitle, $this->newTitle, $user ) );
236 // If it is a file, move it first.
237 // It is done before all other moving stuff is done because it's hard to revert.
238 $dbw = wfGetDB( DB_MASTER );
239 if ( $this->oldTitle->getNamespace() == NS_FILE ) {
240 $file = wfLocalFile( $this->oldTitle );
241 if ( $file->exists() ) {
242 $status = $file->move( $this->newTitle );
243 if ( !$status->isOk() ) {
244 return $status;
247 // Clear RepoGroup process cache
248 RepoGroup::singleton()->clearCache( $this->oldTitle );
249 RepoGroup::singleton()->clearCache( $this->newTitle ); # clear false negative cache
252 $dbw->begin( __METHOD__ ); # If $file was a LocalFile, its transaction would have closed our own.
253 $pageid = $this->oldTitle->getArticleID( Title::GAID_FOR_UPDATE );
254 $protected = $this->oldTitle->isProtected();
256 // Do the actual move
257 $this->moveToInternal( $user, $this->newTitle, $reason, $createRedirect );
259 // Refresh the sortkey for this row. Be careful to avoid resetting
260 // cl_timestamp, which may disturb time-based lists on some sites.
261 // @todo This block should be killed, it's duplicating code
262 // from LinksUpdate::getCategoryInsertions() and friends.
263 $prefixes = $dbw->select(
264 'categorylinks',
265 array( 'cl_sortkey_prefix', 'cl_to' ),
266 array( 'cl_from' => $pageid ),
267 __METHOD__
269 if ( $this->newTitle->getNamespace() == NS_CATEGORY ) {
270 $type = 'subcat';
271 } elseif ( $this->newTitle->getNamespace() == NS_FILE ) {
272 $type = 'file';
273 } else {
274 $type = 'page';
276 foreach ( $prefixes as $prefixRow ) {
277 $prefix = $prefixRow->cl_sortkey_prefix;
278 $catTo = $prefixRow->cl_to;
279 $dbw->update( 'categorylinks',
280 array(
281 'cl_sortkey' => Collation::singleton()->getSortKey(
282 $this->newTitle->getCategorySortkey( $prefix ) ),
283 'cl_collation' => $wgCategoryCollation,
284 'cl_type' => $type,
285 'cl_timestamp=cl_timestamp' ),
286 array(
287 'cl_from' => $pageid,
288 'cl_to' => $catTo ),
289 __METHOD__
293 $redirid = $this->oldTitle->getArticleID();
295 if ( $protected ) {
296 # Protect the redirect title as the title used to be...
297 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
298 array(
299 'pr_page' => $redirid,
300 'pr_type' => 'pr_type',
301 'pr_level' => 'pr_level',
302 'pr_cascade' => 'pr_cascade',
303 'pr_user' => 'pr_user',
304 'pr_expiry' => 'pr_expiry'
306 array( 'pr_page' => $pageid ),
307 __METHOD__,
308 array( 'IGNORE' )
310 # Update the protection log
311 $log = new LogPage( 'protect' );
312 $comment = wfMessage(
313 'prot_1movedto2',
314 $this->oldTitle->getPrefixedText(),
315 $this->newTitle->getPrefixedText()
316 )->inContentLanguage()->text();
317 if ( $reason ) {
318 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
320 // @todo FIXME: $params?
321 $logId = $log->addEntry(
322 'move_prot',
323 $this->newTitle,
324 $comment,
325 array( $this->oldTitle->getPrefixedText() ),
326 $user
329 // reread inserted pr_ids for log relation
330 $insertedPrIds = $dbw->select(
331 'page_restrictions',
332 'pr_id',
333 array( 'pr_page' => $redirid ),
334 __METHOD__
336 $logRelationsValues = array();
337 foreach ( $insertedPrIds as $prid ) {
338 $logRelationsValues[] = $prid->pr_id;
340 $log->addRelations( 'pr_id', $logRelationsValues, $logId );
343 // Update *_from_namespace fields as needed
344 if ( $this->oldTitle->getNamespace() != $this->newTitle->getNamespace() ) {
345 $dbw->update( 'pagelinks',
346 array( 'pl_from_namespace' => $this->newTitle->getNamespace() ),
347 array( 'pl_from' => $pageid ),
348 __METHOD__
350 $dbw->update( 'templatelinks',
351 array( 'tl_from_namespace' => $this->newTitle->getNamespace() ),
352 array( 'tl_from' => $pageid ),
353 __METHOD__
355 $dbw->update( 'imagelinks',
356 array( 'il_from_namespace' => $this->newTitle->getNamespace() ),
357 array( 'il_from' => $pageid ),
358 __METHOD__
362 # Update watchlists
363 $oldtitle = $this->oldTitle->getDBkey();
364 $newtitle = $this->newTitle->getDBkey();
365 $oldsnamespace = MWNamespace::getSubject( $this->oldTitle->getNamespace() );
366 $newsnamespace = MWNamespace::getSubject( $this->newTitle->getNamespace() );
367 if ( $oldsnamespace != $newsnamespace || $oldtitle != $newtitle ) {
368 WatchedItem::duplicateEntries( $this->oldTitle, $this->newTitle );
371 $dbw->commit( __METHOD__ );
373 Hooks::run( 'TitleMoveComplete', array( &$this->oldTitle, &$this->newTitle, &$user, $pageid, $redirid, $reason ) );
374 return Status::newGood();
378 * Move page to a title which is either a redirect to the
379 * source page or nonexistent
381 * @fixme This was basically directly moved from Title, it should be split into smaller functions
382 * @param User $user the User doing the move
383 * @param Title $nt The page to move to, which should be a redirect or nonexistent
384 * @param string $reason The reason for the move
385 * @param bool $createRedirect Whether to leave a redirect at the old title. Does not check
386 * if the user has the suppressredirect right
387 * @throws MWException
389 private function moveToInternal( User $user, &$nt, $reason = '', $createRedirect = true ) {
390 global $wgContLang;
392 if ( $nt->exists() ) {
393 $moveOverRedirect = true;
394 $logType = 'move_redir';
395 } else {
396 $moveOverRedirect = false;
397 $logType = 'move';
400 if ( $createRedirect ) {
401 if ( $this->oldTitle->getNamespace() == NS_CATEGORY
402 && !wfMessage( 'category-move-redirect-override' )->inContentLanguage()->isDisabled()
404 $redirectContent = new WikitextContent(
405 wfMessage( 'category-move-redirect-override' )
406 ->params( $nt->getPrefixedText() )->inContentLanguage()->plain() );
407 } else {
408 $contentHandler = ContentHandler::getForTitle( $this->oldTitle );
409 $redirectContent = $contentHandler->makeRedirectContent( $nt,
410 wfMessage( 'move-redirect-text' )->inContentLanguage()->plain() );
413 // NOTE: If this page's content model does not support redirects, $redirectContent will be null.
414 } else {
415 $redirectContent = null;
418 // bug 57084: log_page should be the ID of the *moved* page
419 $oldid = $this->oldTitle->getArticleID();
420 $logTitle = clone $this->oldTitle;
422 $logEntry = new ManualLogEntry( 'move', $logType );
423 $logEntry->setPerformer( $user );
424 $logEntry->setTarget( $logTitle );
425 $logEntry->setComment( $reason );
426 $logEntry->setParameters( array(
427 '4::target' => $nt->getPrefixedText(),
428 '5::noredir' => $redirectContent ? '0': '1',
429 ) );
431 $formatter = LogFormatter::newFromEntry( $logEntry );
432 $formatter->setContext( RequestContext::newExtraneousContext( $this->oldTitle ) );
433 $comment = $formatter->getPlainActionText();
434 if ( $reason ) {
435 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
437 # Truncate for whole multibyte characters.
438 $comment = $wgContLang->truncate( $comment, 255 );
440 $dbw = wfGetDB( DB_MASTER );
442 $oldpage = WikiPage::factory( $this->oldTitle );
443 $oldcountable = $oldpage->isCountable();
445 $newpage = WikiPage::factory( $nt );
447 if ( $moveOverRedirect ) {
448 $newid = $nt->getArticleID();
449 $newcontent = $newpage->getContent();
451 # Delete the old redirect. We don't save it to history since
452 # by definition if we've got here it's rather uninteresting.
453 # We have to remove it so that the next step doesn't trigger
454 # a conflict on the unique namespace+title index...
455 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__ );
457 $newpage->doDeleteUpdates( $newid, $newcontent );
460 # Save a null revision in the page's history notifying of the move
461 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true, $user );
462 if ( !is_object( $nullRevision ) ) {
463 throw new MWException( 'No valid null revision produced in ' . __METHOD__ );
466 $nullRevision->insertOn( $dbw );
468 # Change the name of the target page:
469 $dbw->update( 'page',
470 /* SET */ array(
471 'page_namespace' => $nt->getNamespace(),
472 'page_title' => $nt->getDBkey(),
474 /* WHERE */ array( 'page_id' => $oldid ),
475 __METHOD__
478 // clean up the old title before reset article id - bug 45348
479 if ( !$redirectContent ) {
480 WikiPage::onArticleDelete( $this->oldTitle );
483 $this->oldTitle->resetArticleID( 0 ); // 0 == non existing
484 $nt->resetArticleID( $oldid );
485 $newpage->loadPageData( WikiPage::READ_LOCKING ); // bug 46397
487 $newpage->updateRevisionOn( $dbw, $nullRevision );
489 Hooks::run( 'NewRevisionFromEditComplete',
490 array( $newpage, $nullRevision, $nullRevision->getParentId(), $user ) );
492 $newpage->doEditUpdates( $nullRevision, $user,
493 array( 'changed' => false, 'moved' => true, 'oldcountable' => $oldcountable ) );
495 if ( !$moveOverRedirect ) {
496 WikiPage::onArticleCreate( $nt );
499 # Recreate the redirect, this time in the other direction.
500 if ( $redirectContent ) {
501 $redirectArticle = WikiPage::factory( $this->oldTitle );
502 $redirectArticle->loadFromRow( false, WikiPage::READ_LOCKING ); // bug 46397
503 $newid = $redirectArticle->insertOn( $dbw );
504 if ( $newid ) { // sanity
505 $this->oldTitle->resetArticleID( $newid );
506 $redirectRevision = new Revision( array(
507 'title' => $this->oldTitle, // for determining the default content model
508 'page' => $newid,
509 'user_text' => $user->getName(),
510 'user' => $user->getId(),
511 'comment' => $comment,
512 'content' => $redirectContent ) );
513 $redirectRevision->insertOn( $dbw );
514 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
516 Hooks::run( 'NewRevisionFromEditComplete',
517 array( $redirectArticle, $redirectRevision, false, $user ) );
519 $redirectArticle->doEditUpdates( $redirectRevision, $user, array( 'created' => true ) );
523 # Log the move
524 $logid = $logEntry->insert();
525 $logEntry->publish( $logid );