MediaWiki  1.27.2
ResourceLoaderWikiModule.php
Go to the documentation of this file.
1 <?php
47  protected $position = 'bottom';
48 
49  // Origin defaults to users with sitewide authority
50  protected $origin = self::ORIGIN_USER_SITEWIDE;
51 
52  // In-process cache for title info
53  protected $titleInfo = [];
54 
55  // List of page names that contain CSS
56  protected $styles = [];
57 
58  // List of page names that contain JavaScript
59  protected $scripts = [];
60 
61  // Group of module
62  protected $group;
63 
67  public function __construct( array $options = null ) {
68  if ( is_null( $options ) ) {
69  return;
70  }
71 
72  foreach ( $options as $member => $option ) {
73  switch ( $member ) {
74  case 'position':
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_SLAVE );
143  }
144 
149  protected function getContent( $titleText ) {
150  $title = Title::newFromText( $titleText );
151  if ( !$title ) {
152  return null;
153  }
154 
156  if ( $handler->isSupportedFormat( CONTENT_FORMAT_CSS ) ) {
157  $format = CONTENT_FORMAT_CSS;
158  } elseif ( $handler->isSupportedFormat( CONTENT_FORMAT_JAVASCRIPT ) ) {
159  $format = CONTENT_FORMAT_JAVASCRIPT;
160  } else {
161  return null;
162  }
163 
164  $revision = Revision::newFromTitle( $title, false, Revision::READ_NORMAL );
165  if ( !$revision ) {
166  return null;
167  }
168 
169  $content = $revision->getContent( Revision::RAW );
170 
171  if ( !$content ) {
172  wfDebugLog( 'resourceloader', __METHOD__ . ': failed to load content of JS/CSS page!' );
173  return null;
174  }
175 
176  return $content->serialize( $format );
177  }
178 
184  $scripts = '';
185  foreach ( $this->getPages( $context ) as $titleText => $options ) {
186  if ( $options['type'] !== 'script' ) {
187  continue;
188  }
189  $script = $this->getContent( $titleText );
190  if ( strval( $script ) !== '' ) {
191  $script = $this->validateScriptFile( $titleText, $script );
192  $scripts .= ResourceLoader::makeComment( $titleText ) . $script . "\n";
193  }
194  }
195  return $scripts;
196  }
197 
203  $styles = [];
204  foreach ( $this->getPages( $context ) as $titleText => $options ) {
205  if ( $options['type'] !== 'style' ) {
206  continue;
207  }
208  $media = isset( $options['media'] ) ? $options['media'] : 'all';
209  $style = $this->getContent( $titleText );
210  if ( strval( $style ) === '' ) {
211  continue;
212  }
213  if ( $this->getFlip( $context ) ) {
214  $style = CSSJanus::transform( $style, true, false );
215  }
216  $style = MemoizedCallable::call( 'CSSMin::remap',
217  [ $style, false, $this->getConfig()->get( 'ScriptPath' ), true ] );
218  if ( !isset( $styles[$media] ) ) {
219  $styles[$media] = [];
220  }
221  $style = ResourceLoader::makeComment( $titleText ) . $style;
222  $styles[$media][] = $style;
223  }
224  return $styles;
225  }
226 
237  public function enableModuleContentVersion() {
238  return false;
239  }
240 
246  $summary = parent::getDefinitionSummary( $context );
247  $summary[] = [
248  'pages' => $this->getPages( $context ),
249  // Includes SHA1 of content
250  'titleInfo' => $this->getTitleInfo( $context ),
251  ];
252  return $summary;
253  }
254 
260  $revisions = $this->getTitleInfo( $context );
261 
262  // For user modules, don't needlessly load if there are no non-empty pages
263  if ( $this->getGroup() === 'user' ) {
264  foreach ( $revisions as $revision ) {
265  if ( $revision['rev_len'] > 0 ) {
266  // At least one non-empty page, module should be loaded
267  return false;
268  }
269  }
270  return true;
271  }
272 
273  // Bug 68488: For other modules (i.e. ones that are called in cached html output) only check
274  // page existance. This ensures that, if some pages in a module are temporarily blanked,
275  // we don't end omit the module's script or link tag on some pages.
276  return count( $revisions ) === 0;
277  }
278 
285  $dbr = $this->getDB();
286  if ( !$dbr ) {
287  // We're dealing with a subclass that doesn't have a DB
288  return [];
289  }
290 
291  $pages = $this->getPages( $context );
292  $key = implode( '|', array_keys( $pages ) );
293  if ( !isset( $this->titleInfo[$key] ) ) {
294  $this->titleInfo[$key] = [];
295  $batch = new LinkBatch;
296  foreach ( $pages as $titleText => $options ) {
297  $batch->addObj( Title::newFromText( $titleText ) );
298  }
299 
300  if ( !$batch->isEmpty() ) {
301  $res = $dbr->select( [ 'page', 'revision' ],
302  // Include page_touched to allow purging if cache is poisoned (T117587, T113916)
303  [ 'page_namespace', 'page_title', 'page_touched', 'rev_len', 'rev_sha1' ],
304  $batch->constructSet( 'page', $dbr ),
305  __METHOD__,
306  [],
307  [ 'revision' => [ 'INNER JOIN', [ 'page_latest=rev_id' ] ] ]
308  );
309  foreach ( $res as $row ) {
310  // Avoid including ids or timestamps of revision/page tables so
311  // that versions are not wasted
312  $title = Title::makeTitle( $row->page_namespace, $row->page_title );
313  $this->titleInfo[$key][$title->getPrefixedText()] = [
314  'rev_len' => $row->rev_len,
315  'rev_sha1' => $row->rev_sha1,
316  'page_touched' => $row->page_touched,
317  ];
318  }
319  }
320  }
321  return $this->titleInfo[$key];
322  }
323 
324  public function getPosition() {
325  return $this->position;
326  }
327 }
Abstraction for ResourceLoader modules which pull from wiki pages.
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().
magic word the default is to use $key to get the and $key value or $key value text $key value html to format the value $key
Definition: hooks.txt:2321
$context
Definition: load.php:44
Abstraction for ResourceLoader modules, with name registration and maxage functionality.
static newFromText($text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:277
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:117
get($name)
Get a configuration variable such as "Sitename" or "UploadMaintenance.".
$batch
Definition: linkcache.txt:23
const CONTENT_FORMAT_CSS
Definition: Defines.php:296
Class representing a list of titles The execute() method checks them all for existence and adds them ...
Definition: LinkBatch.php:31
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:1004
$res
Definition: database.txt:21
$summary
string $position
Position on the page to load this module at.
const DB_SLAVE
Definition: Defines.php:46
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:912
const RAW
Definition: Revision.php:85
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.
getScript(ResourceLoaderContext $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 $content
Definition: hooks.txt:1004
isKnownEmpty(ResourceLoaderContext $context)
const CONTENT_FORMAT_JAVASCRIPT
Definition: Defines.php:294
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:762
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:524
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...