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