Merge "Update MediaWikiTitleCodec to use NamespaceInfo"
[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 * @return Config
138 */
139 public function getConfig() {
140 return $this->getResourceLoader()->getConfig();
141 }
142
143 /**
144 * @return WebRequest
145 */
146 public function getRequest() {
147 return $this->request;
148 }
149
150 /**
151 * @since 1.27
152 * @return \Psr\Log\LoggerInterface
153 */
154 public function getLogger() {
155 return $this->logger;
156 }
157
158 /**
159 * @return array
160 */
161 public function getModules() {
162 return $this->modules;
163 }
164
165 /**
166 * @return string
167 */
168 public function getLanguage() {
169 if ( $this->language === null ) {
170 // Must be a valid language code after this point (T64849)
171 // Only support uselang values that follow built-in conventions (T102058)
172 $lang = $this->getRequest()->getRawVal( 'lang', '' );
173 // Stricter version of RequestContext::sanitizeLangCode()
174 if ( !Language::isValidBuiltInCode( $lang ) ) {
175 // The 'lang' parameter is required. (Not yet enforced.)
176 // If omitted, localise with the dummy language code.
177 $lang = 'qqx';
178 }
179 $this->language = $lang;
180 }
181 return $this->language;
182 }
183
184 /**
185 * @return string
186 */
187 public function getDirection() {
188 if ( $this->direction === null ) {
189 $this->direction = $this->getRequest()->getRawVal( 'dir' );
190 if ( !$this->direction ) {
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 * @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 }