Added direction to ResourceLoaderContext hashing (prevents cache mangling), dropped...
[lhc/web/wiklou.git] / includes / 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 /* Protected Members */
28
29 protected $name = null;
30
31 /* Methods */
32
33 /**
34 * Get this module's name. This is set when the module is registered
35 * with ResourceLoader::register()
36 *
37 * @return Mixed: name (string) or null if no name was set
38 */
39 public function getName() {
40 return $this->name;
41 }
42
43 /**
44 * Set this module's name. This is called by ResourceLodaer::register()
45 * when registering the module. Other code should not call this.
46 *
47 * @param $name String: name
48 */
49 public function setName( $name ) {
50 $this->name = $name;
51 }
52
53 /**
54 * The maximum number of seconds to cache this module for in the
55 * client-side (browser) cache. Override this only if you have a good
56 * reason not to use $wgResourceLoaderClientMaxage.
57 *
58 * @return Integer: cache maxage in seconds
59 */
60 public function getClientMaxage() {
61 global $wgResourceLoaderClientMaxage;
62 return $wgResourceLoaderClientMaxage;
63 }
64
65 /**
66 * The maximum number of seconds to cache this module for in the
67 * server-side (Squid / proxy) cache. Override this only if you have a
68 * good reason not to use $wgResourceLoaderServerMaxage.
69 *
70 * @return Integer: cache maxage in seconds
71 */
72 public function getServerMaxage() {
73 global $wgResourceLoaderServerMaxage;
74 return $wgResourceLoaderServerMaxage;
75 }
76
77 /**
78 * Get whether CSS for this module should be flipped
79 */
80 public function getFlip( $context ) {
81 return $context->getDirection() === 'rtl';
82 }
83
84 /**
85 * Get all JS for this module for a given language and skin.
86 * Includes all relevant JS except loader scripts.
87 *
88 * @param $context ResourceLoaderContext object
89 * @return String: JS
90 */
91 public function getScript( ResourceLoaderContext $context ) {
92 // Stub, override expected
93 return '';
94 }
95
96 /**
97 * Get all CSS for this module for a given skin.
98 *
99 * @param $context ResourceLoaderContext object
100 * @return array: strings of CSS keyed by media type
101 */
102 public function getStyles( ResourceLoaderContext $context ) {
103 // Stub, override expected
104 return '';
105 }
106
107 /**
108 * Get the messages needed for this module.
109 *
110 * To get a JSON blob with messages, use MessageBlobStore::get()
111 *
112 * @return array of message keys. Keys may occur more than once
113 */
114 public function getMessages() {
115 // Stub, override expected
116 return array();
117 }
118
119 /**
120 * Get the loader JS for this module, if set.
121 *
122 * @return Mixed: loader JS (string) or false if no custom loader set
123 */
124 public function getLoaderScript() {
125 // Stub, override expected
126 return '';
127 }
128
129 /**
130 * Get a list of modules this module depends on.
131 *
132 * Dependency information is taken into account when loading a module
133 * on the client side. When adding a module on the server side,
134 * dependency information is NOT taken into account and YOU are
135 * responsible for adding dependent modules as well. If you don't do
136 * this, the client side loader will send a second request back to the
137 * server to fetch the missing modules, which kind of defeats the
138 * purpose of the resource loader.
139 *
140 * To add dependencies dynamically on the client side, use a custom
141 * loader script, see getLoaderScript()
142 * @return Array of module names (strings)
143 */
144 public function getDependencies() {
145 // Stub, override expected
146 return array();
147 }
148
149 /* Abstract Methods */
150
151 /**
152 * Get this module's last modification timestamp for a given
153 * combination of language, skin and debug mode flag. This is typically
154 * the highest of each of the relevant components' modification
155 * timestamps. Whenever anything happens that changes the module's
156 * contents for these parameters, the mtime should increase.
157 *
158 * @param $context ResourceLoaderContext object
159 * @return int UNIX timestamp
160 */
161 public abstract function getModifiedTime( ResourceLoaderContext $context );
162 }
163
164 /**
165 * Module based on local JS/CSS files. This is the most common type of module.
166 */
167 class ResourceLoaderFileModule extends ResourceLoaderModule {
168 /* Protected Members */
169
170 protected $scripts = array();
171 protected $styles = array();
172 protected $messages = array();
173 protected $dependencies = array();
174 protected $debugScripts = array();
175 protected $languageScripts = array();
176 protected $skinScripts = array();
177 protected $skinStyles = array();
178 protected $loaders = array();
179 protected $parameters = array();
180
181 // In-object cache for file dependencies
182 protected $fileDeps = array();
183 // In-object cache for mtime
184 protected $modifiedTime = array();
185
186 /* Methods */
187
188 /**
189 * Construct a new module from an options array.
190 *
191 * @param $options array Options array. If empty, an empty module will be constructed
192 *
193 * $options format:
194 * array(
195 * // Required module options (mutually exclusive)
196 * 'scripts' => 'dir/script.js' | array( 'dir/script1.js', 'dir/script2.js' ... ),
197 *
198 * // Optional module options
199 * 'languageScripts' => array(
200 * '[lang name]' => 'dir/lang.js' | '[lang name]' => array( 'dir/lang1.js', 'dir/lang2.js' ... )
201 * ...
202 * ),
203 * 'skinScripts' => 'dir/skin.js' | array( 'dir/skin1.js', 'dir/skin2.js' ... ),
204 * 'debugScripts' => 'dir/debug.js' | array( 'dir/debug1.js', 'dir/debug2.js' ... ),
205 *
206 * // Non-raw module options
207 * 'dependencies' => 'module' | array( 'module1', 'module2' ... )
208 * 'loaderScripts' => 'dir/loader.js' | array( 'dir/loader1.js', 'dir/loader2.js' ... ),
209 * 'styles' => 'dir/file.css' | array( 'dir/file1.css', 'dir/file2.css' ... ), |
210 * array( 'dir/file1.css' => array( 'media' => 'print' ) ),
211 * 'skinStyles' => array(
212 * '[skin name]' => 'dir/skin.css' | array( 'dir/skin1.css', 'dir/skin2.css' ... ) |
213 * array( 'dir/file1.css' => array( 'media' => 'print' )
214 * ...
215 * ),
216 * 'messages' => array( 'message1', 'message2' ... ),
217 * )
218 */
219 public function __construct( $options = array() ) {
220 foreach ( $options as $option => $value ) {
221 switch ( $option ) {
222 case 'scripts':
223 $this->scripts = (array)$value;
224 break;
225 case 'styles':
226 $this->styles = (array)$value;
227 break;
228 case 'messages':
229 $this->messages = (array)$value;
230 break;
231 case 'dependencies':
232 $this->dependencies = (array)$value;
233 break;
234 case 'debugScripts':
235 $this->debugScripts = (array)$value;
236 break;
237 case 'languageScripts':
238 $this->languageScripts = (array)$value;
239 break;
240 case 'skinScripts':
241 $this->skinScripts = (array)$value;
242 break;
243 case 'skinStyles':
244 $this->skinStyles = (array)$value;
245 break;
246 case 'loaders':
247 $this->loaders = (array)$value;
248 break;
249 }
250 }
251 }
252
253 /**
254 * Add script files to this module. In order to be valid, a module
255 * must contain at least one script file.
256 *
257 * @param $scripts Mixed: path to script file (string) or array of paths
258 */
259 public function addScripts( $scripts ) {
260 $this->scripts = array_merge( $this->scripts, (array)$scripts );
261 }
262
263 /**
264 * Add style (CSS) files to this module.
265 *
266 * @param $styles Mixed: path to CSS file (string) or array of paths
267 */
268 public function addStyles( $styles ) {
269 $this->styles = array_merge( $this->styles, (array)$styles );
270 }
271
272 /**
273 * Add messages to this module.
274 *
275 * @param $messages Mixed: message key (string) or array of message keys
276 */
277 public function addMessages( $messages ) {
278 $this->messages = array_merge( $this->messages, (array)$messages );
279 }
280
281 /**
282 * Add dependencies. Dependency information is taken into account when
283 * loading a module on the client side. When adding a module on the
284 * server side, dependency information is NOT taken into account and
285 * YOU are responsible for adding dependent modules as well. If you
286 * don't do this, the client side loader will send a second request
287 * back to the server to fetch the missing modules, which kind of
288 * defeats the point of using the resource loader in the first place.
289 *
290 * To add dependencies dynamically on the client side, use a custom
291 * loader (see addLoaders())
292 *
293 * @param $dependencies Mixed: module name (string) or array of module names
294 */
295 public function addDependencies( $dependencies ) {
296 $this->dependencies = array_merge( $this->dependencies, (array)$dependencies );
297 }
298
299 /**
300 * Add debug scripts to the module. These scripts are only included
301 * in debug mode.
302 *
303 * @param $scripts Mixed: path to script file (string) or array of paths
304 */
305 public function addDebugScripts( $scripts ) {
306 $this->debugScripts = array_merge( $this->debugScripts, (array)$scripts );
307 }
308
309 /**
310 * Add language-specific scripts. These scripts are only included for
311 * a given language.
312 *
313 * @param $lang String: language code
314 * @param $scripts Mixed: path to script file (string) or array of paths
315 */
316 public function addLanguageScripts( $lang, $scripts ) {
317 $this->languageScripts = array_merge_recursive(
318 $this->languageScripts,
319 array( $lang => $scripts )
320 );
321 }
322
323 /**
324 * Add skin-specific scripts. These scripts are only included for
325 * a given skin.
326 *
327 * @param $skin String: skin name, or 'default'
328 * @param $scripts Mixed: path to script file (string) or array of paths
329 */
330 public function addSkinScripts( $skin, $scripts ) {
331 $this->skinScripts = array_merge_recursive(
332 $this->skinScripts,
333 array( $skin => $scripts )
334 );
335 }
336
337 /**
338 * Add skin-specific CSS. These CSS files are only included for a
339 * given skin. If there are no skin-specific CSS files for a skin,
340 * the files defined for 'default' will be used, if any.
341 *
342 * @param $skin String: skin name, or 'default'
343 * @param $scripts Mixed: path to CSS file (string) or array of paths
344 */
345 public function addSkinStyles( $skin, $scripts ) {
346 $this->skinStyles = array_merge_recursive(
347 $this->skinStyles,
348 array( $skin => $scripts )
349 );
350 }
351
352 /**
353 * Add loader scripts. These scripts are loaded on every page and are
354 * responsible for registering this module using
355 * mediaWiki.loader.register(). If there are no loader scripts defined,
356 * the resource loader will register the module itself.
357 *
358 * Loader scripts are used to determine a module's dependencies
359 * dynamically on the client side (e.g. based on browser type/version).
360 * Note that loader scripts are included on every page, so they should
361 * be lightweight and use mediaWiki.loader.register()'s callback
362 * feature to defer dependency calculation.
363 *
364 * @param $scripts Mixed: path to script file (string) or array of paths
365 */
366 public function addLoaders( $scripts ) {
367 $this->loaders = array_merge( $this->loaders, (array)$scripts );
368 }
369
370 public function getScript( ResourceLoaderContext $context ) {
371 $retval = $this->getPrimaryScript() . "\n" .
372 $this->getLanguageScript( $context->getLanguage() ) . "\n" .
373 $this->getSkinScript( $context->getSkin() );
374
375 if ( $context->getDebug() ) {
376 $retval .= $this->getDebugScript();
377 }
378
379 return $retval;
380 }
381
382 public function getStyles( ResourceLoaderContext $context ) {
383 $styles = array();
384 foreach ( $this->getPrimaryStyles() as $media => $style ) {
385 if ( !isset( $styles[$media] ) ) {
386 $styles[$media] = '';
387 }
388 $styles[$media] .= $style;
389 }
390 foreach ( $this->getSkinStyles( $context->getSkin() ) as $media => $style ) {
391 if ( !isset( $styles[$media] ) ) {
392 $styles[$media] = '';
393 }
394 $styles[$media] .= $style;
395 }
396
397 // Collect referenced files
398 $files = array();
399 foreach ( $styles as $media => $style ) {
400 // Extract and store the list of referenced files
401 $files = array_merge( $files, CSSMin::getLocalFileReferences( $style ) );
402 }
403
404 // Only store if modified
405 if ( $files !== $this->getFileDependencies( $context->getSkin() ) ) {
406 $encFiles = FormatJson::encode( $files );
407 $dbw = wfGetDb( DB_MASTER );
408 $dbw->replace( 'module_deps',
409 array( array( 'md_module', 'md_skin' ) ), array(
410 'md_module' => $this->getName(),
411 'md_skin' => $context->getSkin(),
412 'md_deps' => $encFiles,
413 )
414 );
415
416 // Save into memcached
417 global $wgMemc;
418
419 $key = wfMemcKey( 'resourceloader', 'module_deps', $this->getName(), $context->getSkin() );
420 $wgMemc->set( $key, $encFiles );
421 }
422
423 return $styles;
424 }
425
426 public function getMessages() {
427 return $this->messages;
428 }
429
430 public function getDependencies() {
431 return $this->dependencies;
432 }
433
434 public function getLoaderScript() {
435 if ( count( $this->loaders ) == 0 ) {
436 return false;
437 }
438
439 return self::concatScripts( $this->loaders );
440 }
441
442 /**
443 * Get the last modified timestamp of this module, which is calculated
444 * as the highest last modified timestamp of its constituent files and
445 * the files it depends on (see getFileDependencies()). Only files
446 * relevant to the given language and skin are taken into account, and
447 * files only relevant in debug mode are not taken into account when
448 * debug mode is off.
449 *
450 * @param $context ResourceLoaderContext object
451 * @return Integer: UNIX timestamp
452 */
453 public function getModifiedTime( ResourceLoaderContext $context ) {
454 if ( isset( $this->modifiedTime[$context->getHash()] ) ) {
455 return $this->modifiedTime[$context->getHash()];
456 }
457
458 // Sort of nasty way we can get a flat list of files depended on by all styles
459 $styles = array();
460 foreach ( self::organizeFilesByOption( $this->styles, 'media', 'all' ) as $media => $styleFiles ) {
461 $styles = array_merge( $styles, $styleFiles );
462 }
463 $skinFiles = (array) self::getSkinFiles(
464 $context->getSkin(), self::organizeFilesByOption( $this->skinStyles, 'media', 'all' )
465 );
466 foreach ( $skinFiles as $media => $styleFiles ) {
467 $styles = array_merge( $styles, $styleFiles );
468 }
469
470 // Final merge, this should result in a master list of dependent files
471 $files = array_merge(
472 $this->scripts,
473 $styles,
474 $context->getDebug() ? $this->debugScripts : array(),
475 isset( $this->languageScripts[$context->getLanguage()] ) ?
476 (array) $this->languageScripts[$context->getLanguage()] : array(),
477 (array) self::getSkinFiles( $context->getSkin(), $this->skinScripts ),
478 $this->loaders,
479 $this->getFileDependencies( $context->getSkin() )
480 );
481
482 $filesMtime = max( array_map( 'filemtime', array_map( array( __CLASS__, 'remapFilename' ), $files ) ) );
483
484 // Get the mtime of the message blob
485 // TODO: This timestamp is queried a lot and queried separately for each module. Maybe it should be put in memcached?
486 $dbr = wfGetDb( DB_SLAVE );
487 $msgBlobMtime = $dbr->selectField( 'msg_resource', 'mr_timestamp', array(
488 'mr_resource' => $this->getName(),
489 'mr_lang' => $context->getLanguage()
490 ), __METHOD__
491 );
492 $msgBlobMtime = $msgBlobMtime ? wfTimestamp( TS_UNIX, $msgBlobMtime ) : 0;
493
494 $this->modifiedTime[$context->getHash()] = max( $filesMtime, $msgBlobMtime );
495 return $this->modifiedTime[$context->getHash()];
496 }
497
498 /* Protected Members */
499
500 /**
501 * Get the primary JS for this module. This is pulled from the
502 * script files added through addScripts()
503 *
504 * @return String: JS
505 */
506 protected function getPrimaryScript() {
507 return self::concatScripts( $this->scripts );
508 }
509
510 /**
511 * Get the primary CSS for this module. This is pulled from the CSS
512 * files added through addStyles()
513 *
514 * @return String: JS
515 */
516 protected function getPrimaryStyles() {
517 return self::concatStyles( $this->styles );
518 }
519
520 /**
521 * Get the debug JS for this module. This is pulled from the script
522 * files added through addDebugScripts()
523 *
524 * @return String: JS
525 */
526 protected function getDebugScript() {
527 return self::concatScripts( $this->debugScripts );
528 }
529
530 /**
531 * Get the language-specific JS for a given language. This is pulled
532 * from the language-specific script files added through addLanguageScripts()
533 *
534 * @return String: JS
535 */
536 protected function getLanguageScript( $lang ) {
537 if ( !isset( $this->languageScripts[$lang] ) ) {
538 return '';
539 }
540 return self::concatScripts( $this->languageScripts[$lang] );
541 }
542
543 /**
544 * Get the skin-specific JS for a given skin. This is pulled from the
545 * skin-specific JS files added through addSkinScripts()
546 *
547 * @return String: JS
548 */
549 protected function getSkinScript( $skin ) {
550 return self::concatScripts( self::getSkinFiles( $skin, $this->skinScripts ) );
551 }
552
553 /**
554 * Get the skin-specific CSS for a given skin. This is pulled from the
555 * skin-specific CSS files added through addSkinStyles()
556 *
557 * @return Array: list of CSS strings keyed by media type
558 */
559 protected function getSkinStyles( $skin ) {
560 return self::concatStyles( self::getSkinFiles( $skin, $this->skinStyles ) );
561 }
562
563 /**
564 * Helper function to get skin-specific data from an array.
565 *
566 * @param $skin String: skin name
567 * @param $map Array: map of skin names to arrays
568 * @return $map[$skin] if set and non-empty, or $map['default'] if set, or an empty array
569 */
570 protected static function getSkinFiles( $skin, $map ) {
571 $retval = array();
572
573 if ( isset( $map[$skin] ) && $map[$skin] ) {
574 $retval = $map[$skin];
575 } else if ( isset( $map['default'] ) ) {
576 $retval = $map['default'];
577 }
578
579 return $retval;
580 }
581
582 /**
583 * Get the files this module depends on indirectly for a given skin.
584 * Currently these are only image files referenced by the module's CSS.
585 *
586 * @param $skin String: skin name
587 * @return array of files
588 */
589 protected function getFileDependencies( $skin ) {
590 // Try in-object cache first
591 if ( isset( $this->fileDeps[$skin] ) ) {
592 return $this->fileDeps[$skin];
593 }
594
595 // Now try memcached
596 global $wgMemc;
597
598 $key = wfMemcKey( 'resourceloader', 'module_deps', $this->getName(), $skin );
599 $deps = $wgMemc->get( $key );
600
601 if ( !$deps ) {
602 $dbr = wfGetDb( DB_SLAVE );
603 $deps = $dbr->selectField( 'module_deps', 'md_deps', array(
604 'md_module' => $this->getName(),
605 'md_skin' => $skin,
606 ), __METHOD__
607 );
608 if ( !$deps ) {
609 $deps = '[]'; // Empty array so we can do negative caching
610 }
611 $wgMemc->set( $key, $deps );
612 }
613
614 $this->fileDeps = FormatJson::decode( $deps, true );
615
616 return $this->fileDeps;
617 }
618
619 /**
620 * Get the contents of a set of files and concatenate them, with
621 * newlines in between. Each file is used only once.
622 *
623 * @param $files Array of file names
624 * @return String: concatenated contents of $files
625 */
626 protected static function concatScripts( $files ) {
627 return implode( "\n", array_map( 'file_get_contents', array_map( array( __CLASS__, 'remapFilename' ), array_unique( (array) $files ) ) ) );
628 }
629
630 protected static function organizeFilesByOption( $files, $option, $default ) {
631 $organizedFiles = array();
632 foreach ( (array) $files as $key => $value ) {
633 if ( is_int( $key ) ) {
634 // File name as the value
635 if ( !isset( $organizedFiles[$default] ) ) {
636 $organizedFiles[$default] = array();
637 }
638 $organizedFiles[$default][] = $value;
639 } else if ( is_array( $value ) ) {
640 // File name as the key, options array as the value
641 $media = isset( $value[$option] ) ? $value[$option] : $default;
642 if ( !isset( $organizedFiles[$media] ) ) {
643 $organizedFiles[$media] = array();
644 }
645 $organizedFiles[$media][] = $key;
646 }
647 }
648 return $organizedFiles;
649 }
650
651 /**
652 * Get the contents of a set of CSS files, remap then and concatenate
653 * them, with newlines in between. Each file is used only once.
654 *
655 * @param $files Array of file names
656 * @return Array: list of concatenated and remapped contents of $files keyed by media type
657 */
658 protected static function concatStyles( $styles ) {
659 $styles = self::organizeFilesByOption( $styles, 'media', 'all' );
660 foreach ( $styles as $media => $files ) {
661 $styles[$media] =
662 implode( "\n", array_map( array( __CLASS__, 'remapStyle' ), array_unique( (array) $files ) ) );
663 }
664 return $styles;
665 }
666
667 /**
668 * Remap a relative to $IP. Used as a callback for array_map()
669 *
670 * @param $file String: file name
671 * @return string $IP/$file
672 */
673 protected static function remapFilename( $file ) {
674 global $IP;
675
676 return "$IP/$file";
677 }
678
679 /**
680 * Get the contents of a CSS file and run it through CSSMin::remap().
681 * This wrapper is needed so we can use array_map() in concatStyles()
682 *
683 * @param $file String: file name
684 * @return string Remapped CSS
685 */
686 protected static function remapStyle( $file ) {
687 global $wgUseDataURLs;
688 return CSSMin::remap( file_get_contents( self::remapFilename( $file ) ), dirname( $file ), $wgUseDataURLs );
689 }
690 }
691
692 /**
693 * Abstraction for resource loader modules which pull from wiki pages
694 */
695 abstract class ResourceLoaderWikiModule extends ResourceLoaderModule {
696
697 /* Protected Members */
698
699 // In-object cache for modified time
700 protected $modifiedTime = array();
701
702 /* Abstract Protected Methods */
703
704 abstract protected function getPages( ResourceLoaderContext $context );
705
706 /* Protected Methods */
707
708 protected function getContent( $page, $ns ) {
709 if ( $ns === NS_MEDIAWIKI ) {
710 return wfMsgExt( $page, 'content' );
711 }
712 if ( $title = Title::newFromText( $page, $ns ) ) {
713 if ( $title->isValidCssJsSubpage() && $revision = Revision::newFromTitle( $title ) ) {
714 return $revision->getRawText();
715 }
716 }
717 return null;
718 }
719
720 /* Methods */
721
722 public function getScript( ResourceLoaderContext $context ) {
723 global $wgCanonicalNamespaceNames;
724
725 $scripts = '';
726 foreach ( $this->getPages( $context ) as $page => $options ) {
727 if ( $options['type'] === 'script' ) {
728 if ( $script = $this->getContent( $page, $options['ns'] ) ) {
729 $ns = $wgCanonicalNamespaceNames[$options['ns']];
730 $scripts .= "/*$ns:$page */\n$script\n";
731 }
732 }
733 }
734 return $scripts;
735 }
736
737 public function getStyles( ResourceLoaderContext $context ) {
738 global $wgCanonicalNamespaceNames;
739
740 $styles = array();
741 foreach ( $this->getPages( $context ) as $page => $options ) {
742 if ( $options['type'] === 'style' ) {
743 $media = isset( $options['media'] ) ? $options['media'] : 'all';
744 if ( $style = $this->getContent( $page, $options['ns'] ) ) {
745 if ( !isset( $styles[$media] ) ) {
746 $styles[$media] = '';
747 }
748 $ns = $wgCanonicalNamespaceNames[$options['ns']];
749 $styles[$media] .= "/* $ns:$page */\n$style\n";
750 }
751 }
752 }
753 return $styles;
754 }
755
756 public function getModifiedTime( ResourceLoaderContext $context ) {
757 $hash = $context->getHash();
758 if ( isset( $this->modifiedTime[$hash] ) ) {
759 return $this->modifiedTime[$hash];
760 }
761 $titles = array();
762 foreach ( $this->getPages( $context ) as $page => $options ) {
763 $titles[] = Title::makeTitle( $options['ns'], $page );
764 }
765 // Do batch existence check
766 // TODO: This would work better if page_touched were loaded by this as well
767 $lb = new LinkBatch( $titles );
768 $lb->execute();
769 $modifiedTime = 1; // wfTimestamp() interprets 0 as "now"
770 foreach ( $titles as $title ) {
771 if ( $title->exists() ) {
772 $modifiedTime = max( $modifiedTime, wfTimestamp( TS_UNIX, $title->getTouched() ) );
773 }
774 }
775 return $this->modifiedTime[$hash] = $modifiedTime;
776 }
777 }
778
779 /**
780 * Module for site customizations
781 */
782 class ResourceLoaderSiteModule extends ResourceLoaderWikiModule {
783
784 /* Protected Methods */
785
786 protected function getPages( ResourceLoaderContext $context ) {
787 global $wgHandheldStyle;
788
789 $pages = array(
790 'Common.js' => array( 'ns' => NS_MEDIAWIKI, 'type' => 'script' ),
791 'Common.css' => array( 'ns' => NS_MEDIAWIKI, 'type' => 'style' ),
792 ucfirst( $context->getSkin() ) . '.js' => array( 'ns' => NS_MEDIAWIKI, 'type' => 'script' ),
793 ucfirst( $context->getSkin() ) . '.css' => array( 'ns' => NS_MEDIAWIKI, 'type' => 'style' ),
794 'Print.css' => array( 'ns' => NS_MEDIAWIKI, 'type' => 'style', 'media' => 'print' ),
795 );
796 if ( $wgHandheldStyle ) {
797 $pages['Handheld.css'] = array( 'ns' => NS_MEDIAWIKI, 'type' => 'style', 'media' => 'handheld' );
798 }
799 return $pages;
800 }
801 }
802
803 /**
804 * Module for user customizations
805 */
806 class ResourceLoaderUserModule extends ResourceLoaderWikiModule {
807
808 /* Protected Methods */
809
810 protected function getPages( ResourceLoaderContext $context ) {
811 global $wgAllowUserCss;
812
813 if ( $context->getUser() && $wgAllowUserCss ) {
814 $username = $context->getUser();
815 return array(
816 "$username/common.js" => array( 'ns' => NS_USER, 'type' => 'script' ),
817 "$username/" . $context->getSkin() . '.js' => array( 'ns' => NS_USER, 'type' => 'script' ),
818 "$username/common.css" => array( 'ns' => NS_USER, 'type' => 'style' ),
819 "$username/" . $context->getSkin() . '.css' => array( 'ns' => NS_USER, 'type' => 'style' ),
820 );
821 }
822 return array();
823 }
824 }
825
826 /**
827 * Module for user preference customizations
828 */
829 class ResourceLoaderUserPreferencesModule extends ResourceLoaderModule {
830
831 /* Protected Members */
832
833 protected $modifiedTime = array();
834
835 /* Methods */
836
837 public function getModifiedTime( ResourceLoaderContext $context ) {
838 $hash = $context->getHash();
839 if ( isset( $this->modifiedTime[$hash] ) ) {
840 return $this->modifiedTime[$hash];
841 }
842 if ( $context->getUser() ) {
843 $user = User::newFromName( $context->getUser() );
844 return $this->modifiedTime[$hash] = $user->getTouched();
845 } else {
846 return 0;
847 }
848 }
849
850 public function getStyles( ResourceLoaderContext $context ) {
851 global $wgAllowUserCssPrefs;
852 if ( $wgAllowUserCssPrefs ) {
853 $user = User::newFromName( $context->getUser() );
854 $rules = array();
855 if ( ( $underline = $user->getOption( 'underline' ) ) < 2 ) {
856 $rules[] = "a { text-decoration: " . ( $underline ? 'underline' : 'none' ) . "; }";
857 }
858 if ( $user->getOption( 'highlightbroken' ) ) {
859 $rules[] = "a.new, #quickbar a.new { color: #CC2200; }\n";
860 } else {
861 $rules[] = "a.new, #quickbar a.new, a.stub, #quickbar a.stub { color: inherit; }";
862 $rules[] = "a.new:after, #quickbar a.new:after { content: '?'; color: #CC2200; }";
863 $rules[] = "a.stub:after, #quickbar a.stub:after { content: '!'; color: #772233; }";
864 }
865 if ( $user->getOption( 'justify' ) ) {
866 $rules[] = "#article, #bodyContent, #mw_content { text-align: justify; }\n";
867 }
868 if ( !$user->getOption( 'showtoc' ) ) {
869 $rules[] = "#toc { display: none; }\n";
870 }
871 if ( !$user->getOption( 'editsection' ) ) {
872 $rules[] = ".editsection { display: none; }\n";
873 }
874 if ( ( $fontstyle = $user->getOption( 'editfont' ) ) !== 'default' ) {
875 $rules[] = "textarea { font-family: $fontstyle; }\n";
876 }
877 return array( 'all' => implode( "\n", $rules ) );
878 }
879 return array();
880 }
881
882 public function getFlip( $context ) {
883 global $wgContLang;
884
885 return $wgContLang->getDir() !== $context->getDirection();
886 }
887 }
888
889 class ResourceLoaderStartUpModule extends ResourceLoaderModule {
890 /* Protected Members */
891
892 protected $modifiedTime = array();
893
894 /* Protected Methods */
895
896 protected function getConfig( $context ) {
897 global $wgLoadScript, $wgScript, $wgStylePath, $wgScriptExtension, $wgArticlePath, $wgScriptPath, $wgServer,
898 $wgContLang, $wgBreakFrames, $wgVariantArticlePath, $wgActionPaths, $wgUseAjax, $wgAjaxWatch, $wgVersion,
899 $wgEnableAPI, $wgEnableWriteAPI, $wgDBname, $wgEnableMWSuggest, $wgSitename, $wgFileExtensions;
900
901 // Pre-process information
902 $separatorTransTable = $wgContLang->separatorTransformTable();
903 $separatorTransTable = $separatorTransTable ? $separatorTransTable : array();
904 $compactSeparatorTransTable = array(
905 implode( "\t", array_keys( $separatorTransTable ) ),
906 implode( "\t", $separatorTransTable ),
907 );
908 $digitTransTable = $wgContLang->digitTransformTable();
909 $digitTransTable = $digitTransTable ? $digitTransTable : array();
910 $compactDigitTransTable = array(
911 implode( "\t", array_keys( $digitTransTable ) ),
912 implode( "\t", $digitTransTable ),
913 );
914 $mainPage = Title::newMainPage();
915
916 // Build list of variables
917 $vars = array(
918 'wgLoadScript' => $wgLoadScript,
919 'debug' => $context->getDebug(),
920 'skin' => $context->getSkin(),
921 'stylepath' => $wgStylePath,
922 'wgUrlProtocols' => wfUrlProtocols(),
923 'wgArticlePath' => $wgArticlePath,
924 'wgScriptPath' => $wgScriptPath,
925 'wgScriptExtension' => $wgScriptExtension,
926 'wgScript' => $wgScript,
927 'wgVariantArticlePath' => $wgVariantArticlePath,
928 'wgActionPaths' => $wgActionPaths,
929 'wgServer' => $wgServer,
930 'wgUserLanguage' => $context->getLanguage(),
931 'wgContentLanguage' => $wgContLang->getCode(),
932 'wgBreakFrames' => $wgBreakFrames,
933 'wgVersion' => $wgVersion,
934 'wgEnableAPI' => $wgEnableAPI,
935 'wgEnableWriteAPI' => $wgEnableWriteAPI,
936 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
937 'wgDigitTransformTable' => $compactDigitTransTable,
938 'wgMainPageTitle' => $mainPage ? $mainPage->getPrefixedText() : null,
939 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(),
940 'wgNamespaceIds' => $wgContLang->getNamespaceIds(),
941 'wgSiteName' => $wgSitename,
942 'wgFileExtensions' => $wgFileExtensions,
943 );
944 if ( $wgContLang->hasVariants() ) {
945 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
946 }
947 if ( $wgUseAjax && $wgEnableMWSuggest ) {
948 $vars['wgMWSuggestTemplate'] = SearchEngine::getMWSuggestTemplate();
949 $vars['wgDBname'] = $wgDBname;
950 }
951
952 return $vars;
953 }
954
955 /* Methods */
956
957 public function getScript( ResourceLoaderContext $context ) {
958 global $IP, $wgStylePath, $wgLoadScript;
959
960 $scripts = file_get_contents( "$IP/resources/startup.js" );
961
962 if ( $context->getOnly() === 'scripts' ) {
963 // Get all module registrations
964 $registration = ResourceLoader::getModuleRegistrations( $context );
965 // Build configuration
966 $config = FormatJson::encode( $this->getConfig( $context ) );
967 // Add a well-known start-up function
968 $scripts .= "window.startUp = function() { $registration mediaWiki.config.set( $config ); };";
969 // Build load query for jquery and mediawiki modules
970 $query = array(
971 'modules' => implode( '|', array( 'jquery', 'mediawiki' ) ),
972 'only' => 'scripts',
973 'lang' => $context->getLanguage(),
974 'skin' => $context->getSkin(),
975 'debug' => $context->getDebug() ? 'true' : 'false',
976 'version' => wfTimestamp( TS_ISO_8601, round( max(
977 ResourceLoader::getModule( 'jquery' )->getModifiedTime( $context ),
978 ResourceLoader::getModule( 'mediawiki' )->getModifiedTime( $context )
979 ), -2 ) )
980 );
981 // Uniform query order
982 ksort( $query );
983 // Build HTML code for loading jquery and mediawiki modules
984 $loadScript = Html::linkedScript( $wgLoadScript . '?' . wfArrayToCGI( $query ) );
985 // Add code to add jquery and mediawiki loading code; only if the current client is compatible
986 $scripts .= "if ( isCompatible() ) { document.write( '$loadScript' ); }";
987 // Delete the compatible function - it's not needed anymore
988 $scripts .= "delete window['isCompatible'];";
989 }
990
991 return $scripts;
992 }
993
994 public function getModifiedTime( ResourceLoaderContext $context ) {
995 global $IP;
996
997 $hash = $context->getHash();
998 if ( isset( $this->modifiedTime[$hash] ) ) {
999 return $this->modifiedTime[$hash];
1000 }
1001 $this->modifiedTime[$hash] = filemtime( "$IP/resources/startup.js" );
1002 // ATTENTION!: Because of the line above, this is not going to cause infinite recursion - think carefully
1003 // before making changes to this code!
1004 $this->modifiedTime[$hash] = ResourceLoader::getHighestModifiedTime( $context );
1005 return $this->modifiedTime[$hash];
1006 }
1007
1008 public function getClientMaxage() {
1009 return 300; // 5 minutes
1010 }
1011
1012 public function getServerMaxage() {
1013 return 300; // 5 minutes
1014 }
1015
1016 public function getFlip( $context ) {
1017 global $wgContLang;
1018
1019 return $wgContLang->getDir() !== $context->getDirection();
1020 }
1021 }