MediaWiki  master
ContentHandler.php
Go to the documentation of this file.
1 <?php
2 
34 
54 abstract class ContentHandler {
84  public static function getContentText( Content $content = null ) {
86 
87  if ( is_null( $content ) ) {
88  return '';
89  }
90 
91  if ( $content instanceof TextContent ) {
92  return $content->getText();
93  }
94 
95  wfDebugLog( 'ContentHandler', 'Accessing ' . $content->getModel() . ' content as text!' );
96 
97  if ( $wgContentHandlerTextFallback == 'fail' ) {
98  throw new MWException(
99  "Attempt to get text from Content with model " .
100  $content->getModel()
101  );
102  }
103 
104  if ( $wgContentHandlerTextFallback == 'serialize' ) {
105  return $content->serialize();
106  }
107 
108  return null;
109  }
110 
134  public static function makeContent( $text, Title $title = null,
135  $modelId = null, $format = null ) {
136  if ( is_null( $modelId ) ) {
137  if ( is_null( $title ) ) {
138  throw new MWException( "Must provide a Title object or a content model ID." );
139  }
140 
141  $modelId = $title->getContentModel();
142  }
143 
144  $handler = self::getForModelID( $modelId );
145 
146  return $handler->unserializeContent( $text, $format );
147  }
148 
185  public static function getDefaultModelFor( Title $title ) {
186  $slotRoleregistry = MediaWikiServices::getInstance()->getSlotRoleRegistry();
187  $mainSlotHandler = $slotRoleregistry->getRoleHandler( 'main' );
188  return $mainSlotHandler->getDefaultModel( $title );
189  }
190 
200  public static function getForTitle( Title $title ) {
201  $modelId = $title->getContentModel();
202 
203  return self::getForModelID( $modelId );
204  }
205 
216  public static function getForContent( Content $content ) {
217  $modelId = $content->getModel();
218 
219  return self::getForModelID( $modelId );
220  }
221 
225  protected static $handlers;
226 
253  public static function getForModelID( $modelId ) {
254  global $wgContentHandlers;
255 
256  if ( isset( self::$handlers[$modelId] ) ) {
257  return self::$handlers[$modelId];
258  }
259 
260  if ( empty( $wgContentHandlers[$modelId] ) ) {
261  $handler = null;
262 
263  Hooks::run( 'ContentHandlerForModelID', [ $modelId, &$handler ] );
264 
265  if ( $handler === null ) {
266  throw new MWUnknownContentModelException( $modelId );
267  }
268 
269  if ( !( $handler instanceof ContentHandler ) ) {
270  throw new MWException( "ContentHandlerForModelID must supply a ContentHandler instance" );
271  }
272  } else {
273  $classOrCallback = $wgContentHandlers[$modelId];
274 
275  if ( is_callable( $classOrCallback ) ) {
276  $handler = call_user_func( $classOrCallback, $modelId );
277  } else {
278  $handler = new $classOrCallback( $modelId );
279  }
280 
281  if ( !( $handler instanceof ContentHandler ) ) {
282  throw new MWException( "$classOrCallback from \$wgContentHandlers is not " .
283  "compatible with ContentHandler" );
284  }
285  }
286 
287  wfDebugLog( 'ContentHandler', 'Created handler for ' . $modelId
288  . ': ' . get_class( $handler ) );
289 
290  self::$handlers[$modelId] = $handler;
291 
292  return self::$handlers[$modelId];
293  }
294 
298  public static function cleanupHandlersCache() {
299  self::$handlers = [];
300  }
301 
315  public static function getLocalizedName( $name, Language $lang = null ) {
316  // Messages: content-model-wikitext, content-model-text,
317  // content-model-javascript, content-model-css
318  $key = "content-model-$name";
319 
320  $msg = wfMessage( $key );
321  if ( $lang ) {
322  $msg->inLanguage( $lang );
323  }
324 
325  return $msg->exists() ? $msg->plain() : $name;
326  }
327 
328  public static function getContentModels() {
329  global $wgContentHandlers;
330 
331  $models = array_keys( $wgContentHandlers );
332  Hooks::run( 'GetContentModels', [ &$models ] );
333  return $models;
334  }
335 
336  public static function getAllContentFormats() {
337  global $wgContentHandlers;
338 
339  $formats = [];
340 
341  foreach ( $wgContentHandlers as $model => $class ) {
342  $handler = self::getForModelID( $model );
343  $formats = array_merge( $formats, $handler->getSupportedFormats() );
344  }
345 
346  $formats = array_unique( $formats );
347 
348  return $formats;
349  }
350 
351  // ------------------------------------------------------------------------
352 
356  protected $mModelID;
357 
362 
372  public function __construct( $modelId, $formats ) {
373  $this->mModelID = $modelId;
374  $this->mSupportedFormats = $formats;
375  }
376 
387  abstract public function serializeContent( Content $content, $format = null );
388 
399  public function exportTransform( $blob, $format = null ) {
400  return $blob;
401  }
402 
413  abstract public function unserializeContent( $blob, $format = null );
414 
426  public function importTransform( $blob, $format = null ) {
427  return $blob;
428  }
429 
438  abstract public function makeEmptyContent();
439 
457  public function makeRedirectContent( Title $destination, $text = '' ) {
458  return null;
459  }
460 
469  public function getModelID() {
470  return $this->mModelID;
471  }
472 
481  protected function checkModelID( $model_id ) {
482  if ( $model_id !== $this->mModelID ) {
483  throw new MWException( "Bad content model: " .
484  "expected {$this->mModelID} " .
485  "but got $model_id." );
486  }
487  }
488 
498  public function getSupportedFormats() {
500  }
501 
513  public function getDefaultFormat() {
514  return $this->mSupportedFormats[0];
515  }
516 
530  public function isSupportedFormat( $format ) {
531  if ( !$format ) {
532  return true; // this means "use the default"
533  }
534 
535  return in_array( $format, $this->mSupportedFormats );
536  }
537 
545  protected function checkFormat( $format ) {
546  if ( !$this->isSupportedFormat( $format ) ) {
547  throw new MWException(
548  "Format $format is not supported for content model "
549  . $this->getModelID()
550  );
551  }
552  }
553 
569  public function getActionOverrides() {
570  return [];
571  }
572 
600  public function createDifferenceEngine( IContextSource $context, $old = 0, $new = 0,
601  $rcid = 0, // FIXME: Deprecated, no longer used
602  $refreshCache = false, $unhide = false
603  ) {
604  $diffEngineClass = $this->getDiffEngineClass();
605  $differenceEngine = new $diffEngineClass( $context, $old, $new, $rcid, $refreshCache, $unhide );
606  Hooks::run( 'GetDifferenceEngine', [ $context, $old, $new, $refreshCache, $unhide,
607  &$differenceEngine ] );
608  return $differenceEngine;
609  }
610 
617  final public function getSlotDiffRenderer( IContextSource $context ) {
618  $slotDiffRenderer = $this->getSlotDiffRendererInternal( $context );
619  if ( get_class( $slotDiffRenderer ) === TextSlotDiffRenderer::class ) {
620  // To keep B/C, when SlotDiffRenderer is not overridden for a given content type
621  // but DifferenceEngine is, use that instead.
622  $differenceEngine = $this->createDifferenceEngine( $context );
623  if ( get_class( $differenceEngine ) !== DifferenceEngine::class ) {
624  // TODO turn this into a deprecation warning in a later release
625  LoggerFactory::getInstance( 'diff' )->info(
626  'Falling back to DifferenceEngineSlotDiffRenderer', [
627  'modelID' => $this->getModelID(),
628  'DifferenceEngine' => get_class( $differenceEngine ),
629  ] );
630  $slotDiffRenderer = new DifferenceEngineSlotDiffRenderer( $differenceEngine );
631  }
632  }
633  Hooks::run( 'GetSlotDiffRenderer', [ $this, &$slotDiffRenderer, $context ] );
634  return $slotDiffRenderer;
635  }
636 
643  $contentLanguage = MediaWikiServices::getInstance()->getContentLanguage();
644  $statsdDataFactory = MediaWikiServices::getInstance()->getStatsdDataFactory();
645  $slotDiffRenderer = new TextSlotDiffRenderer();
646  $slotDiffRenderer->setStatsdDataFactory( $statsdDataFactory );
647  // XXX using the page language would be better, but it's unclear how that should be injected
648  $slotDiffRenderer->setLanguage( $contentLanguage );
649 
651  if ( $engine === false ) {
652  $slotDiffRenderer->setEngine( TextSlotDiffRenderer::ENGINE_PHP );
653  } elseif ( $engine === 'wikidiff2' ) {
654  $slotDiffRenderer->setEngine( TextSlotDiffRenderer::ENGINE_WIKIDIFF2 );
655  } else {
656  $slotDiffRenderer->setEngine( TextSlotDiffRenderer::ENGINE_EXTERNAL, $engine );
657  }
658 
659  return $slotDiffRenderer;
660  }
661 
681  public function getPageLanguage( Title $title, Content $content = null ) {
682  global $wgLang;
683  $pageLang = MediaWikiServices::getInstance()->getContentLanguage();
684 
685  if ( $title->inNamespace( NS_MEDIAWIKI ) ) {
686  // Parse mediawiki messages with correct target language
687  list( /* $unused */, $lang ) = MessageCache::singleton()->figureMessage( $title->getText() );
688  $pageLang = Language::factory( $lang );
689  }
690 
691  // Simplify hook handlers by only passing objects of one type, in case nothing
692  // else has unstubbed the StubUserLang object by now.
693  StubObject::unstub( $wgLang );
694 
695  Hooks::run( 'PageContentLanguage', [ $title, &$pageLang, $wgLang ] );
696 
697  return wfGetLangObj( $pageLang );
698  }
699 
720  public function getPageViewLanguage( Title $title, Content $content = null ) {
721  $pageLang = $this->getPageLanguage( $title, $content );
722 
723  if ( $title->getNamespace() !== NS_MEDIAWIKI ) {
724  // If the user chooses a variant, the content is actually
725  // in a language whose code is the variant code.
726  $variant = $pageLang->getPreferredVariant();
727  if ( $pageLang->getCode() !== $variant ) {
728  $pageLang = Language::factory( $variant );
729  }
730  }
731 
732  return $pageLang;
733  }
734 
753  public function canBeUsedOn( Title $title ) {
754  $ok = true;
755 
756  Hooks::run( 'ContentModelCanBeUsedOn', [ $this->getModelID(), $title, &$ok ] );
757 
758  return $ok;
759  }
760 
768  protected function getDiffEngineClass() {
770  }
771 
786  public function merge3( Content $oldContent, Content $myContent, Content $yourContent ) {
787  return false;
788  }
789 
801  private function getChangeType(
802  Content $oldContent = null,
803  Content $newContent = null,
804  $flags = 0
805  ) {
806  $oldTarget = $oldContent !== null ? $oldContent->getRedirectTarget() : null;
807  $newTarget = $newContent !== null ? $newContent->getRedirectTarget() : null;
808 
809  // We check for the type of change in the given edit, and return string key accordingly
810 
811  // Blanking of a page
812  if ( $oldContent && $oldContent->getSize() > 0 &&
813  $newContent && $newContent->getSize() === 0
814  ) {
815  return 'blank';
816  }
817 
818  // Redirects
819  if ( $newTarget ) {
820  if ( !$oldTarget ) {
821  // New redirect page (by creating new page or by changing content page)
822  return 'new-redirect';
823  } elseif ( !$newTarget->equals( $oldTarget ) ||
824  $oldTarget->getFragment() !== $newTarget->getFragment()
825  ) {
826  // Redirect target changed
827  return 'changed-redirect-target';
828  }
829  } elseif ( $oldTarget ) {
830  // Changing an existing redirect into a non-redirect
831  return 'removed-redirect';
832  }
833 
834  // New page created
835  if ( $flags & EDIT_NEW && $newContent ) {
836  if ( $newContent->getSize() === 0 ) {
837  // New blank page
838  return 'newblank';
839  } else {
840  return 'newpage';
841  }
842  }
843 
844  // Removing more than 90% of the page
845  if ( $oldContent && $newContent && $oldContent->getSize() > 10 * $newContent->getSize() ) {
846  return 'replace';
847  }
848 
849  // Content model changed
850  if ( $oldContent && $newContent && $oldContent->getModel() !== $newContent->getModel() ) {
851  return 'contentmodelchange';
852  }
853 
854  return null;
855  }
856 
868  public function getAutosummary(
869  Content $oldContent = null,
870  Content $newContent = null,
871  $flags = 0
872  ) {
873  $changeType = $this->getChangeType( $oldContent, $newContent, $flags );
874 
875  // There's no applicable auto-summary for our case, so our auto-summary is empty.
876  if ( !$changeType ) {
877  return '';
878  }
879 
880  // Decide what kind of auto-summary is needed.
881  switch ( $changeType ) {
882  case 'new-redirect':
883  $newTarget = $newContent->getRedirectTarget();
884  $truncatedtext = $newContent->getTextForSummary(
885  250
886  - strlen( wfMessage( 'autoredircomment' )->inContentLanguage()->text() )
887  - strlen( $newTarget->getFullText() )
888  );
889 
890  return wfMessage( 'autoredircomment', $newTarget->getFullText() )
891  ->plaintextParams( $truncatedtext )->inContentLanguage()->text();
892  case 'changed-redirect-target':
893  $oldTarget = $oldContent->getRedirectTarget();
894  $newTarget = $newContent->getRedirectTarget();
895 
896  $truncatedtext = $newContent->getTextForSummary(
897  250
898  - strlen( wfMessage( 'autosumm-changed-redirect-target' )
899  ->inContentLanguage()->text() )
900  - strlen( $oldTarget->getFullText() )
901  - strlen( $newTarget->getFullText() )
902  );
903 
904  return wfMessage( 'autosumm-changed-redirect-target',
905  $oldTarget->getFullText(),
906  $newTarget->getFullText() )
907  ->rawParams( $truncatedtext )->inContentLanguage()->text();
908  case 'removed-redirect':
909  $oldTarget = $oldContent->getRedirectTarget();
910  $truncatedtext = $newContent->getTextForSummary(
911  250
912  - strlen( wfMessage( 'autosumm-removed-redirect' )
913  ->inContentLanguage()->text() )
914  - strlen( $oldTarget->getFullText() ) );
915 
916  return wfMessage( 'autosumm-removed-redirect', $oldTarget->getFullText() )
917  ->rawParams( $truncatedtext )->inContentLanguage()->text();
918  case 'newpage':
919  // If they're making a new article, give its text, truncated, in the summary.
920  $truncatedtext = $newContent->getTextForSummary(
921  200 - strlen( wfMessage( 'autosumm-new' )->inContentLanguage()->text() ) );
922 
923  return wfMessage( 'autosumm-new' )->rawParams( $truncatedtext )
924  ->inContentLanguage()->text();
925  case 'blank':
926  return wfMessage( 'autosumm-blank' )->inContentLanguage()->text();
927  case 'replace':
928  $truncatedtext = $newContent->getTextForSummary(
929  200 - strlen( wfMessage( 'autosumm-replace' )->inContentLanguage()->text() ) );
930 
931  return wfMessage( 'autosumm-replace' )->rawParams( $truncatedtext )
932  ->inContentLanguage()->text();
933  case 'newblank':
934  return wfMessage( 'autosumm-newblank' )->inContentLanguage()->text();
935  default:
936  return '';
937  }
938  }
939 
951  public function getChangeTag(
952  Content $oldContent = null,
953  Content $newContent = null,
954  $flags = 0
955  ) {
956  $changeType = $this->getChangeType( $oldContent, $newContent, $flags );
957 
958  // There's no applicable tag for this change.
959  if ( !$changeType ) {
960  return null;
961  }
962 
963  // Core tags use the same keys as ones returned from $this->getChangeType()
964  // but prefixed with pseudo namespace 'mw-', so we add the prefix before checking
965  // if this type of change should be tagged
966  $tag = 'mw-' . $changeType;
967 
968  // Not all change types are tagged, so we check against the list of defined tags.
969  if ( in_array( $tag, ChangeTags::getSoftwareTags() ) ) {
970  return $tag;
971  }
972 
973  return null;
974  }
975 
991  public function getAutoDeleteReason( Title $title, &$hasHistory ) {
992  $dbr = wfGetDB( DB_REPLICA );
993 
994  // Get the last revision
995  $rev = Revision::newFromTitle( $title );
996 
997  if ( is_null( $rev ) ) {
998  return false;
999  }
1000 
1001  // Get the article's contents
1002  $content = $rev->getContent();
1003  $blank = false;
1004 
1005  // If the page is blank, use the text from the previous revision,
1006  // which can only be blank if there's a move/import/protect dummy
1007  // revision involved
1008  if ( !$content || $content->isEmpty() ) {
1009  $prev = $rev->getPrevious();
1010 
1011  if ( $prev ) {
1012  $rev = $prev;
1013  $content = $rev->getContent();
1014  $blank = true;
1015  }
1016  }
1017 
1018  $this->checkModelID( $rev->getContentModel() );
1019 
1020  // Find out if there was only one contributor
1021  // Only scan the last 20 revisions
1023  $res = $dbr->select(
1024  $revQuery['tables'],
1025  [ 'rev_user_text' => $revQuery['fields']['rev_user_text'] ],
1026  [
1027  'rev_page' => $title->getArticleID(),
1028  $dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0'
1029  ],
1030  __METHOD__,
1031  [ 'LIMIT' => 20 ],
1032  $revQuery['joins']
1033  );
1034 
1035  if ( $res === false ) {
1036  // This page has no revisions, which is very weird
1037  return false;
1038  }
1039 
1040  $hasHistory = ( $res->numRows() > 1 );
1041  $row = $dbr->fetchObject( $res );
1042 
1043  if ( $row ) { // $row is false if the only contributor is hidden
1044  $onlyAuthor = $row->rev_user_text;
1045  // Try to find a second contributor
1046  foreach ( $res as $row ) {
1047  if ( $row->rev_user_text != $onlyAuthor ) { // T24999
1048  $onlyAuthor = false;
1049  break;
1050  }
1051  }
1052  } else {
1053  $onlyAuthor = false;
1054  }
1055 
1056  // Generate the summary with a '$1' placeholder
1057  if ( $blank ) {
1058  // The current revision is blank and the one before is also
1059  // blank. It's just not our lucky day
1060  $reason = wfMessage( 'exbeforeblank', '$1' )->inContentLanguage()->text();
1061  } else {
1062  if ( $onlyAuthor ) {
1063  $reason = wfMessage(
1064  'excontentauthor',
1065  '$1',
1066  $onlyAuthor
1067  )->inContentLanguage()->text();
1068  } else {
1069  $reason = wfMessage( 'excontent', '$1' )->inContentLanguage()->text();
1070  }
1071  }
1072 
1073  if ( $reason == '-' ) {
1074  // Allow these UI messages to be blanked out cleanly
1075  return '';
1076  }
1077 
1078  // Max content length = max comment length - length of the comment (excl. $1)
1079  $text = $content ? $content->getTextForSummary( 255 - ( strlen( $reason ) - 2 ) ) : '';
1080 
1081  // Now replace the '$1' placeholder
1082  $reason = str_replace( '$1', $text, $reason );
1083 
1084  return $reason;
1085  }
1086 
1103  public function getUndoContent( $current, $undo, $undoafter, $undoIsLatest = false ) {
1104  Assert::parameterType( Revision::class . '|' . Content::class, $current, '$current' );
1105  if ( $current instanceof Content ) {
1106  Assert::parameter( $undo instanceof Content, '$undo',
1107  'Must be Content when $current is Content' );
1108  Assert::parameter( $undoafter instanceof Content, '$undoafter',
1109  'Must be Content when $current is Content' );
1110  $cur_content = $current;
1111  $undo_content = $undo;
1112  $undoafter_content = $undoafter;
1113  } else {
1114  Assert::parameter( $undo instanceof Revision, '$undo',
1115  'Must be Revision when $current is Revision' );
1116  Assert::parameter( $undoafter instanceof Revision, '$undoafter',
1117  'Must be Revision when $current is Revision' );
1118 
1119  $cur_content = $current->getContent();
1120 
1121  if ( empty( $cur_content ) ) {
1122  return false; // no page
1123  }
1124 
1125  $undo_content = $undo->getContent();
1126  $undoafter_content = $undoafter->getContent();
1127 
1128  if ( !$undo_content || !$undoafter_content ) {
1129  return false; // no content to undo
1130  }
1131 
1132  $undoIsLatest = $current->getId() === $undo->getId();
1133  }
1134 
1135  try {
1136  $this->checkModelID( $cur_content->getModel() );
1137  $this->checkModelID( $undo_content->getModel() );
1138  if ( !$undoIsLatest ) {
1139  // If we are undoing the most recent revision,
1140  // its ok to revert content model changes. However
1141  // if we are undoing a revision in the middle, then
1142  // doing that will be confusing.
1143  $this->checkModelID( $undoafter_content->getModel() );
1144  }
1145  } catch ( MWException $e ) {
1146  // If the revisions have different content models
1147  // just return false
1148  return false;
1149  }
1150 
1151  if ( $cur_content->equals( $undo_content ) ) {
1152  // No use doing a merge if it's just a straight revert.
1153  return $undoafter_content;
1154  }
1155 
1156  $undone_content = $this->merge3( $undo_content, $undoafter_content, $cur_content );
1157 
1158  return $undone_content;
1159  }
1160 
1177  public function makeParserOptions( $context ) {
1178  wfDeprecated( __METHOD__, '1.32' );
1180  }
1181 
1190  public function isParserCacheSupported() {
1191  return false;
1192  }
1193 
1203  public function supportsSections() {
1204  return false;
1205  }
1206 
1213  public function supportsCategories() {
1214  return true;
1215  }
1216 
1226  public function supportsRedirects() {
1227  return false;
1228  }
1229 
1235  public function supportsDirectEditing() {
1236  return false;
1237  }
1238 
1244  public function supportsDirectApiEditing() {
1245  return $this->supportsDirectEditing();
1246  }
1247 
1259  $fields['category'] = $engine->makeSearchFieldMapping(
1260  'category',
1262  );
1263  $fields['category']->setFlag( SearchIndexField::FLAG_CASEFOLD );
1264 
1265  $fields['external_link'] = $engine->makeSearchFieldMapping(
1266  'external_link',
1268  );
1269 
1270  $fields['outgoing_link'] = $engine->makeSearchFieldMapping(
1271  'outgoing_link',
1273  );
1274 
1275  $fields['template'] = $engine->makeSearchFieldMapping(
1276  'template',
1278  );
1279  $fields['template']->setFlag( SearchIndexField::FLAG_CASEFOLD );
1280 
1281  $fields['content_model'] = $engine->makeSearchFieldMapping(
1282  'content_model',
1284  );
1285 
1286  return $fields;
1287  }
1288 
1298  protected function addSearchField( &$fields, SearchEngine $engine, $name, $type ) {
1299  $fields[$name] = $engine->makeSearchFieldMapping( $name, $type );
1300  return $fields;
1301  }
1302 
1314  public function getDataForSearchIndex(
1315  WikiPage $page,
1318  ) {
1319  $fieldData = [];
1320  $content = $page->getContent();
1321 
1322  if ( $content ) {
1323  $searchDataExtractor = new ParserOutputSearchDataExtractor();
1324 
1325  $fieldData['category'] = $searchDataExtractor->getCategories( $output );
1326  $fieldData['external_link'] = $searchDataExtractor->getExternalLinks( $output );
1327  $fieldData['outgoing_link'] = $searchDataExtractor->getOutgoingLinks( $output );
1328  $fieldData['template'] = $searchDataExtractor->getTemplates( $output );
1329 
1330  $text = $content->getTextForSearchIndex();
1331 
1332  $fieldData['text'] = $text;
1333  $fieldData['source_text'] = $text;
1334  $fieldData['text_bytes'] = $content->getSize();
1335  $fieldData['content_model'] = $content->getModel();
1336  }
1337 
1338  Hooks::run( 'SearchDataForIndex', [ &$fieldData, $this, $page, $output, $engine ] );
1339  return $fieldData;
1340  }
1341 
1352  // TODO: MCR: ContentHandler should be called per slot, not for the whole page.
1353  // See T190066.
1354  $parserOptions = $page->makeParserOptions( 'canonical' );
1355  if ( $cache ) {
1356  $parserOutput = $cache->get( $page, $parserOptions );
1357  }
1358 
1359  if ( empty( $parserOutput ) ) {
1360  $renderer = MediaWikiServices::getInstance()->getRevisionRenderer();
1361  $parserOutput =
1362  $renderer->getRenderedRevision(
1363  $page->getRevision()->getRevisionRecord(),
1364  $parserOptions
1365  )->getRevisionParserOutput();
1366  if ( $cache ) {
1367  $cache->save( $parserOutput, $page, $parserOptions );
1368  }
1369  }
1370  return $parserOutput;
1371  }
1372 
1403  public function getSecondaryDataUpdates(
1404  Title $title,
1405  Content $content,
1406  $role,
1407  SlotRenderingProvider $slotOutput
1408  ) {
1409  return [];
1410  }
1411 
1440  public function getDeletionUpdates( Title $title, $role ) {
1441  return [];
1442  }
1443 
1444 }
getContent( $audience=Revision::FOR_PUBLIC, User $user=null)
Get the content of the current revision.
Definition: WikiPage.php:816
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:3005
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:984
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:2159
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:1217
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.
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:1585
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:2217
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:780
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:928
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.
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:1585
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:780
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:925
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:1026
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
const NS_MEDIAWIKI
Definition: Defines.php:72
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:2898
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:1945
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.
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:1585
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
const DELETED_USER
Definition: Revision.php:48
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:152
getContentModel( $flags=0)
Get the page&#39;s content model id, see the CONTENT_MODEL_XXX constants.
Definition: Title.php:1038
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.
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:2633
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...