* Changed the expiry time strategy, now treating any request to ResourceLoader::respo...
[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
458 $filesMtime = max( array_map( 'filemtime', array_map( array( __CLASS__, 'remapFilename' ), $files ) ) );
459
460 // Get the mtime of the message blob
461 // TODO: This timestamp is queried a lot and queried separately for each module. Maybe it should be put in memcached?
462 $dbr = wfGetDb( DB_SLAVE );
463 $msgBlobMtime = $dbr->selectField( 'msg_resource', 'mr_timestamp', array(
464 'mr_resource' => $this->getName(),
465 'mr_lang' => $context->getLanguage()
466 ), __METHOD__
467 );
468 $msgBlobMtime = $msgBlobMtime ? wfTimestamp( TS_UNIX, $msgBlobMtime ) : 0;
469
470 $this->modifiedTime[$context->getHash()] = max( $filesMtime, $msgBlobMtime );
471 return $this->modifiedTime[$context->getHash()];
472 }
473
474 /* Protected Members */
475
476 /**
477 * Get the primary JS for this module. This is pulled from the
478 * script files added through addScripts()
479 *
480 * @return String: JS
481 */
482 protected function getPrimaryScript() {
483 return self::concatScripts( $this->scripts );
484 }
485
486 /**
487 * Get the primary CSS for this module. This is pulled from the CSS
488 * files added through addStyles()
489 *
490 * @return String: JS
491 */
492 protected function getPrimaryStyles() {
493 return self::concatStyles( $this->styles );
494 }
495
496 /**
497 * Get the debug JS for this module. This is pulled from the script
498 * files added through addDebugScripts()
499 *
500 * @return String: JS
501 */
502 protected function getDebugScript() {
503 return self::concatScripts( $this->debugScripts );
504 }
505
506 /**
507 * Get the language-specific JS for a given language. This is pulled
508 * from the language-specific script files added through addLanguageScripts()
509 *
510 * @return String: JS
511 */
512 protected function getLanguageScript( $lang ) {
513 if ( !isset( $this->languageScripts[$lang] ) ) {
514 return '';
515 }
516 return self::concatScripts( $this->languageScripts[$lang] );
517 }
518
519 /**
520 * Get the skin-specific JS for a given skin. This is pulled from the
521 * skin-specific JS files added through addSkinScripts()
522 *
523 * @return String: JS
524 */
525 protected function getSkinScript( $skin ) {
526 return self::concatScripts( self::getSkinFiles( $skin, $this->skinScripts ) );
527 }
528
529 /**
530 * Get the skin-specific CSS for a given skin. This is pulled from the
531 * skin-specific CSS files added through addSkinStyles()
532 *
533 * @return Array: list of CSS strings keyed by media type
534 */
535 protected function getSkinStyles( $skin ) {
536 return self::concatStyles( self::getSkinFiles( $skin, $this->skinStyles ) );
537 }
538
539 /**
540 * Helper function to get skin-specific data from an array.
541 *
542 * @param $skin String: skin name
543 * @param $map Array: map of skin names to arrays
544 * @return $map[$skin] if set and non-empty, or $map['default'] if set, or an empty array
545 */
546 protected static function getSkinFiles( $skin, $map ) {
547 $retval = array();
548
549 if ( isset( $map[$skin] ) && $map[$skin] ) {
550 $retval = $map[$skin];
551 } else if ( isset( $map['default'] ) ) {
552 $retval = $map['default'];
553 }
554
555 return $retval;
556 }
557
558 /**
559 * Get the files this module depends on indirectly for a given skin.
560 * Currently these are only image files referenced by the module's CSS.
561 *
562 * @param $skin String: skin name
563 * @return array of files
564 */
565 protected function getFileDependencies( $skin ) {
566 // Try in-object cache first
567 if ( isset( $this->fileDeps[$skin] ) ) {
568 return $this->fileDeps[$skin];
569 }
570
571 // Now try memcached
572 global $wgMemc;
573
574 $key = wfMemcKey( 'resourceloader', 'module_deps', $this->getName(), $skin );
575 $deps = $wgMemc->get( $key );
576
577 if ( !$deps ) {
578 $dbr = wfGetDb( DB_SLAVE );
579 $deps = $dbr->selectField( 'module_deps', 'md_deps', array(
580 'md_module' => $this->getName(),
581 'md_skin' => $skin,
582 ), __METHOD__
583 );
584 if ( !$deps ) {
585 $deps = '[]'; // Empty array so we can do negative caching
586 }
587 $wgMemc->set( $key, $deps );
588 }
589
590 $this->fileDeps = FormatJson::decode( $deps, true );
591
592 return $this->fileDeps;
593 }
594
595 /**
596 * Get the contents of a set of files and concatenate them, with
597 * newlines in between. Each file is used only once.
598 *
599 * @param $files Array of file names
600 * @return String: concatenated contents of $files
601 */
602 protected static function concatScripts( $files ) {
603 return implode( "\n", array_map( 'file_get_contents', array_map( array( __CLASS__, 'remapFilename' ), array_unique( (array) $files ) ) ) );
604 }
605
606 protected static function organizeFilesByOption( $files, $option, $default ) {
607 $organizedFiles = array();
608 foreach ( (array) $files as $key => $value ) {
609 if ( is_int( $key ) ) {
610 // File name as the value
611 if ( !isset( $organizedFiles[$default] ) ) {
612 $organizedFiles[$default] = array();
613 }
614 $organizedFiles[$default][] = $value;
615 } else if ( is_array( $value ) ) {
616 // File name as the key, options array as the value
617 $media = isset( $value[$option] ) ? $value[$option] : $default;
618 if ( !isset( $organizedFiles[$media] ) ) {
619 $organizedFiles[$media] = array();
620 }
621 $organizedFiles[$media][] = $key;
622 }
623 }
624 return $organizedFiles;
625 }
626
627 /**
628 * Get the contents of a set of CSS files, remap then and concatenate
629 * them, with newlines in between. Each file is used only once.
630 *
631 * @param $files Array of file names
632 * @return Array: list of concatenated and remapped contents of $files keyed by media type
633 */
634 protected static function concatStyles( $styles ) {
635 $styles = self::organizeFilesByOption( $styles, 'media', 'all' );
636 foreach ( $styles as $media => $files ) {
637 $styles[$media] =
638 implode( "\n", array_map( array( __CLASS__, 'remapStyle' ), array_unique( (array) $files ) ) );
639 }
640 return $styles;
641 }
642
643 /**
644 * Remap a relative to $IP. Used as a callback for array_map()
645 *
646 * @param $file String: file name
647 * @return string $IP/$file
648 */
649 protected static function remapFilename( $file ) {
650 global $IP;
651
652 return "$IP/$file";
653 }
654
655 /**
656 * Get the contents of a CSS file and run it through CSSMin::remap().
657 * This wrapper is needed so we can use array_map() in concatStyles()
658 *
659 * @param $file String: file name
660 * @return string Remapped CSS
661 */
662 protected static function remapStyle( $file ) {
663 global $wgUseDataURLs, $wgScriptPath;
664 return CSSMin::remap(
665 file_get_contents( self::remapFilename( $file ) ),
666 dirname( $file ),
667 $wgScriptPath . '/' . dirname( $file ),
668 $wgUseDataURLs
669 );
670 }
671 }
672
673 /**
674 * Abstraction for resource loader modules which pull from wiki pages
675 */
676 abstract class ResourceLoaderWikiModule extends ResourceLoaderModule {
677
678 /* Protected Members */
679
680 // In-object cache for modified time
681 protected $modifiedTime = array();
682
683 /* Abstract Protected Methods */
684
685 abstract protected function getPages( ResourceLoaderContext $context );
686
687 /* Protected Methods */
688
689 protected function getContent( $page, $ns ) {
690 if ( $ns === NS_MEDIAWIKI ) {
691 return wfMsgExt( $page, 'content' );
692 }
693 if ( $title = Title::newFromText( $page, $ns ) ) {
694 if ( $title->isValidCssJsSubpage() && $revision = Revision::newFromTitle( $title ) ) {
695 return $revision->getRawText();
696 }
697 }
698 return null;
699 }
700
701 /* Methods */
702
703 public function getScript( ResourceLoaderContext $context ) {
704 global $wgCanonicalNamespaceNames;
705
706 $scripts = '';
707 foreach ( $this->getPages( $context ) as $page => $options ) {
708 if ( $options['type'] === 'script' ) {
709 if ( $script = $this->getContent( $page, $options['ns'] ) ) {
710 $ns = $wgCanonicalNamespaceNames[$options['ns']];
711 $scripts .= "/*$ns:$page */\n$script\n";
712 }
713 }
714 }
715 return $scripts;
716 }
717
718 public function getStyles( ResourceLoaderContext $context ) {
719 global $wgCanonicalNamespaceNames;
720
721 $styles = array();
722 foreach ( $this->getPages( $context ) as $page => $options ) {
723 if ( $options['type'] === 'style' ) {
724 $media = isset( $options['media'] ) ? $options['media'] : 'all';
725 if ( $style = $this->getContent( $page, $options['ns'] ) ) {
726 if ( !isset( $styles[$media] ) ) {
727 $styles[$media] = '';
728 }
729 $ns = $wgCanonicalNamespaceNames[$options['ns']];
730 $styles[$media] .= "/* $ns:$page */\n$style\n";
731 }
732 }
733 }
734 return $styles;
735 }
736
737 public function getModifiedTime( ResourceLoaderContext $context ) {
738 $hash = $context->getHash();
739 if ( isset( $this->modifiedTime[$hash] ) ) {
740 return $this->modifiedTime[$hash];
741 }
742 $titles = array();
743 foreach ( $this->getPages( $context ) as $page => $options ) {
744 $titles[] = Title::makeTitle( $options['ns'], $page );
745 }
746 // Do batch existence check
747 // TODO: This would work better if page_touched were loaded by this as well
748 $lb = new LinkBatch( $titles );
749 $lb->execute();
750 $modifiedTime = 1; // wfTimestamp() interprets 0 as "now"
751 foreach ( $titles as $title ) {
752 if ( $title->exists() ) {
753 $modifiedTime = max( $modifiedTime, wfTimestamp( TS_UNIX, $title->getTouched() ) );
754 }
755 }
756 return $this->modifiedTime[$hash] = $modifiedTime;
757 }
758 }
759
760 /**
761 * Module for site customizations
762 */
763 class ResourceLoaderSiteModule extends ResourceLoaderWikiModule {
764
765 /* Protected Methods */
766
767 protected function getPages( ResourceLoaderContext $context ) {
768 global $wgHandheldStyle;
769
770 $pages = array(
771 'Common.js' => array( 'ns' => NS_MEDIAWIKI, 'type' => 'script' ),
772 'Common.css' => array( 'ns' => NS_MEDIAWIKI, 'type' => 'style' ),
773 ucfirst( $context->getSkin() ) . '.js' => array( 'ns' => NS_MEDIAWIKI, 'type' => 'script' ),
774 ucfirst( $context->getSkin() ) . '.css' => array( 'ns' => NS_MEDIAWIKI, 'type' => 'style' ),
775 'Print.css' => array( 'ns' => NS_MEDIAWIKI, 'type' => 'style', 'media' => 'print' ),
776 );
777 if ( $wgHandheldStyle ) {
778 $pages['Handheld.css'] = array( 'ns' => NS_MEDIAWIKI, 'type' => 'style', 'media' => 'handheld' );
779 }
780 return $pages;
781 }
782 }
783
784 /**
785 * Module for user customizations
786 */
787 class ResourceLoaderUserModule extends ResourceLoaderWikiModule {
788
789 /* Protected Methods */
790
791 protected function getPages( ResourceLoaderContext $context ) {
792 global $wgAllowUserCss;
793
794 if ( $context->getUser() && $wgAllowUserCss ) {
795 $username = $context->getUser();
796 return array(
797 "$username/common.js" => array( 'ns' => NS_USER, 'type' => 'script' ),
798 "$username/" . $context->getSkin() . '.js' => array( 'ns' => NS_USER, 'type' => 'script' ),
799 "$username/common.css" => array( 'ns' => NS_USER, 'type' => 'style' ),
800 "$username/" . $context->getSkin() . '.css' => array( 'ns' => NS_USER, 'type' => 'style' ),
801 );
802 }
803 return array();
804 }
805 }
806
807 /**
808 * Module for user preference customizations
809 */
810 class ResourceLoaderUserPreferencesModule extends ResourceLoaderModule {
811
812 /* Protected Members */
813
814 protected $modifiedTime = array();
815
816 /* Methods */
817
818 public function getModifiedTime( ResourceLoaderContext $context ) {
819 $hash = $context->getHash();
820 if ( isset( $this->modifiedTime[$hash] ) ) {
821 return $this->modifiedTime[$hash];
822 }
823 if ( $context->getUser() && $user = User::newFromName( $context->getUser() ) ) {
824 return $this->modifiedTime[$hash] = $user->getTouched();
825 } else {
826 return 0;
827 }
828 }
829
830 public function getStyles( ResourceLoaderContext $context ) {
831 global $wgAllowUserCssPrefs;
832 if ( $wgAllowUserCssPrefs ) {
833 $user = User::newFromName( $context->getUser() );
834 if ( $user === false ) {
835 $user = User::newFromId( 0 );
836 }
837
838 $rules = array();
839 if ( ( $underline = $user->getOption( 'underline' ) ) < 2 ) {
840 $rules[] = "a { text-decoration: " . ( $underline ? 'underline' : 'none' ) . "; }";
841 }
842 if ( $user->getOption( 'highlightbroken' ) ) {
843 $rules[] = "a.new, #quickbar a.new { color: #CC2200; }\n";
844 } else {
845 $rules[] = "a.new, #quickbar a.new, a.stub, #quickbar a.stub { color: inherit; }";
846 $rules[] = "a.new:after, #quickbar a.new:after { content: '?'; color: #CC2200; }";
847 $rules[] = "a.stub:after, #quickbar a.stub:after { content: '!'; color: #772233; }";
848 }
849 if ( $user->getOption( 'justify' ) ) {
850 $rules[] = "#article, #bodyContent, #mw_content { text-align: justify; }\n";
851 }
852 if ( !$user->getOption( 'showtoc' ) ) {
853 $rules[] = "#toc { display: none; }\n";
854 }
855 if ( !$user->getOption( 'editsection' ) ) {
856 $rules[] = ".editsection { display: none; }\n";
857 }
858 if ( ( $fontstyle = $user->getOption( 'editfont' ) ) !== 'default' ) {
859 $rules[] = "textarea { font-family: $fontstyle; }\n";
860 }
861 return array( 'all' => implode( "\n", $rules ) );
862 }
863 return array();
864 }
865
866 public function getFlip( $context ) {
867 global $wgContLang;
868
869 return $wgContLang->getDir() !== $context->getDirection();
870 }
871 }
872
873 class ResourceLoaderStartUpModule extends ResourceLoaderModule {
874 /* Protected Members */
875
876 protected $modifiedTime = array();
877
878 /* Protected Methods */
879
880 protected function getConfig( $context ) {
881 global $wgLoadScript, $wgScript, $wgStylePath, $wgScriptExtension, $wgArticlePath, $wgScriptPath, $wgServer,
882 $wgContLang, $wgBreakFrames, $wgVariantArticlePath, $wgActionPaths, $wgUseAjax, $wgVersion,
883 $wgEnableAPI, $wgEnableWriteAPI, $wgDBname, $wgEnableMWSuggest, $wgSitename, $wgFileExtensions;
884
885 // Pre-process information
886 $separatorTransTable = $wgContLang->separatorTransformTable();
887 $separatorTransTable = $separatorTransTable ? $separatorTransTable : array();
888 $compactSeparatorTransTable = array(
889 implode( "\t", array_keys( $separatorTransTable ) ),
890 implode( "\t", $separatorTransTable ),
891 );
892 $digitTransTable = $wgContLang->digitTransformTable();
893 $digitTransTable = $digitTransTable ? $digitTransTable : array();
894 $compactDigitTransTable = array(
895 implode( "\t", array_keys( $digitTransTable ) ),
896 implode( "\t", $digitTransTable ),
897 );
898 $mainPage = Title::newMainPage();
899
900 // Build list of variables
901 $vars = array(
902 'wgLoadScript' => $wgLoadScript,
903 'debug' => $context->getDebug(),
904 'skin' => $context->getSkin(),
905 'stylepath' => $wgStylePath,
906 'wgUrlProtocols' => wfUrlProtocols(),
907 'wgArticlePath' => $wgArticlePath,
908 'wgScriptPath' => $wgScriptPath,
909 'wgScriptExtension' => $wgScriptExtension,
910 'wgScript' => $wgScript,
911 'wgVariantArticlePath' => $wgVariantArticlePath,
912 'wgActionPaths' => $wgActionPaths,
913 'wgServer' => $wgServer,
914 'wgUserLanguage' => $context->getLanguage(),
915 'wgContentLanguage' => $wgContLang->getCode(),
916 'wgBreakFrames' => $wgBreakFrames,
917 'wgVersion' => $wgVersion,
918 'wgEnableAPI' => $wgEnableAPI,
919 'wgEnableWriteAPI' => $wgEnableWriteAPI,
920 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
921 'wgDigitTransformTable' => $compactDigitTransTable,
922 'wgMainPageTitle' => $mainPage ? $mainPage->getPrefixedText() : null,
923 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(),
924 'wgNamespaceIds' => $wgContLang->getNamespaceIds(),
925 'wgSiteName' => $wgSitename,
926 'wgFileExtensions' => $wgFileExtensions,
927 );
928 if ( $wgContLang->hasVariants() ) {
929 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
930 }
931 if ( $wgUseAjax && $wgEnableMWSuggest ) {
932 $vars['wgMWSuggestTemplate'] = SearchEngine::getMWSuggestTemplate();
933 $vars['wgDBname'] = $wgDBname;
934 }
935
936 return $vars;
937 }
938
939 /* Methods */
940
941 public function getScript( ResourceLoaderContext $context ) {
942 global $IP, $wgLoadScript;
943
944 $scripts = file_get_contents( "$IP/resources/startup.js" );
945
946 if ( $context->getOnly() === 'scripts' ) {
947 // Get all module registrations
948 $registration = ResourceLoader::getModuleRegistrations( $context );
949 // Build configuration
950 $config = FormatJson::encode( $this->getConfig( $context ) );
951 // Add a well-known start-up function
952 $scripts .= "window.startUp = function() { $registration mediaWiki.config.set( $config ); };";
953 // Build load query for jquery and mediawiki modules
954 $query = array(
955 'modules' => implode( '|', array( 'jquery', 'mediawiki' ) ),
956 'only' => 'scripts',
957 'lang' => $context->getLanguage(),
958 'skin' => $context->getSkin(),
959 'debug' => $context->getDebug() ? 'true' : 'false',
960 'version' => wfTimestamp( TS_ISO_8601, round( max(
961 ResourceLoader::getModule( 'jquery' )->getModifiedTime( $context ),
962 ResourceLoader::getModule( 'mediawiki' )->getModifiedTime( $context )
963 ), -2 ) )
964 );
965 // Uniform query order
966 ksort( $query );
967 // Build HTML code for loading jquery and mediawiki modules
968 $loadScript = Html::linkedScript( $wgLoadScript . '?' . wfArrayToCGI( $query ) );
969 // Add code to add jquery and mediawiki loading code; only if the current client is compatible
970 $scripts .= "if ( isCompatible() ) { document.write( '$loadScript' ); }";
971 // Delete the compatible function - it's not needed anymore
972 $scripts .= "delete window['isCompatible'];";
973 }
974
975 return $scripts;
976 }
977
978 public function getModifiedTime( ResourceLoaderContext $context ) {
979 global $IP;
980
981 $hash = $context->getHash();
982 if ( isset( $this->modifiedTime[$hash] ) ) {
983 return $this->modifiedTime[$hash];
984 }
985 $this->modifiedTime[$hash] = filemtime( "$IP/resources/startup.js" );
986 // ATTENTION!: Because of the line above, this is not going to cause infinite recursion - think carefully
987 // before making changes to this code!
988 $this->modifiedTime[$hash] = ResourceLoader::getHighestModifiedTime( $context );
989 return $this->modifiedTime[$hash];
990 }
991
992 public function getFlip( $context ) {
993 global $wgContLang;
994
995 return $wgContLang->getDir() !== $context->getDirection();
996 }
997 }