Модул:Languages — разлика између измена

Iz Vojne Enciklopedije
Пређи на навигацију Пређи на претрагу
мНема описа измене
 
м (1 измена увезена)
Ред 1: Ред 1:
-- Модул за рад са језицима ISO 639
--[=[
Not globally exposed. Internal function only.


-- учитавање модула са таблицом језичких података
language_subpages( frame, transform, options )
local languages = mw.loadData('Module:Languages/data')
Parameters
local p = {}
    frame:    The frame that was passed to the method invoked. The first argument or the page argument will be respected.
    transform: A transform function. Example: function( basepagename, subpagename, code, langname ) end
    options:  An object with options. Example: { abort= { on=function() end, time=0.8 } }
        Following options are available:
        abort: Aborts iterating over the subpages if one of the conditions is met. If the process is aborted, nil is returned!
            on: Function to be called if an abort-condition was met.
            cycles: The maximum number of subpages to run over.
            time: Maximum time to spend running over the subpages.


-- проверава да ли је задани параметар празан
]=]
local function isEmpty(s)
function language_subpages( frame, transform, options )
return s == nil or s == ''
    local args, pargs, options = frame.args, ( frame:getParent() or {} ).args or {}, options or {};
end
    local title = args.page or args[1] or pargs.page or pargs[1] or "";
    local abort = options.abort or {};
    local at, clock = type( abort.on ), os.clock();
    local ac = function()
        if  at == 'function' or ( at == 'table' and getmetatable(abort.on).__call ) then
            abort.on();
        end
    end
    local tt = type( transform );
    local page = require( 'Module:Page' );
 
    title = page.clean(title);
 
    if tt == 'function' or ( tt == 'table' and getmetatable(transform).__call ) then
        local fetch, pages, langcode, langname = mw.language.fetchLanguageName, {};
--[==[


-- помоћна функција која уклања размаке
    / \
local function trimstr(s)
    / | \
  return (s:gsub("^%s*(.-)%s*$", "%1"))
  /  ·  \
  ¯¯¯¯¯¯¯
  Page.subpages() no longer works because it attempted to parse the HTML content generated by
  calling the parser function "Special:Prefixindex:" which is no longer expanded in Lua but
  converted to a "stripped tag" (containing a unique identifier surrounded by ASCII DEL characters)
  representing the tag name and its parameters.
  The actual expansion of stripped tags can no longer be performed in Lua.
  Now unstripping these tags just kills ALL these tags (except "wiki" tags) instead of performing
  their expansion by running the extension code. Only MediaWiki can unstrip these tags in texts after
  they have been returned by Lua.
  For this reason, page.subpages() is now completely empty (Module:Page no longer works).
  This cannot be bypassed, except by using a Scribunto extension library if lifting the limits set by mw.unstrip.
  Note that "Special:Prefixindex:" is also costly, even if it just requires a single database query to
  get all subpages, instead of one costly #ifexist or one costly mw.title() property reading per
  tested subpage to know if it exists.
  For now there's still no reliable way to get a list of subpages, or performing queries similar to
  the [[Special:Prefixindex]] page or list members of a category like when viewing a category page.
  Ideally, there should exist a method for such queries on Title objects returned by the mw.title library;
  but for now there's none.
  In Lua now, the only expansion possible with an immediate effect is the expansion of standard templates,
  all special tags or special pages, or parser function extensions do not work (Only the #expr parser
  function is supported by using an external Scribunto library).
--]==]
        for pg in page.subpages( title, { ignoreNS=true } ) do
            if abort.cycles then
                abort.cycles = abort.cycles - 1
                if 0 == abort.cycles then return ac()  end
            end
            if abort.time then
                if (os.clock() - clock) > abort.time then return ac()  end
            end
            if mw.ustring.len( pg ) <= 12 then
                langcode = string.lower( pg );
                langname = fetch( langcode );
                if langname ~= '' then
                    table.insert( pages, transform( title, pg, langcode, langname ) );
                end
            end
        end
        return pages;
    end
    return {};
end
end


-- добавља језички код, враћа везу и нормализовани код језика (или празан текстуални низ)
function cloneArgs(frame)
local function get_lang_data(code)
     local args, pargs = {}, {}
     local l = languages[code];
    for k,v in pairs( frame.args ) do args[k] = v end
     if l ~= nil then
     if frame:getParent() then
         return "[[" .. l[2] .. "|" .. l[1] .. "]]", code
         for k,v in pairs( frame:getParent().args ) do pargs[k] = v end
    elseif code ~= "" then
        return code, ""
    else
        return "", ""
     end
     end
    return args, pargs;
end
end


function p.getRefHtmlFrame( frame )
 
return p.getRefHtml( trimstr( frame.args[1] ) )
 
local p = {};
 
--[=[
Usage:
{{#invoke:languages|internal|Template:Adjective}}
]=]
function p.internal(frame)
    pages = language_subpages( frame, function( title, page, code, name )
        return mw.ustring.format( '<span lang="%s" xml:lang="%s" class="language lang-%s"><bdi>[[%s/%s|%s]]</bdi></span>',
            code, code, code, title, page, name
        );
    end);
    return table.concat( pages, '&nbsp;·&nbsp;' );
end
end


function p.getRefHtml( wikidataItemId )
--[=[
local codeByItemId = mw.loadData( "Module:Wikidata/Language-codes" )
Usage:
local code = codeByItemId[ wikidataItemId ];
{{#invoke:languages|external|Template:Adjective}}
if code == nil then
]=]
mw.log( 'Језички код није пронађен за ' .. wikidataItemId )
function p.external(frame)
return ""
    pages = language_subpages( frame, function( title, page, code, name )
else
        return mw.ustring.format( '<span lang="%s" xml:lang="%s" class="language lang-%s"><bdi>[%s/%s %s]</bdi></span>',
    local l = languages[code];
            code, code, code, tostring( mw.uri.fullUrl( title ) ), page:gsub( ' ', '_' ), name
if l == nil then
        );
mw.log( 'Опис језика за код ' .. code .. ' није пронађен' )
    end);
        return ""
    return table.concat( pages, '&nbsp;| ' );
    else
        return '<span class="ref-info" title="' .. l[ 2 ] .. '" style="font-size:85%; cursor:help; color:#888;">(' .. l[ 1 ] .. ')</span>'
    end
end
end
end


-- прихвата zh код, враћа скраћеницу
--[=[
function p.abbr(frame)
forEachLanguage
local code = trimstr( frame.args[1] )
 
if not isEmpty(code) then
This function iterates over all language codes known to MediaWiki based on a maintained list
return (languages[code] and languages[code][1] or '')
replacing patterns in a pattern-string for each language
end
 
end
Usage:
{{#invoke:Languages|forEachLanguage
  |pattern=patternstring
  |before=string to insert before iteration
  |after=string added after iteration
  |sep=separator string between iterations
  |inLang=langcode used for $lnTrP and $lnTrUC1
}}
 
Parameters
    pattern: A pattern string which is processed for each language and which is concatenated at the end and returned as one string
    before: A string that is inserted before the concatenated result
    after: A string that is inserted after the concatenated result
    sep: A string that is inserted between each line created from the pattern while iterating (like ProcessedPattern_sep_ProcessedPattern_sep_ProcessedPattern)
    inLang: Langcode to use for $lnTrP and $lnTrUC1
 
Patterns:
    $lc - language code such as en or de
    $lnP - language name in own language (autonym)
    $lnUC1 - language name in own language (autonym), first letter upper case
    $lnTrP - language name translated to the language requested by language code passed to inLang
    $lnTrUC1 - language name translated to the language requested by language code passed to inLang, first letter upper case
 
Example
  {{#invoke:Languages|forEachLanguage|pattern=<span lang="$lc" xml:lang="$lc" class="language lang-$lc">[[Page/$lc|$lnP]]</span>}}
]=]
 
-- =p.forEachLanguage({ args= { pattern = "$lc - $lnTrP\n", inLang = "en" } })
function p.forEachLanguage(frame)
    local l = require( "Module:Languages/List" )


-- прихвата zh|我|tt|мин код, враћа наслов ставке из Module:Languages/data
    local ret = {}
function p.name(frame)
    local lang    = mw.language
local code = trimstr( frame.args[1] )
    local line
if code ~= nil and code ~= '' then
    local pattern = frame.args.pattern  or frame.args[1] or ""
return (languages[code] and languages[code][2] or '')
    local prefix  = frame.args.before    or frame.args[2] or ""
end
    local postfix = frame.args.after    or frame.args[3] or ""
end
    local sep    = frame.args.sep      or frame.args.separator or frame.args[4] or ""
    local inLang  = frame.args.inLang    or frame.args[5] or nil


-- прихвата zh|我|tt|мин код, враћа списак одвојен зарезом
    local langNameUCFirstReq          = not not pattern:find( "$lnUC1", 1, true )
function p.list(frame)
    local langNameReq                  = not not pattern:find( "$lnP", 1, true ) or langNameUCFirstReq
     local curr_lang = nil
    local langNameTranslatedUCFirstReq = not not pattern:find( "$lnTrUC1", 1, true )
     local result = nil
    local langNameTranslatedReq        = not not pattern:find( "$lnTrP", 1, true ) or langNameTranslatedUCFirstReq
    local contentLangInstance = mw.language.getContentLanguage()
     local inLangLangInstance
    local l = mw.language.fetchLanguageNames() -- autonyms
     local lTr
    local lcIdList = require( 'Module:Languages/List' ).getSortedList( l )


     for n, v in frame:argumentPairs() do
     if langNameTranslatedReq then
local trimmed = trimstr(v)
        inLangLangInstance = --[==[
if curr_lang == nil then
            mw.getLanguage( inLang ) -- Quota hit in :ucfirst() if using too many langInstances
if trimmed ~= '' then
            --]==] contentLangInstance
-- ако језички код недостаје, остаје претходни
        lTr = mw.language.fetchLanguageNames( inLang ) -- translated names
curr_lang = trimstr(v)
end
else
if trimmed ~= '' then
local link, lang_code = get_lang_data(curr_lang)
local list_item
if lang_code ~= '' then
list_item = link .. "&nbsp;<span dir='auto' lang='" .. lang_code .. "'>" .. trimmed .. "</span>"
else
list_item = link .. " <span class='unknown-foreign-lang'>" .. trimmed .. "</span>".."[[Категорија:Википедија:Чланци са непознатим језиком]]"
end
if result == nil then
result = list_item
else
result = result .. ", " .. list_item
end
else
-- празан текст — значи да је тренутни језик исти као следећи
local link, lang_code = get_lang_data(curr_lang)
if result == nil then
result = link
else
result = result .. ", " .. link
end
end
curr_lang = nil
      end
     end
     end
      
 
    -- просто #invoke:Languages|list|yue и даље треба да врати везу без текста
     for _, lcId in pairs( lcIdList ) do
    if curr_lang ~= nil then
        local subst = lcId:gsub('%%', '%%%%')
        local link, lang_code = get_lang_data(curr_lang)
        line = pattern:gsub( "%$lc", subst )
         if result ~= nil then
        local langName, langInstance
             result = result .. ", " .. link
        -- autonym (name of lcId in locale lcId)
         else
        if langNameReq then
             result = link
            langName = l[lcId]
            subst = langName:gsub('%%', '%%%%')
            line = line:gsub( "%$lnP", subst )
        end
         if langNameUCFirstReq then
             langInstance = --[==[
                mw.getLanguage( lcId ) -- Quota hit in :ucfirst() if using too many langInstances
                --]==] contentLangInstance
            langName = langInstance:ucfirst( langName )
            subst = langName:gsub('%%', '%%%%')
            line = line:gsub( "%$lnUC1", subst )
        end
 
        -- translated name (name of lcId in locale inLang)
        if langNameTranslatedReq then
            langName = lTr[lcId]
            subst = langName:gsub('%%', '%%%%')
            line = line:gsub( "%$lnTrP", subst )
        end
         if langNameTranslatedUCFirstReq then
            langName = inLangLangInstance:ucfirst( langName )
            subst = langName:gsub('%%', '%%%%')
             line = line:gsub( "%$lnTrUC1", subst )
         end
         end
        table.insert(ret, line)
     end
     end
     return result
     return prefix .. table.concat( ret, sep ) .. postfix
end
 
--[=[
Provide logic for [[Template:Lle]] (Language Links external, to be substituted)
]=]
function p.lle(frame)
    local ret
    local pattern = "{{<includeonly/>subst:#ifexist:{{{1}}}/$lc|[{{fullurl:{{{1}}}/$lc}} $lnUC1]&nbsp;{{<includeonly/>subst:!}} <!--\n-->}}"
    ret = p.forEachLanguage({ args= { pattern = pattern } })
    ret = frame:preprocess(ret)
    return ret
end
end


-- прихвата zh|tt код, враћа ref-zh, ref-tt
--[=[
function p.list_ref(frame)
Provide logic for [[Template:Ll]] (Language Links, to be substituted)
     local result = ''
]=]
     local v = frame.args['в'] or nil
function p.ll(frame)
local ref = nil
     local ret
    local pattern = "{{<includeonly/>subst:#ifexist:{{{1}}}/$lc|[[{{{1}}}/$lc{{<includeonly/>subst:!}}$lnUC1]]&nbsp;{{<includeonly/>subst:!}} <!--\n-->}}"
     ret = p.forEachLanguage({ args= { pattern = pattern } })
    ret = frame:preprocess(ret)
    return ret
end


if v then
ref = '&nbsp;<span class="ref-info" style="cursor:help;" title="на %2%">&#091;%1%&#093;</span>'
else
ref = '&nbsp;<span class="ref-info" style="cursor:help;" title="на %2%">(%1%)</span>'
end


    for x, lg in pairs( frame.args ) do
--------------------------------------------------------
local code = trimstr(lg)
--- Different approaches for [[Template:Lang links]] ---
if code ~= '' and code ~= 'в' then
--------------------------------------------------------
local l = languages[code]
 
if l and l ~= nil then
--[=[
result = result .. mw.ustring.gsub(mw.ustring.gsub(ref, '%%2%%', p._transform_lang(code)), '%%1%%', l[1])
Provide logic for [[Template:Lang links]]
else
Using a cute Hybrid-Method:
result = result .. frame:expandTemplate{ title = 'ref-' .. code } .. '[[Категорија:Википедија:Чланци са непознатим језиком (ref)]]'
    First check the subpages which is quite fast; if there are too many fall back to checking for each language page individually
end
]=]
end
 
-- =p.langLinksNonExpensive({ args= { page='Commons:Picture of the Year/2010' }, getParent=function() end })
-- =p.langLinksNonExpensive({ args= { page='Main Page' }, getParent=function() end })
-- =p.langLinksNonExpensive({ args= { page='Template:No_source_since' }, getParent=function() end })
-- =p.langLinksNonExpensive({ args= { page='MediaWiki:Gadget-HotCat' }, getParent=function() end })
function p.langLinksNonExpensive(frame)
    local args, pargs = frame.args, ( frame:getParent() or {} ).args or {};
    local title = args.page or args[1] or pargs.page or pargs[1] or "";
    local contentLangInstance = mw.language.getContentLanguage();
    local pages2
    if frame.preprocess == nil then
        frame = mw.getCurrentFrame()
     end
     end
    --[==[
    local options = { abort= { time=3.5, on=function()
            pages2 = p.forEachLanguage({ args= { pattern = '{{#ifexist:' .. title .. '/$lc|[[' .. title .. '/$lc|$lnUC1]]&nbsp;&#124;&#32;}}' } })
        end } }
    local pages = language_subpages( frame, function( basepagename, subpagename, code, langname )
        return mw.ustring.format( '<span lang="%s" xml:lang="%s" class="language lang-%s" style="white-space:nowrap"><bdi>[[%s/%s|%s]]</bdi></span>&nbsp;| ',
            code, code, code, basepagename, subpagename, contentLangInstance:ucfirst( langname ) )
    end, options );
    return pages2 and frame:preprocess(pages2) or table.concat(  pages, '' );
    ]==]
    return frame:preprocess( p.forEachLanguage({ args= { pattern = '{{#ifexist:' .. title .. '/$lc|[[' .. title .. '/$lc|$lnUC1]]&nbsp;&#124;&#32;}}' } }) )
end


    return result
---------------------------------------------------------
end
----------------- [[Template:Autolang]] -----------------
---------------------------------------------------------
--[[
  Works like {{autotranslate}} just allowing an unlimited number of arguments, even named arguments.
  It's doing Magic! No arguments should be passed to {{#invoke:}}
]]


-- Приказује име језика у предложеном падежу
function p.autolang(frame)
function p._transform_lang(code)
    local args, pargs = cloneArgs( frame )
if isEmpty(languages[code]) then return '&lt;непознат код ' .. code .. '&gt;' end
     if nil == args.useargs then
     if languages[code][3] then return languages[code][3] end
         if not args.base then args = pargs end
    local ln = mw.ustring.lower(
     elseif 'both' == args.useargs then
        languages[code] and languages[code][2]
        for k,v in pairs(args) do pargs[k] = v end
         or mw.language.fetchLanguageName(code,'sr')
         args = pargs
    ):gsub('%s+језик%s+',  ' '):gsub('%s*%(?језик%)?%s*',  '')
    elseif 'parent' == args.useargs then
    if not ln then return 'језик с ISO-кодом '..code..' (?)' end
         args = pargs
     if ln:match('.*лингва$') then return ln:gsub('а$','е') end
         if pargs.base and not args.base then
    if mw.ustring.match(ln,'[сц]кий$') or ln:match('ный$') or mw.ustring.match(ln,'[сц]кий%s%b()$') or ln:match('ный%s%b()$')
             args.base = pargs.base
    then
         ln = mw.ustring.gsub(
            mw.ustring.gsub(ln, 'н([ыи])й(%A)', function(y,s) return (y=='ы' and 'ном' or 'нем')..s end)
                :gsub('ный$', 'ном'),
            '([сц]к)ий(%A)', '%1ом%2'
         ):gsub('ский$', 'ском'):gsub('цкий$', 'цком');
         if ln:match('%)$') and not (ln:match('ом%)$') or ln:match('нем%)$')) -- «језик» перед уточнением, если оно не склоняется
        then  
             local r,s=ln:gsub('(%s)(%b())$','%1језик%1%2');
            if s==1 then return r end
         end
         end
        return ln..' језик'
    else
        return 'језик '..ln
     end
     end
end
    local base = args.base
    local userlang = frame:preprocess( '{{int:lang}}' )
    local tl, tlns = 'Template:', 10
    local tlb, fallback1, currenttemplate
    local fallback, contentlang = mw.text.split( userlang, '-', true )[1], mw.language.getContentLanguage():getCode()
 
    local createReturn = function(title)
        local ret
        local tlargs = {}
        -- When LUA is invoked, templates are already expanded. This must be respected.
        return frame:expandTemplate{ title = title, args = args }
    end
 
    if not base then
        return ("'autolang' in [[Module:Languages]] was called but the 'base' parameter could not be found." ..
            "The base parameter specifies the template that's subpages will be sought for a suitable translation.")
    end
    tlb = tl .. base .. '/'
 
    currenttemplate = tlb .. userlang
    local ok, exists = pcall( function()
        return mw.title.new( currenttemplate, tlns ).exists
    end )
    if ok and exists then
        return createReturn(currenttemplate)
    end
 
    fallback1 = frame:preprocess( '{{Fallback|1=' .. base .. '|2=' .. userlang .. '}}' )
    if fallback1 ~= contentlang then
        return createReturn(tlb .. fallback1)
    end


function p.transform_lang(frame)
    currenttemplate = tlb .. fallback
return p._transform_lang(trimstr(frame.args[1]))
    local ok, exists = pcall( function()
end
        return mw.title.new( currenttemplate, tlns ).exists
    end )
    if ok and exists then
        return createReturn(currenttemplate)
    end


-- Проверава постоји ли страница и преусмјеравање
    currenttemplate = tlb .. contentlang
local function getTitle(page)
    local ok, exists = pcall( function()
local success, result = pcall(function()
        return mw.title.new( currenttemplate, tlns ).exists
local title = mw.title.new(page)
    end )
return { title.exists, title.isRedirect }
    if ok and exists then
end)
        return createReturn(currenttemplate)
return success and result or nil
    end
    return createReturn(tl .. base)
end
end


-- Помоћна функција за {{Непреведено 5}}: видети шаблон
--[=[
function p._newIW(title, text, lang, page, state, nocat)
Usage:
local mwlang = mw.getContentLanguage()
{{#invoke:languages|isKnownLanguageTag|gsw}} -> 1
local origPage = page
{{#invoke:languages|isKnownLanguageTag|doesNotExist}} ->
]=]
-- Слике за стару функцију приказа статуса
function p.isKnownLanguageTag(frame)
local states = {
    return mw.language.isKnownLanguageTag( frame.args[1] or frame.args.tag or frame.args.code or '' ) and '1' or ''
['СЧ'] = {'Википедија:Сјајни чланци','Сјајан чланак','Small Skew Star SVG.svg'},
['ДЧ'] = {'Википедија:Добри чланци','Добар чланак','Blue star unboxed.svg'},
['ИС'] = {'Википедија:Изабрани спискови','Избрани списак','Purple star unboxed.svg'}
}
-- Категорије шаблона
local categoryErrors = '[[Категорија:Википедија:Чланци са погрешно попуњеним шаблоном Непреведено]]'
local categoryExists = '[[Категорија:Википедија:Чланци са застарелим шаблоном Непреведено]]'
local categoryRedirect = '[[Категорија:Википедија:Захтеви за замену преусмеравања преводима]]'
-- Проверава постојање параметара и замењује их алтернативним
if isEmpty(text) then
text = title
end
if isEmpty(lang) then
lang = "en"
end
if isEmpty(page) then
page = title
end
-- Ствара шаблон
if title ~= '{{{1}}}' then
local this = mw.title.getCurrentTitle()
local titleObj = getTitle(title)
local ifExists, ifRedirect
local type = ''
local s = ''
local langName = ''
if lang ~= 'd' then
if isEmpty(languages[lang]) then
if this.namespace == 0 and isEmpty(nocat) then
s = s .. categoryErrors
end
else
langName = ' data-lang-name="' .. (languages[lang][1] and languages[lang][1] or '???') .. '"'
end
end
-- Проверава ограничење позива
if titleObj ~= nil then
ifExists = titleObj[1]
ifRedirect = titleObj[2]
end
-- Приказује везу за преусмеравање или црвену везу
local class = (ifExists and (ifRedirect and ' iw--redirect' or ' iw--exists') or '')
s = s .. string.format('<span class="iw%s plainlinks" data-title="%s" data-lang="%s"' .. langName .. '>', class, mwlang:ucfirst(title), lang)
if ifRedirect then
if this.namespace == 0 and isEmpty(nocat) then
s = s .. categoryRedirect
end
s = s .. string.format('[%s %s]', tostring(mw.uri.fullUrl(title,'redirect=no')), text)
else
s = s .. string.format('[[%s|%s]]', title, text)
end
-- Приказује везу на чланак на страном језику или предлог за уклањање шаблона
if ifExists and not ifRedirect then
s = s .. '<sup class="iw__notice noprint">[[Шаблон:Непреведено 5#Ако постоји чланак|'
  .. '<span style="color:red; font-style:normal; font-weight:bold;" title="Уклоните шаблон «Непреведено 5» из чланка '
  .. 'и замените га једноставном вики везом">?!</span>]]</sup>'
if this.namespace == 0 and isEmpty(nocat) then
s = s .. categoryExists
end
else
-- Ствара опис
local t = ''
if lang == 'd' then
t = string.format('Ставка чланка на «%s» в Википодацима', mwlang:ucfirst(title))
page = page .. '#sitelinks-wikipedia'
else
if not isEmpty(origPage) then
t = string.format('%s — верзија чланка', page)
else
t = 'Верзија чланка'
end
t = t .. string.format(' «%s» на %s', mwlang:ucfirst(title), p._transform_lang(lang))
end
-- Ствара белешку о преусмеравању
local aster = ''
if ifRedirect then
aster = '<sup class="iw__notice noprint" style="font-style:normal; font-weight:normal; margin:0 0 0 1px;">'
.. '[[Шаблон:Непреведено 5#Ако постоји преусмеравање|'
.. '<span style="color:red; font-weight:bold;" title="Замените наслов преусмеравања са насловом чланка или уклоните шаблон «Непреведено 5»">*</span>]]'
.. '</sup>'
end
-- Приказује везу до странице на страном језику
s = s .. '<sup class="iw__note noprint" style="font-style:normal; font-weight:normal;">' ..
string.format('[[:%s:%s|<span class="iw__tooltip" title="%s">[%s]</span>]]</sup>', lang, page, t, lang) ..
aster
 
-- Приказује статус странице на страном језику
if not isEmpty(state) and not isEmpty(states[state]) then
s = s .. string.format('<sup class="iw__status noprint" style="margin:0 0 0 1px;">[[Файл:%s|8px|link=%s|%s]]</sup>',
states[state][3], states[state][1], states[state][2])
end
end
return s .. '</span>'
else
-- Ако нема потребног параметра, приказује се црвени текст
local htmlerror = require('Module:Error').error
return htmlerror{'Наведите наслов странице.'}
end
end
end


-- Помоћна функција за {{Непреведено 5}}: излази замена шаблона
function p.file_languages(frame)
function p._substIW(title, text)
    local M_link = require( 'Module:Link' )
local s = '[[' .. title
    local contentLangInstance = mw.language.getContentLanguage()
if not isEmpty(text) and title ~= text then
    local pattern = frame.args.pattern or '%s (%s)'
s = s .. '|' .. text
    local original = frame.args.original or mw.title.getCurrentTitle().text
end
    local ext_start, _ = string.find( original, '\.%w+$' )
    local file_ext = string.sub( original, ext_start )
return s .. ']]'
    original = string.sub( original, 0, ext_start-1 )
    return frame:preprocess('<gallery>\n'..(table.concat(M_link.forEachLink( p.forEachLanguage( { args= { pattern = '[[$lc]]' } } ),
        function(linkInfo)
            local filename = mw.ustring.format( pattern, original, linkInfo.text ) .. file_ext
            local ok, exists = pcall( function()
                return mw.title.new( filename, 6 ).exists
            end )
            if ok and exists then
                return mw.ustring.format( '%s|%s', filename, contentLangInstance:ucfirst( mw.language.fetchLanguageName( linkInfo.text ) ) )
            else
                return nil
            end
        end
    ), '\n'))..'\n</gallery>')
end
end


-- Враћа {{Непреведено 5}}
function p.runTests()
function p.getIW(frame)
    return p.langLinksNonExpensive({ args= { page='Module:Languages/testcases/test' }, getParent=function() end }) == "[[Module:Languages/testcases/test/de|Deutsch]]&nbsp;&#124;&#32;[[Module:Languages/testcases/test/en|English]]&nbsp;&#124;&#32;"
local mwlang = mw.getContentLanguage()
local f = frame.args
local title = f.title
local text = f.text
local lang = mwlang:lc(f.lang)
local page = f.page
local state = f.state
local nocat = f.nocat
if not mw.isSubsting() then
return p._newIW(title, text, lang, page, state, nocat)
end
return p._substIW(title, text)
end
end


return p
return p;

Верзија на датум 1. новембар 2020. у 13:48

Овај модул се користи у шаблону {{l6e}} при стварању одговарајућих језичких веза коришћењем {{#invoke:Languages|list|множество языков}}. За детаљнију документацију о начину рада шаблона, погледајте документацију. За списак подржаних језичких скраћеница, погледајте Модул:Languages/data.

Также модуль используется для различных преобразований кодов языков.

Услужне категорије модула

Тестови

Неуспелих тестова: 4

test_getRefHtml:

Текст Очекивано Стварно
НеН {{ #invoke:Languages | getRefHtmlFrame | }} Script error: The function "getRefHtmlFrame" does not exist.
НеН {{ #invoke:Languages | getRefHtmlFrame | QNNN }} Script error: The function "getRefHtmlFrame" does not exist.
НеН {{ #invoke:Languages | getRefHtmlFrame | Q1860 }} (енг.) Script error: The function "getRefHtmlFrame" does not exist.
НеН {{ #invoke:Languages | getRefHtmlFrame | Q7737 }} (рус.) Script error: The function "getRefHtmlFrame" does not exist.




--[=[
Not globally exposed. Internal function only.

language_subpages( frame, transform, options )
Parameters
    frame:     The frame that was passed to the method invoked. The first argument or the page argument will be respected.
    transform: A transform function. Example: function( basepagename, subpagename, code, langname ) end
    options:   An object with options. Example: { abort= { on=function() end, time=0.8 }  }
        Following options are available:
        abort: Aborts iterating over the subpages if one of the conditions is met. If the process is aborted, nil is returned!
            on: Function to be called if an abort-condition was met.
            cycles: The maximum number of subpages to run over.
            time: Maximum time to spend running over the subpages.

]=]
function language_subpages( frame, transform, options )
    local args, pargs, options = frame.args, ( frame:getParent() or {} ).args or {}, options or {};
    local title = args.page or args[1] or pargs.page or pargs[1] or "";
    local abort = options.abort or {};
    local at, clock = type( abort.on ), os.clock();
    local ac = function()
        if  at == 'function' or ( at == 'table' and getmetatable(abort.on).__call ) then
            abort.on();
        end
    end
    local tt = type( transform );
    local page = require( 'Module:Page' );

    title = page.clean(title);

    if tt == 'function' or ( tt == 'table' and getmetatable(transform).__call ) then
        local fetch, pages, langcode, langname = mw.language.fetchLanguageName, {};
--[==[

     / \
    / | \
   /  ·  \
   ¯¯¯¯¯¯¯
   Page.subpages() no longer works because it attempted to parse the HTML content generated by
   calling the parser function "Special:Prefixindex:" which is no longer expanded in Lua but
   converted to a "stripped tag" (containing a unique identifier surrounded by ASCII DEL characters)
   representing the tag name and its parameters.
   The actual expansion of stripped tags can no longer be performed in Lua.
   Now unstripping these tags just kills ALL these tags (except "wiki" tags) instead of performing
   their expansion by running the extension code. Only MediaWiki can unstrip these tags in texts after
   they have been returned by Lua.
   For this reason, page.subpages() is now completely empty (Module:Page no longer works).
   This cannot be bypassed, except by using a Scribunto extension library if lifting the limits set by mw.unstrip.
   Note that "Special:Prefixindex:" is also costly, even if it just requires a single database query to
   get all subpages, instead of one costly #ifexist or one costly mw.title() property reading per
   tested subpage to know if it exists.
   For now there's still no reliable way to get a list of subpages, or performing queries similar to
   the [[Special:Prefixindex]] page or list members of a category like when viewing a category page.
   Ideally, there should exist a method for such queries on Title objects returned by the mw.title library;
   but for now there's none.
   In Lua now, the only expansion possible with an immediate effect is the expansion of standard templates,
   all special tags or special pages, or parser function extensions do not work (Only the #expr parser
   function is supported by using an external Scribunto library).
--]==]
        for pg in page.subpages( title, { ignoreNS=true } ) do
            if abort.cycles then
                abort.cycles = abort.cycles - 1
                if 0 == abort.cycles then return ac()  end
            end
            if abort.time then
                if (os.clock() - clock) > abort.time then return ac()  end
            end
            if mw.ustring.len( pg ) <= 12 then
                langcode = string.lower( pg );
                langname = fetch( langcode );
                if langname ~= '' then
                    table.insert( pages, transform( title, pg, langcode, langname ) );
                end
            end
        end
        return pages;
    end
    return {};
end

function cloneArgs(frame)
    local args, pargs = {}, {}
    for k,v in pairs( frame.args ) do args[k] = v end
    if frame:getParent() then
        for k,v in pairs( frame:getParent().args ) do pargs[k] = v end
    end
    return args, pargs;
end



local p = {};

--[=[
Usage:
{{#invoke:languages|internal|Template:Adjective}}
]=]
function p.internal(frame)
    pages = language_subpages( frame, function( title, page, code, name )
        return mw.ustring.format( '<span lang="%s" xml:lang="%s" class="language lang-%s"><bdi>[[%s/%s|%s]]</bdi></span>',
            code, code, code, title, page, name
        );
    end);
    return table.concat( pages, '&nbsp;·&nbsp;' );
end

--[=[
Usage:
{{#invoke:languages|external|Template:Adjective}}
]=]
function p.external(frame)
    pages = language_subpages( frame, function( title, page, code, name )
        return mw.ustring.format( '<span lang="%s" xml:lang="%s" class="language lang-%s"><bdi>[%s/%s %s]</bdi></span>',
            code, code, code, tostring( mw.uri.fullUrl( title ) ), page:gsub( ' ', '_' ), name
        );
    end);
    return table.concat( pages, '&nbsp;| ' );
end

--[=[
forEachLanguage

This function iterates over all language codes known to MediaWiki based on a maintained list
replacing patterns in a pattern-string for each language

Usage:
{{#invoke:Languages|forEachLanguage
  |pattern=patternstring
  |before=string to insert before iteration
  |after=string added after iteration
  |sep=separator string between iterations
  |inLang=langcode used for $lnTrP and $lnTrUC1
}}

Parameters
    pattern: A pattern string which is processed for each language and which is concatenated at the end and returned as one string
    before: A string that is inserted before the concatenated result
    after: A string that is inserted after the concatenated result
    sep: A string that is inserted between each line created from the pattern while iterating (like ProcessedPattern_sep_ProcessedPattern_sep_ProcessedPattern)
    inLang: Langcode to use for $lnTrP and $lnTrUC1

Patterns:
    $lc - language code such as en or de
    $lnP - language name in own language (autonym)
    $lnUC1 - language name in own language (autonym), first letter upper case
    $lnTrP - language name translated to the language requested by language code passed to inLang
    $lnTrUC1 - language name translated to the language requested by language code passed to inLang, first letter upper case

Example
   {{#invoke:Languages|forEachLanguage|pattern=<span lang="$lc" xml:lang="$lc" class="language lang-$lc">[[Page/$lc|$lnP]]</span>}}
]=]

-- =p.forEachLanguage({ args= { pattern = "$lc - $lnTrP\n", inLang = "en" } })
function p.forEachLanguage(frame)
    local l = require( "Module:Languages/List" )

    local ret = {}
    local lang    = mw.language
    local line
    local pattern = frame.args.pattern   or frame.args[1] or ""
    local prefix  = frame.args.before    or frame.args[2] or ""
    local postfix = frame.args.after     or frame.args[3] or ""
    local sep     = frame.args.sep       or frame.args.separator or frame.args[4] or ""
    local inLang  = frame.args.inLang    or frame.args[5] or nil

    local langNameUCFirstReq           = not not pattern:find( "$lnUC1", 1, true )
    local langNameReq                  = not not pattern:find( "$lnP", 1, true ) or langNameUCFirstReq
    local langNameTranslatedUCFirstReq = not not pattern:find( "$lnTrUC1", 1, true )
    local langNameTranslatedReq        = not not pattern:find( "$lnTrP", 1, true ) or langNameTranslatedUCFirstReq
    local contentLangInstance = mw.language.getContentLanguage()
    local inLangLangInstance
    local l = mw.language.fetchLanguageNames() -- autonyms
    local lTr
    local lcIdList = require( 'Module:Languages/List' ).getSortedList( l )

    if langNameTranslatedReq then
        inLangLangInstance = --[==[
            mw.getLanguage( inLang ) -- Quota hit in :ucfirst() if using too many langInstances
            --]==] contentLangInstance
        lTr = mw.language.fetchLanguageNames( inLang ) -- translated names
    end

    for _, lcId in pairs( lcIdList ) do
        local subst = lcId:gsub('%%', '%%%%')
        line = pattern:gsub( "%$lc", subst )
        local langName, langInstance
        -- autonym (name of lcId in locale lcId)
        if langNameReq then
            langName = l[lcId]
            subst = langName:gsub('%%', '%%%%')
            line = line:gsub( "%$lnP", subst )
        end
        if langNameUCFirstReq then
            langInstance = --[==[
                mw.getLanguage( lcId ) -- Quota hit in :ucfirst() if using too many langInstances
                --]==] contentLangInstance
            langName = langInstance:ucfirst( langName )
            subst = langName:gsub('%%', '%%%%')
            line = line:gsub( "%$lnUC1", subst )
        end

        -- translated name (name of lcId in locale inLang)
        if langNameTranslatedReq then
            langName = lTr[lcId]
            subst = langName:gsub('%%', '%%%%')
            line = line:gsub( "%$lnTrP", subst )
        end
        if langNameTranslatedUCFirstReq then
            langName = inLangLangInstance:ucfirst( langName )
            subst = langName:gsub('%%', '%%%%')
            line = line:gsub( "%$lnTrUC1", subst )
        end

        table.insert(ret, line)
    end
    return prefix .. table.concat( ret, sep ) .. postfix
end

--[=[
 Provide logic for [[Template:Lle]] (Language Links external, to be substituted)
]=]
function p.lle(frame)
    local ret
    local pattern = "{{<includeonly/>subst:#ifexist:{{{1}}}/$lc|[{{fullurl:{{{1}}}/$lc}} $lnUC1]&nbsp;{{<includeonly/>subst:!}} <!--\n-->}}"
    ret = p.forEachLanguage({ args= { pattern = pattern } })
    ret = frame:preprocess(ret)
    return ret
end

--[=[
 Provide logic for [[Template:Ll]] (Language Links, to be substituted)
]=]
function p.ll(frame)
    local ret
    local pattern = "{{<includeonly/>subst:#ifexist:{{{1}}}/$lc|[[{{{1}}}/$lc{{<includeonly/>subst:!}}$lnUC1]]&nbsp;{{<includeonly/>subst:!}} <!--\n-->}}"
    ret = p.forEachLanguage({ args= { pattern = pattern } })
    ret = frame:preprocess(ret)
    return ret
end


--------------------------------------------------------
--- Different approaches for [[Template:Lang links]] ---
--------------------------------------------------------

--[=[
 Provide logic for [[Template:Lang links]]
 Using a cute Hybrid-Method:
    First check the subpages which is quite fast; if there are too many fall back to checking for each language page individually
]=]

-- =p.langLinksNonExpensive({ args= { page='Commons:Picture of the Year/2010' }, getParent=function() end })
-- =p.langLinksNonExpensive({ args= { page='Main Page' }, getParent=function() end })
-- =p.langLinksNonExpensive({ args= { page='Template:No_source_since' }, getParent=function() end })
-- =p.langLinksNonExpensive({ args= { page='MediaWiki:Gadget-HotCat' }, getParent=function() end })
function p.langLinksNonExpensive(frame)
    local args, pargs = frame.args, ( frame:getParent() or {} ).args or {};
    local title = args.page or args[1] or pargs.page or pargs[1] or "";
    local contentLangInstance = mw.language.getContentLanguage();
    local pages2
    if frame.preprocess == nil then
        frame = mw.getCurrentFrame()
    end
    --[==[
    local options = { abort= { time=3.5, on=function()
            pages2 = p.forEachLanguage({ args= { pattern = '{{#ifexist:' .. title .. '/$lc|[[' .. title .. '/$lc|$lnUC1]]&nbsp;&#124;&#32;}}' } })
        end } }
    local pages = language_subpages( frame, function( basepagename, subpagename, code, langname )
        return mw.ustring.format( '<span lang="%s" xml:lang="%s" class="language lang-%s" style="white-space:nowrap"><bdi>[[%s/%s|%s]]</bdi></span>&nbsp;| ',
            code, code, code, basepagename, subpagename, contentLangInstance:ucfirst( langname ) )
    end, options );
    return pages2 and frame:preprocess(pages2) or table.concat(  pages, '' );
    ]==]
    return frame:preprocess( p.forEachLanguage({ args= { pattern = '{{#ifexist:' .. title .. '/$lc|[[' .. title .. '/$lc|$lnUC1]]&nbsp;&#124;&#32;}}' } }) )
end

---------------------------------------------------------
----------------- [[Template:Autolang]] -----------------
---------------------------------------------------------
--[[
  Works like {{autotranslate}} just allowing an unlimited number of arguments, even named arguments.
  It's doing Magic! No arguments should be passed to {{#invoke:}}
]]

function p.autolang(frame)
    local args, pargs = cloneArgs( frame )
    if nil == args.useargs then
        if not args.base then args = pargs end
    elseif 'both' == args.useargs then
        for k,v in pairs(args) do pargs[k] = v end
        args = pargs
    elseif 'parent' == args.useargs then
        args = pargs
        if pargs.base and not args.base then
            args.base = pargs.base
        end
    end
    local base = args.base
    local userlang = frame:preprocess( '{{int:lang}}' )
    local tl, tlns = 'Template:', 10
    local tlb, fallback1, currenttemplate
    local fallback, contentlang = mw.text.split( userlang, '-', true )[1], mw.language.getContentLanguage():getCode()

    local createReturn = function(title)
        local ret
        local tlargs = {}
         -- When LUA is invoked, templates are already expanded. This must be respected.
        return frame:expandTemplate{ title = title, args = args }
    end

    if not base then
        return ("'autolang' in [[Module:Languages]] was called but the 'base' parameter could not be found." ..
            "The base parameter specifies the template that's subpages will be sought for a suitable translation.")
    end
    tlb = tl .. base .. '/'

    currenttemplate = tlb .. userlang
    local ok, exists = pcall( function()
        return mw.title.new( currenttemplate, tlns ).exists
    end )
    if ok and exists then
        return createReturn(currenttemplate)
    end

    fallback1 = frame:preprocess( '{{Fallback|1=' .. base .. '|2=' .. userlang .. '}}' )
    if fallback1 ~= contentlang then
        return createReturn(tlb .. fallback1)
    end

    currenttemplate = tlb .. fallback
    local ok, exists = pcall( function()
        return mw.title.new( currenttemplate, tlns ).exists
    end )
    if ok and exists then
        return createReturn(currenttemplate)
    end

    currenttemplate = tlb .. contentlang
    local ok, exists = pcall( function()
        return mw.title.new( currenttemplate, tlns ).exists
    end )
    if ok and exists then
        return createReturn(currenttemplate)
    end
    return createReturn(tl .. base)
end

--[=[
Usage:
{{#invoke:languages|isKnownLanguageTag|gsw}} -> 1
{{#invoke:languages|isKnownLanguageTag|doesNotExist}} ->
]=]
function p.isKnownLanguageTag(frame)
    return mw.language.isKnownLanguageTag( frame.args[1] or frame.args.tag or frame.args.code or '' ) and '1' or ''
end

function p.file_languages(frame)
    local M_link = require( 'Module:Link' )
    local contentLangInstance = mw.language.getContentLanguage()
    local pattern = frame.args.pattern or '%s (%s)'
    local original = frame.args.original or mw.title.getCurrentTitle().text
    local ext_start, _ = string.find( original, '\.%w+$' )
    local file_ext = string.sub( original, ext_start )
    original = string.sub( original, 0, ext_start-1 )
    return frame:preprocess('<gallery>\n'..(table.concat(M_link.forEachLink( p.forEachLanguage( { args= { pattern = '[[$lc]]' } } ),
        function(linkInfo)
            local filename = mw.ustring.format( pattern, original, linkInfo.text ) .. file_ext
            local ok, exists = pcall( function()
                return mw.title.new( filename, 6 ).exists
            end )
            if ok and exists then
                return mw.ustring.format( '%s|%s', filename, contentLangInstance:ucfirst( mw.language.fetchLanguageName( linkInfo.text ) ) )
            else
                return nil
            end
        end
    ), '\n'))..'\n</gallery>')
end

function p.runTests()
    return p.langLinksNonExpensive({ args= { page='Module:Languages/testcases/test' }, getParent=function() end }) == "[[Module:Languages/testcases/test/de|Deutsch]]&nbsp;&#124;&#32;[[Module:Languages/testcases/test/en|English]]&nbsp;&#124;&#32;"
end

return p;