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