Use only single query for determinging highest page_touched, which is not loaded...
[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 $titles = array();
744 foreach ( $this->getPages( $context ) as $page => $options ) {
745 $titles[] = Title::makeTitle( $options['ns'], $page );
746 }
747 // Do batch existence check
748 // TODO: This would work better if page_touched were loaded by this as well
749 $lb = new LinkBatch( $titles );
750 $lb->setCaller( __METHOD__ );
751 $lb->execute();
752 $modifiedTime = 1; // wfTimestamp() interprets 0 as "now"
753
754 $ids = array();
755 foreach ( $titles as $title ) {
756 if ( $title->exists() ) {
757 $ids[] = $title->getArticleId();
758 }
759 }
760
761 $dbr = wfGetDB( DB_SLAVE );
762 $modifiedTime = $dbr->selectField( 'page', 'MAX(page_touched)', array( 'page_id' => $ids ), __METHOD__ );
763
764 return $this->modifiedTime[$hash] = wfTimestamp( TS_UNIX, $modifiedTime );
765 }
766 }
767
768 /**
769 * Module for site customizations
770 */
771 class ResourceLoaderSiteModule extends ResourceLoaderWikiModule {
772
773 /* Protected Methods */
774
775 protected function getPages( ResourceLoaderContext $context ) {
776 global $wgHandheldStyle;
777
778 $pages = array(
779 'Common.js' => array( 'ns' => NS_MEDIAWIKI, 'type' => 'script' ),
780 'Common.css' => array( 'ns' => NS_MEDIAWIKI, 'type' => 'style' ),
781 ucfirst( $context->getSkin() ) . '.js' => array( 'ns' => NS_MEDIAWIKI, 'type' => 'script' ),
782 ucfirst( $context->getSkin() ) . '.css' => array( 'ns' => NS_MEDIAWIKI, 'type' => 'style' ),
783 'Print.css' => array( 'ns' => NS_MEDIAWIKI, 'type' => 'style', 'media' => 'print' ),
784 );
785 if ( $wgHandheldStyle ) {
786 $pages['Handheld.css'] = array( 'ns' => NS_MEDIAWIKI, 'type' => 'style', 'media' => 'handheld' );
787 }
788 return $pages;
789 }
790 }
791
792 /**
793 * Module for user customizations
794 */
795 class ResourceLoaderUserModule extends ResourceLoaderWikiModule {
796
797 /* Protected Methods */
798
799 protected function getPages( ResourceLoaderContext $context ) {
800 global $wgAllowUserCss;
801
802 if ( $context->getUser() && $wgAllowUserCss ) {
803 $username = $context->getUser();
804 return array(
805 "$username/common.js" => array( 'ns' => NS_USER, 'type' => 'script' ),
806 "$username/" . $context->getSkin() . '.js' => array( 'ns' => NS_USER, 'type' => 'script' ),
807 "$username/common.css" => array( 'ns' => NS_USER, 'type' => 'style' ),
808 "$username/" . $context->getSkin() . '.css' => array( 'ns' => NS_USER, 'type' => 'style' ),
809 );
810 }
811 return array();
812 }
813 }
814
815 /**
816 * Module for user preference customizations
817 */
818 class ResourceLoaderUserPreferencesModule extends ResourceLoaderModule {
819
820 /* Protected Members */
821
822 protected $modifiedTime = array();
823
824 /* Methods */
825
826 public function getModifiedTime( ResourceLoaderContext $context ) {
827 $hash = $context->getHash();
828 if ( isset( $this->modifiedTime[$hash] ) ) {
829 return $this->modifiedTime[$hash];
830 }
831 if ( $context->getUser() && $user = User::newFromName( $context->getUser() ) ) {
832 return $this->modifiedTime[$hash] = $user->getTouched();
833 } else {
834 return 0;
835 }
836 }
837
838 public function getStyles( ResourceLoaderContext $context ) {
839 global $wgAllowUserCssPrefs;
840 if ( $wgAllowUserCssPrefs ) {
841 $user = User::newFromName( $context->getUser() );
842 if ( $user === false ) {
843 $user = User::newFromId( 0 );
844 }
845
846 $rules = array();
847 if ( ( $underline = $user->getOption( 'underline' ) ) < 2 ) {
848 $rules[] = "a { text-decoration: " . ( $underline ? 'underline' : 'none' ) . "; }";
849 }
850 if ( $user->getOption( 'highlightbroken' ) ) {
851 $rules[] = "a.new, #quickbar a.new { color: #CC2200; }\n";
852 } else {
853 $rules[] = "a.new, #quickbar a.new, a.stub, #quickbar a.stub { color: inherit; }";
854 $rules[] = "a.new:after, #quickbar a.new:after { content: '?'; color: #CC2200; }";
855 $rules[] = "a.stub:after, #quickbar a.stub:after { content: '!'; color: #772233; }";
856 }
857 if ( $user->getOption( 'justify' ) ) {
858 $rules[] = "#article, #bodyContent, #mw_content { text-align: justify; }\n";
859 }
860 if ( !$user->getOption( 'showtoc' ) ) {
861 $rules[] = "#toc { display: none; }\n";
862 }
863 if ( !$user->getOption( 'editsection' ) ) {
864 $rules[] = ".editsection { display: none; }\n";
865 }
866 if ( ( $fontstyle = $user->getOption( 'editfont' ) ) !== 'default' ) {
867 $rules[] = "textarea { font-family: $fontstyle; }\n";
868 }
869 return array( 'all' => implode( "\n", $rules ) );
870 }
871 return array();
872 }
873
874 public function getFlip( $context ) {
875 global $wgContLang;
876
877 return $wgContLang->getDir() !== $context->getDirection();
878 }
879 }
880
881 class ResourceLoaderStartUpModule extends ResourceLoaderModule {
882 /* Protected Members */
883
884 protected $modifiedTime = array();
885
886 /* Protected Methods */
887
888 protected function getConfig( $context ) {
889 global $wgLoadScript, $wgScript, $wgStylePath, $wgScriptExtension, $wgArticlePath, $wgScriptPath, $wgServer,
890 $wgContLang, $wgBreakFrames, $wgVariantArticlePath, $wgActionPaths, $wgUseAjax, $wgVersion,
891 $wgEnableAPI, $wgEnableWriteAPI, $wgDBname, $wgEnableMWSuggest, $wgSitename, $wgFileExtensions;
892
893 // Pre-process information
894 $separatorTransTable = $wgContLang->separatorTransformTable();
895 $separatorTransTable = $separatorTransTable ? $separatorTransTable : array();
896 $compactSeparatorTransTable = array(
897 implode( "\t", array_keys( $separatorTransTable ) ),
898 implode( "\t", $separatorTransTable ),
899 );
900 $digitTransTable = $wgContLang->digitTransformTable();
901 $digitTransTable = $digitTransTable ? $digitTransTable : array();
902 $compactDigitTransTable = array(
903 implode( "\t", array_keys( $digitTransTable ) ),
904 implode( "\t", $digitTransTable ),
905 );
906 $mainPage = Title::newMainPage();
907
908 // Build list of variables
909 $vars = array(
910 'wgLoadScript' => $wgLoadScript,
911 'debug' => $context->getDebug(),
912 'skin' => $context->getSkin(),
913 'stylepath' => $wgStylePath,
914 'wgUrlProtocols' => wfUrlProtocols(),
915 'wgArticlePath' => $wgArticlePath,
916 'wgScriptPath' => $wgScriptPath,
917 'wgScriptExtension' => $wgScriptExtension,
918 'wgScript' => $wgScript,
919 'wgVariantArticlePath' => $wgVariantArticlePath,
920 'wgActionPaths' => $wgActionPaths,
921 'wgServer' => $wgServer,
922 'wgUserLanguage' => $context->getLanguage(),
923 'wgContentLanguage' => $wgContLang->getCode(),
924 'wgBreakFrames' => $wgBreakFrames,
925 'wgVersion' => $wgVersion,
926 'wgEnableAPI' => $wgEnableAPI,
927 'wgEnableWriteAPI' => $wgEnableWriteAPI,
928 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
929 'wgDigitTransformTable' => $compactDigitTransTable,
930 'wgMainPageTitle' => $mainPage ? $mainPage->getPrefixedText() : null,
931 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(),
932 'wgNamespaceIds' => $wgContLang->getNamespaceIds(),
933 'wgSiteName' => $wgSitename,
934 'wgFileExtensions' => $wgFileExtensions,
935 );
936 if ( $wgContLang->hasVariants() ) {
937 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
938 }
939 if ( $wgUseAjax && $wgEnableMWSuggest ) {
940 $vars['wgMWSuggestTemplate'] = SearchEngine::getMWSuggestTemplate();
941 $vars['wgDBname'] = $wgDBname;
942 }
943
944 return $vars;
945 }
946
947 /* Methods */
948
949 public function getScript( ResourceLoaderContext $context ) {
950 global $IP, $wgLoadScript;
951
952 $scripts = file_get_contents( "$IP/resources/startup.js" );
953
954 if ( $context->getOnly() === 'scripts' ) {
955 // Get all module registrations
956 $registration = ResourceLoader::getModuleRegistrations( $context );
957 // Build configuration
958 $config = FormatJson::encode( $this->getConfig( $context ) );
959 // Add a well-known start-up function
960 $scripts .= "window.startUp = function() { $registration mediaWiki.config.set( $config ); };";
961 // Build load query for jquery and mediawiki modules
962 $query = array(
963 'modules' => implode( '|', array( 'jquery', 'mediawiki' ) ),
964 'only' => 'scripts',
965 'lang' => $context->getLanguage(),
966 'skin' => $context->getSkin(),
967 'debug' => $context->getDebug() ? 'true' : 'false',
968 'version' => wfTimestamp( TS_ISO_8601, round( max(
969 ResourceLoader::getModule( 'jquery' )->getModifiedTime( $context ),
970 ResourceLoader::getModule( 'mediawiki' )->getModifiedTime( $context )
971 ), -2 ) )
972 );
973 // Uniform query order
974 ksort( $query );
975 // Build HTML code for loading jquery and mediawiki modules
976 $loadScript = Html::linkedScript( $wgLoadScript . '?' . wfArrayToCGI( $query ) );
977 // Add code to add jquery and mediawiki loading code; only if the current client is compatible
978 $scripts .= "if ( isCompatible() ) { document.write( '$loadScript' ); }";
979 // Delete the compatible function - it's not needed anymore
980 $scripts .= "delete window['isCompatible'];";
981 }
982
983 return $scripts;
984 }
985
986 public function getModifiedTime( ResourceLoaderContext $context ) {
987 global $IP;
988
989 $hash = $context->getHash();
990 if ( isset( $this->modifiedTime[$hash] ) ) {
991 return $this->modifiedTime[$hash];
992 }
993 $this->modifiedTime[$hash] = filemtime( "$IP/resources/startup.js" );
994 // ATTENTION!: Because of the line above, this is not going to cause infinite recursion - think carefully
995 // before making changes to this code!
996 $this->modifiedTime[$hash] = ResourceLoader::getHighestModifiedTime( $context );
997 return $this->modifiedTime[$hash];
998 }
999
1000 public function getFlip( $context ) {
1001 global $wgContLang;
1002
1003 return $wgContLang->getDir() !== $context->getDirection();
1004 }
1005 }