MediaWiki  master
MovePage.php
Go to the documentation of this file.
1 <?php
2 
29 
36 class MovePage {
37 
41  protected $oldTitle;
42 
46  protected $newTitle;
47 
51  protected $options;
52 
56  protected $loadBalancer;
57 
61  protected $nsInfo;
62 
66  protected $watchedItems;
67 
71  protected $permMgr;
72 
76  protected $repoGroup;
77 
89  public function __construct(
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
498  private function moveUnsafe( User $user, $reason, $createRedirect, array $changeTags ) {
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->setTags( $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 = [
655  &$user,
656  $pageid,
657  $redirid,
658  $reason,
659  $nullRevision
660  ];
661  // Keep each single hook handler atomic
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 
686  private function moveFile( $oldTitle, $newTitle ) {
688  'cannotdelete',
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 
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 
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 
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->setTags( $changeTags );
899  $logEntry->publish( $logid );
900 
901  return $nullRevision;
902  }
903 }
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:138
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:3388
WatchedItemStore $watchedItems
Definition: MovePage.php:66
either a plain
Definition: hooks.txt:2039
moveUnsafe(User $user, $reason, $createRedirect, array $changeTags)
Moves without any sort of safety or sanity checks.
Definition: MovePage.php:498
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Definition: router.php:42
static singleton()
Definition: Collation.php:36
static escapeRegexReplacement( $string)
Escape a string to make it suitable for inclusion in a preg_replace() replacement parameter...
static newFromEntry(LogEntry $entry)
Constructs a new formatter suitable for given entry.
const READ_LOCKING
Constants for object loading bitfield flags (higher => higher QoS)
static getDefaultModelFor(Title $title)
Returns the name of the default content model to be used for the page with the given title...
wfStripIllegalFilenameChars( $name)
Replace all invalid characters with &#39;-&#39;.
hasSubpages( $index)
Does the namespace allow subpages?
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
getPrefixedText()
Get the prefixed title with spaces.
Definition: Title.php:1724
static getLocalizedName( $name, Language $lang=null)
Returns the localized name for a given content model.
static newFromTitle(LinkTarget $linkTarget, $id=0, $flags=0)
Load either the current, or a specified, revision that&#39;s attached to a given link target...
Definition: Revision.php:137
const DB_MASTER
Definition: defines.php:26
getName()
Get the user name, or the IP of an anonymous user.
Definition: User.php:2251
moveIfAllowed(User $user, $reason=null, $createRedirect=true, array $changeTags=[])
Same as move(), but with permissions checks.
Definition: MovePage.php:339
A class for passing options to services.
The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time).
Definition: User.php:51
you have access to all of the normal MediaWiki so you can get a DB use the cache
Definition: maintenance.txt:52
moveSubpages(User $user, $reason=null, $createRedirect=true, array $changeTags=[])
Move the source page&#39;s subpages to be subpages of the target page, without checking user permissions...
Definition: MovePage.php:377
static newFatal( $message)
Factory function for fatal errors.
Definition: StatusValue.php:68
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action, or null $user:User who performed the tagging when the tagging is subsequent to the action, or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy:boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
Definition: hooks.txt:1250
wfMergeErrorArrays(... $args)
Merge arrays in the style of getUserPermissionsErrors, with duplicate removal e.g.
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt
checkPermissions(User $user, $reason)
Check if the user is allowed to perform the move.
Definition: MovePage.php:121
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set but before ordinary actions take place or wrap services the preferred way to define a new service is the $wgServiceWiringFiles array $services
Definition: hooks.txt:2211
LoadBalancer $loadBalancer
Definition: MovePage.php:56
PermissionManager $permMgr
Definition: MovePage.php:71
$res
Definition: database.txt:21
moveFile( $oldTitle, $newTitle)
Move a file associated with a page to a new location.
Definition: MovePage.php:686
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:81
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
moveToInternal(User $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:719
const GAID_FOR_UPDATE
Used to be GAID_FOR_UPDATE define.
Definition: Title.php:57
incEditCount()
Schedule a deferred update to update the user&#39;s edit count.
Definition: User.php:5016
$params
const NS_CATEGORY
Definition: Defines.php:74
static getSoftwareTags( $all=false)
Loads defined core tags, checks for invalid types (if not array), and filters for supported and enabl...
Definition: ChangeTags.php:58
static newExtraneousContext(Title $title, $request=[])
Create a new extraneous context.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:773
RepoGroup $repoGroup
Definition: MovePage.php:76
const NS_FILE
Definition: Defines.php:66
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
Definition: hooks.txt:1754
static getForTitle(Title $title)
Returns the appropriate ContentHandler singleton for the given title.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
ServiceOptions $options
Definition: MovePage.php:51
insertOn( $dbw)
Insert a new revision into the database, returning the new revision ID number on success and dies hor...
Definition: Revision.php:1150
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:620
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
isValidFileMove()
Sanity checks for when a file is being moved.
Definition: MovePage.php:237
static checkExtensionCompatibility(File $old, $new)
Checks if file extensions are compatible.
Definition: File.php:259
static addUpdate(DeferrableUpdate $update, $stage=self::POSTSEND)
Add an update to the deferred list to be run later by execute()
Using a hook running we can avoid having all this option specific stuff in our mainline code Using the function We ve cleaned up the code here by removing clumps of infrequently used code and moving them off somewhere else It s much easier for someone working with this code to see what s _really_ going and make changes or fix bugs In we can take all the code that deals with the little used title reversing options(say) and put it in one place. Instead of having little title-reversing if-blocks spread all over the codebase in showAnArticle
moveSubpagesInternal( $checkPermissions, User $user, $reason, $createRedirect, array $changeTags)
Definition: MovePage.php:410
moveSubpagesIfAllowed(User $user, $reason=null, $createRedirect=true, array $changeTags=[])
Move the source page&#39;s subpages to be subpages of the target page, with user permission checks...
Definition: MovePage.php:396
spreadAnyEditBlock()
If this user is logged-in and blocked, block any IP address they&#39;ve successfully logged in from...
Definition: User.php:4246
NamespaceInfo $nsInfo
Definition: MovePage.php:61
isValidMoveTarget()
Checks if $this can be moved to a given Title.
Definition: MovePage.php:267
getId()
Get the user&#39;s ID.
Definition: User.php:2224
static matchSummarySpamRegex( $text)
Check given input text against $wgSummarySpamRegex, and return the text of the first match...
Definition: EditPage.php:2484
static onArticleDelete(Title $title)
Clears caches when article is deleted.
Definition: WikiPage.php:3421
move(User $user, $reason=null, $createRedirect=true, array $changeTags=[])
Move a page without taking user permissions into account.
Definition: MovePage.php:319
getCanonicalName( $index)
Returns the canonical (English) name for a given index.
Database connection, tracking, load balancing, and transaction manager for a cluster.
static canAddTagsAccompanyingChange(array $tags, User $user=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:521
Title $oldTitle
Definition: MovePage.php:41
$content
Definition: pageupdater.txt:72
isValidMove()
Does various sanity checks that the move is valid.
Definition: MovePage.php:163
getTalkPage()
Get this user&#39;s talk page title.
Definition: User.php:4340
static newNullRevision( $dbw, $pageId, $summary, $minor, $user=null)
Create a new null-revision for insertion into a page&#39;s history.
Definition: Revision.php:1196
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:251
Title $newTitle
Definition: MovePage.php:46
$wgMaximumMovedPages
Maximum number of pages to move at once when moving subpages with a page.
__construct(Title $oldTitle, Title $newTitle, ServiceOptions $options=null, LoadBalancer $loadBalancer=null, NamespaceInfo $nsInfo=null, WatchedItemStore $watchedItems=null, PermissionManager $permMgr=null, RepoGroup $repoGroup=null)
Calling this directly is deprecated in 1.34.
Definition: MovePage.php:89
A service class for checking permissions To obtain an instance, use MediaWikiServices::getInstance()-...
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1460
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200