Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
95.83% covered (success)
95.83%
184 / 192
92.86% covered (success)
92.86%
13 / 14
CRAP
0.00% covered (danger)
0.00%
0 / 1
ClientHtml
95.83% covered (success)
95.83%
184 / 192
92.86% covered (success)
92.86%
13 / 14
65
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 setConfig
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 setModules
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 setModuleStyles
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 setExemptStates
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getData
100.00% covered (success)
100.00%
51 / 51
100.00% covered (success)
100.00%
1 / 1
18
 getDocumentAttributes
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getDocumentClassNameScript
42.86% covered (danger)
42.86%
6 / 14
0.00% covered (danger)
0.00%
0 / 1
2.75
 getHeadHtml
100.00% covered (success)
100.00%
47 / 47
100.00% covered (success)
100.00%
1 / 1
10
 getBodyHtml
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
3
 getContext
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getLoad
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 makeContext
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
5
 makeLoad
100.00% covered (success)
100.00%
49 / 49
100.00% covered (success)
100.00%
1 / 1
18
1<?php
2/**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21namespace MediaWiki\ResourceLoader;
22
23use MediaWiki\Html\Html;
24use Wikimedia\WrappedString;
25use Wikimedia\WrappedStringList;
26
27/**
28 * Load and configure a ResourceLoader client on an HTML page.
29 *
30 * @ingroup ResourceLoader
31 * @since 1.28
32 */
33class ClientHtml {
34    /** @var Context */
35    private $context;
36
37    /** @var ResourceLoader */
38    private $resourceLoader;
39
40    /** @var array<string,string|null|false> */
41    private $options;
42
43    /** @var array<string,mixed> */
44    private $config = [];
45
46    /** @var string[] */
47    private $modules = [];
48
49    /** @var string[] */
50    private $moduleStyles = [];
51
52    /** @var array<string,string> */
53    private $exemptStates = [];
54
55    /** @var array */
56    private $data;
57
58    /**
59     * @param Context $context
60     * @param array $options [optional] Array of options
61     *  - 'target': Parameter for modules=startup request, see StartUpModule.
62     *  - 'safemode': Parameter for modules=startup request, see StartUpModule.
63     *  - 'clientPrefEnabled': See Skin options.
64     *  - 'clientPrefCookiePrefix': See $wgCookiePrefix.
65     */
66    public function __construct( Context $context, array $options = [] ) {
67        $this->context = $context;
68        $this->resourceLoader = $context->getResourceLoader();
69        $this->options = $options + [
70            'target' => null,
71            'safemode' => null,
72            'clientPrefEnabled' => false,
73            'clientPrefCookiePrefix' => '',
74        ];
75    }
76
77    /**
78     * Set mw.config variables.
79     *
80     * @param array $vars Array of key/value pairs
81     */
82    public function setConfig( array $vars ): void {
83        foreach ( $vars as $key => $value ) {
84            $this->config[$key] = $value;
85        }
86    }
87
88    /**
89     * Ensure one or more modules are loaded.
90     *
91     * @param string[] $modules Array of module names
92     */
93    public function setModules( array $modules ): void {
94        $this->modules = $modules;
95    }
96
97    /**
98     * Ensure the styles of one or more modules are loaded.
99     *
100     * @param string[] $modules Array of module names
101     */
102    public function setModuleStyles( array $modules ): void {
103        $this->moduleStyles = $modules;
104    }
105
106    /**
107     * Set state of special modules that are handled by the caller manually.
108     *
109     * See OutputPage::buildExemptModules() for use cases.
110     *
111     * @param array<string,string> $states Module state keyed by module name
112     */
113    public function setExemptStates( array $states ): void {
114        $this->exemptStates = $states;
115    }
116
117    private function getData(): array {
118        if ( $this->data ) {
119            // @codeCoverageIgnoreStart
120            return $this->data;
121            // @codeCoverageIgnoreEnd
122        }
123
124        $rl = $this->resourceLoader;
125        $data = [
126            'states' => [
127                // moduleName => state
128            ],
129            'general' => [],
130            'styles' => [],
131            // Embedding for private modules
132            'embed' => [
133                'styles' => [],
134                'general' => [],
135            ],
136            // Deprecation warnings for style-only modules
137            'styleDeprecations' => [],
138        ];
139
140        foreach ( $this->modules as $name ) {
141            $module = $rl->getModule( $name );
142            if ( !$module ) {
143                continue;
144            }
145
146            $group = $module->getGroup();
147            $context = $this->getContext( $group, Module::TYPE_COMBINED );
148            $shouldEmbed = $module->shouldEmbedModule( $this->context );
149
150            if ( ( $group === Module::GROUP_USER || $shouldEmbed ) &&
151                $module->isKnownEmpty( $context ) ) {
152                // This is a user-specific or embedded module, which means its output
153                // can be specific to the current page or user. As such, we can optimise
154                // the way we load it based on the current version of the module.
155                // Avoid needless embed for empty module, preset ready state.
156                $data['states'][$name] = 'ready';
157            } elseif ( $group === Module::GROUP_USER || $shouldEmbed ) {
158                // - For group=user: We need to provide a pre-generated load.php
159                //   url to the client that has the 'user' and 'version' parameters
160                //   filled in. Without this, the client would wrongly use the static
161                //   version hash, per T64602.
162                // - For shouldEmbed=true:  Embed via mw.loader.impl, per T36907.
163                $data['embed']['general'][] = $name;
164                // Avoid duplicate request from mw.loader
165                $data['states'][$name] = 'loading';
166            } else {
167                // Load via mw.loader.load()
168                $data['general'][] = $name;
169            }
170        }
171
172        foreach ( $this->moduleStyles as $name ) {
173            $module = $rl->getModule( $name );
174            if ( !$module ) {
175                continue;
176            }
177
178            if ( $module->getType() !== Module::LOAD_STYLES ) {
179                $logger = $rl->getLogger();
180                $logger->error( 'Unexpected general module "{module}" in styles queue.', [
181                    'module' => $name,
182                ] );
183                continue;
184            }
185
186            // Stylesheet doesn't trigger mw.loader callback.
187            // Set "ready" state to allow script modules to depend on this module  (T87871).
188            // And to avoid duplicate requests at run-time from mw.loader.
189            //
190            // Optimization: Exclude state for "noscript" modules. Since these are also excluded
191            // from the startup registry, no need to send their states (T291735).
192            $group = $module->getGroup();
193            if ( $group !== Module::GROUP_NOSCRIPT ) {
194                $data['states'][$name] = 'ready';
195            }
196
197            $context = $this->getContext( $group, Module::TYPE_STYLES );
198            if ( $module->shouldEmbedModule( $this->context ) ) {
199                // Avoid needless embed for private embeds we know are empty.
200                // (Set "ready" state directly instead, which we do a few lines above.)
201                if ( !$module->isKnownEmpty( $context ) ) {
202                    // Embed via <style> element
203                    $data['embed']['styles'][] = $name;
204                }
205            // For other style modules, always request them, regardless of whether they are
206            // currently known to be empty. Because:
207            // 1. Those modules are requested in batch, so there is no extra request overhead
208            //    or extra HTML element to be avoided.
209            // 2. Checking isKnownEmpty for those can be expensive and slow down page view
210            //    generation (T230260).
211            // 3. We don't want cached HTML to vary on the current state of a module.
212            //    If the module becomes non-empty a few minutes later, it should start working
213            //    on cached HTML without requiring a purge.
214            //
215            // But, user-specific modules:
216            // * ... are used on page views not publicly cached.
217            // * ... are in their own group and thus a require a request we can avoid
218            // * ... have known-empty status preloaded by ResourceLoader.
219            } elseif ( $group !== Module::GROUP_USER || !$module->isKnownEmpty( $context ) ) {
220                // Load from load.php?only=styles via <link rel=stylesheet>
221                $data['styles'][] = $name;
222            }
223            $deprecation = $module->getDeprecationWarning();
224            if ( $deprecation ) {
225                $data['styleDeprecations'][] = $deprecation;
226            }
227        }
228
229        return $data;
230    }
231
232    /**
233     * @return array<string,string> Attributes pairs for the HTML document element
234     */
235    public function getDocumentAttributes() {
236        return [ 'class' => 'client-nojs' ];
237    }
238
239    /**
240     * Set relevant classes on document.documentElement
241     *
242     * @param string|null $nojsClass Class name that Skin will set on HTML document
243     * @return string
244     */
245    private function getDocumentClassNameScript( $nojsClass ) {
246        // Change "client-nojs" to "client-js".
247        // This enables server rendering of UI components, even for those that should be hidden
248        // in Grade C where JavaScript is unsupported, whilst avoiding a flash of wrong content.
249        //
250        // See also Skin:getHtmlElementAttributes() and startup/startup.js.
251        //
252        // Optimisation: Produce shorter and faster JS by only writing to DOM.
253        // This is possible because Skin informs RL about the final value of <html class>, and
254        // because RL already controls the first element in HTML <head> for performance reasons.
255        // - Avoid reading HTMLElement.className
256        // - Avoid executing JS regexes in the common case, by doing the string replace in PHP.
257        $nojsClass ??= $this->getDocumentAttributes()['class'];
258        $jsClass = preg_replace( '/(^|\s)client-nojs(\s|$)/', '$1client-js$2', $nojsClass );
259        $jsClassJson = $this->context->encodeJson( $jsClass );
260
261        // Apply client preferences stored by mw.user.clientPrefs as "class1,class2", where each
262        // item is an <html> class following the pattern "<key>-clientpref-<value>" (T339268)
263        if ( $this->options['clientPrefEnabled'] ) {
264            $cookiePrefix = $this->options['clientPrefCookiePrefix'];
265            $script = strtr(
266                file_get_contents( MW_INSTALL_PATH . '/resources/src/startup/clientprefs.js' ),
267                [
268                    '$VARS.jsClass' => $jsClassJson,
269                    '__COOKIE_PREFIX__' => $cookiePrefix,
270                ]
271            );
272        } else {
273            $script = "document.documentElement.className = {$jsClassJson};";
274        }
275
276        return $script;
277    }
278
279    /**
280     * The order of elements in the head is as follows:
281     * - Inline scripts.
282     * - Stylesheets.
283     * - Async external script-src.
284     *
285     * Reasons:
286     * - Script execution may be blocked on preceding stylesheets.
287     * - Async scripts are not blocked on stylesheets.
288     * - Inline scripts can't be asynchronous.
289     * - For styles, earlier is better.
290     *
291     * @param string|null $nojsClass Class name that caller uses on HTML document element
292     * @return string|WrappedStringList HTML
293     */
294    public function getHeadHtml( $nojsClass = null ) {
295        $script = $this->getDocumentClassNameScript( $nojsClass );
296
297        // Inline script: Declare mw.config variables for this page.
298        if ( $this->config ) {
299            $confJson = $this->context->encodeJson( $this->config );
300            $script .= "
301RLCONF = {$confJson};
302";
303        }
304
305        $data = $this->getData();
306
307        // Inline script: Declare initial module states for this page.
308        $states = array_merge( $this->exemptStates, $data['states'] );
309        if ( $states ) {
310            $stateJson = $this->context->encodeJson( $states );
311            $script .= "
312RLSTATE = {$stateJson};
313";
314        }
315
316        // Inline script: Declare general modules to load on this page.
317        if ( $data['general'] ) {
318            $pageModulesJson = $this->context->encodeJson( $data['general'] );
319            $script .= "
320RLPAGEMODULES = {$pageModulesJson};
321";
322        }
323
324        if ( !$this->context->getDebug() ) {
325            $script = ResourceLoader::filter( 'minify-js', $script, [ 'cache' => false ] );
326        }
327
328        $chunks = [];
329        $chunks[] = Html::inlineScript( $script );
330
331        // Inline RLQ: Embedded modules
332        if ( $data['embed']['general'] ) {
333            $chunks[] = $this->getLoad(
334                $data['embed']['general'],
335                Module::TYPE_COMBINED
336            );
337        }
338
339        // External stylesheets (only=styles)
340        if ( $data['styles'] ) {
341            $chunks[] = $this->getLoad(
342                $data['styles'],
343                Module::TYPE_STYLES
344            );
345        }
346
347        // Inline stylesheets (embedded only=styles)
348        if ( $data['embed']['styles'] ) {
349            $chunks[] = $this->getLoad(
350                $data['embed']['styles'],
351                Module::TYPE_STYLES
352            );
353        }
354
355        // Async scripts. Once the startup is loaded, inline RLQ scripts will run.
356        // Pass-through a custom 'target' from OutputPage (T143066).
357        $startupQuery = [ 'raw' => '1' ];
358        foreach ( [ 'target', 'safemode' ] as $param ) {
359            if ( $this->options[$param] !== null ) {
360                $startupQuery[$param] = (string)$this->options[$param];
361            }
362        }
363        $chunks[] = $this->getLoad(
364            'startup',
365            Module::TYPE_SCRIPTS,
366            $startupQuery
367        );
368
369        return WrappedString::join( "\n", $chunks );
370    }
371
372    /**
373     * @return string|WrappedStringList HTML
374     */
375    public function getBodyHtml() {
376        $data = $this->getData();
377        $chunks = [];
378
379        // Deprecations for only=styles modules
380        if ( $data['styleDeprecations'] ) {
381            $calls = '';
382            foreach ( $data['styleDeprecations'] as $warning ) {
383                $calls .= Html::encodeJsCall( 'mw.log.warn', [ $warning ] );
384            }
385            $chunks[] = ResourceLoader::makeInlineScript( $calls );
386        }
387
388        return WrappedString::join( "\n", $chunks );
389    }
390
391    private function getContext( $group, $type ): Context {
392        return self::makeContext( $this->context, $group, $type );
393    }
394
395    private function getLoad( $modules, $only, array $extraQuery = [] ) {
396        return self::makeLoad( $this->context, (array)$modules, $only, $extraQuery );
397    }
398
399    private static function makeContext( Context $mainContext, $group, $type,
400        array $extraQuery = []
401    ): DerivativeContext {
402        // Allow caller to setVersion() and setModules()
403        $ret = new DerivativeContext( $mainContext );
404        // Set 'only' if not combined
405        $ret->setOnly( $type === Module::TYPE_COMBINED ? null : $type );
406        // Remove user parameter in most cases
407        if ( $group !== Module::GROUP_USER && $group !== Module::GROUP_PRIVATE ) {
408            $ret->setUser( null );
409        }
410        if ( isset( $extraQuery['raw'] ) ) {
411            $ret->setRaw( true );
412        }
413        return $ret;
414    }
415
416    /**
417     * Explicitly load or embed modules on a page.
418     *
419     * @param Context $mainContext
420     * @param string[] $modules One or more module names
421     * @param string $only Module TYPE_ class constant
422     * @param array $extraQuery [optional] Array with extra query parameters for the request
423     * @return string|WrappedStringList HTML
424     */
425    public static function makeLoad( Context $mainContext, array $modules, $only,
426        array $extraQuery = []
427    ) {
428        $rl = $mainContext->getResourceLoader();
429        $chunks = [];
430
431        // Sort module names so requests are more uniform
432        sort( $modules );
433
434        if ( $mainContext->getDebug() && count( $modules ) > 1 ) {
435            // Recursively call us for every item
436            foreach ( $modules as $name ) {
437                $chunks[] = self::makeLoad( $mainContext, [ $name ], $only, $extraQuery );
438            }
439            return new WrappedStringList( "\n", $chunks );
440        }
441
442        // Create keyed-by-source and then keyed-by-group list of module objects from modules list
443        $sortedModules = [];
444        foreach ( $modules as $name ) {
445            $module = $rl->getModule( $name );
446            if ( !$module ) {
447                $rl->getLogger()->warning( 'Unknown module "{module}"', [ 'module' => $name ] );
448                continue;
449            }
450            $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
451        }
452
453        foreach ( $sortedModules as $source => $groups ) {
454            foreach ( $groups as $group => $grpModules ) {
455                $context = self::makeContext( $mainContext, $group, $only, $extraQuery );
456
457                // Separate sets of linked and embedded modules while preserving order
458                $moduleSets = [];
459                $idx = -1;
460                foreach ( $grpModules as $name => $module ) {
461                    $shouldEmbed = $module->shouldEmbedModule( $context );
462                    if ( !$moduleSets || $moduleSets[$idx][0] !== $shouldEmbed ) {
463                        $moduleSets[++$idx] = [ $shouldEmbed, [] ];
464                    }
465                    $moduleSets[$idx][1][$name] = $module;
466                }
467
468                // Link/embed each set
469                foreach ( $moduleSets as [ $embed, $moduleSet ] ) {
470                    $moduleSetNames = array_keys( $moduleSet );
471                    $context->setModules( $moduleSetNames );
472                    if ( $embed ) {
473                        $response = $rl->makeModuleResponse( $context, $moduleSet );
474                        // Decide whether to use style or script element
475                        if ( $only == Module::TYPE_STYLES ) {
476                            $chunks[] = Html::inlineStyle( $response );
477                        } else {
478                            $chunks[] = ResourceLoader::makeInlineScript( $response );
479                        }
480                    } else {
481                        // Not embedded
482
483                        // Special handling for the user group; because users might change their stuff
484                        // on-wiki like user pages, or user preferences; we need to find the highest
485                        // timestamp of these user-changeable modules so we can ensure cache misses on change
486                        // This should NOT be done for the site group (T29564) because anons get that too
487                        // and we shouldn't be putting timestamps in CDN-cached HTML
488                        if ( $group === Module::GROUP_USER ) {
489                            $context->setVersion( $rl->makeVersionQuery( $context, $moduleSetNames ) );
490                        }
491
492                        // Must setModules() before createLoaderURL()
493                        $url = $rl->createLoaderURL( $source, $context, $extraQuery );
494
495                        // Decide whether to use 'style' or 'script' element
496                        if ( $only === Module::TYPE_STYLES ) {
497                            $chunk = Html::linkedStyle( $url );
498                        } elseif ( $context->getRaw() ) {
499                            // This request is asking for the module to be delivered standalone,
500                            // (aka "raw") without communicating to any mw.loader client.
501                            // For:
502                            // - startup (naturally because this is what will define mw.loader)
503                            $chunk = Html::element( 'script', [
504                                'async' => true,
505                                'src' => $url,
506                            ] );
507                        } else {
508                            $chunk = ResourceLoader::makeInlineScript(
509                                'mw.loader.load(' . $mainContext->encodeJson( $url ) . ');'
510                            );
511                        }
512
513                        if ( $group == Module::GROUP_NOSCRIPT ) {
514                            $chunks[] = Html::rawElement( 'noscript', [], $chunk );
515                        } else {
516                            $chunks[] = $chunk;
517                        }
518                    }
519                }
520            }
521        }
522
523        return new WrappedStringList( "\n", $chunks );
524    }
525}