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