3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
19 * @author Trevor Parscal
20 * @author Roan Kattouw
24 * Abstraction for resource loader modules, with name registration and maxage functionality.
26 abstract class ResourceLoaderModule
{
29 const TYPE_SCRIPTS
= 'scripts';
30 const TYPE_STYLES
= 'styles';
31 const TYPE_MESSAGES
= 'messages';
32 const TYPE_COMBINED
= 'combined';
34 # sitewide core module like a skin file or jQuery component
35 const ORIGIN_CORE_SITEWIDE
= 1;
37 # per-user module generated by the software
38 const ORIGIN_CORE_INDIVIDUAL
= 2;
40 # sitewide module generated from user-editable files, like MediaWiki:Common.js, or
41 # modules accessible to multiple users, such as those generated by the Gadgets extension.
42 const ORIGIN_USER_SITEWIDE
= 3;
44 # per-user module generated from user-editable files, like User:Me/vector.js
45 const ORIGIN_USER_INDIVIDUAL
= 4;
47 # an access constant; make sure this is kept as the largest number in this group
48 const ORIGIN_ALL
= 10;
50 # script and style modules form a hierarchy of trustworthiness, with core modules like
51 # skins and jQuery as most trustworthy, and user scripts as least trustworthy. We can
52 # limit the types of scripts and styles we allow to load on, say, sensitive special
53 # pages like Special:UserLogin and Special:Preferences
54 protected $origin = self
::ORIGIN_CORE_SITEWIDE
;
56 /* Protected Members */
58 protected $name = null;
60 // In-object cache for file dependencies
61 protected $fileDeps = array();
62 // In-object cache for message blob mtime
63 protected $msgBlobMtime = array();
68 * Get this module's name. This is set when the module is registered
69 * with ResourceLoader::register()
71 * @return Mixed: Name (string) or null if no name was set
73 public function getName() {
78 * Set this module's name. This is called by ResourceLodaer::register()
79 * when registering the module. Other code should not call this.
81 * @param $name String: Name
83 public function setName( $name ) {
88 * Get this module's origin. This is set when the module is registered
89 * with ResourceLoader::register()
91 * @return Int ResourceLoaderModule class constant, the subclass default
94 public function getOrigin() {
99 * Set this module's origin. This is called by ResourceLodaer::register()
100 * when registering the module. Other code should not call this.
102 * @param $origin Int origin
104 public function setOrigin( $origin ) {
105 $this->origin
= $origin;
109 * @param $context ResourceLoaderContext
112 public function getFlip( $context ) {
115 return $wgContLang->getDir() !== $context->getDirection();
119 * Get all JS for this module for a given language and skin.
120 * Includes all relevant JS except loader scripts.
122 * @param $context ResourceLoaderContext: Context object
123 * @return String: JavaScript code
125 public function getScript( ResourceLoaderContext
$context ) {
126 // Stub, override expected
131 * Get the URL or URLs to load for this module's JS in debug mode.
132 * The default behavior is to return a load.php?only=scripts URL for
133 * the module, but file-based modules will want to override this to
134 * load the files directly.
136 * This function is called only when 1) we're in debug mode, 2) there
137 * is no only= parameter and 3) supportsURLLoading() returns true.
138 * #2 is important to prevent an infinite loop, therefore this function
139 * MUST return either an only= URL or a non-load.php URL.
141 * @param $context ResourceLoaderContext: Context object
142 * @return Array of URLs
144 public function getScriptURLsForDebug( ResourceLoaderContext
$context ) {
145 $url = ResourceLoader
::makeLoaderURL(
146 array( $this->getName() ),
147 $context->getLanguage(),
150 $context->getVersion(),
153 $context->getRequest()->getBool( 'printable' ),
154 $context->getRequest()->getBool( 'handheld' )
156 return array( $url );
160 * Whether this module supports URL loading. If this function returns false,
161 * getScript() will be used even in cases (debug mode, no only param) where
162 * getScriptURLsForDebug() would normally be used instead.
165 public function supportsURLLoading() {
170 * Get all CSS for this module for a given skin.
172 * @param $context ResourceLoaderContext: Context object
173 * @return Array: List of CSS strings keyed by media type
175 public function getStyles( ResourceLoaderContext
$context ) {
176 // Stub, override expected
181 * Get the URL or URLs to load for this module's CSS in debug mode.
182 * The default behavior is to return a load.php?only=styles URL for
183 * the module, but file-based modules will want to override this to
184 * load the files directly. See also getScriptURLsForDebug()
186 * @param $context ResourceLoaderContext: Context object
187 * @return Array: array( mediaType => array( URL1, URL2, ... ), ... )
189 public function getStyleURLsForDebug( ResourceLoaderContext
$context ) {
190 $url = ResourceLoader
::makeLoaderURL(
191 array( $this->getName() ),
192 $context->getLanguage(),
195 $context->getVersion(),
198 $context->getRequest()->getBool( 'printable' ),
199 $context->getRequest()->getBool( 'handheld' )
201 return array( 'all' => array( $url ) );
205 * Get the messages needed for this module.
207 * To get a JSON blob with messages, use MessageBlobStore::get()
209 * @return Array: List of message keys. Keys may occur more than once
211 public function getMessages() {
212 // Stub, override expected
217 * Get the group this module is in.
219 * @return String: Group name
221 public function getGroup() {
222 // Stub, override expected
227 * Get the origin of this module. Should only be overridden for foreign modules.
229 * @return String: Origin name, 'local' for local modules
231 public function getSource() {
232 // Stub, override expected
237 * Where on the HTML page should this module's JS be loaded?
238 * 'top': in the <head>
239 * 'bottom': at the bottom of the <body>
243 public function getPosition() {
248 * Get the loader JS for this module, if set.
250 * @return Mixed: JavaScript loader code as a string or boolean false if no custom loader set
252 public function getLoaderScript() {
253 // Stub, override expected
258 * Get a list of modules this module depends on.
260 * Dependency information is taken into account when loading a module
261 * on the client side. When adding a module on the server side,
262 * dependency information is NOT taken into account and YOU are
263 * responsible for adding dependent modules as well. If you don't do
264 * this, the client side loader will send a second request back to the
265 * server to fetch the missing modules, which kind of defeats the
266 * purpose of the resource loader.
268 * To add dependencies dynamically on the client side, use a custom
269 * loader script, see getLoaderScript()
270 * @return Array: List of module names as strings
272 public function getDependencies() {
273 // Stub, override expected
278 * Get the files this module depends on indirectly for a given skin.
279 * Currently these are only image files referenced by the module's CSS.
281 * @param $skin String: Skin name
282 * @return Array: List of files
284 public function getFileDependencies( $skin ) {
285 // Try in-object cache first
286 if ( isset( $this->fileDeps
[$skin] ) ) {
287 return $this->fileDeps
[$skin];
290 $dbr = wfGetDB( DB_SLAVE
);
291 $deps = $dbr->selectField( 'module_deps', 'md_deps', array(
292 'md_module' => $this->getName(),
296 if ( !is_null( $deps ) ) {
297 $this->fileDeps
[$skin] = (array) FormatJson
::decode( $deps, true );
299 $this->fileDeps
[$skin] = array();
301 return $this->fileDeps
[$skin];
305 * Set preloaded file dependency information. Used so we can load this
306 * information for all modules at once.
307 * @param $skin String: Skin name
308 * @param $deps Array: Array of file names
310 public function setFileDependencies( $skin, $deps ) {
311 $this->fileDeps
[$skin] = $deps;
315 * Get the last modification timestamp of the message blob for this
316 * module in a given language.
317 * @param $lang String: Language code
318 * @return Integer: UNIX timestamp, or 0 if the module doesn't have messages
320 public function getMsgBlobMtime( $lang ) {
321 if ( !isset( $this->msgBlobMtime
[$lang] ) ) {
322 if ( !count( $this->getMessages() ) )
325 $dbr = wfGetDB( DB_SLAVE
);
326 $msgBlobMtime = $dbr->selectField( 'msg_resource', 'mr_timestamp', array(
327 'mr_resource' => $this->getName(),
331 // If no blob was found, but the module does have messages, that means we need
332 // to regenerate it. Return NOW
333 if ( $msgBlobMtime === false ) {
334 $msgBlobMtime = wfTimestampNow();
336 $this->msgBlobMtime
[$lang] = wfTimestamp( TS_UNIX
, $msgBlobMtime );
338 return $this->msgBlobMtime
[$lang];
342 * Set a preloaded message blob last modification timestamp. Used so we
343 * can load this information for all modules at once.
344 * @param $lang String: Language code
345 * @param $mtime Integer: UNIX timestamp or 0 if there is no such blob
347 public function setMsgBlobMtime( $lang, $mtime ) {
348 $this->msgBlobMtime
[$lang] = $mtime;
351 /* Abstract Methods */
354 * Get this module's last modification timestamp for a given
355 * combination of language, skin and debug mode flag. This is typically
356 * the highest of each of the relevant components' modification
357 * timestamps. Whenever anything happens that changes the module's
358 * contents for these parameters, the mtime should increase.
360 * NOTE: The mtime of the module's messages is NOT automatically included.
361 * If you want this to happen, you'll need to call getMsgBlobMtime()
362 * yourself and take its result into consideration.
364 * @param $context ResourceLoaderContext: Context object
365 * @return Integer: UNIX timestamp
367 public function getModifiedTime( ResourceLoaderContext
$context ) {
373 * Check whether this module is known to be empty. If a child class
374 * has an easy and cheap way to determine that this module is
375 * definitely going to be empty, it should override this method to
376 * return true in that case. Callers may optimize the request for this
377 * module away if this function returns true.
378 * @param $context ResourceLoaderContext: Context object
381 public function isKnownEmpty( ResourceLoaderContext
$context ) {
386 /** @var JSParser lazy-initialized; use self::javaScriptParser() */
387 private static $jsParser;
388 private static $parseCacheVersion = 1;
391 * Validate a given script file; if valid returns the original source.
392 * If invalid, returns replacement JS source that throws an exception.
394 * @param string $fileName
395 * @param string $contents
396 * @return string JS with the original, or a replacement error
398 protected function validateScriptFile( $fileName, $contents ) {
399 global $wgResourceLoaderValidateJS;
400 if ( $wgResourceLoaderValidateJS ) {
402 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
403 $key = wfMemcKey( 'resourceloader', 'jsparse', self
::$parseCacheVersion, md5( $contents ) );
404 $cache = wfGetCache( CACHE_ANYTHING
);
405 $cacheEntry = $cache->get( $key );
406 if ( is_string( $cacheEntry ) ) {
410 $parser = self
::javaScriptParser();
412 $parser->parse( $contents, $fileName, 1 );
414 } catch (Exception
$e) {
415 // We'll save this to cache to avoid having to validate broken JS over and over...
416 $err = $e->getMessage();
417 $result = "throw new Error(" . Xml
::encodeJsVar("JavaScript parse error: $err") . ");";
420 $cache->set( $key, $result );
430 protected static function javaScriptParser() {
431 if ( !self
::$jsParser ) {
432 self
::$jsParser = new JSParser();
434 return self
::$jsParser;