MediaWiki  1.29.1
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 
101  protected function getPages( ResourceLoaderContext $context ) {
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 
165  if ( $handler->isSupportedFormat( CONTENT_FORMAT_CSS ) ) {
166  $format = CONTENT_FORMAT_CSS;
167  } elseif ( $handler->isSupportedFormat( CONTENT_FORMAT_JAVASCRIPT ) ) {
168  $format = 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->getArticleID(),
187  $title->getLatestRevID() );
188  if ( !$revision ) {
189  return null;
190  }
191  $revision->setTitle( $title );
192  $content = $revision->getContent( Revision::RAW );
193  if ( !$content ) {
194  wfDebugLog( 'resourceloader', __METHOD__ . ': failed to load content of JS/CSS page!' );
195  return null;
196  }
197  return $content;
198  }
199 
205  $scripts = '';
206  foreach ( $this->getPages( $context ) as $titleText => $options ) {
207  if ( $options['type'] !== 'script' ) {
208  continue;
209  }
210  $script = $this->getContent( $titleText );
211  if ( strval( $script ) !== '' ) {
212  $script = $this->validateScriptFile( $titleText, $script );
213  $scripts .= ResourceLoader::makeComment( $titleText ) . $script . "\n";
214  }
215  }
216  return $scripts;
217  }
218 
224  $styles = [];
225  foreach ( $this->getPages( $context ) as $titleText => $options ) {
226  if ( $options['type'] !== 'style' ) {
227  continue;
228  }
229  $media = isset( $options['media'] ) ? $options['media'] : 'all';
230  $style = $this->getContent( $titleText );
231  if ( strval( $style ) === '' ) {
232  continue;
233  }
234  if ( $this->getFlip( $context ) ) {
235  $style = CSSJanus::transform( $style, true, false );
236  }
237  $style = MemoizedCallable::call( 'CSSMin::remap',
238  [ $style, false, $this->getConfig()->get( 'ScriptPath' ), true ] );
239  if ( !isset( $styles[$media] ) ) {
240  $styles[$media] = [];
241  }
242  $style = ResourceLoader::makeComment( $titleText ) . $style;
243  $styles[$media][] = $style;
244  }
245  return $styles;
246  }
247 
258  public function enableModuleContentVersion() {
259  return false;
260  }
261 
267  $summary = parent::getDefinitionSummary( $context );
268  $summary[] = [
269  'pages' => $this->getPages( $context ),
270  // Includes meta data of current revisions
271  'titleInfo' => $this->getTitleInfo( $context ),
272  ];
273  return $summary;
274  }
275 
281  $revisions = $this->getTitleInfo( $context );
282 
283  // For user modules, don't needlessly load if there are no non-empty pages
284  if ( $this->getGroup() === 'user' ) {
285  foreach ( $revisions as $revision ) {
286  if ( $revision['page_len'] > 0 ) {
287  // At least one non-empty page, module should be loaded
288  return false;
289  }
290  }
291  return true;
292  }
293 
294  // T70488: For other modules (i.e. ones that are called in cached html output) only check
295  // page existance. This ensures that, if some pages in a module are temporarily blanked,
296  // we don't end omit the module's script or link tag on some pages.
297  return count( $revisions ) === 0;
298  }
299 
300  private function setTitleInfo( $key, array $titleInfo ) {
301  $this->titleInfo[$key] = $titleInfo;
302  }
303 
310  $dbr = $this->getDB();
311  if ( !$dbr ) {
312  // We're dealing with a subclass that doesn't have a DB
313  return [];
314  }
315 
316  $pageNames = array_keys( $this->getPages( $context ) );
317  sort( $pageNames );
318  $key = implode( '|', $pageNames );
319  if ( !isset( $this->titleInfo[$key] ) ) {
320  $this->titleInfo[$key] = static::fetchTitleInfo( $dbr, $pageNames, __METHOD__ );
321  }
322  return $this->titleInfo[$key];
323  }
324 
325  protected static function fetchTitleInfo( IDatabase $db, array $pages, $fname = __METHOD__ ) {
326  $titleInfo = [];
327  $batch = new LinkBatch;
328  foreach ( $pages as $titleText ) {
329  $title = Title::newFromText( $titleText );
330  if ( $title ) {
331  // Page name may be invalid if user-provided (e.g. gadgets)
332  $batch->addObj( $title );
333  }
334  }
335  if ( !$batch->isEmpty() ) {
336  $res = $db->select( 'page',
337  // Include page_touched to allow purging if cache is poisoned (T117587, T113916)
338  [ 'page_namespace', 'page_title', 'page_touched', 'page_len', 'page_latest' ],
339  $batch->constructSet( 'page', $db ),
340  $fname
341  );
342  foreach ( $res as $row ) {
343  // Avoid including ids or timestamps of revision/page tables so
344  // that versions are not wasted
345  $title = Title::makeTitle( $row->page_namespace, $row->page_title );
346  $titleInfo[$title->getPrefixedText()] = [
347  'page_len' => $row->page_len,
348  'page_latest' => $row->page_latest,
349  'page_touched' => $row->page_touched,
350  ];
351  }
352  }
353  return $titleInfo;
354  }
355 
362  public static function preloadTitleInfo(
363  ResourceLoaderContext $context, IDatabase $db, array $moduleNames
364  ) {
365  $rl = $context->getResourceLoader();
366  // getDB() can be overridden to point to a foreign database.
367  // For now, only preload local. In the future, we could preload by wikiID.
368  $allPages = [];
370  $wikiModules = [];
371  foreach ( $moduleNames as $name ) {
372  $module = $rl->getModule( $name );
373  if ( $module instanceof self ) {
374  $mDB = $module->getDB();
375  // Subclasses may disable getDB and implement getTitleInfo differently
376  if ( $mDB && $mDB->getWikiID() === $db->getWikiID() ) {
377  $wikiModules[] = $module;
378  $allPages += $module->getPages( $context );
379  }
380  }
381  }
382 
383  if ( !$wikiModules ) {
384  // Nothing to preload
385  return;
386  }
387 
388  $pageNames = array_keys( $allPages );
389  sort( $pageNames );
390  $hash = sha1( implode( '|', $pageNames ) );
391 
392  // Avoid Zend bug where "static::" does not apply LSB in the closure
393  $func = [ static::class, 'fetchTitleInfo' ];
394  $fname = __METHOD__;
395 
397  $allInfo = $cache->getWithSetCallback(
398  $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $db->getWikiID(), $hash ),
399  $cache::TTL_HOUR,
400  function ( $curVal, &$ttl, array &$setOpts ) use ( $func, $pageNames, $db, $fname ) {
401  $setOpts += Database::getCacheSetOptions( $db );
402 
403  return call_user_func( $func, $db, $pageNames, $fname );
404  },
405  [ 'checkKeys' => [ $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $db->getWikiID() ) ] ]
406  );
407 
408  foreach ( $wikiModules as $wikiModule ) {
409  $pages = $wikiModule->getPages( $context );
410  // Before we intersect, map the names to canonical form (T145673).
411  $intersect = [];
412  foreach ( $pages as $page => $unused ) {
414  if ( $title ) {
415  $intersect[ $title->getPrefixedText() ] = 1;
416  } else {
417  // Page name may be invalid if user-provided (e.g. gadgets)
418  $rl->getLogger()->info(
419  'Invalid wiki page title "{title}" in ' . __METHOD__,
420  [ 'title' => $page ]
421  );
422  }
423  }
424  $info = array_intersect_key( $allInfo, $intersect );
425  $pageNames = array_keys( $pages );
426  sort( $pageNames );
427  $key = implode( '|', $pageNames );
428  $wikiModule->setTitleInfo( $key, $info );
429  }
430  }
431 
442  public static function invalidateModuleCache(
443  Title $title, Revision $old = null, Revision $new = null, $wikiId
444  ) {
445  static $formats = [ CONTENT_FORMAT_CSS, CONTENT_FORMAT_JAVASCRIPT ];
446 
447  if ( $old && in_array( $old->getContentFormat(), $formats ) ) {
448  $purge = true;
449  } elseif ( $new && in_array( $new->getContentFormat(), $formats ) ) {
450  $purge = true;
451  } else {
452  $purge = ( $title->isCssOrJsPage() || $title->isCssJsSubpage() );
453  }
454 
455  if ( $purge ) {
457  $key = $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $wikiId );
458  $cache->touchCheckKey( $key );
459  }
460  }
461 
466  public function getType() {
467  // Check both because subclasses don't always pass pages via the constructor,
468  // they may also override getPages() instead, in which case we should keep
469  // defaulting to LOAD_GENERAL and allow them to override getType() separately.
470  return ( $this->styles && !$this->scripts ) ? self::LOAD_STYLES : self::LOAD_GENERAL;
471  }
472 }
ResourceLoaderModule\LOAD_GENERAL
const LOAD_GENERAL
Definition: ResourceLoaderModule.php:44
ResourceLoaderContext
Object passed around to modules which contains information about the state of a specific loader reque...
Definition: ResourceLoaderContext.php:32
Wikimedia\Rdbms\Database
Relational database abstraction object.
Definition: Database.php:45
$context
error also a ContextSource you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition: hooks.txt:2612
Title\newFromText
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:265
ResourceLoaderWikiModule\$styles
$styles
Definition: ResourceLoaderWikiModule.php:57
ResourceLoaderModule\getFlip
getFlip( $context)
Definition: ResourceLoaderModule.php:134
LinkBatch
Class representing a list of titles The execute() method checks them all for existence and adds them ...
Definition: LinkBatch.php:34
ResourceLoaderWikiModule\getDB
getDB()
Get the Database object used in getTitleInfo().
Definition: ResourceLoaderWikiModule.php:141
captcha-old.count
count
Definition: captcha-old.py:225
ResourceLoaderModule\ORIGIN_USER_SITEWIDE
const ORIGIN_USER_SITEWIDE
Definition: ResourceLoaderModule.php:54
ResourceLoaderWikiModule\getStyles
getStyles(ResourceLoaderContext $context)
Definition: ResourceLoaderWikiModule.php:223
Wikimedia\Rdbms\IDatabase\getWikiID
getWikiID()
Alias for getDomainID()
Revision\newKnownCurrent
static newKnownCurrent(IDatabase $db, $pageId, $revId)
Load a revision based on a known page ID and current revision ID from the DB.
Definition: Revision.php:1921
ResourceLoaderWikiModule
Abstraction for ResourceLoader modules which pull from wiki pages.
Definition: ResourceLoaderWikiModule.php:48
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
ResourceLoaderWikiModule\getGroup
getGroup()
Get group name.
Definition: ResourceLoaderWikiModule.php:126
ResourceLoaderWikiModule\getScript
getScript(ResourceLoaderContext $context)
Definition: ResourceLoaderWikiModule.php:204
$fname
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined.
Definition: Setup.php:36
CONTENT_FORMAT_CSS
const CONTENT_FORMAT_CSS
Definition: Defines.php:252
ContentHandler\getForTitle
static getForTitle(Title $title)
Returns the appropriate ContentHandler singleton for the given title.
Definition: ContentHandler.php:240
$res
$res
Definition: database.txt:21
ResourceLoaderWikiModule\isKnownEmpty
isKnownEmpty(ResourceLoaderContext $context)
Definition: ResourceLoaderWikiModule.php:280
wfDebugLog
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
Definition: GlobalFunctions.php:1092
php
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:35
Wikimedia\Rdbms\IDatabase
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:40
ResourceLoaderWikiModule\$titleInfo
$titleInfo
Definition: ResourceLoaderWikiModule.php:54
MemoizedCallable\call
static call( $callable, array $args=[], $ttl=3600)
Shortcut method for creating a MemoizedCallable and invoking it with the specified arguments.
Definition: MemoizedCallable.php:151
Revision
Definition: Revision.php:33
$title
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:934
ResourceLoaderWikiModule\getType
getType()
Definition: ResourceLoaderWikiModule.php:466
ResourceLoaderWikiModule\preloadTitleInfo
static preloadTitleInfo(ResourceLoaderContext $context, IDatabase $db, array $moduleNames)
Definition: ResourceLoaderWikiModule.php:362
$content
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content $content
Definition: hooks.txt:1049
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:3060
$page
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached $page
Definition: hooks.txt:2536
ResourceLoaderWikiModule\enableModuleContentVersion
enableModuleContentVersion()
Disable module content versioning.
Definition: ResourceLoaderWikiModule.php:258
Title\makeTitle
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:514
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
ResourceLoaderWikiModule\fetchTitleInfo
static fetchTitleInfo(IDatabase $db, array $pages, $fname=__METHOD__)
Definition: ResourceLoaderWikiModule.php:325
ResourceLoaderWikiModule\getContent
getContent( $titleText)
Definition: ResourceLoaderWikiModule.php:149
ResourceLoaderWikiModule\$scripts
$scripts
Definition: ResourceLoaderWikiModule.php:60
ResourceLoaderModule\$name
$name
Definition: ResourceLoaderModule.php:70
ResourceLoaderWikiModule\__construct
__construct(array $options=null)
Definition: ResourceLoaderWikiModule.php:68
ResourceLoaderModule\LOAD_STYLES
const LOAD_STYLES
Definition: ResourceLoaderModule.php:42
Revision\RAW
const RAW
Definition: Revision.php:100
ResourceLoaderModule\validateScriptFile
validateScriptFile( $fileName, $contents)
Validate a given script file; if valid returns the original source.
Definition: ResourceLoaderModule.php:933
$handler
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:783
ResourceLoaderWikiModule\setTitleInfo
setTitleInfo( $key, array $titleInfo)
Definition: ResourceLoaderWikiModule.php:300
scripts
The package scripts
Definition: README.txt:1
ResourceLoaderWikiModule\$origin
$origin
Definition: ResourceLoaderWikiModule.php:51
ResourceLoaderWikiModule\getContentObj
getContentObj(Title $title)
Definition: ResourceLoaderWikiModule.php:185
ResourceLoaderWikiModule\$group
$group
Definition: ResourceLoaderWikiModule.php:63
Title
Represents a title within MediaWiki.
Definition: Title.php:39
ResourceLoaderModule
Abstraction for ResourceLoader modules, with name registration and maxage functionality.
Definition: ResourceLoaderModule.php:34
ResourceLoaderModule\$config
Config $config
Definition: ResourceLoaderModule.php:85
$dbr
if(! $regexes) $dbr
Definition: cleanup.php:94
$cache
$cache
Definition: mcc.php:33
ObjectCache\getMainWANInstance
static getMainWANInstance()
Get the main WAN cache object.
Definition: ObjectCache.php:370
as
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
Definition: distributors.txt:9
ResourceLoaderWikiModule\getDefinitionSummary
getDefinitionSummary(ResourceLoaderContext $context)
Definition: ResourceLoaderWikiModule.php:266
Wikimedia\Rdbms\IDatabase\select
select( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Execute a SELECT query constructed using the various parameters provided.
$batch
$batch
Definition: linkcache.txt:23
ResourceLoaderWikiModule\getPages
getPages(ResourceLoaderContext $context)
Subclasses should return an associative array of resources in the module.
Definition: ResourceLoaderWikiModule.php:101
class
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
CONTENT_FORMAT_JAVASCRIPT
const CONTENT_FORMAT_JAVASCRIPT
Definition: Defines.php:250
ResourceLoaderWikiModule\invalidateModuleCache
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...
Definition: ResourceLoaderWikiModule.php:442
$options
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Definition: hooks.txt:1049
ResourceLoaderModule\getConfig
getConfig()
Definition: ResourceLoaderModule.php:188
ResourceLoaderWikiModule\getTitleInfo
getTitleInfo(ResourceLoaderContext $context)
Get the information about the wiki pages for a given context.
Definition: ResourceLoaderWikiModule.php:309
array
the array() calling protocol came about after MediaWiki 1.4rc1.