Merge "rdbms: simplify LoadBalancer::getLaggedReplicaMode()"
[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\Config\ServiceOptions;
23 use MediaWiki\MediaWikiServices;
24 use MediaWiki\Page\MovePageFactory;
25 use MediaWiki\Permissions\PermissionManager;
26 use MediaWiki\Revision\SlotRecord;
27 use Wikimedia\Rdbms\IDatabase;
28 use Wikimedia\Rdbms\LoadBalancer;
29
30 /**
31 * Handles the backend logic of moving a page from one title
32 * to another.
33 *
34 * @since 1.24
35 */
36 class MovePage {
37
38 /**
39 * @var Title
40 */
41 protected $oldTitle;
42
43 /**
44 * @var Title
45 */
46 protected $newTitle;
47
48 /**
49 * @var ServiceOptions
50 */
51 protected $options;
52
53 /**
54 * @var LoadBalancer
55 */
56 protected $loadBalancer;
57
58 /**
59 * @var NamespaceInfo
60 */
61 protected $nsInfo;
62
63 /**
64 * @var WatchedItemStore
65 */
66 protected $watchedItems;
67
68 /**
69 * @var PermissionManager
70 */
71 protected $permMgr;
72
73 /**
74 * @var RepoGroup
75 */
76 protected $repoGroup;
77
78 /**
79 * Calling this directly is deprecated in 1.34. Use MovePageFactory instead.
80 *
81 * @param Title $oldTitle
82 * @param Title $newTitle
83 * @param ServiceOptions|null $options
84 * @param LoadBalancer|null $loadBalancer
85 * @param NamespaceInfo|null $nsInfo
86 * @param WatchedItemStore|null $watchedItems
87 * @param PermissionManager|null $permMgr
88 */
89 public function __construct(
90 Title $oldTitle,
91 Title $newTitle,
92 ServiceOptions $options = null,
93 LoadBalancer $loadBalancer = null,
94 NamespaceInfo $nsInfo = null,
95 WatchedItemStore $watchedItems = null,
96 PermissionManager $permMgr = null,
97 RepoGroup $repoGroup = null
98 ) {
99 $this->oldTitle = $oldTitle;
100 $this->newTitle = $newTitle;
101 $this->options = $options ??
102 new ServiceOptions( MovePageFactory::$constructorOptions,
103 MediaWikiServices::getInstance()->getMainConfig() );
104 $this->loadBalancer =
105 $loadBalancer ?? MediaWikiServices::getInstance()->getDBLoadBalancer();
106 $this->nsInfo = $nsInfo ?? MediaWikiServices::getInstance()->getNamespaceInfo();
107 $this->watchedItems =
108 $watchedItems ?? MediaWikiServices::getInstance()->getWatchedItemStore();
109 $this->permMgr = $permMgr ?? MediaWikiServices::getInstance()->getPermissionManager();
110 $this->repoGroup = $repoGroup ?? MediaWikiServices::getInstance()->getRepoGroup();
111 }
112
113 /**
114 * Check if the user is allowed to perform the move.
115 *
116 * @param User $user
117 * @param string|null $reason To check against summary spam regex. Set to null to skip the check,
118 * for instance to display errors preemptively before the user has filled in a summary.
119 * @return Status
120 */
121 public function checkPermissions( User $user, $reason ) {
122 $status = new Status();
123
124 $errors = wfMergeErrorArrays(
125 $this->permMgr->getPermissionErrors( 'move', $user, $this->oldTitle ),
126 $this->permMgr->getPermissionErrors( 'edit', $user, $this->oldTitle ),
127 $this->permMgr->getPermissionErrors( 'move-target', $user, $this->newTitle ),
128 $this->permMgr->getPermissionErrors( 'edit', $user, $this->newTitle )
129 );
130
131 // Convert into a Status object
132 if ( $errors ) {
133 foreach ( $errors as $error ) {
134 $status->fatal( ...$error );
135 }
136 }
137
138 if ( $reason !== null && EditPage::matchSummarySpamRegex( $reason ) !== false ) {
139 // This is kind of lame, won't display nice
140 $status->fatal( 'spamprotectiontext' );
141 }
142
143 $tp = $this->newTitle->getTitleProtection();
144 if ( $tp !== false && !$user->isAllowed( $tp['permission'] ) ) {
145 $status->fatal( 'cantmove-titleprotected' );
146 }
147
148 Hooks::run( 'MovePageCheckPermissions',
149 [ $this->oldTitle, $this->newTitle, $user, $reason, $status ]
150 );
151
152 return $status;
153 }
154
155 /**
156 * Does various sanity checks that the move is
157 * valid. Only things based on the two titles
158 * should be checked here.
159 *
160 * @return Status
161 */
162 public function isValidMove() {
163 $status = new Status();
164
165 if ( $this->oldTitle->equals( $this->newTitle ) ) {
166 $status->fatal( 'selfmove' );
167 } elseif ( $this->newTitle->getArticleID() && !$this->isValidMoveTarget() ) {
168 // The move is allowed only if (1) the target doesn't exist, or (2) the target is a
169 // redirect to the source, and has no history (so we can undo bad moves right after
170 // they're done).
171 $status->fatal( 'articleexists' );
172 }
173
174 // @todo If the old title is invalid, maybe we should check if it somehow exists in the
175 // database and allow moving it to a valid name? Why prohibit the move from an empty name
176 // without checking in the database?
177 if ( $this->oldTitle->getDBkey() == '' ) {
178 $status->fatal( 'badarticleerror' );
179 } elseif ( $this->oldTitle->isExternal() ) {
180 $status->fatal( 'immobile-source-namespace-iw' );
181 } elseif ( !$this->oldTitle->isMovable() ) {
182 $status->fatal( 'immobile-source-namespace', $this->oldTitle->getNsText() );
183 } elseif ( !$this->oldTitle->exists() ) {
184 $status->fatal( 'movepage-source-doesnt-exist' );
185 }
186
187 if ( $this->newTitle->isExternal() ) {
188 $status->fatal( 'immobile-target-namespace-iw' );
189 } elseif ( !$this->newTitle->isMovable() ) {
190 $status->fatal( 'immobile-target-namespace', $this->newTitle->getNsText() );
191 }
192 if ( !$this->newTitle->isValid() ) {
193 $status->fatal( 'movepage-invalid-target-title' );
194 }
195
196 // Content model checks
197 if ( !$this->options->get( 'ContentHandlerUseDB' ) &&
198 $this->oldTitle->getContentModel() !== $this->newTitle->getContentModel() ) {
199 // can't move a page if that would change the page's content model
200 $status->fatal(
201 'bad-target-model',
202 ContentHandler::getLocalizedName( $this->oldTitle->getContentModel() ),
203 ContentHandler::getLocalizedName( $this->newTitle->getContentModel() )
204 );
205 } elseif (
206 !ContentHandler::getForTitle( $this->oldTitle )->canBeUsedOn( $this->newTitle )
207 ) {
208 $status->fatal(
209 'content-not-allowed-here',
210 ContentHandler::getLocalizedName( $this->oldTitle->getContentModel() ),
211 $this->newTitle->getPrefixedText(),
212 SlotRecord::MAIN
213 );
214 }
215
216 // Image-specific checks
217 if ( $this->oldTitle->inNamespace( NS_FILE ) ) {
218 $status->merge( $this->isValidFileMove() );
219 }
220
221 if ( $this->newTitle->inNamespace( NS_FILE ) && !$this->oldTitle->inNamespace( NS_FILE ) ) {
222 $status->fatal( 'nonfile-cannot-move-to-file' );
223 }
224
225 // Hook for extensions to say a title can't be moved for technical reasons
226 Hooks::run( 'MovePageIsValidMove', [ $this->oldTitle, $this->newTitle, $status ] );
227
228 return $status;
229 }
230
231 /**
232 * Sanity checks for when a file is being moved
233 *
234 * @return Status
235 */
236 protected function isValidFileMove() {
237 $status = new Status();
238
239 if ( !$this->newTitle->inNamespace( NS_FILE ) ) {
240 $status->fatal( 'imagenocrossnamespace' );
241 // No need for further errors about the target filename being wrong
242 return $status;
243 }
244
245 $file = $this->repoGroup->getLocalRepo()->newFile( $this->oldTitle );
246 $file->load( File::READ_LATEST );
247 if ( $file->exists() ) {
248 if ( $this->newTitle->getText() != wfStripIllegalFilenameChars( $this->newTitle->getText() ) ) {
249 $status->fatal( 'imageinvalidfilename' );
250 }
251 if ( !File::checkExtensionCompatibility( $file, $this->newTitle->getDBkey() ) ) {
252 $status->fatal( 'imagetypemismatch' );
253 }
254 }
255
256 return $status;
257 }
258
259 /**
260 * Checks if $this can be moved to a given Title
261 * - Selects for update, so don't call it unless you mean business
262 *
263 * @since 1.25
264 * @return bool
265 */
266 protected function isValidMoveTarget() {
267 # Is it an existing file?
268 if ( $this->newTitle->inNamespace( NS_FILE ) ) {
269 $file = $this->repoGroup->getLocalRepo()->newFile( $this->newTitle );
270 $file->load( File::READ_LATEST );
271 if ( $file->exists() ) {
272 wfDebug( __METHOD__ . ": file exists\n" );
273 return false;
274 }
275 }
276 # Is it a redirect with no history?
277 if ( !$this->newTitle->isSingleRevRedirect() ) {
278 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
279 return false;
280 }
281 # Get the article text
282 $rev = Revision::newFromTitle( $this->newTitle, false, Revision::READ_LATEST );
283 if ( !is_object( $rev ) ) {
284 return false;
285 }
286 $content = $rev->getContent();
287 # Does the redirect point to the source?
288 # Or is it a broken self-redirect, usually caused by namespace collisions?
289 $redirTitle = $content ? $content->getRedirectTarget() : null;
290
291 if ( $redirTitle ) {
292 if ( $redirTitle->getPrefixedDBkey() !== $this->oldTitle->getPrefixedDBkey() &&
293 $redirTitle->getPrefixedDBkey() !== $this->newTitle->getPrefixedDBkey() ) {
294 wfDebug( __METHOD__ . ": redirect points to other page\n" );
295 return false;
296 } else {
297 return true;
298 }
299 } else {
300 # Fail safe (not a redirect after all. strange.)
301 wfDebug( __METHOD__ . ": failsafe: database says " . $this->newTitle->getPrefixedDBkey() .
302 " is a redirect, but it doesn't contain a valid redirect.\n" );
303 return false;
304 }
305 }
306
307 /**
308 * Move a page without taking user permissions into account. Only checks if the move is itself
309 * invalid, e.g., trying to move a special page or trying to move a page onto one that already
310 * exists.
311 *
312 * @param User $user
313 * @param string|null $reason
314 * @param bool|null $createRedirect
315 * @param string[] $changeTags Change tags to apply to the entry in the move log
316 * @return Status
317 */
318 public function move(
319 User $user, $reason = null, $createRedirect = true, array $changeTags = []
320 ) {
321 $status = $this->isValidMove();
322 if ( !$status->isOK() ) {
323 return $status;
324 }
325
326 return $this->moveUnsafe( $user, $reason, $createRedirect, $changeTags );
327 }
328
329 /**
330 * Same as move(), but with permissions checks.
331 *
332 * @param User $user
333 * @param string|null $reason
334 * @param bool|null $createRedirect Ignored if user doesn't have suppressredirect permission
335 * @param string[] $changeTags Change tags to apply to the entry in the move log
336 * @return Status
337 */
338 public function moveIfAllowed(
339 User $user, $reason = null, $createRedirect = true, array $changeTags = []
340 ) {
341 $status = $this->isValidMove();
342 $status->merge( $this->checkPermissions( $user, $reason ) );
343 if ( $changeTags ) {
344 $status->merge( ChangeTags::canAddTagsAccompanyingChange( $changeTags, $user ) );
345 }
346
347 if ( !$status->isOK() ) {
348 // Auto-block user's IP if the account was "hard" blocked
349 $user->spreadAnyEditBlock();
350 return $status;
351 }
352
353 // Check suppressredirect permission
354 if ( !$user->isAllowed( 'suppressredirect' ) ) {
355 $createRedirect = true;
356 }
357
358 return $this->moveUnsafe( $user, $reason, $createRedirect, $changeTags );
359 }
360
361 /**
362 * Move the source page's subpages to be subpages of the target page, without checking user
363 * permissions. The caller is responsible for moving the source page itself. We will still not
364 * do moves that are inherently not allowed, nor will we move more than $wgMaximumMovedPages.
365 *
366 * @param User $user
367 * @param string|null $reason The reason for the move
368 * @param bool|null $createRedirect Whether to create redirects from the old subpages to
369 * the new ones
370 * @param string[] $changeTags Applied to entries in the move log and redirect page revision
371 * @return Status Good if no errors occurred. Ok if at least one page succeeded. The "value"
372 * of the top-level status is an array containing the per-title status for each page. For any
373 * move that succeeded, the "value" of the per-title status is the new page title.
374 */
375 public function moveSubpages(
376 User $user, $reason = null, $createRedirect = true, array $changeTags = []
377 ) {
378 return $this->moveSubpagesInternal( false, $user, $reason, $createRedirect, $changeTags );
379 }
380
381 /**
382 * Move the source page's subpages to be subpages of the target page, with user permission
383 * checks. The caller is responsible for moving the source page itself.
384 *
385 * @param User $user
386 * @param string|null $reason The reason for the move
387 * @param bool|null $createRedirect Whether to create redirects from the old subpages to
388 * the new ones. Ignored if the user doesn't have the 'suppressredirect' right.
389 * @param string[] $changeTags Applied to entries in the move log and redirect page revision
390 * @return Status Good if no errors occurred. Ok if at least one page succeeded. The "value"
391 * of the top-level status is an array containing the per-title status for each page. For any
392 * move that succeeded, the "value" of the per-title status is the new page title.
393 */
394 public function moveSubpagesIfAllowed(
395 User $user, $reason = null, $createRedirect = true, array $changeTags = []
396 ) {
397 return $this->moveSubpagesInternal( true, $user, $reason, $createRedirect, $changeTags );
398 }
399
400 /**
401 * @param bool $checkPermissions
402 * @param User $user
403 * @param string $reason
404 * @param bool $createRedirect
405 * @param array $changeTags
406 * @return Status
407 */
408 private function moveSubpagesInternal(
409 $checkPermissions, User $user, $reason, $createRedirect, array $changeTags
410 ) {
411 global $wgMaximumMovedPages;
412 $services = MediaWikiServices::getInstance();
413
414 if ( $checkPermissions ) {
415 if ( !$services->getPermissionManager()->userCan(
416 'move-subpages', $user, $this->oldTitle )
417 ) {
418 return Status::newFatal( 'cant-move-subpages' );
419 }
420 }
421
422 $nsInfo = $services->getNamespaceInfo();
423
424 // Do the source and target namespaces support subpages?
425 if ( !$nsInfo->hasSubpages( $this->oldTitle->getNamespace() ) ) {
426 return Status::newFatal( 'namespace-nosubpages',
427 $nsInfo->getCanonicalName( $this->oldTitle->getNamespace() ) );
428 }
429 if ( !$nsInfo->hasSubpages( $this->newTitle->getNamespace() ) ) {
430 return Status::newFatal( 'namespace-nosubpages',
431 $nsInfo->getCanonicalName( $this->newTitle->getNamespace() ) );
432 }
433
434 // Return a status for the overall result. Its value will be an array with per-title
435 // status for each subpage. Merge any errors from the per-title statuses into the
436 // top-level status without resetting the overall result.
437 $topStatus = Status::newGood();
438 $perTitleStatus = [];
439 $subpages = $this->oldTitle->getSubpages( $wgMaximumMovedPages + 1 );
440 $count = 0;
441 foreach ( $subpages as $oldSubpage ) {
442 $count++;
443 if ( $count > $wgMaximumMovedPages ) {
444 $status = Status::newFatal( 'movepage-max-pages', $wgMaximumMovedPages );
445 $perTitleStatus[$oldSubpage->getPrefixedText()] = $status;
446 $topStatus->merge( $status );
447 $topStatus->setOk( true );
448 break;
449 }
450
451 // We don't know whether this function was called before or after moving the root page,
452 // so check both titles
453 if ( $oldSubpage->getArticleID() == $this->oldTitle->getArticleID() ||
454 $oldSubpage->getArticleID() == $this->newTitle->getArticleID()
455 ) {
456 // When moving a page to a subpage of itself, don't move it twice
457 continue;
458 }
459 $newPageName = preg_replace(
460 '#^' . preg_quote( $this->oldTitle->getDBkey(), '#' ) . '#',
461 StringUtils::escapeRegexReplacement( $this->newTitle->getDBkey() ), # T23234
462 $oldSubpage->getDBkey() );
463 if ( $oldSubpage->isTalkPage() ) {
464 $newNs = $this->newTitle->getTalkPage()->getNamespace();
465 } else {
466 $newNs = $this->newTitle->getSubjectPage()->getNamespace();
467 }
468 // T16385: we need makeTitleSafe because the new page names may be longer than 255
469 // characters.
470 $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
471
472 $mp = new MovePage( $oldSubpage, $newSubpage );
473 $method = $checkPermissions ? 'moveIfAllowed' : 'move';
474 $status = $mp->$method( $user, $reason, $createRedirect, $changeTags );
475 if ( $status->isOK() ) {
476 $status->setResult( true, $newSubpage->getPrefixedText() );
477 }
478 $perTitleStatus[$oldSubpage->getPrefixedText()] = $status;
479 $topStatus->merge( $status );
480 $topStatus->setOk( true );
481 }
482
483 $topStatus->value = $perTitleStatus;
484 return $topStatus;
485 }
486
487 /**
488 * Moves *without* any sort of safety or sanity checks. Hooks can still fail the move, however.
489 *
490 * @param User $user
491 * @param string $reason
492 * @param bool $createRedirect
493 * @param string[] $changeTags Change tags to apply to the entry in the move log
494 * @return Status
495 */
496 private function moveUnsafe( User $user, $reason, $createRedirect, array $changeTags ) {
497 $status = Status::newGood();
498 Hooks::run( 'TitleMove', [ $this->oldTitle, $this->newTitle, $user, $reason, &$status ] );
499 if ( !$status->isOK() ) {
500 // Move was aborted by the hook
501 return $status;
502 }
503
504 $dbw = $this->loadBalancer->getConnection( DB_MASTER );
505 $dbw->startAtomic( __METHOD__, IDatabase::ATOMIC_CANCELABLE );
506
507 Hooks::run( 'TitleMoveStarting', [ $this->oldTitle, $this->newTitle, $user ] );
508
509 $pageid = $this->oldTitle->getArticleID( Title::GAID_FOR_UPDATE );
510 $protected = $this->oldTitle->isProtected();
511
512 // Do the actual move; if this fails, it will throw an MWException(!)
513 $nullRevision = $this->moveToInternal( $user, $this->newTitle, $reason, $createRedirect,
514 $changeTags );
515
516 // Refresh the sortkey for this row. Be careful to avoid resetting
517 // cl_timestamp, which may disturb time-based lists on some sites.
518 // @todo This block should be killed, it's duplicating code
519 // from LinksUpdate::getCategoryInsertions() and friends.
520 $prefixes = $dbw->select(
521 'categorylinks',
522 [ 'cl_sortkey_prefix', 'cl_to' ],
523 [ 'cl_from' => $pageid ],
524 __METHOD__
525 );
526 $type = $this->nsInfo->getCategoryLinkType( $this->newTitle->getNamespace() );
527 foreach ( $prefixes as $prefixRow ) {
528 $prefix = $prefixRow->cl_sortkey_prefix;
529 $catTo = $prefixRow->cl_to;
530 $dbw->update( 'categorylinks',
531 [
532 'cl_sortkey' => Collation::singleton()->getSortKey(
533 $this->newTitle->getCategorySortkey( $prefix ) ),
534 'cl_collation' => $this->options->get( 'CategoryCollation' ),
535 'cl_type' => $type,
536 'cl_timestamp=cl_timestamp' ],
537 [
538 'cl_from' => $pageid,
539 'cl_to' => $catTo ],
540 __METHOD__
541 );
542 }
543
544 $redirid = $this->oldTitle->getArticleID();
545
546 if ( $protected ) {
547 # Protect the redirect title as the title used to be...
548 $res = $dbw->select(
549 'page_restrictions',
550 [ 'pr_type', 'pr_level', 'pr_cascade', 'pr_user', 'pr_expiry' ],
551 [ 'pr_page' => $pageid ],
552 __METHOD__,
553 'FOR UPDATE'
554 );
555 $rowsInsert = [];
556 foreach ( $res as $row ) {
557 $rowsInsert[] = [
558 'pr_page' => $redirid,
559 'pr_type' => $row->pr_type,
560 'pr_level' => $row->pr_level,
561 'pr_cascade' => $row->pr_cascade,
562 'pr_user' => $row->pr_user,
563 'pr_expiry' => $row->pr_expiry
564 ];
565 }
566 $dbw->insert( 'page_restrictions', $rowsInsert, __METHOD__, [ 'IGNORE' ] );
567
568 // Build comment for log
569 $comment = wfMessage(
570 'prot_1movedto2',
571 $this->oldTitle->getPrefixedText(),
572 $this->newTitle->getPrefixedText()
573 )->inContentLanguage()->text();
574 if ( $reason ) {
575 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
576 }
577
578 // reread inserted pr_ids for log relation
579 $insertedPrIds = $dbw->select(
580 'page_restrictions',
581 'pr_id',
582 [ 'pr_page' => $redirid ],
583 __METHOD__
584 );
585 $logRelationsValues = [];
586 foreach ( $insertedPrIds as $prid ) {
587 $logRelationsValues[] = $prid->pr_id;
588 }
589
590 // Update the protection log
591 $logEntry = new ManualLogEntry( 'protect', 'move_prot' );
592 $logEntry->setTarget( $this->newTitle );
593 $logEntry->setComment( $comment );
594 $logEntry->setPerformer( $user );
595 $logEntry->setParameters( [
596 '4::oldtitle' => $this->oldTitle->getPrefixedText(),
597 ] );
598 $logEntry->setRelations( [ 'pr_id' => $logRelationsValues ] );
599 $logEntry->setTags( $changeTags );
600 $logId = $logEntry->insert();
601 $logEntry->publish( $logId );
602 }
603
604 // Update *_from_namespace fields as needed
605 if ( $this->oldTitle->getNamespace() != $this->newTitle->getNamespace() ) {
606 $dbw->update( 'pagelinks',
607 [ 'pl_from_namespace' => $this->newTitle->getNamespace() ],
608 [ 'pl_from' => $pageid ],
609 __METHOD__
610 );
611 $dbw->update( 'templatelinks',
612 [ 'tl_from_namespace' => $this->newTitle->getNamespace() ],
613 [ 'tl_from' => $pageid ],
614 __METHOD__
615 );
616 $dbw->update( 'imagelinks',
617 [ 'il_from_namespace' => $this->newTitle->getNamespace() ],
618 [ 'il_from' => $pageid ],
619 __METHOD__
620 );
621 }
622
623 # Update watchlists
624 $oldtitle = $this->oldTitle->getDBkey();
625 $newtitle = $this->newTitle->getDBkey();
626 $oldsnamespace = $this->nsInfo->getSubject( $this->oldTitle->getNamespace() );
627 $newsnamespace = $this->nsInfo->getSubject( $this->newTitle->getNamespace() );
628 if ( $oldsnamespace != $newsnamespace || $oldtitle != $newtitle ) {
629 $this->watchedItems->duplicateAllAssociatedEntries( $this->oldTitle, $this->newTitle );
630 }
631
632 // If it is a file then move it last.
633 // This is done after all database changes so that file system errors cancel the transaction.
634 if ( $this->oldTitle->getNamespace() == NS_FILE ) {
635 $status = $this->moveFile( $this->oldTitle, $this->newTitle );
636 if ( !$status->isOK() ) {
637 $dbw->cancelAtomic( __METHOD__ );
638 return $status;
639 }
640 }
641
642 Hooks::run(
643 'TitleMoveCompleting',
644 [ $this->oldTitle, $this->newTitle,
645 $user, $pageid, $redirid, $reason, $nullRevision ]
646 );
647
648 $dbw->endAtomic( __METHOD__ );
649
650 $params = [
651 &$this->oldTitle,
652 &$this->newTitle,
653 &$user,
654 $pageid,
655 $redirid,
656 $reason,
657 $nullRevision
658 ];
659 // Keep each single hook handler atomic
660 DeferredUpdates::addUpdate(
661 new AtomicSectionUpdate(
662 $dbw,
663 __METHOD__,
664 // Hold onto $user to avoid HHVM bug where it no longer
665 // becomes a reference (T118683)
666 function () use ( $params, &$user ) {
667 Hooks::run( 'TitleMoveComplete', $params );
668 }
669 )
670 );
671
672 return Status::newGood();
673 }
674
675 /**
676 * Move a file associated with a page to a new location.
677 * Can also be used to revert after a DB failure.
678 *
679 * @private
680 * @param Title $oldTitle Old location to move the file from.
681 * @param Title $newTitle New location to move the file to.
682 * @return Status
683 */
684 private function moveFile( $oldTitle, $newTitle ) {
685 $status = Status::newFatal(
686 'cannotdelete',
687 $oldTitle->getPrefixedText()
688 );
689
690 $file = $this->repoGroup->getLocalRepo()->newFile( $oldTitle );
691 $file->load( File::READ_LATEST );
692 if ( $file->exists() ) {
693 $status = $file->move( $newTitle );
694 }
695
696 // Clear RepoGroup process cache
697 $this->repoGroup->clearCache( $oldTitle );
698 $this->repoGroup->clearCache( $newTitle ); # clear false negative cache
699 return $status;
700 }
701
702 /**
703 * Move page to a title which is either a redirect to the
704 * source page or nonexistent
705 *
706 * @todo This was basically directly moved from Title, it should be split into
707 * smaller functions
708 * @param User $user the User doing the move
709 * @param Title $nt The page to move to, which should be a redirect or non-existent
710 * @param string $reason The reason for the move
711 * @param bool $createRedirect Whether to leave a redirect at the old title. Does not check
712 * if the user has the suppressredirect right
713 * @param string[] $changeTags Change tags to apply to the entry in the move log
714 * @return Revision the revision created by the move
715 * @throws MWException
716 */
717 private function moveToInternal( User $user, &$nt, $reason = '', $createRedirect = true,
718 array $changeTags = []
719 ) {
720 if ( $nt->exists() ) {
721 $moveOverRedirect = true;
722 $logType = 'move_redir';
723 } else {
724 $moveOverRedirect = false;
725 $logType = 'move';
726 }
727
728 if ( $moveOverRedirect ) {
729 $overwriteMessage = wfMessage(
730 'delete_and_move_reason',
731 $this->oldTitle->getPrefixedText()
732 )->inContentLanguage()->text();
733 $newpage = WikiPage::factory( $nt );
734 $errs = [];
735 $status = $newpage->doDeleteArticleReal(
736 $overwriteMessage,
737 /* $suppress */ false,
738 $nt->getArticleID(),
739 /* $commit */ false,
740 $errs,
741 $user,
742 $changeTags,
743 'delete_redir'
744 );
745
746 if ( !$status->isGood() ) {
747 throw new MWException( 'Failed to delete page-move revision: '
748 . $status->getWikiText( false, false, 'en' ) );
749 }
750
751 $nt->resetArticleID( false );
752 }
753
754 if ( $createRedirect ) {
755 if ( $this->oldTitle->getNamespace() == NS_CATEGORY
756 && !wfMessage( 'category-move-redirect-override' )->inContentLanguage()->isDisabled()
757 ) {
758 $redirectContent = new WikitextContent(
759 wfMessage( 'category-move-redirect-override' )
760 ->params( $nt->getPrefixedText() )->inContentLanguage()->plain() );
761 } else {
762 $contentHandler = ContentHandler::getForTitle( $this->oldTitle );
763 $redirectContent = $contentHandler->makeRedirectContent( $nt,
764 wfMessage( 'move-redirect-text' )->inContentLanguage()->plain() );
765 }
766
767 // NOTE: If this page's content model does not support redirects, $redirectContent will be null.
768 } else {
769 $redirectContent = null;
770 }
771
772 // Figure out whether the content model is no longer the default
773 $oldDefault = ContentHandler::getDefaultModelFor( $this->oldTitle );
774 $contentModel = $this->oldTitle->getContentModel();
775 $newDefault = ContentHandler::getDefaultModelFor( $nt );
776 $defaultContentModelChanging = ( $oldDefault !== $newDefault
777 && $oldDefault === $contentModel );
778
779 // T59084: log_page should be the ID of the *moved* page
780 $oldid = $this->oldTitle->getArticleID();
781 $logTitle = clone $this->oldTitle;
782
783 $logEntry = new ManualLogEntry( 'move', $logType );
784 $logEntry->setPerformer( $user );
785 $logEntry->setTarget( $logTitle );
786 $logEntry->setComment( $reason );
787 $logEntry->setParameters( [
788 '4::target' => $nt->getPrefixedText(),
789 '5::noredir' => $redirectContent ? '0' : '1',
790 ] );
791
792 $formatter = LogFormatter::newFromEntry( $logEntry );
793 $formatter->setContext( RequestContext::newExtraneousContext( $this->oldTitle ) );
794 $comment = $formatter->getPlainActionText();
795 if ( $reason ) {
796 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
797 }
798
799 $dbw = $this->loadBalancer->getConnection( DB_MASTER );
800
801 $oldpage = WikiPage::factory( $this->oldTitle );
802 $oldcountable = $oldpage->isCountable();
803
804 $newpage = WikiPage::factory( $nt );
805
806 # Change the name of the target page:
807 $dbw->update( 'page',
808 /* SET */ [
809 'page_namespace' => $nt->getNamespace(),
810 'page_title' => $nt->getDBkey(),
811 ],
812 /* WHERE */ [ 'page_id' => $oldid ],
813 __METHOD__
814 );
815
816 # Save a null revision in the page's history notifying of the move
817 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true, $user );
818 if ( !is_object( $nullRevision ) ) {
819 throw new MWException( 'Failed to create null revision while moving page ID '
820 . $oldid . ' to ' . $nt->getPrefixedDBkey() );
821 }
822
823 $nullRevId = $nullRevision->insertOn( $dbw );
824 $logEntry->setAssociatedRevId( $nullRevId );
825
826 /**
827 * T163966
828 * Increment user_editcount during page moves
829 * Moved from SpecialMovepage.php per T195550
830 */
831 $user->incEditCount();
832
833 if ( !$redirectContent ) {
834 // Clean up the old title *before* reset article id - T47348
835 WikiPage::onArticleDelete( $this->oldTitle );
836 }
837
838 $this->oldTitle->resetArticleID( 0 ); // 0 == non existing
839 $nt->resetArticleID( $oldid );
840 $newpage->loadPageData( WikiPage::READ_LOCKING ); // T48397
841
842 $newpage->updateRevisionOn( $dbw, $nullRevision );
843
844 Hooks::run( 'NewRevisionFromEditComplete',
845 [ $newpage, $nullRevision, $nullRevision->getParentId(), $user ] );
846
847 $newpage->doEditUpdates( $nullRevision, $user,
848 [ 'changed' => false, 'moved' => true, 'oldcountable' => $oldcountable ] );
849
850 // If the default content model changes, we need to populate rev_content_model
851 if ( $defaultContentModelChanging ) {
852 $dbw->update(
853 'revision',
854 [ 'rev_content_model' => $contentModel ],
855 [ 'rev_page' => $nt->getArticleID(), 'rev_content_model IS NULL' ],
856 __METHOD__
857 );
858 }
859
860 WikiPage::onArticleCreate( $nt );
861
862 # Recreate the redirect, this time in the other direction.
863 if ( $redirectContent ) {
864 $redirectArticle = WikiPage::factory( $this->oldTitle );
865 $redirectArticle->loadFromRow( false, WikiPage::READ_LOCKING ); // T48397
866 $newid = $redirectArticle->insertOn( $dbw );
867 if ( $newid ) { // sanity
868 $this->oldTitle->resetArticleID( $newid );
869 $redirectRevision = new Revision( [
870 'title' => $this->oldTitle, // for determining the default content model
871 'page' => $newid,
872 'user_text' => $user->getName(),
873 'user' => $user->getId(),
874 'comment' => $comment,
875 'content' => $redirectContent ] );
876 $redirectRevId = $redirectRevision->insertOn( $dbw );
877 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
878
879 Hooks::run( 'NewRevisionFromEditComplete',
880 [ $redirectArticle, $redirectRevision, false, $user ] );
881
882 $redirectArticle->doEditUpdates( $redirectRevision, $user, [ 'created' => true ] );
883
884 // make a copy because of log entry below
885 $redirectTags = $changeTags;
886 if ( in_array( 'mw-new-redirect', ChangeTags::getSoftwareTags() ) ) {
887 $redirectTags[] = 'mw-new-redirect';
888 }
889 ChangeTags::addTags( $redirectTags, null, $redirectRevId, null );
890 }
891 }
892
893 # Log the move
894 $logid = $logEntry->insert();
895
896 $logEntry->setTags( $changeTags );
897 $logEntry->publish( $logid );
898
899 return $nullRevision;
900 }
901 }