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