MediaWiki  master
ContentHandler.php
Go to the documentation of this file.
1 <?php
2 
35 
55 abstract class ContentHandler {
85  public static function getContentText( Content $content = null ) {
87 
88  if ( is_null( $content ) ) {
89  return '';
90  }
91 
92  if ( $content instanceof TextContent ) {
93  return $content->getText();
94  }
95 
96  wfDebugLog( 'ContentHandler', 'Accessing ' . $content->getModel() . ' content as text!' );
97 
98  if ( $wgContentHandlerTextFallback == 'fail' ) {
99  throw new MWException(
100  "Attempt to get text from Content with model " .
101  $content->getModel()
102  );
103  }
104 
105  if ( $wgContentHandlerTextFallback == 'serialize' ) {
106  return $content->serialize();
107  }
108 
109  return null;
110  }
111 
135  public static function makeContent( $text, Title $title = null,
136  $modelId = null, $format = null ) {
137  if ( is_null( $modelId ) ) {
138  if ( is_null( $title ) ) {
139  throw new MWException( "Must provide a Title object or a content model ID." );
140  }
141 
142  $modelId = $title->getContentModel();
143  }
144 
145  $handler = self::getForModelID( $modelId );
146 
147  return $handler->unserializeContent( $text, $format );
148  }
149 
186  public static function getDefaultModelFor( Title $title ) {
187  $slotRoleregistry = MediaWikiServices::getInstance()->getSlotRoleRegistry();
188  $mainSlotHandler = $slotRoleregistry->getRoleHandler( 'main' );
189  return $mainSlotHandler->getDefaultModel( $title );
190  }
191 
201  public static function getForTitle( Title $title ) {
202  $modelId = $title->getContentModel();
203 
204  return self::getForModelID( $modelId );
205  }
206 
217  public static function getForContent( Content $content ) {
218  $modelId = $content->getModel();
219 
220  return self::getForModelID( $modelId );
221  }
222 
226  protected static $handlers;
227 
254  public static function getForModelID( $modelId ) {
255  global $wgContentHandlers;
256 
257  if ( isset( self::$handlers[$modelId] ) ) {
258  return self::$handlers[$modelId];
259  }
260 
261  if ( empty( $wgContentHandlers[$modelId] ) ) {
262  $handler = null;
263 
264  Hooks::run( 'ContentHandlerForModelID', [ $modelId, &$handler ] );
265 
266  if ( $handler === null ) {
267  throw new MWUnknownContentModelException( $modelId );
268  }
269 
270  if ( !( $handler instanceof ContentHandler ) ) {
271  throw new MWException( "ContentHandlerForModelID must supply a ContentHandler instance" );
272  }
273  } else {
274  $classOrCallback = $wgContentHandlers[$modelId];
275 
276  if ( is_callable( $classOrCallback ) ) {
277  $handler = call_user_func( $classOrCallback, $modelId );
278  } else {
279  $handler = new $classOrCallback( $modelId );
280  }
281 
282  if ( !( $handler instanceof ContentHandler ) ) {
283  throw new MWException( "$classOrCallback from \$wgContentHandlers is not " .
284  "compatible with ContentHandler" );
285  }
286  }
287 
288  wfDebugLog( 'ContentHandler', 'Created handler for ' . $modelId
289  . ': ' . get_class( $handler ) );
290 
291  self::$handlers[$modelId] = $handler;
292 
293  return self::$handlers[$modelId];
294  }
295 
299  public static function cleanupHandlersCache() {
300  self::$handlers = [];
301  }
302 
316  public static function getLocalizedName( $name, Language $lang = null ) {
317  // Messages: content-model-wikitext, content-model-text,
318  // content-model-javascript, content-model-css
319  $key = "content-model-$name";
320 
321  $msg = wfMessage( $key );
322  if ( $lang ) {
323  $msg->inLanguage( $lang );
324  }
325 
326  return $msg->exists() ? $msg->plain() : $name;
327  }
328 
329  public static function getContentModels() {
330  global $wgContentHandlers;
331 
332  $models = array_keys( $wgContentHandlers );
333  Hooks::run( 'GetContentModels', [ &$models ] );
334  return $models;
335  }
336 
337  public static function getAllContentFormats() {
338  global $wgContentHandlers;
339 
340  $formats = [];
341 
342  foreach ( $wgContentHandlers as $model => $class ) {
343  $handler = self::getForModelID( $model );
344  $formats = array_merge( $formats, $handler->getSupportedFormats() );
345  }
346 
347  $formats = array_unique( $formats );
348 
349  return $formats;
350  }
351 
352  // ------------------------------------------------------------------------
353 
357  protected $mModelID;
358 
363 
373  public function __construct( $modelId, $formats ) {
374  $this->mModelID = $modelId;
375  $this->mSupportedFormats = $formats;
376  }
377 
388  abstract public function serializeContent( Content $content, $format = null );
389 
400  public function exportTransform( $blob, $format = null ) {
401  return $blob;
402  }
403 
414  abstract public function unserializeContent( $blob, $format = null );
415 
427  public function importTransform( $blob, $format = null ) {
428  return $blob;
429  }
430 
439  abstract public function makeEmptyContent();
440 
458  public function makeRedirectContent( Title $destination, $text = '' ) {
459  return null;
460  }
461 
470  public function getModelID() {
471  return $this->mModelID;
472  }
473 
482  protected function checkModelID( $model_id ) {
483  if ( $model_id !== $this->mModelID ) {
484  throw new MWException( "Bad content model: " .
485  "expected {$this->mModelID} " .
486  "but got $model_id." );
487  }
488  }
489 
499  public function getSupportedFormats() {
501  }
502 
514  public function getDefaultFormat() {
515  return $this->mSupportedFormats[0];
516  }
517 
531  public function isSupportedFormat( $format ) {
532  if ( !$format ) {
533  return true; // this means "use the default"
534  }
535 
536  return in_array( $format, $this->mSupportedFormats );
537  }
538 
546  protected function checkFormat( $format ) {
547  if ( !$this->isSupportedFormat( $format ) ) {
548  throw new MWException(
549  "Format $format is not supported for content model "
550  . $this->getModelID()
551  );
552  }
553  }
554 
570  public function getActionOverrides() {
571  return [];
572  }
573 
601  public function createDifferenceEngine( IContextSource $context, $old = 0, $new = 0,
602  $rcid = 0, // FIXME: Deprecated, no longer used
603  $refreshCache = false, $unhide = false
604  ) {
605  $diffEngineClass = $this->getDiffEngineClass();
606  $differenceEngine = new $diffEngineClass( $context, $old, $new, $rcid, $refreshCache, $unhide );
607  Hooks::run( 'GetDifferenceEngine', [ $context, $old, $new, $refreshCache, $unhide,
608  &$differenceEngine ] );
609  return $differenceEngine;
610  }
611 
618  final public function getSlotDiffRenderer( IContextSource $context ) {
619  $slotDiffRenderer = $this->getSlotDiffRendererInternal( $context );
620  if ( get_class( $slotDiffRenderer ) === TextSlotDiffRenderer::class ) {
621  // To keep B/C, when SlotDiffRenderer is not overridden for a given content type
622  // but DifferenceEngine is, use that instead.
623  $differenceEngine = $this->createDifferenceEngine( $context );
624  if ( get_class( $differenceEngine ) !== DifferenceEngine::class ) {
625  // TODO turn this into a deprecation warning in a later release
626  LoggerFactory::getInstance( 'diff' )->info(
627  'Falling back to DifferenceEngineSlotDiffRenderer', [
628  'modelID' => $this->getModelID(),
629  'DifferenceEngine' => get_class( $differenceEngine ),
630  ] );
631  $slotDiffRenderer = new DifferenceEngineSlotDiffRenderer( $differenceEngine );
632  }
633  }
634  Hooks::run( 'GetSlotDiffRenderer', [ $this, &$slotDiffRenderer, $context ] );
635  return $slotDiffRenderer;
636  }
637 
644  $contentLanguage = MediaWikiServices::getInstance()->getContentLanguage();
645  $statsdDataFactory = MediaWikiServices::getInstance()->getStatsdDataFactory();
646  $slotDiffRenderer = new TextSlotDiffRenderer();
647  $slotDiffRenderer->setStatsdDataFactory( $statsdDataFactory );
648  // XXX using the page language would be better, but it's unclear how that should be injected
649  $slotDiffRenderer->setLanguage( $contentLanguage );
650 
652  if ( $engine === false ) {
653  $slotDiffRenderer->setEngine( TextSlotDiffRenderer::ENGINE_PHP );
654  } elseif ( $engine === 'wikidiff2' ) {
655  $slotDiffRenderer->setEngine( TextSlotDiffRenderer::ENGINE_WIKIDIFF2 );
656  } else {
657  $slotDiffRenderer->setEngine( TextSlotDiffRenderer::ENGINE_EXTERNAL, $engine );
658  }
659 
660  return $slotDiffRenderer;
661  }
662 
682  public function getPageLanguage( Title $title, Content $content = null ) {
683  global $wgLang;
684  $pageLang = MediaWikiServices::getInstance()->getContentLanguage();
685 
686  if ( $title->inNamespace( NS_MEDIAWIKI ) ) {
687  // Parse mediawiki messages with correct target language
688  list( /* $unused */, $lang ) = MessageCache::singleton()->figureMessage( $title->getText() );
689  $pageLang = Language::factory( $lang );
690  }
691 
692  // Simplify hook handlers by only passing objects of one type, in case nothing
693  // else has unstubbed the StubUserLang object by now.
694  StubObject::unstub( $wgLang );
695 
696  Hooks::run( 'PageContentLanguage', [ $title, &$pageLang, $wgLang ] );
697 
698  return wfGetLangObj( $pageLang );
699  }
700 
721  public function getPageViewLanguage( Title $title, Content $content = null ) {
722  $pageLang = $this->getPageLanguage( $title, $content );
723 
724  if ( $title->getNamespace() !== NS_MEDIAWIKI ) {
725  // If the user chooses a variant, the content is actually
726  // in a language whose code is the variant code.
727  $variant = $pageLang->getPreferredVariant();
728  if ( $pageLang->getCode() !== $variant ) {
729  $pageLang = Language::factory( $variant );
730  }
731  }
732 
733  return $pageLang;
734  }
735 
754  public function canBeUsedOn( Title $title ) {
755  $ok = true;
756 
757  Hooks::run( 'ContentModelCanBeUsedOn', [ $this->getModelID(), $title, &$ok ] );
758 
759  return $ok;
760  }
761 
769  protected function getDiffEngineClass() {
771  }
772 
787  public function merge3( Content $oldContent, Content $myContent, Content $yourContent ) {
788  return false;
789  }
790 
802  private function getChangeType(
803  Content $oldContent = null,
804  Content $newContent = null,
805  $flags = 0
806  ) {
807  $oldTarget = $oldContent !== null ? $oldContent->getRedirectTarget() : null;
808  $newTarget = $newContent !== null ? $newContent->getRedirectTarget() : null;
809 
810  // We check for the type of change in the given edit, and return string key accordingly
811 
812  // Blanking of a page
813  if ( $oldContent && $oldContent->getSize() > 0 &&
814  $newContent && $newContent->getSize() === 0
815  ) {
816  return 'blank';
817  }
818 
819  // Redirects
820  if ( $newTarget ) {
821  if ( !$oldTarget ) {
822  // New redirect page (by creating new page or by changing content page)
823  return 'new-redirect';
824  } elseif ( !$newTarget->equals( $oldTarget ) ||
825  $oldTarget->getFragment() !== $newTarget->getFragment()
826  ) {
827  // Redirect target changed
828  return 'changed-redirect-target';
829  }
830  } elseif ( $oldTarget ) {
831  // Changing an existing redirect into a non-redirect
832  return 'removed-redirect';
833  }
834 
835  // New page created
836  if ( $flags & EDIT_NEW && $newContent ) {
837  if ( $newContent->getSize() === 0 ) {
838  // New blank page
839  return 'newblank';
840  } else {
841  return 'newpage';
842  }
843  }
844 
845  // Removing more than 90% of the page
846  if ( $oldContent && $newContent && $oldContent->getSize() > 10 * $newContent->getSize() ) {
847  return 'replace';
848  }
849 
850  // Content model changed
851  if ( $oldContent && $newContent && $oldContent->getModel() !== $newContent->getModel() ) {
852  return 'contentmodelchange';
853  }
854 
855  return null;
856  }
857 
869  public function getAutosummary(
870  Content $oldContent = null,
871  Content $newContent = null,
872  $flags = 0
873  ) {
874  $changeType = $this->getChangeType( $oldContent, $newContent, $flags );
875 
876  // There's no applicable auto-summary for our case, so our auto-summary is empty.
877  if ( !$changeType ) {
878  return '';
879  }
880 
881  // Decide what kind of auto-summary is needed.
882  switch ( $changeType ) {
883  case 'new-redirect':
884  $newTarget = $newContent->getRedirectTarget();
885  $truncatedtext = $newContent->getTextForSummary(
886  250
887  - strlen( wfMessage( 'autoredircomment' )->inContentLanguage()->text() )
888  - strlen( $newTarget->getFullText() )
889  );
890 
891  return wfMessage( 'autoredircomment', $newTarget->getFullText() )
892  ->plaintextParams( $truncatedtext )->inContentLanguage()->text();
893  case 'changed-redirect-target':
894  $oldTarget = $oldContent->getRedirectTarget();
895  $newTarget = $newContent->getRedirectTarget();
896 
897  $truncatedtext = $newContent->getTextForSummary(
898  250
899  - strlen( wfMessage( 'autosumm-changed-redirect-target' )
900  ->inContentLanguage()->text() )
901  - strlen( $oldTarget->getFullText() )
902  - strlen( $newTarget->getFullText() )
903  );
904 
905  return wfMessage( 'autosumm-changed-redirect-target',
906  $oldTarget->getFullText(),
907  $newTarget->getFullText() )
908  ->rawParams( $truncatedtext )->inContentLanguage()->text();
909  case 'removed-redirect':
910  $oldTarget = $oldContent->getRedirectTarget();
911  $truncatedtext = $newContent->getTextForSummary(
912  250
913  - strlen( wfMessage( 'autosumm-removed-redirect' )
914  ->inContentLanguage()->text() )
915  - strlen( $oldTarget->getFullText() ) );
916 
917  return wfMessage( 'autosumm-removed-redirect', $oldTarget->getFullText() )
918  ->rawParams( $truncatedtext )->inContentLanguage()->text();
919  case 'newpage':
920  // If they're making a new article, give its text, truncated, in the summary.
921  $truncatedtext = $newContent->getTextForSummary(
922  200 - strlen( wfMessage( 'autosumm-new' )->inContentLanguage()->text() ) );
923 
924  return wfMessage( 'autosumm-new' )->rawParams( $truncatedtext )
925  ->inContentLanguage()->text();
926  case 'blank':
927  return wfMessage( 'autosumm-blank' )->inContentLanguage()->text();
928  case 'replace':
929  $truncatedtext = $newContent->getTextForSummary(
930  200 - strlen( wfMessage( 'autosumm-replace' )->inContentLanguage()->text() ) );
931 
932  return wfMessage( 'autosumm-replace' )->rawParams( $truncatedtext )
933  ->inContentLanguage()->text();
934  case 'newblank':
935  return wfMessage( 'autosumm-newblank' )->inContentLanguage()->text();
936  default:
937  return '';
938  }
939  }
940 
952  public function getChangeTag(
953  Content $oldContent = null,
954  Content $newContent = null,
955  $flags = 0
956  ) {
957  $changeType = $this->getChangeType( $oldContent, $newContent, $flags );
958 
959  // There's no applicable tag for this change.
960  if ( !$changeType ) {
961  return null;
962  }
963 
964  // Core tags use the same keys as ones returned from $this->getChangeType()
965  // but prefixed with pseudo namespace 'mw-', so we add the prefix before checking
966  // if this type of change should be tagged
967  $tag = 'mw-' . $changeType;
968 
969  // Not all change types are tagged, so we check against the list of defined tags.
970  if ( in_array( $tag, ChangeTags::getSoftwareTags() ) ) {
971  return $tag;
972  }
973 
974  return null;
975  }
976 
992  public function getAutoDeleteReason( Title $title, &$hasHistory ) {
993  $dbr = wfGetDB( DB_REPLICA );
994 
995  // Get the last revision
996  $rev = Revision::newFromTitle( $title );
997 
998  if ( is_null( $rev ) ) {
999  return false;
1000  }
1001 
1002  // Get the article's contents
1003  $content = $rev->getContent();
1004  $blank = false;
1005 
1006  // If the page is blank, use the text from the previous revision,
1007  // which can only be blank if there's a move/import/protect dummy
1008  // revision involved
1009  if ( !$content || $content->isEmpty() ) {
1010  $prev = $rev->getPrevious();
1011 
1012  if ( $prev ) {
1013  $rev = $prev;
1014  $content = $rev->getContent();
1015  $blank = true;
1016  }
1017  }
1018 
1019  $this->checkModelID( $rev->getContentModel() );
1020 
1021  // Find out if there was only one contributor
1022  // Only scan the last 20 revisions
1024  $res = $dbr->select(
1025  $revQuery['tables'],
1026  [ 'rev_user_text' => $revQuery['fields']['rev_user_text'] ],
1027  [
1028  'rev_page' => $title->getArticleID(),
1029  $dbr->bitAnd( 'rev_deleted', RevisionRecord::DELETED_USER ) . ' = 0'
1030  ],
1031  __METHOD__,
1032  [ 'LIMIT' => 20 ],
1033  $revQuery['joins']
1034  );
1035 
1036  if ( $res === false ) {
1037  // This page has no revisions, which is very weird
1038  return false;
1039  }
1040 
1041  $hasHistory = ( $res->numRows() > 1 );
1042  $row = $dbr->fetchObject( $res );
1043 
1044  if ( $row ) { // $row is false if the only contributor is hidden
1045  $onlyAuthor = $row->rev_user_text;
1046  // Try to find a second contributor
1047  foreach ( $res as $row ) {
1048  if ( $row->rev_user_text != $onlyAuthor ) { // T24999
1049  $onlyAuthor = false;
1050  break;
1051  }
1052  }
1053  } else {
1054  $onlyAuthor = false;
1055  }
1056 
1057  // Generate the summary with a '$1' placeholder
1058  if ( $blank ) {
1059  // The current revision is blank and the one before is also
1060  // blank. It's just not our lucky day
1061  $reason = wfMessage( 'exbeforeblank', '$1' )->inContentLanguage()->text();
1062  } else {
1063  if ( $onlyAuthor ) {
1064  $reason = wfMessage(
1065  'excontentauthor',
1066  '$1',
1067  $onlyAuthor
1068  )->inContentLanguage()->text();
1069  } else {
1070  $reason = wfMessage( 'excontent', '$1' )->inContentLanguage()->text();
1071  }
1072  }
1073 
1074  if ( $reason == '-' ) {
1075  // Allow these UI messages to be blanked out cleanly
1076  return '';
1077  }
1078 
1079  // Max content length = max comment length - length of the comment (excl. $1)
1080  $text = $content ? $content->getTextForSummary( 255 - ( strlen( $reason ) - 2 ) ) : '';
1081 
1082  // Now replace the '$1' placeholder
1083  $reason = str_replace( '$1', $text, $reason );
1084 
1085  return $reason;
1086  }
1087 
1104  public function getUndoContent( $current, $undo, $undoafter, $undoIsLatest = false ) {
1105  Assert::parameterType( Revision::class . '|' . Content::class, $current, '$current' );
1106  if ( $current instanceof Content ) {
1107  Assert::parameter( $undo instanceof Content, '$undo',
1108  'Must be Content when $current is Content' );
1109  Assert::parameter( $undoafter instanceof Content, '$undoafter',
1110  'Must be Content when $current is Content' );
1111  $cur_content = $current;
1112  $undo_content = $undo;
1113  $undoafter_content = $undoafter;
1114  } else {
1115  Assert::parameter( $undo instanceof Revision, '$undo',
1116  'Must be Revision when $current is Revision' );
1117  Assert::parameter( $undoafter instanceof Revision, '$undoafter',
1118  'Must be Revision when $current is Revision' );
1119 
1120  $cur_content = $current->getContent();
1121 
1122  if ( empty( $cur_content ) ) {
1123  return false; // no page
1124  }
1125 
1126  $undo_content = $undo->getContent();
1127  $undoafter_content = $undoafter->getContent();
1128 
1129  if ( !$undo_content || !$undoafter_content ) {
1130  return false; // no content to undo
1131  }
1132 
1133  $undoIsLatest = $current->getId() === $undo->getId();
1134  }
1135 
1136  try {
1137  $this->checkModelID( $cur_content->getModel() );
1138  $this->checkModelID( $undo_content->getModel() );
1139  if ( !$undoIsLatest ) {
1140  // If we are undoing the most recent revision,
1141  // its ok to revert content model changes. However
1142  // if we are undoing a revision in the middle, then
1143  // doing that will be confusing.
1144  $this->checkModelID( $undoafter_content->getModel() );
1145  }
1146  } catch ( MWException $e ) {
1147  // If the revisions have different content models
1148  // just return false
1149  return false;
1150  }
1151 
1152  if ( $cur_content->equals( $undo_content ) ) {
1153  // No use doing a merge if it's just a straight revert.
1154  return $undoafter_content;
1155  }
1156 
1157  $undone_content = $this->merge3( $undo_content, $undoafter_content, $cur_content );
1158 
1159  return $undone_content;
1160  }
1161 
1178  public function makeParserOptions( $context ) {
1179  wfDeprecated( __METHOD__, '1.32' );
1181  }
1182 
1191  public function isParserCacheSupported() {
1192  return false;
1193  }
1194 
1204  public function supportsSections() {
1205  return false;
1206  }
1207 
1214  public function supportsCategories() {
1215  return true;
1216  }
1217 
1227  public function supportsRedirects() {
1228  return false;
1229  }
1230 
1236  public function supportsDirectEditing() {
1237  return false;
1238  }
1239 
1245  public function supportsDirectApiEditing() {
1246  return $this->supportsDirectEditing();
1247  }
1248 
1260  $fields['category'] = $engine->makeSearchFieldMapping(
1261  'category',
1263  );
1264  $fields['category']->setFlag( SearchIndexField::FLAG_CASEFOLD );
1265 
1266  $fields['external_link'] = $engine->makeSearchFieldMapping(
1267  'external_link',
1269  );
1270 
1271  $fields['outgoing_link'] = $engine->makeSearchFieldMapping(
1272  'outgoing_link',
1274  );
1275 
1276  $fields['template'] = $engine->makeSearchFieldMapping(
1277  'template',
1279  );
1280  $fields['template']->setFlag( SearchIndexField::FLAG_CASEFOLD );
1281 
1282  $fields['content_model'] = $engine->makeSearchFieldMapping(
1283  'content_model',
1285  );
1286 
1287  return $fields;
1288  }
1289 
1299  protected function addSearchField( &$fields, SearchEngine $engine, $name, $type ) {
1300  $fields[$name] = $engine->makeSearchFieldMapping( $name, $type );
1301  return $fields;
1302  }
1303 
1315  public function getDataForSearchIndex(
1316  WikiPage $page,
1319  ) {
1320  $fieldData = [];
1321  $content = $page->getContent();
1322 
1323  if ( $content ) {
1324  $searchDataExtractor = new ParserOutputSearchDataExtractor();
1325 
1326  $fieldData['category'] = $searchDataExtractor->getCategories( $output );
1327  $fieldData['external_link'] = $searchDataExtractor->getExternalLinks( $output );
1328  $fieldData['outgoing_link'] = $searchDataExtractor->getOutgoingLinks( $output );
1329  $fieldData['template'] = $searchDataExtractor->getTemplates( $output );
1330 
1331  $text = $content->getTextForSearchIndex();
1332 
1333  $fieldData['text'] = $text;
1334  $fieldData['source_text'] = $text;
1335  $fieldData['text_bytes'] = $content->getSize();
1336  $fieldData['content_model'] = $content->getModel();
1337  }
1338 
1339  Hooks::run( 'SearchDataForIndex', [ &$fieldData, $this, $page, $output, $engine ] );
1340  return $fieldData;
1341  }
1342 
1353  // TODO: MCR: ContentHandler should be called per slot, not for the whole page.
1354  // See T190066.
1355  $parserOptions = $page->makeParserOptions( 'canonical' );
1356  if ( $cache ) {
1357  $parserOutput = $cache->get( $page, $parserOptions );
1358  }
1359 
1360  if ( empty( $parserOutput ) ) {
1361  $renderer = MediaWikiServices::getInstance()->getRevisionRenderer();
1362  $parserOutput =
1363  $renderer->getRenderedRevision(
1364  $page->getRevision()->getRevisionRecord(),
1365  $parserOptions
1366  )->getRevisionParserOutput();
1367  if ( $cache ) {
1368  $cache->save( $parserOutput, $page, $parserOptions );
1369  }
1370  }
1371  return $parserOutput;
1372  }
1373 
1404  public function getSecondaryDataUpdates(
1405  Title $title,
1406  Content $content,
1407  $role,
1408  SlotRenderingProvider $slotOutput
1409  ) {
1410  return [];
1411  }
1412 
1441  public function getDeletionUpdates( Title $title, $role ) {
1442  return [];
1443  }
1444 
1445 }
merge3(Content $oldContent, Content $myContent, Content $yourContent)
Attempts to merge differences between three versions.
getAutoDeleteReason(Title $title, &$hasHistory)
Auto-generates a deletion reason.
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
supportsSections()
Returns true if this content model supports sections.
getArticleID( $flags=0)
Get the article ID for this Title from the link cache, adding it if necessary.
Definition: Title.php:3026
getSecondaryDataUpdates(Title $title, Content $content, $role, SlotRenderingProvider $slotOutput)
Returns a list of DeferrableUpdate objects for recording information about the given Content in some ...
getChangeTag(Content $oldContent=null, Content $newContent=null, $flags=0)
Return an applicable tag if one exists for the given edit or return null.
getAutosummary(Content $oldContent=null, Content $newContent=null, $flags=0)
Return an applicable auto-summary if one exists for the given edit.
getText()
Get the text form (spaces not underscores) of the main part.
Definition: Title.php:1002
return true to allow those checks to and false if checking is done remove or add to the links of a group of changes in EnhancedChangesList Hook subscribers can return false to omit this line from recentchanges use this to change the tables headers change it to an object instance and return false override the list derivative used $groups Array of ChangesListFilterGroup objects(added in 1.34) 'FileDeleteComplete' null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify as strings Extensions should add to this list prev or next $refreshCache
Definition: hooks.txt:1529
supportsRedirects()
Returns true if this content model supports redirects.
A lazy provider of ParserOutput objects for a revision&#39;s individual slots.
static getAllContentFormats()
static array $handlers
A Cache of ContentHandler instances by model id.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
unserializeContent( $blob, $format=null)
Unserializes a Content object of the type supported by this ContentHandler.
static cleanupHandlersCache()
Clean up handlers cache.
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2147
if(!isset( $args[0])) $lang
static getContentModels()
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
static getDefaultModelFor(Title $title)
Returns the name of the default content model to be used for the page with the given title...
importTransform( $blob, $format=null)
Apply import transformation (per default, returns $blob unchanged).
getModelID()
Returns the model id that identifies the content model this ContentHandler can handle.
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
inNamespace( $ns)
Returns true if the title is inside the specified namespace.
Definition: Title.php:1241
getTextForSearchIndex()
getParserOutputForIndexing(WikiPage $page, ParserCache $cache=null)
Produce page output suitable for indexing.
static getLocalizedName( $name, Language $lang=null)
Returns the localized name for a given content model.
B/C adapter for turning a DifferenceEngine into a SlotDiffRenderer.
getPageLanguage(Title $title, Content $content=null)
Get the language in which the content of the given page is written.
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
$wgContentHandlerTextFallback
How to react if a plain text version of a non-text Content object is requested using ContentHandler::...
This list may contain false positives That usually means there is additional text with links below the first Each row contains links to the first and second as well as the first line of the second redirect text
wfGetLangObj( $langcode=false)
Return a Language object from $langcode.
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 $output
Definition: hooks.txt:2205
return true to allow those checks to and false if checking is done remove or add to the links of a group of changes in EnhancedChangesList Hook subscribers can return false to omit this line from recentchanges use this to change the tables headers change it to an object instance and return false override the list derivative used $groups Array of ChangesListFilterGroup objects(added in 1.34) 'FileDeleteComplete' null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify as strings Extensions should add to this list prev or next refreshes the diff cache $unhide
Definition: hooks.txt:1529
static newCanonical( $context=null, $userLang=null)
Creates a "canonical" ParserOptions object.
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 it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check set to true or false to override the $wgMaxImageArea check result gives extension the possibility to transform it themselves $handler
Definition: hooks.txt:767
getSize()
Returns the content&#39;s nominal size in "bogo-bytes".
checkModelID( $model_id)
getRevision()
Get the latest revision.
Definition: WikiPage.php:783
exportTransform( $blob, $format=null)
Applies transformations on export (returns the blob unchanged per default).
const INDEX_TYPE_TEXT
TEXT fields are suitable for natural language and may be subject to analysis such as stemming...
getDeletionUpdates(Title $title, $role)
Returns a list of DeferrableUpdate objects for removing information about content in some secondary d...
__construct( $modelId, $formats)
Constructor, initializing the ContentHandler instance with its model ID and a list of supported forma...
$wgLang
Definition: Setup.php:940
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
static getForModelID( $modelId)
Returns the ContentHandler singleton for the given model ID.
Renders a slot diff by doing a text diff on the native representation.
return true to allow those checks to and false if checking is done remove or add to the links of a group of changes in EnhancedChangesList Hook subscribers can return false to omit this line from recentchanges use this to change the tables headers change it to an object instance and return false override the list derivative used $groups Array of ChangesListFilterGroup objects(added in 1.34) 'FileDeleteComplete' null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify as strings Extensions should add to this list prev or next refreshes the diff cache allow viewing deleted revs & $differenceEngine
Definition: hooks.txt:1529
Extracts data from ParserOutput for indexing in the search engine.
getActionOverrides()
Returns overrides for action handlers.
static getForContent(Content $content)
Returns the appropriate ContentHandler singleton for the given Content object.
$res
Definition: database.txt:21
static getContentText(Content $content=null)
Convenience function for getting flat text from a Content object.
getDiffEngineClass()
Returns the name of the diff engine to use.
isEmpty()
Returns true if this Content object represents empty content.
static getEngine()
Process $wgExternalDiffEngine and get a sane, usable engine.
getSlotDiffRenderer(IContextSource $context)
Get an appropriate SlotDiffRenderer for this content model.
makeRedirectContent(Title $destination, $text='')
Creates a new Content object that acts as a redirect to the given page, or null if redirects are not ...
$cache
Definition: mcc.php:33
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
makeSearchFieldMapping( $name, $type)
Create a search field definition.
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:767
makeEmptyContent()
Creates an empty Content object of the type supported by this ContentHandler.
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:912
const FLAG_CASEFOLD
Generic field flags.
static getQueryInfo( $options=[])
Return the tables, fields, and join conditions to be selected to create a new revision object...
Definition: Revision.php:511
static factory( $code)
Get a cached or new language object for a given language code.
Definition: Language.php:216
getNamespace()
Get the namespace index, i.e.
Definition: Title.php:1044
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:1748
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
const NS_MEDIAWIKI
Definition: Defines.php:68
isSupportedFormat( $format)
Returns true if $format is a serialization format supported by this ContentHandler, and false otherwise.
supportsDirectApiEditing()
Whether or not this content model supports direct editing via ApiEditPage.
the value to return A Title object or null for latest all implement SearchIndexField $engine
Definition: hooks.txt:2886
const ENGINE_PHP
Use the PHP diff implementation (DiffEngine).
canBeUsedOn(Title $title)
Determines whether the content type handled by this ContentHandler can be used for the main slot of t...
makeParserOptions( $context)
Get parser options suitable for rendering the primary article wikitext.
Definition: WikiPage.php:1950
static unstub(&$obj)
Unstubs an object, if it is a stub object.
Definition: StubObject.php:93
addSearchField(&$fields, SearchEngine $engine, $name, $type)
Add new field definition to array.
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
checkFormat( $format)
Convenient for checking whether a format provided as a parameter is actually supported.
const INDEX_TYPE_KEYWORD
KEYWORD fields are indexed without any processing, so are appropriate for e.g.
string [] $mSupportedFormats
const ENGINE_WIKIDIFF2
Use the wikidiff2 PHP module.
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
const EDIT_NEW
Definition: Defines.php:132
getContentModel( $flags=0)
Get the page&#39;s content model id, see the CONTENT_MODEL_XXX constants.
Definition: Title.php:1056
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not...
$wgContentHandlers
Plugins for page content model handling.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
$revQuery
serializeContent(Content $content, $format=null)
Serializes a Content object of the type supported by this ContentHandler.
getContent( $audience=RevisionRecord::FOR_PUBLIC, User $user=null)
Get the content of the current revision.
Definition: WikiPage.php:816
isParserCacheSupported()
Returns true for content models that support caching using the ParserCache mechanism.
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition: hooks.txt:2621
MediaWiki Logger LoggerFactory implements a PSR [0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method. MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances. The "Spi" in MediaWiki\Logger\Spi stands for "service provider interface". An SPI is an API intended to be implemented or extended by a third party. This software design pattern is intended to enable framework extension and replaceable components. It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki. The service provider interface allows the backend logging library to be implemented in multiple ways. The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime. This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance. Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
Definition: logger.txt:5
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
const ENGINE_EXTERNAL
Use an external executable.
getSlotDiffRendererInternal(IContextSource $context)
Return the SlotDiffRenderer appropriate for this content handler.
getTextForSummary( $maxLength=250)
Returns a textual representation of the content suitable for use in edit summaries and log messages...
const DB_REPLICA
Definition: defines.php:25
createDifferenceEngine(IContextSource $context, $old=0, $new=0, $rcid=0, $refreshCache=false, $unhide=false)
Factory for creating an appropriate DifferenceEngine for this content model.
getSupportedFormats()
Returns a list of serialization formats supported by the serializeContent() and unserializeContent() ...
getModel()
Returns the ID of the content model used by this Content object.
supportsDirectEditing()
Return true if this content model supports direct editing, such as via EditPage.
getDataForSearchIndex(WikiPage $page, ParserOutput $output, SearchEngine $engine)
Return fields to be indexed by search engine as representation of this document.
supportsCategories()
Returns true if this content model supports categories.
static makeContent( $text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
getChangeType(Content $oldContent=null, Content $newContent=null, $flags=0)
Return type of change if one exists for the given edit.
$content
Definition: pageupdater.txt:72
getFieldsForSearchIndex(SearchEngine $engine)
Get fields definition for search index.
makeParserOptions( $context)
Get parser options suitable for rendering and caching the article.
getPageViewLanguage(Title $title, Content $content=null)
Get the language in which the content of this page is written when viewed by user.
getDefaultFormat()
The format used for serialization/deserialization by default by this ContentHandler.
static singleton()
Get the signleton instance of this class.
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
getUndoContent( $current, $undo, $undoafter, $undoIsLatest=false)
Get the Content object that needs to be saved in order to undo all revisions between $undo and $undoa...