MediaWiki  master
MovePage.php
Go to the documentation of this file.
1 <?php
2 
25 
32 class MovePage {
33 
37  protected $oldTitle;
38 
42  protected $newTitle;
43 
44  public function __construct( Title $oldTitle, Title $newTitle ) {
45  $this->oldTitle = $oldTitle;
46  $this->newTitle = $newTitle;
47  }
48 
57  public function checkPermissions( User $user, $reason ) {
58  $status = new Status();
59 
60  $errors = wfMergeErrorArrays(
61  $this->oldTitle->getUserPermissionsErrors( 'move', $user ),
62  $this->oldTitle->getUserPermissionsErrors( 'edit', $user ),
63  $this->newTitle->getUserPermissionsErrors( 'move-target', $user ),
64  $this->newTitle->getUserPermissionsErrors( 'edit', $user )
65  );
66 
67  // Convert into a Status object
68  if ( $errors ) {
69  foreach ( $errors as $error ) {
70  $status->fatal( ...$error );
71  }
72  }
73 
74  if ( $reason !== null && EditPage::matchSummarySpamRegex( $reason ) !== false ) {
75  // This is kind of lame, won't display nice
76  $status->fatal( 'spamprotectiontext' );
77  }
78 
79  $tp = $this->newTitle->getTitleProtection();
80  if ( $tp !== false && !$user->isAllowed( $tp['permission'] ) ) {
81  $status->fatal( 'cantmove-titleprotected' );
82  }
83 
84  Hooks::run( 'MovePageCheckPermissions',
85  [ $this->oldTitle, $this->newTitle, $user, $reason, $status ]
86  );
87 
88  return $status;
89  }
90 
98  public function isValidMove() {
100  $status = new Status();
101 
102  if ( $this->oldTitle->equals( $this->newTitle ) ) {
103  $status->fatal( 'selfmove' );
104  }
105  if ( !$this->oldTitle->isMovable() ) {
106  $status->fatal( 'immobile-source-namespace', $this->oldTitle->getNsText() );
107  }
108  if ( $this->newTitle->isExternal() ) {
109  $status->fatal( 'immobile-target-namespace-iw' );
110  }
111  if ( !$this->newTitle->isMovable() ) {
112  $status->fatal( 'immobile-target-namespace', $this->newTitle->getNsText() );
113  }
114 
115  $oldid = $this->oldTitle->getArticleID();
116 
117  if ( $this->newTitle->getDBkey() === '' ) {
118  $status->fatal( 'articleexists' );
119  }
120  if (
121  ( $this->oldTitle->getDBkey() == '' ) ||
122  ( !$oldid ) ||
123  ( $this->newTitle->getDBkey() == '' )
124  ) {
125  $status->fatal( 'badarticleerror' );
126  }
127 
128  # The move is allowed only if (1) the target doesn't exist, or
129  # (2) the target is a redirect to the source, and has no history
130  # (so we can undo bad moves right after they're done).
131  if ( $this->newTitle->getArticleID() && !$this->isValidMoveTarget() ) {
132  $status->fatal( 'articleexists' );
133  }
134 
135  // Content model checks
136  if ( !$wgContentHandlerUseDB &&
137  $this->oldTitle->getContentModel() !== $this->newTitle->getContentModel() ) {
138  // can't move a page if that would change the page's content model
139  $status->fatal(
140  'bad-target-model',
141  ContentHandler::getLocalizedName( $this->oldTitle->getContentModel() ),
142  ContentHandler::getLocalizedName( $this->newTitle->getContentModel() )
143  );
144  } elseif (
145  !ContentHandler::getForTitle( $this->oldTitle )->canBeUsedOn( $this->newTitle )
146  ) {
147  $status->fatal(
148  'content-not-allowed-here',
149  ContentHandler::getLocalizedName( $this->oldTitle->getContentModel() ),
150  $this->newTitle->getPrefixedText(),
151  SlotRecord::MAIN
152  );
153  }
154 
155  // Image-specific checks
156  if ( $this->oldTitle->inNamespace( NS_FILE ) ) {
157  $status->merge( $this->isValidFileMove() );
158  }
159 
160  if ( $this->newTitle->inNamespace( NS_FILE ) && !$this->oldTitle->inNamespace( NS_FILE ) ) {
161  $status->fatal( 'nonfile-cannot-move-to-file' );
162  }
163 
164  // Hook for extensions to say a title can't be moved for technical reasons
165  Hooks::run( 'MovePageIsValidMove', [ $this->oldTitle, $this->newTitle, $status ] );
166 
167  return $status;
168  }
169 
175  protected function isValidFileMove() {
176  $status = new Status();
177  $file = wfLocalFile( $this->oldTitle );
178  $file->load( File::READ_LATEST );
179  if ( $file->exists() ) {
180  if ( $this->newTitle->getText() != wfStripIllegalFilenameChars( $this->newTitle->getText() ) ) {
181  $status->fatal( 'imageinvalidfilename' );
182  }
183  if ( !File::checkExtensionCompatibility( $file, $this->newTitle->getDBkey() ) ) {
184  $status->fatal( 'imagetypemismatch' );
185  }
186  }
187 
188  if ( !$this->newTitle->inNamespace( NS_FILE ) ) {
189  $status->fatal( 'imagenocrossnamespace' );
190  }
191 
192  return $status;
193  }
194 
202  protected function isValidMoveTarget() {
203  # Is it an existing file?
204  if ( $this->newTitle->inNamespace( NS_FILE ) ) {
205  $file = wfLocalFile( $this->newTitle );
206  $file->load( File::READ_LATEST );
207  if ( $file->exists() ) {
208  wfDebug( __METHOD__ . ": file exists\n" );
209  return false;
210  }
211  }
212  # Is it a redirect with no history?
213  if ( !$this->newTitle->isSingleRevRedirect() ) {
214  wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
215  return false;
216  }
217  # Get the article text
218  $rev = Revision::newFromTitle( $this->newTitle, false, Revision::READ_LATEST );
219  if ( !is_object( $rev ) ) {
220  return false;
221  }
222  $content = $rev->getContent();
223  # Does the redirect point to the source?
224  # Or is it a broken self-redirect, usually caused by namespace collisions?
225  $redirTitle = $content ? $content->getRedirectTarget() : null;
226 
227  if ( $redirTitle ) {
228  if ( $redirTitle->getPrefixedDBkey() !== $this->oldTitle->getPrefixedDBkey() &&
229  $redirTitle->getPrefixedDBkey() !== $this->newTitle->getPrefixedDBkey() ) {
230  wfDebug( __METHOD__ . ": redirect points to other page\n" );
231  return false;
232  } else {
233  return true;
234  }
235  } else {
236  # Fail safe (not a redirect after all. strange.)
237  wfDebug( __METHOD__ . ": failsafe: database says " . $this->newTitle->getPrefixedDBkey() .
238  " is a redirect, but it doesn't contain a valid redirect.\n" );
239  return false;
240  }
241  }
242 
254  public function move(
255  User $user, $reason = null, $createRedirect = true, array $changeTags = []
256  ) {
257  $status = $this->isValidMove();
258  if ( !$status->isOK() ) {
259  return $status;
260  }
261 
262  return $this->moveUnsafe( $user, $reason, $createRedirect, $changeTags );
263  }
264 
274  public function moveIfAllowed(
275  User $user, $reason = null, $createRedirect = true, array $changeTags = []
276  ) {
277  $status = $this->isValidMove();
278  $status->merge( $this->checkPermissions( $user, $reason ) );
279  if ( $changeTags ) {
280  $status->merge( ChangeTags::canAddTagsAccompanyingChange( $changeTags, $user ) );
281  }
282 
283  if ( !$status->isOK() ) {
284  // Auto-block user's IP if the account was "hard" blocked
285  $user->spreadAnyEditBlock();
286  return $status;
287  }
288 
289  // Check suppressredirect permission
290  if ( !$user->isAllowed( 'suppressredirect' ) ) {
291  $createRedirect = true;
292  }
293 
294  return $this->moveUnsafe( $user, $reason, $createRedirect, $changeTags );
295  }
296 
311  public function moveSubpages(
312  User $user, $reason = null, $createRedirect = true, array $changeTags = []
313  ) {
314  return $this->moveSubpagesInternal( false, $user, $reason, $createRedirect, $changeTags );
315  }
316 
330  public function moveSubpagesIfAllowed(
331  User $user, $reason = null, $createRedirect = true, array $changeTags = []
332  ) {
333  return $this->moveSubpagesInternal( true, $user, $reason, $createRedirect, $changeTags );
334  }
335 
344  private function moveSubpagesInternal(
345  $checkPermissions, User $user, $reason, $createRedirect, array $changeTags
346  ) {
347  global $wgMaximumMovedPages;
348  $services = MediaWikiServices::getInstance();
349 
350  if ( $checkPermissions ) {
351  if ( !$services->getPermissionManager()->userCan(
352  'move-subpages', $user, $this->oldTitle )
353  ) {
354  return Status::newFatal( 'cant-move-subpages' );
355  }
356  }
357 
358  $nsInfo = $services->getNamespaceInfo();
359 
360  // Do the source and target namespaces support subpages?
361  if ( !$nsInfo->hasSubpages( $this->oldTitle->getNamespace() ) ) {
362  return Status::newFatal( 'namespace-nosubpages',
363  $nsInfo->getCanonicalName( $this->oldTitle->getNamespace() ) );
364  }
365  if ( !$nsInfo->hasSubpages( $this->newTitle->getNamespace() ) ) {
366  return Status::newFatal( 'namespace-nosubpages',
367  $nsInfo->getCanonicalName( $this->newTitle->getNamespace() ) );
368  }
369 
370  // Return a status for the overall result. Its value will be an array with per-title
371  // status for each subpage. Merge any errors from the per-title statuses into the
372  // top-level status without resetting the overall result.
373  $topStatus = Status::newGood();
374  $perTitleStatus = [];
375  $subpages = $this->oldTitle->getSubpages( $wgMaximumMovedPages + 1 );
376  $count = 0;
377  foreach ( $subpages as $oldSubpage ) {
378  $count++;
379  if ( $count > $wgMaximumMovedPages ) {
380  $status = Status::newFatal( 'movepage-max-pages', $wgMaximumMovedPages );
381  $perTitleStatus[$oldSubpage->getPrefixedText()] = $status;
382  $topStatus->merge( $status );
383  $topStatus->setOk( true );
384  break;
385  }
386 
387  // We don't know whether this function was called before or after moving the root page,
388  // so check both titles
389  if ( $oldSubpage->getArticleID() == $this->oldTitle->getArticleID() ||
390  $oldSubpage->getArticleID() == $this->newTitle->getArticleID()
391  ) {
392  // When moving a page to a subpage of itself, don't move it twice
393  continue;
394  }
395  $newPageName = preg_replace(
396  '#^' . preg_quote( $this->oldTitle->getDBkey(), '#' ) . '#',
397  StringUtils::escapeRegexReplacement( $this->newTitle->getDBkey() ), # T23234
398  $oldSubpage->getDBkey() );
399  if ( $oldSubpage->isTalkPage() ) {
400  $newNs = $this->newTitle->getTalkPage()->getNamespace();
401  } else {
402  $newNs = $this->newTitle->getSubjectPage()->getNamespace();
403  }
404  // T16385: we need makeTitleSafe because the new page names may be longer than 255
405  // characters.
406  $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
407 
408  $mp = new MovePage( $oldSubpage, $newSubpage );
409  $method = $checkPermissions ? 'moveIfAllowed' : 'move';
410  $status = $mp->$method( $user, $reason, $createRedirect, $changeTags );
411  if ( $status->isOK() ) {
412  $status->setResult( true, $newSubpage->getPrefixedText() );
413  }
414  $perTitleStatus[$oldSubpage->getPrefixedText()] = $status;
415  $topStatus->merge( $status );
416  $topStatus->setOk( true );
417  }
418 
419  $topStatus->value = $perTitleStatus;
420  return $topStatus;
421  }
422 
432  private function moveUnsafe( User $user, $reason, $createRedirect, array $changeTags ) {
433  global $wgCategoryCollation;
434 
436  Hooks::run( 'TitleMove', [ $this->oldTitle, $this->newTitle, $user, $reason, &$status ] );
437  if ( !$status->isOK() ) {
438  // Move was aborted by the hook
439  return $status;
440  }
441 
442  $dbw = wfGetDB( DB_MASTER );
443  $dbw->startAtomic( __METHOD__, IDatabase::ATOMIC_CANCELABLE );
444 
445  Hooks::run( 'TitleMoveStarting', [ $this->oldTitle, $this->newTitle, $user ] );
446 
447  $pageid = $this->oldTitle->getArticleID( Title::GAID_FOR_UPDATE );
448  $protected = $this->oldTitle->isProtected();
449 
450  // Do the actual move; if this fails, it will throw an MWException(!)
451  $nullRevision = $this->moveToInternal( $user, $this->newTitle, $reason, $createRedirect,
452  $changeTags );
453 
454  // Refresh the sortkey for this row. Be careful to avoid resetting
455  // cl_timestamp, which may disturb time-based lists on some sites.
456  // @todo This block should be killed, it's duplicating code
457  // from LinksUpdate::getCategoryInsertions() and friends.
458  $prefixes = $dbw->select(
459  'categorylinks',
460  [ 'cl_sortkey_prefix', 'cl_to' ],
461  [ 'cl_from' => $pageid ],
462  __METHOD__
463  );
464  $services = MediaWikiServices::getInstance();
465  $type = $services->getNamespaceInfo()->
466  getCategoryLinkType( $this->newTitle->getNamespace() );
467  foreach ( $prefixes as $prefixRow ) {
468  $prefix = $prefixRow->cl_sortkey_prefix;
469  $catTo = $prefixRow->cl_to;
470  $dbw->update( 'categorylinks',
471  [
472  'cl_sortkey' => Collation::singleton()->getSortKey(
473  $this->newTitle->getCategorySortkey( $prefix ) ),
474  'cl_collation' => $wgCategoryCollation,
475  'cl_type' => $type,
476  'cl_timestamp=cl_timestamp' ],
477  [
478  'cl_from' => $pageid,
479  'cl_to' => $catTo ],
480  __METHOD__
481  );
482  }
483 
484  $redirid = $this->oldTitle->getArticleID();
485 
486  if ( $protected ) {
487  # Protect the redirect title as the title used to be...
488  $res = $dbw->select(
489  'page_restrictions',
490  [ 'pr_type', 'pr_level', 'pr_cascade', 'pr_user', 'pr_expiry' ],
491  [ 'pr_page' => $pageid ],
492  __METHOD__,
493  'FOR UPDATE'
494  );
495  $rowsInsert = [];
496  foreach ( $res as $row ) {
497  $rowsInsert[] = [
498  'pr_page' => $redirid,
499  'pr_type' => $row->pr_type,
500  'pr_level' => $row->pr_level,
501  'pr_cascade' => $row->pr_cascade,
502  'pr_user' => $row->pr_user,
503  'pr_expiry' => $row->pr_expiry
504  ];
505  }
506  $dbw->insert( 'page_restrictions', $rowsInsert, __METHOD__, [ 'IGNORE' ] );
507 
508  // Build comment for log
509  $comment = wfMessage(
510  'prot_1movedto2',
511  $this->oldTitle->getPrefixedText(),
512  $this->newTitle->getPrefixedText()
513  )->inContentLanguage()->text();
514  if ( $reason ) {
515  $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
516  }
517 
518  // reread inserted pr_ids for log relation
519  $insertedPrIds = $dbw->select(
520  'page_restrictions',
521  'pr_id',
522  [ 'pr_page' => $redirid ],
523  __METHOD__
524  );
525  $logRelationsValues = [];
526  foreach ( $insertedPrIds as $prid ) {
527  $logRelationsValues[] = $prid->pr_id;
528  }
529 
530  // Update the protection log
531  $logEntry = new ManualLogEntry( 'protect', 'move_prot' );
532  $logEntry->setTarget( $this->newTitle );
533  $logEntry->setComment( $comment );
534  $logEntry->setPerformer( $user );
535  $logEntry->setParameters( [
536  '4::oldtitle' => $this->oldTitle->getPrefixedText(),
537  ] );
538  $logEntry->setRelations( [ 'pr_id' => $logRelationsValues ] );
539  $logEntry->setTags( $changeTags );
540  $logId = $logEntry->insert();
541  $logEntry->publish( $logId );
542  }
543 
544  // Update *_from_namespace fields as needed
545  if ( $this->oldTitle->getNamespace() != $this->newTitle->getNamespace() ) {
546  $dbw->update( 'pagelinks',
547  [ 'pl_from_namespace' => $this->newTitle->getNamespace() ],
548  [ 'pl_from' => $pageid ],
549  __METHOD__
550  );
551  $dbw->update( 'templatelinks',
552  [ 'tl_from_namespace' => $this->newTitle->getNamespace() ],
553  [ 'tl_from' => $pageid ],
554  __METHOD__
555  );
556  $dbw->update( 'imagelinks',
557  [ 'il_from_namespace' => $this->newTitle->getNamespace() ],
558  [ 'il_from' => $pageid ],
559  __METHOD__
560  );
561  }
562 
563  # Update watchlists
564  $oldtitle = $this->oldTitle->getDBkey();
565  $newtitle = $this->newTitle->getDBkey();
566  $oldsnamespace = $services->getNamespaceInfo()->
567  getSubject( $this->oldTitle->getNamespace() );
568  $newsnamespace = $services->getNamespaceInfo()->
569  getSubject( $this->newTitle->getNamespace() );
570  if ( $oldsnamespace != $newsnamespace || $oldtitle != $newtitle ) {
571  $services->getWatchedItemStore()->duplicateAllAssociatedEntries(
572  $this->oldTitle, $this->newTitle );
573  }
574 
575  // If it is a file then move it last.
576  // This is done after all database changes so that file system errors cancel the transaction.
577  if ( $this->oldTitle->getNamespace() == NS_FILE ) {
578  $status = $this->moveFile( $this->oldTitle, $this->newTitle );
579  if ( !$status->isOK() ) {
580  $dbw->cancelAtomic( __METHOD__ );
581  return $status;
582  }
583  }
584 
585  Hooks::run(
586  'TitleMoveCompleting',
587  [ $this->oldTitle, $this->newTitle,
588  $user, $pageid, $redirid, $reason, $nullRevision ]
589  );
590 
591  $dbw->endAtomic( __METHOD__ );
592 
593  $params = [
596  &$user,
597  $pageid,
598  $redirid,
599  $reason,
600  $nullRevision
601  ];
602  // Keep each single hook handler atomic
605  $dbw,
606  __METHOD__,
607  // Hold onto $user to avoid HHVM bug where it no longer
608  // becomes a reference (T118683)
609  function () use ( $params, &$user ) {
610  Hooks::run( 'TitleMoveComplete', $params );
611  }
612  )
613  );
614 
615  return Status::newGood();
616  }
617 
627  private function moveFile( $oldTitle, $newTitle ) {
629  'cannotdelete',
631  );
632 
634  $file->load( File::READ_LATEST );
635  if ( $file->exists() ) {
636  $status = $file->move( $newTitle );
637  }
638 
639  // Clear RepoGroup process cache
640  RepoGroup::singleton()->clearCache( $oldTitle );
641  RepoGroup::singleton()->clearCache( $newTitle ); # clear false negative cache
642  return $status;
643  }
644 
660  private function moveToInternal( User $user, &$nt, $reason = '', $createRedirect = true,
661  array $changeTags = []
662  ) {
663  if ( $nt->exists() ) {
664  $moveOverRedirect = true;
665  $logType = 'move_redir';
666  } else {
667  $moveOverRedirect = false;
668  $logType = 'move';
669  }
670 
671  if ( $moveOverRedirect ) {
672  $overwriteMessage = wfMessage(
673  'delete_and_move_reason',
674  $this->oldTitle->getPrefixedText()
675  )->inContentLanguage()->text();
676  $newpage = WikiPage::factory( $nt );
677  $errs = [];
678  $status = $newpage->doDeleteArticleReal(
679  $overwriteMessage,
680  /* $suppress */ false,
681  $nt->getArticleID(),
682  /* $commit */ false,
683  $errs,
684  $user,
685  $changeTags,
686  'delete_redir'
687  );
688 
689  if ( !$status->isGood() ) {
690  throw new MWException( 'Failed to delete page-move revision: '
691  . $status->getWikiText( false, false, 'en' ) );
692  }
693 
694  $nt->resetArticleID( false );
695  }
696 
697  if ( $createRedirect ) {
698  if ( $this->oldTitle->getNamespace() == NS_CATEGORY
699  && !wfMessage( 'category-move-redirect-override' )->inContentLanguage()->isDisabled()
700  ) {
701  $redirectContent = new WikitextContent(
702  wfMessage( 'category-move-redirect-override' )
703  ->params( $nt->getPrefixedText() )->inContentLanguage()->plain() );
704  } else {
705  $contentHandler = ContentHandler::getForTitle( $this->oldTitle );
706  $redirectContent = $contentHandler->makeRedirectContent( $nt,
707  wfMessage( 'move-redirect-text' )->inContentLanguage()->plain() );
708  }
709 
710  // NOTE: If this page's content model does not support redirects, $redirectContent will be null.
711  } else {
712  $redirectContent = null;
713  }
714 
715  // Figure out whether the content model is no longer the default
716  $oldDefault = ContentHandler::getDefaultModelFor( $this->oldTitle );
717  $contentModel = $this->oldTitle->getContentModel();
718  $newDefault = ContentHandler::getDefaultModelFor( $nt );
719  $defaultContentModelChanging = ( $oldDefault !== $newDefault
720  && $oldDefault === $contentModel );
721 
722  // T59084: log_page should be the ID of the *moved* page
723  $oldid = $this->oldTitle->getArticleID();
724  $logTitle = clone $this->oldTitle;
725 
726  $logEntry = new ManualLogEntry( 'move', $logType );
727  $logEntry->setPerformer( $user );
728  $logEntry->setTarget( $logTitle );
729  $logEntry->setComment( $reason );
730  $logEntry->setParameters( [
731  '4::target' => $nt->getPrefixedText(),
732  '5::noredir' => $redirectContent ? '0' : '1',
733  ] );
734 
735  $formatter = LogFormatter::newFromEntry( $logEntry );
736  $formatter->setContext( RequestContext::newExtraneousContext( $this->oldTitle ) );
737  $comment = $formatter->getPlainActionText();
738  if ( $reason ) {
739  $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
740  }
741 
742  $dbw = wfGetDB( DB_MASTER );
743 
744  $oldpage = WikiPage::factory( $this->oldTitle );
745  $oldcountable = $oldpage->isCountable();
746 
747  $newpage = WikiPage::factory( $nt );
748 
749  # Change the name of the target page:
750  $dbw->update( 'page',
751  /* SET */ [
752  'page_namespace' => $nt->getNamespace(),
753  'page_title' => $nt->getDBkey(),
754  ],
755  /* WHERE */ [ 'page_id' => $oldid ],
756  __METHOD__
757  );
758 
759  # Save a null revision in the page's history notifying of the move
760  $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true, $user );
761  if ( !is_object( $nullRevision ) ) {
762  throw new MWException( 'Failed to create null revision while moving page ID '
763  . $oldid . ' to ' . $nt->getPrefixedDBkey() );
764  }
765 
766  $nullRevId = $nullRevision->insertOn( $dbw );
767  $logEntry->setAssociatedRevId( $nullRevId );
768 
774  $user->incEditCount();
775 
776  if ( !$redirectContent ) {
777  // Clean up the old title *before* reset article id - T47348
778  WikiPage::onArticleDelete( $this->oldTitle );
779  }
780 
781  $this->oldTitle->resetArticleID( 0 ); // 0 == non existing
782  $nt->resetArticleID( $oldid );
783  $newpage->loadPageData( WikiPage::READ_LOCKING ); // T48397
784 
785  $newpage->updateRevisionOn( $dbw, $nullRevision );
786 
787  Hooks::run( 'NewRevisionFromEditComplete',
788  [ $newpage, $nullRevision, $nullRevision->getParentId(), $user ] );
789 
790  $newpage->doEditUpdates( $nullRevision, $user,
791  [ 'changed' => false, 'moved' => true, 'oldcountable' => $oldcountable ] );
792 
793  // If the default content model changes, we need to populate rev_content_model
794  if ( $defaultContentModelChanging ) {
795  $dbw->update(
796  'revision',
797  [ 'rev_content_model' => $contentModel ],
798  [ 'rev_page' => $nt->getArticleID(), 'rev_content_model IS NULL' ],
799  __METHOD__
800  );
801  }
802 
804 
805  # Recreate the redirect, this time in the other direction.
806  if ( $redirectContent ) {
807  $redirectArticle = WikiPage::factory( $this->oldTitle );
808  $redirectArticle->loadFromRow( false, WikiPage::READ_LOCKING ); // T48397
809  $newid = $redirectArticle->insertOn( $dbw );
810  if ( $newid ) { // sanity
811  $this->oldTitle->resetArticleID( $newid );
812  $redirectRevision = new Revision( [
813  'title' => $this->oldTitle, // for determining the default content model
814  'page' => $newid,
815  'user_text' => $user->getName(),
816  'user' => $user->getId(),
817  'comment' => $comment,
818  'content' => $redirectContent ] );
819  $redirectRevId = $redirectRevision->insertOn( $dbw );
820  $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
821 
822  Hooks::run( 'NewRevisionFromEditComplete',
823  [ $redirectArticle, $redirectRevision, false, $user ] );
824 
825  $redirectArticle->doEditUpdates( $redirectRevision, $user, [ 'created' => true ] );
826 
827  // make a copy because of log entry below
828  $redirectTags = $changeTags;
829  if ( in_array( 'mw-new-redirect', ChangeTags::getSoftwareTags() ) ) {
830  $redirectTags[] = 'mw-new-redirect';
831  }
832  ChangeTags::addTags( $redirectTags, null, $redirectRevId, null );
833  }
834  }
835 
836  # Log the move
837  $logid = $logEntry->insert();
838 
839  $logEntry->setTags( $changeTags );
840  $logEntry->publish( $logid );
841 
842  return $nullRevision;
843  }
844 }
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:3375
either a plain
Definition: hooks.txt:2043
Handles the backend logic of moving a page from one title to another.
Definition: MovePage.php:32
moveUnsafe(User $user, $reason, $createRedirect, array $changeTags)
Moves without any sort of safety or sanity checks.
Definition: MovePage.php:432
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.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
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;.
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:1696
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
wfLocalFile( $title)
Get an object referring to a locally registered file.
$wgCategoryCollation
Specify how category names should be sorted, when listed on a category page.
const DB_MASTER
Definition: defines.php:26
getName()
Get the user name, or the IP of an anonymous user.
Definition: User.php:2311
moveIfAllowed(User $user, $reason=null, $createRedirect=true, array $changeTags=[])
Same as move(), but with permissions checks.
Definition: MovePage.php:274
The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time).
Definition: User.php:51
$wgContentHandlerUseDB
Set to false to disable use of the database fields introduced by the ContentHandler facility...
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:311
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:1263
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:57
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:2217
$res
Definition: database.txt:21
static singleton()
Definition: RepoGroup.php:60
moveFile( $oldTitle, $newTitle)
Move a file associated with a page to a new location.
Definition: MovePage.php:627
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:660
const GAID_FOR_UPDATE
Used to be GAID_FOR_UPDATE define.
Definition: Title.php:55
incEditCount()
Schedule a deferred update to update the user&#39;s edit count.
Definition: User.php:5164
$params
const NS_CATEGORY
Definition: Defines.php:74
isAllowed( $action='')
Internal mechanics of testing a permission.
Definition: User.php:3730
static getSoftwareTags( $all=false)
Loads defined core tags, checks for invalid types (if not array), and filters for supported and enabl...
Definition: ChangeTags.php:57
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:780
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:1766
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
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:617
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:175
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()
moveSubpagesInternal( $checkPermissions, User $user, $reason, $createRedirect, array $changeTags)
Definition: MovePage.php:344
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:330
__construct(Title $oldTitle, Title $newTitle)
Definition: MovePage.php:44
spreadAnyEditBlock()
If this user is logged-in and blocked, block any IP address they&#39;ve successfully logged in from...
Definition: User.php:4338
isValidMoveTarget()
Checks if $this can be moved to a given Title.
Definition: MovePage.php:202
getId()
Get the user&#39;s ID.
Definition: User.php:2284
static matchSummarySpamRegex( $text)
Check given input text against $wgSummarySpamRegex, and return the text of the first match...
Definition: EditPage.php:2483
static onArticleDelete(Title $title)
Clears caches when article is deleted.
Definition: WikiPage.php:3408
move(User $user, $reason=null, $createRedirect=true, array $changeTags=[])
Move a page without taking user permissions into account.
Definition: MovePage.php:254
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:481
Title $oldTitle
Definition: MovePage.php:37
$content
Definition: pageupdater.txt:72
isValidMove()
Does various sanity checks that the move is valid.
Definition: MovePage.php:98
getTalkPage()
Get this user&#39;s talk page title.
Definition: User.php:4432
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:226
Title $newTitle
Definition: MovePage.php:42
$wgMaximumMovedPages
Maximum number of pages to move at once when moving subpages with a page.
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1473
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200