Merge "Delete always true condition"
[lhc/web/wiklou.git] / includes / MovePage.php
1 <?php
2
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.
8 *
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.
13 *
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
18 *
19 * @file
20 */
21
22 use MediaWiki\MediaWikiServices;
23 use MediaWiki\Revision\SlotRecord;
24
25 /**
26 * Handles the backend logic of moving a page from one title
27 * to another.
28 *
29 * @since 1.24
30 */
31 class MovePage {
32
33 /**
34 * @var Title
35 */
36 protected $oldTitle;
37
38 /**
39 * @var Title
40 */
41 protected $newTitle;
42
43 public function __construct( Title $oldTitle, Title $newTitle ) {
44 $this->oldTitle = $oldTitle;
45 $this->newTitle = $newTitle;
46 }
47
48 public function checkPermissions( User $user, $reason ) {
49 $status = new Status();
50
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 )
56 );
57
58 // Convert into a Status object
59 if ( $errors ) {
60 foreach ( $errors as $error ) {
61 $status->fatal( ...$error );
62 }
63 }
64
65 if ( EditPage::matchSummarySpamRegex( $reason ) !== false ) {
66 // This is kind of lame, won't display nice
67 $status->fatal( 'spamprotectiontext' );
68 }
69
70 $tp = $this->newTitle->getTitleProtection();
71 if ( $tp !== false && !$user->isAllowed( $tp['permission'] ) ) {
72 $status->fatal( 'cantmove-titleprotected' );
73 }
74
75 Hooks::run( 'MovePageCheckPermissions',
76 [ $this->oldTitle, $this->newTitle, $user, $reason, $status ]
77 );
78
79 return $status;
80 }
81
82 /**
83 * Does various sanity checks that the move is
84 * valid. Only things based on the two titles
85 * should be checked here.
86 *
87 * @return Status
88 */
89 public function isValidMove() {
90 global $wgContentHandlerUseDB;
91 $status = new Status();
92
93 if ( $this->oldTitle->equals( $this->newTitle ) ) {
94 $status->fatal( 'selfmove' );
95 }
96 if ( !$this->oldTitle->isMovable() ) {
97 $status->fatal( 'immobile-source-namespace', $this->oldTitle->getNsText() );
98 }
99 if ( $this->newTitle->isExternal() ) {
100 $status->fatal( 'immobile-target-namespace-iw' );
101 }
102 if ( !$this->newTitle->isMovable() ) {
103 $status->fatal( 'immobile-target-namespace', $this->newTitle->getNsText() );
104 }
105
106 $oldid = $this->oldTitle->getArticleID();
107
108 if ( strlen( $this->newTitle->getDBkey() ) < 1 ) {
109 $status->fatal( 'articleexists' );
110 }
111 if (
112 ( $this->oldTitle->getDBkey() == '' ) ||
113 ( !$oldid ) ||
114 ( $this->newTitle->getDBkey() == '' )
115 ) {
116 $status->fatal( 'badarticleerror' );
117 }
118
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' );
124 }
125
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
130 $status->fatal(
131 'bad-target-model',
132 ContentHandler::getLocalizedName( $this->oldTitle->getContentModel() ),
133 ContentHandler::getLocalizedName( $this->newTitle->getContentModel() )
134 );
135 } elseif (
136 !ContentHandler::getForTitle( $this->oldTitle )->canBeUsedOn( $this->newTitle )
137 ) {
138 $status->fatal(
139 'content-not-allowed-here',
140 ContentHandler::getLocalizedName( $this->oldTitle->getContentModel() ),
141 $this->newTitle->getPrefixedText(),
142 SlotRecord::MAIN
143 );
144 }
145
146 // Image-specific checks
147 if ( $this->oldTitle->inNamespace( NS_FILE ) ) {
148 $status->merge( $this->isValidFileMove() );
149 }
150
151 if ( $this->newTitle->inNamespace( NS_FILE ) && !$this->oldTitle->inNamespace( NS_FILE ) ) {
152 $status->fatal( 'nonfile-cannot-move-to-file' );
153 }
154
155 // Hook for extensions to say a title can't be moved for technical reasons
156 Hooks::run( 'MovePageIsValidMove', [ $this->oldTitle, $this->newTitle, $status ] );
157
158 return $status;
159 }
160
161 /**
162 * Sanity checks for when a file is being moved
163 *
164 * @return Status
165 */
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' );
173 }
174 if ( !File::checkExtensionCompatibility( $file, $this->newTitle->getDBkey() ) ) {
175 $status->fatal( 'imagetypemismatch' );
176 }
177 }
178
179 if ( !$this->newTitle->inNamespace( NS_FILE ) ) {
180 $status->fatal( 'imagenocrossnamespace' );
181 }
182
183 return $status;
184 }
185
186 /**
187 * Checks if $this can be moved to a given Title
188 * - Selects for update, so don't call it unless you mean business
189 *
190 * @since 1.25
191 * @return bool
192 */
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" );
200 return false;
201 }
202 }
203 # Is it a redirect with no history?
204 if ( !$this->newTitle->isSingleRevRedirect() ) {
205 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
206 return false;
207 }
208 # Get the article text
209 $rev = Revision::newFromTitle( $this->newTitle, false, Revision::READ_LATEST );
210 if ( !is_object( $rev ) ) {
211 return false;
212 }
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;
217
218 if ( $redirTitle ) {
219 if ( $redirTitle->getPrefixedDBkey() !== $this->oldTitle->getPrefixedDBkey() &&
220 $redirTitle->getPrefixedDBkey() !== $this->newTitle->getPrefixedDBkey() ) {
221 wfDebug( __METHOD__ . ": redirect points to other page\n" );
222 return false;
223 } else {
224 return true;
225 }
226 } else {
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" );
230 return false;
231 }
232 }
233
234 /**
235 * @param User $user
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
240 * @return Status
241 */
242 public function move( User $user, $reason, $createRedirect, array $changeTags = [] ) {
243 global $wgCategoryCollation;
244
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
249 return $status;
250 }
251
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() ) {
261 return $status;
262 }
263 }
264 // Clear RepoGroup process cache
265 RepoGroup::singleton()->clearCache( $this->oldTitle );
266 RepoGroup::singleton()->clearCache( $this->newTitle ); # clear false negative cache
267 }
268
269 $dbw->startAtomic( __METHOD__ );
270
271 Hooks::run( 'TitleMoveStarting', [ $this->oldTitle, $this->newTitle, $user ] );
272
273 $pageid = $this->oldTitle->getArticleID( Title::GAID_FOR_UPDATE );
274 $protected = $this->oldTitle->isProtected();
275
276 // Do the actual move; if this fails, it will throw an MWException(!)
277 $nullRevision = $this->moveToInternal( $user, $this->newTitle, $reason, $createRedirect,
278 $changeTags );
279
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(
285 'categorylinks',
286 [ 'cl_sortkey_prefix', 'cl_to' ],
287 [ 'cl_from' => $pageid ],
288 __METHOD__
289 );
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',
295 [
296 'cl_sortkey' => Collation::singleton()->getSortKey(
297 $this->newTitle->getCategorySortkey( $prefix ) ),
298 'cl_collation' => $wgCategoryCollation,
299 'cl_type' => $type,
300 'cl_timestamp=cl_timestamp' ],
301 [
302 'cl_from' => $pageid,
303 'cl_to' => $catTo ],
304 __METHOD__
305 );
306 }
307
308 $redirid = $this->oldTitle->getArticleID();
309
310 if ( $protected ) {
311 # Protect the redirect title as the title used to be...
312 $res = $dbw->select(
313 'page_restrictions',
314 [ 'pr_type', 'pr_level', 'pr_cascade', 'pr_user', 'pr_expiry' ],
315 [ 'pr_page' => $pageid ],
316 __METHOD__,
317 'FOR UPDATE'
318 );
319 $rowsInsert = [];
320 foreach ( $res as $row ) {
321 $rowsInsert[] = [
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
328 ];
329 }
330 $dbw->insert( 'page_restrictions', $rowsInsert, __METHOD__, [ 'IGNORE' ] );
331
332 // Build comment for log
333 $comment = wfMessage(
334 'prot_1movedto2',
335 $this->oldTitle->getPrefixedText(),
336 $this->newTitle->getPrefixedText()
337 )->inContentLanguage()->text();
338 if ( $reason ) {
339 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
340 }
341
342 // reread inserted pr_ids for log relation
343 $insertedPrIds = $dbw->select(
344 'page_restrictions',
345 'pr_id',
346 [ 'pr_page' => $redirid ],
347 __METHOD__
348 );
349 $logRelationsValues = [];
350 foreach ( $insertedPrIds as $prid ) {
351 $logRelationsValues[] = $prid->pr_id;
352 }
353
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(),
361 ] );
362 $logEntry->setRelations( [ 'pr_id' => $logRelationsValues ] );
363 $logEntry->setTags( $changeTags );
364 $logId = $logEntry->insert();
365 $logEntry->publish( $logId );
366 }
367
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 ],
373 __METHOD__
374 );
375 $dbw->update( 'templatelinks',
376 [ 'tl_from_namespace' => $this->newTitle->getNamespace() ],
377 [ 'tl_from' => $pageid ],
378 __METHOD__
379 );
380 $dbw->update( 'imagelinks',
381 [ 'il_from_namespace' => $this->newTitle->getNamespace() ],
382 [ 'il_from' => $pageid ],
383 __METHOD__
384 );
385 }
386
387 # Update watchlists
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 );
395 }
396
397 Hooks::run(
398 'TitleMoveCompleting',
399 [ $this->oldTitle, $this->newTitle,
400 $user, $pageid, $redirid, $reason, $nullRevision ]
401 );
402
403 $dbw->endAtomic( __METHOD__ );
404
405 $params = [
406 &$this->oldTitle,
407 &$this->newTitle,
408 &$user,
409 $pageid,
410 $redirid,
411 $reason,
412 $nullRevision
413 ];
414 // Keep each single hook handler atomic
415 DeferredUpdates::addUpdate(
416 new AtomicSectionUpdate(
417 $dbw,
418 __METHOD__,
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 );
423 }
424 )
425 );
426
427 return Status::newGood();
428 }
429
430 /**
431 * Move page to a title which is either a redirect to the
432 * source page or nonexistent
433 *
434 * @todo This was basically directly moved from Title, it should be split into
435 * smaller functions
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
444 */
445 private function moveToInternal( User $user, &$nt, $reason = '', $createRedirect = true,
446 array $changeTags = []
447 ) {
448 if ( $nt->exists() ) {
449 $moveOverRedirect = true;
450 $logType = 'move_redir';
451 } else {
452 $moveOverRedirect = false;
453 $logType = 'move';
454 }
455
456 if ( $moveOverRedirect ) {
457 $overwriteMessage = wfMessage(
458 'delete_and_move_reason',
459 $this->oldTitle->getPrefixedText()
460 )->inContentLanguage()->text();
461 $newpage = WikiPage::factory( $nt );
462 $errs = [];
463 $status = $newpage->doDeleteArticleReal(
464 $overwriteMessage,
465 /* $suppress */ false,
466 $nt->getArticleID(),
467 /* $commit */ false,
468 $errs,
469 $user,
470 $changeTags,
471 'delete_redir'
472 );
473
474 if ( !$status->isGood() ) {
475 throw new MWException( 'Failed to delete page-move revision: ' . $status );
476 }
477
478 $nt->resetArticleID( false );
479 }
480
481 if ( $createRedirect ) {
482 if ( $this->oldTitle->getNamespace() == NS_CATEGORY
483 && !wfMessage( 'category-move-redirect-override' )->inContentLanguage()->isDisabled()
484 ) {
485 $redirectContent = new WikitextContent(
486 wfMessage( 'category-move-redirect-override' )
487 ->params( $nt->getPrefixedText() )->inContentLanguage()->plain() );
488 } else {
489 $contentHandler = ContentHandler::getForTitle( $this->oldTitle );
490 $redirectContent = $contentHandler->makeRedirectContent( $nt,
491 wfMessage( 'move-redirect-text' )->inContentLanguage()->plain() );
492 }
493
494 // NOTE: If this page's content model does not support redirects, $redirectContent will be null.
495 } else {
496 $redirectContent = null;
497 }
498
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 );
505
506 // T59084: log_page should be the ID of the *moved* page
507 $oldid = $this->oldTitle->getArticleID();
508 $logTitle = clone $this->oldTitle;
509
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',
517 ] );
518
519 $formatter = LogFormatter::newFromEntry( $logEntry );
520 $formatter->setContext( RequestContext::newExtraneousContext( $this->oldTitle ) );
521 $comment = $formatter->getPlainActionText();
522 if ( $reason ) {
523 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
524 }
525
526 $dbw = wfGetDB( DB_MASTER );
527
528 $oldpage = WikiPage::factory( $this->oldTitle );
529 $oldcountable = $oldpage->isCountable();
530
531 $newpage = WikiPage::factory( $nt );
532
533 # Change the name of the target page:
534 $dbw->update( 'page',
535 /* SET */ [
536 'page_namespace' => $nt->getNamespace(),
537 'page_title' => $nt->getDBkey(),
538 ],
539 /* WHERE */ [ 'page_id' => $oldid ],
540 __METHOD__
541 );
542
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() );
548 }
549
550 $nullRevId = $nullRevision->insertOn( $dbw );
551 $logEntry->setAssociatedRevId( $nullRevId );
552
553 /**
554 * T163966
555 * Increment user_editcount during page moves
556 * Moved from SpecialMovepage.php per T195550
557 */
558 $user->incEditCount();
559
560 if ( !$redirectContent ) {
561 // Clean up the old title *before* reset article id - T47348
562 WikiPage::onArticleDelete( $this->oldTitle );
563 }
564
565 $this->oldTitle->resetArticleID( 0 ); // 0 == non existing
566 $nt->resetArticleID( $oldid );
567 $newpage->loadPageData( WikiPage::READ_LOCKING ); // T48397
568
569 $newpage->updateRevisionOn( $dbw, $nullRevision );
570
571 Hooks::run( 'NewRevisionFromEditComplete',
572 [ $newpage, $nullRevision, $nullRevision->getParentId(), $user ] );
573
574 $newpage->doEditUpdates( $nullRevision, $user,
575 [ 'changed' => false, 'moved' => true, 'oldcountable' => $oldcountable ] );
576
577 // If the default content model changes, we need to populate rev_content_model
578 if ( $defaultContentModelChanging ) {
579 $dbw->update(
580 'revision',
581 [ 'rev_content_model' => $contentModel ],
582 [ 'rev_page' => $nt->getArticleID(), 'rev_content_model IS NULL' ],
583 __METHOD__
584 );
585 }
586
587 WikiPage::onArticleCreate( $nt );
588
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
598 'page' => $newid,
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 );
605
606 Hooks::run( 'NewRevisionFromEditComplete',
607 [ $redirectArticle, $redirectRevision, false, $user ] );
608
609 $redirectArticle->doEditUpdates( $redirectRevision, $user, [ 'created' => true ] );
610
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';
615 }
616 ChangeTags::addTags( $redirectTags, null, $redirectRevId, null );
617 }
618 }
619
620 # Log the move
621 $logid = $logEntry->insert();
622
623 $logEntry->setTags( $changeTags );
624 $logEntry->publish( $logid );
625
626 return $nullRevision;
627 }
628 }