Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
25.14% covered (danger)
25.14%
135 / 537
9.09% covered (danger)
9.09%
2 / 22
CRAP
0.00% covered (danger)
0.00%
0 / 1
Score
25.14% covered (danger)
25.14%
135 / 537
9.09% covered (danger)
9.09%
2 / 22
8843.22
0.00% covered (danger)
0.00%
0 / 1
 throwCallException
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 getLilypondVersion
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
3
 fetchLilypondVersion
50.00% covered (danger)
50.00%
6 / 12
0.00% covered (danger)
0.00%
0 / 1
4.12
 boxedCommand
33.33% covered (danger)
33.33%
2 / 6
0.00% covered (danger)
0.00%
0 / 1
3.19
 createDirectory
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
 getBaseUrl
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 getBackend
84.21% covered (warning)
84.21%
16 / 19
0.00% covered (danger)
0.00%
0 / 1
4.06
 render
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 renderScore
65.93% covered (warning)
65.93%
60 / 91
0.00% covered (danger)
0.00%
0 / 1
46.77
 generateHTML
22.14% covered (danger)
22.14%
31 / 140
0.00% covered (danger)
0.00%
0 / 1
795.12
 generatePngAndMidi
1.61% covered (danger)
1.61%
2 / 124
0.00% covered (danger)
0.00%
0 / 1
774.67
 addScript
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 throwCompileException
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
30
 throwSynthException
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 extractMessage
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
42
 imageSize
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 getPaperCode
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 embedLilypondCode
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
12
 generateAudio
0.00% covered (danger)
0.00%
0 / 47
0.00% covered (danger)
0.00%
0 / 1
42
 getDurationFromScriptOutput
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 eraseDirectory
28.57% covered (danger)
28.57%
2 / 7
0.00% covered (danger)
0.00%
0 / 1
6.28
 debug
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/*
3    Score, a MediaWiki extension for rendering musical scores with LilyPond.
4    Copyright © 2011 Alexander Klauer
5
6    This program is free software: you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation, either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
19    To contact the author:
20    <Graf.Zahl@gmx.net>
21    http://en.wikisource.org/wiki/User_talk:GrafZahl
22    https://github.com/TheCount/score
23
24 */
25
26namespace MediaWiki\Extension\Score;
27
28use Exception;
29use MediaWiki\Html\Html;
30use MediaWiki\Json\FormatJson;
31use MediaWiki\Logger\LoggerFactory;
32use MediaWiki\MediaWikiServices;
33use MediaWiki\Message\Message;
34use MediaWiki\Output\StreamFile;
35use MediaWiki\Parser\Parser;
36use MediaWiki\Parser\PPFrame;
37use MediaWiki\Status\Status;
38use MediaWiki\Title\Title;
39use MediaWiki\WikiMap\WikiMap;
40use Shellbox\Command\BoxedCommand;
41use Wikimedia\FileBackend\FileBackend;
42use Wikimedia\FileBackend\FSFileBackend;
43use Wikimedia\LockManager\NullLockManager;
44use Wikimedia\ScopedCallback;
45
46/**
47 * Score class.
48 */
49class Score {
50    /**
51     * Version for cache invalidation.
52     */
53    private const int CACHE_VERSION = 1;
54
55    /**
56     * Cache expiry time for the LilyPond version
57     */
58    private const int VERSION_TTL = 3600;
59
60    /**
61     * Supported score languages.
62     */
63    private const array SUPPORTED_LANGS = [ 'lilypond', 'ABC' ];
64
65    /**
66     * Supported note languages.
67     * Key is LilyPond filename. Value is language code
68     */
69    public const array SUPPORTED_NOTE_LANGUAGES = [
70        'arabic' => 'ar',
71        'catalan' => 'ca',
72        'deutsch' => 'de',
73        'english' => 'en',
74        'espanol' => 'es',
75        'italiano' => 'it',
76        'nederlands' => 'nl',
77        'norsk' => 'no',
78        'portugues' => 'pt',
79        'suomi' => 'fi',
80        'svenska' => 'sv',
81        'vlaams' => 'vls',
82    ];
83
84    /**
85     * Default language used for notes.
86     */
87    private const string DEFAULT_NOTE_LANGUAGE = 'nederlands';
88
89    /**
90     * LilyPond version string.
91     * It defaults to null and is set the first time it is required.
92     */
93    private static ?string $lilypondVersion = null;
94
95    private static ?FileBackend $backend = null;
96
97    /**
98     * Throws proper ScoreException in case of failed shell executions.
99     *
100     * @param string $message Message key to display
101     * @param array $params Message parameters
102     * @param string $output collected output from stderr.
103     * @param string|bool $factoryDir The factory directory to replace with "..."
104     *
105     * @throws ScoreException always.
106     */
107    private static function throwCallException( $message, array $params, $output, $factoryDir = false ): never {
108        /* clean up the output a bit */
109        if ( $factoryDir ) {
110            $output = str_replace( $factoryDir, '...', $output );
111        }
112        $params[] = Html::rawElement( 'pre',
113            // Error messages from LilyPond & abc2ly are always English
114            [ 'lang' => 'en', 'dir' => 'ltr' ],
115            htmlspecialchars( $output )
116        );
117        throw new ScoreException( $message, $params );
118    }
119
120    /**
121     * @throws ScoreException if LilyPond could not be executed properly.
122     */
123    public static function getLilypondVersion(): string {
124        global $wgScoreLilyPondFakeVersion;
125
126        if ( strlen( $wgScoreLilyPondFakeVersion ) ) {
127            return $wgScoreLilyPondFakeVersion;
128        }
129        if ( self::$lilypondVersion === null ) {
130            // In case fetchLilypondVersion() throws an exception
131            self::$lilypondVersion = 'disabled';
132
133            $cache = MediaWikiServices::getInstance()->getLocalServerObjectCache();
134            self::$lilypondVersion = $cache->getWithSetCallback(
135                $cache->makeGlobalKey( __CLASS__, 'lilypond-version' ),
136                self::VERSION_TTL,
137                function () {
138                    return self::fetchLilypondVersion();
139                }
140            );
141        }
142
143        return self::$lilypondVersion;
144    }
145
146    /**
147     * Determines the version of LilyPond in use without caching
148     *
149     * @throws ScoreException if LilyPond could not be executed properly.
150     */
151    private static function fetchLilypondVersion(): string {
152        global $wgScoreLilyPond, $wgScoreEnvironment;
153
154        $result = self::boxedCommand()
155            ->routeName( 'score-lilypond' )
156            ->params( $wgScoreLilyPond, '--version' )
157            ->environment( $wgScoreEnvironment )
158            ->includeStderr()
159            ->execute();
160
161        $output = $result->getStdout();
162        if ( $result->getExitCode() != 0 ) {
163            self::throwCallException( 'score-versionerr', [], $output );
164        }
165
166        if ( !preg_match( '/^GNU LilyPond (\S+)/', $output, $m ) ) {
167            self::throwCallException( 'score-versionerr', [], $output );
168        }
169        return $m[1];
170    }
171
172    /**
173     * Return a BoxedCommand object, or throw an exception if shell execution is
174     * disabled.
175     *
176     * The check for $wgScoreDisableExec should be redundant with checks in the
177     * callers, since the callers generally need to avoid writing input files.
178     * We check twice to be safe.
179     *
180     * @throws ScoreDisabledException
181     */
182    private static function boxedCommand(): BoxedCommand {
183        global $wgScoreDisableExec;
184
185        if ( $wgScoreDisableExec ) {
186            throw new ScoreDisabledException();
187        }
188
189        return MediaWikiServices::getInstance()->getShellCommandFactory()
190            ->createBoxed( 'score' )
191            ->disableNetwork()
192            ->firejailDefaultSeccomp();
193    }
194
195    /**
196     * Creates the specified local directory if it does not exist yet.
197     * Otherwise does nothing.
198     *
199     * @param string $path Local path to directory to be created.
200     * @param int|null $mode Chmod value of the new directory.
201     *
202     * @throws ScoreException if the directory does not exist and could not
203     *     be created.
204     */
205    private static function createDirectory( string $path, ?int $mode = null ) {
206        if ( !is_dir( $path ) ) {
207            $rc = wfMkdirParents( $path, $mode, __METHOD__ );
208            if ( !$rc ) {
209                throw new ScoreException( 'score-nooutput', [ $path ] );
210            }
211        }
212    }
213
214    private static function getBaseUrl(): bool|string {
215        global $wgScorePath, $wgUploadPath;
216        if ( $wgScorePath === false ) {
217            return "{$wgUploadPath}/lilypond";
218        }
219
220        return $wgScorePath;
221    }
222
223    public static function getBackend(): FileBackend {
224        global $wgScoreFileBackend;
225
226        if ( $wgScoreFileBackend ) {
227            return MediaWikiServices::getInstance()->getFileBackendGroup()
228                ->get( $wgScoreFileBackend );
229        }
230
231        if ( !self::$backend ) {
232            global $wgScoreDirectory, $wgUploadDirectory;
233            if ( $wgScoreDirectory === false ) {
234                $dir = "{$wgUploadDirectory}/lilypond";
235            } else {
236                $dir = $wgScoreDirectory;
237            }
238            self::$backend = new FSFileBackend( [
239                'name' => 'score-backend',
240                'wikiId' => WikiMap::getCurrentWikiId(),
241                'lockManager' => new NullLockManager( [] ),
242                'containerPaths' => [ 'score-render' => $dir ],
243                'fileMode' => 0777,
244                'obResetFunc' => wfResetOutputBuffers( ... ),
245                'streamMimeFunc' => StreamFile::contentTypeFromPath( ... ),
246                'statusWrapper' => Status::wrap( ... ),
247                'logger' => LoggerFactory::getInstance( 'score' ),
248            ] );
249        }
250
251        return self::$backend;
252    }
253
254    /**
255     * Callback for Parser's hook on 'score' tags. Renders the score code.
256     *
257     * @param string|null $code Score code.
258     * @param array $args Array of score tag attributes.
259     * @param Parser $parser
260     * @param PPFrame $frame Expansion frame, not used by this extension.
261     *
262     * @throws ScoreException
263     * @return string Image link HTML, and possibly anchor to MIDI file.
264     */
265    public static function render( $code, array $args, Parser $parser, PPFrame $frame ) {
266        return self::renderScore( $code, $args, $parser );
267    }
268
269    /**
270     * Renders the score code (LilyPond, ABC, etc.) in a <score>…</score> tag.
271     *
272     * @param string|null $code Score code.
273     * @param array $args Array of score tag attributes.
274     * @param Parser|null $parser Parser must be set when called during a wiki page parse.
275     *
276     * @throws ScoreException
277     * @return string Image link HTML, and possibly anchor to MIDI file.
278     */
279    public static function renderScore( $code, array $args, ?Parser $parser = null ) {
280        global $wgTmpDirectory;
281
282        // T388821
283        if ( $code === null ) {
284            return '';
285        }
286
287        try {
288            $baseUrl = self::getBaseUrl();
289            $baseStoragePath = self::getBackend()->getRootStoragePath() . '/score-render';
290
291            // options to self::generateHTML()
292            $options = [];
293
294            if ( isset( $args['line_width_inches'] ) ) {
295                $lineWidthInches = abs( (float)$args[ 'line_width_inches' ] );
296                if ( $lineWidthInches > 0 ) {
297                    $options['line_width_inches'] = $lineWidthInches;
298                }
299            }
300
301            /* temporary working directory to use */
302            $fuzz = md5( (string)mt_rand() );
303            $options['factory_directory'] = $wgTmpDirectory . "/MWLP.$fuzz";
304
305            /* Score language selection */
306            if ( array_key_exists( 'lang', $args ) ) {
307                $options['lang'] = $args['lang'];
308            } else {
309                $options['lang'] = 'lilypond';
310            }
311            if ( !in_array( $options['lang'], self::SUPPORTED_LANGS, true ) ) {
312                throw new ScoreException( 'score-invalidlang',
313                    [ htmlspecialchars( $options['lang'] ) ] );
314            }
315
316            /* Override MIDI file? */
317            if ( array_key_exists( 'override_midi', $args ) ) {
318                $file = MediaWikiServices::getInstance()->getRepoGroup()
319                    ->findFile( $args['override_midi'] );
320                if ( $file === false ) {
321                    throw new ScoreException( 'score-midioverridenotfound',
322                        [ htmlspecialchars( $args['override_midi'] ) ] );
323                }
324                if ( $parser ) {
325                    $parser->getOutput()->addImage( $file->getName() );
326                }
327
328                $options['override_midi'] = true;
329                $options['midi_file'] = $file;
330                /* Set output stuff in case audio rendering is requested */
331                $sha1 = $file->getSha1();
332                $audioRelDir = "override-midi/{$sha1[0]}/{$sha1[1]}";
333                $audioRel = "$audioRelDir/$sha1.mp3";
334                $options['audio_storage_dir'] = "$baseStoragePath/$audioRelDir";
335                $options['audio_storage_path'] = "$baseStoragePath/$audioRel";
336                $options['audio_url'] = "$baseUrl/$audioRel";
337                $options['audio_sha_name'] = "$sha1.mp3";
338                if ( $parser ) {
339                    $parser->addTrackingCategory( 'score-deprecated-category' );
340                }
341            } else {
342                $options['override_midi'] = false;
343            }
344
345            // Raw rendering?
346            $options['raw'] = array_key_exists( 'raw', $args );
347
348            /* Note language selection */
349            if ( array_key_exists( 'note-language', $args ) ) {
350                if ( !$options['raw'] ) {
351                    $options['note-language'] = $args['note-language'];
352                } else {
353                    throw new ScoreException( 'score-notelanguagewithraw' );
354                }
355            } else {
356                $options['note-language'] = self::DEFAULT_NOTE_LANGUAGE;
357            }
358            if ( !isset( self::SUPPORTED_NOTE_LANGUAGES[$options['note-language']] ) ) {
359                throw new ScoreException(
360                    'score-invalidnotelanguage', [
361                        Message::plaintextParam( $options['note-language'] ),
362                        Message::plaintextParam( implode( ', ', array_keys( self::SUPPORTED_NOTE_LANGUAGES ) ) )
363                    ]
364                );
365            }
366
367            /* Override audio file? */
368            if ( array_key_exists( 'override_audio', $args )
369                || array_key_exists( 'override_ogg', $args ) ) {
370                $overrideAudio = $args['override_ogg'] ?? $args['override_audio'];
371                $t = Title::newFromText( $overrideAudio, NS_FILE );
372                if ( $t === null ) {
373                    throw new ScoreException( 'score-invalidaudiooverride',
374                        [ htmlspecialchars( $overrideAudio ) ] );
375                }
376                if ( !$t->isKnown() ) {
377                    throw new ScoreException( 'score-audiooverridenotfound',
378                        [ htmlspecialchars( $overrideAudio ) ] );
379                }
380                $options['override_audio'] = true;
381                $options['audio_name'] = $overrideAudio;
382                if ( $parser ) {
383                    $parser->addTrackingCategory( 'score-deprecated-category' );
384                }
385            } else {
386                $options['override_audio'] = false;
387            }
388
389            /* Audio rendering? */
390            $options['generate_audio'] = array_key_exists( 'sound', $args )
391                || array_key_exists( 'vorbis', $args );
392
393            if ( $options['generate_audio'] && $options['override_audio'] ) {
394                throw new ScoreException( 'score-convertoverrideaudio' );
395            }
396
397            // Input for cache key
398            $cacheOptions = [
399                'code' => $code,
400                'lang' => $options['lang'],
401                'note-language' => $options['note-language'],
402                'raw' => $options['raw'],
403                'ExtVersion' => self::CACHE_VERSION,
404                'LyVersion' => self::getLilypondVersion(),
405            ];
406
407            /* image file path and URL prefixes */
408            $imageCacheName = \Wikimedia\base_convert( sha1( serialize( $cacheOptions ) ), 16, 36, 31 );
409            $imagePrefixEnd = "{$imageCacheName[0]}/" .
410                "{$imageCacheName[1]}/$imageCacheName";
411            $options['dest_storage_path'] = "$baseStoragePath/$imagePrefixEnd";
412            $options['dest_url'] = "$baseUrl/$imagePrefixEnd";
413            $options['file_name_prefix'] = substr( $imageCacheName, 0, 8 );
414
415            $html = self::generateHTML( $parser, $code, $options );
416        } catch ( ScoreException $e ) {
417            if ( $parser ) {
418                if ( $e->isTracked() ) {
419                    $parser->addTrackingCategory( 'score-error-category' );
420                }
421            }
422            $html = $e->getHtml();
423        }
424
425        // Mark the page as using the score extension, it makes easier
426        // to track all those pages.
427        $parser?->addTrackingCategory( 'score-use-category' );
428
429        return $html;
430    }
431
432    /**
433     * Generates the HTML code for a score tag.
434     *
435     * @param Parser|null $parser MediaWiki parser, provide when inside parse of wiki page
436     * @param string $code Score code.
437     * @param array $options array of rendering options.
438     *     The options keys are:
439     *     - factory_directory: string Path to directory in which files
440     *         may be generated without stepping on someone else's
441     *         toes. The directory may not exist yet. Required.
442     *     - generate_audio: bool Whether to create an audio file in
443     *         TimedMediaHandler. If set to true, the override_audio option
444     *         must be set to false. Required.
445     *  - dest_storage_path: The path of the destination directory relative to
446     *      the current backend. Required.
447     *  - dest_url: The default destination URL. Required.
448     *  - file_name_prefix: The filename prefix used for all files
449     *      in the default destination directory. Required.
450     *     - lang: string Score language. Required.
451     *     - override_midi: bool Whether to use a user-provided MIDI file.
452     *         Required.
453     *     - midi_file: If override_midi is true, MIDI file object.
454     *     - audio_storage_dir: If override_midi and generate_audio are true, the
455     *         backend directory in which the audio file is to be stored.
456     *     - audio_storage_path: string If override_midi and generate_audio are true,
457     *         the backend path at which the generated audio file is to be
458     *         stored.
459     *     - audio_url: string If override_midi and generate_audio is true,
460     *         the URL corresponding to audio_storage_path
461     *  - audio_sha_name: string If override_midi, generated audio file name.
462     *     - override_audio: bool Whether to generate a wikilink to a
463     *         user-provided audio file. If set to true, the sound
464     *         option must be set to false. Required.
465     *     - audio_name: string If override_audio is true, the audio file name
466     *     - raw: bool Whether to assume raw LilyPond code. Ignored if the
467     *         language is not lilypond, required otherwise.
468     *    - note-language: language to use for notes (one of supported by LilyPond)
469     *
470     * @return string HTML.
471     *
472     * @throws Exception
473     * @throws ScoreException if an error occurs.
474     */
475    private static function generateHTML( ?Parser $parser, $code, $options ) {
476        global $wgScoreOfferSourceDownload, $wgScoreUseSvg;
477
478        $cleanup = new ScopedCallback( function () use ( $options ) {
479            self::eraseDirectory( $options['factory_directory'] );
480        } );
481        if ( $parser ) {
482            $parser->getOutput()->addModuleStyles( [ 'ext.score.styles' ] );
483            $parser->getOutput()->addModules( [ 'ext.score.popup' ] );
484        }
485
486        $backend = self::getBackend();
487        $fileIter = $backend->getFileList(
488            [ 'dir' => $options['dest_storage_path'], 'topOnly' => true ] );
489        if ( $fileIter === null ) {
490            throw new ScoreException( 'score-file-list-error' );
491        }
492        $existingFiles = [];
493        foreach ( $fileIter as $file ) {
494            $existingFiles[$file] = true;
495        }
496
497        /* Generate SVG, PNG and MIDI files if necessary */
498        $imageFileName = "{$options['file_name_prefix']}.png";
499        $imageSvgFileName = "{$options['file_name_prefix']}.svg";
500        $multi1FileName = "{$options['file_name_prefix']}-page1.png";
501        $multi1SvgFileName = "{$options['file_name_prefix']}-1.svg";
502        $midiFileName = "{$options['file_name_prefix']}.midi";
503        $metaDataFileName = "{$options['file_name_prefix']}.json";
504        $audioUrl = '';
505
506        if ( isset( $existingFiles[$metaDataFileName] ) ) {
507            $metaDataFile = $backend->getFileContents(
508                [ 'src' => "{$options['dest_storage_path']}/$metaDataFileName" ] );
509            if ( $metaDataFile === false ) {
510                throw new ScoreException( 'score-nocontent', [ $metaDataFileName ] );
511            }
512            $metaData = FormatJson::decode( $metaDataFile, true );
513        } else {
514            $metaData = [];
515        }
516
517        if (
518            !isset( $existingFiles[$metaDataFileName] )
519            || (
520                !isset( $existingFiles[$imageFileName] )
521                && !isset( $existingFiles[$multi1FileName] )
522            )
523            || (
524                $wgScoreUseSvg
525                && !isset( $existingFiles[$multi1SvgFileName] )
526                && !isset( $existingFiles[$imageSvgFileName] )
527            )
528            || (
529                !isset( $metaData[$imageFileName]['size'] )
530                && !isset( $metaData[$multi1FileName]['size'] )
531            )
532            || !isset( $existingFiles[$midiFileName] ) ) {
533            $existingFiles += self::generatePngAndMidi( $code, $options, $metaData );
534        }
535
536        /* Generate audio file if necessary */
537        if ( $options['generate_audio'] ) {
538            $audioFileName = "{$options['file_name_prefix']}.mp3";
539            if ( $options['override_midi'] ) {
540                $audioUrl = $options['audio_url'];
541                $audioPath = $options['audio_storage_path'];
542                $exists = $backend->fileExists( [ 'src' => $options['audio_storage_path'] ] );
543                if (
544                    !$exists ||
545                    !isset( $metaData[ $options['audio_sha_name'] ]['length'] ) ||
546                    !$metaData[ $options['audio_sha_name'] ]['length']
547                ) {
548                    $backend->prepare( [ 'dir' => $options['audio_storage_dir'] ] );
549                    $sourcePath = $options['midi_file']->getLocalRefPath();
550                    self::generateAudio( $sourcePath, $options, $audioPath, $metaData );
551                }
552            } else {
553                $audioUrl = "{$options['dest_url']}/$audioFileName";
554                $audioPath = "{$options['dest_storage_path']}/$audioFileName";
555                if (
556                    !isset( $existingFiles[$audioFileName] ) ||
557                    !isset( $metaData[$audioFileName]['length'] ) ||
558                    !$metaData[$audioFileName]['length']
559                ) {
560                    // Maybe we just generated it
561                    $sourcePath = "{$options['factory_directory']}/file.midi";
562                    if ( !file_exists( $sourcePath ) ) {
563                        // No, need to fetch it from the backend
564                        $sourceFileRef = $backend->getLocalReference(
565                            [ 'src' => "{$options['dest_storage_path']}/$midiFileName" ] );
566                        if ( !$sourceFileRef ) {
567                            throw new ScoreException( 'score-audioconversionerr', [ $sourcePath ] );
568                        }
569                        $sourcePath = $sourceFileRef->getPath();
570                    }
571                    self::generateAudio( $sourcePath, $options, $audioPath, $metaData );
572                }
573            }
574        }
575
576        /* return output link(s) */
577        if ( isset( $existingFiles[$imageFileName] ) ) {
578            [ $width, $height ] = $metaData[$imageFileName]['size'];
579            $attribs = [
580                'src' => "{$options['dest_url']}/$imageFileName",
581                'width' => $width,
582                'height' => $height,
583                'alt' => $code,
584            ];
585            if ( $wgScoreUseSvg ) {
586                $attribs['src'] = "{$options['dest_url']}/$imageSvgFileName";
587            }
588            $link = Html::rawElement( 'img', $attribs );
589        } elseif ( isset( $existingFiles[$multi1FileName] ) ) {
590            $link = '';
591            for ( $i = 1; ; ++$i ) {
592                $fileName = "{$options['file_name_prefix']}-page$i.png";
593                if ( !isset( $existingFiles[$fileName] ) ) {
594                    break;
595                }
596                $pageNumb = wfMessage( 'score-page' )
597                    ->inContentLanguage()
598                    ->numParams( $i )
599                    ->plain();
600                [ $width, $height ] = $metaData[$fileName]['size'];
601                $attribs = [
602                    'src' => "{$options['dest_url']}/$fileName",
603                    'width' => $width,
604                    'height' => $height,
605                    'alt' => $pageNumb,
606                    'title' => $pageNumb,
607                    'style' => "margin-bottom:1em"
608                ];
609                if ( $wgScoreUseSvg ) {
610                    $svgFileName = "{$options['file_name_prefix']}-$i.svg";
611                    $attribs['src'] = "{$options['dest_url']}/$svgFileName";
612                }
613                $link .= Html::rawElement( 'img', $attribs );
614            }
615        } else {
616            $link = '';
617        }
618        if ( $options['generate_audio'] ) {
619            $link .= '<div style="margin-top: 3px;">' .
620                Html::rawElement(
621                    'audio',
622                    [
623                        'controls' => true
624                    ],
625                    Html::openElement(
626                        'source',
627                        [
628                            'src' => $audioUrl,
629                            'type' => 'audio/mpeg',
630                        ]
631                    ) .
632                    "<div>" .
633                    wfMessage( 'score-audio-fallback' )
634                        ->params(
635                            (string)MediaWikiServices::getInstance()->getUrlUtils()
636                                ->expand( $audioUrl, PROTO_CURRENT )
637                        )
638                        ->parse() .
639                    '</div>'
640                ) .
641                '</div>';
642        }
643        if ( $parser && $options['override_audio'] !== false ) {
644            $link .= $parser->recursiveTagParse( "[[File:{$options['audio_name']}]]" );
645        }
646
647        // Clean up the factory directory now
648        ScopedCallback::consume( $cleanup );
649
650        $attributes = [
651            'class' => 'mw-ext-score noresize'
652        ];
653
654        // support SVG dark mode output, T431148
655        if ( $wgScoreUseSvg ) {
656            $attributes['class'] .= ' mw-ext-score-svg skin-invert';
657        } else {
658            $attributes['class'] .= ' mw-ext-score-png';
659        }
660
661        if ( $options['override_midi']
662            || isset( $existingFiles["{$options['file_name_prefix']}.midi"] ) ) {
663            $attributes['data-mw-midi'] = $options['override_midi'] ?
664                $options['midi_file']->getUrl()
665                : "{$options['dest_url']}/{$options['file_name_prefix']}.midi";
666        }
667
668        if ( $wgScoreOfferSourceDownload
669            && isset( $existingFiles["{$options['file_name_prefix']}.ly"] )
670        ) {
671            $attributes['data-mw-source'] = "{$options['dest_url']}/{$options['file_name_prefix']}.ly";
672        }
673
674        // Wrap score in div container.
675        return Html::rawElement( 'div', $attributes, $link );
676    }
677
678    /**
679     * Generates score PNG file(s) and a MIDI file. Stores lilypond file.
680     *
681     * @param string $code Score code.
682     * @param array $options Rendering options. They are the same as for
683     *     Score::generateHTML().
684     * @param array &$metaData array to hold information about images
685     *
686     * @return array of file names placed in the remote dest dir, with the
687     *     file names in each key.
688     *
689     * @throws ScoreException on error.
690     */
691    private static function generatePngAndMidi( $code, $options, &$metaData ) {
692        global $wgScoreLilyPond, $wgScoreTrim, $wgScoreDisableExec,
693            $wgScoreGhostscript, $wgScoreAbc2Ly, $wgImageMagickConvertCommand, $wgScoreUseSvg,
694            $wgShellboxShell, $wgPhpCli, $wgScoreEnvironment, $wgScoreImageMagickConvert;
695
696        if ( $wgScoreDisableExec ) {
697            throw new ScoreDisabledException();
698        }
699
700        /* Create the working environment */
701        $factoryDirectory = $options['factory_directory'];
702        self::createDirectory( $factoryDirectory, 0700 );
703        $factoryMidi = "$factoryDirectory/file.midi";
704
705        $command = self::boxedCommand()
706            ->routeName( 'score-lilypond' )
707            ->params(
708                $wgShellboxShell,
709                'scripts/generatePngAndMidi.sh' )
710            ->outputFileToFile( 'file.midi', $factoryMidi )
711            ->outputGlobToFile( 'file', 'png', $factoryDirectory )
712            ->outputGlobToFile( 'file', 'svg', $factoryDirectory )
713            ->includeStderr()
714            ->environment( [
715                'SCORE_ABC2LY' => $wgScoreAbc2Ly,
716                'SCORE_LILYPOND' => $wgScoreLilyPond,
717                'SCORE_USESVG' => $wgScoreUseSvg ? 'yes' : 'no',
718                'SCORE_GHOSTSCRIPT' => $wgScoreGhostscript,
719                'SCORE_CONVERT' => $wgScoreImageMagickConvert ?: $wgImageMagickConvertCommand,
720                'SCORE_TRIM' => $wgScoreTrim ? 'yes' : 'no',
721                'SCORE_PHP' => $wgPhpCli
722            ] + $wgScoreEnvironment );
723        self::addScript( $command, 'generatePngAndMidi.sh' );
724        if ( !$wgScoreUseSvg ) {
725            self::addScript( $command, 'extractPostScriptPageSize.php' );
726        }
727        if ( $options['lang'] === 'lilypond' ) {
728            if ( $options['raw'] ) {
729                $lilypondCode = $code;
730            } else {
731                $paperConfig = [];
732                if ( isset( $options['line_width_inches'] ) ) {
733                    $paperConfig['line-width'] = $options['line_width_inches'] . "\in";
734                }
735                $paperCode = self::getPaperCode( $paperConfig );
736
737                $lilypondCode = self::embedLilypondCode( $code, $options['note-language'], $paperCode );
738            }
739            $command->inputFileFromString( 'file.ly', $lilypondCode );
740        } else {
741            self::addScript( $command, 'removeTagline.php' );
742            $command->inputFileFromString( 'file.abc', $code );
743            $command->outputFileToString( 'file.ly' );
744            $lilypondCode = '';
745        }
746        $result = $command->execute();
747
748        if ( $result->getExitCode() != 0 ) {
749            self::throwCompileException( $result->getStdout(), $options );
750        }
751
752        if ( $result->wasReceived( 'file.ly' ) ) {
753            $lilypondCode = $result->getFileContents( 'file.ly' );
754        }
755
756        $numPages = 0;
757        for ( $i = 1; ; $i++ ) {
758            if ( !$result->wasReceived( "file-page$i.png" ) ) {
759                $numPages = $i - 1;
760                break;
761            }
762        }
763
764        # LilyPond 2.24+ generates file.png and file.svg if there is only one page
765        if ( $wgScoreUseSvg && $result->wasReceived( 'file.svg' ) ) {
766            $numPages = 1;
767        }
768
769        if ( $numPages === 0 ) {
770            throw new ScoreException( 'score-noimages' );
771        }
772
773        $needMidi = false;
774        $haveMidi = $result->wasReceived( 'file.midi' );
775        if ( !$options['raw'] || ( $options['generate_audio'] && !$options['override_midi'] ) ) {
776            $needMidi = true;
777            if ( !$haveMidi ) {
778                throw new ScoreException( 'score-nomidi' );
779            }
780        }
781
782        // Create the destination directory if it doesn't exist
783        $backend = self::getBackend();
784        $status = $backend->prepare( [ 'dir' => $options['dest_storage_path'] ] );
785        if ( !$status->isOK() ) {
786            throw new ScoreBackendException( $status );
787        }
788
789        // File names of generated files
790        $newFiles = [];
791        // Backend operation batch
792        $ops = [];
793
794        // Add LY source to its file
795        $ops[] = [
796            'op' => 'create',
797            'content' => $lilypondCode,
798            'dst' => "{$options['dest_storage_path']}/{$options['file_name_prefix']}.ly",
799            'headers' => [
800                'Content-Type' => 'text/x-lilypond; charset=utf-8'
801            ]
802        ];
803        $newFiles["{$options['file_name_prefix']}.ly"] = true;
804
805        if ( $needMidi ) {
806            // Add the MIDI file to the batch
807            $ops[] = [
808                'op' => 'store',
809                'src' => $factoryMidi,
810                'dst' => "{$options['dest_storage_path']}/{$options['file_name_prefix']}.midi" ];
811            $newFiles["{$options['file_name_prefix']}.midi"] = true;
812            if ( !$status->isOK() ) {
813                throw new ScoreBackendException( $status );
814            }
815        }
816
817        // Add the PNG and SVG image files
818        for ( $i = 1; $i <= $numPages; ++$i ) {
819            $srcPng = "$factoryDirectory/file-page$i.png";
820            $srcSvg = "$factoryDirectory/file-$i.svg";
821            $dstPngFileName = "{$options['file_name_prefix']}-page$i.png";
822            $dstSvgFileName = "{$options['file_name_prefix']}-$i.svg";
823            if ( $numPages === 1 ) {
824                $dstPngFileName = "{$options['file_name_prefix']}.png";
825                if ( $wgScoreUseSvg ) {
826                    $srcPng = "$factoryDirectory/file.png";
827                    $srcSvg = "$factoryDirectory/file.svg";
828                    $dstSvgFileName = "{$options['file_name_prefix']}.svg";
829                }
830            }
831            $destPng = "{$options['dest_storage_path']}/$dstPngFileName";
832            $ops[] = [
833                'op' => 'store',
834                'src' => $srcPng,
835                'dst' => $destPng
836            ];
837            [ $width, $height ] = self::imageSize( $srcPng );
838            $metaData[$dstPngFileName]['size'] = [ $width, $height ];
839            $newFiles[$dstPngFileName] = true;
840
841            if ( $wgScoreUseSvg ) {
842                $destSvg = "{$options['dest_storage_path']}/$dstSvgFileName";
843                $ops[] = [
844                    'op' => 'store',
845                    'src' => $srcSvg,
846                    'dst' => $destSvg,
847                    'headers' => [
848                        'Content-Type' => 'image/svg+xml'
849                    ]
850                ];
851                $newFiles[$dstSvgFileName] = true;
852            }
853        }
854
855        $dstFileName = "{$options['file_name_prefix']}.json";
856        $dest = "{$options['dest_storage_path']}/$dstFileName";
857        $ops[] = [
858            'op' => 'create',
859            'content' => FormatJson::encode( $metaData ),
860            'dst' => $dest ];
861
862        $newFiles[$dstFileName] = true;
863
864        // Execute the batch
865        $status = $backend->doQuickOperations( $ops );
866        if ( !$status->isOK() ) {
867            throw new ScoreBackendException( $status );
868        }
869        return $newFiles;
870    }
871
872    /**
873     * Add an input file from the scripts directory
874     */
875    private static function addScript( BoxedCommand $command, string $script ): void {
876        $command->inputFileFromFile( "scripts/$script",
877            __DIR__ . "/../scripts/$script" );
878    }
879
880    /**
881     * Get error information from the output returned by scripts/generatePngAndMidi.sh
882     * and throw a relevant error.
883     *
884     * @throws ScoreException
885     */
886    private static function throwCompileException( string $stdout, array $options ): never {
887        global $wgScoreDebugOutput;
888
889        $message = self::extractMessage( $stdout );
890        if ( !$message ) {
891            $message = [ 'score-compilererr', [] ];
892        } elseif ( !$wgScoreDebugOutput && $message[0] === 'score-compilererr' ) {
893            // when input is not raw, we build the final lilypond file content
894            // in self::embedLilypondCode. The user input then is not inserted
895            // on the first line in the file we pass to lilypond and so we need
896            // to offset error messages back.
897            $scoreFirstLineOffset = $options['raw'] ? 0 : 7;
898            $errMsgBeautifier = new LilypondErrorMessageBeautifier( $scoreFirstLineOffset );
899
900            $stdout = $errMsgBeautifier->beautifyMessage( $stdout );
901        }
902        self::throwCallException(
903            $message[0],
904            $message[1],
905            $stdout
906        );
907    }
908
909    /**
910     * Get error information from the output returned by scripts/synth.sh
911     * and throw a relevant error.
912     *
913     * @throws ScoreException
914     */
915    private static function throwSynthException( string $stdout ): never {
916        $message = self::extractMessage( $stdout );
917        if ( !$message ) {
918            $message = [ 'score-audioconversionerr', [] ];
919        }
920        self::throwCallException(
921            $message[0],
922            $message[1],
923            $stdout
924        );
925    }
926
927    /**
928     * Parse the script return value and extract any mw-msg lines. Modify the
929     * text to remove the lines. Return the first mw-msg line as a message
930     * key and parameters. If there was no mw-msg line, return null.
931     *
932     * @param string &$stdout
933     * @return array|null
934     */
935    private static function extractMessage( string &$stdout ) {
936        $filteredStdout = '';
937        $messageParams = [];
938        foreach ( explode( "\n", $stdout ) as $line ) {
939            if ( preg_match( '/^mw-msg:\t/', $line ) ) {
940                if ( !$messageParams ) {
941                    $messageParams = array_slice( explode( "\t", $line ), 1 );
942                }
943            } else {
944                if ( $filteredStdout !== '' ) {
945                    $filteredStdout .= "\n";
946                }
947                $filteredStdout .= $line;
948            }
949        }
950        $stdout = $filteredStdout;
951        if ( $messageParams ) {
952            $messageName = array_shift( $messageParams );
953            // Used messages:
954            // - score-abc2lynotexecutable
955            // - score-abcconversionerr
956            // - score-notexecutable
957            // - score-compilererr
958            // - score-nops
959            // - score-scripterr
960            // - score-gs-error
961            // - score-trimerr
962            // - score-readerr
963            // - score-pregreplaceerr
964            // - score-audioconversionerr
965            // - score-soundfontnotexists
966            // - score-fallbacknotexecutable
967            // - score-lamenotexecutable
968            return [ $messageName, $messageParams ];
969        } else {
970            return null;
971        }
972    }
973
974    /**
975     * Extract the size of one of our generated PNG images
976     *
977     * @param string $filename
978     * @return array of ints (width, height)
979     */
980    private static function imageSize( string $filename ): array {
981        [ $width, $height ] = getimagesize( $filename );
982        return [ $width, $height ];
983    }
984
985    private static function getPaperCode( array $paperConfig = [] ): string {
986        $config = array_merge( [
987            "indent" => "0\\mm",
988        ], $paperConfig );
989
990        $paperCode = "\\paper {\n";
991        foreach ( $config as $key => $value ) {
992            $paperCode .= "\t$key = $value\n";
993        }
994        $paperCode .= "}";
995
996        return $paperCode;
997    }
998
999    /**
1000     * Embeds simple LilyPond code in a score block.
1001     *
1002     * @param string $lilypondCode Simple LilyPond code.
1003     * @param string $noteLanguage Language of notes.
1004     * @param string $paperCode
1005     *
1006     * @return string Raw lilypond code.
1007     *
1008     * @throws ScoreException if determining the LilyPond version fails.
1009     */
1010    private static function embedLilypondCode( string $lilypondCode, string $noteLanguage, string $paperCode ): string {
1011        $version = self::getLilypondVersion();
1012
1013        // Check if parameters have already been supplied (hybrid-raw mode)
1014        $options = "";
1015        if ( !str_contains( $lilypondCode, "\\layout" ) ) {
1016            $options .= "\\layout { }\n";
1017        }
1018        if ( !str_contains( $lilypondCode, "\\midi" ) ) {
1019            $options .= <<<LY
1020    \\midi {
1021        \\context { \Score tempoWholesPerMinute = #(ly:make-moment 100 4) }
1022    }
1023LY;
1024        }
1025
1026        /* Raw code. In Scheme, ##f is false and ##t is true. */
1027        /* Set the default MIDI tempo to 100, 60 is a bit too slow */
1028        return <<<LILYPOND
1029\\header {
1030    tagline = ##f
1031}
1032\\version "$version"
1033\\language "$noteLanguage"
1034\\score {
1035
1036$lilypondCode
1037$options
1038
1039}
1040$paperCode
1041LILYPOND;
1042    }
1043
1044    /**
1045     * Generates an audio file from a MIDI file using fluidsynth with TiMidity as fallback.
1046     *
1047     * @param string $sourceFile The local filename of the MIDI file
1048     * @param array $options array of rendering options.
1049     * @param string $remoteDest The backend storage path to upload the audio file to
1050     * @param array &$metaData Array with metadata information
1051     *
1052     * @throws ScoreException if an error occurs.
1053     */
1054    private static function generateAudio(
1055        string $sourceFile, array $options, string $remoteDest, array &$metaData
1056    ): void {
1057        global $wgScoreFluidsynth, $wgScoreSoundfont, $wgScoreLame, $wgScoreDisableExec,
1058            $wgScoreEnvironment, $wgShellboxShell, $wgPhpCli;
1059
1060        if ( $wgScoreDisableExec ) {
1061            throw new ScoreDisabledException();
1062        }
1063
1064        // Working environment
1065        $factoryDir = $options['factory_directory'];
1066        self::createDirectory( $factoryDir, 0700 );
1067        $factoryFile = "$factoryDir/file.mp3";
1068
1069        // Run FluidSynth and LAME
1070        $command = self::boxedCommand()
1071            ->routeName( 'score-fluidsynth' )
1072            ->params(
1073                $wgShellboxShell,
1074                'scripts/synth.sh'
1075            )
1076            ->environment( [
1077                'SCORE_FLUIDSYNTH' => $wgScoreFluidsynth,
1078                'SCORE_SOUNDFONT' => $wgScoreSoundfont,
1079                'SCORE_LAME' => $wgScoreLame,
1080                'SCORE_PHP' => $wgPhpCli
1081            ] + $wgScoreEnvironment )
1082            ->inputFileFromFile( 'file.midi', $sourceFile )
1083            ->outputFileToFile( 'file.mp3', $factoryFile )
1084            ->includeStderr()
1085            // 150 MB max. filesize (for large MIDIs)
1086            ->fileSizeLimit( 150 * 1024 * 1024 );
1087
1088        self::addScript( $command, 'synth.sh' );
1089        self::addScript( $command, 'getWavDuration.php' );
1090
1091        $result = $command->execute();
1092
1093        if ( ( $result->getExitCode() != 0 ) || !$result->wasReceived( 'file.mp3' ) ) {
1094            self::throwSynthException( $result->getStdout() );
1095        }
1096
1097        // Move file to the final destination
1098        $backend = self::getBackend();
1099        $status = $backend->doQuickOperation( [
1100            'op' => 'store',
1101            'src' => $factoryFile,
1102            'dst' => $remoteDest
1103        ] );
1104
1105        if ( !$status->isOK() ) {
1106            throw new ScoreBackendException( $status );
1107        }
1108
1109        // Create metadata json
1110        $metaData[basename( $remoteDest )]['length'] = self::getDurationFromScriptOutput(
1111            $result->getStdout() );
1112        $dstFileName = "{$options['file_name_prefix']}.json";
1113        $dest = "{$options['dest_storage_path']}/$dstFileName";
1114
1115        // Store metadata in backend
1116        $backend = self::getBackend();
1117        $status = $backend->doQuickOperation( [
1118            'op' => 'create',
1119            'content' => FormatJson::encode( $metaData ),
1120            'dst' => $dest
1121        ] );
1122
1123        if ( !$status->isOK() ) {
1124            throw new ScoreBackendException( $status );
1125        }
1126    }
1127
1128    /**
1129     * Get the duration of the audio file from the script stdout
1130     *
1131     * @param string $stdout The script output
1132     * @return float duration in seconds
1133     */
1134    private static function getDurationFromScriptOutput( string $stdout ): float {
1135        if ( preg_match( '/^wavDuration: ([0-9.]+)$/m', $stdout, $m ) ) {
1136            return (float)$m[1];
1137        } else {
1138            return 0.0;
1139        }
1140    }
1141
1142    /**
1143     * Deletes a local directory with no subdirectories with all files in it.
1144     *
1145     * @param string $dir Local path to the directory that is to be deleted.
1146     *
1147     * @return bool true on success, false on error
1148     */
1149    private static function eraseDirectory( string $dir ): bool {
1150        if ( file_exists( $dir ) ) {
1151            // @phan-suppress-next-line PhanPluginUseReturnValueInternalKnown
1152            array_map( 'unlink', glob( "$dir/*", GLOB_NOSORT ) );
1153            $rc = rmdir( $dir );
1154            if ( !$rc ) {
1155                self::debug( "Unable to remove directory $dir\n." );
1156            }
1157            return $rc;
1158        }
1159
1160        /* Nothing to do */
1161        return true;
1162    }
1163
1164    /**
1165     * Writes the specified message to the Score debug log.
1166     *
1167     * @param string $msg message to log.
1168     */
1169    private static function debug( string $msg ): void {
1170        wfDebugLog( 'Score', $msg );
1171    }
1172
1173}