Merge "Remove suggestions for negative namespaces in Page Restrictions"
[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 *
137 * Use cases:
138 * - Creating html5shiv script tag in OutputPage.
139 * - Unit tests (deprecated, create empty instance directly or use RLTestCase).
140 *
141 * @return ResourceLoaderContext
142 */
143 public static function newDummyContext() {
144 // This currently creates a non-empty instance of ResourceLoader (all modules registered),
145 // but that's probably not needed. So once that moves into ServiceWiring, this'll
146 // become more like the EmptyResourceLoader class we have in PHPUnit tests, which
147 // is what this should've had originally. If this turns out to be untrue, change to:
148 // `MediaWikiServices::getInstance()->getResourceLoader()` instead.
149 return new self( new ResourceLoader(
150 MediaWikiServices::getInstance()->getMainConfig(),
151 LoggerFactory::getInstance( 'resourceloader' )
152 ), new FauxRequest( [] ) );
153 }
154
155 /**
156 * @return ResourceLoader
157 */
158 public function getResourceLoader() {
159 return $this->resourceLoader;
160 }
161
162 /**
163 * @return Config
164 */
165 public function getConfig() {
166 return $this->getResourceLoader()->getConfig();
167 }
168
169 /**
170 * @return WebRequest
171 */
172 public function getRequest() {
173 return $this->request;
174 }
175
176 /**
177 * @since 1.27
178 * @return \Psr\Log\LoggerInterface
179 */
180 public function getLogger() {
181 return $this->logger;
182 }
183
184 /**
185 * @return array
186 */
187 public function getModules() {
188 return $this->modules;
189 }
190
191 /**
192 * @return string
193 */
194 public function getLanguage() {
195 if ( $this->language === null ) {
196 // Must be a valid language code after this point (T64849)
197 // Only support uselang values that follow built-in conventions (T102058)
198 $lang = $this->getRequest()->getRawVal( 'lang', '' );
199 // Stricter version of RequestContext::sanitizeLangCode()
200 if ( !Language::isValidBuiltInCode( $lang ) ) {
201 $lang = $this->getConfig()->get( 'LanguageCode' );
202 }
203 $this->language = $lang;
204 }
205 return $this->language;
206 }
207
208 /**
209 * @return string
210 */
211 public function getDirection() {
212 if ( $this->direction === null ) {
213 $this->direction = $this->getRequest()->getRawVal( 'dir' );
214 if ( !$this->direction ) {
215 // Determine directionality based on user language (T8100)
216 $this->direction = Language::factory( $this->getLanguage() )->getDir();
217 }
218 }
219 return $this->direction;
220 }
221
222 /**
223 * @return string
224 */
225 public function getSkin() {
226 return $this->skin;
227 }
228
229 /**
230 * @return string|null
231 */
232 public function getUser() {
233 return $this->user;
234 }
235
236 /**
237 * Get a Message object with context set. See wfMessage for parameters.
238 *
239 * @since 1.27
240 * @param string|string[]|MessageSpecifier $key Message key, or array of keys,
241 * or a MessageSpecifier.
242 * @param mixed $args,...
243 * @return Message
244 */
245 public function msg( $key ) {
246 return wfMessage( ...func_get_args() )
247 ->inLanguage( $this->getLanguage() )
248 // Use a dummy title because there is no real title
249 // for this endpoint, and the cache won't vary on it
250 // anyways.
251 ->title( Title::newFromText( 'Dwimmerlaik' ) );
252 }
253
254 /**
255 * Get the possibly-cached User object for the specified username
256 *
257 * @since 1.25
258 * @return User
259 */
260 public function getUserObj() {
261 if ( $this->userObj === null ) {
262 $username = $this->getUser();
263 if ( $username ) {
264 // Use provided username if valid, fallback to anonymous user
265 $this->userObj = User::newFromName( $username ) ?: new User;
266 } else {
267 // Anonymous user
268 $this->userObj = new User;
269 }
270 }
271
272 return $this->userObj;
273 }
274
275 /**
276 * @return bool
277 */
278 public function getDebug() {
279 return $this->debug;
280 }
281
282 /**
283 * @return string|null
284 */
285 public function getOnly() {
286 return $this->only;
287 }
288
289 /**
290 * @see ResourceLoaderModule::getVersionHash
291 * @see ResourceLoaderClientHtml::makeLoad
292 * @return string|null
293 */
294 public function getVersion() {
295 return $this->version;
296 }
297
298 /**
299 * @return bool
300 */
301 public function getRaw() {
302 return $this->raw;
303 }
304
305 /**
306 * @return string|null
307 */
308 public function getImage() {
309 return $this->image;
310 }
311
312 /**
313 * @return string|null
314 */
315 public function getVariant() {
316 return $this->variant;
317 }
318
319 /**
320 * @return string|null
321 */
322 public function getFormat() {
323 return $this->format;
324 }
325
326 /**
327 * If this is a request for an image, get the ResourceLoaderImage object.
328 *
329 * @since 1.25
330 * @return ResourceLoaderImage|bool false if a valid object cannot be created
331 */
332 public function getImageObj() {
333 if ( $this->imageObj === null ) {
334 $this->imageObj = false;
335
336 if ( !$this->image ) {
337 return $this->imageObj;
338 }
339
340 $modules = $this->getModules();
341 if ( count( $modules ) !== 1 ) {
342 return $this->imageObj;
343 }
344
345 $module = $this->getResourceLoader()->getModule( $modules[0] );
346 if ( !$module || !$module instanceof ResourceLoaderImageModule ) {
347 return $this->imageObj;
348 }
349
350 $image = $module->getImage( $this->image, $this );
351 if ( !$image ) {
352 return $this->imageObj;
353 }
354
355 $this->imageObj = $image;
356 }
357
358 return $this->imageObj;
359 }
360
361 /**
362 * Return the replaced-content mapping callback
363 *
364 * When editing a page that's used to generate the scripts or styles of a
365 * ResourceLoaderWikiModule, a preview should use the to-be-saved version of
366 * the page rather than the current version in the database. A context
367 * supporting such previews should return a callback to return these
368 * mappings here.
369 *
370 * @since 1.32
371 * @return callable|null Signature is `Content|null func( Title $t )`
372 */
373 public function getContentOverrideCallback() {
374 return null;
375 }
376
377 /**
378 * @return bool
379 */
380 public function shouldIncludeScripts() {
381 return $this->getOnly() === null || $this->getOnly() === 'scripts';
382 }
383
384 /**
385 * @return bool
386 */
387 public function shouldIncludeStyles() {
388 return $this->getOnly() === null || $this->getOnly() === 'styles';
389 }
390
391 /**
392 * @return bool
393 */
394 public function shouldIncludeMessages() {
395 return $this->getOnly() === null;
396 }
397
398 /**
399 * All factors that uniquely identify this request, except 'modules'.
400 *
401 * The list of modules is excluded here for legacy reasons as most callers already
402 * split up handling of individual modules. Including it here would massively fragment
403 * the cache and decrease its usefulness.
404 *
405 * E.g. Used by RequestFileCache to form a cache key for storing the reponse output.
406 *
407 * @return string
408 */
409 public function getHash() {
410 if ( !isset( $this->hash ) ) {
411 $this->hash = implode( '|', [
412 // Module content vary
413 $this->getLanguage(),
414 $this->getSkin(),
415 $this->getDebug(),
416 $this->getUser(),
417 // Request vary
418 $this->getOnly(),
419 $this->getVersion(),
420 $this->getRaw(),
421 $this->getImage(),
422 $this->getVariant(),
423 $this->getFormat(),
424 ] );
425 }
426 return $this->hash;
427 }
428 }