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.
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.
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
19 * @author Trevor Parscal
20 * @author Roan Kattouw
23 use MediaWiki\Linker\LinkTarget
;
24 use MediaWiki\Revision\RevisionRecord
;
25 use Wikimedia\Assert\Assert
;
26 use Wikimedia\Rdbms\Database
;
27 use Wikimedia\Rdbms\IDatabase
;
28 use MediaWiki\MediaWikiServices
;
31 * Abstraction for ResourceLoader modules which pull from wiki pages
33 * This can only be used for wiki pages in the MediaWiki and User namespaces,
34 * because of its dependence on the functionality of Title::isUserConfigPage()
35 * and Title::isSiteConfigPage().
37 * This module supports being used as a placeholder for a module on a remote wiki.
38 * To do so, getDB() must be overloaded to return a foreign database object that
39 * allows local wikis to query page metadata.
41 * Safe for calls on local wikis are:
45 * - Basic methods that strictly involve the foreign database
50 * @ingroup ResourceLoader
53 class ResourceLoaderWikiModule
extends ResourceLoaderModule
{
55 // Origin defaults to users with sitewide authority
56 protected $origin = self
::ORIGIN_USER_SITEWIDE
;
58 // In-process cache for title info, structured as an array
60 // <batchKey> // Pipe-separated list of sorted keys from getPages
62 // <titleKey> => [ // Normalised title key
64 // 'page_latest' => ..,
65 // 'page_touched' => ..,
69 // @see self::fetchTitleInfo()
70 // @see self::makeTitleKey()
71 protected $titleInfo = [];
73 // List of page names that contain CSS
74 protected $styles = [];
76 // List of page names that contain JavaScript
77 protected $scripts = [];
83 * @param array|null $options For back-compat, this can be omitted in favour of overwriting
86 public function __construct( array $options = null ) {
87 if ( $options === null ) {
91 foreach ( $options as $member => $option ) {
97 $this->{$member} = $option;
104 * Subclasses should return an associative array of resources in the module.
105 * Keys should be the title of a page in the MediaWiki or User namespace.
107 * Values should be a nested array of options. The supported keys are 'type' and
108 * (CSS only) 'media'.
110 * For scripts, 'type' should be 'script'.
112 * For stylesheets, 'type' should be 'style'.
113 * There is an optional media key, the value of which can be the
114 * medium ('screen', 'print', etc.) of the stylesheet.
116 * @param ResourceLoaderContext $context
119 protected function getPages( ResourceLoaderContext
$context ) {
120 $config = $this->getConfig();
123 // Filter out pages from origins not allowed by the current wiki configuration.
124 if ( $config->get( 'UseSiteJs' ) ) {
125 foreach ( $this->scripts
as $script ) {
126 $pages[$script] = [ 'type' => 'script' ];
130 if ( $config->get( 'UseSiteCss' ) ) {
131 foreach ( $this->styles
as $style ) {
132 $pages[$style] = [ 'type' => 'style' ];
144 public function getGroup() {
149 * Get the Database handle used for computing the module version.
151 * Subclasses may override this to return a foreign database, which would
152 * allow them to register a module on wiki A that fetches wiki pages from
155 * The way this works is that the local module is a placeholder that can
156 * only computer a module version hash. The 'source' of the module must
157 * be set to the foreign wiki directly. Methods getScript() and getContent()
158 * will not use this handle and are not valid on the local wiki.
162 protected function getDB() {
163 return wfGetDB( DB_REPLICA
);
167 * @param string $titleText
168 * @param ResourceLoaderContext $context
169 * @return null|string
170 * @since 1.32 added the $context parameter
172 protected function getContent( $titleText, ResourceLoaderContext
$context ) {
173 $title = Title
::newFromText( $titleText );
175 return null; // Bad title
178 $content = $this->getContentObj( $title, $context );
180 return null; // No content found
183 $handler = $content->getContentHandler();
184 if ( $handler->isSupportedFormat( CONTENT_FORMAT_CSS
) ) {
185 $format = CONTENT_FORMAT_CSS
;
186 } elseif ( $handler->isSupportedFormat( CONTENT_FORMAT_JAVASCRIPT
) ) {
187 $format = CONTENT_FORMAT_JAVASCRIPT
;
189 return null; // Bad content model
192 return $content->serialize( $format );
196 * @param Title $title
197 * @param ResourceLoaderContext $context
198 * @param int|null $maxRedirects Maximum number of redirects to follow. If
199 * null, uses $wgMaxRedirects
200 * @return Content|null
201 * @since 1.32 added the $context and $maxRedirects parameters
203 protected function getContentObj(
204 Title
$title, ResourceLoaderContext
$context, $maxRedirects = null
206 $overrideCallback = $context->getContentOverrideCallback();
207 $content = $overrideCallback ?
call_user_func( $overrideCallback, $title ) : null;
209 if ( !$content instanceof Content
) {
210 $this->getLogger()->error(
211 'Bad content override for "{title}" in ' . __METHOD__
,
212 [ 'title' => $title->getPrefixedText() ]
217 $revision = Revision
::newKnownCurrent( wfGetDB( DB_REPLICA
), $title );
221 $content = $revision->getContent( RevisionRecord
::RAW
);
224 $this->getLogger()->error(
225 'Failed to load content of JS/CSS page "{title}" in ' . __METHOD__
,
226 [ 'title' => $title->getPrefixedText() ]
232 if ( $content && $content->isRedirect() ) {
233 if ( $maxRedirects === null ) {
234 $maxRedirects = $this->getConfig()->get( 'MaxRedirects' ) ?
: 0;
236 if ( $maxRedirects > 0 ) {
237 $newTitle = $content->getRedirectTarget();
238 return $newTitle ?
$this->getContentObj( $newTitle, $context, $maxRedirects - 1 ) : null;
246 * @param ResourceLoaderContext $context
249 public function shouldEmbedModule( ResourceLoaderContext
$context ) {
250 $overrideCallback = $context->getContentOverrideCallback();
251 if ( $overrideCallback && $this->getSource() === 'local' ) {
252 foreach ( $this->getPages( $context ) as $page => $info ) {
253 $title = Title
::newFromText( $page );
254 if ( $title && call_user_func( $overrideCallback, $title ) !== null ) {
260 return parent
::shouldEmbedModule( $context );
264 * @param ResourceLoaderContext $context
265 * @return string JavaScript code
267 public function getScript( ResourceLoaderContext
$context ) {
269 foreach ( $this->getPages( $context ) as $titleText => $options ) {
270 if ( $options['type'] !== 'script' ) {
273 $script = $this->getContent( $titleText, $context );
274 if ( strval( $script ) !== '' ) {
275 $script = $this->validateScriptFile( $titleText, $script );
276 $scripts .= ResourceLoader
::makeComment( $titleText ) . $script . "\n";
283 * @param ResourceLoaderContext $context
286 public function getStyles( ResourceLoaderContext
$context ) {
288 foreach ( $this->getPages( $context ) as $titleText => $options ) {
289 if ( $options['type'] !== 'style' ) {
292 $media = $options['media'] ??
'all';
293 $style = $this->getContent( $titleText, $context );
294 if ( strval( $style ) === '' ) {
297 if ( $this->getFlip( $context ) ) {
298 $style = CSSJanus
::transform( $style, true, false );
300 $style = MemoizedCallable
::call( 'CSSMin::remap',
301 [ $style, false, $this->getConfig()->get( 'ScriptPath' ), true ] );
302 if ( !isset( $styles[$media] ) ) {
303 $styles[$media] = [];
305 $style = ResourceLoader
::makeComment( $titleText ) . $style;
306 $styles[$media][] = $style;
312 * Disable module content versioning.
314 * This class does not support generating content outside of a module
315 * request due to foreign database support.
317 * See getDefinitionSummary() for meta-data versioning.
321 public function enableModuleContentVersion() {
326 * @param ResourceLoaderContext $context
329 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
330 $summary = parent
::getDefinitionSummary( $context );
332 'pages' => $this->getPages( $context ),
333 // Includes meta data of current revisions
334 'titleInfo' => $this->getTitleInfo( $context ),
340 * @param ResourceLoaderContext $context
343 public function isKnownEmpty( ResourceLoaderContext
$context ) {
344 $revisions = $this->getTitleInfo( $context );
346 // If a module has dependencies it cannot be empty. An empty array will be cast to false
347 if ( $this->getDependencies() ) {
350 // For user modules, don't needlessly load if there are no non-empty pages
351 if ( $this->getGroup() === 'user' ) {
352 foreach ( $revisions as $revision ) {
353 if ( $revision['page_len'] > 0 ) {
354 // At least one non-empty page, module should be loaded
361 // T70488: For other modules (i.e. ones that are called in cached html output) only check
362 // page existance. This ensures that, if some pages in a module are temporarily blanked,
363 // we don't end omit the module's script or link tag on some pages.
364 return count( $revisions ) === 0;
367 private function setTitleInfo( $batchKey, array $titleInfo ) {
368 $this->titleInfo
[$batchKey] = $titleInfo;
371 private static function makeTitleKey( LinkTarget
$title ) {
372 // Used for keys in titleInfo.
373 return "{$title->getNamespace()}:{$title->getDBkey()}";
377 * Get the information about the wiki pages for a given context.
378 * @param ResourceLoaderContext $context
379 * @return array Keyed by page name
381 protected function getTitleInfo( ResourceLoaderContext
$context ) {
382 $dbr = $this->getDB();
384 $pageNames = array_keys( $this->getPages( $context ) );
386 $batchKey = implode( '|', $pageNames );
387 if ( !isset( $this->titleInfo
[$batchKey] ) ) {
388 $this->titleInfo
[$batchKey] = static::fetchTitleInfo( $dbr, $pageNames, __METHOD__
);
391 $titleInfo = $this->titleInfo
[$batchKey];
393 // Override the title info from the overrides, if any
394 $overrideCallback = $context->getContentOverrideCallback();
395 if ( $overrideCallback ) {
396 foreach ( $pageNames as $page ) {
397 $title = Title
::newFromText( $page );
398 $content = $title ?
call_user_func( $overrideCallback, $title ) : null;
399 if ( $content !== null ) {
400 $titleInfo[$title->getPrefixedText()] = [
401 'page_len' => $content->getSize(),
402 'page_latest' => 'TBD', // None available
403 'page_touched' => wfTimestamp( TS_MW
),
413 protected static function fetchTitleInfo( IDatabase
$db, array $pages, $fname = __METHOD__
) {
415 $batch = new LinkBatch
;
416 foreach ( $pages as $titleText ) {
417 $title = Title
::newFromText( $titleText );
419 // Page name may be invalid if user-provided (e.g. gadgets)
420 $batch->addObj( $title );
423 if ( !$batch->isEmpty() ) {
424 $res = $db->select( 'page',
425 // Include page_touched to allow purging if cache is poisoned (T117587, T113916)
426 [ 'page_namespace', 'page_title', 'page_touched', 'page_len', 'page_latest' ],
427 $batch->constructSet( 'page', $db ),
430 foreach ( $res as $row ) {
431 // Avoid including ids or timestamps of revision/page tables so
432 // that versions are not wasted
433 $title = new TitleValue( (int)$row->page_namespace
, $row->page_title
);
434 $titleInfo[self
::makeTitleKey( $title )] = [
435 'page_len' => $row->page_len
,
436 'page_latest' => $row->page_latest
,
437 'page_touched' => $row->page_touched
,
446 * @param ResourceLoaderContext $context
447 * @param IDatabase $db
448 * @param string[] $moduleNames
450 public static function preloadTitleInfo(
451 ResourceLoaderContext
$context, IDatabase
$db, array $moduleNames
453 $rl = $context->getResourceLoader();
454 // getDB() can be overridden to point to a foreign database.
455 // For now, only preload local. In the future, we could preload by wikiID.
457 /** @var ResourceLoaderWikiModule[] $wikiModules */
459 foreach ( $moduleNames as $name ) {
460 $module = $rl->getModule( $name );
461 if ( $module instanceof self
) {
462 $mDB = $module->getDB();
463 // Subclasses may implement getDB differently
464 if ( $mDB->getDomainID() === $db->getDomainID() ) {
465 $wikiModules[] = $module;
466 $allPages +
= $module->getPages( $context );
471 if ( !$wikiModules ) {
472 // Nothing to preload
476 $pageNames = array_keys( $allPages );
478 $hash = sha1( implode( '|', $pageNames ) );
480 // Avoid Zend bug where "static::" does not apply LSB in the closure
481 $func = [ static::class, 'fetchTitleInfo' ];
484 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
485 $allInfo = $cache->getWithSetCallback(
486 $cache->makeGlobalKey( 'resourceloader-titleinfo', $db->getDomainID(), $hash ),
488 function ( $curVal, &$ttl, array &$setOpts ) use ( $func, $pageNames, $db, $fname ) {
489 $setOpts +
= Database
::getCacheSetOptions( $db );
491 return call_user_func( $func, $db, $pageNames, $fname );
495 $cache->makeGlobalKey( 'resourceloader-titleinfo', $db->getDomainID() ) ]
499 foreach ( $wikiModules as $wikiModule ) {
500 $pages = $wikiModule->getPages( $context );
501 // Before we intersect, map the names to canonical form (T145673).
503 foreach ( $pages as $pageName => $unused ) {
504 $title = Title
::newFromText( $pageName );
506 $intersect[ self
::makeTitleKey( $title ) ] = 1;
508 // Page name may be invalid if user-provided (e.g. gadgets)
509 $rl->getLogger()->info(
510 'Invalid wiki page title "{title}" in ' . __METHOD__
,
511 [ 'title' => $pageName ]
515 $info = array_intersect_key( $allInfo, $intersect );
516 $pageNames = array_keys( $pages );
518 $batchKey = implode( '|', $pageNames );
519 $wikiModule->setTitleInfo( $batchKey, $info );
524 * Clear the preloadTitleInfo() cache for all wiki modules on this wiki on
525 * page change if it was a JS or CSS page
527 * @param Title $title
528 * @param Revision|null $old Prior page revision
529 * @param Revision|null $new New page revision
530 * @param string $domain Database domain ID
533 public static function invalidateModuleCache(
534 Title
$title, Revision
$old = null, Revision
$new = null, $domain
536 static $formats = [ CONTENT_FORMAT_CSS
, CONTENT_FORMAT_JAVASCRIPT
];
538 Assert
::parameterType( 'string', $domain, '$domain' );
540 // TODO: MCR: differentiate between page functionality and content model!
541 // Not all pages containing CSS or JS have to be modules! [PageType]
542 if ( $old && in_array( $old->getContentFormat(), $formats ) ) {
544 } elseif ( $new && in_array( $new->getContentFormat(), $formats ) ) {
547 $purge = ( $title->isSiteConfigPage() ||
$title->isUserConfigPage() );
551 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
552 $key = $cache->makeGlobalKey( 'resourceloader-titleinfo', $domain );
553 $cache->touchCheckKey( $key );
561 public function getType() {
562 // Check both because subclasses don't always pass pages via the constructor,
563 // they may also override getPages() instead, in which case we should keep
564 // defaulting to LOAD_GENERAL and allow them to override getType() separately.
565 return ( $this->styles
&& !$this->scripts
) ? self
::LOAD_STYLES
: self
::LOAD_GENERAL
;