function redircite_render($input, $args, &$parser) {
	// Generate HTML code and add it to the $redirciteMarkerList array
	// Add "xx-redircite-marker-NUMBER-redircite-xx" to the output,
	// which will be translated to the HTML stored in $redirciteMarkerList by
	// redircite_afterTidy()
	global $redirciteMarkerList;
	# Verify that $input is a valid title
	$inputTitle = Title::newFromText($input);
	if(!$inputTitle)
		return $input;
	$link1 = $parser->recursiveTagParse("[[$input]]");
	$title1 = Title::newFromText($input);
	if(!$title1->exists()) // Page doesn't exist
		// Just output a normal (red) link
		return $link1;
	$articleObj = new Article($title1);
	$title2 = Title::newFromRedirect($articleObj->fetchContent());
	if(!$title2) // Page is not a redirect
		// Just output a normal link
		return $link1;
	
	$link2 = $parser->recursiveTagParse("[[{$title2->getPrefixedText()}|$input]]");
	
	$marker = "xx-redircite-marker-" . count($redirciteMarkerList) . "-redircite-xx";
	$onmouseout = 'this.firstChild.innerHTML = "'. Xml::escapeJsString($input) . '";';
	$onmouseover = 'this.firstChild.innerHTML = "' . Xml::escapeJsString($title2->getPrefixedText()) . '";';
	return Xml::tags('span', array(
					'onmouseout' => $onmouseout,
					'onmouseover' => $onmouseover),
					$link2);
}
Example #2
0
 /**
  * Encode a variable of unknown type to JavaScript.
  * Arrays are converted to JS arrays, objects are converted to JS associative
  * arrays (objects). So cast your PHP associative arrays to objects before
  * passing them to here.
  * 
  * This is a copy of
  * @see Xml::encodeJsVar
  * which fixes incorrect behaviour with floats.
  * 
  * @since 0.7.1
  * 
  * @param mixed $value
  *
  * @return tring
  */
 public static function encodeJsVar($value)
 {
     if (is_bool($value)) {
         $s = $value ? 'true' : 'false';
     } elseif (is_null($value)) {
         $s = 'null';
     } elseif (is_int($value) || is_float($value)) {
         $s = $value;
     } elseif (is_array($value) && array_keys($value) === range(0, count($value) - 1) || count($value) == 0) {
         $s = '[';
         foreach ($value as $elt) {
             if ($s != '[') {
                 $s .= ', ';
             }
             $s .= self::encodeJsVar($elt);
         }
         $s .= ']';
     } elseif (is_object($value) || is_array($value)) {
         // Objects and associative arrays
         $s = '{';
         foreach ((array) $value as $name => $elt) {
             if ($s != '{') {
                 $s .= ', ';
             }
             $s .= '"' . Xml::escapeJsString($name) . '": ' . self::encodeJsVar($elt);
         }
         $s .= '}';
     } else {
         $s = '"' . Xml::escapeJsString($value) . '"';
     }
     return $s;
 }
 /**
  * AjaxAddScript hook
  * Adds scripts
  */
 public static function addResources($out)
 {
     global $wgExtensionAssetsPath, $wgJsMimeType;
     global $wgUsabilityInitiativeResourceMode;
     global $wgEnableJS2system, $wgEditToolbarRunTests;
     global $wgStyleVersion;
     wfRunHooks('UsabilityInitiativeLoadModules');
     if (!self::$doOutput) {
         return true;
     }
     // Default to raw
     $mode = $wgUsabilityInitiativeResourceMode;
     // Just an alias
     if (!isset(self::$scriptFiles['base_sets'][$mode])) {
         $mode = 'raw';
     }
     // Include base-set of scripts
     self::$scripts = array_merge(self::$scriptFiles['base_sets'][$mode], self::$scriptFiles['modules'][$mode], self::$scripts);
     // Provide enough support to make things work, even when js2 is not
     // in use (eventually it will be standard, but right now it's not)
     if (!$wgEnableJS2system) {
         $out->includeJQuery();
     }
     // Include base-set of styles
     self::$styles = array_merge(self::$styleFiles['base_sets'][$mode], self::$styles);
     if ($wgEditToolbarRunTests) {
         // Include client side tests
         self::$scripts = array_merge(self::$scripts, self::$scriptFiles['tests']);
     }
     // Loops over each script
     foreach (self::$scripts as $script) {
         // Add javascript to document
         if ($script['src'][0] == '/') {
             // Path is relative to $wgScriptPath
             global $wgScriptPath;
             $src = "{$wgScriptPath}{$script['src']}";
         } else {
             // Path is relative to $wgExtensionAssetsPath
             $src = "{$wgExtensionAssetsPath}/UsabilityInitiative/{$script['src']}";
         }
         $version = isset($script['version']) ? $script['version'] : $wgStyleVersion;
         $out->addScriptFile($src, $version);
     }
     // Transforms messages into javascript object members
     foreach (self::$messages as $i => $message) {
         $escapedMessageValue = Xml::escapeJsString(wfMsg($message));
         $escapedMessageKey = Xml::escapeJsString($message);
         self::$messages[$i] = "'{$escapedMessageKey}':'{$escapedMessageValue}'";
     }
     // Add javascript to document
     if (count(self::$messages) > 0) {
         $out->addScript(Xml::tags('script', array('type' => $wgJsMimeType), 'mw.usability.addMessages({' . implode(',', self::$messages) . '});'));
     }
     // Loops over each style
     foreach (self::$styles as $style) {
         // Add css for various styles
         $out->addLink(array('rel' => 'stylesheet', 'type' => 'text/css', 'href' => $wgExtensionAssetsPath . "/UsabilityInitiative/" . "{$style['src']}?{$style['version']}"));
     }
     return true;
 }
Example #4
0
 /**
  * Static setup method for input type "menuselect".
  * Adds the Javascript code and css used by all menuselects.
  */
 private static function setup()
 {
     global $wgOut, $wgLang;
     static $hasRun = false;
     if (!$hasRun) {
         $hasRun = true;
         // set localized messages (use MW i18n, not jQuery i18n)
         $jstext = "jQuery(function(){mw.loader.using('jquery.ui.datepicker', function(){\n" . "\tjQuery.datepicker.regional['wiki'] = {\n" . "\t\tcloseText: '" . Xml::escapeJsString(wfMsg('semanticformsinputs-close')) . "',\n" . "\t\tprevText: '" . Xml::escapeJsString(wfMsg('semanticformsinputs-prev')) . "',\n" . "\t\tnextText: '" . Xml::escapeJsString(wfMsg('semanticformsinputs-next')) . "',\n" . "\t\tcurrentText: '" . Xml::escapeJsString(wfMsg('semanticformsinputs-today')) . "',\n" . "\t\tmonthNames: ['" . Xml::escapeJsString(wfMsg('january')) . "','" . Xml::escapeJsString(wfMsg('february')) . "','" . Xml::escapeJsString(wfMsg('march')) . "','" . Xml::escapeJsString(wfMsg('april')) . "','" . Xml::escapeJsString(wfMsg('may_long')) . "','" . Xml::escapeJsString(wfMsg('june')) . "','" . Xml::escapeJsString(wfMsg('july')) . "','" . Xml::escapeJsString(wfMsg('august')) . "','" . Xml::escapeJsString(wfMsg('september')) . "','" . Xml::escapeJsString(wfMsg('october')) . "','" . Xml::escapeJsString(wfMsg('november')) . "','" . Xml::escapeJsString(wfMsg('december')) . "'],\n" . "\t\tmonthNamesShort: ['" . Xml::escapeJsString(wfMsg('jan')) . "','" . Xml::escapeJsString(wfMsg('feb')) . "','" . Xml::escapeJsString(wfMsg('mar')) . "','" . Xml::escapeJsString(wfMsg('apr')) . "','" . Xml::escapeJsString(wfMsg('may')) . "','" . Xml::escapeJsString(wfMsg('jun')) . "','" . Xml::escapeJsString(wfMsg('jul')) . "','" . Xml::escapeJsString(wfMsg('aug')) . "','" . Xml::escapeJsString(wfMsg('sep')) . "','" . Xml::escapeJsString(wfMsg('oct')) . "','" . Xml::escapeJsString(wfMsg('nov')) . "','" . Xml::escapeJsString(wfMsg('dec')) . "'],\n" . "\t\tdayNames: ['" . Xml::escapeJsString(wfMsg('sunday')) . "','" . Xml::escapeJsString(wfMsg('monday')) . "','" . Xml::escapeJsString(wfMsg('tuesday')) . "','" . Xml::escapeJsString(wfMsg('wednesday')) . "','" . Xml::escapeJsString(wfMsg('thursday')) . "','" . Xml::escapeJsString(wfMsg('friday')) . "','" . Xml::escapeJsString(wfMsg('saturday')) . "'],\n" . "\t\tdayNamesShort: ['" . Xml::escapeJsString(wfMsg('sun')) . "','" . Xml::escapeJsString(wfMsg('mon')) . "','" . Xml::escapeJsString(wfMsg('tue')) . "','" . Xml::escapeJsString(wfMsg('wed')) . "','" . Xml::escapeJsString(wfMsg('thu')) . "','" . Xml::escapeJsString(wfMsg('fri')) . "','" . Xml::escapeJsString(wfMsg('sat')) . "'],\n" . "\t\tdayNamesMin: ['" . Xml::escapeJsString($wgLang->firstChar(wfMsg('sun'))) . "','" . Xml::escapeJsString($wgLang->firstChar(wfMsg('mon'))) . "','" . Xml::escapeJsString($wgLang->firstChar(wfMsg('tue'))) . "','" . Xml::escapeJsString($wgLang->firstChar(wfMsg('wed'))) . "','" . Xml::escapeJsString($wgLang->firstChar(wfMsg('thu'))) . "','" . Xml::escapeJsString($wgLang->firstChar(wfMsg('fri'))) . "','" . Xml::escapeJsString($wgLang->firstChar(wfMsg('sat'))) . "'],\n" . "\t\tweekHeader: '',\n" . "\t\tdateFormat: '" . Xml::escapeJsString(wfMsg('semanticformsinputs-dateformatshort')) . "',\n" . "\t\tfirstDay: '" . Xml::escapeJsString(wfMsg('semanticformsinputs-firstdayofweek')) . "',\n" . "\t\tisRTL: " . ($wgLang->isRTL() ? "true" : "false") . ",\n" . "\t\tshowMonthAfterYear: false,\n" . "\t\tyearSuffix: ''};\n" . "\tjQuery.datepicker.setDefaults(jQuery.datepicker.regional['wiki']);\n" . "});});\n";
         $wgOut->addScript(Html::inlineScript($jstext));
     }
 }
    /**
     * @see MapsBaseMap::addSpecificMapHTML()
     *
     */
    public function addSpecificMapHTML(Parser $parser)
    {
        global $egValidatorErrorLevel;
        MapsGoogleMaps::addOverlayOutput($this->output, $this->mapName, $this->overlays, $this->controls);
        if ($egValidatorErrorLevel >= Validator_ERRORS_WARN) {
            $couldNotGeocodeMsg = Xml::escapeJsString(wfMsg('ukgeocoding_couldNotGeocode'));
            $showErrorJs = "document.getElementById( '{$this->mapName}_errors' ).innerHTML = '{$couldNotGeocodeMsg}';";
        } else {
            $showErrorJs = '';
        }
        $this->output .= Html::element('div', array('id' => $this->mapName, 'style' => "width: {$this->width}; height: {$this->height}; background-color: #cccccc;"), wfMsg('maps-loading-map')) . "<div id='{$this->mapName}_errors'></div>";
        $parser->getOutput()->addHeadItem(Html::inlineScript(<<<EOT
\$(function() {
\tvar map = initializeGoogleMap('{$this->mapName}', 
\t\t{
\t\tlat: 0,
\t\tlon: 0,
\t\tzoom: {$this->zoom},
\t\ttype: {$this->type},
\t\ttypes: [{$this->types}],
\t\tcontrols: [{$this->controls}],
\t\tscrollWheelZoom: {$this->autozoom}
\t\t},
\t\t[]
\t);
\tvar localSearch = new GlocalSearch();
\tfunction usePointFromPostcode( marker, callbackFunction ) {
\t\tlocalSearch.setSearchCompleteCallback( null,
\t\t\tfunction() {
\t\t\t\tif ( localSearch.results[0] ) {    
\t\t\t\t\tcallbackFunction(new GLatLng(localSearch.results[0].lat, localSearch.results[0].lng), marker);
\t\t\t\t} else {
\t\t\t\t\t{$showErrorJs}
\t\t\t\t}
\t\t\t}
\t\t);
\t\tlocalSearch.execute(marker.location + ", UK");
\t}
\tfunction updateGoogleMap(point, marker) {
\t\tmap.addOverlay(createGMarker(point, marker.title, marker.label, marker.icon));
\t\tbounds.extend(point);
\t\tmap.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
\t\tif({$this->zoom}!=null) map.setZoom({$this->zoom});
\t}
\tvar markers = [{$this->markerString}];
\tvar bounds = new GLatLngBounds();
\tfor(i in markers) {
\t\tusePointFromPostcode(markers[i], updateGoogleMap);
\t}
});\t\t\t\t
EOT
));
    }
 static function getJsObject($method_name)
 {
     $args = func_get_args();
     array_shift($args);
     // remove $method_name from $args
     $result = '{ ';
     $firstElem = true;
     foreach ($args as &$arg) {
         if ($firstElem) {
             $firstElem = false;
         } else {
             $result .= ', ';
         }
         $result .= $arg . ': "' . Xml::escapeJsString(call_user_func(array('self', $method_name), $arg)) . '"';
     }
     $result .= ' }';
     return $result;
 }
Example #7
0
function fnWoopraJavascript($out)
{
        global $wgUser, $wgWoopraSitekey;
 
		if ( $wgWoopraSitekey === false )
			return true;
 
        $html = "<script type=\"text/javascript\">\r\n";
        $html .= "woopra_id = '" . Xml::escapeJsString( $wgWoopraSitekey ) . "';\r\n";
 
        if (!$wgUser->isAnon())
        {
                $html .= "var woopra_array = new Array();\r\n";
                $html .= "woopra_array['name'] = '" .  Xml::escapeJsString( $wgUser->getRealName() ) . "';\r\n";
                $html .= "woopra_array['Email'] = '" . Xml::escapeJsString( $wgUser->getEmail() ) . "';\r\n";
                // Add custom tracking code here!
        }
        $html .= "</script>\r\n";
        $html .= "<script type=\"text/javascript\" src=\"http://static.woopra.com/js/woopra.js\"></script>";
 
        $out->addScript($html);
        return true;
}
Example #8
0
 /**
  * If this request is a redirect view, send "redirected from" subtitle to
  * the output. Returns true if the header was needed, false if this is not
  * a redirect view. Handles both local and remote redirects.
  *
  * @return boolean
  */
 public function showRedirectedFromHeader()
 {
     global $wgRedirectSources;
     $outputPage = $this->getContext()->getOutput();
     $rdfrom = $this->getContext()->getRequest()->getVal('rdfrom');
     if (isset($this->mRedirectedFrom)) {
         // This is an internally redirected page view.
         // We'll need a backlink to the source page for navigation.
         if (wfRunHooks('ArticleViewRedirect', array(&$this))) {
             $redir = Linker::linkKnown($this->mRedirectedFrom, null, array(), array('redirect' => 'no'));
             $outputPage->addSubtitle(wfMessage('redirectedfrom')->rawParams($redir));
             // Set the fragment if one was specified in the redirect
             if (strval($this->getTitle()->getFragment()) != '') {
                 $fragment = Xml::escapeJsString($this->getTitle()->getFragmentForURL());
                 $outputPage->addInlineScript("redirectToFragment(\"{$fragment}\");");
             }
             // Add a <link rel="canonical"> tag
             $outputPage->addLink(array('rel' => 'canonical', 'href' => $this->getTitle()->getLocalURL()));
             // Tell the output object that the user arrived at this article through a redirect
             $outputPage->setRedirectedFrom($this->mRedirectedFrom);
             return true;
         }
     } elseif ($rdfrom) {
         // This is an externally redirected view, from some other wiki.
         // If it was reported from a trusted site, supply a backlink.
         if ($wgRedirectSources && preg_match($wgRedirectSources, $rdfrom)) {
             $redir = Linker::makeExternalLink($rdfrom, $rdfrom);
             $outputPage->addSubtitle(wfMessage('redirectedfrom')->rawParams($redir));
             return true;
         }
     }
     return false;
 }
Example #9
0
 private function doAddJsVar($key, $value)
 {
     global $wgOut;
     $wgOut->addScript('<script type="text/javascript"> var ' . $key . '="' . Xml::escapeJsString($value) . '"; </script>');
 }
 /**
  * Returns a string with a HTML represenation of the given page.
  * $info must be an associative array, containing at least a Title object under the 'title' key.
  * @param $title Title
  * @param $cat Category
  * @param $children int
  * @param $loadchildren bool
  * @return string
  */
 function renderNodeInfo($title, $cat, $children = 0, $loadchildren = false)
 {
     static $uniq = 0;
     $mode = $this->getOption('mode');
     $load = false;
     if ($children > 0 && $loadchildren) {
         $uniq += 1;
         $load = 'ct-' . $uniq . '-' . mt_rand(1, 100000);
     }
     $ns = $title->getNamespace();
     $key = $title->getDBkey();
     # $trans = $title->getLocalizedText();
     $trans = '';
     # place holder for when translated titles are available
     $hideprefix = $this->getOption('hideprefix');
     if ($hideprefix == CT_HIDEPREFIX_ALWAYS) {
         $hideprefix = true;
     } elseif ($hideprefix == CT_HIDEPREFIX_AUTO) {
         $hideprefix = $mode == CT_MODE_CATEGORIES;
     } elseif ($hideprefix == CT_HIDEPREFIX_CATEGORIES) {
         $hideprefix = $ns == NS_CATEGORY;
     } else {
         $hideprefix = true;
     }
     # when showing only categories, omit namespace in label unless we explicitely defined the configuration setting
     # patch contributed by Manuel Schneider <*****@*****.**>, Bug 8011
     if ($hideprefix) {
         $label = htmlspecialchars($title->getText());
     } else {
         $label = htmlspecialchars($title->getPrefixedText());
     }
     if ($trans && $trans != $label) {
         $label .= ' ' . Xml::element('i', array('class' => 'translation'), $trans);
     }
     $labelClass = 'CategoryTreeLabel ' . ' CategoryTreeLabelNs' . $ns;
     if (!$title->getArticleId()) {
         $labelClass .= ' new';
         $wikiLink = $title->getLocalURL('action=edit&redlink=1');
     } else {
         $wikiLink = $title->getLocalURL();
     }
     if ($ns == NS_CATEGORY) {
         $labelClass .= ' CategoryTreeLabelCategory';
     } else {
         $labelClass .= ' CategoryTreeLabelPage';
     }
     if ($ns % 2 > 0) {
         $labelClass .= ' CategoryTreeLabelTalk';
     }
     $count = false;
     $s = '';
     # NOTE: things in CategoryTree.js rely on the exact order of tags!
     #      Specifically, the CategoryTreeChildren div must be the first
     #      sibling with nodeName = DIV of the grandparent of the expland link.
     $s .= Xml::openElement('div', array('class' => 'CategoryTreeSection'));
     $s .= Xml::openElement('div', array('class' => 'CategoryTreeItem'));
     $attr = array('class' => 'CategoryTreeBullet');
     # Get counts, with conversion to integer so === works
     # Note: $allCount is the total number of cat members,
     # not the count of how many members are normal pages.
     $allCount = $cat ? intval($cat->getPageCount()) : 0;
     $subcatCount = $cat ? intval($cat->getSubcatCount()) : 0;
     $fileCount = $cat ? intval($cat->getFileCount()) : 0;
     if ($ns == NS_CATEGORY) {
         if ($cat) {
             if ($mode == CT_MODE_CATEGORIES) {
                 $count = $subcatCount;
             } elseif ($mode == CT_MODE_PAGES) {
                 $count = $allCount - $fileCount;
             } else {
                 $count = $allCount;
             }
         }
         if ($count === 0) {
             $bullet = wfMsgNoTrans('categorytree-empty-bullet') . ' ';
             $attr['class'] = 'CategoryTreeEmptyBullet';
         } else {
             $linkattr = array();
             if ($load) {
                 $linkattr['id'] = $load;
             }
             $linkattr['class'] = "CategoryTreeToggle";
             $linkattr['style'] = 'display: none;';
             // Unhidden by JS
             $linkattr['data-ct-title'] = $key;
             if ($children == 0 || $loadchildren) {
                 $tag = 'span';
                 $txt = wfMsgNoTrans('categorytree-expand-bullet');
                 # Don't load this message for ajax requests, so that we don't have to initialise $wgLang
                 $linkattr['title'] = $this->mIsAjaxRequest ? '##LOAD##' : wfMsgNoTrans('categorytree-expand');
                 $linkattr['data-ct-state'] = 'collapsed';
             } else {
                 $tag = 'span';
                 $txt = wfMsgNoTrans('categorytree-collapse-bullet');
                 $linkattr['title'] = wfMsgNoTrans('categorytree-collapse');
                 $linkattr['data-ct-loaded'] = true;
                 $linkattr['data-ct-state'] = 'expanded';
             }
             if ($tag == 'a') {
                 $linkattr['href'] = $wikiLink;
             }
             $bullet = Xml::openElement($tag, $linkattr) . $txt . Xml::closeElement($tag) . ' ';
         }
     } else {
         $bullet = wfMsgNoTrans('categorytree-page-bullet');
     }
     $s .= Xml::tags('span', $attr, $bullet) . ' ';
     $s .= Xml::openElement('a', array('class' => $labelClass, 'href' => $wikiLink)) . $label . Xml::closeElement('a');
     if ($count !== false && $this->getOption('showcount')) {
         $pages = $allCount - $subcatCount - $fileCount;
         global $wgContLang, $wgLang;
         $attr = array('title' => wfMsgExt('categorytree-member-counts', 'parsemag', $subcatCount, $pages, $fileCount, $allCount, $count), 'dir' => $wgLang->getDir());
         $s .= $wgContLang->getDirMark() . ' ';
         # Create a list of category members with only non-zero member counts
         $memberNums = array();
         if ($subcatCount) {
             $memberNums[] = wfMessage('categorytree-num-categories', $wgLang->formatNum($subcatCount))->text();
         }
         if ($pages) {
             $memberNums[] = wfMessage('categorytree-num-pages', $wgLang->formatNum($pages))->text();
         }
         if ($fileCount) {
             $memberNums[] = wfMessage('categorytree-num-files', $wgLang->formatNum($fileCount))->text();
         }
         $memberNumsShort = $memberNums ? $wgLang->commaList($memberNums) : wfMessage('categorytree-num-empty')->text();
         # Only $5 is actually used in the default message.
         # Other arguments can be used in a customized message.
         $s .= Xml::tags('span', $attr, wfMsgExt('categorytree-member-num', array('parsemag', 'escapenoentities'), $subcatCount, $pages, $fileCount, $allCount, $memberNumsShort));
     }
     $s .= Xml::closeElement('div');
     $s .= "\n\t\t";
     $s .= Xml::openElement('div', array('class' => 'CategoryTreeChildren', 'style' => $children > 0 ? "display:block" : "display:none"));
     if ($ns == NS_CATEGORY && $children > 0 && !$loadchildren) {
         $children = $this->renderChildren($title, $children);
         if ($children == '') {
             $s .= Xml::openElement('i', array('class' => 'CategoryTreeNotice'));
             if ($mode == CT_MODE_CATEGORIES) {
                 $s .= wfMsgExt('categorytree-no-subcategories', 'parsemag');
             } elseif ($mode == CT_MODE_PAGES) {
                 $s .= wfMsgExt('categorytree-no-pages', 'parsemag');
             } elseif ($mode == CT_MODE_PARENTS) {
                 $s .= wfMsgExt('categorytree-no-parent-categories', 'parsemag');
             } else {
                 $s .= wfMsgExt('categorytree-nothing-found', 'parsemag');
             }
             $s .= Xml::closeElement('i');
         } else {
             $s .= $children;
         }
     }
     $s .= Xml::closeElement('div');
     $s .= Xml::closeElement('div');
     if ($load) {
         $s .= "\n\t\t";
         $s .= Xml::openElement('script', array('type' => 'text/javascript'));
         $s .= 'categoryTreeExpandNode("' . Xml::escapeJsString($key) . '", ' . $this->getOptionsAsJsStructure($children) . ', document.getElementById("' . $load . '"));';
         $s .= Xml::closeElement('script');
     }
     $s .= "\n\t\t";
     return $s;
 }
	/**
	 * Static setup method for input type "menuselect".
	 * Adds the Javascript code and css used by all menuselects.
	 */
	static private function setup() {

		global $wgOut, $wgLang;
		global $sfgScriptPath, $sfigSettings;

		static $hasRun = false;

		if ( !$hasRun ) {
			$hasRun = true;
			
			$wgOut->addExtensionStyle( $sfgScriptPath . '/skins/jquery-ui/base/jquery.ui.datepicker.css' );
			$wgOut->addExtensionStyle( $sfgScriptPath . '/skins/jquery-ui/base/jquery.ui.theme.css' );
			$wgOut->addScript( '<script type="text/javascript" src="' . $sfgScriptPath . '/libs/jquery-ui/jquery.ui.datepicker.min.js"></script> ' );
			$wgOut->addScript( '<script type="text/javascript" src="' . $sfigSettings->scriptPath . '/libs/datepicker.js"></script> ' );

			// set localized messages (use MW i18n, not jQuery i18n)
			$jstext =
				"jQuery(function(){\n"
				. "	jQuery.datepicker.regional['wiki'] = {\n"
				. "		closeText: '" . Xml::escapeJsString( wfMsg( 'semanticformsinputs-close' ) ) . "',\n"
				. "		prevText: '" . Xml::escapeJsString( wfMsg( 'semanticformsinputs-prev' ) ) . "',\n"
				. "		nextText: '" . Xml::escapeJsString( wfMsg( 'semanticformsinputs-next' ) ) . "',\n"
				. "		currentText: '" . Xml::escapeJsString( wfMsg( 'semanticformsinputs-today' ) ) . "',\n"
				. "		monthNames: ['"
				. Xml::escapeJsString( wfMsg( 'january' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'february' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'march' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'april' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'may_long' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'june' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'july' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'august' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'september' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'october' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'november' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'december' ) ) . "'],\n"
				. "		monthNamesShort: ['"
				. Xml::escapeJsString( wfMsg( 'jan' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'feb' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'mar' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'apr' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'may' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'jun' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'jul' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'aug' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'sep' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'oct' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'nov' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'dec' ) ) . "'],\n"
				. "		dayNames: ['"
				. Xml::escapeJsString( wfMsg( 'sunday' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'monday' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'tuesday' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'wednesday' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'thursday' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'friday' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'saturday' ) ) . "'],\n"
				. "		dayNamesShort: ['"
				. Xml::escapeJsString( wfMsg( 'sun' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'mon' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'tue' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'wed' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'thu' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'fri' ) ) . "','"
				. Xml::escapeJsString( wfMsg( 'sat' ) ) . "'],\n"
				. "		dayNamesMin: ['"
				. Xml::escapeJsString( $wgLang->firstChar( wfMsg( 'sun' ) ) ) . "','"
				. Xml::escapeJsString( $wgLang->firstChar( wfMsg( 'mon' ) ) ) . "','"
				. Xml::escapeJsString( $wgLang->firstChar( wfMsg( 'tue' ) ) ) . "','"
				. Xml::escapeJsString( $wgLang->firstChar( wfMsg( 'wed' ) ) ) . "','"
				. Xml::escapeJsString( $wgLang->firstChar( wfMsg( 'thu' ) ) ) . "','"
				. Xml::escapeJsString( $wgLang->firstChar( wfMsg( 'fri' ) ) ) . "','"
				. Xml::escapeJsString( $wgLang->firstChar( wfMsg( 'sat' ) ) ) . "'],\n"
				. "		weekHeader: '',\n"
				. "		dateFormat: '" . Xml::escapeJsString( wfMsg( 'semanticformsinputs-dateformatshort' ) ) . "',\n"
				. "		firstDay: '" . Xml::escapeJsString( wfMsg( 'semanticformsinputs-firstdayofweek' ) ) . "',\n"
				. "		isRTL: " . ( $wgLang->isRTL() ? "true" : "false" ) . ",\n"
				. "		showMonthAfterYear: false,\n"
				. "		yearSuffix: ''};\n"
				. "	jQuery.datepicker.setDefaults(jQuery.datepicker.regional['wiki']);\n"
				. "});\n";

			$wgOut->addScript( Html::inlineScript(  $jstext ) );
			
		}
	}
Example #12
0
 function getAjaxPlaceholder($attributes, $pageopt)
 {
     global $wgUser, $wgPlayerExtensionPath, $wgUseAjax;
     $sk = $wgUser->getSkin();
     $this->assertAllowedType();
     if ($pageopt) {
         $pagequery = "options=" . urlencode(urlencodeMap($pageopt));
     } else {
         $pagequery = '';
     }
     $sptitle = $this->getPlayerTitle();
     $spurl = $sptitle->getLocalURL($pagequery);
     $ajaxopt = $this->options;
     $ajaxopt['width'] = $this->width;
     $ajaxopt['height'] = $this->height;
     unset($ajaxopt['caption']);
     $ajaxopt = urlencodeMap($ajaxopt);
     if ($wgUseAjax) {
         $js = ' this.href="javascript:void(0);"; loadPlayer("' . Xml::escapeJsString($this->title->getDBkey()) . '", "' . Xml::escapeJsString($ajaxopt) . '", "' . Xml::escapeJsString($this->uniq) . '");';
     } else {
         $js = '';
     }
     $alt = htmlspecialchars(wfMsg('player-clicktoplay', $this->title->getText()));
     $blank = "<img src=\"{$wgPlayerExtensionPath}/blank.gif\" width=\"{$this->width}\" height=\"{$this->height}\" border=\"0\" alt=\"{$alt}\" class=\"thumbimage\" style=\"width:{$this->width} ! important; height:{$this->height} ! important;\"/>";
     $thumbstyle = '';
     $thumbimg = null;
     $thumbname = @$attributes['thumb'];
     if ($thumbname) {
         $thumbimg = wfFindFile($thumbname);
     }
     if ($thumbimg && $thumbimg->exists()) {
         $tni = $thumbimg->transform(array('width' => $this->width, 'height' => $this->height), 0);
         if ($tni) {
             $thumbstyle = 'background-image:url(' . $tni->getUrl() . '); background-position:center; background-repeat:no-repeat; text-decoration:none;';
         }
     }
     $placeholder = '<a href="' . htmlspecialchars($spurl) . '" onclick="' . htmlspecialchars($js) . '" title="' . $alt . '" class="internal" style="display:block; ' . $thumbstyle . '">' . $blank . '</a>';
     $overlay = "<a id=\"{$this->uniq}-overlay\" href=\"" . htmlspecialchars($spurl) . "\" onclick=\"" . htmlspecialchars($js) . "\" title=\"{$alt}\" class=\"internal\" style=\"display:block; position:absolute; top:0; left:0; width:{$this->width}; height:{$this->height}; background-image:url({$wgPlayerExtensionPath}/play.gif); background-position:center; background-repeat:no-repeat; text-decoration:none; \">" . $blank . "</a>";
     return "<div style='position:relative; width:{$this->width}; height:{$this->height};'>{$placeholder} {$overlay}</div>";
 }
Example #13
0
 /**
  * If this request is a redirect view, send "redirected from" subtitle to
  * $wgOut. Returns true if the header was needed, false if this is not a
  * redirect view. Handles both local and remote redirects.
  *
  * @return boolean
  */
 public function showRedirectedFromHeader()
 {
     global $wgOut, $wgUser, $wgRequest, $wgRedirectSources;
     $rdfrom = $wgRequest->getVal('rdfrom');
     $sk = $wgUser->getSkin();
     if (isset($this->mRedirectedFrom)) {
         // This is an internally redirected page view.
         // We'll need a backlink to the source page for navigation.
         if (wfRunHooks('ArticleViewRedirect', array(&$this))) {
             $redir = $sk->link($this->mRedirectedFrom, null, array(), array('redirect' => 'no'), array('known', 'noclasses'));
             $s = wfMsgExt('redirectedfrom', array('parseinline', 'replaceafter'), $redir);
             $wgOut->setSubtitle($s);
             // Set the fragment if one was specified in the redirect
             if (strval($this->mTitle->getFragment()) != '') {
                 $fragment = Xml::escapeJsString($this->mTitle->getFragmentForURL());
                 $wgOut->addInlineScript("redirectToFragment(\"{$fragment}\");");
             }
             // Add a <link rel="canonical"> tag
             $wgOut->addLink(array('rel' => 'canonical', 'href' => $this->mTitle->getLocalURL()));
             return true;
         }
     } elseif ($rdfrom) {
         // This is an externally redirected view, from some other wiki.
         // If it was reported from a trusted site, supply a backlink.
         if ($wgRedirectSources && preg_match($wgRedirectSources, $rdfrom)) {
             $redir = $sk->makeExternalLink($rdfrom, $rdfrom);
             $s = wfMsgExt('redirectedfrom', array('parseinline', 'replaceafter'), $redir);
             $wgOut->setSubtitle($s);
             return true;
         }
     }
     return false;
 }
function wfDismissableSiteNotice(&$notice)
{
    global $wgMajorSiteNoticeID, $wgUser;
    if (!$notice) {
        return true;
    }
    wfLoadExtensionMessages('DismissableSiteNotice');
    $encNotice = Xml::escapeJsString($notice);
    $encClose = Xml::escapeJsString(wfMsg('sitenotice_close'));
    $id = intval($wgMajorSiteNoticeID) . "." . intval(wfMsgForContent('sitenotice_id'));
    // No dismissal for anons
    if ($wgUser->isAnon()) {
        $notice = <<<EOT
<script type="text/javascript" language="JavaScript">
<!--
document.writeln("{$encNotice}");
-->
</script>
EOT;
        return true;
    }
    $notice = <<<EOT
<script type="text/javascript" language="JavaScript">
<!--
var cookieName = "dismissSiteNotice=";
var cookiePos = document.cookie.indexOf(cookieName);
var siteNoticeID = "{$id}";
var siteNoticeValue = "{$encNotice}";
var cookieValue = "";
var msgClose = "{$encClose}";

if (cookiePos > -1) {
\tcookiePos = cookiePos + cookieName.length;
\tvar endPos = document.cookie.indexOf(";", cookiePos);
\tif (endPos > -1) {
\t\tcookieValue = document.cookie.substring(cookiePos, endPos);
\t} else {
\t\tcookieValue = document.cookie.substring(cookiePos);
\t}
}
if (cookieValue != siteNoticeID) {
\tfunction dismissNotice() {
\t\tvar date = new Date();
\t\tdate.setTime(date.getTime() + 30*86400*1000);
\t\tdocument.cookie = cookieName + siteNoticeID + "; expires="+date.toGMTString() + "; path=/";
\t\tvar element = document.getElementById('siteNotice');
\t\telement.parentNode.removeChild(element);
\t}
\tdocument.writeln('<table width="100%" id="mw-dismissable-notice"><tr><td width="80%">'+siteNoticeValue+'</td>');
\tdocument.writeln('<td width="20%" align="right">[<a href="javascript:dismissNotice();">'+msgClose+'</a>]</td></tr></table>');
}
-->
</script>
EOT;
    // Compact the string a bit
    /*
    	$notice = strtr( $notice, array(
    		"\r\n" => '',
    		"\n" => '',
    		"\t" => '',
    		'cookieName' => 'n',
    		'cookiePos' => 'p',
    		'siteNoticeID' => 'i',
    		'siteNoticeValue' => 'sv',
    		'cookieValue' => 'cv',
    		'msgClose' => 'c',
    		'endPos' => 'e',
    	));*/
    return true;
}
Example #15
0
 /**
  * @covers Xml::escapeJsString
  */
 public function testEscapeJsStringSpecialChars()
 {
     $this->assertEquals('\\\\\\r\\n', Xml::escapeJsString("\\\r\n"), 'escapeJsString() with special characters');
 }
Example #16
0
 /**
  * This is the default action of the script: just view the page of
  * the given title.
  */
 function view()
 {
     global $wgUser, $wgOut, $wgRequest, $wgContLang;
     global $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol, $wgParser;
     global $wgUseTrackbacks, $wgNamespaceRobotPolicies;
     $sk = $wgUser->getSkin();
     wfProfileIn(__METHOD__);
     $parserCache =& ParserCache::singleton();
     $ns = $this->mTitle->getNamespace();
     # shortcut
     # Get variables from query string
     $oldid = $this->getOldID();
     # getOldID may want us to redirect somewhere else
     if ($this->mRedirectUrl) {
         $wgOut->redirect($this->mRedirectUrl);
         wfProfileOut(__METHOD__);
         return;
     }
     $diff = $wgRequest->getVal('diff');
     $rcid = $wgRequest->getVal('rcid');
     $rdfrom = $wgRequest->getVal('rdfrom');
     $wgOut->setArticleFlag(true);
     if (isset($wgNamespaceRobotPolicies[$ns])) {
         $policy = $wgNamespaceRobotPolicies[$ns];
     } else {
         # The default policy. Dev note: make sure you change the documentation
         # in DefaultSettings.php before changing it.
         $policy = 'index,follow';
     }
     $wgOut->setRobotpolicy($policy);
     # If we got diff and oldid in the query, we want to see a
     # diff page instead of the article.
     if (!is_null($diff)) {
         $wgOut->setPageTitle($this->mTitle->getPrefixedText());
         $de = new DifferenceEngine($this->mTitle, $oldid, $diff, $rcid);
         // DifferenceEngine directly fetched the revision:
         $this->mRevIdFetched = $de->mNewid;
         $de->showDiffPage();
         // Needed to get the page's current revision
         $this->loadPageData();
         if ($diff == 0 || $diff == $this->mLatest) {
             # Run view updates for current revision only
             $this->viewUpdates();
         }
         wfProfileOut(__METHOD__);
         return;
     }
     if (empty($oldid) && $this->checkTouched()) {
         $wgOut->setETag($parserCache->getETag($this, $wgUser));
         if ($wgOut->checkLastModified($this->mTouched)) {
             wfProfileOut(__METHOD__);
             return;
         } else {
             if ($this->tryFileCache()) {
                 # tell wgOut that output is taken care of
                 $wgOut->disable();
                 $this->viewUpdates();
                 wfProfileOut(__METHOD__);
                 return;
             }
         }
     }
     # Should the parser cache be used?
     $pcache = $wgEnableParserCache && intval($wgUser->getOption('stubthreshold')) == 0 && $this->exists() && empty($oldid);
     wfDebug('Article::view using parser cache: ' . ($pcache ? 'yes' : 'no') . "\n");
     if ($wgUser->getOption('stubthreshold')) {
         wfIncrStats('pcache_miss_stub');
     }
     $wasRedirected = false;
     if (isset($this->mRedirectedFrom)) {
         // This is an internally redirected page view.
         // We'll need a backlink to the source page for navigation.
         if (wfRunHooks('ArticleViewRedirect', array(&$this))) {
             $sk = $wgUser->getSkin();
             $redir = $sk->makeKnownLinkObj($this->mRedirectedFrom, '', 'redirect=no');
             $s = wfMsg('redirectedfrom', $redir);
             $wgOut->setSubtitle($s);
             // Set the fragment if one was specified in the redirect
             if (strval($this->mTitle->getFragment()) != '') {
                 $fragment = Xml::escapeJsString($this->mTitle->getFragmentForURL());
                 $wgOut->addInlineScript("redirectToFragment(\"{$fragment}\");");
             }
             $wasRedirected = true;
         }
     } elseif (!empty($rdfrom)) {
         // This is an externally redirected view, from some other wiki.
         // If it was reported from a trusted site, supply a backlink.
         global $wgRedirectSources;
         if ($wgRedirectSources && preg_match($wgRedirectSources, $rdfrom)) {
             $sk = $wgUser->getSkin();
             $redir = $sk->makeExternalLink($rdfrom, $rdfrom);
             $s = wfMsg('redirectedfrom', $redir);
             $wgOut->setSubtitle($s);
             $wasRedirected = true;
         }
     }
     $outputDone = false;
     if ($pcache) {
         if ($wgOut->tryParserCache($this, $wgUser)) {
             wfRunHooks('ArticleViewHeader', array(&$this));
             $outputDone = true;
         }
     }
     if (!$outputDone) {
         $text = $this->getContent();
         if ($text === false) {
             # Failed to load, replace text with error message
             $t = $this->mTitle->getPrefixedText();
             if ($oldid) {
                 $t .= ',oldid=' . $oldid;
                 $text = wfMsg('missingarticle', $t);
             } else {
                 $text = wfMsg('noarticletext', $t);
             }
         }
         # Another whitelist check in case oldid is altering the title
         if (!$this->mTitle->userCanRead()) {
             $wgOut->loginToUse();
             $wgOut->output();
             exit;
         }
         # We're looking at an old revision
         if (!empty($oldid)) {
             $wgOut->setRobotpolicy('noindex,nofollow');
             if (is_null($this->mRevision)) {
                 // FIXME: This would be a nice place to load the 'no such page' text.
             } else {
                 $this->setOldSubtitle(isset($this->mOldId) ? $this->mOldId : $oldid);
                 if ($this->mRevision->isDeleted(Revision::DELETED_TEXT)) {
                     if (!$this->mRevision->userCan(Revision::DELETED_TEXT)) {
                         $wgOut->addWikiText(wfMsg('rev-deleted-text-permission'));
                         $wgOut->setPageTitle($this->mTitle->getPrefixedText());
                         return;
                     } else {
                         $wgOut->addWikiText(wfMsg('rev-deleted-text-view'));
                         // and we are allowed to see...
                     }
                 }
             }
         }
     }
     if (!$outputDone) {
         /**
          * @fixme: this hook doesn't work most of the time, as it doesn't
          * trigger when the parser cache is used.
          */
         wfRunHooks('ArticleViewHeader', array(&$this));
         $wgOut->setRevisionId($this->getRevIdFetched());
         # wrap user css and user js in pre and don't parse
         # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
         if ($ns == NS_USER && preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle->getDBkey())) {
             $wgOut->addWikiText(wfMsg('clearyourcache'));
             $wgOut->addHTML('<pre>' . htmlspecialchars($this->mContent) . "\n</pre>");
         } else {
             if ($rt = Title::newFromRedirect($text)) {
                 # Display redirect
                 $imageDir = $wgContLang->isRTL() ? 'rtl' : 'ltr';
                 $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
                 # Don't overwrite the subtitle if this was an old revision
                 if (!$wasRedirected && $this->isCurrent()) {
                     $wgOut->setSubtitle(wfMsgHtml('redirectpagesub'));
                 }
                 $link = $sk->makeLinkObj($rt, $rt->getFullText());
                 $wgOut->addHTML('<img src="' . $imageUrl . '" alt="#REDIRECT " />' . '<span class="redirectText">' . $link . '</span>');
                 $parseout = $wgParser->parse($text, $this->mTitle, ParserOptions::newFromUser($wgUser));
                 $wgOut->addParserOutputNoText($parseout);
             } else {
                 if ($pcache) {
                     # Display content and save to parser cache
                     $wgOut->addPrimaryWikiText($text, $this);
                 } else {
                     # Display content, don't attempt to save to parser cache
                     # Don't show section-edit links on old revisions... this way lies madness.
                     if (!$this->isCurrent()) {
                         $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection(false);
                     }
                     # Display content and don't save to parser cache
                     $wgOut->addPrimaryWikiText($text, $this, false);
                     if (!$this->isCurrent()) {
                         $wgOut->parserOptions()->setEditSection($oldEditSectionSetting);
                     }
                 }
             }
         }
     }
     /* title may have been set from the cache */
     $t = $wgOut->getPageTitle();
     if (empty($t)) {
         $wgOut->setPageTitle($this->mTitle->getPrefixedText());
     }
     # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
     if ($ns == NS_USER_TALK && User::isIP($this->mTitle->getText())) {
         $wgOut->addWikiText(wfMsg('anontalkpagetext'));
     }
     # If we have been passed an &rcid= parameter, we want to give the user a
     # chance to mark this new article as patrolled.
     if ($wgUseRCPatrol && !is_null($rcid) && $rcid != 0 && $wgUser->isAllowed('patrol')) {
         $wgOut->addHTML("<div class='patrollink'>" . wfMsg('markaspatrolledlink', $sk->makeKnownLinkObj($this->mTitle, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid={$rcid}")) . '</div>');
     }
     # Trackbacks
     if ($wgUseTrackbacks) {
         $this->addTrackbacks();
     }
     $this->viewUpdates();
     wfProfileOut(__METHOD__);
 }
 /**
  * Created and outputs an "add new" button linking to the Special:Install page. 
  * 
  * @since 0.1
  */
 protected function displayAddNewButton()
 {
     global $wgOut;
     $wgOut->addHTML(Html::element('button', array('type' => 'button', 'onclick' => 'window.location="' . Xml::escapeJsString(SpecialPage::getTitleFor('install')->getFullURL()) . '"'), wfMsg('add-new-extensions')));
 }
Example #18
0
 /**
  * Special function to transform css output and wrap in js call
  */
 private function transformCssOutput($resourceName, $cssString, $path = '')
 {
     global $wgScriptLoaderRelativeCss;
     // Minify and update paths on cssString:
     $cssOptions = array();
     // Set comments preservation based on debug state
     $cssOptions['preserveComments'] = $this->debug;
     // Check for the two ResourceLoader entry points:
     if ($wgScriptLoaderRelativeCss) {
         // Using the local mediaWiki entry point we should have our $wgScriptPath global
         global $wgScriptPath;
         $prePendPath = $wgScriptPath == '' ? '' : $wgScriptPath . '/';
         $cssOptions['prependRelativePath'] = $prePendPath . dirname($path) . '/';
     } else {
         // Get the server URL
         $serverUri = $this->getResourceLoaderUri();
         $cssOptions['prependRelativePath'] = str_replace('ResourceLoader.php', '', $serverUri) . dirname($path) . '/';
     }
     // We always run minify to update css image urls
     $cssString = Minify_CSS::minify($cssString, $cssOptions);
     // Check output format ( if format is "css" ) return the css string directly
     if ($this->outputFormat == 'css') {
         return $cssString;
     }
     // Output Format is "javascript" return the string in an addStyleString call
     // CSS classes should be of form mw.style.{className}
     $cssStyleName = str_replace('mw.style.', '', $resourceName);
     return 'mw.addStyleString("' . Xml::escapeJsString($cssStyleName) . '", "' . Xml::escapeJsString($cssString) . '");' . "\n";
 }
 /**
  * returns JS function call used to navigate to the next page of this pager
  * when placeholders = true, empty html placeholder should be generated in pager view instead of link
  * when placeholders = false, nothing ('') will be generated in pager view instead of link
  */
 function getNextAjaxLink()
 {
     $result = (object) array("call" => 'return CategoryBrowser.rootCats(\'' . Xml::escapeJsString($this->sqlCond->getEncodedQueue(false)) . '\',' . $this->getNextOffset() . ($this->limit == CB_PAGING_ROWS ? '' : ',' . $this->limit) . ')', "placeholders" => false);
     return $result;
 }
Example #20
0
/**
 * @param Article $article
 * @param OutputPage $out
 * @param string $text
 * @return bool
 */
function wfAutoPageCreateViewPage($article, $out, &$text)
{
    wfProfileIn(__METHOD__);
    global $wgOut;
    $article->autoPageCreate__content = null;
    $origText = $text;
    $title = $article->mTitle;
    $ns = $title->getNamespace();
    $retval = true;
    switch ($ns) {
        case NS_MEDIAWIKI:
            // BugId:15387 - Let's skip user pages too.
        // BugId:15387 - Let's skip user pages too.
        case NS_USER:
        case NS_CATEGORY:
        case NS_HELP:
            $text = "<div class=\"noarticletext\">\n{$text}\n</div>";
            $retval = false;
            break;
        default:
            $text = $title->isContentPage() ? wfMsgForContent("newpagelayout") : '';
            $overlayMsgKey = "autopagecreate-newpage-notice-other";
            if ($title->isContentPage()) {
                $overlayMsgKey = "autopagecreate-newpage-notice-content";
            } elseif ($title->isTalkPage()) {
                $overlayMsgKey = "autopagecreate-newpage-notice-talk";
                $wgOut->setRobotPolicy('noindex,nofollow');
            } else {
                switch ($ns) {
                    case NS_USER:
                        // RT #48042
                        if ($title->isSubpage()) {
                            $overlayMsgKey = false;
                        } else {
                            if (!wfAutoPageCreateIsAnonUserpage($title->getText())) {
                                $text = wfMsgForContent('welcome-user-page', $title->getText());
                                $overlayMsgKey = "autopagecreate-newpage-notice-user";
                            } else {
                                $overlayMsgKey = "autopagecreate-empty";
                            }
                        }
                        break;
                    case NS_PROJECT:
                        $overlayMsgKey = "autopagecreate-newpage-notice-project";
                        break;
                    case NS_TEMPLATE:
                        $overlayMsgKey = "autopagecreate-newpage-notice-template";
                        break;
                    case NS_FORUM:
                        $overlayMsgKey = "autopagecreate-newpage-notice-forum";
                        break;
                    case 502:
                        $overlayMsgKey = "autopagecreate-newpage-notice-blog";
                        break;
                }
                $wgOut->setRobotPolicy('noindex,nofollow');
            }
            if (!empty($overlayMsgKey)) {
                wfDebug(__METHOD__ . ": showing message '{$overlayMsgKey}'\n");
                $overlayMsg4JS = Xml::escapeJsString(wfMsgExt($overlayMsgKey, "parseinline"));
                if ($overlayMsg4JS != "-") {
                    $js = <<<END
wgAfterContentAndJS.push( function() { \$( function() {
\t\$("#wikia_page").prepend("<div id=\\"NoArticleTextNotice\\">{$overlayMsg4JS}<img id=\\"NoArticleTextNoticeClose\\" src=\\""+wgBlankImgUrl+"\\" class=\\"sprite close\\" /></div>");
\t\$("#NoArticleTextNoticeClose").click( function() { \$(this).parent().slideUp() } );
} ) } );
END;
                    $wgOut->addInlineScript($js);
                }
            } else {
                wfDebug(__METHOD__ . ": forced to not show the message\n");
            }
    }
    if ($text !== $origText) {
        $article->autoPageCreate__content = $text;
    }
    wfProfileOut(__METHOD__);
    return $retval;
}
Example #21
0
 public function view()
 {
     global $wgOut, $wgShowEXIF, $wgRequest, $wgUser;
     $this->loadFile();
     if ($this->mTitle->getNamespace() == NS_FILE && $this->img->getRedirected()) {
         if ($this->mTitle->getDBkey() == $this->img->getName()) {
             // mTitle is the same as the redirect target so ask Article
             // to perform the redirect for us.
             return Article::view();
         } else {
             // mTitle is not the same as the redirect target so it is
             // probably the redirect page itself. Fake the redirect symbol
             $wgOut->setPageTitle($this->mTitle->getPrefixedText());
             $wgOut->addHTML($this->viewRedirect(Title::makeTitle(NS_FILE, $this->img->getName()), true, true));
             $this->viewUpdates();
             return;
         }
     }
     $diff = $wgRequest->getVal('diff');
     $diffOnly = $wgRequest->getBool('diffonly', $wgUser->getOption('diffonly'));
     if ($this->mTitle->getNamespace() != NS_FILE || isset($diff) && $diffOnly) {
         return Article::view();
     }
     $this->showRedirectedFromHeader();
     if ($wgShowEXIF && $this->displayImg->exists()) {
         // FIXME: bad interface, see note on MediaHandler::formatMetadata().
         $formattedMetadata = $this->displayImg->formatMetadata();
         $showmeta = $formattedMetadata !== false;
     } else {
         $showmeta = false;
     }
     if (!$diff && $this->displayImg->exists()) {
         $wgOut->addHTML($this->showTOC($showmeta));
     }
     if (!$diff) {
         $this->openShowImage();
     }
     # No need to display noarticletext, we use our own message, output in openShowImage()
     if ($this->getID()) {
         Article::view();
     } else {
         # Just need to set the right headers
         $wgOut->setArticleFlag(true);
         $wgOut->setPageTitle($this->mTitle->getPrefixedText());
         $this->viewUpdates();
     }
     # Show shared description, if needed
     if ($this->mExtraDescription) {
         $fol = wfMsgNoTrans('shareddescriptionfollows');
         if ($fol != '-' && !wfEmptyMsg('shareddescriptionfollows', $fol)) {
             $wgOut->addWikiText($fol);
         }
         $wgOut->addHTML('<div id="shared-image-desc">' . $this->mExtraDescription . "</div>\n");
     }
     $this->closeShowImage();
     $this->imageHistory();
     // TODO: Cleanup the following
     $wgOut->addHTML(Xml::element('h2', array('id' => 'filelinks'), wfMsg('imagelinks')) . "\n");
     $this->imageDupes();
     # TODO! FIXME! For some freaky reason, we can't redirect to foreign images.
     # Yet we return metadata about the target. Definitely an issue in the FileRepo
     $this->imageRedirects();
     $this->imageLinks();
     # Allow extensions to add something after the image links
     $html = '';
     wfRunHooks('ImagePageAfterImageLinks', array($this, &$html));
     if ($html) {
         $wgOut->addHTML($html);
     }
     if ($showmeta) {
         global $wgStylePath, $wgStyleVersion;
         $expand = htmlspecialchars(Xml::escapeJsString(wfMsg('metadata-expand')));
         $collapse = htmlspecialchars(Xml::escapeJsString(wfMsg('metadata-collapse')));
         $wgOut->addHTML(Xml::element('h2', array('id' => 'metadata'), wfMsg('metadata')) . "\n");
         $wgOut->addWikiText($this->makeMetadataTable($formattedMetadata));
         $wgOut->addScriptFile('metadata.js');
         $wgOut->addHTML("<script type=\"text/javascript\">attachMetadataToggle('mw_metadata', '{$expand}', '{$collapse}');</script>\n");
     }
 }
Example #22
0
 public static function listDrafts(&$title = null, $user = null)
 {
     global $wgOut, $wgRequest, $wgUser, $wgLang;
     //added twice?
     $wgOut->addScript('<style type="text/css" media="all">/*<![CDATA[*/ @import "' . wfGetPad('/extensions/min/f/extensions/Drafts/Drafts.css?rev=') . WH_SITEREV . '"; /*]]>*/</style>');
     // Get draftID
     $currentDraft = Draft::newFromID($wgRequest->getIntOrNull('draft'));
     //based on user preference
     $adv = $wgUser->getOption('defaulteditor', '') == 'advanced' ? '&advanced=true' : '';
     // Output HTML for list of drafts
     $drafts = Draft::getDrafts($title, $user);
     if (count($drafts) > 0) {
         global $egDraftsLifeSpan;
         // Internationalization
         wfLoadExtensionMessages('Drafts');
         // Add a summary, on Special:Drafts only
         if (!$title || $title->getNamespace() == NS_SPECIAL) {
             $wgOut->wrapWikiMsg('<div class="mw-drafts-summary">$1</div>', array('drafts-view-summary', $wgLang->formatNum($egDraftsLifeSpan)));
         }
         // Build XML
         $wgOut->addHTML(Xml::openElement('table', array('cellpadding' => 5, 'cellspacing' => 0, 'border' => 0, 'id' => 'drafts-list-table', 'class' => 'section_text', 'style' => 'margin-top:15px')));
         $wgOut->addHTML(Xml::openElement('tr'));
         $wgOut->addHTML(Xml::element('th', array('align' => 'left', 'nowrap' => 'nowrap', 'style' => 'text-align:center;'), wfMsg('drafts-view-article')));
         $wgOut->addHTML(Xml::element('th', array('align' => 'left', 'nowrap' => 'nowrap', 'style' => 'text-align:center;'), wfMsg('drafts-view-saved')));
         $wgOut->addHTML(Xml::element('th', array(), wfMsg('edit')));
         $wgOut->addHTML(Xml::element('th', array(), wfMsg('discard')));
         $wgOut->addHTML(Xml::closeElement('tr'));
         // Add existing drafts for this page and user
         $index = 0;
         foreach ($drafts as $draft) {
             // Get article title text
             $htmlTitle = $draft->getTitle()->getEscapedText();
             // Build Article Load link
             if ($draft->getHTML5()) {
                 $params = 'h5e=true&draft=' . urlencode($draft->getID());
                 if ($draft->getTitle()->getArticleID() == 0) {
                     $params .= "&create-new-article=true";
                 }
                 $urlLoad = $draft->getTitle()->getFullUrl($params);
             } else {
                 $urlLoad = $draft->getTitle()->getFullUrl('action=edit' . $adv . '&draft=' . urlencode($draft->getID()));
             }
             // Build discard link
             $urlDiscard = sprintf('%s?discard=%s&token=%s', SpecialPage::getTitleFor('Drafts')->getFullUrl(), urlencode($draft->getID()), urlencode($wgUser->editToken()));
             // If in edit mode, return to editor
             if ($wgRequest->getText('action') == 'edit' || $wgRequest->getText('action') == 'submit') {
                 $urlDiscard .= '&returnto=' . urlencode('edit');
             }
             // Append section to titles and links
             if ($draft->getSection() !== null) {
                 // Detect section name
                 $lines = explode("\n", $draft->getText());
                 // If there is any content in the section
                 if (count($lines) > 0) {
                     $htmlTitle .= '#' . htmlspecialchars(trim(trim(substr($lines[0], 0, 255), '=')));
                 }
                 // Modify article link and title
                 $urlLoad .= '&section=' . urlencode($draft->getSection());
                 $urlDiscard .= '&section=' . urlencode($draft->getSection());
             }
             // Build XML
             if ($index % 2 == 1) {
                 $wgOut->addHTML(Xml::openElement('tr', array('style' => 'background: #eee;')));
             } else {
                 $wgOut->addHTML(Xml::openElement('tr', array('style' => '')));
             }
             $wgOut->addHTML(Xml::openElement('td', array('align' => 'left', 'class' => 'draftpage')));
             $wgOut->addHTML(Xml::element('a', array('href' => $urlLoad, 'style' => 'font-weight:' . ($currentDraft->getID() == $draft->getID() ? 'bold' : 'normal')), $htmlTitle));
             $wgOut->addHTML(Xml::closeElement('td'));
             $wgOut->addHTML(Xml::element('td', array('align' => 'left', 'nowrap' => 'nowrap', 'class' => 'draftsaved'), $wgLang->timeanddate($draft->getSaveTime(), true)));
             // edit link
             $wgOut->addHTML(Xml::openElement('td', array('align' => 'left', 'nowrap' => 'nowrap', 'class' => 'draftedit')));
             $wgOut->addHTML(Xml::element('a', array('href' => $urlLoad), wfMsg('edit')));
             $wgOut->addHTML(Xml::closeElement('td'));
             $wgOut->addHTML(Xml::openElement('td', array('align' => 'left', 'nowrap' => 'nowrap', 'class' => 'draftdiscard')));
             $wgOut->addHTML(Xml::element('a', array('href' => $urlDiscard, 'onclick' => "if( true || !wgAjaxSaveDraft.insync ) return confirm('" . Xml::escapeJsString(wfMsgHTML('drafts-discard-warn', $draft->getTitle()->getText())) . "')"), wfMsg('drafts-view-discard')));
             $wgOut->addHTML(Xml::closeElement('td'));
             $wgOut->addHTML(Xml::closeElement('tr'));
             $index++;
         }
         $wgOut->addHTML(Xml::closeElement('table'));
         // Return number of drafts
         return count($drafts);
     }
     return 0;
 }
	function doSpecialCreateForm() {
		global $wgOut, $wgRequest, $wgUser, $sfgScriptPath;
		$db = wfGetDB( DB_SLAVE );

		// Create Javascript to populate fields to let the user input
		// parameters for the field, based on the input type selected
		// in the dropdown.
		$skin = $wgUser->getSkin();
		$url = $skin->makeSpecialUrl( 'CreateForm', "showinputtypeoptions=' + this.val() + '&formfield=' + this.attr('formfieldid') + '" );
		foreach ( $wgRequest->getValues() as $param => $value ) {
			$url .= '&params[' . Xml::escapeJsString( $param ) . ']=' . Xml::escapeJsString( $value );
		}

		// Only add 'collapsible' ability if the ResourceLoader exists,
		// i.e. for MW 1.17 - adding backwards compatibility doesn't
		// seem worth it for this relatively minor piece of
		// functionality.
		if ( method_exists( $wgOut, 'addModules' ) ) {
			$wgOut->addModules( 'ext.semanticforms.collapsible' );
		}

		$wgOut->addScript("<script>
jQuery.fn.displayInputParams = function() {
	inputParamsDiv = this.closest('.formField').find('.otherInputParams');
	jQuery.ajax({
		url: '$url',
		context: document.body,
		success: function(data){
			inputParamsDiv.html(data);
		}
	});
};
jQuery(document).ready(function() {
	jQuery('.inputTypeSelector').change( function() {
		jQuery(this).displayInputParams();
	});
});
</script>");


		// Get the names of all templates on this site.
		$all_templates = array();
		$res = $db->select(
			'page',
			'page_title',
			array( 'page_namespace' => NS_TEMPLATE, 'page_is_redirect' => 0 ),
			array( 'ORDER BY' => 'page_title' )
		);

		if ( $db->numRows( $res ) > 0 ) {
			while ( $row = $db->fetchRow( $res ) ) {
				$template_name = str_replace( '_', ' ', $row[0] );
				$all_templates[] = $template_name;
			}
		}

		$form_templates = array();
		$i = 1;
		$deleted_template_loc = null;

		# handle inputs
		$form_name = $wgRequest->getVal( 'form_name' );
		foreach ( $wgRequest->getValues() as $var => $val ) {
			# ignore variables that are not of the right form
			if ( strpos( $var, "_" ) != false ) {
				# get the template declarations and work from there
				list ( $action, $id ) = explode( "_", $var, 2 );
				if ( $action == "template" ) {
					// If the button was pressed to remove
					// this template, just don't add it to
					// the array.
					if ( $wgRequest->getVal( "del_$id" ) != null ) {
						$deleted_template_loc = $id;
					} else {
						$form_template = SFTemplateInForm::create( $val,
							$wgRequest->getVal( "label_$id" ),
							$wgRequest->getVal( "allow_multiple_$id" ) );
						$form_templates[] = $form_template;
					}
				}
			}
		}
		if ( $wgRequest->getVal( 'add_field' ) != null ) {
			$form_template = SFTemplateInForm::create( $wgRequest->getVal( 'new_template' ), "", false );
			$new_template_loc = $wgRequest->getVal( 'before_template' );
			if ( $new_template_loc === null ) { $new_template_loc = 0; }
			// @HACK - array_splice() doesn't work for objects, so
			// we have to first insert a stub element into the
			// array, then replace that with the actual object.
			array_splice( $form_templates, $new_template_loc, 0, "stub" );
			$form_templates[$new_template_loc] = $form_template;
		} else {
			$new_template_loc = null;
		}

		// Now cycle through the templates and fields, modifying each
		// one per the query variables.
		foreach ( $form_templates as $i => $ft ) {
			foreach ( $ft->getFields() as $j => $field ) {
				// handle the change in indexing if a new template was
				// inserted before the end, or one was deleted
				$old_i = $i;
				if ( $new_template_loc != null ) {
					if ( $i > $new_template_loc ) {
						$old_i = $i - 1;
					} elseif ( $i == $new_template_loc ) {
						// it's the new template; it shouldn't
						// get any query-string data
						$old_i = - 1;
					}
				} elseif ( $deleted_template_loc != null ) {
					if ( $i >= $deleted_template_loc ) {
						$old_i = $i + 1;
					}
				}
				foreach ( $wgRequest->getValues() as $key => $value ) {
					if ( ( $pos = strpos( $key, '_' . $old_i . '_' . $j ) ) != false ) {
						$paramName = substr( $key, 0, $pos );
						// Spaces got replaced by
						// underlines in the query.
						$paramName = str_replace( '_', ' ', $paramName );
					} else {
						continue;
					}

					if ( $paramName == 'label' ) {
						$field->template_field->setLabel( $value );
					} elseif ( $paramName == 'input type' ) {
						$input_type = $wgRequest->getVal( "input_type_" . $old_i . "_" . $j );
						if ( $input_type == 'hidden' ) {
							$field->template_field->setInputType( $input_type );
							$field->setIsHidden( true );
						} elseif ( substr( $input_type, 0, 1 ) == '.' ) {
							// It's the default input type -
							// don't do anything.
						} else {
							$field->template_field->setInputType( $input_type );
						}
					} else {
						if ( ! empty( $value ) ) {
							if ( $value == 'on' ) {
								$value = true;
							}
							$field->setFieldArg( $paramName, $value );
						}
					}
				}
			}
		}
		$form = SFForm::create( $form_name, $form_templates );

		// If a submit button was pressed, create the form-definition
		// file, then redirect.
		$save_page = $wgRequest->getCheck( 'wpSave' );
		$preview_page = $wgRequest->getCheck( 'wpPreview' );
		if ( $save_page || $preview_page ) {
			// Validate form name
			if ( $form->getFormName() == "" ) {
				$form_name_error_str = wfMsg( 'sf_blank_error' );
			} else {
				// Redirect to wiki interface
				$wgOut->setArticleBodyOnly( true );
				$title = Title::makeTitleSafe( SF_NS_FORM, $form->getFormName() );
				$full_text = $form->createMarkup();
				$text = SFUtils::printRedirectForm( $title, $full_text, "", $save_page, $preview_page, false, false, false, null, null );
				$wgOut->addHTML( $text );
				return;
			}
		}

		$text = "\t" . '<form action="" method="post">' . "\n";
		// Set 'title' field, in case there's no URL niceness
		$text .= SFFormUtils::hiddenFieldHTML( 'title', $this->getTitle()->getPrefixedText() );
		$text .= "\t<p>" . wfMsg( 'sf_createform_nameinput' ) . ' ' . wfMsg( 'sf_createform_nameinputdesc' ) . ' <input size=25 name="form_name" value="' . $form_name . '" />';
		if ( ! empty( $form_name_error_str ) )
			$text .= "\t" . Html::element( 'font', array( 'color' => 'red' ), $form_name_error_str );
		$text .= "</p>\n";

		$text .= $form->creationHTML();

		$text .= "\t<p>" . wfMsg( 'sf_createform_addtemplate' ) . "\n";

		$select_body = "";
		foreach ( $all_templates as $template ) {
			$select_body .= "	" . Html::element( 'option', array( 'value' => $template ), $template ) . "\n";
		}
		$text .= "\t" . Html::rawElement( 'select', array( 'name' => 'new_template' ), $select_body ) . "\n";
		// If a template has already been added, show a dropdown letting
		// the user choose where in the list to add a new dropdown.
		if ( count( $form_templates ) > 0 ) {
			$before_template_msg = wfMsg( 'sf_createform_beforetemplate' );
			$text .= $before_template_msg;
			$select_body = "";
			foreach ( $form_templates as $i => $ft ) {
				$select_body .= "\t" . Html::element( 'option', array( 'value' => $i ), $ft->getTemplateName() ) . "\n";
			}
			$final_index = count( $form_templates );
			$at_end_msg = wfMsg( 'sf_createform_atend' );
			$select_body .= "\t" . Html::element( 'option', array( 'value' => $final_index, 'selected' => 'selected' ), $at_end_msg );
			$text .= Html::rawElement( 'select', array( 'name' => 'before_template' ), $select_body ) . "\n";
		}

		// Disable 'save' and 'preview' buttons if user has not yet
		// added any templates.
		$disabled_text = ( count( $form_templates ) == 0 ) ? "disabled" : "";
		$add_button_text = wfMsg( 'sf_createform_add' );
		$sk = $wgUser->getSkin();
		$create_template_link = SFUtils::linkForSpecialPage( $sk, 'CreateTemplate' );
		$text .= "\t" . Html::input( 'add_field', $add_button_text, 'submit' );
		$text .= <<<END
</p>
	<br />

END;
		$saveAttrs = array( 'id' => 'wpSave' );
		if ( count( $form_templates ) == 0 ) {
			$saveAttrs['disabled'] = true;
		}
		$editButtonsText = "\t" . Html::input( 'wpSave', wfMsg( 'savearticle' ), 'submit', $saveAttrs ) . "\n";
		$previewAttrs = array( 'id' => 'wpPreview' );
		if ( count( $form_templates ) == 0 ) {
			$previewAttrs['disabled'] = true;
		}
		$editButtonsText .= "\t" . Html::input( 'wpPreview',  wfMsg( 'preview' ), 'submit', $previewAttrs ) . "\n";
		$text .= "\t" . Html::rawElement( 'div', array( 'class' => 'editButtons' ),
			Html::rawElement( 'p', array(), $editButtonsText ) . "\n" ) . "\n";
		// Explanatory message if buttons are disabled because no
		// templates have been added.
		if ( count( $form_templates ) == 0 ) {
			$text .= "\t" . Html::element( 'p', null, "(" . wfMsg( 'sf_createtemplate_addtemplatebeforesave' ) . ")" );
		}
		$text .= <<<END
	</form>
	<hr /><br />

END;
		$text .= "\t" . Html::rawElement( 'p', null, $create_template_link . '.' );

		$wgOut->addExtensionStyle( $sfgScriptPath . "/skins/SemanticForms.css" );
		$wgOut->addHTML( $text );
	}
 /**
  * Returns a string with a HTML represenation of the given page.
  * $title must be a Title object
  */
 function renderNode(&$title, $mode = NULL, $children = false, $loadchildren = false, $depth = 1)
 {
     global $wgCategoryTreeOmitNamespace, $wgCategoryTreeDefaultMode;
     static $uniq = 0;
     if ($mode === NULL) {
         $wgCategoryTreeDefaultMode;
     }
     $load = false;
     if ($children && $loadchildren) {
         $uniq += 1;
         $load = 'ct-' . $uniq . '-' . mt_rand(1, 100000);
         $children = false;
     }
     $ns = $title->getNamespace();
     $key = $title->getDBkey();
     #$trans = $title->getLocalizedText();
     $trans = '';
     #place holder for when translated titles are available
     #when showing only categories, omit namespace in label unless we explicitely defined the configuration setting
     #patch contributed by Manuel Schneider <*****@*****.**>, Bug 8011
     if ($wgCategoryTreeOmitNamespace || $mode == CT_MODE_CATEGORIES) {
         $label = htmlspecialchars($title->getText());
     } else {
         $label = htmlspecialchars($title->getPrefixedText());
     }
     if ($trans && $trans != $label) {
         $label .= ' ' . wfElement('i', array('class' => 'translation'), $trans);
     }
     $wikiLink = $title->getLocalURL();
     $labelClass = 'CategoryTreeLabel ' . ' CategoryTreeLabelNs' . $ns;
     if ($ns == NS_CATEGORY) {
         $labelClass .= ' CategoryTreeLabelCategory';
     } else {
         $labelClass .= ' CategoryTreeLabelPage';
     }
     if ($ns % 2 > 0) {
         $labelClass .= ' CategoryTreeLabelTalk';
     }
     $linkattr = array('href' => '#');
     if ($load) {
         $linkattr['id'] = $load;
     }
     if (!$children) {
         $txt = '+';
         $linkattr['onclick'] = "this.href='javascript:void(0)'; categoryTreeExpandNode('" . Xml::escapeJsString($key) . "','" . $mode . "',this);";
         # Don't load this message for ajax requests, so that we don't have to initialise $wgLang
         $linkattr['title'] = $this->mIsAjaxRequest ? '##LOAD##' : self::msg('expand');
     } else {
         $txt = '–';
         #NOTE: that's not a minus but a unicode ndash!
         $linkattr['onclick'] = "this.href='javascript:void(0)'; categoryTreeCollapseNode('" . Xml::escapeJsString($key) . "','" . $mode . "',this);";
         $linkattr['title'] = self::msg('collapse');
         $linkattr['class'] = 'CategoryTreeLoaded';
     }
     $s = '';
     #NOTE: things in CategoryTree.js rely on the exact order of tags!
     #      Specifically, the CategoryTreeChildren div must be the first
     #      sibling with nodeName = DIV of the grandparent of the expland link.
     $s .= wfOpenElement('div', array('class' => 'CategoryTreeSection'));
     $s .= wfOpenElement('div', array('class' => 'CategoryTreeItem'));
     if ($ns == NS_CATEGORY) {
         $s .= wfOpenElement('span', array('class' => 'CategoryTreeBullet'));
         $s .= '[' . wfElement('a', $linkattr, $txt) . '] ';
         $s .= wfCloseElement('span');
     } else {
         $s .= ' ';
     }
     $s .= wfOpenElement('a', array('class' => $labelClass, 'href' => $wikiLink)) . $label . wfCloseElement('a');
     $s .= wfCloseElement('div');
     $s .= "\n\t\t";
     $s .= wfOpenElement('div', array('class' => 'CategoryTreeChildren', 'style' => $children ? "display:block" : "display:none"));
     //HACK here?
     if ($children) {
         $s .= $this->renderChildren($title, $mode, $depth);
     }
     $s .= wfCloseElement('div');
     $s .= wfCloseElement('div');
     if ($load) {
         $s .= "\n\t\t";
         $s .= wfOpenElement('script', array('type' => 'text/javascript'));
         $s .= 'categoryTreeExpandNode("' . Xml::escapeJsString($key) . '", "' . $mode . '", document.getElementById("' . $load . '") );';
         $s .= wfCloseElement('script');
     }
     $s .= "\n\t\t";
     return $s;
 }
    function getScriptFunctions()
    {
        global $wgNoticeFundraisingUrl;
        $script = <<<JAVASCRIPT
function insertBanner( bannerJson ) {
\tvar url, targets;

\tjQuery( 'div#centralNotice' ).prepend( bannerJson.bannerHtml );
\tif ( bannerJson.autolink ) {
JAVASCRIPT;
        $script .= "\n\t\turl = '" . Xml::escapeJsString($wgNoticeFundraisingUrl) . "';\n";
        $script .= <<<JAVASCRIPT
\t\tif ( ( bannerJson.landingPages !== null ) && bannerJson.landingPages.length ) {
\t\t\ttargets = String( bannerJson.landingPages ).split(',');
\t\t\turl += "?" + jQuery.param( {
\t\t\t\tlanding_page: targets[Math.floor( Math.random() * targets.length )].replace( /^\\s+|\\s+\$/, '' )
\t\t\t} );
\t\t\turl += "&" + jQuery.param( {
\t\t\t\tutm_medium: 'sitenotice',
\t\t\t\tutm_campaign: bannerJson.campaign,
\t\t\t\tutm_source: bannerJson.bannerName,
\t\t\t\tlanguage: mw.config.get( 'wgUserLanguage' ),
\t\t\t\tcountry: Geo.country
\t\t\t} );
\t\t\tjQuery( '#cn-landingpage-link' ).attr( 'href', url );
\t\t}
\t}
}
function setBannerHidingCookie( bannerType ) {
\tvar e = new Date();
\te.setTime( e.getTime() + (14*24*60*60*1000) ); // two weeks
\tvar work = 'centralnotice_' + bannerType + '=hide; expires=' + e.toGMTString() + '; path=/';
\tdocument.cookie = work;
}
function hideBanner() {
\tjQuery( '#centralNotice' ).hide(); // Hide current banner
\tvar bannerType = jQuery.centralNotice.data.bannerType;
\tif ( bannerType === undefined ) {
\t\tbannerType = 'default';
\t}
\tsetBannerHidingCookie( bannerType ); // Hide future banners of the same type
}
// This function is deprecated
function toggleNotice() {
\thideBanner();
}

JAVASCRIPT;
        return $script;
    }
Example #26
0
 /**
  * @param $sk Skin The given Skin
  * @param $includeStyle Boolean: unused
  * @return String: The doctype, opening <html>, and head element.
  */
 public function headElement(Skin $sk, $includeStyle = true)
 {
     global $wgContLang, $wgUseTrackbacks;
     $userdir = $this->getLang()->getDir();
     $sitedir = $wgContLang->getDir();
     if ($sk->commonPrintStylesheet()) {
         $this->addModuleStyles('mediawiki.legacy.wikiprintable');
     }
     $sk->setupUserCss($this);
     $ret = Html::htmlHeader(array('lang' => $this->getLang()->getCode(), 'dir' => $userdir, 'class' => 'client-nojs'));
     if ($this->getHTMLTitle() == '') {
         $this->setHTMLTitle(wfMsg('pagetitle', $this->getPageTitle()));
     }
     $openHead = Html::openElement('head');
     if ($openHead) {
         # Don't bother with the newline if $head == ''
         $ret .= "{$openHead}\n";
     }
     $ret .= Html::element('title', null, $this->getHTMLTitle()) . "\n";
     $ret .= implode("\n", array($this->getHeadLinks($sk, true), $this->buildCssLinks($sk), $this->getHeadScripts($sk), $this->getHeadItems()));
     if ($wgUseTrackbacks && $this->isArticleRelated()) {
         $ret .= $this->getTitle()->trackbackRDF();
     }
     $closeHead = Html::closeElement('head');
     if ($closeHead) {
         $ret .= "{$closeHead}\n";
     }
     $bodyAttrs = array();
     # Crazy edit-on-double-click stuff
     $action = $this->getRequest()->getVal('action', 'view');
     if ($this->getTitle()->getNamespace() != NS_SPECIAL && in_array($action, array('view', 'purge')) && $this->getUser()->getOption('editondblclick')) {
         $editUrl = $this->getTitle()->getLocalUrl($sk->editUrlOptions());
         $bodyAttrs['ondblclick'] = "document.location = '" . Xml::escapeJsString($editUrl) . "'";
     }
     # Classes for LTR/RTL directionality support
     $bodyAttrs['class'] = "mediawiki {$userdir} sitedir-{$sitedir}";
     if ($this->getContext()->getLang()->capitalizeAllNouns()) {
         # A <body> class is probably not the best way to do this . . .
         $bodyAttrs['class'] .= ' capitalize-all-nouns';
     }
     $bodyAttrs['class'] .= ' ' . $sk->getPageClasses($this->getTitle());
     $bodyAttrs['class'] .= ' skin-' . Sanitizer::escapeClass($sk->getSkinName());
     $sk->addToBodyAttributes($this, $bodyAttrs);
     // Allow skins to add body attributes they need
     wfRunHooks('OutputPageBodyAttributes', array($this, $sk, &$bodyAttrs));
     $ret .= Html::openElement('body', $bodyAttrs) . "\n";
     return $ret;
 }
Example #27
0
	/**
	 * @param $collection MessageCollection
	 * @return string
	 */
	public function writeReal( MessageCollection $collection ) {
		$header = $this->header( $collection->code, $collection->getAuthors() );

		$mangler = $this->group->getMangler();

		/**
		 * Get and write messages.
		 */
		$body = '';
		foreach ( $collection as $message ) {
			if ( strlen( $message->translation() ) === 0 ) {
				continue;
			}

			$key = $mangler->unmangle( $message->key() );
			$key = $this->transformKey( Xml::escapeJsString( $key ) );

			$translation = Xml::escapeJsString( $message->translation() );

			$body .= "\t{$key}: \"{$translation}\",\n";
		}

		if ( strlen( $body ) === 0 ) {
			return false;
		}

		/**
		 * Strip last comma, re-add trailing newlines.
		 */
		$body = substr( $body, 0, -2 );
		$body .= "\n";

		return $header . $body . $this->footer();
	}
Example #28
0
 function buildCleanupScript()
 {
     global $wgRestrictionLevels, $wgGroupPermissions;
     $script = 'var wgCascadeableLevels=';
     $CascadeableLevels = array();
     foreach ($wgRestrictionLevels as $key) {
         if (isset($wgGroupPermissions[$key]['protect']) && $wgGroupPermissions[$key]['protect'] || $key == 'protect') {
             $CascadeableLevels[] = "'" . Xml::escapeJsString($key) . "'";
         }
     }
     $script .= "[" . implode(',', $CascadeableLevels) . "];\n";
     $options = (object) array('tableId' => 'mwProtectSet', 'labelText' => wfMsg('protect-unchain-permissions'), 'numTypes' => count($this->mApplicableTypes), 'existingMatch' => 1 == count(array_unique($this->mExistingExpiry)));
     $encOptions = Xml::encodeJsVar($options);
     $script .= "ProtectionForm.init({$encOptions})";
     return Html::inlineScript("if ( window.mediaWiki ) { {$script} }");
 }
Example #29
0
 function getBodyOptions()
 {
     global $wgUser, $wgTitle, $wgOut, $wgRequest, $wgContLang;
     extract($wgRequest->getValues('oldid', 'redirect', 'diff'));
     if (0 != $wgTitle->getNamespace()) {
         $a = array('bgcolor' => '#ffffec');
     } else {
         $a = array('bgcolor' => '#FFFFFF');
     }
     if ($wgOut->isArticle() && $wgUser->getOption('editondblclick') && $wgTitle->quickUserCan('edit')) {
         $s = $wgTitle->getFullURL($this->editUrlOptions());
         $s = 'document.location = "' . Xml::escapeJsString($s) . '";';
         $a += array('ondblclick' => $s);
     }
     $a['onload'] = $wgOut->getOnloadHandler();
     $a['class'] = 'mediawiki' . ' ' . ($wgContLang->isRTL() ? "rtl" : "ltr") . ' ' . $this->getPageClasses($wgTitle) . ' skin-' . Sanitizer::escapeClass($this->getSkinName());
     return $a;
 }
Example #30
0
 /**
  * @private
  */
 function jstext($str)
 {
     echo Xml::escapeJsString($this->data[$str]);
 }