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
24 * Abstraction for resource loader modules, with name registration and maxage functionality.
26 abstract class ResourceLoaderModule
{
27 /* Protected Members */
29 protected $name = null;
31 // In-object cache for file dependencies
32 protected $fileDeps = array();
33 // In-object cache for message blob mtime
34 protected $msgBlobMtime = array();
39 * Get this module's name. This is set when the module is registered
40 * with ResourceLoader::register()
42 * @return Mixed: name (string) or null if no name was set
44 public function getName() {
49 * Set this module's name. This is called by ResourceLodaer::register()
50 * when registering the module. Other code should not call this.
52 * @param $name String: name
54 public function setName( $name ) {
59 * Get whether CSS for this module should be flipped
61 public function getFlip( $context ) {
62 return $context->getDirection() === 'rtl';
66 * Get all JS for this module for a given language and skin.
67 * Includes all relevant JS except loader scripts.
69 * @param $context ResourceLoaderContext object
72 public function getScript( ResourceLoaderContext
$context ) {
73 // Stub, override expected
78 * Get all CSS for this module for a given skin.
80 * @param $context ResourceLoaderContext object
81 * @return array: strings of CSS keyed by media type
83 public function getStyles( ResourceLoaderContext
$context ) {
84 // Stub, override expected
89 * Get the messages needed for this module.
91 * To get a JSON blob with messages, use MessageBlobStore::get()
93 * @return array of message keys. Keys may occur more than once
95 public function getMessages() {
96 // Stub, override expected
101 * Get the group this module is in.
103 * @return string of group name
105 public function getGroup() {
106 // Stub, override expected
111 * Get the loader JS for this module, if set.
113 * @return Mixed: loader JS (string) or false if no custom loader set
115 public function getLoaderScript() {
116 // Stub, override expected
121 * Get a list of modules this module depends on.
123 * Dependency information is taken into account when loading a module
124 * on the client side. When adding a module on the server side,
125 * dependency information is NOT taken into account and YOU are
126 * responsible for adding dependent modules as well. If you don't do
127 * this, the client side loader will send a second request back to the
128 * server to fetch the missing modules, which kind of defeats the
129 * purpose of the resource loader.
131 * To add dependencies dynamically on the client side, use a custom
132 * loader script, see getLoaderScript()
133 * @return Array of module names (strings)
135 public function getDependencies() {
136 // Stub, override expected
141 * Get the files this module depends on indirectly for a given skin.
142 * Currently these are only image files referenced by the module's CSS.
144 * @param $skin String: skin name
145 * @return array of files
147 public function getFileDependencies( $skin ) {
148 // Try in-object cache first
149 if ( isset( $this->fileDeps
[$skin] ) ) {
150 return $this->fileDeps
[$skin];
153 $dbr = wfGetDB( DB_SLAVE
);
154 $deps = $dbr->selectField( 'module_deps', 'md_deps', array(
155 'md_module' => $this->getName(),
159 if ( !is_null( $deps ) ) {
160 $this->fileDeps
[$skin] = (array) FormatJson
::decode( $deps, true );
162 return $this->fileDeps
[$skin];
166 * Set preloaded file dependency information. Used so we can load this
167 * information for all modules at once.
168 * @param $skin string Skin name
169 * @param $deps array Array of file names
171 public function setFileDependencies( $skin, $deps ) {
172 $this->fileDeps
[$skin] = $deps;
176 * Get the last modification timestamp of the message blob for this
177 * module in a given language.
178 * @param $lang string Language code
179 * @return int UNIX timestamp, or 0 if no blob found
181 public function getMsgBlobMtime( $lang ) {
182 if ( !count( $this->getMessages() ) )
185 $dbr = wfGetDB( DB_SLAVE
);
186 $msgBlobMtime = $dbr->selectField( 'msg_resource', 'mr_timestamp', array(
187 'mr_resource' => $this->getName(),
191 $this->msgBlobMtime
[$lang] = $msgBlobMtime ?
wfTimestamp( TS_UNIX
, $msgBlobMtime ) : 0;
192 return $this->msgBlobMtime
[$lang];
196 * Set a preloaded message blob last modification timestamp. Used so we
197 * can load this information for all modules at once.
198 * @param $lang string Language code
199 * @param $mtime int UNIX timestamp or 0 if there is no such blob
201 public function setMsgBlobMtime( $lang, $mtime ) {
202 $this->msgBlobMtime
[$lang] = $mtime;
206 /* Abstract Methods */
209 * Get this module's last modification timestamp for a given
210 * combination of language, skin and debug mode flag. This is typically
211 * the highest of each of the relevant components' modification
212 * timestamps. Whenever anything happens that changes the module's
213 * contents for these parameters, the mtime should increase.
215 * @param $context ResourceLoaderContext object
216 * @return int UNIX timestamp
218 public abstract function getModifiedTime( ResourceLoaderContext
$context );
222 * Module based on local JS/CSS files. This is the most common type of module.
224 class ResourceLoaderFileModule
extends ResourceLoaderModule
{
225 /* Protected Members */
227 protected $scripts = array();
228 protected $styles = array();
229 protected $messages = array();
231 protected $dependencies = array();
232 protected $debugScripts = array();
233 protected $languageScripts = array();
234 protected $skinScripts = array();
235 protected $skinStyles = array();
236 protected $loaders = array();
237 protected $parameters = array();
239 // In-object cache for file dependencies
240 protected $fileDeps = array();
241 // In-object cache for mtime
242 protected $modifiedTime = array();
247 * Construct a new module from an options array.
249 * @param $options array Options array. If empty, an empty module will be constructed
253 * // Required module options (mutually exclusive)
254 * 'scripts' => 'dir/script.js' | array( 'dir/script1.js', 'dir/script2.js' ... ),
256 * // Optional module options
257 * 'languageScripts' => array(
258 * '[lang name]' => 'dir/lang.js' | '[lang name]' => array( 'dir/lang1.js', 'dir/lang2.js' ... )
261 * 'skinScripts' => 'dir/skin.js' | array( 'dir/skin1.js', 'dir/skin2.js' ... ),
262 * 'debugScripts' => 'dir/debug.js' | array( 'dir/debug1.js', 'dir/debug2.js' ... ),
264 * // Non-raw module options
265 * 'dependencies' => 'module' | array( 'module1', 'module2' ... )
266 * 'loaderScripts' => 'dir/loader.js' | array( 'dir/loader1.js', 'dir/loader2.js' ... ),
267 * 'styles' => 'dir/file.css' | array( 'dir/file1.css', 'dir/file2.css' ... ), |
268 * array( 'dir/file1.css' => array( 'media' => 'print' ) ),
269 * 'skinStyles' => array(
270 * '[skin name]' => 'dir/skin.css' | array( 'dir/skin1.css', 'dir/skin2.css' ... ) |
271 * array( 'dir/file1.css' => array( 'media' => 'print' )
274 * 'messages' => array( 'message1', 'message2' ... ),
275 * 'group' => 'stuff',
278 public function __construct( $options = array() ) {
279 foreach ( $options as $option => $value ) {
282 $this->scripts
= (array)$value;
285 $this->styles
= (array)$value;
288 $this->messages
= (array)$value;
291 $this->group
= (string)$value;
294 $this->dependencies
= (array)$value;
297 $this->debugScripts
= (array)$value;
299 case 'languageScripts':
300 $this->languageScripts
= (array)$value;
303 $this->skinScripts
= (array)$value;
306 $this->skinStyles
= (array)$value;
309 $this->loaders
= (array)$value;
316 * Add script files to this module. In order to be valid, a module
317 * must contain at least one script file.
319 * @param $scripts Mixed: path to script file (string) or array of paths
321 public function addScripts( $scripts ) {
322 $this->scripts
= array_merge( $this->scripts
, (array)$scripts );
326 * Add style (CSS) files to this module.
328 * @param $styles Mixed: path to CSS file (string) or array of paths
330 public function addStyles( $styles ) {
331 $this->styles
= array_merge( $this->styles
, (array)$styles );
335 * Add messages to this module.
337 * @param $messages Mixed: message key (string) or array of message keys
339 public function addMessages( $messages ) {
340 $this->messages
= array_merge( $this->messages
, (array)$messages );
344 * Sets the group of this module.
346 * @param $group string group name
348 public function setGroup( $group ) {
349 $this->group
= $group;
353 * Add dependencies. Dependency information is taken into account when
354 * loading a module on the client side. When adding a module on the
355 * server side, dependency information is NOT taken into account and
356 * YOU are responsible for adding dependent modules as well. If you
357 * don't do this, the client side loader will send a second request
358 * back to the server to fetch the missing modules, which kind of
359 * defeats the point of using the resource loader in the first place.
361 * To add dependencies dynamically on the client side, use a custom
362 * loader (see addLoaders())
364 * @param $dependencies Mixed: module name (string) or array of module names
366 public function addDependencies( $dependencies ) {
367 $this->dependencies
= array_merge( $this->dependencies
, (array)$dependencies );
371 * Add debug scripts to the module. These scripts are only included
374 * @param $scripts Mixed: path to script file (string) or array of paths
376 public function addDebugScripts( $scripts ) {
377 $this->debugScripts
= array_merge( $this->debugScripts
, (array)$scripts );
381 * Add language-specific scripts. These scripts are only included for
384 * @param $lang String: language code
385 * @param $scripts Mixed: path to script file (string) or array of paths
387 public function addLanguageScripts( $lang, $scripts ) {
388 $this->languageScripts
= array_merge_recursive(
389 $this->languageScripts
,
390 array( $lang => $scripts )
395 * Add skin-specific scripts. These scripts are only included for
398 * @param $skin String: skin name, or 'default'
399 * @param $scripts Mixed: path to script file (string) or array of paths
401 public function addSkinScripts( $skin, $scripts ) {
402 $this->skinScripts
= array_merge_recursive(
404 array( $skin => $scripts )
409 * Add skin-specific CSS. These CSS files are only included for a
410 * given skin. If there are no skin-specific CSS files for a skin,
411 * the files defined for 'default' will be used, if any.
413 * @param $skin String: skin name, or 'default'
414 * @param $scripts Mixed: path to CSS file (string) or array of paths
416 public function addSkinStyles( $skin, $scripts ) {
417 $this->skinStyles
= array_merge_recursive(
419 array( $skin => $scripts )
424 * Add loader scripts. These scripts are loaded on every page and are
425 * responsible for registering this module using
426 * mediaWiki.loader.register(). If there are no loader scripts defined,
427 * the resource loader will register the module itself.
429 * Loader scripts are used to determine a module's dependencies
430 * dynamically on the client side (e.g. based on browser type/version).
431 * Note that loader scripts are included on every page, so they should
432 * be lightweight and use mediaWiki.loader.register()'s callback
433 * feature to defer dependency calculation.
435 * @param $scripts Mixed: path to script file (string) or array of paths
437 public function addLoaders( $scripts ) {
438 $this->loaders
= array_merge( $this->loaders
, (array)$scripts );
441 public function getScript( ResourceLoaderContext
$context ) {
442 $retval = $this->getPrimaryScript() . "\n" .
443 $this->getLanguageScript( $context->getLanguage() ) . "\n" .
444 $this->getSkinScript( $context->getSkin() );
446 if ( $context->getDebug() ) {
447 $retval .= $this->getDebugScript();
453 public function getStyles( ResourceLoaderContext
$context ) {
455 foreach ( $this->getPrimaryStyles() as $media => $style ) {
456 if ( !isset( $styles[$media] ) ) {
457 $styles[$media] = '';
459 $styles[$media] .= $style;
461 foreach ( $this->getSkinStyles( $context->getSkin() ) as $media => $style ) {
462 if ( !isset( $styles[$media] ) ) {
463 $styles[$media] = '';
465 $styles[$media] .= $style;
468 // Collect referenced files
470 foreach ( $styles as $media => $style ) {
471 // Extract and store the list of referenced files
472 $files = array_merge( $files, CSSMin
::getLocalFileReferences( $style ) );
475 // Only store if modified
476 if ( $files !== $this->getFileDependencies( $context->getSkin() ) ) {
477 $encFiles = FormatJson
::encode( $files );
478 $dbw = wfGetDB( DB_MASTER
);
479 $dbw->replace( 'module_deps',
480 array( array( 'md_module', 'md_skin' ) ), array(
481 'md_module' => $this->getName(),
482 'md_skin' => $context->getSkin(),
483 'md_deps' => $encFiles,
487 // Save into memcached
490 $key = wfMemcKey( 'resourceloader', 'module_deps', $this->getName(), $context->getSkin() );
491 $wgMemc->set( $key, $encFiles );
497 public function getMessages() {
498 return $this->messages
;
501 public function getGroup() {
505 public function getDependencies() {
506 return $this->dependencies
;
509 public function getLoaderScript() {
510 if ( count( $this->loaders
) == 0 ) {
514 return self
::concatScripts( $this->loaders
);
518 * Get the last modified timestamp of this module, which is calculated
519 * as the highest last modified timestamp of its constituent files and
520 * the files it depends on (see getFileDependencies()). Only files
521 * relevant to the given language and skin are taken into account, and
522 * files only relevant in debug mode are not taken into account when
525 * @param $context ResourceLoaderContext object
526 * @return Integer: UNIX timestamp
528 public function getModifiedTime( ResourceLoaderContext
$context ) {
529 if ( isset( $this->modifiedTime
[$context->getHash()] ) ) {
530 return $this->modifiedTime
[$context->getHash()];
532 wfProfileIn( __METHOD__
);
534 // Sort of nasty way we can get a flat list of files depended on by all styles
536 foreach ( self
::organizeFilesByOption( $this->styles
, 'media', 'all' ) as $media => $styleFiles ) {
537 $styles = array_merge( $styles, $styleFiles );
539 $skinFiles = (array) self
::getSkinFiles(
540 $context->getSkin(), self
::organizeFilesByOption( $this->skinStyles
, 'media', 'all' )
542 foreach ( $skinFiles as $media => $styleFiles ) {
543 $styles = array_merge( $styles, $styleFiles );
546 // Final merge, this should result in a master list of dependent files
547 $files = array_merge(
550 $context->getDebug() ?
$this->debugScripts
: array(),
551 isset( $this->languageScripts
[$context->getLanguage()] ) ?
552 (array) $this->languageScripts
[$context->getLanguage()] : array(),
553 (array) self
::getSkinFiles( $context->getSkin(), $this->skinScripts
),
555 $this->getFileDependencies( $context->getSkin() )
558 wfProfileIn( __METHOD__
.'-filemtime' );
559 $filesMtime = max( array_map( 'filemtime', array_map( array( __CLASS__
, 'remapFilename' ), $files ) ) );
560 wfProfileOut( __METHOD__
.'-filemtime' );
561 $this->modifiedTime
[$context->getHash()] = max( $filesMtime, $this->getMsgBlobMtime( $context->getLanguage() ) );
562 wfProfileOut( __METHOD__
);
563 return $this->modifiedTime
[$context->getHash()];
566 /* Protected Members */
569 * Get the primary JS for this module. This is pulled from the
570 * script files added through addScripts()
574 protected function getPrimaryScript() {
575 return self
::concatScripts( $this->scripts
);
579 * Get the primary CSS for this module. This is pulled from the CSS
580 * files added through addStyles()
584 protected function getPrimaryStyles() {
585 return self
::concatStyles( $this->styles
);
589 * Get the debug JS for this module. This is pulled from the script
590 * files added through addDebugScripts()
594 protected function getDebugScript() {
595 return self
::concatScripts( $this->debugScripts
);
599 * Get the language-specific JS for a given language. This is pulled
600 * from the language-specific script files added through addLanguageScripts()
604 protected function getLanguageScript( $lang ) {
605 if ( !isset( $this->languageScripts
[$lang] ) ) {
608 return self
::concatScripts( $this->languageScripts
[$lang] );
612 * Get the skin-specific JS for a given skin. This is pulled from the
613 * skin-specific JS files added through addSkinScripts()
617 protected function getSkinScript( $skin ) {
618 return self
::concatScripts( self
::getSkinFiles( $skin, $this->skinScripts
) );
622 * Get the skin-specific CSS for a given skin. This is pulled from the
623 * skin-specific CSS files added through addSkinStyles()
625 * @return Array: list of CSS strings keyed by media type
627 protected function getSkinStyles( $skin ) {
628 return self
::concatStyles( self
::getSkinFiles( $skin, $this->skinStyles
) );
632 * Helper function to get skin-specific data from an array.
634 * @param $skin String: skin name
635 * @param $map Array: map of skin names to arrays
636 * @return $map[$skin] if set and non-empty, or $map['default'] if set, or an empty array
638 protected static function getSkinFiles( $skin, $map ) {
641 if ( isset( $map[$skin] ) && $map[$skin] ) {
642 $retval = $map[$skin];
643 } else if ( isset( $map['default'] ) ) {
644 $retval = $map['default'];
651 * Get the contents of a set of files and concatenate them, with
652 * newlines in between. Each file is used only once.
654 * @param $files Array of file names
655 * @return String: concatenated contents of $files
657 protected static function concatScripts( $files ) {
658 return implode( "\n",
662 array( __CLASS__
, 'remapFilename' ),
663 array_unique( (array) $files ) ) ) );
666 protected static function organizeFilesByOption( $files, $option, $default ) {
667 $organizedFiles = array();
668 foreach ( (array) $files as $key => $value ) {
669 if ( is_int( $key ) ) {
670 // File name as the value
671 if ( !isset( $organizedFiles[$default] ) ) {
672 $organizedFiles[$default] = array();
674 $organizedFiles[$default][] = $value;
675 } else if ( is_array( $value ) ) {
676 // File name as the key, options array as the value
677 $media = isset( $value[$option] ) ?
$value[$option] : $default;
678 if ( !isset( $organizedFiles[$media] ) ) {
679 $organizedFiles[$media] = array();
681 $organizedFiles[$media][] = $key;
684 return $organizedFiles;
688 * Get the contents of a set of CSS files, remap then and concatenate
689 * them, with newlines in between. Each file is used only once.
691 * @param $files Array of file names
692 * @return Array: list of concatenated and remapped contents of $files keyed by media type
694 protected static function concatStyles( $styles ) {
695 $styles = self
::organizeFilesByOption( $styles, 'media', 'all' );
696 foreach ( $styles as $media => $files ) {
700 array( __CLASS__
, 'remapStyle' ),
701 array_unique( (array) $files ) ) );
707 * Remap a relative to $IP. Used as a callback for array_map()
709 * @param $file String: file name
710 * @return string $IP/$file
712 protected static function remapFilename( $file ) {
719 * Get the contents of a CSS file and run it through CSSMin::remap().
720 * This wrapper is needed so we can use array_map() in concatStyles()
722 * @param $file String: file name
723 * @return string Remapped CSS
725 protected static function remapStyle( $file ) {
726 global $wgUseDataURLs, $wgScriptPath;
727 return CSSMin
::remap(
728 file_get_contents( self
::remapFilename( $file ) ),
730 $wgScriptPath . '/' . dirname( $file ),
737 * Abstraction for resource loader modules which pull from wiki pages
739 abstract class ResourceLoaderWikiModule
extends ResourceLoaderModule
{
741 /* Protected Members */
743 // In-object cache for modified time
744 protected $modifiedTime = array();
746 /* Abstract Protected Methods */
748 abstract protected function getPages( ResourceLoaderContext
$context );
750 /* Protected Methods */
752 protected function getContent( $page, $ns ) {
753 if ( $ns === NS_MEDIAWIKI
) {
754 return wfMsgExt( $page, 'content' );
756 if ( $title = Title
::newFromText( $page, $ns ) ) {
757 if ( $title->isValidCssJsSubpage() && $revision = Revision
::newFromTitle( $title ) ) {
758 return $revision->getRawText();
766 public function getScript( ResourceLoaderContext
$context ) {
767 global $wgCanonicalNamespaceNames;
770 foreach ( $this->getPages( $context ) as $page => $options ) {
771 if ( $options['type'] === 'script' ) {
772 if ( $script = $this->getContent( $page, $options['ns'] ) ) {
773 $ns = $wgCanonicalNamespaceNames[$options['ns']];
774 $scripts .= "/*$ns:$page */\n$script\n";
781 public function getStyles( ResourceLoaderContext
$context ) {
782 global $wgCanonicalNamespaceNames;
785 foreach ( $this->getPages( $context ) as $page => $options ) {
786 if ( $options['type'] === 'style' ) {
787 $media = isset( $options['media'] ) ?
$options['media'] : 'all';
788 if ( $style = $this->getContent( $page, $options['ns'] ) ) {
789 if ( !isset( $styles[$media] ) ) {
790 $styles[$media] = '';
792 $ns = $wgCanonicalNamespaceNames[$options['ns']];
793 $styles[$media] .= "/* $ns:$page */\n$style\n";
800 public function getModifiedTime( ResourceLoaderContext
$context ) {
801 $hash = $context->getHash();
802 if ( isset( $this->modifiedTime
[$hash] ) ) {
803 return $this->modifiedTime
[$hash];
807 foreach ( $this->getPages( $context ) as $page => $options ) {
808 $titles[$options['ns']][$page] = true;
811 $modifiedTime = 1; // wfTimestamp() interprets 0 as "now"
814 $dbr = wfGetDB( DB_SLAVE
);
815 $latest = $dbr->selectField( 'page', 'MAX(page_touched)',
816 $dbr->makeWhereFrom2d( $titles, 'page_namespace', 'page_title' ),
820 $modifiedTime = wfTimestamp( TS_UNIX
, $modifiedTime );
824 return $this->modifiedTime
[$hash] = $modifiedTime;
829 * Module for site customizations
831 class ResourceLoaderSiteModule
extends ResourceLoaderWikiModule
{
833 /* Protected Methods */
835 protected function getPages( ResourceLoaderContext
$context ) {
836 global $wgHandheldStyle;
839 'Common.js' => array( 'ns' => NS_MEDIAWIKI
, 'type' => 'script' ),
840 'Common.css' => array( 'ns' => NS_MEDIAWIKI
, 'type' => 'style' ),
841 ucfirst( $context->getSkin() ) . '.js' => array( 'ns' => NS_MEDIAWIKI
, 'type' => 'script' ),
842 ucfirst( $context->getSkin() ) . '.css' => array( 'ns' => NS_MEDIAWIKI
, 'type' => 'style' ),
843 'Print.css' => array( 'ns' => NS_MEDIAWIKI
, 'type' => 'style', 'media' => 'print' ),
845 if ( $wgHandheldStyle ) {
846 $pages['Handheld.css'] = array( 'ns' => NS_MEDIAWIKI
, 'type' => 'style', 'media' => 'handheld' );
853 public function getGroup() {
859 * Module for user customizations
861 class ResourceLoaderUserModule
extends ResourceLoaderWikiModule
{
863 /* Protected Methods */
865 protected function getPages( ResourceLoaderContext
$context ) {
866 global $wgAllowUserCss;
868 if ( $context->getUser() && $wgAllowUserCss ) {
869 $username = $context->getUser();
871 "$username/common.js" => array( 'ns' => NS_USER
, 'type' => 'script' ),
872 "$username/" . $context->getSkin() . '.js' => array( 'ns' => NS_USER
, 'type' => 'script' ),
873 "$username/common.css" => array( 'ns' => NS_USER
, 'type' => 'style' ),
874 "$username/" . $context->getSkin() . '.css' => array( 'ns' => NS_USER
, 'type' => 'style' ),
882 public function getGroup() {
888 * Module for user preference customizations
890 class ResourceLoaderUserOptionsModule
extends ResourceLoaderModule
{
892 /* Protected Members */
894 protected $modifiedTime = array();
898 public function getModifiedTime( ResourceLoaderContext
$context ) {
899 $hash = $context->getHash();
900 if ( isset( $this->modifiedTime
[$hash] ) ) {
901 return $this->modifiedTime
[$hash];
905 $username = $context->getUser();
906 // Avoid extra db query by using $wgUser if possible
907 $user = $wgUser->getName() === $username ?
$wgUser : User
::newFromName( $username );
910 return $this->modifiedTime
[$hash] = $user->getTouched();
916 public function getScript( ResourceLoaderContext
$context ) {
917 $user = User
::newFromName( $context->getUser() );
918 if ( $user instanceof User
) {
919 $options = FormatJson
::encode( $user->getOptions() );
921 $options = FormatJson
::encode( User
::getDefaultOptions() );
923 return "mediaWiki.user.options.set( $options );";
926 public function getStyles( ResourceLoaderContext
$context ) {
927 global $wgAllowUserCssPrefs;
928 if ( $wgAllowUserCssPrefs ) {
929 $user = User
::newFromName( $context->getUser() );
930 $options = $user instanceof User ?
$user->getOptions() : User
::getDefaultOptions();
933 if ( $options['underline'] < 2 ) {
934 $rules[] = "a { text-decoration: " . ( $options['underline'] ?
'underline' : 'none' ) . "; }";
936 if ( $options['highlightbroken'] ) {
937 $rules[] = "a.new, #quickbar a.new { color: #CC2200; }\n";
939 $rules[] = "a.new, #quickbar a.new, a.stub, #quickbar a.stub { color: inherit; }";
940 $rules[] = "a.new:after, #quickbar a.new:after { content: '?'; color: #CC2200; }";
941 $rules[] = "a.stub:after, #quickbar a.stub:after { content: '!'; color: #772233; }";
943 if ( $options['justify'] ) {
944 $rules[] = "#article, #bodyContent, #mw_content { text-align: justify; }\n";
946 if ( !$options['showtoc'] ) {
947 $rules[] = "#toc { display: none; }\n";
949 if ( !$options['editsection'] ) {
950 $rules[] = ".editsection { display: none; }\n";
952 if ( $options['editfont'] !== 'default' ) {
953 $rules[] = "textarea { font-family: {$options['editfont']}; }\n";
955 return array( 'all' => implode( "\n", $rules ) );
960 public function getFlip( $context ) {
963 return $wgContLang->getDir() !== $context->getDirection();
966 public function getGroup() {
971 class ResourceLoaderStartUpModule
extends ResourceLoaderModule
{
972 /* Protected Members */
974 protected $modifiedTime = array();
976 /* Protected Methods */
978 protected function getConfig( $context ) {
979 global $wgLoadScript, $wgScript, $wgStylePath, $wgScriptExtension,
980 $wgArticlePath, $wgScriptPath, $wgServer, $wgContLang, $wgBreakFrames,
981 $wgVariantArticlePath, $wgActionPaths, $wgUseAjax, $wgVersion,
982 $wgEnableAPI, $wgEnableWriteAPI, $wgDBname, $wgEnableMWSuggest,
983 $wgSitename, $wgFileExtensions;
985 // Pre-process information
986 $separatorTransTable = $wgContLang->separatorTransformTable();
987 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : array();
988 $compactSeparatorTransTable = array(
989 implode( "\t", array_keys( $separatorTransTable ) ),
990 implode( "\t", $separatorTransTable ),
992 $digitTransTable = $wgContLang->digitTransformTable();
993 $digitTransTable = $digitTransTable ?
$digitTransTable : array();
994 $compactDigitTransTable = array(
995 implode( "\t", array_keys( $digitTransTable ) ),
996 implode( "\t", $digitTransTable ),
998 $mainPage = Title
::newMainPage();
1000 // Build list of variables
1002 'wgLoadScript' => $wgLoadScript,
1003 'debug' => $context->getDebug(),
1004 'skin' => $context->getSkin(),
1005 'stylepath' => $wgStylePath,
1006 'wgUrlProtocols' => wfUrlProtocols(),
1007 'wgArticlePath' => $wgArticlePath,
1008 'wgScriptPath' => $wgScriptPath,
1009 'wgScriptExtension' => $wgScriptExtension,
1010 'wgScript' => $wgScript,
1011 'wgVariantArticlePath' => $wgVariantArticlePath,
1012 'wgActionPaths' => $wgActionPaths,
1013 'wgServer' => $wgServer,
1014 'wgUserLanguage' => $context->getLanguage(),
1015 'wgContentLanguage' => $wgContLang->getCode(),
1016 'wgBreakFrames' => $wgBreakFrames,
1017 'wgVersion' => $wgVersion,
1018 'wgEnableAPI' => $wgEnableAPI,
1019 'wgEnableWriteAPI' => $wgEnableWriteAPI,
1020 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
1021 'wgDigitTransformTable' => $compactDigitTransTable,
1022 'wgMainPageTitle' => $mainPage ?
$mainPage->getPrefixedText() : null,
1023 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(),
1024 'wgNamespaceIds' => $wgContLang->getNamespaceIds(),
1025 'wgSiteName' => $wgSitename,
1026 'wgFileExtensions' => $wgFileExtensions,
1028 if ( $wgContLang->hasVariants() ) {
1029 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
1031 if ( $wgUseAjax && $wgEnableMWSuggest ) {
1032 $vars['wgMWSuggestTemplate'] = SearchEngine
::getMWSuggestTemplate();
1033 $vars['wgDBname'] = $wgDBname;
1041 public function getScript( ResourceLoaderContext
$context ) {
1042 global $IP, $wgLoadScript;
1044 $scripts = file_get_contents( "$IP/resources/startup.js" );
1046 if ( $context->getOnly() === 'scripts' ) {
1047 // Get all module registrations
1048 $registration = ResourceLoader
::getModuleRegistrations( $context );
1049 // Build configuration
1050 $config = FormatJson
::encode( $this->getConfig( $context ) );
1051 // Add a well-known start-up function
1052 $scripts .= <<<JAVASCRIPT
1053 window.startUp = function() {
1055 mediaWiki.config.set( $config );
1058 // Build load query for jquery and mediawiki modules
1060 'modules' => implode( '|', array( 'jquery', 'mediawiki' ) ),
1061 'only' => 'scripts',
1062 'lang' => $context->getLanguage(),
1063 'skin' => $context->getSkin(),
1064 'debug' => $context->getDebug() ?
'true' : 'false',
1065 'version' => wfTimestamp( TS_ISO_8601
, round( max(
1066 ResourceLoader
::getModule( 'jquery' )->getModifiedTime( $context ),
1067 ResourceLoader
::getModule( 'mediawiki' )->getModifiedTime( $context )
1070 // Uniform query order
1072 // Build HTML code for loading jquery and mediawiki modules
1073 $loadScript = Html
::linkedScript( $wgLoadScript . '?' . wfArrayToCGI( $query ) );
1074 // Add code to add jquery and mediawiki loading code; only if the current client is compatible
1075 $scripts .= "if ( isCompatible() ) { document.write( " . FormatJson
::encode( $loadScript ) . "); }\n";
1076 // Delete the compatible function - it's not needed anymore
1077 $scripts .= "delete window['isCompatible'];\n";
1083 public function getModifiedTime( ResourceLoaderContext
$context ) {
1086 $hash = $context->getHash();
1087 if ( isset( $this->modifiedTime
[$hash] ) ) {
1088 return $this->modifiedTime
[$hash];
1090 $this->modifiedTime
[$hash] = filemtime( "$IP/resources/startup.js" );
1091 // ATTENTION!: Because of the line above, this is not going to cause infinite recursion - think carefully
1092 // before making changes to this code!
1093 $this->modifiedTime
[$hash] = ResourceLoader
::getHighestModifiedTime( $context );
1094 return $this->modifiedTime
[$hash];
1097 public function getFlip( $context ) {
1100 return $wgContLang->getDir() !== $context->getDirection();
1105 public function getGroup() {