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