MediaWiki REL1_31
ResourceLoaderWikiModule.php
Go to the documentation of this file.
1<?php
27
49
50 // Origin defaults to users with sitewide authority
52
53 // In-process cache for title info
54 protected $titleInfo = [];
55
56 // List of page names that contain CSS
57 protected $styles = [];
58
59 // List of page names that contain JavaScript
60 protected $scripts = [];
61
62 // Group of module
63 protected $group;
64
68 public function __construct( array $options = null ) {
69 if ( is_null( $options ) ) {
70 return;
71 }
72
73 foreach ( $options as $member => $option ) {
74 switch ( $member ) {
75 case 'styles':
76 case 'scripts':
77 case 'group':
78 case 'targets':
79 $this->{$member} = $option;
80 break;
81 }
82 }
83 }
84
102 $config = $this->getConfig();
103 $pages = [];
104
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' ];
109 }
110 }
111
112 if ( $config->get( 'UseSiteCss' ) ) {
113 foreach ( $this->styles as $style ) {
114 $pages[$style] = [ 'type' => 'style' ];
115 }
116 }
117
118 return $pages;
119 }
120
126 public function getGroup() {
127 return $this->group;
128 }
129
141 protected function getDB() {
142 return wfGetDB( DB_REPLICA );
143 }
144
149 protected function getContent( $titleText ) {
150 $title = Title::newFromText( $titleText );
151 if ( !$title ) {
152 return null; // Bad title
153 }
154
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;
159 if ( !$title ) {
160 return null; // Dead redirect
161 }
162 }
163
164 $handler = ContentHandler::getForTitle( $title );
165 if ( $handler->isSupportedFormat( CONTENT_FORMAT_CSS ) ) {
166 $format = CONTENT_FORMAT_CSS;
167 } elseif ( $handler->isSupportedFormat( CONTENT_FORMAT_JAVASCRIPT ) ) {
169 } else {
170 return null; // Bad content model
171 }
172
173 $content = $this->getContentObj( $title );
174 if ( !$content ) {
175 return null; // No content found
176 }
177
178 return $content->serialize( $format );
179 }
180
185 protected function getContentObj( Title $title ) {
186 $revision = Revision::newKnownCurrent( wfGetDB( DB_REPLICA ), $title );
187 if ( !$revision ) {
188 return null;
189 }
190 $content = $revision->getContent( Revision::RAW );
191 if ( !$content ) {
192 wfDebugLog( 'resourceloader', __METHOD__ . ': failed to load content of JS/CSS page!' );
193 return null;
194 }
195 return $content;
196 }
197
203 $scripts = '';
204 foreach ( $this->getPages( $context ) as $titleText => $options ) {
205 if ( $options['type'] !== 'script' ) {
206 continue;
207 }
208 $script = $this->getContent( $titleText );
209 if ( strval( $script ) !== '' ) {
210 $script = $this->validateScriptFile( $titleText, $script );
211 $scripts .= ResourceLoader::makeComment( $titleText ) . $script . "\n";
212 }
213 }
214 return $scripts;
215 }
216
222 $styles = [];
223 foreach ( $this->getPages( $context ) as $titleText => $options ) {
224 if ( $options['type'] !== 'style' ) {
225 continue;
226 }
227 $media = isset( $options['media'] ) ? $options['media'] : 'all';
228 $style = $this->getContent( $titleText );
229 if ( strval( $style ) === '' ) {
230 continue;
231 }
232 if ( $this->getFlip( $context ) ) {
233 $style = CSSJanus::transform( $style, true, false );
234 }
235 $style = MemoizedCallable::call( 'CSSMin::remap',
236 [ $style, false, $this->getConfig()->get( 'ScriptPath' ), true ] );
237 if ( !isset( $styles[$media] ) ) {
238 $styles[$media] = [];
239 }
240 $style = ResourceLoader::makeComment( $titleText ) . $style;
241 $styles[$media][] = $style;
242 }
243 return $styles;
244 }
245
256 public function enableModuleContentVersion() {
257 return false;
258 }
259
265 $summary = parent::getDefinitionSummary( $context );
266 $summary[] = [
267 'pages' => $this->getPages( $context ),
268 // Includes meta data of current revisions
269 'titleInfo' => $this->getTitleInfo( $context ),
270 ];
271 return $summary;
272 }
273
279 $revisions = $this->getTitleInfo( $context );
280
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
286 return false;
287 }
288 }
289 return true;
290 }
291
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;
296 }
297
298 private function setTitleInfo( $key, array $titleInfo ) {
299 $this->titleInfo[$key] = $titleInfo;
300 }
301
308 $dbr = $this->getDB();
309 if ( !$dbr ) {
310 // We're dealing with a subclass that doesn't have a DB
311 return [];
312 }
313
314 $pageNames = array_keys( $this->getPages( $context ) );
315 sort( $pageNames );
316 $key = implode( '|', $pageNames );
317 if ( !isset( $this->titleInfo[$key] ) ) {
318 $this->titleInfo[$key] = static::fetchTitleInfo( $dbr, $pageNames, __METHOD__ );
319 }
320 return $this->titleInfo[$key];
321 }
322
323 protected static function fetchTitleInfo( IDatabase $db, array $pages, $fname = __METHOD__ ) {
324 $titleInfo = [];
325 $batch = new LinkBatch;
326 foreach ( $pages as $titleText ) {
327 $title = Title::newFromText( $titleText );
328 if ( $title ) {
329 // Page name may be invalid if user-provided (e.g. gadgets)
330 $batch->addObj( $title );
331 }
332 }
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 ),
338 $fname
339 );
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,
348 ];
349 }
350 }
351 return $titleInfo;
352 }
353
360 public static function preloadTitleInfo(
361 ResourceLoaderContext $context, IDatabase $db, array $moduleNames
362 ) {
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.
366 $allPages = [];
368 $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 );
377 }
378 }
379 }
380
381 if ( !$wikiModules ) {
382 // Nothing to preload
383 return;
384 }
385
386 $pageNames = array_keys( $allPages );
387 sort( $pageNames );
388 $hash = sha1( implode( '|', $pageNames ) );
389
390 // Avoid Zend bug where "static::" does not apply LSB in the closure
391 $func = [ static::class, 'fetchTitleInfo' ];
392 $fname = __METHOD__;
393
394 $cache = ObjectCache::getMainWANInstance();
395 $allInfo = $cache->getWithSetCallback(
396 $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $db->getDomainID(), $hash ),
397 $cache::TTL_HOUR,
398 function ( $curVal, &$ttl, array &$setOpts ) use ( $func, $pageNames, $db, $fname ) {
399 $setOpts += Database::getCacheSetOptions( $db );
400
401 return call_user_func( $func, $db, $pageNames, $fname );
402 },
403 [
404 'checkKeys' => [
405 $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $db->getDomainID() ) ]
406 ]
407 );
408
409 foreach ( $wikiModules as $wikiModule ) {
410 $pages = $wikiModule->getPages( $context );
411 // Before we intersect, map the names to canonical form (T145673).
412 $intersect = [];
413 foreach ( $pages as $page => $unused ) {
414 $title = Title::newFromText( $page );
415 if ( $title ) {
416 $intersect[ $title->getPrefixedText() ] = 1;
417 } else {
418 // Page name may be invalid if user-provided (e.g. gadgets)
419 $rl->getLogger()->info(
420 'Invalid wiki page title "{title}" in ' . __METHOD__,
421 [ 'title' => $page ]
422 );
423 }
424 }
425 $info = array_intersect_key( $allInfo, $intersect );
426 $pageNames = array_keys( $pages );
427 sort( $pageNames );
428 $key = implode( '|', $pageNames );
429 $wikiModule->setTitleInfo( $key, $info );
430 }
431 }
432
443 public static function invalidateModuleCache(
444 Title $title, Revision $old = null, Revision $new = null, $wikiId
445 ) {
446 static $formats = [ CONTENT_FORMAT_CSS, CONTENT_FORMAT_JAVASCRIPT ];
447
448 if ( $old && in_array( $old->getContentFormat(), $formats ) ) {
449 $purge = true;
450 } elseif ( $new && in_array( $new->getContentFormat(), $formats ) ) {
451 $purge = true;
452 } else {
453 $purge = ( $title->isSiteConfigPage() || $title->isUserConfigPage() );
454 }
455
456 if ( $purge ) {
457 $cache = ObjectCache::getMainWANInstance();
458 $key = $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $wikiId );
459 $cache->touchCheckKey( $key );
460 }
461 }
462
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;
472 }
473}
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
The package scripts
Definition README.txt:1
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
Definition Setup.php:112
Class representing a list of titles The execute() method checks them all for existence and adds them ...
Definition LinkBatch.php:34
static call( $callable, array $args=[], $ttl=3600)
Shortcut method for creating a MemoizedCallable and invoking it with the specified arguments.
Object passed around to modules which contains information about the state of a specific loader reque...
Abstraction for ResourceLoader modules, with name registration and maxage functionality.
validateScriptFile( $fileName, $contents)
Validate a given script file; if valid returns the original source.
Abstraction for ResourceLoader modules which pull from wiki pages.
setTitleInfo( $key, array $titleInfo)
getTitleInfo(ResourceLoaderContext $context)
Get the information about the wiki pages for a given context.
getDB()
Get the Database object used in getTitleInfo().
static preloadTitleInfo(ResourceLoaderContext $context, IDatabase $db, array $moduleNames)
enableModuleContentVersion()
Disable module content versioning.
getPages(ResourceLoaderContext $context)
Subclasses should return an associative array of resources in the module.
static fetchTitleInfo(IDatabase $db, array $pages, $fname=__METHOD__)
getDefinitionSummary(ResourceLoaderContext $context)
getStyles(ResourceLoaderContext $context)
static invalidateModuleCache(Title $title, Revision $old=null, Revision $new=null, $wikiId)
Clear the preloadTitleInfo() cache for all wiki modules on this wiki on page change if it was a JS or...
isKnownEmpty(ResourceLoaderContext $context)
getScript(ResourceLoaderContext $context)
static makeComment( $text)
Generate a CSS or JS comment block.
Represents a title within MediaWiki.
Definition Title.php:39
Relational database abstraction object.
Definition Database.php:48
$res
Definition database.txt:21
when a variable name is used in a function
Definition design.txt:94
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition hooks.txt:2001
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition hooks.txt:2811
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check set to true or false to override the $wgMaxImageArea check result gives extension the possibility to transform it themselves $handler
Definition hooks.txt:903
const CONTENT_FORMAT_JAVASCRIPT
Definition Defines.php:262
const CONTENT_FORMAT_CSS
Definition Defines.php:264
get( $name)
Get a configuration variable such as "Sitename" or "UploadMaintenance.".
Basic database interface for live and lazy-loaded relation database handles.
Definition IDatabase.php:38
select( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Execute a SELECT query constructed using the various parameters provided.
$batch
Definition linkcache.txt:23
$cache
Definition mcc.php:33
const DB_REPLICA
Definition defines.php:25