ResourceLoaderWikiModule.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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\Linker\LinkTarget;
  23. use MediaWiki\Revision\RevisionRecord;
  24. use Wikimedia\Assert\Assert;
  25. use Wikimedia\Rdbms\Database;
  26. use Wikimedia\Rdbms\IDatabase;
  27. use MediaWiki\MediaWikiServices;
  28. /**
  29. * Abstraction for ResourceLoader modules which pull from wiki pages
  30. *
  31. * This can only be used for wiki pages in the MediaWiki and User namespaces,
  32. * because of its dependence on the functionality of Title::isUserConfigPage()
  33. * and Title::isSiteConfigPage().
  34. *
  35. * This module supports being used as a placeholder for a module on a remote wiki.
  36. * To do so, getDB() must be overloaded to return a foreign database object that
  37. * allows local wikis to query page metadata.
  38. *
  39. * Safe for calls on local wikis are:
  40. * - Option getters:
  41. * - getGroup()
  42. * - getPages()
  43. * - Basic methods that strictly involve the foreign database
  44. * - getDB()
  45. * - isKnownEmpty()
  46. * - getTitleInfo()
  47. *
  48. * @ingroup ResourceLoader
  49. * @since 1.17
  50. */
  51. class ResourceLoaderWikiModule extends ResourceLoaderModule {
  52. // Origin defaults to users with sitewide authority
  53. protected $origin = self::ORIGIN_USER_SITEWIDE;
  54. // In-process cache for title info, structured as an array
  55. // [
  56. // <batchKey> // Pipe-separated list of sorted keys from getPages
  57. // => [
  58. // <titleKey> => [ // Normalised title key
  59. // 'page_len' => ..,
  60. // 'page_latest' => ..,
  61. // 'page_touched' => ..,
  62. // ]
  63. // ]
  64. // ]
  65. // @see self::fetchTitleInfo()
  66. // @see self::makeTitleKey()
  67. protected $titleInfo = [];
  68. // List of page names that contain CSS
  69. protected $styles = [];
  70. // List of page names that contain JavaScript
  71. protected $scripts = [];
  72. // Group of module
  73. protected $group;
  74. /**
  75. * @param array|null $options For back-compat, this can be omitted in favour of overwriting
  76. * getPages.
  77. */
  78. public function __construct( array $options = null ) {
  79. if ( $options === null ) {
  80. return;
  81. }
  82. foreach ( $options as $member => $option ) {
  83. switch ( $member ) {
  84. case 'styles':
  85. case 'scripts':
  86. case 'group':
  87. case 'targets':
  88. $this->{$member} = $option;
  89. break;
  90. }
  91. }
  92. }
  93. /**
  94. * Subclasses should return an associative array of resources in the module.
  95. * Keys should be the title of a page in the MediaWiki or User namespace.
  96. *
  97. * Values should be a nested array of options. The supported keys are 'type' and
  98. * (CSS only) 'media'.
  99. *
  100. * For scripts, 'type' should be 'script'.
  101. *
  102. * For stylesheets, 'type' should be 'style'.
  103. * There is an optional media key, the value of which can be the
  104. * medium ('screen', 'print', etc.) of the stylesheet.
  105. *
  106. * @param ResourceLoaderContext $context
  107. * @return array
  108. */
  109. protected function getPages( ResourceLoaderContext $context ) {
  110. $config = $this->getConfig();
  111. $pages = [];
  112. // Filter out pages from origins not allowed by the current wiki configuration.
  113. if ( $config->get( 'UseSiteJs' ) ) {
  114. foreach ( $this->scripts as $script ) {
  115. $pages[$script] = [ 'type' => 'script' ];
  116. }
  117. }
  118. if ( $config->get( 'UseSiteCss' ) ) {
  119. foreach ( $this->styles as $style ) {
  120. $pages[$style] = [ 'type' => 'style' ];
  121. }
  122. }
  123. return $pages;
  124. }
  125. /**
  126. * Get group name
  127. *
  128. * @return string
  129. */
  130. public function getGroup() {
  131. return $this->group;
  132. }
  133. /**
  134. * Get the Database handle used for computing the module version.
  135. *
  136. * Subclasses may override this to return a foreign database, which would
  137. * allow them to register a module on wiki A that fetches wiki pages from
  138. * wiki B.
  139. *
  140. * The way this works is that the local module is a placeholder that can
  141. * only computer a module version hash. The 'source' of the module must
  142. * be set to the foreign wiki directly. Methods getScript() and getContent()
  143. * will not use this handle and are not valid on the local wiki.
  144. *
  145. * @return IDatabase
  146. */
  147. protected function getDB() {
  148. return wfGetDB( DB_REPLICA );
  149. }
  150. /**
  151. * @param string $titleText
  152. * @param ResourceLoaderContext $context
  153. * @return null|string
  154. * @since 1.32 added the $context parameter
  155. */
  156. protected function getContent( $titleText, ResourceLoaderContext $context ) {
  157. $title = Title::newFromText( $titleText );
  158. if ( !$title ) {
  159. return null; // Bad title
  160. }
  161. $content = $this->getContentObj( $title, $context );
  162. if ( !$content ) {
  163. return null; // No content found
  164. }
  165. $handler = $content->getContentHandler();
  166. if ( $handler->isSupportedFormat( CONTENT_FORMAT_CSS ) ) {
  167. $format = CONTENT_FORMAT_CSS;
  168. } elseif ( $handler->isSupportedFormat( CONTENT_FORMAT_JAVASCRIPT ) ) {
  169. $format = CONTENT_FORMAT_JAVASCRIPT;
  170. } else {
  171. return null; // Bad content model
  172. }
  173. return $content->serialize( $format );
  174. }
  175. /**
  176. * @param Title $title
  177. * @param ResourceLoaderContext $context
  178. * @param int|null $maxRedirects Maximum number of redirects to follow. If
  179. * null, uses $wgMaxRedirects
  180. * @return Content|null
  181. * @since 1.32 added the $context and $maxRedirects parameters
  182. */
  183. protected function getContentObj(
  184. Title $title, ResourceLoaderContext $context, $maxRedirects = null
  185. ) {
  186. $overrideCallback = $context->getContentOverrideCallback();
  187. $content = $overrideCallback ? call_user_func( $overrideCallback, $title ) : null;
  188. if ( $content ) {
  189. if ( !$content instanceof Content ) {
  190. $this->getLogger()->error(
  191. 'Bad content override for "{title}" in ' . __METHOD__,
  192. [ 'title' => $title->getPrefixedText() ]
  193. );
  194. return null;
  195. }
  196. } else {
  197. $revision = Revision::newKnownCurrent( wfGetDB( DB_REPLICA ), $title );
  198. if ( !$revision ) {
  199. return null;
  200. }
  201. $content = $revision->getContent( RevisionRecord::RAW );
  202. if ( !$content ) {
  203. $this->getLogger()->error(
  204. 'Failed to load content of JS/CSS page "{title}" in ' . __METHOD__,
  205. [ 'title' => $title->getPrefixedText() ]
  206. );
  207. return null;
  208. }
  209. }
  210. if ( $content && $content->isRedirect() ) {
  211. if ( $maxRedirects === null ) {
  212. $maxRedirects = $this->getConfig()->get( 'MaxRedirects' ) ?: 0;
  213. }
  214. if ( $maxRedirects > 0 ) {
  215. $newTitle = $content->getRedirectTarget();
  216. return $newTitle ? $this->getContentObj( $newTitle, $context, $maxRedirects - 1 ) : null;
  217. }
  218. }
  219. return $content;
  220. }
  221. /**
  222. * @param ResourceLoaderContext $context
  223. * @return bool
  224. */
  225. public function shouldEmbedModule( ResourceLoaderContext $context ) {
  226. $overrideCallback = $context->getContentOverrideCallback();
  227. if ( $overrideCallback && $this->getSource() === 'local' ) {
  228. foreach ( $this->getPages( $context ) as $page => $info ) {
  229. $title = Title::newFromText( $page );
  230. if ( $title && call_user_func( $overrideCallback, $title ) !== null ) {
  231. return true;
  232. }
  233. }
  234. }
  235. return parent::shouldEmbedModule( $context );
  236. }
  237. /**
  238. * @param ResourceLoaderContext $context
  239. * @return string JavaScript code
  240. */
  241. public function getScript( ResourceLoaderContext $context ) {
  242. $scripts = '';
  243. foreach ( $this->getPages( $context ) as $titleText => $options ) {
  244. if ( $options['type'] !== 'script' ) {
  245. continue;
  246. }
  247. $script = $this->getContent( $titleText, $context );
  248. if ( strval( $script ) !== '' ) {
  249. $script = $this->validateScriptFile( $titleText, $script );
  250. $scripts .= ResourceLoader::makeComment( $titleText ) . $script . "\n";
  251. }
  252. }
  253. return $scripts;
  254. }
  255. /**
  256. * @param ResourceLoaderContext $context
  257. * @return array
  258. */
  259. public function getStyles( ResourceLoaderContext $context ) {
  260. $styles = [];
  261. foreach ( $this->getPages( $context ) as $titleText => $options ) {
  262. if ( $options['type'] !== 'style' ) {
  263. continue;
  264. }
  265. $media = $options['media'] ?? 'all';
  266. $style = $this->getContent( $titleText, $context );
  267. if ( strval( $style ) === '' ) {
  268. continue;
  269. }
  270. if ( $this->getFlip( $context ) ) {
  271. $style = CSSJanus::transform( $style, true, false );
  272. }
  273. $style = MemoizedCallable::call( 'CSSMin::remap',
  274. [ $style, false, $this->getConfig()->get( 'ScriptPath' ), true ] );
  275. if ( !isset( $styles[$media] ) ) {
  276. $styles[$media] = [];
  277. }
  278. $style = ResourceLoader::makeComment( $titleText ) . $style;
  279. $styles[$media][] = $style;
  280. }
  281. return $styles;
  282. }
  283. /**
  284. * Disable module content versioning.
  285. *
  286. * This class does not support generating content outside of a module
  287. * request due to foreign database support.
  288. *
  289. * See getDefinitionSummary() for meta-data versioning.
  290. *
  291. * @return bool
  292. */
  293. public function enableModuleContentVersion() {
  294. return false;
  295. }
  296. /**
  297. * @param ResourceLoaderContext $context
  298. * @return array
  299. */
  300. public function getDefinitionSummary( ResourceLoaderContext $context ) {
  301. $summary = parent::getDefinitionSummary( $context );
  302. $summary[] = [
  303. 'pages' => $this->getPages( $context ),
  304. // Includes meta data of current revisions
  305. 'titleInfo' => $this->getTitleInfo( $context ),
  306. ];
  307. return $summary;
  308. }
  309. /**
  310. * @param ResourceLoaderContext $context
  311. * @return bool
  312. */
  313. public function isKnownEmpty( ResourceLoaderContext $context ) {
  314. $revisions = $this->getTitleInfo( $context );
  315. // If a module has dependencies it cannot be empty. An empty array will be cast to false
  316. if ( $this->getDependencies() ) {
  317. return false;
  318. }
  319. // For user modules, don't needlessly load if there are no non-empty pages
  320. if ( $this->getGroup() === 'user' ) {
  321. foreach ( $revisions as $revision ) {
  322. if ( $revision['page_len'] > 0 ) {
  323. // At least one non-empty page, module should be loaded
  324. return false;
  325. }
  326. }
  327. return true;
  328. }
  329. // T70488: For other modules (i.e. ones that are called in cached html output) only check
  330. // page existance. This ensures that, if some pages in a module are temporarily blanked,
  331. // we don't end omit the module's script or link tag on some pages.
  332. return count( $revisions ) === 0;
  333. }
  334. private function setTitleInfo( $batchKey, array $titleInfo ) {
  335. $this->titleInfo[$batchKey] = $titleInfo;
  336. }
  337. private static function makeTitleKey( LinkTarget $title ) {
  338. // Used for keys in titleInfo.
  339. return "{$title->getNamespace()}:{$title->getDBkey()}";
  340. }
  341. /**
  342. * Get the information about the wiki pages for a given context.
  343. * @param ResourceLoaderContext $context
  344. * @return array Keyed by page name
  345. */
  346. protected function getTitleInfo( ResourceLoaderContext $context ) {
  347. $dbr = $this->getDB();
  348. $pageNames = array_keys( $this->getPages( $context ) );
  349. sort( $pageNames );
  350. $batchKey = implode( '|', $pageNames );
  351. if ( !isset( $this->titleInfo[$batchKey] ) ) {
  352. $this->titleInfo[$batchKey] = static::fetchTitleInfo( $dbr, $pageNames, __METHOD__ );
  353. }
  354. $titleInfo = $this->titleInfo[$batchKey];
  355. // Override the title info from the overrides, if any
  356. $overrideCallback = $context->getContentOverrideCallback();
  357. if ( $overrideCallback ) {
  358. foreach ( $pageNames as $page ) {
  359. $title = Title::newFromText( $page );
  360. $content = $title ? call_user_func( $overrideCallback, $title ) : null;
  361. if ( $content !== null ) {
  362. $titleInfo[$title->getPrefixedText()] = [
  363. 'page_len' => $content->getSize(),
  364. 'page_latest' => 'TBD', // None available
  365. 'page_touched' => wfTimestamp( TS_MW ),
  366. ];
  367. }
  368. }
  369. }
  370. return $titleInfo;
  371. }
  372. /** @return array */
  373. protected static function fetchTitleInfo( IDatabase $db, array $pages, $fname = __METHOD__ ) {
  374. $titleInfo = [];
  375. $batch = new LinkBatch;
  376. foreach ( $pages as $titleText ) {
  377. $title = Title::newFromText( $titleText );
  378. if ( $title ) {
  379. // Page name may be invalid if user-provided (e.g. gadgets)
  380. $batch->addObj( $title );
  381. }
  382. }
  383. if ( !$batch->isEmpty() ) {
  384. $res = $db->select( 'page',
  385. // Include page_touched to allow purging if cache is poisoned (T117587, T113916)
  386. [ 'page_namespace', 'page_title', 'page_touched', 'page_len', 'page_latest' ],
  387. $batch->constructSet( 'page', $db ),
  388. $fname
  389. );
  390. foreach ( $res as $row ) {
  391. // Avoid including ids or timestamps of revision/page tables so
  392. // that versions are not wasted
  393. $title = new TitleValue( (int)$row->page_namespace, $row->page_title );
  394. $titleInfo[self::makeTitleKey( $title )] = [
  395. 'page_len' => $row->page_len,
  396. 'page_latest' => $row->page_latest,
  397. 'page_touched' => $row->page_touched,
  398. ];
  399. }
  400. }
  401. return $titleInfo;
  402. }
  403. /**
  404. * @since 1.28
  405. * @param ResourceLoaderContext $context
  406. * @param IDatabase $db
  407. * @param string[] $moduleNames
  408. */
  409. public static function preloadTitleInfo(
  410. ResourceLoaderContext $context, IDatabase $db, array $moduleNames
  411. ) {
  412. $rl = $context->getResourceLoader();
  413. // getDB() can be overridden to point to a foreign database.
  414. // For now, only preload local. In the future, we could preload by wikiID.
  415. $allPages = [];
  416. /** @var ResourceLoaderWikiModule[] $wikiModules */
  417. $wikiModules = [];
  418. foreach ( $moduleNames as $name ) {
  419. $module = $rl->getModule( $name );
  420. if ( $module instanceof self ) {
  421. $mDB = $module->getDB();
  422. // Subclasses may implement getDB differently
  423. if ( $mDB->getDomainID() === $db->getDomainID() ) {
  424. $wikiModules[] = $module;
  425. $allPages += $module->getPages( $context );
  426. }
  427. }
  428. }
  429. if ( !$wikiModules ) {
  430. // Nothing to preload
  431. return;
  432. }
  433. $pageNames = array_keys( $allPages );
  434. sort( $pageNames );
  435. $hash = sha1( implode( '|', $pageNames ) );
  436. // Avoid Zend bug where "static::" does not apply LSB in the closure
  437. $func = [ static::class, 'fetchTitleInfo' ];
  438. $fname = __METHOD__;
  439. $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
  440. $allInfo = $cache->getWithSetCallback(
  441. $cache->makeGlobalKey( 'resourceloader-titleinfo', $db->getDomainID(), $hash ),
  442. $cache::TTL_HOUR,
  443. function ( $curVal, &$ttl, array &$setOpts ) use ( $func, $pageNames, $db, $fname ) {
  444. $setOpts += Database::getCacheSetOptions( $db );
  445. return call_user_func( $func, $db, $pageNames, $fname );
  446. },
  447. [
  448. 'checkKeys' => [
  449. $cache->makeGlobalKey( 'resourceloader-titleinfo', $db->getDomainID() ) ]
  450. ]
  451. );
  452. foreach ( $wikiModules as $wikiModule ) {
  453. $pages = $wikiModule->getPages( $context );
  454. // Before we intersect, map the names to canonical form (T145673).
  455. $intersect = [];
  456. foreach ( $pages as $pageName => $unused ) {
  457. $title = Title::newFromText( $pageName );
  458. if ( $title ) {
  459. $intersect[ self::makeTitleKey( $title ) ] = 1;
  460. } else {
  461. // Page name may be invalid if user-provided (e.g. gadgets)
  462. $rl->getLogger()->info(
  463. 'Invalid wiki page title "{title}" in ' . __METHOD__,
  464. [ 'title' => $pageName ]
  465. );
  466. }
  467. }
  468. $info = array_intersect_key( $allInfo, $intersect );
  469. $pageNames = array_keys( $pages );
  470. sort( $pageNames );
  471. $batchKey = implode( '|', $pageNames );
  472. $wikiModule->setTitleInfo( $batchKey, $info );
  473. }
  474. }
  475. /**
  476. * Clear the preloadTitleInfo() cache for all wiki modules on this wiki on
  477. * page change if it was a JS or CSS page
  478. *
  479. * @param Title $title
  480. * @param Revision|null $old Prior page revision
  481. * @param Revision|null $new New page revision
  482. * @param string $domain Database domain ID
  483. * @since 1.28
  484. */
  485. public static function invalidateModuleCache(
  486. Title $title, Revision $old = null, Revision $new = null, $domain
  487. ) {
  488. static $formats = [ CONTENT_FORMAT_CSS, CONTENT_FORMAT_JAVASCRIPT ];
  489. Assert::parameterType( 'string', $domain, '$domain' );
  490. // TODO: MCR: differentiate between page functionality and content model!
  491. // Not all pages containing CSS or JS have to be modules! [PageType]
  492. if ( $old && in_array( $old->getContentFormat(), $formats ) ) {
  493. $purge = true;
  494. } elseif ( $new && in_array( $new->getContentFormat(), $formats ) ) {
  495. $purge = true;
  496. } else {
  497. $purge = ( $title->isSiteConfigPage() || $title->isUserConfigPage() );
  498. }
  499. if ( $purge ) {
  500. $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
  501. $key = $cache->makeGlobalKey( 'resourceloader-titleinfo', $domain );
  502. $cache->touchCheckKey( $key );
  503. }
  504. }
  505. /**
  506. * @since 1.28
  507. * @return string
  508. */
  509. public function getType() {
  510. // Check both because subclasses don't always pass pages via the constructor,
  511. // they may also override getPages() instead, in which case we should keep
  512. // defaulting to LOAD_GENERAL and allow them to override getType() separately.
  513. return ( $this->styles && !$this->scripts ) ? self::LOAD_STYLES : self::LOAD_GENERAL;
  514. }
  515. }