MediaWiki REL1_32
ResourceLoader.php
Go to the documentation of this file.
1<?php
26use Psr\Log\LoggerAwareInterface;
27use Psr\Log\LoggerInterface;
28use Psr\Log\NullLogger;
30use Wikimedia\WrappedString;
31
38class ResourceLoader implements LoggerAwareInterface {
40 const CACHE_VERSION = 8;
41
43 protected static $debugMode = null;
44
49 protected $modules = [];
50
55 protected $moduleInfos = [];
56
58 protected $config;
59
65 protected $testModuleNames = [];
66
71 protected $sources = [];
72
77 protected $errors = [];
78
86 protected $extraHeaders = [];
87
91 protected $blobStore;
92
96 private $logger;
97
99 const FILTER_NOMIN = '/*@nomin*/';
100
115 public function preloadModuleInfo( array $moduleNames, ResourceLoaderContext $context ) {
116 if ( !$moduleNames ) {
117 // Or else Database*::select() will explode, plus it's cheaper!
118 return;
119 }
121 $skin = $context->getSkin();
122 $lang = $context->getLanguage();
123
124 // Batched version of ResourceLoaderModule::getFileDependencies
125 $vary = "$skin|$lang";
126 $res = $dbr->select( 'module_deps', [ 'md_module', 'md_deps' ], [
127 'md_module' => $moduleNames,
128 'md_skin' => $vary,
129 ], __METHOD__
130 );
131
132 // Prime in-object cache for file dependencies
133 $modulesWithDeps = [];
134 foreach ( $res as $row ) {
135 $module = $this->getModule( $row->md_module );
136 if ( $module ) {
137 $module->setFileDependencies( $context, ResourceLoaderModule::expandRelativePaths(
138 json_decode( $row->md_deps, true )
139 ) );
140 $modulesWithDeps[] = $row->md_module;
141 }
142 }
143 // Register the absence of a dependency row too
144 foreach ( array_diff( $moduleNames, $modulesWithDeps ) as $name ) {
145 $module = $this->getModule( $name );
146 if ( $module ) {
147 $this->getModule( $name )->setFileDependencies( $context, [] );
148 }
149 }
150
151 // Batched version of ResourceLoaderWikiModule::getTitleInfo
152 ResourceLoaderWikiModule::preloadTitleInfo( $context, $dbr, $moduleNames );
153
154 // Prime in-object cache for message blobs for modules with messages
155 $modules = [];
156 foreach ( $moduleNames as $name ) {
157 $module = $this->getModule( $name );
158 if ( $module && $module->getMessages() ) {
159 $modules[$name] = $module;
160 }
161 }
162 $store = $this->getMessageBlobStore();
163 $blobs = $store->getBlobs( $modules, $lang );
164 foreach ( $blobs as $name => $blob ) {
165 $modules[$name]->setMessageBlob( $blob, $lang );
166 }
167 }
168
186 public static function filter( $filter, $data, array $options = [] ) {
187 if ( strpos( $data, self::FILTER_NOMIN ) !== false ) {
188 return $data;
189 }
190
191 if ( isset( $options['cache'] ) && $options['cache'] === false ) {
192 return self::applyFilter( $filter, $data );
193 }
194
195 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
196 $cache = ObjectCache::getLocalServerInstance( CACHE_ANYTHING );
197
198 $key = $cache->makeGlobalKey(
199 'resourceloader',
200 'filter',
201 $filter,
202 self::CACHE_VERSION,
203 md5( $data )
204 );
205
206 $result = $cache->get( $key );
207 if ( $result === false ) {
208 $stats->increment( "resourceloader_cache.$filter.miss" );
209 $result = self::applyFilter( $filter, $data );
210 $cache->set( $key, $result, 24 * 3600 );
211 } else {
212 $stats->increment( "resourceloader_cache.$filter.hit" );
213 }
214 if ( $result === null ) {
215 // Cached failure
216 $result = $data;
217 }
218
219 return $result;
220 }
221
222 private static function applyFilter( $filter, $data ) {
223 $data = trim( $data );
224 if ( $data ) {
225 try {
226 $data = ( $filter === 'minify-css' )
227 ? CSSMin::minify( $data )
229 } catch ( Exception $e ) {
230 MWExceptionHandler::logException( $e );
231 return null;
232 }
233 }
234 return $data;
235 }
236
242 public function __construct( Config $config = null, LoggerInterface $logger = null ) {
243 global $IP;
244
245 $this->logger = $logger ?: new NullLogger();
246
247 if ( !$config ) {
248 $this->logger->debug( __METHOD__ . ' was called without providing a Config instance' );
249 $config = MediaWikiServices::getInstance()->getMainConfig();
250 }
251 $this->config = $config;
252
253 // Add 'local' source first
254 $this->addSource( 'local', $config->get( 'LoadScript' ) );
255
256 // Add other sources
257 $this->addSource( $config->get( 'ResourceLoaderSources' ) );
258
259 // Register core modules
260 $this->register( include "$IP/resources/Resources.php" );
261 // Register extension modules
262 $this->register( $config->get( 'ResourceModules' ) );
263
264 // Avoid PHP 7.1 warning from passing $this by reference
265 $rl = $this;
266 Hooks::run( 'ResourceLoaderRegisterModules', [ &$rl ] );
267
268 if ( $config->get( 'EnableJavaScriptTest' ) === true ) {
269 $this->registerTestModules();
270 }
271
272 $this->setMessageBlobStore( new MessageBlobStore( $this, $this->logger ) );
273 }
274
278 public function getConfig() {
279 return $this->config;
280 }
281
286 public function setLogger( LoggerInterface $logger ) {
287 $this->logger = $logger;
288 }
289
294 public function getLogger() {
295 return $this->logger;
296 }
297
302 public function getMessageBlobStore() {
303 return $this->blobStore;
304 }
305
311 $this->blobStore = $blobStore;
312 }
313
327 public function register( $name, $info = null ) {
328 $moduleSkinStyles = $this->config->get( 'ResourceModuleSkinStyles' );
329
330 // Allow multiple modules to be registered in one call
331 $registrations = is_array( $name ) ? $name : [ $name => $info ];
332 foreach ( $registrations as $name => $info ) {
333 // Warn on duplicate registrations
334 if ( isset( $this->moduleInfos[$name] ) ) {
335 // A module has already been registered by this name
336 $this->logger->warning(
337 'ResourceLoader duplicate registration warning. ' .
338 'Another module has already been registered as ' . $name
339 );
340 }
341
342 // Check $name for validity
343 if ( !self::isValidModuleName( $name ) ) {
344 throw new MWException( "ResourceLoader module name '$name' is invalid, "
345 . "see ResourceLoader::isValidModuleName()" );
346 }
347
348 // Attach module
349 if ( $info instanceof ResourceLoaderModule ) {
350 $this->moduleInfos[$name] = [ 'object' => $info ];
351 $info->setName( $name );
352 $this->modules[$name] = $info;
353 } elseif ( is_array( $info ) ) {
354 // New calling convention
355 $this->moduleInfos[$name] = $info;
356 } else {
357 throw new MWException(
358 'ResourceLoader module info type error for module \'' . $name .
359 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
360 );
361 }
362
363 // Last-minute changes
364
365 // Apply custom skin-defined styles to existing modules.
366 if ( $this->isFileModule( $name ) ) {
367 foreach ( $moduleSkinStyles as $skinName => $skinStyles ) {
368 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
369 if ( isset( $this->moduleInfos[$name]['skinStyles'][$skinName] ) ) {
370 continue;
371 }
372
373 // If $name is preceded with a '+', the defined style files will be added to 'default'
374 // skinStyles, otherwise 'default' will be ignored as it normally would be.
375 if ( isset( $skinStyles[$name] ) ) {
376 $paths = (array)$skinStyles[$name];
377 $styleFiles = [];
378 } elseif ( isset( $skinStyles['+' . $name] ) ) {
379 $paths = (array)$skinStyles['+' . $name];
380 $styleFiles = isset( $this->moduleInfos[$name]['skinStyles']['default'] ) ?
381 (array)$this->moduleInfos[$name]['skinStyles']['default'] :
382 [];
383 } else {
384 continue;
385 }
386
387 // Add new file paths, remapping them to refer to our directories and not use settings
388 // from the module we're modifying, which come from the base definition.
389 list( $localBasePath, $remoteBasePath ) =
391
392 foreach ( $paths as $path ) {
393 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
394 }
395
396 $this->moduleInfos[$name]['skinStyles'][$skinName] = $styleFiles;
397 }
398 }
399 }
400 }
401
402 public function registerTestModules() {
403 global $IP;
404
405 if ( $this->config->get( 'EnableJavaScriptTest' ) !== true ) {
406 throw new MWException( 'Attempt to register JavaScript test modules '
407 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
408 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
409 }
410
411 // Get core test suites
412 $testModules = [];
413 $testModules['qunit'] = [];
414 // Get other test suites (e.g. from extensions)
415 // Avoid PHP 7.1 warning from passing $this by reference
416 $rl = $this;
417 Hooks::run( 'ResourceLoaderTestModules', [ &$testModules, &$rl ] );
418
419 // Add the testrunner (which configures QUnit) to the dependencies.
420 // Since it must be ready before any of the test suites are executed.
421 foreach ( $testModules['qunit'] as &$module ) {
422 // Make sure all test modules are top-loading so that when QUnit starts
423 // on document-ready, it will run once and finish. If some tests arrive
424 // later (possibly after QUnit has already finished) they will be ignored.
425 $module['position'] = 'top';
426 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
427 }
428
429 $testModules['qunit'] =
430 ( include "$IP/tests/qunit/QUnitTestResources.php" ) + $testModules['qunit'];
431
432 foreach ( $testModules as $id => $names ) {
433 // Register test modules
434 $this->register( $testModules[$id] );
435
436 // Keep track of their names so that they can be loaded together
437 $this->testModuleNames[$id] = array_keys( $testModules[$id] );
438 }
439 }
440
451 public function addSource( $id, $loadUrl = null ) {
452 // Allow multiple sources to be registered in one call
453 if ( is_array( $id ) ) {
454 foreach ( $id as $key => $value ) {
455 $this->addSource( $key, $value );
456 }
457 return;
458 }
459
460 // Disallow duplicates
461 if ( isset( $this->sources[$id] ) ) {
462 throw new MWException(
463 'ResourceLoader duplicate source addition error. ' .
464 'Another source has already been registered as ' . $id
465 );
466 }
467
468 // Pre 1.24 backwards-compatibility
469 if ( is_array( $loadUrl ) ) {
470 if ( !isset( $loadUrl['loadScript'] ) ) {
471 throw new MWException(
472 __METHOD__ . ' was passed an array with no "loadScript" key.'
473 );
474 }
475
476 $loadUrl = $loadUrl['loadScript'];
477 }
478
479 $this->sources[$id] = $loadUrl;
480 }
481
487 public function getModuleNames() {
488 return array_keys( $this->moduleInfos );
489 }
490
501 public function getTestModuleNames( $framework = 'all' ) {
503 if ( $framework == 'all' ) {
504 return $this->testModuleNames;
505 } elseif ( isset( $this->testModuleNames[$framework] )
506 && is_array( $this->testModuleNames[$framework] )
507 ) {
508 return $this->testModuleNames[$framework];
509 } else {
510 return [];
511 }
512 }
513
521 public function isModuleRegistered( $name ) {
522 return isset( $this->moduleInfos[$name] );
523 }
524
536 public function getModule( $name ) {
537 if ( !isset( $this->modules[$name] ) ) {
538 if ( !isset( $this->moduleInfos[$name] ) ) {
539 // No such module
540 return null;
541 }
542 // Construct the requested object
543 $info = $this->moduleInfos[$name];
545 if ( isset( $info['object'] ) ) {
546 // Object given in info array
547 $object = $info['object'];
548 } elseif ( isset( $info['factory'] ) ) {
549 $object = call_user_func( $info['factory'], $info );
550 $object->setConfig( $this->getConfig() );
551 $object->setLogger( $this->logger );
552 } else {
553 if ( !isset( $info['class'] ) ) {
554 $class = ResourceLoaderFileModule::class;
555 } else {
556 $class = $info['class'];
557 }
559 $object = new $class( $info );
560 $object->setConfig( $this->getConfig() );
561 $object->setLogger( $this->logger );
562 }
563 $object->setName( $name );
564 $this->modules[$name] = $object;
565 }
566
567 return $this->modules[$name];
568 }
569
576 protected function isFileModule( $name ) {
577 if ( !isset( $this->moduleInfos[$name] ) ) {
578 return false;
579 }
580 $info = $this->moduleInfos[$name];
581 if ( isset( $info['object'] ) ) {
582 return false;
583 }
584 return (
585 // The implied default for 'class' is ResourceLoaderFileModule
586 !isset( $info['class'] ) ||
587 // Explicit default
588 $info['class'] === ResourceLoaderFileModule::class ||
589 is_subclass_of( $info['class'], ResourceLoaderFileModule::class )
590 );
591 }
592
598 public function getSources() {
599 return $this->sources;
600 }
601
611 public function getLoadScript( $source ) {
612 if ( !isset( $this->sources[$source] ) ) {
613 throw new MWException( "The $source source was never registered in ResourceLoader." );
614 }
615 return $this->sources[$source];
616 }
617
623 public static function makeHash( $value ) {
624 $hash = hash( 'fnv132', $value );
625 return Wikimedia\base_convert( $hash, 16, 36, 7 );
626 }
627
637 public function outputErrorAndLog( Exception $e, $msg, array $context = [] ) {
638 MWExceptionHandler::logException( $e );
639 $this->logger->warning(
640 $msg,
641 $context + [ 'exception' => $e ]
642 );
643 $this->errors[] = self::formatExceptionNoComment( $e );
644 }
645
654 public function getCombinedVersion( ResourceLoaderContext $context, array $moduleNames ) {
655 if ( !$moduleNames ) {
656 return '';
657 }
658 $hashes = array_map( function ( $module ) use ( $context ) {
659 try {
660 return $this->getModule( $module )->getVersionHash( $context );
661 } catch ( Exception $e ) {
662 // If modules fail to compute a version, don't fail the request (T152266)
663 // and still compute versions of other modules.
664 $this->outputErrorAndLog( $e,
665 'Calculating version for "{module}" failed: {exception}',
666 [
667 'module' => $module,
668 ]
669 );
670 return '';
671 }
672 }, $moduleNames );
673 return self::makeHash( implode( '', $hashes ) );
674 }
675
690 // As of MediaWiki 1.28, the server and client use the same algorithm for combining
691 // version hashes. There is no technical reason for this to be same, and for years the
692 // implementations differed. If getCombinedVersion in PHP (used for StartupModule and
693 // E-Tag headers) differs in the future from getCombinedVersion in JS (used for 'version'
694 // query parameter), then this method must continue to match the JS one.
695 $moduleNames = [];
696 foreach ( $context->getModules() as $name ) {
697 if ( !$this->getModule( $name ) ) {
698 // If a versioned request contains a missing module, the version is a mismatch
699 // as the client considered a module (and version) we don't have.
700 return '';
701 }
702 $moduleNames[] = $name;
703 }
704 return $this->getCombinedVersion( $context, $moduleNames );
705 }
706
713 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
714 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
715 // is used: ob_clean() will clear the GZIP header in that case and it won't come
716 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
717 // the whole thing in our own output buffer to be sure the active buffer
718 // doesn't use ob_gzhandler.
719 // See https://bugs.php.net/bug.php?id=36514
720 ob_start();
721
722 $this->measureResponseTime( RequestContext::getMain()->getTiming() );
723
724 // Find out which modules are missing and instantiate the others
725 $modules = [];
726 $missing = [];
727 foreach ( $context->getModules() as $name ) {
728 $module = $this->getModule( $name );
729 if ( $module ) {
730 // Do not allow private modules to be loaded from the web.
731 // This is a security issue, see T36907.
732 if ( $module->getGroup() === 'private' ) {
733 $this->logger->debug( "Request for private module '$name' denied" );
734 $this->errors[] = "Cannot show private module \"$name\"";
735 continue;
736 }
737 $modules[$name] = $module;
738 } else {
739 $missing[] = $name;
740 }
741 }
742
743 try {
744 // Preload for getCombinedVersion() and for batch makeModuleResponse()
745 $this->preloadModuleInfo( array_keys( $modules ), $context );
746 } catch ( Exception $e ) {
747 $this->outputErrorAndLog( $e, 'Preloading module info failed: {exception}' );
748 }
749
750 // Combine versions to propagate cache invalidation
751 $versionHash = '';
752 try {
753 $versionHash = $this->getCombinedVersion( $context, array_keys( $modules ) );
754 } catch ( Exception $e ) {
755 $this->outputErrorAndLog( $e, 'Calculating version hash failed: {exception}' );
756 }
757
758 // See RFC 2616 § 3.11 Entity Tags
759 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
760 $etag = 'W/"' . $versionHash . '"';
761
762 // Try the client-side cache first
763 if ( $this->tryRespondNotModified( $context, $etag ) ) {
764 return; // output handled (buffers cleared)
765 }
766
767 // Use file cache if enabled and available...
768 if ( $this->config->get( 'UseFileCache' ) ) {
770 if ( $this->tryRespondFromFileCache( $fileCache, $context, $etag ) ) {
771 return; // output handled
772 }
773 }
774
775 // Generate a response
776 $response = $this->makeModuleResponse( $context, $modules, $missing );
777
778 // Capture any PHP warnings from the output buffer and append them to the
779 // error list if we're in debug mode.
780 if ( $context->getDebug() ) {
781 $warnings = ob_get_contents();
782 if ( strlen( $warnings ) ) {
783 $this->errors[] = $warnings;
784 }
785 }
786
787 // Save response to file cache unless there are errors
788 if ( isset( $fileCache ) && !$this->errors && !count( $missing ) ) {
789 // Cache single modules and images...and other requests if there are enough hits
791 if ( $fileCache->isCacheWorthy() ) {
792 $fileCache->saveText( $response );
793 } else {
794 $fileCache->incrMissesRecent( $context->getRequest() );
795 }
796 }
797 }
798
799 $this->sendResponseHeaders( $context, $etag, (bool)$this->errors, $this->extraHeaders );
800
801 // Remove the output buffer and output the response
802 ob_end_clean();
803
804 if ( $context->getImageObj() && $this->errors ) {
805 // We can't show both the error messages and the response when it's an image.
806 $response = implode( "\n\n", $this->errors );
807 } elseif ( $this->errors ) {
808 $errorText = implode( "\n\n", $this->errors );
809 $errorResponse = self::makeComment( $errorText );
810 if ( $context->shouldIncludeScripts() ) {
811 $errorResponse .= 'if (window.console && console.error) {'
812 . Xml::encodeJsCall( 'console.error', [ $errorText ] )
813 . "}\n";
814 }
815
816 // Prepend error info to the response
817 $response = $errorResponse . $response;
818 }
819
820 $this->errors = [];
821 echo $response;
822 }
823
824 protected function measureResponseTime( Timing $timing ) {
825 DeferredUpdates::addCallableUpdate( function () use ( $timing ) {
826 $measure = $timing->measure( 'responseTime', 'requestStart', 'requestShutdown' );
827 if ( $measure !== false ) {
828 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
829 $stats->timing( 'resourceloader.responseTime', $measure['duration'] * 1000 );
830 }
831 } );
832 }
833
845 protected function sendResponseHeaders(
846 ResourceLoaderContext $context, $etag, $errors, array $extra = []
847 ) {
848 \MediaWiki\HeaderCallback::warnIfHeadersSent();
849 $rlMaxage = $this->config->get( 'ResourceLoaderMaxage' );
850 // Use a short cache expiry so that updates propagate to clients quickly, if:
851 // - No version specified (shared resources, e.g. stylesheets)
852 // - There were errors (recover quickly)
853 // - Version mismatch (T117587, T47877)
854 if ( is_null( $context->getVersion() )
855 || $errors
856 || $context->getVersion() !== $this->makeVersionQuery( $context )
857 ) {
858 $maxage = $rlMaxage['unversioned']['client'];
859 $smaxage = $rlMaxage['unversioned']['server'];
860 // If a version was specified we can use a longer expiry time since changing
861 // version numbers causes cache misses
862 } else {
863 $maxage = $rlMaxage['versioned']['client'];
864 $smaxage = $rlMaxage['versioned']['server'];
865 }
866 if ( $context->getImageObj() ) {
867 // Output different headers if we're outputting textual errors.
868 if ( $errors ) {
869 header( 'Content-Type: text/plain; charset=utf-8' );
870 } else {
871 $context->getImageObj()->sendResponseHeaders( $context );
872 }
873 } elseif ( $context->getOnly() === 'styles' ) {
874 header( 'Content-Type: text/css; charset=utf-8' );
875 header( 'Access-Control-Allow-Origin: *' );
876 } else {
877 header( 'Content-Type: text/javascript; charset=utf-8' );
878 }
879 // See RFC 2616 § 14.19 ETag
880 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
881 header( 'ETag: ' . $etag );
882 if ( $context->getDebug() ) {
883 // Do not cache debug responses
884 header( 'Cache-Control: private, no-cache, must-revalidate' );
885 header( 'Pragma: no-cache' );
886 } else {
887 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
888 $exp = min( $maxage, $smaxage );
889 header( 'Expires: ' . wfTimestamp( TS_RFC2822, $exp + time() ) );
890 }
891 foreach ( $extra as $header ) {
892 header( $header );
893 }
894 }
895
907 // See RFC 2616 § 14.26 If-None-Match
908 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
909 $clientKeys = $context->getRequest()->getHeader( 'If-None-Match', WebRequest::GETHEADER_LIST );
910 // Never send 304s in debug mode
911 if ( $clientKeys !== false && !$context->getDebug() && in_array( $etag, $clientKeys ) ) {
912 // There's another bug in ob_gzhandler (see also the comment at
913 // the top of this function) that causes it to gzip even empty
914 // responses, meaning it's impossible to produce a truly empty
915 // response (because the gzip header is always there). This is
916 // a problem because 304 responses have to be completely empty
917 // per the HTTP spec, and Firefox behaves buggily when they're not.
918 // See also https://bugs.php.net/bug.php?id=51579
919 // To work around this, we tear down all output buffering before
920 // sending the 304.
921 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
922
923 HttpStatus::header( 304 );
924
925 $this->sendResponseHeaders( $context, $etag, false );
926 return true;
927 }
928 return false;
929 }
930
939 protected function tryRespondFromFileCache(
940 ResourceFileCache $fileCache,
942 $etag
943 ) {
944 $rlMaxage = $this->config->get( 'ResourceLoaderMaxage' );
945 // Buffer output to catch warnings.
946 ob_start();
947 // Get the maximum age the cache can be
948 $maxage = is_null( $context->getVersion() )
949 ? $rlMaxage['unversioned']['server']
950 : $rlMaxage['versioned']['server'];
951 // Minimum timestamp the cache file must have
952 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW, time() - $maxage ) );
953 if ( !$good ) {
954 try { // RL always hits the DB on file cache miss...
956 } catch ( DBConnectionError $e ) { // ...check if we need to fallback to cache
957 $good = $fileCache->isCacheGood(); // cache existence check
958 }
959 }
960 if ( $good ) {
961 $ts = $fileCache->cacheTimestamp();
962 // Send content type and cache headers
963 $this->sendResponseHeaders( $context, $etag, false );
964 $response = $fileCache->fetchText();
965 // Capture any PHP warnings from the output buffer and append them to the
966 // response in a comment if we're in debug mode.
967 if ( $context->getDebug() ) {
968 $warnings = ob_get_contents();
969 if ( strlen( $warnings ) ) {
970 $response = self::makeComment( $warnings ) . $response;
971 }
972 }
973 // Remove the output buffer and output the response
974 ob_end_clean();
975 echo $response . "\n/* Cached {$ts} */";
976 return true; // cache hit
977 }
978 // Clear buffer
979 ob_end_clean();
980
981 return false; // cache miss
982 }
983
992 public static function makeComment( $text ) {
993 $encText = str_replace( '*/', '* /', $text );
994 return "/*\n$encText\n*/\n";
995 }
996
1003 public static function formatException( $e ) {
1004 return self::makeComment( self::formatExceptionNoComment( $e ) );
1005 }
1006
1014 protected static function formatExceptionNoComment( $e ) {
1016
1017 if ( !$wgShowExceptionDetails ) {
1018 return MWExceptionHandler::getPublicLogMessage( $e );
1019 }
1020
1021 return MWExceptionHandler::getLogMessage( $e ) .
1022 "\nBacktrace:\n" .
1023 MWExceptionHandler::getRedactedTraceAsString( $e );
1024 }
1025
1038 array $modules, array $missing = []
1039 ) {
1040 $out = '';
1041 $states = [];
1042
1043 if ( !count( $modules ) && !count( $missing ) ) {
1044 return <<<MESSAGE
1045/* This file is the Web entry point for MediaWiki's ResourceLoader:
1046 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
1047 no modules were requested. Max made me put this here. */
1048MESSAGE;
1049 }
1050
1051 $image = $context->getImageObj();
1052 if ( $image ) {
1053 $data = $image->getImageData( $context );
1054 if ( $data === false ) {
1055 $data = '';
1056 $this->errors[] = 'Image generation failed';
1057 }
1058 return $data;
1059 }
1060
1061 foreach ( $missing as $name ) {
1062 $states[$name] = 'missing';
1063 }
1064
1065 // Generate output
1066 $isRaw = false;
1067
1068 $filter = $context->getOnly() === 'styles' ? 'minify-css' : 'minify-js';
1069
1070 foreach ( $modules as $name => $module ) {
1071 try {
1072 $content = $module->getModuleContent( $context );
1073 $implementKey = $name . '@' . $module->getVersionHash( $context );
1074 $strContent = '';
1075
1076 if ( isset( $content['headers'] ) ) {
1077 $this->extraHeaders = array_merge( $this->extraHeaders, $content['headers'] );
1078 }
1079
1080 // Append output
1081 switch ( $context->getOnly() ) {
1082 case 'scripts':
1083 $scripts = $content['scripts'];
1084 if ( is_string( $scripts ) ) {
1085 // Load scripts raw...
1086 $strContent = $scripts;
1087 } elseif ( is_array( $scripts ) ) {
1088 // ...except when $scripts is an array of URLs
1089 $strContent = self::makeLoaderImplementScript( $implementKey, $scripts, [], [], [] );
1090 }
1091 break;
1092 case 'styles':
1093 $styles = $content['styles'];
1094 // We no longer separate into media, they are all combined now with
1095 // custom media type groups into @media .. {} sections as part of the css string.
1096 // Module returns either an empty array or a numerical array with css strings.
1097 $strContent = isset( $styles['css'] ) ? implode( '', $styles['css'] ) : '';
1098 break;
1099 default:
1100 $scripts = $content['scripts'] ?? '';
1101 if ( is_string( $scripts ) ) {
1102 if ( $name === 'site' || $name === 'user' ) {
1103 // Legacy scripts that run in the global scope without a closure.
1104 // mw.loader.implement will use globalEval if scripts is a string.
1105 // Minify manually here, because general response minification is
1106 // not effective due it being a string literal, not a function.
1107 if ( !self::inDebugMode() ) {
1108 $scripts = self::filter( 'minify-js', $scripts ); // T107377
1109 }
1110 } else {
1111 $scripts = new XmlJsCode( $scripts );
1112 }
1113 }
1114 $strContent = self::makeLoaderImplementScript(
1115 $implementKey,
1116 $scripts,
1117 $content['styles'] ?? [],
1118 isset( $content['messagesBlob'] ) ? new XmlJsCode( $content['messagesBlob'] ) : [],
1119 $content['templates'] ?? []
1120 );
1121 break;
1122 }
1123
1124 if ( !$context->getDebug() ) {
1125 $strContent = self::filter( $filter, $strContent );
1126 }
1127
1128 if ( $context->getOnly() === 'scripts' ) {
1129 // Use a linebreak between module scripts (T162719)
1130 $out .= $this->ensureNewline( $strContent );
1131 } else {
1132 $out .= $strContent;
1133 }
1134
1135 } catch ( Exception $e ) {
1136 $this->outputErrorAndLog( $e, 'Generating module package failed: {exception}' );
1137
1138 // Respond to client with error-state instead of module implementation
1139 $states[$name] = 'error';
1140 unset( $modules[$name] );
1141 }
1142 $isRaw |= $module->isRaw();
1143 }
1144
1145 // Update module states
1146 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1147 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1148 // Set the state of modules loaded as only scripts to ready as
1149 // they don't have an mw.loader.implement wrapper that sets the state
1150 foreach ( $modules as $name => $module ) {
1151 $states[$name] = 'ready';
1152 }
1153 }
1154
1155 // Set the state of modules we didn't respond to with mw.loader.implement
1156 if ( count( $states ) ) {
1157 $stateScript = self::makeLoaderStateScript( $states );
1158 if ( !$context->getDebug() ) {
1159 $stateScript = self::filter( 'minify-js', $stateScript );
1160 }
1161 // Use a linebreak between module script and state script (T162719)
1162 $out = $this->ensureNewline( $out ) . $stateScript;
1163 }
1164 } else {
1165 if ( $states ) {
1166 $this->errors[] = 'Problematic modules: '
1167 . self::encodeJsonForScript( $states );
1168 }
1169 }
1170
1171 return $out;
1172 }
1173
1179 private function ensureNewline( $str ) {
1180 $end = substr( $str, -1 );
1181 if ( $end === false || $end === "\n" ) {
1182 return $str;
1183 }
1184 return $str . "\n";
1185 }
1186
1193 public function getModulesByMessage( $messageKey ) {
1194 $moduleNames = [];
1195 foreach ( $this->getModuleNames() as $moduleName ) {
1196 $module = $this->getModule( $moduleName );
1197 if ( in_array( $messageKey, $module->getMessages() ) ) {
1198 $moduleNames[] = $moduleName;
1199 }
1200 }
1201 return $moduleNames;
1202 }
1203
1220 protected static function makeLoaderImplementScript(
1221 $name, $scripts, $styles, $messages, $templates
1222 ) {
1223 if ( $scripts instanceof XmlJsCode ) {
1224 if ( self::inDebugMode() ) {
1225 $scripts = new XmlJsCode( "function ( $, jQuery, require, module ) {\n{$scripts->value}\n}" );
1226 } else {
1227 $scripts = new XmlJsCode( 'function($,jQuery,require,module){' . $scripts->value . '}' );
1228 }
1229 } elseif ( !is_string( $scripts ) && !is_array( $scripts ) ) {
1230 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1231 }
1232 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1233 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1234 // of "{}". Force them to objects.
1235 $module = [
1236 $name,
1237 $scripts,
1238 (object)$styles,
1239 (object)$messages,
1240 (object)$templates,
1241 ];
1242 self::trimArray( $module );
1243
1244 return Xml::encodeJsCall( 'mw.loader.implement', $module, self::inDebugMode() );
1245 }
1246
1254 public static function makeMessageSetScript( $messages ) {
1255 return Xml::encodeJsCall(
1256 'mw.messages.set',
1257 [ (object)$messages ],
1258 self::inDebugMode()
1259 );
1260 }
1261
1269 public static function makeCombinedStyles( array $stylePairs ) {
1270 $out = [];
1271 foreach ( $stylePairs as $media => $styles ) {
1272 // ResourceLoaderFileModule::getStyle can return the styles
1273 // as a string or an array of strings. This is to allow separation in
1274 // the front-end.
1275 $styles = (array)$styles;
1276 foreach ( $styles as $style ) {
1277 $style = trim( $style );
1278 // Don't output an empty "@media print { }" block (T42498)
1279 if ( $style !== '' ) {
1280 // Transform the media type based on request params and config
1281 // The way that this relies on $wgRequest to propagate request params is slightly evil
1282 $media = OutputPage::transformCssMedia( $media );
1283
1284 if ( $media === '' || $media == 'all' ) {
1285 $out[] = $style;
1286 } elseif ( is_string( $media ) ) {
1287 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1288 }
1289 // else: skip
1290 }
1291 }
1292 }
1293 return $out;
1294 }
1295
1305 public static function encodeJsonForScript( $data ) {
1306 // Keep output as small as possible by disabling needless escape modes
1307 // that PHP uses by default.
1308 // However, while most module scripts are only served on HTTP responses
1309 // for JavaScript, some modules can also be embedded in the HTML as inline
1310 // scripts. This, and the fact that we sometimes need to export strings
1311 // containing user-generated content and labels that may genuinely contain
1312 // a sequences like "</script>", we need to encode either '/' or '<'.
1313 // By default PHP escapes '/'. Let's escape '<' instead which is less common
1314 // and allows URLs to mostly remain readable.
1315 $jsonFlags = JSON_UNESCAPED_SLASHES |
1316 JSON_UNESCAPED_UNICODE |
1317 JSON_HEX_TAG |
1318 JSON_HEX_AMP;
1319 if ( self::inDebugMode() ) {
1320 $jsonFlags |= JSON_PRETTY_PRINT;
1321 }
1322 return json_encode( $data, $jsonFlags );
1323 }
1324
1339 public static function makeLoaderStateScript( $states, $state = null ) {
1340 if ( !is_array( $states ) ) {
1341 $states = [ $states => $state ];
1342 }
1343 return Xml::encodeJsCall(
1344 'mw.loader.state',
1345 [ $states ],
1346 self::inDebugMode()
1347 );
1349
1350 private static function isEmptyObject( stdClass $obj ) {
1351 foreach ( $obj as $key => $value ) {
1352 return false;
1353 }
1354 return true;
1355 }
1356
1369 private static function trimArray( array &$array ) {
1370 $i = count( $array );
1371 while ( $i-- ) {
1372 if ( $array[$i] === null
1373 || $array[$i] === []
1374 || ( $array[$i] instanceof XmlJsCode && $array[$i]->value === '{}' )
1375 || ( $array[$i] instanceof stdClass && self::isEmptyObject( $array[$i] ) )
1376 ) {
1377 unset( $array[$i] );
1378 } else {
1379 break;
1380 }
1381 }
1382 }
1383
1409 public static function makeLoaderRegisterScript( array $modules ) {
1410 // Optimisation: Transform dependency names into indexes when possible
1411 // to produce smaller output. They are expanded by mw.loader.register on
1412 // the other end using resolveIndexedDependencies().
1413 $index = [];
1414 foreach ( $modules as $i => &$module ) {
1415 // Build module name index
1416 $index[$module[0]] = $i;
1417 }
1418 foreach ( $modules as &$module ) {
1419 if ( isset( $module[2] ) ) {
1420 foreach ( $module[2] as &$dependency ) {
1421 if ( isset( $index[$dependency] ) ) {
1422 // Replace module name in dependency list with index
1423 $dependency = $index[$dependency];
1424 }
1425 }
1426 }
1427 }
1428
1429 array_walk( $modules, [ 'self', 'trimArray' ] );
1430
1431 return Xml::encodeJsCall(
1432 'mw.loader.register',
1433 [ $modules ],
1434 self::inDebugMode()
1435 );
1436 }
1437
1452 public static function makeLoaderSourcesScript( $sources, $loadUrl = null ) {
1453 if ( !is_array( $sources ) ) {
1454 $sources = [ $sources => $loadUrl ];
1455 }
1456 return Xml::encodeJsCall(
1457 'mw.loader.addSource',
1458 [ $sources ],
1459 self::inDebugMode()
1460 );
1461 }
1462
1469 public static function makeLoaderConditionalScript( $script ) {
1470 // Adds a function to lazy-created RLQ
1471 return '(window.RLQ=window.RLQ||[]).push(function(){' .
1472 trim( $script ) . '});';
1473 }
1474
1483 public static function makeInlineCodeWithModule( $modules, $script ) {
1484 // Adds an array to lazy-created RLQ
1485 return '(window.RLQ=window.RLQ||[]).push(['
1486 . self::encodeJsonForScript( $modules ) . ','
1487 . 'function(){' . trim( $script ) . '}'
1488 . ']);';
1489 }
1490
1502 public static function makeInlineScript( $script, $nonce = null ) {
1503 $js = self::makeLoaderConditionalScript( $script );
1504 $escNonce = '';
1505 if ( $nonce === null ) {
1506 wfWarn( __METHOD__ . " did not get nonce. Will break CSP" );
1507 } elseif ( $nonce !== false ) {
1508 // If it was false, CSP is disabled, so no nonce attribute.
1509 // Nonce should be only base64 characters, so should be safe,
1510 // but better to be safely escaped than sorry.
1511 $escNonce = ' nonce="' . htmlspecialchars( $nonce ) . '"';
1512 }
1513
1514 return new WrappedString(
1515 Html::inlineScript( $js, $nonce ),
1516 "<script$escNonce>(window.RLQ=window.RLQ||[]).push(function(){",
1517 '});</script>'
1518 );
1519 }
1520
1529 public static function makeConfigSetScript( array $configuration ) {
1530 $js = Xml::encodeJsCall(
1531 'mw.config.set',
1532 [ $configuration ],
1533 self::inDebugMode()
1534 );
1535 if ( $js === false ) {
1536 throw new Exception(
1537 'JSON serialization of config data failed. ' .
1538 'This usually means the config data is not valid UTF-8.'
1539 );
1540 }
1541 return $js;
1542 }
1543
1557 public static function makePackedModulesString( $modules ) {
1558 $moduleMap = []; // [ prefix => [ suffixes ] ]
1559 foreach ( $modules as $module ) {
1560 $pos = strrpos( $module, '.' );
1561 $prefix = $pos === false ? '' : substr( $module, 0, $pos );
1562 $suffix = $pos === false ? $module : substr( $module, $pos + 1 );
1563 $moduleMap[$prefix][] = $suffix;
1564 }
1565
1566 $arr = [];
1567 foreach ( $moduleMap as $prefix => $suffixes ) {
1568 $p = $prefix === '' ? '' : $prefix . '.';
1569 $arr[] = $p . implode( ',', $suffixes );
1570 }
1571 return implode( '|', $arr );
1572 }
1573
1579 public static function inDebugMode() {
1580 if ( self::$debugMode === null ) {
1582 self::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1583 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1584 );
1585 }
1586 return self::$debugMode;
1587 }
1588
1599 public static function clearCache() {
1600 self::$debugMode = null;
1601 }
1602
1612 public function createLoaderURL( $source, ResourceLoaderContext $context,
1613 $extraQuery = []
1614 ) {
1615 $query = self::createLoaderQuery( $context, $extraQuery );
1616 $script = $this->getLoadScript( $source );
1617
1618 return wfAppendQuery( $script, $query );
1619 }
1620
1630 protected static function createLoaderQuery( ResourceLoaderContext $context, $extraQuery = [] ) {
1631 return self::makeLoaderQuery(
1632 $context->getModules(),
1633 $context->getLanguage(),
1634 $context->getSkin(),
1635 $context->getUser(),
1636 $context->getVersion(),
1637 $context->getDebug(),
1638 $context->getOnly(),
1639 $context->getRequest()->getBool( 'printable' ),
1640 $context->getRequest()->getBool( 'handheld' ),
1641 $extraQuery
1642 );
1643 }
1644
1662 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1663 $version = null, $debug = false, $only = null, $printable = false,
1664 $handheld = false, $extraQuery = []
1665 ) {
1666 $query = [
1667 'modules' => self::makePackedModulesString( $modules ),
1668 'lang' => $lang,
1669 'skin' => $skin,
1670 'debug' => $debug ? 'true' : 'false',
1671 ];
1672 if ( $user !== null ) {
1673 $query['user'] = $user;
1674 }
1675 if ( $version !== null ) {
1676 $query['version'] = $version;
1677 }
1678 if ( $only !== null ) {
1679 $query['only'] = $only;
1680 }
1681 if ( $printable ) {
1682 $query['printable'] = 1;
1683 }
1684 if ( $handheld ) {
1685 $query['handheld'] = 1;
1686 }
1687 $query += $extraQuery;
1688
1689 // Make queries uniform in order
1690 ksort( $query );
1691 return $query;
1692 }
1693
1703 public static function isValidModuleName( $moduleName ) {
1704 return strcspn( $moduleName, '!,|', 0, 255 ) === strlen( $moduleName );
1705 }
1706
1717 public function getLessCompiler( $vars = [] ) {
1718 global $IP;
1719 // When called from the installer, it is possible that a required PHP extension
1720 // is missing (at least for now; see T49564). If this is the case, throw an
1721 // exception (caught by the installer) to prevent a fatal error later on.
1722 if ( !class_exists( 'Less_Parser' ) ) {
1723 throw new MWException( 'MediaWiki requires the less.php parser' );
1724 }
1725
1726 $parser = new Less_Parser;
1727 $parser->ModifyVars( $vars );
1728 $parser->SetImportDirs( [
1729 "$IP/resources/src/mediawiki.less/" => '',
1730 ] );
1731 $parser->SetOption( 'relativeUrls', false );
1732
1733 return $parser;
1734 }
1735
1743 public function getLessVars() {
1744 return [];
1745 }
1746}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for and distribution as defined by Sections through of this document Licensor shall mean the copyright owner or entity authorized by the copyright owner that is granting the License Legal Entity shall mean the union of the acting entity and all other entities that control are controlled by or are under common control with that entity For the purposes of this definition control direct or to cause the direction or management of such whether by contract or including but not limited to software source documentation and configuration files Object form shall mean any form resulting from mechanical transformation or translation of a Source including but not limited to compiled object generated and conversions to other media types Work shall mean the work of whether in Source or Object made available under the as indicated by a copyright notice that is included in or attached to the whether in Source or Object that is based or other modifications as a an original work of authorship For the purposes of this Derivative Works shall not include works that remain separable or merely the Work and Derivative Works thereof Contribution shall mean any work of including the original version of the Work and any modifications or additions to that Work or Derivative Works that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner For the purposes of this definition
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for and distribution as defined by Sections through of this document Licensor shall mean the copyright owner or entity authorized by the copyright owner that is granting the License Legal Entity shall mean the union of the acting entity and all other entities that control are controlled by or are under common control with that entity For the purposes of this definition control direct or to cause the direction or management of such whether by contract or including but not limited to software source documentation and configuration files Object form shall mean any form resulting from mechanical transformation or translation of a Source including but not limited to compiled object generated and conversions to other media types Work shall mean the work of whether in Source or Object made available under the as indicated by a copyright notice that is included in or attached to the whether in Source or Object that is based or other modifications as a an original work of authorship For the purposes of this Derivative Works shall not include works that remain separable from
$wgResourceLoaderDebug
The default debug mode (on/off) for of ResourceLoader requests.
$wgShowExceptionDetails
If set to true, uncaught exceptions will print the exception message and a complete stack trace to ou...
wfWarn( $msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
wfResetOutputBuffers( $resetGzipEncoding=true)
Clear away any user-level output buffers, discarding contents.
$messages
if(! $wgDBerrorLogTZ) $wgRequest
Definition Setup.php:747
$IP
Definition WebStart.php:41
static minify( $css)
Removes whitespace from CSS data.
Definition CSSMin.php:544
isCacheGood( $timestamp='')
Check if up to date cache file exists.
fetchText()
Get the uncompressed text from the cache.
cacheTimestamp()
Get the last-modified timestamp of the cache file.
static header( $code)
Output an HTTP status code header.
static minify( $s)
Returns minified JavaScript code.
MediaWiki exception.
MediaWikiServices is the service locator for the application scope of MediaWiki.
This class generates message blobs for use by ResourceLoader modules.
get(ResourceLoader $resourceLoader, $modules, $lang)
static transformCssMedia( $media)
Transform "media" attribute based on request parameters.
ResourceLoader request result caching in the file system.
static useFileCache(ResourceLoaderContext $context)
Check if an RL request can be cached.
static newFromContext(ResourceLoaderContext $context)
Construct an ResourceFileCache from a context.
Object passed around to modules which contains information about the state of a specific loader reque...
static extractBasePaths( $options=[], $localBasePath=null, $remoteBasePath=null)
Extract a pair of local and remote base paths from module definition information.
An object to represent a path to a JavaScript/CSS file, along with a remote and local base path,...
Abstraction for ResourceLoader modules, with name registration and maxage functionality.
static expandRelativePaths(array $filePaths)
Expand directories relative to $IP.
Dynamic JavaScript and CSS resource loading system.
__construct(Config $config=null, LoggerInterface $logger=null)
Register core modules and runs registration hooks.
static formatExceptionNoComment( $e)
Handle exception display.
tryRespondFromFileCache(ResourceFileCache $fileCache, ResourceLoaderContext $context, $etag)
Send out code for a response from file cache if possible.
isFileModule( $name)
Whether the module is a ResourceLoaderFileModule (including subclasses).
getModuleNames()
Get a list of module names.
setMessageBlobStore(MessageBlobStore $blobStore)
makeModuleResponse(ResourceLoaderContext $context, array $modules, array $missing=[])
Generate code for a response.
LoggerInterface $logger
setLogger(LoggerInterface $logger)
getTestModuleNames( $framework='all')
Get a list of test module names for one (or all) frameworks.
getLoadScript( $source)
Get the URL to the load.php endpoint for the given ResourceLoader source.
sendResponseHeaders(ResourceLoaderContext $context, $etag, $errors, array $extra=[])
Send main response headers to the client.
static bool $debugMode
array $extraHeaders
List of extra HTTP response headers provided by loaded modules.
tryRespondNotModified(ResourceLoaderContext $context, $etag)
Respond with HTTP 304 Not Modified if appropiate.
getSources()
Get the list of sources.
addSource( $id, $loadUrl=null)
Add a foreign source of modules.
array $moduleInfos
Associative array mapping module name to info associative array.
outputErrorAndLog(Exception $e, $msg, array $context=[])
Add an error to the 'errors' array and log it.
array $testModuleNames
Associative array mapping framework ids to a list of names of test suite modules like [ 'qunit' => [ ...
makeVersionQuery(ResourceLoaderContext $context)
Get the expected value of the 'version' query parameter.
getModule( $name)
Get the ResourceLoaderModule object for a given module name.
array $modules
Module name/ResourceLoaderModule object pairs.
isModuleRegistered( $name)
Check whether a ResourceLoader module is registered.
static applyFilter( $filter, $data)
measureResponseTime(Timing $timing)
static formatException( $e)
Handle exception display.
MessageBlobStore $blobStore
array $errors
Errors accumulated during current respond() call.
static makeComment( $text)
Generate a CSS or JS comment block.
getCombinedVersion(ResourceLoaderContext $context, array $moduleNames)
Helper method to get and combine versions of multiple modules.
respond(ResourceLoaderContext $context)
Output a response to a load request, including the content-type header.
static makeHash( $value)
static filter( $filter, $data, array $options=[])
Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
preloadModuleInfo(array $moduleNames, ResourceLoaderContext $context)
Load information stored in the database about modules.
An interface to help developers measure the performance of their applications.
Definition Timing.php:45
measure( $measureName, $startMark='requestStart', $endMark=null)
This method stores the duration between two marks along with the associated name (a "measure").
Definition Timing.php:124
A wrapper class which causes Xml::encodeJsVar() and Xml::encodeJsCall() to interpret a given string a...
Definition XmlJsCode.php:39
static encodeJsCall( $name, $args, $pretty=false)
Create a call to a JavaScript function.
Definition Xml.php:679
$res
Definition database.txt:21
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition deferred.txt:11
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
globals will be eliminated from MediaWiki replaced by an application object which would be passed to constructors Whether that would be an convenient solution remains to be but certainly PHP makes such object oriented programming models easier than they were in previous versions For the time being MediaWiki programmers will have to work in an environment with some global context At the time of globals were initialised on startup by MediaWiki of these were configuration which are documented in DefaultSettings php There is no comprehensive documentation for the remaining however some of the most important ones are listed below They are typically initialised either in index php or in Setup php $wgTitle Title object created from the request URL $wgOut OutputPage object for HTTP response $wgUser User object for the user associated with the current request $wgLang Language object selected by user preferences $wgContLang Language object associated with the wiki being viewed $wgParser Parser object Parser extensions register their hooks here $wgRequest WebRequest object
Definition globals.txt:62
const CACHE_ANYTHING
Definition Defines.php:101
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
Definition hooks.txt:2278
see documentation in includes Linker php for Linker::makeImageLink or false for current used if you return false $parser
Definition hooks.txt:1873
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. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. '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 '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 '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 '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. '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 IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() '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 Sanitizer::validateEmail(), 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. 'LanguageGetMagic':DEPRECATED since 1.16! 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) '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 '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:Array with elements of the form "language:title" in the order that they will be output. & $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. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. 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:2042
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 $image
Definition hooks.txt:925
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition hooks.txt:2050
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition hooks.txt:2885
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 $out
Definition hooks.txt:894
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:302
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:2060
this hook is for auditing only $response
Definition hooks.txt:813
the value of this variable comes from LanguageConverter indexed by page_id indexed by prefixed DB keys on which the links will be shown can modify can modify can modify this should be populated with an alert message to that effect to be fed to an HTMLForm object and populate $result with the reason in the form of[messagename, param1, param2,...] or a MessageSpecifier error messages should be plain text with no special etc to show that they re errors
Definition hooks.txt:1789
null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition hooks.txt:1656
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 local account $user
Definition hooks.txt:247
returning false will NOT prevent logging $e
Definition hooks.txt:2226
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37
Interface for configuration instances.
Definition Config.php:28
$debug
Definition mcc.php:31
$cache
Definition mcc.php:33
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
$source
$content
const DB_REPLICA
Definition defines.php:25
if(!isset( $args[0])) $lang
$header