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