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 Wikimedia\Rdbms\Database
;
26 use Wikimedia\Rdbms\IDatabase
;
29 * Abstraction for ResourceLoader modules which pull from wiki pages
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().
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.
39 * Safe for calls on local wikis are:
43 * - Basic methods that strictly involve the foreign database
48 class ResourceLoaderWikiModule
extends ResourceLoaderModule
{
50 // Origin defaults to users with sitewide authority
51 protected $origin = self
::ORIGIN_USER_SITEWIDE
;
53 // In-process cache for title info
54 protected $titleInfo = [];
56 // List of page names that contain CSS
57 protected $styles = [];
59 // List of page names that contain JavaScript
60 protected $scripts = [];
66 * @param array $options For back-compat, this can be omitted in favour of overwriting getPages.
68 public function __construct( array $options = null ) {
69 if ( is_null( $options ) ) {
73 foreach ( $options as $member => $option ) {
79 $this->{$member} = $option;
86 * Subclasses should return an associative array of resources in the module.
87 * Keys should be the title of a page in the MediaWiki or User namespace.
89 * Values should be a nested array of options. The supported keys are 'type' and
92 * For scripts, 'type' should be 'script'.
94 * For stylesheets, 'type' should be 'style'.
95 * There is an optional media key, the value of which can be the
96 * medium ('screen', 'print', etc.) of the stylesheet.
98 * @param ResourceLoaderContext $context
101 protected function getPages( ResourceLoaderContext
$context ) {
102 $config = $this->getConfig();
105 // Filter out pages from origins not allowed by the current wiki configuration.
106 if ( $config->get( 'UseSiteJs' ) ) {
107 foreach ( $this->scripts
as $script ) {
108 $pages[$script] = [ 'type' => 'script' ];
112 if ( $config->get( 'UseSiteCss' ) ) {
113 foreach ( $this->styles
as $style ) {
114 $pages[$style] = [ 'type' => 'style' ];
126 public function getGroup() {
131 * Get the Database object used in getTitleInfo().
133 * Defaults to the local replica DB. Subclasses may want to override this to return a foreign
134 * database object, or null if getTitleInfo() shouldn't access the database.
136 * NOTE: This ONLY works for getTitleInfo() and isKnownEmpty(), NOT FOR ANYTHING ELSE.
137 * In particular, it doesn't work for getContent() or getScript() etc.
139 * @return IDatabase|null
141 protected function getDB() {
142 return wfGetDB( DB_REPLICA
);
146 * @param string $titleText
147 * @return null|string
149 protected function getContent( $titleText ) {
150 $title = Title
::newFromText( $titleText );
152 return null; // Bad title
155 // If the page is a redirect, follow the redirect.
156 if ( $title->isRedirect() ) {
157 $content = $this->getContentObj( $title );
158 $title = $content ?
$content->getUltimateRedirectTarget() : null;
160 return null; // Dead redirect
164 $handler = ContentHandler
::getForTitle( $title );
165 if ( $handler->isSupportedFormat( CONTENT_FORMAT_CSS
) ) {
166 $format = CONTENT_FORMAT_CSS
;
167 } elseif ( $handler->isSupportedFormat( CONTENT_FORMAT_JAVASCRIPT
) ) {
168 $format = CONTENT_FORMAT_JAVASCRIPT
;
170 return null; // Bad content model
173 $content = $this->getContentObj( $title );
175 return null; // No content found
178 return $content->serialize( $format );
182 * @param Title $title
183 * @return Content|null
185 protected function getContentObj( Title
$title ) {
186 $revision = Revision
::newKnownCurrent( wfGetDB( DB_REPLICA
), $title );
190 $content = $revision->getContent( Revision
::RAW
);
192 wfDebugLog( 'resourceloader', __METHOD__
. ': failed to load content of JS/CSS page!' );
199 * @param ResourceLoaderContext $context
200 * @return string JavaScript code
202 public function getScript( ResourceLoaderContext
$context ) {
204 foreach ( $this->getPages( $context ) as $titleText => $options ) {
205 if ( $options['type'] !== 'script' ) {
208 $script = $this->getContent( $titleText );
209 if ( strval( $script ) !== '' ) {
210 $script = $this->validateScriptFile( $titleText, $script );
211 $scripts .= ResourceLoader
::makeComment( $titleText ) . $script . "\n";
218 * @param ResourceLoaderContext $context
221 public function getStyles( ResourceLoaderContext
$context ) {
223 foreach ( $this->getPages( $context ) as $titleText => $options ) {
224 if ( $options['type'] !== 'style' ) {
227 $media = isset( $options['media'] ) ?
$options['media'] : 'all';
228 $style = $this->getContent( $titleText );
229 if ( strval( $style ) === '' ) {
232 if ( $this->getFlip( $context ) ) {
233 $style = CSSJanus
::transform( $style, true, false );
235 $style = MemoizedCallable
::call( 'CSSMin::remap',
236 [ $style, false, $this->getConfig()->get( 'ScriptPath' ), true ] );
237 if ( !isset( $styles[$media] ) ) {
238 $styles[$media] = [];
240 $style = ResourceLoader
::makeComment( $titleText ) . $style;
241 $styles[$media][] = $style;
247 * Disable module content versioning.
249 * This class does not support generating content outside of a module
250 * request due to foreign database support.
252 * See getDefinitionSummary() for meta-data versioning.
256 public function enableModuleContentVersion() {
261 * @param ResourceLoaderContext $context
264 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
265 $summary = parent
::getDefinitionSummary( $context );
267 'pages' => $this->getPages( $context ),
268 // Includes meta data of current revisions
269 'titleInfo' => $this->getTitleInfo( $context ),
275 * @param ResourceLoaderContext $context
278 public function isKnownEmpty( ResourceLoaderContext
$context ) {
279 $revisions = $this->getTitleInfo( $context );
281 // For user modules, don't needlessly load if there are no non-empty pages
282 if ( $this->getGroup() === 'user' ) {
283 foreach ( $revisions as $revision ) {
284 if ( $revision['page_len'] > 0 ) {
285 // At least one non-empty page, module should be loaded
292 // T70488: For other modules (i.e. ones that are called in cached html output) only check
293 // page existance. This ensures that, if some pages in a module are temporarily blanked,
294 // we don't end omit the module's script or link tag on some pages.
295 return count( $revisions ) === 0;
298 private function setTitleInfo( $key, array $titleInfo ) {
299 $this->titleInfo
[$key] = $titleInfo;
303 * Get the information about the wiki pages for a given context.
304 * @param ResourceLoaderContext $context
305 * @return array Keyed by page name
307 protected function getTitleInfo( ResourceLoaderContext
$context ) {
308 $dbr = $this->getDB();
310 // We're dealing with a subclass that doesn't have a DB
314 $pageNames = array_keys( $this->getPages( $context ) );
316 $key = implode( '|', $pageNames );
317 if ( !isset( $this->titleInfo
[$key] ) ) {
318 $this->titleInfo
[$key] = static::fetchTitleInfo( $dbr, $pageNames, __METHOD__
);
320 return $this->titleInfo
[$key];
323 protected static function fetchTitleInfo( IDatabase
$db, array $pages, $fname = __METHOD__
) {
325 $batch = new LinkBatch
;
326 foreach ( $pages as $titleText ) {
327 $title = Title
::newFromText( $titleText );
329 // Page name may be invalid if user-provided (e.g. gadgets)
330 $batch->addObj( $title );
333 if ( !$batch->isEmpty() ) {
334 $res = $db->select( 'page',
335 // Include page_touched to allow purging if cache is poisoned (T117587, T113916)
336 [ 'page_namespace', 'page_title', 'page_touched', 'page_len', 'page_latest' ],
337 $batch->constructSet( 'page', $db ),
340 foreach ( $res as $row ) {
341 // Avoid including ids or timestamps of revision/page tables so
342 // that versions are not wasted
343 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
344 $titleInfo[$title->getPrefixedText()] = [
345 'page_len' => $row->page_len
,
346 'page_latest' => $row->page_latest
,
347 'page_touched' => $row->page_touched
,
356 * @param ResourceLoaderContext $context
357 * @param IDatabase $db
358 * @param string[] $moduleNames
360 public static function preloadTitleInfo(
361 ResourceLoaderContext
$context, IDatabase
$db, array $moduleNames
363 $rl = $context->getResourceLoader();
364 // getDB() can be overridden to point to a foreign database.
365 // For now, only preload local. In the future, we could preload by wikiID.
367 /** @var ResourceLoaderWikiModule[] $wikiModules */
369 foreach ( $moduleNames as $name ) {
370 $module = $rl->getModule( $name );
371 if ( $module instanceof self
) {
372 $mDB = $module->getDB();
373 // Subclasses may disable getDB and implement getTitleInfo differently
374 if ( $mDB && $mDB->getDomainID() === $db->getDomainID() ) {
375 $wikiModules[] = $module;
376 $allPages +
= $module->getPages( $context );
381 if ( !$wikiModules ) {
382 // Nothing to preload
386 $pageNames = array_keys( $allPages );
388 $hash = sha1( implode( '|', $pageNames ) );
390 // Avoid Zend bug where "static::" does not apply LSB in the closure
391 $func = [ static::class, 'fetchTitleInfo' ];
394 $cache = ObjectCache
::getMainWANInstance();
395 $allInfo = $cache->getWithSetCallback(
396 $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $db->getDomainID(), $hash ),
398 function ( $curVal, &$ttl, array &$setOpts ) use ( $func, $pageNames, $db, $fname ) {
399 $setOpts +
= Database
::getCacheSetOptions( $db );
401 return call_user_func( $func, $db, $pageNames, $fname );
405 $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $db->getDomainID() ) ]
409 foreach ( $wikiModules as $wikiModule ) {
410 $pages = $wikiModule->getPages( $context );
411 // Before we intersect, map the names to canonical form (T145673).
413 foreach ( $pages as $page => $unused ) {
414 $title = Title
::newFromText( $page );
416 $intersect[ $title->getPrefixedText() ] = 1;
418 // Page name may be invalid if user-provided (e.g. gadgets)
419 $rl->getLogger()->info(
420 'Invalid wiki page title "{title}" in ' . __METHOD__
,
425 $info = array_intersect_key( $allInfo, $intersect );
426 $pageNames = array_keys( $pages );
428 $key = implode( '|', $pageNames );
429 $wikiModule->setTitleInfo( $key, $info );
434 * Clear the preloadTitleInfo() cache for all wiki modules on this wiki on
435 * page change if it was a JS or CSS page
437 * @param Title $title
438 * @param Revision|null $old Prior page revision
439 * @param Revision|null $new New page revision
440 * @param string $wikiId
443 public static function invalidateModuleCache(
444 Title
$title, Revision
$old = null, Revision
$new = null, $wikiId
446 static $formats = [ CONTENT_FORMAT_CSS
, CONTENT_FORMAT_JAVASCRIPT
];
448 if ( $old && in_array( $old->getContentFormat(), $formats ) ) {
450 } elseif ( $new && in_array( $new->getContentFormat(), $formats ) ) {
453 $purge = ( $title->isSiteConfigPage() ||
$title->isUserConfigPage() );
457 $cache = ObjectCache
::getMainWANInstance();
458 $key = $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $wikiId );
459 $cache->touchCheckKey( $key );
467 public function getType() {
468 // Check both because subclasses don't always pass pages via the constructor,
469 // they may also override getPages() instead, in which case we should keep
470 // defaulting to LOAD_GENERAL and allow them to override getType() separately.
471 return ( $this->styles
&& !$this->scripts
) ? self
::LOAD_STYLES
: self
::LOAD_GENERAL
;