resourceloader: Deprecate ResourceLoaderContext::getConfig and ::getLogger
[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 $this->direction = $this->getRequest()->getRawVal( 'dir' );
194 if ( !$this->direction ) {
195 // Determine directionality based on user language (T8100)
196 $this->direction = Language::factory( $this->getLanguage() )->getDir();
197 }
198 }
199 return $this->direction;
200 }
201
202 /**
203 * @return string
204 */
205 public function getSkin() {
206 return $this->skin;
207 }
208
209 /**
210 * @return string|null
211 */
212 public function getUser() {
213 return $this->user;
214 }
215
216 /**
217 * Get a Message object with context set. See wfMessage for parameters.
218 *
219 * @since 1.27
220 * @param string|string[]|MessageSpecifier $key Message key, or array of keys,
221 * or a MessageSpecifier.
222 * @param mixed $args,...
223 * @return Message
224 */
225 public function msg( $key ) {
226 return wfMessage( ...func_get_args() )
227 ->inLanguage( $this->getLanguage() )
228 // Use a dummy title because there is no real title
229 // for this endpoint, and the cache won't vary on it
230 // anyways.
231 ->title( Title::newFromText( 'Dwimmerlaik' ) );
232 }
233
234 /**
235 * Get the possibly-cached User object for the specified username
236 *
237 * @since 1.25
238 * @return User
239 */
240 public function getUserObj() {
241 if ( $this->userObj === null ) {
242 $username = $this->getUser();
243 if ( $username ) {
244 // Use provided username if valid, fallback to anonymous user
245 $this->userObj = User::newFromName( $username ) ?: new User;
246 } else {
247 // Anonymous user
248 $this->userObj = new User;
249 }
250 }
251
252 return $this->userObj;
253 }
254
255 /**
256 * @return bool
257 */
258 public function getDebug() {
259 return $this->debug;
260 }
261
262 /**
263 * @return string|null
264 */
265 public function getOnly() {
266 return $this->only;
267 }
268
269 /**
270 * @see ResourceLoaderModule::getVersionHash
271 * @see ResourceLoaderClientHtml::makeLoad
272 * @return string|null
273 */
274 public function getVersion() {
275 return $this->version;
276 }
277
278 /**
279 * @return bool
280 */
281 public function getRaw() {
282 return $this->raw;
283 }
284
285 /**
286 * @return string|null
287 */
288 public function getImage() {
289 return $this->image;
290 }
291
292 /**
293 * @return string|null
294 */
295 public function getVariant() {
296 return $this->variant;
297 }
298
299 /**
300 * @return string|null
301 */
302 public function getFormat() {
303 return $this->format;
304 }
305
306 /**
307 * If this is a request for an image, get the ResourceLoaderImage object.
308 *
309 * @since 1.25
310 * @return ResourceLoaderImage|bool false if a valid object cannot be created
311 */
312 public function getImageObj() {
313 if ( $this->imageObj === null ) {
314 $this->imageObj = false;
315
316 if ( !$this->image ) {
317 return $this->imageObj;
318 }
319
320 $modules = $this->getModules();
321 if ( count( $modules ) !== 1 ) {
322 return $this->imageObj;
323 }
324
325 $module = $this->getResourceLoader()->getModule( $modules[0] );
326 if ( !$module || !$module instanceof ResourceLoaderImageModule ) {
327 return $this->imageObj;
328 }
329
330 $image = $module->getImage( $this->image, $this );
331 if ( !$image ) {
332 return $this->imageObj;
333 }
334
335 $this->imageObj = $image;
336 }
337
338 return $this->imageObj;
339 }
340
341 /**
342 * Return the replaced-content mapping callback
343 *
344 * When editing a page that's used to generate the scripts or styles of a
345 * ResourceLoaderWikiModule, a preview should use the to-be-saved version of
346 * the page rather than the current version in the database. A context
347 * supporting such previews should return a callback to return these
348 * mappings here.
349 *
350 * @since 1.32
351 * @return callable|null Signature is `Content|null func( Title $t )`
352 */
353 public function getContentOverrideCallback() {
354 return null;
355 }
356
357 /**
358 * @return bool
359 */
360 public function shouldIncludeScripts() {
361 return $this->getOnly() === null || $this->getOnly() === 'scripts';
362 }
363
364 /**
365 * @return bool
366 */
367 public function shouldIncludeStyles() {
368 return $this->getOnly() === null || $this->getOnly() === 'styles';
369 }
370
371 /**
372 * @return bool
373 */
374 public function shouldIncludeMessages() {
375 return $this->getOnly() === null;
376 }
377
378 /**
379 * All factors that uniquely identify this request, except 'modules'.
380 *
381 * The list of modules is excluded here for legacy reasons as most callers already
382 * split up handling of individual modules. Including it here would massively fragment
383 * the cache and decrease its usefulness.
384 *
385 * E.g. Used by RequestFileCache to form a cache key for storing the reponse output.
386 *
387 * @return string
388 */
389 public function getHash() {
390 if ( !isset( $this->hash ) ) {
391 $this->hash = implode( '|', [
392 // Module content vary
393 $this->getLanguage(),
394 $this->getSkin(),
395 $this->getDebug(),
396 $this->getUser(),
397 // Request vary
398 $this->getOnly(),
399 $this->getVersion(),
400 $this->getRaw(),
401 $this->getImage(),
402 $this->getVariant(),
403 $this->getFormat(),
404 ] );
405 }
406 return $this->hash;
407 }
408 }