Модул:utilities
Ин модул вазифаҳои гуногуни умумии коммуналиро содир мекунад, ки онҳоро дигар модулҳо метавонанд истифода баранд.
Ҳуҷҷатҳои муфассал
[вироиш]export.safe_require
[вироиш]function export.safe_require(modname)
Мисли талаб, аммо баргардонидани бардурӯғ, агар модул ба ҷои партофтани хато мавҷуд набошад. Натиҷаҳо дар package.loaded кэш карда мешаванд, ки ин барои ҳама намуди модулҳо тезтар аст, аммо барои модулҳои мавҷуда хеле тезтар, зеро талаб ҳар дафъа кӯшиш мекунад, ки боркунаки пурраро истифода барад (зеро онҳо дар package.loaded кэш карда намешаванд) . Эзоҳ: гарчанде ки модулҳои мавҷуда ҳамчун false дар package.loaded кэш карда мешаванд, онҳо то ҳол бо талаботи муқаррарӣ кор намекунанд, зеро он ба ҷои тафтиши арзиши баргардонидани nil чеки бардурӯғро истифода мебарад.
export.dec_to_hex
[вироиш]function export.dec_to_hex(dec)
Convert decimal to hexadecimal.
Note: About three times as fast as the hex library.
export.get_plaintext
[вироиш]function export.get_plaintext(text)
A helper function to strip wiki markup, giving the plaintext of what is displayed on the page.
export.format_categories
[вироиш]function export.format_categories(categories, lang, sort_key, sort_base, force_output, sc)
Format the categories with the appropriate sort key.
categoriesis a list of categories. Each entry in the list can be either a string (the full category, minus the"Category:"prefix) or an object. In the latter case, the object should have fieldscat: the full category, minus the"Category:"prefix (required);lang: optional language object to override the overalllang;sort_key: optional sort key to override the overallsort_key;sort_base: optional sort base to override the overallsort_base;sc: optional script object to override the overallsc.
langis an object encapsulating a language; ifnil, the object for language code"und"(undetermined) will be used.langis used when computing the sort key (either from the subpage name or sort base).sort_keyis placed in the category invocation, and indicates how the page will sort in the respective category. Normally do not use this. Instead, leave itnil, and if you need to a control the sort order, usesort_base, so that language-specific normalization is applied on top of the specified sort base. If neithersort_keynorsort_baseis specified, the default is to apply language-specific normalization to the subpage name; see below.sort_baselets you override the default sort key while still maintaining appropriate language-specific normalization. Ifnilis specified, this defaults to the subpage name, which is the portion of the full pagename after subtracting the namespace prefix (and, in certain namespaces such asUser:, but notably not in the mainspace, after subtracting anything up through the final slash). The actual sort key is derived from the sort base approximately by lowercasing, applying language-specific normalization and then uppercasing; note that the same process is applied in deriving the sort key when no sort base is specified. For example, for French, Spanish, etc. the normalization process maps accented letters to their unaccented equivalents, so that e.g. in French, ҷинси мардона sorts after ҷинси мардона (instead of after the default Wikimedia sort order, which is approximately based on Unicode sort order and places ç after z) and ҷинси мардона sorts after ҷинси мардона (instead of between c and d). Similarly, in Russian the normalization process converts Cyrillic ё to a string consisting of Cyrillic е followed by U+10FFFF, so that effectively ё sorts after е instead of the default Wikimedia sort, which (I think) puts ё after я, the last letter of the Cyrillic alphabet.force_outputforces normal output in all namespaces. Normally, nothing is output if the page isn't in the main, Appendix:, Thesaurus:, Reconstruction: or Citations: namespaces.scis a script object; if nil, the default will be derived from the sort base (or its default value, the subpage name) by callinglang:findBestScript(). The value ofscis used during the sort base normalization process; for example, languages with multiple scripts will often have script-specific normalization processes.
export.catfix
[вироиш]function export.catfix(lang, sc)
Илова кардани "catfix", ки дар саҳифаҳои категорияи мушаххаси забон барои илова кардани атрибутҳои забон ва аксар вақт скрипт истифода мешавад дарсҳо ба ҳамаи номҳои вуруд. Илова кардани атрибутҳои забон ва синфҳои скрипт номҳои вурудро намоиш медиҳад беҳтар аст (бо истифода аз услубҳои мушаххаси забон ё скрипт дар MediaWiki:Common.css), ки махсусан барои забонҳои ғайри англисӣ муҳим аст, ки дар браузерҳо дастгирии доимии шрифт надоранд.
Атрибутҳои забон барои ҳама забонҳо илова карда мешаванд, аммо синфҳои скрипт танҳо барои забонҳои дорои як скрипт илова карда мешаванд дар файли додаҳои онҳо номбар шудаанд ё барои забонҳое, ки скрипти пешфарз дар рӯйхати catfix_script дар Модул:utilities/data. Баъзе забонҳо ба таври равшан скрипти пешфарз доранд, аммо ба ҳар ҳол скриптҳои дигар дар рӯйхат ҳастанд файли додаҳои онҳо ва аз ин рӯ бояд скрипти пешфарзашон муайян карда шавад. Дигарон скрипти пешфарз надоранд.
- Сербо-хорватӣ мунтазам бо хати лотинӣ ва кириллӣ навишта мешавад. Азбаски он ду скриптро истифода мебарад, Сербо-Хорватӣ наметавонад синфи скриптро дошта бошад, ки ба вурудот дар саҳифаҳои категорияи он истифода шавад, зеро танҳо як синфи скрипт дар як вакт муайян кардан мумкин аст.
- Забони русӣ одатан бо хатти кириллӣ (
{{{2}}}) навишта мешавад, аммо алифбои Брайл ({{{2}}}) низ дар рӯйхат оварда шудааст. файли маълумотии он. Пас, забони русӣ дар рӯйхатиcatfix_scriptсабт лозим аст, то ки скрипти{{{2}}}(кириллӣ) синф ба сабтҳо дар саҳифаҳои категорияи худ татбиқ карда мешавад.
Барои дарёфти скриптҳое, ки барои забон номбар шудаанд, ба Module:languages гузаред ва қуттии ҷустуҷӯро барои дарёфти файли маълумот истифода баред барои забон. Барои фаҳмидани он ки рамзи скрипт чӣ маъно дорад, рамзи скриптро дар Модул:scripts/data ҷустуҷӯ кунед.
export.check_object
[вироиш]function export.check_object(typ, noErr, ...)
Бо назардошти як навъ (ҳамчун сатр) ва шумораи ихтиёрии объектҳо, тафтиш мекунад, ки оё ҳамаи ин объектҳо забонанд, оила, скрипт, системаи хаттӣ ё объектҳои забони Викимедиа. Барои коркарди хатогиҳо дар функсияҳое, ки талаб мекунанд, муфид аст яке аз ин гуна объектхо.
Агар noErr муқаррар карда шуда бошад, функсия ба ҷои хатогие баргардонад, ки ин имкон медиҳад, ки коркарди хатогиҳои фармоишӣ дар функсияи даъват анҷом дода мешавад.
local mw = mw
local package = package
local table = table
local require = require
local require_when_needed = require("Module:require when needed")
local anchor_encode = mw.uri.anchorEncode
local concat = table.concat
local decode_entities = require_when_needed("Module:string utilities", "decode_entities")
local format = string.format
local insert = table.insert
local ipairs = ipairs
local tonumber = tonumber
local trim = require_when_needed("Module:string utilities", "trim")
local type = type
local unstrip = mw.text.unstrip
local export = {}
do
local loaded = package.loaded
local loader = package.loaders[2]
--[==[
Мисли талаб, аммо баргардонидани бардурӯғ, агар модул ба ҷои партофтани хато мавҷуд набошад.
Натиҷаҳо дар {package.loaded} кэш карда мешаванд, ки ин барои ҳама намуди модулҳо тезтар аст, аммо барои модулҳои мавҷуда хеле тезтар, зеро талаб ҳар дафъа кӯшиш мекунад, ки боркунаки пурраро истифода барад (зеро онҳо дар {package.loaded} кэш карда намешаванд) .
Эзоҳ: гарчанде ки модулҳои мавҷуда ҳамчун {false} дар {package.loaded} кэш карда мешаванд, онҳо то ҳол бо талаботи муқаррарӣ кор намекунанд, зеро он ба ҷои тафтиши арзиши баргардонидани {nil} чеки бардурӯғро истифода мебарад.
]==]
function export.safe_require(modname)
local module = loaded[modname]
if module ~= nil then
return module
end
-- Боркунак функсияро дар сурати мавҷуд будани модул бар мегардонад ё агар он набошад, сифрро бармегардонад ва тафтиши ин назар ба истифодаи pcall бо талаб тезтар аст. Агар пайдо шавад, мо то ҳол ба ҷои боркунӣ ва кэшкунии мустақим талабро истифода мебарем, зеро талаб санҷишҳои бехатариро бар зидди ҳалқаҳои беохири боркунӣ дар бар мегирад (ва мо мехоҳем, ки онҳо хато кунанд).
module = loader(modname)
if module then
return require(modname)
end
loaded[modname] = false
return false
end
end
--[==[
Convert decimal to hexadecimal.
Note: About three times as fast as the hex library.
]==]
function export.dec_to_hex(dec)
dec = tonumber(dec)
if not dec or dec % 1 ~= 0 then
error("Input should be a decimal integer.")
end
return format("%X", dec)
end
--[==[
A helper function to strip wiki markup, giving the plaintext of what is displayed on the page.
]==]
function export.get_plaintext(text)
text = text
:gsub("%[%[", "\1")
:gsub("%]%]", "\2")
-- Remove strip markers and HTML tags.
text = unstrip(text):gsub("<[^<>\1\2]+>", "")
-- Parse internal links for the display text, and remove categories.
text = require("Module:links").remove_links(text)
-- Remove files.
for _, falsePositive in ipairs({"File", "Image"}) do
text = text:gsub("\1" .. falsePositive .. ":[^\1\2]+\2", "")
end
-- Parse external links for the display text.
text = text:gsub("%[(https?://[^%[%]]+)%]",
function(capture)
return capture:match("https?://[^%s%]]+%s([^%]]+)") or ""
end)
-- Any remaining square brackets aren't involved in links, but must be escaped to avoid creating new links.
:gsub("\1", "[[")
:gsub("\2", "]]")
:gsub("%[", "[")
:gsub("]", "]")
-- Strip bold, italics and soft hyphens.
:gsub("('*)'''(.-'*)'''", "%1%2")
:gsub("('*)''(.-'*)''", "%1%2")
:gsub("", "")
-- Get any HTML entities.
-- Note: don't decode URL percent encoding, as it shouldn't be used in display text and may cause problems if % is used.
text = decode_entities(text)
return trim(text)
end
do
local title_obj, category_namespaces, page_data, pagename, pagename_defaultsort
--[==[
Format the categories with the appropriate sort key.
* `categories` is a list of categories. Each entry in the list can be either a string (the full category, minus
the {"Category:"} prefix) or an object. In the latter case, the object should have fields
** `cat`: the full category, minus the {"Category:"} prefix (required);
** `lang`: optional language object to override the overall `lang`;
** `sort_key`: optional sort key to override the overall `sort_key`;
** `sort_base`: optional sort base to override the overall `sort_base`;
** `sc`: optional script object to override the overall `sc`.
* `lang` is an object encapsulating a language; if {nil}, the object for language code {"und"} (undetermined) will
be used. `lang` is used when computing the sort key (either from the subpage name or sort base).
* `sort_key` is placed in the category invocation, and indicates how the page will sort in the respective category.
Normally '''do not use this'''. Instead, leave it {nil}, and if you need to a control the sort order, use
{sort_base}, so that language-specific normalization is applied on top of the specified sort base. If neither
{sort_key} nor {sort_base} is specified, the default is to apply language-specific normalization to the subpage
name; see below.
* `sort_base` lets you override the default sort key while still maintaining appropriate language-specific
normalization. If {nil} is specified, this defaults to the subpage name, which is the portion of the full pagename
after subtracting the namespace prefix (and, in certain namespaces such as {User:}, but notably not in the
mainspace, after subtracting anything up through the final slash). The actual sort key is derived from the sort
base approximately by lowercasing, applying language-specific normalization and then uppercasing; note that the
same process is applied in deriving the sort key when no sort base is specified. For example, for French, Spanish,
etc. the normalization process maps accented letters to their unaccented equivalents, so that e.g. in French,
{{m|fr|ça}} sorts after {{m|fr|ca}} (instead of after the default Wikimedia sort order, which is approximately
based on Unicode sort order and places ç after z) and {{m|fr|côté}} sorts after {{m|fr|coté}} (instead of between
c and d). Similarly, in Russian the normalization process converts Cyrillic ё to a string consisting of Cyrillic е
followed by U+10FFFF, so that effectively ё sorts after е instead of the default Wikimedia sort, which (I think)
puts ё after я, the last letter of the Cyrillic alphabet.
* `force_output` forces normal output in all namespaces. Normally, nothing is output if the page isn't in the main,
Appendix:, Thesaurus:, Reconstruction: or Citations: namespaces.
* `sc` is a script object; if nil, the default will be derived from the sort base (or its default value, the
subpage name) by calling {lang:findBestScript()}. The value of `sc` is used during the sort base normalization
process; for example, languages with multiple scripts will often have script-specific normalization processes.
]==]
function export.format_categories(categories, lang, sort_key, sort_base, force_output, sc)
if type(lang) == "table" and not lang.getCode then
error("Далели дуюм ба формат_категорияҳо бояд объекти забонӣ бошад.")
end
title_obj = title_obj or mw.title.getCurrentTitle()
category_namespaces = category_namespaces or mw.loadData("Module:utilities/data").category_namespaces
if not (
force_output or
category_namespaces[title_obj.namespace] or
title_obj.prefixedText == "Wiktionary:Sandbox"
) then
return ""
elseif not page_data then
page_data = mw.loadData("Module:headword/data").page
pagename = page_data.encoded_pagename
pagename_defaultsort = page_data.pagename_defaultsort
end
local extra_categories
local function generate_sort_key(lang, sort_key, sort_base, sc)
-- Калиди ҷудокунии пешфарзро тавлид кунед.
-- Агар калиди навъбандӣ "-" бошад, раванди тавлиди калиди навъбандиро комилан аз байн баред. Ин ҳангоми гурӯҳбандии (масалан) дархостҳои тарҷума матлуб аст, зеро саҳифаҳои гурӯҳбандӣ ҳамеша бо забони англисӣ/транслингвалӣ мебошанд.
if sort_key == "-" then
sort_key = sort_base and sort_base:uupper() or pagename_defaultsort
else
lang = lang or require("Module:languages").getByCode("und")
sort_base = lang:makeSortKey(sort_base or pagename, sc) or pagename_defaultsort
if not sort_key or sort_key == "" then
sort_key = sort_base
elseif lang:getCode() ~= "und" then
if not extra_categories then
extra_categories = {}
end
insert(extra_categories, lang:getFullName() .. " шартҳо бо " .. (
sort_key:uupper() == sort_base and "зиёдатӣ" or
"non-redundant non-automated"
) .. " sortkeys")
end
end
if not sort_key or sort_key == "" then
sort_key = pagename_defaultsort
end
return sort_key
end
local ret = {}
local default_sort_key = generate_sort_key(lang, sort_key, sort_base, sc)
local ins_point = 0
local function process_category(cat)
local this_sort_key
if type(cat) == "string" then
this_sort_key = default_sort_key
else
this_sort_key = generate_sort_key(cat.lang or lang, cat.sort_key or sort_key,
cat.sort_base or sort_base, cat.sc or sc)
cat = cat.cat
end
ins_point = ins_point + 1
ret[ins_point] = "[[Category:" .. cat .. "|" .. this_sort_key .. "]]"
end
for _, cat in ipairs(categories) do
process_category(cat)
end
if extra_categories then
for _, cat in ipairs(extra_categories) do
process_category(cat)
end
end
return concat(ret)
end
end
do
local catfix_scripts
--[==[
Илова кардани "catfix", ки дар саҳифаҳои категорияи мушаххаси забон барои илова кардани атрибутҳои забон ва аксар вақт скрипт истифода мешавад
дарсҳо ба ҳамаи номҳои вуруд. Илова кардани атрибутҳои забон ва синфҳои скрипт номҳои вурудро намоиш медиҳад
беҳтар аст (бо истифода аз услубҳои мушаххаси забон ё скрипт дар [[MediaWiki:Common.css]]), ки махсусан
барои забонҳои ғайри англисӣ муҳим аст, ки дар браузерҳо дастгирии доимии шрифт надоранд.
Атрибутҳои забон барои ҳама забонҳо илова карда мешаванд, аммо синфҳои скрипт танҳо барои забонҳои дорои як скрипт илова карда мешаванд
дар файли додаҳои онҳо номбар шудаанд ё барои забонҳое, ки скрипти пешфарз дар рӯйхати {catfix_script} дар
[[Модул:utilities/data]]. Баъзе забонҳо ба таври равшан скрипти пешфарз доранд, аммо ба ҳар ҳол скриптҳои дигар дар рӯйхат ҳастанд
файли додаҳои онҳо ва аз ин рӯ бояд скрипти пешфарзашон муайян карда шавад. Дигарон скрипти пешфарз надоранд.
* Сербо-хорватӣ мунтазам бо хати лотинӣ ва кириллӣ навишта мешавад. Азбаски он ду скриптро истифода мебарад,
Сербо-Хорватӣ наметавонад синфи скриптро дошта бошад, ки ба вурудот дар саҳифаҳои категорияи он истифода шавад, зеро танҳо як синфи скрипт
дар як вакт муайян кардан мумкин аст.
* Забони русӣ одатан бо хатти кириллӣ ({{cd|Cyrl}}) навишта мешавад, аммо алифбои Брайл ({{cd|Brai}}) низ дар рӯйхат оварда шудааст.
файли маълумотии он. Пас, забони русӣ дар рӯйхати {catfix_script} сабт лозим аст, то ки скрипти {{cd|Cyrl}} (кириллӣ)
синф ба сабтҳо дар саҳифаҳои категорияи худ татбиқ карда мешавад.
Барои дарёфти скриптҳое, ки барои забон номбар шудаанд, ба [[Module:languages]] гузаред ва қуттии ҷустуҷӯро барои дарёфти файли маълумот истифода баред
барои забон. Барои фаҳмидани он ки рамзи скрипт чӣ маъно дорад, рамзи скриптро дар [[Модул:scripts/data]] ҷустуҷӯ кунед.
]==]
function export.catfix(lang, sc)
if not lang or not lang.getCanonicalName then
error('Далели аввал барои функсияи "catfix" бояд объекти забонӣ аз [[Модул:languages]] ё [[Модул:etymology languages]] бошад.')
end
if sc and not sc.getCode then
error('Далели дуюм ба функсияи "catfix" бояд объекти скрипт аз [[Модул:scripts]] бошад..')
end
local canonicalName = lang:getCanonicalName()
local fullName = lang:getFullName()
-- Барои илова кардани синфҳои скрипт ба истинодҳо дар саҳифаҳое, ки аз ҷониби қолибҳои категорияи дегхона сохта шудаанд.
if not sc then
catfix_scripts = catfix_scripts or mw.loadData("Module:utilities/data").catfix_scripts
sc = catfix_scripts[lang:getCode()] or catfix_scripts[lang:getFullCode()]
if sc then
sc = require("Module:scripts").getByCode(sc)
end
end
local catfix_class = anchor_encode("CATFIX-" .. canonicalName)
if fullName ~= canonicalName then
catfix_class = catfix_class .. " " .. anchor_encode("CATFIX-" .. fullName)
end
return "<span id=\"catfix\" style=\"display:none;\" class=\"" .. catfix_class .. "\">" ..
require("Module:script utilities").tag_text(" ", lang, sc, nil) ..
"</span>"
end
end
--[==[
Бо назардошти як навъ (ҳамчун сатр) ва шумораи ихтиёрии объектҳо, тафтиш мекунад, ки оё ҳамаи ин объектҳо забонанд,
оила, скрипт, системаи хаттӣ ё объектҳои забони Викимедиа. Барои коркарди хатогиҳо дар функсияҳое, ки талаб мекунанд, муфид аст
яке аз ин гуна объектхо.
Агар `noErr` муқаррар карда шуда бошад, функсия ба ҷои хатогие баргардонад, ки ин имкон медиҳад, ки коркарди хатогиҳои фармоишӣ
дар функсияи даъват анҷом дода мешавад.
]==]
function export.check_object(typ, noErr, ...)
local function fail(message)
if noErr then
return false
else
error(message, 3)
end
end
local objs = {...}
if #objs == 0 then
return fail("Must provide at least one object to check.")
end
for _, obj in ipairs(objs) do
if type(obj) ~= "table" or type(obj.hasType) ~= "function" then
return fail("Function expected a " .. typ .. " object, but received a " .. type(obj) .. " instead.")
elseif not (typ == "object" or obj:hasType(typ)) then
for _, wrong_type in ipairs{"family", "language", "script", "Wikimedia language", "writing system"} do
if obj:hasType(wrong_type) then
return fail("Function expected a " .. typ .. " object, but received a " .. wrong_type .. " object instead.")
end
end
return fail("Function expected a " .. typ .. " object, but received another type of object instead.")
end
end
return true
end
return export