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\Rdbms\Database
;
27 use Wikimedia\Rdbms\IDatabase
;
30 * Abstraction for ResourceLoader modules which pull from wiki pages
32 * This can only be used for wiki pages in the MediaWiki and User namespaces,
33 * because of its dependence on the functionality of Title::isUserConfigPage()
34 * and Title::isSiteConfigPage().
36 * This module supports being used as a placeholder for a module on a remote wiki.
37 * To do so, getDB() must be overloaded to return a foreign database object that
38 * allows local wikis to query page metadata.
40 * Safe for calls on local wikis are:
44 * - Basic methods that strictly involve the foreign database
49 class ResourceLoaderWikiModule
extends ResourceLoaderModule
{
51 // Origin defaults to users with sitewide authority
52 protected $origin = self
::ORIGIN_USER_SITEWIDE
;
54 // In-process cache for title info, structured as an array
56 // <batchKey> // Pipe-separated list of sorted keys from getPages
58 // <titleKey> => [ // Normalised title key
60 // 'page_latest' => ..,
61 // 'page_touched' => ..,
65 // @see self::fetchTitleInfo()
66 // @see self::makeTitleKey()
67 protected $titleInfo = [];
69 // List of page names that contain CSS
70 protected $styles = [];
72 // List of page names that contain JavaScript
73 protected $scripts = [];
79 * @param array $options For back-compat, this can be omitted in favour of overwriting getPages.
81 public function __construct( array $options = null ) {
82 if ( is_null( $options ) ) {
86 foreach ( $options as $member => $option ) {
92 $this->{$member} = $option;
99 * Subclasses should return an associative array of resources in the module.
100 * Keys should be the title of a page in the MediaWiki or User namespace.
102 * Values should be a nested array of options. The supported keys are 'type' and
103 * (CSS only) 'media'.
105 * For scripts, 'type' should be 'script'.
107 * For stylesheets, 'type' should be 'style'.
108 * There is an optional media key, the value of which can be the
109 * medium ('screen', 'print', etc.) of the stylesheet.
111 * @param ResourceLoaderContext $context
114 protected function getPages( ResourceLoaderContext
$context ) {
115 $config = $this->getConfig();
118 // Filter out pages from origins not allowed by the current wiki configuration.
119 if ( $config->get( 'UseSiteJs' ) ) {
120 foreach ( $this->scripts
as $script ) {
121 $pages[$script] = [ 'type' => 'script' ];
125 if ( $config->get( 'UseSiteCss' ) ) {
126 foreach ( $this->styles
as $style ) {
127 $pages[$style] = [ 'type' => 'style' ];
139 public function getGroup() {
144 * Get the Database object used in getTitleInfo().
146 * Defaults to the local replica DB. Subclasses may want to override this to return a foreign
147 * database object, or null if getTitleInfo() shouldn't access the database.
149 * NOTE: This ONLY works for getTitleInfo() and isKnownEmpty(), NOT FOR ANYTHING ELSE.
150 * In particular, it doesn't work for getContent() or getScript() etc.
152 * @return IDatabase|null
154 protected function getDB() {
155 return wfGetDB( DB_REPLICA
);
159 * @param string $titleText
160 * @param ResourceLoaderContext|null $context (but passing null is deprecated)
161 * @return null|string
162 * @since 1.32 added the $context parameter
164 protected function getContent( $titleText, ResourceLoaderContext
$context = null ) {
165 $title = Title
::newFromText( $titleText );
167 return null; // Bad title
170 $content = $this->getContentObj( $title, $context );
172 return null; // No content found
175 $handler = $content->getContentHandler();
176 if ( $handler->isSupportedFormat( CONTENT_FORMAT_CSS
) ) {
177 $format = CONTENT_FORMAT_CSS
;
178 } elseif ( $handler->isSupportedFormat( CONTENT_FORMAT_JAVASCRIPT
) ) {
179 $format = CONTENT_FORMAT_JAVASCRIPT
;
181 return null; // Bad content model
184 return $content->serialize( $format );
188 * @param Title $title
189 * @param ResourceLoaderContext|null $context (but passing null is deprecated)
190 * @param int|null $maxRedirects Maximum number of redirects to follow. If
191 * null, uses $wgMaxRedirects
192 * @return Content|null
193 * @since 1.32 added the $context and $maxRedirects parameters
195 protected function getContentObj(
196 Title
$title, ResourceLoaderContext
$context = null, $maxRedirects = null
198 if ( $context === null ) {
199 wfDeprecated( __METHOD__
. ' without a ResourceLoader context', '1.32' );
202 $overrideCallback = $context ?
$context->getContentOverrideCallback() : null;
203 $content = $overrideCallback ?
call_user_func( $overrideCallback, $title ) : null;
205 if ( !$content instanceof Content
) {
206 $this->getLogger()->error(
207 'Bad content override for "{title}" in ' . __METHOD__
,
208 [ 'title' => $title->getPrefixedText() ]
213 $revision = Revision
::newKnownCurrent( wfGetDB( DB_REPLICA
), $title );
217 $content = $revision->getContent( Revision
::RAW
);
220 $this->getLogger()->error(
221 'Failed to load content of JS/CSS page "{title}" in ' . __METHOD__
,
222 [ 'title' => $title->getPrefixedText() ]
228 if ( $content && $content->isRedirect() ) {
229 if ( $maxRedirects === null ) {
230 $maxRedirects = $this->getConfig()->get( 'MaxRedirects' ) ?
: 0;
232 if ( $maxRedirects > 0 ) {
233 $newTitle = $content->getRedirectTarget();
234 return $newTitle ?
$this->getContentObj( $newTitle, $context, $maxRedirects - 1 ) : null;
242 * @param ResourceLoaderContext $context
245 public function shouldEmbedModule( ResourceLoaderContext
$context ) {
246 $overrideCallback = $context->getContentOverrideCallback();
247 if ( $overrideCallback && $this->getSource() === 'local' ) {
248 foreach ( $this->getPages( $context ) as $page => $info ) {
249 $title = Title
::newFromText( $page );
250 if ( $title && call_user_func( $overrideCallback, $title ) !== null ) {
256 return parent
::shouldEmbedModule( $context );
260 * @param ResourceLoaderContext $context
261 * @return string JavaScript code
263 public function getScript( ResourceLoaderContext
$context ) {
265 foreach ( $this->getPages( $context ) as $titleText => $options ) {
266 if ( $options['type'] !== 'script' ) {
269 $script = $this->getContent( $titleText, $context );
270 if ( strval( $script ) !== '' ) {
271 $script = $this->validateScriptFile( $titleText, $script );
272 $scripts .= ResourceLoader
::makeComment( $titleText ) . $script . "\n";
279 * @param ResourceLoaderContext $context
282 public function getStyles( ResourceLoaderContext
$context ) {
284 foreach ( $this->getPages( $context ) as $titleText => $options ) {
285 if ( $options['type'] !== 'style' ) {
288 $media = isset( $options['media'] ) ?
$options['media'] : 'all';
289 $style = $this->getContent( $titleText, $context );
290 if ( strval( $style ) === '' ) {
293 if ( $this->getFlip( $context ) ) {
294 $style = CSSJanus
::transform( $style, true, false );
296 $style = MemoizedCallable
::call( 'CSSMin::remap',
297 [ $style, false, $this->getConfig()->get( 'ScriptPath' ), true ] );
298 if ( !isset( $styles[$media] ) ) {
299 $styles[$media] = [];
301 $style = ResourceLoader
::makeComment( $titleText ) . $style;
302 $styles[$media][] = $style;
308 * Disable module content versioning.
310 * This class does not support generating content outside of a module
311 * request due to foreign database support.
313 * See getDefinitionSummary() for meta-data versioning.
317 public function enableModuleContentVersion() {
322 * @param ResourceLoaderContext $context
325 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
326 $summary = parent
::getDefinitionSummary( $context );
328 'pages' => $this->getPages( $context ),
329 // Includes meta data of current revisions
330 'titleInfo' => $this->getTitleInfo( $context ),
336 * @param ResourceLoaderContext $context
339 public function isKnownEmpty( ResourceLoaderContext
$context ) {
340 $revisions = $this->getTitleInfo( $context );
342 // If a module has dependencies it cannot be empty. An empty array will be cast to false
343 if ( $this->getDependencies() ) {
346 // For user modules, don't needlessly load if there are no non-empty pages
347 if ( $this->getGroup() === 'user' ) {
348 foreach ( $revisions as $revision ) {
349 if ( $revision['page_len'] > 0 ) {
350 // At least one non-empty page, module should be loaded
357 // T70488: For other modules (i.e. ones that are called in cached html output) only check
358 // page existance. This ensures that, if some pages in a module are temporarily blanked,
359 // we don't end omit the module's script or link tag on some pages.
360 return count( $revisions ) === 0;
363 private function setTitleInfo( $batchKey, array $titleInfo ) {
364 $this->titleInfo
[$batchKey] = $titleInfo;
367 private static function makeTitleKey( LinkTarget
$title ) {
368 // Used for keys in titleInfo.
369 return "{$title->getNamespace()}:{$title->getDBkey()}";
373 * Get the information about the wiki pages for a given context.
374 * @param ResourceLoaderContext $context
375 * @return array Keyed by page name
377 protected function getTitleInfo( ResourceLoaderContext
$context ) {
378 $dbr = $this->getDB();
380 // We're dealing with a subclass that doesn't have a DB
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
),
412 protected static function fetchTitleInfo( IDatabase
$db, array $pages, $fname = __METHOD__
) {
414 $batch = new LinkBatch
;
415 foreach ( $pages as $titleText ) {
416 $title = Title
::newFromText( $titleText );
418 // Page name may be invalid if user-provided (e.g. gadgets)
419 $batch->addObj( $title );
422 if ( !$batch->isEmpty() ) {
423 $res = $db->select( 'page',
424 // Include page_touched to allow purging if cache is poisoned (T117587, T113916)
425 [ 'page_namespace', 'page_title', 'page_touched', 'page_len', 'page_latest' ],
426 $batch->constructSet( 'page', $db ),
429 foreach ( $res as $row ) {
430 // Avoid including ids or timestamps of revision/page tables so
431 // that versions are not wasted
432 $title = new TitleValue( (int)$row->page_namespace
, $row->page_title
);
433 $titleInfo[ self
::makeTitleKey( $title ) ] = [
434 'page_len' => $row->page_len
,
435 'page_latest' => $row->page_latest
,
436 'page_touched' => $row->page_touched
,
445 * @param ResourceLoaderContext $context
446 * @param IDatabase $db
447 * @param string[] $moduleNames
449 public static function preloadTitleInfo(
450 ResourceLoaderContext
$context, IDatabase
$db, array $moduleNames
452 $rl = $context->getResourceLoader();
453 // getDB() can be overridden to point to a foreign database.
454 // For now, only preload local. In the future, we could preload by wikiID.
456 /** @var ResourceLoaderWikiModule[] $wikiModules */
458 foreach ( $moduleNames as $name ) {
459 $module = $rl->getModule( $name );
460 if ( $module instanceof self
) {
461 $mDB = $module->getDB();
462 // Subclasses may disable getDB and implement getTitleInfo differently
463 if ( $mDB && $mDB->getDomainID() === $db->getDomainID() ) {
464 $wikiModules[] = $module;
465 $allPages +
= $module->getPages( $context );
470 if ( !$wikiModules ) {
471 // Nothing to preload
475 $pageNames = array_keys( $allPages );
477 $hash = sha1( implode( '|', $pageNames ) );
479 // Avoid Zend bug where "static::" does not apply LSB in the closure
480 $func = [ static::class, 'fetchTitleInfo' ];
483 $cache = ObjectCache
::getMainWANInstance();
484 $allInfo = $cache->getWithSetCallback(
485 $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $db->getDomainID(), $hash ),
487 function ( $curVal, &$ttl, array &$setOpts ) use ( $func, $pageNames, $db, $fname ) {
488 $setOpts +
= Database
::getCacheSetOptions( $db );
490 return call_user_func( $func, $db, $pageNames, $fname );
494 $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $db->getDomainID() ) ]
498 foreach ( $wikiModules as $wikiModule ) {
499 $pages = $wikiModule->getPages( $context );
500 // Before we intersect, map the names to canonical form (T145673).
502 foreach ( $pages as $pageName => $unused ) {
503 $title = Title
::newFromText( $pageName );
505 $intersect[ self
::makeTitleKey( $title ) ] = 1;
507 // Page name may be invalid if user-provided (e.g. gadgets)
508 $rl->getLogger()->info(
509 'Invalid wiki page title "{title}" in ' . __METHOD__
,
510 [ 'title' => $pageName ]
514 $info = array_intersect_key( $allInfo, $intersect );
515 $pageNames = array_keys( $pages );
517 $batchKey = implode( '|', $pageNames );
518 $wikiModule->setTitleInfo( $batchKey, $info );
523 * Clear the preloadTitleInfo() cache for all wiki modules on this wiki on
524 * page change if it was a JS or CSS page
526 * @param Title $title
527 * @param Revision|null $old Prior page revision
528 * @param Revision|null $new New page revision
529 * @param string $wikiId
532 public static function invalidateModuleCache(
533 Title
$title, Revision
$old = null, Revision
$new = null, $wikiId
535 static $formats = [ CONTENT_FORMAT_CSS
, CONTENT_FORMAT_JAVASCRIPT
];
537 if ( $old && in_array( $old->getContentFormat(), $formats ) ) {
539 } elseif ( $new && in_array( $new->getContentFormat(), $formats ) ) {
542 $purge = ( $title->isSiteConfigPage() ||
$title->isUserConfigPage() );
546 $cache = ObjectCache
::getMainWANInstance();
547 $key = $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $wikiId );
548 $cache->touchCheckKey( $key );
556 public function getType() {
557 // Check both because subclasses don't always pass pages via the constructor,
558 // they may also override getPages() instead, in which case we should keep
559 // defaulting to LOAD_GENERAL and allow them to override getType() separately.
560 return ( $this->styles
&& !$this->scripts
) ? self
::LOAD_STYLES
: self
::LOAD_GENERAL
;