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
26 * Abstraction for ResourceLoader modules which pull from wiki pages
28 * This can only be used for wiki pages in the MediaWiki and User namespaces,
29 * because of its dependence on the functionality of Title::isCssJsSubpage
30 * and Title::isCssOrJsPage().
32 * This module supports being used as a placeholder for a module on a remote wiki.
33 * To do so, getDB() must be overloaded to return a foreign database object that
34 * allows local wikis to query page metadata.
36 * Safe for calls on local wikis are:
40 * - Basic methods that strictly involve the foreign database
45 class ResourceLoaderWikiModule
extends ResourceLoaderModule
{
47 // Origin defaults to users with sitewide authority
48 protected $origin = self
::ORIGIN_USER_SITEWIDE
;
50 // In-process cache for title info
51 protected $titleInfo = [];
53 // List of page names that contain CSS
54 protected $styles = [];
56 // List of page names that contain JavaScript
57 protected $scripts = [];
63 * @param array $options For back-compat, this can be omitted in favour of overwriting getPages.
65 public function __construct( array $options = null ) {
66 if ( is_null( $options ) ) {
70 foreach ( $options as $member => $option ) {
76 $this->{$member} = $option;
83 * Subclasses should return an associative array of resources in the module.
84 * Keys should be the title of a page in the MediaWiki or User namespace.
86 * Values should be a nested array of options. The supported keys are 'type' and
89 * For scripts, 'type' should be 'script'.
91 * For stylesheets, 'type' should be 'style'.
92 * There is an optional media key, the value of which can be the
93 * medium ('screen', 'print', etc.) of the stylesheet.
95 * @param ResourceLoaderContext $context
98 protected function getPages( ResourceLoaderContext
$context ) {
99 $config = $this->getConfig();
102 // Filter out pages from origins not allowed by the current wiki configuration.
103 if ( $config->get( 'UseSiteJs' ) ) {
104 foreach ( $this->scripts
as $script ) {
105 $pages[$script] = [ 'type' => 'script' ];
109 if ( $config->get( 'UseSiteCss' ) ) {
110 foreach ( $this->styles
as $style ) {
111 $pages[$style] = [ 'type' => 'style' ];
123 public function getGroup() {
128 * Get the Database object used in getTitleInfo().
130 * Defaults to the local replica DB. Subclasses may want to override this to return a foreign
131 * database object, or null if getTitleInfo() shouldn't access the database.
133 * NOTE: This ONLY works for getTitleInfo() and isKnownEmpty(), NOT FOR ANYTHING ELSE.
134 * In particular, it doesn't work for getContent() or getScript() etc.
136 * @return IDatabase|null
138 protected function getDB() {
139 return wfGetDB( DB_REPLICA
);
143 * @param string $titleText
144 * @return null|string
146 protected function getContent( $titleText ) {
147 $title = Title
::newFromText( $titleText );
152 // If the page is a redirect, follow the redirect.
153 if ( $title->isRedirect() ) {
154 $content = $this->getContentObj( $title );
155 $title = $content ?
$content->getUltimateRedirectTarget() : null;
161 $handler = ContentHandler
::getForTitle( $title );
162 if ( $handler->isSupportedFormat( CONTENT_FORMAT_CSS
) ) {
163 $format = CONTENT_FORMAT_CSS
;
164 } elseif ( $handler->isSupportedFormat( CONTENT_FORMAT_JAVASCRIPT
) ) {
165 $format = CONTENT_FORMAT_JAVASCRIPT
;
170 $content = $this->getContentObj( $title );
175 return $content->serialize( $format );
179 * @param Title $title
180 * @return Content|null
182 protected function getContentObj( Title
$title ) {
183 $revision = Revision
::newKnownCurrent( wfGetDB( DB_REPLICA
), $title->getArticleID(),
184 $title->getLatestRevID() );
188 $revision->setTitle( $title );
189 $content = $revision->getContent( Revision
::RAW
);
191 wfDebugLog( 'resourceloader', __METHOD__
. ': failed to load content of JS/CSS page!' );
198 * @param ResourceLoaderContext $context
201 public function getScript( ResourceLoaderContext
$context ) {
203 foreach ( $this->getPages( $context ) as $titleText => $options ) {
204 if ( $options['type'] !== 'script' ) {
207 $script = $this->getContent( $titleText );
208 if ( strval( $script ) !== '' ) {
209 $script = $this->validateScriptFile( $titleText, $script );
210 $scripts .= ResourceLoader
::makeComment( $titleText ) . $script . "\n";
217 * @param ResourceLoaderContext $context
220 public function getStyles( ResourceLoaderContext
$context ) {
222 foreach ( $this->getPages( $context ) as $titleText => $options ) {
223 if ( $options['type'] !== 'style' ) {
226 $media = isset( $options['media'] ) ?
$options['media'] : 'all';
227 $style = $this->getContent( $titleText );
228 if ( strval( $style ) === '' ) {
231 if ( $this->getFlip( $context ) ) {
232 $style = CSSJanus
::transform( $style, true, false );
234 $style = MemoizedCallable
::call( 'CSSMin::remap',
235 [ $style, false, $this->getConfig()->get( 'ScriptPath' ), true ] );
236 if ( !isset( $styles[$media] ) ) {
237 $styles[$media] = [];
239 $style = ResourceLoader
::makeComment( $titleText ) . $style;
240 $styles[$media][] = $style;
246 * Disable module content versioning.
248 * This class does not support generating content outside of a module
249 * request due to foreign database support.
251 * See getDefinitionSummary() for meta-data versioning.
255 public function enableModuleContentVersion() {
260 * @param ResourceLoaderContext $context
263 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
264 $summary = parent
::getDefinitionSummary( $context );
266 'pages' => $this->getPages( $context ),
267 // Includes meta data of current revisions
268 'titleInfo' => $this->getTitleInfo( $context ),
274 * @param ResourceLoaderContext $context
277 public function isKnownEmpty( ResourceLoaderContext
$context ) {
278 $revisions = $this->getTitleInfo( $context );
280 // For user modules, don't needlessly load if there are no non-empty pages
281 if ( $this->getGroup() === 'user' ) {
282 foreach ( $revisions as $revision ) {
283 if ( $revision['page_len'] > 0 ) {
284 // At least one non-empty page, module should be loaded
291 // T70488: For other modules (i.e. ones that are called in cached html output) only check
292 // page existance. This ensures that, if some pages in a module are temporarily blanked,
293 // we don't end omit the module's script or link tag on some pages.
294 return count( $revisions ) === 0;
297 private function setTitleInfo( $key, array $titleInfo ) {
298 $this->titleInfo
[$key] = $titleInfo;
302 * Get the information about the wiki pages for a given context.
303 * @param ResourceLoaderContext $context
304 * @return array Keyed by page name
306 protected function getTitleInfo( ResourceLoaderContext
$context ) {
307 $dbr = $this->getDB();
309 // We're dealing with a subclass that doesn't have a DB
313 $pageNames = array_keys( $this->getPages( $context ) );
315 $key = implode( '|', $pageNames );
316 if ( !isset( $this->titleInfo
[$key] ) ) {
317 $this->titleInfo
[$key] = static::fetchTitleInfo( $dbr, $pageNames, __METHOD__
);
319 return $this->titleInfo
[$key];
322 protected static function fetchTitleInfo( IDatabase
$db, array $pages, $fname = __METHOD__
) {
324 $batch = new LinkBatch
;
325 foreach ( $pages as $titleText ) {
326 $title = Title
::newFromText( $titleText );
328 // Page name may be invalid if user-provided (e.g. gadgets)
329 $batch->addObj( $title );
332 if ( !$batch->isEmpty() ) {
333 $res = $db->select( 'page',
334 // Include page_touched to allow purging if cache is poisoned (T117587, T113916)
335 [ 'page_namespace', 'page_title', 'page_touched', 'page_len', 'page_latest' ],
336 $batch->constructSet( 'page', $db ),
339 foreach ( $res as $row ) {
340 // Avoid including ids or timestamps of revision/page tables so
341 // that versions are not wasted
342 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
343 $titleInfo[$title->getPrefixedText()] = [
344 'page_len' => $row->page_len
,
345 'page_latest' => $row->page_latest
,
346 'page_touched' => $row->page_touched
,
355 * @param ResourceLoaderContext $context
356 * @param IDatabase $db
357 * @param string[] $moduleNames
359 public static function preloadTitleInfo(
360 ResourceLoaderContext
$context, IDatabase
$db, array $moduleNames
362 $rl = $context->getResourceLoader();
363 // getDB() can be overridden to point to a foreign database.
364 // For now, only preload local. In the future, we could preload by wikiID.
366 /** @var ResourceLoaderWikiModule[] $wikiModules */
368 foreach ( $moduleNames as $name ) {
369 $module = $rl->getModule( $name );
370 if ( $module instanceof self
) {
371 $mDB = $module->getDB();
372 // Subclasses may disable getDB and implement getTitleInfo differently
373 if ( $mDB && $mDB->getWikiID() === $db->getWikiID() ) {
374 $wikiModules[] = $module;
375 $allPages +
= $module->getPages( $context );
380 if ( !$wikiModules ) {
381 // Nothing to preload
385 $pageNames = array_keys( $allPages );
387 $hash = sha1( implode( '|', $pageNames ) );
389 // Avoid Zend bug where "static::" does not apply LSB in the closure
390 $func = [ static::class, 'fetchTitleInfo' ];
393 $cache = ObjectCache
::getMainWANInstance();
394 $allInfo = $cache->getWithSetCallback(
395 $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $db->getWikiID(), $hash ),
397 function ( $curVal, &$ttl, array &$setOpts ) use ( $func, $pageNames, $db, $fname ) {
398 $setOpts +
= Database
::getCacheSetOptions( $db );
400 return call_user_func( $func, $db, $pageNames, $fname );
402 [ 'checkKeys' => [ $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $db->getWikiID() ) ] ]
405 foreach ( $wikiModules as $wikiModule ) {
406 $pages = $wikiModule->getPages( $context );
407 // Before we intersect, map the names to canonical form (T145673).
409 foreach ( $pages as $page => $unused ) {
410 $title = Title
::newFromText( $page );
412 $intersect[ $title->getPrefixedText() ] = 1;
414 // Page name may be invalid if user-provided (e.g. gadgets)
415 $rl->getLogger()->info(
416 'Invalid wiki page title "{title}" in ' . __METHOD__
,
421 $info = array_intersect_key( $allInfo, $intersect );
422 $pageNames = array_keys( $pages );
424 $key = implode( '|', $pageNames );
425 $wikiModule->setTitleInfo( $key, $info );
430 * Clear the preloadTitleInfo() cache for all wiki modules on this wiki on
431 * page change if it was a JS or CSS page
433 * @param Title $title
434 * @param Revision|null $old Prior page revision
435 * @param Revision|null $new New page revision
436 * @param string $wikiId
439 public static function invalidateModuleCache(
440 Title
$title, Revision
$old = null, Revision
$new = null, $wikiId
442 static $formats = [ CONTENT_FORMAT_CSS
, CONTENT_FORMAT_JAVASCRIPT
];
444 if ( $old && in_array( $old->getContentFormat(), $formats ) ) {
446 } elseif ( $new && in_array( $new->getContentFormat(), $formats ) ) {
449 $purge = ( $title->isCssOrJsPage() ||
$title->isCssJsSubpage() );
453 $cache = ObjectCache
::getMainWANInstance();
454 $key = $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $wikiId );
455 $cache->touchCheckKey( $key );
463 public function getType() {
464 // Check both because subclasses don't always pass pages via the constructor,
465 // they may also override getPages() instead, in which case we should keep
466 // defaulting to LOAD_GENERAL and allow them to override getType() separately.
467 return ( $this->styles
&& !$this->scripts
) ? self
::LOAD_STYLES
: self
::LOAD_GENERAL
;