Пример #1
0
 /**
  * @dataProvider dataGetPageLanguage
  */
 public function testGetPageLanguage($title, $expected)
 {
     if (is_string($title)) {
         $title = Title::newFromText($title);
     }
     $expected = wfGetLangObj($expected);
     $handler = ContentHandler::getForTitle($title);
     $lang = $handler->getPageLanguage($title);
     $this->assertEquals($expected->getCode(), $lang->getCode());
 }
Пример #2
0
 /**
  * Show the special page
  *
  * @param string $par Parameter passed to the page or null
  */
 public function execute($par)
 {
     $request = $this->getRequest();
     $out = $this->getOutput();
     $this->setHeaders();
     if (!$this->getConfig()->get('UseDatabaseMessages')) {
         $out->addWikiMsg('allmessagesnotsupportedDB');
         return;
     }
     $this->outputHeader('allmessagestext');
     $out->addModuleStyles('mediawiki.special');
     $this->table = new AllmessagesTablePager($this, array(), wfGetLangObj($request->getVal('lang', $par)));
     $this->langcode = $this->table->lang->getCode();
     $out->addHTML($this->table->buildForm());
     $out->addParserOutputContent($this->table->getFullOutput());
 }
 /**
  * Show the special page
  *
  * @param $par Mixed: parameter passed to the page or null
  */
 public function execute($par)
 {
     $request = $this->getRequest();
     $out = $this->getOutput();
     $this->setHeaders();
     global $wgUseDatabaseMessages;
     if (!$wgUseDatabaseMessages) {
         $out->addWikiMsg('allmessagesnotsupportedDB');
         return;
     } else {
         $this->outputHeader('allmessagestext');
     }
     $out->addModuleStyles('mediawiki.special');
     $this->table = new AllmessagesTablePager($this, array(), wfGetLangObj($request->getVal('lang', $par)));
     $this->langcode = $this->table->lang->getCode();
     $out->addHTML($this->table->buildForm() . $this->table->getNavigationBar() . $this->table->getBody() . $this->table->getNavigationBar());
 }
Пример #4
0
 /**
  * Show the special page
  *
  * @param $par Mixed: parameter passed to the page or null
  */
 public function execute($par)
 {
     global $wgOut, $wgRequest;
     $this->setHeaders();
     global $wgUseDatabaseMessages;
     if (!$wgUseDatabaseMessages) {
         $wgOut->addWikiMsg('allmessagesnotsupportedDB');
         return;
     } else {
         $this->outputHeader('allmessagestext');
     }
     $this->filter = $wgRequest->getVal('filter', 'all');
     $this->prefix = $wgRequest->getVal('prefix', '');
     $this->table = new AllmessagesTablePager($this, $conds = array(), wfGetLangObj($wgRequest->getVal('lang', $par)));
     $this->langCode = $this->table->lang->getCode();
     $wgOut->addHTML($this->buildForm() . $this->table->getNavigationBar() . $this->table->getLimitForm() . $this->table->getBody() . $this->table->getNavigationBar());
 }
 public function executeIndex()
 {
     global $wgRequest, $wgContLang;
     $day = $wgRequest->getVal('day');
     $type = $wgRequest->getVal('type');
     $lang = $wgRequest->getVal('lang', 'en');
     if ($type != 'views-digest' && $type != 'complete-digest') {
         $wgContLang = wfGetLangObj($lang);
     }
     if (!empty($day)) {
         $this->previewBody = F::app()->renderView("FounderEmails", $day, array('language' => $lang));
         $this->previewBody = strtr($this->previewBody, array('$USERNAME' => 'UserName', '$WIKINAME' => '<a href="#" style="color:#2C85D5;">WikiName</a>', '$HDWIKINAME' => '<a href="#" style="color:#fa5c1f;">WikiName</a>', '$UNIQUEVIEWS' => '6'));
     } else {
         if (!empty($type)) {
             $this->previewBody = F::app()->renderView("FounderEmails", 'GeneralUpdate', array('type' => $type, 'language' => $lang, '$PAGEURL' => 'http://www.wikia.com', '$MYHOMEURL' => 'http://www.wikia.com', '$UNIQUEVIEWS' => '1', '$USEREDITS' => '2', '$USERJOINS' => '3', '$EDITORTALKPAGEURL' => 'http://www.wikia.com'));
             $this->previewBody = strtr($this->previewBody, array('$USERNAME' => 'UserName', '$WIKINAME' => '<a href="#" style="color:#2C85D5;">WikiName</a>', '$PAGETITLE' => '<a href="#" style="color:#2C85D5;">PageTitle</a>', '$EDITORNAME' => '<a href="#" style="color:#2C85D5;">EditorName</a>'));
         }
     }
 }
Пример #6
0
 /**
  * Get the language in which the content of this page is written when
  * viewed by user. Defaults to $wgContLang, but in certain cases it can be
  * e.g. $wgLang (such as special pages, which are in the user language).
  *
  * @since 1.20
  * @return Language
  */
 public function getPageViewLanguage()
 {
     global $wgLang;
     if ($this->isSpecialPage()) {
         // If the user chooses a variant, the content is actually
         // in a language whose code is the variant code.
         $variant = $wgLang->getPreferredVariant();
         if ($wgLang->getCode() !== $variant) {
             return Language::factory($variant);
         }
         return $wgLang;
     }
     // Checking if DB language is set
     $dbPageLanguage = $this->getDbPageLanguageCode();
     if ($dbPageLanguage) {
         $pageLang = wfGetLangObj($dbPageLanguage);
         $variant = $pageLang->getPreferredVariant();
         if ($pageLang->getCode() !== $variant) {
             $pageLang = Language::factory($variant);
         }
         return $pageLang;
     }
     // @note Can't be cached persistently, depends on user settings.
     // @note ContentHandler::getPageViewLanguage() may need to load the
     //   content to determine the page language!
     $contentHandler = ContentHandler::getForTitle($this);
     $pageLang = $contentHandler->getPageViewLanguage($this);
     return $pageLang;
 }
Пример #7
0
 /**
  * Returns an array of config data for this filter to be stored in the JS
  * @return null
  */
 public function getJsData()
 {
     global $wgAmericanDates;
     return $this->getParamHashes($this->getQueryResults(), $this->getActualParameters()) + array('firstDay' => $wgAmericanDates ? '0' : wfMsg('srf-filtered-firstdayofweek'), 'isRTL' => wfGetLangObj(true)->isRTL());
 }
Пример #8
0
 /**
  * Get a DateFormatter object
  *
  * @param Language|string|null $lang In which language to format the date
  * 		Defaults to the site content language
  * @return DateFormatter
  */
 public static function getInstance($lang = null)
 {
     global $wgContLang, $wgMainCacheType;
     $lang = $lang ? wfGetLangObj($lang) : $wgContLang;
     $cache = ObjectCache::getLocalServerInstance($wgMainCacheType);
     static $dateFormatter = false;
     if (!$dateFormatter) {
         $dateFormatter = $cache->getWithSetCallback($cache->makeKey('dateformatter', $lang->getCode()), $cache::TTL_HOUR, function () use($lang) {
             return new DateFormatter($lang);
         });
     }
     return $dateFormatter;
 }
 /**
  * Returns an array of config data for this filter to be stored in the JS
  * @return null
  */
 public function getJsData()
 {
     global $wgAmericanDates;
     return $this->getParamHashes($this->getQueryResults(), $this->getActualParameters()) + array('firstDay' => $wgAmericanDates ? '0' : Message::newFromKey('srf-filtered-firstdayofweek')->inContentLanguage()->text(), 'isRTL' => wfGetLangObj(true)->isRTL());
 }
Пример #10
0
 /**
  * Returns the english language, because CSS is english, and should be handled as such.
  *
  * @param Title $title
  * @param Content $content
  * @return Language wfGetLangObj( 'en' )
  *
  * @see ContentHandler::getPageViewLanguage()
  */
 public function getPageViewLanguage(Title $title, Content $content = null)
 {
     return wfGetLangObj('en');
 }
Пример #11
0
 /**
  * Create a section edit link.  This supersedes editSectionLink() and
  * editSectionLinkForOther().
  *
  * @param $nt      Title  The title being linked to (may not be the same as
  *   $wgTitle, if the section is included from a template)
  * @param string $section The designation of the section being pointed to,
  *   to be included in the link, like "&section=$section"
  * @param string $tooltip The tooltip to use for the link: will be escaped
  *   and wrapped in the 'editsectionhint' message
  * @param $lang    string Language code
  * @return         string HTML to use for edit link
  */
 public function doEditSectionLink(Title $nt, $section, $tooltip = null, $lang = false)
 {
     // HTML generated here should probably have userlangattributes
     // added to it for LTR text on RTL pages
     $lang = wfGetLangObj($lang);
     $attribs = array();
     if (!is_null($tooltip)) {
         # Bug 25462: undo double-escaping.
         $tooltip = Sanitizer::decodeCharReferences($tooltip);
         $attribs['title'] = wfMessage('editsectionhint')->rawParams($tooltip)->inLanguage($lang)->text();
     }
     $link = Linker::link($nt, wfMessage('editsection')->inLanguage($lang)->text(), $attribs, array('action' => 'edit', 'section' => $section), array('noclasses', 'known'));
     # Run the old hook.  This takes up half of the function . . . hopefully
     # we can rid of it someday.
     $attribs = '';
     if ($tooltip) {
         $attribs = wfMessage('editsectionhint')->rawParams($tooltip)->inLanguage($lang)->escaped();
         $attribs = " title=\"{$attribs}\"";
     }
     $result = null;
     wfRunHooks('EditSectionLink', array(&$this, $nt, $section, $attribs, $link, &$result, $lang));
     if (!is_null($result)) {
         # For reverse compatibility, add the brackets *after* the hook is
         # run, and even add them to hook-provided text.  (This is the main
         # reason that the EditSectionLink hook is deprecated in favor of
         # DoEditSectionLink: it can't change the brackets or the span.)
         $result = wfMessage('editsection-brackets')->rawParams($result)->inLanguage($lang)->escaped();
         return "<span class=\"editsection\">{$result}</span>";
     }
     # Add the brackets and the span, and *then* run the nice new hook, with
     # clean and non-redundant arguments.
     $result = wfMessage('editsection-brackets')->rawParams($link)->inLanguage($lang)->escaped();
     $result = "<span class=\"editsection\">{$result}</span>";
     wfRunHooks('DoEditSectionLink', array($this, $nt, $section, $tooltip, &$result, $lang));
     return $result;
 }
/**
 * Returns message in the requested format
 * @param $key String: key of the message
 * @param $options Array: processing rules. Can take the following options:
 *   <i>parse</i>: parses wikitext to HTML
 *   <i>parseinline</i>: parses wikitext to HTML and removes the surrounding
 *       p's added by parser or tidy
 *   <i>escape</i>: filters message through htmlspecialchars
 *   <i>escapenoentities</i>: same, but allows entity references like &#160; through
 *   <i>replaceafter</i>: parameters are substituted after parsing or escaping
 *   <i>parsemag</i>: transform the message using magic phrases
 *   <i>content</i>: fetch message for content language instead of interface
 * Also can accept a single associative argument, of the form 'language' => 'xx':
 *   <i>language</i>: Language object or language code to fetch message for
 *       (overriden by <i>content</i>).
 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
 *
 * @return String
 */
function wfMsgExt($key, $options)
{
    $args = func_get_args();
    array_shift($args);
    array_shift($args);
    $options = (array) $options;
    foreach ($options as $arrayKey => $option) {
        if (!preg_match('/^[0-9]+|language$/', $arrayKey)) {
            # An unknown index, neither numeric nor "language"
            wfWarn("wfMsgExt called with incorrect parameter key {$arrayKey}", 1, E_USER_WARNING);
        } elseif (preg_match('/^[0-9]+$/', $arrayKey) && !in_array($option, array('parse', 'parseinline', 'escape', 'escapenoentities', 'replaceafter', 'parsemag', 'content'))) {
            # A numeric index with unknown value
            wfWarn("wfMsgExt called with incorrect parameter {$option}", 1, E_USER_WARNING);
        }
    }
    if (in_array('content', $options, true)) {
        $forContent = true;
        $langCode = true;
        $langCodeObj = null;
    } elseif (array_key_exists('language', $options)) {
        $forContent = false;
        $langCode = wfGetLangObj($options['language']);
        $langCodeObj = $langCode;
    } else {
        $forContent = false;
        $langCode = false;
        $langCodeObj = null;
    }
    $string = wfMsgGetKey($key, true, $langCode, false);
    if (!in_array('replaceafter', $options, true)) {
        $string = wfMsgReplaceArgs($string, $args);
    }
    $messageCache = MessageCache::singleton();
    if (in_array('parse', $options, true)) {
        $string = $messageCache->parse($string, null, true, !$forContent, $langCodeObj)->getText();
    } elseif (in_array('parseinline', $options, true)) {
        $string = $messageCache->parse($string, null, true, !$forContent, $langCodeObj)->getText();
        $m = array();
        if (preg_match('/^<p>(.*)\\n?<\\/p>\\n?$/sU', $string, $m)) {
            $string = $m[1];
        }
    } elseif (in_array('parsemag', $options, true)) {
        $string = $messageCache->transform($string, !$forContent, $langCodeObj);
    }
    if (in_array('escape', $options, true)) {
        $string = htmlspecialchars($string);
    } elseif (in_array('escapenoentities', $options, true)) {
        $string = Sanitizer::escapeHtmlAllowEntities($string);
    }
    if (in_array('replaceafter', $options, true)) {
        $string = wfMsgReplaceArgs($string, $args);
    }
    return $string;
}
Пример #13
0
	/**
	 * Create a section edit link.  This supersedes editSectionLink() and
	 * editSectionLinkForOther().
	 *
	 * @param $nt      Title  The title being linked to (may not be the same as
	 *   $wgTitle, if the section is included from a template)
	 * @param string $section The designation of the section being pointed to,
	 *   to be included in the link, like "&section=$section"
	 * @param string $tooltip The tooltip to use for the link: will be escaped
	 *   and wrapped in the 'editsectionhint' message
	 * @param $lang    string Language code
	 * @return         string HTML to use for edit link
	 */
	public function doEditSectionLink( Title $nt, $section, $tooltip = null, $lang = false ) {
		// HTML generated here should probably have userlangattributes
		// added to it for LTR text on RTL pages

		$lang = wfGetLangObj( $lang );

		$attribs = array();
		if ( !is_null( $tooltip ) ) {
			# Bug 25462: undo double-escaping.
			$tooltip = Sanitizer::decodeCharReferences( $tooltip );
			$attribs['title'] = wfMessage( 'editsectionhint' )->rawParams( $tooltip )
				->inLanguage( $lang )->text();
		}
		$link = Linker::link( $nt, wfMessage( 'editsection' )->inLanguage( $lang )->text(),
			$attribs,
			array( 'action' => 'edit', 'section' => $section ),
			array( 'noclasses', 'known' )
		);

		# Add the brackets and the span and run the hook.
		$result = '<span class="mw-editsection">'
			. '<span class="mw-editsection-bracket">[</span>'
			. $link
			. '<span class="mw-editsection-bracket">]</span>'
			. '</span>';

		wfRunHooks( 'DoEditSectionLink', array( $this, $nt, $section, $tooltip, &$result, $lang ) );
		return $result;
	}
Пример #14
0
 /**
  * Get the rendered text for previewing.
  * @return string
  */
 function getPreviewText()
 {
     global $wgOut, $wgUser, $wgTitle, $wgParser, $wgLang, $wgContLang, $wgMessageCache;
     wfProfileIn(__METHOD__);
     if ($this->mTriedSave && !$this->mTokenOk) {
         if ($this->mTokenOkExceptSuffix) {
             $note = wfMsg('token_suffix_mismatch');
         } else {
             $note = wfMsg('session_fail_preview');
         }
     } else {
         $note = wfMsg('previewnote');
     }
     $parserOptions = ParserOptions::newFromUser($wgUser);
     $parserOptions->setEditSection(false);
     $parserOptions->setIsPreview(true);
     $parserOptions->setIsSectionPreview(!is_null($this->section) && $this->section !== '');
     global $wgRawHtml;
     if ($wgRawHtml && !$this->mTokenOk) {
         // Could be an offsite preview attempt. This is very unsafe if
         // HTML is enabled, as it could be an attack.
         return $wgOut->parse("<div class='previewnote'>" . wfMsg('session_fail_preview_html') . "</div>");
     }
     # don't parse user css/js, show message about preview
     # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
     if ($this->isCssJsSubpage) {
         if (preg_match("/\\.css\$/", $this->mTitle->getText())) {
             $previewtext = wfMsg('usercsspreview');
         } else {
             if (preg_match("/\\.js\$/", $this->mTitle->getText())) {
                 $previewtext = wfMsg('userjspreview');
             }
         }
         $parserOptions->setTidy(true);
         $parserOutput = $wgParser->parse($previewtext, $this->mTitle, $parserOptions);
         $previewHTML = $parserOutput->mText;
     } elseif ($rt = Title::newFromRedirectArray($this->textbox1)) {
         $previewHTML = $this->mArticle->viewRedirect($rt, false);
     } else {
         $toparse = $this->textbox1;
         # If we're adding a comment, we need to show the
         # summary as the headline
         if ($this->section == "new" && $this->summary != "") {
             $toparse = "== {$this->summary} ==\n\n" . $toparse;
         }
         if ($this->mMetaData != "") {
             $toparse .= "\n" . $this->mMetaData;
         }
         // Parse mediawiki messages with correct target language
         if ($this->mTitle->getNamespace() == NS_MEDIAWIKI) {
             list(, $lang) = $wgMessageCache->figureMessage($this->mTitle->getText());
             $obj = wfGetLangObj($lang);
             $parserOptions->setTargetLanguage($obj);
         }
         $parserOptions->setTidy(true);
         $parserOptions->enableLimitReport();
         $parserOutput = $wgParser->parse($this->mArticle->preSaveTransform($toparse), $this->mTitle, $parserOptions);
         $previewHTML = $parserOutput->getText();
         $this->mParserOutput = $parserOutput;
         $wgOut->addParserOutputNoText($parserOutput);
         if (count($parserOutput->getWarnings())) {
             $note .= "\n\n" . implode("\n\n", $parserOutput->getWarnings());
         }
     }
     $previewhead = '<h2>' . htmlspecialchars(wfMsg('preview')) . "</h2>\n" . "<div class='previewnote'>" . $wgOut->parse($note) . "</div>\n";
     if ($this->isConflict) {
         $previewhead .= '<h2>' . htmlspecialchars(wfMsg('previewconflict')) . "</h2>\n";
     }
     wfProfileOut(__METHOD__);
     return $previewhead . $previewHTML;
 }
Пример #15
0
 /**
  * Get a message from either the content language or the user language.
  *
  * @param string $key The message cache key
  * @param bool $useDB Get the message from the DB, false to use only the localisation
  * @param string $langcode Code of the language to get the message for, if
  *                         it is a valid code create a language for that
  *                         language, if it is a string but not a valid code
  *                         then make a basic language object, if it is a
  *                         false boolean then use the current users
  *                         language (as a fallback for the old parameter
  *                         functionality), or if it is a true boolean then
  *                         use the wikis content language (also as a
  *                         fallback).
  * @param bool $isFullKey Specifies whether $key is a two part key "lang/msg".
  */
 function get($key, $useDB = true, $langcode = true, $isFullKey = false)
 {
     global $wgContLanguageCode, $wgContLang;
     $lang = wfGetLangObj($langcode);
     $langcode = $lang->getCode();
     # If uninitialised, someone is trying to call this halfway through Setup.php
     if (!$this->mInitialised) {
         return '&lt;' . htmlspecialchars($key) . '&gt;';
     }
     $message = false;
     # Normalise title-case input
     $lckey = $wgContLang->lcfirst($key);
     $lckey = str_replace(' ', '_', $lckey);
     # Try the MediaWiki namespace
     if (!$this->mDisable && $useDB) {
         $title = $wgContLang->ucfirst($lckey);
         if (!$isFullKey && $langcode != $wgContLanguageCode) {
             $title .= '/' . $langcode;
         }
         $message = $this->getMsgFromNamespace($title, $langcode);
     }
     # Try the extension array
     if ($message === false && isset($this->mExtensionMessages[$langcode][$lckey])) {
         $message = $this->mExtensionMessages[$langcode][$lckey];
     }
     if ($message === false && isset($this->mExtensionMessages['en'][$lckey])) {
         $message = $this->mExtensionMessages['en'][$lckey];
     }
     # Try the array in the language object
     if ($message === false) {
         $message = $lang->getMessage($lckey);
         if (is_null($message)) {
             $message = false;
         }
     }
     # Try the array of another language
     $pos = strrpos($lckey, '/');
     if ($message === false && $pos !== false) {
         $mkey = substr($lckey, 0, $pos);
         $code = substr($lckey, $pos + 1);
         if ($code) {
             # We may get calls for things that are http-urls from sidebar
             # Let's not load nonexistent languages for those
             $validCodes = array_keys(Language::getLanguageNames());
             if (in_array($code, $validCodes)) {
                 $message = Language::getMessageFor($mkey, $code);
                 if (is_null($message)) {
                     $message = false;
                 }
             }
         }
     }
     # Is this a custom message? Try the default language in the db...
     if (($message === false || $message === '-') && !$this->mDisable && $useDB && !$isFullKey && $langcode != $wgContLanguageCode) {
         $message = $this->getMsgFromNamespace($wgContLang->ucfirst($lckey), $wgContLanguageCode);
     }
     # Final fallback
     if ($message === false) {
         return '&lt;' . htmlspecialchars($key) . '&gt;';
     }
     return $message;
 }
Пример #16
0
 /**
  * Get the language in which the content of this page is written in
  * wikitext. Defaults to $wgContLang, but in certain cases it can be
  * e.g. $wgLang (such as special pages, which are in the user language).
  *
  * @since 1.18
  * @return Language
  */
 public function getPageLanguage()
 {
     global $wgLang;
     if ($this->isSpecialPage()) {
         // special pages are in the user language
         return $wgLang;
     }
     //TODO: use the LinkCache to cache this! Note that this may depend on user settings, so the cache should be only per-request.
     //NOTE: ContentHandler::getPageLanguage() may need to load the content to determine the page language!
     $contentHandler = ContentHandler::getForTitle($this);
     $pageLang = $contentHandler->getPageLanguage($this);
     return wfGetLangObj($pageLang);
 }
Пример #17
0
 /**
  * Get the language in which the content of the given page is written.
  *
  * This default implementation just returns $wgContLang (except for pages
  * in the MediaWiki namespace)
  *
  * Note that the pages language is not cacheable, since it may in some
  * cases depend on user settings.
  *
  * Also note that the page language may or may not depend on the actual content of the page,
  * that is, this method may load the content in order to determine the language.
  *
  * @since 1.21
  *
  * @param Title $title The page to determine the language for.
  * @param Content $content The page's content, if you have it handy, to avoid reloading it.
  *
  * @return Language The page's language
  */
 public function getPageLanguage(Title $title, Content $content = null)
 {
     global $wgContLang, $wgLang;
     $pageLang = $wgContLang;
     if ($title->getNamespace() == NS_MEDIAWIKI) {
         // Parse mediawiki messages with correct target language
         list(, $lang) = MessageCache::singleton()->figureMessage($title->getText());
         $pageLang = wfGetLangObj($lang);
     }
     wfRunHooks('PageContentLanguage', array($title, &$pageLang, $wgLang));
     return wfGetLangObj($pageLang);
 }
Пример #18
0
 /**
  * Return list of messages matching given pattern
  *
  * Example: 'feature-foo-*'
  *
  * @param string $pattern - pattern to match against ALL messages in the system
  * @return array - key/value list of matching messages
  */
 private static function resolveMessagesPattern($pattern)
 {
     $fname = __METHOD__ . "::{$pattern}";
     wfProfileIn($fname);
     self::log(__METHOD__, $pattern);
     $pattern = substr($pattern, 0, -1);
     $patternLen = strlen($pattern);
     // get list of all messages loaded by MW
     $lang = wfGetLangObj(false);
     $langCode = $lang->getCode();
     if ($lang instanceof StubUserLang) {
         $lang = $lang->_newObject();
     }
     $messageKeys = self::getAllMessageKeys($lang);
     $ret = array();
     foreach ($messageKeys as $msg) {
         if (is_array($msg)) {
             var_dump($msg);
         }
         if (substr($msg, 0, $patternLen) === $pattern) {
             $ret[$msg] = wfmsgExt($msg, array('language' => $langCode));
         }
     }
     wfProfileOut($fname);
     return $ret;
 }
Пример #19
0
 /**
  * Get the language in which the content of this page is written.
  * Defaults to $wgContLang, but in certain cases it can be e.g.
  * $wgLang (such as special pages, which are in the user language).
  *
  * @since 1.18
  * @return object Language
  */
 public function getPageLanguage()
 {
     global $wgLang;
     if ($this->getNamespace() == NS_SPECIAL) {
         // special pages are in the user language
         return $wgLang;
     } elseif ($this->isRedirect()) {
         // the arrow on a redirect page is aligned according to the user language
         return $wgLang;
     } elseif ($this->isCssOrJsPage()) {
         // css/js should always be LTR and is, in fact, English
         return wfGetLangObj('en');
     } elseif ($this->getNamespace() == NS_MEDIAWIKI) {
         // Parse mediawiki messages with correct target language
         list(, $lang) = MessageCache::singleton()->figureMessage($this->getText());
         return wfGetLangObj($lang);
     }
     global $wgContLang;
     // If nothing special, it should be in the wiki content language
     $pageLang = $wgContLang;
     // Hook at the end because we don't want to override the above stuff
     wfRunHooks('PageContentLanguage', array($this, &$pageLang, $wgLang));
     return wfGetLangObj($pageLang);
 }
Пример #20
0
 /**
  * @param $source jQuery selector for element containing the source
  * @param $lang Language code or object
  * @return string
  */
 public function adder($source, $lang)
 {
     if (!$this->editMode) {
         return '';
     }
     $target = self::jQueryPathId($this->getTextareaId());
     $source = self::jQueryPathId($source);
     $dir = wfGetLangObj($lang)->getDir();
     $params = array('onclick' => "jQuery({$target}).val(jQuery({$source}).text()).focus(); return false;", 'href' => '#', 'title' => wfMsg('translate-use-suggestion'), 'class' => 'mw-translate-adder mw-translate-adder-' . $dir);
     return Html::element('a', $params, '↓');
 }
Пример #21
0
 /**
  * Wraps the TOC in a table and provides the hide/collapse javascript.
  *
  * @param $toc String: html of the Table Of Contents
  * @param $lang String|Language|false: Language for the toc title, defaults to user language
  * @return String: full html of the TOC
  */
 public static function tocList($toc, $lang = false)
 {
     $lang = wfGetLangObj($lang);
     $title = wfMessage('toc')->inLanguage($lang)->escaped();
     return '<table id="toc" class="toc"><tr><td>' . '<div id="toctitle"><h2>' . $title . "</h2></div>\n" . $toc . "</ul>\n</td></tr></table>\n";
 }
Пример #22
0
 /**
  * Get a message from either the content language or the user language.
  *
  * First, assemble a list of languages to attempt getting the message from. This
  * chain begins with the requested language and its fallbacks and then continues with
  * the content language and its fallbacks. For each language in the chain, the following
  * process will occur (in this order):
  *  1. If a language-specific override, i.e., [[MW:msg/lang]], is available, use that.
  *     Note: for the content language, there is no /lang subpage.
  *  2. Fetch from the static CDB cache.
  *  3. If available, check the database for fallback language overrides.
  *
  * This process provides a number of guarantees. When changing this code, make sure all
  * of these guarantees are preserved.
  *  * If the requested language is *not* the content language, then the CDB cache for that
  *    specific language will take precedence over the root database page ([[MW:msg]]).
  *  * Fallbacks will be just that: fallbacks. A fallback language will never be reached if
  *    the message is available *anywhere* in the language for which it is a fallback.
  *
  * @param string $key The message key
  * @param bool $useDB If true, look for the message in the DB, false
  *   to use only the compiled l10n cache.
  * @param bool|string|object $langcode Code of the language to get the message for.
  *   - If string and a valid code, will create a standard language object
  *   - If string but not a valid code, will create a basic language object
  *   - If boolean and false, create object from the current users language
  *   - If boolean and true, create object from the wikis content language
  *   - If language object, use it as given
  * @param bool $isFullKey Specifies whether $key is a two part key "msg/lang".
  *
  * @throws MWException When given an invalid key
  * @return string|bool False if the message doesn't exist, otherwise the
  *   message (which can be empty)
  */
 function get($key, $useDB = true, $langcode = true, $isFullKey = false)
 {
     global $wgContLang;
     if (is_int($key)) {
         // Fix numerical strings that somehow become ints
         // on their way here
         $key = (string) $key;
     } elseif (!is_string($key)) {
         throw new MWException('Non-string key given');
     } elseif ($key === '') {
         // Shortcut: the empty key is always missing
         return false;
     }
     // For full keys, get the language code from the key
     $pos = strrpos($key, '/');
     if ($isFullKey && $pos !== false) {
         $langcode = substr($key, $pos + 1);
         $key = substr($key, 0, $pos);
     }
     // Normalise title-case input (with some inlining)
     $lckey = MessageCache::normalizeKey($key);
     Hooks::run('MessageCache::get', array(&$lckey));
     if (ord($lckey) < 128) {
         $uckey = ucfirst($lckey);
     } else {
         $uckey = $wgContLang->ucfirst($lckey);
     }
     // Loop through each language in the fallback list until we find something useful
     $lang = wfGetLangObj($langcode);
     $message = $this->getMessageFromFallbackChain($lang, $lckey, $uckey, !$this->mDisable && $useDB);
     // If we still have no message, maybe the key was in fact a full key so try that
     if ($message === false) {
         $parts = explode('/', $lckey);
         // We may get calls for things that are http-urls from sidebar
         // Let's not load nonexistent languages for those
         // They usually have more than one slash.
         if (count($parts) == 2 && $parts[1] !== '') {
             $message = Language::getMessageFor($parts[0], $parts[1]);
             if ($message === null) {
                 $message = false;
             }
         }
     }
     // Post-processing if the message exists
     if ($message !== false) {
         // Fix whitespace
         $message = str_replace(array('&#32;', '&nbsp;', '&#160;'), array(' ', " ", " "), $message);
     }
     return $message;
 }
Пример #23
0
/**
 * Returns message in the requested format
 *
 * @deprecated since 1.18
 *
 * @param string $key Key of the message
 * @param array $options Processing rules.
 *   Can take the following options:
 *     parse: parses wikitext to HTML
 *     parseinline: parses wikitext to HTML and removes the surrounding
 *       p's added by parser or tidy
 *     escape: filters message through htmlspecialchars
 *     escapenoentities: same, but allows entity references like &#160; through
 *     replaceafter: parameters are substituted after parsing or escaping
 *     parsemag: transform the message using magic phrases
 *     content: fetch message for content language instead of interface
 *   Also can accept a single associative argument, of the form 'language' => 'xx':
 *     language: Language object or language code to fetch message for
 *       (overridden by content).
 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
 *
 * @return string
 */
function wfMsgExt($key, $options)
{
    wfDeprecated(__METHOD__, '1.21');
    $args = func_get_args();
    array_shift($args);
    array_shift($args);
    $options = (array) $options;
    $validOptions = array('parse', 'parseinline', 'escape', 'escapenoentities', 'replaceafter', 'parsemag', 'content');
    foreach ($options as $arrayKey => $option) {
        if (!preg_match('/^[0-9]+|language$/', $arrayKey)) {
            // An unknown index, neither numeric nor "language"
            wfWarn("wfMsgExt called with incorrect parameter key {$arrayKey}", 1, E_USER_WARNING);
        } elseif (preg_match('/^[0-9]+$/', $arrayKey) && !in_array($option, $validOptions)) {
            // A numeric index with unknown value
            wfWarn("wfMsgExt called with incorrect parameter {$option}", 1, E_USER_WARNING);
        }
    }
    if (in_array('content', $options, true)) {
        $forContent = true;
        $langCode = true;
        $langCodeObj = null;
    } elseif (array_key_exists('language', $options)) {
        $forContent = false;
        $langCode = wfGetLangObj($options['language']);
        $langCodeObj = $langCode;
    } else {
        $forContent = false;
        $langCode = false;
        $langCodeObj = null;
    }
    $string = wfMsgGetKey($key, true, $langCode, false);
    if (!in_array('replaceafter', $options, true)) {
        $string = wfMsgReplaceArgs($string, $args);
    }
    $messageCache = MessageCache::singleton();
    $parseInline = in_array('parseinline', $options, true);
    if (in_array('parse', $options, true) || $parseInline) {
        $string = $messageCache->parse($string, null, true, !$forContent, $langCodeObj);
        if ($string instanceof ParserOutput) {
            $string = $string->getText();
        }
        if ($parseInline) {
            $string = Parser::stripOuterParagraph($string);
        }
    } elseif (in_array('parsemag', $options, true)) {
        $string = $messageCache->transform($string, !$forContent, $langCodeObj);
    }
    if (in_array('escape', $options, true)) {
        $string = htmlspecialchars($string);
    } elseif (in_array('escapenoentities', $options, true)) {
        $string = Sanitizer::escapeHtmlAllowEntities($string);
    }
    if (in_array('replaceafter', $options, true)) {
        $string = wfMsgReplaceArgs($string, $args);
    }
    return $string;
}
Пример #24
0
 /**
  * Get the language in which the content of this page is written in
  * wikitext. Defaults to $wgContLang, but in certain cases it can be
  * e.g. $wgLang (such as special pages, which are in the user language).
  *
  * @since 1.18
  * @return Language
  */
 public function getPageLanguage()
 {
     global $wgLang, $wgLanguageCode;
     if ($this->isSpecialPage()) {
         // special pages are in the user language
         return $wgLang;
     }
     // Checking if DB language is set
     if ($this->mDbPageLanguage) {
         return wfGetLangObj($this->mDbPageLanguage);
     }
     if (!$this->mPageLanguage || $this->mPageLanguage[1] !== $wgLanguageCode) {
         // Note that this may depend on user settings, so the cache should
         // be only per-request.
         // NOTE: ContentHandler::getPageLanguage() may need to load the
         // content to determine the page language!
         // Checking $wgLanguageCode hasn't changed for the benefit of unit
         // tests.
         $contentHandler = ContentHandler::getForTitle($this);
         $langObj = wfGetLangObj($contentHandler->getPageLanguage($this));
         $this->mPageLanguage = array($langObj->getCode(), $wgLanguageCode);
     } else {
         $langObj = wfGetLangObj($this->mPageLanguage[0]);
     }
     return $langObj;
 }
Пример #25
0
 /**
  * Get a message from either the content language or the user language.
  *
  * @param string $key the message cache key
  * @param $useDB Boolean: get the message from the DB, false to use only
  *               the localisation
  * @param bool|string $langcode Code of the language to get the message for, if
  *                  it is a valid code create a language for that language,
  *                  if it is a string but not a valid code then make a basic
  *                  language object, if it is a false boolean then use the
  *                  current users language (as a fallback for the old
  *                  parameter functionality), or if it is a true boolean
  *                  then use the wikis content language (also as a
  *                  fallback).
  * @param $isFullKey Boolean: specifies whether $key is a two part key
  *                   "msg/lang".
  *
  * @throws MWException
  * @return string|bool
  */
 function get($key, $useDB = true, $langcode = true, $isFullKey = false)
 {
     global $wgLanguageCode, $wgContLang;
     if (is_int($key)) {
         // "Non-string key given" exception sometimes happens for numerical strings that become ints somewhere on their way here
         $key = strval($key);
     }
     if (!is_string($key)) {
         throw new MWException('Non-string key given');
     }
     if (strval($key) === '') {
         # Shortcut: the empty key is always missing
         return false;
     }
     $lang = wfGetLangObj($langcode);
     if (!$lang) {
         throw new MWException("Bad lang code {$langcode} given");
     }
     $langcode = $lang->getCode();
     $message = false;
     # Normalise title-case input (with some inlining)
     $lckey = str_replace(' ', '_', $key);
     if (ord($key) < 128) {
         $lckey[0] = strtolower($lckey[0]);
         $uckey = ucfirst($lckey);
     } else {
         $lckey = $wgContLang->lcfirst($lckey);
         $uckey = $wgContLang->ucfirst($lckey);
     }
     # Try the MediaWiki namespace
     if (!$this->mDisable && $useDB) {
         $title = $uckey;
         if (!$isFullKey && $langcode != $wgLanguageCode) {
             $title .= '/' . $langcode;
         }
         $message = $this->getMsgFromNamespace($title, $langcode);
     }
     # Try the array in the language object
     if ($message === false) {
         $message = $lang->getMessage($lckey);
         if (is_null($message)) {
             $message = false;
         }
     }
     # Try the array of another language
     if ($message === false) {
         $parts = explode('/', $lckey);
         # We may get calls for things that are http-urls from sidebar
         # Let's not load nonexistent languages for those
         # They usually have more than one slash.
         if (count($parts) == 2 && $parts[1] !== '') {
             $message = Language::getMessageFor($parts[0], $parts[1]);
             if (is_null($message)) {
                 $message = false;
             }
         }
     }
     # Is this a custom message? Try the default language in the db...
     if (($message === false || $message === '-') && !$this->mDisable && $useDB && !$isFullKey && $langcode != $wgLanguageCode) {
         $message = $this->getMsgFromNamespace($uckey, $wgLanguageCode);
     }
     # Final fallback
     if ($message === false) {
         return false;
     }
     # Fix whitespace
     $message = strtr($message, array('&#32;' => ' ', '&nbsp;' => " ", '&#160;' => " "));
     return $message;
 }
Пример #26
0
 /**
  * Get a DateFormatter object
  *
  * @param $lang Language|string|null In which language to format the date
  * 		Defaults to the site content language
  * @return DateFormatter object
  */
 public static function &getInstance($lang = null)
 {
     global $wgMemc, $wgContLang;
     static $dateFormatter = false;
     $lang = $lang ? wfGetLangObj($lang) : $wgContLang;
     $key = wfMemcKey('dateformatter', $lang->getCode());
     if (!$dateFormatter) {
         $dateFormatter = $wgMemc->get($key);
         if (!$dateFormatter) {
             $dateFormatter = new DateFormatter($lang);
             $wgMemc->set($key, $dateFormatter, 3600);
         }
     }
     return $dateFormatter;
 }
Пример #27
0
 /**
  * Set the language in which the diff text is written
  * (Defaults to page content language).
  * @param Language|string $lang
  * @since 1.19
  */
 public function setTextLanguage($lang)
 {
     $this->mDiffLang = wfGetLangObj($lang);
 }
Пример #28
0
 /**
  * Create a section edit link.  This supersedes editSectionLink() and
  * editSectionLinkForOther().
  *
  * @param Title $nt The title being linked to (may not be the same as
  *   the current page, if the section is included from a template)
  * @param string $section The designation of the section being pointed to,
  *   to be included in the link, like "&section=$section"
  * @param string $tooltip The tooltip to use for the link: will be escaped
  *   and wrapped in the 'editsectionhint' message
  * @param string $lang Language code
  * @return string HTML to use for edit link
  */
 public function doEditSectionLink(Title $nt, $section, $tooltip = null, $lang = false)
 {
     // HTML generated here should probably have userlangattributes
     // added to it for LTR text on RTL pages
     $lang = wfGetLangObj($lang);
     $attribs = array();
     if (!is_null($tooltip)) {
         # Bug 25462: undo double-escaping.
         $tooltip = Sanitizer::decodeCharReferences($tooltip);
         $attribs['title'] = wfMessage('editsectionhint')->rawParams($tooltip)->inLanguage($lang)->text();
     }
     $links = array('editsection' => array('text' => wfMessage('editsection')->inLanguage($lang)->escaped(), 'targetTitle' => $nt, 'attribs' => $attribs, 'query' => array('action' => 'edit', 'section' => $section), 'options' => array('noclasses', 'known')));
     Hooks::run('SkinEditSectionLinks', array($this, $nt, $section, $tooltip, &$links, $lang));
     $result = '<span class="mw-editsection"><span class="mw-editsection-bracket">[</span>';
     $linksHtml = array();
     foreach ($links as $k => $linkDetails) {
         $linksHtml[] = Linker::link($linkDetails['targetTitle'], $linkDetails['text'], $linkDetails['attribs'], $linkDetails['query'], $linkDetails['options']);
     }
     $result .= implode('<span class="mw-editsection-divider">' . wfMessage('pipe-separator')->inLanguage($lang)->text() . '</span>', $linksHtml);
     $result .= '<span class="mw-editsection-bracket">]</span></span>';
     // Deprecated, use SkinEditSectionLinks hook instead
     Hooks::run('DoEditSectionLink', array($this, $nt, $section, $tooltip, &$result, $lang), '1.25');
     return $result;
 }
 /**
  * Overrides Skin::doEditSectionLink
  * @param Title $nt
  * @param string $section
  * @param string $tooltip
  * @param string $lang
  * @return string
  */
 public function doEditSectionLink(Title $nt, $section, $tooltip = null, $lang = false)
 {
     if ($this->isAllowedPageAction('edit')) {
         $lang = wfGetLangObj($lang);
         $message = wfMessage('mobile-frontend-editor-edit')->inLanguage($lang)->text();
         return Html::element('a', array('href' => '#/editor/' . $section, 'title' => wfMessage('editsectionhint', $tooltip)->inLanguage($lang)->text(), 'data-section' => $section, 'class' => MobileUI::iconClass('edit-enabled', 'element', 'edit-page icon-32px')), $message);
     }
 }
	/**
	 * Make section elements.
	 *
	 * @param $legend \string Legend as raw html.
	 * @param $type \string Contents of type class.
	 * @param $content \string Contents as raw html.
	 * @param $lang Language The language in which the text is written.
	 * @return \string Section element as html.
	 */
	public static function makeSectionElement( $legend, $type, $content, $lang = null ) {
		$containerParams = array( 'class' => "mw-tpt-sp-section mw-tpt-sp-section-type-{$type}" );
		$legendParams = array( 'class' => 'mw-tpt-sp-legend' );
		$contentParams = array( 'class' => 'mw-tpt-sp-content' );
		if ( $lang ) {
			$contentParams['dir'] = wfGetLangObj( $lang )->getDir();
			$contentParams['lang'] = wfGetLangObj( $lang )->getCode();
		}

		$items = new TagContainer();
		$items[] = new HtmlTag( 'div', new RawHtml( $legend ), $legendParams );
		$items[] = new HtmlTag( 'div', new RawHtml( $content ), $contentParams );

		return new HtmlTag( 'div', $items, $containerParams );
	}