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 public function __construct( $options = array(), $basePath = null ) {
284 foreach ( $options as $option => $value ) {
288 case 'languageScripts':
291 $this->{$option} = (array)$value;
292 // Automatically prefix script paths
293 if ( is_string( $basePath ) ) {
294 foreach ( $this->{$option} as $key => $value ) {
295 $this->{$option}[$key] = $basePath . $value;
301 $this->{$option} = (array)$value;
302 // Automatically prefix style paths
303 if ( is_string( $basePath ) ) {
304 foreach ( $this->{$option} as $key => $value ) {
305 if ( is_array( $value ) ) {
306 $this->{$option}[$basePath . $key] = $value;
307 unset( $this->{$option}[$key] );
309 $this->{$option}[$key] = $basePath . $value;
316 $this->{$option} = (array)$value;
319 $this->group
= (string)$value;
326 * Add script files to this module. In order to be valid, a module
327 * must contain at least one script file.
329 * @param $scripts Mixed: path to script file (string) or array of paths
331 public function addScripts( $scripts ) {
332 $this->scripts
= array_merge( $this->scripts
, (array)$scripts );
336 * Add style (CSS) files to this module.
338 * @param $styles Mixed: path to CSS file (string) or array of paths
340 public function addStyles( $styles ) {
341 $this->styles
= array_merge( $this->styles
, (array)$styles );
345 * Add messages to this module.
347 * @param $messages Mixed: message key (string) or array of message keys
349 public function addMessages( $messages ) {
350 $this->messages
= array_merge( $this->messages
, (array)$messages );
354 * Sets the group of this module.
356 * @param $group string group name
358 public function setGroup( $group ) {
359 $this->group
= $group;
363 * Add dependencies. Dependency information is taken into account when
364 * loading a module on the client side. When adding a module on the
365 * server side, dependency information is NOT taken into account and
366 * YOU are responsible for adding dependent modules as well. If you
367 * don't do this, the client side loader will send a second request
368 * back to the server to fetch the missing modules, which kind of
369 * defeats the point of using the resource loader in the first place.
371 * To add dependencies dynamically on the client side, use a custom
372 * loader (see addLoaders())
374 * @param $dependencies Mixed: module name (string) or array of module names
376 public function addDependencies( $dependencies ) {
377 $this->dependencies
= array_merge( $this->dependencies
, (array)$dependencies );
381 * Add debug scripts to the module. These scripts are only included
384 * @param $scripts Mixed: path to script file (string) or array of paths
386 public function addDebugScripts( $scripts ) {
387 $this->debugScripts
= array_merge( $this->debugScripts
, (array)$scripts );
391 * Add language-specific scripts. These scripts are only included for
394 * @param $lang String: language code
395 * @param $scripts Mixed: path to script file (string) or array of paths
397 public function addLanguageScripts( $lang, $scripts ) {
398 $this->languageScripts
= array_merge_recursive(
399 $this->languageScripts
,
400 array( $lang => $scripts )
405 * Add skin-specific scripts. These scripts are only included for
408 * @param $skin String: skin name, or 'default'
409 * @param $scripts Mixed: path to script file (string) or array of paths
411 public function addSkinScripts( $skin, $scripts ) {
412 $this->skinScripts
= array_merge_recursive(
414 array( $skin => $scripts )
419 * Add skin-specific CSS. These CSS files are only included for a
420 * given skin. If there are no skin-specific CSS files for a skin,
421 * the files defined for 'default' will be used, if any.
423 * @param $skin String: skin name, or 'default'
424 * @param $scripts Mixed: path to CSS file (string) or array of paths
426 public function addSkinStyles( $skin, $scripts ) {
427 $this->skinStyles
= array_merge_recursive(
429 array( $skin => $scripts )
434 * Add loader scripts. These scripts are loaded on every page and are
435 * responsible for registering this module using
436 * mediaWiki.loader.register(). If there are no loader scripts defined,
437 * the resource loader will register the module itself.
439 * Loader scripts are used to determine a module's dependencies
440 * dynamically on the client side (e.g. based on browser type/version).
441 * Note that loader scripts are included on every page, so they should
442 * be lightweight and use mediaWiki.loader.register()'s callback
443 * feature to defer dependency calculation.
445 * @param $scripts Mixed: path to script file (string) or array of paths
447 public function addLoaders( $scripts ) {
448 $this->loaders
= array_merge( $this->loaders
, (array)$scripts );
451 public function getScript( ResourceLoaderContext
$context ) {
452 $retval = $this->getPrimaryScript() . "\n" .
453 $this->getLanguageScript( $context->getLanguage() ) . "\n" .
454 $this->getSkinScript( $context->getSkin() );
456 if ( $context->getDebug() ) {
457 $retval .= $this->getDebugScript();
463 public function getStyles( ResourceLoaderContext
$context ) {
465 foreach ( $this->getPrimaryStyles() as $media => $style ) {
466 if ( !isset( $styles[$media] ) ) {
467 $styles[$media] = '';
469 $styles[$media] .= $style;
471 foreach ( $this->getSkinStyles( $context->getSkin() ) as $media => $style ) {
472 if ( !isset( $styles[$media] ) ) {
473 $styles[$media] = '';
475 $styles[$media] .= $style;
478 // Collect referenced files
480 foreach ( $styles as $style ) {
481 // Extract and store the list of referenced files
482 $files = array_merge( $files, CSSMin
::getLocalFileReferences( $style ) );
485 // Only store if modified
486 if ( $files !== $this->getFileDependencies( $context->getSkin() ) ) {
487 $encFiles = FormatJson
::encode( $files );
488 $dbw = wfGetDB( DB_MASTER
);
489 $dbw->replace( 'module_deps',
490 array( array( 'md_module', 'md_skin' ) ), array(
491 'md_module' => $this->getName(),
492 'md_skin' => $context->getSkin(),
493 'md_deps' => $encFiles,
501 public function getMessages() {
502 return $this->messages
;
505 public function getGroup() {
509 public function getDependencies() {
510 return $this->dependencies
;
513 public function getLoaderScript() {
514 if ( count( $this->loaders
) == 0 ) {
518 return self
::concatScripts( $this->loaders
);
522 * Get the last modified timestamp of this module, which is calculated
523 * as the highest last modified timestamp of its constituent files and
524 * the files it depends on (see getFileDependencies()). Only files
525 * relevant to the given language and skin are taken into account, and
526 * files only relevant in debug mode are not taken into account when
529 * @param $context ResourceLoaderContext object
530 * @return Integer: UNIX timestamp
532 public function getModifiedTime( ResourceLoaderContext
$context ) {
533 if ( isset( $this->modifiedTime
[$context->getHash()] ) ) {
534 return $this->modifiedTime
[$context->getHash()];
536 wfProfileIn( __METHOD__
);
538 // Sort of nasty way we can get a flat list of files depended on by all styles
540 foreach ( self
::organizeFilesByOption( $this->styles
, 'media', 'all' ) as $styleFiles ) {
541 $styles = array_merge( $styles, $styleFiles );
543 $skinFiles = (array) self
::getSkinFiles(
544 $context->getSkin(), self
::organizeFilesByOption( $this->skinStyles
, 'media', 'all' )
546 foreach ( $skinFiles as $styleFiles ) {
547 $styles = array_merge( $styles, $styleFiles );
550 // Final merge, this should result in a master list of dependent files
551 $files = array_merge(
554 $context->getDebug() ?
$this->debugScripts
: array(),
555 isset( $this->languageScripts
[$context->getLanguage()] ) ?
556 (array) $this->languageScripts
[$context->getLanguage()] : array(),
557 (array) self
::getSkinFiles( $context->getSkin(), $this->skinScripts
),
559 $this->getFileDependencies( $context->getSkin() )
562 wfProfileIn( __METHOD__
.'-filemtime' );
563 $filesMtime = max( array_map( 'filemtime', array_map( array( __CLASS__
, 'remapFilename' ), $files ) ) );
564 wfProfileOut( __METHOD__
.'-filemtime' );
565 $this->modifiedTime
[$context->getHash()] = max( $filesMtime, $this->getMsgBlobMtime( $context->getLanguage() ) );
566 wfProfileOut( __METHOD__
);
567 return $this->modifiedTime
[$context->getHash()];
570 /* Protected Members */
573 * Get the primary JS for this module. This is pulled from the
574 * script files added through addScripts()
578 protected function getPrimaryScript() {
579 return self
::concatScripts( $this->scripts
);
583 * Get the primary CSS for this module. This is pulled from the CSS
584 * files added through addStyles()
588 protected function getPrimaryStyles() {
589 return self
::concatStyles( $this->styles
);
593 * Get the debug JS for this module. This is pulled from the script
594 * files added through addDebugScripts()
598 protected function getDebugScript() {
599 return self
::concatScripts( $this->debugScripts
);
603 * Get the language-specific JS for a given language. This is pulled
604 * from the language-specific script files added through addLanguageScripts()
608 protected function getLanguageScript( $lang ) {
609 if ( !isset( $this->languageScripts
[$lang] ) ) {
612 return self
::concatScripts( $this->languageScripts
[$lang] );
616 * Get the skin-specific JS for a given skin. This is pulled from the
617 * skin-specific JS files added through addSkinScripts()
621 protected function getSkinScript( $skin ) {
622 return self
::concatScripts( self
::getSkinFiles( $skin, $this->skinScripts
) );
626 * Get the skin-specific CSS for a given skin. This is pulled from the
627 * skin-specific CSS files added through addSkinStyles()
629 * @return Array: list of CSS strings keyed by media type
631 protected function getSkinStyles( $skin ) {
632 return self
::concatStyles( self
::getSkinFiles( $skin, $this->skinStyles
) );
636 * Helper function to get skin-specific data from an array.
638 * @param $skin String: skin name
639 * @param $map Array: map of skin names to arrays
640 * @return $map[$skin] if set and non-empty, or $map['default'] if set, or an empty array
642 protected static function getSkinFiles( $skin, $map ) {
645 if ( isset( $map[$skin] ) && $map[$skin] ) {
646 $retval = $map[$skin];
647 } else if ( isset( $map['default'] ) ) {
648 $retval = $map['default'];
655 * Get the contents of a set of files and concatenate them, with
656 * newlines in between. Each file is used only once.
658 * @param $files Array of file names
659 * @return String: concatenated contents of $files
661 protected static function concatScripts( $files ) {
662 return implode( "\n",
666 array( __CLASS__
, 'remapFilename' ),
667 array_unique( (array) $files ) ) ) );
670 protected static function organizeFilesByOption( $files, $option, $default ) {
671 $organizedFiles = array();
672 foreach ( (array) $files as $key => $value ) {
673 if ( is_int( $key ) ) {
674 // File name as the value
675 if ( !isset( $organizedFiles[$default] ) ) {
676 $organizedFiles[$default] = array();
678 $organizedFiles[$default][] = $value;
679 } else if ( is_array( $value ) ) {
680 // File name as the key, options array as the value
681 $media = isset( $value[$option] ) ?
$value[$option] : $default;
682 if ( !isset( $organizedFiles[$media] ) ) {
683 $organizedFiles[$media] = array();
685 $organizedFiles[$media][] = $key;
688 return $organizedFiles;
692 * Get the contents of a set of CSS files, remap then and concatenate
693 * them, with newlines in between. Each file is used only once.
695 * @param $files Array of file names
696 * @return Array: list of concatenated and remapped contents of $files keyed by media type
698 protected static function concatStyles( $styles ) {
699 $styles = self
::organizeFilesByOption( $styles, 'media', 'all' );
700 foreach ( $styles as $media => $files ) {
704 array( __CLASS__
, 'remapStyle' ),
705 array_unique( (array) $files ) ) );
711 * Remap a relative to $IP. Used as a callback for array_map()
713 * @param $file String: file name
714 * @return string $IP/$file
716 protected static function remapFilename( $file ) {
723 * Get the contents of a CSS file and run it through CSSMin::remap().
724 * This wrapper is needed so we can use array_map() in concatStyles()
726 * @param $file String: file name
727 * @return string Remapped CSS
729 protected static function remapStyle( $file ) {
730 global $wgScriptPath;
731 return CSSMin
::remap(
732 file_get_contents( self
::remapFilename( $file ) ),
734 $wgScriptPath . '/' . dirname( $file ),
741 * Abstraction for resource loader modules which pull from wiki pages
743 * This can only be used for wiki pages in the MediaWiki and User namespaces, because of it's dependence on the
744 * functionality of Title::isValidCssJsSubpage.
746 abstract class ResourceLoaderWikiModule
extends ResourceLoaderModule
{
748 /* Protected Members */
750 // In-object cache for modified time
751 protected $modifiedTime = array();
753 /* Abstract Protected Methods */
755 abstract protected function getPages( ResourceLoaderContext
$context );
757 /* Protected Methods */
759 protected function getContent( $page, $ns ) {
760 if ( $ns === NS_MEDIAWIKI
) {
761 return wfMsgExt( $page, 'content' );
763 if ( $title = Title
::newFromText( $page, $ns ) ) {
764 if ( $title->isValidCssJsSubpage() && $revision = Revision
::newFromTitle( $title ) ) {
765 return $revision->getRawText();
773 public function getScript( ResourceLoaderContext
$context ) {
775 foreach ( $this->getPages( $context ) as $page => $options ) {
776 if ( $options['type'] === 'script' ) {
777 if ( $script = $this->getContent( $page, $options['ns'] ) ) {
778 $ns = MWNamespace
::getCanonicalName( $options['ns'] );
779 $scripts .= "/*$ns:$page */\n$script\n";
786 public function getStyles( ResourceLoaderContext
$context ) {
789 foreach ( $this->getPages( $context ) as $page => $options ) {
790 if ( $options['type'] === 'style' ) {
791 $media = isset( $options['media'] ) ?
$options['media'] : 'all';
792 if ( $style = $this->getContent( $page, $options['ns'] ) ) {
793 if ( !isset( $styles[$media] ) ) {
794 $styles[$media] = '';
796 $ns = MWNamespace
::getCanonicalName( $options['ns'] );
797 $styles[$media] .= "/* $ns:$page */\n$style\n";
804 public function getModifiedTime( ResourceLoaderContext
$context ) {
805 $hash = $context->getHash();
806 if ( isset( $this->modifiedTime
[$hash] ) ) {
807 return $this->modifiedTime
[$hash];
811 foreach ( $this->getPages( $context ) as $page => $options ) {
812 $titles[$options['ns']][$page] = true;
815 $modifiedTime = 1; // wfTimestamp() interprets 0 as "now"
818 $dbr = wfGetDB( DB_SLAVE
);
819 $latest = $dbr->selectField( 'page', 'MAX(page_touched)',
820 $dbr->makeWhereFrom2d( $titles, 'page_namespace', 'page_title' ),
824 $modifiedTime = wfTimestamp( TS_UNIX
, $latest );
828 return $this->modifiedTime
[$hash] = $modifiedTime;
833 * Module for site customizations
835 class ResourceLoaderSiteModule
extends ResourceLoaderWikiModule
{
837 /* Protected Methods */
839 protected function getPages( ResourceLoaderContext
$context ) {
840 global $wgHandheldStyle;
843 'Common.js' => array( 'ns' => NS_MEDIAWIKI
, 'type' => 'script' ),
844 'Common.css' => array( 'ns' => NS_MEDIAWIKI
, 'type' => 'style' ),
845 ucfirst( $context->getSkin() ) . '.js' => array( 'ns' => NS_MEDIAWIKI
, 'type' => 'script' ),
846 ucfirst( $context->getSkin() ) . '.css' => array( 'ns' => NS_MEDIAWIKI
, 'type' => 'style' ),
847 'Print.css' => array( 'ns' => NS_MEDIAWIKI
, 'type' => 'style', 'media' => 'print' ),
849 if ( $wgHandheldStyle ) {
850 $pages['Handheld.css'] = array( 'ns' => NS_MEDIAWIKI
, 'type' => 'style', 'media' => 'handheld' );
857 public function getGroup() {
863 * Module for user customizations
865 class ResourceLoaderUserModule
extends ResourceLoaderWikiModule
{
867 /* Protected Methods */
869 protected function getPages( ResourceLoaderContext
$context ) {
870 global $wgAllowUserCss;
872 if ( $context->getUser() && $wgAllowUserCss ) {
873 $username = $context->getUser();
875 "$username/common.js" => array( 'ns' => NS_USER
, 'type' => 'script' ),
876 "$username/" . $context->getSkin() . '.js' => array( 'ns' => NS_USER
, 'type' => 'script' ),
877 "$username/common.css" => array( 'ns' => NS_USER
, 'type' => 'style' ),
878 "$username/" . $context->getSkin() . '.css' => array( 'ns' => NS_USER
, 'type' => 'style' ),
886 public function getGroup() {
892 * Module for user preference customizations
894 class ResourceLoaderUserOptionsModule
extends ResourceLoaderModule
{
896 /* Protected Members */
898 protected $modifiedTime = array();
902 public function getModifiedTime( ResourceLoaderContext
$context ) {
903 $hash = $context->getHash();
904 if ( isset( $this->modifiedTime
[$hash] ) ) {
905 return $this->modifiedTime
[$hash];
910 if ( $context->getUser() === $wgUser->getName() ) {
911 return $this->modifiedTime
[$hash] = $wgUser->getTouched();
918 * Fetch the context's user options, or if it doesn't match current user,
919 * the default options.
921 * @param ResourceLoaderContext $context
924 protected function contextUserOptions( ResourceLoaderContext
$context ) {
927 // Verify identity -- this is a private module
928 if ( $context->getUser() === $wgUser->getName() ) {
929 return $wgUser->getOptions();
931 return User
::getDefaultOptions();
935 public function getScript( ResourceLoaderContext
$context ) {
936 $encOptions = FormatJson
::encode( $this->contextUserOptions( $context ) );
937 return "mediaWiki.user.options.set( $encOptions );";
940 public function getStyles( ResourceLoaderContext
$context ) {
941 global $wgAllowUserCssPrefs;
943 if ( $wgAllowUserCssPrefs ) {
944 $options = $this->contextUserOptions( $context );
948 if ( $options['underline'] < 2 ) {
949 $rules[] = "a { text-decoration: " . ( $options['underline'] ?
'underline' : 'none' ) . "; }";
951 if ( $options['highlightbroken'] ) {
952 $rules[] = "a.new, #quickbar a.new { color: #ba0000; }\n";
954 $rules[] = "a.new, #quickbar a.new, a.stub, #quickbar a.stub { color: inherit; }";
955 $rules[] = "a.new:after, #quickbar a.new:after { content: '?'; color: #ba0000; }";
956 $rules[] = "a.stub:after, #quickbar a.stub:after { content: '!'; color: #772233; }";
958 if ( $options['justify'] ) {
959 $rules[] = "#article, #bodyContent, #mw_content { text-align: justify; }\n";
961 if ( !$options['showtoc'] ) {
962 $rules[] = "#toc { display: none; }\n";
964 if ( !$options['editsection'] ) {
965 $rules[] = ".editsection { display: none; }\n";
967 if ( $options['editfont'] !== 'default' ) {
968 $rules[] = "textarea { font-family: {$options['editfont']}; }\n";
970 return array( 'all' => implode( "\n", $rules ) );
975 public function getFlip( $context ) {
978 return $wgContLang->getDir() !== $context->getDirection();
981 public function getGroup() {
986 class ResourceLoaderStartUpModule
extends ResourceLoaderModule
{
987 /* Protected Members */
989 protected $modifiedTime = array();
991 /* Protected Methods */
993 protected function getConfig( $context ) {
994 global $wgLoadScript, $wgScript, $wgStylePath, $wgScriptExtension,
995 $wgArticlePath, $wgScriptPath, $wgServer, $wgContLang, $wgBreakFrames,
996 $wgVariantArticlePath, $wgActionPaths, $wgUseAjax, $wgVersion,
997 $wgEnableAPI, $wgEnableWriteAPI, $wgDBname, $wgEnableMWSuggest,
998 $wgSitename, $wgFileExtensions;
1000 // Pre-process information
1001 $separatorTransTable = $wgContLang->separatorTransformTable();
1002 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : array();
1003 $compactSeparatorTransTable = array(
1004 implode( "\t", array_keys( $separatorTransTable ) ),
1005 implode( "\t", $separatorTransTable ),
1007 $digitTransTable = $wgContLang->digitTransformTable();
1008 $digitTransTable = $digitTransTable ?
$digitTransTable : array();
1009 $compactDigitTransTable = array(
1010 implode( "\t", array_keys( $digitTransTable ) ),
1011 implode( "\t", $digitTransTable ),
1013 $mainPage = Title
::newMainPage();
1015 // Build list of variables
1017 'wgLoadScript' => $wgLoadScript,
1018 'debug' => $context->getDebug(),
1019 'skin' => $context->getSkin(),
1020 'stylepath' => $wgStylePath,
1021 'wgUrlProtocols' => wfUrlProtocols(),
1022 'wgArticlePath' => $wgArticlePath,
1023 'wgScriptPath' => $wgScriptPath,
1024 'wgScriptExtension' => $wgScriptExtension,
1025 'wgScript' => $wgScript,
1026 'wgVariantArticlePath' => $wgVariantArticlePath,
1027 'wgActionPaths' => $wgActionPaths,
1028 'wgServer' => $wgServer,
1029 'wgUserLanguage' => $context->getLanguage(),
1030 'wgContentLanguage' => $wgContLang->getCode(),
1031 'wgBreakFrames' => $wgBreakFrames,
1032 'wgVersion' => $wgVersion,
1033 'wgEnableAPI' => $wgEnableAPI,
1034 'wgEnableWriteAPI' => $wgEnableWriteAPI,
1035 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
1036 'wgDigitTransformTable' => $compactDigitTransTable,
1037 'wgMainPageTitle' => $mainPage ?
$mainPage->getPrefixedText() : null,
1038 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(),
1039 'wgNamespaceIds' => $wgContLang->getNamespaceIds(),
1040 'wgSiteName' => $wgSitename,
1041 'wgFileExtensions' => $wgFileExtensions,
1042 'wgDBname' => $wgDBname,
1044 if ( $wgContLang->hasVariants() ) {
1045 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
1047 if ( $wgUseAjax && $wgEnableMWSuggest ) {
1048 $vars['wgMWSuggestTemplate'] = SearchEngine
::getMWSuggestTemplate();
1055 * Gets registration code for all modules
1057 * @param $context ResourceLoaderContext object
1058 * @return String: JavaScript code for registering all modules with the client loader
1060 public static function getModuleRegistrations( ResourceLoaderContext
$context ) {
1061 global $wgCacheEpoch;
1062 wfProfileIn( __METHOD__
);
1065 $registrations = array();
1066 foreach ( $context->getResourceLoader()->getModules() as $name => $module ) {
1067 // Support module loader scripts
1068 if ( ( $loader = $module->getLoaderScript() ) !== false ) {
1069 $deps = $module->getDependencies();
1070 $group = $module->getGroup();
1071 $version = wfTimestamp( TS_ISO_8601_BASIC
, round( $module->getModifiedTime( $context ), -2 ) );
1072 $out .= ResourceLoader
::makeCustomLoaderScript( $name, $version, $deps, $group, $loader );
1074 // Automatically register module
1076 $mtime = max( $module->getModifiedTime( $context ), wfTimestamp( TS_UNIX
, $wgCacheEpoch ) );
1077 // Modules without dependencies or a group pass two arguments (name, timestamp) to
1078 // mediaWiki.loader.register()
1079 if ( !count( $module->getDependencies() && $module->getGroup() === null ) ) {
1080 $registrations[] = array( $name, $mtime );
1082 // Modules with dependencies but no group pass three arguments (name, timestamp, dependencies)
1083 // to mediaWiki.loader.register()
1084 else if ( $module->getGroup() === null ) {
1085 $registrations[] = array(
1086 $name, $mtime, $module->getDependencies() );
1088 // Modules with dependencies pass four arguments (name, timestamp, dependencies, group)
1089 // to mediaWiki.loader.register()
1091 $registrations[] = array(
1092 $name, $mtime, $module->getDependencies(), $module->getGroup() );
1096 $out .= ResourceLoader
::makeLoaderRegisterScript( $registrations );
1098 wfProfileOut( __METHOD__
);
1104 public function getScript( ResourceLoaderContext
$context ) {
1105 global $IP, $wgLoadScript;
1107 $out = file_get_contents( "$IP/resources/startup.js" );
1108 if ( $context->getOnly() === 'scripts' ) {
1109 // Build load query for jquery and mediawiki modules
1111 'modules' => implode( '|', array( 'jquery', 'mediawiki' ) ),
1112 'only' => 'scripts',
1113 'lang' => $context->getLanguage(),
1114 'skin' => $context->getSkin(),
1115 'debug' => $context->getDebug() ?
'true' : 'false',
1116 'version' => wfTimestamp( TS_ISO_8601_BASIC
, round( max(
1117 $context->getResourceLoader()->getModule( 'jquery' )->getModifiedTime( $context ),
1118 $context->getResourceLoader()->getModule( 'mediawiki' )->getModifiedTime( $context )
1121 // Ensure uniform query order
1125 $configuration = FormatJson
::encode( $this->getConfig( $context ) );
1126 $registrations = self
::getModuleRegistrations( $context );
1127 $out .= "var startUp = function() {\n\t$registrations\n\tmediaWiki.config.set( $configuration );\n};";
1129 // Conditional script injection
1130 $scriptTag = Xml
::escapeJsString( Html
::linkedScript( $wgLoadScript . '?' . wfArrayToCGI( $query ) ) );
1131 $out .= "if ( isCompatible() ) {\n\tdocument.write( '$scriptTag' );\n}\ndelete isCompatible;";
1137 public function getModifiedTime( ResourceLoaderContext
$context ) {
1138 global $IP, $wgCacheEpoch;
1140 $hash = $context->getHash();
1141 if ( isset( $this->modifiedTime
[$hash] ) ) {
1142 return $this->modifiedTime
[$hash];
1144 $this->modifiedTime
[$hash] = filemtime( "$IP/resources/startup.js" );
1146 // ATTENTION!: Because of the line above, this is not going to cause infinite recursion - think carefully
1147 // before making changes to this code!
1148 $time = wfTimestamp( TS_UNIX
, $wgCacheEpoch );
1149 foreach ( $context->getResourceLoader()->getModules() as $module ) {
1150 $time = max( $time, $module->getModifiedTime( $context ) );
1152 return $this->modifiedTime
[$hash] = $time;
1155 public function getFlip( $context ) {
1158 return $wgContLang->getDir() !== $context->getDirection();
1163 public function getGroup() {