Debian Codegraph @

extensions/SyntaxHighlight_GeSHi/includes/Pygmentize.php

raw symbols SCIP
1 <?php
2 /**
3 * Copyright (C) 2021 Kunal Mehta <[email protected]>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 */
20
21 namespace MediaWiki\SyntaxHighlight;
22
23 use MediaWiki\MediaWikiServices;
24 use Shellbox\Command\BoxedCommand;
25 use Shellbox\ShellboxError;
26
27 /**
28 * Wrapper around the `pygmentize` command
29 */
30 class Pygmentize {
31
32 /**
33 * If no pygmentize is configured, use bundled
34 */
35 public static function useBundled(): bool {
36 $config = MediaWikiServices::getInstance()->getMainConfig();
37 return $config->get( 'PygmentizePath' ) === false;
38 }
39
40 /**
41 * Get a real path to pygmentize
42 */
43 private static function getPath(): string {
44 $config = MediaWikiServices::getInstance()->getMainConfig();
45 // If $wgPygmentizePath is unset, use the bundled copy.
46 return $config->get( 'PygmentizePath' ) ?: __DIR__ . '/../pygments/pygmentize';
47 }
48
49 /**
50 * Get the version of pygments (cached)
51 */
52 public static function getVersion(): string {
53 static $version;
54 if ( $version !== null ) {
55 return $version;
56 }
57 if ( self::useBundled() ) {
58 $version = self::getBundledVersion();
59 return $version;
60 }
61
62 // This is called a lot, during both page views, edits, and load.php startup request.
63 // It also gets called multiple times during the same request. As such, prefer
64 // low latency via php-apcu.
65 //
66 // This value also controls cache invalidation and propagation through embedding
67 // in other keys from this class, and thus has a low expiry. Avoid latency from
68 // frequent cache misses by by sharing the values with other servers via Memcached
69 // as well.
70
71 $srvCache = MediaWikiServices::getInstance()->getLocalServerObjectCache();
72 return $srvCache->getWithSetCallback(
73 $srvCache->makeGlobalKey( 'pygmentize-version' ),
74 // Spread between 55 min and 1 hour
75 mt_rand( 55 * $srvCache::TTL_MINUTE, 60 * $srvCache::TTL_MINUTE ),
76 static function () {
77 $wanCache = MediaWikiServices::getInstance()->getMainWANObjectCache();
78 return $wanCache->getWithSetCallback(
79 $wanCache->makeGlobalKey( 'pygmentize-version' ),
80 // Must be under 55 min to avoid renewing stale data in upper layer
81 30 * $wanCache::TTL_MINUTE,
82 [ __CLASS__, 'fetchVersion' ]
83 );
84 }
85 );
86 }
87
88 /**
89 * Get the version of bundled pygments
90 */
91 private static function getBundledVersion(): string {
92 return trim( file_get_contents( __DIR__ . '/../pygments/VERSION' ) );
93 }
94
95 /**
96 * Shell out to get installed pygments version
97 *
98 * @internal For use by WANObjectCache/BagOStuff only
99 */
100 public static function fetchVersion(): string {
101 $result = self::boxedCommand()
102 ->params( self::getPath(), '-V' )
103 ->includeStderr()
104 ->execute();
105 self::recordShellout( 'version' );
106
107 $output = $result->getStdout();
108 if ( $result->getExitCode() != 0 ||
109 !preg_match( '/^Pygments version (\S+),/', $output, $matches )
110 ) {
111 throw new PygmentsException( $output );
112 }
113
114 return $matches[1];
115 }
116
117 /**
118 * Get the pygments generated CSS (cached)
119 *
120 * Note: if using bundled, the CSS is already available
121 * in modules/pygments.generated.css.
122 */
123 public static function getGeneratedCSS(): string {
124 // This is rarely called as the result gets HTTP-cached via long-expiry load.php.
125 // When it gets called once, after a deployment, during that brief spike of
126 // dedicated requests from each wiki. Leverage Memcached to share this.
127 // Its likely not needed again on the same server for a while after that.
128 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
129 return $cache->getWithSetCallback(
130 $cache->makeGlobalKey( 'pygmentize-css', self::getVersion() ),
131 $cache::TTL_WEEK,
132 [ __CLASS__, 'fetchGeneratedCSS' ]
133 );
134 }
135
136 /**
137 * Shell out to get generated CSS from pygments
138 *
139 * @internal Only public for updateCSS.php
140 */
141 public static function fetchGeneratedCSS(): string {
142 $lightModeRun = self::boxedCommand()
143 ->params(
144 self::getPath(), '-f', 'html',
145 '-S', 'default', '-a', '.mw-highlight' )
146 ->includeStderr()
147 ->execute();
148 $darkModeRun = self::boxedCommand()
149 ->params(
150 self::getPath(), '-f', 'html',
151 '-S', 'monokai', '-a', ' .skin-theme-clientpref-night .mw-highlight' )
152 ->includeStderr()
153 ->execute();
154 self::recordShellout( 'generated_css' );
155
156 $lightModeOutput = trim( $lightModeRun->getStdout() );
157 if ( $lightModeRun->getExitCode() != 0 ) {
158 throw new PygmentsException( $lightModeOutput );
159 }
160 $darkModeOutput = trim( $darkModeRun->getStdout() );
161 if ( $darkModeRun->getExitCode() != 0 ) {
162 throw new PygmentsException( $darkModeOutput );
163 }
164
165 $lightModeRules = explode( "\n", $lightModeOutput );
166 $darkModeRules = explode( "\n", $darkModeOutput );
167 $commonRules = array_intersect( $lightModeRules, $darkModeRules );
168
169 $nightThemeCss = implode( "\n", array_diff( $darkModeRules, $commonRules ) );
170 $osThemeCss = str_replace( '.skin-theme-clientpref-night',
171 '.skin-theme-clientpref-os', $nightThemeCss );
172
173 return <<<EOD
174 $lightModeOutput
175 @media screen {
176 $nightThemeCss
177 }
178 @media screen and ( prefers-color-scheme: dark ) {
179 $osThemeCss
180 }
181
182 EOD;
183 }
184
185 /**
186 * Get the list of supported lexers by pygments (cached)
187 *
188 * @return array<string,true>
189 */
190 public static function getLexers(): array {
191 if ( self::useBundled() ) {
192 return require __DIR__ . '/../SyntaxHighlight.lexers.php';
193 }
194
195 // This is called during page views and edits, and may be called
196 // repeatedly. Trade low latency for higher shell rate by caching
197 // on each server separately. This is made up for with a high TTL,
198 // which is fine because we vary by version, thus ensuring quick
199 // propagation separate from the TTL.
200 $cache = MediaWikiServices::getInstance()->getLocalServerObjectCache();
201 return $cache->getWithSetCallback(
202 $cache->makeGlobalKey( 'pygmentize-lexers', self::getVersion() ),
203 $cache::TTL_WEEK,
204 [ __CLASS__, 'fetchLexers' ]
205 );
206 }
207
208 /**
209 * Determine if the pygments command line supports the --json option
210 *
211 * @return bool
212 */
213 private static function pygmentsSupportsJsonOutput(): bool {
214 $version = self::getVersion();
215 return ( version_compare( $version, '2.11.0' ) !== -1 );
216 }
217
218 /**
219 * Shell out to get supported lexers by pygments
220 *
221 * @internal Only public for updateLexerList.php
222 * @return array<string,true>
223 */
224 public static function fetchLexers(): array {
225 $cliParams = [ self::getPath(), '-L', 'lexer' ];
226 if ( self::pygmentsSupportsJsonOutput() ) {
227 $cliParams[] = '--json';
228 }
229
230 $result = self::boxedCommand()
231 ->params( $cliParams )
232 ->includeStderr()
233 ->execute();
234 self::recordShellout( 'fetch_lexers' );
235 $output = $result->getStdout();
236 if ( $result->getExitCode() != 0 ) {
237 throw new PygmentsException( $output );
238 }
239
240 if ( self::pygmentsSupportsJsonOutput() ) {
241 $lexers = self::parseLexersFromJson( $output );
242 } else {
243 $lexers = self::parseLexersFromText( $output );
244 }
245
246 sort( $lexers );
247 return array_fill_keys( $lexers, true );
248 }
249
250 /**
251 * Parse json output of the pygments lexers list and return as php array
252 *
253 * @param string $output JSON formatted output of pygments lexers list
254 * @return array
255 */
256 private static function parseLexersFromJson( $output ): array {
257 $data = json_decode( $output, true );
258 if ( $data === null ) {
259 throw new PygmentsException(
260 'Got invalid JSON from Pygments: ' . $output );
261 }
262 $lexers = [];
263 foreach ( array_values( $data['lexers'] ) as $lexer ) {
264 $lexers = array_merge( $lexers, $lexer['aliases'] );
265 }
266 return $lexers;
267 }
268
269 /**
270 * Parse original stdout of the pygments lexers list
271 * This was the only format available before pygments 2.11.0
272 * NOTE: Should be removed when pygments 2.11 is the minimum version expected to be installed
273 *
274 * @param string $output Textual list of pygments lexers
275 * @return array
276 */
277 private static function parseLexersFromText( $output ): array {
278 $lexers = [];
279 foreach ( explode( "\n", $output ) as $line ) {
280 if ( str_starts_with( $line, '*' ) ) {
281 $newLexers = explode( ', ', trim( $line, "* :\r\n" ) );
282
283 // Skip internal, unnamed lexers
284 if ( $newLexers[0] !== '' ) {
285 $lexers = array_merge( $lexers, $newLexers );
286 }
287 }
288 }
289 return $lexers;
290 }
291
292 /**
293 * Actually highlight some text
294 *
295 * @param string $lexer Lexer name
296 * @param string $code Code to highlight
297 * @param array $options Options to pass to pygments
298 * @return string
299 */
300 public static function highlight( $lexer, $code, array $options ): string {
301 $optionPairs = [];
302 foreach ( $options as $k => $v ) {
303 $optionPairs[] = "{$k}={$v}";
304 }
305 self::recordShellout( 'highlight' );
306
307 try {
308 $result = self::boxedCommand()
309 ->params(
310 self::getPath(),
311 '-l', $lexer,
312 '-f', 'html',
313 '-O', implode( ',', $optionPairs ),
314 'file'
315 )
316 ->inputFileFromString( 'file', $code )
317 ->execute();
318 } catch ( ShellboxError $exception ) {
319 // If we have trouble sending or receiving over the network to
320 // Shellbox, we technically don't know if the command succeed or failed,
321 // but, treat the highlight() command as recoverable by wrapping this in
322 // PygmentsException. This permits the Parser tag to fallback to
323 // plainCodeWrap(), thus avoiding a fatal on pageviews (T292663).
324 throw new PygmentsException( 'ShellboxError', 0, $exception );
325 }
326
327 $output = $result->getStdout();
328 if ( $result->getExitCode() != 0 ) {
329 if ( $output === "" || $output === null ) {
330 // Stdout was empty, report stderr instead
331 $output = $result->getStderr();
332 }
333 throw new PygmentsException( (string)$output );
334 }
335
336 return $output;
337 }
338
339 private static function boxedCommand(): BoxedCommand {
340 $command = MediaWikiServices::getInstance()->getShellCommandFactory()
341 ->createBoxed( 'syntaxhighlight' )
342 ->disableNetwork()
343 ->firejailDefaultSeccomp()
344 ->routeName( 'syntaxhighlight-pygments' );
345
346 if ( wfIsWindows() ) {
347 // Python requires the SystemRoot environment variable to initialize (T300223)
348 $command->environment( [
349 'SystemRoot' => getenv( 'SystemRoot' ),
350 ] );
351 }
352
353 return $command;
354 }
355
356 /**
357 * Track how often we do each type of shellout in statsd
358 *
359 * @param string $type Type of shellout
360 */
361 private static function recordShellout( $type ) {
362 MediaWikiServices::getInstance()->getStatsFactory()
363 ->getCounter( 'syntaxhighlight_shell_total' )
364 ->setLabel( 'type', $type )
365 ->copyToStatsdAt( "syntaxhighlight_shell.$type" )
366 ->increment();
367 }
368 }