MediaWiki  1.23.12
ResourceLoader.php
Go to the documentation of this file.
1 <?php
32 
36  protected static $filterCacheVersion = 7;
40  protected static $requiredSourceProperties = array( 'loadScript' );
41 
45  protected $modules = array();
46 
50  protected $moduleInfos = array();
51 
56  protected $testModuleNames = array();
57 
61  protected $sources = array();
62 
66  protected $hasErrors = false;
67 
82  public function preloadModuleInfo( array $modules, ResourceLoaderContext $context ) {
83  if ( !count( $modules ) ) {
84  // Or else Database*::select() will explode, plus it's cheaper!
85  return;
86  }
87  $dbr = wfGetDB( DB_SLAVE );
88  $skin = $context->getSkin();
89  $lang = $context->getLanguage();
90 
91  // Get file dependency information
92  $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
93  'md_module' => $modules,
94  'md_skin' => $skin
95  ), __METHOD__
96  );
97 
98  // Set modules' dependencies
99  $modulesWithDeps = array();
100  foreach ( $res as $row ) {
101  $module = $this->getModule( $row->md_module );
102  if ( $module ) {
103  $module->setFileDependencies( $skin, FormatJson::decode( $row->md_deps, true ) );
104  $modulesWithDeps[] = $row->md_module;
105  }
106  }
107 
108  // Register the absence of a dependency row too
109  foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
110  $module = $this->getModule( $name );
111  if ( $module ) {
112  $this->getModule( $name )->setFileDependencies( $skin, array() );
113  }
114  }
115 
116  // Get message blob mtimes. Only do this for modules with messages
117  $modulesWithMessages = array();
118  foreach ( $modules as $name ) {
119  $module = $this->getModule( $name );
120  if ( $module && count( $module->getMessages() ) ) {
121  $modulesWithMessages[] = $name;
122  }
123  }
124  $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
125  if ( count( $modulesWithMessages ) ) {
126  $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
127  'mr_resource' => $modulesWithMessages,
128  'mr_lang' => $lang
129  ), __METHOD__
130  );
131  foreach ( $res as $row ) {
132  $module = $this->getModule( $row->mr_resource );
133  if ( $module ) {
134  $module->setMsgBlobMtime( $lang, wfTimestamp( TS_UNIX, $row->mr_timestamp ) );
135  unset( $modulesWithoutMessages[$row->mr_resource] );
136  }
137  }
138  }
139  foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
140  $module = $this->getModule( $name );
141  if ( $module ) {
142  $module->setMsgBlobMtime( $lang, 0 );
143  }
144  }
145  }
146 
162  protected function filter( $filter, $data ) {
163  global $wgResourceLoaderMinifierStatementsOnOwnLine, $wgResourceLoaderMinifierMaxLineLength;
164  wfProfileIn( __METHOD__ );
165 
166  // For empty/whitespace-only data or for unknown filters, don't perform
167  // any caching or processing
168  if ( trim( $data ) === '' || !in_array( $filter, array( 'minify-js', 'minify-css' ) ) ) {
169  wfProfileOut( __METHOD__ );
170  return $data;
171  }
172 
173  // Try for cache hit
174  // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
175  $key = wfMemcKey( 'resourceloader', 'filter', $filter, self::$filterCacheVersion, md5( $data ) );
177  $cacheEntry = $cache->get( $key );
178  if ( is_string( $cacheEntry ) ) {
179  wfIncrStats( "rl-$filter-cache-hits" );
180  wfProfileOut( __METHOD__ );
181  return $cacheEntry;
182  }
183 
184  $result = '';
185  // Run the filter - we've already verified one of these will work
186  try {
187  wfIncrStats( "rl-$filter-cache-misses" );
188  switch ( $filter ) {
189  case 'minify-js':
191  $wgResourceLoaderMinifierStatementsOnOwnLine,
192  $wgResourceLoaderMinifierMaxLineLength
193  );
194  $result .= "\n/* cache key: $key */";
195  break;
196  case 'minify-css':
197  $result = CSSMin::minify( $data );
198  $result .= "\n/* cache key: $key */";
199  break;
200  }
201 
202  // Save filtered text to Memcached
203  $cache->set( $key, $result );
204  } catch ( Exception $e ) {
206  wfDebugLog( 'resourceloader', __METHOD__ . ": minification failed: $e" );
207  $this->hasErrors = true;
208  // Return exception as a comment
210  }
211 
212  wfProfileOut( __METHOD__ );
213 
214  return $result;
215  }
216 
217  /* Methods */
218 
222  public function __construct() {
223  global $IP, $wgResourceModules, $wgResourceLoaderSources, $wgLoadScript, $wgEnableJavaScriptTest;
224 
225  wfProfileIn( __METHOD__ );
226 
227  // Add 'local' source first
228  $this->addSource( 'local', array( 'loadScript' => $wgLoadScript, 'apiScript' => wfScript( 'api' ) ) );
229 
230  // Add other sources
231  $this->addSource( $wgResourceLoaderSources );
232 
233  // Register core modules
234  $this->register( include "$IP/resources/Resources.php" );
235  // Register extension modules
236  wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
237  $this->register( $wgResourceModules );
238 
239  if ( $wgEnableJavaScriptTest === true ) {
240  $this->registerTestModules();
241  }
242 
243  wfProfileOut( __METHOD__ );
244  }
245 
259  public function register( $name, $info = null ) {
260  wfProfileIn( __METHOD__ );
261 
262  // Allow multiple modules to be registered in one call
263  $registrations = is_array( $name ) ? $name : array( $name => $info );
264  foreach ( $registrations as $name => $info ) {
265  // Disallow duplicate registrations
266  if ( isset( $this->moduleInfos[$name] ) ) {
267  wfProfileOut( __METHOD__ );
268  // A module has already been registered by this name
269  throw new MWException(
270  'ResourceLoader duplicate registration error. ' .
271  'Another module has already been registered as ' . $name
272  );
273  }
274 
275  // Check $name for validity
276  if ( !self::isValidModuleName( $name ) ) {
277  wfProfileOut( __METHOD__ );
278  throw new MWException( "ResourceLoader module name '$name' is invalid, see ResourceLoader::isValidModuleName()" );
279  }
280 
281  // Attach module
282  if ( $info instanceof ResourceLoaderModule ) {
283  $this->moduleInfos[$name] = array( 'object' => $info );
284  $info->setName( $name );
285  $this->modules[$name] = $info;
286  } elseif ( is_array( $info ) ) {
287  // New calling convention
288  $this->moduleInfos[$name] = $info;
289  } else {
290  wfProfileOut( __METHOD__ );
291  throw new MWException(
292  'ResourceLoader module info type error for module \'' . $name .
293  '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
294  );
295  }
296  }
297 
298  wfProfileOut( __METHOD__ );
299  }
300 
303  public function registerTestModules() {
304  global $IP, $wgEnableJavaScriptTest;
305 
306  if ( $wgEnableJavaScriptTest !== true ) {
307  throw new MWException( 'Attempt to register JavaScript test modules but <code>$wgEnableJavaScriptTest</code> is false. Edit your <code>LocalSettings.php</code> to enable it.' );
308  }
309 
310  wfProfileIn( __METHOD__ );
311 
312  // Get core test suites
313  $testModules = array();
314  $testModules['qunit'] = array();
315  // Get other test suites (e.g. from extensions)
316  wfRunHooks( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
317 
318  // Add the testrunner (which configures QUnit) to the dependencies.
319  // Since it must be ready before any of the test suites are executed.
320  foreach ( $testModules['qunit'] as &$module ) {
321  // Make sure all test modules are top-loading so that when QUnit starts
322  // on document-ready, it will run once and finish. If some tests arrive
323  // later (possibly after QUnit has already finished) they will be ignored.
324  $module['position'] = 'top';
325  $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
326  }
327 
328  $testModules['qunit'] = ( include "$IP/tests/qunit/QUnitTestResources.php" ) + $testModules['qunit'];
329 
330  foreach ( $testModules as $id => $names ) {
331  // Register test modules
332  $this->register( $testModules[$id] );
333 
334  // Keep track of their names so that they can be loaded together
335  $this->testModuleNames[$id] = array_keys( $testModules[$id] );
336  }
337 
338  wfProfileOut( __METHOD__ );
339  }
340 
351  public function addSource( $id, $properties = null ) {
352  // Allow multiple sources to be registered in one call
353  if ( is_array( $id ) ) {
354  foreach ( $id as $key => $value ) {
355  $this->addSource( $key, $value );
356  }
357  return;
358  }
359 
360  // Disallow duplicates
361  if ( isset( $this->sources[$id] ) ) {
362  throw new MWException(
363  'ResourceLoader duplicate source addition error. ' .
364  'Another source has already been registered as ' . $id
365  );
366  }
367 
368  // Validate properties
369  foreach ( self::$requiredSourceProperties as $prop ) {
370  if ( !isset( $properties[$prop] ) ) {
371  throw new MWException( "Required property $prop missing from source ID $id" );
372  }
373  }
374 
375  $this->sources[$id] = $properties;
376  }
377 
383  public function getModuleNames() {
384  return array_keys( $this->moduleInfos );
385  }
386 
397  public function getTestModuleNames( $framework = 'all' ) {
399  if ( $framework == 'all' ) {
400  return $this->testModuleNames;
401  } elseif ( isset( $this->testModuleNames[$framework] ) && is_array( $this->testModuleNames[$framework] ) ) {
402  return $this->testModuleNames[$framework];
403  } else {
404  return array();
405  }
406  }
407 
419  public function getModule( $name ) {
420  if ( !isset( $this->modules[$name] ) ) {
421  if ( !isset( $this->moduleInfos[$name] ) ) {
422  // No such module
423  return null;
424  }
425  // Construct the requested object
426  $info = $this->moduleInfos[$name];
428  if ( isset( $info['object'] ) ) {
429  // Object given in info array
430  $object = $info['object'];
431  } else {
432  if ( !isset( $info['class'] ) ) {
433  $class = 'ResourceLoaderFileModule';
434  } else {
435  $class = $info['class'];
436  }
437  $object = new $class( $info );
438  }
439  $object->setName( $name );
440  $this->modules[$name] = $object;
441  }
442 
443  return $this->modules[$name];
444  }
445 
451  public function getSources() {
452  return $this->sources;
453  }
454 
460  public function respond( ResourceLoaderContext $context ) {
461  global $wgCacheEpoch, $wgUseFileCache;
462 
463  // Use file cache if enabled and available...
464  if ( $wgUseFileCache ) {
465  $fileCache = ResourceFileCache::newFromContext( $context );
466  if ( $this->tryRespondFromFileCache( $fileCache, $context ) ) {
467  return; // output handled
468  }
469  }
470 
471  // Buffer output to catch warnings. Normally we'd use ob_clean() on the
472  // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
473  // is used: ob_clean() will clear the GZIP header in that case and it won't come
474  // back for subsequent output, resulting in invalid GZIP. So we have to wrap
475  // the whole thing in our own output buffer to be sure the active buffer
476  // doesn't use ob_gzhandler.
477  // See http://bugs.php.net/bug.php?id=36514
478  ob_start();
479 
480  wfProfileIn( __METHOD__ );
481  $errors = '';
482 
483  // Find out which modules are missing and instantiate the others
484  $modules = array();
485  $missing = array();
486  foreach ( $context->getModules() as $name ) {
487  $module = $this->getModule( $name );
488  if ( $module ) {
489  // Do not allow private modules to be loaded from the web.
490  // This is a security issue, see bug 34907.
491  if ( $module->getGroup() === 'private' ) {
492  wfDebugLog( 'resourceloader', __METHOD__ . ": request for private module '$name' denied" );
493  $this->hasErrors = true;
494  // Add exception to the output as a comment
495  $errors .= self::makeComment( "Cannot show private module \"$name\"" );
496 
497  continue;
498  }
499  $modules[$name] = $module;
500  } else {
501  $missing[] = $name;
502  }
503  }
504 
505  // Preload information needed to the mtime calculation below
506  try {
507  $this->preloadModuleInfo( array_keys( $modules ), $context );
508  } catch ( Exception $e ) {
510  wfDebugLog( 'resourceloader', __METHOD__ . ": preloading module info failed: $e" );
511  $this->hasErrors = true;
512  // Add exception to the output as a comment
513  $errors .= self::formatException( $e );
514  }
515 
516  wfProfileIn( __METHOD__ . '-getModifiedTime' );
517 
518  // To send Last-Modified and support If-Modified-Since, we need to detect
519  // the last modified time
520  $mtime = wfTimestamp( TS_UNIX, $wgCacheEpoch );
521  foreach ( $modules as $module ) {
525  try {
526  // Calculate maximum modified time
527  $mtime = max( $mtime, $module->getModifiedTime( $context ) );
528  } catch ( Exception $e ) {
530  wfDebugLog( 'resourceloader', __METHOD__ . ": calculating maximum modified time failed: $e" );
531  $this->hasErrors = true;
532  // Add exception to the output as a comment
533  $errors .= self::formatException( $e );
534  }
535  }
536 
537  wfProfileOut( __METHOD__ . '-getModifiedTime' );
538 
539  // If there's an If-Modified-Since header, respond with a 304 appropriately
540  if ( $this->tryRespondLastModified( $context, $mtime ) ) {
541  wfProfileOut( __METHOD__ );
542  return; // output handled (buffers cleared)
543  }
544 
545  // Generate a response
546  $response = $this->makeModuleResponse( $context, $modules, $missing );
547 
548  // Prepend comments indicating exceptions
549  $response = $errors . $response;
550 
551  // Capture any PHP warnings from the output buffer and append them to the
552  // response in a comment if we're in debug mode.
553  if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
554  $response = self::makeComment( $warnings ) . $response;
555  $this->hasErrors = true;
556  }
557 
558  // Save response to file cache unless there are errors
559  if ( isset( $fileCache ) && !$errors && !count( $missing ) ) {
560  // Cache single modules...and other requests if there are enough hits
561  if ( ResourceFileCache::useFileCache( $context ) ) {
562  if ( $fileCache->isCacheWorthy() ) {
563  $fileCache->saveText( $response );
564  } else {
565  $fileCache->incrMissesRecent( $context->getRequest() );
566  }
567  }
568  }
569 
570  // Send content type and cache related headers
571  $this->sendResponseHeaders( $context, $mtime, $this->hasErrors );
572 
573  // Remove the output buffer and output the response
574  ob_end_clean();
575  echo $response;
576 
577  wfProfileOut( __METHOD__ );
578  }
579 
587  protected function sendResponseHeaders( ResourceLoaderContext $context, $mtime, $errors ) {
588  global $wgResourceLoaderMaxage;
589  // If a version wasn't specified we need a shorter expiry time for updates
590  // to propagate to clients quickly
591  // If there were errors, we also need a shorter expiry time so we can recover quickly
592  if ( is_null( $context->getVersion() ) || $errors ) {
593  $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
594  $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
595  // If a version was specified we can use a longer expiry time since changing
596  // version numbers causes cache misses
597  } else {
598  $maxage = $wgResourceLoaderMaxage['versioned']['client'];
599  $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
600  }
601  if ( $context->getOnly() === 'styles' ) {
602  header( 'Content-Type: text/css; charset=utf-8' );
603  header( 'Access-Control-Allow-Origin: *' );
604  } else {
605  header( 'Content-Type: text/javascript; charset=utf-8' );
606  }
607  header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $mtime ) );
608  if ( $context->getDebug() ) {
609  // Do not cache debug responses
610  header( 'Cache-Control: private, no-cache, must-revalidate' );
611  header( 'Pragma: no-cache' );
612  } else {
613  header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
614  $exp = min( $maxage, $smaxage );
615  header( 'Expires: ' . wfTimestamp( TS_RFC2822, $exp + time() ) );
616  }
617  }
618 
629  protected function tryRespondLastModified( ResourceLoaderContext $context, $mtime ) {
630  // If there's an If-Modified-Since header, respond with a 304 appropriately
631  // Some clients send "timestamp;length=123". Strip the part after the first ';'
632  // so we get a valid timestamp.
633  $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
634  // Never send 304s in debug mode
635  if ( $ims !== false && !$context->getDebug() ) {
636  $imsTS = strtok( $ims, ';' );
637  if ( $mtime <= wfTimestamp( TS_UNIX, $imsTS ) ) {
638  // There's another bug in ob_gzhandler (see also the comment at
639  // the top of this function) that causes it to gzip even empty
640  // responses, meaning it's impossible to produce a truly empty
641  // response (because the gzip header is always there). This is
642  // a problem because 304 responses have to be completely empty
643  // per the HTTP spec, and Firefox behaves buggily when they're not.
644  // See also http://bugs.php.net/bug.php?id=51579
645  // To work around this, we tear down all output buffering before
646  // sending the 304.
647  wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
648 
649  header( 'HTTP/1.0 304 Not Modified' );
650  header( 'Status: 304 Not Modified' );
651  return true;
652  }
653  }
654  return false;
655  }
656 
664  protected function tryRespondFromFileCache(
665  ResourceFileCache $fileCache, ResourceLoaderContext $context
666  ) {
667  global $wgResourceLoaderMaxage;
668  // Buffer output to catch warnings.
669  ob_start();
670  // Get the maximum age the cache can be
671  $maxage = is_null( $context->getVersion() )
672  ? $wgResourceLoaderMaxage['unversioned']['server']
673  : $wgResourceLoaderMaxage['versioned']['server'];
674  // Minimum timestamp the cache file must have
675  $good = $fileCache->isCacheGood( wfTimestamp( TS_MW, time() - $maxage ) );
676  if ( !$good ) {
677  try { // RL always hits the DB on file cache miss...
678  wfGetDB( DB_SLAVE );
679  } catch ( DBConnectionError $e ) { // ...check if we need to fallback to cache
680  $good = $fileCache->isCacheGood(); // cache existence check
681  }
682  }
683  if ( $good ) {
684  $ts = $fileCache->cacheTimestamp();
685  // Send content type and cache headers
686  $this->sendResponseHeaders( $context, $ts, false );
687  // If there's an If-Modified-Since header, respond with a 304 appropriately
688  if ( $this->tryRespondLastModified( $context, $ts ) ) {
689  return false; // output handled (buffers cleared)
690  }
691  $response = $fileCache->fetchText();
692  // Capture any PHP warnings from the output buffer and append them to the
693  // response in a comment if we're in debug mode.
694  if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
695  $response = "/*\n$warnings\n*/\n" . $response;
696  }
697  // Remove the output buffer and output the response
698  ob_end_clean();
699  echo $response . "\n/* Cached {$ts} */";
700  return true; // cache hit
701  }
702  // Clear buffer
703  ob_end_clean();
704 
705  return false; // cache miss
706  }
707 
716  public static function makeComment( $text ) {
717  $encText = str_replace( '*/', '* /', $text );
718  return "/*\n$encText\n*/\n";
719  }
720 
727  public static function formatException( $e ) {
728  global $wgShowExceptionDetails;
729 
730  if ( $wgShowExceptionDetails ) {
731  return self::makeComment( $e->__toString() );
732  } else {
733  return self::makeComment( wfMessage( 'internalerror' )->text() );
734  }
735  }
736 
745  public function makeModuleResponse( ResourceLoaderContext $context,
746  array $modules, array $missing = array()
747  ) {
748  $out = '';
749  $exceptions = '';
750  $states = array();
751 
752  if ( !count( $modules ) && !count( $missing ) ) {
753  return "/* This file is the Web entry point for MediaWiki's ResourceLoader:
754  <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
755  no modules were requested. Max made me put this here. */";
756  }
757 
758  wfProfileIn( __METHOD__ );
759 
760  // Pre-fetch blobs
761  if ( $context->shouldIncludeMessages() ) {
762  try {
763  $blobs = MessageBlobStore::get( $this, $modules, $context->getLanguage() );
764  } catch ( Exception $e ) {
766  wfDebugLog( 'resourceloader', __METHOD__ . ": pre-fetching blobs from MessageBlobStore failed: $e" );
767  $this->hasErrors = true;
768  // Add exception to the output as a comment
770  }
771  } else {
772  $blobs = array();
773  }
774 
775  foreach ( $missing as $name ) {
776  $states[$name] = 'missing';
777  }
778 
779  // Generate output
780  $isRaw = false;
781  foreach ( $modules as $name => $module ) {
786  wfProfileIn( __METHOD__ . '-' . $name );
787  try {
788  $scripts = '';
789  if ( $context->shouldIncludeScripts() ) {
790  // If we are in debug mode, we'll want to return an array of URLs if possible
791  // However, we can't do this if the module doesn't support it
792  // We also can't do this if there is an only= parameter, because we have to give
793  // the module a way to return a load.php URL without causing an infinite loop
794  if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
795  $scripts = $module->getScriptURLsForDebug( $context );
796  } else {
797  $scripts = $module->getScript( $context );
798  // rtrim() because there are usually a few line breaks after the last ';'.
799  // A new line at EOF, a new line added by ResourceLoaderFileModule::readScriptFiles, etc.
800  if ( is_string( $scripts ) && strlen( $scripts ) && substr( rtrim( $scripts ), -1 ) !== ';' ) {
801  // Append semicolon to prevent weird bugs caused by files not
802  // terminating their statements right (bug 27054)
803  $scripts .= ";\n";
804  }
805  }
806  }
807  // Styles
808  $styles = array();
809  if ( $context->shouldIncludeStyles() ) {
810  // Don't create empty stylesheets like array( '' => '' ) for modules
811  // that don't *have* any stylesheets (bug 38024).
812  $stylePairs = $module->getStyles( $context );
813  if ( count ( $stylePairs ) ) {
814  // If we are in debug mode without &only= set, we'll want to return an array of URLs
815  // See comment near shouldIncludeScripts() for more details
816  if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
817  $styles = array(
818  'url' => $module->getStyleURLsForDebug( $context )
819  );
820  } else {
821  // Minify CSS before embedding in mw.loader.implement call
822  // (unless in debug mode)
823  if ( !$context->getDebug() ) {
824  foreach ( $stylePairs as $media => $style ) {
825  // Can be either a string or an array of strings.
826  if ( is_array( $style ) ) {
827  $stylePairs[$media] = array();
828  foreach ( $style as $cssText ) {
829  if ( is_string( $cssText ) ) {
830  $stylePairs[$media][] = $this->filter( 'minify-css', $cssText );
831  }
832  }
833  } elseif ( is_string( $style ) ) {
834  $stylePairs[$media] = $this->filter( 'minify-css', $style );
835  }
836  }
837  }
838  // Wrap styles into @media groups as needed and flatten into a numerical array
839  $styles = array(
840  'css' => self::makeCombinedStyles( $stylePairs )
841  );
842  }
843  }
844  }
845 
846  // Messages
847  $messagesBlob = isset( $blobs[$name] ) ? $blobs[$name] : '{}';
848 
849  // Append output
850  switch ( $context->getOnly() ) {
851  case 'scripts':
852  if ( is_string( $scripts ) ) {
853  // Load scripts raw...
854  $out .= $scripts;
855  } elseif ( is_array( $scripts ) ) {
856  // ...except when $scripts is an array of URLs
857  $out .= self::makeLoaderImplementScript( $name, $scripts, array(), array() );
858  }
859  break;
860  case 'styles':
861  // We no longer seperate into media, they are all combined now with
862  // custom media type groups into @media .. {} sections as part of the css string.
863  // Module returns either an empty array or a numerical array with css strings.
864  $out .= isset( $styles['css'] ) ? implode( '', $styles['css'] ) : '';
865  break;
866  case 'messages':
867  $out .= self::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
868  break;
869  default:
871  $name,
872  $scripts,
873  $styles,
874  new XmlJsCode( $messagesBlob )
875  );
876  break;
877  }
878  } catch ( Exception $e ) {
880  wfDebugLog( 'resourceloader', __METHOD__ . ": generating module package failed: $e" );
881  $this->hasErrors = true;
882  // Add exception to the output as a comment
884 
885  // Respond to client with error-state instead of module implementation
886  $states[$name] = 'error';
887  unset( $modules[$name] );
888  }
889  $isRaw |= $module->isRaw();
890  wfProfileOut( __METHOD__ . '-' . $name );
891  }
892 
893  // Update module states
894  if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
895  if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
896  // Set the state of modules loaded as only scripts to ready as
897  // they don't have an mw.loader.implement wrapper that sets the state
898  foreach ( $modules as $name => $module ) {
899  $states[$name] = 'ready';
900  }
901  }
902 
903  // Set the state of modules we didn't respond to with mw.loader.implement
904  if ( count( $states ) ) {
905  $out .= self::makeLoaderStateScript( $states );
906  }
907  }
908 
909  if ( !$context->getDebug() ) {
910  if ( $context->getOnly() === 'styles' ) {
911  $out = $this->filter( 'minify-css', $out );
912  } else {
913  $out = $this->filter( 'minify-js', $out );
914  }
915  }
916 
917  wfProfileOut( __METHOD__ );
918  return $exceptions . $out;
919  }
920 
921  /* Static Methods */
922 
936  public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
937  if ( is_string( $scripts ) ) {
938  $scripts = new XmlJsCode( "function ( $, jQuery ) {\n{$scripts}\n}" );
939  } elseif ( !is_array( $scripts ) ) {
940  throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
941  }
942  return Xml::encodeJsCall(
943  'mw.loader.implement',
944  array(
945  $name,
946  $scripts,
947  // Force objects. mw.loader.implement requires them to be javascript objects.
948  // Although these variables are associative arrays, which become javascript
949  // objects through json_encode. In many cases they will be empty arrays, and
950  // PHP/json_encode() consider empty arrays to be numerical arrays and
951  // output javascript "[]" instead of "{}". This fixes that.
952  (object)$styles,
953  (object)$messages
954  ),
956  );
957  }
958 
966  public static function makeMessageSetScript( $messages ) {
967  return Xml::encodeJsCall(
968  'mw.messages.set',
969  array( (object)$messages ),
971  );
972  }
973 
981  private static function makeCombinedStyles( array $stylePairs ) {
982  $out = array();
983  foreach ( $stylePairs as $media => $styles ) {
984  // ResourceLoaderFileModule::getStyle can return the styles
985  // as a string or an array of strings. This is to allow separation in
986  // the front-end.
987  $styles = (array)$styles;
988  foreach ( $styles as $style ) {
989  $style = trim( $style );
990  // Don't output an empty "@media print { }" block (bug 40498)
991  if ( $style !== '' ) {
992  // Transform the media type based on request params and config
993  // The way that this relies on $wgRequest to propagate request params is slightly evil
994  $media = OutputPage::transformCssMedia( $media );
995 
996  if ( $media === '' || $media == 'all' ) {
997  $out[] = $style;
998  } elseif ( is_string( $media ) ) {
999  $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1000  }
1001  // else: skip
1002  }
1003  }
1004  }
1005  return $out;
1006  }
1007 
1022  public static function makeLoaderStateScript( $name, $state = null ) {
1023  if ( is_array( $name ) ) {
1024  return Xml::encodeJsCall(
1025  'mw.loader.state',
1026  array( $name ),
1028  );
1029  } else {
1030  return Xml::encodeJsCall(
1031  'mw.loader.state',
1032  array( $name, $state ),
1034  );
1035  }
1036  }
1037 
1052  public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $source, $script ) {
1053  $script = str_replace( "\n", "\n\t", trim( $script ) );
1054  return Xml::encodeJsCall(
1055  "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1056  array( $name, $version, $dependencies, $group, $source ),
1058  );
1059  }
1060 
1085  public static function makeLoaderRegisterScript( $name, $version = null,
1086  $dependencies = null, $group = null, $source = null
1087  ) {
1088  if ( is_array( $name ) ) {
1089  return Xml::encodeJsCall(
1090  'mw.loader.register',
1091  array( $name ),
1093  );
1094  } else {
1095  $version = (int)$version > 1 ? (int)$version : 1;
1096  return Xml::encodeJsCall(
1097  'mw.loader.register',
1098  array( $name, $version, $dependencies, $group, $source ),
1100  );
1101  }
1102  }
1103 
1118  public static function makeLoaderSourcesScript( $id, $properties = null ) {
1119  if ( is_array( $id ) ) {
1120  return Xml::encodeJsCall(
1121  'mw.loader.addSource',
1122  array( $id ),
1124  );
1125  } else {
1126  return Xml::encodeJsCall(
1127  'mw.loader.addSource',
1128  array( $id, $properties ),
1130  );
1131  }
1132  }
1133 
1141  public static function makeLoaderConditionalScript( $script ) {
1142  return "if(window.mw){\n" . trim( $script ) . "\n}";
1143  }
1144 
1152  public static function makeConfigSetScript( array $configuration ) {
1153  return Xml::encodeJsCall(
1154  'mw.config.set',
1155  array( $configuration ),
1157  );
1158  }
1159 
1168  public static function makePackedModulesString( $modules ) {
1169  $groups = array(); // array( prefix => array( suffixes ) )
1170  foreach ( $modules as $module ) {
1171  $pos = strrpos( $module, '.' );
1172  $prefix = $pos === false ? '' : substr( $module, 0, $pos );
1173  $suffix = $pos === false ? $module : substr( $module, $pos + 1 );
1174  $groups[$prefix][] = $suffix;
1175  }
1176 
1177  $arr = array();
1178  foreach ( $groups as $prefix => $suffixes ) {
1179  $p = $prefix === '' ? '' : $prefix . '.';
1180  $arr[] = $p . implode( ',', $suffixes );
1181  }
1182  $str = implode( '|', $arr );
1183  return $str;
1184  }
1185 
1191  public static function inDebugMode() {
1192  global $wgRequest, $wgResourceLoaderDebug;
1193  static $retval = null;
1194  if ( is_null( $retval ) ) {
1195  $retval = $wgRequest->getFuzzyBool( 'debug',
1196  $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug ) );
1197  }
1198  return $retval;
1199  }
1200 
1215  public static function makeLoaderURL( $modules, $lang, $skin, $user = null, $version = null, $debug = false, $only = null,
1216  $printable = false, $handheld = false, $extraQuery = array() ) {
1217  global $wgLoadScript;
1219  $only, $printable, $handheld, $extraQuery
1220  );
1221 
1222  // Prevent the IE6 extension check from being triggered (bug 28840)
1223  // by appending a character that's invalid in Windows extensions ('*')
1224  return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE );
1225  }
1226 
1244  public static function makeLoaderQuery( $modules, $lang, $skin, $user = null, $version = null, $debug = false, $only = null,
1245  $printable = false, $handheld = false, $extraQuery = array() ) {
1246  $query = array(
1247  'modules' => self::makePackedModulesString( $modules ),
1248  'lang' => $lang,
1249  'skin' => $skin,
1250  'debug' => $debug ? 'true' : 'false',
1251  );
1252  if ( $user !== null ) {
1253  $query['user'] = $user;
1254  }
1255  if ( $version !== null ) {
1256  $query['version'] = $version;
1257  }
1258  if ( $only !== null ) {
1259  $query['only'] = $only;
1260  }
1261  if ( $printable ) {
1262  $query['printable'] = 1;
1263  }
1264  if ( $handheld ) {
1265  $query['handheld'] = 1;
1266  }
1267  $query += $extraQuery;
1268 
1269  // Make queries uniform in order
1270  ksort( $query );
1271  return $query;
1272  }
1273 
1283  public static function isValidModuleName( $moduleName ) {
1284  return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;
1285  }
1286 
1293  public static function getLessCompiler() {
1294  global $wgResourceLoaderLESSFunctions, $wgResourceLoaderLESSImportPaths;
1295 
1296  // When called from the installer, it is possible that a required PHP extension
1297  // is missing (at least for now; see bug 47564). If this is the case, throw an
1298  // exception (caught by the installer) to prevent a fatal error later on.
1299  if ( !function_exists( 'ctype_digit' ) ) {
1300  throw new MWException( 'lessc requires the Ctype extension' );
1301  }
1302 
1303  $less = new lessc();
1304  $less->setPreserveComments( true );
1305  $less->setVariables( self::getLESSVars() );
1306  $less->setImportDir( $wgResourceLoaderLESSImportPaths );
1307  foreach ( $wgResourceLoaderLESSFunctions as $name => $func ) {
1308  $less->registerFunction( $name, $func );
1309  }
1310  return $less;
1311  }
1312 
1319  public static function getLESSVars() {
1320  global $wgResourceLoaderLESSVars;
1321 
1322  $lessVars = $wgResourceLoaderLESSVars;
1323  // Sort by key to ensure consistent hashing for cache lookups.
1324  ksort( $lessVars );
1325  return $lessVars;
1326  }
1327 }
ResourceLoader\makeLoaderConditionalScript
static makeLoaderConditionalScript( $script)
Returns JS code which runs given JS code if the client-side framework is present.
Definition: ResourceLoader.php:1138
ResourceLoaderContext
Object passed around to modules which contains information about the state of a specific loader reque...
Definition: ResourceLoaderContext.php:29
ResourceLoader\$hasErrors
bool $hasErrors
Definition: ResourceLoader.php:63
$result
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. $reader:XMLReader object $logInfo:Array of information Return false to stop further processing of the tag 'ImportHandlePageXMLTag':When parsing a XML tag in a page. $reader:XMLReader object $pageInfo:Array of information Return false to stop further processing of the tag 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information Return false to stop further processing of the tag 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. $reader:XMLReader object Return false to stop further processing of the tag 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. $reader:XMLReader object $revisionInfo:Array of information Return false to stop further processing of the tag 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. $title:Title object for the current page $request:WebRequest $ignoreRedirect:boolean to skip redirect check $target:Title/string of redirect target $article:Article object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) $article:article(object) being checked 'IsTrustedProxy':Override the result of wfIsTrustedProxy() $ip:IP being check $result:Change this value to override the result of wfIsTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of User::isValidEmailAddr(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetMagic':DEPRECATED, use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetSpecialPageAliases':DEPRECATED, use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Associative array mapping language codes to prefixed links of the form "language:title". & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LinkBegin':Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1528
wfResetOutputBuffers
wfResetOutputBuffers( $resetGzipEncoding=true)
Clear away any user-level output buffers, discarding contents.
Definition: GlobalFunctions.php:2273
CSSMin\minify
static minify( $css)
Removes whitespace from CSS data.
Definition: CSSMin.php:306
php
skin txt MediaWiki includes four core it has been set as the default in MediaWiki since the replacing Monobook it had been been the default skin since before being replaced by Vector largely rewritten in while keeping its appearance Several legacy skins were removed in the as the burden of supporting them became too heavy to bear Those in etc for skin dependent CSS etc for skin dependent JavaScript These can also be customised on a per user by etc This feature has led to a wide variety of user styles becoming that gallery is a good place to ending in php
Definition: skin.txt:62
ResourceLoader\makeConfigSetScript
static makeConfigSetScript(array $configuration)
Returns JS code which will set the MediaWiki configuration array to the given value.
Definition: ResourceLoader.php:1149
FileCacheBase\isCacheGood
isCacheGood( $timestamp='')
Check if up to date cache file exists.
Definition: FileCacheBase.php:117
$response
$response
Definition: opensearch_desc.php:32
ResourceLoader\formatException
static formatException( $e)
Handle exception display.
Definition: ResourceLoader.php:724
is
We use the convention $dbr for read and $dbw for write to help you keep track of whether the database object is a the world will explode Or to be a subsequent write query which succeeded on the master may fail when replicated to the slave due to a unique key collision Replication on the slave will stop and it may take hours to repair the database and get it back online Setting read_only in my cnf on the slave will avoid this but given the dire we prefer to have as many checks as possible We provide a but the wrapper functions like please read the documentation for except in special pages derived from QueryPage It s a common pitfall for new developers to submit code containing SQL queries which examine huge numbers of rows Remember that COUNT * is(N), counting rows in atable is like counting beans in a bucket.------------------------------------------------------------------------ Replication------------------------------------------------------------------------The largest installation of MediaWiki, Wikimedia, uses a large set ofslave MySQL servers replicating writes made to a master MySQL server. Itis important to understand the issues associated with this setup if youwant to write code destined for Wikipedia.It 's often the case that the best algorithm to use for a given taskdepends on whether or not replication is in use. Due to our unabashedWikipedia-centrism, we often just use the replication-friendly version, but if you like, you can use wfGetLB() ->getServerCount() > 1 tocheck to see if replication is in use.===Lag===Lag primarily occurs when large write queries are sent to the master.Writes on the master are executed in parallel, but they are executed inserial when they are replicated to the slaves. The master writes thequery to the binlog when the transaction is committed. The slaves pollthe binlog and start executing the query as soon as it appears. They canservice reads while they are performing a write query, but will not readanything more from the binlog and thus will perform no more writes. Thismeans that if the write query runs for a long time, the slaves will lagbehind the master for the time it takes for the write query to complete.Lag can be exacerbated by high read load. MediaWiki 's load balancer willstop sending reads to a slave when it is lagged by more than 30 seconds.If the load ratios are set incorrectly, or if there is too much loadgenerally, this may lead to a slave permanently hovering around 30seconds lag.If all slaves are lagged by more than 30 seconds, MediaWiki will stopwriting to the database. All edits and other write operations will berefused, with an error returned to the user. This gives the slaves achance to catch up. Before we had this mechanism, the slaves wouldregularly lag by several minutes, making review of recent editsdifficult.In addition to this, MediaWiki attempts to ensure that the user seesevents occurring on the wiki in chronological order. A few seconds of lagcan be tolerated, as long as the user sees a consistent picture fromsubsequent requests. This is done by saving the master binlog positionin the session, and then at the start of each request, waiting for theslave to catch up to that position before doing any reads from it. Ifthis wait times out, reads are allowed anyway, but the request isconsidered to be in "lagged slave mode". Lagged slave mode can bechecked by calling wfGetLB() ->getLaggedSlaveMode(). The onlypractical consequence at present is a warning displayed in the pagefooter.===Lag avoidance===To avoid excessive lag, queries which write large numbers of rows shouldbe split up, generally to write one row at a time. Multi-row INSERT ...SELECT queries are the worst offenders should be avoided altogether.Instead do the select first and then the insert.===Working with lag===Despite our best efforts, it 's not practical to guarantee a low-lagenvironment. Lag will usually be less than one second, but mayoccasionally be up to 30 seconds. For scalability, it 's very importantto keep load on the master low, so simply sending all your queries tothe master is not the answer. So when you have a genuine need forup-to-date data, the following approach is advised:1) Do a quick query to the master for a sequence number or timestamp 2) Run the full query on the slave and check if it matches the data you gotfrom the master 3) If it doesn 't, run the full query on the masterTo avoid swamping the master every time the slaves lag, use of thisapproach should be kept to a minimum. In most cases you should just readfrom the slave and let the user deal with the delay.------------------------------------------------------------------------ Lock contention------------------------------------------------------------------------Due to the high write rate on Wikipedia(and some other wikis), MediaWiki developers need to be very careful to structure their writesto avoid long-lasting locks. By default, MediaWiki opens a transactionat the first query, and commits it before the output is sent. Locks willbe held from the time when the query is done until the commit. So youcan reduce lock time by doing as much processing as possible before youdo your write queries.Often this approach is not good enough, and it becomes necessary toenclose small groups of queries in their own transaction. Use thefollowing syntax:$dbw=wfGetDB(DB_MASTER
ResourceLoader\makeLoaderImplementScript
static makeLoaderImplementScript( $name, $scripts, $styles, $messages)
Return JS code that calls mw.loader.implement with given module properties.
Definition: ResourceLoader.php:933
ResourceLoader\makeLoaderSourcesScript
static makeLoaderSourcesScript( $id, $properties=null)
Returns JS code which calls mw.loader.addSource() with the given parameters.
Definition: ResourceLoader.php:1115
wfGetDB
& wfGetDB( $db, $groups=array(), $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:3706
text
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add text
Definition: design.txt:12
ResourceLoaderContext\getModules
getModules()
Definition: ResourceLoaderContext.php:136
ResourceLoader\makePackedModulesString
static makePackedModulesString( $modules)
Convert an array of module names to a packed query string.
Definition: ResourceLoader.php:1165
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:2530
wfDebugLog
wfDebugLog( $logGroup, $text, $dest='all')
Send a line to a supplementary debug log file, if configured, or main debug log if not.
Definition: GlobalFunctions.php:1087
wfProfileIn
wfProfileIn( $functionname)
Begin profiling of a function.
Definition: Profiler.php:33
JavaScriptMinifier\minify
static minify( $s, $statementsOnOwnLine=false, $maxLineLength=1000)
Returns minified JavaScript code.
Definition: JavaScriptMinifier.php:80
ResourceLoader\sendResponseHeaders
sendResponseHeaders(ResourceLoaderContext $context, $mtime, $errors)
Send content type and last modified headers to the client.
Definition: ResourceLoader.php:584
wfGetCache
wfGetCache( $inputType)
Get a cache object.
Definition: GlobalFunctions.php:4005
ResourceLoader\$filterCacheVersion
static $filterCacheVersion
Definition: ResourceLoader.php:36
ResourceLoaderContext\getOnly
getOnly()
Definition: ResourceLoaderContext.php:189
ResourceLoader\$moduleInfos
array $moduleInfos
Associative array mapping module name to info associative array.
Definition: ResourceLoader.php:49
$messages
$messages
Definition: LogTests.i18n.php:8
OutputPage\transformCssMedia
static transformCssMedia( $media)
Transform "media" attribute based on request parameters.
Definition: OutputPage.php:3591
$dbr
$dbr
Definition: testCompression.php:48
ResourceLoader\makeModuleResponse
makeModuleResponse(ResourceLoaderContext $context, array $modules, array $missing=array())
Generate code for a response.
Definition: ResourceLoader.php:742
ResourceLoaderFileModule
ResourceLoader module based on local JavaScript/CSS files.
Definition: ResourceLoaderFileModule.php:28
ResourceLoader\preloadModuleInfo
preloadModuleInfo(array $modules, ResourceLoaderContext $context)
Load information stored in the database about modules.
Definition: ResourceLoader.php:79
ResourceLoader\makeLoaderQuery
static makeLoaderQuery( $modules, $lang, $skin, $user=null, $version=null, $debug=false, $only=null, $printable=false, $handheld=false, $extraQuery=array())
Build a query array (array representation of query string) for load.php.
Definition: ResourceLoader.php:1241
wfAppendQuery
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
Definition: GlobalFunctions.php:506
XmlJsCode
A wrapper class which causes Xml::encodeJsVar() and Xml::encodeJsCall() to interpret a given string a...
Definition: Xml.php:967
ResourceLoader\makeLoaderRegisterScript
static makeLoaderRegisterScript( $name, $version=null, $dependencies=null, $group=null, $source=null)
Returns JS code which calls mw.loader.register with the given parameters.
Definition: ResourceLoader.php:1082
Xml\encodeJsCall
static encodeJsCall( $name, $args, $pretty=false)
Create a call to a JavaScript function.
Definition: Xml.php:665
FormatJson\decode
static decode( $value, $assoc=false)
Decodes a JSON string.
Definition: FormatJson.php:126
MWException
MediaWiki exception.
Definition: MWException.php:26
wfMemcKey
wfMemcKey()
Get a cache key.
Definition: GlobalFunctions.php:3627
$out
$out
Definition: UtfNormalGenerate.php:167
MessageBlobStore\get
static get(ResourceLoader $resourceLoader, $modules, $lang)
Get the message blobs for a set of modules.
Definition: MessageBlobStore.php:44
ResourceLoaderContext\getRequest
getRequest()
Definition: ResourceLoaderContext.php:129
wfScript
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
Definition: GlobalFunctions.php:3786
wfIncrStats
wfIncrStats( $key, $count=1)
Increment a statistics counter.
Definition: GlobalFunctions.php:1351
ResourceLoader\makeLoaderStateScript
static makeLoaderStateScript( $name, $state=null)
Returns a JS call to mw.loader.state, which sets the state of a module or modules to a given value.
Definition: ResourceLoader.php:1019
ResourceLoaderContext\getDebug
getDebug()
Definition: ResourceLoaderContext.php:182
ResourceLoader\$sources
$sources
Definition: ResourceLoader.php:59
wfProfileOut
wfProfileOut( $functionname='missing')
Stop profiling of a function.
Definition: Profiler.php:46
wfMessage
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 noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing after in associative array form externallinks including delete and has completed for all link tables default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt
wfRunHooks
wfRunHooks( $event, array $args=array(), $deprecatedVersion=null)
Call hook functions defined in $wgHooks.
Definition: GlobalFunctions.php:4058
array
the array() calling protocol came about after MediaWiki 1.4rc1.
List of Api Query prop modules.
ResourceLoader\makeComment
static makeComment( $text)
Generate a CSS or JS comment block.
Definition: ResourceLoader.php:713
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
ResourceLoader\makeLoaderURL
static makeLoaderURL( $modules, $lang, $skin, $user=null, $version=null, $debug=false, $only=null, $printable=false, $handheld=false, $extraQuery=array())
Build a load.php URL.
Definition: ResourceLoader.php:1212
ResourceLoaderContext\getLanguage
getLanguage()
Definition: ResourceLoaderContext.php:143
DBConnectionError
Definition: DatabaseError.php:98
ResourceLoaderContext\getVersion
getVersion()
Definition: ResourceLoaderContext.php:196
FileCacheBase\fetchText
fetchText()
Get the uncompressed text from the cache.
Definition: FileCacheBase.php:144
ResourceLoaderContext\shouldIncludeStyles
shouldIncludeStyles()
Definition: ResourceLoaderContext.php:217
TS_MW
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
Definition: GlobalFunctions.php:2478
ResourceLoader\getModule
getModule( $name)
Get the ResourceLoaderModule object for a given module name.
Definition: ResourceLoader.php:416
ResourceFileCache\useFileCache
static useFileCache(ResourceLoaderContext $context)
Check if an RL request can be cached.
Definition: ResourceFileCache.php:64
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:336
ResourceLoader\tryRespondFromFileCache
tryRespondFromFileCache(ResourceFileCache $fileCache, ResourceLoaderContext $context)
Send out code for a response from file cache if possible.
Definition: ResourceLoader.php:661
ResourceLoader\getLESSVars
static getLESSVars()
Get global LESS variables.
Definition: ResourceLoader.php:1316
ResourceLoader\makeCombinedStyles
static makeCombinedStyles(array $stylePairs)
Combines an associative array mapping media type to CSS into a single stylesheet with "@media" blocks...
Definition: ResourceLoader.php:978
ResourceLoaderContext\shouldIncludeMessages
shouldIncludeMessages()
Definition: ResourceLoaderContext.php:224
CACHE_ANYTHING
const CACHE_ANYTHING
Definition: Defines.php:111
ResourceLoader\$testModuleNames
array $testModuleNames
Associative array mapping framework ids to a list of names of test suite modules like array( 'qunit' ...
Definition: ResourceLoader.php:54
$version
$version
Definition: parserTests.php:86
PROTO_RELATIVE
const PROTO_RELATIVE
Definition: Defines.php:269
ResourceLoaderContext\getSkin
getSkin()
Definition: ResourceLoaderContext.php:168
ResourceLoader\$modules
$modules
Definition: ResourceLoader.php:45
ResourceLoaderContext\shouldIncludeScripts
shouldIncludeScripts()
Definition: ResourceLoaderContext.php:210
addition
We ve cleaned up the code here by removing clumps of infrequently used code and moving them off somewhere else It s much easier for someone working with this code to see what s _really_ going and make changes or fix bugs In addition
Definition: hooks.txt:86
$exceptions
$exceptions
Definition: Utf8Test.php:72
$user
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account $user
Definition: hooks.txt:237
$skin
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 noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned $skin
Definition: hooks.txt:1530
ResourceLoader\getLessCompiler
static getLessCompiler()
Returns LESS compiler set up for use with MediaWiki.
Definition: ResourceLoader.php:1290
it
=Architecture==Two class hierarchies are used to provide the functionality associated with the different content models:*Content interface(and AbstractContent base class) define functionality that acts on the concrete content of a page, and *ContentHandler base class provides functionality specific to a content model, but not acting on concrete content. The most important function of ContentHandler is to act as a factory for the appropriate implementation of Content. These Content objects are to be used by MediaWiki everywhere, instead of passing page content around as text. All manipulation and analysis of page content must be done via the appropriate methods of the Content object. For each content model, a subclass of ContentHandler has to be registered with $wgContentHandlers. The ContentHandler object for a given content model can be obtained using ContentHandler::getForModelID($id). Also Title, WikiPage and Revision now have getContentHandler() methods for convenience. ContentHandler objects are singletons that provide functionality specific to the content type, but not directly acting on the content of some page. ContentHandler::makeEmptyContent() and ContentHandler::unserializeContent() can be used to create a Content object of the appropriate type. However, it is recommended to instead use WikiPage::getContent() resp. Revision::getContent() to get a page 's content as a Content object. These two methods should be the ONLY way in which page content is accessed. Another important function of ContentHandler objects is to define custom action handlers for a content model, see ContentHandler::getActionOverrides(). This is similar to what WikiPage::getActionOverrides() was already doing.==Serialization==With the ContentHandler facility, page content no longer has to be text based. Objects implementing the Content interface are used to represent and handle the content internally. For storage and data exchange, each content model supports at least one serialization format via ContentHandler::serializeContent($content). The list of supported formats for a given content model can be accessed using ContentHandler::getSupportedFormats(). Content serialization formats are identified using MIME type like strings. The following formats are built in:*text/x-wiki - wikitext *text/javascript - for js pages *text/css - for css pages *text/plain - for future use, e.g. with plain text messages. *text/html - for future use, e.g. with plain html messages. *application/vnd.php.serialized - for future use with the api and for extensions *application/json - for future use with the api, and for use by extensions *application/xml - for future use with the api, and for use by extensions In PHP, use the corresponding CONTENT_FORMAT_XXX constant. Note that when using the API to access page content, especially action=edit, action=parse and action=query &prop=revisions, the model and format of the content should always be handled explicitly. Without that information, interpretation of the provided content is not reliable. The same applies to XML dumps generated via maintenance/dumpBackup.php or Special:Export. Also note that the API will provide encapsulated, serialized content - so if the API was called with format=json, and contentformat is also json(or rather, application/json), the page content is represented as a string containing an escaped json structure. Extensions that use JSON to serialize some types of page content may provide specialized API modules that allow access to that content in a more natural form.==Compatibility==The ContentHandler facility is introduced in a way that should allow all existing code to keep functioning at least for pages that contain wikitext or other text based content. However, a number of functions and hooks have been deprecated in favor of new versions that are aware of the page 's content model, and will now generate warnings when used. Most importantly, the following functions have been deprecated:*Revisions::getText() and Revisions::getRawText() is deprecated in favor Revisions::getContent() *WikiPage::getText() is deprecated in favor WikiPage::getContent() Also, the old Article::getContent()(which returns text) is superceded by Article::getContentObject(). However, both methods should be avoided since they do not provide clean access to the page 's actual content. For instance, they may return a system message for non-existing pages. Use WikiPage::getContent() instead. Code that relies on a textual representation of the page content should eventually be rewritten. However, ContentHandler::getContentText() provides a stop-gap that can be used to get text for a page. Its behavior is controlled by $wgContentHandlerTextFallback it
Definition: contenthandler.txt:107
DB_SLAVE
const DB_SLAVE
Definition: Defines.php:55
ResourceLoaderModule
Abstraction for resource loader modules, with name registration and maxage functionality.
Definition: ResourceLoaderModule.php:28
$debug
$debug
Definition: Setup.php:518
ResourceLoader
Dynamic JavaScript and CSS resource loading system.
Definition: ResourceLoader.php:31
$cache
$cache
Definition: mcc.php:32
ResourceLoader\filter
filter( $filter, $data)
Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
Definition: ResourceLoader.php:159
ResourceLoader\inDebugMode
static inDebugMode()
Determine whether debug mode was requested Order of priority is 1) request param, 2) cookie,...
Definition: ResourceLoader.php:1188
on
We ve cleaned up the code here by removing clumps of infrequently used code and moving them off somewhere else It s much easier for someone working with this code to see what s _really_ going on
Definition: hooks.txt:86
ResourceLoader\__construct
__construct()
Register core modules and runs registration hooks.
Definition: ResourceLoader.php:219
TS_UNIX
const TS_UNIX
Unix time - the number of seconds since 1970-01-01 00:00:00 UTC.
Definition: GlobalFunctions.php:2473
ResourceLoader\$requiredSourceProperties
static $requiredSourceProperties
Definition: ResourceLoader.php:40
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
ResourceLoader\makeMessageSetScript
static makeMessageSetScript( $messages)
Returns JS code which, when called, will register a given list of messages.
Definition: ResourceLoader.php:963
ResourceLoader\tryRespondLastModified
tryRespondLastModified(ResourceLoaderContext $context, $mtime)
Respond with 304 Last Modified if appropiate.
Definition: ResourceLoader.php:626
source
return true to allow those checks to and false if checking is done use this to change the tables headers temp or archived zone change it to an object instance and return false override the list derivative used the name of the old file when set the default code will be skipped add a value to it if you want to add a cookie that have to vary cache options can modify source
Definition: hooks.txt:1227
$source
if(PHP_SAPI !='cli') $source
Definition: mwdoc-filter.php:18
ResourceLoader\registerTestModules
registerTestModules()
Definition: ResourceLoader.php:300
MWExceptionHandler\logException
static logException(Exception $e)
Log an exception to the exception log (if enabled).
Definition: MWExceptionHandler.php:351
ResourceLoader\addSource
addSource( $id, $properties=null)
Add a foreign source of modules.
Definition: ResourceLoader.php:348
ResourceLoader\makeCustomLoaderScript
static makeCustomLoaderScript( $name, $version, $dependencies, $group, $source, $script)
Returns JS code which calls the script given by $script.
Definition: ResourceLoader.php:1049
lessc
lessphp v0.4.0@2cc77e3c7b http://leafo.net/lessphp
Definition: lessc.inc.php:68
code
and how to run hooks for an and one after Each event has a preferably in CamelCase For ArticleDelete hook A clump of code and data that should be run when an event happens This can be either a function and a chunk of or an object and a method hook function The function part of a third party developers and administrators to define code that will be run at certain points in the mainline code
Definition: hooks.txt:23
$query
return true to allow those checks to and false if checking is done use this to change the tables headers temp or archived zone change it to an object instance and return false override the list derivative used the name of the old file when set the default code will be skipped add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition: hooks.txt:1105
$IP
$IP
Definition: WebStart.php:88
ResourceFileCache
Resource loader request result caching in the file system.
Definition: ResourceFileCache.php:29
$res
$res
Definition: database.txt:21
ResourceLoaderContext\getRaw
getRaw()
Definition: ResourceLoaderContext.php:203
$retval
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account incomplete not yet checked for validity & $retval
Definition: hooks.txt:237
TS_RFC2822
const TS_RFC2822
RFC 2822 format, for E-mail and HTTP headers.
Definition: GlobalFunctions.php:2488
ResourceLoader\isValidModuleName
static isValidModuleName( $moduleName)
Check a module name for validity.
Definition: ResourceLoader.php:1280
wfExpandUrl
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
Definition: GlobalFunctions.php:544
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:1632
FileCacheBase\cacheTimestamp
cacheTimestamp()
Get the last-modified timestamp of the cache file.
Definition: FileCacheBase.php:103