ResourceLoaderContext.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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. use MediaWiki\Logger\LoggerFactory;
  25. use MediaWiki\MediaWikiServices;
  26. /**
  27. * Object passed around to modules which contains information about the state
  28. * of a specific loader request.
  29. */
  30. class ResourceLoaderContext implements MessageLocalizer {
  31. protected $resourceLoader;
  32. protected $request;
  33. protected $logger;
  34. // Module content vary
  35. protected $skin;
  36. protected $language;
  37. protected $debug;
  38. protected $user;
  39. // Request vary (in addition to cache vary)
  40. protected $modules;
  41. protected $only;
  42. protected $version;
  43. protected $raw;
  44. protected $image;
  45. protected $variant;
  46. protected $format;
  47. protected $direction;
  48. protected $hash;
  49. protected $userObj;
  50. protected $imageObj;
  51. /**
  52. * @param ResourceLoader $resourceLoader
  53. * @param WebRequest $request
  54. */
  55. public function __construct( ResourceLoader $resourceLoader, WebRequest $request ) {
  56. $this->resourceLoader = $resourceLoader;
  57. $this->request = $request;
  58. $this->logger = $resourceLoader->getLogger();
  59. // Future developers: Use WebRequest::getRawVal() instead getVal().
  60. // The getVal() method performs slow Language+UTF logic. (f303bb9360)
  61. // List of modules
  62. $modules = $request->getRawVal( 'modules' );
  63. $this->modules = $modules ? self::expandModuleNames( $modules ) : [];
  64. // Various parameters
  65. $this->user = $request->getRawVal( 'user' );
  66. $this->debug = $request->getFuzzyBool(
  67. 'debug',
  68. $resourceLoader->getConfig()->get( 'ResourceLoaderDebug' )
  69. );
  70. $this->only = $request->getRawVal( 'only', null );
  71. $this->version = $request->getRawVal( 'version', null );
  72. $this->raw = $request->getFuzzyBool( 'raw' );
  73. // Image requests
  74. $this->image = $request->getRawVal( 'image' );
  75. $this->variant = $request->getRawVal( 'variant' );
  76. $this->format = $request->getRawVal( 'format' );
  77. $this->skin = $request->getRawVal( 'skin' );
  78. $skinnames = Skin::getSkinNames();
  79. // If no skin is specified, or we don't recognize the skin, use the default skin
  80. if ( !$this->skin || !isset( $skinnames[$this->skin] ) ) {
  81. $this->skin = $resourceLoader->getConfig()->get( 'DefaultSkin' );
  82. }
  83. }
  84. /**
  85. * Expand a string of the form `jquery.foo,bar|jquery.ui.baz,quux` to
  86. * an array of module names like `[ 'jquery.foo', 'jquery.bar',
  87. * 'jquery.ui.baz', 'jquery.ui.quux' ]`.
  88. *
  89. * This process is reversed by ResourceLoader::makePackedModulesString().
  90. *
  91. * @param string $modules Packed module name list
  92. * @return array Array of module names
  93. */
  94. public static function expandModuleNames( $modules ) {
  95. $retval = [];
  96. $exploded = explode( '|', $modules );
  97. foreach ( $exploded as $group ) {
  98. if ( strpos( $group, ',' ) === false ) {
  99. // This is not a set of modules in foo.bar,baz notation
  100. // but a single module
  101. $retval[] = $group;
  102. } else {
  103. // This is a set of modules in foo.bar,baz notation
  104. $pos = strrpos( $group, '.' );
  105. if ( $pos === false ) {
  106. // Prefixless modules, i.e. without dots
  107. $retval = array_merge( $retval, explode( ',', $group ) );
  108. } else {
  109. // We have a prefix and a bunch of suffixes
  110. $prefix = substr( $group, 0, $pos ); // 'foo'
  111. $suffixes = explode( ',', substr( $group, $pos + 1 ) ); // [ 'bar', 'baz' ]
  112. foreach ( $suffixes as $suffix ) {
  113. $retval[] = "$prefix.$suffix";
  114. }
  115. }
  116. }
  117. }
  118. return $retval;
  119. }
  120. /**
  121. * Return a dummy ResourceLoaderContext object suitable for passing into
  122. * things that don't "really" need a context.
  123. * @return ResourceLoaderContext
  124. */
  125. public static function newDummyContext() {
  126. return new self( new ResourceLoader(
  127. MediaWikiServices::getInstance()->getMainConfig(),
  128. LoggerFactory::getInstance( 'resourceloader' )
  129. ), new FauxRequest( [] ) );
  130. }
  131. /**
  132. * @return ResourceLoader
  133. */
  134. public function getResourceLoader() {
  135. return $this->resourceLoader;
  136. }
  137. /**
  138. * @return WebRequest
  139. */
  140. public function getRequest() {
  141. return $this->request;
  142. }
  143. /**
  144. * @since 1.27
  145. * @return \Psr\Log\LoggerInterface
  146. */
  147. public function getLogger() {
  148. return $this->logger;
  149. }
  150. /**
  151. * @return array
  152. */
  153. public function getModules() {
  154. return $this->modules;
  155. }
  156. /**
  157. * @return string
  158. */
  159. public function getLanguage() {
  160. if ( $this->language === null ) {
  161. // Must be a valid language code after this point (T64849)
  162. // Only support uselang values that follow built-in conventions (T102058)
  163. $lang = $this->getRequest()->getRawVal( 'lang', '' );
  164. // Stricter version of RequestContext::sanitizeLangCode()
  165. if ( !Language::isValidBuiltInCode( $lang ) ) {
  166. $lang = $this->getResourceLoader()->getConfig()->get( 'LanguageCode' );
  167. }
  168. $this->language = $lang;
  169. }
  170. return $this->language;
  171. }
  172. /**
  173. * @return string
  174. */
  175. public function getDirection() {
  176. if ( $this->direction === null ) {
  177. $this->direction = $this->getRequest()->getRawVal( 'dir' );
  178. if ( !$this->direction ) {
  179. // Determine directionality based on user language (T8100)
  180. $this->direction = Language::factory( $this->getLanguage() )->getDir();
  181. }
  182. }
  183. return $this->direction;
  184. }
  185. /**
  186. * @return string
  187. */
  188. public function getSkin() {
  189. return $this->skin;
  190. }
  191. /**
  192. * @return string|null
  193. */
  194. public function getUser() {
  195. return $this->user;
  196. }
  197. /**
  198. * Get a Message object with context set. See wfMessage for parameters.
  199. *
  200. * @since 1.27
  201. * @param string|string[]|MessageSpecifier $key Message key, or array of keys,
  202. * or a MessageSpecifier.
  203. * @param mixed $args,...
  204. * @return Message
  205. */
  206. public function msg( $key ) {
  207. return wfMessage( ...func_get_args() )
  208. ->inLanguage( $this->getLanguage() )
  209. // Use a dummy title because there is no real title
  210. // for this endpoint, and the cache won't vary on it
  211. // anyways.
  212. ->title( Title::newFromText( 'Dwimmerlaik' ) );
  213. }
  214. /**
  215. * Get the possibly-cached User object for the specified username
  216. *
  217. * @since 1.25
  218. * @return User
  219. */
  220. public function getUserObj() {
  221. if ( $this->userObj === null ) {
  222. $username = $this->getUser();
  223. if ( $username ) {
  224. // Use provided username if valid, fallback to anonymous user
  225. $this->userObj = User::newFromName( $username ) ?: new User;
  226. } else {
  227. // Anonymous user
  228. $this->userObj = new User;
  229. }
  230. }
  231. return $this->userObj;
  232. }
  233. /**
  234. * @return bool
  235. */
  236. public function getDebug() {
  237. return $this->debug;
  238. }
  239. /**
  240. * @return string|null
  241. */
  242. public function getOnly() {
  243. return $this->only;
  244. }
  245. /**
  246. * @see ResourceLoaderModule::getVersionHash
  247. * @see ResourceLoaderClientHtml::makeLoad
  248. * @return string|null
  249. */
  250. public function getVersion() {
  251. return $this->version;
  252. }
  253. /**
  254. * @return bool
  255. */
  256. public function getRaw() {
  257. return $this->raw;
  258. }
  259. /**
  260. * @return string|null
  261. */
  262. public function getImage() {
  263. return $this->image;
  264. }
  265. /**
  266. * @return string|null
  267. */
  268. public function getVariant() {
  269. return $this->variant;
  270. }
  271. /**
  272. * @return string|null
  273. */
  274. public function getFormat() {
  275. return $this->format;
  276. }
  277. /**
  278. * If this is a request for an image, get the ResourceLoaderImage object.
  279. *
  280. * @since 1.25
  281. * @return ResourceLoaderImage|bool false if a valid object cannot be created
  282. */
  283. public function getImageObj() {
  284. if ( $this->imageObj === null ) {
  285. $this->imageObj = false;
  286. if ( !$this->image ) {
  287. return $this->imageObj;
  288. }
  289. $modules = $this->getModules();
  290. if ( count( $modules ) !== 1 ) {
  291. return $this->imageObj;
  292. }
  293. $module = $this->getResourceLoader()->getModule( $modules[0] );
  294. if ( !$module || !$module instanceof ResourceLoaderImageModule ) {
  295. return $this->imageObj;
  296. }
  297. $image = $module->getImage( $this->image, $this );
  298. if ( !$image ) {
  299. return $this->imageObj;
  300. }
  301. $this->imageObj = $image;
  302. }
  303. return $this->imageObj;
  304. }
  305. /**
  306. * Return the replaced-content mapping callback
  307. *
  308. * When editing a page that's used to generate the scripts or styles of a
  309. * ResourceLoaderWikiModule, a preview should use the to-be-saved version of
  310. * the page rather than the current version in the database. A context
  311. * supporting such previews should return a callback to return these
  312. * mappings here.
  313. *
  314. * @since 1.32
  315. * @return callable|null Signature is `Content|null func( Title $t )`
  316. */
  317. public function getContentOverrideCallback() {
  318. return null;
  319. }
  320. /**
  321. * @return bool
  322. */
  323. public function shouldIncludeScripts() {
  324. return $this->getOnly() === null || $this->getOnly() === 'scripts';
  325. }
  326. /**
  327. * @return bool
  328. */
  329. public function shouldIncludeStyles() {
  330. return $this->getOnly() === null || $this->getOnly() === 'styles';
  331. }
  332. /**
  333. * @return bool
  334. */
  335. public function shouldIncludeMessages() {
  336. return $this->getOnly() === null;
  337. }
  338. /**
  339. * All factors that uniquely identify this request, except 'modules'.
  340. *
  341. * The list of modules is excluded here for legacy reasons as most callers already
  342. * split up handling of individual modules. Including it here would massively fragment
  343. * the cache and decrease its usefulness.
  344. *
  345. * E.g. Used by RequestFileCache to form a cache key for storing the reponse output.
  346. *
  347. * @return string
  348. */
  349. public function getHash() {
  350. if ( !isset( $this->hash ) ) {
  351. $this->hash = implode( '|', [
  352. // Module content vary
  353. $this->getLanguage(),
  354. $this->getSkin(),
  355. $this->getDebug(),
  356. $this->getUser(),
  357. // Request vary
  358. $this->getOnly(),
  359. $this->getVersion(),
  360. $this->getRaw(),
  361. $this->getImage(),
  362. $this->getVariant(),
  363. $this->getFormat(),
  364. ] );
  365. }
  366. return $this->hash;
  367. }
  368. }