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