Merge "Use MediaWiki\SuppressWarnings around trigger_error('') instead @"
[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 $dbw = wfGetDB( DB_MASTER );
253 $dbw->startAtomic( __METHOD__ );
254
255 Hooks::run( 'TitleMoveStarting', [ $this->oldTitle, $this->newTitle, $user ] );
256
257 $pageid = $this->oldTitle->getArticleID( Title::GAID_FOR_UPDATE );
258 $protected = $this->oldTitle->isProtected();
259
260 // Do the actual move; if this fails, it will throw an MWException(!)
261 $nullRevision = $this->moveToInternal( $user, $this->newTitle, $reason, $createRedirect,
262 $changeTags );
263
264 // Refresh the sortkey for this row. Be careful to avoid resetting
265 // cl_timestamp, which may disturb time-based lists on some sites.
266 // @todo This block should be killed, it's duplicating code
267 // from LinksUpdate::getCategoryInsertions() and friends.
268 $prefixes = $dbw->select(
269 'categorylinks',
270 [ 'cl_sortkey_prefix', 'cl_to' ],
271 [ 'cl_from' => $pageid ],
272 __METHOD__
273 );
274 $type = MWNamespace::getCategoryLinkType( $this->newTitle->getNamespace() );
275 foreach ( $prefixes as $prefixRow ) {
276 $prefix = $prefixRow->cl_sortkey_prefix;
277 $catTo = $prefixRow->cl_to;
278 $dbw->update( 'categorylinks',
279 [
280 'cl_sortkey' => Collation::singleton()->getSortKey(
281 $this->newTitle->getCategorySortkey( $prefix ) ),
282 'cl_collation' => $wgCategoryCollation,
283 'cl_type' => $type,
284 'cl_timestamp=cl_timestamp' ],
285 [
286 'cl_from' => $pageid,
287 'cl_to' => $catTo ],
288 __METHOD__
289 );
290 }
291
292 $redirid = $this->oldTitle->getArticleID();
293
294 if ( $protected ) {
295 # Protect the redirect title as the title used to be...
296 $res = $dbw->select(
297 'page_restrictions',
298 [ 'pr_type', 'pr_level', 'pr_cascade', 'pr_user', 'pr_expiry' ],
299 [ 'pr_page' => $pageid ],
300 __METHOD__,
301 'FOR UPDATE'
302 );
303 $rowsInsert = [];
304 foreach ( $res as $row ) {
305 $rowsInsert[] = [
306 'pr_page' => $redirid,
307 'pr_type' => $row->pr_type,
308 'pr_level' => $row->pr_level,
309 'pr_cascade' => $row->pr_cascade,
310 'pr_user' => $row->pr_user,
311 'pr_expiry' => $row->pr_expiry
312 ];
313 }
314 $dbw->insert( 'page_restrictions', $rowsInsert, __METHOD__, [ 'IGNORE' ] );
315
316 // Build comment for log
317 $comment = wfMessage(
318 'prot_1movedto2',
319 $this->oldTitle->getPrefixedText(),
320 $this->newTitle->getPrefixedText()
321 )->inContentLanguage()->text();
322 if ( $reason ) {
323 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
324 }
325
326 // reread inserted pr_ids for log relation
327 $insertedPrIds = $dbw->select(
328 'page_restrictions',
329 'pr_id',
330 [ 'pr_page' => $redirid ],
331 __METHOD__
332 );
333 $logRelationsValues = [];
334 foreach ( $insertedPrIds as $prid ) {
335 $logRelationsValues[] = $prid->pr_id;
336 }
337
338 // Update the protection log
339 $logEntry = new ManualLogEntry( 'protect', 'move_prot' );
340 $logEntry->setTarget( $this->newTitle );
341 $logEntry->setComment( $comment );
342 $logEntry->setPerformer( $user );
343 $logEntry->setParameters( [
344 '4::oldtitle' => $this->oldTitle->getPrefixedText(),
345 ] );
346 $logEntry->setRelations( [ 'pr_id' => $logRelationsValues ] );
347 $logEntry->setTags( $changeTags );
348 $logId = $logEntry->insert();
349 $logEntry->publish( $logId );
350 }
351
352 // Update *_from_namespace fields as needed
353 if ( $this->oldTitle->getNamespace() != $this->newTitle->getNamespace() ) {
354 $dbw->update( 'pagelinks',
355 [ 'pl_from_namespace' => $this->newTitle->getNamespace() ],
356 [ 'pl_from' => $pageid ],
357 __METHOD__
358 );
359 $dbw->update( 'templatelinks',
360 [ 'tl_from_namespace' => $this->newTitle->getNamespace() ],
361 [ 'tl_from' => $pageid ],
362 __METHOD__
363 );
364 $dbw->update( 'imagelinks',
365 [ 'il_from_namespace' => $this->newTitle->getNamespace() ],
366 [ 'il_from' => $pageid ],
367 __METHOD__
368 );
369 }
370
371 # Update watchlists
372 $oldtitle = $this->oldTitle->getDBkey();
373 $newtitle = $this->newTitle->getDBkey();
374 $oldsnamespace = MWNamespace::getSubject( $this->oldTitle->getNamespace() );
375 $newsnamespace = MWNamespace::getSubject( $this->newTitle->getNamespace() );
376 if ( $oldsnamespace != $newsnamespace || $oldtitle != $newtitle ) {
377 $store = MediaWikiServices::getInstance()->getWatchedItemStore();
378 $store->duplicateAllAssociatedEntries( $this->oldTitle, $this->newTitle );
379 }
380
381 // If it is a file then move it last.
382 // This is done after all database changes so that file system errors cancel the transaction.
383 if ( $this->oldTitle->getNamespace() == NS_FILE ) {
384 $status = $this->moveFile( $this->oldTitle, $this->newTitle );
385 if ( !$status->isOK() ) {
386 $dbw->cancelAtomic( __METHOD__ );
387 return $status;
388 }
389 }
390
391 Hooks::run(
392 'TitleMoveCompleting',
393 [ $this->oldTitle, $this->newTitle,
394 $user, $pageid, $redirid, $reason, $nullRevision ]
395 );
396
397 $dbw->endAtomic( __METHOD__ );
398
399 $params = [
400 &$this->oldTitle,
401 &$this->newTitle,
402 &$user,
403 $pageid,
404 $redirid,
405 $reason,
406 $nullRevision
407 ];
408 // Keep each single hook handler atomic
409 DeferredUpdates::addUpdate(
410 new AtomicSectionUpdate(
411 $dbw,
412 __METHOD__,
413 // Hold onto $user to avoid HHVM bug where it no longer
414 // becomes a reference (T118683)
415 function () use ( $params, &$user ) {
416 Hooks::run( 'TitleMoveComplete', $params );
417 }
418 )
419 );
420
421 return Status::newGood();
422 }
423
424 /**
425 * Move a file associated with a page to a new location.
426 * Can also be used to revert after a DB failure.
427 *
428 * @access private
429 * @param Title Old location to move the file from.
430 * @param Title New location to move the file to.
431 * @return Status
432 */
433 private function moveFile( $oldTitle, $newTitle ) {
434 $status = Status::newFatal(
435 'cannotdelete',
436 $oldTitle->getPrefixedText()
437 );
438
439 $file = wfLocalFile( $oldTitle );
440 $file->load( File::READ_LATEST );
441 if ( $file->exists() ) {
442 $status = $file->move( $newTitle );
443 }
444
445 // Clear RepoGroup process cache
446 RepoGroup::singleton()->clearCache( $oldTitle );
447 RepoGroup::singleton()->clearCache( $newTitle ); # clear false negative cache
448 return $status;
449 }
450
451 /**
452 * Move page to a title which is either a redirect to the
453 * source page or nonexistent
454 *
455 * @todo This was basically directly moved from Title, it should be split into
456 * smaller functions
457 * @param User $user the User doing the move
458 * @param Title $nt The page to move to, which should be a redirect or non-existent
459 * @param string $reason The reason for the move
460 * @param bool $createRedirect Whether to leave a redirect at the old title. Does not check
461 * if the user has the suppressredirect right
462 * @param string[] $changeTags Change tags to apply to the entry in the move log
463 * @return Revision the revision created by the move
464 * @throws MWException
465 */
466 private function moveToInternal( User $user, &$nt, $reason = '', $createRedirect = true,
467 array $changeTags = []
468 ) {
469 if ( $nt->exists() ) {
470 $moveOverRedirect = true;
471 $logType = 'move_redir';
472 } else {
473 $moveOverRedirect = false;
474 $logType = 'move';
475 }
476
477 if ( $moveOverRedirect ) {
478 $overwriteMessage = wfMessage(
479 'delete_and_move_reason',
480 $this->oldTitle->getPrefixedText()
481 )->inContentLanguage()->text();
482 $newpage = WikiPage::factory( $nt );
483 $errs = [];
484 $status = $newpage->doDeleteArticleReal(
485 $overwriteMessage,
486 /* $suppress */ false,
487 $nt->getArticleID(),
488 /* $commit */ false,
489 $errs,
490 $user,
491 $changeTags,
492 'delete_redir'
493 );
494
495 if ( !$status->isGood() ) {
496 throw new MWException( 'Failed to delete page-move revision: ' . $status );
497 }
498
499 $nt->resetArticleID( false );
500 }
501
502 if ( $createRedirect ) {
503 if ( $this->oldTitle->getNamespace() == NS_CATEGORY
504 && !wfMessage( 'category-move-redirect-override' )->inContentLanguage()->isDisabled()
505 ) {
506 $redirectContent = new WikitextContent(
507 wfMessage( 'category-move-redirect-override' )
508 ->params( $nt->getPrefixedText() )->inContentLanguage()->plain() );
509 } else {
510 $contentHandler = ContentHandler::getForTitle( $this->oldTitle );
511 $redirectContent = $contentHandler->makeRedirectContent( $nt,
512 wfMessage( 'move-redirect-text' )->inContentLanguage()->plain() );
513 }
514
515 // NOTE: If this page's content model does not support redirects, $redirectContent will be null.
516 } else {
517 $redirectContent = null;
518 }
519
520 // Figure out whether the content model is no longer the default
521 $oldDefault = ContentHandler::getDefaultModelFor( $this->oldTitle );
522 $contentModel = $this->oldTitle->getContentModel();
523 $newDefault = ContentHandler::getDefaultModelFor( $nt );
524 $defaultContentModelChanging = ( $oldDefault !== $newDefault
525 && $oldDefault === $contentModel );
526
527 // T59084: log_page should be the ID of the *moved* page
528 $oldid = $this->oldTitle->getArticleID();
529 $logTitle = clone $this->oldTitle;
530
531 $logEntry = new ManualLogEntry( 'move', $logType );
532 $logEntry->setPerformer( $user );
533 $logEntry->setTarget( $logTitle );
534 $logEntry->setComment( $reason );
535 $logEntry->setParameters( [
536 '4::target' => $nt->getPrefixedText(),
537 '5::noredir' => $redirectContent ? '0' : '1',
538 ] );
539
540 $formatter = LogFormatter::newFromEntry( $logEntry );
541 $formatter->setContext( RequestContext::newExtraneousContext( $this->oldTitle ) );
542 $comment = $formatter->getPlainActionText();
543 if ( $reason ) {
544 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
545 }
546
547 $dbw = wfGetDB( DB_MASTER );
548
549 $oldpage = WikiPage::factory( $this->oldTitle );
550 $oldcountable = $oldpage->isCountable();
551
552 $newpage = WikiPage::factory( $nt );
553
554 # Change the name of the target page:
555 $dbw->update( 'page',
556 /* SET */ [
557 'page_namespace' => $nt->getNamespace(),
558 'page_title' => $nt->getDBkey(),
559 ],
560 /* WHERE */ [ 'page_id' => $oldid ],
561 __METHOD__
562 );
563
564 # Save a null revision in the page's history notifying of the move
565 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true, $user );
566 if ( !is_object( $nullRevision ) ) {
567 throw new MWException( 'Failed to create null revision while moving page ID '
568 . $oldid . ' to ' . $nt->getPrefixedDBkey() );
569 }
570
571 $nullRevId = $nullRevision->insertOn( $dbw );
572 $logEntry->setAssociatedRevId( $nullRevId );
573
574 /**
575 * T163966
576 * Increment user_editcount during page moves
577 * Moved from SpecialMovepage.php per T195550
578 */
579 $user->incEditCount();
580
581 if ( !$redirectContent ) {
582 // Clean up the old title *before* reset article id - T47348
583 WikiPage::onArticleDelete( $this->oldTitle );
584 }
585
586 $this->oldTitle->resetArticleID( 0 ); // 0 == non existing
587 $nt->resetArticleID( $oldid );
588 $newpage->loadPageData( WikiPage::READ_LOCKING ); // T48397
589
590 $newpage->updateRevisionOn( $dbw, $nullRevision );
591
592 Hooks::run( 'NewRevisionFromEditComplete',
593 [ $newpage, $nullRevision, $nullRevision->getParentId(), $user ] );
594
595 $newpage->doEditUpdates( $nullRevision, $user,
596 [ 'changed' => false, 'moved' => true, 'oldcountable' => $oldcountable ] );
597
598 // If the default content model changes, we need to populate rev_content_model
599 if ( $defaultContentModelChanging ) {
600 $dbw->update(
601 'revision',
602 [ 'rev_content_model' => $contentModel ],
603 [ 'rev_page' => $nt->getArticleID(), 'rev_content_model IS NULL' ],
604 __METHOD__
605 );
606 }
607
608 WikiPage::onArticleCreate( $nt );
609
610 # Recreate the redirect, this time in the other direction.
611 if ( $redirectContent ) {
612 $redirectArticle = WikiPage::factory( $this->oldTitle );
613 $redirectArticle->loadFromRow( false, WikiPage::READ_LOCKING ); // T48397
614 $newid = $redirectArticle->insertOn( $dbw );
615 if ( $newid ) { // sanity
616 $this->oldTitle->resetArticleID( $newid );
617 $redirectRevision = new Revision( [
618 'title' => $this->oldTitle, // for determining the default content model
619 'page' => $newid,
620 'user_text' => $user->getName(),
621 'user' => $user->getId(),
622 'comment' => $comment,
623 'content' => $redirectContent ] );
624 $redirectRevId = $redirectRevision->insertOn( $dbw );
625 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
626
627 Hooks::run( 'NewRevisionFromEditComplete',
628 [ $redirectArticle, $redirectRevision, false, $user ] );
629
630 $redirectArticle->doEditUpdates( $redirectRevision, $user, [ 'created' => true ] );
631
632 // make a copy because of log entry below
633 $redirectTags = $changeTags;
634 if ( in_array( 'mw-new-redirect', ChangeTags::getSoftwareTags() ) ) {
635 $redirectTags[] = 'mw-new-redirect';
636 }
637 ChangeTags::addTags( $redirectTags, null, $redirectRevId, null );
638 }
639 }
640
641 # Log the move
642 $logid = $logEntry->insert();
643
644 $logEntry->setTags( $changeTags );
645 $logEntry->publish( $logid );
646
647 return $nullRevision;
648 }
649 }