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