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