3 * Abstraction for ResourceLoader modules that pull from wiki pages.
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.
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.
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
21 * @author Trevor Parscal
22 * @author Roan Kattouw
25 use MediaWiki\Linker\LinkTarget
;
26 use Wikimedia\Assert\Assert
;
27 use Wikimedia\Rdbms\Database
;
28 use Wikimedia\Rdbms\IDatabase
;
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 class ResourceLoaderWikiModule
extends ResourceLoaderModule
{
52 // Origin defaults to users with sitewide authority
53 protected $origin = self
::ORIGIN_USER_SITEWIDE
;
55 // In-process cache for title info, structured as an array
57 // <batchKey> // Pipe-separated list of sorted keys from getPages
59 // <titleKey> => [ // Normalised title key
61 // 'page_latest' => ..,
62 // 'page_touched' => ..,
66 // @see self::fetchTitleInfo()
67 // @see self::makeTitleKey()
68 protected $titleInfo = [];
70 // List of page names that contain CSS
71 protected $styles = [];
73 // List of page names that contain JavaScript
74 protected $scripts = [];
80 * @param array|null $options For back-compat, this can be omitted in favour of overwriting
83 public function __construct( array $options = null ) {
84 if ( is_null( $options ) ) {
88 foreach ( $options as $member => $option ) {
94 $this->{$member} = $option;
101 * Subclasses should return an associative array of resources in the module.
102 * Keys should be the title of a page in the MediaWiki or User namespace.
104 * Values should be a nested array of options. The supported keys are 'type' and
105 * (CSS only) 'media'.
107 * For scripts, 'type' should be 'script'.
109 * For stylesheets, 'type' should be 'style'.
110 * There is an optional media key, the value of which can be the
111 * medium ('screen', 'print', etc.) of the stylesheet.
113 * @param ResourceLoaderContext $context
116 protected function getPages( ResourceLoaderContext
$context ) {
117 $config = $this->getConfig();
120 // Filter out pages from origins not allowed by the current wiki configuration.
121 if ( $config->get( 'UseSiteJs' ) ) {
122 foreach ( $this->scripts
as $script ) {
123 $pages[$script] = [ 'type' => 'script' ];
127 if ( $config->get( 'UseSiteCss' ) ) {
128 foreach ( $this->styles
as $style ) {
129 $pages[$style] = [ 'type' => 'style' ];
141 public function getGroup() {
146 * Get the Database object used in getTitleInfo().
148 * Defaults to the local replica DB. Subclasses may want to override this to return a foreign
149 * database object, or null if getTitleInfo() shouldn't access the database.
151 * NOTE: This ONLY works for getTitleInfo() and isKnownEmpty(), NOT FOR ANYTHING ELSE.
152 * In particular, it doesn't work for getContent() or getScript() etc.
154 * @return IDatabase|null
156 protected function getDB() {
157 return wfGetDB( DB_REPLICA
);
161 * @param string $titleText
162 * @param ResourceLoaderContext|null $context (but passing null is deprecated)
163 * @return null|string
164 * @since 1.32 added the $context parameter
166 protected function getContent( $titleText, ResourceLoaderContext
$context = null ) {
167 $title = Title
::newFromText( $titleText );
169 return null; // Bad title
172 $content = $this->getContentObj( $title, $context );
174 return null; // No content found
177 $handler = $content->getContentHandler();
178 if ( $handler->isSupportedFormat( CONTENT_FORMAT_CSS
) ) {
179 $format = CONTENT_FORMAT_CSS
;
180 } elseif ( $handler->isSupportedFormat( CONTENT_FORMAT_JAVASCRIPT
) ) {
181 $format = CONTENT_FORMAT_JAVASCRIPT
;
183 return null; // Bad content model
186 return $content->serialize( $format );
190 * @param Title $title
191 * @param ResourceLoaderContext|null $context (but passing null is deprecated)
192 * @param int|null $maxRedirects Maximum number of redirects to follow. If
193 * null, uses $wgMaxRedirects
194 * @return Content|null
195 * @since 1.32 added the $context and $maxRedirects parameters
197 protected function getContentObj(
198 Title
$title, ResourceLoaderContext
$context = null, $maxRedirects = null
200 if ( $context === null ) {
201 wfDeprecated( __METHOD__
. ' without a ResourceLoader context', '1.32' );
204 $overrideCallback = $context ?
$context->getContentOverrideCallback() : null;
205 $content = $overrideCallback ?
call_user_func( $overrideCallback, $title ) : null;
207 if ( !$content instanceof Content
) {
208 $this->getLogger()->error(
209 'Bad content override for "{title}" in ' . __METHOD__
,
210 [ 'title' => $title->getPrefixedText() ]
215 $revision = Revision
::newKnownCurrent( wfGetDB( DB_REPLICA
), $title );
219 $content = $revision->getContent( Revision
::RAW
);
222 $this->getLogger()->error(
223 'Failed to load content of JS/CSS page "{title}" in ' . __METHOD__
,
224 [ 'title' => $title->getPrefixedText() ]
230 if ( $content && $content->isRedirect() ) {
231 if ( $maxRedirects === null ) {
232 $maxRedirects = $this->getConfig()->get( 'MaxRedirects' ) ?
: 0;
234 if ( $maxRedirects > 0 ) {
235 $newTitle = $content->getRedirectTarget();
236 return $newTitle ?
$this->getContentObj( $newTitle, $context, $maxRedirects - 1 ) : null;
244 * @param ResourceLoaderContext $context
247 public function shouldEmbedModule( ResourceLoaderContext
$context ) {
248 $overrideCallback = $context->getContentOverrideCallback();
249 if ( $overrideCallback && $this->getSource() === 'local' ) {
250 foreach ( $this->getPages( $context ) as $page => $info ) {
251 $title = Title
::newFromText( $page );
252 if ( $title && call_user_func( $overrideCallback, $title ) !== null ) {
258 return parent
::shouldEmbedModule( $context );
262 * @param ResourceLoaderContext $context
263 * @return string JavaScript code
265 public function getScript( ResourceLoaderContext
$context ) {
267 foreach ( $this->getPages( $context ) as $titleText => $options ) {
268 if ( $options['type'] !== 'script' ) {
271 $script = $this->getContent( $titleText, $context );
272 if ( strval( $script ) !== '' ) {
273 $script = $this->validateScriptFile( $titleText, $script );
274 $scripts .= ResourceLoader
::makeComment( $titleText ) . $script . "\n";
281 * @param ResourceLoaderContext $context
284 public function getStyles( ResourceLoaderContext
$context ) {
286 foreach ( $this->getPages( $context ) as $titleText => $options ) {
287 if ( $options['type'] !== 'style' ) {
290 $media = $options['media'] ??
'all';
291 $style = $this->getContent( $titleText, $context );
292 if ( strval( $style ) === '' ) {
295 if ( $this->getFlip( $context ) ) {
296 $style = CSSJanus
::transform( $style, true, false );
298 $style = MemoizedCallable
::call( 'CSSMin::remap',
299 [ $style, false, $this->getConfig()->get( 'ScriptPath' ), true ] );
300 if ( !isset( $styles[$media] ) ) {
301 $styles[$media] = [];
303 $style = ResourceLoader
::makeComment( $titleText ) . $style;
304 $styles[$media][] = $style;
310 * Disable module content versioning.
312 * This class does not support generating content outside of a module
313 * request due to foreign database support.
315 * See getDefinitionSummary() for meta-data versioning.
319 public function enableModuleContentVersion() {
324 * @param ResourceLoaderContext $context
327 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
328 $summary = parent
::getDefinitionSummary( $context );
330 'pages' => $this->getPages( $context ),
331 // Includes meta data of current revisions
332 'titleInfo' => $this->getTitleInfo( $context ),
338 * @param ResourceLoaderContext $context
341 public function isKnownEmpty( ResourceLoaderContext
$context ) {
342 $revisions = $this->getTitleInfo( $context );
344 // If a module has dependencies it cannot be empty. An empty array will be cast to false
345 if ( $this->getDependencies() ) {
348 // For user modules, don't needlessly load if there are no non-empty pages
349 if ( $this->getGroup() === 'user' ) {
350 foreach ( $revisions as $revision ) {
351 if ( $revision['page_len'] > 0 ) {
352 // At least one non-empty page, module should be loaded
359 // T70488: For other modules (i.e. ones that are called in cached html output) only check
360 // page existance. This ensures that, if some pages in a module are temporarily blanked,
361 // we don't end omit the module's script or link tag on some pages.
362 return count( $revisions ) === 0;
365 private function setTitleInfo( $batchKey, array $titleInfo ) {
366 $this->titleInfo
[$batchKey] = $titleInfo;
369 private static function makeTitleKey( LinkTarget
$title ) {
370 // Used for keys in titleInfo.
371 return "{$title->getNamespace()}:{$title->getDBkey()}";
375 * Get the information about the wiki pages for a given context.
376 * @param ResourceLoaderContext $context
377 * @return array Keyed by page name
379 protected function getTitleInfo( ResourceLoaderContext
$context ) {
380 $dbr = $this->getDB();
382 // We're dealing with a subclass that doesn't have a DB
386 $pageNames = array_keys( $this->getPages( $context ) );
388 $batchKey = implode( '|', $pageNames );
389 if ( !isset( $this->titleInfo
[$batchKey] ) ) {
390 $this->titleInfo
[$batchKey] = static::fetchTitleInfo( $dbr, $pageNames, __METHOD__
);
393 $titleInfo = $this->titleInfo
[$batchKey];
395 // Override the title info from the overrides, if any
396 $overrideCallback = $context->getContentOverrideCallback();
397 if ( $overrideCallback ) {
398 foreach ( $pageNames as $page ) {
399 $title = Title
::newFromText( $page );
400 $content = $title ?
call_user_func( $overrideCallback, $title ) : null;
401 if ( $content !== null ) {
402 $titleInfo[$title->getPrefixedText()] = [
403 'page_len' => $content->getSize(),
404 'page_latest' => 'TBD', // None available
405 'page_touched' => wfTimestamp( TS_MW
),
414 protected static function fetchTitleInfo( IDatabase
$db, array $pages, $fname = __METHOD__
) {
416 $batch = new LinkBatch
;
417 foreach ( $pages as $titleText ) {
418 $title = Title
::newFromText( $titleText );
420 // Page name may be invalid if user-provided (e.g. gadgets)
421 $batch->addObj( $title );
424 if ( !$batch->isEmpty() ) {
425 $res = $db->select( 'page',
426 // Include page_touched to allow purging if cache is poisoned (T117587, T113916)
427 [ 'page_namespace', 'page_title', 'page_touched', 'page_len', 'page_latest' ],
428 $batch->constructSet( 'page', $db ),
431 foreach ( $res as $row ) {
432 // Avoid including ids or timestamps of revision/page tables so
433 // that versions are not wasted
434 $title = new TitleValue( (int)$row->page_namespace
, $row->page_title
);
435 $titleInfo[ self
::makeTitleKey( $title ) ] = [
436 'page_len' => $row->page_len
,
437 'page_latest' => $row->page_latest
,
438 'page_touched' => $row->page_touched
,
447 * @param ResourceLoaderContext $context
448 * @param IDatabase $db
449 * @param string[] $moduleNames
451 public static function preloadTitleInfo(
452 ResourceLoaderContext
$context, IDatabase
$db, array $moduleNames
454 $rl = $context->getResourceLoader();
455 // getDB() can be overridden to point to a foreign database.
456 // For now, only preload local. In the future, we could preload by wikiID.
458 /** @var ResourceLoaderWikiModule[] $wikiModules */
460 foreach ( $moduleNames as $name ) {
461 $module = $rl->getModule( $name );
462 if ( $module instanceof self
) {
463 $mDB = $module->getDB();
464 // Subclasses may disable getDB and implement getTitleInfo differently
465 if ( $mDB && $mDB->getDomainID() === $db->getDomainID() ) {
466 $wikiModules[] = $module;
467 $allPages +
= $module->getPages( $context );
472 if ( !$wikiModules ) {
473 // Nothing to preload
477 $pageNames = array_keys( $allPages );
479 $hash = sha1( implode( '|', $pageNames ) );
481 // Avoid Zend bug where "static::" does not apply LSB in the closure
482 $func = [ static::class, 'fetchTitleInfo' ];
485 $cache = ObjectCache
::getMainWANInstance();
486 $allInfo = $cache->getWithSetCallback(
487 $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $db->getDomainID(), $hash ),
489 function ( $curVal, &$ttl, array &$setOpts ) use ( $func, $pageNames, $db, $fname ) {
490 $setOpts +
= Database
::getCacheSetOptions( $db );
492 return call_user_func( $func, $db, $pageNames, $fname );
496 $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $db->getDomainID() ) ]
500 foreach ( $wikiModules as $wikiModule ) {
501 $pages = $wikiModule->getPages( $context );
502 // Before we intersect, map the names to canonical form (T145673).
504 foreach ( $pages as $pageName => $unused ) {
505 $title = Title
::newFromText( $pageName );
507 $intersect[ self
::makeTitleKey( $title ) ] = 1;
509 // Page name may be invalid if user-provided (e.g. gadgets)
510 $rl->getLogger()->info(
511 'Invalid wiki page title "{title}" in ' . __METHOD__
,
512 [ 'title' => $pageName ]
516 $info = array_intersect_key( $allInfo, $intersect );
517 $pageNames = array_keys( $pages );
519 $batchKey = implode( '|', $pageNames );
520 $wikiModule->setTitleInfo( $batchKey, $info );
525 * Clear the preloadTitleInfo() cache for all wiki modules on this wiki on
526 * page change if it was a JS or CSS page
528 * @param Title $title
529 * @param Revision|null $old Prior page revision
530 * @param Revision|null $new New page revision
531 * @param string $wikiId
534 public static function invalidateModuleCache(
535 Title
$title, Revision
$old = null, Revision
$new = null, $wikiId
537 static $formats = [ CONTENT_FORMAT_CSS
, CONTENT_FORMAT_JAVASCRIPT
];
539 Assert
::parameterType( 'string', $wikiId, '$wikiId' );
541 // TODO: MCR: differentiate between page functionality and content model!
542 // Not all pages containing CSS or JS have to be modules! [PageType]
543 if ( $old && in_array( $old->getContentFormat(), $formats ) ) {
545 } elseif ( $new && in_array( $new->getContentFormat(), $formats ) ) {
548 $purge = ( $title->isSiteConfigPage() ||
$title->isUserConfigPage() );
552 $cache = ObjectCache
::getMainWANInstance();
553 $key = $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $wikiId );
554 $cache->touchCheckKey( $key );
562 public function getType() {
563 // Check both because subclasses don't always pass pages via the constructor,
564 // they may also override getPages() instead, in which case we should keep
565 // defaulting to LOAD_GENERAL and allow them to override getType() separately.
566 return ( $this->styles
&& !$this->scripts
) ? self
::LOAD_STYLES
: self
::LOAD_GENERAL
;