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