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