Debian Codegraph @

extensions/Scribunto/includes/ScribuntoContentHandler.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Extension\Scribunto;
4
5 use MediaWiki\Content\CodeContentHandler;
6 use MediaWiki\Content\Content;
7 use MediaWiki\Content\Renderer\ContentParseParams;
8 use MediaWiki\Content\TextContent;
9 use MediaWiki\Content\ValidationParams;
10 use MediaWiki\Html\Html;
11 use MediaWiki\MediaWikiServices;
12 use MediaWiki\Page\PageIdentity;
13 use MediaWiki\Parser\ParserOutput;
14 use MediaWiki\Registration\ExtensionRegistry;
15 use MediaWiki\Status\Status;
16 use MediaWiki\SyntaxHighlight\SyntaxHighlight;
17 use MediaWiki\Title\Title;
18
19 /**
20 * Scribunto Content Handler
21 *
22 * @file
23 * @ingroup Extensions
24 * @ingroup Scribunto
25 *
26 * @author Brad Jorsch <[email protected]>
27 */
28
29 class ScribuntoContentHandler extends CodeContentHandler {
30
31 /**
32 * @param string $modelId
33 * @param string[] $formats
34 */
35 public function __construct(
36 $modelId = CONTENT_MODEL_SCRIBUNTO, $formats = [ CONTENT_FORMAT_TEXT ]
37 ) {
38 parent::__construct( $modelId, $formats );
39 }
40
41 /** @inheritDoc */
42 protected function getContentClass() {
43 return ScribuntoContent::class;
44 }
45
46 /**
47 * @param string $format
48 * @return bool
49 */
50 public function isSupportedFormat( $format ) {
51 // An error in an earlier version of Scribunto means we might see this.
52 if ( $format === 'CONTENT_FORMAT_TEXT' ) {
53 $format = CONTENT_FORMAT_TEXT;
54 }
55 return parent::isSupportedFormat( $format );
56 }
57
58 /**
59 * Only allow this content handler to be used in the Module namespace
60 * @param Title $title
61 * @return bool
62 */
63 public function canBeUsedOn( Title $title ) {
64 if ( $title->getNamespace() !== NS_MODULE ) {
65 return false;
66 }
67
68 return parent::canBeUsedOn( $title );
69 }
70
71 /** @inheritDoc */
72 public function supportsPreloadContent(): bool {
73 return true;
74 }
75
76 /**
77 * @inheritDoc
78 */
79 public function validateSave(
80 Content $content,
81 ValidationParams $validationParams
82 ) {
83 '@phan-var ScribuntoContent $content';
84 return $this->validate( $content, $validationParams->getPageIdentity() );
85 }
86
87 /**
88 * Checks whether the script is valid
89 *
90 * @param TextContent $content
91 * @param PageIdentity $page
92 * @return Status
93 */
94 public function validate( TextContent $content, PageIdentity $page ) {
95 if ( !( $page instanceof Title ) ) {
96 $titleFactory = MediaWikiServices::getInstance()->getTitleFactory();
97 $page = $titleFactory->newFromPageIdentity( $page );
98 }
99
100 $engine = Scribunto::newDefaultEngine();
101 $engine->setTitle( $page );
102 return $engine->validate( $content->getText(), $page->getPrefixedDBkey() );
103 }
104
105 /**
106 * @inheritDoc
107 */
108 protected function fillParserOutput(
109 Content $content,
110 ContentParseParams $cpoParams,
111 ParserOutput &$parserOutput
112 ) {
113 '@phan-var ScribuntoContent $content';
114 $page = $cpoParams->getPage();
115 $title = Title::newFromPageReference( $page );
116 $parserOptions = $cpoParams->getParserOptions();
117 $revId = $cpoParams->getRevId();
118 $generateHtml = $cpoParams->getGenerateHtml();
119 $parser = MediaWikiServices::getInstance()->getParserFactory()->getInstance();
120 $sourceCode = $content->getText();
121 $docTitle = Scribunto::getDocPage( $title );
122 $docMsg = $docTitle ? wfMessage(
123 $docTitle->exists() ? 'scribunto-doc-page-show' : 'scribunto-doc-page-does-not-exist',
124 $docTitle->getPrefixedText()
125 )->inContentLanguage() : null;
126
127 // Accumulate the following output:
128 // - docs (if any)
129 // - validation error (if any)
130 // - highlighted source code
131 $html = '';
132
133 if ( $docMsg && !$docMsg->isDisabled() ) {
134 // In order to allow the doc page to categorize the Module page,
135 // we need access to the ParserOutput of the doc page.
136 // This is why we can't simply use $docMsg->parse().
137 //
138 // We also can't use use ParserOutput::getText and ParserOutput::collectMetadata
139 // to merge the result into $parserOutput, because doing so would remove the
140 // ability for Skin/OutputPage to (post-cache) decide on the ParserOutput::getText
141 // parameters edit section links, TOC, and user language etc.
142 //
143 // So instead, this uses the doc page's ParserOutput as the actual ParserOutput
144 // we return, and add the other stuff to it. This is the only way to leave
145 // skin-decisions undecided and in-tact.
146 if ( $parserOptions->getTargetLanguage() === null ) {
147 $parserOptions->setTargetLanguage( $docTitle->getPageLanguage() );
148 }
149 $parserOutput = $parser->parse( $docMsg->plain(), $page, $parserOptions, true, true, $revId );
150
151 // Code is displayed and syntax highlighted as LTR, but the
152 // documentation can be RTL on RTL-language wikis.
153 //
154 // As long as we leave the $parserOutput in-tact, it will preserve the appropiate
155 // lang, dir, and class attributes (mw-content-ltr or mw-content-rtl) as needed
156 // for correct styling and accessiblity of the documentation page content.
157 // These will be applied when OutputPage eventually calls ParserOutput::getText()
158 $html .= $parserOutput->getRawText();
159 } else {
160 $parserOutput = new ParserOutput();
161 $parserOutput->setLanguage( $parserOptions->getTargetLanguage() ?? $docTitle->getPageLanguage() );
162 }
163
164 if ( $docTitle ) {
165 // Mark the doc page as transcluded, so that edits to the doc page will
166 // purge this Module page.
167 $parserOutput->addTemplate( $docTitle, $docTitle->getArticleID(), $docTitle->getLatestRevID() );
168 }
169
170 // Validate the script, and include an error message and tracking
171 // category if it's invalid
172 $status = $this->validate( $content, $title );
173 if ( !$status->isOK() ) {
174 // FIXME: This uses a Status object, which in turn uses global RequestContext
175 // to localize the message. This would poison the ParserCache.
176 //
177 // But, this code is almost unreachable in practice because there has
178 // been no way to create a Module page with invalid content since 2014
179 // (we validate and abort on edit, undelete, content-model change etc.).
180 // See also T304381.
181 $html .= Html::rawElement( 'div', [ 'class' => 'errorbox' ],
182 $status->getHTML( 'scribunto-error-short', 'scribunto-error-long' )
183 );
184 $trackingCategories = MediaWikiServices::getInstance()->getTrackingCategories();
185 $trackingCategories->addTrackingCategory( $parserOutput, 'scribunto-module-with-errors-category', $page );
186 }
187
188 if ( !$generateHtml ) {
189 // The doc page and validation error produce metadata and must happen
190 // unconditionally. The next step (syntax highlight) can be skipped if
191 // we don't actually need the HTML.
192 $parserOutput->setRawText( '' );
193 return;
194 }
195
196 $engine = Scribunto::newDefaultEngine();
197 $engine->setTitle( $title );
198 $codeLang = $engine->getGeSHiLanguage();
199 $html .= $this->highlight( $sourceCode, $parserOutput, $codeLang );
200
201 $parserOutput->setRawText( $html );
202 }
203
204 /**
205 * Get syntax highlighted code and add metadata to output.
206 *
207 * If SyntaxHighlight is not possible, falls back to a `<pre>` element.
208 *
209 * @param string $source Source code
210 * @param ParserOutput $parserOutput
211 * @param string|false $codeLang
212 * @return string HTML
213 */
214 private function highlight( $source, ParserOutput $parserOutput, $codeLang ) {
215 $useGeSHi = MediaWikiServices::getInstance()->getMainConfig()->get( 'ScribuntoUseGeSHi' );
216 if (
217 $useGeSHi && $codeLang && ExtensionRegistry::getInstance()->isLoaded( 'SyntaxHighlight' )
218 ) {
219 $status = SyntaxHighlight::highlight( $source, $codeLang, [ 'line' => true, 'linelinks' => 'L' ] );
220 if ( $status->isGood() ) {
221 // @todo replace addModuleStyles line with the appropriate call on
222 // SyntaxHighlight once one is created
223 $parserOutput->addModuleStyles( [ 'ext.pygments' ] );
224 $parserOutput->addModules( [ 'ext.pygments.view' ] );
225 return $status->getValue();
226 }
227 }
228
229 return Html::element( 'pre', [
230 // Same as CodeContentHandler
231 'lang' => 'en',
232 'dir' => 'ltr',
233 'class' => 'mw-code mw-script'
234 ], "\n$source\n" );
235 }
236
237 /**
238 * Create a redirect version of the content
239 *
240 * @param Title $target
241 * @param string $text
242 * @return ScribuntoContent
243 */
244 public function makeRedirectContent( Title $target, $text = '' ) {
245 return Scribunto::newDefaultEngine()->makeRedirectContent( $target, $text );
246 }
247
248 /**
249 * @return bool
250 */
251 public function supportsRedirects() {
252 return Scribunto::newDefaultEngine()->supportsRedirects();
253 }
254 }