MediaWiki REL1_32
ResourceLoaderWikiModule.php
Go to the documentation of this file.
1<?php
26use Wikimedia\Assert\Assert;
29
51
52 // Origin defaults to users with sitewide authority
53 protected $origin = self::ORIGIN_USER_SITEWIDE;
54
55 // In-process cache for title info, structured as an array
56 // [
57 // <batchKey> // Pipe-separated list of sorted keys from getPages
58 // => [
59 // <titleKey> => [ // Normalised title key
60 // 'page_len' => ..,
61 // 'page_latest' => ..,
62 // 'page_touched' => ..,
63 // ]
64 // ]
65 // ]
66 // @see self::fetchTitleInfo()
67 // @see self::makeTitleKey()
68 protected $titleInfo = [];
69
70 // List of page names that contain CSS
71 protected $styles = [];
72
73 // List of page names that contain JavaScript
74 protected $scripts = [];
75
76 // Group of module
77 protected $group;
78
83 public function __construct( array $options = null ) {
84 if ( is_null( $options ) ) {
85 return;
86 }
87
88 foreach ( $options as $member => $option ) {
89 switch ( $member ) {
90 case 'styles':
91 case 'scripts':
92 case 'group':
93 case 'targets':
94 $this->{$member} = $option;
95 break;
96 }
97 }
98 }
99
117 $config = $this->getConfig();
118 $pages = [];
119
120 // Filter out pages from origins not allowed by the current wiki configuration.
121 if ( $config->get( 'UseSiteJs' ) ) {
122 foreach ( $this->scripts as $script ) {
123 $pages[$script] = [ 'type' => 'script' ];
124 }
125 }
126
127 if ( $config->get( 'UseSiteCss' ) ) {
128 foreach ( $this->styles as $style ) {
129 $pages[$style] = [ 'type' => 'style' ];
130 }
131 }
132
133 return $pages;
134 }
135
141 public function getGroup() {
142 return $this->group;
143 }
144
156 protected function getDB() {
157 return wfGetDB( DB_REPLICA );
158 }
159
166 protected function getContent( $titleText, ResourceLoaderContext $context = null ) {
167 $title = Title::newFromText( $titleText );
168 if ( !$title ) {
169 return null; // Bad title
170 }
171
173 if ( !$content ) {
174 return null; // No content found
175 }
176
177 $handler = $content->getContentHandler();
178 if ( $handler->isSupportedFormat( CONTENT_FORMAT_CSS ) ) {
179 $format = CONTENT_FORMAT_CSS;
180 } elseif ( $handler->isSupportedFormat( CONTENT_FORMAT_JAVASCRIPT ) ) {
182 } else {
183 return null; // Bad content model
184 }
185
186 return $content->serialize( $format );
187 }
188
197 protected function getContentObj(
198 Title $title, ResourceLoaderContext $context = null, $maxRedirects = null
199 ) {
200 if ( $context === null ) {
201 wfDeprecated( __METHOD__ . ' without a ResourceLoader context', '1.32' );
202 }
203
204 $overrideCallback = $context ? $context->getContentOverrideCallback() : null;
205 $content = $overrideCallback ? call_user_func( $overrideCallback, $title ) : null;
206 if ( $content ) {
207 if ( !$content instanceof Content ) {
208 $this->getLogger()->error(
209 'Bad content override for "{title}" in ' . __METHOD__,
210 [ 'title' => $title->getPrefixedText() ]
211 );
212 return null;
213 }
214 } else {
216 if ( !$revision ) {
217 return null;
218 }
219 $content = $revision->getContent( Revision::RAW );
220
221 if ( !$content ) {
222 $this->getLogger()->error(
223 'Failed to load content of JS/CSS page "{title}" in ' . __METHOD__,
224 [ 'title' => $title->getPrefixedText() ]
225 );
226 return null;
227 }
228 }
229
230 if ( $content && $content->isRedirect() ) {
231 if ( $maxRedirects === null ) {
232 $maxRedirects = $this->getConfig()->get( 'MaxRedirects' ) ?: 0;
233 }
234 if ( $maxRedirects > 0 ) {
235 $newTitle = $content->getRedirectTarget();
236 return $newTitle ? $this->getContentObj( $newTitle, $context, $maxRedirects - 1 ) : null;
237 }
238 }
239
240 return $content;
241 }
242
248 $overrideCallback = $context->getContentOverrideCallback();
249 if ( $overrideCallback && $this->getSource() === 'local' ) {
250 foreach ( $this->getPages( $context ) as $page => $info ) {
251 $title = Title::newFromText( $page );
252 if ( $title && call_user_func( $overrideCallback, $title ) !== null ) {
253 return true;
254 }
255 }
256 }
257
258 return parent::shouldEmbedModule( $context );
259 }
260
266 $scripts = '';
267 foreach ( $this->getPages( $context ) as $titleText => $options ) {
268 if ( $options['type'] !== 'script' ) {
269 continue;
270 }
271 $script = $this->getContent( $titleText, $context );
272 if ( strval( $script ) !== '' ) {
273 $script = $this->validateScriptFile( $titleText, $script );
274 $scripts .= ResourceLoader::makeComment( $titleText ) . $script . "\n";
275 }
276 }
277 return $scripts;
278 }
279
285 $styles = [];
286 foreach ( $this->getPages( $context ) as $titleText => $options ) {
287 if ( $options['type'] !== 'style' ) {
288 continue;
289 }
290 $media = $options['media'] ?? 'all';
291 $style = $this->getContent( $titleText, $context );
292 if ( strval( $style ) === '' ) {
293 continue;
294 }
295 if ( $this->getFlip( $context ) ) {
296 $style = CSSJanus::transform( $style, true, false );
297 }
298 $style = MemoizedCallable::call( 'CSSMin::remap',
299 [ $style, false, $this->getConfig()->get( 'ScriptPath' ), true ] );
300 if ( !isset( $styles[$media] ) ) {
301 $styles[$media] = [];
302 }
303 $style = ResourceLoader::makeComment( $titleText ) . $style;
304 $styles[$media][] = $style;
305 }
306 return $styles;
307 }
308
319 public function enableModuleContentVersion() {
320 return false;
321 }
322
328 $summary = parent::getDefinitionSummary( $context );
329 $summary[] = [
330 'pages' => $this->getPages( $context ),
331 // Includes meta data of current revisions
332 'titleInfo' => $this->getTitleInfo( $context ),
333 ];
334 return $summary;
335 }
336
342 $revisions = $this->getTitleInfo( $context );
343
344 // If a module has dependencies it cannot be empty. An empty array will be cast to false
345 if ( $this->getDependencies() ) {
346 return false;
347 }
348 // For user modules, don't needlessly load if there are no non-empty pages
349 if ( $this->getGroup() === 'user' ) {
350 foreach ( $revisions as $revision ) {
351 if ( $revision['page_len'] > 0 ) {
352 // At least one non-empty page, module should be loaded
353 return false;
354 }
355 }
356 return true;
357 }
358
359 // T70488: For other modules (i.e. ones that are called in cached html output) only check
360 // page existance. This ensures that, if some pages in a module are temporarily blanked,
361 // we don't end omit the module's script or link tag on some pages.
362 return count( $revisions ) === 0;
363 }
364
365 private function setTitleInfo( $batchKey, array $titleInfo ) {
366 $this->titleInfo[$batchKey] = $titleInfo;
367 }
368
369 private static function makeTitleKey( LinkTarget $title ) {
370 // Used for keys in titleInfo.
371 return "{$title->getNamespace()}:{$title->getDBkey()}";
372 }
373
380 $dbr = $this->getDB();
381 if ( !$dbr ) {
382 // We're dealing with a subclass that doesn't have a DB
383 return [];
384 }
385
386 $pageNames = array_keys( $this->getPages( $context ) );
387 sort( $pageNames );
388 $batchKey = implode( '|', $pageNames );
389 if ( !isset( $this->titleInfo[$batchKey] ) ) {
390 $this->titleInfo[$batchKey] = static::fetchTitleInfo( $dbr, $pageNames, __METHOD__ );
391 }
392
393 $titleInfo = $this->titleInfo[$batchKey];
394
395 // Override the title info from the overrides, if any
396 $overrideCallback = $context->getContentOverrideCallback();
397 if ( $overrideCallback ) {
398 foreach ( $pageNames as $page ) {
399 $title = Title::newFromText( $page );
400 $content = $title ? call_user_func( $overrideCallback, $title ) : null;
401 if ( $content !== null ) {
402 $titleInfo[$title->getPrefixedText()] = [
403 'page_len' => $content->getSize(),
404 'page_latest' => 'TBD', // None available
405 'page_touched' => wfTimestamp( TS_MW ),
406 ];
407 }
408 }
409 }
410
411 return $titleInfo;
412 }
413
414 protected static function fetchTitleInfo( IDatabase $db, array $pages, $fname = __METHOD__ ) {
415 $titleInfo = [];
416 $batch = new LinkBatch;
417 foreach ( $pages as $titleText ) {
418 $title = Title::newFromText( $titleText );
419 if ( $title ) {
420 // Page name may be invalid if user-provided (e.g. gadgets)
421 $batch->addObj( $title );
422 }
423 }
424 if ( !$batch->isEmpty() ) {
425 $res = $db->select( 'page',
426 // Include page_touched to allow purging if cache is poisoned (T117587, T113916)
427 [ 'page_namespace', 'page_title', 'page_touched', 'page_len', 'page_latest' ],
428 $batch->constructSet( 'page', $db ),
429 $fname
430 );
431 foreach ( $res as $row ) {
432 // Avoid including ids or timestamps of revision/page tables so
433 // that versions are not wasted
434 $title = new TitleValue( (int)$row->page_namespace, $row->page_title );
435 $titleInfo[ self::makeTitleKey( $title ) ] = [
436 'page_len' => $row->page_len,
437 'page_latest' => $row->page_latest,
438 'page_touched' => $row->page_touched,
439 ];
440 }
441 }
442 return $titleInfo;
443 }
444
451 public static function preloadTitleInfo(
453 ) {
454 $rl = $context->getResourceLoader();
455 // getDB() can be overridden to point to a foreign database.
456 // For now, only preload local. In the future, we could preload by wikiID.
457 $allPages = [];
459 $wikiModules = [];
460 foreach ( $moduleNames as $name ) {
461 $module = $rl->getModule( $name );
462 if ( $module instanceof self ) {
463 $mDB = $module->getDB();
464 // Subclasses may disable getDB and implement getTitleInfo differently
465 if ( $mDB && $mDB->getDomainID() === $db->getDomainID() ) {
466 $wikiModules[] = $module;
467 $allPages += $module->getPages( $context );
468 }
469 }
470 }
471
472 if ( !$wikiModules ) {
473 // Nothing to preload
474 return;
475 }
476
477 $pageNames = array_keys( $allPages );
478 sort( $pageNames );
479 $hash = sha1( implode( '|', $pageNames ) );
480
481 // Avoid Zend bug where "static::" does not apply LSB in the closure
482 $func = [ static::class, 'fetchTitleInfo' ];
483 $fname = __METHOD__;
484
485 $cache = ObjectCache::getMainWANInstance();
486 $allInfo = $cache->getWithSetCallback(
487 $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $db->getDomainID(), $hash ),
488 $cache::TTL_HOUR,
489 function ( $curVal, &$ttl, array &$setOpts ) use ( $func, $pageNames, $db, $fname ) {
490 $setOpts += Database::getCacheSetOptions( $db );
491
492 return call_user_func( $func, $db, $pageNames, $fname );
493 },
494 [
495 'checkKeys' => [
496 $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $db->getDomainID() ) ]
497 ]
498 );
499
500 foreach ( $wikiModules as $wikiModule ) {
501 $pages = $wikiModule->getPages( $context );
502 // Before we intersect, map the names to canonical form (T145673).
503 $intersect = [];
504 foreach ( $pages as $pageName => $unused ) {
505 $title = Title::newFromText( $pageName );
506 if ( $title ) {
507 $intersect[ self::makeTitleKey( $title ) ] = 1;
508 } else {
509 // Page name may be invalid if user-provided (e.g. gadgets)
510 $rl->getLogger()->info(
511 'Invalid wiki page title "{title}" in ' . __METHOD__,
512 [ 'title' => $pageName ]
513 );
514 }
515 }
516 $info = array_intersect_key( $allInfo, $intersect );
517 $pageNames = array_keys( $pages );
518 sort( $pageNames );
519 $batchKey = implode( '|', $pageNames );
520 $wikiModule->setTitleInfo( $batchKey, $info );
521 }
522 }
523
534 public static function invalidateModuleCache(
535 Title $title, Revision $old = null, Revision $new = null, $wikiId
536 ) {
537 static $formats = [ CONTENT_FORMAT_CSS, CONTENT_FORMAT_JAVASCRIPT ];
538
539 Assert::parameterType( 'string', $wikiId, '$wikiId' );
540
541 // TODO: MCR: differentiate between page functionality and content model!
542 // Not all pages containing CSS or JS have to be modules! [PageType]
543 if ( $old && in_array( $old->getContentFormat(), $formats ) ) {
544 $purge = true;
545 } elseif ( $new && in_array( $new->getContentFormat(), $formats ) ) {
546 $purge = true;
547 } else {
548 $purge = ( $title->isSiteConfigPage() || $title->isUserConfigPage() );
549 }
550
551 if ( $purge ) {
552 $cache = ObjectCache::getMainWANInstance();
553 $key = $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $wikiId );
554 $cache->touchCheckKey( $key );
555 }
556 }
557
562 public function getType() {
563 // Check both because subclasses don't always pass pages via the constructor,
564 // they may also override getPages() instead, in which case we should keep
565 // defaulting to LOAD_GENERAL and allow them to override getType() separately.
566 return ( $this->styles && !$this->scripts ) ? self::LOAD_STYLES : self::LOAD_GENERAL;
567 }
568}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
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:121
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.
getDependencies(ResourceLoaderContext $context=null)
Get a list of modules this module depends on.
validateScriptFile( $fileName, $contents)
Validate a given script file; if valid returns the original source.
getSource()
Get the source of this module.
Abstraction for ResourceLoader modules which pull from wiki pages.
getContentObj(Title $title, ResourceLoaderContext $context=null, $maxRedirects=null)
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.
shouldEmbedModule(ResourceLoaderContext $context)
static fetchTitleInfo(IDatabase $db, array $pages, $fname=__METHOD__)
static makeTitleKey(LinkTarget $title)
getDefinitionSummary(ResourceLoaderContext $context)
setTitleInfo( $batchKey, array $titleInfo)
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)
getContent( $titleText, ResourceLoaderContext $context=null)
getScript(ResourceLoaderContext $context)
static makeComment( $text)
Generate a CSS or JS comment block.
static newKnownCurrent(IDatabase $db, $pageIdOrTitle, $revId=0)
Load a revision based on a known page ID and current revision ID from the DB.
const RAW
Definition Revision.php:57
Represents a page (or page fragment) title within MediaWiki.
Represents a title within MediaWiki.
Definition Title.php:39
Relational database abstraction object.
Definition Database.php:48
$res
Definition database.txt:21
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
const CONTENT_FORMAT_JAVASCRIPT
Definition Defines.php:252
const CONTENT_FORMAT_CSS
Definition Defines.php:254
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:2050
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:2885
namespace and then decline to actually register it file or subcat img or subcat $title
Definition hooks.txt:994
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:302
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:933
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback function
Definition injection.txt:30
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37
get( $name)
Get a configuration variable such as "Sitename" or "UploadMaintenance.".
Base interface for content objects.
Definition Content.php:34
Basic database interface for live and lazy-loaded relation database handles.
Definition IDatabase.php:38
getDomainID()
Return the currently selected domain ID.
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
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
$content
const DB_REPLICA
Definition defines.php:25