Merge "Rewrite pref cleanup script"
[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 $lang = $this->getResourceLoader()->getConfig()->get( 'LanguageCode' );
186 }
187 $this->language = $lang;
188 }
189 return $this->language;
190 }
191
192 /**
193 * @return string
194 */
195 public function getDirection() {
196 if ( $this->direction === null ) {
197 $this->direction = $this->getRequest()->getRawVal( 'dir' );
198 if ( !$this->direction ) {
199 // Determine directionality based on user language (T8100)
200 $this->direction = Language::factory( $this->getLanguage() )->getDir();
201 }
202 }
203 return $this->direction;
204 }
205
206 /**
207 * @return string
208 */
209 public function getSkin() {
210 return $this->skin;
211 }
212
213 /**
214 * @return string|null
215 */
216 public function getUser() {
217 return $this->user;
218 }
219
220 /**
221 * Get a Message object with context set. See wfMessage for parameters.
222 *
223 * @since 1.27
224 * @param string|string[]|MessageSpecifier $key Message key, or array of keys,
225 * or a MessageSpecifier.
226 * @param mixed $args,...
227 * @return Message
228 */
229 public function msg( $key ) {
230 return call_user_func_array( 'wfMessage', func_get_args() )
231 ->inLanguage( $this->getLanguage() )
232 // Use a dummy title because there is no real title
233 // for this endpoint, and the cache won't vary on it
234 // anyways.
235 ->title( Title::newFromText( 'Dwimmerlaik' ) );
236 }
237
238 /**
239 * Get the possibly-cached User object for the specified username
240 *
241 * @since 1.25
242 * @return User
243 */
244 public function getUserObj() {
245 if ( $this->userObj === null ) {
246 $username = $this->getUser();
247 if ( $username ) {
248 // Use provided username if valid, fallback to anonymous user
249 $this->userObj = User::newFromName( $username ) ?: new User;
250 } else {
251 // Anonymous user
252 $this->userObj = new User;
253 }
254 }
255
256 return $this->userObj;
257 }
258
259 /**
260 * @return bool
261 */
262 public function getDebug() {
263 return $this->debug;
264 }
265
266 /**
267 * @return string|null
268 */
269 public function getOnly() {
270 return $this->only;
271 }
272
273 /**
274 * @see ResourceLoaderModule::getVersionHash
275 * @see ResourceLoaderClientHtml::makeLoad
276 * @return string|null
277 */
278 public function getVersion() {
279 return $this->version;
280 }
281
282 /**
283 * @return bool
284 */
285 public function getRaw() {
286 return $this->raw;
287 }
288
289 /**
290 * @return string|null
291 */
292 public function getImage() {
293 return $this->image;
294 }
295
296 /**
297 * @return string|null
298 */
299 public function getVariant() {
300 return $this->variant;
301 }
302
303 /**
304 * @return string|null
305 */
306 public function getFormat() {
307 return $this->format;
308 }
309
310 /**
311 * If this is a request for an image, get the ResourceLoaderImage object.
312 *
313 * @since 1.25
314 * @return ResourceLoaderImage|bool false if a valid object cannot be created
315 */
316 public function getImageObj() {
317 if ( $this->imageObj === null ) {
318 $this->imageObj = false;
319
320 if ( !$this->image ) {
321 return $this->imageObj;
322 }
323
324 $modules = $this->getModules();
325 if ( count( $modules ) !== 1 ) {
326 return $this->imageObj;
327 }
328
329 $module = $this->getResourceLoader()->getModule( $modules[0] );
330 if ( !$module || !$module instanceof ResourceLoaderImageModule ) {
331 return $this->imageObj;
332 }
333
334 $image = $module->getImage( $this->image, $this );
335 if ( !$image ) {
336 return $this->imageObj;
337 }
338
339 $this->imageObj = $image;
340 }
341
342 return $this->imageObj;
343 }
344
345 /**
346 * @return bool
347 */
348 public function shouldIncludeScripts() {
349 return $this->getOnly() === null || $this->getOnly() === 'scripts';
350 }
351
352 /**
353 * @return bool
354 */
355 public function shouldIncludeStyles() {
356 return $this->getOnly() === null || $this->getOnly() === 'styles';
357 }
358
359 /**
360 * @return bool
361 */
362 public function shouldIncludeMessages() {
363 return $this->getOnly() === null;
364 }
365
366 /**
367 * All factors that uniquely identify this request, except 'modules'.
368 *
369 * The list of modules is excluded here for legacy reasons as most callers already
370 * split up handling of individual modules. Including it here would massively fragment
371 * the cache and decrease its usefulness.
372 *
373 * E.g. Used by RequestFileCache to form a cache key for storing the reponse output.
374 *
375 * @return string
376 */
377 public function getHash() {
378 if ( !isset( $this->hash ) ) {
379 $this->hash = implode( '|', [
380 // Module content vary
381 $this->getLanguage(),
382 $this->getSkin(),
383 $this->getDebug(),
384 $this->getUser(),
385 // Request vary
386 $this->getOnly(),
387 $this->getVersion(),
388 $this->getRaw(),
389 $this->getImage(),
390 $this->getVariant(),
391 $this->getFormat(),
392 ] );
393 }
394 return $this->hash;
395 }
396 }