Merge "Avoid DBPerformance log warnings in SpecialEditWatchlist"
[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 call_user_func_array( [ $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 }
135
136 // Image-specific checks
137 if ( $this->oldTitle->inNamespace( NS_FILE ) ) {
138 $status->merge( $this->isValidFileMove() );
139 }
140
141 if ( $this->newTitle->inNamespace( NS_FILE ) && !$this->oldTitle->inNamespace( NS_FILE ) ) {
142 $status->fatal( 'nonfile-cannot-move-to-file' );
143 }
144
145 // Hook for extensions to say a title can't be moved for technical reasons
146 Hooks::run( 'MovePageIsValidMove', [ $this->oldTitle, $this->newTitle, $status ] );
147
148 return $status;
149 }
150
151 /**
152 * Sanity checks for when a file is being moved
153 *
154 * @return Status
155 */
156 protected function isValidFileMove() {
157 $status = new Status();
158 $file = wfLocalFile( $this->oldTitle );
159 $file->load( File::READ_LATEST );
160 if ( $file->exists() ) {
161 if ( $this->newTitle->getText() != wfStripIllegalFilenameChars( $this->newTitle->getText() ) ) {
162 $status->fatal( 'imageinvalidfilename' );
163 }
164 if ( !File::checkExtensionCompatibility( $file, $this->newTitle->getDBkey() ) ) {
165 $status->fatal( 'imagetypemismatch' );
166 }
167 }
168
169 if ( !$this->newTitle->inNamespace( NS_FILE ) ) {
170 $status->fatal( 'imagenocrossnamespace' );
171 }
172
173 return $status;
174 }
175
176 /**
177 * Checks if $this can be moved to a given Title
178 * - Selects for update, so don't call it unless you mean business
179 *
180 * @since 1.25
181 * @return bool
182 */
183 protected function isValidMoveTarget() {
184 # Is it an existing file?
185 if ( $this->newTitle->inNamespace( NS_FILE ) ) {
186 $file = wfLocalFile( $this->newTitle );
187 $file->load( File::READ_LATEST );
188 if ( $file->exists() ) {
189 wfDebug( __METHOD__ . ": file exists\n" );
190 return false;
191 }
192 }
193 # Is it a redirect with no history?
194 if ( !$this->newTitle->isSingleRevRedirect() ) {
195 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
196 return false;
197 }
198 # Get the article text
199 $rev = Revision::newFromTitle( $this->newTitle, false, Revision::READ_LATEST );
200 if ( !is_object( $rev ) ) {
201 return false;
202 }
203 $content = $rev->getContent();
204 # Does the redirect point to the source?
205 # Or is it a broken self-redirect, usually caused by namespace collisions?
206 $redirTitle = $content ? $content->getRedirectTarget() : null;
207
208 if ( $redirTitle ) {
209 if ( $redirTitle->getPrefixedDBkey() !== $this->oldTitle->getPrefixedDBkey() &&
210 $redirTitle->getPrefixedDBkey() !== $this->newTitle->getPrefixedDBkey() ) {
211 wfDebug( __METHOD__ . ": redirect points to other page\n" );
212 return false;
213 } else {
214 return true;
215 }
216 } else {
217 # Fail safe (not a redirect after all. strange.)
218 wfDebug( __METHOD__ . ": failsafe: database says " . $this->newTitle->getPrefixedDBkey() .
219 " is a redirect, but it doesn't contain a valid redirect.\n" );
220 return false;
221 }
222 }
223
224 /**
225 * @param User $user
226 * @param string $reason
227 * @param bool $createRedirect
228 * @return Status
229 */
230 public function move( User $user, $reason, $createRedirect ) {
231 global $wgCategoryCollation;
232
233 Hooks::run( 'TitleMove', [ $this->oldTitle, $this->newTitle, $user ] );
234
235 // If it is a file, move it first.
236 // It is done before all other moving stuff is done because it's hard to revert.
237 $dbw = wfGetDB( DB_MASTER );
238 if ( $this->oldTitle->getNamespace() == NS_FILE ) {
239 $file = wfLocalFile( $this->oldTitle );
240 $file->load( File::READ_LATEST );
241 if ( $file->exists() ) {
242 $status = $file->move( $this->newTitle );
243 if ( !$status->isOK() ) {
244 return $status;
245 }
246 }
247 // Clear RepoGroup process cache
248 RepoGroup::singleton()->clearCache( $this->oldTitle );
249 RepoGroup::singleton()->clearCache( $this->newTitle ); # clear false negative cache
250 }
251
252 $dbw->startAtomic( __METHOD__ );
253
254 Hooks::run( 'TitleMoveStarting', [ $this->oldTitle, $this->newTitle, $user ] );
255
256 $pageid = $this->oldTitle->getArticleID( Title::GAID_FOR_UPDATE );
257 $protected = $this->oldTitle->isProtected();
258
259 // Do the actual move; if this fails, it will throw an MWException(!)
260 $nullRevision = $this->moveToInternal( $user, $this->newTitle, $reason, $createRedirect );
261
262 // Refresh the sortkey for this row. Be careful to avoid resetting
263 // cl_timestamp, which may disturb time-based lists on some sites.
264 // @todo This block should be killed, it's duplicating code
265 // from LinksUpdate::getCategoryInsertions() and friends.
266 $prefixes = $dbw->select(
267 'categorylinks',
268 [ 'cl_sortkey_prefix', 'cl_to' ],
269 [ 'cl_from' => $pageid ],
270 __METHOD__
271 );
272 if ( $this->newTitle->getNamespace() == NS_CATEGORY ) {
273 $type = 'subcat';
274 } elseif ( $this->newTitle->getNamespace() == NS_FILE ) {
275 $type = 'file';
276 } else {
277 $type = 'page';
278 }
279 foreach ( $prefixes as $prefixRow ) {
280 $prefix = $prefixRow->cl_sortkey_prefix;
281 $catTo = $prefixRow->cl_to;
282 $dbw->update( 'categorylinks',
283 [
284 'cl_sortkey' => Collation::singleton()->getSortKey(
285 $this->newTitle->getCategorySortkey( $prefix ) ),
286 'cl_collation' => $wgCategoryCollation,
287 'cl_type' => $type,
288 'cl_timestamp=cl_timestamp' ],
289 [
290 'cl_from' => $pageid,
291 'cl_to' => $catTo ],
292 __METHOD__
293 );
294 }
295
296 $redirid = $this->oldTitle->getArticleID();
297
298 if ( $protected ) {
299 # Protect the redirect title as the title used to be...
300 $res = $dbw->select(
301 'page_restrictions',
302 '*',
303 [ 'pr_page' => $pageid ],
304 __METHOD__,
305 'FOR UPDATE'
306 );
307 $rowsInsert = [];
308 foreach ( $res as $row ) {
309 $rowsInsert[] = [
310 'pr_page' => $redirid,
311 'pr_type' => $row->pr_type,
312 'pr_level' => $row->pr_level,
313 'pr_cascade' => $row->pr_cascade,
314 'pr_user' => $row->pr_user,
315 'pr_expiry' => $row->pr_expiry
316 ];
317 }
318 $dbw->insert( 'page_restrictions', $rowsInsert, __METHOD__, [ 'IGNORE' ] );
319
320 // Build comment for log
321 $comment = wfMessage(
322 'prot_1movedto2',
323 $this->oldTitle->getPrefixedText(),
324 $this->newTitle->getPrefixedText()
325 )->inContentLanguage()->text();
326 if ( $reason ) {
327 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
328 }
329
330 // reread inserted pr_ids for log relation
331 $insertedPrIds = $dbw->select(
332 'page_restrictions',
333 'pr_id',
334 [ 'pr_page' => $redirid ],
335 __METHOD__
336 );
337 $logRelationsValues = [];
338 foreach ( $insertedPrIds as $prid ) {
339 $logRelationsValues[] = $prid->pr_id;
340 }
341
342 // Update the protection log
343 $logEntry = new ManualLogEntry( 'protect', 'move_prot' );
344 $logEntry->setTarget( $this->newTitle );
345 $logEntry->setComment( $comment );
346 $logEntry->setPerformer( $user );
347 $logEntry->setParameters( [
348 '4::oldtitle' => $this->oldTitle->getPrefixedText(),
349 ] );
350 $logEntry->setRelations( [ 'pr_id' => $logRelationsValues ] );
351 $logId = $logEntry->insert();
352 $logEntry->publish( $logId );
353 }
354
355 // Update *_from_namespace fields as needed
356 if ( $this->oldTitle->getNamespace() != $this->newTitle->getNamespace() ) {
357 $dbw->update( 'pagelinks',
358 [ 'pl_from_namespace' => $this->newTitle->getNamespace() ],
359 [ 'pl_from' => $pageid ],
360 __METHOD__
361 );
362 $dbw->update( 'templatelinks',
363 [ 'tl_from_namespace' => $this->newTitle->getNamespace() ],
364 [ 'tl_from' => $pageid ],
365 __METHOD__
366 );
367 $dbw->update( 'imagelinks',
368 [ 'il_from_namespace' => $this->newTitle->getNamespace() ],
369 [ 'il_from' => $pageid ],
370 __METHOD__
371 );
372 }
373
374 # Update watchlists
375 $oldtitle = $this->oldTitle->getDBkey();
376 $newtitle = $this->newTitle->getDBkey();
377 $oldsnamespace = MWNamespace::getSubject( $this->oldTitle->getNamespace() );
378 $newsnamespace = MWNamespace::getSubject( $this->newTitle->getNamespace() );
379 if ( $oldsnamespace != $newsnamespace || $oldtitle != $newtitle ) {
380 $store = MediaWikiServices::getInstance()->getWatchedItemStore();
381 $store->duplicateAllAssociatedEntries( $this->oldTitle, $this->newTitle );
382 }
383
384 Hooks::run(
385 'TitleMoveCompleting',
386 [ $this->oldTitle, $this->newTitle,
387 $user, $pageid, $redirid, $reason, $nullRevision ]
388 );
389
390 $dbw->endAtomic( __METHOD__ );
391
392 $params = [
393 &$this->oldTitle,
394 &$this->newTitle,
395 &$user,
396 $pageid,
397 $redirid,
398 $reason,
399 $nullRevision
400 ];
401 // Keep each single hook handler atomic
402 DeferredUpdates::addUpdate(
403 new AtomicSectionUpdate(
404 $dbw,
405 __METHOD__,
406 function () use ( $params ) {
407 Hooks::run( 'TitleMoveComplete', $params );
408 }
409 )
410 );
411
412 return Status::newGood();
413 }
414
415 /**
416 * Move page to a title which is either a redirect to the
417 * source page or nonexistent
418 *
419 * @fixme This was basically directly moved from Title, it should be split into smaller functions
420 * @param User $user the User doing the move
421 * @param Title $nt The page to move to, which should be a redirect or non-existent
422 * @param string $reason The reason for the move
423 * @param bool $createRedirect Whether to leave a redirect at the old title. Does not check
424 * if the user has the suppressredirect right
425 * @return Revision the revision created by the move
426 * @throws MWException
427 */
428 private function moveToInternal( User $user, &$nt, $reason = '', $createRedirect = true ) {
429 global $wgContLang;
430
431 if ( $nt->exists() ) {
432 $moveOverRedirect = true;
433 $logType = 'move_redir';
434 } else {
435 $moveOverRedirect = false;
436 $logType = 'move';
437 }
438
439 if ( $moveOverRedirect ) {
440 $overwriteMessage = wfMessage(
441 'delete_and_move_reason',
442 $this->oldTitle->getPrefixedText()
443 )->text();
444 $newpage = WikiPage::factory( $nt );
445 $errs = [];
446 $status = $newpage->doDeleteArticleReal(
447 $overwriteMessage,
448 /* $suppress */ false,
449 $nt->getArticleID(),
450 /* $commit */ false,
451 $errs,
452 $user
453 );
454
455 if ( !$status->isGood() ) {
456 throw new MWException( 'Failed to delete page-move revision: ' . $status );
457 }
458
459 $nt->resetArticleID( false );
460 }
461
462 if ( $createRedirect ) {
463 if ( $this->oldTitle->getNamespace() == NS_CATEGORY
464 && !wfMessage( 'category-move-redirect-override' )->inContentLanguage()->isDisabled()
465 ) {
466 $redirectContent = new WikitextContent(
467 wfMessage( 'category-move-redirect-override' )
468 ->params( $nt->getPrefixedText() )->inContentLanguage()->plain() );
469 } else {
470 $contentHandler = ContentHandler::getForTitle( $this->oldTitle );
471 $redirectContent = $contentHandler->makeRedirectContent( $nt,
472 wfMessage( 'move-redirect-text' )->inContentLanguage()->plain() );
473 }
474
475 // NOTE: If this page's content model does not support redirects, $redirectContent will be null.
476 } else {
477 $redirectContent = null;
478 }
479
480 // Figure out whether the content model is no longer the default
481 $oldDefault = ContentHandler::getDefaultModelFor( $this->oldTitle );
482 $contentModel = $this->oldTitle->getContentModel();
483 $newDefault = ContentHandler::getDefaultModelFor( $nt );
484 $defaultContentModelChanging = ( $oldDefault !== $newDefault
485 && $oldDefault === $contentModel );
486
487 // bug 57084: log_page should be the ID of the *moved* page
488 $oldid = $this->oldTitle->getArticleID();
489 $logTitle = clone $this->oldTitle;
490
491 $logEntry = new ManualLogEntry( 'move', $logType );
492 $logEntry->setPerformer( $user );
493 $logEntry->setTarget( $logTitle );
494 $logEntry->setComment( $reason );
495 $logEntry->setParameters( [
496 '4::target' => $nt->getPrefixedText(),
497 '5::noredir' => $redirectContent ? '0': '1',
498 ] );
499
500 $formatter = LogFormatter::newFromEntry( $logEntry );
501 $formatter->setContext( RequestContext::newExtraneousContext( $this->oldTitle ) );
502 $comment = $formatter->getPlainActionText();
503 if ( $reason ) {
504 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
505 }
506 # Truncate for whole multibyte characters.
507 $comment = $wgContLang->truncate( $comment, 255 );
508
509 $dbw = wfGetDB( DB_MASTER );
510
511 $oldpage = WikiPage::factory( $this->oldTitle );
512 $oldcountable = $oldpage->isCountable();
513
514 $newpage = WikiPage::factory( $nt );
515
516 # Save a null revision in the page's history notifying of the move
517 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true, $user );
518 if ( !is_object( $nullRevision ) ) {
519 throw new MWException( 'No valid null revision produced in ' . __METHOD__ );
520 }
521
522 $nullRevision->insertOn( $dbw );
523
524 # Change the name of the target page:
525 $dbw->update( 'page',
526 /* SET */ [
527 'page_namespace' => $nt->getNamespace(),
528 'page_title' => $nt->getDBkey(),
529 ],
530 /* WHERE */ [ 'page_id' => $oldid ],
531 __METHOD__
532 );
533
534 // clean up the old title before reset article id - bug 45348
535 if ( !$redirectContent ) {
536 WikiPage::onArticleDelete( $this->oldTitle );
537 }
538
539 $this->oldTitle->resetArticleID( 0 ); // 0 == non existing
540 $nt->resetArticleID( $oldid );
541 $newpage->loadPageData( WikiPage::READ_LOCKING ); // bug 46397
542
543 $newpage->updateRevisionOn( $dbw, $nullRevision );
544
545 Hooks::run( 'NewRevisionFromEditComplete',
546 [ $newpage, $nullRevision, $nullRevision->getParentId(), $user ] );
547
548 $newpage->doEditUpdates( $nullRevision, $user,
549 [ 'changed' => false, 'moved' => true, 'oldcountable' => $oldcountable ] );
550
551 // If the default content model changes, we need to populate rev_content_model
552 if ( $defaultContentModelChanging ) {
553 $dbw->update(
554 'revision',
555 [ 'rev_content_model' => $contentModel ],
556 [ 'rev_page' => $nt->getArticleID(), 'rev_content_model IS NULL' ],
557 __METHOD__
558 );
559 }
560
561 WikiPage::onArticleCreate( $nt );
562
563 # Recreate the redirect, this time in the other direction.
564 if ( $redirectContent ) {
565 $redirectArticle = WikiPage::factory( $this->oldTitle );
566 $redirectArticle->loadFromRow( false, WikiPage::READ_LOCKING ); // bug 46397
567 $newid = $redirectArticle->insertOn( $dbw );
568 if ( $newid ) { // sanity
569 $this->oldTitle->resetArticleID( $newid );
570 $redirectRevision = new Revision( [
571 'title' => $this->oldTitle, // for determining the default content model
572 'page' => $newid,
573 'user_text' => $user->getName(),
574 'user' => $user->getId(),
575 'comment' => $comment,
576 'content' => $redirectContent ] );
577 $redirectRevision->insertOn( $dbw );
578 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
579
580 Hooks::run( 'NewRevisionFromEditComplete',
581 [ $redirectArticle, $redirectRevision, false, $user ] );
582
583 $redirectArticle->doEditUpdates( $redirectRevision, $user, [ 'created' => true ] );
584 }
585 }
586
587 # Log the move
588 $logid = $logEntry->insert();
589 $logEntry->publish( $logid );
590
591 return $nullRevision;
592 }
593 }