3 * Abstraction for resource loader modules.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @author Trevor Parscal
22 * @author Roan Kattouw
26 * Abstraction for resource loader modules, with name registration and maxage functionality.
28 abstract class ResourceLoaderModule
{
31 const TYPE_SCRIPTS
= 'scripts';
32 const TYPE_STYLES
= 'styles';
33 const TYPE_MESSAGES
= 'messages';
34 const TYPE_COMBINED
= 'combined';
36 # sitewide core module like a skin file or jQuery component
37 const ORIGIN_CORE_SITEWIDE
= 1;
39 # per-user module generated by the software
40 const ORIGIN_CORE_INDIVIDUAL
= 2;
42 # sitewide module generated from user-editable files, like MediaWiki:Common.js, or
43 # modules accessible to multiple users, such as those generated by the Gadgets extension.
44 const ORIGIN_USER_SITEWIDE
= 3;
46 # per-user module generated from user-editable files, like User:Me/vector.js
47 const ORIGIN_USER_INDIVIDUAL
= 4;
49 # an access constant; make sure this is kept as the largest number in this group
50 const ORIGIN_ALL
= 10;
52 # script and style modules form a hierarchy of trustworthiness, with core modules like
53 # skins and jQuery as most trustworthy, and user scripts as least trustworthy. We can
54 # limit the types of scripts and styles we allow to load on, say, sensitive special
55 # pages like Special:UserLogin and Special:Preferences
56 protected $origin = self
::ORIGIN_CORE_SITEWIDE
;
58 /* Protected Members */
60 protected $name = null;
62 // In-object cache for file dependencies
63 protected $fileDeps = array();
64 // In-object cache for message blob mtime
65 protected $msgBlobMtime = array();
70 * Get this module's name. This is set when the module is registered
71 * with ResourceLoader::register()
73 * @return Mixed: Name (string) or null if no name was set
75 public function getName() {
80 * Set this module's name. This is called by ResourceLodaer::register()
81 * when registering the module. Other code should not call this.
83 * @param $name String: Name
85 public function setName( $name ) {
90 * Get this module's origin. This is set when the module is registered
91 * with ResourceLoader::register()
93 * @return Int ResourceLoaderModule class constant, the subclass default
96 public function getOrigin() {
101 * Set this module's origin. This is called by ResourceLodaer::register()
102 * when registering the module. Other code should not call this.
104 * @param $origin Int origin
106 public function setOrigin( $origin ) {
107 $this->origin
= $origin;
111 * @param $context ResourceLoaderContext
114 public function getFlip( $context ) {
117 return $wgContLang->getDir() !== $context->getDirection();
121 * Get all JS for this module for a given language and skin.
122 * Includes all relevant JS except loader scripts.
124 * @param $context ResourceLoaderContext: Context object
125 * @return String: JavaScript code
127 public function getScript( ResourceLoaderContext
$context ) {
128 // Stub, override expected
133 * Get the URL or URLs to load for this module's JS in debug mode.
134 * The default behavior is to return a load.php?only=scripts URL for
135 * the module, but file-based modules will want to override this to
136 * load the files directly.
138 * This function is called only when 1) we're in debug mode, 2) there
139 * is no only= parameter and 3) supportsURLLoading() returns true.
140 * #2 is important to prevent an infinite loop, therefore this function
141 * MUST return either an only= URL or a non-load.php URL.
143 * @param $context ResourceLoaderContext: Context object
144 * @return Array of URLs
146 public function getScriptURLsForDebug( ResourceLoaderContext
$context ) {
147 $url = ResourceLoader
::makeLoaderURL(
148 array( $this->getName() ),
149 $context->getLanguage(),
152 $context->getVersion(),
155 $context->getRequest()->getBool( 'printable' ),
156 $context->getRequest()->getBool( 'handheld' )
158 return array( $url );
162 * Whether this module supports URL loading. If this function returns false,
163 * getScript() will be used even in cases (debug mode, no only param) where
164 * getScriptURLsForDebug() would normally be used instead.
167 public function supportsURLLoading() {
172 * Get all CSS for this module for a given skin.
174 * @param $context ResourceLoaderContext: Context object
175 * @return Array: List of CSS strings keyed by media type
177 public function getStyles( ResourceLoaderContext
$context ) {
178 // Stub, override expected
183 * Get the URL or URLs to load for this module's CSS in debug mode.
184 * The default behavior is to return a load.php?only=styles URL for
185 * the module, but file-based modules will want to override this to
186 * load the files directly. See also getScriptURLsForDebug()
188 * @param $context ResourceLoaderContext: Context object
189 * @return Array: array( mediaType => array( URL1, URL2, ... ), ... )
191 public function getStyleURLsForDebug( ResourceLoaderContext
$context ) {
192 $url = ResourceLoader
::makeLoaderURL(
193 array( $this->getName() ),
194 $context->getLanguage(),
197 $context->getVersion(),
200 $context->getRequest()->getBool( 'printable' ),
201 $context->getRequest()->getBool( 'handheld' )
203 return array( 'all' => array( $url ) );
207 * Get the messages needed for this module.
209 * To get a JSON blob with messages, use MessageBlobStore::get()
211 * @return Array: List of message keys. Keys may occur more than once
213 public function getMessages() {
214 // Stub, override expected
219 * Get the group this module is in.
221 * @return String: Group name
223 public function getGroup() {
224 // Stub, override expected
229 * Get the origin of this module. Should only be overridden for foreign modules.
231 * @return String: Origin name, 'local' for local modules
233 public function getSource() {
234 // Stub, override expected
239 * Where on the HTML page should this module's JS be loaded?
240 * 'top': in the <head>
241 * 'bottom': at the bottom of the <body>
245 public function getPosition() {
250 * Whether this module's JS expects to work without the client-side ResourceLoader module.
251 * Returning true from this function will prevent mw.loader.state() call from being
252 * appended to the bottom of the script.
256 public function isRaw() {
261 * Get the loader JS for this module, if set.
263 * @return Mixed: JavaScript loader code as a string or boolean false if no custom loader set
265 public function getLoaderScript() {
266 // Stub, override expected
271 * Get a list of modules this module depends on.
273 * Dependency information is taken into account when loading a module
274 * on the client side. When adding a module on the server side,
275 * dependency information is NOT taken into account and YOU are
276 * responsible for adding dependent modules as well. If you don't do
277 * this, the client side loader will send a second request back to the
278 * server to fetch the missing modules, which kind of defeats the
279 * purpose of the resource loader.
281 * To add dependencies dynamically on the client side, use a custom
282 * loader script, see getLoaderScript()
283 * @return Array: List of module names as strings
285 public function getDependencies() {
286 // Stub, override expected
291 * Get the files this module depends on indirectly for a given skin.
292 * Currently these are only image files referenced by the module's CSS.
294 * @param $skin String: Skin name
295 * @return Array: List of files
297 public function getFileDependencies( $skin ) {
298 // Try in-object cache first
299 if ( isset( $this->fileDeps
[$skin] ) ) {
300 return $this->fileDeps
[$skin];
303 $dbr = wfGetDB( DB_SLAVE
);
304 $deps = $dbr->selectField( 'module_deps', 'md_deps', array(
305 'md_module' => $this->getName(),
309 if ( !is_null( $deps ) ) {
310 $this->fileDeps
[$skin] = (array) FormatJson
::decode( $deps, true );
312 $this->fileDeps
[$skin] = array();
314 return $this->fileDeps
[$skin];
318 * Set preloaded file dependency information. Used so we can load this
319 * information for all modules at once.
320 * @param $skin String: Skin name
321 * @param $deps Array: Array of file names
323 public function setFileDependencies( $skin, $deps ) {
324 $this->fileDeps
[$skin] = $deps;
328 * Get the last modification timestamp of the message blob for this
329 * module in a given language.
330 * @param $lang String: Language code
331 * @return Integer: UNIX timestamp, or 0 if the module doesn't have messages
333 public function getMsgBlobMtime( $lang ) {
334 if ( !isset( $this->msgBlobMtime
[$lang] ) ) {
335 if ( !count( $this->getMessages() ) )
338 $dbr = wfGetDB( DB_SLAVE
);
339 $msgBlobMtime = $dbr->selectField( 'msg_resource', 'mr_timestamp', array(
340 'mr_resource' => $this->getName(),
344 // If no blob was found, but the module does have messages, that means we need
345 // to regenerate it. Return NOW
346 if ( $msgBlobMtime === false ) {
347 $msgBlobMtime = wfTimestampNow();
349 $this->msgBlobMtime
[$lang] = wfTimestamp( TS_UNIX
, $msgBlobMtime );
351 return $this->msgBlobMtime
[$lang];
355 * Set a preloaded message blob last modification timestamp. Used so we
356 * can load this information for all modules at once.
357 * @param $lang String: Language code
358 * @param $mtime Integer: UNIX timestamp or 0 if there is no such blob
360 public function setMsgBlobMtime( $lang, $mtime ) {
361 $this->msgBlobMtime
[$lang] = $mtime;
364 /* Abstract Methods */
367 * Get this module's last modification timestamp for a given
368 * combination of language, skin and debug mode flag. This is typically
369 * the highest of each of the relevant components' modification
370 * timestamps. Whenever anything happens that changes the module's
371 * contents for these parameters, the mtime should increase.
373 * NOTE: The mtime of the module's messages is NOT automatically included.
374 * If you want this to happen, you'll need to call getMsgBlobMtime()
375 * yourself and take its result into consideration.
377 * @param $context ResourceLoaderContext: Context object
378 * @return Integer: UNIX timestamp
380 public function getModifiedTime( ResourceLoaderContext
$context ) {
386 * Check whether this module is known to be empty. If a child class
387 * has an easy and cheap way to determine that this module is
388 * definitely going to be empty, it should override this method to
389 * return true in that case. Callers may optimize the request for this
390 * module away if this function returns true.
391 * @param $context ResourceLoaderContext: Context object
394 public function isKnownEmpty( ResourceLoaderContext
$context ) {
399 /** @var JSParser lazy-initialized; use self::javaScriptParser() */
400 private static $jsParser;
401 private static $parseCacheVersion = 1;
404 * Validate a given script file; if valid returns the original source.
405 * If invalid, returns replacement JS source that throws an exception.
407 * @param string $fileName
408 * @param string $contents
409 * @return string JS with the original, or a replacement error
411 protected function validateScriptFile( $fileName, $contents ) {
412 global $wgResourceLoaderValidateJS;
413 if ( $wgResourceLoaderValidateJS ) {
415 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
416 $key = wfMemcKey( 'resourceloader', 'jsparse', self
::$parseCacheVersion, md5( $contents ) );
417 $cache = wfGetCache( CACHE_ANYTHING
);
418 $cacheEntry = $cache->get( $key );
419 if ( is_string( $cacheEntry ) ) {
423 $parser = self
::javaScriptParser();
425 $parser->parse( $contents, $fileName, 1 );
427 } catch (Exception
$e) {
428 // We'll save this to cache to avoid having to validate broken JS over and over...
429 $err = $e->getMessage();
430 $result = "throw new Error(" . Xml
::encodeJsVar("JavaScript parse error: $err") . ");";
433 $cache->set( $key, $result );
443 protected static function javaScriptParser() {
444 if ( !self
::$jsParser ) {
445 self
::$jsParser = new JSParser();
447 return self
::$jsParser;