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