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