2010-09-04 04:00:09 +00:00
|
|
|
<?php
|
|
|
|
|
/**
|
2012-04-30 07:16:10 +00:00
|
|
|
* Base class for resource loading system.
|
|
|
|
|
*
|
2010-09-04 04:00:09 +00:00
|
|
|
* This program is free software; you can redistribute it and/or modify
|
|
|
|
|
* it under the terms of the GNU General Public License as published by
|
|
|
|
|
* the Free Software Foundation; either version 2 of the License, or
|
|
|
|
|
* (at your option) any later version.
|
|
|
|
|
*
|
|
|
|
|
* This program is distributed in the hope that it will be useful,
|
|
|
|
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
|
* GNU General Public License for more details.
|
|
|
|
|
*
|
|
|
|
|
* You should have received a copy of the GNU General Public License along
|
|
|
|
|
* with this program; if not, write to the Free Software Foundation, Inc.,
|
|
|
|
|
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
|
|
|
|
* http://www.gnu.org/copyleft/gpl.html
|
|
|
|
|
*
|
2010-09-05 13:31:34 +00:00
|
|
|
* @file
|
2010-09-04 04:00:09 +00:00
|
|
|
* @author Roan Kattouw
|
|
|
|
|
* @author Trevor Parscal
|
|
|
|
|
*/
|
|
|
|
|
|
2016-11-22 23:39:22 +00:00
|
|
|
use MediaWiki\MediaWikiServices;
|
2015-06-04 03:52:45 +00:00
|
|
|
use Psr\Log\LoggerAwareInterface;
|
|
|
|
|
use Psr\Log\LoggerInterface;
|
|
|
|
|
use Psr\Log\NullLogger;
|
2015-07-31 00:13:04 +00:00
|
|
|
use WrappedString\WrappedString;
|
2017-02-24 16:17:16 +00:00
|
|
|
use Wikimedia\Rdbms\DBConnectionError;
|
2015-06-04 03:52:45 +00:00
|
|
|
|
2010-09-05 13:31:34 +00:00
|
|
|
/**
|
2010-10-19 20:45:02 +00:00
|
|
|
* Dynamic JavaScript and CSS resource loading system.
|
|
|
|
|
*
|
2014-03-07 19:13:43 +00:00
|
|
|
* Most of the documentation is on the MediaWiki documentation wiki starting at:
|
2014-03-07 16:50:57 +00:00
|
|
|
* https://www.mediawiki.org/wiki/ResourceLoader
|
2010-09-04 04:00:09 +00:00
|
|
|
*/
|
2015-06-04 03:52:45 +00:00
|
|
|
class ResourceLoader implements LoggerAwareInterface {
|
2014-05-10 08:39:37 +00:00
|
|
|
/** @var int */
|
2011-11-23 00:22:46 +00:00
|
|
|
protected static $filterCacheVersion = 7;
|
2014-05-10 08:39:37 +00:00
|
|
|
|
2014-04-30 21:06:51 +00:00
|
|
|
/** @var bool */
|
|
|
|
|
protected static $debugMode = null;
|
|
|
|
|
|
2015-02-01 21:37:34 +00:00
|
|
|
/** @var array */
|
2016-01-08 22:09:36 +00:00
|
|
|
private $lessVars = null;
|
2015-02-01 21:37:34 +00:00
|
|
|
|
2014-08-30 16:51:42 +00:00
|
|
|
/**
|
|
|
|
|
* Module name/ResourceLoaderModule object pairs
|
|
|
|
|
* @var array
|
|
|
|
|
*/
|
2016-02-17 09:09:32 +00:00
|
|
|
protected $modules = [];
|
2011-07-26 21:10:34 +00:00
|
|
|
|
2014-08-30 16:51:42 +00:00
|
|
|
/**
|
|
|
|
|
* Associative array mapping module name to info associative array
|
|
|
|
|
* @var array
|
|
|
|
|
*/
|
2016-02-17 09:09:32 +00:00
|
|
|
protected $moduleInfos = [];
|
2012-10-19 20:03:05 +00:00
|
|
|
|
2014-08-07 10:25:56 +00:00
|
|
|
/** @var Config $config */
|
2016-08-25 01:50:30 +00:00
|
|
|
protected $config;
|
2014-08-07 10:25:56 +00:00
|
|
|
|
2014-03-07 19:13:43 +00:00
|
|
|
/**
|
2014-08-30 16:51:42 +00:00
|
|
|
* Associative array mapping framework ids to a list of names of test suite modules
|
2016-08-13 01:10:40 +00:00
|
|
|
* like [ 'qunit' => [ 'mediawiki.tests.qunit.suites', 'ext.foo.tests', ... ], ... ]
|
2014-08-30 16:51:42 +00:00
|
|
|
* @var array
|
2014-03-07 19:13:43 +00:00
|
|
|
*/
|
2016-02-17 09:09:32 +00:00
|
|
|
protected $testModuleNames = [];
|
2010-09-04 12:53:01 +00:00
|
|
|
|
2014-08-30 16:51:42 +00:00
|
|
|
/**
|
2016-08-13 01:10:40 +00:00
|
|
|
* E.g. [ 'source-id' => 'http://.../load.php' ]
|
2014-08-30 16:51:42 +00:00
|
|
|
* @var array
|
|
|
|
|
*/
|
2016-02-17 09:09:32 +00:00
|
|
|
protected $sources = [];
|
2011-07-26 21:10:34 +00:00
|
|
|
|
2014-11-11 20:00:17 +00:00
|
|
|
/**
|
|
|
|
|
* Errors accumulated during current respond() call.
|
|
|
|
|
* @var array
|
|
|
|
|
*/
|
2016-02-17 09:09:32 +00:00
|
|
|
protected $errors = [];
|
2013-07-01 18:01:11 +00:00
|
|
|
|
resourceloader: Add support for modules sending preload headers
ResourceLoaderModule objects gain a new method getPreloadLinks() which
returns an array with the meta data required to build a Link rel=preload
header according to the current draft for W3C Preload.
<https://w3c.github.io/preload/>
Another implementation of this is already in use in OutputPage for
preloading the logo image.
This array is formatted by the ResourceLoaderModule::getHeaders method,
which is implemented as "final" at this time, thus restricting use to
the Link rel=preload header.
Headers are exposed and process-cached, like all other content
(scripts, styles, etc.), through ResourceLoaderModule::getModuleContent,
and aggregated by ResoureLoader::makeModuleResponse.
I had hoped for the getPreloadLinks to be stateless (not vary on $context).
Whether something should be preloaded and what, should not vary on the
skin or language. However, while that conceptually holds true, the exact
url for any given resource may still vary. Even the main use case for this
feature (T164299, preloading base modules request) require $context to pass
down skin and lang to the load.php url.
Add full test coverage and example documentation.
Bug: T164299
Change-Id: I2bfe0796ceaa0c82579c501f5b10e931f2175681
2017-07-18 02:36:01 +00:00
|
|
|
/**
|
|
|
|
|
* List of extra HTTP response headers provided by loaded modules.
|
|
|
|
|
*
|
|
|
|
|
* Populated by makeModuleResponse().
|
|
|
|
|
*
|
|
|
|
|
* @var array
|
|
|
|
|
*/
|
|
|
|
|
protected $extraHeaders = [];
|
|
|
|
|
|
2015-03-29 04:24:31 +00:00
|
|
|
/**
|
|
|
|
|
* @var MessageBlobStore
|
|
|
|
|
*/
|
|
|
|
|
protected $blobStore;
|
|
|
|
|
|
2015-06-04 03:52:45 +00:00
|
|
|
/**
|
|
|
|
|
* @var LoggerInterface
|
|
|
|
|
*/
|
|
|
|
|
private $logger;
|
|
|
|
|
|
2015-10-01 18:05:08 +00:00
|
|
|
/** @var string JavaScript / CSS pragma to disable minification. **/
|
2016-02-18 16:33:15 +00:00
|
|
|
const FILTER_NOMIN = '/*@nomin*/';
|
2015-10-01 18:05:08 +00:00
|
|
|
|
2010-09-29 19:04:04 +00:00
|
|
|
/**
|
2014-03-07 16:50:57 +00:00
|
|
|
* Load information stored in the database about modules.
|
2011-06-17 16:05:05 +00:00
|
|
|
*
|
|
|
|
|
* This method grabs modules dependencies from the database and updates modules
|
2010-11-03 07:58:03 +00:00
|
|
|
* objects.
|
2011-06-17 16:05:05 +00:00
|
|
|
*
|
|
|
|
|
* This is not inside the module code because it is much faster to
|
|
|
|
|
* request all of the information at once than it is to have each module
|
2010-11-19 06:52:38 +00:00
|
|
|
* requests its own information. This sacrifice of modularity yields a substantial
|
2010-10-20 00:22:25 +00:00
|
|
|
* performance improvement.
|
2011-06-17 16:05:05 +00:00
|
|
|
*
|
2015-11-13 00:04:12 +00:00
|
|
|
* @param array $moduleNames List of module names to preload information for
|
2014-03-07 16:50:57 +00:00
|
|
|
* @param ResourceLoaderContext $context Context to load the information within
|
2010-09-24 18:49:19 +00:00
|
|
|
*/
|
2015-11-13 00:04:12 +00:00
|
|
|
public function preloadModuleInfo( array $moduleNames, ResourceLoaderContext $context ) {
|
|
|
|
|
if ( !$moduleNames ) {
|
2013-10-17 10:33:26 +00:00
|
|
|
// Or else Database*::select() will explode, plus it's cheaper!
|
|
|
|
|
return;
|
2010-10-02 10:18:48 +00:00
|
|
|
}
|
2016-09-05 19:55:19 +00:00
|
|
|
$dbr = wfGetDB( DB_REPLICA );
|
2010-09-23 21:23:51 +00:00
|
|
|
$skin = $context->getSkin();
|
|
|
|
|
$lang = $context->getLanguage();
|
2011-06-17 16:05:05 +00:00
|
|
|
|
2015-09-30 00:15:57 +00:00
|
|
|
// Batched version of ResourceLoaderModule::getFileDependencies
|
|
|
|
|
$vary = "$skin|$lang";
|
2016-02-17 09:09:32 +00:00
|
|
|
$res = $dbr->select( 'module_deps', [ 'md_module', 'md_deps' ], [
|
2015-11-13 00:04:12 +00:00
|
|
|
'md_module' => $moduleNames,
|
2015-09-30 00:15:57 +00:00
|
|
|
'md_skin' => $vary,
|
2016-02-17 09:09:32 +00:00
|
|
|
], __METHOD__
|
2010-09-23 21:23:51 +00:00
|
|
|
);
|
2015-11-13 00:04:12 +00:00
|
|
|
|
|
|
|
|
// Prime in-object cache for file dependencies
|
2016-02-17 09:09:32 +00:00
|
|
|
$modulesWithDeps = [];
|
2010-09-23 21:23:51 +00:00
|
|
|
foreach ( $res as $row ) {
|
2014-04-03 23:09:09 +00:00
|
|
|
$module = $this->getModule( $row->md_module );
|
|
|
|
|
if ( $module ) {
|
2015-10-02 00:36:38 +00:00
|
|
|
$module->setFileDependencies( $context, ResourceLoaderModule::expandRelativePaths(
|
2015-10-02 00:14:19 +00:00
|
|
|
FormatJson::decode( $row->md_deps, true )
|
|
|
|
|
) );
|
2014-04-03 23:09:09 +00:00
|
|
|
$modulesWithDeps[] = $row->md_module;
|
|
|
|
|
}
|
2010-09-23 21:23:51 +00:00
|
|
|
}
|
2010-10-19 20:45:02 +00:00
|
|
|
// Register the absence of a dependency row too
|
2015-11-13 00:04:12 +00:00
|
|
|
foreach ( array_diff( $moduleNames, $modulesWithDeps ) as $name ) {
|
2014-04-03 23:09:09 +00:00
|
|
|
$module = $this->getModule( $name );
|
|
|
|
|
if ( $module ) {
|
2016-02-17 09:09:32 +00:00
|
|
|
$this->getModule( $name )->setFileDependencies( $context, [] );
|
2014-04-03 23:09:09 +00:00
|
|
|
}
|
2010-09-23 21:23:51 +00:00
|
|
|
}
|
2011-06-17 16:05:05 +00:00
|
|
|
|
2016-09-08 03:26:48 +00:00
|
|
|
// Batched version of ResourceLoaderWikiModule::getTitleInfo
|
|
|
|
|
ResourceLoaderWikiModule::preloadTitleInfo( $context, $dbr, $moduleNames );
|
|
|
|
|
|
2015-11-13 00:04:12 +00:00
|
|
|
// Prime in-object cache for message blobs for modules with messages
|
2016-02-17 09:09:32 +00:00
|
|
|
$modules = [];
|
2015-11-13 00:04:12 +00:00
|
|
|
foreach ( $moduleNames as $name ) {
|
2014-04-03 23:09:09 +00:00
|
|
|
$module = $this->getModule( $name );
|
2015-11-13 00:04:12 +00:00
|
|
|
if ( $module && $module->getMessages() ) {
|
|
|
|
|
$modules[$name] = $module;
|
2010-09-23 21:23:51 +00:00
|
|
|
}
|
2011-06-17 16:05:05 +00:00
|
|
|
}
|
2015-11-13 00:04:12 +00:00
|
|
|
$store = $this->getMessageBlobStore();
|
|
|
|
|
$blobs = $store->getBlobs( $modules, $lang );
|
|
|
|
|
foreach ( $blobs as $name => $blob ) {
|
|
|
|
|
$modules[$name]->setMessageBlob( $blob, $lang );
|
2010-09-23 21:23:51 +00:00
|
|
|
}
|
|
|
|
|
}
|
2010-09-15 18:27:47 +00:00
|
|
|
|
2010-09-04 04:00:09 +00:00
|
|
|
/**
|
2014-03-07 16:50:57 +00:00
|
|
|
* Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
|
2011-06-17 16:05:05 +00:00
|
|
|
*
|
2010-10-20 14:58:35 +00:00
|
|
|
* Available filters are:
|
2014-03-07 16:50:57 +00:00
|
|
|
*
|
|
|
|
|
* - minify-js \see JavaScriptMinifier::minify
|
|
|
|
|
* - minify-css \see CSSMin::minify
|
2011-06-17 16:05:05 +00:00
|
|
|
*
|
|
|
|
|
* If $data is empty, only contains whitespace or the filter was unknown,
|
2010-11-03 07:58:03 +00:00
|
|
|
* $data is returned unmodified.
|
2011-06-17 16:05:05 +00:00
|
|
|
*
|
2013-03-11 17:15:01 +00:00
|
|
|
* @param string $filter Name of filter to run
|
|
|
|
|
* @param string $data Text to filter, such as JavaScript or CSS text
|
2015-10-01 18:05:08 +00:00
|
|
|
* @param array $options Keys:
|
2015-05-14 01:31:42 +00:00
|
|
|
* - (bool) cache: Whether to allow caching this data. Default: true.
|
2014-03-07 16:50:57 +00:00
|
|
|
* @return string Filtered data, or a comment containing an error message
|
2010-09-04 04:00:09 +00:00
|
|
|
*/
|
2016-02-17 10:31:52 +00:00
|
|
|
public static function filter( $filter, $data, array $options = [] ) {
|
2017-07-23 01:24:09 +00:00
|
|
|
if ( strpos( $data, self::FILTER_NOMIN ) !== false ) {
|
2010-09-04 04:00:09 +00:00
|
|
|
return $data;
|
|
|
|
|
}
|
2010-09-04 12:53:01 +00:00
|
|
|
|
2015-10-01 18:05:08 +00:00
|
|
|
if ( isset( $options['cache'] ) && $options['cache'] === false ) {
|
|
|
|
|
return self::applyFilter( $filter, $data );
|
2010-09-04 04:00:09 +00:00
|
|
|
}
|
2010-09-04 12:53:01 +00:00
|
|
|
|
2017-03-17 10:57:37 +00:00
|
|
|
$stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
|
2015-10-31 18:42:48 +00:00
|
|
|
$cache = ObjectCache::getLocalServerInstance( CACHE_ANYTHING );
|
2015-10-01 18:05:08 +00:00
|
|
|
|
2015-10-19 17:00:50 +00:00
|
|
|
$key = $cache->makeGlobalKey(
|
2015-10-01 18:05:08 +00:00
|
|
|
'resourceloader',
|
|
|
|
|
'filter',
|
|
|
|
|
$filter,
|
|
|
|
|
self::$filterCacheVersion, md5( $data )
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
$result = $cache->get( $key );
|
|
|
|
|
if ( $result === false ) {
|
|
|
|
|
$stats->increment( "resourceloader_cache.$filter.miss" );
|
|
|
|
|
$result = self::applyFilter( $filter, $data );
|
|
|
|
|
$cache->set( $key, $result, 24 * 3600 );
|
2015-05-14 01:31:42 +00:00
|
|
|
} else {
|
2015-10-01 18:05:08 +00:00
|
|
|
$stats->increment( "resourceloader_cache.$filter.hit" );
|
|
|
|
|
}
|
|
|
|
|
if ( $result === null ) {
|
|
|
|
|
// Cached failure
|
|
|
|
|
$result = $data;
|
2015-05-14 01:31:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return $result;
|
|
|
|
|
}
|
|
|
|
|
|
2015-10-01 18:05:08 +00:00
|
|
|
private static function applyFilter( $filter, $data ) {
|
|
|
|
|
$data = trim( $data );
|
|
|
|
|
if ( $data ) {
|
|
|
|
|
try {
|
|
|
|
|
$data = ( $filter === 'minify-css' )
|
|
|
|
|
? CSSMin::minify( $data )
|
|
|
|
|
: JavaScriptMinifier::minify( $data );
|
|
|
|
|
} catch ( Exception $e ) {
|
|
|
|
|
MWExceptionHandler::logException( $e );
|
|
|
|
|
return null;
|
|
|
|
|
}
|
2015-06-26 05:57:17 +00:00
|
|
|
}
|
|
|
|
|
return $data;
|
2010-09-04 04:00:09 +00:00
|
|
|
}
|
2010-09-04 12:53:01 +00:00
|
|
|
|
2010-09-29 19:04:04 +00:00
|
|
|
/* Methods */
|
|
|
|
|
|
|
|
|
|
/**
|
2014-03-07 16:50:57 +00:00
|
|
|
* Register core modules and runs registration hooks.
|
2015-11-10 03:12:24 +00:00
|
|
|
* @param Config $config [optional]
|
|
|
|
|
* @param LoggerInterface $logger [optional]
|
2010-09-29 19:04:04 +00:00
|
|
|
*/
|
2015-06-04 03:52:45 +00:00
|
|
|
public function __construct( Config $config = null, LoggerInterface $logger = null ) {
|
2014-08-07 10:25:56 +00:00
|
|
|
global $IP;
|
2011-06-17 16:05:05 +00:00
|
|
|
|
2015-11-13 00:04:12 +00:00
|
|
|
$this->logger = $logger ?: new NullLogger();
|
2014-08-07 10:25:56 +00:00
|
|
|
|
2015-06-04 03:52:45 +00:00
|
|
|
if ( !$config ) {
|
2015-06-04 03:53:23 +00:00
|
|
|
$this->logger->debug( __METHOD__ . ' was called without providing a Config instance' );
|
2016-11-22 23:39:22 +00:00
|
|
|
$config = MediaWikiServices::getInstance()->getMainConfig();
|
2015-06-04 03:52:45 +00:00
|
|
|
}
|
2014-08-07 10:25:56 +00:00
|
|
|
$this->config = $config;
|
|
|
|
|
|
2011-07-26 21:10:34 +00:00
|
|
|
// Add 'local' source first
|
resourceloader: Move queue formatting out of OutputPage
HTML formatting of the queue was distributed over several OutputPage methods.
Each method demanding a snippet of HTML by calling makeResourceLoaderLink()
with a limited amount of information. As such, makeResourceLoaderLink() was
unable to provide the client with the proper state information.
Centralising it also allows it to better reduce duplication in HTML output
and maintain a more accurate state.
Problems fixed by centralising:
1. The 'user' module is special (due to per-user 'version' and 'user' params).
It is manually requested via script-src. To avoid a separate (and wrong)
request from something that requires it, we set state=loading directly.
However, because the module is in the bottom, the old HTML formatter could
only put state=loading in the bottom also. This sometimes caused a wrong
request to be fired for modules=user if something in the top queue
triggered a requirement for it.
2. Since a464d1d4 (T87871) we track states of page-style modules, with purpose
of allowing dependencies on style modules without risking duplicate loading
on pages where the styles are loaded already. This didn't work, because the
state information about page-style modules is output near the stylesheet,
which is after the script tag with mw.loader.load(). That runs first, and
mw.loader would still make a duplicate request before it learns the state.
Changes:
* Document reasons for style/script tag order in getHeadHtml (per 09537e83).
* Pass $type from getModuleStyles() to getAllowedModules(). This wasn't needed
before since a duplicate check in makeResourceLoaderLink() verified the
origin a second time.
* Declare explicit position 'top' on 'user.options' and 'user.tokens' module.
Previously, OutputPage hardcoded them in the top. The new formatter doesn't.
* Remove getHeadScripts().
* Remove getInlineHeadScripts().
* Remove getExternalHeadScripts().
* Remove buildCssLinks().
* Remove getScriptsForBottomQueue().
* Change where Skin::setupSkinUserCss() is called. This methods lets the skin
add modules to the queue. Previously it was called from buildCssLinks(),
via headElement(), via prepareQuickTemplate(), via OutputPage::output().
It's now in OutputPage::output() directly (slightly earlier). This is needed
because prepareQuickTemplate() calls bottomScripts() before headElement().
And bottomScript() would lazy-initialise the queue and lock it before
setupSkinUserCss() is called from headElement().
This makes execution order more predictable instead of being dependent on
the arbitrary order of data extraction in prepareQuickTemplate (which varies
from one skin to another).
* Compute isUserModulePreview() and isKnownEmpty() for the 'user' module early
on so. This avoids wrongful loading and fixes problem 1.
Effective changes in output:
* mw.loader.state() is now before mw.loader.load(). This fixes problem 2.
* mw.loader.state() now sets 'user.options' and 'user.tokens' to "loading".
* mw.loader.state() now sets 'user' (as "loading" or "ready"). Fixes problem 1.
* The <script async src> tag for 'startup' changed position (slightly).
Previously it was after all inline scripts and stylesheets. It's still after
all inline scripts and after most stylesheets, but before any user styles.
Since the queue is now formatted outside OutputPage, it can't inject the
meta-ResourceLoaderDynamicStyles tag and user-stylesheet hack in the middle
of existing output. This shouldn't have any noticable impact.
Bug: T87871
Change-Id: I605b8cd1e1fc009b4662a0edbc54d09dd65ee1df
2016-07-15 14:13:09 +00:00
|
|
|
$this->addSource( 'local', $config->get( 'LoadScript' ) );
|
2011-07-26 21:10:34 +00:00
|
|
|
|
|
|
|
|
// Add other sources
|
2014-08-07 10:25:56 +00:00
|
|
|
$this->addSource( $config->get( 'ResourceLoaderSources' ) );
|
2011-07-26 21:10:34 +00:00
|
|
|
|
2010-09-29 19:04:04 +00:00
|
|
|
// Register core modules
|
2013-05-17 00:16:59 +00:00
|
|
|
$this->register( include "$IP/resources/Resources.php" );
|
2010-09-29 19:04:04 +00:00
|
|
|
// Register extension modules
|
2014-08-07 10:25:56 +00:00
|
|
|
$this->register( $config->get( 'ResourceModules' ) );
|
2017-02-01 04:01:54 +00:00
|
|
|
|
|
|
|
|
// Avoid PHP 7.1 warning from passing $this by reference
|
|
|
|
|
$rl = $this;
|
|
|
|
|
Hooks::run( 'ResourceLoaderRegisterModules', [ &$rl ] );
|
2011-06-17 16:05:05 +00:00
|
|
|
|
2014-08-07 10:25:56 +00:00
|
|
|
if ( $config->get( 'EnableJavaScriptTest' ) === true ) {
|
2012-01-03 18:33:26 +00:00
|
|
|
$this->registerTestModules();
|
|
|
|
|
}
|
|
|
|
|
|
2015-11-13 00:04:12 +00:00
|
|
|
$this->setMessageBlobStore( new MessageBlobStore( $this, $this->logger ) );
|
2010-09-29 19:04:04 +00:00
|
|
|
}
|
2010-09-04 12:53:01 +00:00
|
|
|
|
2014-08-07 10:25:56 +00:00
|
|
|
/**
|
|
|
|
|
* @return Config
|
|
|
|
|
*/
|
|
|
|
|
public function getConfig() {
|
|
|
|
|
return $this->config;
|
|
|
|
|
}
|
|
|
|
|
|
2015-11-10 03:12:24 +00:00
|
|
|
/**
|
|
|
|
|
* @since 1.26
|
|
|
|
|
* @param LoggerInterface $logger
|
|
|
|
|
*/
|
2015-06-04 03:52:45 +00:00
|
|
|
public function setLogger( LoggerInterface $logger ) {
|
|
|
|
|
$this->logger = $logger;
|
|
|
|
|
}
|
|
|
|
|
|
2015-11-10 03:12:24 +00:00
|
|
|
/**
|
|
|
|
|
* @since 1.27
|
|
|
|
|
* @return LoggerInterface
|
|
|
|
|
*/
|
|
|
|
|
public function getLogger() {
|
|
|
|
|
return $this->logger;
|
|
|
|
|
}
|
|
|
|
|
|
2015-03-29 04:24:31 +00:00
|
|
|
/**
|
2015-05-14 19:05:47 +00:00
|
|
|
* @since 1.26
|
|
|
|
|
* @return MessageBlobStore
|
|
|
|
|
*/
|
|
|
|
|
public function getMessageBlobStore() {
|
|
|
|
|
return $this->blobStore;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
2015-03-29 04:24:31 +00:00
|
|
|
* @since 1.25
|
2015-05-14 19:05:47 +00:00
|
|
|
* @param MessageBlobStore $blobStore
|
2015-03-29 04:24:31 +00:00
|
|
|
*/
|
|
|
|
|
public function setMessageBlobStore( MessageBlobStore $blobStore ) {
|
|
|
|
|
$this->blobStore = $blobStore;
|
|
|
|
|
}
|
|
|
|
|
|
2010-09-04 04:00:09 +00:00
|
|
|
/**
|
2014-03-07 16:50:57 +00:00
|
|
|
* Register a module with the ResourceLoader system.
|
2011-06-17 16:05:05 +00:00
|
|
|
*
|
2014-03-07 16:50:57 +00:00
|
|
|
* @param mixed $name Name of module as a string or List of name/object pairs as an array
|
2013-03-11 17:15:01 +00:00
|
|
|
* @param array $info Module info array. For backwards compatibility with 1.17alpha,
|
2011-06-17 16:05:05 +00:00
|
|
|
* this may also be a ResourceLoaderModule object. Optional when using
|
* Made Resources.php return a pure-data array instead of an ugly mix of data and code. This allows the class code to be lazy-loaded with the autoloader, for a performance advantage especially on non-APC installs. And using the convention where if the class is omitted, ResourceLoaderFileModule is assumed, the registration code becomes shorter and simpler.
* Modified ResourceLoader to lazy-initialise module objects, for a further performance advantage.
* Deleted ResourceLoader::getModules(), provided getModuleNames() instead. Although the startup module needs this functionality, it's slow to generate, so to avoid misuse, it's better to provide a foolproof fast interface and let the startup module do the slow thing itself.
* Modified ResourceLoader::register() to optionally accept an info array instead of an object.
* Added $wgResourceModules, allowing extensions to efficiently define their own resource loader modules. The trouble with hooks is that they contain code, and code is slow. We've been through all this before with i18n. Hooks are useful as a performance tool only if you call them very rarely.
* Moved ResourceLoader settings to their own section in DefaultSettings.php
* Added options to ResourceLoaderFileModule equivalent to the $localBasePath and $remoteBasePath parameters, to allow it to be instantiated via the new array style. Also added remoteExtPath, which allows modules to be registered before $wgExtensionAssetsPath is known.
* Added OutputPage::getResourceLoader(), mostly for debugging.
* The time saving at the moment is about 5ms per request with no extensions, which is significant already with 6 load.php requests for a cold cache page view. This is a much more scalable interface; the relative saving will grow as more extensions are added which use this interface, especially for non-APC installs.
Although the interface is backwards compatible, extension updates will follow in a subsequent commit.
2010-11-19 10:41:06 +00:00
|
|
|
* multiple-registration calling style.
|
2014-04-20 21:33:05 +00:00
|
|
|
* @throws MWException If a duplicate module registration is attempted
|
|
|
|
|
* @throws MWException If a module name contains illegal characters (pipes or commas)
|
|
|
|
|
* @throws MWException If something other than a ResourceLoaderModule is being registered
|
|
|
|
|
* @return bool False if there were any errors, in which case one or more modules were
|
2014-03-07 16:50:57 +00:00
|
|
|
* not registered
|
2010-09-04 04:00:09 +00:00
|
|
|
*/
|
* Made Resources.php return a pure-data array instead of an ugly mix of data and code. This allows the class code to be lazy-loaded with the autoloader, for a performance advantage especially on non-APC installs. And using the convention where if the class is omitted, ResourceLoaderFileModule is assumed, the registration code becomes shorter and simpler.
* Modified ResourceLoader to lazy-initialise module objects, for a further performance advantage.
* Deleted ResourceLoader::getModules(), provided getModuleNames() instead. Although the startup module needs this functionality, it's slow to generate, so to avoid misuse, it's better to provide a foolproof fast interface and let the startup module do the slow thing itself.
* Modified ResourceLoader::register() to optionally accept an info array instead of an object.
* Added $wgResourceModules, allowing extensions to efficiently define their own resource loader modules. The trouble with hooks is that they contain code, and code is slow. We've been through all this before with i18n. Hooks are useful as a performance tool only if you call them very rarely.
* Moved ResourceLoader settings to their own section in DefaultSettings.php
* Added options to ResourceLoaderFileModule equivalent to the $localBasePath and $remoteBasePath parameters, to allow it to be instantiated via the new array style. Also added remoteExtPath, which allows modules to be registered before $wgExtensionAssetsPath is known.
* Added OutputPage::getResourceLoader(), mostly for debugging.
* The time saving at the moment is about 5ms per request with no extensions, which is significant already with 6 load.php requests for a cold cache page view. This is a much more scalable interface; the relative saving will grow as more extensions are added which use this interface, especially for non-APC installs.
Although the interface is backwards compatible, extension updates will follow in a subsequent commit.
2010-11-19 10:41:06 +00:00
|
|
|
public function register( $name, $info = null ) {
|
2016-06-08 19:57:50 +00:00
|
|
|
$moduleSkinStyles = $this->config->get( 'ResourceModuleSkinStyles' );
|
2010-10-20 00:22:25 +00:00
|
|
|
|
2010-09-04 04:00:09 +00:00
|
|
|
// Allow multiple modules to be registered in one call
|
2016-02-17 09:09:32 +00:00
|
|
|
$registrations = is_array( $name ) ? $name : [ $name => $info ];
|
2011-11-19 16:02:26 +00:00
|
|
|
foreach ( $registrations as $name => $info ) {
|
2015-10-26 18:23:43 +00:00
|
|
|
// Warn on duplicate registrations
|
2011-11-19 16:02:26 +00:00
|
|
|
if ( isset( $this->moduleInfos[$name] ) ) {
|
|
|
|
|
// A module has already been registered by this name
|
2015-10-27 07:44:47 +00:00
|
|
|
$this->logger->warning(
|
|
|
|
|
'ResourceLoader duplicate registration warning. ' .
|
|
|
|
|
'Another module has already been registered as ' . $name
|
|
|
|
|
);
|
2010-09-04 04:00:09 +00:00
|
|
|
}
|
2011-06-17 16:05:05 +00:00
|
|
|
|
2012-05-09 21:10:33 +00:00
|
|
|
// Check $name for validity
|
|
|
|
|
if ( !self::isValidModuleName( $name ) ) {
|
2014-05-10 08:39:37 +00:00
|
|
|
throw new MWException( "ResourceLoader module name '$name' is invalid, "
|
|
|
|
|
. "see ResourceLoader::isValidModuleName()" );
|
* Made Resources.php return a pure-data array instead of an ugly mix of data and code. This allows the class code to be lazy-loaded with the autoloader, for a performance advantage especially on non-APC installs. And using the convention where if the class is omitted, ResourceLoaderFileModule is assumed, the registration code becomes shorter and simpler.
* Modified ResourceLoader to lazy-initialise module objects, for a further performance advantage.
* Deleted ResourceLoader::getModules(), provided getModuleNames() instead. Although the startup module needs this functionality, it's slow to generate, so to avoid misuse, it's better to provide a foolproof fast interface and let the startup module do the slow thing itself.
* Modified ResourceLoader::register() to optionally accept an info array instead of an object.
* Added $wgResourceModules, allowing extensions to efficiently define their own resource loader modules. The trouble with hooks is that they contain code, and code is slow. We've been through all this before with i18n. Hooks are useful as a performance tool only if you call them very rarely.
* Moved ResourceLoader settings to their own section in DefaultSettings.php
* Added options to ResourceLoaderFileModule equivalent to the $localBasePath and $remoteBasePath parameters, to allow it to be instantiated via the new array style. Also added remoteExtPath, which allows modules to be registered before $wgExtensionAssetsPath is known.
* Added OutputPage::getResourceLoader(), mostly for debugging.
* The time saving at the moment is about 5ms per request with no extensions, which is significant already with 6 load.php requests for a cold cache page view. This is a much more scalable interface; the relative saving will grow as more extensions are added which use this interface, especially for non-APC installs.
Although the interface is backwards compatible, extension updates will follow in a subsequent commit.
2010-11-19 10:41:06 +00:00
|
|
|
}
|
|
|
|
|
|
2011-11-19 16:02:26 +00:00
|
|
|
// Attach module
|
2014-04-03 23:09:09 +00:00
|
|
|
if ( $info instanceof ResourceLoaderModule ) {
|
2016-02-17 09:09:32 +00:00
|
|
|
$this->moduleInfos[$name] = [ 'object' => $info ];
|
2011-11-19 16:02:26 +00:00
|
|
|
$info->setName( $name );
|
|
|
|
|
$this->modules[$name] = $info;
|
2014-04-03 23:09:09 +00:00
|
|
|
} elseif ( is_array( $info ) ) {
|
2011-11-19 16:02:26 +00:00
|
|
|
// New calling convention
|
|
|
|
|
$this->moduleInfos[$name] = $info;
|
2014-04-03 23:09:09 +00:00
|
|
|
} else {
|
|
|
|
|
throw new MWException(
|
|
|
|
|
'ResourceLoader module info type error for module \'' . $name .
|
|
|
|
|
'\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
|
|
|
|
|
);
|
2011-11-19 16:02:26 +00:00
|
|
|
}
|
2014-06-26 14:29:31 +00:00
|
|
|
|
|
|
|
|
// Last-minute changes
|
|
|
|
|
|
|
|
|
|
// Apply custom skin-defined styles to existing modules.
|
|
|
|
|
if ( $this->isFileModule( $name ) ) {
|
2016-06-08 19:57:50 +00:00
|
|
|
foreach ( $moduleSkinStyles as $skinName => $skinStyles ) {
|
2014-06-26 14:29:31 +00:00
|
|
|
// If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
|
|
|
|
|
if ( isset( $this->moduleInfos[$name]['skinStyles'][$skinName] ) ) {
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// If $name is preceded with a '+', the defined style files will be added to 'default'
|
|
|
|
|
// skinStyles, otherwise 'default' will be ignored as it normally would be.
|
2014-08-04 09:51:22 +00:00
|
|
|
if ( isset( $skinStyles[$name] ) ) {
|
|
|
|
|
$paths = (array)$skinStyles[$name];
|
2016-02-17 09:09:32 +00:00
|
|
|
$styleFiles = [];
|
2014-08-04 09:51:22 +00:00
|
|
|
} elseif ( isset( $skinStyles['+' . $name] ) ) {
|
|
|
|
|
$paths = (array)$skinStyles['+' . $name];
|
2014-06-26 14:29:31 +00:00
|
|
|
$styleFiles = isset( $this->moduleInfos[$name]['skinStyles']['default'] ) ?
|
2015-05-07 13:51:09 +00:00
|
|
|
(array)$this->moduleInfos[$name]['skinStyles']['default'] :
|
2016-02-17 09:09:32 +00:00
|
|
|
[];
|
2014-06-26 14:29:31 +00:00
|
|
|
} else {
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Add new file paths, remapping them to refer to our directories and not use settings
|
2015-04-06 22:31:31 +00:00
|
|
|
// from the module we're modifying, which come from the base definition.
|
2014-06-26 14:29:31 +00:00
|
|
|
list( $localBasePath, $remoteBasePath ) =
|
|
|
|
|
ResourceLoaderFileModule::extractBasePaths( $skinStyles );
|
|
|
|
|
|
|
|
|
|
foreach ( $paths as $path ) {
|
|
|
|
|
$styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$this->moduleInfos[$name]['skinStyles'][$skinName] = $styleFiles;
|
|
|
|
|
}
|
|
|
|
|
}
|
2010-09-29 23:57:53 +00:00
|
|
|
}
|
2010-09-04 04:00:09 +00:00
|
|
|
}
|
2010-09-04 12:53:01 +00:00
|
|
|
|
2012-01-03 18:33:26 +00:00
|
|
|
public function registerTestModules() {
|
2014-08-07 10:25:56 +00:00
|
|
|
global $IP;
|
2012-01-03 18:33:26 +00:00
|
|
|
|
2014-08-07 10:25:56 +00:00
|
|
|
if ( $this->config->get( 'EnableJavaScriptTest' ) !== true ) {
|
2014-05-10 08:39:37 +00:00
|
|
|
throw new MWException( 'Attempt to register JavaScript test modules '
|
|
|
|
|
. 'but <code>$wgEnableJavaScriptTest</code> is false. '
|
|
|
|
|
. 'Edit your <code>LocalSettings.php</code> to enable it.' );
|
2012-01-03 18:33:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Get core test suites
|
2016-02-17 09:09:32 +00:00
|
|
|
$testModules = [];
|
|
|
|
|
$testModules['qunit'] = [];
|
2012-01-03 18:33:26 +00:00
|
|
|
// Get other test suites (e.g. from extensions)
|
2017-02-01 04:01:54 +00:00
|
|
|
// Avoid PHP 7.1 warning from passing $this by reference
|
|
|
|
|
$rl = $this;
|
|
|
|
|
Hooks::run( 'ResourceLoaderTestModules', [ &$testModules, &$rl ] );
|
2012-01-03 18:33:26 +00:00
|
|
|
|
|
|
|
|
// Add the testrunner (which configures QUnit) to the dependencies.
|
|
|
|
|
// Since it must be ready before any of the test suites are executed.
|
2013-04-17 14:52:47 +00:00
|
|
|
foreach ( $testModules['qunit'] as &$module ) {
|
2013-04-02 17:59:07 +00:00
|
|
|
// Make sure all test modules are top-loading so that when QUnit starts
|
|
|
|
|
// on document-ready, it will run once and finish. If some tests arrive
|
|
|
|
|
// later (possibly after QUnit has already finished) they will be ignored.
|
2013-04-02 20:31:20 +00:00
|
|
|
$module['position'] = 'top';
|
2014-02-05 05:17:48 +00:00
|
|
|
$module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
|
2012-01-03 18:33:26 +00:00
|
|
|
}
|
|
|
|
|
|
2014-05-10 08:39:37 +00:00
|
|
|
$testModules['qunit'] =
|
|
|
|
|
( include "$IP/tests/qunit/QUnitTestResources.php" ) + $testModules['qunit'];
|
2014-02-05 05:17:48 +00:00
|
|
|
|
2013-04-17 14:52:47 +00:00
|
|
|
foreach ( $testModules as $id => $names ) {
|
2012-01-03 18:33:26 +00:00
|
|
|
// Register test modules
|
|
|
|
|
$this->register( $testModules[$id] );
|
|
|
|
|
|
|
|
|
|
// Keep track of their names so that they can be loaded together
|
|
|
|
|
$this->testModuleNames[$id] = array_keys( $testModules[$id] );
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2011-07-26 21:10:34 +00:00
|
|
|
/**
|
|
|
|
|
* Add a foreign source of modules.
|
2011-10-14 08:06:54 +00:00
|
|
|
*
|
2015-11-20 00:48:01 +00:00
|
|
|
* Source IDs are typically the same as the Wiki ID or database name (e.g. lowercase a-z).
|
|
|
|
|
*
|
2016-08-13 01:10:40 +00:00
|
|
|
* @param array|string $id Source ID (string), or [ id1 => loadUrl, id2 => loadUrl, ... ]
|
2014-08-25 08:02:48 +00:00
|
|
|
* @param string|array $loadUrl load.php url (string), or array with loadUrl key for
|
2014-09-13 06:30:48 +00:00
|
|
|
* backwards-compatibility.
|
2012-10-07 23:35:26 +00:00
|
|
|
* @throws MWException
|
2011-07-26 21:10:34 +00:00
|
|
|
*/
|
2014-08-25 08:02:48 +00:00
|
|
|
public function addSource( $id, $loadUrl = null ) {
|
2011-07-26 21:10:34 +00:00
|
|
|
// Allow multiple sources to be registered in one call
|
|
|
|
|
if ( is_array( $id ) ) {
|
|
|
|
|
foreach ( $id as $key => $value ) {
|
|
|
|
|
$this->addSource( $key, $value );
|
|
|
|
|
}
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Disallow duplicates
|
|
|
|
|
if ( isset( $this->sources[$id] ) ) {
|
|
|
|
|
throw new MWException(
|
|
|
|
|
'ResourceLoader duplicate source addition error. ' .
|
|
|
|
|
'Another source has already been registered as ' . $id
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
2014-09-13 06:30:48 +00:00
|
|
|
// Pre 1.24 backwards-compatibility
|
2014-08-25 08:02:48 +00:00
|
|
|
if ( is_array( $loadUrl ) ) {
|
|
|
|
|
if ( !isset( $loadUrl['loadScript'] ) ) {
|
|
|
|
|
throw new MWException(
|
|
|
|
|
__METHOD__ . ' was passed an array with no "loadScript" key.'
|
|
|
|
|
);
|
2011-07-26 21:10:34 +00:00
|
|
|
}
|
2014-08-25 08:02:48 +00:00
|
|
|
|
|
|
|
|
$loadUrl = $loadUrl['loadScript'];
|
2011-07-26 21:10:34 +00:00
|
|
|
}
|
|
|
|
|
|
2014-08-25 08:02:48 +00:00
|
|
|
$this->sources[$id] = $loadUrl;
|
2011-07-26 21:10:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
2014-03-07 16:50:57 +00:00
|
|
|
* Get a list of module names.
|
2010-09-04 04:00:09 +00:00
|
|
|
*
|
2014-03-07 16:50:57 +00:00
|
|
|
* @return array List of module names
|
2010-09-04 04:00:09 +00:00
|
|
|
*/
|
* Made Resources.php return a pure-data array instead of an ugly mix of data and code. This allows the class code to be lazy-loaded with the autoloader, for a performance advantage especially on non-APC installs. And using the convention where if the class is omitted, ResourceLoaderFileModule is assumed, the registration code becomes shorter and simpler.
* Modified ResourceLoader to lazy-initialise module objects, for a further performance advantage.
* Deleted ResourceLoader::getModules(), provided getModuleNames() instead. Although the startup module needs this functionality, it's slow to generate, so to avoid misuse, it's better to provide a foolproof fast interface and let the startup module do the slow thing itself.
* Modified ResourceLoader::register() to optionally accept an info array instead of an object.
* Added $wgResourceModules, allowing extensions to efficiently define their own resource loader modules. The trouble with hooks is that they contain code, and code is slow. We've been through all this before with i18n. Hooks are useful as a performance tool only if you call them very rarely.
* Moved ResourceLoader settings to their own section in DefaultSettings.php
* Added options to ResourceLoaderFileModule equivalent to the $localBasePath and $remoteBasePath parameters, to allow it to be instantiated via the new array style. Also added remoteExtPath, which allows modules to be registered before $wgExtensionAssetsPath is known.
* Added OutputPage::getResourceLoader(), mostly for debugging.
* The time saving at the moment is about 5ms per request with no extensions, which is significant already with 6 load.php requests for a cold cache page view. This is a much more scalable interface; the relative saving will grow as more extensions are added which use this interface, especially for non-APC installs.
Although the interface is backwards compatible, extension updates will follow in a subsequent commit.
2010-11-19 10:41:06 +00:00
|
|
|
public function getModuleNames() {
|
|
|
|
|
return array_keys( $this->moduleInfos );
|
2010-09-04 04:00:09 +00:00
|
|
|
}
|
2012-10-19 20:03:05 +00:00
|
|
|
|
2012-10-26 15:42:13 +00:00
|
|
|
/**
|
2012-01-03 18:33:26 +00:00
|
|
|
* Get a list of test module names for one (or all) frameworks.
|
2014-03-07 16:50:57 +00:00
|
|
|
*
|
2012-01-03 18:33:26 +00:00
|
|
|
* If the given framework id is unknkown, or if the in-object variable is not an array,
|
|
|
|
|
* then it will return an empty array.
|
|
|
|
|
*
|
2014-03-07 16:50:57 +00:00
|
|
|
* @param string $framework Get only the test module names for one
|
|
|
|
|
* particular framework (optional)
|
2014-04-20 21:33:05 +00:00
|
|
|
* @return array
|
2012-01-03 18:33:26 +00:00
|
|
|
*/
|
|
|
|
|
public function getTestModuleNames( $framework = 'all' ) {
|
2014-05-10 08:39:37 +00:00
|
|
|
/** @todo api siteinfo prop testmodulenames modulenames */
|
2012-01-03 18:33:26 +00:00
|
|
|
if ( $framework == 'all' ) {
|
|
|
|
|
return $this->testModuleNames;
|
2014-05-10 08:39:37 +00:00
|
|
|
} elseif ( isset( $this->testModuleNames[$framework] )
|
|
|
|
|
&& is_array( $this->testModuleNames[$framework] )
|
|
|
|
|
) {
|
2012-01-03 18:33:26 +00:00
|
|
|
return $this->testModuleNames[$framework];
|
|
|
|
|
} else {
|
2016-02-17 09:09:32 +00:00
|
|
|
return [];
|
2012-01-03 18:33:26 +00:00
|
|
|
}
|
|
|
|
|
}
|
2010-09-04 12:53:01 +00:00
|
|
|
|
2015-01-30 21:36:52 +00:00
|
|
|
/**
|
|
|
|
|
* Check whether a ResourceLoader module is registered
|
|
|
|
|
*
|
|
|
|
|
* @since 1.25
|
|
|
|
|
* @param string $name
|
|
|
|
|
* @return bool
|
|
|
|
|
*/
|
|
|
|
|
public function isModuleRegistered( $name ) {
|
|
|
|
|
return isset( $this->moduleInfos[$name] );
|
|
|
|
|
}
|
|
|
|
|
|
2010-09-04 04:00:09 +00:00
|
|
|
/**
|
2010-10-20 00:22:25 +00:00
|
|
|
* Get the ResourceLoaderModule object for a given module name.
|
2010-09-05 13:31:34 +00:00
|
|
|
*
|
2014-04-03 23:09:09 +00:00
|
|
|
* If an array of module parameters exists but a ResourceLoaderModule object has not
|
|
|
|
|
* yet been instantiated, this method will instantiate and cache that object such that
|
|
|
|
|
* subsequent calls simply return the same object.
|
|
|
|
|
*
|
2013-03-11 17:15:01 +00:00
|
|
|
* @param string $name Module name
|
2014-04-03 23:09:09 +00:00
|
|
|
* @return ResourceLoaderModule|null If module has been registered, return a
|
|
|
|
|
* ResourceLoaderModule instance. Otherwise, return null.
|
2010-09-04 04:00:09 +00:00
|
|
|
*/
|
2010-09-29 19:04:04 +00:00
|
|
|
public function getModule( $name ) {
|
* Made Resources.php return a pure-data array instead of an ugly mix of data and code. This allows the class code to be lazy-loaded with the autoloader, for a performance advantage especially on non-APC installs. And using the convention where if the class is omitted, ResourceLoaderFileModule is assumed, the registration code becomes shorter and simpler.
* Modified ResourceLoader to lazy-initialise module objects, for a further performance advantage.
* Deleted ResourceLoader::getModules(), provided getModuleNames() instead. Although the startup module needs this functionality, it's slow to generate, so to avoid misuse, it's better to provide a foolproof fast interface and let the startup module do the slow thing itself.
* Modified ResourceLoader::register() to optionally accept an info array instead of an object.
* Added $wgResourceModules, allowing extensions to efficiently define their own resource loader modules. The trouble with hooks is that they contain code, and code is slow. We've been through all this before with i18n. Hooks are useful as a performance tool only if you call them very rarely.
* Moved ResourceLoader settings to their own section in DefaultSettings.php
* Added options to ResourceLoaderFileModule equivalent to the $localBasePath and $remoteBasePath parameters, to allow it to be instantiated via the new array style. Also added remoteExtPath, which allows modules to be registered before $wgExtensionAssetsPath is known.
* Added OutputPage::getResourceLoader(), mostly for debugging.
* The time saving at the moment is about 5ms per request with no extensions, which is significant already with 6 load.php requests for a cold cache page view. This is a much more scalable interface; the relative saving will grow as more extensions are added which use this interface, especially for non-APC installs.
Although the interface is backwards compatible, extension updates will follow in a subsequent commit.
2010-11-19 10:41:06 +00:00
|
|
|
if ( !isset( $this->modules[$name] ) ) {
|
|
|
|
|
if ( !isset( $this->moduleInfos[$name] ) ) {
|
|
|
|
|
// No such module
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
// Construct the requested object
|
|
|
|
|
$info = $this->moduleInfos[$name];
|
2013-07-01 18:01:11 +00:00
|
|
|
/** @var ResourceLoaderModule $object */
|
* Made Resources.php return a pure-data array instead of an ugly mix of data and code. This allows the class code to be lazy-loaded with the autoloader, for a performance advantage especially on non-APC installs. And using the convention where if the class is omitted, ResourceLoaderFileModule is assumed, the registration code becomes shorter and simpler.
* Modified ResourceLoader to lazy-initialise module objects, for a further performance advantage.
* Deleted ResourceLoader::getModules(), provided getModuleNames() instead. Although the startup module needs this functionality, it's slow to generate, so to avoid misuse, it's better to provide a foolproof fast interface and let the startup module do the slow thing itself.
* Modified ResourceLoader::register() to optionally accept an info array instead of an object.
* Added $wgResourceModules, allowing extensions to efficiently define their own resource loader modules. The trouble with hooks is that they contain code, and code is slow. We've been through all this before with i18n. Hooks are useful as a performance tool only if you call them very rarely.
* Moved ResourceLoader settings to their own section in DefaultSettings.php
* Added options to ResourceLoaderFileModule equivalent to the $localBasePath and $remoteBasePath parameters, to allow it to be instantiated via the new array style. Also added remoteExtPath, which allows modules to be registered before $wgExtensionAssetsPath is known.
* Added OutputPage::getResourceLoader(), mostly for debugging.
* The time saving at the moment is about 5ms per request with no extensions, which is significant already with 6 load.php requests for a cold cache page view. This is a much more scalable interface; the relative saving will grow as more extensions are added which use this interface, especially for non-APC installs.
Although the interface is backwards compatible, extension updates will follow in a subsequent commit.
2010-11-19 10:41:06 +00:00
|
|
|
if ( isset( $info['object'] ) ) {
|
|
|
|
|
// Object given in info array
|
|
|
|
|
$object = $info['object'];
|
2017-05-04 16:10:28 +00:00
|
|
|
} elseif ( isset( $info['factory'] ) ) {
|
|
|
|
|
$object = call_user_func( $info['factory'], $info );
|
|
|
|
|
$object->setConfig( $this->getConfig() );
|
|
|
|
|
$object->setLogger( $this->logger );
|
* Made Resources.php return a pure-data array instead of an ugly mix of data and code. This allows the class code to be lazy-loaded with the autoloader, for a performance advantage especially on non-APC installs. And using the convention where if the class is omitted, ResourceLoaderFileModule is assumed, the registration code becomes shorter and simpler.
* Modified ResourceLoader to lazy-initialise module objects, for a further performance advantage.
* Deleted ResourceLoader::getModules(), provided getModuleNames() instead. Although the startup module needs this functionality, it's slow to generate, so to avoid misuse, it's better to provide a foolproof fast interface and let the startup module do the slow thing itself.
* Modified ResourceLoader::register() to optionally accept an info array instead of an object.
* Added $wgResourceModules, allowing extensions to efficiently define their own resource loader modules. The trouble with hooks is that they contain code, and code is slow. We've been through all this before with i18n. Hooks are useful as a performance tool only if you call them very rarely.
* Moved ResourceLoader settings to their own section in DefaultSettings.php
* Added options to ResourceLoaderFileModule equivalent to the $localBasePath and $remoteBasePath parameters, to allow it to be instantiated via the new array style. Also added remoteExtPath, which allows modules to be registered before $wgExtensionAssetsPath is known.
* Added OutputPage::getResourceLoader(), mostly for debugging.
* The time saving at the moment is about 5ms per request with no extensions, which is significant already with 6 load.php requests for a cold cache page view. This is a much more scalable interface; the relative saving will grow as more extensions are added which use this interface, especially for non-APC installs.
Although the interface is backwards compatible, extension updates will follow in a subsequent commit.
2010-11-19 10:41:06 +00:00
|
|
|
} else {
|
|
|
|
|
if ( !isset( $info['class'] ) ) {
|
|
|
|
|
$class = 'ResourceLoaderFileModule';
|
|
|
|
|
} else {
|
|
|
|
|
$class = $info['class'];
|
|
|
|
|
}
|
2014-08-07 10:25:56 +00:00
|
|
|
/** @var ResourceLoaderModule $object */
|
* Made Resources.php return a pure-data array instead of an ugly mix of data and code. This allows the class code to be lazy-loaded with the autoloader, for a performance advantage especially on non-APC installs. And using the convention where if the class is omitted, ResourceLoaderFileModule is assumed, the registration code becomes shorter and simpler.
* Modified ResourceLoader to lazy-initialise module objects, for a further performance advantage.
* Deleted ResourceLoader::getModules(), provided getModuleNames() instead. Although the startup module needs this functionality, it's slow to generate, so to avoid misuse, it's better to provide a foolproof fast interface and let the startup module do the slow thing itself.
* Modified ResourceLoader::register() to optionally accept an info array instead of an object.
* Added $wgResourceModules, allowing extensions to efficiently define their own resource loader modules. The trouble with hooks is that they contain code, and code is slow. We've been through all this before with i18n. Hooks are useful as a performance tool only if you call them very rarely.
* Moved ResourceLoader settings to their own section in DefaultSettings.php
* Added options to ResourceLoaderFileModule equivalent to the $localBasePath and $remoteBasePath parameters, to allow it to be instantiated via the new array style. Also added remoteExtPath, which allows modules to be registered before $wgExtensionAssetsPath is known.
* Added OutputPage::getResourceLoader(), mostly for debugging.
* The time saving at the moment is about 5ms per request with no extensions, which is significant already with 6 load.php requests for a cold cache page view. This is a much more scalable interface; the relative saving will grow as more extensions are added which use this interface, especially for non-APC installs.
Although the interface is backwards compatible, extension updates will follow in a subsequent commit.
2010-11-19 10:41:06 +00:00
|
|
|
$object = new $class( $info );
|
2014-08-07 10:25:56 +00:00
|
|
|
$object->setConfig( $this->getConfig() );
|
2015-11-13 00:04:12 +00:00
|
|
|
$object->setLogger( $this->logger );
|
* Made Resources.php return a pure-data array instead of an ugly mix of data and code. This allows the class code to be lazy-loaded with the autoloader, for a performance advantage especially on non-APC installs. And using the convention where if the class is omitted, ResourceLoaderFileModule is assumed, the registration code becomes shorter and simpler.
* Modified ResourceLoader to lazy-initialise module objects, for a further performance advantage.
* Deleted ResourceLoader::getModules(), provided getModuleNames() instead. Although the startup module needs this functionality, it's slow to generate, so to avoid misuse, it's better to provide a foolproof fast interface and let the startup module do the slow thing itself.
* Modified ResourceLoader::register() to optionally accept an info array instead of an object.
* Added $wgResourceModules, allowing extensions to efficiently define their own resource loader modules. The trouble with hooks is that they contain code, and code is slow. We've been through all this before with i18n. Hooks are useful as a performance tool only if you call them very rarely.
* Moved ResourceLoader settings to their own section in DefaultSettings.php
* Added options to ResourceLoaderFileModule equivalent to the $localBasePath and $remoteBasePath parameters, to allow it to be instantiated via the new array style. Also added remoteExtPath, which allows modules to be registered before $wgExtensionAssetsPath is known.
* Added OutputPage::getResourceLoader(), mostly for debugging.
* The time saving at the moment is about 5ms per request with no extensions, which is significant already with 6 load.php requests for a cold cache page view. This is a much more scalable interface; the relative saving will grow as more extensions are added which use this interface, especially for non-APC installs.
Although the interface is backwards compatible, extension updates will follow in a subsequent commit.
2010-11-19 10:41:06 +00:00
|
|
|
}
|
|
|
|
|
$object->setName( $name );
|
|
|
|
|
$this->modules[$name] = $object;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return $this->modules[$name];
|
2010-09-04 04:00:09 +00:00
|
|
|
}
|
2010-09-04 12:53:01 +00:00
|
|
|
|
2014-06-26 14:29:31 +00:00
|
|
|
/**
|
2017-06-05 23:04:19 +00:00
|
|
|
* Return whether the definition of a module corresponds to a simple ResourceLoaderFileModule
|
|
|
|
|
* or one of its subclasses.
|
2014-06-26 14:29:31 +00:00
|
|
|
*
|
|
|
|
|
* @param string $name Module name
|
2014-08-04 10:00:15 +00:00
|
|
|
* @return bool
|
2014-06-26 14:29:31 +00:00
|
|
|
*/
|
|
|
|
|
protected function isFileModule( $name ) {
|
|
|
|
|
if ( !isset( $this->moduleInfos[$name] ) ) {
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
$info = $this->moduleInfos[$name];
|
2017-06-05 23:04:19 +00:00
|
|
|
if ( isset( $info['object'] ) ) {
|
|
|
|
|
return false;
|
|
|
|
|
}
|
2017-06-05 17:32:23 +00:00
|
|
|
if (
|
2017-06-05 23:04:19 +00:00
|
|
|
isset( $info['class'] ) &&
|
|
|
|
|
$info['class'] !== 'ResourceLoaderFileModule' &&
|
|
|
|
|
!is_subclass_of( $info['class'], 'ResourceLoaderFileModule' )
|
2017-06-05 17:32:23 +00:00
|
|
|
) {
|
2014-06-26 14:29:31 +00:00
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
|
2011-07-26 21:10:34 +00:00
|
|
|
/**
|
2014-03-07 16:50:57 +00:00
|
|
|
* Get the list of sources.
|
2011-10-14 08:06:54 +00:00
|
|
|
*
|
2016-08-13 01:10:40 +00:00
|
|
|
* @return array Like [ id => load.php url, ... ]
|
2011-07-26 21:10:34 +00:00
|
|
|
*/
|
|
|
|
|
public function getSources() {
|
|
|
|
|
return $this->sources;
|
|
|
|
|
}
|
|
|
|
|
|
2014-06-28 02:57:40 +00:00
|
|
|
/**
|
|
|
|
|
* Get the URL to the load.php endpoint for the given
|
|
|
|
|
* ResourceLoader source
|
|
|
|
|
*
|
|
|
|
|
* @since 1.24
|
|
|
|
|
* @param string $source
|
2014-07-24 17:43:25 +00:00
|
|
|
* @throws MWException On an invalid $source name
|
2014-06-28 02:57:40 +00:00
|
|
|
* @return string
|
|
|
|
|
*/
|
|
|
|
|
public function getLoadScript( $source ) {
|
|
|
|
|
if ( !isset( $this->sources[$source] ) ) {
|
|
|
|
|
throw new MWException( "The $source source was never registered in ResourceLoader." );
|
|
|
|
|
}
|
2014-08-25 08:02:48 +00:00
|
|
|
return $this->sources[$source];
|
2014-06-28 02:57:40 +00:00
|
|
|
}
|
|
|
|
|
|
resourceloader: Replace timestamp system with version hashing
Modules now track their version via getVersionHash() instead of getModifiedTime().
== Background ==
While some resources have observeable timestamps (e.g. files stored on disk),
many other resources do not. E.g. config variables, and module definitions.
For static file modules, one can e.g. revert one of more files in a module to a
previous version and not affect the max timestamp.
Wiki modules include pages only if they exist. The user module supports common.js
and skin.js. By default neither exists. If a user has both, and then the
less-recently modified one is deleted, the max-timestamp remains unchanged.
For client-side caching, batch requests use "Math.max" on the relevant timestamps.
Again, if a module changes but another module is more recent (e.g. out-of-order
deployment, or out-of-order discovery), the change would not result in a cache miss.
More scenarios can be found in the associated Phabricator tasks.
== Version hash ==
Previously we virtually mapped these variables to a timestamp by storing the current
time alongside a hash of the value in ObjectCache. Considering the number of
possible request contexts (wikis * modules * users * skins * languages) this doesn't
work well. It results in needless cache invalidation when the first time observation
is purged due to LRU algorithms. It also has other minor bugs leading to fewer
cache hits.
All modules automatically get the benefits of version hashing with this change.
The old getDefinitionMtime() and getHashMtime() have been replaced with dummies
that return 1. These functions are often called from getModifiedTime() in subclasses.
For backward-compatibility, their respective values (definition summary and hash)
are now included in getVersionHash directly.
As examples, the following modules have been updated to use getVersionHash directly.
Other modules still work fine and can be updated later.
* ResourceLoaderFileModule
* ResourceLoaderEditToolbarModule
* ResourceLoaderStartUpModule
* ResourceLoaderWikiModule
The presence of hashes in place of timestamps increases the startup module size on
a default MediaWiki install from 4.4k to 5.8k (after gzip and minification).
== ETag ==
Since timestamps are no longer tracked, we need a different way to implement caching
for cache proxies (e.g. Varnish) and web browsers. Previously we used the
Last-Modified header (in combination with Cache-Control and Expires).
Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match).
Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default.
They instruct browsers to allow usage of partial Range requests. Since our responses
are dynamically generated, we need to use the Weak version of ETag.
While this sounds bad, it's no different than Last-Modified. As reassured by
RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the
specified behaviour behind Last-Modified follows the same "Weak" caching logic as
Entity tags. It's just that entity tags are capable of a stricter mode (whereas
Last-Modified is inherently weak).
== File cache ==
If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache
load.php responses. While the blind TTL handling (during the allowed expiry period)
is still maxage/timestamp based, tryRespondNotModified() now requires the caller to
know the expected ETag.
For this to work, the FileCache handling had to be moved from the top of
ResoureLoader::respond() to after the expected ETag is computed.
This also allows us to remove the duplicate tryRespondNotModified() handling since
that's is already handled by ResourceLoader::respond() meanwhile.
== Misc ==
* Remove redundant modifiedTime cache in ResourceLoaderFileModule.
* Change bugzilla references to Phabricator.
* Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this
logic was duplicated in each place the modified timestamp was used.
* It's easy to forget calling the parent class in getDefinitionSummary().
Previously this method only tracked 'class' by default. As such, various
extensions hardcoded that one value instead of calling the parent and extending
the array. To better prevent this in the future, getVersionHash() now asserts
that the '_cacheEpoch' property made it through.
* tests: Don't use getDefinitionSummary() as an API.
Fix ResourceLoaderWikiModuleTest to call getPages properly.
* In tests, the default timestamp used to be 1388534400000 (which is the unix time
of 20140101000000; the unit tests' CacheEpoch). The new version hash of these
modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of:
'{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}'
* Add sha1.js library for client-side hash generation.
Compared various different implementations for code size (after minfication/gzip),
and speed (when used for short hexidecimal strings).
https://jsperf.com/sha1-implementations
- CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k)
http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js
Chrome: 45k, Firefox: 89k, Safari: 92k
- jsSHA <https://github.com/Caligatio/jsSHA>
https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k)
Chrome: 65k, Firefox: 53k, Safari: 69k
- phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k)
https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js
Chrome: 200k, Firefox: 280k, Safari: 78k
Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous,
only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate
code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being
needed in the module loader, we'd have to load the fallback regardless. Considering
this is not used in a critical path for performance, it's not worth shipping two
implementations for this optimisation.
May also resolve:
* T44094
* T90411
* T94810
Bug: T94074
Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
|
|
|
/**
|
|
|
|
|
* @since 1.26
|
|
|
|
|
* @param string $value
|
|
|
|
|
* @return string Hash
|
|
|
|
|
*/
|
|
|
|
|
public static function makeHash( $value ) {
|
resourceloader: Replace SHA1 with 32-bit FNV-1 as hash function
SHA-1 is not secure enough to be used as a cryptographic hash function, and its
implementation in JavaScript is too long and too slow for it to be a good
general-purpose hash function. And we currently throw away most of the work:
SHA-1 produces 160-bit hash values, of which we keep 48.
Although the JavaScript implementation is not exported, SHA-1 is a well-known
hash function, and I'm willing to bet that sooner or later someone will move to
make it accessible to other modules, at which point usage will start to spread.
For ResourceLoader, the qualities we're looking for in a hash function are:
* Already implemented in PHP
* Easy to implement in JavaScript
* Fast
* Collision-resistant
The requirement that hashes be cheap to compute in JavaScript narrows the field
to 32-bit hash functions, because in JavaScript bitwise operators treat their
operands as 32 bits, and arithmetic uses double-precision floats, which have a
total precision of 53 bits. It's possible to work around these limitations, but
it's a lot of extra work.
The best match I found is the 32-bit variant of FNV-1, which is available in
PHP as of version 5.4 (as 'fnv1a32'). The fnv132 JavaScript function is
around ten times faster and eight times shorter than sha1.
Change-Id: I1e4fb08d17948538d96f241b2464d594fdc14578
2016-06-22 22:32:58 +00:00
|
|
|
$hash = hash( 'fnv132', $value );
|
|
|
|
|
return Wikimedia\base_convert( $hash, 16, 36, 7 );
|
resourceloader: Replace timestamp system with version hashing
Modules now track their version via getVersionHash() instead of getModifiedTime().
== Background ==
While some resources have observeable timestamps (e.g. files stored on disk),
many other resources do not. E.g. config variables, and module definitions.
For static file modules, one can e.g. revert one of more files in a module to a
previous version and not affect the max timestamp.
Wiki modules include pages only if they exist. The user module supports common.js
and skin.js. By default neither exists. If a user has both, and then the
less-recently modified one is deleted, the max-timestamp remains unchanged.
For client-side caching, batch requests use "Math.max" on the relevant timestamps.
Again, if a module changes but another module is more recent (e.g. out-of-order
deployment, or out-of-order discovery), the change would not result in a cache miss.
More scenarios can be found in the associated Phabricator tasks.
== Version hash ==
Previously we virtually mapped these variables to a timestamp by storing the current
time alongside a hash of the value in ObjectCache. Considering the number of
possible request contexts (wikis * modules * users * skins * languages) this doesn't
work well. It results in needless cache invalidation when the first time observation
is purged due to LRU algorithms. It also has other minor bugs leading to fewer
cache hits.
All modules automatically get the benefits of version hashing with this change.
The old getDefinitionMtime() and getHashMtime() have been replaced with dummies
that return 1. These functions are often called from getModifiedTime() in subclasses.
For backward-compatibility, their respective values (definition summary and hash)
are now included in getVersionHash directly.
As examples, the following modules have been updated to use getVersionHash directly.
Other modules still work fine and can be updated later.
* ResourceLoaderFileModule
* ResourceLoaderEditToolbarModule
* ResourceLoaderStartUpModule
* ResourceLoaderWikiModule
The presence of hashes in place of timestamps increases the startup module size on
a default MediaWiki install from 4.4k to 5.8k (after gzip and minification).
== ETag ==
Since timestamps are no longer tracked, we need a different way to implement caching
for cache proxies (e.g. Varnish) and web browsers. Previously we used the
Last-Modified header (in combination with Cache-Control and Expires).
Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match).
Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default.
They instruct browsers to allow usage of partial Range requests. Since our responses
are dynamically generated, we need to use the Weak version of ETag.
While this sounds bad, it's no different than Last-Modified. As reassured by
RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the
specified behaviour behind Last-Modified follows the same "Weak" caching logic as
Entity tags. It's just that entity tags are capable of a stricter mode (whereas
Last-Modified is inherently weak).
== File cache ==
If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache
load.php responses. While the blind TTL handling (during the allowed expiry period)
is still maxage/timestamp based, tryRespondNotModified() now requires the caller to
know the expected ETag.
For this to work, the FileCache handling had to be moved from the top of
ResoureLoader::respond() to after the expected ETag is computed.
This also allows us to remove the duplicate tryRespondNotModified() handling since
that's is already handled by ResourceLoader::respond() meanwhile.
== Misc ==
* Remove redundant modifiedTime cache in ResourceLoaderFileModule.
* Change bugzilla references to Phabricator.
* Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this
logic was duplicated in each place the modified timestamp was used.
* It's easy to forget calling the parent class in getDefinitionSummary().
Previously this method only tracked 'class' by default. As such, various
extensions hardcoded that one value instead of calling the parent and extending
the array. To better prevent this in the future, getVersionHash() now asserts
that the '_cacheEpoch' property made it through.
* tests: Don't use getDefinitionSummary() as an API.
Fix ResourceLoaderWikiModuleTest to call getPages properly.
* In tests, the default timestamp used to be 1388534400000 (which is the unix time
of 20140101000000; the unit tests' CacheEpoch). The new version hash of these
modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of:
'{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}'
* Add sha1.js library for client-side hash generation.
Compared various different implementations for code size (after minfication/gzip),
and speed (when used for short hexidecimal strings).
https://jsperf.com/sha1-implementations
- CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k)
http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js
Chrome: 45k, Firefox: 89k, Safari: 92k
- jsSHA <https://github.com/Caligatio/jsSHA>
https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k)
Chrome: 65k, Firefox: 53k, Safari: 69k
- phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k)
https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js
Chrome: 200k, Firefox: 280k, Safari: 78k
Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous,
only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate
code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being
needed in the module loader, we'd have to load the fallback regardless. Considering
this is not used in a critical path for performance, it's not worth shipping two
implementations for this optimisation.
May also resolve:
* T44094
* T90411
* T94810
Bug: T94074
Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
|
|
|
}
|
|
|
|
|
|
2016-12-03 03:57:42 +00:00
|
|
|
/**
|
|
|
|
|
* Add an error to the 'errors' array and log it.
|
|
|
|
|
*
|
|
|
|
|
* Should only be called from within respond().
|
|
|
|
|
*
|
|
|
|
|
* @since 1.29
|
|
|
|
|
* @param Exception $e
|
|
|
|
|
* @param string $msg
|
|
|
|
|
* @param array $context
|
|
|
|
|
*/
|
|
|
|
|
protected function outputErrorAndLog( Exception $e, $msg, array $context = [] ) {
|
|
|
|
|
MWExceptionHandler::logException( $e );
|
|
|
|
|
$this->logger->warning(
|
|
|
|
|
$msg,
|
|
|
|
|
$context + [ 'exception' => $e ]
|
|
|
|
|
);
|
|
|
|
|
$this->errors[] = self::formatExceptionNoComment( $e );
|
|
|
|
|
}
|
|
|
|
|
|
resourceloader: Replace timestamp system with version hashing
Modules now track their version via getVersionHash() instead of getModifiedTime().
== Background ==
While some resources have observeable timestamps (e.g. files stored on disk),
many other resources do not. E.g. config variables, and module definitions.
For static file modules, one can e.g. revert one of more files in a module to a
previous version and not affect the max timestamp.
Wiki modules include pages only if they exist. The user module supports common.js
and skin.js. By default neither exists. If a user has both, and then the
less-recently modified one is deleted, the max-timestamp remains unchanged.
For client-side caching, batch requests use "Math.max" on the relevant timestamps.
Again, if a module changes but another module is more recent (e.g. out-of-order
deployment, or out-of-order discovery), the change would not result in a cache miss.
More scenarios can be found in the associated Phabricator tasks.
== Version hash ==
Previously we virtually mapped these variables to a timestamp by storing the current
time alongside a hash of the value in ObjectCache. Considering the number of
possible request contexts (wikis * modules * users * skins * languages) this doesn't
work well. It results in needless cache invalidation when the first time observation
is purged due to LRU algorithms. It also has other minor bugs leading to fewer
cache hits.
All modules automatically get the benefits of version hashing with this change.
The old getDefinitionMtime() and getHashMtime() have been replaced with dummies
that return 1. These functions are often called from getModifiedTime() in subclasses.
For backward-compatibility, their respective values (definition summary and hash)
are now included in getVersionHash directly.
As examples, the following modules have been updated to use getVersionHash directly.
Other modules still work fine and can be updated later.
* ResourceLoaderFileModule
* ResourceLoaderEditToolbarModule
* ResourceLoaderStartUpModule
* ResourceLoaderWikiModule
The presence of hashes in place of timestamps increases the startup module size on
a default MediaWiki install from 4.4k to 5.8k (after gzip and minification).
== ETag ==
Since timestamps are no longer tracked, we need a different way to implement caching
for cache proxies (e.g. Varnish) and web browsers. Previously we used the
Last-Modified header (in combination with Cache-Control and Expires).
Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match).
Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default.
They instruct browsers to allow usage of partial Range requests. Since our responses
are dynamically generated, we need to use the Weak version of ETag.
While this sounds bad, it's no different than Last-Modified. As reassured by
RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the
specified behaviour behind Last-Modified follows the same "Weak" caching logic as
Entity tags. It's just that entity tags are capable of a stricter mode (whereas
Last-Modified is inherently weak).
== File cache ==
If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache
load.php responses. While the blind TTL handling (during the allowed expiry period)
is still maxage/timestamp based, tryRespondNotModified() now requires the caller to
know the expected ETag.
For this to work, the FileCache handling had to be moved from the top of
ResoureLoader::respond() to after the expected ETag is computed.
This also allows us to remove the duplicate tryRespondNotModified() handling since
that's is already handled by ResourceLoader::respond() meanwhile.
== Misc ==
* Remove redundant modifiedTime cache in ResourceLoaderFileModule.
* Change bugzilla references to Phabricator.
* Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this
logic was duplicated in each place the modified timestamp was used.
* It's easy to forget calling the parent class in getDefinitionSummary().
Previously this method only tracked 'class' by default. As such, various
extensions hardcoded that one value instead of calling the parent and extending
the array. To better prevent this in the future, getVersionHash() now asserts
that the '_cacheEpoch' property made it through.
* tests: Don't use getDefinitionSummary() as an API.
Fix ResourceLoaderWikiModuleTest to call getPages properly.
* In tests, the default timestamp used to be 1388534400000 (which is the unix time
of 20140101000000; the unit tests' CacheEpoch). The new version hash of these
modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of:
'{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}'
* Add sha1.js library for client-side hash generation.
Compared various different implementations for code size (after minfication/gzip),
and speed (when used for short hexidecimal strings).
https://jsperf.com/sha1-implementations
- CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k)
http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js
Chrome: 45k, Firefox: 89k, Safari: 92k
- jsSHA <https://github.com/Caligatio/jsSHA>
https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k)
Chrome: 65k, Firefox: 53k, Safari: 69k
- phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k)
https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js
Chrome: 200k, Firefox: 280k, Safari: 78k
Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous,
only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate
code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being
needed in the module loader, we'd have to load the fallback regardless. Considering
this is not used in a critical path for performance, it's not worth shipping two
implementations for this optimisation.
May also resolve:
* T44094
* T90411
* T94810
Bug: T94074
Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
|
|
|
/**
|
|
|
|
|
* Helper method to get and combine versions of multiple modules.
|
|
|
|
|
*
|
|
|
|
|
* @since 1.26
|
|
|
|
|
* @param ResourceLoaderContext $context
|
2016-09-02 22:44:59 +00:00
|
|
|
* @param string[] $modules List of known module names
|
resourceloader: Replace timestamp system with version hashing
Modules now track their version via getVersionHash() instead of getModifiedTime().
== Background ==
While some resources have observeable timestamps (e.g. files stored on disk),
many other resources do not. E.g. config variables, and module definitions.
For static file modules, one can e.g. revert one of more files in a module to a
previous version and not affect the max timestamp.
Wiki modules include pages only if they exist. The user module supports common.js
and skin.js. By default neither exists. If a user has both, and then the
less-recently modified one is deleted, the max-timestamp remains unchanged.
For client-side caching, batch requests use "Math.max" on the relevant timestamps.
Again, if a module changes but another module is more recent (e.g. out-of-order
deployment, or out-of-order discovery), the change would not result in a cache miss.
More scenarios can be found in the associated Phabricator tasks.
== Version hash ==
Previously we virtually mapped these variables to a timestamp by storing the current
time alongside a hash of the value in ObjectCache. Considering the number of
possible request contexts (wikis * modules * users * skins * languages) this doesn't
work well. It results in needless cache invalidation when the first time observation
is purged due to LRU algorithms. It also has other minor bugs leading to fewer
cache hits.
All modules automatically get the benefits of version hashing with this change.
The old getDefinitionMtime() and getHashMtime() have been replaced with dummies
that return 1. These functions are often called from getModifiedTime() in subclasses.
For backward-compatibility, their respective values (definition summary and hash)
are now included in getVersionHash directly.
As examples, the following modules have been updated to use getVersionHash directly.
Other modules still work fine and can be updated later.
* ResourceLoaderFileModule
* ResourceLoaderEditToolbarModule
* ResourceLoaderStartUpModule
* ResourceLoaderWikiModule
The presence of hashes in place of timestamps increases the startup module size on
a default MediaWiki install from 4.4k to 5.8k (after gzip and minification).
== ETag ==
Since timestamps are no longer tracked, we need a different way to implement caching
for cache proxies (e.g. Varnish) and web browsers. Previously we used the
Last-Modified header (in combination with Cache-Control and Expires).
Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match).
Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default.
They instruct browsers to allow usage of partial Range requests. Since our responses
are dynamically generated, we need to use the Weak version of ETag.
While this sounds bad, it's no different than Last-Modified. As reassured by
RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the
specified behaviour behind Last-Modified follows the same "Weak" caching logic as
Entity tags. It's just that entity tags are capable of a stricter mode (whereas
Last-Modified is inherently weak).
== File cache ==
If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache
load.php responses. While the blind TTL handling (during the allowed expiry period)
is still maxage/timestamp based, tryRespondNotModified() now requires the caller to
know the expected ETag.
For this to work, the FileCache handling had to be moved from the top of
ResoureLoader::respond() to after the expected ETag is computed.
This also allows us to remove the duplicate tryRespondNotModified() handling since
that's is already handled by ResourceLoader::respond() meanwhile.
== Misc ==
* Remove redundant modifiedTime cache in ResourceLoaderFileModule.
* Change bugzilla references to Phabricator.
* Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this
logic was duplicated in each place the modified timestamp was used.
* It's easy to forget calling the parent class in getDefinitionSummary().
Previously this method only tracked 'class' by default. As such, various
extensions hardcoded that one value instead of calling the parent and extending
the array. To better prevent this in the future, getVersionHash() now asserts
that the '_cacheEpoch' property made it through.
* tests: Don't use getDefinitionSummary() as an API.
Fix ResourceLoaderWikiModuleTest to call getPages properly.
* In tests, the default timestamp used to be 1388534400000 (which is the unix time
of 20140101000000; the unit tests' CacheEpoch). The new version hash of these
modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of:
'{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}'
* Add sha1.js library for client-side hash generation.
Compared various different implementations for code size (after minfication/gzip),
and speed (when used for short hexidecimal strings).
https://jsperf.com/sha1-implementations
- CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k)
http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js
Chrome: 45k, Firefox: 89k, Safari: 92k
- jsSHA <https://github.com/Caligatio/jsSHA>
https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k)
Chrome: 65k, Firefox: 53k, Safari: 69k
- phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k)
https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js
Chrome: 200k, Firefox: 280k, Safari: 78k
Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous,
only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate
code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being
needed in the module loader, we'd have to load the fallback regardless. Considering
this is not used in a critical path for performance, it's not worth shipping two
implementations for this optimisation.
May also resolve:
* T44094
* T90411
* T94810
Bug: T94074
Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
|
|
|
* @return string Hash
|
|
|
|
|
*/
|
2016-09-02 22:44:59 +00:00
|
|
|
public function getCombinedVersion( ResourceLoaderContext $context, array $moduleNames ) {
|
|
|
|
|
if ( !$moduleNames ) {
|
resourceloader: Replace timestamp system with version hashing
Modules now track their version via getVersionHash() instead of getModifiedTime().
== Background ==
While some resources have observeable timestamps (e.g. files stored on disk),
many other resources do not. E.g. config variables, and module definitions.
For static file modules, one can e.g. revert one of more files in a module to a
previous version and not affect the max timestamp.
Wiki modules include pages only if they exist. The user module supports common.js
and skin.js. By default neither exists. If a user has both, and then the
less-recently modified one is deleted, the max-timestamp remains unchanged.
For client-side caching, batch requests use "Math.max" on the relevant timestamps.
Again, if a module changes but another module is more recent (e.g. out-of-order
deployment, or out-of-order discovery), the change would not result in a cache miss.
More scenarios can be found in the associated Phabricator tasks.
== Version hash ==
Previously we virtually mapped these variables to a timestamp by storing the current
time alongside a hash of the value in ObjectCache. Considering the number of
possible request contexts (wikis * modules * users * skins * languages) this doesn't
work well. It results in needless cache invalidation when the first time observation
is purged due to LRU algorithms. It also has other minor bugs leading to fewer
cache hits.
All modules automatically get the benefits of version hashing with this change.
The old getDefinitionMtime() and getHashMtime() have been replaced with dummies
that return 1. These functions are often called from getModifiedTime() in subclasses.
For backward-compatibility, their respective values (definition summary and hash)
are now included in getVersionHash directly.
As examples, the following modules have been updated to use getVersionHash directly.
Other modules still work fine and can be updated later.
* ResourceLoaderFileModule
* ResourceLoaderEditToolbarModule
* ResourceLoaderStartUpModule
* ResourceLoaderWikiModule
The presence of hashes in place of timestamps increases the startup module size on
a default MediaWiki install from 4.4k to 5.8k (after gzip and minification).
== ETag ==
Since timestamps are no longer tracked, we need a different way to implement caching
for cache proxies (e.g. Varnish) and web browsers. Previously we used the
Last-Modified header (in combination with Cache-Control and Expires).
Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match).
Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default.
They instruct browsers to allow usage of partial Range requests. Since our responses
are dynamically generated, we need to use the Weak version of ETag.
While this sounds bad, it's no different than Last-Modified. As reassured by
RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the
specified behaviour behind Last-Modified follows the same "Weak" caching logic as
Entity tags. It's just that entity tags are capable of a stricter mode (whereas
Last-Modified is inherently weak).
== File cache ==
If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache
load.php responses. While the blind TTL handling (during the allowed expiry period)
is still maxage/timestamp based, tryRespondNotModified() now requires the caller to
know the expected ETag.
For this to work, the FileCache handling had to be moved from the top of
ResoureLoader::respond() to after the expected ETag is computed.
This also allows us to remove the duplicate tryRespondNotModified() handling since
that's is already handled by ResourceLoader::respond() meanwhile.
== Misc ==
* Remove redundant modifiedTime cache in ResourceLoaderFileModule.
* Change bugzilla references to Phabricator.
* Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this
logic was duplicated in each place the modified timestamp was used.
* It's easy to forget calling the parent class in getDefinitionSummary().
Previously this method only tracked 'class' by default. As such, various
extensions hardcoded that one value instead of calling the parent and extending
the array. To better prevent this in the future, getVersionHash() now asserts
that the '_cacheEpoch' property made it through.
* tests: Don't use getDefinitionSummary() as an API.
Fix ResourceLoaderWikiModuleTest to call getPages properly.
* In tests, the default timestamp used to be 1388534400000 (which is the unix time
of 20140101000000; the unit tests' CacheEpoch). The new version hash of these
modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of:
'{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}'
* Add sha1.js library for client-side hash generation.
Compared various different implementations for code size (after minfication/gzip),
and speed (when used for short hexidecimal strings).
https://jsperf.com/sha1-implementations
- CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k)
http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js
Chrome: 45k, Firefox: 89k, Safari: 92k
- jsSHA <https://github.com/Caligatio/jsSHA>
https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k)
Chrome: 65k, Firefox: 53k, Safari: 69k
- phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k)
https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js
Chrome: 200k, Firefox: 280k, Safari: 78k
Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous,
only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate
code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being
needed in the module loader, we'd have to load the fallback regardless. Considering
this is not used in a critical path for performance, it's not worth shipping two
implementations for this optimisation.
May also resolve:
* T44094
* T90411
* T94810
Bug: T94074
Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
|
|
|
return '';
|
|
|
|
|
}
|
2016-02-10 17:13:38 +00:00
|
|
|
$hashes = array_map( function ( $module ) use ( $context ) {
|
resourceloader: Don't let module exception break startup
When getScript (or some other method used in a module response)
throws an error, only that module fails (by outputting mw.loader.state
instead of mw.loader.implement). Other modules will work.
This has always been the case and is working fine. For example,
"load.php?modules=foo|bar", where 'foo' throws, will return:
```js
/* exception message: .. */
mw.loader.implement('bar', ..)
mw.loader.state('foo', 'error')
```
The problem, however, is that during the generation of the startup
module, we iterate over all other modules. In 2011, the
getVersionHash method (then: getModifiedTime) was fairly simple
and unlikely to throw errors.
Nowadays, some modules use enableModuleContentVersion which will
involve the same code path as for regular module responses.
The try/catch in ResourceLoader::makeModuleResponse() suffices
for the case of loading modules other than startup. But when
loading the startup module, and an exception happens in getVersionHash,
then the entire startup response is replaced with an exception comment.
Example case:
* A file not existing for a FileModule subclass that uses
enableModuleContentVersion.
* A database error from a data module, like CiteDataModule or
CNChoiceData.
Changes:
* Ensure E-Tag is still useful while an error happens in production
because we respond with 200 OK and one error isn't the same as
another.
Fixed by try/catch in getCombinedVersion.
* Ensure start manifest isn't disrupted by one broken module.
Fixed by try/catch in StartupModule::getModuleRegistrations().
Tests:
* testMakeModuleResponseError: The case that already worked fined.
* testMakeModuleResponseStartupError: The case fixed in this commit.
* testGetCombinedVersion: The case fixed in this commit for E-Tag.
Bug: T152266
Change-Id: Ice4ede5ea594bf3fa591134bc9382bd9c24e2f39
2016-12-03 00:48:14 +00:00
|
|
|
try {
|
|
|
|
|
return $this->getModule( $module )->getVersionHash( $context );
|
|
|
|
|
} catch ( Exception $e ) {
|
|
|
|
|
// If modules fail to compute a version, do still consider the versions
|
|
|
|
|
// of other modules - don't set an empty string E-Tag for the whole request.
|
|
|
|
|
// See also T152266 and StartupModule::getModuleRegistrations().
|
2016-12-03 03:57:42 +00:00
|
|
|
$this->outputErrorAndLog( $e,
|
resourceloader: Don't let module exception break startup
When getScript (or some other method used in a module response)
throws an error, only that module fails (by outputting mw.loader.state
instead of mw.loader.implement). Other modules will work.
This has always been the case and is working fine. For example,
"load.php?modules=foo|bar", where 'foo' throws, will return:
```js
/* exception message: .. */
mw.loader.implement('bar', ..)
mw.loader.state('foo', 'error')
```
The problem, however, is that during the generation of the startup
module, we iterate over all other modules. In 2011, the
getVersionHash method (then: getModifiedTime) was fairly simple
and unlikely to throw errors.
Nowadays, some modules use enableModuleContentVersion which will
involve the same code path as for regular module responses.
The try/catch in ResourceLoader::makeModuleResponse() suffices
for the case of loading modules other than startup. But when
loading the startup module, and an exception happens in getVersionHash,
then the entire startup response is replaced with an exception comment.
Example case:
* A file not existing for a FileModule subclass that uses
enableModuleContentVersion.
* A database error from a data module, like CiteDataModule or
CNChoiceData.
Changes:
* Ensure E-Tag is still useful while an error happens in production
because we respond with 200 OK and one error isn't the same as
another.
Fixed by try/catch in getCombinedVersion.
* Ensure start manifest isn't disrupted by one broken module.
Fixed by try/catch in StartupModule::getModuleRegistrations().
Tests:
* testMakeModuleResponseError: The case that already worked fined.
* testMakeModuleResponseStartupError: The case fixed in this commit.
* testGetCombinedVersion: The case fixed in this commit for E-Tag.
Bug: T152266
Change-Id: Ice4ede5ea594bf3fa591134bc9382bd9c24e2f39
2016-12-03 00:48:14 +00:00
|
|
|
'Calculating version for "{module}" failed: {exception}',
|
|
|
|
|
[
|
|
|
|
|
'module' => $module,
|
|
|
|
|
]
|
|
|
|
|
);
|
|
|
|
|
return '';
|
|
|
|
|
}
|
2016-09-02 22:44:59 +00:00
|
|
|
}, $moduleNames );
|
|
|
|
|
return self::makeHash( implode( '', $hashes ) );
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Get the expected value of the 'version' query parameter.
|
|
|
|
|
*
|
|
|
|
|
* This is used by respond() to set a short Cache-Control header for requests with
|
|
|
|
|
* information newer than the current server has. This avoids pollution of edge caches.
|
|
|
|
|
* Typically during deployment. (T117587)
|
|
|
|
|
*
|
|
|
|
|
* This MUST match return value of `mw.loader#getCombinedVersion()` client-side.
|
|
|
|
|
*
|
|
|
|
|
* @since 1.28
|
|
|
|
|
* @param ResourceLoaderContext $context
|
|
|
|
|
* @param string[] $modules List of module names
|
|
|
|
|
* @return string Hash
|
|
|
|
|
*/
|
2016-09-07 21:39:22 +00:00
|
|
|
public function makeVersionQuery( ResourceLoaderContext $context ) {
|
2016-09-02 22:44:59 +00:00
|
|
|
// As of MediaWiki 1.28, the server and client use the same algorithm for combining
|
|
|
|
|
// version hashes. There is no technical reason for this to be same, and for years the
|
|
|
|
|
// implementations differed. If getCombinedVersion in PHP (used for StartupModule and
|
|
|
|
|
// E-Tag headers) differs in the future from getCombinedVersion in JS (used for 'version'
|
|
|
|
|
// query parameter), then this method must continue to match the JS one.
|
|
|
|
|
$moduleNames = [];
|
|
|
|
|
foreach ( $context->getModules() as $name ) {
|
|
|
|
|
if ( !$this->getModule( $name ) ) {
|
|
|
|
|
// If a versioned request contains a missing module, the version is a mismatch
|
|
|
|
|
// as the client considered a module (and version) we don't have.
|
|
|
|
|
return '';
|
|
|
|
|
}
|
|
|
|
|
$moduleNames[] = $name;
|
|
|
|
|
}
|
|
|
|
|
return $this->getCombinedVersion( $context, $moduleNames );
|
resourceloader: Replace timestamp system with version hashing
Modules now track their version via getVersionHash() instead of getModifiedTime().
== Background ==
While some resources have observeable timestamps (e.g. files stored on disk),
many other resources do not. E.g. config variables, and module definitions.
For static file modules, one can e.g. revert one of more files in a module to a
previous version and not affect the max timestamp.
Wiki modules include pages only if they exist. The user module supports common.js
and skin.js. By default neither exists. If a user has both, and then the
less-recently modified one is deleted, the max-timestamp remains unchanged.
For client-side caching, batch requests use "Math.max" on the relevant timestamps.
Again, if a module changes but another module is more recent (e.g. out-of-order
deployment, or out-of-order discovery), the change would not result in a cache miss.
More scenarios can be found in the associated Phabricator tasks.
== Version hash ==
Previously we virtually mapped these variables to a timestamp by storing the current
time alongside a hash of the value in ObjectCache. Considering the number of
possible request contexts (wikis * modules * users * skins * languages) this doesn't
work well. It results in needless cache invalidation when the first time observation
is purged due to LRU algorithms. It also has other minor bugs leading to fewer
cache hits.
All modules automatically get the benefits of version hashing with this change.
The old getDefinitionMtime() and getHashMtime() have been replaced with dummies
that return 1. These functions are often called from getModifiedTime() in subclasses.
For backward-compatibility, their respective values (definition summary and hash)
are now included in getVersionHash directly.
As examples, the following modules have been updated to use getVersionHash directly.
Other modules still work fine and can be updated later.
* ResourceLoaderFileModule
* ResourceLoaderEditToolbarModule
* ResourceLoaderStartUpModule
* ResourceLoaderWikiModule
The presence of hashes in place of timestamps increases the startup module size on
a default MediaWiki install from 4.4k to 5.8k (after gzip and minification).
== ETag ==
Since timestamps are no longer tracked, we need a different way to implement caching
for cache proxies (e.g. Varnish) and web browsers. Previously we used the
Last-Modified header (in combination with Cache-Control and Expires).
Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match).
Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default.
They instruct browsers to allow usage of partial Range requests. Since our responses
are dynamically generated, we need to use the Weak version of ETag.
While this sounds bad, it's no different than Last-Modified. As reassured by
RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the
specified behaviour behind Last-Modified follows the same "Weak" caching logic as
Entity tags. It's just that entity tags are capable of a stricter mode (whereas
Last-Modified is inherently weak).
== File cache ==
If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache
load.php responses. While the blind TTL handling (during the allowed expiry period)
is still maxage/timestamp based, tryRespondNotModified() now requires the caller to
know the expected ETag.
For this to work, the FileCache handling had to be moved from the top of
ResoureLoader::respond() to after the expected ETag is computed.
This also allows us to remove the duplicate tryRespondNotModified() handling since
that's is already handled by ResourceLoader::respond() meanwhile.
== Misc ==
* Remove redundant modifiedTime cache in ResourceLoaderFileModule.
* Change bugzilla references to Phabricator.
* Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this
logic was duplicated in each place the modified timestamp was used.
* It's easy to forget calling the parent class in getDefinitionSummary().
Previously this method only tracked 'class' by default. As such, various
extensions hardcoded that one value instead of calling the parent and extending
the array. To better prevent this in the future, getVersionHash() now asserts
that the '_cacheEpoch' property made it through.
* tests: Don't use getDefinitionSummary() as an API.
Fix ResourceLoaderWikiModuleTest to call getPages properly.
* In tests, the default timestamp used to be 1388534400000 (which is the unix time
of 20140101000000; the unit tests' CacheEpoch). The new version hash of these
modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of:
'{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}'
* Add sha1.js library for client-side hash generation.
Compared various different implementations for code size (after minfication/gzip),
and speed (when used for short hexidecimal strings).
https://jsperf.com/sha1-implementations
- CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k)
http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js
Chrome: 45k, Firefox: 89k, Safari: 92k
- jsSHA <https://github.com/Caligatio/jsSHA>
https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k)
Chrome: 65k, Firefox: 53k, Safari: 69k
- phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k)
https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js
Chrome: 200k, Firefox: 280k, Safari: 78k
Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous,
only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate
code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being
needed in the module loader, we'd have to load the fallback regardless. Considering
this is not used in a critical path for performance, it's not worth shipping two
implementations for this optimisation.
May also resolve:
* T44094
* T90411
* T94810
Bug: T94074
Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
|
|
|
}
|
|
|
|
|
|
2010-09-05 13:31:34 +00:00
|
|
|
/**
|
2014-03-07 16:50:57 +00:00
|
|
|
* Output a response to a load request, including the content-type header.
|
2010-09-04 04:00:09 +00:00
|
|
|
*
|
2014-03-07 16:50:57 +00:00
|
|
|
* @param ResourceLoaderContext $context Context in which a response should be formed
|
2010-09-04 04:00:09 +00:00
|
|
|
*/
|
2010-09-29 19:04:04 +00:00
|
|
|
public function respond( ResourceLoaderContext $context ) {
|
2010-12-10 17:06:00 +00:00
|
|
|
// Buffer output to catch warnings. Normally we'd use ob_clean() on the
|
|
|
|
|
// top-level output buffer to clear warnings, but that breaks when ob_gzhandler
|
|
|
|
|
// is used: ob_clean() will clear the GZIP header in that case and it won't come
|
|
|
|
|
// back for subsequent output, resulting in invalid GZIP. So we have to wrap
|
|
|
|
|
// the whole thing in our own output buffer to be sure the active buffer
|
|
|
|
|
// doesn't use ob_gzhandler.
|
2016-10-13 05:34:26 +00:00
|
|
|
// See https://bugs.php.net/bug.php?id=36514
|
2010-12-10 17:06:00 +00:00
|
|
|
ob_start();
|
2010-09-13 23:19:05 +00:00
|
|
|
|
2013-10-17 10:33:26 +00:00
|
|
|
// Find out which modules are missing and instantiate the others
|
2016-02-17 09:09:32 +00:00
|
|
|
$modules = [];
|
|
|
|
|
$missing = [];
|
2010-09-04 04:00:09 +00:00
|
|
|
foreach ( $context->getModules() as $name ) {
|
2014-04-03 23:09:09 +00:00
|
|
|
$module = $this->getModule( $name );
|
|
|
|
|
if ( $module ) {
|
2012-03-22 19:52:37 +00:00
|
|
|
// Do not allow private modules to be loaded from the web.
|
2017-02-20 22:44:19 +00:00
|
|
|
// This is a security issue, see T36907.
|
2012-03-22 19:52:37 +00:00
|
|
|
if ( $module->getGroup() === 'private' ) {
|
2015-06-04 03:53:23 +00:00
|
|
|
$this->logger->debug( "Request for private module '$name' denied" );
|
2014-11-11 20:00:17 +00:00
|
|
|
$this->errors[] = "Cannot show private module \"$name\"";
|
2012-03-22 19:52:37 +00:00
|
|
|
continue;
|
|
|
|
|
}
|
2013-03-06 00:24:57 +00:00
|
|
|
$modules[$name] = $module;
|
2010-09-04 04:00:09 +00:00
|
|
|
} else {
|
|
|
|
|
$missing[] = $name;
|
|
|
|
|
}
|
|
|
|
|
}
|
2010-09-04 12:53:01 +00:00
|
|
|
|
2010-12-23 20:14:18 +00:00
|
|
|
try {
|
2015-11-13 00:04:12 +00:00
|
|
|
// Preload for getCombinedVersion() and for batch makeModuleResponse()
|
2010-12-23 20:14:18 +00:00
|
|
|
$this->preloadModuleInfo( array_keys( $modules ), $context );
|
2013-04-27 12:02:08 +00:00
|
|
|
} catch ( Exception $e ) {
|
2016-12-03 03:57:42 +00:00
|
|
|
$this->outputErrorAndLog( $e, 'Preloading module info failed: {exception}' );
|
2010-12-23 20:14:18 +00:00
|
|
|
}
|
2010-09-23 21:23:51 +00:00
|
|
|
|
resourceloader: Replace timestamp system with version hashing
Modules now track their version via getVersionHash() instead of getModifiedTime().
== Background ==
While some resources have observeable timestamps (e.g. files stored on disk),
many other resources do not. E.g. config variables, and module definitions.
For static file modules, one can e.g. revert one of more files in a module to a
previous version and not affect the max timestamp.
Wiki modules include pages only if they exist. The user module supports common.js
and skin.js. By default neither exists. If a user has both, and then the
less-recently modified one is deleted, the max-timestamp remains unchanged.
For client-side caching, batch requests use "Math.max" on the relevant timestamps.
Again, if a module changes but another module is more recent (e.g. out-of-order
deployment, or out-of-order discovery), the change would not result in a cache miss.
More scenarios can be found in the associated Phabricator tasks.
== Version hash ==
Previously we virtually mapped these variables to a timestamp by storing the current
time alongside a hash of the value in ObjectCache. Considering the number of
possible request contexts (wikis * modules * users * skins * languages) this doesn't
work well. It results in needless cache invalidation when the first time observation
is purged due to LRU algorithms. It also has other minor bugs leading to fewer
cache hits.
All modules automatically get the benefits of version hashing with this change.
The old getDefinitionMtime() and getHashMtime() have been replaced with dummies
that return 1. These functions are often called from getModifiedTime() in subclasses.
For backward-compatibility, their respective values (definition summary and hash)
are now included in getVersionHash directly.
As examples, the following modules have been updated to use getVersionHash directly.
Other modules still work fine and can be updated later.
* ResourceLoaderFileModule
* ResourceLoaderEditToolbarModule
* ResourceLoaderStartUpModule
* ResourceLoaderWikiModule
The presence of hashes in place of timestamps increases the startup module size on
a default MediaWiki install from 4.4k to 5.8k (after gzip and minification).
== ETag ==
Since timestamps are no longer tracked, we need a different way to implement caching
for cache proxies (e.g. Varnish) and web browsers. Previously we used the
Last-Modified header (in combination with Cache-Control and Expires).
Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match).
Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default.
They instruct browsers to allow usage of partial Range requests. Since our responses
are dynamically generated, we need to use the Weak version of ETag.
While this sounds bad, it's no different than Last-Modified. As reassured by
RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the
specified behaviour behind Last-Modified follows the same "Weak" caching logic as
Entity tags. It's just that entity tags are capable of a stricter mode (whereas
Last-Modified is inherently weak).
== File cache ==
If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache
load.php responses. While the blind TTL handling (during the allowed expiry period)
is still maxage/timestamp based, tryRespondNotModified() now requires the caller to
know the expected ETag.
For this to work, the FileCache handling had to be moved from the top of
ResoureLoader::respond() to after the expected ETag is computed.
This also allows us to remove the duplicate tryRespondNotModified() handling since
that's is already handled by ResourceLoader::respond() meanwhile.
== Misc ==
* Remove redundant modifiedTime cache in ResourceLoaderFileModule.
* Change bugzilla references to Phabricator.
* Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this
logic was duplicated in each place the modified timestamp was used.
* It's easy to forget calling the parent class in getDefinitionSummary().
Previously this method only tracked 'class' by default. As such, various
extensions hardcoded that one value instead of calling the parent and extending
the array. To better prevent this in the future, getVersionHash() now asserts
that the '_cacheEpoch' property made it through.
* tests: Don't use getDefinitionSummary() as an API.
Fix ResourceLoaderWikiModuleTest to call getPages properly.
* In tests, the default timestamp used to be 1388534400000 (which is the unix time
of 20140101000000; the unit tests' CacheEpoch). The new version hash of these
modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of:
'{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}'
* Add sha1.js library for client-side hash generation.
Compared various different implementations for code size (after minfication/gzip),
and speed (when used for short hexidecimal strings).
https://jsperf.com/sha1-implementations
- CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k)
http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js
Chrome: 45k, Firefox: 89k, Safari: 92k
- jsSHA <https://github.com/Caligatio/jsSHA>
https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k)
Chrome: 65k, Firefox: 53k, Safari: 69k
- phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k)
https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js
Chrome: 200k, Firefox: 280k, Safari: 78k
Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous,
only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate
code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being
needed in the module loader, we'd have to load the fallback regardless. Considering
this is not used in a critical path for performance, it's not worth shipping two
implementations for this optimisation.
May also resolve:
* T44094
* T90411
* T94810
Bug: T94074
Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
|
|
|
// Combine versions to propagate cache invalidation
|
|
|
|
|
$versionHash = '';
|
|
|
|
|
try {
|
|
|
|
|
$versionHash = $this->getCombinedVersion( $context, array_keys( $modules ) );
|
|
|
|
|
} catch ( Exception $e ) {
|
2016-12-03 03:57:42 +00:00
|
|
|
$this->outputErrorAndLog( $e, 'Calculating version hash failed: {exception}' );
|
2010-09-04 08:38:45 +00:00
|
|
|
}
|
2010-10-20 00:22:25 +00:00
|
|
|
|
resourceloader: Replace timestamp system with version hashing
Modules now track their version via getVersionHash() instead of getModifiedTime().
== Background ==
While some resources have observeable timestamps (e.g. files stored on disk),
many other resources do not. E.g. config variables, and module definitions.
For static file modules, one can e.g. revert one of more files in a module to a
previous version and not affect the max timestamp.
Wiki modules include pages only if they exist. The user module supports common.js
and skin.js. By default neither exists. If a user has both, and then the
less-recently modified one is deleted, the max-timestamp remains unchanged.
For client-side caching, batch requests use "Math.max" on the relevant timestamps.
Again, if a module changes but another module is more recent (e.g. out-of-order
deployment, or out-of-order discovery), the change would not result in a cache miss.
More scenarios can be found in the associated Phabricator tasks.
== Version hash ==
Previously we virtually mapped these variables to a timestamp by storing the current
time alongside a hash of the value in ObjectCache. Considering the number of
possible request contexts (wikis * modules * users * skins * languages) this doesn't
work well. It results in needless cache invalidation when the first time observation
is purged due to LRU algorithms. It also has other minor bugs leading to fewer
cache hits.
All modules automatically get the benefits of version hashing with this change.
The old getDefinitionMtime() and getHashMtime() have been replaced with dummies
that return 1. These functions are often called from getModifiedTime() in subclasses.
For backward-compatibility, their respective values (definition summary and hash)
are now included in getVersionHash directly.
As examples, the following modules have been updated to use getVersionHash directly.
Other modules still work fine and can be updated later.
* ResourceLoaderFileModule
* ResourceLoaderEditToolbarModule
* ResourceLoaderStartUpModule
* ResourceLoaderWikiModule
The presence of hashes in place of timestamps increases the startup module size on
a default MediaWiki install from 4.4k to 5.8k (after gzip and minification).
== ETag ==
Since timestamps are no longer tracked, we need a different way to implement caching
for cache proxies (e.g. Varnish) and web browsers. Previously we used the
Last-Modified header (in combination with Cache-Control and Expires).
Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match).
Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default.
They instruct browsers to allow usage of partial Range requests. Since our responses
are dynamically generated, we need to use the Weak version of ETag.
While this sounds bad, it's no different than Last-Modified. As reassured by
RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the
specified behaviour behind Last-Modified follows the same "Weak" caching logic as
Entity tags. It's just that entity tags are capable of a stricter mode (whereas
Last-Modified is inherently weak).
== File cache ==
If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache
load.php responses. While the blind TTL handling (during the allowed expiry period)
is still maxage/timestamp based, tryRespondNotModified() now requires the caller to
know the expected ETag.
For this to work, the FileCache handling had to be moved from the top of
ResoureLoader::respond() to after the expected ETag is computed.
This also allows us to remove the duplicate tryRespondNotModified() handling since
that's is already handled by ResourceLoader::respond() meanwhile.
== Misc ==
* Remove redundant modifiedTime cache in ResourceLoaderFileModule.
* Change bugzilla references to Phabricator.
* Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this
logic was duplicated in each place the modified timestamp was used.
* It's easy to forget calling the parent class in getDefinitionSummary().
Previously this method only tracked 'class' by default. As such, various
extensions hardcoded that one value instead of calling the parent and extending
the array. To better prevent this in the future, getVersionHash() now asserts
that the '_cacheEpoch' property made it through.
* tests: Don't use getDefinitionSummary() as an API.
Fix ResourceLoaderWikiModuleTest to call getPages properly.
* In tests, the default timestamp used to be 1388534400000 (which is the unix time
of 20140101000000; the unit tests' CacheEpoch). The new version hash of these
modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of:
'{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}'
* Add sha1.js library for client-side hash generation.
Compared various different implementations for code size (after minfication/gzip),
and speed (when used for short hexidecimal strings).
https://jsperf.com/sha1-implementations
- CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k)
http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js
Chrome: 45k, Firefox: 89k, Safari: 92k
- jsSHA <https://github.com/Caligatio/jsSHA>
https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k)
Chrome: 65k, Firefox: 53k, Safari: 69k
- phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k)
https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js
Chrome: 200k, Firefox: 280k, Safari: 78k
Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous,
only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate
code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being
needed in the module loader, we'd have to load the fallback regardless. Considering
this is not used in a critical path for performance, it's not worth shipping two
implementations for this optimisation.
May also resolve:
* T44094
* T90411
* T94810
Bug: T94074
Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
|
|
|
// See RFC 2616 § 3.11 Entity Tags
|
2016-10-13 05:34:26 +00:00
|
|
|
// https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
|
resourceloader: Replace timestamp system with version hashing
Modules now track their version via getVersionHash() instead of getModifiedTime().
== Background ==
While some resources have observeable timestamps (e.g. files stored on disk),
many other resources do not. E.g. config variables, and module definitions.
For static file modules, one can e.g. revert one of more files in a module to a
previous version and not affect the max timestamp.
Wiki modules include pages only if they exist. The user module supports common.js
and skin.js. By default neither exists. If a user has both, and then the
less-recently modified one is deleted, the max-timestamp remains unchanged.
For client-side caching, batch requests use "Math.max" on the relevant timestamps.
Again, if a module changes but another module is more recent (e.g. out-of-order
deployment, or out-of-order discovery), the change would not result in a cache miss.
More scenarios can be found in the associated Phabricator tasks.
== Version hash ==
Previously we virtually mapped these variables to a timestamp by storing the current
time alongside a hash of the value in ObjectCache. Considering the number of
possible request contexts (wikis * modules * users * skins * languages) this doesn't
work well. It results in needless cache invalidation when the first time observation
is purged due to LRU algorithms. It also has other minor bugs leading to fewer
cache hits.
All modules automatically get the benefits of version hashing with this change.
The old getDefinitionMtime() and getHashMtime() have been replaced with dummies
that return 1. These functions are often called from getModifiedTime() in subclasses.
For backward-compatibility, their respective values (definition summary and hash)
are now included in getVersionHash directly.
As examples, the following modules have been updated to use getVersionHash directly.
Other modules still work fine and can be updated later.
* ResourceLoaderFileModule
* ResourceLoaderEditToolbarModule
* ResourceLoaderStartUpModule
* ResourceLoaderWikiModule
The presence of hashes in place of timestamps increases the startup module size on
a default MediaWiki install from 4.4k to 5.8k (after gzip and minification).
== ETag ==
Since timestamps are no longer tracked, we need a different way to implement caching
for cache proxies (e.g. Varnish) and web browsers. Previously we used the
Last-Modified header (in combination with Cache-Control and Expires).
Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match).
Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default.
They instruct browsers to allow usage of partial Range requests. Since our responses
are dynamically generated, we need to use the Weak version of ETag.
While this sounds bad, it's no different than Last-Modified. As reassured by
RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the
specified behaviour behind Last-Modified follows the same "Weak" caching logic as
Entity tags. It's just that entity tags are capable of a stricter mode (whereas
Last-Modified is inherently weak).
== File cache ==
If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache
load.php responses. While the blind TTL handling (during the allowed expiry period)
is still maxage/timestamp based, tryRespondNotModified() now requires the caller to
know the expected ETag.
For this to work, the FileCache handling had to be moved from the top of
ResoureLoader::respond() to after the expected ETag is computed.
This also allows us to remove the duplicate tryRespondNotModified() handling since
that's is already handled by ResourceLoader::respond() meanwhile.
== Misc ==
* Remove redundant modifiedTime cache in ResourceLoaderFileModule.
* Change bugzilla references to Phabricator.
* Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this
logic was duplicated in each place the modified timestamp was used.
* It's easy to forget calling the parent class in getDefinitionSummary().
Previously this method only tracked 'class' by default. As such, various
extensions hardcoded that one value instead of calling the parent and extending
the array. To better prevent this in the future, getVersionHash() now asserts
that the '_cacheEpoch' property made it through.
* tests: Don't use getDefinitionSummary() as an API.
Fix ResourceLoaderWikiModuleTest to call getPages properly.
* In tests, the default timestamp used to be 1388534400000 (which is the unix time
of 20140101000000; the unit tests' CacheEpoch). The new version hash of these
modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of:
'{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}'
* Add sha1.js library for client-side hash generation.
Compared various different implementations for code size (after minfication/gzip),
and speed (when used for short hexidecimal strings).
https://jsperf.com/sha1-implementations
- CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k)
http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js
Chrome: 45k, Firefox: 89k, Safari: 92k
- jsSHA <https://github.com/Caligatio/jsSHA>
https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k)
Chrome: 65k, Firefox: 53k, Safari: 69k
- phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k)
https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js
Chrome: 200k, Firefox: 280k, Safari: 78k
Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous,
only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate
code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being
needed in the module loader, we'd have to load the fallback regardless. Considering
this is not used in a critical path for performance, it's not worth shipping two
implementations for this optimisation.
May also resolve:
* T44094
* T90411
* T94810
Bug: T94074
Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
|
|
|
$etag = 'W/"' . $versionHash . '"';
|
|
|
|
|
|
|
|
|
|
// Try the client-side cache first
|
|
|
|
|
if ( $this->tryRespondNotModified( $context, $etag ) ) {
|
2011-10-01 04:15:07 +00:00
|
|
|
return; // output handled (buffers cleared)
|
|
|
|
|
}
|
|
|
|
|
|
resourceloader: Replace timestamp system with version hashing
Modules now track their version via getVersionHash() instead of getModifiedTime().
== Background ==
While some resources have observeable timestamps (e.g. files stored on disk),
many other resources do not. E.g. config variables, and module definitions.
For static file modules, one can e.g. revert one of more files in a module to a
previous version and not affect the max timestamp.
Wiki modules include pages only if they exist. The user module supports common.js
and skin.js. By default neither exists. If a user has both, and then the
less-recently modified one is deleted, the max-timestamp remains unchanged.
For client-side caching, batch requests use "Math.max" on the relevant timestamps.
Again, if a module changes but another module is more recent (e.g. out-of-order
deployment, or out-of-order discovery), the change would not result in a cache miss.
More scenarios can be found in the associated Phabricator tasks.
== Version hash ==
Previously we virtually mapped these variables to a timestamp by storing the current
time alongside a hash of the value in ObjectCache. Considering the number of
possible request contexts (wikis * modules * users * skins * languages) this doesn't
work well. It results in needless cache invalidation when the first time observation
is purged due to LRU algorithms. It also has other minor bugs leading to fewer
cache hits.
All modules automatically get the benefits of version hashing with this change.
The old getDefinitionMtime() and getHashMtime() have been replaced with dummies
that return 1. These functions are often called from getModifiedTime() in subclasses.
For backward-compatibility, their respective values (definition summary and hash)
are now included in getVersionHash directly.
As examples, the following modules have been updated to use getVersionHash directly.
Other modules still work fine and can be updated later.
* ResourceLoaderFileModule
* ResourceLoaderEditToolbarModule
* ResourceLoaderStartUpModule
* ResourceLoaderWikiModule
The presence of hashes in place of timestamps increases the startup module size on
a default MediaWiki install from 4.4k to 5.8k (after gzip and minification).
== ETag ==
Since timestamps are no longer tracked, we need a different way to implement caching
for cache proxies (e.g. Varnish) and web browsers. Previously we used the
Last-Modified header (in combination with Cache-Control and Expires).
Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match).
Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default.
They instruct browsers to allow usage of partial Range requests. Since our responses
are dynamically generated, we need to use the Weak version of ETag.
While this sounds bad, it's no different than Last-Modified. As reassured by
RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the
specified behaviour behind Last-Modified follows the same "Weak" caching logic as
Entity tags. It's just that entity tags are capable of a stricter mode (whereas
Last-Modified is inherently weak).
== File cache ==
If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache
load.php responses. While the blind TTL handling (during the allowed expiry period)
is still maxage/timestamp based, tryRespondNotModified() now requires the caller to
know the expected ETag.
For this to work, the FileCache handling had to be moved from the top of
ResoureLoader::respond() to after the expected ETag is computed.
This also allows us to remove the duplicate tryRespondNotModified() handling since
that's is already handled by ResourceLoader::respond() meanwhile.
== Misc ==
* Remove redundant modifiedTime cache in ResourceLoaderFileModule.
* Change bugzilla references to Phabricator.
* Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this
logic was duplicated in each place the modified timestamp was used.
* It's easy to forget calling the parent class in getDefinitionSummary().
Previously this method only tracked 'class' by default. As such, various
extensions hardcoded that one value instead of calling the parent and extending
the array. To better prevent this in the future, getVersionHash() now asserts
that the '_cacheEpoch' property made it through.
* tests: Don't use getDefinitionSummary() as an API.
Fix ResourceLoaderWikiModuleTest to call getPages properly.
* In tests, the default timestamp used to be 1388534400000 (which is the unix time
of 20140101000000; the unit tests' CacheEpoch). The new version hash of these
modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of:
'{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}'
* Add sha1.js library for client-side hash generation.
Compared various different implementations for code size (after minfication/gzip),
and speed (when used for short hexidecimal strings).
https://jsperf.com/sha1-implementations
- CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k)
http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js
Chrome: 45k, Firefox: 89k, Safari: 92k
- jsSHA <https://github.com/Caligatio/jsSHA>
https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k)
Chrome: 65k, Firefox: 53k, Safari: 69k
- phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k)
https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js
Chrome: 200k, Firefox: 280k, Safari: 78k
Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous,
only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate
code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being
needed in the module loader, we'd have to load the fallback regardless. Considering
this is not used in a critical path for performance, it's not worth shipping two
implementations for this optimisation.
May also resolve:
* T44094
* T90411
* T94810
Bug: T94074
Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
|
|
|
// Use file cache if enabled and available...
|
|
|
|
|
if ( $this->config->get( 'UseFileCache' ) ) {
|
|
|
|
|
$fileCache = ResourceFileCache::newFromContext( $context );
|
|
|
|
|
if ( $this->tryRespondFromFileCache( $fileCache, $context, $etag ) ) {
|
|
|
|
|
return; // output handled
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2011-10-01 04:15:07 +00:00
|
|
|
// Generate a response
|
|
|
|
|
$response = $this->makeModuleResponse( $context, $modules, $missing );
|
|
|
|
|
|
|
|
|
|
// Capture any PHP warnings from the output buffer and append them to the
|
2014-11-11 19:50:44 +00:00
|
|
|
// error list if we're in debug mode.
|
2015-11-01 19:56:20 +00:00
|
|
|
if ( $context->getDebug() ) {
|
|
|
|
|
$warnings = ob_get_contents();
|
|
|
|
|
if ( strlen( $warnings ) ) {
|
|
|
|
|
$this->errors[] = $warnings;
|
|
|
|
|
}
|
2014-11-11 19:50:44 +00:00
|
|
|
}
|
|
|
|
|
|
2012-03-22 19:52:37 +00:00
|
|
|
// Save response to file cache unless there are errors
|
2014-11-11 20:00:17 +00:00
|
|
|
if ( isset( $fileCache ) && !$this->errors && !count( $missing ) ) {
|
2014-11-11 19:50:44 +00:00
|
|
|
// Cache single modules and images...and other requests if there are enough hits
|
2011-10-02 17:53:33 +00:00
|
|
|
if ( ResourceFileCache::useFileCache( $context ) ) {
|
|
|
|
|
if ( $fileCache->isCacheWorthy() ) {
|
|
|
|
|
$fileCache->saveText( $response );
|
|
|
|
|
} else {
|
|
|
|
|
$fileCache->incrMissesRecent( $context->getRequest() );
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
resourceloader: Add support for modules sending preload headers
ResourceLoaderModule objects gain a new method getPreloadLinks() which
returns an array with the meta data required to build a Link rel=preload
header according to the current draft for W3C Preload.
<https://w3c.github.io/preload/>
Another implementation of this is already in use in OutputPage for
preloading the logo image.
This array is formatted by the ResourceLoaderModule::getHeaders method,
which is implemented as "final" at this time, thus restricting use to
the Link rel=preload header.
Headers are exposed and process-cached, like all other content
(scripts, styles, etc.), through ResourceLoaderModule::getModuleContent,
and aggregated by ResoureLoader::makeModuleResponse.
I had hoped for the getPreloadLinks to be stateless (not vary on $context).
Whether something should be preloaded and what, should not vary on the
skin or language. However, while that conceptually holds true, the exact
url for any given resource may still vary. Even the main use case for this
feature (T164299, preloading base modules request) require $context to pass
down skin and lang to the load.php url.
Add full test coverage and example documentation.
Bug: T164299
Change-Id: I2bfe0796ceaa0c82579c501f5b10e931f2175681
2017-07-18 02:36:01 +00:00
|
|
|
$this->sendResponseHeaders( $context, $etag, (bool)$this->errors, $this->extraHeaders );
|
2013-01-15 23:32:10 +00:00
|
|
|
|
2012-04-16 19:17:02 +00:00
|
|
|
// Remove the output buffer and output the response
|
|
|
|
|
ob_end_clean();
|
2014-11-11 20:00:17 +00:00
|
|
|
|
|
|
|
|
if ( $context->getImageObj() && $this->errors ) {
|
|
|
|
|
// We can't show both the error messages and the response when it's an image.
|
2015-09-26 20:32:31 +00:00
|
|
|
$response = implode( "\n\n", $this->errors );
|
2014-11-11 20:00:17 +00:00
|
|
|
} elseif ( $this->errors ) {
|
2015-09-15 03:17:47 +00:00
|
|
|
$errorText = implode( "\n\n", $this->errors );
|
|
|
|
|
$errorResponse = self::makeComment( $errorText );
|
|
|
|
|
if ( $context->shouldIncludeScripts() ) {
|
|
|
|
|
$errorResponse .= 'if (window.console && console.error) {'
|
2016-02-17 09:09:32 +00:00
|
|
|
. Xml::encodeJsCall( 'console.error', [ $errorText ] )
|
2015-09-15 03:17:47 +00:00
|
|
|
. "}\n";
|
2014-11-11 20:00:17 +00:00
|
|
|
}
|
2015-09-15 03:17:47 +00:00
|
|
|
|
|
|
|
|
// Prepend error info to the response
|
|
|
|
|
$response = $errorResponse . $response;
|
2014-11-11 20:00:17 +00:00
|
|
|
}
|
|
|
|
|
|
2016-02-17 09:09:32 +00:00
|
|
|
$this->errors = [];
|
2012-04-16 19:17:02 +00:00
|
|
|
echo $response;
|
2011-10-01 04:15:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
resourceloader: Replace timestamp system with version hashing
Modules now track their version via getVersionHash() instead of getModifiedTime().
== Background ==
While some resources have observeable timestamps (e.g. files stored on disk),
many other resources do not. E.g. config variables, and module definitions.
For static file modules, one can e.g. revert one of more files in a module to a
previous version and not affect the max timestamp.
Wiki modules include pages only if they exist. The user module supports common.js
and skin.js. By default neither exists. If a user has both, and then the
less-recently modified one is deleted, the max-timestamp remains unchanged.
For client-side caching, batch requests use "Math.max" on the relevant timestamps.
Again, if a module changes but another module is more recent (e.g. out-of-order
deployment, or out-of-order discovery), the change would not result in a cache miss.
More scenarios can be found in the associated Phabricator tasks.
== Version hash ==
Previously we virtually mapped these variables to a timestamp by storing the current
time alongside a hash of the value in ObjectCache. Considering the number of
possible request contexts (wikis * modules * users * skins * languages) this doesn't
work well. It results in needless cache invalidation when the first time observation
is purged due to LRU algorithms. It also has other minor bugs leading to fewer
cache hits.
All modules automatically get the benefits of version hashing with this change.
The old getDefinitionMtime() and getHashMtime() have been replaced with dummies
that return 1. These functions are often called from getModifiedTime() in subclasses.
For backward-compatibility, their respective values (definition summary and hash)
are now included in getVersionHash directly.
As examples, the following modules have been updated to use getVersionHash directly.
Other modules still work fine and can be updated later.
* ResourceLoaderFileModule
* ResourceLoaderEditToolbarModule
* ResourceLoaderStartUpModule
* ResourceLoaderWikiModule
The presence of hashes in place of timestamps increases the startup module size on
a default MediaWiki install from 4.4k to 5.8k (after gzip and minification).
== ETag ==
Since timestamps are no longer tracked, we need a different way to implement caching
for cache proxies (e.g. Varnish) and web browsers. Previously we used the
Last-Modified header (in combination with Cache-Control and Expires).
Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match).
Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default.
They instruct browsers to allow usage of partial Range requests. Since our responses
are dynamically generated, we need to use the Weak version of ETag.
While this sounds bad, it's no different than Last-Modified. As reassured by
RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the
specified behaviour behind Last-Modified follows the same "Weak" caching logic as
Entity tags. It's just that entity tags are capable of a stricter mode (whereas
Last-Modified is inherently weak).
== File cache ==
If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache
load.php responses. While the blind TTL handling (during the allowed expiry period)
is still maxage/timestamp based, tryRespondNotModified() now requires the caller to
know the expected ETag.
For this to work, the FileCache handling had to be moved from the top of
ResoureLoader::respond() to after the expected ETag is computed.
This also allows us to remove the duplicate tryRespondNotModified() handling since
that's is already handled by ResourceLoader::respond() meanwhile.
== Misc ==
* Remove redundant modifiedTime cache in ResourceLoaderFileModule.
* Change bugzilla references to Phabricator.
* Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this
logic was duplicated in each place the modified timestamp was used.
* It's easy to forget calling the parent class in getDefinitionSummary().
Previously this method only tracked 'class' by default. As such, various
extensions hardcoded that one value instead of calling the parent and extending
the array. To better prevent this in the future, getVersionHash() now asserts
that the '_cacheEpoch' property made it through.
* tests: Don't use getDefinitionSummary() as an API.
Fix ResourceLoaderWikiModuleTest to call getPages properly.
* In tests, the default timestamp used to be 1388534400000 (which is the unix time
of 20140101000000; the unit tests' CacheEpoch). The new version hash of these
modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of:
'{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}'
* Add sha1.js library for client-side hash generation.
Compared various different implementations for code size (after minfication/gzip),
and speed (when used for short hexidecimal strings).
https://jsperf.com/sha1-implementations
- CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k)
http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js
Chrome: 45k, Firefox: 89k, Safari: 92k
- jsSHA <https://github.com/Caligatio/jsSHA>
https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k)
Chrome: 65k, Firefox: 53k, Safari: 69k
- phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k)
https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js
Chrome: 200k, Firefox: 280k, Safari: 78k
Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous,
only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate
code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being
needed in the module loader, we'd have to load the fallback regardless. Considering
this is not used in a critical path for performance, it's not worth shipping two
implementations for this optimisation.
May also resolve:
* T44094
* T90411
* T94810
Bug: T94074
Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
|
|
|
* Send main response headers to the client.
|
|
|
|
|
*
|
|
|
|
|
* Deals with Content-Type, CORS (for stylesheets), and caching.
|
|
|
|
|
*
|
2014-03-07 16:50:57 +00:00
|
|
|
* @param ResourceLoaderContext $context
|
resourceloader: Replace timestamp system with version hashing
Modules now track their version via getVersionHash() instead of getModifiedTime().
== Background ==
While some resources have observeable timestamps (e.g. files stored on disk),
many other resources do not. E.g. config variables, and module definitions.
For static file modules, one can e.g. revert one of more files in a module to a
previous version and not affect the max timestamp.
Wiki modules include pages only if they exist. The user module supports common.js
and skin.js. By default neither exists. If a user has both, and then the
less-recently modified one is deleted, the max-timestamp remains unchanged.
For client-side caching, batch requests use "Math.max" on the relevant timestamps.
Again, if a module changes but another module is more recent (e.g. out-of-order
deployment, or out-of-order discovery), the change would not result in a cache miss.
More scenarios can be found in the associated Phabricator tasks.
== Version hash ==
Previously we virtually mapped these variables to a timestamp by storing the current
time alongside a hash of the value in ObjectCache. Considering the number of
possible request contexts (wikis * modules * users * skins * languages) this doesn't
work well. It results in needless cache invalidation when the first time observation
is purged due to LRU algorithms. It also has other minor bugs leading to fewer
cache hits.
All modules automatically get the benefits of version hashing with this change.
The old getDefinitionMtime() and getHashMtime() have been replaced with dummies
that return 1. These functions are often called from getModifiedTime() in subclasses.
For backward-compatibility, their respective values (definition summary and hash)
are now included in getVersionHash directly.
As examples, the following modules have been updated to use getVersionHash directly.
Other modules still work fine and can be updated later.
* ResourceLoaderFileModule
* ResourceLoaderEditToolbarModule
* ResourceLoaderStartUpModule
* ResourceLoaderWikiModule
The presence of hashes in place of timestamps increases the startup module size on
a default MediaWiki install from 4.4k to 5.8k (after gzip and minification).
== ETag ==
Since timestamps are no longer tracked, we need a different way to implement caching
for cache proxies (e.g. Varnish) and web browsers. Previously we used the
Last-Modified header (in combination with Cache-Control and Expires).
Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match).
Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default.
They instruct browsers to allow usage of partial Range requests. Since our responses
are dynamically generated, we need to use the Weak version of ETag.
While this sounds bad, it's no different than Last-Modified. As reassured by
RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the
specified behaviour behind Last-Modified follows the same "Weak" caching logic as
Entity tags. It's just that entity tags are capable of a stricter mode (whereas
Last-Modified is inherently weak).
== File cache ==
If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache
load.php responses. While the blind TTL handling (during the allowed expiry period)
is still maxage/timestamp based, tryRespondNotModified() now requires the caller to
know the expected ETag.
For this to work, the FileCache handling had to be moved from the top of
ResoureLoader::respond() to after the expected ETag is computed.
This also allows us to remove the duplicate tryRespondNotModified() handling since
that's is already handled by ResourceLoader::respond() meanwhile.
== Misc ==
* Remove redundant modifiedTime cache in ResourceLoaderFileModule.
* Change bugzilla references to Phabricator.
* Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this
logic was duplicated in each place the modified timestamp was used.
* It's easy to forget calling the parent class in getDefinitionSummary().
Previously this method only tracked 'class' by default. As such, various
extensions hardcoded that one value instead of calling the parent and extending
the array. To better prevent this in the future, getVersionHash() now asserts
that the '_cacheEpoch' property made it through.
* tests: Don't use getDefinitionSummary() as an API.
Fix ResourceLoaderWikiModuleTest to call getPages properly.
* In tests, the default timestamp used to be 1388534400000 (which is the unix time
of 20140101000000; the unit tests' CacheEpoch). The new version hash of these
modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of:
'{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}'
* Add sha1.js library for client-side hash generation.
Compared various different implementations for code size (after minfication/gzip),
and speed (when used for short hexidecimal strings).
https://jsperf.com/sha1-implementations
- CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k)
http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js
Chrome: 45k, Firefox: 89k, Safari: 92k
- jsSHA <https://github.com/Caligatio/jsSHA>
https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k)
Chrome: 65k, Firefox: 53k, Safari: 69k
- phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k)
https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js
Chrome: 200k, Firefox: 280k, Safari: 78k
Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous,
only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate
code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being
needed in the module loader, we'd have to load the fallback regardless. Considering
this is not used in a critical path for performance, it's not worth shipping two
implementations for this optimisation.
May also resolve:
* T44094
* T90411
* T94810
Bug: T94074
Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
|
|
|
* @param string $etag ETag header value
|
2014-11-11 20:00:17 +00:00
|
|
|
* @param bool $errors Whether there are errors in the response
|
resourceloader: Add support for modules sending preload headers
ResourceLoaderModule objects gain a new method getPreloadLinks() which
returns an array with the meta data required to build a Link rel=preload
header according to the current draft for W3C Preload.
<https://w3c.github.io/preload/>
Another implementation of this is already in use in OutputPage for
preloading the logo image.
This array is formatted by the ResourceLoaderModule::getHeaders method,
which is implemented as "final" at this time, thus restricting use to
the Link rel=preload header.
Headers are exposed and process-cached, like all other content
(scripts, styles, etc.), through ResourceLoaderModule::getModuleContent,
and aggregated by ResoureLoader::makeModuleResponse.
I had hoped for the getPreloadLinks to be stateless (not vary on $context).
Whether something should be preloaded and what, should not vary on the
skin or language. However, while that conceptually holds true, the exact
url for any given resource may still vary. Even the main use case for this
feature (T164299, preloading base modules request) require $context to pass
down skin and lang to the load.php url.
Add full test coverage and example documentation.
Bug: T164299
Change-Id: I2bfe0796ceaa0c82579c501f5b10e931f2175681
2017-07-18 02:36:01 +00:00
|
|
|
* @param string[] $extra Array of extra HTTP response headers
|
2012-01-12 19:41:18 +00:00
|
|
|
* @return void
|
2011-10-01 04:15:07 +00:00
|
|
|
*/
|
resourceloader: Add support for modules sending preload headers
ResourceLoaderModule objects gain a new method getPreloadLinks() which
returns an array with the meta data required to build a Link rel=preload
header according to the current draft for W3C Preload.
<https://w3c.github.io/preload/>
Another implementation of this is already in use in OutputPage for
preloading the logo image.
This array is formatted by the ResourceLoaderModule::getHeaders method,
which is implemented as "final" at this time, thus restricting use to
the Link rel=preload header.
Headers are exposed and process-cached, like all other content
(scripts, styles, etc.), through ResourceLoaderModule::getModuleContent,
and aggregated by ResoureLoader::makeModuleResponse.
I had hoped for the getPreloadLinks to be stateless (not vary on $context).
Whether something should be preloaded and what, should not vary on the
skin or language. However, while that conceptually holds true, the exact
url for any given resource may still vary. Even the main use case for this
feature (T164299, preloading base modules request) require $context to pass
down skin and lang to the load.php url.
Add full test coverage and example documentation.
Bug: T164299
Change-Id: I2bfe0796ceaa0c82579c501f5b10e931f2175681
2017-07-18 02:36:01 +00:00
|
|
|
protected function sendResponseHeaders(
|
|
|
|
|
ResourceLoaderContext $context, $etag, $errors, array $extra = []
|
|
|
|
|
) {
|
2017-02-20 05:29:54 +00:00
|
|
|
\MediaWiki\HeaderCallback::warnIfHeadersSent();
|
2014-08-07 10:25:56 +00:00
|
|
|
$rlMaxage = $this->config->get( 'ResourceLoaderMaxage' );
|
2016-09-02 22:44:59 +00:00
|
|
|
// Use a short cache expiry so that updates propagate to clients quickly, if:
|
|
|
|
|
// - No version specified (shared resources, e.g. stylesheets)
|
|
|
|
|
// - There were errors (recover quickly)
|
|
|
|
|
// - Version mismatch (T117587, T47877)
|
|
|
|
|
if ( is_null( $context->getVersion() )
|
|
|
|
|
|| $errors
|
2016-09-07 21:39:22 +00:00
|
|
|
|| $context->getVersion() !== $this->makeVersionQuery( $context )
|
2016-09-02 22:44:59 +00:00
|
|
|
) {
|
2014-08-07 10:25:56 +00:00
|
|
|
$maxage = $rlMaxage['unversioned']['client'];
|
|
|
|
|
$smaxage = $rlMaxage['unversioned']['server'];
|
2011-10-01 04:15:07 +00:00
|
|
|
// If a version was specified we can use a longer expiry time since changing
|
|
|
|
|
// version numbers causes cache misses
|
|
|
|
|
} else {
|
2014-08-07 10:25:56 +00:00
|
|
|
$maxage = $rlMaxage['versioned']['client'];
|
|
|
|
|
$smaxage = $rlMaxage['versioned']['server'];
|
2011-10-01 04:15:07 +00:00
|
|
|
}
|
2014-11-11 19:50:44 +00:00
|
|
|
if ( $context->getImageObj() ) {
|
2014-11-11 20:00:17 +00:00
|
|
|
// Output different headers if we're outputting textual errors.
|
2014-11-11 19:50:44 +00:00
|
|
|
if ( $errors ) {
|
|
|
|
|
header( 'Content-Type: text/plain; charset=utf-8' );
|
|
|
|
|
} else {
|
|
|
|
|
$context->getImageObj()->sendResponseHeaders( $context );
|
|
|
|
|
}
|
|
|
|
|
} elseif ( $context->getOnly() === 'styles' ) {
|
2011-04-01 20:48:50 +00:00
|
|
|
header( 'Content-Type: text/css; charset=utf-8' );
|
2013-04-21 14:38:23 +00:00
|
|
|
header( 'Access-Control-Allow-Origin: *' );
|
2010-11-03 07:58:03 +00:00
|
|
|
} else {
|
2011-04-01 20:48:50 +00:00
|
|
|
header( 'Content-Type: text/javascript; charset=utf-8' );
|
2010-11-03 07:58:03 +00:00
|
|
|
}
|
resourceloader: Replace timestamp system with version hashing
Modules now track their version via getVersionHash() instead of getModifiedTime().
== Background ==
While some resources have observeable timestamps (e.g. files stored on disk),
many other resources do not. E.g. config variables, and module definitions.
For static file modules, one can e.g. revert one of more files in a module to a
previous version and not affect the max timestamp.
Wiki modules include pages only if they exist. The user module supports common.js
and skin.js. By default neither exists. If a user has both, and then the
less-recently modified one is deleted, the max-timestamp remains unchanged.
For client-side caching, batch requests use "Math.max" on the relevant timestamps.
Again, if a module changes but another module is more recent (e.g. out-of-order
deployment, or out-of-order discovery), the change would not result in a cache miss.
More scenarios can be found in the associated Phabricator tasks.
== Version hash ==
Previously we virtually mapped these variables to a timestamp by storing the current
time alongside a hash of the value in ObjectCache. Considering the number of
possible request contexts (wikis * modules * users * skins * languages) this doesn't
work well. It results in needless cache invalidation when the first time observation
is purged due to LRU algorithms. It also has other minor bugs leading to fewer
cache hits.
All modules automatically get the benefits of version hashing with this change.
The old getDefinitionMtime() and getHashMtime() have been replaced with dummies
that return 1. These functions are often called from getModifiedTime() in subclasses.
For backward-compatibility, their respective values (definition summary and hash)
are now included in getVersionHash directly.
As examples, the following modules have been updated to use getVersionHash directly.
Other modules still work fine and can be updated later.
* ResourceLoaderFileModule
* ResourceLoaderEditToolbarModule
* ResourceLoaderStartUpModule
* ResourceLoaderWikiModule
The presence of hashes in place of timestamps increases the startup module size on
a default MediaWiki install from 4.4k to 5.8k (after gzip and minification).
== ETag ==
Since timestamps are no longer tracked, we need a different way to implement caching
for cache proxies (e.g. Varnish) and web browsers. Previously we used the
Last-Modified header (in combination with Cache-Control and Expires).
Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match).
Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default.
They instruct browsers to allow usage of partial Range requests. Since our responses
are dynamically generated, we need to use the Weak version of ETag.
While this sounds bad, it's no different than Last-Modified. As reassured by
RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the
specified behaviour behind Last-Modified follows the same "Weak" caching logic as
Entity tags. It's just that entity tags are capable of a stricter mode (whereas
Last-Modified is inherently weak).
== File cache ==
If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache
load.php responses. While the blind TTL handling (during the allowed expiry period)
is still maxage/timestamp based, tryRespondNotModified() now requires the caller to
know the expected ETag.
For this to work, the FileCache handling had to be moved from the top of
ResoureLoader::respond() to after the expected ETag is computed.
This also allows us to remove the duplicate tryRespondNotModified() handling since
that's is already handled by ResourceLoader::respond() meanwhile.
== Misc ==
* Remove redundant modifiedTime cache in ResourceLoaderFileModule.
* Change bugzilla references to Phabricator.
* Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this
logic was duplicated in each place the modified timestamp was used.
* It's easy to forget calling the parent class in getDefinitionSummary().
Previously this method only tracked 'class' by default. As such, various
extensions hardcoded that one value instead of calling the parent and extending
the array. To better prevent this in the future, getVersionHash() now asserts
that the '_cacheEpoch' property made it through.
* tests: Don't use getDefinitionSummary() as an API.
Fix ResourceLoaderWikiModuleTest to call getPages properly.
* In tests, the default timestamp used to be 1388534400000 (which is the unix time
of 20140101000000; the unit tests' CacheEpoch). The new version hash of these
modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of:
'{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}'
* Add sha1.js library for client-side hash generation.
Compared various different implementations for code size (after minfication/gzip),
and speed (when used for short hexidecimal strings).
https://jsperf.com/sha1-implementations
- CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k)
http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js
Chrome: 45k, Firefox: 89k, Safari: 92k
- jsSHA <https://github.com/Caligatio/jsSHA>
https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k)
Chrome: 65k, Firefox: 53k, Safari: 69k
- phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k)
https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js
Chrome: 200k, Firefox: 280k, Safari: 78k
Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous,
only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate
code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being
needed in the module loader, we'd have to load the fallback regardless. Considering
this is not used in a critical path for performance, it's not worth shipping two
implementations for this optimisation.
May also resolve:
* T44094
* T90411
* T94810
Bug: T94074
Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
|
|
|
// See RFC 2616 § 14.19 ETag
|
2016-10-13 05:34:26 +00:00
|
|
|
// https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
|
resourceloader: Replace timestamp system with version hashing
Modules now track their version via getVersionHash() instead of getModifiedTime().
== Background ==
While some resources have observeable timestamps (e.g. files stored on disk),
many other resources do not. E.g. config variables, and module definitions.
For static file modules, one can e.g. revert one of more files in a module to a
previous version and not affect the max timestamp.
Wiki modules include pages only if they exist. The user module supports common.js
and skin.js. By default neither exists. If a user has both, and then the
less-recently modified one is deleted, the max-timestamp remains unchanged.
For client-side caching, batch requests use "Math.max" on the relevant timestamps.
Again, if a module changes but another module is more recent (e.g. out-of-order
deployment, or out-of-order discovery), the change would not result in a cache miss.
More scenarios can be found in the associated Phabricator tasks.
== Version hash ==
Previously we virtually mapped these variables to a timestamp by storing the current
time alongside a hash of the value in ObjectCache. Considering the number of
possible request contexts (wikis * modules * users * skins * languages) this doesn't
work well. It results in needless cache invalidation when the first time observation
is purged due to LRU algorithms. It also has other minor bugs leading to fewer
cache hits.
All modules automatically get the benefits of version hashing with this change.
The old getDefinitionMtime() and getHashMtime() have been replaced with dummies
that return 1. These functions are often called from getModifiedTime() in subclasses.
For backward-compatibility, their respective values (definition summary and hash)
are now included in getVersionHash directly.
As examples, the following modules have been updated to use getVersionHash directly.
Other modules still work fine and can be updated later.
* ResourceLoaderFileModule
* ResourceLoaderEditToolbarModule
* ResourceLoaderStartUpModule
* ResourceLoaderWikiModule
The presence of hashes in place of timestamps increases the startup module size on
a default MediaWiki install from 4.4k to 5.8k (after gzip and minification).
== ETag ==
Since timestamps are no longer tracked, we need a different way to implement caching
for cache proxies (e.g. Varnish) and web browsers. Previously we used the
Last-Modified header (in combination with Cache-Control and Expires).
Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match).
Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default.
They instruct browsers to allow usage of partial Range requests. Since our responses
are dynamically generated, we need to use the Weak version of ETag.
While this sounds bad, it's no different than Last-Modified. As reassured by
RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the
specified behaviour behind Last-Modified follows the same "Weak" caching logic as
Entity tags. It's just that entity tags are capable of a stricter mode (whereas
Last-Modified is inherently weak).
== File cache ==
If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache
load.php responses. While the blind TTL handling (during the allowed expiry period)
is still maxage/timestamp based, tryRespondNotModified() now requires the caller to
know the expected ETag.
For this to work, the FileCache handling had to be moved from the top of
ResoureLoader::respond() to after the expected ETag is computed.
This also allows us to remove the duplicate tryRespondNotModified() handling since
that's is already handled by ResourceLoader::respond() meanwhile.
== Misc ==
* Remove redundant modifiedTime cache in ResourceLoaderFileModule.
* Change bugzilla references to Phabricator.
* Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this
logic was duplicated in each place the modified timestamp was used.
* It's easy to forget calling the parent class in getDefinitionSummary().
Previously this method only tracked 'class' by default. As such, various
extensions hardcoded that one value instead of calling the parent and extending
the array. To better prevent this in the future, getVersionHash() now asserts
that the '_cacheEpoch' property made it through.
* tests: Don't use getDefinitionSummary() as an API.
Fix ResourceLoaderWikiModuleTest to call getPages properly.
* In tests, the default timestamp used to be 1388534400000 (which is the unix time
of 20140101000000; the unit tests' CacheEpoch). The new version hash of these
modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of:
'{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}'
* Add sha1.js library for client-side hash generation.
Compared various different implementations for code size (after minfication/gzip),
and speed (when used for short hexidecimal strings).
https://jsperf.com/sha1-implementations
- CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k)
http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js
Chrome: 45k, Firefox: 89k, Safari: 92k
- jsSHA <https://github.com/Caligatio/jsSHA>
https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k)
Chrome: 65k, Firefox: 53k, Safari: 69k
- phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k)
https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js
Chrome: 200k, Firefox: 280k, Safari: 78k
Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous,
only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate
code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being
needed in the module loader, we'd have to load the fallback regardless. Considering
this is not used in a critical path for performance, it's not worth shipping two
implementations for this optimisation.
May also resolve:
* T44094
* T90411
* T94810
Bug: T94074
Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
|
|
|
header( 'ETag: ' . $etag );
|
2010-11-01 20:48:30 +00:00
|
|
|
if ( $context->getDebug() ) {
|
2011-01-19 19:31:14 +00:00
|
|
|
// Do not cache debug responses
|
|
|
|
|
header( 'Cache-Control: private, no-cache, must-revalidate' );
|
|
|
|
|
header( 'Pragma: no-cache' );
|
2010-11-01 20:48:30 +00:00
|
|
|
} else {
|
2015-08-11 01:13:45 +00:00
|
|
|
header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
|
2012-03-22 19:52:37 +00:00
|
|
|
$exp = min( $maxage, $smaxage );
|
2011-01-19 19:31:14 +00:00
|
|
|
header( 'Expires: ' . wfTimestamp( TS_RFC2822, $exp + time() ) );
|
2010-11-01 20:48:30 +00:00
|
|
|
}
|
resourceloader: Add support for modules sending preload headers
ResourceLoaderModule objects gain a new method getPreloadLinks() which
returns an array with the meta data required to build a Link rel=preload
header according to the current draft for W3C Preload.
<https://w3c.github.io/preload/>
Another implementation of this is already in use in OutputPage for
preloading the logo image.
This array is formatted by the ResourceLoaderModule::getHeaders method,
which is implemented as "final" at this time, thus restricting use to
the Link rel=preload header.
Headers are exposed and process-cached, like all other content
(scripts, styles, etc.), through ResourceLoaderModule::getModuleContent,
and aggregated by ResoureLoader::makeModuleResponse.
I had hoped for the getPreloadLinks to be stateless (not vary on $context).
Whether something should be preloaded and what, should not vary on the
skin or language. However, while that conceptually holds true, the exact
url for any given resource may still vary. Even the main use case for this
feature (T164299, preloading base modules request) require $context to pass
down skin and lang to the load.php url.
Add full test coverage and example documentation.
Bug: T164299
Change-Id: I2bfe0796ceaa0c82579c501f5b10e931f2175681
2017-07-18 02:36:01 +00:00
|
|
|
foreach ( $extra as $header ) {
|
|
|
|
|
header( $header );
|
|
|
|
|
}
|
2011-10-01 04:15:07 +00:00
|
|
|
}
|
2010-09-04 12:53:01 +00:00
|
|
|
|
2011-10-01 04:15:07 +00:00
|
|
|
/**
|
resourceloader: Replace timestamp system with version hashing
Modules now track their version via getVersionHash() instead of getModifiedTime().
== Background ==
While some resources have observeable timestamps (e.g. files stored on disk),
many other resources do not. E.g. config variables, and module definitions.
For static file modules, one can e.g. revert one of more files in a module to a
previous version and not affect the max timestamp.
Wiki modules include pages only if they exist. The user module supports common.js
and skin.js. By default neither exists. If a user has both, and then the
less-recently modified one is deleted, the max-timestamp remains unchanged.
For client-side caching, batch requests use "Math.max" on the relevant timestamps.
Again, if a module changes but another module is more recent (e.g. out-of-order
deployment, or out-of-order discovery), the change would not result in a cache miss.
More scenarios can be found in the associated Phabricator tasks.
== Version hash ==
Previously we virtually mapped these variables to a timestamp by storing the current
time alongside a hash of the value in ObjectCache. Considering the number of
possible request contexts (wikis * modules * users * skins * languages) this doesn't
work well. It results in needless cache invalidation when the first time observation
is purged due to LRU algorithms. It also has other minor bugs leading to fewer
cache hits.
All modules automatically get the benefits of version hashing with this change.
The old getDefinitionMtime() and getHashMtime() have been replaced with dummies
that return 1. These functions are often called from getModifiedTime() in subclasses.
For backward-compatibility, their respective values (definition summary and hash)
are now included in getVersionHash directly.
As examples, the following modules have been updated to use getVersionHash directly.
Other modules still work fine and can be updated later.
* ResourceLoaderFileModule
* ResourceLoaderEditToolbarModule
* ResourceLoaderStartUpModule
* ResourceLoaderWikiModule
The presence of hashes in place of timestamps increases the startup module size on
a default MediaWiki install from 4.4k to 5.8k (after gzip and minification).
== ETag ==
Since timestamps are no longer tracked, we need a different way to implement caching
for cache proxies (e.g. Varnish) and web browsers. Previously we used the
Last-Modified header (in combination with Cache-Control and Expires).
Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match).
Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default.
They instruct browsers to allow usage of partial Range requests. Since our responses
are dynamically generated, we need to use the Weak version of ETag.
While this sounds bad, it's no different than Last-Modified. As reassured by
RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the
specified behaviour behind Last-Modified follows the same "Weak" caching logic as
Entity tags. It's just that entity tags are capable of a stricter mode (whereas
Last-Modified is inherently weak).
== File cache ==
If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache
load.php responses. While the blind TTL handling (during the allowed expiry period)
is still maxage/timestamp based, tryRespondNotModified() now requires the caller to
know the expected ETag.
For this to work, the FileCache handling had to be moved from the top of
ResoureLoader::respond() to after the expected ETag is computed.
This also allows us to remove the duplicate tryRespondNotModified() handling since
that's is already handled by ResourceLoader::respond() meanwhile.
== Misc ==
* Remove redundant modifiedTime cache in ResourceLoaderFileModule.
* Change bugzilla references to Phabricator.
* Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this
logic was duplicated in each place the modified timestamp was used.
* It's easy to forget calling the parent class in getDefinitionSummary().
Previously this method only tracked 'class' by default. As such, various
extensions hardcoded that one value instead of calling the parent and extending
the array. To better prevent this in the future, getVersionHash() now asserts
that the '_cacheEpoch' property made it through.
* tests: Don't use getDefinitionSummary() as an API.
Fix ResourceLoaderWikiModuleTest to call getPages properly.
* In tests, the default timestamp used to be 1388534400000 (which is the unix time
of 20140101000000; the unit tests' CacheEpoch). The new version hash of these
modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of:
'{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}'
* Add sha1.js library for client-side hash generation.
Compared various different implementations for code size (after minfication/gzip),
and speed (when used for short hexidecimal strings).
https://jsperf.com/sha1-implementations
- CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k)
http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js
Chrome: 45k, Firefox: 89k, Safari: 92k
- jsSHA <https://github.com/Caligatio/jsSHA>
https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k)
Chrome: 65k, Firefox: 53k, Safari: 69k
- phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k)
https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js
Chrome: 200k, Firefox: 280k, Safari: 78k
Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous,
only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate
code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being
needed in the module loader, we'd have to load the fallback regardless. Considering
this is not used in a critical path for performance, it's not worth shipping two
implementations for this optimisation.
May also resolve:
* T44094
* T90411
* T94810
Bug: T94074
Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
|
|
|
* Respond with HTTP 304 Not Modified if appropiate.
|
2014-03-07 16:50:57 +00:00
|
|
|
*
|
resourceloader: Replace timestamp system with version hashing
Modules now track their version via getVersionHash() instead of getModifiedTime().
== Background ==
While some resources have observeable timestamps (e.g. files stored on disk),
many other resources do not. E.g. config variables, and module definitions.
For static file modules, one can e.g. revert one of more files in a module to a
previous version and not affect the max timestamp.
Wiki modules include pages only if they exist. The user module supports common.js
and skin.js. By default neither exists. If a user has both, and then the
less-recently modified one is deleted, the max-timestamp remains unchanged.
For client-side caching, batch requests use "Math.max" on the relevant timestamps.
Again, if a module changes but another module is more recent (e.g. out-of-order
deployment, or out-of-order discovery), the change would not result in a cache miss.
More scenarios can be found in the associated Phabricator tasks.
== Version hash ==
Previously we virtually mapped these variables to a timestamp by storing the current
time alongside a hash of the value in ObjectCache. Considering the number of
possible request contexts (wikis * modules * users * skins * languages) this doesn't
work well. It results in needless cache invalidation when the first time observation
is purged due to LRU algorithms. It also has other minor bugs leading to fewer
cache hits.
All modules automatically get the benefits of version hashing with this change.
The old getDefinitionMtime() and getHashMtime() have been replaced with dummies
that return 1. These functions are often called from getModifiedTime() in subclasses.
For backward-compatibility, their respective values (definition summary and hash)
are now included in getVersionHash directly.
As examples, the following modules have been updated to use getVersionHash directly.
Other modules still work fine and can be updated later.
* ResourceLoaderFileModule
* ResourceLoaderEditToolbarModule
* ResourceLoaderStartUpModule
* ResourceLoaderWikiModule
The presence of hashes in place of timestamps increases the startup module size on
a default MediaWiki install from 4.4k to 5.8k (after gzip and minification).
== ETag ==
Since timestamps are no longer tracked, we need a different way to implement caching
for cache proxies (e.g. Varnish) and web browsers. Previously we used the
Last-Modified header (in combination with Cache-Control and Expires).
Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match).
Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default.
They instruct browsers to allow usage of partial Range requests. Since our responses
are dynamically generated, we need to use the Weak version of ETag.
While this sounds bad, it's no different than Last-Modified. As reassured by
RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the
specified behaviour behind Last-Modified follows the same "Weak" caching logic as
Entity tags. It's just that entity tags are capable of a stricter mode (whereas
Last-Modified is inherently weak).
== File cache ==
If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache
load.php responses. While the blind TTL handling (during the allowed expiry period)
is still maxage/timestamp based, tryRespondNotModified() now requires the caller to
know the expected ETag.
For this to work, the FileCache handling had to be moved from the top of
ResoureLoader::respond() to after the expected ETag is computed.
This also allows us to remove the duplicate tryRespondNotModified() handling since
that's is already handled by ResourceLoader::respond() meanwhile.
== Misc ==
* Remove redundant modifiedTime cache in ResourceLoaderFileModule.
* Change bugzilla references to Phabricator.
* Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this
logic was duplicated in each place the modified timestamp was used.
* It's easy to forget calling the parent class in getDefinitionSummary().
Previously this method only tracked 'class' by default. As such, various
extensions hardcoded that one value instead of calling the parent and extending
the array. To better prevent this in the future, getVersionHash() now asserts
that the '_cacheEpoch' property made it through.
* tests: Don't use getDefinitionSummary() as an API.
Fix ResourceLoaderWikiModuleTest to call getPages properly.
* In tests, the default timestamp used to be 1388534400000 (which is the unix time
of 20140101000000; the unit tests' CacheEpoch). The new version hash of these
modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of:
'{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}'
* Add sha1.js library for client-side hash generation.
Compared various different implementations for code size (after minfication/gzip),
and speed (when used for short hexidecimal strings).
https://jsperf.com/sha1-implementations
- CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k)
http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js
Chrome: 45k, Firefox: 89k, Safari: 92k
- jsSHA <https://github.com/Caligatio/jsSHA>
https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k)
Chrome: 65k, Firefox: 53k, Safari: 69k
- phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k)
https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js
Chrome: 200k, Firefox: 280k, Safari: 78k
Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous,
only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate
code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being
needed in the module loader, we'd have to load the fallback regardless. Considering
this is not used in a critical path for performance, it's not worth shipping two
implementations for this optimisation.
May also resolve:
* T44094
* T90411
* T94810
Bug: T94074
Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
|
|
|
* If there's an If-None-Match header, respond with a 304 appropriately
|
2011-10-01 04:15:07 +00:00
|
|
|
* and clear out the output buffer. If the client cache is too old then do nothing.
|
2014-03-07 16:50:57 +00:00
|
|
|
*
|
2014-04-20 21:33:05 +00:00
|
|
|
* @param ResourceLoaderContext $context
|
resourceloader: Replace timestamp system with version hashing
Modules now track their version via getVersionHash() instead of getModifiedTime().
== Background ==
While some resources have observeable timestamps (e.g. files stored on disk),
many other resources do not. E.g. config variables, and module definitions.
For static file modules, one can e.g. revert one of more files in a module to a
previous version and not affect the max timestamp.
Wiki modules include pages only if they exist. The user module supports common.js
and skin.js. By default neither exists. If a user has both, and then the
less-recently modified one is deleted, the max-timestamp remains unchanged.
For client-side caching, batch requests use "Math.max" on the relevant timestamps.
Again, if a module changes but another module is more recent (e.g. out-of-order
deployment, or out-of-order discovery), the change would not result in a cache miss.
More scenarios can be found in the associated Phabricator tasks.
== Version hash ==
Previously we virtually mapped these variables to a timestamp by storing the current
time alongside a hash of the value in ObjectCache. Considering the number of
possible request contexts (wikis * modules * users * skins * languages) this doesn't
work well. It results in needless cache invalidation when the first time observation
is purged due to LRU algorithms. It also has other minor bugs leading to fewer
cache hits.
All modules automatically get the benefits of version hashing with this change.
The old getDefinitionMtime() and getHashMtime() have been replaced with dummies
that return 1. These functions are often called from getModifiedTime() in subclasses.
For backward-compatibility, their respective values (definition summary and hash)
are now included in getVersionHash directly.
As examples, the following modules have been updated to use getVersionHash directly.
Other modules still work fine and can be updated later.
* ResourceLoaderFileModule
* ResourceLoaderEditToolbarModule
* ResourceLoaderStartUpModule
* ResourceLoaderWikiModule
The presence of hashes in place of timestamps increases the startup module size on
a default MediaWiki install from 4.4k to 5.8k (after gzip and minification).
== ETag ==
Since timestamps are no longer tracked, we need a different way to implement caching
for cache proxies (e.g. Varnish) and web browsers. Previously we used the
Last-Modified header (in combination with Cache-Control and Expires).
Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match).
Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default.
They instruct browsers to allow usage of partial Range requests. Since our responses
are dynamically generated, we need to use the Weak version of ETag.
While this sounds bad, it's no different than Last-Modified. As reassured by
RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the
specified behaviour behind Last-Modified follows the same "Weak" caching logic as
Entity tags. It's just that entity tags are capable of a stricter mode (whereas
Last-Modified is inherently weak).
== File cache ==
If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache
load.php responses. While the blind TTL handling (during the allowed expiry period)
is still maxage/timestamp based, tryRespondNotModified() now requires the caller to
know the expected ETag.
For this to work, the FileCache handling had to be moved from the top of
ResoureLoader::respond() to after the expected ETag is computed.
This also allows us to remove the duplicate tryRespondNotModified() handling since
that's is already handled by ResourceLoader::respond() meanwhile.
== Misc ==
* Remove redundant modifiedTime cache in ResourceLoaderFileModule.
* Change bugzilla references to Phabricator.
* Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this
logic was duplicated in each place the modified timestamp was used.
* It's easy to forget calling the parent class in getDefinitionSummary().
Previously this method only tracked 'class' by default. As such, various
extensions hardcoded that one value instead of calling the parent and extending
the array. To better prevent this in the future, getVersionHash() now asserts
that the '_cacheEpoch' property made it through.
* tests: Don't use getDefinitionSummary() as an API.
Fix ResourceLoaderWikiModuleTest to call getPages properly.
* In tests, the default timestamp used to be 1388534400000 (which is the unix time
of 20140101000000; the unit tests' CacheEpoch). The new version hash of these
modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of:
'{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}'
* Add sha1.js library for client-side hash generation.
Compared various different implementations for code size (after minfication/gzip),
and speed (when used for short hexidecimal strings).
https://jsperf.com/sha1-implementations
- CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k)
http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js
Chrome: 45k, Firefox: 89k, Safari: 92k
- jsSHA <https://github.com/Caligatio/jsSHA>
https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k)
Chrome: 65k, Firefox: 53k, Safari: 69k
- phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k)
https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js
Chrome: 200k, Firefox: 280k, Safari: 78k
Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous,
only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate
code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being
needed in the module loader, we'd have to load the fallback regardless. Considering
this is not used in a critical path for performance, it's not worth shipping two
implementations for this optimisation.
May also resolve:
* T44094
* T90411
* T94810
Bug: T94074
Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
|
|
|
* @param string $etag ETag header value
|
|
|
|
|
* @return bool True if HTTP 304 was sent and output handled
|
2011-10-01 04:15:07 +00:00
|
|
|
*/
|
resourceloader: Replace timestamp system with version hashing
Modules now track their version via getVersionHash() instead of getModifiedTime().
== Background ==
While some resources have observeable timestamps (e.g. files stored on disk),
many other resources do not. E.g. config variables, and module definitions.
For static file modules, one can e.g. revert one of more files in a module to a
previous version and not affect the max timestamp.
Wiki modules include pages only if they exist. The user module supports common.js
and skin.js. By default neither exists. If a user has both, and then the
less-recently modified one is deleted, the max-timestamp remains unchanged.
For client-side caching, batch requests use "Math.max" on the relevant timestamps.
Again, if a module changes but another module is more recent (e.g. out-of-order
deployment, or out-of-order discovery), the change would not result in a cache miss.
More scenarios can be found in the associated Phabricator tasks.
== Version hash ==
Previously we virtually mapped these variables to a timestamp by storing the current
time alongside a hash of the value in ObjectCache. Considering the number of
possible request contexts (wikis * modules * users * skins * languages) this doesn't
work well. It results in needless cache invalidation when the first time observation
is purged due to LRU algorithms. It also has other minor bugs leading to fewer
cache hits.
All modules automatically get the benefits of version hashing with this change.
The old getDefinitionMtime() and getHashMtime() have been replaced with dummies
that return 1. These functions are often called from getModifiedTime() in subclasses.
For backward-compatibility, their respective values (definition summary and hash)
are now included in getVersionHash directly.
As examples, the following modules have been updated to use getVersionHash directly.
Other modules still work fine and can be updated later.
* ResourceLoaderFileModule
* ResourceLoaderEditToolbarModule
* ResourceLoaderStartUpModule
* ResourceLoaderWikiModule
The presence of hashes in place of timestamps increases the startup module size on
a default MediaWiki install from 4.4k to 5.8k (after gzip and minification).
== ETag ==
Since timestamps are no longer tracked, we need a different way to implement caching
for cache proxies (e.g. Varnish) and web browsers. Previously we used the
Last-Modified header (in combination with Cache-Control and Expires).
Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match).
Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default.
They instruct browsers to allow usage of partial Range requests. Since our responses
are dynamically generated, we need to use the Weak version of ETag.
While this sounds bad, it's no different than Last-Modified. As reassured by
RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the
specified behaviour behind Last-Modified follows the same "Weak" caching logic as
Entity tags. It's just that entity tags are capable of a stricter mode (whereas
Last-Modified is inherently weak).
== File cache ==
If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache
load.php responses. While the blind TTL handling (during the allowed expiry period)
is still maxage/timestamp based, tryRespondNotModified() now requires the caller to
know the expected ETag.
For this to work, the FileCache handling had to be moved from the top of
ResoureLoader::respond() to after the expected ETag is computed.
This also allows us to remove the duplicate tryRespondNotModified() handling since
that's is already handled by ResourceLoader::respond() meanwhile.
== Misc ==
* Remove redundant modifiedTime cache in ResourceLoaderFileModule.
* Change bugzilla references to Phabricator.
* Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this
logic was duplicated in each place the modified timestamp was used.
* It's easy to forget calling the parent class in getDefinitionSummary().
Previously this method only tracked 'class' by default. As such, various
extensions hardcoded that one value instead of calling the parent and extending
the array. To better prevent this in the future, getVersionHash() now asserts
that the '_cacheEpoch' property made it through.
* tests: Don't use getDefinitionSummary() as an API.
Fix ResourceLoaderWikiModuleTest to call getPages properly.
* In tests, the default timestamp used to be 1388534400000 (which is the unix time
of 20140101000000; the unit tests' CacheEpoch). The new version hash of these
modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of:
'{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}'
* Add sha1.js library for client-side hash generation.
Compared various different implementations for code size (after minfication/gzip),
and speed (when used for short hexidecimal strings).
https://jsperf.com/sha1-implementations
- CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k)
http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js
Chrome: 45k, Firefox: 89k, Safari: 92k
- jsSHA <https://github.com/Caligatio/jsSHA>
https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k)
Chrome: 65k, Firefox: 53k, Safari: 69k
- phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k)
https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js
Chrome: 200k, Firefox: 280k, Safari: 78k
Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous,
only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate
code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being
needed in the module loader, we'd have to load the fallback regardless. Considering
this is not used in a critical path for performance, it's not worth shipping two
implementations for this optimisation.
May also resolve:
* T44094
* T90411
* T94810
Bug: T94074
Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
|
|
|
protected function tryRespondNotModified( ResourceLoaderContext $context, $etag ) {
|
|
|
|
|
// See RFC 2616 § 14.26 If-None-Match
|
2016-10-13 05:34:26 +00:00
|
|
|
// https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
|
resourceloader: Replace timestamp system with version hashing
Modules now track their version via getVersionHash() instead of getModifiedTime().
== Background ==
While some resources have observeable timestamps (e.g. files stored on disk),
many other resources do not. E.g. config variables, and module definitions.
For static file modules, one can e.g. revert one of more files in a module to a
previous version and not affect the max timestamp.
Wiki modules include pages only if they exist. The user module supports common.js
and skin.js. By default neither exists. If a user has both, and then the
less-recently modified one is deleted, the max-timestamp remains unchanged.
For client-side caching, batch requests use "Math.max" on the relevant timestamps.
Again, if a module changes but another module is more recent (e.g. out-of-order
deployment, or out-of-order discovery), the change would not result in a cache miss.
More scenarios can be found in the associated Phabricator tasks.
== Version hash ==
Previously we virtually mapped these variables to a timestamp by storing the current
time alongside a hash of the value in ObjectCache. Considering the number of
possible request contexts (wikis * modules * users * skins * languages) this doesn't
work well. It results in needless cache invalidation when the first time observation
is purged due to LRU algorithms. It also has other minor bugs leading to fewer
cache hits.
All modules automatically get the benefits of version hashing with this change.
The old getDefinitionMtime() and getHashMtime() have been replaced with dummies
that return 1. These functions are often called from getModifiedTime() in subclasses.
For backward-compatibility, their respective values (definition summary and hash)
are now included in getVersionHash directly.
As examples, the following modules have been updated to use getVersionHash directly.
Other modules still work fine and can be updated later.
* ResourceLoaderFileModule
* ResourceLoaderEditToolbarModule
* ResourceLoaderStartUpModule
* ResourceLoaderWikiModule
The presence of hashes in place of timestamps increases the startup module size on
a default MediaWiki install from 4.4k to 5.8k (after gzip and minification).
== ETag ==
Since timestamps are no longer tracked, we need a different way to implement caching
for cache proxies (e.g. Varnish) and web browsers. Previously we used the
Last-Modified header (in combination with Cache-Control and Expires).
Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match).
Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default.
They instruct browsers to allow usage of partial Range requests. Since our responses
are dynamically generated, we need to use the Weak version of ETag.
While this sounds bad, it's no different than Last-Modified. As reassured by
RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the
specified behaviour behind Last-Modified follows the same "Weak" caching logic as
Entity tags. It's just that entity tags are capable of a stricter mode (whereas
Last-Modified is inherently weak).
== File cache ==
If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache
load.php responses. While the blind TTL handling (during the allowed expiry period)
is still maxage/timestamp based, tryRespondNotModified() now requires the caller to
know the expected ETag.
For this to work, the FileCache handling had to be moved from the top of
ResoureLoader::respond() to after the expected ETag is computed.
This also allows us to remove the duplicate tryRespondNotModified() handling since
that's is already handled by ResourceLoader::respond() meanwhile.
== Misc ==
* Remove redundant modifiedTime cache in ResourceLoaderFileModule.
* Change bugzilla references to Phabricator.
* Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this
logic was duplicated in each place the modified timestamp was used.
* It's easy to forget calling the parent class in getDefinitionSummary().
Previously this method only tracked 'class' by default. As such, various
extensions hardcoded that one value instead of calling the parent and extending
the array. To better prevent this in the future, getVersionHash() now asserts
that the '_cacheEpoch' property made it through.
* tests: Don't use getDefinitionSummary() as an API.
Fix ResourceLoaderWikiModuleTest to call getPages properly.
* In tests, the default timestamp used to be 1388534400000 (which is the unix time
of 20140101000000; the unit tests' CacheEpoch). The new version hash of these
modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of:
'{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}'
* Add sha1.js library for client-side hash generation.
Compared various different implementations for code size (after minfication/gzip),
and speed (when used for short hexidecimal strings).
https://jsperf.com/sha1-implementations
- CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k)
http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js
Chrome: 45k, Firefox: 89k, Safari: 92k
- jsSHA <https://github.com/Caligatio/jsSHA>
https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k)
Chrome: 65k, Firefox: 53k, Safari: 69k
- phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k)
https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js
Chrome: 200k, Firefox: 280k, Safari: 78k
Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous,
only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate
code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being
needed in the module loader, we'd have to load the fallback regardless. Considering
this is not used in a critical path for performance, it's not worth shipping two
implementations for this optimisation.
May also resolve:
* T44094
* T90411
* T94810
Bug: T94074
Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
|
|
|
$clientKeys = $context->getRequest()->getHeader( 'If-None-Match', WebRequest::GETHEADER_LIST );
|
2011-02-12 23:41:28 +00:00
|
|
|
// Never send 304s in debug mode
|
resourceloader: Replace timestamp system with version hashing
Modules now track their version via getVersionHash() instead of getModifiedTime().
== Background ==
While some resources have observeable timestamps (e.g. files stored on disk),
many other resources do not. E.g. config variables, and module definitions.
For static file modules, one can e.g. revert one of more files in a module to a
previous version and not affect the max timestamp.
Wiki modules include pages only if they exist. The user module supports common.js
and skin.js. By default neither exists. If a user has both, and then the
less-recently modified one is deleted, the max-timestamp remains unchanged.
For client-side caching, batch requests use "Math.max" on the relevant timestamps.
Again, if a module changes but another module is more recent (e.g. out-of-order
deployment, or out-of-order discovery), the change would not result in a cache miss.
More scenarios can be found in the associated Phabricator tasks.
== Version hash ==
Previously we virtually mapped these variables to a timestamp by storing the current
time alongside a hash of the value in ObjectCache. Considering the number of
possible request contexts (wikis * modules * users * skins * languages) this doesn't
work well. It results in needless cache invalidation when the first time observation
is purged due to LRU algorithms. It also has other minor bugs leading to fewer
cache hits.
All modules automatically get the benefits of version hashing with this change.
The old getDefinitionMtime() and getHashMtime() have been replaced with dummies
that return 1. These functions are often called from getModifiedTime() in subclasses.
For backward-compatibility, their respective values (definition summary and hash)
are now included in getVersionHash directly.
As examples, the following modules have been updated to use getVersionHash directly.
Other modules still work fine and can be updated later.
* ResourceLoaderFileModule
* ResourceLoaderEditToolbarModule
* ResourceLoaderStartUpModule
* ResourceLoaderWikiModule
The presence of hashes in place of timestamps increases the startup module size on
a default MediaWiki install from 4.4k to 5.8k (after gzip and minification).
== ETag ==
Since timestamps are no longer tracked, we need a different way to implement caching
for cache proxies (e.g. Varnish) and web browsers. Previously we used the
Last-Modified header (in combination with Cache-Control and Expires).
Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match).
Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default.
They instruct browsers to allow usage of partial Range requests. Since our responses
are dynamically generated, we need to use the Weak version of ETag.
While this sounds bad, it's no different than Last-Modified. As reassured by
RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the
specified behaviour behind Last-Modified follows the same "Weak" caching logic as
Entity tags. It's just that entity tags are capable of a stricter mode (whereas
Last-Modified is inherently weak).
== File cache ==
If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache
load.php responses. While the blind TTL handling (during the allowed expiry period)
is still maxage/timestamp based, tryRespondNotModified() now requires the caller to
know the expected ETag.
For this to work, the FileCache handling had to be moved from the top of
ResoureLoader::respond() to after the expected ETag is computed.
This also allows us to remove the duplicate tryRespondNotModified() handling since
that's is already handled by ResourceLoader::respond() meanwhile.
== Misc ==
* Remove redundant modifiedTime cache in ResourceLoaderFileModule.
* Change bugzilla references to Phabricator.
* Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this
logic was duplicated in each place the modified timestamp was used.
* It's easy to forget calling the parent class in getDefinitionSummary().
Previously this method only tracked 'class' by default. As such, various
extensions hardcoded that one value instead of calling the parent and extending
the array. To better prevent this in the future, getVersionHash() now asserts
that the '_cacheEpoch' property made it through.
* tests: Don't use getDefinitionSummary() as an API.
Fix ResourceLoaderWikiModuleTest to call getPages properly.
* In tests, the default timestamp used to be 1388534400000 (which is the unix time
of 20140101000000; the unit tests' CacheEpoch). The new version hash of these
modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of:
'{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}'
* Add sha1.js library for client-side hash generation.
Compared various different implementations for code size (after minfication/gzip),
and speed (when used for short hexidecimal strings).
https://jsperf.com/sha1-implementations
- CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k)
http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js
Chrome: 45k, Firefox: 89k, Safari: 92k
- jsSHA <https://github.com/Caligatio/jsSHA>
https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k)
Chrome: 65k, Firefox: 53k, Safari: 69k
- phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k)
https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js
Chrome: 200k, Firefox: 280k, Safari: 78k
Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous,
only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate
code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being
needed in the module loader, we'd have to load the fallback regardless. Considering
this is not used in a critical path for performance, it's not worth shipping two
implementations for this optimisation.
May also resolve:
* T44094
* T90411
* T94810
Bug: T94074
Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
|
|
|
if ( $clientKeys !== false && !$context->getDebug() && in_array( $etag, $clientKeys ) ) {
|
|
|
|
|
// There's another bug in ob_gzhandler (see also the comment at
|
|
|
|
|
// the top of this function) that causes it to gzip even empty
|
|
|
|
|
// responses, meaning it's impossible to produce a truly empty
|
|
|
|
|
// response (because the gzip header is always there). This is
|
|
|
|
|
// a problem because 304 responses have to be completely empty
|
|
|
|
|
// per the HTTP spec, and Firefox behaves buggily when they're not.
|
2016-10-13 05:34:26 +00:00
|
|
|
// See also https://bugs.php.net/bug.php?id=51579
|
resourceloader: Replace timestamp system with version hashing
Modules now track their version via getVersionHash() instead of getModifiedTime().
== Background ==
While some resources have observeable timestamps (e.g. files stored on disk),
many other resources do not. E.g. config variables, and module definitions.
For static file modules, one can e.g. revert one of more files in a module to a
previous version and not affect the max timestamp.
Wiki modules include pages only if they exist. The user module supports common.js
and skin.js. By default neither exists. If a user has both, and then the
less-recently modified one is deleted, the max-timestamp remains unchanged.
For client-side caching, batch requests use "Math.max" on the relevant timestamps.
Again, if a module changes but another module is more recent (e.g. out-of-order
deployment, or out-of-order discovery), the change would not result in a cache miss.
More scenarios can be found in the associated Phabricator tasks.
== Version hash ==
Previously we virtually mapped these variables to a timestamp by storing the current
time alongside a hash of the value in ObjectCache. Considering the number of
possible request contexts (wikis * modules * users * skins * languages) this doesn't
work well. It results in needless cache invalidation when the first time observation
is purged due to LRU algorithms. It also has other minor bugs leading to fewer
cache hits.
All modules automatically get the benefits of version hashing with this change.
The old getDefinitionMtime() and getHashMtime() have been replaced with dummies
that return 1. These functions are often called from getModifiedTime() in subclasses.
For backward-compatibility, their respective values (definition summary and hash)
are now included in getVersionHash directly.
As examples, the following modules have been updated to use getVersionHash directly.
Other modules still work fine and can be updated later.
* ResourceLoaderFileModule
* ResourceLoaderEditToolbarModule
* ResourceLoaderStartUpModule
* ResourceLoaderWikiModule
The presence of hashes in place of timestamps increases the startup module size on
a default MediaWiki install from 4.4k to 5.8k (after gzip and minification).
== ETag ==
Since timestamps are no longer tracked, we need a different way to implement caching
for cache proxies (e.g. Varnish) and web browsers. Previously we used the
Last-Modified header (in combination with Cache-Control and Expires).
Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match).
Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default.
They instruct browsers to allow usage of partial Range requests. Since our responses
are dynamically generated, we need to use the Weak version of ETag.
While this sounds bad, it's no different than Last-Modified. As reassured by
RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the
specified behaviour behind Last-Modified follows the same "Weak" caching logic as
Entity tags. It's just that entity tags are capable of a stricter mode (whereas
Last-Modified is inherently weak).
== File cache ==
If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache
load.php responses. While the blind TTL handling (during the allowed expiry period)
is still maxage/timestamp based, tryRespondNotModified() now requires the caller to
know the expected ETag.
For this to work, the FileCache handling had to be moved from the top of
ResoureLoader::respond() to after the expected ETag is computed.
This also allows us to remove the duplicate tryRespondNotModified() handling since
that's is already handled by ResourceLoader::respond() meanwhile.
== Misc ==
* Remove redundant modifiedTime cache in ResourceLoaderFileModule.
* Change bugzilla references to Phabricator.
* Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this
logic was duplicated in each place the modified timestamp was used.
* It's easy to forget calling the parent class in getDefinitionSummary().
Previously this method only tracked 'class' by default. As such, various
extensions hardcoded that one value instead of calling the parent and extending
the array. To better prevent this in the future, getVersionHash() now asserts
that the '_cacheEpoch' property made it through.
* tests: Don't use getDefinitionSummary() as an API.
Fix ResourceLoaderWikiModuleTest to call getPages properly.
* In tests, the default timestamp used to be 1388534400000 (which is the unix time
of 20140101000000; the unit tests' CacheEpoch). The new version hash of these
modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of:
'{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}'
* Add sha1.js library for client-side hash generation.
Compared various different implementations for code size (after minfication/gzip),
and speed (when used for short hexidecimal strings).
https://jsperf.com/sha1-implementations
- CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k)
http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js
Chrome: 45k, Firefox: 89k, Safari: 92k
- jsSHA <https://github.com/Caligatio/jsSHA>
https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k)
Chrome: 65k, Firefox: 53k, Safari: 69k
- phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k)
https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js
Chrome: 200k, Firefox: 280k, Safari: 78k
Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous,
only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate
code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being
needed in the module loader, we'd have to load the fallback regardless. Considering
this is not used in a critical path for performance, it's not worth shipping two
implementations for this optimisation.
May also resolve:
* T44094
* T90411
* T94810
Bug: T94074
Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
|
|
|
// To work around this, we tear down all output buffering before
|
|
|
|
|
// sending the 304.
|
|
|
|
|
wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
|
|
|
|
|
|
2015-06-01 14:31:52 +00:00
|
|
|
HttpStatus::header( 304 );
|
resourceloader: Replace timestamp system with version hashing
Modules now track their version via getVersionHash() instead of getModifiedTime().
== Background ==
While some resources have observeable timestamps (e.g. files stored on disk),
many other resources do not. E.g. config variables, and module definitions.
For static file modules, one can e.g. revert one of more files in a module to a
previous version and not affect the max timestamp.
Wiki modules include pages only if they exist. The user module supports common.js
and skin.js. By default neither exists. If a user has both, and then the
less-recently modified one is deleted, the max-timestamp remains unchanged.
For client-side caching, batch requests use "Math.max" on the relevant timestamps.
Again, if a module changes but another module is more recent (e.g. out-of-order
deployment, or out-of-order discovery), the change would not result in a cache miss.
More scenarios can be found in the associated Phabricator tasks.
== Version hash ==
Previously we virtually mapped these variables to a timestamp by storing the current
time alongside a hash of the value in ObjectCache. Considering the number of
possible request contexts (wikis * modules * users * skins * languages) this doesn't
work well. It results in needless cache invalidation when the first time observation
is purged due to LRU algorithms. It also has other minor bugs leading to fewer
cache hits.
All modules automatically get the benefits of version hashing with this change.
The old getDefinitionMtime() and getHashMtime() have been replaced with dummies
that return 1. These functions are often called from getModifiedTime() in subclasses.
For backward-compatibility, their respective values (definition summary and hash)
are now included in getVersionHash directly.
As examples, the following modules have been updated to use getVersionHash directly.
Other modules still work fine and can be updated later.
* ResourceLoaderFileModule
* ResourceLoaderEditToolbarModule
* ResourceLoaderStartUpModule
* ResourceLoaderWikiModule
The presence of hashes in place of timestamps increases the startup module size on
a default MediaWiki install from 4.4k to 5.8k (after gzip and minification).
== ETag ==
Since timestamps are no longer tracked, we need a different way to implement caching
for cache proxies (e.g. Varnish) and web browsers. Previously we used the
Last-Modified header (in combination with Cache-Control and Expires).
Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match).
Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default.
They instruct browsers to allow usage of partial Range requests. Since our responses
are dynamically generated, we need to use the Weak version of ETag.
While this sounds bad, it's no different than Last-Modified. As reassured by
RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the
specified behaviour behind Last-Modified follows the same "Weak" caching logic as
Entity tags. It's just that entity tags are capable of a stricter mode (whereas
Last-Modified is inherently weak).
== File cache ==
If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache
load.php responses. While the blind TTL handling (during the allowed expiry period)
is still maxage/timestamp based, tryRespondNotModified() now requires the caller to
know the expected ETag.
For this to work, the FileCache handling had to be moved from the top of
ResoureLoader::respond() to after the expected ETag is computed.
This also allows us to remove the duplicate tryRespondNotModified() handling since
that's is already handled by ResourceLoader::respond() meanwhile.
== Misc ==
* Remove redundant modifiedTime cache in ResourceLoaderFileModule.
* Change bugzilla references to Phabricator.
* Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this
logic was duplicated in each place the modified timestamp was used.
* It's easy to forget calling the parent class in getDefinitionSummary().
Previously this method only tracked 'class' by default. As such, various
extensions hardcoded that one value instead of calling the parent and extending
the array. To better prevent this in the future, getVersionHash() now asserts
that the '_cacheEpoch' property made it through.
* tests: Don't use getDefinitionSummary() as an API.
Fix ResourceLoaderWikiModuleTest to call getPages properly.
* In tests, the default timestamp used to be 1388534400000 (which is the unix time
of 20140101000000; the unit tests' CacheEpoch). The new version hash of these
modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of:
'{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}'
* Add sha1.js library for client-side hash generation.
Compared various different implementations for code size (after minfication/gzip),
and speed (when used for short hexidecimal strings).
https://jsperf.com/sha1-implementations
- CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k)
http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js
Chrome: 45k, Firefox: 89k, Safari: 92k
- jsSHA <https://github.com/Caligatio/jsSHA>
https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k)
Chrome: 65k, Firefox: 53k, Safari: 69k
- phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k)
https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js
Chrome: 200k, Firefox: 280k, Safari: 78k
Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous,
only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate
code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being
needed in the module loader, we'd have to load the fallback regardless. Considering
this is not used in a critical path for performance, it's not worth shipping two
implementations for this optimisation.
May also resolve:
* T44094
* T90411
* T94810
Bug: T94074
Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
|
|
|
|
|
|
|
|
$this->sendResponseHeaders( $context, $etag, false );
|
|
|
|
|
return true;
|
2010-09-04 04:00:09 +00:00
|
|
|
}
|
2011-10-01 04:15:07 +00:00
|
|
|
return false;
|
2010-09-24 22:10:25 +00:00
|
|
|
}
|
|
|
|
|
|
2011-10-02 17:53:33 +00:00
|
|
|
/**
|
2014-03-07 16:50:57 +00:00
|
|
|
* Send out code for a response from file cache if possible.
|
2011-10-02 17:53:33 +00:00
|
|
|
*
|
2014-03-07 16:50:57 +00:00
|
|
|
* @param ResourceFileCache $fileCache Cache object for this request URL
|
|
|
|
|
* @param ResourceLoaderContext $context Context in which to generate a response
|
resourceloader: Replace timestamp system with version hashing
Modules now track their version via getVersionHash() instead of getModifiedTime().
== Background ==
While some resources have observeable timestamps (e.g. files stored on disk),
many other resources do not. E.g. config variables, and module definitions.
For static file modules, one can e.g. revert one of more files in a module to a
previous version and not affect the max timestamp.
Wiki modules include pages only if they exist. The user module supports common.js
and skin.js. By default neither exists. If a user has both, and then the
less-recently modified one is deleted, the max-timestamp remains unchanged.
For client-side caching, batch requests use "Math.max" on the relevant timestamps.
Again, if a module changes but another module is more recent (e.g. out-of-order
deployment, or out-of-order discovery), the change would not result in a cache miss.
More scenarios can be found in the associated Phabricator tasks.
== Version hash ==
Previously we virtually mapped these variables to a timestamp by storing the current
time alongside a hash of the value in ObjectCache. Considering the number of
possible request contexts (wikis * modules * users * skins * languages) this doesn't
work well. It results in needless cache invalidation when the first time observation
is purged due to LRU algorithms. It also has other minor bugs leading to fewer
cache hits.
All modules automatically get the benefits of version hashing with this change.
The old getDefinitionMtime() and getHashMtime() have been replaced with dummies
that return 1. These functions are often called from getModifiedTime() in subclasses.
For backward-compatibility, their respective values (definition summary and hash)
are now included in getVersionHash directly.
As examples, the following modules have been updated to use getVersionHash directly.
Other modules still work fine and can be updated later.
* ResourceLoaderFileModule
* ResourceLoaderEditToolbarModule
* ResourceLoaderStartUpModule
* ResourceLoaderWikiModule
The presence of hashes in place of timestamps increases the startup module size on
a default MediaWiki install from 4.4k to 5.8k (after gzip and minification).
== ETag ==
Since timestamps are no longer tracked, we need a different way to implement caching
for cache proxies (e.g. Varnish) and web browsers. Previously we used the
Last-Modified header (in combination with Cache-Control and Expires).
Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match).
Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default.
They instruct browsers to allow usage of partial Range requests. Since our responses
are dynamically generated, we need to use the Weak version of ETag.
While this sounds bad, it's no different than Last-Modified. As reassured by
RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the
specified behaviour behind Last-Modified follows the same "Weak" caching logic as
Entity tags. It's just that entity tags are capable of a stricter mode (whereas
Last-Modified is inherently weak).
== File cache ==
If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache
load.php responses. While the blind TTL handling (during the allowed expiry period)
is still maxage/timestamp based, tryRespondNotModified() now requires the caller to
know the expected ETag.
For this to work, the FileCache handling had to be moved from the top of
ResoureLoader::respond() to after the expected ETag is computed.
This also allows us to remove the duplicate tryRespondNotModified() handling since
that's is already handled by ResourceLoader::respond() meanwhile.
== Misc ==
* Remove redundant modifiedTime cache in ResourceLoaderFileModule.
* Change bugzilla references to Phabricator.
* Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this
logic was duplicated in each place the modified timestamp was used.
* It's easy to forget calling the parent class in getDefinitionSummary().
Previously this method only tracked 'class' by default. As such, various
extensions hardcoded that one value instead of calling the parent and extending
the array. To better prevent this in the future, getVersionHash() now asserts
that the '_cacheEpoch' property made it through.
* tests: Don't use getDefinitionSummary() as an API.
Fix ResourceLoaderWikiModuleTest to call getPages properly.
* In tests, the default timestamp used to be 1388534400000 (which is the unix time
of 20140101000000; the unit tests' CacheEpoch). The new version hash of these
modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of:
'{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}'
* Add sha1.js library for client-side hash generation.
Compared various different implementations for code size (after minfication/gzip),
and speed (when used for short hexidecimal strings).
https://jsperf.com/sha1-implementations
- CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k)
http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js
Chrome: 45k, Firefox: 89k, Safari: 92k
- jsSHA <https://github.com/Caligatio/jsSHA>
https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k)
Chrome: 65k, Firefox: 53k, Safari: 69k
- phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k)
https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js
Chrome: 200k, Firefox: 280k, Safari: 78k
Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous,
only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate
code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being
needed in the module loader, we'd have to load the fallback regardless. Considering
this is not used in a critical path for performance, it's not worth shipping two
implementations for this optimisation.
May also resolve:
* T44094
* T90411
* T94810
Bug: T94074
Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
|
|
|
* @param string $etag ETag header value
|
2011-10-02 17:53:33 +00:00
|
|
|
* @return bool If this found a cache file and handled the response
|
|
|
|
|
*/
|
|
|
|
|
protected function tryRespondFromFileCache(
|
resourceloader: Replace timestamp system with version hashing
Modules now track their version via getVersionHash() instead of getModifiedTime().
== Background ==
While some resources have observeable timestamps (e.g. files stored on disk),
many other resources do not. E.g. config variables, and module definitions.
For static file modules, one can e.g. revert one of more files in a module to a
previous version and not affect the max timestamp.
Wiki modules include pages only if they exist. The user module supports common.js
and skin.js. By default neither exists. If a user has both, and then the
less-recently modified one is deleted, the max-timestamp remains unchanged.
For client-side caching, batch requests use "Math.max" on the relevant timestamps.
Again, if a module changes but another module is more recent (e.g. out-of-order
deployment, or out-of-order discovery), the change would not result in a cache miss.
More scenarios can be found in the associated Phabricator tasks.
== Version hash ==
Previously we virtually mapped these variables to a timestamp by storing the current
time alongside a hash of the value in ObjectCache. Considering the number of
possible request contexts (wikis * modules * users * skins * languages) this doesn't
work well. It results in needless cache invalidation when the first time observation
is purged due to LRU algorithms. It also has other minor bugs leading to fewer
cache hits.
All modules automatically get the benefits of version hashing with this change.
The old getDefinitionMtime() and getHashMtime() have been replaced with dummies
that return 1. These functions are often called from getModifiedTime() in subclasses.
For backward-compatibility, their respective values (definition summary and hash)
are now included in getVersionHash directly.
As examples, the following modules have been updated to use getVersionHash directly.
Other modules still work fine and can be updated later.
* ResourceLoaderFileModule
* ResourceLoaderEditToolbarModule
* ResourceLoaderStartUpModule
* ResourceLoaderWikiModule
The presence of hashes in place of timestamps increases the startup module size on
a default MediaWiki install from 4.4k to 5.8k (after gzip and minification).
== ETag ==
Since timestamps are no longer tracked, we need a different way to implement caching
for cache proxies (e.g. Varnish) and web browsers. Previously we used the
Last-Modified header (in combination with Cache-Control and Expires).
Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match).
Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default.
They instruct browsers to allow usage of partial Range requests. Since our responses
are dynamically generated, we need to use the Weak version of ETag.
While this sounds bad, it's no different than Last-Modified. As reassured by
RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the
specified behaviour behind Last-Modified follows the same "Weak" caching logic as
Entity tags. It's just that entity tags are capable of a stricter mode (whereas
Last-Modified is inherently weak).
== File cache ==
If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache
load.php responses. While the blind TTL handling (during the allowed expiry period)
is still maxage/timestamp based, tryRespondNotModified() now requires the caller to
know the expected ETag.
For this to work, the FileCache handling had to be moved from the top of
ResoureLoader::respond() to after the expected ETag is computed.
This also allows us to remove the duplicate tryRespondNotModified() handling since
that's is already handled by ResourceLoader::respond() meanwhile.
== Misc ==
* Remove redundant modifiedTime cache in ResourceLoaderFileModule.
* Change bugzilla references to Phabricator.
* Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this
logic was duplicated in each place the modified timestamp was used.
* It's easy to forget calling the parent class in getDefinitionSummary().
Previously this method only tracked 'class' by default. As such, various
extensions hardcoded that one value instead of calling the parent and extending
the array. To better prevent this in the future, getVersionHash() now asserts
that the '_cacheEpoch' property made it through.
* tests: Don't use getDefinitionSummary() as an API.
Fix ResourceLoaderWikiModuleTest to call getPages properly.
* In tests, the default timestamp used to be 1388534400000 (which is the unix time
of 20140101000000; the unit tests' CacheEpoch). The new version hash of these
modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of:
'{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}'
* Add sha1.js library for client-side hash generation.
Compared various different implementations for code size (after minfication/gzip),
and speed (when used for short hexidecimal strings).
https://jsperf.com/sha1-implementations
- CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k)
http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js
Chrome: 45k, Firefox: 89k, Safari: 92k
- jsSHA <https://github.com/Caligatio/jsSHA>
https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k)
Chrome: 65k, Firefox: 53k, Safari: 69k
- phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k)
https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js
Chrome: 200k, Firefox: 280k, Safari: 78k
Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous,
only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate
code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being
needed in the module loader, we'd have to load the fallback regardless. Considering
this is not used in a critical path for performance, it's not worth shipping two
implementations for this optimisation.
May also resolve:
* T44094
* T90411
* T94810
Bug: T94074
Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
|
|
|
ResourceFileCache $fileCache,
|
|
|
|
|
ResourceLoaderContext $context,
|
|
|
|
|
$etag
|
2011-10-02 17:53:33 +00:00
|
|
|
) {
|
2014-08-07 10:25:56 +00:00
|
|
|
$rlMaxage = $this->config->get( 'ResourceLoaderMaxage' );
|
2011-10-02 17:53:33 +00:00
|
|
|
// Buffer output to catch warnings.
|
|
|
|
|
ob_start();
|
|
|
|
|
// Get the maximum age the cache can be
|
|
|
|
|
$maxage = is_null( $context->getVersion() )
|
2014-08-07 10:25:56 +00:00
|
|
|
? $rlMaxage['unversioned']['server']
|
|
|
|
|
: $rlMaxage['versioned']['server'];
|
2011-10-02 17:53:33 +00:00
|
|
|
// Minimum timestamp the cache file must have
|
|
|
|
|
$good = $fileCache->isCacheGood( wfTimestamp( TS_MW, time() - $maxage ) );
|
|
|
|
|
if ( !$good ) {
|
|
|
|
|
try { // RL always hits the DB on file cache miss...
|
2016-09-05 19:55:19 +00:00
|
|
|
wfGetDB( DB_REPLICA );
|
2013-04-27 12:02:08 +00:00
|
|
|
} catch ( DBConnectionError $e ) { // ...check if we need to fallback to cache
|
2011-10-02 17:53:33 +00:00
|
|
|
$good = $fileCache->isCacheGood(); // cache existence check
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if ( $good ) {
|
|
|
|
|
$ts = $fileCache->cacheTimestamp();
|
2015-05-12 01:18:31 +00:00
|
|
|
// Send content type and cache headers
|
resourceloader: Replace timestamp system with version hashing
Modules now track their version via getVersionHash() instead of getModifiedTime().
== Background ==
While some resources have observeable timestamps (e.g. files stored on disk),
many other resources do not. E.g. config variables, and module definitions.
For static file modules, one can e.g. revert one of more files in a module to a
previous version and not affect the max timestamp.
Wiki modules include pages only if they exist. The user module supports common.js
and skin.js. By default neither exists. If a user has both, and then the
less-recently modified one is deleted, the max-timestamp remains unchanged.
For client-side caching, batch requests use "Math.max" on the relevant timestamps.
Again, if a module changes but another module is more recent (e.g. out-of-order
deployment, or out-of-order discovery), the change would not result in a cache miss.
More scenarios can be found in the associated Phabricator tasks.
== Version hash ==
Previously we virtually mapped these variables to a timestamp by storing the current
time alongside a hash of the value in ObjectCache. Considering the number of
possible request contexts (wikis * modules * users * skins * languages) this doesn't
work well. It results in needless cache invalidation when the first time observation
is purged due to LRU algorithms. It also has other minor bugs leading to fewer
cache hits.
All modules automatically get the benefits of version hashing with this change.
The old getDefinitionMtime() and getHashMtime() have been replaced with dummies
that return 1. These functions are often called from getModifiedTime() in subclasses.
For backward-compatibility, their respective values (definition summary and hash)
are now included in getVersionHash directly.
As examples, the following modules have been updated to use getVersionHash directly.
Other modules still work fine and can be updated later.
* ResourceLoaderFileModule
* ResourceLoaderEditToolbarModule
* ResourceLoaderStartUpModule
* ResourceLoaderWikiModule
The presence of hashes in place of timestamps increases the startup module size on
a default MediaWiki install from 4.4k to 5.8k (after gzip and minification).
== ETag ==
Since timestamps are no longer tracked, we need a different way to implement caching
for cache proxies (e.g. Varnish) and web browsers. Previously we used the
Last-Modified header (in combination with Cache-Control and Expires).
Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match).
Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default.
They instruct browsers to allow usage of partial Range requests. Since our responses
are dynamically generated, we need to use the Weak version of ETag.
While this sounds bad, it's no different than Last-Modified. As reassured by
RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the
specified behaviour behind Last-Modified follows the same "Weak" caching logic as
Entity tags. It's just that entity tags are capable of a stricter mode (whereas
Last-Modified is inherently weak).
== File cache ==
If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache
load.php responses. While the blind TTL handling (during the allowed expiry period)
is still maxage/timestamp based, tryRespondNotModified() now requires the caller to
know the expected ETag.
For this to work, the FileCache handling had to be moved from the top of
ResoureLoader::respond() to after the expected ETag is computed.
This also allows us to remove the duplicate tryRespondNotModified() handling since
that's is already handled by ResourceLoader::respond() meanwhile.
== Misc ==
* Remove redundant modifiedTime cache in ResourceLoaderFileModule.
* Change bugzilla references to Phabricator.
* Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this
logic was duplicated in each place the modified timestamp was used.
* It's easy to forget calling the parent class in getDefinitionSummary().
Previously this method only tracked 'class' by default. As such, various
extensions hardcoded that one value instead of calling the parent and extending
the array. To better prevent this in the future, getVersionHash() now asserts
that the '_cacheEpoch' property made it through.
* tests: Don't use getDefinitionSummary() as an API.
Fix ResourceLoaderWikiModuleTest to call getPages properly.
* In tests, the default timestamp used to be 1388534400000 (which is the unix time
of 20140101000000; the unit tests' CacheEpoch). The new version hash of these
modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of:
'{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}'
* Add sha1.js library for client-side hash generation.
Compared various different implementations for code size (after minfication/gzip),
and speed (when used for short hexidecimal strings).
https://jsperf.com/sha1-implementations
- CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k)
http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js
Chrome: 45k, Firefox: 89k, Safari: 92k
- jsSHA <https://github.com/Caligatio/jsSHA>
https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k)
Chrome: 65k, Firefox: 53k, Safari: 69k
- phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k)
https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js
Chrome: 200k, Firefox: 280k, Safari: 78k
Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous,
only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate
code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being
needed in the module loader, we'd have to load the fallback regardless. Considering
this is not used in a critical path for performance, it's not worth shipping two
implementations for this optimisation.
May also resolve:
* T44094
* T90411
* T94810
Bug: T94074
Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
|
|
|
$this->sendResponseHeaders( $context, $etag, false );
|
2015-05-12 01:18:31 +00:00
|
|
|
$response = $fileCache->fetchText();
|
2011-12-17 05:02:15 +00:00
|
|
|
// Capture any PHP warnings from the output buffer and append them to the
|
|
|
|
|
// response in a comment if we're in debug mode.
|
2015-11-01 19:56:20 +00:00
|
|
|
if ( $context->getDebug() ) {
|
|
|
|
|
$warnings = ob_get_contents();
|
|
|
|
|
if ( strlen( $warnings ) ) {
|
|
|
|
|
$response = self::makeComment( $warnings ) . $response;
|
|
|
|
|
}
|
2011-12-17 05:02:15 +00:00
|
|
|
}
|
2011-10-02 17:53:33 +00:00
|
|
|
// Remove the output buffer and output the response
|
|
|
|
|
ob_end_clean();
|
|
|
|
|
echo $response . "\n/* Cached {$ts} */";
|
|
|
|
|
return true; // cache hit
|
|
|
|
|
}
|
|
|
|
|
// Clear buffer
|
|
|
|
|
ob_end_clean();
|
|
|
|
|
|
|
|
|
|
return false; // cache miss
|
|
|
|
|
}
|
|
|
|
|
|
2013-08-11 07:11:17 +00:00
|
|
|
/**
|
2014-03-07 16:50:57 +00:00
|
|
|
* Generate a CSS or JS comment block.
|
|
|
|
|
*
|
|
|
|
|
* Only use this for public data, not error message details.
|
2013-08-11 07:11:17 +00:00
|
|
|
*
|
2014-03-07 16:50:57 +00:00
|
|
|
* @param string $text
|
2013-08-11 07:11:17 +00:00
|
|
|
* @return string
|
|
|
|
|
*/
|
|
|
|
|
public static function makeComment( $text ) {
|
2012-03-22 19:52:37 +00:00
|
|
|
$encText = str_replace( '*/', '* /', $text );
|
|
|
|
|
return "/*\n$encText\n*/\n";
|
|
|
|
|
}
|
|
|
|
|
|
2013-08-16 23:20:26 +00:00
|
|
|
/**
|
2014-03-07 16:50:57 +00:00
|
|
|
* Handle exception display.
|
2013-08-16 23:20:26 +00:00
|
|
|
*
|
2014-04-20 21:33:05 +00:00
|
|
|
* @param Exception $e Exception to be shown to the user
|
2014-11-11 20:00:17 +00:00
|
|
|
* @return string Sanitized text in a CSS/JS comment that can be returned to the user
|
2013-08-16 23:20:26 +00:00
|
|
|
*/
|
|
|
|
|
public static function formatException( $e ) {
|
2014-11-11 20:00:17 +00:00
|
|
|
return self::makeComment( self::formatExceptionNoComment( $e ) );
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Handle exception display.
|
|
|
|
|
*
|
|
|
|
|
* @since 1.25
|
|
|
|
|
* @param Exception $e Exception to be shown to the user
|
|
|
|
|
* @return string Sanitized text that can be returned to the user
|
|
|
|
|
*/
|
|
|
|
|
protected static function formatExceptionNoComment( $e ) {
|
2013-08-16 23:20:26 +00:00
|
|
|
global $wgShowExceptionDetails;
|
|
|
|
|
|
2015-09-15 18:35:13 +00:00
|
|
|
if ( !$wgShowExceptionDetails ) {
|
2015-09-23 16:36:10 +00:00
|
|
|
return MWExceptionHandler::getPublicLogMessage( $e );
|
2013-08-16 23:20:26 +00:00
|
|
|
}
|
2015-09-15 18:35:13 +00:00
|
|
|
|
2016-12-03 03:57:42 +00:00
|
|
|
return MWExceptionHandler::getLogMessage( $e ) .
|
|
|
|
|
"\nBacktrace:\n" .
|
|
|
|
|
MWExceptionHandler::getRedactedTraceAsString( $e );
|
2013-08-16 23:20:26 +00:00
|
|
|
}
|
|
|
|
|
|
2010-10-19 20:45:02 +00:00
|
|
|
/**
|
2014-03-07 16:50:57 +00:00
|
|
|
* Generate code for a response.
|
2011-06-17 16:05:05 +00:00
|
|
|
*
|
resourceloader: Add support for modules sending preload headers
ResourceLoaderModule objects gain a new method getPreloadLinks() which
returns an array with the meta data required to build a Link rel=preload
header according to the current draft for W3C Preload.
<https://w3c.github.io/preload/>
Another implementation of this is already in use in OutputPage for
preloading the logo image.
This array is formatted by the ResourceLoaderModule::getHeaders method,
which is implemented as "final" at this time, thus restricting use to
the Link rel=preload header.
Headers are exposed and process-cached, like all other content
(scripts, styles, etc.), through ResourceLoaderModule::getModuleContent,
and aggregated by ResoureLoader::makeModuleResponse.
I had hoped for the getPreloadLinks to be stateless (not vary on $context).
Whether something should be preloaded and what, should not vary on the
skin or language. However, while that conceptually holds true, the exact
url for any given resource may still vary. Even the main use case for this
feature (T164299, preloading base modules request) require $context to pass
down skin and lang to the load.php url.
Add full test coverage and example documentation.
Bug: T164299
Change-Id: I2bfe0796ceaa0c82579c501f5b10e931f2175681
2017-07-18 02:36:01 +00:00
|
|
|
* Calling this method also populates the `errors` and `headers` members,
|
|
|
|
|
* later used by respond().
|
|
|
|
|
*
|
2014-04-20 21:33:05 +00:00
|
|
|
* @param ResourceLoaderContext $context Context in which to generate a response
|
2015-09-28 19:18:46 +00:00
|
|
|
* @param ResourceLoaderModule[] $modules List of module objects keyed by module name
|
|
|
|
|
* @param string[] $missing List of requested module names that are unregistered (optional)
|
2013-10-17 10:33:26 +00:00
|
|
|
* @return string Response data
|
2010-10-19 20:45:02 +00:00
|
|
|
*/
|
2011-06-17 16:05:05 +00:00
|
|
|
public function makeModuleResponse( ResourceLoaderContext $context,
|
2016-02-17 09:09:32 +00:00
|
|
|
array $modules, array $missing = []
|
2013-04-02 20:28:40 +00:00
|
|
|
) {
|
2010-12-23 20:14:18 +00:00
|
|
|
$out = '';
|
2016-02-17 09:09:32 +00:00
|
|
|
$states = [];
|
2013-10-17 10:33:26 +00:00
|
|
|
|
|
|
|
|
if ( !count( $modules ) && !count( $missing ) ) {
|
2015-03-15 01:52:45 +00:00
|
|
|
return <<<MESSAGE
|
|
|
|
|
/* This file is the Web entry point for MediaWiki's ResourceLoader:
|
2014-01-17 07:43:31 +00:00
|
|
|
<https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
|
2015-03-15 01:52:45 +00:00
|
|
|
no modules were requested. Max made me put this here. */
|
|
|
|
|
MESSAGE;
|
2010-12-10 17:21:09 +00:00
|
|
|
}
|
2011-06-17 16:05:05 +00:00
|
|
|
|
2014-11-11 19:50:44 +00:00
|
|
|
$image = $context->getImageObj();
|
|
|
|
|
if ( $image ) {
|
|
|
|
|
$data = $image->getImageData( $context );
|
2014-11-11 20:00:17 +00:00
|
|
|
if ( $data === false ) {
|
|
|
|
|
$data = '';
|
|
|
|
|
$this->errors[] = 'Image generation failed';
|
|
|
|
|
}
|
2014-11-11 19:50:44 +00:00
|
|
|
return $data;
|
|
|
|
|
}
|
|
|
|
|
|
2013-10-17 10:33:26 +00:00
|
|
|
foreach ( $missing as $name ) {
|
|
|
|
|
$states[$name] = 'missing';
|
|
|
|
|
}
|
|
|
|
|
|
2010-09-04 04:00:09 +00:00
|
|
|
// Generate output
|
2012-05-11 19:16:29 +00:00
|
|
|
$isRaw = false;
|
2015-10-01 00:26:46 +00:00
|
|
|
|
|
|
|
|
$filter = $context->getOnly() === 'styles' ? 'minify-css' : 'minify-js';
|
|
|
|
|
|
2010-09-24 22:10:25 +00:00
|
|
|
foreach ( $modules as $name => $module ) {
|
2010-12-23 20:14:18 +00:00
|
|
|
try {
|
2015-05-14 19:05:47 +00:00
|
|
|
$content = $module->getModuleContent( $context );
|
2016-09-12 20:52:10 +00:00
|
|
|
$implementKey = $name . '@' . $module->getVersionHash( $context );
|
2015-10-01 00:26:46 +00:00
|
|
|
$strContent = '';
|
2010-12-23 20:14:18 +00:00
|
|
|
|
resourceloader: Add support for modules sending preload headers
ResourceLoaderModule objects gain a new method getPreloadLinks() which
returns an array with the meta data required to build a Link rel=preload
header according to the current draft for W3C Preload.
<https://w3c.github.io/preload/>
Another implementation of this is already in use in OutputPage for
preloading the logo image.
This array is formatted by the ResourceLoaderModule::getHeaders method,
which is implemented as "final" at this time, thus restricting use to
the Link rel=preload header.
Headers are exposed and process-cached, like all other content
(scripts, styles, etc.), through ResourceLoaderModule::getModuleContent,
and aggregated by ResoureLoader::makeModuleResponse.
I had hoped for the getPreloadLinks to be stateless (not vary on $context).
Whether something should be preloaded and what, should not vary on the
skin or language. However, while that conceptually holds true, the exact
url for any given resource may still vary. Even the main use case for this
feature (T164299, preloading base modules request) require $context to pass
down skin and lang to the load.php url.
Add full test coverage and example documentation.
Bug: T164299
Change-Id: I2bfe0796ceaa0c82579c501f5b10e931f2175681
2017-07-18 02:36:01 +00:00
|
|
|
if ( isset( $content['headers'] ) ) {
|
|
|
|
|
$this->extraHeaders = array_merge( $this->extraHeaders, $content['headers'] );
|
|
|
|
|
}
|
|
|
|
|
|
2010-12-23 20:14:18 +00:00
|
|
|
// Append output
|
|
|
|
|
switch ( $context->getOnly() ) {
|
|
|
|
|
case 'scripts':
|
2015-05-14 19:05:47 +00:00
|
|
|
$scripts = $content['scripts'];
|
2011-05-14 12:15:58 +00:00
|
|
|
if ( is_string( $scripts ) ) {
|
2011-07-28 05:48:57 +00:00
|
|
|
// Load scripts raw...
|
2015-10-01 00:26:46 +00:00
|
|
|
$strContent = $scripts;
|
2011-06-17 16:05:05 +00:00
|
|
|
} elseif ( is_array( $scripts ) ) {
|
2011-07-28 05:48:57 +00:00
|
|
|
// ...except when $scripts is an array of URLs
|
2016-09-12 20:52:10 +00:00
|
|
|
$strContent = self::makeLoaderImplementScript( $implementKey, $scripts, [], [], [] );
|
2011-05-14 12:15:58 +00:00
|
|
|
}
|
2010-12-23 20:14:18 +00:00
|
|
|
break;
|
|
|
|
|
case 'styles':
|
2015-05-14 19:05:47 +00:00
|
|
|
$styles = $content['styles'];
|
ResourceLoader: Refactor style loading
Fixes:
* bug 31676: Work around IE stylesheet limit.
* bug 35562: @import styles broken in modules that combine
multiple stylesheets.
* bug 40498: Don't output empty "@media print { }" blocks.
* bug 40500: Don't ignore media-type for urls in debug mode.
Approach:
* Re-use the same <style> tag so that we stay under the 31
stylesheet limit in IE. Unless the to-be-added css text from
the being-loaded module contains @import, in which case we do
create a new <style> tag and then re-use that one from that
point on (bug 31676).
* Return stylesheets as arrays, instead of a concatenated string.
This fixes bug 35562, because @import only works when at the
top of a stylesheet. By not unconditionally concatenating files
within a module on the server side already, @import will work
in e.g. module 'site' that contains 2 wiki pages.
This is normalized in ResourceLoader::makeCombinedStyles(),
so far only ResourceLoaderWikiModule makes use of this.
Misc. clean up and bug fixes:
* Reducing usage of jQuery() and mw.html.element() where
native DOM would be very simple and faster. Aside from
simplicity and speed, this is also working towards a more
stand-alone ResourceLoader.
* Trim server output a little bit more
- Redundant new line after minify-css (it is now an array, so
no need to keep space afterwards)
- Redundant semi-colon after minify-js if it ends in a colon
* Allow space in styleTest.css.php
* Clean up and extend unit tests to cover for these features
and bug fixes.
* Don't set styleEl.rel = 'stylesheet'; that has no business
on a <style> tag.
* Fix bug in mw.loader's addStyleTag(). It turns out IE6
has an odd security measure that does not allow manipulation
of elements (at least style tags) that are created by a
different script (even if that script was served from the same
domain/origin etc.). We didn't ran into this before because
we only created new style tags, never appended to them. Now
that we do, this came up. Took a while to figure out because
it was created by mediawiki.js but it calls jQuery which did
the actual dom insertion. Odd thing is, we load jquery.js and
mediawiki.js in the same request even...
Without this all css-url related mw.loader tests would fail
in IE6.
* mediawiki.js and mediawiki.test.js now pass jshint again.
Tested (and passing qunit/?module=mediawiki; 123 of 123):
* Chrome 14, 21
* Firefox 3.0, 3.6, 4, 7, 14, 15, 16beta
* IE 6, 7, 8, 9
* Safari 4.0, 5.0, 5.1
* Opera 10.0, 11.1, 11.5, 11.6, 12.0, 12.5beta
* iPhone 3GS / iOS 3.0 / Mobile Safari 4.0
iPhone 4 / iOS 4.0.1 / Mobile Safari 4.0.5
iPhone 4S / iOS 6.0 Beta / Mobile Safari 6.0
Change-Id: I3e8227ddb87fd9441071ca935439fc6467751dab
2012-07-25 21:20:21 +00:00
|
|
|
// We no longer seperate into media, they are all combined now with
|
|
|
|
|
// custom media type groups into @media .. {} sections as part of the css string.
|
|
|
|
|
// Module returns either an empty array or a numerical array with css strings.
|
2015-10-01 00:26:46 +00:00
|
|
|
$strContent = isset( $styles['css'] ) ? implode( '', $styles['css'] ) : '';
|
2010-12-23 20:14:18 +00:00
|
|
|
break;
|
|
|
|
|
default:
|
2016-09-15 04:01:09 +00:00
|
|
|
$scripts = isset( $content['scripts'] ) ? $content['scripts'] : '';
|
|
|
|
|
if ( is_string( $scripts ) ) {
|
|
|
|
|
if ( $name === 'site' || $name === 'user' ) {
|
|
|
|
|
// Legacy scripts that run in the global scope without a closure.
|
|
|
|
|
// mw.loader.implement will use globalEval if scripts is a string.
|
|
|
|
|
// Minify manually here, because general response minification is
|
|
|
|
|
// not effective due it being a string literal, not a function.
|
2017-07-23 01:24:09 +00:00
|
|
|
if ( !self::inDebugMode() ) {
|
2016-09-15 04:01:09 +00:00
|
|
|
$scripts = self::filter( 'minify-js', $scripts ); // T107377
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
$scripts = new XmlJsCode( $scripts );
|
|
|
|
|
}
|
|
|
|
|
}
|
2015-10-01 00:26:46 +00:00
|
|
|
$strContent = self::makeLoaderImplementScript(
|
2016-09-12 20:52:10 +00:00
|
|
|
$implementKey,
|
2016-09-15 04:01:09 +00:00
|
|
|
$scripts,
|
2016-02-17 09:09:32 +00:00
|
|
|
isset( $content['styles'] ) ? $content['styles'] : [],
|
|
|
|
|
isset( $content['messagesBlob'] ) ? new XmlJsCode( $content['messagesBlob'] ) : [],
|
|
|
|
|
isset( $content['templates'] ) ? $content['templates'] : []
|
2012-06-13 23:50:13 +00:00
|
|
|
);
|
2010-12-23 20:14:18 +00:00
|
|
|
break;
|
|
|
|
|
}
|
2015-10-01 00:26:46 +00:00
|
|
|
|
|
|
|
|
if ( !$context->getDebug() ) {
|
2015-10-01 18:05:08 +00:00
|
|
|
$strContent = self::filter( $filter, $strContent );
|
2015-10-01 00:26:46 +00:00
|
|
|
}
|
|
|
|
|
|
2017-06-28 02:51:03 +00:00
|
|
|
if ( $context->getOnly() === 'scripts' ) {
|
|
|
|
|
// Use a linebreak between module scripts (T162719)
|
|
|
|
|
$out .= $this->ensureNewline( $strContent );
|
|
|
|
|
} else {
|
|
|
|
|
$out .= $strContent;
|
|
|
|
|
}
|
2015-10-01 00:26:46 +00:00
|
|
|
|
2010-12-23 20:14:18 +00:00
|
|
|
} catch ( Exception $e ) {
|
2016-12-03 03:57:42 +00:00
|
|
|
$this->outputErrorAndLog( $e, 'Generating module package failed: {exception}' );
|
2010-10-20 00:22:25 +00:00
|
|
|
|
2013-10-17 10:33:26 +00:00
|
|
|
// Respond to client with error-state instead of module implementation
|
|
|
|
|
$states[$name] = 'error';
|
2010-12-23 20:14:18 +00:00
|
|
|
unset( $modules[$name] );
|
|
|
|
|
}
|
2012-05-11 19:16:29 +00:00
|
|
|
$isRaw |= $module->isRaw();
|
2010-09-04 04:00:09 +00:00
|
|
|
}
|
2010-09-04 12:53:01 +00:00
|
|
|
|
2010-09-24 18:49:19 +00:00
|
|
|
// Update module states
|
2012-05-11 19:16:29 +00:00
|
|
|
if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
|
|
|
|
|
if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
|
2013-10-17 10:33:26 +00:00
|
|
|
// Set the state of modules loaded as only scripts to ready as
|
|
|
|
|
// they don't have an mw.loader.implement wrapper that sets the state
|
|
|
|
|
foreach ( $modules as $name => $module ) {
|
|
|
|
|
$states[$name] = 'ready';
|
|
|
|
|
}
|
2010-09-24 18:49:19 +00:00
|
|
|
}
|
2013-10-17 10:33:26 +00:00
|
|
|
|
|
|
|
|
// Set the state of modules we didn't respond to with mw.loader.implement
|
|
|
|
|
if ( count( $states ) ) {
|
2015-10-01 00:26:46 +00:00
|
|
|
$stateScript = self::makeLoaderStateScript( $states );
|
|
|
|
|
if ( !$context->getDebug() ) {
|
2015-10-01 18:05:08 +00:00
|
|
|
$stateScript = self::filter( 'minify-js', $stateScript );
|
2015-10-01 00:26:46 +00:00
|
|
|
}
|
2017-06-28 02:51:03 +00:00
|
|
|
// Use a linebreak between module script and state script (T162719)
|
|
|
|
|
$out = $this->ensureNewline( $out ) . $stateScript;
|
2010-09-04 04:00:09 +00:00
|
|
|
}
|
2014-05-04 14:46:16 +00:00
|
|
|
} else {
|
|
|
|
|
if ( count( $states ) ) {
|
2014-11-11 20:00:17 +00:00
|
|
|
$this->errors[] = 'Problematic modules: ' .
|
2017-07-23 01:24:09 +00:00
|
|
|
FormatJson::encode( $states, self::inDebugMode() );
|
2014-05-04 14:46:16 +00:00
|
|
|
}
|
2010-09-04 04:00:09 +00:00
|
|
|
}
|
2010-09-04 12:53:01 +00:00
|
|
|
|
2014-11-11 20:00:17 +00:00
|
|
|
return $out;
|
2010-09-04 04:00:09 +00:00
|
|
|
}
|
2010-10-20 00:22:25 +00:00
|
|
|
|
2017-06-28 02:51:03 +00:00
|
|
|
/**
|
|
|
|
|
* Ensure the string is either empty or ends in a line break
|
|
|
|
|
* @param string $str
|
|
|
|
|
* @return string
|
|
|
|
|
*/
|
|
|
|
|
private function ensureNewline( $str ) {
|
|
|
|
|
$end = substr( $str, -1 );
|
|
|
|
|
if ( $end === false || $end === "\n" ) {
|
|
|
|
|
return $str;
|
|
|
|
|
}
|
|
|
|
|
return $str . "\n";
|
|
|
|
|
}
|
|
|
|
|
|
2015-11-06 23:20:16 +00:00
|
|
|
/**
|
|
|
|
|
* Get names of modules that use a certain message.
|
|
|
|
|
*
|
|
|
|
|
* @param string $messageKey
|
|
|
|
|
* @return array List of module names
|
|
|
|
|
*/
|
|
|
|
|
public function getModulesByMessage( $messageKey ) {
|
2016-02-17 09:09:32 +00:00
|
|
|
$moduleNames = [];
|
2015-11-06 23:20:16 +00:00
|
|
|
foreach ( $this->getModuleNames() as $moduleName ) {
|
|
|
|
|
$module = $this->getModule( $moduleName );
|
|
|
|
|
if ( in_array( $messageKey, $module->getMessages() ) ) {
|
|
|
|
|
$moduleNames[] = $moduleName;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return $moduleNames;
|
|
|
|
|
}
|
|
|
|
|
|
2010-09-29 19:04:04 +00:00
|
|
|
/* Static Methods */
|
2010-10-20 00:22:25 +00:00
|
|
|
|
* Introduced Xml::encodeJsCall(), to replace the awkward repetitive code that was doing the same thing throughout the resource loader with varying degrees of security and correctness.
* Modified Xml::encodeJsVar() to allow it to pass through JS expressions without encoding, using a special object.
* In ResourceLoader::makeModuleResponse(), renamed $messages to $messagesBlob to make it clear that it's JSON-encoded, not an array.
* Fixed MessageBlobStore to store {} for an empty message array instead of [].
* In ResourceLoader::makeMessageSetScript(), fixed call to non-existent function mediaWiki.msg.set.
* For security, changed the calling convention of makeMessageSetScript() and makeLoaderImplementScript() to require explicit object construction of XmlJsCode() before interpreting their input as JS code.
* Documented several ResourceLoader static functions.
* In ResourceLoaderWikiModule, for readability, reduced the indenting level by flipping some if blocks and adding continue statements.
* In makeCustomLoaderScript(), allow non-numeric $version. The only caller I can find is already sending a non-numeric $version, presumably it was broken. Luckily there aren't any loader scripts in existence, I had to make one to test it.
* wfGetDb -> wfGetDB
* Added an extra line break in the startup module output, for readability.
* In ResourceLoaderStartUpModule::getModuleRegistrations(), fixed another assignment expression
2010-11-04 07:53:37 +00:00
|
|
|
/**
|
2014-03-07 16:50:57 +00:00
|
|
|
* Return JS code that calls mw.loader.implement with given module properties.
|
* Introduced Xml::encodeJsCall(), to replace the awkward repetitive code that was doing the same thing throughout the resource loader with varying degrees of security and correctness.
* Modified Xml::encodeJsVar() to allow it to pass through JS expressions without encoding, using a special object.
* In ResourceLoader::makeModuleResponse(), renamed $messages to $messagesBlob to make it clear that it's JSON-encoded, not an array.
* Fixed MessageBlobStore to store {} for an empty message array instead of [].
* In ResourceLoader::makeMessageSetScript(), fixed call to non-existent function mediaWiki.msg.set.
* For security, changed the calling convention of makeMessageSetScript() and makeLoaderImplementScript() to require explicit object construction of XmlJsCode() before interpreting their input as JS code.
* Documented several ResourceLoader static functions.
* In ResourceLoaderWikiModule, for readability, reduced the indenting level by flipping some if blocks and adding continue statements.
* In makeCustomLoaderScript(), allow non-numeric $version. The only caller I can find is already sending a non-numeric $version, presumably it was broken. Luckily there aren't any loader scripts in existence, I had to make one to test it.
* wfGetDb -> wfGetDB
* Added an extra line break in the startup module output, for readability.
* In ResourceLoaderStartUpModule::getModuleRegistrations(), fixed another assignment expression
2010-11-04 07:53:37 +00:00
|
|
|
*
|
2016-09-12 20:52:10 +00:00
|
|
|
* @param string $name Module name or implement key (format "`[name]@[version]`")
|
2016-09-15 04:01:09 +00:00
|
|
|
* @param XmlJsCode|array|string $scripts Code as XmlJsCode (to be wrapped in a closure),
|
|
|
|
|
* list of URLs to JavaScript files, or a string of JavaScript for `$.globalEval`.
|
2014-03-07 16:50:57 +00:00
|
|
|
* @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
|
|
|
|
|
* to CSS files keyed by media type
|
|
|
|
|
* @param mixed $messages List of messages associated with this module. May either be an
|
|
|
|
|
* associative array mapping message key to value, or a JSON-encoded message blob containing
|
|
|
|
|
* the same data, wrapped in an XmlJsCode object.
|
2014-10-10 00:07:14 +00:00
|
|
|
* @param array $templates Keys are name of templates and values are the source of
|
|
|
|
|
* the template.
|
2012-10-07 23:35:26 +00:00
|
|
|
* @throws MWException
|
2017-06-08 13:11:13 +00:00
|
|
|
* @return string JavaScript code
|
* Introduced Xml::encodeJsCall(), to replace the awkward repetitive code that was doing the same thing throughout the resource loader with varying degrees of security and correctness.
* Modified Xml::encodeJsVar() to allow it to pass through JS expressions without encoding, using a special object.
* In ResourceLoader::makeModuleResponse(), renamed $messages to $messagesBlob to make it clear that it's JSON-encoded, not an array.
* Fixed MessageBlobStore to store {} for an empty message array instead of [].
* In ResourceLoader::makeMessageSetScript(), fixed call to non-existent function mediaWiki.msg.set.
* For security, changed the calling convention of makeMessageSetScript() and makeLoaderImplementScript() to require explicit object construction of XmlJsCode() before interpreting their input as JS code.
* Documented several ResourceLoader static functions.
* In ResourceLoaderWikiModule, for readability, reduced the indenting level by flipping some if blocks and adding continue statements.
* In makeCustomLoaderScript(), allow non-numeric $version. The only caller I can find is already sending a non-numeric $version, presumably it was broken. Luckily there aren't any loader scripts in existence, I had to make one to test it.
* wfGetDb -> wfGetDB
* Added an extra line break in the startup module output, for readability.
* In ResourceLoaderStartUpModule::getModuleRegistrations(), fixed another assignment expression
2010-11-04 07:53:37 +00:00
|
|
|
*/
|
2016-09-15 04:01:09 +00:00
|
|
|
protected static function makeLoaderImplementScript(
|
2015-05-13 19:17:35 +00:00
|
|
|
$name, $scripts, $styles, $messages, $templates
|
2014-10-10 00:07:14 +00:00
|
|
|
) {
|
2016-09-15 04:01:09 +00:00
|
|
|
if ( $scripts instanceof XmlJsCode ) {
|
|
|
|
|
$scripts = new XmlJsCode( "function ( $, jQuery, require, module ) {\n{$scripts->value}\n}" );
|
|
|
|
|
} elseif ( !is_string( $scripts ) && !is_array( $scripts ) ) {
|
2011-05-15 12:36:21 +00:00
|
|
|
throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
|
2010-09-24 18:49:19 +00:00
|
|
|
}
|
2014-12-09 01:17:53 +00:00
|
|
|
// mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
|
|
|
|
|
// arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
|
|
|
|
|
// of "{}". Force them to objects.
|
2016-02-17 09:09:32 +00:00
|
|
|
$module = [
|
2014-12-09 01:17:53 +00:00
|
|
|
$name,
|
|
|
|
|
$scripts,
|
2015-06-17 20:01:00 +00:00
|
|
|
(object)$styles,
|
|
|
|
|
(object)$messages,
|
|
|
|
|
(object)$templates,
|
2016-02-17 09:09:32 +00:00
|
|
|
];
|
2014-12-09 01:17:53 +00:00
|
|
|
self::trimArray( $module );
|
|
|
|
|
|
2017-07-23 01:24:09 +00:00
|
|
|
return Xml::encodeJsCall( 'mw.loader.implement', $module, self::inDebugMode() );
|
2010-09-24 18:49:19 +00:00
|
|
|
}
|
|
|
|
|
|
* Introduced Xml::encodeJsCall(), to replace the awkward repetitive code that was doing the same thing throughout the resource loader with varying degrees of security and correctness.
* Modified Xml::encodeJsVar() to allow it to pass through JS expressions without encoding, using a special object.
* In ResourceLoader::makeModuleResponse(), renamed $messages to $messagesBlob to make it clear that it's JSON-encoded, not an array.
* Fixed MessageBlobStore to store {} for an empty message array instead of [].
* In ResourceLoader::makeMessageSetScript(), fixed call to non-existent function mediaWiki.msg.set.
* For security, changed the calling convention of makeMessageSetScript() and makeLoaderImplementScript() to require explicit object construction of XmlJsCode() before interpreting their input as JS code.
* Documented several ResourceLoader static functions.
* In ResourceLoaderWikiModule, for readability, reduced the indenting level by flipping some if blocks and adding continue statements.
* In makeCustomLoaderScript(), allow non-numeric $version. The only caller I can find is already sending a non-numeric $version, presumably it was broken. Luckily there aren't any loader scripts in existence, I had to make one to test it.
* wfGetDb -> wfGetDB
* Added an extra line break in the startup module output, for readability.
* In ResourceLoaderStartUpModule::getModuleRegistrations(), fixed another assignment expression
2010-11-04 07:53:37 +00:00
|
|
|
/**
|
|
|
|
|
* Returns JS code which, when called, will register a given list of messages.
|
|
|
|
|
*
|
2014-03-07 16:50:57 +00:00
|
|
|
* @param mixed $messages Either an associative array mapping message key to value, or a
|
|
|
|
|
* JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
|
2017-06-08 13:11:13 +00:00
|
|
|
* @return string JavaScript code
|
* Introduced Xml::encodeJsCall(), to replace the awkward repetitive code that was doing the same thing throughout the resource loader with varying degrees of security and correctness.
* Modified Xml::encodeJsVar() to allow it to pass through JS expressions without encoding, using a special object.
* In ResourceLoader::makeModuleResponse(), renamed $messages to $messagesBlob to make it clear that it's JSON-encoded, not an array.
* Fixed MessageBlobStore to store {} for an empty message array instead of [].
* In ResourceLoader::makeMessageSetScript(), fixed call to non-existent function mediaWiki.msg.set.
* For security, changed the calling convention of makeMessageSetScript() and makeLoaderImplementScript() to require explicit object construction of XmlJsCode() before interpreting their input as JS code.
* Documented several ResourceLoader static functions.
* In ResourceLoaderWikiModule, for readability, reduced the indenting level by flipping some if blocks and adding continue statements.
* In makeCustomLoaderScript(), allow non-numeric $version. The only caller I can find is already sending a non-numeric $version, presumably it was broken. Luckily there aren't any loader scripts in existence, I had to make one to test it.
* wfGetDb -> wfGetDB
* Added an extra line break in the startup module output, for readability.
* In ResourceLoaderStartUpModule::getModuleRegistrations(), fixed another assignment expression
2010-11-04 07:53:37 +00:00
|
|
|
*/
|
2010-09-24 18:49:19 +00:00
|
|
|
public static function makeMessageSetScript( $messages ) {
|
2014-03-07 17:49:50 +00:00
|
|
|
return Xml::encodeJsCall(
|
|
|
|
|
'mw.messages.set',
|
2016-02-17 09:09:32 +00:00
|
|
|
[ (object)$messages ],
|
2017-07-23 01:24:09 +00:00
|
|
|
self::inDebugMode()
|
2014-03-07 17:49:50 +00:00
|
|
|
);
|
2010-09-24 18:49:19 +00:00
|
|
|
}
|
|
|
|
|
|
* Introduced Xml::encodeJsCall(), to replace the awkward repetitive code that was doing the same thing throughout the resource loader with varying degrees of security and correctness.
* Modified Xml::encodeJsVar() to allow it to pass through JS expressions without encoding, using a special object.
* In ResourceLoader::makeModuleResponse(), renamed $messages to $messagesBlob to make it clear that it's JSON-encoded, not an array.
* Fixed MessageBlobStore to store {} for an empty message array instead of [].
* In ResourceLoader::makeMessageSetScript(), fixed call to non-existent function mediaWiki.msg.set.
* For security, changed the calling convention of makeMessageSetScript() and makeLoaderImplementScript() to require explicit object construction of XmlJsCode() before interpreting their input as JS code.
* Documented several ResourceLoader static functions.
* In ResourceLoaderWikiModule, for readability, reduced the indenting level by flipping some if blocks and adding continue statements.
* In makeCustomLoaderScript(), allow non-numeric $version. The only caller I can find is already sending a non-numeric $version, presumably it was broken. Luckily there aren't any loader scripts in existence, I had to make one to test it.
* wfGetDb -> wfGetDB
* Added an extra line break in the startup module output, for readability.
* In ResourceLoaderStartUpModule::getModuleRegistrations(), fixed another assignment expression
2010-11-04 07:53:37 +00:00
|
|
|
/**
|
2011-06-17 16:05:05 +00:00
|
|
|
* Combines an associative array mapping media type to CSS into a
|
2012-07-10 12:48:06 +00:00
|
|
|
* single stylesheet with "@media" blocks.
|
* Introduced Xml::encodeJsCall(), to replace the awkward repetitive code that was doing the same thing throughout the resource loader with varying degrees of security and correctness.
* Modified Xml::encodeJsVar() to allow it to pass through JS expressions without encoding, using a special object.
* In ResourceLoader::makeModuleResponse(), renamed $messages to $messagesBlob to make it clear that it's JSON-encoded, not an array.
* Fixed MessageBlobStore to store {} for an empty message array instead of [].
* In ResourceLoader::makeMessageSetScript(), fixed call to non-existent function mediaWiki.msg.set.
* For security, changed the calling convention of makeMessageSetScript() and makeLoaderImplementScript() to require explicit object construction of XmlJsCode() before interpreting their input as JS code.
* Documented several ResourceLoader static functions.
* In ResourceLoaderWikiModule, for readability, reduced the indenting level by flipping some if blocks and adding continue statements.
* In makeCustomLoaderScript(), allow non-numeric $version. The only caller I can find is already sending a non-numeric $version, presumably it was broken. Luckily there aren't any loader scripts in existence, I had to make one to test it.
* wfGetDb -> wfGetDB
* Added an extra line break in the startup module output, for readability.
* In ResourceLoaderStartUpModule::getModuleRegistrations(), fixed another assignment expression
2010-11-04 07:53:37 +00:00
|
|
|
*
|
2014-03-07 16:50:57 +00:00
|
|
|
* @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
|
|
|
|
|
* @return array
|
* Introduced Xml::encodeJsCall(), to replace the awkward repetitive code that was doing the same thing throughout the resource loader with varying degrees of security and correctness.
* Modified Xml::encodeJsVar() to allow it to pass through JS expressions without encoding, using a special object.
* In ResourceLoader::makeModuleResponse(), renamed $messages to $messagesBlob to make it clear that it's JSON-encoded, not an array.
* Fixed MessageBlobStore to store {} for an empty message array instead of [].
* In ResourceLoader::makeMessageSetScript(), fixed call to non-existent function mediaWiki.msg.set.
* For security, changed the calling convention of makeMessageSetScript() and makeLoaderImplementScript() to require explicit object construction of XmlJsCode() before interpreting their input as JS code.
* Documented several ResourceLoader static functions.
* In ResourceLoaderWikiModule, for readability, reduced the indenting level by flipping some if blocks and adding continue statements.
* In makeCustomLoaderScript(), allow non-numeric $version. The only caller I can find is already sending a non-numeric $version, presumably it was broken. Luckily there aren't any loader scripts in existence, I had to make one to test it.
* wfGetDb -> wfGetDB
* Added an extra line break in the startup module output, for readability.
* In ResourceLoaderStartUpModule::getModuleRegistrations(), fixed another assignment expression
2010-11-04 07:53:37 +00:00
|
|
|
*/
|
2014-06-04 19:30:14 +00:00
|
|
|
public static function makeCombinedStyles( array $stylePairs ) {
|
2016-02-17 09:09:32 +00:00
|
|
|
$out = [];
|
ResourceLoader: Refactor style loading
Fixes:
* bug 31676: Work around IE stylesheet limit.
* bug 35562: @import styles broken in modules that combine
multiple stylesheets.
* bug 40498: Don't output empty "@media print { }" blocks.
* bug 40500: Don't ignore media-type for urls in debug mode.
Approach:
* Re-use the same <style> tag so that we stay under the 31
stylesheet limit in IE. Unless the to-be-added css text from
the being-loaded module contains @import, in which case we do
create a new <style> tag and then re-use that one from that
point on (bug 31676).
* Return stylesheets as arrays, instead of a concatenated string.
This fixes bug 35562, because @import only works when at the
top of a stylesheet. By not unconditionally concatenating files
within a module on the server side already, @import will work
in e.g. module 'site' that contains 2 wiki pages.
This is normalized in ResourceLoader::makeCombinedStyles(),
so far only ResourceLoaderWikiModule makes use of this.
Misc. clean up and bug fixes:
* Reducing usage of jQuery() and mw.html.element() where
native DOM would be very simple and faster. Aside from
simplicity and speed, this is also working towards a more
stand-alone ResourceLoader.
* Trim server output a little bit more
- Redundant new line after minify-css (it is now an array, so
no need to keep space afterwards)
- Redundant semi-colon after minify-js if it ends in a colon
* Allow space in styleTest.css.php
* Clean up and extend unit tests to cover for these features
and bug fixes.
* Don't set styleEl.rel = 'stylesheet'; that has no business
on a <style> tag.
* Fix bug in mw.loader's addStyleTag(). It turns out IE6
has an odd security measure that does not allow manipulation
of elements (at least style tags) that are created by a
different script (even if that script was served from the same
domain/origin etc.). We didn't ran into this before because
we only created new style tags, never appended to them. Now
that we do, this came up. Took a while to figure out because
it was created by mediawiki.js but it calls jQuery which did
the actual dom insertion. Odd thing is, we load jquery.js and
mediawiki.js in the same request even...
Without this all css-url related mw.loader tests would fail
in IE6.
* mediawiki.js and mediawiki.test.js now pass jshint again.
Tested (and passing qunit/?module=mediawiki; 123 of 123):
* Chrome 14, 21
* Firefox 3.0, 3.6, 4, 7, 14, 15, 16beta
* IE 6, 7, 8, 9
* Safari 4.0, 5.0, 5.1
* Opera 10.0, 11.1, 11.5, 11.6, 12.0, 12.5beta
* iPhone 3GS / iOS 3.0 / Mobile Safari 4.0
iPhone 4 / iOS 4.0.1 / Mobile Safari 4.0.5
iPhone 4S / iOS 6.0 Beta / Mobile Safari 6.0
Change-Id: I3e8227ddb87fd9441071ca935439fc6467751dab
2012-07-25 21:20:21 +00:00
|
|
|
foreach ( $stylePairs as $media => $styles ) {
|
|
|
|
|
// ResourceLoaderFileModule::getStyle can return the styles
|
|
|
|
|
// as a string or an array of strings. This is to allow separation in
|
|
|
|
|
// the front-end.
|
2013-04-02 20:28:40 +00:00
|
|
|
$styles = (array)$styles;
|
ResourceLoader: Refactor style loading
Fixes:
* bug 31676: Work around IE stylesheet limit.
* bug 35562: @import styles broken in modules that combine
multiple stylesheets.
* bug 40498: Don't output empty "@media print { }" blocks.
* bug 40500: Don't ignore media-type for urls in debug mode.
Approach:
* Re-use the same <style> tag so that we stay under the 31
stylesheet limit in IE. Unless the to-be-added css text from
the being-loaded module contains @import, in which case we do
create a new <style> tag and then re-use that one from that
point on (bug 31676).
* Return stylesheets as arrays, instead of a concatenated string.
This fixes bug 35562, because @import only works when at the
top of a stylesheet. By not unconditionally concatenating files
within a module on the server side already, @import will work
in e.g. module 'site' that contains 2 wiki pages.
This is normalized in ResourceLoader::makeCombinedStyles(),
so far only ResourceLoaderWikiModule makes use of this.
Misc. clean up and bug fixes:
* Reducing usage of jQuery() and mw.html.element() where
native DOM would be very simple and faster. Aside from
simplicity and speed, this is also working towards a more
stand-alone ResourceLoader.
* Trim server output a little bit more
- Redundant new line after minify-css (it is now an array, so
no need to keep space afterwards)
- Redundant semi-colon after minify-js if it ends in a colon
* Allow space in styleTest.css.php
* Clean up and extend unit tests to cover for these features
and bug fixes.
* Don't set styleEl.rel = 'stylesheet'; that has no business
on a <style> tag.
* Fix bug in mw.loader's addStyleTag(). It turns out IE6
has an odd security measure that does not allow manipulation
of elements (at least style tags) that are created by a
different script (even if that script was served from the same
domain/origin etc.). We didn't ran into this before because
we only created new style tags, never appended to them. Now
that we do, this came up. Took a while to figure out because
it was created by mediawiki.js but it calls jQuery which did
the actual dom insertion. Odd thing is, we load jquery.js and
mediawiki.js in the same request even...
Without this all css-url related mw.loader tests would fail
in IE6.
* mediawiki.js and mediawiki.test.js now pass jshint again.
Tested (and passing qunit/?module=mediawiki; 123 of 123):
* Chrome 14, 21
* Firefox 3.0, 3.6, 4, 7, 14, 15, 16beta
* IE 6, 7, 8, 9
* Safari 4.0, 5.0, 5.1
* Opera 10.0, 11.1, 11.5, 11.6, 12.0, 12.5beta
* iPhone 3GS / iOS 3.0 / Mobile Safari 4.0
iPhone 4 / iOS 4.0.1 / Mobile Safari 4.0.5
iPhone 4S / iOS 6.0 Beta / Mobile Safari 6.0
Change-Id: I3e8227ddb87fd9441071ca935439fc6467751dab
2012-07-25 21:20:21 +00:00
|
|
|
foreach ( $styles as $style ) {
|
|
|
|
|
$style = trim( $style );
|
2017-02-20 22:44:19 +00:00
|
|
|
// Don't output an empty "@media print { }" block (T42498)
|
ResourceLoader: Refactor style loading
Fixes:
* bug 31676: Work around IE stylesheet limit.
* bug 35562: @import styles broken in modules that combine
multiple stylesheets.
* bug 40498: Don't output empty "@media print { }" blocks.
* bug 40500: Don't ignore media-type for urls in debug mode.
Approach:
* Re-use the same <style> tag so that we stay under the 31
stylesheet limit in IE. Unless the to-be-added css text from
the being-loaded module contains @import, in which case we do
create a new <style> tag and then re-use that one from that
point on (bug 31676).
* Return stylesheets as arrays, instead of a concatenated string.
This fixes bug 35562, because @import only works when at the
top of a stylesheet. By not unconditionally concatenating files
within a module on the server side already, @import will work
in e.g. module 'site' that contains 2 wiki pages.
This is normalized in ResourceLoader::makeCombinedStyles(),
so far only ResourceLoaderWikiModule makes use of this.
Misc. clean up and bug fixes:
* Reducing usage of jQuery() and mw.html.element() where
native DOM would be very simple and faster. Aside from
simplicity and speed, this is also working towards a more
stand-alone ResourceLoader.
* Trim server output a little bit more
- Redundant new line after minify-css (it is now an array, so
no need to keep space afterwards)
- Redundant semi-colon after minify-js if it ends in a colon
* Allow space in styleTest.css.php
* Clean up and extend unit tests to cover for these features
and bug fixes.
* Don't set styleEl.rel = 'stylesheet'; that has no business
on a <style> tag.
* Fix bug in mw.loader's addStyleTag(). It turns out IE6
has an odd security measure that does not allow manipulation
of elements (at least style tags) that are created by a
different script (even if that script was served from the same
domain/origin etc.). We didn't ran into this before because
we only created new style tags, never appended to them. Now
that we do, this came up. Took a while to figure out because
it was created by mediawiki.js but it calls jQuery which did
the actual dom insertion. Odd thing is, we load jquery.js and
mediawiki.js in the same request even...
Without this all css-url related mw.loader tests would fail
in IE6.
* mediawiki.js and mediawiki.test.js now pass jshint again.
Tested (and passing qunit/?module=mediawiki; 123 of 123):
* Chrome 14, 21
* Firefox 3.0, 3.6, 4, 7, 14, 15, 16beta
* IE 6, 7, 8, 9
* Safari 4.0, 5.0, 5.1
* Opera 10.0, 11.1, 11.5, 11.6, 12.0, 12.5beta
* iPhone 3GS / iOS 3.0 / Mobile Safari 4.0
iPhone 4 / iOS 4.0.1 / Mobile Safari 4.0.5
iPhone 4S / iOS 6.0 Beta / Mobile Safari 6.0
Change-Id: I3e8227ddb87fd9441071ca935439fc6467751dab
2012-07-25 21:20:21 +00:00
|
|
|
if ( $style !== '' ) {
|
|
|
|
|
// Transform the media type based on request params and config
|
|
|
|
|
// The way that this relies on $wgRequest to propagate request params is slightly evil
|
|
|
|
|
$media = OutputPage::transformCssMedia( $media );
|
|
|
|
|
|
|
|
|
|
if ( $media === '' || $media == 'all' ) {
|
|
|
|
|
$out[] = $style;
|
2013-04-17 14:52:47 +00:00
|
|
|
} elseif ( is_string( $media ) ) {
|
ResourceLoader: Refactor style loading
Fixes:
* bug 31676: Work around IE stylesheet limit.
* bug 35562: @import styles broken in modules that combine
multiple stylesheets.
* bug 40498: Don't output empty "@media print { }" blocks.
* bug 40500: Don't ignore media-type for urls in debug mode.
Approach:
* Re-use the same <style> tag so that we stay under the 31
stylesheet limit in IE. Unless the to-be-added css text from
the being-loaded module contains @import, in which case we do
create a new <style> tag and then re-use that one from that
point on (bug 31676).
* Return stylesheets as arrays, instead of a concatenated string.
This fixes bug 35562, because @import only works when at the
top of a stylesheet. By not unconditionally concatenating files
within a module on the server side already, @import will work
in e.g. module 'site' that contains 2 wiki pages.
This is normalized in ResourceLoader::makeCombinedStyles(),
so far only ResourceLoaderWikiModule makes use of this.
Misc. clean up and bug fixes:
* Reducing usage of jQuery() and mw.html.element() where
native DOM would be very simple and faster. Aside from
simplicity and speed, this is also working towards a more
stand-alone ResourceLoader.
* Trim server output a little bit more
- Redundant new line after minify-css (it is now an array, so
no need to keep space afterwards)
- Redundant semi-colon after minify-js if it ends in a colon
* Allow space in styleTest.css.php
* Clean up and extend unit tests to cover for these features
and bug fixes.
* Don't set styleEl.rel = 'stylesheet'; that has no business
on a <style> tag.
* Fix bug in mw.loader's addStyleTag(). It turns out IE6
has an odd security measure that does not allow manipulation
of elements (at least style tags) that are created by a
different script (even if that script was served from the same
domain/origin etc.). We didn't ran into this before because
we only created new style tags, never appended to them. Now
that we do, this came up. Took a while to figure out because
it was created by mediawiki.js but it calls jQuery which did
the actual dom insertion. Odd thing is, we load jquery.js and
mediawiki.js in the same request even...
Without this all css-url related mw.loader tests would fail
in IE6.
* mediawiki.js and mediawiki.test.js now pass jshint again.
Tested (and passing qunit/?module=mediawiki; 123 of 123):
* Chrome 14, 21
* Firefox 3.0, 3.6, 4, 7, 14, 15, 16beta
* IE 6, 7, 8, 9
* Safari 4.0, 5.0, 5.1
* Opera 10.0, 11.1, 11.5, 11.6, 12.0, 12.5beta
* iPhone 3GS / iOS 3.0 / Mobile Safari 4.0
iPhone 4 / iOS 4.0.1 / Mobile Safari 4.0.5
iPhone 4S / iOS 6.0 Beta / Mobile Safari 6.0
Change-Id: I3e8227ddb87fd9441071ca935439fc6467751dab
2012-07-25 21:20:21 +00:00
|
|
|
$out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
|
|
|
|
|
}
|
|
|
|
|
// else: skip
|
|
|
|
|
}
|
2011-01-07 20:22:50 +00:00
|
|
|
}
|
2010-09-24 18:49:19 +00:00
|
|
|
}
|
|
|
|
|
return $out;
|
|
|
|
|
}
|
|
|
|
|
|
* Introduced Xml::encodeJsCall(), to replace the awkward repetitive code that was doing the same thing throughout the resource loader with varying degrees of security and correctness.
* Modified Xml::encodeJsVar() to allow it to pass through JS expressions without encoding, using a special object.
* In ResourceLoader::makeModuleResponse(), renamed $messages to $messagesBlob to make it clear that it's JSON-encoded, not an array.
* Fixed MessageBlobStore to store {} for an empty message array instead of [].
* In ResourceLoader::makeMessageSetScript(), fixed call to non-existent function mediaWiki.msg.set.
* For security, changed the calling convention of makeMessageSetScript() and makeLoaderImplementScript() to require explicit object construction of XmlJsCode() before interpreting their input as JS code.
* Documented several ResourceLoader static functions.
* In ResourceLoaderWikiModule, for readability, reduced the indenting level by flipping some if blocks and adding continue statements.
* In makeCustomLoaderScript(), allow non-numeric $version. The only caller I can find is already sending a non-numeric $version, presumably it was broken. Luckily there aren't any loader scripts in existence, I had to make one to test it.
* wfGetDb -> wfGetDB
* Added an extra line break in the startup module output, for readability.
* In ResourceLoaderStartUpModule::getModuleRegistrations(), fixed another assignment expression
2010-11-04 07:53:37 +00:00
|
|
|
/**
|
2011-06-17 16:05:05 +00:00
|
|
|
* Returns a JS call to mw.loader.state, which sets the state of a
|
* Introduced Xml::encodeJsCall(), to replace the awkward repetitive code that was doing the same thing throughout the resource loader with varying degrees of security and correctness.
* Modified Xml::encodeJsVar() to allow it to pass through JS expressions without encoding, using a special object.
* In ResourceLoader::makeModuleResponse(), renamed $messages to $messagesBlob to make it clear that it's JSON-encoded, not an array.
* Fixed MessageBlobStore to store {} for an empty message array instead of [].
* In ResourceLoader::makeMessageSetScript(), fixed call to non-existent function mediaWiki.msg.set.
* For security, changed the calling convention of makeMessageSetScript() and makeLoaderImplementScript() to require explicit object construction of XmlJsCode() before interpreting their input as JS code.
* Documented several ResourceLoader static functions.
* In ResourceLoaderWikiModule, for readability, reduced the indenting level by flipping some if blocks and adding continue statements.
* In makeCustomLoaderScript(), allow non-numeric $version. The only caller I can find is already sending a non-numeric $version, presumably it was broken. Luckily there aren't any loader scripts in existence, I had to make one to test it.
* wfGetDb -> wfGetDB
* Added an extra line break in the startup module output, for readability.
* In ResourceLoaderStartUpModule::getModuleRegistrations(), fixed another assignment expression
2010-11-04 07:53:37 +00:00
|
|
|
* module or modules to a given value. Has two calling conventions:
|
|
|
|
|
*
|
|
|
|
|
* - ResourceLoader::makeLoaderStateScript( $name, $state ):
|
|
|
|
|
* Set the state of a single module called $name to $state
|
|
|
|
|
*
|
2016-08-13 01:10:40 +00:00
|
|
|
* - ResourceLoader::makeLoaderStateScript( [ $name => $state, ... ] ):
|
* Introduced Xml::encodeJsCall(), to replace the awkward repetitive code that was doing the same thing throughout the resource loader with varying degrees of security and correctness.
* Modified Xml::encodeJsVar() to allow it to pass through JS expressions without encoding, using a special object.
* In ResourceLoader::makeModuleResponse(), renamed $messages to $messagesBlob to make it clear that it's JSON-encoded, not an array.
* Fixed MessageBlobStore to store {} for an empty message array instead of [].
* In ResourceLoader::makeMessageSetScript(), fixed call to non-existent function mediaWiki.msg.set.
* For security, changed the calling convention of makeMessageSetScript() and makeLoaderImplementScript() to require explicit object construction of XmlJsCode() before interpreting their input as JS code.
* Documented several ResourceLoader static functions.
* In ResourceLoaderWikiModule, for readability, reduced the indenting level by flipping some if blocks and adding continue statements.
* In makeCustomLoaderScript(), allow non-numeric $version. The only caller I can find is already sending a non-numeric $version, presumably it was broken. Luckily there aren't any loader scripts in existence, I had to make one to test it.
* wfGetDb -> wfGetDB
* Added an extra line break in the startup module output, for readability.
* In ResourceLoaderStartUpModule::getModuleRegistrations(), fixed another assignment expression
2010-11-04 07:53:37 +00:00
|
|
|
* Set the state of modules with the given names to the given states
|
2011-05-21 17:45:20 +00:00
|
|
|
*
|
2014-03-07 16:50:57 +00:00
|
|
|
* @param string $name
|
2014-04-20 21:33:05 +00:00
|
|
|
* @param string $state
|
2017-06-08 13:11:13 +00:00
|
|
|
* @return string JavaScript code
|
* Introduced Xml::encodeJsCall(), to replace the awkward repetitive code that was doing the same thing throughout the resource loader with varying degrees of security and correctness.
* Modified Xml::encodeJsVar() to allow it to pass through JS expressions without encoding, using a special object.
* In ResourceLoader::makeModuleResponse(), renamed $messages to $messagesBlob to make it clear that it's JSON-encoded, not an array.
* Fixed MessageBlobStore to store {} for an empty message array instead of [].
* In ResourceLoader::makeMessageSetScript(), fixed call to non-existent function mediaWiki.msg.set.
* For security, changed the calling convention of makeMessageSetScript() and makeLoaderImplementScript() to require explicit object construction of XmlJsCode() before interpreting their input as JS code.
* Documented several ResourceLoader static functions.
* In ResourceLoaderWikiModule, for readability, reduced the indenting level by flipping some if blocks and adding continue statements.
* In makeCustomLoaderScript(), allow non-numeric $version. The only caller I can find is already sending a non-numeric $version, presumably it was broken. Luckily there aren't any loader scripts in existence, I had to make one to test it.
* wfGetDb -> wfGetDB
* Added an extra line break in the startup module output, for readability.
* In ResourceLoaderStartUpModule::getModuleRegistrations(), fixed another assignment expression
2010-11-04 07:53:37 +00:00
|
|
|
*/
|
2010-09-24 18:49:19 +00:00
|
|
|
public static function makeLoaderStateScript( $name, $state = null ) {
|
|
|
|
|
if ( is_array( $name ) ) {
|
2014-03-07 17:49:50 +00:00
|
|
|
return Xml::encodeJsCall(
|
|
|
|
|
'mw.loader.state',
|
2016-02-17 09:09:32 +00:00
|
|
|
[ $name ],
|
2017-07-23 01:24:09 +00:00
|
|
|
self::inDebugMode()
|
2014-03-07 17:49:50 +00:00
|
|
|
);
|
2010-09-24 18:49:19 +00:00
|
|
|
} else {
|
2014-03-07 17:49:50 +00:00
|
|
|
return Xml::encodeJsCall(
|
|
|
|
|
'mw.loader.state',
|
2016-02-17 09:09:32 +00:00
|
|
|
[ $name, $state ],
|
2017-07-23 01:24:09 +00:00
|
|
|
self::inDebugMode()
|
2014-03-07 17:49:50 +00:00
|
|
|
);
|
2010-09-24 18:49:19 +00:00
|
|
|
}
|
|
|
|
|
}
|
2010-09-24 22:10:25 +00:00
|
|
|
|
* Introduced Xml::encodeJsCall(), to replace the awkward repetitive code that was doing the same thing throughout the resource loader with varying degrees of security and correctness.
* Modified Xml::encodeJsVar() to allow it to pass through JS expressions without encoding, using a special object.
* In ResourceLoader::makeModuleResponse(), renamed $messages to $messagesBlob to make it clear that it's JSON-encoded, not an array.
* Fixed MessageBlobStore to store {} for an empty message array instead of [].
* In ResourceLoader::makeMessageSetScript(), fixed call to non-existent function mediaWiki.msg.set.
* For security, changed the calling convention of makeMessageSetScript() and makeLoaderImplementScript() to require explicit object construction of XmlJsCode() before interpreting their input as JS code.
* Documented several ResourceLoader static functions.
* In ResourceLoaderWikiModule, for readability, reduced the indenting level by flipping some if blocks and adding continue statements.
* In makeCustomLoaderScript(), allow non-numeric $version. The only caller I can find is already sending a non-numeric $version, presumably it was broken. Luckily there aren't any loader scripts in existence, I had to make one to test it.
* wfGetDb -> wfGetDB
* Added an extra line break in the startup module output, for readability.
* In ResourceLoaderStartUpModule::getModuleRegistrations(), fixed another assignment expression
2010-11-04 07:53:37 +00:00
|
|
|
/**
|
|
|
|
|
* Returns JS code which calls the script given by $script. The script will
|
2011-06-17 16:05:05 +00:00
|
|
|
* be called with local variables name, version, dependencies and group,
|
|
|
|
|
* which will have values corresponding to $name, $version, $dependencies
|
|
|
|
|
* and $group as supplied.
|
* Introduced Xml::encodeJsCall(), to replace the awkward repetitive code that was doing the same thing throughout the resource loader with varying degrees of security and correctness.
* Modified Xml::encodeJsVar() to allow it to pass through JS expressions without encoding, using a special object.
* In ResourceLoader::makeModuleResponse(), renamed $messages to $messagesBlob to make it clear that it's JSON-encoded, not an array.
* Fixed MessageBlobStore to store {} for an empty message array instead of [].
* In ResourceLoader::makeMessageSetScript(), fixed call to non-existent function mediaWiki.msg.set.
* For security, changed the calling convention of makeMessageSetScript() and makeLoaderImplementScript() to require explicit object construction of XmlJsCode() before interpreting their input as JS code.
* Documented several ResourceLoader static functions.
* In ResourceLoaderWikiModule, for readability, reduced the indenting level by flipping some if blocks and adding continue statements.
* In makeCustomLoaderScript(), allow non-numeric $version. The only caller I can find is already sending a non-numeric $version, presumably it was broken. Luckily there aren't any loader scripts in existence, I had to make one to test it.
* wfGetDb -> wfGetDB
* Added an extra line break in the startup module output, for readability.
* In ResourceLoaderStartUpModule::getModuleRegistrations(), fixed another assignment expression
2010-11-04 07:53:37 +00:00
|
|
|
*
|
2013-03-11 17:15:01 +00:00
|
|
|
* @param string $name Module name
|
resourceloader: Replace timestamp system with version hashing
Modules now track their version via getVersionHash() instead of getModifiedTime().
== Background ==
While some resources have observeable timestamps (e.g. files stored on disk),
many other resources do not. E.g. config variables, and module definitions.
For static file modules, one can e.g. revert one of more files in a module to a
previous version and not affect the max timestamp.
Wiki modules include pages only if they exist. The user module supports common.js
and skin.js. By default neither exists. If a user has both, and then the
less-recently modified one is deleted, the max-timestamp remains unchanged.
For client-side caching, batch requests use "Math.max" on the relevant timestamps.
Again, if a module changes but another module is more recent (e.g. out-of-order
deployment, or out-of-order discovery), the change would not result in a cache miss.
More scenarios can be found in the associated Phabricator tasks.
== Version hash ==
Previously we virtually mapped these variables to a timestamp by storing the current
time alongside a hash of the value in ObjectCache. Considering the number of
possible request contexts (wikis * modules * users * skins * languages) this doesn't
work well. It results in needless cache invalidation when the first time observation
is purged due to LRU algorithms. It also has other minor bugs leading to fewer
cache hits.
All modules automatically get the benefits of version hashing with this change.
The old getDefinitionMtime() and getHashMtime() have been replaced with dummies
that return 1. These functions are often called from getModifiedTime() in subclasses.
For backward-compatibility, their respective values (definition summary and hash)
are now included in getVersionHash directly.
As examples, the following modules have been updated to use getVersionHash directly.
Other modules still work fine and can be updated later.
* ResourceLoaderFileModule
* ResourceLoaderEditToolbarModule
* ResourceLoaderStartUpModule
* ResourceLoaderWikiModule
The presence of hashes in place of timestamps increases the startup module size on
a default MediaWiki install from 4.4k to 5.8k (after gzip and minification).
== ETag ==
Since timestamps are no longer tracked, we need a different way to implement caching
for cache proxies (e.g. Varnish) and web browsers. Previously we used the
Last-Modified header (in combination with Cache-Control and Expires).
Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match).
Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default.
They instruct browsers to allow usage of partial Range requests. Since our responses
are dynamically generated, we need to use the Weak version of ETag.
While this sounds bad, it's no different than Last-Modified. As reassured by
RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the
specified behaviour behind Last-Modified follows the same "Weak" caching logic as
Entity tags. It's just that entity tags are capable of a stricter mode (whereas
Last-Modified is inherently weak).
== File cache ==
If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache
load.php responses. While the blind TTL handling (during the allowed expiry period)
is still maxage/timestamp based, tryRespondNotModified() now requires the caller to
know the expected ETag.
For this to work, the FileCache handling had to be moved from the top of
ResoureLoader::respond() to after the expected ETag is computed.
This also allows us to remove the duplicate tryRespondNotModified() handling since
that's is already handled by ResourceLoader::respond() meanwhile.
== Misc ==
* Remove redundant modifiedTime cache in ResourceLoaderFileModule.
* Change bugzilla references to Phabricator.
* Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this
logic was duplicated in each place the modified timestamp was used.
* It's easy to forget calling the parent class in getDefinitionSummary().
Previously this method only tracked 'class' by default. As such, various
extensions hardcoded that one value instead of calling the parent and extending
the array. To better prevent this in the future, getVersionHash() now asserts
that the '_cacheEpoch' property made it through.
* tests: Don't use getDefinitionSummary() as an API.
Fix ResourceLoaderWikiModuleTest to call getPages properly.
* In tests, the default timestamp used to be 1388534400000 (which is the unix time
of 20140101000000; the unit tests' CacheEpoch). The new version hash of these
modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of:
'{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}'
* Add sha1.js library for client-side hash generation.
Compared various different implementations for code size (after minfication/gzip),
and speed (when used for short hexidecimal strings).
https://jsperf.com/sha1-implementations
- CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k)
http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js
Chrome: 45k, Firefox: 89k, Safari: 92k
- jsSHA <https://github.com/Caligatio/jsSHA>
https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k)
Chrome: 65k, Firefox: 53k, Safari: 69k
- phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k)
https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js
Chrome: 200k, Firefox: 280k, Safari: 78k
Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous,
only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate
code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being
needed in the module loader, we'd have to load the fallback regardless. Considering
this is not used in a critical path for performance, it's not worth shipping two
implementations for this optimisation.
May also resolve:
* T44094
* T90411
* T94810
Bug: T94074
Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
|
|
|
* @param string $version Module version hash
|
2013-03-11 17:15:01 +00:00
|
|
|
* @param array $dependencies List of module names on which this module depends
|
|
|
|
|
* @param string $group Group which the module is in.
|
|
|
|
|
* @param string $source Source of the module, or 'local' if not foreign.
|
|
|
|
|
* @param string $script JavaScript code
|
2017-06-08 13:11:13 +00:00
|
|
|
* @return string JavaScript code
|
* Introduced Xml::encodeJsCall(), to replace the awkward repetitive code that was doing the same thing throughout the resource loader with varying degrees of security and correctness.
* Modified Xml::encodeJsVar() to allow it to pass through JS expressions without encoding, using a special object.
* In ResourceLoader::makeModuleResponse(), renamed $messages to $messagesBlob to make it clear that it's JSON-encoded, not an array.
* Fixed MessageBlobStore to store {} for an empty message array instead of [].
* In ResourceLoader::makeMessageSetScript(), fixed call to non-existent function mediaWiki.msg.set.
* For security, changed the calling convention of makeMessageSetScript() and makeLoaderImplementScript() to require explicit object construction of XmlJsCode() before interpreting their input as JS code.
* Documented several ResourceLoader static functions.
* In ResourceLoaderWikiModule, for readability, reduced the indenting level by flipping some if blocks and adding continue statements.
* In makeCustomLoaderScript(), allow non-numeric $version. The only caller I can find is already sending a non-numeric $version, presumably it was broken. Luckily there aren't any loader scripts in existence, I had to make one to test it.
* wfGetDb -> wfGetDB
* Added an extra line break in the startup module output, for readability.
* In ResourceLoaderStartUpModule::getModuleRegistrations(), fixed another assignment expression
2010-11-04 07:53:37 +00:00
|
|
|
*/
|
2014-05-10 08:39:37 +00:00
|
|
|
public static function makeCustomLoaderScript( $name, $version, $dependencies,
|
|
|
|
|
$group, $source, $script
|
|
|
|
|
) {
|
2010-09-24 21:03:29 +00:00
|
|
|
$script = str_replace( "\n", "\n\t", trim( $script ) );
|
2011-06-17 16:05:05 +00:00
|
|
|
return Xml::encodeJsCall(
|
2012-02-13 15:17:15 +00:00
|
|
|
"( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
|
2016-02-17 09:09:32 +00:00
|
|
|
[ $name, $version, $dependencies, $group, $source ],
|
2017-07-23 01:24:09 +00:00
|
|
|
self::inDebugMode()
|
2014-03-07 17:49:50 +00:00
|
|
|
);
|
2010-09-24 21:03:29 +00:00
|
|
|
}
|
2010-09-24 22:10:25 +00:00
|
|
|
|
2014-12-09 01:17:53 +00:00
|
|
|
private static function isEmptyObject( stdClass $obj ) {
|
2015-09-28 19:18:46 +00:00
|
|
|
foreach ( $obj as $key => $value ) {
|
2014-12-09 01:17:53 +00:00
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
|
2014-12-09 00:29:19 +00:00
|
|
|
/**
|
|
|
|
|
* Remove empty values from the end of an array.
|
|
|
|
|
*
|
|
|
|
|
* Values considered empty:
|
|
|
|
|
*
|
|
|
|
|
* - null
|
2016-09-12 10:06:37 +00:00
|
|
|
* - []
|
2014-12-09 01:17:53 +00:00
|
|
|
* - new XmlJsCode( '{}' )
|
2016-09-12 10:06:37 +00:00
|
|
|
* - new stdClass() // (object) []
|
2014-12-09 00:29:19 +00:00
|
|
|
*
|
|
|
|
|
* @param Array $array
|
|
|
|
|
*/
|
2016-02-17 10:31:52 +00:00
|
|
|
private static function trimArray( array &$array ) {
|
2014-12-09 00:29:19 +00:00
|
|
|
$i = count( $array );
|
|
|
|
|
while ( $i-- ) {
|
2014-12-09 01:17:53 +00:00
|
|
|
if ( $array[$i] === null
|
2016-02-17 09:09:32 +00:00
|
|
|
|| $array[$i] === []
|
2014-12-09 01:17:53 +00:00
|
|
|
|| ( $array[$i] instanceof XmlJsCode && $array[$i]->value === '{}' )
|
|
|
|
|
|| ( $array[$i] instanceof stdClass && self::isEmptyObject( $array[$i] ) )
|
|
|
|
|
) {
|
2014-12-09 00:29:19 +00:00
|
|
|
unset( $array[$i] );
|
|
|
|
|
} else {
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
* Introduced Xml::encodeJsCall(), to replace the awkward repetitive code that was doing the same thing throughout the resource loader with varying degrees of security and correctness.
* Modified Xml::encodeJsVar() to allow it to pass through JS expressions without encoding, using a special object.
* In ResourceLoader::makeModuleResponse(), renamed $messages to $messagesBlob to make it clear that it's JSON-encoded, not an array.
* Fixed MessageBlobStore to store {} for an empty message array instead of [].
* In ResourceLoader::makeMessageSetScript(), fixed call to non-existent function mediaWiki.msg.set.
* For security, changed the calling convention of makeMessageSetScript() and makeLoaderImplementScript() to require explicit object construction of XmlJsCode() before interpreting their input as JS code.
* Documented several ResourceLoader static functions.
* In ResourceLoaderWikiModule, for readability, reduced the indenting level by flipping some if blocks and adding continue statements.
* In makeCustomLoaderScript(), allow non-numeric $version. The only caller I can find is already sending a non-numeric $version, presumably it was broken. Luckily there aren't any loader scripts in existence, I had to make one to test it.
* wfGetDb -> wfGetDB
* Added an extra line break in the startup module output, for readability.
* In ResourceLoaderStartUpModule::getModuleRegistrations(), fixed another assignment expression
2010-11-04 07:53:37 +00:00
|
|
|
/**
|
2011-06-17 16:05:05 +00:00
|
|
|
* Returns JS code which calls mw.loader.register with the given
|
* Introduced Xml::encodeJsCall(), to replace the awkward repetitive code that was doing the same thing throughout the resource loader with varying degrees of security and correctness.
* Modified Xml::encodeJsVar() to allow it to pass through JS expressions without encoding, using a special object.
* In ResourceLoader::makeModuleResponse(), renamed $messages to $messagesBlob to make it clear that it's JSON-encoded, not an array.
* Fixed MessageBlobStore to store {} for an empty message array instead of [].
* In ResourceLoader::makeMessageSetScript(), fixed call to non-existent function mediaWiki.msg.set.
* For security, changed the calling convention of makeMessageSetScript() and makeLoaderImplementScript() to require explicit object construction of XmlJsCode() before interpreting their input as JS code.
* Documented several ResourceLoader static functions.
* In ResourceLoaderWikiModule, for readability, reduced the indenting level by flipping some if blocks and adding continue statements.
* In makeCustomLoaderScript(), allow non-numeric $version. The only caller I can find is already sending a non-numeric $version, presumably it was broken. Luckily there aren't any loader scripts in existence, I had to make one to test it.
* wfGetDb -> wfGetDB
* Added an extra line break in the startup module output, for readability.
* In ResourceLoaderStartUpModule::getModuleRegistrations(), fixed another assignment expression
2010-11-04 07:53:37 +00:00
|
|
|
* parameters. Has three calling conventions:
|
|
|
|
|
*
|
2014-08-25 11:43:41 +00:00
|
|
|
* - ResourceLoader::makeLoaderRegisterScript( $name, $version,
|
|
|
|
|
* $dependencies, $group, $source, $skip
|
|
|
|
|
* ):
|
|
|
|
|
* Register a single module.
|
* Introduced Xml::encodeJsCall(), to replace the awkward repetitive code that was doing the same thing throughout the resource loader with varying degrees of security and correctness.
* Modified Xml::encodeJsVar() to allow it to pass through JS expressions without encoding, using a special object.
* In ResourceLoader::makeModuleResponse(), renamed $messages to $messagesBlob to make it clear that it's JSON-encoded, not an array.
* Fixed MessageBlobStore to store {} for an empty message array instead of [].
* In ResourceLoader::makeMessageSetScript(), fixed call to non-existent function mediaWiki.msg.set.
* For security, changed the calling convention of makeMessageSetScript() and makeLoaderImplementScript() to require explicit object construction of XmlJsCode() before interpreting their input as JS code.
* Documented several ResourceLoader static functions.
* In ResourceLoaderWikiModule, for readability, reduced the indenting level by flipping some if blocks and adding continue statements.
* In makeCustomLoaderScript(), allow non-numeric $version. The only caller I can find is already sending a non-numeric $version, presumably it was broken. Luckily there aren't any loader scripts in existence, I had to make one to test it.
* wfGetDb -> wfGetDB
* Added an extra line break in the startup module output, for readability.
* In ResourceLoaderStartUpModule::getModuleRegistrations(), fixed another assignment expression
2010-11-04 07:53:37 +00:00
|
|
|
*
|
2016-08-13 01:10:40 +00:00
|
|
|
* - ResourceLoader::makeLoaderRegisterScript( [ $name1, $name2 ] ):
|
2014-08-25 11:43:41 +00:00
|
|
|
* Register modules with the given names.
|
* Introduced Xml::encodeJsCall(), to replace the awkward repetitive code that was doing the same thing throughout the resource loader with varying degrees of security and correctness.
* Modified Xml::encodeJsVar() to allow it to pass through JS expressions without encoding, using a special object.
* In ResourceLoader::makeModuleResponse(), renamed $messages to $messagesBlob to make it clear that it's JSON-encoded, not an array.
* Fixed MessageBlobStore to store {} for an empty message array instead of [].
* In ResourceLoader::makeMessageSetScript(), fixed call to non-existent function mediaWiki.msg.set.
* For security, changed the calling convention of makeMessageSetScript() and makeLoaderImplementScript() to require explicit object construction of XmlJsCode() before interpreting their input as JS code.
* Documented several ResourceLoader static functions.
* In ResourceLoaderWikiModule, for readability, reduced the indenting level by flipping some if blocks and adding continue statements.
* In makeCustomLoaderScript(), allow non-numeric $version. The only caller I can find is already sending a non-numeric $version, presumably it was broken. Luckily there aren't any loader scripts in existence, I had to make one to test it.
* wfGetDb -> wfGetDB
* Added an extra line break in the startup module output, for readability.
* In ResourceLoaderStartUpModule::getModuleRegistrations(), fixed another assignment expression
2010-11-04 07:53:37 +00:00
|
|
|
*
|
2016-08-13 01:10:40 +00:00
|
|
|
* - ResourceLoader::makeLoaderRegisterScript( [
|
|
|
|
|
* [ $name1, $version1, $dependencies1, $group1, $source1, $skip1 ],
|
|
|
|
|
* [ $name2, $version2, $dependencies1, $group2, $source2, $skip2 ],
|
* Introduced Xml::encodeJsCall(), to replace the awkward repetitive code that was doing the same thing throughout the resource loader with varying degrees of security and correctness.
* Modified Xml::encodeJsVar() to allow it to pass through JS expressions without encoding, using a special object.
* In ResourceLoader::makeModuleResponse(), renamed $messages to $messagesBlob to make it clear that it's JSON-encoded, not an array.
* Fixed MessageBlobStore to store {} for an empty message array instead of [].
* In ResourceLoader::makeMessageSetScript(), fixed call to non-existent function mediaWiki.msg.set.
* For security, changed the calling convention of makeMessageSetScript() and makeLoaderImplementScript() to require explicit object construction of XmlJsCode() before interpreting their input as JS code.
* Documented several ResourceLoader static functions.
* In ResourceLoaderWikiModule, for readability, reduced the indenting level by flipping some if blocks and adding continue statements.
* In makeCustomLoaderScript(), allow non-numeric $version. The only caller I can find is already sending a non-numeric $version, presumably it was broken. Luckily there aren't any loader scripts in existence, I had to make one to test it.
* wfGetDb -> wfGetDB
* Added an extra line break in the startup module output, for readability.
* In ResourceLoaderStartUpModule::getModuleRegistrations(), fixed another assignment expression
2010-11-04 07:53:37 +00:00
|
|
|
* ...
|
2016-08-13 01:10:40 +00:00
|
|
|
* ] ):
|
* Introduced Xml::encodeJsCall(), to replace the awkward repetitive code that was doing the same thing throughout the resource loader with varying degrees of security and correctness.
* Modified Xml::encodeJsVar() to allow it to pass through JS expressions without encoding, using a special object.
* In ResourceLoader::makeModuleResponse(), renamed $messages to $messagesBlob to make it clear that it's JSON-encoded, not an array.
* Fixed MessageBlobStore to store {} for an empty message array instead of [].
* In ResourceLoader::makeMessageSetScript(), fixed call to non-existent function mediaWiki.msg.set.
* For security, changed the calling convention of makeMessageSetScript() and makeLoaderImplementScript() to require explicit object construction of XmlJsCode() before interpreting their input as JS code.
* Documented several ResourceLoader static functions.
* In ResourceLoaderWikiModule, for readability, reduced the indenting level by flipping some if blocks and adding continue statements.
* In makeCustomLoaderScript(), allow non-numeric $version. The only caller I can find is already sending a non-numeric $version, presumably it was broken. Luckily there aren't any loader scripts in existence, I had to make one to test it.
* wfGetDb -> wfGetDB
* Added an extra line break in the startup module output, for readability.
* In ResourceLoaderStartUpModule::getModuleRegistrations(), fixed another assignment expression
2010-11-04 07:53:37 +00:00
|
|
|
* Registers modules with the given names and parameters.
|
|
|
|
|
*
|
2013-03-11 17:15:01 +00:00
|
|
|
* @param string $name Module name
|
resourceloader: Replace timestamp system with version hashing
Modules now track their version via getVersionHash() instead of getModifiedTime().
== Background ==
While some resources have observeable timestamps (e.g. files stored on disk),
many other resources do not. E.g. config variables, and module definitions.
For static file modules, one can e.g. revert one of more files in a module to a
previous version and not affect the max timestamp.
Wiki modules include pages only if they exist. The user module supports common.js
and skin.js. By default neither exists. If a user has both, and then the
less-recently modified one is deleted, the max-timestamp remains unchanged.
For client-side caching, batch requests use "Math.max" on the relevant timestamps.
Again, if a module changes but another module is more recent (e.g. out-of-order
deployment, or out-of-order discovery), the change would not result in a cache miss.
More scenarios can be found in the associated Phabricator tasks.
== Version hash ==
Previously we virtually mapped these variables to a timestamp by storing the current
time alongside a hash of the value in ObjectCache. Considering the number of
possible request contexts (wikis * modules * users * skins * languages) this doesn't
work well. It results in needless cache invalidation when the first time observation
is purged due to LRU algorithms. It also has other minor bugs leading to fewer
cache hits.
All modules automatically get the benefits of version hashing with this change.
The old getDefinitionMtime() and getHashMtime() have been replaced with dummies
that return 1. These functions are often called from getModifiedTime() in subclasses.
For backward-compatibility, their respective values (definition summary and hash)
are now included in getVersionHash directly.
As examples, the following modules have been updated to use getVersionHash directly.
Other modules still work fine and can be updated later.
* ResourceLoaderFileModule
* ResourceLoaderEditToolbarModule
* ResourceLoaderStartUpModule
* ResourceLoaderWikiModule
The presence of hashes in place of timestamps increases the startup module size on
a default MediaWiki install from 4.4k to 5.8k (after gzip and minification).
== ETag ==
Since timestamps are no longer tracked, we need a different way to implement caching
for cache proxies (e.g. Varnish) and web browsers. Previously we used the
Last-Modified header (in combination with Cache-Control and Expires).
Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match).
Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default.
They instruct browsers to allow usage of partial Range requests. Since our responses
are dynamically generated, we need to use the Weak version of ETag.
While this sounds bad, it's no different than Last-Modified. As reassured by
RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the
specified behaviour behind Last-Modified follows the same "Weak" caching logic as
Entity tags. It's just that entity tags are capable of a stricter mode (whereas
Last-Modified is inherently weak).
== File cache ==
If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache
load.php responses. While the blind TTL handling (during the allowed expiry period)
is still maxage/timestamp based, tryRespondNotModified() now requires the caller to
know the expected ETag.
For this to work, the FileCache handling had to be moved from the top of
ResoureLoader::respond() to after the expected ETag is computed.
This also allows us to remove the duplicate tryRespondNotModified() handling since
that's is already handled by ResourceLoader::respond() meanwhile.
== Misc ==
* Remove redundant modifiedTime cache in ResourceLoaderFileModule.
* Change bugzilla references to Phabricator.
* Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this
logic was duplicated in each place the modified timestamp was used.
* It's easy to forget calling the parent class in getDefinitionSummary().
Previously this method only tracked 'class' by default. As such, various
extensions hardcoded that one value instead of calling the parent and extending
the array. To better prevent this in the future, getVersionHash() now asserts
that the '_cacheEpoch' property made it through.
* tests: Don't use getDefinitionSummary() as an API.
Fix ResourceLoaderWikiModuleTest to call getPages properly.
* In tests, the default timestamp used to be 1388534400000 (which is the unix time
of 20140101000000; the unit tests' CacheEpoch). The new version hash of these
modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of:
'{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}'
* Add sha1.js library for client-side hash generation.
Compared various different implementations for code size (after minfication/gzip),
and speed (when used for short hexidecimal strings).
https://jsperf.com/sha1-implementations
- CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k)
http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js
Chrome: 45k, Firefox: 89k, Safari: 92k
- jsSHA <https://github.com/Caligatio/jsSHA>
https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k)
Chrome: 65k, Firefox: 53k, Safari: 69k
- phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k)
https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js
Chrome: 200k, Firefox: 280k, Safari: 78k
Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous,
only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate
code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being
needed in the module loader, we'd have to load the fallback regardless. Considering
this is not used in a critical path for performance, it's not worth shipping two
implementations for this optimisation.
May also resolve:
* T44094
* T90411
* T94810
Bug: T94074
Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
|
|
|
* @param string $version Module version hash
|
2013-03-11 17:15:01 +00:00
|
|
|
* @param array $dependencies List of module names on which this module depends
|
2014-03-07 16:50:57 +00:00
|
|
|
* @param string $group Group which the module is in
|
|
|
|
|
* @param string $source Source of the module, or 'local' if not foreign
|
2014-04-30 21:06:51 +00:00
|
|
|
* @param string $skip Script body of the skip function
|
2017-06-08 13:11:13 +00:00
|
|
|
* @return string JavaScript code
|
* Introduced Xml::encodeJsCall(), to replace the awkward repetitive code that was doing the same thing throughout the resource loader with varying degrees of security and correctness.
* Modified Xml::encodeJsVar() to allow it to pass through JS expressions without encoding, using a special object.
* In ResourceLoader::makeModuleResponse(), renamed $messages to $messagesBlob to make it clear that it's JSON-encoded, not an array.
* Fixed MessageBlobStore to store {} for an empty message array instead of [].
* In ResourceLoader::makeMessageSetScript(), fixed call to non-existent function mediaWiki.msg.set.
* For security, changed the calling convention of makeMessageSetScript() and makeLoaderImplementScript() to require explicit object construction of XmlJsCode() before interpreting their input as JS code.
* Documented several ResourceLoader static functions.
* In ResourceLoaderWikiModule, for readability, reduced the indenting level by flipping some if blocks and adding continue statements.
* In makeCustomLoaderScript(), allow non-numeric $version. The only caller I can find is already sending a non-numeric $version, presumably it was broken. Luckily there aren't any loader scripts in existence, I had to make one to test it.
* wfGetDb -> wfGetDB
* Added an extra line break in the startup module output, for readability.
* In ResourceLoaderStartUpModule::getModuleRegistrations(), fixed another assignment expression
2010-11-04 07:53:37 +00:00
|
|
|
*/
|
2011-06-17 16:05:05 +00:00
|
|
|
public static function makeLoaderRegisterScript( $name, $version = null,
|
2014-04-30 21:06:51 +00:00
|
|
|
$dependencies = null, $group = null, $source = null, $skip = null
|
2013-04-02 20:28:40 +00:00
|
|
|
) {
|
2010-09-24 21:03:29 +00:00
|
|
|
if ( is_array( $name ) ) {
|
2014-10-25 00:18:24 +00:00
|
|
|
// Build module name index
|
2016-02-17 09:09:32 +00:00
|
|
|
$index = [];
|
2014-12-09 00:29:19 +00:00
|
|
|
foreach ( $name as $i => &$module ) {
|
2014-10-25 00:18:24 +00:00
|
|
|
$index[$module[0]] = $i;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Transform dependency names into indexes when possible, they will be resolved by
|
|
|
|
|
// mw.loader.register on the other end
|
|
|
|
|
foreach ( $name as &$module ) {
|
|
|
|
|
if ( isset( $module[2] ) ) {
|
|
|
|
|
foreach ( $module[2] as &$dependency ) {
|
|
|
|
|
if ( isset( $index[$dependency] ) ) {
|
|
|
|
|
$dependency = $index[$dependency];
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2016-02-17 09:09:32 +00:00
|
|
|
array_walk( $name, [ 'self', 'trimArray' ] );
|
2014-12-09 00:29:19 +00:00
|
|
|
|
2014-03-07 17:49:50 +00:00
|
|
|
return Xml::encodeJsCall(
|
|
|
|
|
'mw.loader.register',
|
2016-02-17 09:09:32 +00:00
|
|
|
[ $name ],
|
2017-07-23 01:24:09 +00:00
|
|
|
self::inDebugMode()
|
2014-03-07 17:49:50 +00:00
|
|
|
);
|
2010-09-24 21:03:29 +00:00
|
|
|
} else {
|
2016-02-17 09:09:32 +00:00
|
|
|
$registration = [ $name, $version, $dependencies, $group, $source, $skip ];
|
2014-12-09 00:29:19 +00:00
|
|
|
self::trimArray( $registration );
|
2014-03-07 17:49:50 +00:00
|
|
|
return Xml::encodeJsCall(
|
|
|
|
|
'mw.loader.register',
|
2014-12-09 00:29:19 +00:00
|
|
|
$registration,
|
2017-07-23 01:24:09 +00:00
|
|
|
self::inDebugMode()
|
2014-03-07 17:49:50 +00:00
|
|
|
);
|
2011-07-26 21:10:34 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Returns JS code which calls mw.loader.addSource() with the given
|
|
|
|
|
* parameters. Has two calling conventions:
|
2011-10-14 08:06:54 +00:00
|
|
|
*
|
2011-07-26 21:10:34 +00:00
|
|
|
* - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
|
|
|
|
|
* Register a single source
|
2011-10-14 08:06:54 +00:00
|
|
|
*
|
2016-08-13 01:10:40 +00:00
|
|
|
* - ResourceLoader::makeLoaderSourcesScript( [ $id1 => $loadUrl, $id2 => $loadUrl, ... ] );
|
2011-07-26 21:10:34 +00:00
|
|
|
* Register sources with the given IDs and properties.
|
2011-10-14 08:06:54 +00:00
|
|
|
*
|
2014-04-20 21:33:05 +00:00
|
|
|
* @param string $id Source ID
|
2016-08-25 01:50:30 +00:00
|
|
|
* @param string $loadUrl load.php url
|
2017-06-08 13:11:13 +00:00
|
|
|
* @return string JavaScript code
|
2011-07-26 21:10:34 +00:00
|
|
|
*/
|
2016-08-25 01:50:30 +00:00
|
|
|
public static function makeLoaderSourcesScript( $id, $loadUrl = null ) {
|
2011-07-26 21:10:34 +00:00
|
|
|
if ( is_array( $id ) ) {
|
2014-03-07 17:49:50 +00:00
|
|
|
return Xml::encodeJsCall(
|
|
|
|
|
'mw.loader.addSource',
|
2016-02-17 09:09:32 +00:00
|
|
|
[ $id ],
|
2017-07-23 01:24:09 +00:00
|
|
|
self::inDebugMode()
|
2014-03-07 17:49:50 +00:00
|
|
|
);
|
2011-07-26 21:10:34 +00:00
|
|
|
} else {
|
2014-03-07 17:49:50 +00:00
|
|
|
return Xml::encodeJsCall(
|
|
|
|
|
'mw.loader.addSource',
|
2016-08-25 01:50:30 +00:00
|
|
|
[ $id, $loadUrl ],
|
2017-07-23 01:24:09 +00:00
|
|
|
self::inDebugMode()
|
2014-03-07 17:49:50 +00:00
|
|
|
);
|
2010-09-24 21:03:29 +00:00
|
|
|
}
|
|
|
|
|
}
|
2010-09-24 22:10:25 +00:00
|
|
|
|
* Introduced Xml::encodeJsCall(), to replace the awkward repetitive code that was doing the same thing throughout the resource loader with varying degrees of security and correctness.
* Modified Xml::encodeJsVar() to allow it to pass through JS expressions without encoding, using a special object.
* In ResourceLoader::makeModuleResponse(), renamed $messages to $messagesBlob to make it clear that it's JSON-encoded, not an array.
* Fixed MessageBlobStore to store {} for an empty message array instead of [].
* In ResourceLoader::makeMessageSetScript(), fixed call to non-existent function mediaWiki.msg.set.
* For security, changed the calling convention of makeMessageSetScript() and makeLoaderImplementScript() to require explicit object construction of XmlJsCode() before interpreting their input as JS code.
* Documented several ResourceLoader static functions.
* In ResourceLoaderWikiModule, for readability, reduced the indenting level by flipping some if blocks and adding continue statements.
* In makeCustomLoaderScript(), allow non-numeric $version. The only caller I can find is already sending a non-numeric $version, presumably it was broken. Luckily there aren't any loader scripts in existence, I had to make one to test it.
* wfGetDb -> wfGetDB
* Added an extra line break in the startup module output, for readability.
* In ResourceLoaderStartUpModule::getModuleRegistrations(), fixed another assignment expression
2010-11-04 07:53:37 +00:00
|
|
|
/**
|
2011-06-17 16:05:05 +00:00
|
|
|
* Returns JS code which runs given JS code if the client-side framework is
|
* Introduced Xml::encodeJsCall(), to replace the awkward repetitive code that was doing the same thing throughout the resource loader with varying degrees of security and correctness.
* Modified Xml::encodeJsVar() to allow it to pass through JS expressions without encoding, using a special object.
* In ResourceLoader::makeModuleResponse(), renamed $messages to $messagesBlob to make it clear that it's JSON-encoded, not an array.
* Fixed MessageBlobStore to store {} for an empty message array instead of [].
* In ResourceLoader::makeMessageSetScript(), fixed call to non-existent function mediaWiki.msg.set.
* For security, changed the calling convention of makeMessageSetScript() and makeLoaderImplementScript() to require explicit object construction of XmlJsCode() before interpreting their input as JS code.
* Documented several ResourceLoader static functions.
* In ResourceLoaderWikiModule, for readability, reduced the indenting level by flipping some if blocks and adding continue statements.
* In makeCustomLoaderScript(), allow non-numeric $version. The only caller I can find is already sending a non-numeric $version, presumably it was broken. Luckily there aren't any loader scripts in existence, I had to make one to test it.
* wfGetDb -> wfGetDB
* Added an extra line break in the startup module output, for readability.
* In ResourceLoaderStartUpModule::getModuleRegistrations(), fixed another assignment expression
2010-11-04 07:53:37 +00:00
|
|
|
* present.
|
|
|
|
|
*
|
2015-03-25 04:48:02 +00:00
|
|
|
* @deprecated since 1.25; use makeInlineScript instead
|
2013-03-11 17:15:01 +00:00
|
|
|
* @param string $script JavaScript code
|
2017-06-08 13:11:13 +00:00
|
|
|
* @return string JavaScript code
|
* Introduced Xml::encodeJsCall(), to replace the awkward repetitive code that was doing the same thing throughout the resource loader with varying degrees of security and correctness.
* Modified Xml::encodeJsVar() to allow it to pass through JS expressions without encoding, using a special object.
* In ResourceLoader::makeModuleResponse(), renamed $messages to $messagesBlob to make it clear that it's JSON-encoded, not an array.
* Fixed MessageBlobStore to store {} for an empty message array instead of [].
* In ResourceLoader::makeMessageSetScript(), fixed call to non-existent function mediaWiki.msg.set.
* For security, changed the calling convention of makeMessageSetScript() and makeLoaderImplementScript() to require explicit object construction of XmlJsCode() before interpreting their input as JS code.
* Documented several ResourceLoader static functions.
* In ResourceLoaderWikiModule, for readability, reduced the indenting level by flipping some if blocks and adding continue statements.
* In makeCustomLoaderScript(), allow non-numeric $version. The only caller I can find is already sending a non-numeric $version, presumably it was broken. Luckily there aren't any loader scripts in existence, I had to make one to test it.
* wfGetDb -> wfGetDB
* Added an extra line break in the startup module output, for readability.
* In ResourceLoaderStartUpModule::getModuleRegistrations(), fixed another assignment expression
2010-11-04 07:53:37 +00:00
|
|
|
*/
|
2010-09-24 22:10:25 +00:00
|
|
|
public static function makeLoaderConditionalScript( $script ) {
|
2016-02-18 16:33:15 +00:00
|
|
|
return '(window.RLQ=window.RLQ||[]).push(function(){' .
|
|
|
|
|
trim( $script ) . '});';
|
2010-09-24 22:10:25 +00:00
|
|
|
}
|
|
|
|
|
|
2015-03-25 04:48:02 +00:00
|
|
|
/**
|
|
|
|
|
* Construct an inline script tag with given JS code.
|
|
|
|
|
*
|
|
|
|
|
* The code will be wrapped in a closure, and it will be executed by ResourceLoader
|
|
|
|
|
* only if the client has adequate support for MediaWiki JavaScript code.
|
|
|
|
|
*
|
|
|
|
|
* @param string $script JavaScript code
|
2015-07-31 00:13:04 +00:00
|
|
|
* @return WrappedString HTML
|
2015-03-25 04:48:02 +00:00
|
|
|
*/
|
|
|
|
|
public static function makeInlineScript( $script ) {
|
|
|
|
|
$js = self::makeLoaderConditionalScript( $script );
|
2015-07-31 00:13:04 +00:00
|
|
|
return new WrappedString(
|
|
|
|
|
Html::inlineScript( $js ),
|
2016-02-18 16:33:15 +00:00
|
|
|
'<script>(window.RLQ=window.RLQ||[]).push(function(){',
|
|
|
|
|
'});</script>'
|
2015-07-31 00:13:04 +00:00
|
|
|
);
|
2015-03-25 04:48:02 +00:00
|
|
|
}
|
|
|
|
|
|
* Introduced Xml::encodeJsCall(), to replace the awkward repetitive code that was doing the same thing throughout the resource loader with varying degrees of security and correctness.
* Modified Xml::encodeJsVar() to allow it to pass through JS expressions without encoding, using a special object.
* In ResourceLoader::makeModuleResponse(), renamed $messages to $messagesBlob to make it clear that it's JSON-encoded, not an array.
* Fixed MessageBlobStore to store {} for an empty message array instead of [].
* In ResourceLoader::makeMessageSetScript(), fixed call to non-existent function mediaWiki.msg.set.
* For security, changed the calling convention of makeMessageSetScript() and makeLoaderImplementScript() to require explicit object construction of XmlJsCode() before interpreting their input as JS code.
* Documented several ResourceLoader static functions.
* In ResourceLoaderWikiModule, for readability, reduced the indenting level by flipping some if blocks and adding continue statements.
* In makeCustomLoaderScript(), allow non-numeric $version. The only caller I can find is already sending a non-numeric $version, presumably it was broken. Luckily there aren't any loader scripts in existence, I had to make one to test it.
* wfGetDb -> wfGetDB
* Added an extra line break in the startup module output, for readability.
* In ResourceLoaderStartUpModule::getModuleRegistrations(), fixed another assignment expression
2010-11-04 07:53:37 +00:00
|
|
|
/**
|
2011-06-17 16:05:05 +00:00
|
|
|
* Returns JS code which will set the MediaWiki configuration array to
|
* Introduced Xml::encodeJsCall(), to replace the awkward repetitive code that was doing the same thing throughout the resource loader with varying degrees of security and correctness.
* Modified Xml::encodeJsVar() to allow it to pass through JS expressions without encoding, using a special object.
* In ResourceLoader::makeModuleResponse(), renamed $messages to $messagesBlob to make it clear that it's JSON-encoded, not an array.
* Fixed MessageBlobStore to store {} for an empty message array instead of [].
* In ResourceLoader::makeMessageSetScript(), fixed call to non-existent function mediaWiki.msg.set.
* For security, changed the calling convention of makeMessageSetScript() and makeLoaderImplementScript() to require explicit object construction of XmlJsCode() before interpreting their input as JS code.
* Documented several ResourceLoader static functions.
* In ResourceLoaderWikiModule, for readability, reduced the indenting level by flipping some if blocks and adding continue statements.
* In makeCustomLoaderScript(), allow non-numeric $version. The only caller I can find is already sending a non-numeric $version, presumably it was broken. Luckily there aren't any loader scripts in existence, I had to make one to test it.
* wfGetDb -> wfGetDB
* Added an extra line break in the startup module output, for readability.
* In ResourceLoaderStartUpModule::getModuleRegistrations(), fixed another assignment expression
2010-11-04 07:53:37 +00:00
|
|
|
* the given value.
|
|
|
|
|
*
|
2013-03-11 17:15:01 +00:00
|
|
|
* @param array $configuration List of configuration values keyed by variable name
|
2017-06-08 13:11:13 +00:00
|
|
|
* @return string JavaScript code
|
* Introduced Xml::encodeJsCall(), to replace the awkward repetitive code that was doing the same thing throughout the resource loader with varying degrees of security and correctness.
* Modified Xml::encodeJsVar() to allow it to pass through JS expressions without encoding, using a special object.
* In ResourceLoader::makeModuleResponse(), renamed $messages to $messagesBlob to make it clear that it's JSON-encoded, not an array.
* Fixed MessageBlobStore to store {} for an empty message array instead of [].
* In ResourceLoader::makeMessageSetScript(), fixed call to non-existent function mediaWiki.msg.set.
* For security, changed the calling convention of makeMessageSetScript() and makeLoaderImplementScript() to require explicit object construction of XmlJsCode() before interpreting their input as JS code.
* Documented several ResourceLoader static functions.
* In ResourceLoaderWikiModule, for readability, reduced the indenting level by flipping some if blocks and adding continue statements.
* In makeCustomLoaderScript(), allow non-numeric $version. The only caller I can find is already sending a non-numeric $version, presumably it was broken. Luckily there aren't any loader scripts in existence, I had to make one to test it.
* wfGetDb -> wfGetDB
* Added an extra line break in the startup module output, for readability.
* In ResourceLoaderStartUpModule::getModuleRegistrations(), fixed another assignment expression
2010-11-04 07:53:37 +00:00
|
|
|
*/
|
2016-11-08 21:03:21 +00:00
|
|
|
public static function makeConfigSetScript( array $configuration ) {
|
2015-10-01 18:05:08 +00:00
|
|
|
return Xml::encodeJsCall(
|
|
|
|
|
'mw.config.set',
|
2016-02-17 09:09:32 +00:00
|
|
|
[ $configuration ],
|
2017-07-23 01:24:09 +00:00
|
|
|
self::inDebugMode()
|
2016-02-18 16:33:15 +00:00
|
|
|
);
|
2010-09-24 22:10:25 +00:00
|
|
|
}
|
2011-05-21 17:45:20 +00:00
|
|
|
|
2011-05-05 13:46:47 +00:00
|
|
|
/**
|
|
|
|
|
* Convert an array of module names to a packed query string.
|
2011-06-17 16:05:05 +00:00
|
|
|
*
|
2016-08-13 01:10:40 +00:00
|
|
|
* For example, [ 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' ]
|
2011-05-26 09:49:45 +00:00
|
|
|
* becomes 'foo.bar,baz|bar.baz,quux'
|
2014-03-07 16:50:57 +00:00
|
|
|
* @param array $modules List of module names (strings)
|
2011-05-05 13:46:47 +00:00
|
|
|
* @return string Packed query string
|
|
|
|
|
*/
|
|
|
|
|
public static function makePackedModulesString( $modules ) {
|
2016-08-13 01:10:40 +00:00
|
|
|
$groups = []; // [ prefix => [ suffixes ] ]
|
2011-05-05 13:46:47 +00:00
|
|
|
foreach ( $modules as $module ) {
|
|
|
|
|
$pos = strrpos( $module, '.' );
|
|
|
|
|
$prefix = $pos === false ? '' : substr( $module, 0, $pos );
|
|
|
|
|
$suffix = $pos === false ? $module : substr( $module, $pos + 1 );
|
|
|
|
|
$groups[$prefix][] = $suffix;
|
|
|
|
|
}
|
2011-05-21 17:45:20 +00:00
|
|
|
|
2016-02-17 09:09:32 +00:00
|
|
|
$arr = [];
|
2011-05-05 13:46:47 +00:00
|
|
|
foreach ( $groups as $prefix => $suffixes ) {
|
|
|
|
|
$p = $prefix === '' ? '' : $prefix . '.';
|
|
|
|
|
$arr[] = $p . implode( ',', $suffixes );
|
|
|
|
|
}
|
2011-05-09 13:10:06 +00:00
|
|
|
$str = implode( '|', $arr );
|
2011-05-26 09:49:45 +00:00
|
|
|
return $str;
|
2011-05-05 13:46:47 +00:00
|
|
|
}
|
2011-05-21 17:45:20 +00:00
|
|
|
|
2010-11-05 20:36:13 +00:00
|
|
|
/**
|
|
|
|
|
* Determine whether debug mode was requested
|
|
|
|
|
* Order of priority is 1) request param, 2) cookie, 3) $wg setting
|
|
|
|
|
* @return bool
|
|
|
|
|
*/
|
|
|
|
|
public static function inDebugMode() {
|
2014-04-30 21:06:51 +00:00
|
|
|
if ( self::$debugMode === null ) {
|
|
|
|
|
global $wgRequest, $wgResourceLoaderDebug;
|
|
|
|
|
self::$debugMode = $wgRequest->getFuzzyBool( 'debug',
|
|
|
|
|
$wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
|
|
|
|
|
);
|
2011-05-21 17:45:20 +00:00
|
|
|
}
|
2014-04-30 21:06:51 +00:00
|
|
|
return self::$debugMode;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Reset static members used for caching.
|
|
|
|
|
*
|
|
|
|
|
* Global state and $wgRequest are evil, but we're using it right
|
|
|
|
|
* now and sometimes we need to be able to force ResourceLoader to
|
|
|
|
|
* re-evaluate the context because it has changed (e.g. in the test suite).
|
|
|
|
|
*/
|
|
|
|
|
public static function clearCache() {
|
|
|
|
|
self::$debugMode = null;
|
2010-11-05 20:36:13 +00:00
|
|
|
}
|
2011-09-13 20:36:24 +00:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Build a load.php URL
|
2014-06-28 02:57:40 +00:00
|
|
|
*
|
|
|
|
|
* @since 1.24
|
2014-07-24 17:43:25 +00:00
|
|
|
* @param string $source Name of the ResourceLoader source
|
2014-06-28 02:57:40 +00:00
|
|
|
* @param ResourceLoaderContext $context
|
|
|
|
|
* @param array $extraQuery
|
2015-07-31 02:07:43 +00:00
|
|
|
* @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
|
2014-06-28 02:57:40 +00:00
|
|
|
*/
|
|
|
|
|
public function createLoaderURL( $source, ResourceLoaderContext $context,
|
2016-02-17 09:09:32 +00:00
|
|
|
$extraQuery = []
|
2014-06-28 02:57:40 +00:00
|
|
|
) {
|
|
|
|
|
$query = self::createLoaderQuery( $context, $extraQuery );
|
|
|
|
|
$script = $this->getLoadScript( $source );
|
|
|
|
|
|
2015-09-15 20:21:04 +00:00
|
|
|
return wfAppendQuery( $script, $query );
|
2014-06-28 02:57:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Helper for createLoaderURL()
|
|
|
|
|
*
|
|
|
|
|
* @since 1.24
|
|
|
|
|
* @see makeLoaderQuery
|
|
|
|
|
* @param ResourceLoaderContext $context
|
|
|
|
|
* @param array $extraQuery
|
|
|
|
|
* @return array
|
|
|
|
|
*/
|
2016-07-20 19:47:43 +00:00
|
|
|
protected static function createLoaderQuery( ResourceLoaderContext $context, $extraQuery = [] ) {
|
2014-06-28 02:57:40 +00:00
|
|
|
return self::makeLoaderQuery(
|
|
|
|
|
$context->getModules(),
|
|
|
|
|
$context->getLanguage(),
|
|
|
|
|
$context->getSkin(),
|
|
|
|
|
$context->getUser(),
|
|
|
|
|
$context->getVersion(),
|
|
|
|
|
$context->getDebug(),
|
|
|
|
|
$context->getOnly(),
|
|
|
|
|
$context->getRequest()->getBool( 'printable' ),
|
|
|
|
|
$context->getRequest()->getBool( 'handheld' ),
|
|
|
|
|
$extraQuery
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
2011-09-13 20:36:24 +00:00
|
|
|
/**
|
|
|
|
|
* Build a query array (array representation of query string) for load.php. Helper
|
2016-07-20 19:43:54 +00:00
|
|
|
* function for createLoaderURL().
|
2013-07-01 18:01:11 +00:00
|
|
|
*
|
|
|
|
|
* @param array $modules
|
|
|
|
|
* @param string $lang
|
|
|
|
|
* @param string $skin
|
|
|
|
|
* @param string $user
|
|
|
|
|
* @param string $version
|
|
|
|
|
* @param bool $debug
|
|
|
|
|
* @param string $only
|
|
|
|
|
* @param bool $printable
|
|
|
|
|
* @param bool $handheld
|
|
|
|
|
* @param array $extraQuery
|
|
|
|
|
*
|
2011-09-13 20:36:24 +00:00
|
|
|
* @return array
|
|
|
|
|
*/
|
2014-05-10 08:39:37 +00:00
|
|
|
public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
|
|
|
|
|
$version = null, $debug = false, $only = null, $printable = false,
|
2016-02-17 09:09:32 +00:00
|
|
|
$handheld = false, $extraQuery = []
|
2014-05-10 08:39:37 +00:00
|
|
|
) {
|
2016-02-17 09:09:32 +00:00
|
|
|
$query = [
|
2011-09-13 20:36:24 +00:00
|
|
|
'modules' => self::makePackedModulesString( $modules ),
|
|
|
|
|
'lang' => $lang,
|
|
|
|
|
'skin' => $skin,
|
|
|
|
|
'debug' => $debug ? 'true' : 'false',
|
2016-02-17 09:09:32 +00:00
|
|
|
];
|
2011-09-13 20:36:24 +00:00
|
|
|
if ( $user !== null ) {
|
|
|
|
|
$query['user'] = $user;
|
|
|
|
|
}
|
|
|
|
|
if ( $version !== null ) {
|
|
|
|
|
$query['version'] = $version;
|
|
|
|
|
}
|
|
|
|
|
if ( $only !== null ) {
|
|
|
|
|
$query['only'] = $only;
|
|
|
|
|
}
|
|
|
|
|
if ( $printable ) {
|
|
|
|
|
$query['printable'] = 1;
|
|
|
|
|
}
|
|
|
|
|
if ( $handheld ) {
|
|
|
|
|
$query['handheld'] = 1;
|
|
|
|
|
}
|
|
|
|
|
$query += $extraQuery;
|
2011-10-14 08:06:54 +00:00
|
|
|
|
2011-09-13 20:36:24 +00:00
|
|
|
// Make queries uniform in order
|
|
|
|
|
ksort( $query );
|
|
|
|
|
return $query;
|
|
|
|
|
}
|
2012-05-09 21:10:33 +00:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Check a module name for validity.
|
|
|
|
|
*
|
|
|
|
|
* Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
|
|
|
|
|
* at most 255 bytes.
|
|
|
|
|
*
|
2013-03-11 17:15:01 +00:00
|
|
|
* @param string $moduleName Module name to check
|
2012-05-09 21:10:33 +00:00
|
|
|
* @return bool Whether $moduleName is a valid module name
|
|
|
|
|
*/
|
|
|
|
|
public static function isValidModuleName( $moduleName ) {
|
2015-10-05 18:39:13 +00:00
|
|
|
return strcspn( $moduleName, '!,|', 0, 255 ) === strlen( $moduleName );
|
2012-05-09 21:10:33 +00:00
|
|
|
}
|
2013-09-28 07:40:03 +00:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Returns LESS compiler set up for use with MediaWiki
|
|
|
|
|
*
|
2016-01-08 22:09:36 +00:00
|
|
|
* @since 1.27
|
2015-09-25 17:57:35 +00:00
|
|
|
* @param array $extraVars Associative array of extra (i.e., other than the
|
|
|
|
|
* globally-configured ones) that should be used for compilation.
|
2014-08-07 10:25:56 +00:00
|
|
|
* @throws MWException
|
2015-09-10 22:22:13 +00:00
|
|
|
* @return Less_Parser
|
2013-09-28 07:40:03 +00:00
|
|
|
*/
|
2016-02-17 09:09:32 +00:00
|
|
|
public function getLessCompiler( $extraVars = [] ) {
|
2013-10-14 01:34:58 +00:00
|
|
|
// When called from the installer, it is possible that a required PHP extension
|
2017-02-20 22:44:19 +00:00
|
|
|
// is missing (at least for now; see T49564). If this is the case, throw an
|
2013-10-14 01:34:58 +00:00
|
|
|
// exception (caught by the installer) to prevent a fatal error later on.
|
2015-09-10 22:22:13 +00:00
|
|
|
if ( !class_exists( 'Less_Parser' ) ) {
|
|
|
|
|
throw new MWException( 'MediaWiki requires the less.php parser' );
|
2013-10-14 01:34:58 +00:00
|
|
|
}
|
|
|
|
|
|
2015-09-10 22:22:13 +00:00
|
|
|
$parser = new Less_Parser;
|
2016-01-08 22:09:36 +00:00
|
|
|
$parser->ModifyVars( array_merge( $this->getLessVars(), $extraVars ) );
|
|
|
|
|
$parser->SetImportDirs(
|
|
|
|
|
array_fill_keys( $this->config->get( 'ResourceLoaderLESSImportPaths' ), '' )
|
|
|
|
|
);
|
2015-09-10 22:22:13 +00:00
|
|
|
$parser->SetOption( 'relativeUrls', false );
|
|
|
|
|
|
|
|
|
|
return $parser;
|
2013-09-28 07:40:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Get global LESS variables.
|
|
|
|
|
*
|
2016-01-08 22:09:36 +00:00
|
|
|
* @since 1.27
|
2014-04-20 21:33:05 +00:00
|
|
|
* @return array Map of variable names to string CSS values.
|
2013-09-28 07:40:03 +00:00
|
|
|
*/
|
2016-01-08 22:09:36 +00:00
|
|
|
public function getLessVars() {
|
|
|
|
|
if ( !$this->lessVars ) {
|
|
|
|
|
$lessVars = $this->config->get( 'ResourceLoaderLESSVars' );
|
2016-02-17 09:09:32 +00:00
|
|
|
Hooks::run( 'ResourceLoaderGetLessVars', [ &$lessVars ] );
|
2016-01-08 22:09:36 +00:00
|
|
|
$this->lessVars = $lessVars;
|
2015-02-01 21:37:34 +00:00
|
|
|
}
|
2016-01-08 22:09:36 +00:00
|
|
|
return $this->lessVars;
|
2013-09-28 07:40:03 +00:00
|
|
|
}
|
2010-09-17 11:45:49 +00:00
|
|
|
}
|