/**
  * @param ResourceLoaderContext $context
  * @return array
  */
 protected function getConfigSettings($context)
 {
     $hash = $context->getHash();
     if (isset($this->configVars[$hash])) {
         return $this->configVars[$hash];
     }
     global $wgContLang;
     $mainPage = Title::newMainPage();
     /**
      * Namespace related preparation
      * - wgNamespaceIds: Key-value pairs of all localized, canonical and aliases for namespaces.
      * - wgCaseSensitiveNamespaces: Array of namespaces that are case-sensitive.
      */
     $namespaceIds = $wgContLang->getNamespaceIds();
     $caseSensitiveNamespaces = array();
     foreach (MWNamespace::getCanonicalNamespaces() as $index => $name) {
         $namespaceIds[$wgContLang->lc($name)] = $index;
         if (!MWNamespace::isCapitalized($index)) {
             $caseSensitiveNamespaces[] = $index;
         }
     }
     $conf = $this->getConfig();
     // Build list of variables
     $vars = array('wgLoadScript' => wfScript('load'), 'debug' => $context->getDebug(), 'skin' => $context->getSkin(), 'stylepath' => $conf->get('StylePath'), 'wgUrlProtocols' => wfUrlProtocols(), 'wgArticlePath' => $conf->get('ArticlePath'), 'wgScriptPath' => $conf->get('ScriptPath'), 'wgScriptExtension' => '.php', 'wgScript' => wfScript(), 'wgSearchType' => $conf->get('SearchType'), 'wgVariantArticlePath' => $conf->get('VariantArticlePath'), 'wgActionPaths' => (object) $conf->get('ActionPaths'), 'wgServer' => $conf->get('Server'), 'wgServerName' => $conf->get('ServerName'), 'wgUserLanguage' => $context->getLanguage(), 'wgContentLanguage' => $wgContLang->getCode(), 'wgTranslateNumerals' => $conf->get('TranslateNumerals'), 'wgVersion' => $conf->get('Version'), 'wgEnableAPI' => $conf->get('EnableAPI'), 'wgEnableWriteAPI' => $conf->get('EnableWriteAPI'), 'wgMainPageTitle' => $mainPage->getPrefixedText(), 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(), 'wgNamespaceIds' => $namespaceIds, 'wgContentNamespaces' => MWNamespace::getContentNamespaces(), 'wgSiteName' => $conf->get('Sitename'), 'wgDBname' => $conf->get('DBname'), 'wgExtraSignatureNamespaces' => $conf->get('ExtraSignatureNamespaces'), 'wgAvailableSkins' => Skin::getSkinNames(), 'wgExtensionAssetsPath' => $conf->get('ExtensionAssetsPath'), 'wgCookiePrefix' => $conf->get('CookiePrefix'), 'wgCookieDomain' => $conf->get('CookieDomain'), 'wgCookiePath' => $conf->get('CookiePath'), 'wgCookieExpiration' => $conf->get('CookieExpiration'), 'wgResourceLoaderMaxQueryLength' => $conf->get('ResourceLoaderMaxQueryLength'), 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces, 'wgLegalTitleChars' => Title::convertByteClassToUnicodeClass(Title::legalChars()), 'wgResourceLoaderStorageVersion' => $conf->get('ResourceLoaderStorageVersion'), 'wgResourceLoaderStorageEnabled' => $conf->get('ResourceLoaderStorageEnabled'), 'wgResourceLoaderLegacyModules' => self::getLegacyModules(), 'wgForeignUploadTargets' => $conf->get('ForeignUploadTargets'), 'wgEnableUploads' => $conf->get('EnableUploads'));
     Hooks::run('ResourceLoaderGetConfigVars', array(&$vars));
     $this->configVars[$hash] = $vars;
     return $this->configVars[$hash];
 }
 /**
  * @param ResourceLoaderContext $context
  * @return array
  */
 protected function getConfig($context)
 {
     $hash = $context->getHash();
     if (isset($this->configVars[$hash])) {
         return $this->configVars[$hash];
     }
     global $wgLoadScript, $wgScript, $wgStylePath, $wgScriptExtension, $wgArticlePath, $wgScriptPath, $wgServer, $wgContLang, $wgVariantArticlePath, $wgActionPaths, $wgVersion, $wgEnableAPI, $wgEnableWriteAPI, $wgDBname, $wgSitename, $wgFileExtensions, $wgExtensionAssetsPath, $wgCookiePrefix, $wgResourceLoaderMaxQueryLength, $wgResourceLoaderStorageEnabled, $wgResourceLoaderStorageVersion, $wgSearchType;
     $mainPage = Title::newMainPage();
     /**
      * Namespace related preparation
      * - wgNamespaceIds: Key-value pairs of all localized, canonical and aliases for namespaces.
      * - wgCaseSensitiveNamespaces: Array of namespaces that are case-sensitive.
      */
     $namespaceIds = $wgContLang->getNamespaceIds();
     $caseSensitiveNamespaces = array();
     foreach (MWNamespace::getCanonicalNamespaces() as $index => $name) {
         $namespaceIds[$wgContLang->lc($name)] = $index;
         if (!MWNamespace::isCapitalized($index)) {
             $caseSensitiveNamespaces[] = $index;
         }
     }
     // Build list of variables
     $vars = array('wgLoadScript' => $wgLoadScript, 'debug' => $context->getDebug(), 'skin' => $context->getSkin(), 'stylepath' => $wgStylePath, 'wgUrlProtocols' => wfUrlProtocols(), 'wgArticlePath' => $wgArticlePath, 'wgScriptPath' => $wgScriptPath, 'wgScriptExtension' => $wgScriptExtension, 'wgScript' => $wgScript, 'wgSearchType' => $wgSearchType, 'wgVariantArticlePath' => $wgVariantArticlePath, 'wgActionPaths' => (object) $wgActionPaths, 'wgServer' => $wgServer, 'wgUserLanguage' => $context->getLanguage(), 'wgContentLanguage' => $wgContLang->getCode(), 'wgVersion' => $wgVersion, 'wgEnableAPI' => $wgEnableAPI, 'wgEnableWriteAPI' => $wgEnableWriteAPI, 'wgMainPageTitle' => $mainPage->getPrefixedText(), 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(), 'wgNamespaceIds' => $namespaceIds, 'wgContentNamespaces' => MWNamespace::getContentNamespaces(), 'wgSiteName' => $wgSitename, 'wgFileExtensions' => array_values(array_unique($wgFileExtensions)), 'wgDBname' => $wgDBname, 'wgFileCanRotate' => BitmapHandler::canRotate(), 'wgAvailableSkins' => Skin::getSkinNames(), 'wgExtensionAssetsPath' => $wgExtensionAssetsPath, 'wgCookiePrefix' => $wgCookiePrefix, 'wgResourceLoaderMaxQueryLength' => $wgResourceLoaderMaxQueryLength, 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces, 'wgLegalTitleChars' => Title::convertByteClassToUnicodeClass(Title::legalChars()), 'wgResourceLoaderStorageVersion' => $wgResourceLoaderStorageVersion, 'wgResourceLoaderStorageEnabled' => $wgResourceLoaderStorageEnabled);
     wfRunHooks('ResourceLoaderGetConfigVars', array(&$vars));
     $this->configVars[$hash] = $vars;
     return $this->configVars[$hash];
 }
 /**
  * @param $context ResourceLoaderContext
  * @return array
  */
 protected function getConfig($context)
 {
     global $wgLoadScript, $wgScript, $wgStylePath, $wgScriptExtension, $wgArticlePath, $wgScriptPath, $wgServer, $wgContLang, $wgVariantArticlePath, $wgActionPaths, $wgUseAjax, $wgVersion, $wgEnableAPI, $wgEnableWriteAPI, $wgDBname, $wgEnableMWSuggest, $wgSitename, $wgFileExtensions, $wgExtensionAssetsPath, $wgCookiePrefix, $wgResourceLoaderMaxQueryLength;
     $mainPage = Title::newMainPage();
     /**
      * Namespace related preparation
      * - wgNamespaceIds: Key-value pairs of all localized, canonical and aliases for namespaces.
      * - wgCaseSensitiveNamespaces: Array of namespaces that are case-sensitive.
      */
     $namespaceIds = $wgContLang->getNamespaceIds();
     $caseSensitiveNamespaces = array();
     foreach (MWNamespace::getCanonicalNamespaces() as $index => $name) {
         $namespaceIds[$wgContLang->lc($name)] = $index;
         if (!MWNamespace::isCapitalized($index)) {
             $caseSensitiveNamespaces[] = $index;
         }
     }
     // Build list of variables
     $vars = array('wgLoadScript' => $wgLoadScript, 'debug' => $context->getDebug(), 'skin' => $context->getSkin(), 'stylepath' => $wgStylePath, 'wgUrlProtocols' => wfUrlProtocols(), 'wgArticlePath' => $wgArticlePath, 'wgScriptPath' => $wgScriptPath, 'wgScriptExtension' => $wgScriptExtension, 'wgScript' => $wgScript, 'wgVariantArticlePath' => $wgVariantArticlePath, 'wgActionPaths' => (object) $wgActionPaths, 'wgServer' => $wgServer, 'wgUserLanguage' => $context->getLanguage(), 'wgContentLanguage' => $wgContLang->getCode(), 'wgVersion' => $wgVersion, 'wgEnableAPI' => $wgEnableAPI, 'wgEnableWriteAPI' => $wgEnableWriteAPI, 'wgDefaultDateFormat' => $wgContLang->getDefaultDateFormat(), 'wgMonthNames' => $wgContLang->getMonthNamesArray(), 'wgMonthNamesShort' => $wgContLang->getMonthAbbreviationsArray(), 'wgMainPageTitle' => $mainPage ? $mainPage->getPrefixedText() : null, 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(), 'wgNamespaceIds' => $namespaceIds, 'wgSiteName' => $wgSitename, 'wgFileExtensions' => array_values($wgFileExtensions), 'wgDBname' => $wgDBname, 'wgFileCanRotate' => BitmapHandler::canRotate(), 'wgAvailableSkins' => Skin::getSkinNames(), 'wgExtensionAssetsPath' => $wgExtensionAssetsPath, 'wgCookiePrefix' => $wgCookiePrefix, 'wgResourceLoaderMaxQueryLength' => $wgResourceLoaderMaxQueryLength, 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces, 'wgSassParams' => SassUtil::getSassSettings());
     if ($wgUseAjax && $wgEnableMWSuggest) {
         $vars['wgMWSuggestTemplate'] = SearchEngine::getMWSuggestTemplate();
     }
     wfRunHooks('ResourceLoaderGetConfigVars', array(&$vars));
     return $vars;
 }
 /**
  * Strip markup to show plaintext
  * @param string $text
  * @return string
  * @access private
  */
 function _stripMarkup($text)
 {
     global $wgContLang;
     $text = substr($text, 0, 4096);
     // don't bother with long text...
     $text = str_replace("'''", "", $text);
     $text = str_replace("''", "", $text);
     $text = preg_replace('#__[a-z0-9_]+__#i', '', $text);
     // magic words
     $cleanChar = "[^|\\[\\]]";
     $subLink = "\\[\\[{$cleanChar}*(?:\\|{$cleanChar}*)*\\]\\]";
     $pipeContents = "(?:{$cleanChar}|{$subLink})*";
     $text = preg_replace_callback("#\n\t\t\t\\[\\[\n\t\t\t\t({$cleanChar}*)\n\t\t\t\t(?:\\|({$pipeContents}))?\n\t\t\t\t(?:\\|{$pipeContents})*\n\t\t\t\\]\\]\n\t\t\t#six", array($this, '_stripLink'), $text);
     $protocols = wfUrlProtocols();
     $text = preg_replace('#\\[(?:$protocols).*? (.*?)\\]#s', '$1', $text);
     // URL links
     $text = preg_replace('#</?[a-z0-9]+.*?>#s', '', $text);
     // HTML-style tags
     $text = preg_replace('#\\{\\|.*?\\|\\}#s', '', $text);
     // tables
     $text = preg_replace('#^:.*$#m', '', $text);
     // indented lines near start are usually disambigs or notices
     $text = Sanitizer::decodeCharReferences($text);
     return trim($text);
 }
 /**
  * Outputs the internal image wrapped in a link
  * @param Parser $parser Instance of running Parser.
  * @param String $image Name of image to display.
  * @param String $url External URL to which to link
  * @param String $alt Alternate text for image and link (optional)
  * @return String A parser strip flag which will be later replaced with raw html.
  */
 function imageLink($parser, $image = null, $url = null, $alt = '')
 {
     # Short-circuit if requried params are missing
     if ($image === null || $url === null) {
         return $this->error('missing-params');
     }
     # Prepare incomming params
     $image = trim($image);
     $url = trim($url);
     $alt = trim($alt);
     # Check for bad URLs
     if (!preg_match('/^(' . wfUrlProtocols() . ')/', $url) || preg_match('/\'"/', $url)) {
         $t = Title::newFromText($url);
         if (!$t) {
             return $this->error('bad-url', $url);
         }
         $url = $t->getFullURL();
     }
     # Check to see that the selected image exists
     $imageObj = Image::newFromName($image);
     if (!$imageObj->exists()) {
         return $this->error('no-such-image', $image);
     }
     # Finally, since all checks passed, display it!
     return $parser->insertStripItem($this->msg('embed-clause', htmlentities($url, ENT_COMPAT), $imageObj->getURL(), htmlentities($alt, ENT_COMPAT)), $parser->mStripState);
 }
 /**
  * Constructs HTML for the tutorial (laboriously), including an imagemap for the clickable "Help desk" button.
  *
  * @param MediaTransformOutput $thumb
  * @param String|null $campaign Upload Wizard campaign for which the tutorial should be displayed.
  *
  * @return String HTML representing the image, with clickable helpdesk button
  */
 public static function getImageHtml(MediaTransformOutput $thumb, $campaign = null)
 {
     $helpDeskUrl = wfMessage('mwe-upwiz-help-desk-url')->text();
     // Per convention, we may be either using an absolute URL or a wiki page title in this UI message
     if (preg_match('/^(?:' . wfUrlProtocols() . ')/', $helpDeskUrl)) {
         $helpDeskHref = $helpDeskUrl;
     } else {
         $helpDeskTitle = Title::newFromText($helpDeskUrl);
         $helpDeskHref = $helpDeskTitle ? $helpDeskTitle->getLocalURL() : '#';
     }
     $buttonCoords = UploadWizardConfig::getSetting('tutorialHelpdeskCoords', $campaign);
     $useMap = $buttonCoords !== false && trim($buttonCoords) != '';
     $imgAttributes = array('src' => $thumb->getUrl(), 'width' => $thumb->getWidth(), 'height' => $thumb->getHeight());
     if ($useMap) {
         $imgAttributes['usemap'] = '#' . self::IMAGEMAP_ID;
     }
     // here we use the not-yet-forgotten HTML imagemap to add a clickable area to the tutorial image.
     // we could do more special effects with hovers and images and such, not to mention SVG scripting,
     // but we aren't sure what we want yet...
     $imgHtml = Html::element('img', $imgAttributes);
     if ($useMap) {
         $areaAltText = wfMessage('mwe-upwiz-help-desk')->text();
         $area = Html::element('area', array('shape' => 'rect', 'coords' => $buttonCoords, 'href' => $helpDeskHref, 'alt' => $areaAltText, 'title' => $areaAltText));
         $imgHtml = Html::rawElement('map', array('id' => self::IMAGEMAP_ID, 'name' => self::IMAGEMAP_ID), $area) . $imgHtml;
     }
     return $imgHtml;
 }
	public function parseNext( $text, WikiObjectModelCollection $parentObj, $offset = 0 ) {
		$text = substr( $text, $offset );

		$r = preg_match( '/^\[\[([^\|\]]+)(\|([^\]]+))?\]\]/', $text, $m );
		if ( $r && !preg_match( '/^(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
			return array( 'len' => strlen( $m[0] ), 'obj' => new WOMLinkModel( $m[1], isset( $m[3] ) ? $m[3] : '' ) );
		}
		$r = preg_match( '/^\[((?:' . wfUrlProtocols() . ')[^ \]]+)(\s+([^\]]+))?\]/', $text, $m );
		if ( $r ) {
			return array( 'len' => strlen( $m[0] ), 'obj' => new WOMLinkModel( $m[1], isset( $m[3] ) ? $m[3] : '' ) );
		}
		// includes/Parser.php Parser->doMagicLinks
		$r = preg_match( '/^(?:' . wfUrlProtocols() . ')[^][<>"|}{\\x00-\\x20\\x7F]+/', $text, $m );
		if ( $r ) {
			return array( 'len' => strlen( $m[0] ), 'obj' => new WOMLinkModel( $m[0] ) );
		}

		return null;
	}
 protected function getConfig($context)
 {
     global $wgLoadScript, $wgScript, $wgStylePath, $wgScriptExtension, $wgArticlePath, $wgScriptPath, $wgServer, $wgContLang, $wgVariantArticlePath, $wgActionPaths, $wgUseAjax, $wgVersion, $wgEnableAPI, $wgEnableWriteAPI, $wgDBname, $wgEnableMWSuggest, $wgSitename, $wgFileExtensions, $wgExtensionAssetsPath, $wgResourceLoaderMaxQueryLength;
     // Pre-process information
     $separatorTransTable = $wgContLang->separatorTransformTable();
     $separatorTransTable = $separatorTransTable ? $separatorTransTable : array();
     $compactSeparatorTransTable = array(implode("\t", array_keys($separatorTransTable)), implode("\t", $separatorTransTable));
     $digitTransTable = $wgContLang->digitTransformTable();
     $digitTransTable = $digitTransTable ? $digitTransTable : array();
     $compactDigitTransTable = array(implode("\t", array_keys($digitTransTable)), implode("\t", $digitTransTable));
     $mainPage = Title::newMainPage();
     // Build list of variables
     $vars = array('wgLoadScript' => $wgLoadScript, 'debug' => $context->getDebug(), 'skin' => $context->getSkin(), 'stylepath' => $wgStylePath, 'wgUrlProtocols' => wfUrlProtocols(), 'wgArticlePath' => $wgArticlePath, 'wgScriptPath' => $wgScriptPath, 'wgScriptExtension' => $wgScriptExtension, 'wgScript' => $wgScript, 'wgVariantArticlePath' => $wgVariantArticlePath, 'wgActionPaths' => $wgActionPaths, 'wgServer' => $wgServer, 'wgUserLanguage' => $context->getLanguage(), 'wgContentLanguage' => $wgContLang->getCode(), 'wgVersion' => $wgVersion, 'wgEnableAPI' => $wgEnableAPI, 'wgEnableWriteAPI' => $wgEnableWriteAPI, 'wgSeparatorTransformTable' => $compactSeparatorTransTable, 'wgDigitTransformTable' => $compactDigitTransTable, 'wgMainPageTitle' => $mainPage ? $mainPage->getPrefixedText() : null, 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(), 'wgNamespaceIds' => $wgContLang->getNamespaceIds(), 'wgSiteName' => $wgSitename, 'wgFileExtensions' => array_values($wgFileExtensions), 'wgDBname' => $wgDBname, 'wgExtensionAssetsPath' => $wgExtensionAssetsPath, 'wgResourceLoaderMaxQueryLength' => $wgResourceLoaderMaxQueryLength);
     if ($wgContLang->hasVariants()) {
         $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
     }
     if ($wgUseAjax && $wgEnableMWSuggest) {
         $vars['wgMWSuggestTemplate'] = SearchEngine::getMWSuggestTemplate();
     }
     wfRunHooks('ResourceLoaderGetConfigVars', array(&$vars));
     return $vars;
 }
Example #9
0
 /**
  * Add content from plain text
  * @since 1.17
  * @param $bar array
  * @param $text string
  * @return Array
  */
 function addToSidebarPlain(&$bar, $text)
 {
     $lines = explode("\n", $text);
     $heading = '';
     foreach ($lines as $line) {
         if (strpos($line, '*') !== 0) {
             continue;
         }
         $line = rtrim($line, "\r");
         // for Windows compat
         if (strpos($line, '**') !== 0) {
             $heading = trim($line, '* ');
             if (!array_key_exists($heading, $bar)) {
                 $bar[$heading] = array();
             }
         } else {
             $line = trim($line, '* ');
             if (strpos($line, '|') !== false) {
                 // sanity check
                 $line = MessageCache::singleton()->transform($line, false, null, $this->getTitle());
                 $line = array_map('trim', explode('|', $line, 2));
                 if (count($line) !== 2) {
                     // Second sanity check, could be hit by people doing
                     // funky stuff with parserfuncs... (bug 33321)
                     continue;
                 }
                 $extraAttribs = array();
                 $msgLink = $this->msg($line[0])->inContentLanguage();
                 if ($msgLink->exists()) {
                     $link = $msgLink->text();
                     if ($link == '-') {
                         continue;
                     }
                 } else {
                     $link = $line[0];
                 }
                 $msgText = $this->msg($line[1]);
                 if ($msgText->exists()) {
                     $text = $msgText->text();
                 } else {
                     $text = $line[1];
                 }
                 if (preg_match('/^(?i:' . wfUrlProtocols() . ')/', $link)) {
                     $href = $link;
                     // Parser::getExternalLinkAttribs won't work here because of the Namespace things
                     global $wgNoFollowLinks, $wgNoFollowDomainExceptions;
                     if ($wgNoFollowLinks && !wfMatchesDomainList($href, $wgNoFollowDomainExceptions)) {
                         $extraAttribs['rel'] = 'nofollow';
                     }
                     global $wgExternalLinkTarget;
                     if ($wgExternalLinkTarget) {
                         $extraAttribs['target'] = $wgExternalLinkTarget;
                     }
                 } else {
                     $title = Title::newFromText($link);
                     if ($title) {
                         $title = $title->fixSpecialName();
                         $href = $title->getLinkURL();
                     } else {
                         $href = 'INVALID-TITLE';
                     }
                 }
                 $bar[$heading][] = array_merge(array('text' => $text, 'href' => $href, 'id' => 'n-' . Sanitizer::escapeId(strtr($line[1], ' ', '-'), 'noninitial'), 'active' => false), $extraAttribs);
             } else {
                 continue;
             }
         }
     }
     return $bar;
 }
 private static function getUrlProtocols()
 {
     static $regex = false;
     if ($regex === false) {
         $regex = wfUrlProtocols();
         RTE::log(__METHOD__, $regex);
     }
     return $regex;
 }
Example #11
0
function fnCustomSidebarProcess($NewSideBar)
{
    global $wgParser, $wgUser, $wgArticle, $wgTitle;
    $NewSideBar = fnCustomSidebarPreProcess($NewSideBar);
    // custom loader
    if ($NewSideBar !== false) {
        if (strpos(trim($NewSideBar), '*') === 0) {
            $text = $NewSideBar;
        } else {
            $text = $NewSideBar;
            do {
                $oldtext = $text;
                if ($titleFromText = Title::newFromText($text)) {
                    $article = new Article($titleFromText, 0);
                    $text = $article->getContent();
                    $text = preg_replace('%\\<noinclude\\s*\\>(.*)\\</noinclude\\s*\\>%isU', '', $text);
                    $text = fnCustomSidebarPreProcess($text);
                }
            } while ($text !== $oldtext);
        }
        $lines = explode("\n", $text);
    } else {
        return array();
    }
    $new_bar = array();
    $heading = '';
    // taken directly from MediaWiki source v1.14.0
    foreach ($lines as $line) {
        if (strpos($line, '*') !== 0) {
            continue;
        }
        if (strpos($line, '**') !== 0) {
            $line = trim($line, '* ');
            $heading = $line;
            if (!array_key_exists($heading, $new_bar)) {
                $new_bar[$heading] = array();
            }
        } else {
            if (strpos($line, '|') !== false) {
                // sanity check
                $line = array_map('trim', explode('|', trim($line, '* '), 2));
                $link = wfMsgForContent($line[0]);
                if ($link == '-') {
                    continue;
                }
                $text = wfMsgExt($line[1], 'parsemag');
                if (wfEmptyMsg($line[1], $text)) {
                    $text = $line[1];
                }
                if (wfEmptyMsg($line[0], $link)) {
                    $link = $line[0];
                }
                if (preg_match('/^(?:' . wfUrlProtocols() . ')/', $link)) {
                    $href = $link;
                } else {
                    $title = Title::newFromText($link);
                    if ($title) {
                        $title = $title->fixSpecialName();
                        $href = $title->getLocalURL();
                    } else {
                        $href = 'INVALID-TITLE';
                    }
                }
                $new_bar[$heading][] = array('text' => $text, 'href' => $href, 'id' => 'n-' . strtr($line[1], ' ', '-'), 'active' => false);
            } else {
                continue;
            }
        }
    }
    // End Mediawiki source
    if (count($new_bar) > 0) {
        return $new_bar;
    } else {
        return array();
    }
}
Example #12
0
/**
 * Parse one line from MediaWiki message to array with indexes 'text' and 'href'
 *
 * @return array
 * @author Inez Korczynski <*****@*****.**>
 */
function parseItem($line)
{
    wfProfileIn(__METHOD__);
    $href = $specialCanonicalName = false;
    $line_temp = explode('|', trim($line, '* '), 3);
    $line_temp[0] = trim($line_temp[0], '[]');
    if (count($line_temp) >= 2 && $line_temp[1] != '') {
        $line = trim($line_temp[1]);
        $link = trim(wfMsgForContent($line_temp[0]));
    } else {
        $line = trim($line_temp[0]);
        $link = trim($line_temp[0]);
    }
    $descText = null;
    if (count($line_temp) > 2 && $line_temp[2] != '') {
        $desc = $line_temp[2];
        if (wfEmptyMsg($desc, $descText = wfMsg($desc))) {
            $descText = $desc;
        }
    }
    if (wfEmptyMsg($line, $text = wfMsg($line))) {
        $text = $line;
    }
    if ($link != null) {
        if (wfEmptyMsg($line_temp[0], $link)) {
            $link = $line_temp[0];
        }
        if (preg_match('/^(?:' . wfUrlProtocols() . ')/', $link)) {
            $href = $link;
        } else {
            $title = Title::newFromText($link);
            if ($title) {
                if ($title->getNamespace() == NS_SPECIAL) {
                    $dbkey = $title->getDBkey();
                    $specialCanonicalName = array_shift(SpecialPageFactory::resolveAlias($dbkey));
                    if (!$specialCanonicalName) {
                        $specialCanonicalName = $dbkey;
                    }
                }
                $title = $title->fixSpecialName();
                $href = $title->getLocalURL();
            } else {
                $href = '#';
            }
        }
    }
    wfProfileOut(__METHOD__);
    return array('text' => $text, 'href' => $href, 'org' => $line_temp[0], 'desc' => $descText, 'specialCanonicalName' => $specialCanonicalName);
}
 /**
  * @author: Inez Korczyński
  */
 public function parseOneLine($line)
 {
     wfProfileIn(__METHOD__);
     // trim spaces and asterisks from line and then split it to maximum two chunks
     $lineArr = explode('|', trim($line, '* '), 3);
     if (isset($lineArr[2])) {
         $specialParam = trim(addslashes($lineArr[2]));
         unset($lineArr[2]);
     } else {
         $specialParam = null;
     }
     // trim [ and ] from line to have just http://www.wikia.com instrad of [http://www.wikia.com] for external links
     $lineArr[0] = trim($lineArr[0], '[]');
     if (count($lineArr) == 2 && $lineArr[1] != '') {
         // * Foo|Bar - links with label
         $link = trim(wfMsgForContent($lineArr[0]));
         $desc = trim($lineArr[1]);
     } else {
         // * Foo
         $link = $desc = trim($lineArr[0]);
         // handle __NOLINK__ magic words (BugId:15189)
         if (substr($link, 0, 10) == self::NOLINK) {
             $link = $desc = substr($link, 10);
             $doNotLink = true;
         }
     }
     $text = null;
     if ($this->getShouldTranslateContent()) {
         $text = $this->forContent ? wfMsgForContent($desc) : wfMsg($desc);
     }
     if (empty($text) || wfEmptyMsg($desc, $text)) {
         $text = $desc;
     }
     if (wfEmptyMsg($lineArr[0], $link)) {
         $link = $lineArr[0];
     }
     if (empty($doNotLink)) {
         if (preg_match('/^(?:' . wfUrlProtocols() . ')/', $link)) {
             $href = $link;
         } else {
             if (empty($link)) {
                 $href = '#';
             } else {
                 if ($link[0] == '#') {
                     $href = '#';
                 } else {
                     //BugId:51034 - URL-encoded article titles break inter-wiki links
                     //in global Nav (but work correctly in the article body)
                     $title = Title::newFromText(urldecode($link));
                     if ($title instanceof Title) {
                         $href = $title->fixSpecialName()->getLocalURL();
                         $pos = strpos($link, '#');
                         if ($pos !== false) {
                             $sectionUrl = substr($link, $pos + 1);
                             if ($sectionUrl !== '') {
                                 $href .= '#' . $sectionUrl;
                             }
                         }
                     } else {
                         $href = '#';
                     }
                 }
             }
         }
     } else {
         $href = '#';
     }
     wfProfileOut(__METHOD__);
     return array(self::ORIGINAL => $lineArr[0], self::TEXT => $text, self::HREF => $href, self::SPECIAL => $specialParam);
 }
Example #14
0
 /**
  * Constructor
  *
  * @param $conf array
  */
 public function __construct($conf = array())
 {
     $this->mConf = $conf;
     $this->mUrlProtocols = wfUrlProtocols();
     $this->mExtLinkBracketedRegex = '/\\[(((?i)' . $this->mUrlProtocols . ')' . self::EXT_LINK_URL_CLASS . '+)\\p{Zs}*([^\\]\\x00-\\x08\\x0a-\\x1F]*?)\\]/Su';
     if (isset($conf['preprocessorClass'])) {
         $this->mPreprocessorClass = $conf['preprocessorClass'];
     } elseif (defined('HPHP_VERSION')) {
         # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
         $this->mPreprocessorClass = 'Preprocessor_Hash';
     } elseif (extension_loaded('domxml')) {
         # PECL extension that conflicts with the core DOM extension (bug 13770)
         wfDebug("Warning: you have the obsolete domxml extension for PHP. Please remove it!\n");
         $this->mPreprocessorClass = 'Preprocessor_Hash';
     } elseif (extension_loaded('dom')) {
         $this->mPreprocessorClass = 'Preprocessor_DOM';
     } else {
         $this->mPreprocessorClass = 'Preprocessor_Hash';
     }
     wfDebug(__CLASS__ . ": using preprocessor: {$this->mPreprocessorClass}\n");
 }
Example #15
0
/**
 * Like wfUrlProtocols(), but excludes '//' from the protocol list. Use this if
 * you need a regex that matches all URL protocols but does not match protocol-
 * relative URLs
 * @return string
 */
function wfUrlProtocolsWithoutProtRel()
{
    return wfUrlProtocols(false);
}
 /**
  * Render slideshow preview
  *
  * @author Marooned
  */
 public static function renderFeedSlideshowPreview($slideshow)
 {
     wfProfileIn(__METHOD__);
     $data = WikiaPhotoGalleryRSS::parseFeed($slideshow['params']['rssfeed']);
     //use images from feed
     $slideshow['images'] = $data['images'];
     // handle "crop" attribute
     $crop = isset($slideshow['params']['crop']) ? $slideshow['params']['crop'] == 'true' : false;
     // render thumbnail
     $maxWidth = isset($slideshow['params']['widths']) && is_numeric($slideshow['params']['widths']) ? $slideshow['params']['widths'] : 300;
     $maxHeight = round($maxWidth * 3 / 4);
     // render slideshow images
     foreach ($slideshow['images'] as &$image) {
         preg_match('%(?:' . wfUrlProtocols() . ')([^/]+)%i', $image['link'], $match);
         $image['caption'] = wfMsg('wikiaPhotoGallery-feed-caption', $image['caption'], $image['link'], $match[1]);
         $image['image'] = $image['src'];
     }
     // render gallery HTML preview
     $template = new EasyTemplate(dirname(__FILE__) . '/templates');
     $template->set_vars(array('fromFeed' => true, 'height' => $maxHeight, 'slideshow' => $slideshow, 'width' => $maxWidth));
     $html = $template->render('slideshowPreview');
     wfProfileOut(__METHOD__);
     return $html;
 }
Example #17
0
 static function makeInternalOrExternalUrl($name)
 {
     if (preg_match('/^(?:' . wfUrlProtocols() . ')/', $name)) {
         return $name;
     } else {
         return self::makeUrl($name);
     }
 }
Example #18
0
 /**
  * Build an array that represents the sidebar(s), the navigation bar among them
  *
  * @return array
  * @private
  */
 function buildSidebar()
 {
     global $parserMemc, $wgEnableSidebarCache, $wgSidebarCacheExpiry;
     global $wgLang, $wgContLang;
     $fname = 'SkinTemplate::buildSidebar';
     wfProfileIn($fname);
     $key = wfMemcKey('sidebar');
     $cacheSidebar = $wgEnableSidebarCache && $wgLang->getCode() == $wgContLang->getCode();
     if ($cacheSidebar) {
         $cachedsidebar = $parserMemc->get($key);
         if ($cachedsidebar != "") {
             wfProfileOut($fname);
             return $cachedsidebar;
         }
     }
     $bar = array();
     $lines = explode("\n", wfMsgForContent('sidebar'));
     $heading = '';
     foreach ($lines as $line) {
         if (strpos($line, '*') !== 0) {
             continue;
         }
         if (strpos($line, '**') !== 0) {
             $line = trim($line, '* ');
             $heading = $line;
         } else {
             if (strpos($line, '|') !== false) {
                 // sanity check
                 $line = explode('|', trim($line, '* '), 2);
                 $link = wfMsgForContent($line[0]);
                 if ($link == '-') {
                     continue;
                 }
                 if (wfEmptyMsg($line[1], $text = wfMsg($line[1]))) {
                     $text = $line[1];
                 }
                 if (wfEmptyMsg($line[0], $link)) {
                     $link = $line[0];
                 }
                 if (preg_match('/^(?:' . wfUrlProtocols() . ')/', $link)) {
                     $href = $link;
                 } else {
                     $title = Title::newFromText($link);
                     if ($title) {
                         $title = $title->fixSpecialName();
                         $href = $title->getLocalURL();
                     } else {
                         $href = 'INVALID-TITLE';
                     }
                 }
                 $bar[$heading][] = array('text' => $text, 'href' => $href, 'id' => 'n-' . strtr($line[1], ' ', '-'), 'active' => false);
             } else {
                 continue;
             }
         }
     }
     if ($cacheSidebar) {
         $parserMemc->set($key, $bar, $wgSidebarCacheExpiry);
     }
     wfProfileOut($fname);
     return $bar;
 }
Example #19
0
 /**
  * Insert a NOPARSE hacky thing into any inline links in a chunk that's
  * going to go through further parsing steps before inline URL expansion.
  *
  * In particular this is important when using action=render, which causes
  * full URLs to be included.
  *
  * Oh man I hate our multi-layer parser!
  *
  * @param string more-or-less HTML
  * @return string less-or-more HTML with NOPARSE bits
  */
 function armorLinks($text)
 {
     return preg_replace("/\\b(" . wfUrlProtocols() . ')/', "{$this->mUniqPrefix}NOPARSE\$1", $text);
 }
Example #20
0
 /**
  * Add content from plain text
  * @since 1.17
  * @param &$bar array
  * @param $text string
  */
 function addToSidebarPlain(&$bar, $text)
 {
     $lines = explode("\n", $text);
     $wikiBar = array();
     # We need to handle the wikitext on a different variable, to avoid trying to do an array operation on text, which would be a fatal error.
     $heading = '';
     foreach ($lines as $line) {
         if (strpos($line, '*') !== 0) {
             continue;
         }
         if (strpos($line, '**') !== 0) {
             $heading = trim($line, '* ');
             if (!array_key_exists($heading, $bar)) {
                 $bar[$heading] = array();
             }
         } else {
             $line = trim($line, '* ');
             if (strpos($line, '|') !== false) {
                 // sanity check
                 $line = array_map('trim', explode('|', $line, 2));
                 $link = wfMsgForContent($line[0]);
                 if ($link == '-') {
                     continue;
                 }
                 $text = wfMsgExt($line[1], 'parsemag');
                 if (wfEmptyMsg($line[1], $text)) {
                     $text = $line[1];
                 }
                 if (wfEmptyMsg($line[0], $link)) {
                     $link = $line[0];
                 }
                 if (preg_match('/^(?:' . wfUrlProtocols() . ')/', $link)) {
                     $href = $link;
                 } else {
                     $title = Title::newFromText($link);
                     if ($title) {
                         $title = $title->fixSpecialName();
                         $href = $title->getLocalURL();
                     } else {
                         $href = 'INVALID-TITLE';
                     }
                 }
                 $bar[$heading][] = array('text' => $text, 'href' => $href, 'id' => 'n-' . strtr($line[1], ' ', '-'), 'active' => false);
             } else {
                 if (substr($line, 0, 2) == '{{' && substr($line, -2) == '}}') {
                     global $wgParser, $wgTitle;
                     $line = substr($line, 2, strlen($line) - 4);
                     $options = new ParserOptions();
                     $options->setEditSection(false);
                     $options->setInterfaceMessage(true);
                     $wikiBar[$heading] = $wgParser->parse(wfMsgForContentNoTrans($line), $wgTitle, $options)->getText();
                 } else {
                     continue;
                 }
             }
         }
     }
     if (count($wikiBar) > 0) {
         $bar = array_merge($bar, $wikiBar);
     }
     return $bar;
 }
Example #21
0
 /**
  * Parse one line form MediaWiki-style message as array of 'text' and 'href'
  */
 private function parseItem($line)
 {
     $line_temp = explode('|', trim($line, '* '), 2);
     if (count($line_temp) > 1) {
         $line = $line_temp[1];
         $link = wfMsgForContent($line_temp[0]);
     } else {
         $line = $line_temp[0];
         $link = $line_temp[0];
     }
     if (wfEmptyMsg($line, $text = wfMsg($line))) {
         $text = $line;
     }
     if ($link != null) {
         if (wfEmptyMsg($line_temp[0], $link)) {
             $link = $line_temp[0];
         }
         if (preg_match('/^(?:' . wfUrlProtocols() . ')/', $link)) {
             $href = $link;
         } else {
             $title = Title::newFromText($link);
             if ($title) {
                 $title = $title->fixSpecialName();
                 $href = $title->getLocalURL();
             } else {
                 $href = '#';
             }
         }
     }
     return array('text' => $text, 'href' => $href);
 }
Example #22
0
 /**
  * Encode an attribute value for HTML tags, with extra armoring
  * against further wiki processing.
  * @param string $text
  * @return string HTML-encoded text fragment
  */
 static function safeEncodeAttribute($text)
 {
     $encValue = Sanitizer::encodeAttribute($text);
     # Templates and links may be expanded in later parsing,
     # creating invalid or dangerous output. Suppress this.
     $encValue = strtr($encValue, array('<' => '&lt;', '>' => '&gt;', '"' => '&quot;', '{' => '&#123;', '[' => '&#91;', "''" => '&#39;&#39;', 'ISBN' => '&#73;SBN', 'RFC' => '&#82;FC', 'PMID' => '&#80;MID', '|' => '&#124;', '__' => '&#95;_'));
     # Stupid hack
     $encValue = preg_replace_callback('/((?i)' . wfUrlProtocols() . ')/', array('Sanitizer', 'armorLinksCallback'), $encValue);
     return $encValue;
 }
Example #23
0
 /**
  * Strips a text string of wikitext for use in a section anchor
  *
  * Accepts a text string and then removes all wikitext from the
  * string and leaves only the resultant text (i.e. the result of
  * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
  * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
  * to create valid section anchors by mimicing the output of the
  * parser when headings are parsed.
  *
  * @param $text string Text string to be stripped of wikitext
  * for use in a Section anchor
  * @return Filtered text string
  */
 public function stripSectionName($text)
 {
     # Strip internal link markup
     $text = preg_replace('/\\[\\[:?([^[|]+)\\|([^[]+)\\]\\]/', '$2', $text);
     $text = preg_replace('/\\[\\[:?([^[]+)\\|?\\]\\]/', '$1', $text);
     # Strip external link markup (FIXME: Not Tolerant to blank link text
     # I.E. [http://www.mediawiki.org] will render as [1] or something depending
     # on how many empty links there are on the page - need to figure that out.
     $text = preg_replace('/\\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\\]/', '$2', $text);
     # Parse wikitext quotes (italics & bold)
     $text = $this->doQuotes($text);
     # Strip HTML tags
     $text = StringUtils::delimiterReplace('<', '>', '', $text);
     return $text;
 }
 public static function parseMsg($msg, $isFavicon = false)
 {
     global $wgMemc, $wgArticlePath;
     $mcKey = wfMemcKey("hp_msg_parser", strtolower($msg));
     $out = $wgMemc->get($mcKey);
     if (is_array($out)) {
         return $out;
     }
     wfProfileIn(__METHOD__);
     $message = wfMsgForContent($msg);
     $lines = explode("\n", $message);
     $out = array();
     foreach ($lines as $v) {
         if (preg_match("/^([\\*]+)([^|]+)\\|(((.*)\\|(.*))|(.*))\$/", trim($v), $matches)) {
             $param = "";
             if (!empty($matches[5])) {
                 $param = $matches[6];
                 $title = trim($matches[5]);
             } else {
                 $title = trim($matches[3]);
             }
             if (strlen($matches[1]) == 1) {
                 $matches[2] = trim($matches[2]);
                 if (preg_match('/^(?:' . wfUrlProtocols() . ')/', $matches[2])) {
                     $href = $matches[2];
                 } else {
                     $href = str_replace('$1', $matches[2], $wgArticlePath);
                 }
                 $out[] = array("title" => $title, 'href' => $href, 'sub' => array());
             }
             if (strlen($matches[1]) == 2) {
                 if (count($out) > 0) {
                     if ($isFavicon) {
                         $id = (int) WikiFactory::UrlToID(trim($matches[2]));
                         $favicon = "";
                         if ($id > 0) {
                             $favicon = WikiFactory::getVarValueByName("wgFavicon", $id);
                         }
                     }
                     $out[count($out) - 1]['sub'][] = array("param" => $param, "favicon" => $favicon, "title" => $title, 'href' => trim($matches[2]));
                 }
             }
         }
     }
     if (count($out) > 0) {
         $out[0]['isfirst'] = true;
         $out[count($out) - 1]['islast'] = true;
     }
     $wgMemc->set($mcKey, $out, 60 * 60 * 12);
     wfProfileOut(__METHOD__);
     return $out;
 }
Example #25
0
 /**
  * Build an array that represents the sidebar(s), the navigation bar among them
  *
  * @return array
  */
 function buildSidebar()
 {
     global $parserMemc, $wgEnableSidebarCache, $wgSidebarCacheExpiry;
     global $wgLang;
     wfProfileIn(__METHOD__);
     $key = wfMemcKey('sidebar', $wgLang->getCode());
     if ($wgEnableSidebarCache) {
         $cachedsidebar = $parserMemc->get($key);
         if ($cachedsidebar) {
             wfProfileOut(__METHOD__);
             return $cachedsidebar;
         }
     }
     $bar = array();
     $lines = explode("\n", wfMsgForContent('sidebar'));
     $heading = '';
     foreach ($lines as $line) {
         if (strpos($line, '*') !== 0) {
             continue;
         }
         if (strpos($line, '**') !== 0) {
             $line = trim($line, '* ');
             $heading = $line;
             if (!array_key_exists($heading, $bar)) {
                 $bar[$heading] = array();
             }
         } else {
             if (strpos($line, '|') !== false) {
                 // sanity check
                 $line = array_map('trim', explode('|', trim($line, '* '), 2));
                 $link = wfMsgForContent($line[0]);
                 if ($link == '-') {
                     continue;
                 }
                 $text = wfMsgExt($line[1], 'parsemag');
                 if (wfEmptyMsg($line[1], $text)) {
                     $text = $line[1];
                 }
                 if (wfEmptyMsg($line[0], $link)) {
                     $link = $line[0];
                 }
                 if (preg_match('/^(?:' . wfUrlProtocols() . ')/', $link)) {
                     $href = $link;
                 } else {
                     $title = Title::newFromText($link);
                     if ($title) {
                         $title = $title->fixSpecialName();
                         $href = $title->getLocalURL();
                     } else {
                         $href = 'INVALID-TITLE';
                     }
                 }
                 $bar[$heading][] = array('text' => $text, 'href' => $href, 'id' => 'n-' . strtr($line[1], ' ', '-'), 'active' => false);
             } else {
                 continue;
             }
         }
     }
     wfRunHooks('SkinBuildSidebar', array($this, &$bar));
     if ($wgEnableSidebarCache) {
         $parserMemc->set($key, $bar, $wgSidebarCacheExpiry);
     }
     wfProfileOut(__METHOD__);
     return $bar;
 }
 /**
  * @param string $linkTarget
  *
  * @return string
  * @throws \MWException
  */
 protected function getHrefForTarget($linkTarget)
 {
     if (empty($linkTarget)) {
         return '#';
     } elseif (preg_match('/^(?:' . wfUrlProtocols() . ')/', $linkTarget) || $linkTarget[0] === '#') {
         return $linkTarget;
     } else {
         return $this->getHrefForWikiPage($linkTarget);
     }
 }
function mlGenerateSideBar(&$skin, &$tpl)
{
    global $wgLanguageCode;
    // wfMsg does know to:
    // * return  Mediawiki::Sidebar for default language
    // * return MediaWiki::Sidebar/xx for xx language (if xx is not default)
    $lines = explode("\n", wfMsg('sidebar'));
    foreach ($lines as $line) {
        if (strpos($line, '*') !== 0) {
            continue;
        }
        if (strpos($line, '**') !== 0) {
            $line = trim($line, '* ');
            $heading = $line;
        } else {
            if (strpos($line, '|') !== false) {
                // sanity check
                $line = explode('|', trim($line, '* '), 2);
                $link = wfMsgForContent($line[0]);
                if ($link == '-') {
                    continue;
                }
                if (wfEmptyMsg($line[1], $text = wfMsg($line[1]))) {
                    $text = $line[1];
                }
                if (wfEmptyMsg($line[0], $link)) {
                    $link = $line[0];
                }
                if (preg_match('/^(?:' . wfUrlProtocols() . ')/', $link)) {
                    $href = $link;
                } else {
                    $title = Title::newFromText($link);
                    if ($title) {
                        $title = $title->fixSpecialName();
                        $href = $title->getLocalURL();
                    } else {
                        $href = 'INVALID-TITLE';
                    }
                }
                $bar[$heading][] = array('text' => $text, 'href' => $href, 'id' => 'n-' . strtr($line[1], ' ', '-'), 'active' => false);
                $tpl->set('sidebar', $bar);
            } else {
                continue;
            }
        }
    }
    return true;
}
Example #28
0
 function execute($par)
 {
     global $wgOut, $wgParser, $wgUser, $wgContLang, $wgRequest;
     # Retrieve submitted values
     $titleText = $wgRequest->getVal('commentArticle');
     $commenterName = $wgRequest->getVal('commenterName');
     $commenterURL = trim($wgRequest->getVal('commenterURL'));
     $comment = $wgRequest->getVal('comment');
     // The default value is the same as not providing a URL
     if ($commenterURL == 'http://') {
         $commenterURL = '';
     }
     $title = Title::newFromText($titleText);
     # Perform validation checks on supplied fields
     $messages = array();
     if (!$wgRequest->wasPosted()) {
         $messages[] = wfMsg('article-comments-not-posted');
     }
     if ($titleText === '' || !$title) {
         $messages[] = wfMsg('article-comments-invalid-field', wfMsgForContent('article-comments-title-string'), $titleText);
     }
     if (!$commenterName || strpos($commenterName, "\n") !== false) {
         $messages[] = wfMsg('article-comments-required-field', wfMsgForContent('article-comments-name-string'));
     }
     if ($commenterURL != '' && !preg_match("/^(" . wfUrlProtocols() . ')' . Parser::EXT_LINK_URL_CLASS . '+$/', $commenterURL)) {
         $messages[] = wfMsg('article-comments-invalid-field', wfMsgForContent('article-comments-url-string'), $commenterURL);
     }
     if (!$comment) {
         $messages[] = wfMsg('article-comments-required-field', wfMsg('article-comments-comment-string'));
     }
     if (!empty($messages)) {
         $wgOut->setPageTitle(wfMsg('article-comments-submission-failed'));
         $wikiText = "<div class='errorbox'>\n";
         $wikiText .= wfMsgExt('article-comments-failure-reasons', 'parsemag', count($messages)) . "\n\n";
         foreach ($messages as $message) {
             $wikiText .= "* {$message}\n";
         }
         $wgOut->addWikiText($wikiText . '</div>');
         return;
     }
     # Setup title and talkTitle object
     $article = new Article($title);
     $talkTitle = $title->getTalkPage();
     $talkArticle = new Article($talkTitle);
     # Check whether user is blocked from editing the talk page
     if ($wgUser->isBlockedFrom($talkTitle)) {
         $wgOut->setPageTitle(wfMsg('article-comments-submission-failed'));
         $wikiText = "<div class='errorbox'>\n";
         # 1 error only but message is used above for n errors too
         $wikiText .= wfMsgExt('article-comments-failure-reasons', 'parsemag', 1) . "\n\n";
         $wikiText .= '* ' . wfMsg('article-comments-user-is-blocked', $talkTitle->getPrefixedText()) . "\n";
         $wgOut->addWikiText($wikiText . '</div>');
         return;
     }
     # Retrieve article content
     $articleContent = '';
     if ($title->exists()) {
         $articleContent = $article->getContent();
     }
     # Retrieve existing talk content
     $talkContent = '';
     if ($talkTitle->exists()) {
         $talkContent = $talkArticle->getContent();
     }
     # Check if talk NS is in the namespace display list
     # Note: if so, then there's no need to confirm that <comments /> appears in the article or talk page.
     global $wgArticleCommentsNSDisplayList;
     $skipCheck = is_array($wgArticleCommentsNSDisplayList) ? in_array($talkTitle->getNamespace(), $wgArticleCommentsNSDisplayList) : false;
     # Check whether the article or its talk page contains a <comments /> flag
     if (!$skipCheck && preg_match('/<comments( +[^>]*)?\\/>/', $articleContent) === 0 && preg_match('/<comments( +[^>]*)?\\/>/', $talkContent) === 0) {
         $wgOut->setPageTitle(wfMsgForContent('article-comments-submission-failed'));
         $wgOut->addWikiText('<div class="errorbox">' . wfMsg('article-comments-no-comments', $title->getPrefixedText()) . '</div>');
         return;
     }
     # Run spam checks
     $isSpam = false;
     wfRunHooks('ArticleCommentsSpamCheck', array($comment, $commenterName, $commenterURL, &$isSpam));
     # If it's spam - it's gone!
     if ($isSpam) {
         $wgOut->setPageTitle(wfMsg('article-comments-submission-failed'));
         $wgOut->addWikiText('<div class="errorbox">' . wfMsg('article-comments-no-spam') . '</div>');
         return;
     }
     # Initialize the talk page's content.
     if ($talkContent == '') {
         $talkContent = wfMsgForContent('article-comments-talk-page-starter', $title->getPrefixedText());
     }
     # Search for insertion point, or append most recent comment.
     $commentText = wfMsgForContent('article-comments-new-comment-heading', $commenterName, $commenterURL, '~~~~', $comment);
     $commentText .= '<comment date="' . htmlspecialchars(wfTimestamp(TS_ISO_8601)) . '" name="' . htmlspecialchars($commenterName) . '"';
     if ($commenterURL != '') {
         $commentText .= ' url="' . htmlspecialchars($commenterURL) . '"';
     }
     if ($wgUser->isLoggedIn()) {
         $commentText .= ' signature="' . htmlspecialchars($wgParser->getUserSig($wgUser)) . '"';
     }
     $commentText .= ">\n" . str_replace('</comment', '&lt;/comment', $comment) . "\n</comment>";
     $posAbove = stripos($talkContent, '<!--COMMENTS_ABOVE-->');
     if ($posAbove === false) {
         $posBelow = stripos($talkContent, '<!--COMMENTS_BELOW-->');
     }
     if ($posAbove !== false) {
         # Insert comments above HTML marker
         $talkContent = substr($talkContent, 0, $posAbove) . $commentText . substr($talkContent, $posAbove);
     } elseif ($posBelow !== false) {
         # Insert comments below HTML marker
         $talkContent = substr($talkContent, 0, $posBelow + 21) . $commentText . substr($talkContent, $posBelow + 21);
     } else {
         # No marker found, append to bottom (default)
         $talkContent .= $commentText;
     }
     # Update the talkArticle with the new comment
     $summary = wfMsgForContent('article-comments-summary', $commenterName);
     $talkArticle->doEdit($talkContent, $summary);
     $wgOut->setPageTitle(wfMsg('article-comments-submission-succeeded'));
     $wgOut->addWikiMsg('article-comments-submission-success', $title->getPrefixedText());
     $wgOut->addWikiMsg('article-comments-submission-view-all', $talkTitle->getPrefixedText());
 }
 function replaceInternalLinksCallback($parser, $holders, $markers, $titleText, $paramText)
 {
     wfProfileIn(__METHOD__);
     $wt = isset($paramText) ? "[[{$titleText}|{$paramText}]]" : "[[{$titleText}]]";
     wfProfileIn(__METHOD__ . "-misc");
     # Don't allow internal links to pages containing
     # PROTO: where PROTO is a valid URL protocol; these
     # should be external links.
     if (preg_match('/^\\b(?:' . wfUrlProtocols() . ')/', $titleText)) {
         wfProfileOut(__METHOD__);
         return $wt;
     }
     # Make subpage if necessary
     if ($this->areSubpagesAllowed()) {
         $titleText = $this->maybeDoSubpageLink($titleText, $paramText);
     }
     # Check for a leading colon and strip it if it is there
     $leadingColon = $titleText[0] == ':';
     if ($leadingColon) {
         $titleText = substr($titleText, 1);
     }
     wfProfileOut(__METHOD__ . "-misc");
     # Make title object
     wfProfileIn(__METHOD__ . "-title");
     $title = Title::newFromText($this->mStripState->unstripNoWiki($titleText));
     if (!$title) {
         wfProfileOut(__METHOD__ . "-title");
         wfProfileOut(__METHOD__);
         return $wt;
     }
     $ns = $title->getNamespace();
     wfProfileOut(__METHOD__ . "-title");
     # Default for Namespaces is a default link
     # ToDo: Default for patterns is plain wikitext
     $return = true;
     if (isset($this->mLinkHooks[$ns])) {
         list($callback, $flags) = $this->mLinkHooks[$ns];
         if ($flags & SLH_PATTERN) {
             $args = array($parser, $holders, $markers, $titleText, &$paramText, &$leadingColon);
         } else {
             $args = array($parser, $holders, $markers, $title, $titleText, &$paramText, &$leadingColon);
         }
         # Workaround for PHP bug 35229 and similar
         if (!is_callable($callback)) {
             throw new MWException("Tag hook for namespace {$ns} is not callable\n");
         }
         $return = call_user_func_array($callback, $args);
     }
     if ($return === true) {
         # True (treat as plain link) was returned, call the defaultLinkHook
         $return = CoreLinkFunctions::defaultLinkHook($parser, $holders, $markers, $title, $titleText, $paramText, $leadingColon);
     }
     if ($return === false) {
         # False (no link) was returned, output plain wikitext
         # Build it again as the hook is allowed to modify $paramText
         $return = isset($paramText) ? "[[{$titleText}|{$paramText}]]" : "[[{$titleText}]]";
     }
     # Content was returned, return it
     wfProfileOut(__METHOD__);
     return $return;
 }
 /**
  * Given a text already html-escaped which contains urls in wiki format,
  * convert it to html.
  * @param $text
  * @return string
  */
 public static function parseExternalLinks($text)
 {
     static $urlProtocols = false;
     if (!$urlProtocols) {
         // Allow custom protocols
         if (function_exists('wfUrlProtocols')) {
             $urlProtocols = wfUrlProtocols();
         } else {
             $urlProtocols = 'https?:\\/\\/|ftp:\\/\\/';
         }
     }
     $extLinkBracketedRegex = '/(?:(<[^>]*)|' . '\\[(((?i)' . $urlProtocols . ')' . self::EXT_LINK_URL_CLASS . '+)\\p{Zs}*([^\\]\\x00-\\x08\\x0a-\\x1F]*?)\\]|' . '(((?i)' . $urlProtocols . ')' . self::EXT_LINK_URL_CLASS . '+))/Su';
     return preg_replace_callback($extLinkBracketedRegex, 'self::parseExternalLinkArray', $text);
 }