MediaWiki  1.28.0
ResourceLoaderWikiModule.php
Go to the documentation of this file.
1 <?php
48  protected $position = 'bottom';
49 
50  // Origin defaults to users with sitewide authority
51  protected $origin = self::ORIGIN_USER_SITEWIDE;
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 'position':
76  case 'styles':
77  case 'scripts':
78  case 'group':
79  case 'targets':
80  $this->{$member} = $option;
81  break;
82  }
83  }
84  }
85 
102  protected function getPages( ResourceLoaderContext $context ) {
103  $config = $this->getConfig();
104  $pages = [];
105 
106  // Filter out pages from origins not allowed by the current wiki configuration.
107  if ( $config->get( 'UseSiteJs' ) ) {
108  foreach ( $this->scripts as $script ) {
109  $pages[$script] = [ 'type' => 'script' ];
110  }
111  }
112 
113  if ( $config->get( 'UseSiteCss' ) ) {
114  foreach ( $this->styles as $style ) {
115  $pages[$style] = [ 'type' => 'style' ];
116  }
117  }
118 
119  return $pages;
120  }
121 
127  public function getGroup() {
128  return $this->group;
129  }
130 
142  protected function getDB() {
143  return wfGetDB( DB_REPLICA );
144  }
145 
150  protected function getContent( $titleText ) {
151  $title = Title::newFromText( $titleText );
152  if ( !$title ) {
153  return null;
154  }
155 
157  if ( $handler->isSupportedFormat( CONTENT_FORMAT_CSS ) ) {
158  $format = CONTENT_FORMAT_CSS;
159  } elseif ( $handler->isSupportedFormat( CONTENT_FORMAT_JAVASCRIPT ) ) {
160  $format = CONTENT_FORMAT_JAVASCRIPT;
161  } else {
162  return null;
163  }
164 
165  $revision = Revision::newFromTitle( $title, false, Revision::READ_NORMAL );
166  if ( !$revision ) {
167  return null;
168  }
169 
170  $content = $revision->getContent( Revision::RAW );
171 
172  if ( !$content ) {
173  wfDebugLog( 'resourceloader', __METHOD__ . ': failed to load content of JS/CSS page!' );
174  return null;
175  }
176 
177  return $content->serialize( $format );
178  }
179 
185  $scripts = '';
186  foreach ( $this->getPages( $context ) as $titleText => $options ) {
187  if ( $options['type'] !== 'script' ) {
188  continue;
189  }
190  $script = $this->getContent( $titleText );
191  if ( strval( $script ) !== '' ) {
192  $script = $this->validateScriptFile( $titleText, $script );
193  $scripts .= ResourceLoader::makeComment( $titleText ) . $script . "\n";
194  }
195  }
196  return $scripts;
197  }
198 
204  $styles = [];
205  foreach ( $this->getPages( $context ) as $titleText => $options ) {
206  if ( $options['type'] !== 'style' ) {
207  continue;
208  }
209  $media = isset( $options['media'] ) ? $options['media'] : 'all';
210  $style = $this->getContent( $titleText );
211  if ( strval( $style ) === '' ) {
212  continue;
213  }
214  if ( $this->getFlip( $context ) ) {
215  $style = CSSJanus::transform( $style, true, false );
216  }
217  $style = MemoizedCallable::call( 'CSSMin::remap',
218  [ $style, false, $this->getConfig()->get( 'ScriptPath' ), true ] );
219  if ( !isset( $styles[$media] ) ) {
220  $styles[$media] = [];
221  }
222  $style = ResourceLoader::makeComment( $titleText ) . $style;
223  $styles[$media][] = $style;
224  }
225  return $styles;
226  }
227 
238  public function enableModuleContentVersion() {
239  return false;
240  }
241 
247  $summary = parent::getDefinitionSummary( $context );
248  $summary[] = [
249  'pages' => $this->getPages( $context ),
250  // Includes meta data of current revisions
251  'titleInfo' => $this->getTitleInfo( $context ),
252  ];
253  return $summary;
254  }
255 
261  $revisions = $this->getTitleInfo( $context );
262 
263  // For user modules, don't needlessly load if there are no non-empty pages
264  if ( $this->getGroup() === 'user' ) {
265  foreach ( $revisions as $revision ) {
266  if ( $revision['page_len'] > 0 ) {
267  // At least one non-empty page, module should be loaded
268  return false;
269  }
270  }
271  return true;
272  }
273 
274  // Bug 68488: For other modules (i.e. ones that are called in cached html output) only check
275  // page existance. This ensures that, if some pages in a module are temporarily blanked,
276  // we don't end omit the module's script or link tag on some pages.
277  return count( $revisions ) === 0;
278  }
279 
280  private function setTitleInfo( $key, array $titleInfo ) {
281  $this->titleInfo[$key] = $titleInfo;
282  }
283 
290  $dbr = $this->getDB();
291  if ( !$dbr ) {
292  // We're dealing with a subclass that doesn't have a DB
293  return [];
294  }
295 
296  $pageNames = array_keys( $this->getPages( $context ) );
297  sort( $pageNames );
298  $key = implode( '|', $pageNames );
299  if ( !isset( $this->titleInfo[$key] ) ) {
300  $this->titleInfo[$key] = static::fetchTitleInfo( $dbr, $pageNames, __METHOD__ );
301  }
302  return $this->titleInfo[$key];
303  }
304 
305  protected static function fetchTitleInfo( IDatabase $db, array $pages, $fname = __METHOD__ ) {
306  $titleInfo = [];
307  $batch = new LinkBatch;
308  foreach ( $pages as $titleText ) {
309  $title = Title::newFromText( $titleText );
310  if ( $title ) {
311  // Page name may be invalid if user-provided (e.g. gadgets)
312  $batch->addObj( $title );
313  }
314  }
315  if ( !$batch->isEmpty() ) {
316  $res = $db->select( 'page',
317  // Include page_touched to allow purging if cache is poisoned (T117587, T113916)
318  [ 'page_namespace', 'page_title', 'page_touched', 'page_len', 'page_latest' ],
319  $batch->constructSet( 'page', $db ),
320  $fname
321  );
322  foreach ( $res as $row ) {
323  // Avoid including ids or timestamps of revision/page tables so
324  // that versions are not wasted
325  $title = Title::makeTitle( $row->page_namespace, $row->page_title );
326  $titleInfo[$title->getPrefixedText()] = [
327  'page_len' => $row->page_len,
328  'page_latest' => $row->page_latest,
329  'page_touched' => $row->page_touched,
330  ];
331  }
332  }
333  return $titleInfo;
334  }
335 
342  public static function preloadTitleInfo(
343  ResourceLoaderContext $context, IDatabase $db, array $moduleNames
344  ) {
345  $rl = $context->getResourceLoader();
346  // getDB() can be overridden to point to a foreign database.
347  // For now, only preload local. In the future, we could preload by wikiID.
348  $allPages = [];
350  $wikiModules = [];
351  foreach ( $moduleNames as $name ) {
352  $module = $rl->getModule( $name );
353  if ( $module instanceof self ) {
354  $mDB = $module->getDB();
355  // Subclasses may disable getDB and implement getTitleInfo differently
356  if ( $mDB && $mDB->getWikiID() === $db->getWikiID() ) {
357  $wikiModules[] = $module;
358  $allPages += $module->getPages( $context );
359  }
360  }
361  }
362 
363  $pageNames = array_keys( $allPages );
364  sort( $pageNames );
365  $hash = sha1( implode( '|', $pageNames ) );
366 
367  // Avoid Zend bug where "static::" does not apply LSB in the closure
368  $func = [ static::class, 'fetchTitleInfo' ];
369  $fname = __METHOD__;
370 
372  $allInfo = $cache->getWithSetCallback(
373  $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $db->getWikiID(), $hash ),
374  $cache::TTL_HOUR,
375  function ( $curVal, &$ttl, array &$setOpts ) use ( $func, $pageNames, $db, $fname ) {
376  $setOpts += Database::getCacheSetOptions( $db );
377 
378  return call_user_func( $func, $db, $pageNames, $fname );
379  },
380  [ 'checkKeys' => [ $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $db->getWikiID() ) ] ]
381  );
382 
383  foreach ( $wikiModules as $wikiModule ) {
384  $pages = $wikiModule->getPages( $context );
385  // Before we intersect, map the names to canonical form (T145673).
386  $intersect = [];
387  foreach ( $pages as $page => $unused ) {
389  if ( $title ) {
390  $intersect[ $title->getPrefixedText() ] = 1;
391  } else {
392  // Page name may be invalid if user-provided (e.g. gadgets)
393  $rl->getLogger()->info(
394  'Invalid wiki page title "{title}" in ' . __METHOD__,
395  [ 'title' => $page ]
396  );
397  }
398  }
399  $info = array_intersect_key( $allInfo, $intersect );
400  $pageNames = array_keys( $pages );
401  sort( $pageNames );
402  $key = implode( '|', $pageNames );
403  $wikiModule->setTitleInfo( $key, $info );
404  }
405  }
406 
417  public static function invalidateModuleCache(
418  Title $title, Revision $old = null, Revision $new = null, $wikiId
419  ) {
420  static $formats = [ CONTENT_FORMAT_CSS, CONTENT_FORMAT_JAVASCRIPT ];
421 
422  if ( $old && in_array( $old->getContentFormat(), $formats ) ) {
423  $purge = true;
424  } elseif ( $new && in_array( $new->getContentFormat(), $formats ) ) {
425  $purge = true;
426  } else {
427  $purge = ( $title->isCssOrJsPage() || $title->isCssJsSubpage() );
428  }
429 
430  if ( $purge ) {
432  $key = $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $wikiId );
433  $cache->touchCheckKey( $key );
434  }
435  }
436 
440  public function getPosition() {
441  return $this->position;
442  }
443 
448  public function getType() {
449  // Check both because subclasses don't always pass pages via the constructor,
450  // they may also override getPages() instead, in which case we should keep
451  // defaulting to LOAD_GENERAL and allow them to override getType() separately.
452  return ( $this->styles && !$this->scripts ) ? self::LOAD_STYLES : self::LOAD_GENERAL;
453  }
454 }
static fetchTitleInfo(IDatabase $db, array $pages, $fname=__METHOD__)
Abstraction for ResourceLoader modules which pull from wiki pages.
static getMainWANInstance()
Get the main WAN cache object.
wfGetDB($db, $groups=[], $wiki=false)
Get a Database object.
the array() calling protocol came about after MediaWiki 1.4rc1.
getDB()
Get the Database object used in getTitleInfo().
$context
Definition: load.php:50
Abstraction for ResourceLoader modules, with name registration and maxage functionality.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
static getCacheSetOptions(IDatabase $db1)
Merge the result of getSessionLagStatus() for several DBs using the most pessimistic values to estima...
Definition: Database.php:3025
isCssJsSubpage()
Is this a .css or .js subpage of a user page?
Definition: Title.php:1250
static newFromText($text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:262
The package scripts
Definition: README.txt:1
static newFromTitle(LinkTarget $linkTarget, $id=0, $flags=0)
Load either the current, or a specified, revision that's attached to a given link target...
Definition: Revision.php:128
get($name)
Get a configuration variable such as "Sitename" or "UploadMaintenance.".
$batch
Definition: linkcache.txt:23
const CONTENT_FORMAT_CSS
Definition: Defines.php:258
Class representing a list of titles The execute() method checks them all for existence and adds them ...
Definition: LinkBatch.php:32
wfDebugLog($logGroup, $text, $dest= 'all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not...
enableModuleContentVersion()
Disable module content versioning.
validateScriptFile($fileName, $contents)
Validate a given script file; if valid returns the original source.
getTitleInfo(ResourceLoaderContext $context)
Get the information about the wiki pages for a given context.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist 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:1046
$res
Definition: database.txt:21
$summary
static preloadTitleInfo(ResourceLoaderContext $context, IDatabase $db, array $moduleNames)
$cache
Definition: mcc.php:33
string $position
Position on the page to load this module at.
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:953
const RAW
Definition: Revision.php:94
static getForTitle(Title $title)
Returns the appropriate ContentHandler singleton for the given title.
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
getStyles(ResourceLoaderContext $context)
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
static makeComment($text)
Generate a CSS or JS comment block.
getWikiID()
Alias for getDomainID()
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined...
Definition: Setup.php:36
getScript(ResourceLoaderContext $context)
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
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist 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:1046
isKnownEmpty(ResourceLoaderContext $context)
isCssOrJsPage()
Could this page contain custom CSS or JavaScript for the global UI.
Definition: Title.php:1231
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...
const CONTENT_FORMAT_JAVASCRIPT
Definition: Defines.php:256
const DB_REPLICA
Definition: defines.php:22
setTitleInfo($key, array $titleInfo)
select($table, $vars, $conds= '', $fname=__METHOD__, $options=[], $join_conds=[])
Execute a SELECT query constructed using the various parameters provided.
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:802
getDefinitionSummary(ResourceLoaderContext $context)
getPages(ResourceLoaderContext $context)
Subclasses should return an associative array of resources in the module.
static makeTitle($ns, $title, $fragment= '', $interwiki= '')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:511
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:34
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:2491
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...