ResourceLoaderContext.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. <?php
  2. /**
  3. * This program is free software; you can redistribute it and/or modify
  4. * it under the terms of the GNU General Public License as published by
  5. * the Free Software Foundation; either version 2 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License along
  14. * with this program; if not, write to the Free Software Foundation, Inc.,
  15. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  16. * http://www.gnu.org/copyleft/gpl.html
  17. *
  18. * @file
  19. * @author Trevor Parscal
  20. * @author Roan Kattouw
  21. */
  22. use MediaWiki\Logger\LoggerFactory;
  23. use MediaWiki\MediaWikiServices;
  24. /**
  25. * Context object that contains information about the state of a specific
  26. * ResourceLoader web request. Passed around to ResourceLoaderModule methods.
  27. *
  28. * @ingroup ResourceLoader
  29. * @since 1.17
  30. */
  31. class ResourceLoaderContext implements MessageLocalizer {
  32. const DEFAULT_LANG = 'qqx';
  33. const DEFAULT_SKIN = 'fallback';
  34. protected $resourceLoader;
  35. protected $request;
  36. protected $logger;
  37. // Module content vary
  38. protected $skin;
  39. protected $language;
  40. protected $debug;
  41. protected $user;
  42. // Request vary (in addition to cache vary)
  43. protected $modules;
  44. protected $only;
  45. protected $version;
  46. protected $raw;
  47. protected $image;
  48. protected $variant;
  49. protected $format;
  50. protected $direction;
  51. protected $hash;
  52. protected $userObj;
  53. /** @var ResourceLoaderImage|false */
  54. protected $imageObj;
  55. /**
  56. * @param ResourceLoader $resourceLoader
  57. * @param WebRequest $request
  58. */
  59. public function __construct( ResourceLoader $resourceLoader, WebRequest $request ) {
  60. $this->resourceLoader = $resourceLoader;
  61. $this->request = $request;
  62. $this->logger = $resourceLoader->getLogger();
  63. // Optimisation: Use WebRequest::getRawVal() instead of getVal(). We don't
  64. // need the slow Language+UTF logic meant for user input here. (f303bb9360)
  65. // List of modules
  66. $modules = $request->getRawVal( 'modules' );
  67. $this->modules = $modules ? ResourceLoader::expandModuleNames( $modules ) : [];
  68. // Various parameters
  69. $this->user = $request->getRawVal( 'user' );
  70. $this->debug = $request->getRawVal( 'debug' ) === 'true';
  71. $this->only = $request->getRawVal( 'only' );
  72. $this->version = $request->getRawVal( 'version' );
  73. $this->raw = $request->getFuzzyBool( 'raw' );
  74. // Image requests
  75. $this->image = $request->getRawVal( 'image' );
  76. $this->variant = $request->getRawVal( 'variant' );
  77. $this->format = $request->getRawVal( 'format' );
  78. $this->skin = $request->getRawVal( 'skin' );
  79. $skinnames = Skin::getSkinNames();
  80. if ( !$this->skin || !isset( $skinnames[$this->skin] ) ) {
  81. // The 'skin' parameter is required. (Not yet enforced.)
  82. // For requests without a known skin specified,
  83. // use MediaWiki's 'fallback' skin for skin-specific decisions.
  84. $this->skin = self::DEFAULT_SKIN;
  85. }
  86. }
  87. /**
  88. * Return a dummy ResourceLoaderContext object suitable for passing into
  89. * things that don't "really" need a context.
  90. *
  91. * Use cases:
  92. * - Unit tests (deprecated, create empty instance directly or use RLTestCase).
  93. *
  94. * @return ResourceLoaderContext
  95. */
  96. public static function newDummyContext() {
  97. // This currently creates a non-empty instance of ResourceLoader (all modules registered),
  98. // but that's probably not needed. So once that moves into ServiceWiring, this'll
  99. // become more like the EmptyResourceLoader class we have in PHPUnit tests, which
  100. // is what this should've had originally. If this turns out to be untrue, change to:
  101. // `MediaWikiServices::getInstance()->getResourceLoader()` instead.
  102. return new self( new ResourceLoader(
  103. MediaWikiServices::getInstance()->getMainConfig(),
  104. LoggerFactory::getInstance( 'resourceloader' )
  105. ), new FauxRequest( [] ) );
  106. }
  107. /**
  108. * @return ResourceLoader
  109. */
  110. public function getResourceLoader() {
  111. return $this->resourceLoader;
  112. }
  113. /**
  114. * @deprecated since 1.34 Use ResourceLoaderModule::getConfig instead
  115. * inside module methods. Use ResourceLoader::getConfig elsewhere.
  116. * @return Config
  117. * @codeCoverageIgnore
  118. */
  119. public function getConfig() {
  120. wfDeprecated( __METHOD__, '1.34' );
  121. return $this->getResourceLoader()->getConfig();
  122. }
  123. /**
  124. * @return WebRequest
  125. */
  126. public function getRequest() {
  127. return $this->request;
  128. }
  129. /**
  130. * @deprecated since 1.34 Use ResourceLoaderModule::getLogger instead
  131. * inside module methods. Use ResourceLoader::getLogger elsewhere.
  132. * @since 1.27
  133. * @return \Psr\Log\LoggerInterface
  134. */
  135. public function getLogger() {
  136. return $this->logger;
  137. }
  138. /**
  139. * @return array
  140. */
  141. public function getModules() {
  142. return $this->modules;
  143. }
  144. /**
  145. * @return string
  146. */
  147. public function getLanguage() {
  148. if ( $this->language === null ) {
  149. // Must be a valid language code after this point (T64849)
  150. // Only support uselang values that follow built-in conventions (T102058)
  151. $lang = $this->getRequest()->getRawVal( 'lang', '' );
  152. // Stricter version of RequestContext::sanitizeLangCode()
  153. if ( !Language::isValidBuiltInCode( $lang ) ) {
  154. // The 'lang' parameter is required. (Not yet enforced.)
  155. // If omitted, localise with the dummy language code.
  156. $lang = self::DEFAULT_LANG;
  157. }
  158. $this->language = $lang;
  159. }
  160. return $this->language;
  161. }
  162. /**
  163. * @return string
  164. */
  165. public function getDirection() {
  166. if ( $this->direction === null ) {
  167. $direction = $this->getRequest()->getRawVal( 'dir' );
  168. if ( $direction === 'ltr' || $direction === 'rtl' ) {
  169. $this->direction = $direction;
  170. } else {
  171. // Determine directionality based on user language (T8100)
  172. $this->direction = Language::factory( $this->getLanguage() )->getDir();
  173. }
  174. }
  175. return $this->direction;
  176. }
  177. /**
  178. * @return string
  179. */
  180. public function getSkin() {
  181. return $this->skin;
  182. }
  183. /**
  184. * @return string|null
  185. */
  186. public function getUser() {
  187. return $this->user;
  188. }
  189. /**
  190. * Get a Message object with context set. See wfMessage for parameters.
  191. *
  192. * @since 1.27
  193. * @param string|string[]|MessageSpecifier $key Message key, or array of keys,
  194. * or a MessageSpecifier.
  195. * @param mixed ...$params
  196. * @return Message
  197. */
  198. public function msg( $key, ...$params ) {
  199. return wfMessage( $key, ...$params )
  200. ->inLanguage( $this->getLanguage() )
  201. // Use a dummy title because there is no real title
  202. // for this endpoint, and the cache won't vary on it
  203. // anyways.
  204. ->title( Title::newFromText( 'Dwimmerlaik' ) );
  205. }
  206. /**
  207. * Get the possibly-cached User object for the specified username
  208. *
  209. * @since 1.25
  210. * @return User
  211. */
  212. public function getUserObj() {
  213. if ( $this->userObj === null ) {
  214. $username = $this->getUser();
  215. if ( $username ) {
  216. // Use provided username if valid, fallback to anonymous user
  217. $this->userObj = User::newFromName( $username ) ?: new User;
  218. } else {
  219. // Anonymous user
  220. $this->userObj = new User;
  221. }
  222. }
  223. return $this->userObj;
  224. }
  225. /**
  226. * @return bool
  227. */
  228. public function getDebug() {
  229. return $this->debug;
  230. }
  231. /**
  232. * @return string|null
  233. */
  234. public function getOnly() {
  235. return $this->only;
  236. }
  237. /**
  238. * @see ResourceLoaderModule::getVersionHash
  239. * @see ResourceLoaderClientHtml::makeLoad
  240. * @return string|null
  241. */
  242. public function getVersion() {
  243. return $this->version;
  244. }
  245. /**
  246. * @return bool
  247. */
  248. public function getRaw() {
  249. return $this->raw;
  250. }
  251. /**
  252. * @return string|null
  253. */
  254. public function getImage() {
  255. return $this->image;
  256. }
  257. /**
  258. * @return string|null
  259. */
  260. public function getVariant() {
  261. return $this->variant;
  262. }
  263. /**
  264. * @return string|null
  265. */
  266. public function getFormat() {
  267. return $this->format;
  268. }
  269. /**
  270. * If this is a request for an image, get the ResourceLoaderImage object.
  271. *
  272. * @since 1.25
  273. * @return ResourceLoaderImage|bool false if a valid object cannot be created
  274. */
  275. public function getImageObj() {
  276. if ( $this->imageObj === null ) {
  277. $this->imageObj = false;
  278. if ( !$this->image ) {
  279. return $this->imageObj;
  280. }
  281. $modules = $this->getModules();
  282. if ( count( $modules ) !== 1 ) {
  283. return $this->imageObj;
  284. }
  285. $module = $this->getResourceLoader()->getModule( $modules[0] );
  286. if ( !$module || !$module instanceof ResourceLoaderImageModule ) {
  287. return $this->imageObj;
  288. }
  289. $image = $module->getImage( $this->image, $this );
  290. if ( !$image ) {
  291. return $this->imageObj;
  292. }
  293. $this->imageObj = $image;
  294. }
  295. return $this->imageObj;
  296. }
  297. /**
  298. * Return the replaced-content mapping callback
  299. *
  300. * When editing a page that's used to generate the scripts or styles of a
  301. * ResourceLoaderWikiModule, a preview should use the to-be-saved version of
  302. * the page rather than the current version in the database. A context
  303. * supporting such previews should return a callback to return these
  304. * mappings here.
  305. *
  306. * @since 1.32
  307. * @return callable|null Signature is `Content|null func( Title $t )`
  308. */
  309. public function getContentOverrideCallback() {
  310. return null;
  311. }
  312. /**
  313. * @return bool
  314. */
  315. public function shouldIncludeScripts() {
  316. return $this->getOnly() === null || $this->getOnly() === 'scripts';
  317. }
  318. /**
  319. * @return bool
  320. */
  321. public function shouldIncludeStyles() {
  322. return $this->getOnly() === null || $this->getOnly() === 'styles';
  323. }
  324. /**
  325. * @return bool
  326. */
  327. public function shouldIncludeMessages() {
  328. return $this->getOnly() === null;
  329. }
  330. /**
  331. * All factors that uniquely identify this request, except 'modules'.
  332. *
  333. * The list of modules is excluded here for legacy reasons as most callers already
  334. * split up handling of individual modules. Including it here would massively fragment
  335. * the cache and decrease its usefulness.
  336. *
  337. * E.g. Used by RequestFileCache to form a cache key for storing the reponse output.
  338. *
  339. * @return string
  340. */
  341. public function getHash() {
  342. if ( !isset( $this->hash ) ) {
  343. $this->hash = implode( '|', [
  344. // Module content vary
  345. $this->getLanguage(),
  346. $this->getSkin(),
  347. $this->getDebug(),
  348. $this->getUser(),
  349. // Request vary
  350. $this->getOnly(),
  351. $this->getVersion(),
  352. $this->getRaw(),
  353. $this->getImage(),
  354. $this->getVariant(),
  355. $this->getFormat(),
  356. ] );
  357. }
  358. return $this->hash;
  359. }
  360. /**
  361. * Get the request base parameters, omitting any defaults.
  362. *
  363. * @internal For use by ResourceLoaderStartUpModule only
  364. * @return array
  365. */
  366. public function getReqBase() {
  367. $reqBase = [];
  368. if ( $this->getLanguage() !== self::DEFAULT_LANG ) {
  369. $reqBase['lang'] = $this->getLanguage();
  370. }
  371. if ( $this->getSkin() !== self::DEFAULT_SKIN ) {
  372. $reqBase['skin'] = $this->getSkin();
  373. }
  374. if ( $this->getDebug() ) {
  375. $reqBase['debug'] = 'true';
  376. }
  377. return $reqBase;
  378. }
  379. /**
  380. * Wrapper around json_encode that avoids needless escapes,
  381. * and pretty-prints in debug mode.
  382. *
  383. * @internal
  384. * @param mixed $data
  385. * @return string|false JSON string, false on error
  386. */
  387. public function encodeJson( $data ) {
  388. // Keep output as small as possible by disabling needless escape modes
  389. // that PHP uses by default.
  390. // However, while most module scripts are only served on HTTP responses
  391. // for JavaScript, some modules can also be embedded in the HTML as inline
  392. // scripts. This, and the fact that we sometimes need to export strings
  393. // containing user-generated content and labels that may genuinely contain
  394. // a sequences like "</script>", we need to encode either '/' or '<'.
  395. // By default PHP escapes '/'. Let's escape '<' instead which is less common
  396. // and allows URLs to mostly remain readable.
  397. $jsonFlags = JSON_UNESCAPED_SLASHES |
  398. JSON_UNESCAPED_UNICODE |
  399. JSON_HEX_TAG |
  400. JSON_HEX_AMP;
  401. if ( $this->getDebug() ) {
  402. $jsonFlags |= JSON_PRETTY_PRINT;
  403. }
  404. return json_encode( $data, $jsonFlags );
  405. }
  406. }