Fix the fixme on r88053: dependency handling was broken in debug mode in certain...
[lhc/web/wiklou.git] / includes / resourceloader / ResourceLoaderModule.php
1 <?php
2 /**
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.
7 *
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.
12 *
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
17 *
18 * @file
19 * @author Trevor Parscal
20 * @author Roan Kattouw
21 */
22
23 /**
24 * Abstraction for resource loader modules, with name registration and maxage functionality.
25 */
26 abstract class ResourceLoaderModule {
27
28 # Type of resource
29 const TYPE_SCRIPTS = 'scripts';
30 const TYPE_STYLES = 'styles';
31 const TYPE_MESSAGES = 'messages';
32 const TYPE_COMBINED = 'combined';
33
34 # sitewide core module like a skin file or jQuery component
35 const ORIGIN_CORE_SITEWIDE = 1;
36
37 # per-user module generated by the software
38 const ORIGIN_CORE_INDIVIDUAL = 2;
39
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;
43
44 # per-user module generated from user-editable files, like User:Me/vector.js
45 const ORIGIN_USER_INDIVIDUAL = 4;
46
47 # an access constant; make sure this is kept as the largest number in this group
48 const ORIGIN_ALL = 10;
49
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;
55
56 /* Protected Members */
57
58 protected $name = null;
59
60 // In-object cache for file dependencies
61 protected $fileDeps = array();
62 // In-object cache for message blob mtime
63 protected $msgBlobMtime = array();
64
65 /* Methods */
66
67 /**
68 * Get this module's name. This is set when the module is registered
69 * with ResourceLoader::register()
70 *
71 * @return Mixed: Name (string) or null if no name was set
72 */
73 public function getName() {
74 return $this->name;
75 }
76
77 /**
78 * Set this module's name. This is called by ResourceLodaer::register()
79 * when registering the module. Other code should not call this.
80 *
81 * @param $name String: Name
82 */
83 public function setName( $name ) {
84 $this->name = $name;
85 }
86
87 /**
88 * Get this module's origin. This is set when the module is registered
89 * with ResourceLoader::register()
90 *
91 * @return Int ResourceLoaderModule class constant, the subclass default
92 * if not set manuall
93 */
94 public function getOrigin() {
95 return $this->origin;
96 }
97
98 /**
99 * Set this module's origin. This is called by ResourceLodaer::register()
100 * when registering the module. Other code should not call this.
101 *
102 * @param $origin Int origin
103 */
104 public function setOrigin( $origin ) {
105 $this->origin = $origin;
106 }
107
108 /**
109 * @param $context ResourceLoaderContext
110 * @return bool
111 */
112 public function getFlip( $context ) {
113 global $wgContLang;
114
115 return $wgContLang->getDir() !== $context->getDirection();
116 }
117
118 /**
119 * Get all JS for this module for a given language and skin.
120 * Includes all relevant JS except loader scripts.
121 *
122 * @param $context ResourceLoaderContext: Context object
123 * @return String: JavaScript code
124 */
125 public function getScript( ResourceLoaderContext $context ) {
126 // Stub, override expected
127 return '';
128 }
129
130 /**
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.
135 *
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.
140 *
141 * @param $context ResourceLoaderContext: Context object
142 * @return Array of URLs
143 */
144 public function getScriptURLsForDebug( ResourceLoaderContext $context ) {
145 global $wgLoadScript; // TODO factor out to ResourceLoader static method and deduplicate from makeResourceLoaderLink()
146 $query = array(
147 'modules' => $this->getName(),
148 'only' => 'scripts',
149 'skin' => $context->getSkin(),
150 'user' => $context->getUser(),
151 'debug' => 'true',
152 'version' => $context->getVersion()
153 );
154 ksort( $query );
155 return array( wfAppendQuery( $wgLoadScript, $query ) . '&*' );
156 }
157
158 /**
159 * Whether this module supports URL loading. If this function returns false,
160 * getScript() will be used even in cases (debug mode, no only param) where
161 * getScriptURLsForDebug() would normally be used instead.
162 * @return bool
163 */
164 public function supportsURLLoading() {
165 return true;
166 }
167
168 /**
169 * Get all CSS for this module for a given skin.
170 *
171 * @param $context ResourceLoaderContext: Context object
172 * @return Array: List of CSS strings keyed by media type
173 */
174 public function getStyles( ResourceLoaderContext $context ) {
175 // Stub, override expected
176 return array();
177 }
178
179 /**
180 * Get the URL or URLs to load for this module's CSS in debug mode.
181 * The default behavior is to return a load.php?only=styles URL for
182 * the module, but file-based modules will want to override this to
183 * load the files directly. See also getScriptURLsForDebug()
184 *
185 * @param $context ResourceLoaderContext: Context object
186 * @return Array: array( mediaType => array( URL1, URL2, ... ), ... )
187 */
188 public function getStyleURLsForDebug( ResourceLoaderContext $context ) {
189 global $wgLoadScript; // TODO factor out to ResourceLoader static method and deduplicate from makeResourceLoaderLink()
190 $query = array(
191 'modules' => $this->getName(),
192 'only' => 'styles',
193 'skin' => $context->getSkin(),
194 'user' => $context->getUser(),
195 'debug' => 'true',
196 'version' => $context->getVersion()
197 );
198 ksort( $query );
199 return array( 'all' => array( wfAppendQuery( $wgLoadScript, $query ) . '&*' ) );
200 }
201
202 /**
203 * Get the messages needed for this module.
204 *
205 * To get a JSON blob with messages, use MessageBlobStore::get()
206 *
207 * @return Array: List of message keys. Keys may occur more than once
208 */
209 public function getMessages() {
210 // Stub, override expected
211 return array();
212 }
213
214 /**
215 * Get the group this module is in.
216 *
217 * @return String: Group name
218 */
219 public function getGroup() {
220 // Stub, override expected
221 return null;
222 }
223
224 /**
225 * Get the origin of this module. Should only be overridden for foreign modules.
226 *
227 * @return String: Origin name, 'local' for local modules
228 */
229 public function getSource() {
230 // Stub, override expected
231 return 'local';
232 }
233
234 /**
235 * Where on the HTML page should this module's JS be loaded?
236 * 'top': in the <head>
237 * 'bottom': at the bottom of the <body>
238 *
239 * @return string
240 */
241 public function getPosition() {
242 return 'bottom';
243 }
244
245 /**
246 * Get the loader JS for this module, if set.
247 *
248 * @return Mixed: JavaScript loader code as a string or boolean false if no custom loader set
249 */
250 public function getLoaderScript() {
251 // Stub, override expected
252 return false;
253 }
254
255 /**
256 * Get a list of modules this module depends on.
257 *
258 * Dependency information is taken into account when loading a module
259 * on the client side. When adding a module on the server side,
260 * dependency information is NOT taken into account and YOU are
261 * responsible for adding dependent modules as well. If you don't do
262 * this, the client side loader will send a second request back to the
263 * server to fetch the missing modules, which kind of defeats the
264 * purpose of the resource loader.
265 *
266 * To add dependencies dynamically on the client side, use a custom
267 * loader script, see getLoaderScript()
268 * @return Array: List of module names as strings
269 */
270 public function getDependencies() {
271 // Stub, override expected
272 return array();
273 }
274
275 /**
276 * Get the files this module depends on indirectly for a given skin.
277 * Currently these are only image files referenced by the module's CSS.
278 *
279 * @param $skin String: Skin name
280 * @return Array: List of files
281 */
282 public function getFileDependencies( $skin ) {
283 // Try in-object cache first
284 if ( isset( $this->fileDeps[$skin] ) ) {
285 return $this->fileDeps[$skin];
286 }
287
288 $dbr = wfGetDB( DB_SLAVE );
289 $deps = $dbr->selectField( 'module_deps', 'md_deps', array(
290 'md_module' => $this->getName(),
291 'md_skin' => $skin,
292 ), __METHOD__
293 );
294 if ( !is_null( $deps ) ) {
295 $this->fileDeps[$skin] = (array) FormatJson::decode( $deps, true );
296 } else {
297 $this->fileDeps[$skin] = array();
298 }
299 return $this->fileDeps[$skin];
300 }
301
302 /**
303 * Set preloaded file dependency information. Used so we can load this
304 * information for all modules at once.
305 * @param $skin String: Skin name
306 * @param $deps Array: Array of file names
307 */
308 public function setFileDependencies( $skin, $deps ) {
309 $this->fileDeps[$skin] = $deps;
310 }
311
312 /**
313 * Get the last modification timestamp of the message blob for this
314 * module in a given language.
315 * @param $lang String: Language code
316 * @return Integer: UNIX timestamp, or 0 if the module doesn't have messages
317 */
318 public function getMsgBlobMtime( $lang ) {
319 if ( !isset( $this->msgBlobMtime[$lang] ) ) {
320 if ( !count( $this->getMessages() ) )
321 return 0;
322
323 $dbr = wfGetDB( DB_SLAVE );
324 $msgBlobMtime = $dbr->selectField( 'msg_resource', 'mr_timestamp', array(
325 'mr_resource' => $this->getName(),
326 'mr_lang' => $lang
327 ), __METHOD__
328 );
329 // If no blob was found, but the module does have messages, that means we need
330 // to regenerate it. Return NOW
331 if ( $msgBlobMtime === false ) {
332 $msgBlobMtime = wfTimestampNow();
333 }
334 $this->msgBlobMtime[$lang] = wfTimestamp( TS_UNIX, $msgBlobMtime );
335 }
336 return $this->msgBlobMtime[$lang];
337 }
338
339 /**
340 * Set a preloaded message blob last modification timestamp. Used so we
341 * can load this information for all modules at once.
342 * @param $lang String: Language code
343 * @param $mtime Integer: UNIX timestamp or 0 if there is no such blob
344 */
345 public function setMsgBlobMtime( $lang, $mtime ) {
346 $this->msgBlobMtime[$lang] = $mtime;
347 }
348
349 /* Abstract Methods */
350
351 /**
352 * Get this module's last modification timestamp for a given
353 * combination of language, skin and debug mode flag. This is typically
354 * the highest of each of the relevant components' modification
355 * timestamps. Whenever anything happens that changes the module's
356 * contents for these parameters, the mtime should increase.
357 *
358 * @param $context ResourceLoaderContext: Context object
359 * @return Integer: UNIX timestamp
360 */
361 public function getModifiedTime( ResourceLoaderContext $context ) {
362 // 0 would mean now
363 return 1;
364 }
365
366 /**
367 * Check whether this module is known to be empty. If a child class
368 * has an easy and cheap way to determine that this module is
369 * definitely going to be empty, it should override this method to
370 * return true in that case. Callers may optimize the request for this
371 * module away if this function returns true.
372 * @param $context ResourceLoaderContext: Context object
373 * @return Boolean
374 */
375 public function isKnownEmpty( ResourceLoaderContext $context ) {
376 return false;
377 }
378
379
380 /** @var JSParser lazy-initialized; use self::javaScriptParser() */
381 private static $jsParser;
382 private static $parseCacheVersion = 1;
383
384 /**
385 * Validate a given script file; if valid returns the original source.
386 * If invalid, returns replacement JS source that throws an exception.
387 *
388 * @param string $fileName
389 * @param string $contents
390 * @return string JS with the original, or a replacement error
391 */
392 protected function validateScriptFile( $fileName, $contents ) {
393 global $wgResourceLoaderValidateJS;
394 if ( $wgResourceLoaderValidateJS ) {
395 // Try for cache hit
396 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
397 $key = wfMemcKey( 'resourceloader', 'jsparse', self::$parseCacheVersion, md5( $contents ) );
398 $cache = wfGetCache( CACHE_ANYTHING );
399 $cacheEntry = $cache->get( $key );
400 if ( is_string( $cacheEntry ) ) {
401 return $cacheEntry;
402 }
403
404 $parser = self::javaScriptParser();
405 try {
406 $parser->parse( $contents, $fileName, 1 );
407 $result = $contents;
408 } catch (Exception $e) {
409 // We'll save this to cache to avoid having to validate broken JS over and over...
410 $err = $e->getMessage();
411 $result = "throw new Error(" . Xml::encodeJsVar("JavaScript parse error: $err") . ");";
412 }
413
414 $cache->set( $key, $result );
415 return $result;
416 } else {
417 return $contents;
418 }
419 }
420
421 protected static function javaScriptParser() {
422 if ( !self::$jsParser ) {
423 self::$jsParser = new JSParser();
424 }
425 return self::$jsParser;
426 }
427
428 }