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