Merge "resourceloader: Support 'versionCallback' for computed package files"
[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 of 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 ? ResourceLoader::expandModuleNames( $modules ) : [];
72
73 // Various parameters
74 $this->user = $request->getRawVal( 'user' );
75 $this->debug = $request->getRawVal( 'debug' ) === 'true';
76 $this->only = $request->getRawVal( 'only', null );
77 $this->version = $request->getRawVal( 'version', null );
78 $this->raw = $request->getFuzzyBool( 'raw' );
79
80 // Image requests
81 $this->image = $request->getRawVal( 'image' );
82 $this->variant = $request->getRawVal( 'variant' );
83 $this->format = $request->getRawVal( 'format' );
84
85 $this->skin = $request->getRawVal( 'skin' );
86 $skinnames = Skin::getSkinNames();
87 if ( !$this->skin || !isset( $skinnames[$this->skin] ) ) {
88 // The 'skin' parameter is required. (Not yet enforced.)
89 // For requests without a known skin specified,
90 // use MediaWiki's 'fallback' skin for skin-specific decisions.
91 $this->skin = 'fallback';
92 }
93 }
94
95 /**
96 * Reverse the process done by ResourceLoader::makePackedModulesString().
97 *
98 * @deprecated since 1.33 Use ResourceLoader::expandModuleNames instead.
99 * @param string $modules Packed module name list
100 * @return array Array of module names
101 * @codeCoverageIgnore
102 */
103 public static function expandModuleNames( $modules ) {
104 wfDeprecated( __METHOD__, '1.33' );
105 return ResourceLoader::expandModuleNames( $modules );
106 }
107
108 /**
109 * Return a dummy ResourceLoaderContext object suitable for passing into
110 * things that don't "really" need a context.
111 *
112 * Use cases:
113 * - Unit tests (deprecated, create empty instance directly or use RLTestCase).
114 *
115 * @return ResourceLoaderContext
116 */
117 public static function newDummyContext() {
118 // This currently creates a non-empty instance of ResourceLoader (all modules registered),
119 // but that's probably not needed. So once that moves into ServiceWiring, this'll
120 // become more like the EmptyResourceLoader class we have in PHPUnit tests, which
121 // is what this should've had originally. If this turns out to be untrue, change to:
122 // `MediaWikiServices::getInstance()->getResourceLoader()` instead.
123 return new self( new ResourceLoader(
124 MediaWikiServices::getInstance()->getMainConfig(),
125 LoggerFactory::getInstance( 'resourceloader' )
126 ), new FauxRequest( [] ) );
127 }
128
129 /**
130 * @return ResourceLoader
131 */
132 public function getResourceLoader() {
133 return $this->resourceLoader;
134 }
135
136 /**
137 * @deprecated since 1.34 Use ResourceLoaderModule::getConfig instead
138 * inside module methods. Use ResourceLoader::getConfig elsewhere.
139 * @return Config
140 */
141 public function getConfig() {
142 return $this->getResourceLoader()->getConfig();
143 }
144
145 /**
146 * @return WebRequest
147 */
148 public function getRequest() {
149 return $this->request;
150 }
151
152 /**
153 * @deprecated since 1.34 Use ResourceLoaderModule::getLogger instead
154 * inside module methods. Use ResourceLoader::getLogger elsewhere.
155 * @since 1.27
156 * @return \Psr\Log\LoggerInterface
157 */
158 public function getLogger() {
159 return $this->logger;
160 }
161
162 /**
163 * @return array
164 */
165 public function getModules() {
166 return $this->modules;
167 }
168
169 /**
170 * @return string
171 */
172 public function getLanguage() {
173 if ( $this->language === null ) {
174 // Must be a valid language code after this point (T64849)
175 // Only support uselang values that follow built-in conventions (T102058)
176 $lang = $this->getRequest()->getRawVal( 'lang', '' );
177 // Stricter version of RequestContext::sanitizeLangCode()
178 if ( !Language::isValidBuiltInCode( $lang ) ) {
179 // The 'lang' parameter is required. (Not yet enforced.)
180 // If omitted, localise with the dummy language code.
181 $lang = 'qqx';
182 }
183 $this->language = $lang;
184 }
185 return $this->language;
186 }
187
188 /**
189 * @return string
190 */
191 public function getDirection() {
192 if ( $this->direction === null ) {
193 $direction = $this->getRequest()->getRawVal( 'dir' );
194 if ( $direction === 'ltr' || $direction === 'rtl' ) {
195 $this->direction = $direction;
196 } else {
197 // Determine directionality based on user language (T8100)
198 $this->direction = Language::factory( $this->getLanguage() )->getDir();
199 }
200 }
201 return $this->direction;
202 }
203
204 /**
205 * @return string
206 */
207 public function getSkin() {
208 return $this->skin;
209 }
210
211 /**
212 * @return string|null
213 */
214 public function getUser() {
215 return $this->user;
216 }
217
218 /**
219 * Get a Message object with context set. See wfMessage for parameters.
220 *
221 * @since 1.27
222 * @param string|string[]|MessageSpecifier $key Message key, or array of keys,
223 * or a MessageSpecifier.
224 * @param mixed $args,...
225 * @return Message
226 */
227 public function msg( $key ) {
228 return wfMessage( ...func_get_args() )
229 ->inLanguage( $this->getLanguage() )
230 // Use a dummy title because there is no real title
231 // for this endpoint, and the cache won't vary on it
232 // anyways.
233 ->title( Title::newFromText( 'Dwimmerlaik' ) );
234 }
235
236 /**
237 * Get the possibly-cached User object for the specified username
238 *
239 * @since 1.25
240 * @return User
241 */
242 public function getUserObj() {
243 if ( $this->userObj === null ) {
244 $username = $this->getUser();
245 if ( $username ) {
246 // Use provided username if valid, fallback to anonymous user
247 $this->userObj = User::newFromName( $username ) ?: new User;
248 } else {
249 // Anonymous user
250 $this->userObj = new User;
251 }
252 }
253
254 return $this->userObj;
255 }
256
257 /**
258 * @return bool
259 */
260 public function getDebug() {
261 return $this->debug;
262 }
263
264 /**
265 * @return string|null
266 */
267 public function getOnly() {
268 return $this->only;
269 }
270
271 /**
272 * @see ResourceLoaderModule::getVersionHash
273 * @see ResourceLoaderClientHtml::makeLoad
274 * @return string|null
275 */
276 public function getVersion() {
277 return $this->version;
278 }
279
280 /**
281 * @return bool
282 */
283 public function getRaw() {
284 return $this->raw;
285 }
286
287 /**
288 * @return string|null
289 */
290 public function getImage() {
291 return $this->image;
292 }
293
294 /**
295 * @return string|null
296 */
297 public function getVariant() {
298 return $this->variant;
299 }
300
301 /**
302 * @return string|null
303 */
304 public function getFormat() {
305 return $this->format;
306 }
307
308 /**
309 * If this is a request for an image, get the ResourceLoaderImage object.
310 *
311 * @since 1.25
312 * @return ResourceLoaderImage|bool false if a valid object cannot be created
313 */
314 public function getImageObj() {
315 if ( $this->imageObj === null ) {
316 $this->imageObj = false;
317
318 if ( !$this->image ) {
319 return $this->imageObj;
320 }
321
322 $modules = $this->getModules();
323 if ( count( $modules ) !== 1 ) {
324 return $this->imageObj;
325 }
326
327 $module = $this->getResourceLoader()->getModule( $modules[0] );
328 if ( !$module || !$module instanceof ResourceLoaderImageModule ) {
329 return $this->imageObj;
330 }
331
332 $image = $module->getImage( $this->image, $this );
333 if ( !$image ) {
334 return $this->imageObj;
335 }
336
337 $this->imageObj = $image;
338 }
339
340 return $this->imageObj;
341 }
342
343 /**
344 * Return the replaced-content mapping callback
345 *
346 * When editing a page that's used to generate the scripts or styles of a
347 * ResourceLoaderWikiModule, a preview should use the to-be-saved version of
348 * the page rather than the current version in the database. A context
349 * supporting such previews should return a callback to return these
350 * mappings here.
351 *
352 * @since 1.32
353 * @return callable|null Signature is `Content|null func( Title $t )`
354 */
355 public function getContentOverrideCallback() {
356 return null;
357 }
358
359 /**
360 * @return bool
361 */
362 public function shouldIncludeScripts() {
363 return $this->getOnly() === null || $this->getOnly() === 'scripts';
364 }
365
366 /**
367 * @return bool
368 */
369 public function shouldIncludeStyles() {
370 return $this->getOnly() === null || $this->getOnly() === 'styles';
371 }
372
373 /**
374 * @return bool
375 */
376 public function shouldIncludeMessages() {
377 return $this->getOnly() === null;
378 }
379
380 /**
381 * All factors that uniquely identify this request, except 'modules'.
382 *
383 * The list of modules is excluded here for legacy reasons as most callers already
384 * split up handling of individual modules. Including it here would massively fragment
385 * the cache and decrease its usefulness.
386 *
387 * E.g. Used by RequestFileCache to form a cache key for storing the reponse output.
388 *
389 * @return string
390 */
391 public function getHash() {
392 if ( !isset( $this->hash ) ) {
393 $this->hash = implode( '|', [
394 // Module content vary
395 $this->getLanguage(),
396 $this->getSkin(),
397 $this->getDebug(),
398 $this->getUser(),
399 // Request vary
400 $this->getOnly(),
401 $this->getVersion(),
402 $this->getRaw(),
403 $this->getImage(),
404 $this->getVariant(),
405 $this->getFormat(),
406 ] );
407 }
408 return $this->hash;
409 }
410 }