MediaWiki  master
MovePage.php
Go to the documentation of this file.
1 <?php
2 
40 
47 class MovePage {
48 
52  protected $oldTitle;
53 
57  protected $newTitle;
58 
62  protected $options;
63 
67  protected $loadBalancer;
68 
72  protected $nsInfo;
73 
77  protected $watchedItems;
78 
82  protected $repoGroup;
83 
88 
92  private $revisionStore;
93 
97  private $spamChecker;
98 
102  private $hookContainer;
103 
107  private $hookRunner;
108 
113 
117  private $userFactory;
118 
122  public const CONSTRUCTOR_OPTIONS = [
123  'CategoryCollation'
124  ];
125 
143  public function __construct(
146  ServiceOptions $options = null,
148  NamespaceInfo $nsInfo = null,
150  RepoGroup $repoGroup = null,
153  SpamChecker $spamChecker = null,
157  ) {
158  $this->oldTitle = $oldTitle;
159  $this->newTitle = $newTitle;
160 
161  $services = static function () {
162  // BC hack. Use a closure so this can be unit-tested.
163  return MediaWikiServices::getInstance();
164  };
165  $this->options = $options ??
166  new ServiceOptions(
167  self::CONSTRUCTOR_OPTIONS,
168  $services()->getMainConfig()
169  );
170  $this->loadBalancer = $loadBalancer ?? $services()->getDBLoadBalancer();
171  $this->nsInfo = $nsInfo ?? $services()->getNamespaceInfo();
172  $this->watchedItems = $watchedItems ?? $services()->getWatchedItemStore();
173  $this->repoGroup = $repoGroup ?? $services()->getRepoGroup();
174  $this->contentHandlerFactory =
175  $contentHandlerFactory ?? $services()->getContentHandlerFactory();
176 
177  $this->revisionStore = $revisionStore ?? $services()->getRevisionStore();
178  $this->spamChecker = $spamChecker ?? $services()->getSpamChecker();
179  $this->hookContainer = $hookContainer ?? $services()->getHookContainer();
180  $this->hookRunner = new HookRunner( $this->hookContainer );
181  $this->wikiPageFactory = $wikiPageFactory ?? $services()->getWikiPageFactory();
182  $this->userFactory = $userFactory ?? $services()->getUserFactory();
183  }
184 
191  private function authorizeInternal(
192  callable $authorizer,
193  Authority $performer,
194  ?string $reason
195  ): PermissionStatus {
196  $status = PermissionStatus::newEmpty();
197 
198  $authorizer( 'move', $this->oldTitle, $status );
199  $authorizer( 'edit', $this->oldTitle, $status );
200  $authorizer( 'move-target', $this->newTitle, $status );
201  $authorizer( 'edit', $this->newTitle, $status );
202 
203  if ( $reason !== null && $this->spamChecker->checkSummary( $reason ) !== false ) {
204  // This is kind of lame, won't display nice
205  $status->fatal( 'spamprotectiontext' );
206  }
207 
208  $tp = $this->newTitle->getTitleProtection();
209  if ( $tp !== false && !$performer->isAllowed( $tp['permission'] ) ) {
210  $status->fatal( 'cantmove-titleprotected' );
211  }
212 
213  // TODO: change hook signature to accept Authority and PermissionStatus
214  $user = $this->userFactory->newFromAuthority( $performer );
215  $status = Status::wrap( $status );
216  $this->hookRunner->onMovePageCheckPermissions(
217  $this->oldTitle, $this->newTitle, $user, $reason, $status );
218  // TODO: remove conversion code after hook signature is changed.
219  $permissionStatus = PermissionStatus::newEmpty();
220  foreach ( $status->getErrorsArray() as $error ) {
221  $permissionStatus->fatal( ...$error );
222  }
223  return $permissionStatus;
224  }
225 
237  public function probablyCanMove( Authority $performer, string $reason = null ): PermissionStatus {
238  return $this->authorizeInternal(
239  function ( string $action, PageIdentity $target, PermissionStatus $status ) use ( $performer ) {
240  return $performer->probablyCan( $action, $target, $status );
241  },
242  $performer,
243  $reason
244  );
245  }
246 
258  public function authorizeMove( Authority $performer, string $reason = null ): PermissionStatus {
259  return $this->authorizeInternal(
260  function ( string $action, PageIdentity $target, PermissionStatus $status ) use ( $performer ) {
261  return $performer->authorizeWrite( $action, $target, $status );
262  },
263  $performer,
264  $reason
265  );
266  }
267 
277  public function checkPermissions( Authority $performer, $reason ) {
278  $permissionStatus = $this->authorizeInternal(
279  function ( string $action, PageIdentity $target, PermissionStatus $status ) use ( $performer ) {
280  return $performer->definitelyCan( $action, $target, $status );
281  },
282  $performer,
283  $reason
284  );
285  return Status::wrap( $permissionStatus );
286  }
287 
295  public function isValidMove() {
296  $status = new Status();
297 
298  if ( $this->oldTitle->equals( $this->newTitle ) ) {
299  $status->fatal( 'selfmove' );
300  } elseif ( $this->newTitle->getArticleID() && !$this->isValidMoveTarget() ) {
301  // The move is allowed only if (1) the target doesn't exist, or (2) the target is a
302  // redirect to the source, and has no history (so we can undo bad moves right after
303  // they're done). If the target is a single revision redirect to a different page,
304  // it can be deleted with just `delete-redirect` rights (i.e. without needing
305  // `delete`) - see T239277
306  $fatal = $this->newTitle->isSingleRevRedirect() ? 'redirectexists' : 'articleexists';
307  $status->fatal( $fatal, $this->newTitle->getPrefixedText() );
308  }
309 
310  // @todo If the old title is invalid, maybe we should check if it somehow exists in the
311  // database and allow moving it to a valid name? Why prohibit the move from an empty name
312  // without checking in the database?
313  if ( $this->oldTitle->getDBkey() == '' ) {
314  $status->fatal( 'badarticleerror' );
315  } elseif ( $this->oldTitle->isExternal() ) {
316  $status->fatal( 'immobile-source-namespace-iw' );
317  } elseif ( !$this->oldTitle->isMovable() ) {
318  $nsText = $this->oldTitle->getNsText();
319  if ( $nsText === '' ) {
320  $nsText = wfMessage( 'blanknamespace' )->text();
321  }
322  $status->fatal( 'immobile-source-namespace', $nsText );
323  } elseif ( !$this->oldTitle->exists() ) {
324  $status->fatal( 'movepage-source-doesnt-exist' );
325  }
326 
327  if ( $this->newTitle->isExternal() ) {
328  $status->fatal( 'immobile-target-namespace-iw' );
329  } elseif ( !$this->newTitle->isMovable() ) {
330  $nsText = $this->newTitle->getNsText();
331  if ( $nsText === '' ) {
332  $nsText = wfMessage( 'blanknamespace' )->text();
333  }
334  $status->fatal( 'immobile-target-namespace', $nsText );
335  }
336  if ( !$this->newTitle->isValid() ) {
337  $status->fatal( 'movepage-invalid-target-title' );
338  }
339 
340  // Content model checks
341  if ( !$this->contentHandlerFactory
342  ->getContentHandler( $this->oldTitle->getContentModel() )
343  ->canBeUsedOn( $this->newTitle )
344  ) {
345  $status->fatal(
346  'content-not-allowed-here',
347  ContentHandler::getLocalizedName( $this->oldTitle->getContentModel() ),
348  $this->newTitle->getPrefixedText(),
349  SlotRecord::MAIN
350  );
351  }
352 
353  // Image-specific checks
354  if ( $this->oldTitle->inNamespace( NS_FILE ) ) {
355  $status->merge( $this->isValidFileMove() );
356  }
357 
358  if ( $this->newTitle->inNamespace( NS_FILE ) && !$this->oldTitle->inNamespace( NS_FILE ) ) {
359  $status->fatal( 'nonfile-cannot-move-to-file' );
360  }
361 
362  // Hook for extensions to say a title can't be moved for technical reasons
363  $this->hookRunner->onMovePageIsValidMove( $this->oldTitle, $this->newTitle, $status );
364 
365  return $status;
366  }
367 
373  protected function isValidFileMove() {
374  $status = new Status();
375 
376  if ( !$this->newTitle->inNamespace( NS_FILE ) ) {
377  $status->fatal( 'imagenocrossnamespace' );
378  // No need for further errors about the target filename being wrong
379  return $status;
380  }
381 
382  $file = $this->repoGroup->getLocalRepo()->newFile( $this->oldTitle );
383  $file->load( File::READ_LATEST );
384  if ( $file->exists() ) {
385  if ( $this->newTitle->getText() != wfStripIllegalFilenameChars( $this->newTitle->getText() ) ) {
386  $status->fatal( 'imageinvalidfilename' );
387  }
388  if ( !File::checkExtensionCompatibility( $file, $this->newTitle->getDBkey() ) ) {
389  $status->fatal( 'imagetypemismatch' );
390  }
391  }
392 
393  return $status;
394  }
395 
403  protected function isValidMoveTarget() {
404  # Is it an existing file?
405  if ( $this->newTitle->inNamespace( NS_FILE ) ) {
406  $file = $this->repoGroup->getLocalRepo()->newFile( $this->newTitle );
407  $file->load( File::READ_LATEST );
408  if ( $file->exists() ) {
409  wfDebug( __METHOD__ . ": file exists" );
410  return false;
411  }
412  }
413  # Is it a redirect with no history?
414  if ( !$this->newTitle->isSingleRevRedirect() ) {
415  wfDebug( __METHOD__ . ": not a one-rev redirect" );
416  return false;
417  }
418  # Get the article text
419  $rev = $this->revisionStore->getRevisionByTitle(
420  $this->newTitle,
421  0,
422  RevisionStore::READ_LATEST
423  );
424  if ( !is_object( $rev ) ) {
425  return false;
426  }
427  $content = $rev->getContent( SlotRecord::MAIN );
428  # Does the redirect point to the source?
429  # Or is it a broken self-redirect, usually caused by namespace collisions?
430  $redirTitle = $content ? $content->getRedirectTarget() : null;
431 
432  if ( $redirTitle ) {
433  if ( $redirTitle->getPrefixedDBkey() !== $this->oldTitle->getPrefixedDBkey() &&
434  $redirTitle->getPrefixedDBkey() !== $this->newTitle->getPrefixedDBkey() ) {
435  wfDebug( __METHOD__ . ": redirect points to other page" );
436  return false;
437  } else {
438  return true;
439  }
440  } else {
441  # Fail safe (not a redirect after all. strange.)
442  wfDebug( __METHOD__ . ": failsafe: database says " . $this->newTitle->getPrefixedDBkey() .
443  " is a redirect, but it doesn't contain a valid redirect." );
444  return false;
445  }
446  }
447 
459  public function move(
460  UserIdentity $user, $reason = null, $createRedirect = true, array $changeTags = []
461  ) {
462  $status = $this->isValidMove();
463  if ( !$status->isOK() ) {
464  return $status;
465  }
466 
467  return $this->moveUnsafe( $user, $reason, $createRedirect, $changeTags );
468  }
469 
479  public function moveIfAllowed(
480  Authority $performer, $reason = null, $createRedirect = true, array $changeTags = []
481  ) {
482  $status = $this->isValidMove();
483  $status->merge( $this->authorizeMove( $performer, $reason ) );
484  if ( $changeTags ) {
485  $status->merge( ChangeTags::canAddTagsAccompanyingChange( $changeTags, $performer ) );
486  }
487 
488  if ( !$status->isOK() ) {
489  // TODO: wrap block spreading into Authority side-effect?
490  $user = $this->userFactory->newFromAuthority( $performer );
491  // Auto-block user's IP if the account was "hard" blocked
492  $user->spreadAnyEditBlock();
493  return $status;
494  }
495 
496  // Check suppressredirect permission
497  if ( !$performer->isAllowed( 'suppressredirect' ) ) {
498  $createRedirect = true;
499  }
500 
501  return $this->moveUnsafe( $performer->getUser(), $reason, $createRedirect, $changeTags );
502  }
503 
518  public function moveSubpages(
519  UserIdentity $user, $reason = null, $createRedirect = true, array $changeTags = []
520  ) {
521  return $this->moveSubpagesInternal(
522  function ( Title $oldSubpage, Title $newSubpage )
523  use ( $user, $reason, $createRedirect, $changeTags ) {
524  $mp = new MovePage( $oldSubpage, $newSubpage );
525  return $mp->move( $user, $reason, $createRedirect, $changeTags );
526  }
527  );
528  }
529 
543  public function moveSubpagesIfAllowed(
544  Authority $performer, $reason = null, $createRedirect = true, array $changeTags = []
545  ) {
546  if ( !$performer->authorizeWrite( 'move-subpages', $this->oldTitle ) ) {
547  return Status::newFatal( 'cant-move-subpages' );
548  }
549  return $this->moveSubpagesInternal(
550  function ( Title $oldSubpage, Title $newSubpage )
551  use ( $performer, $reason, $createRedirect, $changeTags ) {
552  $mp = new MovePage( $oldSubpage, $newSubpage );
553  return $mp->moveIfAllowed( $performer, $reason, $createRedirect, $changeTags );
554  }
555  );
556  }
557 
563  private function moveSubpagesInternal( callable $subpageMoveCallback ) {
564  global $wgMaximumMovedPages;
565 
566  // Do the source and target namespaces support subpages?
567  if ( !$this->nsInfo->hasSubpages( $this->oldTitle->getNamespace() ) ) {
568  return Status::newFatal( 'namespace-nosubpages',
569  $this->nsInfo->getCanonicalName( $this->oldTitle->getNamespace() ) );
570  }
571  if ( !$this->nsInfo->hasSubpages( $this->newTitle->getNamespace() ) ) {
572  return Status::newFatal( 'namespace-nosubpages',
573  $this->nsInfo->getCanonicalName( $this->newTitle->getNamespace() ) );
574  }
575 
576  // Return a status for the overall result. Its value will be an array with per-title
577  // status for each subpage. Merge any errors from the per-title statuses into the
578  // top-level status without resetting the overall result.
579  $topStatus = Status::newGood();
580  $perTitleStatus = [];
581  $subpages = $this->oldTitle->getSubpages( $wgMaximumMovedPages + 1 );
582  $count = 0;
583  foreach ( $subpages as $oldSubpage ) {
584  $count++;
585  if ( $count > $wgMaximumMovedPages ) {
586  $status = Status::newFatal( 'movepage-max-pages', $wgMaximumMovedPages );
587  $perTitleStatus[$oldSubpage->getPrefixedText()] = $status;
588  $topStatus->merge( $status );
589  $topStatus->setOK( true );
590  break;
591  }
592 
593  // We don't know whether this function was called before or after moving the root page,
594  // so check both titles
595  if ( $oldSubpage->getArticleID() == $this->oldTitle->getArticleID() ||
596  $oldSubpage->getArticleID() == $this->newTitle->getArticleID()
597  ) {
598  // When moving a page to a subpage of itself, don't move it twice
599  continue;
600  }
601  $newPageName = preg_replace(
602  '#^' . preg_quote( $this->oldTitle->getDBkey(), '#' ) . '#',
603  StringUtils::escapeRegexReplacement( $this->newTitle->getDBkey() ), # T23234
604  $oldSubpage->getDBkey() );
605  if ( $oldSubpage->isTalkPage() ) {
606  $newNs = $this->newTitle->getTalkPage()->getNamespace();
607  } else {
608  $newNs = $this->newTitle->getSubjectPage()->getNamespace();
609  }
610  // T16385: we need makeTitleSafe because the new page names may be longer than 255
611  // characters.
612  $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
613  $status = $subpageMoveCallback( $oldSubpage, $newSubpage );
614  if ( $status->isOK() ) {
615  $status->setResult( true, $newSubpage->getPrefixedText() );
616  }
617  $perTitleStatus[$oldSubpage->getPrefixedText()] = $status;
618  $topStatus->merge( $status );
619  $topStatus->setOK( true );
620  }
621 
622  $topStatus->value = $perTitleStatus;
623  return $topStatus;
624  }
625 
635  private function moveUnsafe( UserIdentity $user, $reason, $createRedirect, array $changeTags ) {
636  $status = Status::newGood();
637 
638  // TODO: make hooks accept UserIdentity
639  $userObj = $this->userFactory->newFromUserIdentity( $user );
640  $this->hookRunner->onTitleMove( $this->oldTitle, $this->newTitle, $userObj, $reason, $status );
641  if ( !$status->isOK() ) {
642  // Move was aborted by the hook
643  return $status;
644  }
645 
646  $dbw = $this->loadBalancer->getConnection( DB_MASTER );
647  $dbw->startAtomic( __METHOD__, IDatabase::ATOMIC_CANCELABLE );
648 
649  $this->hookRunner->onTitleMoveStarting( $this->oldTitle, $this->newTitle, $userObj );
650 
651  $pageid = $this->oldTitle->getArticleID( Title::READ_LATEST );
652  $protected = $this->oldTitle->isProtected();
653 
654  // Attempt the actual move
655  $moveAttemptResult = $this->moveToInternal( $userObj, $this->newTitle, $reason, $createRedirect,
656  $changeTags );
657 
658  if ( $moveAttemptResult instanceof Status ) {
659  // T265779: Attempt to delete target page failed
660  $dbw->cancelAtomic( __METHOD__ );
661  return $moveAttemptResult;
662  } else {
663  $nullRevision = $moveAttemptResult;
664  }
665 
666  // Refresh the sortkey for this row. Be careful to avoid resetting
667  // cl_timestamp, which may disturb time-based lists on some sites.
668  // @todo This block should be killed, it's duplicating code
669  // from LinksUpdate::getCategoryInsertions() and friends.
670  $prefixes = $dbw->select(
671  'categorylinks',
672  [ 'cl_sortkey_prefix', 'cl_to' ],
673  [ 'cl_from' => $pageid ],
674  __METHOD__
675  );
676  $type = $this->nsInfo->getCategoryLinkType( $this->newTitle->getNamespace() );
677  foreach ( $prefixes as $prefixRow ) {
678  $prefix = $prefixRow->cl_sortkey_prefix;
679  $catTo = $prefixRow->cl_to;
680  $dbw->update( 'categorylinks',
681  [
682  'cl_sortkey' => Collation::singleton()->getSortKey(
683  $this->newTitle->getCategorySortkey( $prefix ) ),
684  'cl_collation' => $this->options->get( 'CategoryCollation' ),
685  'cl_type' => $type,
686  'cl_timestamp=cl_timestamp' ],
687  [
688  'cl_from' => $pageid,
689  'cl_to' => $catTo ],
690  __METHOD__
691  );
692  }
693 
694  $redirid = $this->oldTitle->getArticleID();
695 
696  if ( $protected ) {
697  # Protect the redirect title as the title used to be...
698  $res = $dbw->select(
699  'page_restrictions',
700  [ 'pr_type', 'pr_level', 'pr_cascade', 'pr_user', 'pr_expiry' ],
701  [ 'pr_page' => $pageid ],
702  __METHOD__,
703  'FOR UPDATE'
704  );
705  $rowsInsert = [];
706  foreach ( $res as $row ) {
707  $rowsInsert[] = [
708  'pr_page' => $redirid,
709  'pr_type' => $row->pr_type,
710  'pr_level' => $row->pr_level,
711  'pr_cascade' => $row->pr_cascade,
712  'pr_user' => $row->pr_user,
713  'pr_expiry' => $row->pr_expiry
714  ];
715  }
716  $dbw->insert( 'page_restrictions', $rowsInsert, __METHOD__, [ 'IGNORE' ] );
717 
718  // Build comment for log
719  $comment = wfMessage(
720  'prot_1movedto2',
721  $this->oldTitle->getPrefixedText(),
722  $this->newTitle->getPrefixedText()
723  )->inContentLanguage()->text();
724  if ( $reason ) {
725  $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
726  }
727 
728  // reread inserted pr_ids for log relation
729  $insertedPrIds = $dbw->select(
730  'page_restrictions',
731  'pr_id',
732  [ 'pr_page' => $redirid ],
733  __METHOD__
734  );
735  $logRelationsValues = [];
736  foreach ( $insertedPrIds as $prid ) {
737  $logRelationsValues[] = $prid->pr_id;
738  }
739 
740  // Update the protection log
741  $logEntry = new ManualLogEntry( 'protect', 'move_prot' );
742  $logEntry->setTarget( $this->newTitle );
743  $logEntry->setComment( $comment );
744  $logEntry->setPerformer( $user );
745  $logEntry->setParameters( [
746  '4::oldtitle' => $this->oldTitle->getPrefixedText(),
747  ] );
748  $logEntry->setRelations( [ 'pr_id' => $logRelationsValues ] );
749  $logEntry->addTags( $changeTags );
750  $logId = $logEntry->insert();
751  $logEntry->publish( $logId );
752  }
753 
754  // Update *_from_namespace fields as needed
755  if ( $this->oldTitle->getNamespace() != $this->newTitle->getNamespace() ) {
756  $dbw->update( 'pagelinks',
757  [ 'pl_from_namespace' => $this->newTitle->getNamespace() ],
758  [ 'pl_from' => $pageid ],
759  __METHOD__
760  );
761  $dbw->update( 'templatelinks',
762  [ 'tl_from_namespace' => $this->newTitle->getNamespace() ],
763  [ 'tl_from' => $pageid ],
764  __METHOD__
765  );
766  $dbw->update( 'imagelinks',
767  [ 'il_from_namespace' => $this->newTitle->getNamespace() ],
768  [ 'il_from' => $pageid ],
769  __METHOD__
770  );
771  }
772 
773  # Update watchlists
774  $oldtitle = $this->oldTitle->getDBkey();
775  $newtitle = $this->newTitle->getDBkey();
776  $oldsnamespace = $this->nsInfo->getSubject( $this->oldTitle->getNamespace() );
777  $newsnamespace = $this->nsInfo->getSubject( $this->newTitle->getNamespace() );
778  if ( $oldsnamespace != $newsnamespace || $oldtitle != $newtitle ) {
779  $this->watchedItems->duplicateAllAssociatedEntries( $this->oldTitle, $this->newTitle );
780  }
781 
782  // If it is a file then move it last.
783  // This is done after all database changes so that file system errors cancel the transaction.
784  if ( $this->oldTitle->getNamespace() === NS_FILE ) {
785  $status = $this->moveFile( $this->oldTitle, $this->newTitle );
786  if ( !$status->isOK() ) {
787  $dbw->cancelAtomic( __METHOD__ );
788  return $status;
789  }
790  }
791 
792  $this->hookRunner->onPageMoveCompleting(
793  $this->oldTitle, $this->newTitle,
794  $user, $pageid, $redirid, $reason, $nullRevision
795  );
796 
797  // Deprecated since 1.35, use PageMoveCompleting
798  if ( $this->hookContainer->isRegistered( 'TitleMoveCompleting' ) ) {
799  // Only create the Revision object if needed
800  $nullRevisionObj = new Revision( $nullRevision );
801  $this->hookRunner->onTitleMoveCompleting(
802  $this->oldTitle,
803  $this->newTitle,
804  $userObj,
805  $pageid,
806  $redirid,
807  $reason,
808  $nullRevisionObj
809  );
810  }
811 
812  $dbw->endAtomic( __METHOD__ );
813 
814  // Keep each single hook handler atomic
817  $dbw,
818  __METHOD__,
819  function () use ( $user, $userObj, $pageid, $redirid, $reason, $nullRevision ) {
820  $this->hookRunner->onPageMoveComplete(
821  $this->oldTitle,
822  $this->newTitle,
823  $user,
824  $pageid,
825  $redirid,
826  $reason,
827  $nullRevision
828  );
829 
830  if ( !$this->hookContainer->isRegistered( 'TitleMoveComplete' ) ) {
831  // Don't go on to create a Revision unless its needed
832  return;
833  }
834 
835  $nullRevisionObj = new Revision( $nullRevision );
836  // Deprecated since 1.35, use PageMoveComplete
837  $this->hookRunner->onTitleMoveComplete(
838  $this->oldTitle,
839  $this->newTitle,
840  $userObj, $pageid,
841  $redirid,
842  $reason,
843  $nullRevisionObj
844  );
845  }
846  )
847  );
848 
849  return Status::newGood();
850  }
851 
861  private function moveFile( $oldTitle, $newTitle ) {
862  $file = $this->repoGroup->getLocalRepo()->newFile( $oldTitle );
863  $file->load( File::READ_LATEST );
864  if ( $file->exists() ) {
865  $status = $file->move( $newTitle );
866  } else {
867  $status = Status::newGood();
868  }
869 
870  // Clear RepoGroup process cache
871  $this->repoGroup->clearCache( $oldTitle );
872  $this->repoGroup->clearCache( $newTitle ); # clear false negative cache
873  return $status;
874  }
875 
890  private function moveToInternal( UserIdentity $user, &$nt, $reason = '', $createRedirect = true,
891  array $changeTags = []
892  ) {
893  $userObj = $this->userFactory->newFromUserIdentity( $user );
894  if ( $nt->getArticleId( Title::READ_LATEST ) ) {
895  $moveOverRedirect = true;
896  $logType = 'move_redir';
897  } else {
898  $moveOverRedirect = false;
899  $logType = 'move';
900  }
901 
902  if ( $moveOverRedirect ) {
903  $overwriteMessage = wfMessage(
904  'delete_and_move_reason',
905  $this->oldTitle->getPrefixedText()
906  )->inContentLanguage()->text();
907  $newpage = $this->wikiPageFactory->newFromTitle( $nt );
908  $errs = [];
909  $status = $newpage->doDeleteArticleReal(
910  $overwriteMessage,
911  $userObj,
912  /* $suppress */ false,
913  /* unused */ null,
914  $errs,
915  /* unused */ null,
916  $changeTags,
917  'delete_redir'
918  );
919 
920  if ( !$status->isGood() ) {
921  return $status;
922  }
923 
924  $nt->resetArticleID( false );
925  }
926 
927  if ( $createRedirect ) {
928  if ( $this->oldTitle->getNamespace() === NS_CATEGORY
929  && !wfMessage( 'category-move-redirect-override' )->inContentLanguage()->isDisabled()
930  ) {
931  $redirectContent = new WikitextContent(
932  wfMessage( 'category-move-redirect-override' )
933  ->params( $nt->getPrefixedText() )->inContentLanguage()->plain() );
934  } else {
935  $redirectContent = $this->contentHandlerFactory
936  ->getContentHandler( $this->oldTitle->getContentModel() )
937  ->makeRedirectContent(
938  $nt,
939  wfMessage( 'move-redirect-text' )->inContentLanguage()->plain()
940  );
941  }
942 
943  // NOTE: If this page's content model does not support redirects, $redirectContent will be null.
944  } else {
945  $redirectContent = null;
946  }
947 
948  // T59084: log_page should be the ID of the *moved* page
949  $oldid = $this->oldTitle->getArticleID();
950  $logTitle = clone $this->oldTitle;
951 
952  $logEntry = new ManualLogEntry( 'move', $logType );
953  $logEntry->setPerformer( $user );
954  $logEntry->setTarget( $logTitle );
955  $logEntry->setComment( $reason );
956  $logEntry->setParameters( [
957  '4::target' => $nt->getPrefixedText(),
958  '5::noredir' => $redirectContent ? '0' : '1',
959  ] );
960 
961  $formatter = LogFormatter::newFromEntry( $logEntry );
962  $formatter->setContext( RequestContext::newExtraneousContext( $this->oldTitle ) );
963  $comment = $formatter->getPlainActionText();
964  if ( $reason ) {
965  $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
966  }
967 
968  $dbw = $this->loadBalancer->getConnection( DB_MASTER );
969 
970  $oldpage = $this->wikiPageFactory->newFromTitle( $this->oldTitle );
971  $oldcountable = $oldpage->isCountable();
972 
973  $newpage = $this->wikiPageFactory->newFromTitle( $nt );
974 
975  # Change the name of the target page:
976  $dbw->update( 'page',
977  /* SET */ [
978  'page_namespace' => $nt->getNamespace(),
979  'page_title' => $nt->getDBkey(),
980  ],
981  /* WHERE */ [ 'page_id' => $oldid ],
982  __METHOD__
983  );
984 
985  // Reset $nt before using it to create the null revision (T248789).
986  // But not $this->oldTitle yet, see below (T47348).
987  $nt->resetArticleID( $oldid );
988 
989  $commentObj = CommentStoreComment::newUnsavedComment( $comment );
990  # Save a null revision in the page's history notifying of the move
991  $nullRevision = $this->revisionStore->newNullRevision(
992  $dbw,
993  $nt,
994  $commentObj,
995  true,
996  $user
997  );
998  if ( $nullRevision === null ) {
999  $id = $nt->getArticleID( Title::READ_EXCLUSIVE );
1000  $msg = 'Failed to create null revision while moving page ID ' .
1001  $oldid . ' to ' . $nt->getPrefixedDBkey() . " (page ID $id)";
1002 
1003  throw new MWException( $msg );
1004  }
1005 
1006  $nullRevision = $this->revisionStore->insertRevisionOn( $nullRevision, $dbw );
1007  $logEntry->setAssociatedRevId( $nullRevision->getId() );
1008 
1014  $userObj->incEditCount();
1015 
1016  if ( !$redirectContent ) {
1017  // Clean up the old title *before* reset article id - T47348
1018  WikiPage::onArticleDelete( $this->oldTitle );
1019  }
1020 
1021  $this->oldTitle->resetArticleID( 0 ); // 0 == non existing
1022  $newpage->loadPageData( WikiPage::READ_LOCKING ); // T48397
1023 
1024  $newpage->updateRevisionOn( $dbw, $nullRevision );
1025 
1026  $fakeTags = [];
1027  $this->hookRunner->onRevisionFromEditComplete(
1028  $newpage, $nullRevision, $nullRevision->getParentId(), $user, $fakeTags );
1029 
1030  // Hook is hard deprecated since 1.35
1031  if ( $this->hookContainer->isRegistered( 'NewRevisionFromEditComplete' ) ) {
1032  // Only create the Revision object if needed
1033  $nullRevisionObj = new Revision( $nullRevision );
1034  $this->hookRunner->onNewRevisionFromEditComplete(
1035  $newpage,
1036  $nullRevisionObj,
1037  $nullRevision->getParentId(),
1038  $userObj,
1039  $fakeTags
1040  );
1041  }
1042 
1043  $newpage->doEditUpdates( $nullRevision, $userObj,
1044  [ 'changed' => false, 'moved' => true, 'oldcountable' => $oldcountable ] );
1045 
1047 
1048  # Recreate the redirect, this time in the other direction.
1049  if ( $redirectContent ) {
1050  $redirectArticle = $this->wikiPageFactory->newFromTitle( $this->oldTitle );
1051  $redirectArticle->loadFromRow( false, WikiPage::READ_LOCKING ); // T48397
1052  $newid = $redirectArticle->insertOn( $dbw );
1053  if ( $newid ) { // sanity
1054  $this->oldTitle->resetArticleID( $newid );
1055  $redirectRevRecord = new MutableRevisionRecord( $this->oldTitle );
1056  $redirectRevRecord->setPageId( $newid )
1057  ->setUser( $user )
1058  ->setComment( $commentObj )
1059  ->setContent( SlotRecord::MAIN, $redirectContent )
1060  ->setTimestamp( MWTimestamp::now( TS_MW ) );
1061 
1062  $inserted = $this->revisionStore->insertRevisionOn(
1063  $redirectRevRecord,
1064  $dbw
1065  );
1066  $redirectRevId = $inserted->getId();
1067  $redirectArticle->updateRevisionOn( $dbw, $inserted, 0 );
1068 
1069  $fakeTags = [];
1070  $this->hookRunner->onRevisionFromEditComplete(
1071  $redirectArticle,
1072  $inserted,
1073  false,
1074  $user,
1075  $fakeTags
1076  );
1077 
1078  // Hook is hard deprecated since 1.35
1079  if ( $this->hookContainer->isRegistered( 'NewRevisionFromEditComplete' ) ) {
1080  // Only create the Revision object if needed
1081  $redirectRevisionObj = new Revision( $inserted );
1082  $this->hookRunner->onNewRevisionFromEditComplete(
1083  $redirectArticle,
1084  $redirectRevisionObj,
1085  false,
1086  $userObj,
1087  $fakeTags
1088  );
1089  }
1090 
1091  $redirectArticle->doEditUpdates(
1092  $inserted,
1093  $userObj,
1094  [ 'created' => true ]
1095  );
1096 
1097  // make a copy because of log entry below
1098  $redirectTags = $changeTags;
1099  if ( in_array( 'mw-new-redirect', ChangeTags::getSoftwareTags() ) ) {
1100  $redirectTags[] = 'mw-new-redirect';
1101  }
1102  ChangeTags::addTags( $redirectTags, null, $redirectRevId, null );
1103  }
1104  }
1105 
1106  # Log the move
1107  $logid = $logEntry->insert();
1108 
1109  $logEntry->addTags( $changeTags );
1110  $logEntry->publish( $logid );
1111 
1112  return $nullRevision;
1113  }
1114 }
Page\PageIdentity
Interface for objects (potentially) representing an editable wiki page.
Definition: PageIdentity.php:65
MovePage\probablyCanMove
probablyCanMove(Authority $performer, string $reason=null)
Check whether $performer can execute the move.
Definition: MovePage.php:237
CommentStoreComment\newUnsavedComment
static newUnsavedComment( $comment, array $data=null)
Create a new, unsaved CommentStoreComment.
Definition: CommentStoreComment.php:67
File\checkExtensionCompatibility
static checkExtensionCompatibility(File $old, $new)
Checks if file extensions are compatible.
Definition: File.php:264
WikiPage\onArticleCreate
static onArticleCreate(Title $title)
The onArticle*() functions are supposed to be a kind of hooks which should be called whenever any of ...
Definition: WikiPage.php:3656
Revision\RevisionRecord
Page revision base class.
Definition: RevisionRecord.php:47
MovePage\moveSubpages
moveSubpages(UserIdentity $user, $reason=null, $createRedirect=true, array $changeTags=[])
Move the source page's subpages to be subpages of the target page, without checking user permissions.
Definition: MovePage.php:518
MovePage\$loadBalancer
ILoadBalancer $loadBalancer
Definition: MovePage.php:67
StatusValue\newFatal
static newFatal( $message,... $parameters)
Factory function for fatal errors.
Definition: StatusValue.php:70
$wgMaximumMovedPages
$wgMaximumMovedPages
Maximum number of pages to move at once when moving subpages with a page.
Definition: DefaultSettings.php:9121
MovePage\isValidMoveTarget
isValidMoveTarget()
Checks if $this can be moved to a given Title.
Definition: MovePage.php:403
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:173
MovePage\$oldTitle
Title $oldTitle
Definition: MovePage.php:52
Revision\RevisionStore
Service for looking up page revisions.
Definition: RevisionStore.php:89
MovePage\$revisionStore
RevisionStore $revisionStore
Definition: MovePage.php:92
MovePage\authorizeMove
authorizeMove(Authority $performer, string $reason=null)
Authorize the move by $performer.
Definition: MovePage.php:258
MovePage\moveFile
moveFile( $oldTitle, $newTitle)
Move a file associated with a page to a new location.
Definition: MovePage.php:861
DeferredUpdates\addUpdate
static addUpdate(DeferrableUpdate $update, $stage=self::POSTSEND)
Add an update to the pending update queue for execution at the appropriate time.
Definition: DeferredUpdates.php:119
MovePage\isValidMove
isValidMove()
Does various sanity checks that the move is valid.
Definition: MovePage.php:295
StringUtils\escapeRegexReplacement
static escapeRegexReplacement( $string)
Escape a string to make it suitable for inclusion in a preg_replace() replacement parameter.
Definition: StringUtils.php:314
$file
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1231
RequestContext\newExtraneousContext
static newExtraneousContext(Title $title, $request=[])
Create a new extraneous context.
Definition: RequestContext.php:646
$res
$res
Definition: testCompression.php:57
MediaWiki\Permissions\Authority\probablyCan
probablyCan(string $action, PageIdentity $target, PermissionStatus $status=null)
Checks whether this authority can probably perform the given action on the given target page.
MediaWiki\Permissions\Authority\getUser
getUser()
Returns the performer of the actions associated with this authority.
MediaWiki\User\UserIdentity
Interface for objects representing user identity.
Definition: UserIdentity.php:39
Wikimedia\Rdbms\IDatabase
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
MovePage\checkPermissions
checkPermissions(Authority $performer, $reason)
Check if the user is allowed to perform the move.
Definition: MovePage.php:277
MovePage\moveIfAllowed
moveIfAllowed(Authority $performer, $reason=null, $createRedirect=true, array $changeTags=[])
Same as move(), but with permissions checks.
Definition: MovePage.php:479
Status
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Definition: Status.php:44
Collation\singleton
static singleton()
Definition: Collation.php:37
MovePage\move
move(UserIdentity $user, $reason=null, $createRedirect=true, array $changeTags=[])
Move a page without taking user permissions into account.
Definition: MovePage.php:459
Revision
Definition: Revision.php:40
MovePage\$wikiPageFactory
WikiPageFactory $wikiPageFactory
Definition: MovePage.php:112
MovePage\$options
ServiceOptions $options
Definition: MovePage.php:62
MWException
MediaWiki exception.
Definition: MWException.php:29
wfStripIllegalFilenameChars
wfStripIllegalFilenameChars( $name)
Replace all invalid characters with '-'.
Definition: GlobalFunctions.php:2598
MovePage\$repoGroup
RepoGroup $repoGroup
Definition: MovePage.php:82
MediaWiki\Config\ServiceOptions
A class for passing options to services.
Definition: ServiceOptions.php:27
MovePage
Handles the backend logic of moving a page from one title to another.
Definition: MovePage.php:47
Status\wrap
static wrap( $sv)
Succinct helper method to wrap a StatusValue.
Definition: Status.php:62
MovePage\moveSubpagesIfAllowed
moveSubpagesIfAllowed(Authority $performer, $reason=null, $createRedirect=true, array $changeTags=[])
Move the source page's subpages to be subpages of the target page, with user permission checks.
Definition: MovePage.php:543
MovePage\$nsInfo
NamespaceInfo $nsInfo
Definition: MovePage.php:72
WikiPage\onArticleDelete
static onArticleDelete(Title $title)
Clears caches when article is deleted.
Definition: WikiPage.php:3692
MovePage\$hookRunner
HookRunner $hookRunner
Definition: MovePage.php:107
Page\WikiPageFactory
Definition: WikiPageFactory.php:20
ChangeTags\getSoftwareTags
static getSoftwareTags( $all=false)
Loads defined core tags, checks for invalid types (if not array), and filters for supported and enabl...
Definition: ChangeTags.php:140
MovePage\moveToInternal
moveToInternal(UserIdentity $user, &$nt, $reason='', $createRedirect=true, array $changeTags=[])
Move page to a title which is either a redirect to the source page or nonexistent.
Definition: MovePage.php:890
MediaWiki\Permissions\Authority\authorizeWrite
authorizeWrite(string $action, PageIdentity $target, PermissionStatus $status=null)
Authorize write access.
DB_MASTER
const DB_MASTER
Definition: defines.php:26
WikitextContent
Content object for wiki text pages.
Definition: WikitextContent.php:37
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:915
MovePage\__construct
__construct(Title $oldTitle, Title $newTitle, ServiceOptions $options=null, ILoadBalancer $loadBalancer=null, NamespaceInfo $nsInfo=null, WatchedItemStoreInterface $watchedItems=null, RepoGroup $repoGroup=null, IContentHandlerFactory $contentHandlerFactory=null, RevisionStore $revisionStore=null, SpamChecker $spamChecker=null, HookContainer $hookContainer=null, WikiPageFactory $wikiPageFactory=null, UserFactory $userFactory=null)
Calling this directly is deprecated in 1.34.
Definition: MovePage.php:143
MediaWiki\Permissions\Authority\definitelyCan
definitelyCan(string $action, PageIdentity $target, PermissionStatus $status=null)
Checks whether this authority can perform the given action on the given target page.
MediaWiki\Permissions\Authority
Definition: Authority.php:30
AtomicSectionUpdate
Deferrable Update for closure/callback updates via IDatabase::doAtomicSection()
Definition: AtomicSectionUpdate.php:9
ChangeTags\canAddTagsAccompanyingChange
static canAddTagsAccompanyingChange(array $tags, Authority $performer=null)
Is it OK to allow the user to apply all the specified tags at the same time as they edit/make the cha...
Definition: ChangeTags.php:601
Title\makeTitleSafe
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:652
$content
$content
Definition: router.php:76
ContentHandler\getLocalizedName
static getLocalizedName( $name, Language $lang=null)
Returns the localized name for a given content model.
Definition: ContentHandler.php:299
MediaWiki\Content\IContentHandlerFactory
Definition: IContentHandlerFactory.php:10
StatusValue\newGood
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:82
Revision\MutableRevisionRecord
Definition: MutableRevisionRecord.php:45
MediaWiki\EditPage\SpamChecker
Service to check if text (either content or a summary) qualifies as spam.
Definition: SpamChecker.php:14
MovePage\$newTitle
Title $newTitle
Definition: MovePage.php:57
MovePage\moveUnsafe
moveUnsafe(UserIdentity $user, $reason, $createRedirect, array $changeTags)
Moves without any sort of safety or sanity checks.
Definition: MovePage.php:635
MovePage\$watchedItems
WatchedItemStoreInterface $watchedItems
Definition: MovePage.php:77
MovePage\$contentHandlerFactory
IContentHandlerFactory $contentHandlerFactory
Definition: MovePage.php:87
MediaWiki\Permissions\PermissionStatus
A StatusValue for permission errors.
Definition: PermissionStatus.php:34
Title
Represents a title within MediaWiki.
Definition: Title.php:46
MediaWiki\Permissions\Authority\isAllowed
isAllowed(string $permission)
Checks whether this authority has the given permission in general.
MovePage\$userFactory
UserFactory $userFactory
Definition: MovePage.php:117
MovePage\moveSubpagesInternal
moveSubpagesInternal(callable $subpageMoveCallback)
Definition: MovePage.php:563
RepoGroup
Prioritized list of file repositories.
Definition: RepoGroup.php:31
NS_CATEGORY
const NS_CATEGORY
Definition: Defines.php:78
MovePage\isValidFileMove
isValidFileMove()
Sanity checks for when a file is being moved.
Definition: MovePage.php:373
ManualLogEntry
Class for creating new log entries and inserting them into the database.
Definition: ManualLogEntry.php:43
MediaWiki\HookContainer\HookContainer
HookContainer class.
Definition: HookContainer.php:45
NamespaceInfo
This is a utility class for dealing with namespaces that encodes all the "magic" behaviors of them ba...
Definition: NamespaceInfo.php:35
MovePage\$spamChecker
SpamChecker $spamChecker
Definition: MovePage.php:97
MediaWiki\HookContainer\HookRunner
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
Definition: HookRunner.php:576
MovePage\authorizeInternal
authorizeInternal(callable $authorizer, Authority $performer, ?string $reason)
Definition: MovePage.php:191
MovePage\$hookContainer
HookContainer $hookContainer
Definition: MovePage.php:102
NS_FILE
const NS_FILE
Definition: Defines.php:70
WatchedItemStoreInterface
Definition: WatchedItemStoreInterface.php:30
MovePage\CONSTRUCTOR_OPTIONS
const CONSTRUCTOR_OPTIONS
Definition: MovePage.php:122
MediaWiki\User\UserFactory
Creates User objects.
Definition: UserFactory.php:41
Wikimedia\Rdbms\ILoadBalancer
Database cluster connection, tracking, load balancing, and transaction manager interface.
Definition: ILoadBalancer.php:81
ChangeTags\addTags
static addTags( $tags, $rc_id=null, $rev_id=null, $log_id=null, $params=null, RecentChange $rc=null)
Add tags to a change given its rc_id, rev_id and/or log_id.
Definition: ChangeTags.php:310
Revision\SlotRecord
Value object representing a content slot associated with a page revision.
Definition: SlotRecord.php:40
LogFormatter\newFromEntry
static newFromEntry(LogEntry $entry)
Constructs a new formatter suitable for given entry.
Definition: LogFormatter.php:54
$type
$type
Definition: testCompression.php:52