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