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 $handler = ContentHandler
::getForTitle( $title );
153 if ( $handler->isSupportedFormat( CONTENT_FORMAT_CSS
) ) {
154 $format = CONTENT_FORMAT_CSS
;
155 } elseif ( $handler->isSupportedFormat( CONTENT_FORMAT_JAVASCRIPT
) ) {
156 $format = CONTENT_FORMAT_JAVASCRIPT
;
161 $revision = Revision
::newKnownCurrent( wfGetDB( DB_REPLICA
), $title->getArticleID(),
162 $title->getLatestRevID() );
166 $revision->setTitle( $title );
167 $content = $revision->getContent( Revision
::RAW
);
170 wfDebugLog( 'resourceloader', __METHOD__
. ': failed to load content of JS/CSS page!' );
174 return $content->serialize( $format );
178 * @param ResourceLoaderContext $context
181 public function getScript( ResourceLoaderContext
$context ) {
183 foreach ( $this->getPages( $context ) as $titleText => $options ) {
184 if ( $options['type'] !== 'script' ) {
187 $script = $this->getContent( $titleText );
188 if ( strval( $script ) !== '' ) {
189 $script = $this->validateScriptFile( $titleText, $script );
190 $scripts .= ResourceLoader
::makeComment( $titleText ) . $script . "\n";
197 * @param ResourceLoaderContext $context
200 public function getStyles( ResourceLoaderContext
$context ) {
202 foreach ( $this->getPages( $context ) as $titleText => $options ) {
203 if ( $options['type'] !== 'style' ) {
206 $media = isset( $options['media'] ) ?
$options['media'] : 'all';
207 $style = $this->getContent( $titleText );
208 if ( strval( $style ) === '' ) {
211 if ( $this->getFlip( $context ) ) {
212 $style = CSSJanus
::transform( $style, true, false );
214 $style = MemoizedCallable
::call( 'CSSMin::remap',
215 [ $style, false, $this->getConfig()->get( 'ScriptPath' ), true ] );
216 if ( !isset( $styles[$media] ) ) {
217 $styles[$media] = [];
219 $style = ResourceLoader
::makeComment( $titleText ) . $style;
220 $styles[$media][] = $style;
226 * Disable module content versioning.
228 * This class does not support generating content outside of a module
229 * request due to foreign database support.
231 * See getDefinitionSummary() for meta-data versioning.
235 public function enableModuleContentVersion() {
240 * @param ResourceLoaderContext $context
243 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
244 $summary = parent
::getDefinitionSummary( $context );
246 'pages' => $this->getPages( $context ),
247 // Includes meta data of current revisions
248 'titleInfo' => $this->getTitleInfo( $context ),
254 * @param ResourceLoaderContext $context
257 public function isKnownEmpty( ResourceLoaderContext
$context ) {
258 $revisions = $this->getTitleInfo( $context );
260 // For user modules, don't needlessly load if there are no non-empty pages
261 if ( $this->getGroup() === 'user' ) {
262 foreach ( $revisions as $revision ) {
263 if ( $revision['page_len'] > 0 ) {
264 // At least one non-empty page, module should be loaded
271 // Bug 68488: For other modules (i.e. ones that are called in cached html output) only check
272 // page existance. This ensures that, if some pages in a module are temporarily blanked,
273 // we don't end omit the module's script or link tag on some pages.
274 return count( $revisions ) === 0;
277 private function setTitleInfo( $key, array $titleInfo ) {
278 $this->titleInfo
[$key] = $titleInfo;
282 * Get the information about the wiki pages for a given context.
283 * @param ResourceLoaderContext $context
284 * @return array Keyed by page name
286 protected function getTitleInfo( ResourceLoaderContext
$context ) {
287 $dbr = $this->getDB();
289 // We're dealing with a subclass that doesn't have a DB
293 $pageNames = array_keys( $this->getPages( $context ) );
295 $key = implode( '|', $pageNames );
296 if ( !isset( $this->titleInfo
[$key] ) ) {
297 $this->titleInfo
[$key] = static::fetchTitleInfo( $dbr, $pageNames, __METHOD__
);
299 return $this->titleInfo
[$key];
302 protected static function fetchTitleInfo( IDatabase
$db, array $pages, $fname = __METHOD__
) {
304 $batch = new LinkBatch
;
305 foreach ( $pages as $titleText ) {
306 $title = Title
::newFromText( $titleText );
308 // Page name may be invalid if user-provided (e.g. gadgets)
309 $batch->addObj( $title );
312 if ( !$batch->isEmpty() ) {
313 $res = $db->select( 'page',
314 // Include page_touched to allow purging if cache is poisoned (T117587, T113916)
315 [ 'page_namespace', 'page_title', 'page_touched', 'page_len', 'page_latest' ],
316 $batch->constructSet( 'page', $db ),
319 foreach ( $res as $row ) {
320 // Avoid including ids or timestamps of revision/page tables so
321 // that versions are not wasted
322 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
323 $titleInfo[$title->getPrefixedText()] = [
324 'page_len' => $row->page_len
,
325 'page_latest' => $row->page_latest
,
326 'page_touched' => $row->page_touched
,
335 * @param ResourceLoaderContext $context
336 * @param IDatabase $db
337 * @param string[] $moduleNames
339 public static function preloadTitleInfo(
340 ResourceLoaderContext
$context, IDatabase
$db, array $moduleNames
342 $rl = $context->getResourceLoader();
343 // getDB() can be overridden to point to a foreign database.
344 // For now, only preload local. In the future, we could preload by wikiID.
346 /** @var ResourceLoaderWikiModule[] $wikiModules */
348 foreach ( $moduleNames as $name ) {
349 $module = $rl->getModule( $name );
350 if ( $module instanceof self
) {
351 $mDB = $module->getDB();
352 // Subclasses may disable getDB and implement getTitleInfo differently
353 if ( $mDB && $mDB->getWikiID() === $db->getWikiID() ) {
354 $wikiModules[] = $module;
355 $allPages +
= $module->getPages( $context );
360 $pageNames = array_keys( $allPages );
362 $hash = sha1( implode( '|', $pageNames ) );
364 // Avoid Zend bug where "static::" does not apply LSB in the closure
365 $func = [ static::class, 'fetchTitleInfo' ];
368 $cache = ObjectCache
::getMainWANInstance();
369 $allInfo = $cache->getWithSetCallback(
370 $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $db->getWikiID(), $hash ),
372 function ( $curVal, &$ttl, array &$setOpts ) use ( $func, $pageNames, $db, $fname ) {
373 $setOpts +
= Database
::getCacheSetOptions( $db );
375 return call_user_func( $func, $db, $pageNames, $fname );
377 [ 'checkKeys' => [ $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $db->getWikiID() ) ] ]
380 foreach ( $wikiModules as $wikiModule ) {
381 $pages = $wikiModule->getPages( $context );
382 // Before we intersect, map the names to canonical form (T145673).
384 foreach ( $pages as $page => $unused ) {
385 $title = Title
::newFromText( $page );
387 $intersect[ $title->getPrefixedText() ] = 1;
389 // Page name may be invalid if user-provided (e.g. gadgets)
390 $rl->getLogger()->info(
391 'Invalid wiki page title "{title}" in ' . __METHOD__
,
396 $info = array_intersect_key( $allInfo, $intersect );
397 $pageNames = array_keys( $pages );
399 $key = implode( '|', $pageNames );
400 $wikiModule->setTitleInfo( $key, $info );
405 * Clear the preloadTitleInfo() cache for all wiki modules on this wiki on
406 * page change if it was a JS or CSS page
408 * @param Title $title
409 * @param Revision|null $old Prior page revision
410 * @param Revision|null $new New page revision
411 * @param string $wikiId
414 public static function invalidateModuleCache(
415 Title
$title, Revision
$old = null, Revision
$new = null, $wikiId
417 static $formats = [ CONTENT_FORMAT_CSS
, CONTENT_FORMAT_JAVASCRIPT
];
419 if ( $old && in_array( $old->getContentFormat(), $formats ) ) {
421 } elseif ( $new && in_array( $new->getContentFormat(), $formats ) ) {
424 $purge = ( $title->isCssOrJsPage() ||
$title->isCssJsSubpage() );
428 $cache = ObjectCache
::getMainWANInstance();
429 $key = $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $wikiId );
430 $cache->touchCheckKey( $key );
438 public function getType() {
439 // Check both because subclasses don't always pass pages via the constructor,
440 // they may also override getPages() instead, in which case we should keep
441 // defaulting to LOAD_GENERAL and allow them to override getType() separately.
442 return ( $this->styles
&& !$this->scripts
) ? self
::LOAD_STYLES
: self
::LOAD_GENERAL
;