public static function getHTML($cur_value, $input_name, $is_mandatory, $is_disabled, $other_args) { global $sfgTabIndex, $sfgFieldNum; global $wgOut; $scripts = array("https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"); $scriptsHTML = ''; foreach ($scripts as $script) { $scriptsHTML .= Html::linkedScript($script); } $wgOut->addHeadItem($scriptsHTML, $scriptsHTML); $wgOut->addModules('ext.semanticforms.maps'); $parsedCurValue = SFOpenLayersInput::parseCoordinatesString($cur_value); $coordsInput = Html::element('input', array('type' => 'text', 'class' => 'sfCoordsInput', 'name' => $input_name, 'value' => $parsedCurValue, 'size' => 40)); $mapUpdateButton = Html::element('input', array('type' => 'button', 'class' => 'sfUpdateMap', 'value' => wfMessage('sf-maps-setmarker')->parse()), null); $addressLookupInput = Html::element('input', array('type' => 'text', 'class' => 'sfAddressInput', 'size' => 40, 'placeholder' => wfMessage('sf-maps-enteraddress')->parse()), null); $addressLookupButton = Html::element('input', array('type' => 'button', 'class' => 'sfLookUpAddress', 'value' => wfMessage('sf-maps-lookupcoordinates')->parse()), null); $mapCanvas = Html::element('div', array('class' => 'sfMapCanvas', 'style' => 'height: 500px; width: 500px;'), 'Map goes here...'); $fullInputHTML = <<<END <div style="padding-bottom: 10px;"> {$coordsInput} {$mapUpdateButton} </div> <div style="padding-bottom: 10px;"> {$addressLookupInput} {$addressLookupButton} </div> {$mapCanvas} END; $text = Html::rawElement('div', array('class' => 'sfGoogleMapsInput'), $fullInputHTML); return $text; }
/** * Loads the needed JavaScript. * Takes care of non-RL compatibility. * * @since 0.1 */ public static function loadJs() { global $wgOut; $wgOut->addScript(Html::inlineScript('var ltDebugMessages = ' . FormatJson::encode($GLOBALS['egLiveTranslateDebugJS']) . ';')); // For backward compatibility with MW < 1.17. if (is_callable(array($wgOut, 'addModules'))) { $modules = array('ext.livetranslate'); switch ($GLOBALS['egLiveTranslateService']) { case LTS_GOOGLE: $modules[] = 'ext.lt.google'; $wgOut->addHeadItem('ext.lt.google.jsapi', Html::linkedScript('https://www.google.com/jsapi?key=' . htmlspecialchars($GLOBALS['egGoogleApiKey']))); break; case LTS_MS: $modules[] = 'ext.lt.ms'; $wgOut->addScript(Html::inlineScript('var ltMsAppId = ' . FormatJson::encode($GLOBALS['egLiveTranslateMSAppId']) . ';')); break; } $wgOut->addModules($modules); } else { global $egLiveTranslateScriptPath; self::addJSLocalisation(); $wgOut->includeJQuery(); $wgOut->addHeadItem('ext.livetranslate', Html::linkedScript($egLiveTranslateScriptPath . '/includes/ext.livetranslate.js') . Html::linkedScript($egLiveTranslateScriptPath . '/includes/ext.lt.tm.js') . Html::linkedScript($egLiveTranslateScriptPath . '/includes/jquery.replaceText.js') . Html::linkedScript($egLiveTranslateScriptPath . '/includes/jquery.liveTranslate.js')); switch ($GLOBALS['egLiveTranslateService']) { case LTS_GOOGLE: $wgOut->addHeadItem('ext.lt.google.jsapi', Html::linkedScript('https://www.google.com/jsapi?key=' . htmlspecialchars($GLOBALS['egGoogleApiKey']))); $wgOut->addHeadItem('ext.lt.google', Html::linkedScript($egLiveTranslateScriptPath . '/includes/ext.lt.google.js')); break; case LTS_MS: $wgOut->addScript(Html::inlineScript('var ltMsAppId = ' . FormatJson::encode($GLOBALS['egLiveTranslateMSAppId']) . ';')); $wgOut->addHeadItem('ext.lt.ms', Html::linkedScript($egLiveTranslateScriptPath . '/includes/ext.lt.ms.js')); break; } } }
static function tooltip( $parser, $tooltip = null, $text = null ) { if ( !$text ) { return; } $tooltip = Xml::tags( 'span', array( 'style' => 'display: none', 'class' => 'mw-tooltip' ), $tooltip ); $text .= "\n$tooltip"; $text = Xml::tags( 'span', array( 'class' => 'mw-tooltip-text' ), $text ); // Script for hover behaviour hacked in by Andrew Garrett, 2010-08-09 static $scriptDone = false; if ( ! $scriptDone ) { $scriptDone = true; global $wgOut, $IP, $wgScriptPath; $output = $parser->getOutput(); // Figure out the web-accessible path to the extension. $dir = dirname( __FILE__ ); if ( strpos( $dir, $IP ) === 0 ) { $dir = substr( $dir, strlen($IP) ); $dir = $wgScriptPath . $dir; $output->addHeadItem( "<link rel=\"stylesheet\" type=\"text/css\" href=\"$dir/jquery-tooltip/jquery.tooltip.css\"/>" ); $output->addHeadItem( Html::linkedScript( "$dir/jquery-tooltip/jquery.tooltip.pack.js" ) ); $output->addHeadItem( Html::linkedScript( "$dir/hover.js" ) ); } } return $text; }
function __construct() { parent::__construct(); $this->classname = "leaflet"; $this->resourceModules[] = 'ext.MultiMaps.Leaflet'; $leafletPath = $GLOBALS['egMultiMapsScriptPath'] . '/services/Leaflet/leaflet'; $this->headerItem .= \Html::linkedStyle("{$leafletPath}/leaflet.css") . '<!--[if lte IE 8]>' . \Html::linkedStyle("{$leafletPath}/leaflet.ie.css") . '<![endif]-->' . \Html::linkedScript("{$leafletPath}/leaflet.js"); }
function __construct() { parent::__construct(); $this->classname = "google"; $this->resourceModules[] = 'ext.MultiMaps.Google'; $urlArgs = array(); $urlArgs['sensor'] = 'false'; $urlArgs['v'] = '3.10'; $this->headerItem .= \Html::linkedScript('//maps.googleapis.com/maps/api/js?' . wfArrayToCgi($urlArgs)) . "\n"; }
public static function onSkinAfterBottomScripts($skin, &$text) { if (WikiaPageType::isMainPage()) { $scripts = AssetsManager::getInstance()->getURL('njord_js'); foreach ($scripts as $script) { $text .= Html::linkedScript($script); } } return true; }
function __construct() { parent::__construct(); $this->classname = "yandex"; $this->resourceModules[] = 'ext.MultiMaps.Yandex'; $urlArgs = array(); $urlArgs['load'] = 'package.standard,package.geoObjects'; $urlArgs['lang'] = 'ru-RU'; $this->headerItem .= \Html::linkedScript('//api-maps.yandex.ru/2.0-stable/?' . wfArrayToCgi($urlArgs)) . "\n"; }
/** * Adds assets on the bottom of the body tag for special maps page * * @param {String} $skin * @param {String} $text * * @return bool */ public static function onSkinAfterBottomScripts($skin, &$text) { if (self::isSpecialMapsPage()) { $scripts = AssetsManager::getInstance()->getURL('wikia_maps_special_page_js'); foreach ($scripts as $script) { $text .= Html::linkedScript($script); } } return true; }
public static function onSkinAfterBottomScripts(Skin $skin, &$text) { $title = $skin->getTitle(); if (TemplateDraftHelper::allowedForTitle($title)) { $scripts = AssetsManager::getInstance()->getURL('template_draft'); foreach ($scripts as $script) { $text .= Html::linkedScript($script); } } return true; }
/** * Loads the needed JavaScript. * Takes care of non-RL compatibility. * * @since 0.1 */ protected static function loadJs() { global $wgOut; // For backward compatibility with MW < 1.17. if (is_callable(array($wgOut, 'addModules'))) { $wgOut->addModules('ext.push.tab'); } else { global $egPushScriptPath; PushFunctions::addJSLocalisation(); $wgOut->addHeadItem('ext.push.tab', Html::linkedScript($egPushScriptPath . '/includes/ext.push.tab.js')); } }
function getForm() { global $wgAsirraEnlargedPosition, $wgAsirraCellsPerRow, $wgOut, $wgLang; $wgOut->addModules('ext.confirmedit.asirra'); $js = Html::linkedScript($this->asirra_clientscript); $message = Xml::encodeJsVar(wfMessage('asirra-createaccount-fail')->plain()); $js .= Html::inlineScript(<<<JAVASCRIPT var asirra_js_failed = '{$message}'; JAVASCRIPT ); $js .= '<noscript>' . wfMessage('asirra-nojs')->parse() . '</noscript>'; return $js; }
/** * @param array $params experiment parameters */ function __construct(array $params) { $delay = $params['delay']; // add a JS global variable with the defined delay $this->on('WikiaSkinTopScripts', function (array &$vars) use($delay) { $vars['wgPerfTestFrontEndDelay'] = intval($delay); return true; }); $this->on('BeforePageDisplay', function (\OutputPage $out, \Skin $skin) { $out->addScript(\Html::linkedScript(\AssetsManager::getInstance()->getOneCommonURL('extensions/wikia/AbPerformanceTesting/js/FrontendDelay.js'))); return true; }); }
/** * Returns the HTML for a storysubmission form. * * @param Parser $parser * @param array $args * * @return HTML */ private static function getFrom(Parser $parser, array $args) { global $wgUser, $wgStyleVersion, $wgScriptPath, $wgStylePath; global $egStoryboardScriptPath, $egStorysubmissionWidth, $egStoryboardMaxStoryLen, $egStoryboardMinStoryLen; $maxLen = array_key_exists('maxlength', $args) && is_int($args['maxlength']) ? $args['maxlength'] : $egStoryboardMaxStoryLen; $minLen = array_key_exists('minlength', $args) && is_int($args['minlength']) ? $args['minlength'] : $egStoryboardMinStoryLen; efStoryboardAddJSLocalisation($parser); // Loading a seperate JS file would be overkill for just these 3 lines, and be bad for performance. $parser->getOutput()->addHeadItem(Html::linkedStyle("{$egStoryboardScriptPath}/storyboard.css?{$wgStyleVersion}") . Html::linkedScript("{$egStoryboardScriptPath}/storyboard.js?{$wgStyleVersion}") . Html::linkedScript("{$wgStylePath}/common/jquery.min.js?{$wgStyleVersion}") . Html::linkedScript("{$egStoryboardScriptPath}/jquery/jquery.validate.js?{$wgStyleVersion}") . Html::inlineScript(<<<EOT \$(function() { \tdocument.getElementById( 'storysubmission-button' ).disabled = true; \tstbValidateStory( document.getElementById('storytext'), {$minLen}, {$maxLen}, 'storysubmission-charlimitinfo', 'storysubmission-button' ) \t\$("#storyform").validate({ \t\tmessages: { \t\t\tstorytitle: { \t\t\t\tremote: jQuery.validator.format( stbMsg( 'storyboard-alreadyexistschange' ) ) \t\t\t} \t\t} \t});\t\t });\t\t\t EOT )); $fieldSize = 50; $width = StoryboardUtils::getDimension($args, 'width', $egStorysubmissionWidth); $formBody = "<table width='{$width}'>"; $defaultName = ''; $defaultEmail = ''; if ($wgUser->isLoggedIn()) { $defaultName = $wgUser->getRealName() !== '' ? $wgUser->getRealName() : $wgUser->getName(); $defaultEmail = $wgUser->getEmail(); } $formBody .= '<tr>' . Html::element('td', array('width' => '100%'), wfMsg('storyboard-yourname')) . '<td>' . Html::input('name', $defaultName, 'text', array('size' => $fieldSize, 'class' => 'required', 'maxlength' => 255, 'minlength' => 2)) . '</td></tr>'; $formBody .= '<tr>' . Html::element('td', array('width' => '100%'), wfMsg('storyboard-location')) . '<td>' . Html::input('location', '', 'text', array('size' => $fieldSize, 'maxlength' => 255, 'minlength' => 2)) . '</td></tr>'; $formBody .= '<tr>' . Html::element('td', array('width' => '100%'), wfMsg('storyboard-occupation')) . '<td>' . Html::input('occupation', '', 'text', array('size' => $fieldSize, 'maxlength' => 255, 'minlength' => 4)) . '</td></tr>'; $formBody .= '<tr>' . Html::element('td', array('width' => '100%'), wfMsg('storyboard-email')) . '<td>' . Html::input('email', $defaultEmail, 'text', array('size' => $fieldSize, 'class' => 'required email', 'size' => $fieldSize, 'maxlength' => 255)) . '</td></tr>'; $formBody .= '<tr>' . Html::element('td', array('width' => '100%'), wfMsg('storyboard-storytitle')) . '<td>' . Html::input('storytitle', '', 'text', array('size' => $fieldSize, 'class' => 'required storytitle', 'maxlength' => 255, 'minlength' => 2, 'remote' => "{$wgScriptPath}/api.php?format=json&action=storyexists")) . '</td></tr>'; $formBody .= '<tr><td colspan="2">' . wfMsg('storyboard-story') . Html::element('div', array('class' => 'storysubmission-charcount', 'id' => 'storysubmission-charlimitinfo'), wfMsgExt('storyboard-charsneeded', 'parsemag', $minLen)) . '<br />' . Html::element('textarea', array('id' => 'storytext', 'name' => 'storytext', 'rows' => 7, 'class' => 'required', 'onkeyup' => "stbValidateStory( this, {$minLen}, {$maxLen}, 'storysubmission-charlimitinfo', 'storysubmission-button' )"), null) . '</td></tr>'; // TODO: add upload functionality $formBody .= '<tr><td colspan="2"><input type="checkbox" id="storyboard-agreement" /> ' . $parser->recursiveTagParse(htmlspecialchars(wfMsg('storyboard-agreement'))) . '</td></tr>'; $formBody .= '<tr><td colspan="2">' . Html::input('storysubmission-button', wfMsg('htmlform-submit'), 'submit', array('id' => 'storysubmission-button')) . '</td></tr>'; $formBody .= '</table>'; $formBody .= Html::hidden('wpStoryEditToken', $wgUser->editToken()); if (!array_key_exists('language', $args) || !array_key_exists($args['language'], Language::getLanguageNames())) { global $wgContLanguageCode; $args['language'] = $wgContLanguageCode; } $formBody .= Html::hidden('lang', $args['language']); return Html::rawElement('form', array('id' => 'storyform', 'name' => 'storyform', 'method' => 'post', 'action' => SpecialPage::getTitleFor('StorySubmission')->getFullURL(), 'onsubmit' => 'return stbValidateSubmission( "storyboard-agreement" );'), $formBody); }
function elmEasyRefOutput(OutputPage $outputPage, $skin) { global $wgScriptPath; // Options global $wgElmEasyRefAddCSS, $wgElmEasyRefDebugMode, $wgElmEasyRefBodyContentId, $wgElmEasyRefAnimation, $wgElmEasyRefMetrics, $wgElmEasyRefNum_rp, $wgElmEasyRefNum_mt; // Register css for popup field $outputPage->addLink(array('rel' => 'stylesheet', 'type' => 'text/css', 'href' => $wgScriptPath . '/extensions/ElmEasyRef/css/referencefield.css')); // Additonal css if setted if ($wgElmEasyRefAddCSS) { $outputPage->addLink(array('rel' => 'stylesheet', 'type' => 'text/css', 'href' => $wgElmEasyRefAddCSS)); } // Register js-script file $src = '/extensions/ElmEasyRef/js/elmEasyRef'; if (!$wgElmEasyRefDebugMode) { $src .= '-min'; } $outputPage->addScript(Html::linkedScript($wgScriptPath . $src . '.js')); // Settings $settings = ''; if ($wgElmEasyRefDebugMode) { $settings .= 'elmEasyRef.debug = true;'; } if ($wgElmEasyRefBodyContentId) { $settings .= 'elmEasyRef.bodyContentId = ' . Xml::encodeJsVar($wgElmEasyRefBodyContentId) . ';'; } if ($wgElmEasyRefNum_rp) { $settings .= 'elmEasyRef.regRefNum_rp = /' . $wgElmEasyRefNum_rp . '/;'; } if ($wgElmEasyRefNum_mt) { $settings .= 'elmEasyRef.regRefNum_mt = /' . $wgElmEasyRefNum_mt . '/;'; } if ($wgElmEasyRefAnimation) { foreach ($wgElmEasyRefAnimation as $prop => $val) { $settings .= 'elmEasyRef.animation.' . $prop . ' = ' . Xml::encodeJsVar($val) . ';'; } } if ($wgElmEasyRefMetrics) { foreach ($wgElmEasyRefMetrics as $prop => $val) { $settings .= 'elmEasyRef.fieldm.' . $prop . ' = ' . Xml::encodeJsVar($val) . ';'; } } $msg = wfMsgExt('elm-easyref-ref', 'parseinline'); $settings .= 'elmEasyRef.messages.elm_easyref_ref = ' . Xml::encodeJsVar($msg) . ';'; $msg = wfMsgExt('elm-easyref-close', 'parseinline'); $settings .= 'elmEasyRef.messages.elm_easyref_close = ' . Xml::encodeJsVar($msg) . ';'; $outputPage->addInlineScript('addOnloadHook( function() {' . $settings . 'elmEasyRef.prepare();' . '} );'); return true; }
function wfWikimediaMobileAddJs( &$outputPage, &$skin ) { global $wgOut, $wgExtensionAssetsPath, $wgWikimediaMobileVersion; global $wgTitle, $wgRequest, $wgWikimediaMobileUrl; $ns = $wgTitle->getNamespace(); $action = FormatJson::encode( $wgRequest->getVal( 'action', 'view' ) ); $page = FormatJson::encode( $wgTitle->getPrefixedDBkey() ); $mainpage = Title::newMainPage(); $mp = FormatJson::encode( $mainpage ? $mainpage->getPrefixedText() : null ); $url = FormatJson::encode( $wgWikimediaMobileUrl ); $wgOut->addHeadItem( 'mobileredirectvars', Html::inlineScript( "wgNamespaceNumber=$ns;wgAction=$action;wgPageName=$page;wgMainPageTitle=$mp;wgWikimediaMobileUrl=$url;" ) ); $wgOut->addHeadItem( 'mobileredirect', Html::linkedScript( "$wgExtensionAssetsPath/WikimediaMobile/MobileRedirect.js?$wgWikimediaMobileVersion" ) ); return true; }
public static function Inject_JS(OutputPage $out) { global $wgMathJaxJS, $wgMathJaxProcConf, $wgMathJaxLocConf; if (self::$jsInserted === true) { return true; } $userConfig = $wgMathJaxLocConf ?: self::$defaultCustomConfig; $configContents = file_get_contents(__DIR__ . '/../../public' . $userConfig); $out->addScript(\Html::rawElement('script', ['type' => 'text/x-mathjax-config'], "\n" . $configContents . "\n")); $file = $wgMathJaxJS ?: self::$defaultMathJaxPath; $config = $wgMathJaxProcConf ?: self::$defaultMathJaxConfig; $url = $file . '?' . http_build_query(['config' => $config], NULL, '&'); $out->addScript(Html::linkedScript($url)); self::$jsInserted = true; return true; }
public static function getHTML($cur_value, $input_name, $is_mandatory, $is_disabled, $other_args) { global $sfgTabIndex, $sfgFieldNum; global $wgOut; $scripts = array("http://www.openlayers.org/api/OpenLayers.js"); $scriptsHTML = ''; foreach ($scripts as $script) { $scriptsHTML .= Html::linkedScript($script); } $wgOut->addHeadItem($scriptsHTML, $scriptsHTML); $wgOut->addModules('ext.semanticforms.maps'); $parsedCurValue = self::parseCoordinatesString($cur_value); $coordsInput = Html::element('input', array('type' => 'text', 'class' => 'sfCoordsInput', 'name' => $input_name, 'value' => $parsedCurValue, 'size' => 40)); $mapUpdateButton = Html::element('input', array('type' => 'button', 'class' => 'sfUpdateMap', 'value' => wfMessage('sf-maps-setmarker')->parse()), null); // For OpenLayers, doing an address lookup, i.e. a geocode, // will require a separate geocoding address, which may // require a server-side reader to access that API. // For now, let's just not do this, since the Google Maps // input is much more widely used anyway. // @TODO - add this in. //$addressLookupInput = Html::element( 'input', array( 'type' => 'text', 'class' => 'sfAddressInput', 'size' => 40, 'placeholder' => wfMessage( 'sf-maps-enteraddress' )->parse() ), null ); //$addressLookupButton = Html::element( 'input', array( 'type' => 'button', 'class' => 'sfLookUpAddress', 'value' => wfMessage( 'sf-maps-lookupcoordinates' )->parse() ), null ); $mapCanvas = Html::element('div', array('class' => 'sfMapCanvas', 'id' => 'sfMapCanvas' . $sfgFieldNum, 'style' => 'height: 500px; width: 500px;'), null); $fullInputHTML = <<<END <div style="padding-bottom: 10px;"> {$coordsInput} {$mapUpdateButton} </div> END; /* $fullInputHTML = <<<END <div style="padding-bottom: 10px;"> $addressLookupInput $addressLookupButton </div> END; */ $fullInputHTML .= "{$mapCanvas}\n"; $text = Html::rawElement('div', array('class' => 'sfOpenLayersInput'), $fullInputHTML); return $text; }
/** * Renders the storyboard tag. * * @param $input * @param array $args * @param Parser $parser * @param $frame * * @return array */ public static function render($input, array $args, Parser $parser, $frame) { global $wgScriptPath, $wgStylePath, $wgStyleVersion, $wgContLanguageCode; global $egStoryboardScriptPath, $egStoryboardWidth, $egStoryboardHeight; efStoryboardAddJSLocalisation($parser); // TODO: Combine+minfiy JS files, add switch to use combined+minified version $parser->getOutput()->addHeadItem(Html::linkedStyle("{$egStoryboardScriptPath}/storyboard.css?{$wgStyleVersion}") . Html::linkedScript("{$wgStylePath}/common/jquery.min.js?{$wgStyleVersion}") . Html::linkedScript("{$egStoryboardScriptPath}/jquery/jquery.ajaxscroll.js?{$wgStyleVersion}") . Html::linkedScript("{$egStoryboardScriptPath}/tags/Storyboard/storyboard.js?{$wgStyleVersion}") . Html::linkedScript("{$egStoryboardScriptPath}/storyboard.js?{$wgStyleVersion}")); $width = StoryboardUtils::getDimension($args, 'width', $egStoryboardWidth); $height = StoryboardUtils::getDimension($args, 'height', $egStoryboardHeight); $languages = Language::getLanguageNames(); if (array_key_exists('language', $args) && array_key_exists($args['language'], $languages)) { $language = $args['language']; } else { $language = $wgContLanguageCode; } $parser->getOutput()->addHeadItem(Html::inlineScript("var storyboardLanguage = '{$language}';")); $output = Html::element('div', array('class' => 'storyboard', 'style' => "height: {$height}; width: {$width};")); return array($output, 'noparse' => true, 'isHTML' => true); }
/** * @param $context ResourceLoaderContext * @return string */ public function getScript(ResourceLoaderContext $context) { global $IP, $wgLoadScript, $wgLegacyJavaScriptGlobals; $out = file_get_contents("{$IP}/resources/startup.js"); if ($context->getOnly() === 'scripts') { // The core modules: $modules = array('jquery', 'mediawiki'); wfRunHooks('ResourceLoaderGetStartupModules', array(&$modules)); // Get the latest version $version = 0; foreach ($modules as $moduleName) { $version = max($version, $context->getResourceLoader()->getModule($moduleName)->getModifiedTime($context)); } // Build load query for StartupModules $query = array('modules' => ResourceLoader::makePackedModulesString($modules), 'only' => 'scripts', 'lang' => $context->getLanguage(), 'skin' => $context->getSkin(), 'debug' => $context->getDebug() ? 'true' : 'false', 'version' => wfTimestamp(TS_ISO_8601_BASIC, $version)); // Ensure uniform query order ksort($query); // Startup function $configuration = $this->getConfig($context); $registrations = self::getModuleRegistrations($context); $out .= "var startUp = function() {\n" . "\tmw.config = new " . Xml::encodeJsCall('mw.Map', array($wgLegacyJavaScriptGlobals)) . "\n" . "\t{$registrations}\n" . "\t" . Xml::encodeJsCall('mw.config.set', array($configuration)) . "\t" . Xml::encodeJsCall('mw.loader.state', array(array('jquery' => 'ready'))) . "};\n"; // Conditional script injection // Wikia change - begin - @author: wladek // $scriptTag = Html::linkedScript( $wgLoadScript . '?' . wfArrayToCGI( $query ) ); // get jquery from CDN if we have wsl and getJqueryUrl loaded $scriptTagJquery = Xml::encodeJsVar(Html::linkedScript(ResourceLoader::makeLoaderURL($modules, $query['lang'], $query['skin'], null, $query['version'], $context->getDebug(), 'scripts'))); $scriptTagNoJquery = Xml::encodeJsVar(Html::linkedScript(ResourceLoader::makeLoaderURL(array('mediawiki'), $query['lang'], $query['skin'], null, $query['version'], $context->getDebug(), 'scripts'))); $scriptTag = <<<ENDSCRIPT ( (window.wsl && window.getJqueryUrl && window.wgJqueryUrl) ? (wsl.buildScript(window.getJqueryUrl()) + {$scriptTagNoJquery}) : ({$scriptTagJquery}) ) ENDSCRIPT; $scriptTag = new XmlJsCode($scriptTag); // Wikia change - end $out .= "if ( isCompatible() ) {\n" . "\t" . Xml::encodeJsCall('document.write', array($scriptTag)) . "}\n" . "delete isCompatible;"; } return $out; }
/** * @todo Document * @param array|string $modules One or more module names * @param string $only ResourceLoaderModule TYPE_ class constant * @param bool $useESI * @param array $extraQuery Array with extra query parameters to add to each * request. array( param => value ). * @param bool $loadCall If true, output an (asynchronous) mw.loader.load() * call rather than a "<script src='...'>" tag. * @return string The html "<script>", "<link>" and "<style>" tags */ public function makeResourceLoaderLink($modules, $only, $useESI = false, array $extraQuery = array(), $loadCall = false) { $modules = (array) $modules; $links = array('html' => '', 'states' => array()); if (!count($modules)) { return $links; } if (count($modules) > 1) { // Remove duplicate module requests $modules = array_unique($modules); // Sort module names so requests are more uniform sort($modules); if (ResourceLoader::inDebugMode()) { // Recursively call us for every item foreach ($modules as $name) { $link = $this->makeResourceLoaderLink($name, $only, $useESI); $links['html'] .= $link['html']; $links['states'] += $link['states']; } return $links; } } if (!is_null($this->mTarget)) { $extraQuery['target'] = $this->mTarget; } // Create keyed-by-source and then keyed-by-group list of module objects from modules list $sortedModules = array(); $resourceLoader = $this->getResourceLoader(); $resourceLoaderUseESI = $this->getConfig()->get('ResourceLoaderUseESI'); foreach ($modules as $name) { $module = $resourceLoader->getModule($name); # Check that we're allowed to include this module on this page if (!$module || $module->getOrigin() > $this->getAllowedModules(ResourceLoaderModule::TYPE_SCRIPTS) && $only == ResourceLoaderModule::TYPE_SCRIPTS || $module->getOrigin() > $this->getAllowedModules(ResourceLoaderModule::TYPE_STYLES) && $only == ResourceLoaderModule::TYPE_STYLES || $module->getOrigin() > $this->getAllowedModules(ResourceLoaderModule::TYPE_COMBINED) && $only == ResourceLoaderModule::TYPE_COMBINED || $this->mTarget && !in_array($this->mTarget, $module->getTargets())) { continue; } $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module; } foreach ($sortedModules as $source => $groups) { foreach ($groups as $group => $grpModules) { // Special handling for user-specific groups $user = null; if (($group === 'user' || $group === 'private') && $this->getUser()->isLoggedIn()) { $user = $this->getUser()->getName(); } // Create a fake request based on the one we are about to make so modules return // correct timestamp and emptiness data $query = ResourceLoader::makeLoaderQuery(array(), $this->getLanguage()->getCode(), $this->getSkin()->getSkinName(), $user, null, ResourceLoader::inDebugMode(), $only === ResourceLoaderModule::TYPE_COMBINED ? null : $only, $this->isPrintable(), $this->getRequest()->getBool('handheld'), $extraQuery); $context = new ResourceLoaderContext($resourceLoader, new FauxRequest($query)); // Extract modules that know they're empty and see if we have one or more // raw modules $isRaw = false; foreach ($grpModules as $key => $module) { // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857) // If we're only getting the styles, we don't need to do anything for empty modules. if ($module->isKnownEmpty($context)) { unset($grpModules[$key]); if ($only !== ResourceLoaderModule::TYPE_STYLES) { $links['states'][$key] = 'ready'; } } $isRaw |= $module->isRaw(); } // If there are no non-empty modules, skip this group if (count($grpModules) === 0) { continue; } // Inline private modules. These can't be loaded through load.php for security // reasons, see bug 34907. Note that these modules should be loaded from // getHeadScripts() before the first loader call. Otherwise other modules can't // properly use them as dependencies (bug 30914) if ($group === 'private') { if ($only == ResourceLoaderModule::TYPE_STYLES) { $links['html'] .= Html::inlineStyle($resourceLoader->makeModuleResponse($context, $grpModules)); } else { $links['html'] .= ResourceLoader::makeInlineScript($resourceLoader->makeModuleResponse($context, $grpModules)); } $links['html'] .= "\n"; continue; } // Special handling for the user group; because users might change their stuff // on-wiki like user pages, or user preferences; we need to find the highest // timestamp of these user-changeable modules so we can ensure cache misses on change // This should NOT be done for the site group (bug 27564) because anons get that too // and we shouldn't be putting timestamps in Squid-cached HTML $version = null; if ($group === 'user') { $query['version'] = $resourceLoader->getCombinedVersion($context, array_keys($grpModules)); } $query['modules'] = ResourceLoader::makePackedModulesString(array_keys($grpModules)); $moduleContext = new ResourceLoaderContext($resourceLoader, new FauxRequest($query)); $url = $resourceLoader->createLoaderURL($source, $moduleContext, $extraQuery); if ($useESI && $resourceLoaderUseESI) { $esi = Xml::element('esi:include', array('src' => $url)); if ($only == ResourceLoaderModule::TYPE_STYLES) { $link = Html::inlineStyle($esi); } else { $link = Html::inlineScript($esi); } } else { // Automatically select style/script elements if ($only === ResourceLoaderModule::TYPE_STYLES) { $link = Html::linkedStyle($url); } elseif ($loadCall) { $link = ResourceLoader::makeInlineScript(Xml::encodeJsCall('mw.loader.load', array($url, 'text/javascript', true))); } else { $link = Html::linkedScript($url); if (!$context->getRaw() && !$isRaw) { // Wrap only=script / only=combined requests in a conditional as // browsers not supported by the startup module would unconditionally // execute this module. Otherwise users will get "ReferenceError: mw is // undefined" or "jQuery is undefined" from e.g. a "site" module. $link = ResourceLoader::makeInlineScript(Xml::encodeJsCall('document.write', array($link))); } // For modules requested directly in the html via <link> or <script>, // tell mw.loader they are being loading to prevent duplicate requests. foreach ($grpModules as $key => $module) { // Don't output state=loading for the startup module.. if ($key !== 'startup') { $links['states'][$key] = 'loading'; } } } } if ($group == 'noscript') { $links['html'] .= Html::rawElement('noscript', array(), $link) . "\n"; } else { $links['html'] .= $link . "\n"; } } } return $links; }
/** * Add a JavaScript file out of skins/common, or a given relative path. * Internal use only. Use OutputPage::addModules() if possible. * * @param string $file Filename in skins/common or complete on-server path * (/foo/bar.js) * @param string $version Style version of the file. Defaults to $wgStyleVersion */ public function addScriptFile($file, $version = null) { // See if $file parameter is an absolute URL or begins with a slash if (substr($file, 0, 1) == '/' || preg_match('#^[a-z]*://#i', $file)) { $path = $file; } else { $path = $this->getConfig()->get('StylePath') . "/common/{$file}"; } if (is_null($version)) { $version = $this->getConfig()->get('StyleVersion'); } $this->addScript(Html::linkedScript(wfAppendQuery($path, $version))); }
/** * @return string */ public function getJQuery() { return Html::linkedScript("../resources/lib/jquery/jquery.js"); }
/** * Loads the needed JavaScript. * Takes care of non-RL compatibility. * * @since 0.1 * * @param array $parameters */ protected function loadJs( array $parameters ) { static $loadedJs = false; if ( $loadedJs ) { return; } $loadedJs = true; $this->addJSWikiData( $parameters ); // For backward compatibility with MW < 1.17. if ( is_callable( array( $this->parser->getOutput(), 'addModules' ) ) ) { $this->parser->getOutput()->addModules( 'ext.ratings.stars' ); } else { global $egRatingsScriptPath, $wgStylePath, $wgStyleVersion; $this->addJSLocalisation(); $this->parser->getOutput()->addHeadItem( Html::linkedScript( "$wgStylePath/common/jquery.min.js?$wgStyleVersion" ), 'jQuery' ); Ratings::loadJs( $this->parser ); $this->parser->getOutput()->addHeadItem( Html::linkedScript( $egRatingsScriptPath . '/starrating/star-rating/jquery.rating.js' ) . Html::linkedStyle( $egRatingsScriptPath . '/starrating/star-rating/jquery.rating.css' ), 'ext.ratings.stars.jquery' ); $this->parser->getOutput()->addHeadItem( Html::linkedScript( $egRatingsScriptPath . '/starrating/ext.ratings.stars.js' ), 'ext.ratings.stars' ); } }
/** * Loads the needed JavaScript. * Takes care of non-RL compatibility. * * @since 0.1 */ protected function loadJs() { static $loadedJs = false; if ($loadedJs) { return; } $loadedJs = true; $this->addJSWikiData(); // For backward compatibility with MW < 1.17. if (is_callable(array($this->parser->getOutput(), 'addModules'))) { $this->parser->getOutput()->addModules('ext.incwp'); } else { global $egIncWPScriptPath, $wgStylePath, $wgStyleVersion; $this->addJSLocalisation(); $this->parser->getOutput()->addHeadItem(Html::linkedScript("{$wgStylePath}/common/jquery.min.js?{$wgStyleVersion}"), 'jQuery'); $this->parser->getOutput()->addHeadItem(Html::linkedScript($egIncWPScriptPath . '/ext.incwp.js'), 'ext.incwp'); } }
/** * @see MapsMappingService::getDependencies * * @return array */ protected function getDependencies() { global $wgLang; global $egMapsStyleVersion, $egMapsScriptPath; $languageCode = self::getMappedLanguageCode($wgLang->getCode()); return array(Html::linkedScript("http://maps.google.com/maps/api/js?sensor=false&language={$languageCode}")); }
/** * @param $context ResourceLoaderContext * @return string */ public function getScript(ResourceLoaderContext $context) { global $IP, $wgLoadScript, $wgLegacyJavaScriptGlobals; $out = file_get_contents("{$IP}/resources/startup.js"); if ($context->getOnly() === 'scripts') { // The core modules: $moduleNames = array('jquery', 'mediawiki'); wfRunHooks('ResourceLoaderGetStartupModules', array(&$moduleNames)); // Get the latest version $loader = $context->getResourceLoader(); $version = 0; foreach ($moduleNames as $moduleName) { $version = max($version, $loader->getModule($moduleName)->getModifiedTime($context)); } // Build load query for StartupModules $query = array('modules' => ResourceLoader::makePackedModulesString($moduleNames), 'only' => 'scripts', 'lang' => $context->getLanguage(), 'skin' => $context->getSkin(), 'debug' => $context->getDebug() ? 'true' : 'false', 'version' => wfTimestamp(TS_ISO_8601_BASIC, $version)); // Ensure uniform query order ksort($query); // Startup function $configuration = $this->getConfig($context); $registrations = self::getModuleRegistrations($context); $registrations = str_replace("\n", "\n\t", trim($registrations)); // fix indentation $out .= "var startUp = function() {\n" . "\tmw.config = new " . Xml::encodeJsCall('mw.Map', array($wgLegacyJavaScriptGlobals)) . "\n" . "\t{$registrations}\n" . "\t" . Xml::encodeJsCall('mw.config.set', array($configuration)) . "};\n"; // Conditional script injection $scriptTag = Html::linkedScript($wgLoadScript . '?' . wfArrayToCGI($query)); $out .= "if ( isCompatible() ) {\n" . "\t" . Xml::encodeJsCall('document.write', array($scriptTag)) . "}\n" . "delete isCompatible;"; } return $out; }
/** * Emit messages from the queue as: * - JS object in <head> section of the page (INLINE mode) * - JS requested via <script> tag at the bottom of the page (EXTERNAL mode) */ public function onWikiaSkinTopScripts(&$vars, &$scripts, $skin) { $this->app->wf->ProfileIn(__METHOD__); $this->log(__METHOD__, 'preparing list of inline messages...'); // get items to be rendered as a variable in <head> section $packages = $this->queue['inline']; if (!empty($packages)) { $vars['wgMessages'] = $this->getPackages($packages, false); } // messages cache buster used by JSMessages (BugId:6324) $vars['wgJSMessagesCB'] = $this->helper->getMessagesCacheBuster(); $this->log(__METHOD__, 'preparing list of external packages...'); $url = $this->getExternalPackagesUrl(); if ($url != "") { // request a script $this->app->wg->Out->addScript(Html::linkedScript($url)); } $this->app->wf->ProfileOut(__METHOD__); return true; }
/** * Build a script tag to load.php URL using OutputPage instance to get most of the required information * * @param OutputPage $out * @param string|array $modules Module names * @param string $only * @param bool|string $user User name (true to get it from OutputPage) * @param string $version * @param array $extraQuery * @return string */ public static function makeCustomLink(OutputPage $out, $modules, $only = ResourceLoaderModule::TYPE_COMBINED, $user = false, $version = null, $extraQuery = array()) { $url = ResourceLoader::makeCustomURL($out, $modules, $only, $user, $version, $extraQuery); if ($only === ResourceLoaderModule::TYPE_STYLES) { $link = Html::linkedStyle($url); } else { $link = Html::linkedScript($url); } return $link; }
protected function getDependencies() { $leafletPath = $GLOBALS['wgScriptPath'] . '/extensions/Maps/includes/services/Leaflet/leaflet'; return array(Html::linkedStyle("{$leafletPath}/leaflet.css"), '<!--[if lte IE 8]>' . Html::linkedStyle("{$leafletPath}/leaflet.ie.css") . '<![endif]-->', Html::linkedScript("{$leafletPath}/leaflet.js")); }
/** * TODO: Document * @param $skin Skin * @param $modules Array/string with the module name * @param $only String ResourceLoaderModule TYPE_ class constant * @param $useESI boolean * @return string html <script> and <style> tags */ protected function makeResourceLoaderLink(Skin $skin, $modules, $only, $useESI = false) { global $wgLoadScript, $wgResourceLoaderUseESI; // Lazy-load ResourceLoader // TODO: Should this be a static function of ResourceLoader instead? $baseQuery = array('lang' => $this->getContext()->getLang()->getCode(), 'debug' => ResourceLoader::inDebugMode() ? 'true' : 'false', 'skin' => $skin->getSkinName(), 'only' => $only); // Propagate printable and handheld parameters if present if ($this->isPrintable()) { $baseQuery['printable'] = 1; } if ($this->getRequest()->getBool('handheld')) { $baseQuery['handheld'] = 1; } if (!count($modules)) { return ''; } if (count($modules) > 1) { // Remove duplicate module requests $modules = array_unique((array) $modules); // Sort module names so requests are more uniform sort($modules); if (ResourceLoader::inDebugMode()) { // Recursively call us for every item $links = ''; foreach ($modules as $name) { $links .= $this->makeResourceLoaderLink($skin, $name, $only, $useESI); } return $links; } } // Create keyed-by-group list of module objects from modules list $groups = array(); $resourceLoader = $this->getResourceLoader(); foreach ((array) $modules as $name) { $module = $resourceLoader->getModule($name); # Check that we're allowed to include this module on this page if (!$module || $module->getOrigin() > $this->getAllowedModules(ResourceLoaderModule::TYPE_SCRIPTS) && $only == ResourceLoaderModule::TYPE_SCRIPTS || $module->getOrigin() > $this->getAllowedModules(ResourceLoaderModule::TYPE_STYLES) && $only == ResourceLoaderModule::TYPE_STYLES) { continue; } $group = $module->getGroup(); if (!isset($groups[$group])) { $groups[$group] = array(); } $groups[$group][$name] = $module; } $links = ''; foreach ($groups as $group => $modules) { $query = $baseQuery; // Special handling for user-specific groups if (($group === 'user' || $group === 'private') && $this->getUser()->isLoggedIn()) { $query['user'] = $this->getUser()->getName(); } // Create a fake request based on the one we are about to make so modules return // correct timestamp and emptiness data $context = new ResourceLoaderContext($resourceLoader, new FauxRequest($query)); // Drop modules that know they're empty foreach ($modules as $key => $module) { if ($module->isKnownEmpty($context)) { unset($modules[$key]); } } // If there are no modules left, skip this group if ($modules === array()) { continue; } $query['modules'] = ResourceLoader::makePackedModulesString(array_keys($modules)); // Inline private modules. These can't be loaded through load.php for security // reasons, see bug 34907. Note that these modules should be loaded from // getHeadScripts() before the first loader call. Otherwise other modules can't // properly use them as dependencies (bug 30914) if ($group === 'private') { if ($only == ResourceLoaderModule::TYPE_STYLES) { $links .= Html::inlineStyle($resourceLoader->makeModuleResponse($context, $modules)); } else { $links .= Html::inlineScript(ResourceLoader::makeLoaderConditionalScript($resourceLoader->makeModuleResponse($context, $modules))); } continue; } // Special handling for the user group; because users might change their stuff // on-wiki like user pages, or user preferences; we need to find the highest // timestamp of these user-changable modules so we can ensure cache misses on change // This should NOT be done for the site group (bug 27564) because anons get that too // and we shouldn't be putting timestamps in Squid-cached HTML if ($group === 'user') { // Get the maximum timestamp $timestamp = 1; foreach ($modules as $module) { $timestamp = max($timestamp, $module->getModifiedTime($context)); } // Add a version parameter so cache will break when things change $query['version'] = wfTimestamp(TS_ISO_8601_BASIC, $timestamp); } // Make queries uniform in order ksort($query); $url = wfAppendQuery($wgLoadScript, $query); // Prevent the IE6 extension check from being triggered (bug 28840) // by appending a character that's invalid in Windows extensions ('*') $url .= '&*'; if ($useESI && $wgResourceLoaderUseESI) { $esi = Xml::element('esi:include', array('src' => $url)); if ($only == ResourceLoaderModule::TYPE_STYLES) { $link = Html::inlineStyle($esi); } else { $link = Html::inlineScript($esi); } } else { // Automatically select style/script elements if ($only === ResourceLoaderModule::TYPE_STYLES) { $link = Html::linkedStyle($url); } else { $link = Html::linkedScript($url); } } if ($group == 'noscript') { $links .= Html::rawElement('noscript', array(), $link) . "\n"; } else { $links .= $link . "\n"; } } return $links; }