Merge "Hard deprecate codepaths where tidy is disabled"
[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
24 /**
25 * Handles the backend logic of moving a page from one title
26 * to another.
27 *
28 * @since 1.24
29 */
30 class MovePage {
31
32 /**
33 * @var Title
34 */
35 protected $oldTitle;
36
37 /**
38 * @var Title
39 */
40 protected $newTitle;
41
42 public function __construct( Title $oldTitle, Title $newTitle ) {
43 $this->oldTitle = $oldTitle;
44 $this->newTitle = $newTitle;
45 }
46
47 public function checkPermissions( User $user, $reason ) {
48 $status = new Status();
49
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 )
55 );
56
57 // Convert into a Status object
58 if ( $errors ) {
59 foreach ( $errors as $error ) {
60 $status->fatal( ...$error );
61 }
62 }
63
64 if ( EditPage::matchSummarySpamRegex( $reason ) !== false ) {
65 // This is kind of lame, won't display nice
66 $status->fatal( 'spamprotectiontext' );
67 }
68
69 $tp = $this->newTitle->getTitleProtection();
70 if ( $tp !== false && !$user->isAllowed( $tp['permission'] ) ) {
71 $status->fatal( 'cantmove-titleprotected' );
72 }
73
74 Hooks::run( 'MovePageCheckPermissions',
75 [ $this->oldTitle, $this->newTitle, $user, $reason, $status ]
76 );
77
78 return $status;
79 }
80
81 /**
82 * Does various sanity checks that the move is
83 * valid. Only things based on the two titles
84 * should be checked here.
85 *
86 * @return Status
87 */
88 public function isValidMove() {
89 global $wgContentHandlerUseDB;
90 $status = new Status();
91
92 if ( $this->oldTitle->equals( $this->newTitle ) ) {
93 $status->fatal( 'selfmove' );
94 }
95 if ( !$this->oldTitle->isMovable() ) {
96 $status->fatal( 'immobile-source-namespace', $this->oldTitle->getNsText() );
97 }
98 if ( $this->newTitle->isExternal() ) {
99 $status->fatal( 'immobile-target-namespace-iw' );
100 }
101 if ( !$this->newTitle->isMovable() ) {
102 $status->fatal( 'immobile-target-namespace', $this->newTitle->getNsText() );
103 }
104
105 $oldid = $this->oldTitle->getArticleID();
106
107 if ( strlen( $this->newTitle->getDBkey() ) < 1 ) {
108 $status->fatal( 'articleexists' );
109 }
110 if (
111 ( $this->oldTitle->getDBkey() == '' ) ||
112 ( !$oldid ) ||
113 ( $this->newTitle->getDBkey() == '' )
114 ) {
115 $status->fatal( 'badarticleerror' );
116 }
117
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' );
123 }
124
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
129 $status->fatal(
130 'bad-target-model',
131 ContentHandler::getLocalizedName( $this->oldTitle->getContentModel() ),
132 ContentHandler::getLocalizedName( $this->newTitle->getContentModel() )
133 );
134 } elseif (
135 !ContentHandler::getForTitle( $this->oldTitle )->canBeUsedOn( $this->newTitle )
136 ) {
137 $status->fatal(
138 'content-not-allowed-here',
139 ContentHandler::getLocalizedName( $this->oldTitle->getContentModel() ),
140 $this->newTitle->getPrefixedText()
141 );
142 }
143
144 // Image-specific checks
145 if ( $this->oldTitle->inNamespace( NS_FILE ) ) {
146 $status->merge( $this->isValidFileMove() );
147 }
148
149 if ( $this->newTitle->inNamespace( NS_FILE ) && !$this->oldTitle->inNamespace( NS_FILE ) ) {
150 $status->fatal( 'nonfile-cannot-move-to-file' );
151 }
152
153 // Hook for extensions to say a title can't be moved for technical reasons
154 Hooks::run( 'MovePageIsValidMove', [ $this->oldTitle, $this->newTitle, $status ] );
155
156 return $status;
157 }
158
159 /**
160 * Sanity checks for when a file is being moved
161 *
162 * @return Status
163 */
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' );
171 }
172 if ( !File::checkExtensionCompatibility( $file, $this->newTitle->getDBkey() ) ) {
173 $status->fatal( 'imagetypemismatch' );
174 }
175 }
176
177 if ( !$this->newTitle->inNamespace( NS_FILE ) ) {
178 $status->fatal( 'imagenocrossnamespace' );
179 }
180
181 return $status;
182 }
183
184 /**
185 * Checks if $this can be moved to a given Title
186 * - Selects for update, so don't call it unless you mean business
187 *
188 * @since 1.25
189 * @return bool
190 */
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" );
198 return false;
199 }
200 }
201 # Is it a redirect with no history?
202 if ( !$this->newTitle->isSingleRevRedirect() ) {
203 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
204 return false;
205 }
206 # Get the article text
207 $rev = Revision::newFromTitle( $this->newTitle, false, Revision::READ_LATEST );
208 if ( !is_object( $rev ) ) {
209 return false;
210 }
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;
215
216 if ( $redirTitle ) {
217 if ( $redirTitle->getPrefixedDBkey() !== $this->oldTitle->getPrefixedDBkey() &&
218 $redirTitle->getPrefixedDBkey() !== $this->newTitle->getPrefixedDBkey() ) {
219 wfDebug( __METHOD__ . ": redirect points to other page\n" );
220 return false;
221 } else {
222 return true;
223 }
224 } else {
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" );
228 return false;
229 }
230 }
231
232 /**
233 * @param User $user
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
238 * @return Status
239 */
240 public function move( User $user, $reason, $createRedirect, array $changeTags = [] ) {
241 global $wgCategoryCollation;
242
243 $status = Status::newGood();
244 Hooks::run( 'TitleMove', [ $this->oldTitle, $this->newTitle, $user, $reason, &$status ] );
245 if ( !$status->isOK() ) {
246 // Move was aborted by the hook
247 return $status;
248 }
249
250 // If it is a file, move it first.
251 // It is done before all other moving stuff is done because it's hard to revert.
252 $dbw = wfGetDB( DB_MASTER );
253 if ( $this->oldTitle->getNamespace() == NS_FILE ) {
254 $file = wfLocalFile( $this->oldTitle );
255 $file->load( File::READ_LATEST );
256 if ( $file->exists() ) {
257 $status = $file->move( $this->newTitle );
258 if ( !$status->isOK() ) {
259 return $status;
260 }
261 }
262 // Clear RepoGroup process cache
263 RepoGroup::singleton()->clearCache( $this->oldTitle );
264 RepoGroup::singleton()->clearCache( $this->newTitle ); # clear false negative cache
265 }
266
267 $dbw->startAtomic( __METHOD__ );
268
269 Hooks::run( 'TitleMoveStarting', [ $this->oldTitle, $this->newTitle, $user ] );
270
271 $pageid = $this->oldTitle->getArticleID( Title::GAID_FOR_UPDATE );
272 $protected = $this->oldTitle->isProtected();
273
274 // Do the actual move; if this fails, it will throw an MWException(!)
275 $nullRevision = $this->moveToInternal( $user, $this->newTitle, $reason, $createRedirect,
276 $changeTags );
277
278 // Refresh the sortkey for this row. Be careful to avoid resetting
279 // cl_timestamp, which may disturb time-based lists on some sites.
280 // @todo This block should be killed, it's duplicating code
281 // from LinksUpdate::getCategoryInsertions() and friends.
282 $prefixes = $dbw->select(
283 'categorylinks',
284 [ 'cl_sortkey_prefix', 'cl_to' ],
285 [ 'cl_from' => $pageid ],
286 __METHOD__
287 );
288 $type = MWNamespace::getCategoryLinkType( $this->newTitle->getNamespace() );
289 foreach ( $prefixes as $prefixRow ) {
290 $prefix = $prefixRow->cl_sortkey_prefix;
291 $catTo = $prefixRow->cl_to;
292 $dbw->update( 'categorylinks',
293 [
294 'cl_sortkey' => Collation::singleton()->getSortKey(
295 $this->newTitle->getCategorySortkey( $prefix ) ),
296 'cl_collation' => $wgCategoryCollation,
297 'cl_type' => $type,
298 'cl_timestamp=cl_timestamp' ],
299 [
300 'cl_from' => $pageid,
301 'cl_to' => $catTo ],
302 __METHOD__
303 );
304 }
305
306 $redirid = $this->oldTitle->getArticleID();
307
308 if ( $protected ) {
309 # Protect the redirect title as the title used to be...
310 $res = $dbw->select(
311 'page_restrictions',
312 [ 'pr_type', 'pr_level', 'pr_cascade', 'pr_user', 'pr_expiry' ],
313 [ 'pr_page' => $pageid ],
314 __METHOD__,
315 'FOR UPDATE'
316 );
317 $rowsInsert = [];
318 foreach ( $res as $row ) {
319 $rowsInsert[] = [
320 'pr_page' => $redirid,
321 'pr_type' => $row->pr_type,
322 'pr_level' => $row->pr_level,
323 'pr_cascade' => $row->pr_cascade,
324 'pr_user' => $row->pr_user,
325 'pr_expiry' => $row->pr_expiry
326 ];
327 }
328 $dbw->insert( 'page_restrictions', $rowsInsert, __METHOD__, [ 'IGNORE' ] );
329
330 // Build comment for log
331 $comment = wfMessage(
332 'prot_1movedto2',
333 $this->oldTitle->getPrefixedText(),
334 $this->newTitle->getPrefixedText()
335 )->inContentLanguage()->text();
336 if ( $reason ) {
337 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
338 }
339
340 // reread inserted pr_ids for log relation
341 $insertedPrIds = $dbw->select(
342 'page_restrictions',
343 'pr_id',
344 [ 'pr_page' => $redirid ],
345 __METHOD__
346 );
347 $logRelationsValues = [];
348 foreach ( $insertedPrIds as $prid ) {
349 $logRelationsValues[] = $prid->pr_id;
350 }
351
352 // Update the protection log
353 $logEntry = new ManualLogEntry( 'protect', 'move_prot' );
354 $logEntry->setTarget( $this->newTitle );
355 $logEntry->setComment( $comment );
356 $logEntry->setPerformer( $user );
357 $logEntry->setParameters( [
358 '4::oldtitle' => $this->oldTitle->getPrefixedText(),
359 ] );
360 $logEntry->setRelations( [ 'pr_id' => $logRelationsValues ] );
361 $logEntry->setTags( $changeTags );
362 $logId = $logEntry->insert();
363 $logEntry->publish( $logId );
364 }
365
366 // Update *_from_namespace fields as needed
367 if ( $this->oldTitle->getNamespace() != $this->newTitle->getNamespace() ) {
368 $dbw->update( 'pagelinks',
369 [ 'pl_from_namespace' => $this->newTitle->getNamespace() ],
370 [ 'pl_from' => $pageid ],
371 __METHOD__
372 );
373 $dbw->update( 'templatelinks',
374 [ 'tl_from_namespace' => $this->newTitle->getNamespace() ],
375 [ 'tl_from' => $pageid ],
376 __METHOD__
377 );
378 $dbw->update( 'imagelinks',
379 [ 'il_from_namespace' => $this->newTitle->getNamespace() ],
380 [ 'il_from' => $pageid ],
381 __METHOD__
382 );
383 }
384
385 # Update watchlists
386 $oldtitle = $this->oldTitle->getDBkey();
387 $newtitle = $this->newTitle->getDBkey();
388 $oldsnamespace = MWNamespace::getSubject( $this->oldTitle->getNamespace() );
389 $newsnamespace = MWNamespace::getSubject( $this->newTitle->getNamespace() );
390 if ( $oldsnamespace != $newsnamespace || $oldtitle != $newtitle ) {
391 $store = MediaWikiServices::getInstance()->getWatchedItemStore();
392 $store->duplicateAllAssociatedEntries( $this->oldTitle, $this->newTitle );
393 }
394
395 Hooks::run(
396 'TitleMoveCompleting',
397 [ $this->oldTitle, $this->newTitle,
398 $user, $pageid, $redirid, $reason, $nullRevision ]
399 );
400
401 $dbw->endAtomic( __METHOD__ );
402
403 $params = [
404 &$this->oldTitle,
405 &$this->newTitle,
406 &$user,
407 $pageid,
408 $redirid,
409 $reason,
410 $nullRevision
411 ];
412 // Keep each single hook handler atomic
413 DeferredUpdates::addUpdate(
414 new AtomicSectionUpdate(
415 $dbw,
416 __METHOD__,
417 // Hold onto $user to avoid HHVM bug where it no longer
418 // becomes a reference (T118683)
419 function () use ( $params, &$user ) {
420 Hooks::run( 'TitleMoveComplete', $params );
421 }
422 )
423 );
424
425 return Status::newGood();
426 }
427
428 /**
429 * Move page to a title which is either a redirect to the
430 * source page or nonexistent
431 *
432 * @todo This was basically directly moved from Title, it should be split into
433 * smaller functions
434 * @param User $user the User doing the move
435 * @param Title $nt The page to move to, which should be a redirect or non-existent
436 * @param string $reason The reason for the move
437 * @param bool $createRedirect Whether to leave a redirect at the old title. Does not check
438 * if the user has the suppressredirect right
439 * @param string[] $changeTags Change tags to apply to the entry in the move log
440 * @return Revision the revision created by the move
441 * @throws MWException
442 */
443 private function moveToInternal( User $user, &$nt, $reason = '', $createRedirect = true,
444 array $changeTags = []
445 ) {
446 if ( $nt->exists() ) {
447 $moveOverRedirect = true;
448 $logType = 'move_redir';
449 } else {
450 $moveOverRedirect = false;
451 $logType = 'move';
452 }
453
454 if ( $moveOverRedirect ) {
455 $overwriteMessage = wfMessage(
456 'delete_and_move_reason',
457 $this->oldTitle->getPrefixedText()
458 )->inContentLanguage()->text();
459 $newpage = WikiPage::factory( $nt );
460 $errs = [];
461 $status = $newpage->doDeleteArticleReal(
462 $overwriteMessage,
463 /* $suppress */ false,
464 $nt->getArticleID(),
465 /* $commit */ false,
466 $errs,
467 $user,
468 $changeTags,
469 'delete_redir'
470 );
471
472 if ( !$status->isGood() ) {
473 throw new MWException( 'Failed to delete page-move revision: ' . $status );
474 }
475
476 $nt->resetArticleID( false );
477 }
478
479 if ( $createRedirect ) {
480 if ( $this->oldTitle->getNamespace() == NS_CATEGORY
481 && !wfMessage( 'category-move-redirect-override' )->inContentLanguage()->isDisabled()
482 ) {
483 $redirectContent = new WikitextContent(
484 wfMessage( 'category-move-redirect-override' )
485 ->params( $nt->getPrefixedText() )->inContentLanguage()->plain() );
486 } else {
487 $contentHandler = ContentHandler::getForTitle( $this->oldTitle );
488 $redirectContent = $contentHandler->makeRedirectContent( $nt,
489 wfMessage( 'move-redirect-text' )->inContentLanguage()->plain() );
490 }
491
492 // NOTE: If this page's content model does not support redirects, $redirectContent will be null.
493 } else {
494 $redirectContent = null;
495 }
496
497 // Figure out whether the content model is no longer the default
498 $oldDefault = ContentHandler::getDefaultModelFor( $this->oldTitle );
499 $contentModel = $this->oldTitle->getContentModel();
500 $newDefault = ContentHandler::getDefaultModelFor( $nt );
501 $defaultContentModelChanging = ( $oldDefault !== $newDefault
502 && $oldDefault === $contentModel );
503
504 // T59084: log_page should be the ID of the *moved* page
505 $oldid = $this->oldTitle->getArticleID();
506 $logTitle = clone $this->oldTitle;
507
508 $logEntry = new ManualLogEntry( 'move', $logType );
509 $logEntry->setPerformer( $user );
510 $logEntry->setTarget( $logTitle );
511 $logEntry->setComment( $reason );
512 $logEntry->setParameters( [
513 '4::target' => $nt->getPrefixedText(),
514 '5::noredir' => $redirectContent ? '0' : '1',
515 ] );
516
517 $formatter = LogFormatter::newFromEntry( $logEntry );
518 $formatter->setContext( RequestContext::newExtraneousContext( $this->oldTitle ) );
519 $comment = $formatter->getPlainActionText();
520 if ( $reason ) {
521 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
522 }
523
524 $dbw = wfGetDB( DB_MASTER );
525
526 $oldpage = WikiPage::factory( $this->oldTitle );
527 $oldcountable = $oldpage->isCountable();
528
529 $newpage = WikiPage::factory( $nt );
530
531 # Change the name of the target page:
532 $dbw->update( 'page',
533 /* SET */ [
534 'page_namespace' => $nt->getNamespace(),
535 'page_title' => $nt->getDBkey(),
536 ],
537 /* WHERE */ [ 'page_id' => $oldid ],
538 __METHOD__
539 );
540
541 # Save a null revision in the page's history notifying of the move
542 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true, $user );
543 if ( !is_object( $nullRevision ) ) {
544 throw new MWException( 'Failed to create null revision while moving page ID '
545 . $oldid . ' to ' . $nt->getPrefixedDBkey() );
546 }
547
548 $nullRevId = $nullRevision->insertOn( $dbw );
549 $logEntry->setAssociatedRevId( $nullRevId );
550
551 /**
552 * T163966
553 * Increment user_editcount during page moves
554 * Moved from SpecialMovepage.php per T195550
555 */
556 $user->incEditCount();
557
558 if ( !$redirectContent ) {
559 // Clean up the old title *before* reset article id - T47348
560 WikiPage::onArticleDelete( $this->oldTitle );
561 }
562
563 $this->oldTitle->resetArticleID( 0 ); // 0 == non existing
564 $nt->resetArticleID( $oldid );
565 $newpage->loadPageData( WikiPage::READ_LOCKING ); // T48397
566
567 $newpage->updateRevisionOn( $dbw, $nullRevision );
568
569 Hooks::run( 'NewRevisionFromEditComplete',
570 [ $newpage, $nullRevision, $nullRevision->getParentId(), $user ] );
571
572 $newpage->doEditUpdates( $nullRevision, $user,
573 [ 'changed' => false, 'moved' => true, 'oldcountable' => $oldcountable ] );
574
575 // If the default content model changes, we need to populate rev_content_model
576 if ( $defaultContentModelChanging ) {
577 $dbw->update(
578 'revision',
579 [ 'rev_content_model' => $contentModel ],
580 [ 'rev_page' => $nt->getArticleID(), 'rev_content_model IS NULL' ],
581 __METHOD__
582 );
583 }
584
585 WikiPage::onArticleCreate( $nt );
586
587 # Recreate the redirect, this time in the other direction.
588 if ( $redirectContent ) {
589 $redirectArticle = WikiPage::factory( $this->oldTitle );
590 $redirectArticle->loadFromRow( false, WikiPage::READ_LOCKING ); // T48397
591 $newid = $redirectArticle->insertOn( $dbw );
592 if ( $newid ) { // sanity
593 $this->oldTitle->resetArticleID( $newid );
594 $redirectRevision = new Revision( [
595 'title' => $this->oldTitle, // for determining the default content model
596 'page' => $newid,
597 'user_text' => $user->getName(),
598 'user' => $user->getId(),
599 'comment' => $comment,
600 'content' => $redirectContent ] );
601 $redirectRevId = $redirectRevision->insertOn( $dbw );
602 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
603
604 Hooks::run( 'NewRevisionFromEditComplete',
605 [ $redirectArticle, $redirectRevision, false, $user ] );
606
607 $redirectArticle->doEditUpdates( $redirectRevision, $user, [ 'created' => true ] );
608
609 // make a copy because of log entry below
610 $redirectTags = $changeTags;
611 if ( in_array( 'mw-new-redirect', ChangeTags::getSoftwareTags() ) ) {
612 $redirectTags[] = 'mw-new-redirect';
613 }
614 ChangeTags::addTags( $redirectTags, null, $redirectRevId, null );
615 }
616 }
617
618 # Log the move
619 $logid = $logEntry->insert();
620
621 $logEntry->setTags( $changeTags );
622 $logEntry->publish( $logid );
623
624 return $nullRevision;
625 }
626 }