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.
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.
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
19 * @author Trevor Parscal
20 * @author Roan Kattouw
23 defined( 'MEDIAWIKI' ) ||
die( 1 );
26 * Abstraction for resource loader modules, with name registration and maxage functionality.
28 abstract class ResourceLoaderModule
{
30 /* Protected Members */
32 protected $name = null;
34 // In-object cache for file dependencies
35 protected $fileDeps = array();
36 // In-object cache for message blob mtime
37 protected $msgBlobMtime = array();
42 * Get this module's name. This is set when the module is registered
43 * with ResourceLoader::register()
45 * @return Mixed: name (string) or null if no name was set
47 public function getName() {
52 * Set this module's name. This is called by ResourceLodaer::register()
53 * when registering the module. Other code should not call this.
55 * @param $name String: name
57 public function setName( $name ) {
62 * Get whether CSS for this module should be flipped
64 public function getFlip( $context ) {
65 return $context->getDirection() === 'rtl';
69 * Get all JS for this module for a given language and skin.
70 * Includes all relevant JS except loader scripts.
72 * @param $context ResourceLoaderContext object
75 public function getScript( ResourceLoaderContext
$context ) {
76 // Stub, override expected
81 * Get all CSS for this module for a given skin.
83 * @param $context ResourceLoaderContext object
84 * @return array: strings of CSS keyed by media type
86 public function getStyles( ResourceLoaderContext
$context ) {
87 // Stub, override expected
92 * Get the messages needed for this module.
94 * To get a JSON blob with messages, use MessageBlobStore::get()
96 * @return array of message keys. Keys may occur more than once
98 public function getMessages() {
99 // Stub, override expected
104 * Get the group this module is in.
106 * @return string of group name
108 public function getGroup() {
109 // Stub, override expected
114 * Get the loader JS for this module, if set.
116 * @return Mixed: loader JS (string) or false if no custom loader set
118 public function getLoaderScript() {
119 // Stub, override expected
124 * Get a list of modules this module depends on.
126 * Dependency information is taken into account when loading a module
127 * on the client side. When adding a module on the server side,
128 * dependency information is NOT taken into account and YOU are
129 * responsible for adding dependent modules as well. If you don't do
130 * this, the client side loader will send a second request back to the
131 * server to fetch the missing modules, which kind of defeats the
132 * purpose of the resource loader.
134 * To add dependencies dynamically on the client side, use a custom
135 * loader script, see getLoaderScript()
136 * @return Array of module names (strings)
138 public function getDependencies() {
139 // Stub, override expected
144 * Get the files this module depends on indirectly for a given skin.
145 * Currently these are only image files referenced by the module's CSS.
147 * @param $skin String: skin name
148 * @return array of files
150 public function getFileDependencies( $skin ) {
151 // Try in-object cache first
152 if ( isset( $this->fileDeps
[$skin] ) ) {
153 return $this->fileDeps
[$skin];
156 $dbr = wfGetDB( DB_SLAVE
);
157 $deps = $dbr->selectField( 'module_deps', 'md_deps', array(
158 'md_module' => $this->getName(),
162 if ( !is_null( $deps ) ) {
163 return $this->fileDeps
[$skin] = (array) FormatJson
::decode( $deps, true );
165 return $this->fileDeps
[$skin] = array();
169 * Set preloaded file dependency information. Used so we can load this
170 * information for all modules at once.
171 * @param $skin string Skin name
172 * @param $deps array Array of file names
174 public function setFileDependencies( $skin, $deps ) {
175 $this->fileDeps
[$skin] = $deps;
179 * Get the last modification timestamp of the message blob for this
180 * module in a given language.
181 * @param $lang string Language code
182 * @return int UNIX timestamp, or 0 if no blob found
184 public function getMsgBlobMtime( $lang ) {
185 if ( !count( $this->getMessages() ) )
188 $dbr = wfGetDB( DB_SLAVE
);
189 $msgBlobMtime = $dbr->selectField( 'msg_resource', 'mr_timestamp', array(
190 'mr_resource' => $this->getName(),
194 $this->msgBlobMtime
[$lang] = $msgBlobMtime ?
wfTimestamp( TS_UNIX
, $msgBlobMtime ) : 0;
195 return $this->msgBlobMtime
[$lang];
199 * Set a preloaded message blob last modification timestamp. Used so we
200 * can load this information for all modules at once.
201 * @param $lang string Language code
202 * @param $mtime int UNIX timestamp or 0 if there is no such blob
204 public function setMsgBlobMtime( $lang, $mtime ) {
205 $this->msgBlobMtime
[$lang] = $mtime;
208 /* Abstract Methods */
211 * Get this module's last modification timestamp for a given
212 * combination of language, skin and debug mode flag. This is typically
213 * the highest of each of the relevant components' modification
214 * timestamps. Whenever anything happens that changes the module's
215 * contents for these parameters, the mtime should increase.
217 * @param $context ResourceLoaderContext object
218 * @return int UNIX timestamp
220 public function getModifiedTime( ResourceLoaderContext
$context ) {
227 * Module based on local JS/CSS files. This is the most common type of module.
229 class ResourceLoaderFileModule
extends ResourceLoaderModule
{
230 /* Protected Members */
232 protected $scripts = array();
233 protected $styles = array();
234 protected $messages = array();
236 protected $dependencies = array();
237 protected $debugScripts = array();
238 protected $languageScripts = array();
239 protected $skinScripts = array();
240 protected $skinStyles = array();
241 protected $loaders = array();
242 protected $parameters = array();
244 // In-object cache for file dependencies
245 protected $fileDeps = array();
246 // In-object cache for mtime
247 protected $modifiedTime = array();
252 * Construct a new module from an options array.
254 * @param $options array Options array. If empty, an empty module will be constructed
258 * // Required module options (mutually exclusive)
259 * 'scripts' => 'dir/script.js' | array( 'dir/script1.js', 'dir/script2.js' ... ),
261 * // Optional module options
262 * 'languageScripts' => array(
263 * '[lang name]' => 'dir/lang.js' | '[lang name]' => array( 'dir/lang1.js', 'dir/lang2.js' ... )
266 * 'skinScripts' => 'dir/skin.js' | array( 'dir/skin1.js', 'dir/skin2.js' ... ),
267 * 'debugScripts' => 'dir/debug.js' | array( 'dir/debug1.js', 'dir/debug2.js' ... ),
269 * // Non-raw module options
270 * 'dependencies' => 'module' | array( 'module1', 'module2' ... )
271 * 'loaderScripts' => 'dir/loader.js' | array( 'dir/loader1.js', 'dir/loader2.js' ... ),
272 * 'styles' => 'dir/file.css' | array( 'dir/file1.css', 'dir/file2.css' ... ), |
273 * array( 'dir/file1.css' => array( 'media' => 'print' ) ),
274 * 'skinStyles' => array(
275 * '[skin name]' => 'dir/skin.css' | array( 'dir/skin1.css', 'dir/skin2.css' ... ) |
276 * array( 'dir/file1.css' => array( 'media' => 'print' )
279 * 'messages' => array( 'message1', 'message2' ... ),
280 * 'group' => 'stuff',
283 * @param $basePath String: base path to prepend to all paths in $options
285 public function __construct( $options = array(), $basePath = null ) {
286 foreach ( $options as $option => $value ) {
290 case 'languageScripts':
293 $this->{$option} = (array)$value;
294 // Automatically prefix script paths
295 if ( is_string( $basePath ) ) {
296 foreach ( $this->{$option} as $key => $value ) {
297 $this->{$option}[$key] = $basePath . $value;
303 $this->{$option} = (array)$value;
304 // Automatically prefix style paths
305 if ( is_string( $basePath ) ) {
306 foreach ( $this->{$option} as $key => $value ) {
307 if ( is_array( $value ) ) {
308 $this->{$option}[$basePath . $key] = $value;
309 unset( $this->{$option}[$key] );
311 $this->{$option}[$key] = $basePath . $value;
318 $this->{$option} = (array)$value;
321 $this->group
= (string)$value;
328 * Add script files to this module. In order to be valid, a module
329 * must contain at least one script file.
331 * @param $scripts Mixed: path to script file (string) or array of paths
333 public function addScripts( $scripts ) {
334 $this->scripts
= array_merge( $this->scripts
, (array)$scripts );
338 * Add style (CSS) files to this module.
340 * @param $styles Mixed: path to CSS file (string) or array of paths
342 public function addStyles( $styles ) {
343 $this->styles
= array_merge( $this->styles
, (array)$styles );
347 * Add messages to this module.
349 * @param $messages Mixed: message key (string) or array of message keys
351 public function addMessages( $messages ) {
352 $this->messages
= array_merge( $this->messages
, (array)$messages );
356 * Sets the group of this module.
358 * @param $group string group name
360 public function setGroup( $group ) {
361 $this->group
= $group;
365 * Add dependencies. Dependency information is taken into account when
366 * loading a module on the client side. When adding a module on the
367 * server side, dependency information is NOT taken into account and
368 * YOU are responsible for adding dependent modules as well. If you
369 * don't do this, the client side loader will send a second request
370 * back to the server to fetch the missing modules, which kind of
371 * defeats the point of using the resource loader in the first place.
373 * To add dependencies dynamically on the client side, use a custom
374 * loader (see addLoaders())
376 * @param $dependencies Mixed: module name (string) or array of module names
378 public function addDependencies( $dependencies ) {
379 $this->dependencies
= array_merge( $this->dependencies
, (array)$dependencies );
383 * Add debug scripts to the module. These scripts are only included
386 * @param $scripts Mixed: path to script file (string) or array of paths
388 public function addDebugScripts( $scripts ) {
389 $this->debugScripts
= array_merge( $this->debugScripts
, (array)$scripts );
393 * Add language-specific scripts. These scripts are only included for
396 * @param $lang String: language code
397 * @param $scripts Mixed: path to script file (string) or array of paths
399 public function addLanguageScripts( $lang, $scripts ) {
400 $this->languageScripts
= array_merge_recursive(
401 $this->languageScripts
,
402 array( $lang => $scripts )
407 * Add skin-specific scripts. These scripts are only included for
410 * @param $skin String: skin name, or 'default'
411 * @param $scripts Mixed: path to script file (string) or array of paths
413 public function addSkinScripts( $skin, $scripts ) {
414 $this->skinScripts
= array_merge_recursive(
416 array( $skin => $scripts )
421 * Add skin-specific CSS. These CSS files are only included for a
422 * given skin. If there are no skin-specific CSS files for a skin,
423 * the files defined for 'default' will be used, if any.
425 * @param $skin String: skin name, or 'default'
426 * @param $scripts Mixed: path to CSS file (string) or array of paths
428 public function addSkinStyles( $skin, $scripts ) {
429 $this->skinStyles
= array_merge_recursive(
431 array( $skin => $scripts )
436 * Add loader scripts. These scripts are loaded on every page and are
437 * responsible for registering this module using
438 * mediaWiki.loader.register(). If there are no loader scripts defined,
439 * the resource loader will register the module itself.
441 * Loader scripts are used to determine a module's dependencies
442 * dynamically on the client side (e.g. based on browser type/version).
443 * Note that loader scripts are included on every page, so they should
444 * be lightweight and use mediaWiki.loader.register()'s callback
445 * feature to defer dependency calculation.
447 * @param $scripts Mixed: path to script file (string) or array of paths
449 public function addLoaders( $scripts ) {
450 $this->loaders
= array_merge( $this->loaders
, (array)$scripts );
453 public function getScript( ResourceLoaderContext
$context ) {
454 $retval = $this->getPrimaryScript() . "\n" .
455 $this->getLanguageScript( $context->getLanguage() ) . "\n" .
456 $this->getSkinScript( $context->getSkin() );
458 if ( $context->getDebug() ) {
459 $retval .= $this->getDebugScript();
465 public function getStyles( ResourceLoaderContext
$context ) {
467 foreach ( $this->getPrimaryStyles() as $media => $style ) {
468 if ( !isset( $styles[$media] ) ) {
469 $styles[$media] = '';
471 $styles[$media] .= $style;
473 foreach ( $this->getSkinStyles( $context->getSkin() ) as $media => $style ) {
474 if ( !isset( $styles[$media] ) ) {
475 $styles[$media] = '';
477 $styles[$media] .= $style;
480 // Collect referenced files
482 foreach ( $styles as $style ) {
483 // Extract and store the list of referenced files
484 $files = array_merge( $files, CSSMin
::getLocalFileReferences( $style ) );
487 // Only store if modified
488 if ( $files !== $this->getFileDependencies( $context->getSkin() ) ) {
489 $encFiles = FormatJson
::encode( $files );
490 $dbw = wfGetDB( DB_MASTER
);
491 $dbw->replace( 'module_deps',
492 array( array( 'md_module', 'md_skin' ) ), array(
493 'md_module' => $this->getName(),
494 'md_skin' => $context->getSkin(),
495 'md_deps' => $encFiles,
503 public function getMessages() {
504 return $this->messages
;
507 public function getGroup() {
511 public function getDependencies() {
512 return $this->dependencies
;
515 public function getLoaderScript() {
516 if ( count( $this->loaders
) == 0 ) {
520 return self
::concatScripts( $this->loaders
);
524 * Get the last modified timestamp of this module, which is calculated
525 * as the highest last modified timestamp of its constituent files and
526 * the files it depends on (see getFileDependencies()). Only files
527 * relevant to the given language and skin are taken into account, and
528 * files only relevant in debug mode are not taken into account when
531 * @param $context ResourceLoaderContext object
532 * @return Integer: UNIX timestamp
534 public function getModifiedTime( ResourceLoaderContext
$context ) {
535 if ( isset( $this->modifiedTime
[$context->getHash()] ) ) {
536 return $this->modifiedTime
[$context->getHash()];
538 wfProfileIn( __METHOD__
);
540 // Sort of nasty way we can get a flat list of files depended on by all styles
542 foreach ( self
::organizeFilesByOption( $this->styles
, 'media', 'all' ) as $styleFiles ) {
543 $styles = array_merge( $styles, $styleFiles );
545 $skinFiles = (array) self
::getSkinFiles(
546 $context->getSkin(), self
::organizeFilesByOption( $this->skinStyles
, 'media', 'all' )
548 foreach ( $skinFiles as $styleFiles ) {
549 $styles = array_merge( $styles, $styleFiles );
552 // Final merge, this should result in a master list of dependent files
553 $files = array_merge(
556 $context->getDebug() ?
$this->debugScripts
: array(),
557 isset( $this->languageScripts
[$context->getLanguage()] ) ?
558 (array) $this->languageScripts
[$context->getLanguage()] : array(),
559 (array) self
::getSkinFiles( $context->getSkin(), $this->skinScripts
),
561 $this->getFileDependencies( $context->getSkin() )
564 wfProfileIn( __METHOD__
.'-filemtime' );
565 $filesMtime = max( array_map( 'filemtime', array_map( array( __CLASS__
, 'remapFilename' ), $files ) ) );
566 wfProfileOut( __METHOD__
.'-filemtime' );
567 $this->modifiedTime
[$context->getHash()] = max( $filesMtime, $this->getMsgBlobMtime( $context->getLanguage() ) );
568 wfProfileOut( __METHOD__
);
569 return $this->modifiedTime
[$context->getHash()];
572 /* Protected Members */
575 * Get the primary JS for this module. This is pulled from the
576 * script files added through addScripts()
580 protected function getPrimaryScript() {
581 return self
::concatScripts( $this->scripts
);
585 * Get the primary CSS for this module. This is pulled from the CSS
586 * files added through addStyles()
590 protected function getPrimaryStyles() {
591 return self
::concatStyles( $this->styles
);
595 * Get the debug JS for this module. This is pulled from the script
596 * files added through addDebugScripts()
600 protected function getDebugScript() {
601 return self
::concatScripts( $this->debugScripts
);
605 * Get the language-specific JS for a given language. This is pulled
606 * from the language-specific script files added through addLanguageScripts()
610 protected function getLanguageScript( $lang ) {
611 if ( !isset( $this->languageScripts
[$lang] ) ) {
614 return self
::concatScripts( $this->languageScripts
[$lang] );
618 * Get the skin-specific JS for a given skin. This is pulled from the
619 * skin-specific JS files added through addSkinScripts()
623 protected function getSkinScript( $skin ) {
624 return self
::concatScripts( self
::getSkinFiles( $skin, $this->skinScripts
) );
628 * Get the skin-specific CSS for a given skin. This is pulled from the
629 * skin-specific CSS files added through addSkinStyles()
631 * @return Array: list of CSS strings keyed by media type
633 protected function getSkinStyles( $skin ) {
634 return self
::concatStyles( self
::getSkinFiles( $skin, $this->skinStyles
) );
638 * Helper function to get skin-specific data from an array.
640 * @param $skin String: skin name
641 * @param $map Array: map of skin names to arrays
642 * @return $map[$skin] if set and non-empty, or $map['default'] if set, or an empty array
644 protected static function getSkinFiles( $skin, $map ) {
647 if ( isset( $map[$skin] ) && $map[$skin] ) {
648 $retval = $map[$skin];
649 } else if ( isset( $map['default'] ) ) {
650 $retval = $map['default'];
657 * Get the contents of a set of files and concatenate them, with
658 * newlines in between. Each file is used only once.
660 * @param $files Array of file names
661 * @return String: concatenated contents of $files
663 protected static function concatScripts( $files ) {
664 return implode( "\n",
668 array( __CLASS__
, 'remapFilename' ),
669 array_unique( (array) $files ) ) ) );
672 protected static function organizeFilesByOption( $files, $option, $default ) {
673 $organizedFiles = array();
674 foreach ( (array) $files as $key => $value ) {
675 if ( is_int( $key ) ) {
676 // File name as the value
677 if ( !isset( $organizedFiles[$default] ) ) {
678 $organizedFiles[$default] = array();
680 $organizedFiles[$default][] = $value;
681 } else if ( is_array( $value ) ) {
682 // File name as the key, options array as the value
683 $media = isset( $value[$option] ) ?
$value[$option] : $default;
684 if ( !isset( $organizedFiles[$media] ) ) {
685 $organizedFiles[$media] = array();
687 $organizedFiles[$media][] = $key;
690 return $organizedFiles;
694 * Get the contents of a set of CSS files, remap then and concatenate
695 * them, with newlines in between. Each file is used only once.
697 * @param $styles Array of file names
698 * @return Array: list of concatenated and remapped contents of $files keyed by media type
700 protected static function concatStyles( $styles ) {
701 $styles = self
::organizeFilesByOption( $styles, 'media', 'all' );
702 foreach ( $styles as $media => $files ) {
706 array( __CLASS__
, 'remapStyle' ),
707 array_unique( (array) $files ) ) );
713 * Remap a relative to $IP. Used as a callback for array_map()
715 * @param $file String: file name
716 * @return string $IP/$file
718 protected static function remapFilename( $file ) {
725 * Get the contents of a CSS file and run it through CSSMin::remap().
726 * This wrapper is needed so we can use array_map() in concatStyles()
728 * @param $file String: file name
729 * @return string Remapped CSS
731 protected static function remapStyle( $file ) {
732 global $wgScriptPath;
733 return CSSMin
::remap(
734 file_get_contents( self
::remapFilename( $file ) ),
736 $wgScriptPath . '/' . dirname( $file ),
743 * Abstraction for resource loader modules which pull from wiki pages
745 * This can only be used for wiki pages in the MediaWiki and User namespaces, because of it's dependence on the
746 * functionality of Title::isValidCssJsSubpage.
748 abstract class ResourceLoaderWikiModule
extends ResourceLoaderModule
{
750 /* Protected Members */
752 // In-object cache for modified time
753 protected $modifiedTime = array();
755 /* Abstract Protected Methods */
757 abstract protected function getPages( ResourceLoaderContext
$context );
759 /* Protected Methods */
761 protected function getContent( $page, $ns ) {
762 if ( $ns === NS_MEDIAWIKI
) {
763 return wfMsgExt( $page, 'content' );
765 if ( $title = Title
::newFromText( $page, $ns ) ) {
766 if ( $title->isValidCssJsSubpage() && $revision = Revision
::newFromTitle( $title ) ) {
767 return $revision->getRawText();
775 public function getScript( ResourceLoaderContext
$context ) {
777 foreach ( $this->getPages( $context ) as $page => $options ) {
778 if ( $options['type'] === 'script' ) {
779 if ( $script = $this->getContent( $page, $options['ns'] ) ) {
780 $ns = MWNamespace
::getCanonicalName( $options['ns'] );
781 $scripts .= "/*$ns:$page */\n$script\n";
788 public function getStyles( ResourceLoaderContext
$context ) {
791 foreach ( $this->getPages( $context ) as $page => $options ) {
792 if ( $options['type'] === 'style' ) {
793 $media = isset( $options['media'] ) ?
$options['media'] : 'all';
794 if ( $style = $this->getContent( $page, $options['ns'] ) ) {
795 if ( !isset( $styles[$media] ) ) {
796 $styles[$media] = '';
798 $ns = MWNamespace
::getCanonicalName( $options['ns'] );
799 $styles[$media] .= "/* $ns:$page */\n$style\n";
806 public function getModifiedTime( ResourceLoaderContext
$context ) {
807 $hash = $context->getHash();
808 if ( isset( $this->modifiedTime
[$hash] ) ) {
809 return $this->modifiedTime
[$hash];
813 foreach ( $this->getPages( $context ) as $page => $options ) {
814 $titles[$options['ns']][$page] = true;
817 $modifiedTime = 1; // wfTimestamp() interprets 0 as "now"
820 $dbr = wfGetDB( DB_SLAVE
);
821 $latest = $dbr->selectField( 'page', 'MAX(page_touched)',
822 $dbr->makeWhereFrom2d( $titles, 'page_namespace', 'page_title' ),
826 $modifiedTime = wfTimestamp( TS_UNIX
, $latest );
830 return $this->modifiedTime
[$hash] = $modifiedTime;
835 * Module for site customizations
837 class ResourceLoaderSiteModule
extends ResourceLoaderWikiModule
{
839 /* Protected Methods */
841 protected function getPages( ResourceLoaderContext
$context ) {
842 global $wgHandheldStyle;
845 'Common.js' => array( 'ns' => NS_MEDIAWIKI
, 'type' => 'script' ),
846 'Common.css' => array( 'ns' => NS_MEDIAWIKI
, 'type' => 'style' ),
847 ucfirst( $context->getSkin() ) . '.js' => array( 'ns' => NS_MEDIAWIKI
, 'type' => 'script' ),
848 ucfirst( $context->getSkin() ) . '.css' => array( 'ns' => NS_MEDIAWIKI
, 'type' => 'style' ),
849 'Print.css' => array( 'ns' => NS_MEDIAWIKI
, 'type' => 'style', 'media' => 'print' ),
851 if ( $wgHandheldStyle ) {
852 $pages['Handheld.css'] = array( 'ns' => NS_MEDIAWIKI
, 'type' => 'style', 'media' => 'handheld' );
859 public function getGroup() {
865 * Module for user customizations
867 class ResourceLoaderUserModule
extends ResourceLoaderWikiModule
{
869 /* Protected Methods */
871 protected function getPages( ResourceLoaderContext
$context ) {
872 global $wgAllowUserCss;
874 if ( $context->getUser() && $wgAllowUserCss ) {
875 $username = $context->getUser();
877 "$username/common.js" => array( 'ns' => NS_USER
, 'type' => 'script' ),
878 "$username/" . $context->getSkin() . '.js' => array( 'ns' => NS_USER
, 'type' => 'script' ),
879 "$username/common.css" => array( 'ns' => NS_USER
, 'type' => 'style' ),
880 "$username/" . $context->getSkin() . '.css' => array( 'ns' => NS_USER
, 'type' => 'style' ),
888 public function getGroup() {
894 * Module for user preference customizations
896 class ResourceLoaderUserOptionsModule
extends ResourceLoaderModule
{
898 /* Protected Members */
900 protected $modifiedTime = array();
904 public function getModifiedTime( ResourceLoaderContext
$context ) {
905 $hash = $context->getHash();
906 if ( isset( $this->modifiedTime
[$hash] ) ) {
907 return $this->modifiedTime
[$hash];
912 if ( $context->getUser() === $wgUser->getName() ) {
913 return $this->modifiedTime
[$hash] = $wgUser->getTouched();
920 * Fetch the context's user options, or if it doesn't match current user,
921 * the default options.
923 * @param $context ResourceLoaderContext
926 protected function contextUserOptions( ResourceLoaderContext
$context ) {
929 // Verify identity -- this is a private module
930 if ( $context->getUser() === $wgUser->getName() ) {
931 return $wgUser->getOptions();
933 return User
::getDefaultOptions();
937 public function getScript( ResourceLoaderContext
$context ) {
938 $encOptions = FormatJson
::encode( $this->contextUserOptions( $context ) );
939 return "mediaWiki.user.options.set( $encOptions );";
942 public function getStyles( ResourceLoaderContext
$context ) {
943 global $wgAllowUserCssPrefs;
945 if ( $wgAllowUserCssPrefs ) {
946 $options = $this->contextUserOptions( $context );
950 if ( $options['underline'] < 2 ) {
951 $rules[] = "a { text-decoration: " . ( $options['underline'] ?
'underline' : 'none' ) . "; }";
953 if ( $options['highlightbroken'] ) {
954 $rules[] = "a.new, #quickbar a.new { color: #ba0000; }\n";
956 $rules[] = "a.new, #quickbar a.new, a.stub, #quickbar a.stub { color: inherit; }";
957 $rules[] = "a.new:after, #quickbar a.new:after { content: '?'; color: #ba0000; }";
958 $rules[] = "a.stub:after, #quickbar a.stub:after { content: '!'; color: #772233; }";
960 if ( $options['justify'] ) {
961 $rules[] = "#article, #bodyContent, #mw_content { text-align: justify; }\n";
963 if ( !$options['showtoc'] ) {
964 $rules[] = "#toc { display: none; }\n";
966 if ( !$options['editsection'] ) {
967 $rules[] = ".editsection { display: none; }\n";
969 if ( $options['editfont'] !== 'default' ) {
970 $rules[] = "textarea { font-family: {$options['editfont']}; }\n";
972 return array( 'all' => implode( "\n", $rules ) );
977 public function getFlip( $context ) {
980 return $wgContLang->getDir() !== $context->getDirection();
983 public function getGroup() {
988 class ResourceLoaderStartUpModule
extends ResourceLoaderModule
{
989 /* Protected Members */
991 protected $modifiedTime = array();
993 /* Protected Methods */
995 protected function getConfig( $context ) {
996 global $wgLoadScript, $wgScript, $wgStylePath, $wgScriptExtension,
997 $wgArticlePath, $wgScriptPath, $wgServer, $wgContLang, $wgBreakFrames,
998 $wgVariantArticlePath, $wgActionPaths, $wgUseAjax, $wgVersion,
999 $wgEnableAPI, $wgEnableWriteAPI, $wgDBname, $wgEnableMWSuggest,
1000 $wgSitename, $wgFileExtensions;
1002 // Pre-process information
1003 $separatorTransTable = $wgContLang->separatorTransformTable();
1004 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : array();
1005 $compactSeparatorTransTable = array(
1006 implode( "\t", array_keys( $separatorTransTable ) ),
1007 implode( "\t", $separatorTransTable ),
1009 $digitTransTable = $wgContLang->digitTransformTable();
1010 $digitTransTable = $digitTransTable ?
$digitTransTable : array();
1011 $compactDigitTransTable = array(
1012 implode( "\t", array_keys( $digitTransTable ) ),
1013 implode( "\t", $digitTransTable ),
1015 $mainPage = Title
::newMainPage();
1017 // Build list of variables
1019 'wgLoadScript' => $wgLoadScript,
1020 'debug' => $context->getDebug(),
1021 'skin' => $context->getSkin(),
1022 'stylepath' => $wgStylePath,
1023 'wgUrlProtocols' => wfUrlProtocols(),
1024 'wgArticlePath' => $wgArticlePath,
1025 'wgScriptPath' => $wgScriptPath,
1026 'wgScriptExtension' => $wgScriptExtension,
1027 'wgScript' => $wgScript,
1028 'wgVariantArticlePath' => $wgVariantArticlePath,
1029 'wgActionPaths' => $wgActionPaths,
1030 'wgServer' => $wgServer,
1031 'wgUserLanguage' => $context->getLanguage(),
1032 'wgContentLanguage' => $wgContLang->getCode(),
1033 'wgBreakFrames' => $wgBreakFrames,
1034 'wgVersion' => $wgVersion,
1035 'wgEnableAPI' => $wgEnableAPI,
1036 'wgEnableWriteAPI' => $wgEnableWriteAPI,
1037 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
1038 'wgDigitTransformTable' => $compactDigitTransTable,
1039 'wgMainPageTitle' => $mainPage ?
$mainPage->getPrefixedText() : null,
1040 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(),
1041 'wgNamespaceIds' => $wgContLang->getNamespaceIds(),
1042 'wgSiteName' => $wgSitename,
1043 'wgFileExtensions' => $wgFileExtensions,
1044 'wgDBname' => $wgDBname,
1046 if ( $wgContLang->hasVariants() ) {
1047 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
1049 if ( $wgUseAjax && $wgEnableMWSuggest ) {
1050 $vars['wgMWSuggestTemplate'] = SearchEngine
::getMWSuggestTemplate();
1057 * Gets registration code for all modules
1059 * @param $context ResourceLoaderContext object
1060 * @return String: JavaScript code for registering all modules with the client loader
1062 public static function getModuleRegistrations( ResourceLoaderContext
$context ) {
1063 global $wgCacheEpoch;
1064 wfProfileIn( __METHOD__
);
1067 $registrations = array();
1068 foreach ( $context->getResourceLoader()->getModules() as $name => $module ) {
1069 // Support module loader scripts
1070 if ( ( $loader = $module->getLoaderScript() ) !== false ) {
1071 $deps = $module->getDependencies();
1072 $group = $module->getGroup();
1073 $version = wfTimestamp( TS_ISO_8601_BASIC
, round( $module->getModifiedTime( $context ), -2 ) );
1074 $out .= ResourceLoader
::makeCustomLoaderScript( $name, $version, $deps, $group, $loader );
1076 // Automatically register module
1078 $mtime = max( $module->getModifiedTime( $context ), wfTimestamp( TS_UNIX
, $wgCacheEpoch ) );
1079 // Modules without dependencies or a group pass two arguments (name, timestamp) to
1080 // mediaWiki.loader.register()
1081 if ( !count( $module->getDependencies() && $module->getGroup() === null ) ) {
1082 $registrations[] = array( $name, $mtime );
1084 // Modules with dependencies but no group pass three arguments (name, timestamp, dependencies)
1085 // to mediaWiki.loader.register()
1086 else if ( $module->getGroup() === null ) {
1087 $registrations[] = array(
1088 $name, $mtime, $module->getDependencies() );
1090 // Modules with dependencies pass four arguments (name, timestamp, dependencies, group)
1091 // to mediaWiki.loader.register()
1093 $registrations[] = array(
1094 $name, $mtime, $module->getDependencies(), $module->getGroup() );
1098 $out .= ResourceLoader
::makeLoaderRegisterScript( $registrations );
1100 wfProfileOut( __METHOD__
);
1106 public function getScript( ResourceLoaderContext
$context ) {
1107 global $IP, $wgLoadScript;
1109 $out = file_get_contents( "$IP/resources/startup.js" );
1110 if ( $context->getOnly() === 'scripts' ) {
1111 // Build load query for jquery and mediawiki modules
1113 'modules' => implode( '|', array( 'jquery', 'mediawiki' ) ),
1114 'only' => 'scripts',
1115 'lang' => $context->getLanguage(),
1116 'skin' => $context->getSkin(),
1117 'debug' => $context->getDebug() ?
'true' : 'false',
1118 'version' => wfTimestamp( TS_ISO_8601_BASIC
, round( max(
1119 $context->getResourceLoader()->getModule( 'jquery' )->getModifiedTime( $context ),
1120 $context->getResourceLoader()->getModule( 'mediawiki' )->getModifiedTime( $context )
1123 // Ensure uniform query order
1127 $configuration = FormatJson
::encode( $this->getConfig( $context ) );
1128 $registrations = self
::getModuleRegistrations( $context );
1129 $out .= "var startUp = function() {\n\t$registrations\n\tmediaWiki.config.set( $configuration );\n};";
1131 // Conditional script injection
1132 $scriptTag = Xml
::escapeJsString( Html
::linkedScript( $wgLoadScript . '?' . wfArrayToCGI( $query ) ) );
1133 $out .= "if ( isCompatible() ) {\n\tdocument.write( '$scriptTag' );\n}\ndelete isCompatible;";
1139 public function getModifiedTime( ResourceLoaderContext
$context ) {
1140 global $IP, $wgCacheEpoch;
1142 $hash = $context->getHash();
1143 if ( isset( $this->modifiedTime
[$hash] ) ) {
1144 return $this->modifiedTime
[$hash];
1146 $this->modifiedTime
[$hash] = filemtime( "$IP/resources/startup.js" );
1148 // ATTENTION!: Because of the line above, this is not going to cause infinite recursion - think carefully
1149 // before making changes to this code!
1150 $time = wfTimestamp( TS_UNIX
, $wgCacheEpoch );
1151 foreach ( $context->getResourceLoader()->getModules() as $module ) {
1152 $time = max( $time, $module->getModifiedTime( $context ) );
1154 return $this->modifiedTime
[$hash] = $time;
1157 public function getFlip( $context ) {
1160 return $wgContLang->getDir() !== $context->getDirection();
1165 public function getGroup() {