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