MediaWiki REL1_33
ResourceLoaderWikiModule.php
Go to the documentation of this file.
1<?php
26use Wikimedia\Assert\Assert;
30
52
53 // Origin defaults to users with sitewide authority
54 protected $origin = self::ORIGIN_USER_SITEWIDE;
55
56 // In-process cache for title info, structured as an array
57 // [
58 // <batchKey> // Pipe-separated list of sorted keys from getPages
59 // => [
60 // <titleKey> => [ // Normalised title key
61 // 'page_len' => ..,
62 // 'page_latest' => ..,
63 // 'page_touched' => ..,
64 // ]
65 // ]
66 // ]
67 // @see self::fetchTitleInfo()
68 // @see self::makeTitleKey()
69 protected $titleInfo = [];
70
71 // List of page names that contain CSS
72 protected $styles = [];
73
74 // List of page names that contain JavaScript
75 protected $scripts = [];
76
77 // Group of module
78 protected $group;
79
84 public function __construct( array $options = null ) {
85 if ( is_null( $options ) ) {
86 return;
87 }
88
89 foreach ( $options as $member => $option ) {
90 switch ( $member ) {
91 case 'styles':
92 case 'scripts':
93 case 'group':
94 case 'targets':
95 $this->{$member} = $option;
96 break;
97 }
98 }
99 }
100
118 $config = $this->getConfig();
119 $pages = [];
120
121 // Filter out pages from origins not allowed by the current wiki configuration.
122 if ( $config->get( 'UseSiteJs' ) ) {
123 foreach ( $this->scripts as $script ) {
124 $pages[$script] = [ 'type' => 'script' ];
125 }
126 }
127
128 if ( $config->get( 'UseSiteCss' ) ) {
129 foreach ( $this->styles as $style ) {
130 $pages[$style] = [ 'type' => 'style' ];
131 }
132 }
133
134 return $pages;
135 }
136
142 public function getGroup() {
143 return $this->group;
144 }
145
157 protected function getDB() {
158 return wfGetDB( DB_REPLICA );
159 }
160
167 protected function getContent( $titleText, ResourceLoaderContext $context = null ) {
168 $title = Title::newFromText( $titleText );
169 if ( !$title ) {
170 return null; // Bad title
171 }
172
174 if ( !$content ) {
175 return null; // No content found
176 }
177
178 $handler = $content->getContentHandler();
179 if ( $handler->isSupportedFormat( CONTENT_FORMAT_CSS ) ) {
180 $format = CONTENT_FORMAT_CSS;
181 } elseif ( $handler->isSupportedFormat( CONTENT_FORMAT_JAVASCRIPT ) ) {
183 } else {
184 return null; // Bad content model
185 }
186
187 return $content->serialize( $format );
188 }
189
198 protected function getContentObj(
199 Title $title, ResourceLoaderContext $context = null, $maxRedirects = null
200 ) {
201 if ( $context === null ) {
202 wfDeprecated( __METHOD__ . ' without a ResourceLoader context', '1.32' );
203 }
204
205 $overrideCallback = $context ? $context->getContentOverrideCallback() : null;
206 $content = $overrideCallback ? call_user_func( $overrideCallback, $title ) : null;
207 if ( $content ) {
208 if ( !$content instanceof Content ) {
209 $this->getLogger()->error(
210 'Bad content override for "{title}" in ' . __METHOD__,
211 [ 'title' => $title->getPrefixedText() ]
212 );
213 return null;
214 }
215 } else {
217 if ( !$revision ) {
218 return null;
219 }
220 $content = $revision->getContent( Revision::RAW );
221
222 if ( !$content ) {
223 $this->getLogger()->error(
224 'Failed to load content of JS/CSS page "{title}" in ' . __METHOD__,
225 [ 'title' => $title->getPrefixedText() ]
226 );
227 return null;
228 }
229 }
230
231 if ( $content && $content->isRedirect() ) {
232 if ( $maxRedirects === null ) {
233 $maxRedirects = $this->getConfig()->get( 'MaxRedirects' ) ?: 0;
234 }
235 if ( $maxRedirects > 0 ) {
236 $newTitle = $content->getRedirectTarget();
237 return $newTitle ? $this->getContentObj( $newTitle, $context, $maxRedirects - 1 ) : null;
238 }
239 }
240
241 return $content;
242 }
243
249 $overrideCallback = $context->getContentOverrideCallback();
250 if ( $overrideCallback && $this->getSource() === 'local' ) {
251 foreach ( $this->getPages( $context ) as $page => $info ) {
252 $title = Title::newFromText( $page );
253 if ( $title && call_user_func( $overrideCallback, $title ) !== null ) {
254 return true;
255 }
256 }
257 }
258
259 return parent::shouldEmbedModule( $context );
260 }
261
267 $scripts = '';
268 foreach ( $this->getPages( $context ) as $titleText => $options ) {
269 if ( $options['type'] !== 'script' ) {
270 continue;
271 }
272 $script = $this->getContent( $titleText, $context );
273 if ( strval( $script ) !== '' ) {
274 $script = $this->validateScriptFile( $titleText, $script );
275 $scripts .= ResourceLoader::makeComment( $titleText ) . $script . "\n";
276 }
277 }
278 return $scripts;
279 }
280
286 $styles = [];
287 foreach ( $this->getPages( $context ) as $titleText => $options ) {
288 if ( $options['type'] !== 'style' ) {
289 continue;
290 }
291 $media = $options['media'] ?? 'all';
292 $style = $this->getContent( $titleText, $context );
293 if ( strval( $style ) === '' ) {
294 continue;
295 }
296 if ( $this->getFlip( $context ) ) {
297 $style = CSSJanus::transform( $style, true, false );
298 }
299 $style = MemoizedCallable::call( 'CSSMin::remap',
300 [ $style, false, $this->getConfig()->get( 'ScriptPath' ), true ] );
301 if ( !isset( $styles[$media] ) ) {
302 $styles[$media] = [];
303 }
304 $style = ResourceLoader::makeComment( $titleText ) . $style;
305 $styles[$media][] = $style;
306 }
307 return $styles;
308 }
309
320 public function enableModuleContentVersion() {
321 return false;
322 }
323
329 $summary = parent::getDefinitionSummary( $context );
330 $summary[] = [
331 'pages' => $this->getPages( $context ),
332 // Includes meta data of current revisions
333 'titleInfo' => $this->getTitleInfo( $context ),
334 ];
335 return $summary;
336 }
337
343 $revisions = $this->getTitleInfo( $context );
344
345 // If a module has dependencies it cannot be empty. An empty array will be cast to false
346 if ( $this->getDependencies() ) {
347 return false;
348 }
349 // For user modules, don't needlessly load if there are no non-empty pages
350 if ( $this->getGroup() === 'user' ) {
351 foreach ( $revisions as $revision ) {
352 if ( $revision['page_len'] > 0 ) {
353 // At least one non-empty page, module should be loaded
354 return false;
355 }
356 }
357 return true;
358 }
359
360 // T70488: For other modules (i.e. ones that are called in cached html output) only check
361 // page existance. This ensures that, if some pages in a module are temporarily blanked,
362 // we don't end omit the module's script or link tag on some pages.
363 return count( $revisions ) === 0;
364 }
365
366 private function setTitleInfo( $batchKey, array $titleInfo ) {
367 $this->titleInfo[$batchKey] = $titleInfo;
368 }
369
370 private static function makeTitleKey( LinkTarget $title ) {
371 // Used for keys in titleInfo.
372 return "{$title->getNamespace()}:{$title->getDBkey()}";
373 }
374
381 $dbr = $this->getDB();
382 if ( !$dbr ) {
383 // We're dealing with a subclass that doesn't have a DB
384 return [];
385 }
386
387 $pageNames = array_keys( $this->getPages( $context ) );
388 sort( $pageNames );
389 $batchKey = implode( '|', $pageNames );
390 if ( !isset( $this->titleInfo[$batchKey] ) ) {
391 $this->titleInfo[$batchKey] = static::fetchTitleInfo( $dbr, $pageNames, __METHOD__ );
392 }
393
394 $titleInfo = $this->titleInfo[$batchKey];
395
396 // Override the title info from the overrides, if any
397 $overrideCallback = $context->getContentOverrideCallback();
398 if ( $overrideCallback ) {
399 foreach ( $pageNames as $page ) {
400 $title = Title::newFromText( $page );
401 $content = $title ? call_user_func( $overrideCallback, $title ) : null;
402 if ( $content !== null ) {
403 $titleInfo[$title->getPrefixedText()] = [
404 'page_len' => $content->getSize(),
405 'page_latest' => 'TBD', // None available
406 'page_touched' => wfTimestamp( TS_MW ),
407 ];
408 }
409 }
410 }
411
412 return $titleInfo;
413 }
414
415 protected static function fetchTitleInfo( IDatabase $db, array $pages, $fname = __METHOD__ ) {
416 $titleInfo = [];
417 $batch = new LinkBatch;
418 foreach ( $pages as $titleText ) {
419 $title = Title::newFromText( $titleText );
420 if ( $title ) {
421 // Page name may be invalid if user-provided (e.g. gadgets)
422 $batch->addObj( $title );
423 }
424 }
425 if ( !$batch->isEmpty() ) {
426 $res = $db->select( 'page',
427 // Include page_touched to allow purging if cache is poisoned (T117587, T113916)
428 [ 'page_namespace', 'page_title', 'page_touched', 'page_len', 'page_latest' ],
429 $batch->constructSet( 'page', $db ),
430 $fname
431 );
432 foreach ( $res as $row ) {
433 // Avoid including ids or timestamps of revision/page tables so
434 // that versions are not wasted
435 $title = new TitleValue( (int)$row->page_namespace, $row->page_title );
436 $titleInfo[self::makeTitleKey( $title )] = [
437 'page_len' => $row->page_len,
438 'page_latest' => $row->page_latest,
439 'page_touched' => $row->page_touched,
440 ];
441 }
442 }
443 return $titleInfo;
444 }
445
452 public static function preloadTitleInfo(
454 ) {
455 $rl = $context->getResourceLoader();
456 // getDB() can be overridden to point to a foreign database.
457 // For now, only preload local. In the future, we could preload by wikiID.
458 $allPages = [];
460 $wikiModules = [];
461 foreach ( $moduleNames as $name ) {
462 $module = $rl->getModule( $name );
463 if ( $module instanceof self ) {
464 $mDB = $module->getDB();
465 // Subclasses may disable getDB and implement getTitleInfo differently
466 if ( $mDB && $mDB->getDomainID() === $db->getDomainID() ) {
467 $wikiModules[] = $module;
468 $allPages += $module->getPages( $context );
469 }
470 }
471 }
472
473 if ( !$wikiModules ) {
474 // Nothing to preload
475 return;
476 }
477
478 $pageNames = array_keys( $allPages );
479 sort( $pageNames );
480 $hash = sha1( implode( '|', $pageNames ) );
481
482 // Avoid Zend bug where "static::" does not apply LSB in the closure
483 $func = [ static::class, 'fetchTitleInfo' ];
484 $fname = __METHOD__;
485
486 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
487 $allInfo = $cache->getWithSetCallback(
488 $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $db->getDomainID(), $hash ),
489 $cache::TTL_HOUR,
490 function ( $curVal, &$ttl, array &$setOpts ) use ( $func, $pageNames, $db, $fname ) {
491 $setOpts += Database::getCacheSetOptions( $db );
492
493 return call_user_func( $func, $db, $pageNames, $fname );
494 },
495 [
496 'checkKeys' => [
497 $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $db->getDomainID() ) ]
498 ]
499 );
500
501 foreach ( $wikiModules as $wikiModule ) {
502 $pages = $wikiModule->getPages( $context );
503 // Before we intersect, map the names to canonical form (T145673).
504 $intersect = [];
505 foreach ( $pages as $pageName => $unused ) {
506 $title = Title::newFromText( $pageName );
507 if ( $title ) {
508 $intersect[ self::makeTitleKey( $title ) ] = 1;
509 } else {
510 // Page name may be invalid if user-provided (e.g. gadgets)
511 $rl->getLogger()->info(
512 'Invalid wiki page title "{title}" in ' . __METHOD__,
513 [ 'title' => $pageName ]
514 );
515 }
516 }
517 $info = array_intersect_key( $allInfo, $intersect );
518 $pageNames = array_keys( $pages );
519 sort( $pageNames );
520 $batchKey = implode( '|', $pageNames );
521 $wikiModule->setTitleInfo( $batchKey, $info );
522 }
523 }
524
535 public static function invalidateModuleCache(
536 Title $title, Revision $old = null, Revision $new = null, $domain
537 ) {
538 static $formats = [ CONTENT_FORMAT_CSS, CONTENT_FORMAT_JAVASCRIPT ];
539
540 Assert::parameterType( 'string', $domain, '$domain' );
541
542 // TODO: MCR: differentiate between page functionality and content model!
543 // Not all pages containing CSS or JS have to be modules! [PageType]
544 if ( $old && in_array( $old->getContentFormat(), $formats ) ) {
545 $purge = true;
546 } elseif ( $new && in_array( $new->getContentFormat(), $formats ) ) {
547 $purge = true;
548 } else {
549 $purge = ( $title->isSiteConfigPage() || $title->isUserConfigPage() );
550 }
551
552 if ( $purge ) {
553 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
554 $key = $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $domain );
555 $cache->touchCheckKey( $key );
556 }
557 }
558
563 public function getType() {
564 // Check both because subclasses don't always pass pages via the constructor,
565 // they may also override getPages() instead, in which case we should keep
566 // defaulting to LOAD_GENERAL and allow them to override getType() separately.
567 return ( $this->styles && !$this->scripts ) ? self::LOAD_STYLES : self::LOAD_GENERAL;
568 }
569}
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:123
Class representing a list of titles The execute() method checks them all for existence and adds them ...
Definition LinkBatch.php:34
MediaWikiServices is the service locator for the application scope of MediaWiki.
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)
isKnownEmpty(ResourceLoaderContext $context)
getContent( $titleText, ResourceLoaderContext $context=null)
getScript(ResourceLoaderContext $context)
static invalidateModuleCache(Title $title, Revision $old=null, Revision $new=null, $domain)
Clear the preloadTitleInfo() cache for all wiki modules on this wiki on page change if it was a JS or...
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:56
Represents a page (or page fragment) title within MediaWiki.
Represents a title within MediaWiki.
Definition Title.php:40
Relational database abstraction object.
Definition Database.php:49
$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:261
const CONTENT_FORMAT_CSS
Definition Defines.php:263
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password 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:894
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:1999
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:2848
namespace and then decline to actually register it file or subcat img or subcat $title
Definition hooks.txt:955
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:271
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