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