resourceloader: Move expandModuleNames() to ResourceLoader.php
[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 no skin is specified, or we don't recognize the skin, use the default skin
88 if ( !$this->skin || !isset( $skinnames[$this->skin] ) ) {
89 $this->skin = $this->getConfig()->get( 'DefaultSkin' );
90 }
91 }
92
93 /**
94 * Reverse the process done by ResourceLoader::makePackedModulesString().
95 *
96 * @deprecated since 1.33 Use ResourceLoader::expandModuleNames instead.
97 * @param string $modules Packed module name list
98 * @return array Array of module names
99 * @codeCoverageIgnore
100 */
101 public static function expandModuleNames( $modules ) {
102 wfDeprecated( __METHOD__, '1.33' );
103 return ResourceLoader::expandModuleNames( $modules );
104 }
105
106 /**
107 * Return a dummy ResourceLoaderContext object suitable for passing into
108 * things that don't "really" need a context.
109 *
110 * Use cases:
111 * - Unit tests (deprecated, create empty instance directly or use RLTestCase).
112 *
113 * @return ResourceLoaderContext
114 */
115 public static function newDummyContext() {
116 // This currently creates a non-empty instance of ResourceLoader (all modules registered),
117 // but that's probably not needed. So once that moves into ServiceWiring, this'll
118 // become more like the EmptyResourceLoader class we have in PHPUnit tests, which
119 // is what this should've had originally. If this turns out to be untrue, change to:
120 // `MediaWikiServices::getInstance()->getResourceLoader()` instead.
121 return new self( new ResourceLoader(
122 MediaWikiServices::getInstance()->getMainConfig(),
123 LoggerFactory::getInstance( 'resourceloader' )
124 ), new FauxRequest( [] ) );
125 }
126
127 /**
128 * @return ResourceLoader
129 */
130 public function getResourceLoader() {
131 return $this->resourceLoader;
132 }
133
134 /**
135 * @return Config
136 */
137 public function getConfig() {
138 return $this->getResourceLoader()->getConfig();
139 }
140
141 /**
142 * @return WebRequest
143 */
144 public function getRequest() {
145 return $this->request;
146 }
147
148 /**
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 $lang = $this->getConfig()->get( 'LanguageCode' );
174 }
175 $this->language = $lang;
176 }
177 return $this->language;
178 }
179
180 /**
181 * @return string
182 */
183 public function getDirection() {
184 if ( $this->direction === null ) {
185 $this->direction = $this->getRequest()->getRawVal( 'dir' );
186 if ( !$this->direction ) {
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 }