Merge "resourceloader: Instantiate main class via ServiceWiring"
[lhc/web/wiklou.git] / includes / resourceloader / ResourceLoaderContext.php
1 <?php
2 /**
3 * Context for ResourceLoader modules.
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 * @file
21 * @author Trevor Parscal
22 * @author Roan Kattouw
23 */
24
25 use MediaWiki\Logger\LoggerFactory;
26 use MediaWiki\MediaWikiServices;
27
28 /**
29 * Object passed around to modules which contains information about the state
30 * of a specific loader request.
31 */
32 class ResourceLoaderContext implements MessageLocalizer {
33 protected $resourceLoader;
34 protected $request;
35 protected $logger;
36
37 // Module content vary
38 protected $skin;
39 protected $language;
40 protected $debug;
41 protected $user;
42
43 // Request vary (in addition to cache vary)
44 protected $modules;
45 protected $only;
46 protected $version;
47 protected $raw;
48 protected $image;
49 protected $variant;
50 protected $format;
51
52 protected $direction;
53 protected $hash;
54 protected $userObj;
55 protected $imageObj;
56
57 /**
58 * @param ResourceLoader $resourceLoader
59 * @param WebRequest $request
60 */
61 public function __construct( ResourceLoader $resourceLoader, WebRequest $request ) {
62 $this->resourceLoader = $resourceLoader;
63 $this->request = $request;
64 $this->logger = $resourceLoader->getLogger();
65
66 // Future developers: Use WebRequest::getRawVal() instead getVal().
67 // The getVal() method performs slow Language+UTF logic. (f303bb9360)
68
69 // List of modules
70 $modules = $request->getRawVal( 'modules' );
71 $this->modules = $modules ? self::expandModuleNames( $modules ) : [];
72
73 // Various parameters
74 $this->user = $request->getRawVal( 'user' );
75 $this->debug = $request->getFuzzyBool(
76 'debug',
77 $this->getConfig()->get( 'ResourceLoaderDebug' )
78 );
79 $this->only = $request->getRawVal( 'only', null );
80 $this->version = $request->getRawVal( 'version', null );
81 $this->raw = $request->getFuzzyBool( 'raw' );
82
83 // Image requests
84 $this->image = $request->getRawVal( 'image' );
85 $this->variant = $request->getRawVal( 'variant' );
86 $this->format = $request->getRawVal( 'format' );
87
88 $this->skin = $request->getRawVal( 'skin' );
89 $skinnames = Skin::getSkinNames();
90 // If no skin is specified, or we don't recognize the skin, use the default skin
91 if ( !$this->skin || !isset( $skinnames[$this->skin] ) ) {
92 $this->skin = $this->getConfig()->get( 'DefaultSkin' );
93 }
94 }
95
96 /**
97 * Expand a string of the form `jquery.foo,bar|jquery.ui.baz,quux` to
98 * an array of module names like `[ 'jquery.foo', 'jquery.bar',
99 * 'jquery.ui.baz', 'jquery.ui.quux' ]`.
100 *
101 * This process is reversed by ResourceLoader::makePackedModulesString().
102 *
103 * @param string $modules Packed module name list
104 * @return array Array of module names
105 */
106 public static function expandModuleNames( $modules ) {
107 $retval = [];
108 $exploded = explode( '|', $modules );
109 foreach ( $exploded as $group ) {
110 if ( strpos( $group, ',' ) === false ) {
111 // This is not a set of modules in foo.bar,baz notation
112 // but a single module
113 $retval[] = $group;
114 } else {
115 // This is a set of modules in foo.bar,baz notation
116 $pos = strrpos( $group, '.' );
117 if ( $pos === false ) {
118 // Prefixless modules, i.e. without dots
119 $retval = array_merge( $retval, explode( ',', $group ) );
120 } else {
121 // We have a prefix and a bunch of suffixes
122 $prefix = substr( $group, 0, $pos ); // 'foo'
123 $suffixes = explode( ',', substr( $group, $pos + 1 ) ); // [ 'bar', 'baz' ]
124 foreach ( $suffixes as $suffix ) {
125 $retval[] = "$prefix.$suffix";
126 }
127 }
128 }
129 }
130 return $retval;
131 }
132
133 /**
134 * Return a dummy ResourceLoaderContext object suitable for passing into
135 * things that don't "really" need a context.
136 *
137 * Use cases:
138 * - Creating html5shiv script tag in OutputPage.
139 * - FileModule::readStyleFiles (deprecated, to be removed).
140 * - Unit tests (deprecated, create empty instance directly or use RLTestCase).
141 *
142 * @return ResourceLoaderContext
143 */
144 public static function newDummyContext() {
145 // This currently creates a non-empty instance of ResourceLoader (all modules registered),
146 // but that's probably not needed. So once that moves into ServiceWiring, this'll
147 // become more like the EmptyResourceLoader class we have in PHPUnit tests, which
148 // is what this should've had originally. If this turns out to be untrue, change to:
149 // `MediaWikiServices::getInstance()->getResourceLoader()` instead.
150 return new self( new ResourceLoader(
151 MediaWikiServices::getInstance()->getMainConfig(),
152 LoggerFactory::getInstance( 'resourceloader' )
153 ), new FauxRequest( [] ) );
154 }
155
156 /**
157 * @return ResourceLoader
158 */
159 public function getResourceLoader() {
160 return $this->resourceLoader;
161 }
162
163 /**
164 * @return Config
165 */
166 public function getConfig() {
167 return $this->getResourceLoader()->getConfig();
168 }
169
170 /**
171 * @return WebRequest
172 */
173 public function getRequest() {
174 return $this->request;
175 }
176
177 /**
178 * @since 1.27
179 * @return \Psr\Log\LoggerInterface
180 */
181 public function getLogger() {
182 return $this->logger;
183 }
184
185 /**
186 * @return array
187 */
188 public function getModules() {
189 return $this->modules;
190 }
191
192 /**
193 * @return string
194 */
195 public function getLanguage() {
196 if ( $this->language === null ) {
197 // Must be a valid language code after this point (T64849)
198 // Only support uselang values that follow built-in conventions (T102058)
199 $lang = $this->getRequest()->getRawVal( 'lang', '' );
200 // Stricter version of RequestContext::sanitizeLangCode()
201 if ( !Language::isValidBuiltInCode( $lang ) ) {
202 $lang = $this->getConfig()->get( 'LanguageCode' );
203 }
204 $this->language = $lang;
205 }
206 return $this->language;
207 }
208
209 /**
210 * @return string
211 */
212 public function getDirection() {
213 if ( $this->direction === null ) {
214 $this->direction = $this->getRequest()->getRawVal( 'dir' );
215 if ( !$this->direction ) {
216 // Determine directionality based on user language (T8100)
217 $this->direction = Language::factory( $this->getLanguage() )->getDir();
218 }
219 }
220 return $this->direction;
221 }
222
223 /**
224 * @return string
225 */
226 public function getSkin() {
227 return $this->skin;
228 }
229
230 /**
231 * @return string|null
232 */
233 public function getUser() {
234 return $this->user;
235 }
236
237 /**
238 * Get a Message object with context set. See wfMessage for parameters.
239 *
240 * @since 1.27
241 * @param string|string[]|MessageSpecifier $key Message key, or array of keys,
242 * or a MessageSpecifier.
243 * @param mixed $args,...
244 * @return Message
245 */
246 public function msg( $key ) {
247 return wfMessage( ...func_get_args() )
248 ->inLanguage( $this->getLanguage() )
249 // Use a dummy title because there is no real title
250 // for this endpoint, and the cache won't vary on it
251 // anyways.
252 ->title( Title::newFromText( 'Dwimmerlaik' ) );
253 }
254
255 /**
256 * Get the possibly-cached User object for the specified username
257 *
258 * @since 1.25
259 * @return User
260 */
261 public function getUserObj() {
262 if ( $this->userObj === null ) {
263 $username = $this->getUser();
264 if ( $username ) {
265 // Use provided username if valid, fallback to anonymous user
266 $this->userObj = User::newFromName( $username ) ?: new User;
267 } else {
268 // Anonymous user
269 $this->userObj = new User;
270 }
271 }
272
273 return $this->userObj;
274 }
275
276 /**
277 * @return bool
278 */
279 public function getDebug() {
280 return $this->debug;
281 }
282
283 /**
284 * @return string|null
285 */
286 public function getOnly() {
287 return $this->only;
288 }
289
290 /**
291 * @see ResourceLoaderModule::getVersionHash
292 * @see ResourceLoaderClientHtml::makeLoad
293 * @return string|null
294 */
295 public function getVersion() {
296 return $this->version;
297 }
298
299 /**
300 * @return bool
301 */
302 public function getRaw() {
303 return $this->raw;
304 }
305
306 /**
307 * @return string|null
308 */
309 public function getImage() {
310 return $this->image;
311 }
312
313 /**
314 * @return string|null
315 */
316 public function getVariant() {
317 return $this->variant;
318 }
319
320 /**
321 * @return string|null
322 */
323 public function getFormat() {
324 return $this->format;
325 }
326
327 /**
328 * If this is a request for an image, get the ResourceLoaderImage object.
329 *
330 * @since 1.25
331 * @return ResourceLoaderImage|bool false if a valid object cannot be created
332 */
333 public function getImageObj() {
334 if ( $this->imageObj === null ) {
335 $this->imageObj = false;
336
337 if ( !$this->image ) {
338 return $this->imageObj;
339 }
340
341 $modules = $this->getModules();
342 if ( count( $modules ) !== 1 ) {
343 return $this->imageObj;
344 }
345
346 $module = $this->getResourceLoader()->getModule( $modules[0] );
347 if ( !$module || !$module instanceof ResourceLoaderImageModule ) {
348 return $this->imageObj;
349 }
350
351 $image = $module->getImage( $this->image, $this );
352 if ( !$image ) {
353 return $this->imageObj;
354 }
355
356 $this->imageObj = $image;
357 }
358
359 return $this->imageObj;
360 }
361
362 /**
363 * Return the replaced-content mapping callback
364 *
365 * When editing a page that's used to generate the scripts or styles of a
366 * ResourceLoaderWikiModule, a preview should use the to-be-saved version of
367 * the page rather than the current version in the database. A context
368 * supporting such previews should return a callback to return these
369 * mappings here.
370 *
371 * @since 1.32
372 * @return callable|null Signature is `Content|null func( Title $t )`
373 */
374 public function getContentOverrideCallback() {
375 return null;
376 }
377
378 /**
379 * @return bool
380 */
381 public function shouldIncludeScripts() {
382 return $this->getOnly() === null || $this->getOnly() === 'scripts';
383 }
384
385 /**
386 * @return bool
387 */
388 public function shouldIncludeStyles() {
389 return $this->getOnly() === null || $this->getOnly() === 'styles';
390 }
391
392 /**
393 * @return bool
394 */
395 public function shouldIncludeMessages() {
396 return $this->getOnly() === null;
397 }
398
399 /**
400 * All factors that uniquely identify this request, except 'modules'.
401 *
402 * The list of modules is excluded here for legacy reasons as most callers already
403 * split up handling of individual modules. Including it here would massively fragment
404 * the cache and decrease its usefulness.
405 *
406 * E.g. Used by RequestFileCache to form a cache key for storing the reponse output.
407 *
408 * @return string
409 */
410 public function getHash() {
411 if ( !isset( $this->hash ) ) {
412 $this->hash = implode( '|', [
413 // Module content vary
414 $this->getLanguage(),
415 $this->getSkin(),
416 $this->getDebug(),
417 $this->getUser(),
418 // Request vary
419 $this->getOnly(),
420 $this->getVersion(),
421 $this->getRaw(),
422 $this->getImage(),
423 $this->getVariant(),
424 $this->getFormat(),
425 ] );
426 }
427 return $this->hash;
428 }
429 }