Fixed spacing in db/debug/diff/externalstore/objectcache folder
[mediawiki.git] / includes / resourceloader / ResourceLoaderModule.php
blobf6a7114af4b80839576188a20a0ddbee837c781f
1 <?php
2 /**
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
20 * @file
21 * @author Trevor Parscal
22 * @author Roan Kattouw
25 /**
26 * Abstraction for resource loader modules, with name registration and maxage functionality.
28 abstract class ResourceLoaderModule {
30 # Type of resource
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;
61 protected $targets = array( 'desktop' );
63 // In-object cache for file dependencies
64 protected $fileDeps = array();
65 // In-object cache for message blob mtime
66 protected $msgBlobMtime = array();
68 /* Methods */
70 /**
71 * Get this module's name. This is set when the module is registered
72 * with ResourceLoader::register()
74 * @return Mixed: Name (string) or null if no name was set
76 public function getName() {
77 return $this->name;
80 /**
81 * Set this module's name. This is called by ResourceLoader::register()
82 * when registering the module. Other code should not call this.
84 * @param string $name Name
86 public function setName( $name ) {
87 $this->name = $name;
90 /**
91 * Get this module's origin. This is set when the module is registered
92 * with ResourceLoader::register()
94 * @return Int ResourceLoaderModule class constant, the subclass default
95 * if not set manually
97 public function getOrigin() {
98 return $this->origin;
102 * Set this module's origin. This is called by ResourceLoader::register()
103 * when registering the module. Other code should not call this.
105 * @param int $origin origin
107 public function setOrigin( $origin ) {
108 $this->origin = $origin;
112 * @param $context ResourceLoaderContext
113 * @return bool
115 public function getFlip( $context ) {
116 global $wgContLang;
118 return $wgContLang->getDir() !== $context->getDirection();
122 * Get all JS for this module for a given language and skin.
123 * Includes all relevant JS except loader scripts.
125 * @param $context ResourceLoaderContext: Context object
126 * @return String: JavaScript code
128 public function getScript( ResourceLoaderContext $context ) {
129 // Stub, override expected
130 return '';
134 * Get the URL or URLs to load for this module's JS in debug mode.
135 * The default behavior is to return a load.php?only=scripts URL for
136 * the module, but file-based modules will want to override this to
137 * load the files directly.
139 * This function is called only when 1) we're in debug mode, 2) there
140 * is no only= parameter and 3) supportsURLLoading() returns true.
141 * #2 is important to prevent an infinite loop, therefore this function
142 * MUST return either an only= URL or a non-load.php URL.
144 * @param $context ResourceLoaderContext: Context object
145 * @return Array of URLs
147 public function getScriptURLsForDebug( ResourceLoaderContext $context ) {
148 $url = ResourceLoader::makeLoaderURL(
149 array( $this->getName() ),
150 $context->getLanguage(),
151 $context->getSkin(),
152 $context->getUser(),
153 $context->getVersion(),
154 true, // debug
155 'scripts', // only
156 $context->getRequest()->getBool( 'printable' ),
157 $context->getRequest()->getBool( 'handheld' )
159 return array( $url );
163 * Whether this module supports URL loading. If this function returns false,
164 * getScript() will be used even in cases (debug mode, no only param) where
165 * getScriptURLsForDebug() would normally be used instead.
166 * @return bool
168 public function supportsURLLoading() {
169 return true;
173 * Get all CSS for this module for a given skin.
175 * @param $context ResourceLoaderContext: Context object
176 * @return Array: List of CSS strings or array of CSS strings keyed by media type.
177 * like array( 'screen' => '.foo { width: 0 }' );
178 * or array( 'screen' => array( '.foo { width: 0 }' ) );
180 public function getStyles( ResourceLoaderContext $context ) {
181 // Stub, override expected
182 return array();
186 * Get the URL or URLs to load for this module's CSS in debug mode.
187 * The default behavior is to return a load.php?only=styles URL for
188 * the module, but file-based modules will want to override this to
189 * load the files directly. See also getScriptURLsForDebug()
191 * @param $context ResourceLoaderContext: Context object
192 * @return Array: array( mediaType => array( URL1, URL2, ... ), ... )
194 public function getStyleURLsForDebug( ResourceLoaderContext $context ) {
195 $url = ResourceLoader::makeLoaderURL(
196 array( $this->getName() ),
197 $context->getLanguage(),
198 $context->getSkin(),
199 $context->getUser(),
200 $context->getVersion(),
201 true, // debug
202 'styles', // only
203 $context->getRequest()->getBool( 'printable' ),
204 $context->getRequest()->getBool( 'handheld' )
206 return array( 'all' => array( $url ) );
210 * Get the messages needed for this module.
212 * To get a JSON blob with messages, use MessageBlobStore::get()
214 * @return Array: List of message keys. Keys may occur more than once
216 public function getMessages() {
217 // Stub, override expected
218 return array();
222 * Get the group this module is in.
224 * @return String: Group name
226 public function getGroup() {
227 // Stub, override expected
228 return null;
232 * Get the origin of this module. Should only be overridden for foreign modules.
234 * @return String: Origin name, 'local' for local modules
236 public function getSource() {
237 // Stub, override expected
238 return 'local';
242 * Where on the HTML page should this module's JS be loaded?
243 * - 'top': in the "<head>"
244 * - 'bottom': at the bottom of the "<body>"
246 * @return string
248 public function getPosition() {
249 return 'bottom';
253 * Whether this module's JS expects to work without the client-side ResourceLoader module.
254 * Returning true from this function will prevent mw.loader.state() call from being
255 * appended to the bottom of the script.
257 * @return bool
259 public function isRaw() {
260 return false;
264 * Get the loader JS for this module, if set.
266 * @return Mixed: JavaScript loader code as a string or boolean false if no custom loader set
268 public function getLoaderScript() {
269 // Stub, override expected
270 return false;
274 * Get a list of modules this module depends on.
276 * Dependency information is taken into account when loading a module
277 * on the client side. When adding a module on the server side,
278 * dependency information is NOT taken into account and YOU are
279 * responsible for adding dependent modules as well. If you don't do
280 * this, the client side loader will send a second request back to the
281 * server to fetch the missing modules, which kind of defeats the
282 * purpose of the resource loader.
284 * To add dependencies dynamically on the client side, use a custom
285 * loader script, see getLoaderScript()
286 * @return Array: List of module names as strings
288 public function getDependencies() {
289 // Stub, override expected
290 return array();
294 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
296 * @return array of strings
298 public function getTargets() {
299 return $this->targets;
303 * Get the files this module depends on indirectly for a given skin.
304 * Currently these are only image files referenced by the module's CSS.
306 * @param string $skin Skin name
307 * @return Array: List of files
309 public function getFileDependencies( $skin ) {
310 // Try in-object cache first
311 if ( isset( $this->fileDeps[$skin] ) ) {
312 return $this->fileDeps[$skin];
315 $dbr = wfGetDB( DB_SLAVE );
316 $deps = $dbr->selectField( 'module_deps', 'md_deps', array(
317 'md_module' => $this->getName(),
318 'md_skin' => $skin,
319 ), __METHOD__
321 if ( !is_null( $deps ) ) {
322 $this->fileDeps[$skin] = (array)FormatJson::decode( $deps, true );
323 } else {
324 $this->fileDeps[$skin] = array();
326 return $this->fileDeps[$skin];
330 * Set preloaded file dependency information. Used so we can load this
331 * information for all modules at once.
332 * @param string $skin Skin name
333 * @param array $deps Array of file names
335 public function setFileDependencies( $skin, $deps ) {
336 $this->fileDeps[$skin] = $deps;
340 * Get the last modification timestamp of the message blob for this
341 * module in a given language.
342 * @param string $lang Language code
343 * @return Integer: UNIX timestamp, or 0 if the module doesn't have messages
345 public function getMsgBlobMtime( $lang ) {
346 if ( !isset( $this->msgBlobMtime[$lang] ) ) {
347 if ( !count( $this->getMessages() ) ) {
348 return 0;
351 $dbr = wfGetDB( DB_SLAVE );
352 $msgBlobMtime = $dbr->selectField( 'msg_resource', 'mr_timestamp', array(
353 'mr_resource' => $this->getName(),
354 'mr_lang' => $lang
355 ), __METHOD__
357 // If no blob was found, but the module does have messages, that means we need
358 // to regenerate it. Return NOW
359 if ( $msgBlobMtime === false ) {
360 $msgBlobMtime = wfTimestampNow();
362 $this->msgBlobMtime[$lang] = wfTimestamp( TS_UNIX, $msgBlobMtime );
364 return $this->msgBlobMtime[$lang];
368 * Set a preloaded message blob last modification timestamp. Used so we
369 * can load this information for all modules at once.
370 * @param string $lang Language code
371 * @param $mtime Integer: UNIX timestamp or 0 if there is no such blob
373 public function setMsgBlobMtime( $lang, $mtime ) {
374 $this->msgBlobMtime[$lang] = $mtime;
377 /* Abstract Methods */
380 * Get this module's last modification timestamp for a given
381 * combination of language, skin and debug mode flag. This is typically
382 * the highest of each of the relevant components' modification
383 * timestamps. Whenever anything happens that changes the module's
384 * contents for these parameters, the mtime should increase.
386 * NOTE: The mtime of the module's messages is NOT automatically included.
387 * If you want this to happen, you'll need to call getMsgBlobMtime()
388 * yourself and take its result into consideration.
390 * @param $context ResourceLoaderContext: Context object
391 * @return Integer: UNIX timestamp
393 public function getModifiedTime( ResourceLoaderContext $context ) {
394 // 0 would mean now
395 return 1;
399 * Check whether this module is known to be empty. If a child class
400 * has an easy and cheap way to determine that this module is
401 * definitely going to be empty, it should override this method to
402 * return true in that case. Callers may optimize the request for this
403 * module away if this function returns true.
404 * @param $context ResourceLoaderContext: Context object
405 * @return Boolean
407 public function isKnownEmpty( ResourceLoaderContext $context ) {
408 return false;
411 /** @var JSParser lazy-initialized; use self::javaScriptParser() */
412 private static $jsParser;
413 private static $parseCacheVersion = 1;
416 * Validate a given script file; if valid returns the original source.
417 * If invalid, returns replacement JS source that throws an exception.
419 * @param string $fileName
420 * @param string $contents
421 * @return string JS with the original, or a replacement error
423 protected function validateScriptFile( $fileName, $contents ) {
424 global $wgResourceLoaderValidateJS;
425 if ( $wgResourceLoaderValidateJS ) {
426 // Try for cache hit
427 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
428 $key = wfMemcKey( 'resourceloader', 'jsparse', self::$parseCacheVersion, md5( $contents ) );
429 $cache = wfGetCache( CACHE_ANYTHING );
430 $cacheEntry = $cache->get( $key );
431 if ( is_string( $cacheEntry ) ) {
432 return $cacheEntry;
435 $parser = self::javaScriptParser();
436 try {
437 $parser->parse( $contents, $fileName, 1 );
438 $result = $contents;
439 } catch ( Exception $e ) {
440 // We'll save this to cache to avoid having to validate broken JS over and over...
441 $err = $e->getMessage();
442 $result = "throw new Error(" . Xml::encodeJsVar( "JavaScript parse error: $err" ) . ");";
445 $cache->set( $key, $result );
446 return $result;
447 } else {
448 return $contents;
453 * @return JSParser
455 protected static function javaScriptParser() {
456 if ( !self::$jsParser ) {
457 self::$jsParser = new JSParser();
459 return self::$jsParser;
463 * Safe version of filemtime(), which doesn't throw a PHP warning if the file doesn't exist
464 * but returns 1 instead.
465 * @param string $filename File name
466 * @return int UNIX timestamp, or 1 if the file doesn't exist
468 protected static function safeFilemtime( $filename ) {
469 if ( file_exists( $filename ) ) {
470 return filemtime( $filename );
471 } else {
472 // We only ever map this function on an array if we're gonna call max() after,
473 // so return our standard minimum timestamps here. This is 1, not 0, because
474 // wfTimestamp(0) == NOW
475 return 1;