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