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