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