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