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 * @return null|string
162 protected function getContent( $titleText ) {
163 $title = Title
::newFromText( $titleText );
165 return null; // Bad title
168 // If the page is a redirect, follow the redirect.
169 if ( $title->isRedirect() ) {
170 $content = $this->getContentObj( $title );
171 $title = $content ?
$content->getUltimateRedirectTarget() : null;
173 return null; // Dead redirect
177 $handler = ContentHandler
::getForTitle( $title );
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 $content = $this->getContentObj( $title );
188 return null; // No content found
191 return $content->serialize( $format );
195 * @param Title $title
196 * @return Content|null
198 protected function getContentObj( Title
$title ) {
199 $revision = Revision
::newKnownCurrent( wfGetDB( DB_REPLICA
), $title );
203 $content = $revision->getContent( Revision
::RAW
);
205 wfDebugLog( 'resourceloader', __METHOD__
. ': failed to load content of JS/CSS page!' );
212 * @param ResourceLoaderContext $context
213 * @return string JavaScript code
215 public function getScript( ResourceLoaderContext
$context ) {
217 foreach ( $this->getPages( $context ) as $titleText => $options ) {
218 if ( $options['type'] !== 'script' ) {
221 $script = $this->getContent( $titleText );
222 if ( strval( $script ) !== '' ) {
223 $script = $this->validateScriptFile( $titleText, $script );
224 $scripts .= ResourceLoader
::makeComment( $titleText ) . $script . "\n";
231 * @param ResourceLoaderContext $context
234 public function getStyles( ResourceLoaderContext
$context ) {
236 foreach ( $this->getPages( $context ) as $titleText => $options ) {
237 if ( $options['type'] !== 'style' ) {
240 $media = isset( $options['media'] ) ?
$options['media'] : 'all';
241 $style = $this->getContent( $titleText );
242 if ( strval( $style ) === '' ) {
245 if ( $this->getFlip( $context ) ) {
246 $style = CSSJanus
::transform( $style, true, false );
248 $style = MemoizedCallable
::call( 'CSSMin::remap',
249 [ $style, false, $this->getConfig()->get( 'ScriptPath' ), true ] );
250 if ( !isset( $styles[$media] ) ) {
251 $styles[$media] = [];
253 $style = ResourceLoader
::makeComment( $titleText ) . $style;
254 $styles[$media][] = $style;
260 * Disable module content versioning.
262 * This class does not support generating content outside of a module
263 * request due to foreign database support.
265 * See getDefinitionSummary() for meta-data versioning.
269 public function enableModuleContentVersion() {
274 * @param ResourceLoaderContext $context
277 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
278 $summary = parent
::getDefinitionSummary( $context );
280 'pages' => $this->getPages( $context ),
281 // Includes meta data of current revisions
282 'titleInfo' => $this->getTitleInfo( $context ),
288 * @param ResourceLoaderContext $context
291 public function isKnownEmpty( ResourceLoaderContext
$context ) {
292 $revisions = $this->getTitleInfo( $context );
294 // For user modules, don't needlessly load if there are no non-empty pages
295 if ( $this->getGroup() === 'user' ) {
296 foreach ( $revisions as $revision ) {
297 if ( $revision['page_len'] > 0 ) {
298 // At least one non-empty page, module should be loaded
305 // T70488: For other modules (i.e. ones that are called in cached html output) only check
306 // page existance. This ensures that, if some pages in a module are temporarily blanked,
307 // we don't end omit the module's script or link tag on some pages.
308 return count( $revisions ) === 0;
311 private function setTitleInfo( $batchKey, array $titleInfo ) {
312 $this->titleInfo
[$batchKey] = $titleInfo;
315 private static function makeTitleKey( LinkTarget
$title ) {
316 // Used for keys in titleInfo.
317 return "{$title->getNamespace()}:{$title->getDBkey()}";
321 * Get the information about the wiki pages for a given context.
322 * @param ResourceLoaderContext $context
323 * @return array Keyed by page name
325 protected function getTitleInfo( ResourceLoaderContext
$context ) {
326 $dbr = $this->getDB();
328 // We're dealing with a subclass that doesn't have a DB
332 $pageNames = array_keys( $this->getPages( $context ) );
334 $batchKey = implode( '|', $pageNames );
335 if ( !isset( $this->titleInfo
[$batchKey] ) ) {
336 $this->titleInfo
[$batchKey] = static::fetchTitleInfo( $dbr, $pageNames, __METHOD__
);
338 return $this->titleInfo
[$batchKey];
341 protected static function fetchTitleInfo( IDatabase
$db, array $pages, $fname = __METHOD__
) {
343 $batch = new LinkBatch
;
344 foreach ( $pages as $titleText ) {
345 $title = Title
::newFromText( $titleText );
347 // Page name may be invalid if user-provided (e.g. gadgets)
348 $batch->addObj( $title );
351 if ( !$batch->isEmpty() ) {
352 $res = $db->select( 'page',
353 // Include page_touched to allow purging if cache is poisoned (T117587, T113916)
354 [ 'page_namespace', 'page_title', 'page_touched', 'page_len', 'page_latest' ],
355 $batch->constructSet( 'page', $db ),
358 foreach ( $res as $row ) {
359 // Avoid including ids or timestamps of revision/page tables so
360 // that versions are not wasted
361 $title = new TitleValue( (int)$row->page_namespace
, $row->page_title
);
362 $titleInfo[ self
::makeTitleKey( $title ) ] = [
363 'page_len' => $row->page_len
,
364 'page_latest' => $row->page_latest
,
365 'page_touched' => $row->page_touched
,
374 * @param ResourceLoaderContext $context
375 * @param IDatabase $db
376 * @param string[] $moduleNames
378 public static function preloadTitleInfo(
379 ResourceLoaderContext
$context, IDatabase
$db, array $moduleNames
381 $rl = $context->getResourceLoader();
382 // getDB() can be overridden to point to a foreign database.
383 // For now, only preload local. In the future, we could preload by wikiID.
385 /** @var ResourceLoaderWikiModule[] $wikiModules */
387 foreach ( $moduleNames as $name ) {
388 $module = $rl->getModule( $name );
389 if ( $module instanceof self
) {
390 $mDB = $module->getDB();
391 // Subclasses may disable getDB and implement getTitleInfo differently
392 if ( $mDB && $mDB->getDomainID() === $db->getDomainID() ) {
393 $wikiModules[] = $module;
394 $allPages +
= $module->getPages( $context );
399 if ( !$wikiModules ) {
400 // Nothing to preload
404 $pageNames = array_keys( $allPages );
406 $hash = sha1( implode( '|', $pageNames ) );
408 // Avoid Zend bug where "static::" does not apply LSB in the closure
409 $func = [ static::class, 'fetchTitleInfo' ];
412 $cache = ObjectCache
::getMainWANInstance();
413 $allInfo = $cache->getWithSetCallback(
414 $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $db->getDomainID(), $hash ),
416 function ( $curVal, &$ttl, array &$setOpts ) use ( $func, $pageNames, $db, $fname ) {
417 $setOpts +
= Database
::getCacheSetOptions( $db );
419 return call_user_func( $func, $db, $pageNames, $fname );
423 $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $db->getDomainID() ) ]
427 foreach ( $wikiModules as $wikiModule ) {
428 $pages = $wikiModule->getPages( $context );
429 // Before we intersect, map the names to canonical form (T145673).
431 foreach ( $pages as $pageName => $unused ) {
432 $title = Title
::newFromText( $pageName );
434 $intersect[ self
::makeTitleKey( $title ) ] = 1;
436 // Page name may be invalid if user-provided (e.g. gadgets)
437 $rl->getLogger()->info(
438 'Invalid wiki page title "{title}" in ' . __METHOD__
,
439 [ 'title' => $pageName ]
443 $info = array_intersect_key( $allInfo, $intersect );
444 $pageNames = array_keys( $pages );
446 $batchKey = implode( '|', $pageNames );
447 $wikiModule->setTitleInfo( $batchKey, $info );
452 * Clear the preloadTitleInfo() cache for all wiki modules on this wiki on
453 * page change if it was a JS or CSS page
455 * @param Title $title
456 * @param Revision|null $old Prior page revision
457 * @param Revision|null $new New page revision
458 * @param string $wikiId
461 public static function invalidateModuleCache(
462 Title
$title, Revision
$old = null, Revision
$new = null, $wikiId
464 static $formats = [ CONTENT_FORMAT_CSS
, CONTENT_FORMAT_JAVASCRIPT
];
466 if ( $old && in_array( $old->getContentFormat(), $formats ) ) {
468 } elseif ( $new && in_array( $new->getContentFormat(), $formats ) ) {
471 $purge = ( $title->isSiteConfigPage() ||
$title->isUserConfigPage() );
475 $cache = ObjectCache
::getMainWANInstance();
476 $key = $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $wikiId );
477 $cache->touchCheckKey( $key );
485 public function getType() {
486 // Check both because subclasses don't always pass pages via the constructor,
487 // they may also override getPages() instead, in which case we should keep
488 // defaulting to LOAD_GENERAL and allow them to override getType() separately.
489 return ( $this->styles
&& !$this->scripts
) ? self
::LOAD_STYLES
: self
::LOAD_GENERAL
;