wiki.techinc.nl/includes/resourceloader/ResourceLoaderModule.php

656 lines
20 KiB
PHP
Raw Normal View History

<?php
/**
* Abstraction for resource loader modules.
*
* 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-04 12:53:01 +00:00
*
2010-09-05 13:31:34 +00:00
* @file
* @author Trevor Parscal
* @author Roan Kattouw
*/
/**
* Abstraction for resource loader modules, with name registration and maxage functionality.
*/
abstract class ResourceLoaderModule {
# Type of resource
const TYPE_SCRIPTS = 'scripts';
const TYPE_STYLES = 'styles';
const TYPE_MESSAGES = 'messages';
const TYPE_COMBINED = 'combined';
# sitewide core module like a skin file or jQuery component
const ORIGIN_CORE_SITEWIDE = 1;
# per-user module generated by the software
const ORIGIN_CORE_INDIVIDUAL = 2;
# sitewide module generated from user-editable files, like MediaWiki:Common.js, or
# modules accessible to multiple users, such as those generated by the Gadgets extension.
const ORIGIN_USER_SITEWIDE = 3;
# per-user module generated from user-editable files, like User:Me/vector.js
const ORIGIN_USER_INDIVIDUAL = 4;
# an access constant; make sure this is kept as the largest number in this group
const ORIGIN_ALL = 10;
# script and style modules form a hierarchy of trustworthiness, with core modules like
# skins and jQuery as most trustworthy, and user scripts as least trustworthy. We can
# limit the types of scripts and styles we allow to load on, say, sensitive special
# pages like Special:UserLogin and Special:Preferences
protected $origin = self::ORIGIN_CORE_SITEWIDE;
/* Protected Members */
2010-09-04 12:53:01 +00:00
protected $name = null;
protected $targets = array( 'desktop' );
// In-object cache for file dependencies
protected $fileDeps = array();
// In-object cache for message blob mtime
protected $msgBlobMtime = array();
2010-09-04 12:53:01 +00:00
/**
* @var Config
*/
protected $config;
/* Methods */
2010-09-04 12:53:01 +00:00
/**
* Get this module's name. This is set when the module is registered
* with ResourceLoader::register()
2010-09-05 13:31:34 +00:00
*
* @return string|null Name (string) or null if no name was set
*/
public function getName() {
return $this->name;
}
2010-09-04 12:53:01 +00:00
/**
* Set this module's name. This is called by ResourceLoader::register()
* when registering the module. Other code should not call this.
2010-09-05 13:31:34 +00:00
*
* @param string $name Name
*/
public function setName( $name ) {
$this->name = $name;
}
2010-09-04 12:53:01 +00:00
/**
* Get this module's origin. This is set when the module is registered
* with ResourceLoader::register()
*
* @return int ResourceLoaderModule class constant, the subclass default
* if not set manually
*/
public function getOrigin() {
return $this->origin;
}
/**
* Set this module's origin. This is called by ResourceLoader::register()
* when registering the module. Other code should not call this.
*
* @param int $origin Origin
*/
public function setOrigin( $origin ) {
$this->origin = $origin;
}
/**
* @param ResourceLoaderContext $context
* @return bool
*/
public function getFlip( $context ) {
global $wgContLang;
return $wgContLang->getDir() !== $context->getDirection();
}
2010-09-04 12:53:01 +00:00
/**
* Get all JS for this module for a given language and skin.
* Includes all relevant JS except loader scripts.
2010-09-05 13:31:34 +00:00
*
* @param ResourceLoaderContext $context
* @return string JavaScript code
*/
public function getScript( ResourceLoaderContext $context ) {
// Stub, override expected
return '';
}
/**
* Takes named templates by the module and returns an array mapping.
*
* @return array of templates mapping template alias to content
*/
public function getTemplates() {
// Stub, override expected.
return array();
}
/**
* @return Config
* @since 1.24
*/
public function getConfig() {
if ( $this->config === null ) {
// Ugh, fall back to default
$this->config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
}
return $this->config;
}
/**
* @param Config $config
* @since 1.24
*/
public function setConfig( Config $config ) {
$this->config = $config;
}
Fix the fixme on r88053: dependency handling was broken in debug mode in certain cases. More specifically, if A is a file module that depends on B, B is a wiki module that depends on C and C is a file module, the loading order is CBA (correct) in production mode but was BCA (wrong) in debug mode. Fixed this by URL-ifying scripts and styles for those modules in debug mode, as I said to on CR. What this means is that the initial debug=true request for a module will now always return arrays of URLs, never the JS or CSS itself. This was already the case for file modules (which returned arrays of URLs to the raw files), but not for other modules (which returned the JS and CSS itself). So for non-file modules, load.php?modules=foo&debug=true now returns some JS that instructs the loader to fetch the module's JS from load.php?modules=foo&debug=true&only=scripts and the CSS from ...&only=styles . * Removed the magic behavior where ResourceLoaderModule::getScripts() and getStyles() could return an array of URLs where the documentation said they should return a JS/CSS string. Because I didn't restructure the calling code too much, the old magical behavior should still work. * Instead, move this behavior to getScriptURLsForDebug() and getStyleURLsForDebug(). The default implementation constructs a single URL for a load.php request for the module with debug=true&only=scripts (or styles). The URL building code duplicates some things from OutputPage::makeResourceLoaderLink(), I'll clean that up later. ResourceLoaderFileModule overrides this method to return URLs to the raw files, using code that I removed from getScripts()/getStyles() * Add ResourceLoaderModule::supportsURLLoading(), which returns true by default but may return false to indicate that a module does not support loading via a URL. This is needed to respect $this->debugRaw in ResourceLoaderFileModule (set to true for jquery and mediawiki), and obviously for the startup module as well, because we get bootstrapping problems otherwise (can't call mw.loader.implement() when the code for mw.loader isn't loaded yet)
2011-09-13 17:13:53 +00:00
/**
* Get the URL or URLs to load for this module's JS in debug mode.
* The default behavior is to return a load.php?only=scripts URL for
* the module, but file-based modules will want to override this to
* load the files directly.
*
Fix the fixme on r88053: dependency handling was broken in debug mode in certain cases. More specifically, if A is a file module that depends on B, B is a wiki module that depends on C and C is a file module, the loading order is CBA (correct) in production mode but was BCA (wrong) in debug mode. Fixed this by URL-ifying scripts and styles for those modules in debug mode, as I said to on CR. What this means is that the initial debug=true request for a module will now always return arrays of URLs, never the JS or CSS itself. This was already the case for file modules (which returned arrays of URLs to the raw files), but not for other modules (which returned the JS and CSS itself). So for non-file modules, load.php?modules=foo&debug=true now returns some JS that instructs the loader to fetch the module's JS from load.php?modules=foo&debug=true&only=scripts and the CSS from ...&only=styles . * Removed the magic behavior where ResourceLoaderModule::getScripts() and getStyles() could return an array of URLs where the documentation said they should return a JS/CSS string. Because I didn't restructure the calling code too much, the old magical behavior should still work. * Instead, move this behavior to getScriptURLsForDebug() and getStyleURLsForDebug(). The default implementation constructs a single URL for a load.php request for the module with debug=true&only=scripts (or styles). The URL building code duplicates some things from OutputPage::makeResourceLoaderLink(), I'll clean that up later. ResourceLoaderFileModule overrides this method to return URLs to the raw files, using code that I removed from getScripts()/getStyles() * Add ResourceLoaderModule::supportsURLLoading(), which returns true by default but may return false to indicate that a module does not support loading via a URL. This is needed to respect $this->debugRaw in ResourceLoaderFileModule (set to true for jquery and mediawiki), and obviously for the startup module as well, because we get bootstrapping problems otherwise (can't call mw.loader.implement() when the code for mw.loader isn't loaded yet)
2011-09-13 17:13:53 +00:00
* This function is called only when 1) we're in debug mode, 2) there
* is no only= parameter and 3) supportsURLLoading() returns true.
* #2 is important to prevent an infinite loop, therefore this function
* MUST return either an only= URL or a non-load.php URL.
*
* @param ResourceLoaderContext $context
* @return array Array of URLs
Fix the fixme on r88053: dependency handling was broken in debug mode in certain cases. More specifically, if A is a file module that depends on B, B is a wiki module that depends on C and C is a file module, the loading order is CBA (correct) in production mode but was BCA (wrong) in debug mode. Fixed this by URL-ifying scripts and styles for those modules in debug mode, as I said to on CR. What this means is that the initial debug=true request for a module will now always return arrays of URLs, never the JS or CSS itself. This was already the case for file modules (which returned arrays of URLs to the raw files), but not for other modules (which returned the JS and CSS itself). So for non-file modules, load.php?modules=foo&debug=true now returns some JS that instructs the loader to fetch the module's JS from load.php?modules=foo&debug=true&only=scripts and the CSS from ...&only=styles . * Removed the magic behavior where ResourceLoaderModule::getScripts() and getStyles() could return an array of URLs where the documentation said they should return a JS/CSS string. Because I didn't restructure the calling code too much, the old magical behavior should still work. * Instead, move this behavior to getScriptURLsForDebug() and getStyleURLsForDebug(). The default implementation constructs a single URL for a load.php request for the module with debug=true&only=scripts (or styles). The URL building code duplicates some things from OutputPage::makeResourceLoaderLink(), I'll clean that up later. ResourceLoaderFileModule overrides this method to return URLs to the raw files, using code that I removed from getScripts()/getStyles() * Add ResourceLoaderModule::supportsURLLoading(), which returns true by default but may return false to indicate that a module does not support loading via a URL. This is needed to respect $this->debugRaw in ResourceLoaderFileModule (set to true for jquery and mediawiki), and obviously for the startup module as well, because we get bootstrapping problems otherwise (can't call mw.loader.implement() when the code for mw.loader isn't loaded yet)
2011-09-13 17:13:53 +00:00
*/
public function getScriptURLsForDebug( ResourceLoaderContext $context ) {
$resourceLoader = $context->getResourceLoader();
$derivative = new DerivativeResourceLoaderContext( $context );
$derivative->setModules( array( $this->getName() ) );
$derivative->setOnly( 'scripts' );
$derivative->setDebug( true );
$url = $resourceLoader->createLoaderURL(
$this->getSource(),
$derivative
Fix the fixme on r88053: dependency handling was broken in debug mode in certain cases. More specifically, if A is a file module that depends on B, B is a wiki module that depends on C and C is a file module, the loading order is CBA (correct) in production mode but was BCA (wrong) in debug mode. Fixed this by URL-ifying scripts and styles for those modules in debug mode, as I said to on CR. What this means is that the initial debug=true request for a module will now always return arrays of URLs, never the JS or CSS itself. This was already the case for file modules (which returned arrays of URLs to the raw files), but not for other modules (which returned the JS and CSS itself). So for non-file modules, load.php?modules=foo&debug=true now returns some JS that instructs the loader to fetch the module's JS from load.php?modules=foo&debug=true&only=scripts and the CSS from ...&only=styles . * Removed the magic behavior where ResourceLoaderModule::getScripts() and getStyles() could return an array of URLs where the documentation said they should return a JS/CSS string. Because I didn't restructure the calling code too much, the old magical behavior should still work. * Instead, move this behavior to getScriptURLsForDebug() and getStyleURLsForDebug(). The default implementation constructs a single URL for a load.php request for the module with debug=true&only=scripts (or styles). The URL building code duplicates some things from OutputPage::makeResourceLoaderLink(), I'll clean that up later. ResourceLoaderFileModule overrides this method to return URLs to the raw files, using code that I removed from getScripts()/getStyles() * Add ResourceLoaderModule::supportsURLLoading(), which returns true by default but may return false to indicate that a module does not support loading via a URL. This is needed to respect $this->debugRaw in ResourceLoaderFileModule (set to true for jquery and mediawiki), and obviously for the startup module as well, because we get bootstrapping problems otherwise (can't call mw.loader.implement() when the code for mw.loader isn't loaded yet)
2011-09-13 17:13:53 +00:00
);
return array( $url );
Fix the fixme on r88053: dependency handling was broken in debug mode in certain cases. More specifically, if A is a file module that depends on B, B is a wiki module that depends on C and C is a file module, the loading order is CBA (correct) in production mode but was BCA (wrong) in debug mode. Fixed this by URL-ifying scripts and styles for those modules in debug mode, as I said to on CR. What this means is that the initial debug=true request for a module will now always return arrays of URLs, never the JS or CSS itself. This was already the case for file modules (which returned arrays of URLs to the raw files), but not for other modules (which returned the JS and CSS itself). So for non-file modules, load.php?modules=foo&debug=true now returns some JS that instructs the loader to fetch the module's JS from load.php?modules=foo&debug=true&only=scripts and the CSS from ...&only=styles . * Removed the magic behavior where ResourceLoaderModule::getScripts() and getStyles() could return an array of URLs where the documentation said they should return a JS/CSS string. Because I didn't restructure the calling code too much, the old magical behavior should still work. * Instead, move this behavior to getScriptURLsForDebug() and getStyleURLsForDebug(). The default implementation constructs a single URL for a load.php request for the module with debug=true&only=scripts (or styles). The URL building code duplicates some things from OutputPage::makeResourceLoaderLink(), I'll clean that up later. ResourceLoaderFileModule overrides this method to return URLs to the raw files, using code that I removed from getScripts()/getStyles() * Add ResourceLoaderModule::supportsURLLoading(), which returns true by default but may return false to indicate that a module does not support loading via a URL. This is needed to respect $this->debugRaw in ResourceLoaderFileModule (set to true for jquery and mediawiki), and obviously for the startup module as well, because we get bootstrapping problems otherwise (can't call mw.loader.implement() when the code for mw.loader isn't loaded yet)
2011-09-13 17:13:53 +00:00
}
Fix the fixme on r88053: dependency handling was broken in debug mode in certain cases. More specifically, if A is a file module that depends on B, B is a wiki module that depends on C and C is a file module, the loading order is CBA (correct) in production mode but was BCA (wrong) in debug mode. Fixed this by URL-ifying scripts and styles for those modules in debug mode, as I said to on CR. What this means is that the initial debug=true request for a module will now always return arrays of URLs, never the JS or CSS itself. This was already the case for file modules (which returned arrays of URLs to the raw files), but not for other modules (which returned the JS and CSS itself). So for non-file modules, load.php?modules=foo&debug=true now returns some JS that instructs the loader to fetch the module's JS from load.php?modules=foo&debug=true&only=scripts and the CSS from ...&only=styles . * Removed the magic behavior where ResourceLoaderModule::getScripts() and getStyles() could return an array of URLs where the documentation said they should return a JS/CSS string. Because I didn't restructure the calling code too much, the old magical behavior should still work. * Instead, move this behavior to getScriptURLsForDebug() and getStyleURLsForDebug(). The default implementation constructs a single URL for a load.php request for the module with debug=true&only=scripts (or styles). The URL building code duplicates some things from OutputPage::makeResourceLoaderLink(), I'll clean that up later. ResourceLoaderFileModule overrides this method to return URLs to the raw files, using code that I removed from getScripts()/getStyles() * Add ResourceLoaderModule::supportsURLLoading(), which returns true by default but may return false to indicate that a module does not support loading via a URL. This is needed to respect $this->debugRaw in ResourceLoaderFileModule (set to true for jquery and mediawiki), and obviously for the startup module as well, because we get bootstrapping problems otherwise (can't call mw.loader.implement() when the code for mw.loader isn't loaded yet)
2011-09-13 17:13:53 +00:00
/**
* Whether this module supports URL loading. If this function returns false,
* getScript() will be used even in cases (debug mode, no only param) where
* getScriptURLsForDebug() would normally be used instead.
* @return bool
*/
public function supportsURLLoading() {
return true;
}
2010-09-04 12:53:01 +00:00
/**
* Get all CSS for this module for a given skin.
2010-09-05 13:31:34 +00:00
*
* @param ResourceLoaderContext $context
* @return array List of CSS strings or array of CSS strings keyed by media type.
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
* like array( 'screen' => '.foo { width: 0 }' );
* or array( 'screen' => array( '.foo { width: 0 }' ) );
*/
public function getStyles( ResourceLoaderContext $context ) {
// Stub, override expected
return array();
}
Fix the fixme on r88053: dependency handling was broken in debug mode in certain cases. More specifically, if A is a file module that depends on B, B is a wiki module that depends on C and C is a file module, the loading order is CBA (correct) in production mode but was BCA (wrong) in debug mode. Fixed this by URL-ifying scripts and styles for those modules in debug mode, as I said to on CR. What this means is that the initial debug=true request for a module will now always return arrays of URLs, never the JS or CSS itself. This was already the case for file modules (which returned arrays of URLs to the raw files), but not for other modules (which returned the JS and CSS itself). So for non-file modules, load.php?modules=foo&debug=true now returns some JS that instructs the loader to fetch the module's JS from load.php?modules=foo&debug=true&only=scripts and the CSS from ...&only=styles . * Removed the magic behavior where ResourceLoaderModule::getScripts() and getStyles() could return an array of URLs where the documentation said they should return a JS/CSS string. Because I didn't restructure the calling code too much, the old magical behavior should still work. * Instead, move this behavior to getScriptURLsForDebug() and getStyleURLsForDebug(). The default implementation constructs a single URL for a load.php request for the module with debug=true&only=scripts (or styles). The URL building code duplicates some things from OutputPage::makeResourceLoaderLink(), I'll clean that up later. ResourceLoaderFileModule overrides this method to return URLs to the raw files, using code that I removed from getScripts()/getStyles() * Add ResourceLoaderModule::supportsURLLoading(), which returns true by default but may return false to indicate that a module does not support loading via a URL. This is needed to respect $this->debugRaw in ResourceLoaderFileModule (set to true for jquery and mediawiki), and obviously for the startup module as well, because we get bootstrapping problems otherwise (can't call mw.loader.implement() when the code for mw.loader isn't loaded yet)
2011-09-13 17:13:53 +00:00
/**
* Get the URL or URLs to load for this module's CSS in debug mode.
* The default behavior is to return a load.php?only=styles URL for
* the module, but file-based modules will want to override this to
* load the files directly. See also getScriptURLsForDebug()
*
* @param ResourceLoaderContext $context
* @return array Array( mediaType => array( URL1, URL2, ... ), ... )
Fix the fixme on r88053: dependency handling was broken in debug mode in certain cases. More specifically, if A is a file module that depends on B, B is a wiki module that depends on C and C is a file module, the loading order is CBA (correct) in production mode but was BCA (wrong) in debug mode. Fixed this by URL-ifying scripts and styles for those modules in debug mode, as I said to on CR. What this means is that the initial debug=true request for a module will now always return arrays of URLs, never the JS or CSS itself. This was already the case for file modules (which returned arrays of URLs to the raw files), but not for other modules (which returned the JS and CSS itself). So for non-file modules, load.php?modules=foo&debug=true now returns some JS that instructs the loader to fetch the module's JS from load.php?modules=foo&debug=true&only=scripts and the CSS from ...&only=styles . * Removed the magic behavior where ResourceLoaderModule::getScripts() and getStyles() could return an array of URLs where the documentation said they should return a JS/CSS string. Because I didn't restructure the calling code too much, the old magical behavior should still work. * Instead, move this behavior to getScriptURLsForDebug() and getStyleURLsForDebug(). The default implementation constructs a single URL for a load.php request for the module with debug=true&only=scripts (or styles). The URL building code duplicates some things from OutputPage::makeResourceLoaderLink(), I'll clean that up later. ResourceLoaderFileModule overrides this method to return URLs to the raw files, using code that I removed from getScripts()/getStyles() * Add ResourceLoaderModule::supportsURLLoading(), which returns true by default but may return false to indicate that a module does not support loading via a URL. This is needed to respect $this->debugRaw in ResourceLoaderFileModule (set to true for jquery and mediawiki), and obviously for the startup module as well, because we get bootstrapping problems otherwise (can't call mw.loader.implement() when the code for mw.loader isn't loaded yet)
2011-09-13 17:13:53 +00:00
*/
public function getStyleURLsForDebug( ResourceLoaderContext $context ) {
$resourceLoader = $context->getResourceLoader();
$derivative = new DerivativeResourceLoaderContext( $context );
$derivative->setModules( array( $this->getName() ) );
$derivative->setOnly( 'styles' );
$derivative->setDebug( true );
$url = $resourceLoader->createLoaderURL(
$this->getSource(),
$derivative
Fix the fixme on r88053: dependency handling was broken in debug mode in certain cases. More specifically, if A is a file module that depends on B, B is a wiki module that depends on C and C is a file module, the loading order is CBA (correct) in production mode but was BCA (wrong) in debug mode. Fixed this by URL-ifying scripts and styles for those modules in debug mode, as I said to on CR. What this means is that the initial debug=true request for a module will now always return arrays of URLs, never the JS or CSS itself. This was already the case for file modules (which returned arrays of URLs to the raw files), but not for other modules (which returned the JS and CSS itself). So for non-file modules, load.php?modules=foo&debug=true now returns some JS that instructs the loader to fetch the module's JS from load.php?modules=foo&debug=true&only=scripts and the CSS from ...&only=styles . * Removed the magic behavior where ResourceLoaderModule::getScripts() and getStyles() could return an array of URLs where the documentation said they should return a JS/CSS string. Because I didn't restructure the calling code too much, the old magical behavior should still work. * Instead, move this behavior to getScriptURLsForDebug() and getStyleURLsForDebug(). The default implementation constructs a single URL for a load.php request for the module with debug=true&only=scripts (or styles). The URL building code duplicates some things from OutputPage::makeResourceLoaderLink(), I'll clean that up later. ResourceLoaderFileModule overrides this method to return URLs to the raw files, using code that I removed from getScripts()/getStyles() * Add ResourceLoaderModule::supportsURLLoading(), which returns true by default but may return false to indicate that a module does not support loading via a URL. This is needed to respect $this->debugRaw in ResourceLoaderFileModule (set to true for jquery and mediawiki), and obviously for the startup module as well, because we get bootstrapping problems otherwise (can't call mw.loader.implement() when the code for mw.loader isn't loaded yet)
2011-09-13 17:13:53 +00:00
);
return array( 'all' => array( $url ) );
Fix the fixme on r88053: dependency handling was broken in debug mode in certain cases. More specifically, if A is a file module that depends on B, B is a wiki module that depends on C and C is a file module, the loading order is CBA (correct) in production mode but was BCA (wrong) in debug mode. Fixed this by URL-ifying scripts and styles for those modules in debug mode, as I said to on CR. What this means is that the initial debug=true request for a module will now always return arrays of URLs, never the JS or CSS itself. This was already the case for file modules (which returned arrays of URLs to the raw files), but not for other modules (which returned the JS and CSS itself). So for non-file modules, load.php?modules=foo&debug=true now returns some JS that instructs the loader to fetch the module's JS from load.php?modules=foo&debug=true&only=scripts and the CSS from ...&only=styles . * Removed the magic behavior where ResourceLoaderModule::getScripts() and getStyles() could return an array of URLs where the documentation said they should return a JS/CSS string. Because I didn't restructure the calling code too much, the old magical behavior should still work. * Instead, move this behavior to getScriptURLsForDebug() and getStyleURLsForDebug(). The default implementation constructs a single URL for a load.php request for the module with debug=true&only=scripts (or styles). The URL building code duplicates some things from OutputPage::makeResourceLoaderLink(), I'll clean that up later. ResourceLoaderFileModule overrides this method to return URLs to the raw files, using code that I removed from getScripts()/getStyles() * Add ResourceLoaderModule::supportsURLLoading(), which returns true by default but may return false to indicate that a module does not support loading via a URL. This is needed to respect $this->debugRaw in ResourceLoaderFileModule (set to true for jquery and mediawiki), and obviously for the startup module as well, because we get bootstrapping problems otherwise (can't call mw.loader.implement() when the code for mw.loader isn't loaded yet)
2011-09-13 17:13:53 +00:00
}
2010-09-04 12:53:01 +00:00
/**
* Get the messages needed for this module.
*
* To get a JSON blob with messages, use MessageBlobStore::get()
2010-09-05 13:31:34 +00:00
*
* @return array List of message keys. Keys may occur more than once
*/
public function getMessages() {
// Stub, override expected
return array();
}
/**
* Get the group this module is in.
*
* @return string Group name
*/
public function getGroup() {
// Stub, override expected
return null;
}
[ResourceLoader 2]: Add support for multiple loadScript sources Front-end: * New mw.loader method: addSource(). Call with two arguments or an object as first argument for multiple registrations * New property in module registry: "source". Optional for local modules (falls back to 'local'). When loading/using one or more modules, the worker will group the request by source and make separate requests to the sources as needed. * Re-arranging object properties in mw.loader.register to match the same order all other code parts use. * Adding documentation for 'source' and where missing updating it to include 'group' as well. * Refactor of mw.loader.work() by Roan Kattouw and Timo Tijhof:' -- Additional splitting layer by source (in addition to splitting by group), renamed 'groups' to 'splits' -- Clean up of the loop, and removing a no longer needed loop after the for-in-loop -- Much more function documentation in mw.loader.work() -- Moved caching of wgResourceLoaderMaxQueryLength out of the loop and renamed 'limit' to 'maxQueryLength Back-end changed provided through patch by Roan Kattouw (to avoid broken code between commits): * New method in ResourceLoader: addSource(). During construction of ResourceLoader this will be called by default for 'local' with loadScript property set to $wgLoadScript. Additional sources can be registered through $wgResourceLoaderSources (empty array by default) * Calling mw.loader.addSource from the startup module * Passing source to mw.loader.register from startup module * Some new static helper methods Use: * By default nothing should change in core, all modules simply default to 'local'. This info originates from the getSource()-method of the ResourceLoaderModule class, which is inherited to all core ResourceLoaderModule-implementations (none override it) * Third-party users and/or extensions can create new classes extending ResourceLoaderModule, re-implementing the getSource-method to return something else. Basic example: $wgResourceLoaderSources['mywiki'] = array( 'loadScript' => 'http://example.org/w/load.php' ); class MyCentralWikiModule extends ResourceLoaderModule { function getSource(){ return 'mywiki'; } } $wgResourceModules['cool.stuff'] => array( 'class' => 'MyCentralWikiModule' ); More complicated example // imagine some stuff with a ForeignGadgetRepo class, putting stuff in $wgResourceLoaderSources in the __construct() method class ForeignGadgetRepoGadget extends ResourceLoaderModule { function getSource(){ return $this->source; } } Loading: Loading is completely transparent, stuff like $wgOut->addModules() or mw.loader.loader/using both take it as any other module and load from the right source accordingly. -- This commit is part of the ResourceLoader 2 project.
2011-07-26 21:10:34 +00:00
/**
* Get the origin of this module. Should only be overridden for foreign modules.
*
* @return string Origin name, 'local' for local modules
[ResourceLoader 2]: Add support for multiple loadScript sources Front-end: * New mw.loader method: addSource(). Call with two arguments or an object as first argument for multiple registrations * New property in module registry: "source". Optional for local modules (falls back to 'local'). When loading/using one or more modules, the worker will group the request by source and make separate requests to the sources as needed. * Re-arranging object properties in mw.loader.register to match the same order all other code parts use. * Adding documentation for 'source' and where missing updating it to include 'group' as well. * Refactor of mw.loader.work() by Roan Kattouw and Timo Tijhof:' -- Additional splitting layer by source (in addition to splitting by group), renamed 'groups' to 'splits' -- Clean up of the loop, and removing a no longer needed loop after the for-in-loop -- Much more function documentation in mw.loader.work() -- Moved caching of wgResourceLoaderMaxQueryLength out of the loop and renamed 'limit' to 'maxQueryLength Back-end changed provided through patch by Roan Kattouw (to avoid broken code between commits): * New method in ResourceLoader: addSource(). During construction of ResourceLoader this will be called by default for 'local' with loadScript property set to $wgLoadScript. Additional sources can be registered through $wgResourceLoaderSources (empty array by default) * Calling mw.loader.addSource from the startup module * Passing source to mw.loader.register from startup module * Some new static helper methods Use: * By default nothing should change in core, all modules simply default to 'local'. This info originates from the getSource()-method of the ResourceLoaderModule class, which is inherited to all core ResourceLoaderModule-implementations (none override it) * Third-party users and/or extensions can create new classes extending ResourceLoaderModule, re-implementing the getSource-method to return something else. Basic example: $wgResourceLoaderSources['mywiki'] = array( 'loadScript' => 'http://example.org/w/load.php' ); class MyCentralWikiModule extends ResourceLoaderModule { function getSource(){ return 'mywiki'; } } $wgResourceModules['cool.stuff'] => array( 'class' => 'MyCentralWikiModule' ); More complicated example // imagine some stuff with a ForeignGadgetRepo class, putting stuff in $wgResourceLoaderSources in the __construct() method class ForeignGadgetRepoGadget extends ResourceLoaderModule { function getSource(){ return $this->source; } } Loading: Loading is completely transparent, stuff like $wgOut->addModules() or mw.loader.loader/using both take it as any other module and load from the right source accordingly. -- This commit is part of the ResourceLoader 2 project.
2011-07-26 21:10:34 +00:00
*/
public function getSource() {
// Stub, override expected
return 'local';
}
/**
* Where on the HTML page should this module's JS be loaded?
* - 'top': in the "<head>"
* - 'bottom': at the bottom of the "<body>"
*
* @return string
*/
public function getPosition() {
return 'bottom';
}
2010-09-04 12:53:01 +00:00
/**
* Whether this module's JS expects to work without the client-side ResourceLoader module.
* Returning true from this function will prevent mw.loader.state() call from being
* appended to the bottom of the script.
*
* @return bool
*/
public function isRaw() {
return false;
}
/**
* Get the loader JS for this module, if set.
2010-09-05 13:31:34 +00:00
*
* @return mixed JavaScript loader code as a string or boolean false if no custom loader set
*/
public function getLoaderScript() {
// Stub, override expected
return false;
}
2010-09-04 12:53:01 +00:00
/**
* Get a list of modules this module depends on.
*
* Dependency information is taken into account when loading a module
* on the client side.
*
* To add dependencies dynamically on the client side, use a custom
* loader script, see getLoaderScript()
* @return array List of module names as strings
*/
public function getDependencies() {
// Stub, override expected
return array();
}
/**
* Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
*
* @return array Array of strings
*/
public function getTargets() {
return $this->targets;
}
resourceloader: Implement "skip function" feature A module can be registered with a skip function. Such function, if provided, will be invoked by the client when a module is queued for loading. If the function returns true, the client will bypass any further loading action and mark the module as 'ready'. This can be used to implement a feature test for a module providing a shim or polyfill. * Change visibility of method ResourceLoader::filter to public. So that it can be invoked by ResourceLoaderStartupModule. * Add option to suppress the cache key report in ResourceLoader::filter. We usually only call the minifier once on an entire request reponse (because it's all concatenated javascript or embedded javascript in various different closures, still valid as one large script) and only add a little bottom line for the cache key. When embedding the skip function we have to run the minifier on them separately as they're output as strings (not actual functions). These strings are typically quite small and blowing up the response with loads of cache keys is not desirable in production. * Add method to clear the static cache of ResourceLoader::inDebugMode. Global static state is evil but, as long as we have it, we at least need to clear it after switching contexts in the test suite. Also: * Remove obsolete setting of 'debug=true' in the FauxRequest in ResourceLoaderTestCase. It already sets global wgResourceLoaderDebug in the setUp() method. Bug: 66390 Change-Id: I87a0ea888d791ad39f114380c42e2daeca470961
2014-04-30 21:06:51 +00:00
/**
* Get the skip function.
*
* Modules that provide fallback functionality can provide a "skip function". This
* function, if provided, will be passed along to the module registry on the client.
* When this module is loaded (either directly or as a dependency of another module),
* then this function is executed first. If the function returns true, the module will
* instantly be considered "ready" without requesting the associated module resources.
*
* The value returned here must be valid javascript for execution in a private function.
* It must not contain the "function () {" and "}" wrapper though.
*
* @return string|null A JavaScript function body returning a boolean value, or null
*/
public function getSkipFunction() {
return null;
}
/**
* Get the files this module depends on indirectly for a given skin.
* Currently these are only image files referenced by the module's CSS.
*
* @param string $skin Skin name
* @return array List of files
*/
public function getFileDependencies( $skin ) {
// Try in-object cache first
if ( isset( $this->fileDeps[$skin] ) ) {
return $this->fileDeps[$skin];
}
2010-09-04 12:53:01 +00:00
$dbr = wfGetDB( DB_SLAVE );
$deps = $dbr->selectField( 'module_deps', 'md_deps', array(
'md_module' => $this->getName(),
'md_skin' => $skin,
), __METHOD__
);
if ( !is_null( $deps ) ) {
$this->fileDeps[$skin] = (array)FormatJson::decode( $deps, true );
} else {
$this->fileDeps[$skin] = array();
}
return $this->fileDeps[$skin];
}
/**
* Set preloaded file dependency information. Used so we can load this
* information for all modules at once.
* @param string $skin Skin name
* @param array $deps Array of file names
*/
public function setFileDependencies( $skin, $deps ) {
$this->fileDeps[$skin] = $deps;
}
/**
* Get the last modification timestamp of the message blob for this
* module in a given language.
* @param string $lang Language code
* @return int UNIX timestamp, or 0 if the module doesn't have messages
*/
public function getMsgBlobMtime( $lang ) {
if ( !isset( $this->msgBlobMtime[$lang] ) ) {
if ( !count( $this->getMessages() ) ) {
return 0;
}
$dbr = wfGetDB( DB_SLAVE );
$msgBlobMtime = $dbr->selectField( 'msg_resource', 'mr_timestamp', array(
'mr_resource' => $this->getName(),
'mr_lang' => $lang
), __METHOD__
);
// If no blob was found, but the module does have messages, that means we need
// to regenerate it. Return NOW
2011-02-11 08:29:55 +00:00
if ( $msgBlobMtime === false ) {
$msgBlobMtime = wfTimestampNow();
}
$this->msgBlobMtime[$lang] = wfTimestamp( TS_UNIX, $msgBlobMtime );
}
return $this->msgBlobMtime[$lang];
}
/**
* Set a preloaded message blob last modification timestamp. Used so we
* can load this information for all modules at once.
* @param string $lang Language code
* @param int $mtime UNIX timestamp or 0 if there is no such blob
*/
public function setMsgBlobMtime( $lang, $mtime ) {
$this->msgBlobMtime[$lang] = $mtime;
}
/* Abstract Methods */
/**
* Get this module's last modification timestamp for a given
* combination of language, skin and debug mode flag. This is typically
* the highest of each of the relevant components' modification
* timestamps. Whenever anything happens that changes the module's
* contents for these parameters, the mtime should increase.
2010-09-05 13:31:34 +00:00
*
* NOTE: The mtime of the module's messages is NOT automatically included.
* If you want this to happen, you'll need to call getMsgBlobMtime()
* yourself and take its result into consideration.
*
* NOTE: The mtime of the module's hash is NOT automatically included.
* If your module provides a getModifiedHash() method, you'll need to call getHashMtime()
* yourself and take its result into consideration.
*
* @param ResourceLoaderContext $context Context object
* @return int UNIX timestamp
*/
public function getModifiedTime( ResourceLoaderContext $context ) {
// 0 would mean now
return 1;
}
/**
* Helper method for calculating when the module's hash (if it has one) changed.
*
* @param ResourceLoaderContext $context
* @return int UNIX timestamp or 0 if no hash was provided
* by getModifiedHash()
*/
public function getHashMtime( ResourceLoaderContext $context ) {
$hash = $this->getModifiedHash( $context );
if ( !is_string( $hash ) ) {
return 0;
}
$cache = wfGetCache( CACHE_ANYTHING );
resourceloader: Make sure hashmtime cache key is different by language We were continuously invalidating the cache for the ResourceLoaderLanguageDataModule every time a request for a langauge other than the previous request came in as they all resulted in the same cache key. This could be resolved by adding $context->getLang() to the key (which would be enough for langdata module, but not enough for other uses of hashmtime), or by adding $context->getHash() (which will fragment it for all possible context factor combinations, slightly overkill for most cases, but would work). Instead resolving it the same way we did in d3bdda3 for a similar issue in #getDefinitionMtime: by adding the hash itself to the key. That way it will solve the problem, including two nice things: * Not fragment anymore than necessary (if it doesn't vary by skin, it won't vary by skin, and same for language etc.). * Always separate keys when the value is different (if something can very based on other factors, e.g. LocalSettings globals or whatever untracked method may exist for influencing anything, it will all work as expected). * Don't keep alternating and incrementing the timestamp while a multi-server infrastructure is syncing code (e.g. old code and new code for the same request context will not result in the same key and each old/new server alternatingly increasing the timestamp, instead the first new server will make the new key and the other servers will gradually start finding the new key with the timestamp of when it was first seen). Change-Id: Ifa9088c11c388ca6c912e62efc43494e91702603
2013-12-04 00:26:16 +00:00
$key = wfMemcKey( 'resourceloader', 'modulemodifiedhash', $this->getName(), $hash );
$data = $cache->get( $key );
if ( is_array( $data ) && $data['hash'] === $hash ) {
// Hash is still the same, re-use the timestamp of when we first saw this hash.
return $data['timestamp'];
}
$timestamp = wfTimestamp();
$cache->set( $key, array(
'hash' => $hash,
'timestamp' => $timestamp,
) );
return $timestamp;
}
/**
* Get the hash for whatever this module may contain.
*
* This is the method subclasses should implement if they want to make
* use of getHashMTime() inside getModifiedTime().
*
* @param ResourceLoaderContext $context
* @return string|null Hash
*/
public function getModifiedHash( ResourceLoaderContext $context ) {
return null;
}
/**
* Helper method for calculating when this module's definition summary was last changed.
*
* @since 1.23
*
* @param ResourceLoaderContext $context
* @return int UNIX timestamp or 0 if no definition summary was provided
* by getDefinitionSummary()
*/
public function getDefinitionMtime( ResourceLoaderContext $context ) {
wfProfileIn( __METHOD__ );
$summary = $this->getDefinitionSummary( $context );
if ( $summary === null ) {
wfProfileOut( __METHOD__ );
return 0;
}
$hash = md5( json_encode( $summary ) );
$cache = wfGetCache( CACHE_ANYTHING );
// Embed the hash itself in the cache key. This allows for a few nifty things:
// - During deployment, servers with old and new versions of the code communicating
// with the same memcached will not override the same key repeatedly increasing
// the timestamp.
// - In case of the definition changing and then changing back in a short period of time
// (e.g. in case of a revert or a corrupt server) the old timestamp and client-side cache
// url will be re-used.
// - If different context-combinations (e.g. same skin, same language or some combination
// thereof) result in the same definition, they will use the same hash and timestamp.
$key = wfMemcKey( 'resourceloader', 'moduledefinition', $this->getName(), $hash );
$data = $cache->get( $key );
if ( is_int( $data ) && $data > 0 ) {
// We've seen this hash before, re-use the timestamp of when we first saw it.
wfProfileOut( __METHOD__ );
return $data;
}
wfDebugLog( 'resourceloader', __METHOD__ . ": New definition hash for module "
. "{$this->getName()} in context {$context->getHash()}: $hash." );
$timestamp = time();
$cache->set( $key, $timestamp );
wfProfileOut( __METHOD__ );
return $timestamp;
}
/**
* Get the definition summary for this module.
*
* This is the method subclasses should implement if they want to make
* use of getDefinitionMTime() inside getModifiedTime().
*
* Return an array containing values from all significant properties of this
* module's definition. Be sure to include things that are explicitly ordered,
* in their actaul order (bug 37812).
*
* Avoid including things that are insiginificant (e.g. order of message
* keys is insignificant and should be sorted to avoid unnecessary cache
* invalidation).
*
* Avoid including things already considered by other methods inside your
* getModifiedTime(), such as file mtime timestamps.
*
* Serialisation is done using json_encode, which means object state is not
* taken into account when building the hash. This data structure must only
* contain arrays and scalars as values (avoid object instances) which means
* it requires abstraction.
*
* @since 1.23
*
* @param ResourceLoaderContext $context
* @return array|null
*/
public function getDefinitionSummary( ResourceLoaderContext $context ) {
return array(
'class' => get_class( $this ),
);
}
/**
* Check whether this module is known to be empty. If a child class
* has an easy and cheap way to determine that this module is
* definitely going to be empty, it should override this method to
* return true in that case. Callers may optimize the request for this
* module away if this function returns true.
* @param ResourceLoaderContext $context
* @return bool
*/
public function isKnownEmpty( ResourceLoaderContext $context ) {
return false;
}
* (bug 28626) Validate JavaScript files and pages loaded via ResourceLoader before minification, protecting separate modules from interference This is possibly not perfect but seems to serve for a start; follows up on r91591 that adds JSMin+ to use it in some unit tests. May want to adjust some related bits. - $wgResourceLoaderValidateJs on by default (can be disabled) - when loading a JS file through ResourceLoaderFileModule or ResourceLoaderWikiModule, parse it using JSMinPlus's JSParser class. If the parser throws an exception, the JS code of the offending file will be replaced by a JS exception throw listing the file or page name, line number (in original form), and description of the error from the parser. - parsing results are cached based on md5 of content to avoid re-parsing identical text - for JS pages loaded via direct load.php request, the parse error is thrown and visible in the JS console/error log Issues: - the primary use case for this is when a single load.php request implements multiple modules via mw.loader.implement() -- the loader catches the exception and skips on to the next module (good) but doesn't re-throw the exception for the JS console. It does log to console if present, but it'll only show up as a regular debug message, not an error. This can suppress visibility of errors in a module that's loaded together with other modules (such as a gadget). - have not done performance testing on the JSParser - have not done thorough unit testing with the JSParser
2011-07-06 21:48:09 +00:00
/** @var JSParser Lazy-initialized; use self::javaScriptParser() */
* (bug 28626) Validate JavaScript files and pages loaded via ResourceLoader before minification, protecting separate modules from interference This is possibly not perfect but seems to serve for a start; follows up on r91591 that adds JSMin+ to use it in some unit tests. May want to adjust some related bits. - $wgResourceLoaderValidateJs on by default (can be disabled) - when loading a JS file through ResourceLoaderFileModule or ResourceLoaderWikiModule, parse it using JSMinPlus's JSParser class. If the parser throws an exception, the JS code of the offending file will be replaced by a JS exception throw listing the file or page name, line number (in original form), and description of the error from the parser. - parsing results are cached based on md5 of content to avoid re-parsing identical text - for JS pages loaded via direct load.php request, the parse error is thrown and visible in the JS console/error log Issues: - the primary use case for this is when a single load.php request implements multiple modules via mw.loader.implement() -- the loader catches the exception and skips on to the next module (good) but doesn't re-throw the exception for the JS console. It does log to console if present, but it'll only show up as a regular debug message, not an error. This can suppress visibility of errors in a module that's loaded together with other modules (such as a gadget). - have not done performance testing on the JSParser - have not done thorough unit testing with the JSParser
2011-07-06 21:48:09 +00:00
private static $jsParser;
private static $parseCacheVersion = 1;
/**
* Validate a given script file; if valid returns the original source.
* If invalid, returns replacement JS source that throws an exception.
*
* @param string $fileName
* @param string $contents
* @return string JS with the original, or a replacement error
* (bug 28626) Validate JavaScript files and pages loaded via ResourceLoader before minification, protecting separate modules from interference This is possibly not perfect but seems to serve for a start; follows up on r91591 that adds JSMin+ to use it in some unit tests. May want to adjust some related bits. - $wgResourceLoaderValidateJs on by default (can be disabled) - when loading a JS file through ResourceLoaderFileModule or ResourceLoaderWikiModule, parse it using JSMinPlus's JSParser class. If the parser throws an exception, the JS code of the offending file will be replaced by a JS exception throw listing the file or page name, line number (in original form), and description of the error from the parser. - parsing results are cached based on md5 of content to avoid re-parsing identical text - for JS pages loaded via direct load.php request, the parse error is thrown and visible in the JS console/error log Issues: - the primary use case for this is when a single load.php request implements multiple modules via mw.loader.implement() -- the loader catches the exception and skips on to the next module (good) but doesn't re-throw the exception for the JS console. It does log to console if present, but it'll only show up as a regular debug message, not an error. This can suppress visibility of errors in a module that's loaded together with other modules (such as a gadget). - have not done performance testing on the JSParser - have not done thorough unit testing with the JSParser
2011-07-06 21:48:09 +00:00
*/
protected function validateScriptFile( $fileName, $contents ) {
if ( $this->getConfig()->get( 'ResourceLoaderValidateJS' ) ) {
* (bug 28626) Validate JavaScript files and pages loaded via ResourceLoader before minification, protecting separate modules from interference This is possibly not perfect but seems to serve for a start; follows up on r91591 that adds JSMin+ to use it in some unit tests. May want to adjust some related bits. - $wgResourceLoaderValidateJs on by default (can be disabled) - when loading a JS file through ResourceLoaderFileModule or ResourceLoaderWikiModule, parse it using JSMinPlus's JSParser class. If the parser throws an exception, the JS code of the offending file will be replaced by a JS exception throw listing the file or page name, line number (in original form), and description of the error from the parser. - parsing results are cached based on md5 of content to avoid re-parsing identical text - for JS pages loaded via direct load.php request, the parse error is thrown and visible in the JS console/error log Issues: - the primary use case for this is when a single load.php request implements multiple modules via mw.loader.implement() -- the loader catches the exception and skips on to the next module (good) but doesn't re-throw the exception for the JS console. It does log to console if present, but it'll only show up as a regular debug message, not an error. This can suppress visibility of errors in a module that's loaded together with other modules (such as a gadget). - have not done performance testing on the JSParser - have not done thorough unit testing with the JSParser
2011-07-06 21:48:09 +00:00
// Try for cache hit
// Use CACHE_ANYTHING since filtering is very slow compared to DB queries
$key = wfMemcKey( 'resourceloader', 'jsparse', self::$parseCacheVersion, md5( $contents ) );
$cache = wfGetCache( CACHE_ANYTHING );
$cacheEntry = $cache->get( $key );
if ( is_string( $cacheEntry ) ) {
return $cacheEntry;
}
$parser = self::javaScriptParser();
try {
$parser->parse( $contents, $fileName, 1 );
$result = $contents;
} catch ( Exception $e ) {
* (bug 28626) Validate JavaScript files and pages loaded via ResourceLoader before minification, protecting separate modules from interference This is possibly not perfect but seems to serve for a start; follows up on r91591 that adds JSMin+ to use it in some unit tests. May want to adjust some related bits. - $wgResourceLoaderValidateJs on by default (can be disabled) - when loading a JS file through ResourceLoaderFileModule or ResourceLoaderWikiModule, parse it using JSMinPlus's JSParser class. If the parser throws an exception, the JS code of the offending file will be replaced by a JS exception throw listing the file or page name, line number (in original form), and description of the error from the parser. - parsing results are cached based on md5 of content to avoid re-parsing identical text - for JS pages loaded via direct load.php request, the parse error is thrown and visible in the JS console/error log Issues: - the primary use case for this is when a single load.php request implements multiple modules via mw.loader.implement() -- the loader catches the exception and skips on to the next module (good) but doesn't re-throw the exception for the JS console. It does log to console if present, but it'll only show up as a regular debug message, not an error. This can suppress visibility of errors in a module that's loaded together with other modules (such as a gadget). - have not done performance testing on the JSParser - have not done thorough unit testing with the JSParser
2011-07-06 21:48:09 +00:00
// We'll save this to cache to avoid having to validate broken JS over and over...
$err = $e->getMessage();
$result = "throw new Error(" . Xml::encodeJsVar( "JavaScript parse error: $err" ) . ");";
* (bug 28626) Validate JavaScript files and pages loaded via ResourceLoader before minification, protecting separate modules from interference This is possibly not perfect but seems to serve for a start; follows up on r91591 that adds JSMin+ to use it in some unit tests. May want to adjust some related bits. - $wgResourceLoaderValidateJs on by default (can be disabled) - when loading a JS file through ResourceLoaderFileModule or ResourceLoaderWikiModule, parse it using JSMinPlus's JSParser class. If the parser throws an exception, the JS code of the offending file will be replaced by a JS exception throw listing the file or page name, line number (in original form), and description of the error from the parser. - parsing results are cached based on md5 of content to avoid re-parsing identical text - for JS pages loaded via direct load.php request, the parse error is thrown and visible in the JS console/error log Issues: - the primary use case for this is when a single load.php request implements multiple modules via mw.loader.implement() -- the loader catches the exception and skips on to the next module (good) but doesn't re-throw the exception for the JS console. It does log to console if present, but it'll only show up as a regular debug message, not an error. This can suppress visibility of errors in a module that's loaded together with other modules (such as a gadget). - have not done performance testing on the JSParser - have not done thorough unit testing with the JSParser
2011-07-06 21:48:09 +00:00
}
* (bug 28626) Validate JavaScript files and pages loaded via ResourceLoader before minification, protecting separate modules from interference This is possibly not perfect but seems to serve for a start; follows up on r91591 that adds JSMin+ to use it in some unit tests. May want to adjust some related bits. - $wgResourceLoaderValidateJs on by default (can be disabled) - when loading a JS file through ResourceLoaderFileModule or ResourceLoaderWikiModule, parse it using JSMinPlus's JSParser class. If the parser throws an exception, the JS code of the offending file will be replaced by a JS exception throw listing the file or page name, line number (in original form), and description of the error from the parser. - parsing results are cached based on md5 of content to avoid re-parsing identical text - for JS pages loaded via direct load.php request, the parse error is thrown and visible in the JS console/error log Issues: - the primary use case for this is when a single load.php request implements multiple modules via mw.loader.implement() -- the loader catches the exception and skips on to the next module (good) but doesn't re-throw the exception for the JS console. It does log to console if present, but it'll only show up as a regular debug message, not an error. This can suppress visibility of errors in a module that's loaded together with other modules (such as a gadget). - have not done performance testing on the JSParser - have not done thorough unit testing with the JSParser
2011-07-06 21:48:09 +00:00
$cache->set( $key, $result );
return $result;
} else {
return $contents;
}
}
/**
* @return JSParser
*/
* (bug 28626) Validate JavaScript files and pages loaded via ResourceLoader before minification, protecting separate modules from interference This is possibly not perfect but seems to serve for a start; follows up on r91591 that adds JSMin+ to use it in some unit tests. May want to adjust some related bits. - $wgResourceLoaderValidateJs on by default (can be disabled) - when loading a JS file through ResourceLoaderFileModule or ResourceLoaderWikiModule, parse it using JSMinPlus's JSParser class. If the parser throws an exception, the JS code of the offending file will be replaced by a JS exception throw listing the file or page name, line number (in original form), and description of the error from the parser. - parsing results are cached based on md5 of content to avoid re-parsing identical text - for JS pages loaded via direct load.php request, the parse error is thrown and visible in the JS console/error log Issues: - the primary use case for this is when a single load.php request implements multiple modules via mw.loader.implement() -- the loader catches the exception and skips on to the next module (good) but doesn't re-throw the exception for the JS console. It does log to console if present, but it'll only show up as a regular debug message, not an error. This can suppress visibility of errors in a module that's loaded together with other modules (such as a gadget). - have not done performance testing on the JSParser - have not done thorough unit testing with the JSParser
2011-07-06 21:48:09 +00:00
protected static function javaScriptParser() {
if ( !self::$jsParser ) {
self::$jsParser = new JSParser();
}
return self::$jsParser;
}
/**
* Safe version of filemtime(), which doesn't throw a PHP warning if the file doesn't exist
* but returns 1 instead.
* @param string $filename File name
* @return int UNIX timestamp, or 1 if the file doesn't exist
*/
protected static function safeFilemtime( $filename ) {
if ( file_exists( $filename ) ) {
return filemtime( $filename );
} else {
// We only ever map this function on an array if we're gonna call max() after,
// so return our standard minimum timestamps here. This is 1, not 0, because
// wfTimestamp(0) == NOW
return 1;
}
}
}