Edge Rewrite
Jump to content

Module:Wd/sandbox/i18n

From Wikipedia, the free encyclopedia

-- The values and functions in this submodule should be localized per wiki.

local p = {}

function p.init(aliasesP)
	p = {
		["version"] = "9",  -- increment this each time the below parameters are changed to avoid reference conflict errors
		["errors"] = {
			["unknown-data-type"]          = "Unknown or unsupported datatype '%s'.",
			["missing-required-parameter"] = "No required parameters defined, needing at least one",
			["extra-required-parameter"]   = "Parameter '%s' must be defined as optional",
			["no-function-specified"]      = "You must specify a function to call",  -- equal to the standard module error message
			["main-called-twice"]          = 'The function "main" cannot be called twice',
			["no-such-function"]           = 'The function "%s" does not exist',  -- equal to the standard module error message
            ["no-such-reference-template"] = 'Error: template "%s", which is set in %s as the output template for the citation-output type "%s", does not exist',
            -- Parts of the error message signalling a malformed reference.
            ["malformed-reference-header"] = "<div style=\"color:#dd3333\">\nError: Unable to display the reference from Wikidata properly. Technical details:\n",
            ["malformed-reference-footer"] = "See [[Module:wd/doc#References|the documentation]] for further details.\n</div>\n[[Category:Module:Wd reference errors]]",
            ["template-failure-reason"]    = "* Reason for the failure of %s: %s\n",
            ["missing-mandatory-param"]    = 'The output template call would miss the mandatory parameter <code>%s</code>.',
            ["unknown-property-in-ref"]    = 'The Wikidata reference contains the property %s, which is not assigned to any parameter of this template.'
		},
		["info"] = {
			["edit-on-wikidata"] = "Edit this on Wikidata"
		},
		["numeric"] = {
			["decimal-mark"] = ".",
			["delimiter"]    = ","
		},
		["datetime"] = {
			["prefixes"] = {
				["decade-period"] = ""
			},
			["suffixes"] = {
				["decade-period"] = "s",
				["millennium"]    = " millennium",
				["century"]       = " century",
				["million-years"] = " million years",
				["billion-years"] = " billion years",
				["year"]          = " year",
				["years"]         = " years"
			},
			["julian-calendar"] = "Julian calendar",  -- linked page title
			["julian"]          = "Julian",
			["BCE"]             = "BCE",
			["CE"]              = "CE",
			["common-era"]      = "Common Era"  -- linked page title
		},
		["coord"] = {
			["latitude-north"] = "N",
			["latitude-south"] = "S",
			["longitude-east"] = "E",
			["longitude-west"] = "W",
			["degrees"]        = "°",
			["minutes"]        = "'",
			["seconds"]        = '"',
			["separator"]      = ", "
		},
		["values"] = {
			["unknown"] = "unknown",
			["none"]    = "none"
		},
		["cite"] = {
			["output-types"] = {"web", "q"},  -- In this order, the output types will be tried
			["param-mapping"] = {
				["web"] = {
					-- <= left side: all allowed reference properties for *web page sources* per https://www.wikidata.org/wiki/Help:Sources
					-- => right side: corresponding parameter names in (equivalent of) [[:en:Template:Cite web]] (if non-existent, keep empty i.e. "")
					[aliasesP.statedIn]                = "website",
					[aliasesP.referenceURL]            = "url",
					[aliasesP.publicationDate]         = "date",
					[aliasesP.lastUpdate]              = "date",
					[aliasesP.retrieved]               = "access-date",
					[aliasesP.title]                   = "title",
					[aliasesP.subjectNamedAs]          = "title",
					[aliasesP.archiveURL]              = "archive-url",
					[aliasesP.archiveDate]             = "archive-date",
					[aliasesP.language]                = "language",
					[aliasesP.author]                  = "author",
					[aliasesP.authorNameString]        = "author",
					[aliasesP.publisher]               = "publisher",
					[aliasesP.quote]                   = "quote",
					[aliasesP.pages]                   = "pages",  -- extra option
					[aliasesP.publishedIn]             = "website",
					[aliasesP.sectionVerseOrParagraph] = "at",
					["external-id"]                    = "url",  -- used for any type of database property ID
				},
				["q"] = {
					-- <= left side: all allowed reference properties for *sources other than web pages* per https://www.wikidata.org/wiki/Help:Sources
					-- => right side: corresponding parameter names in (equivalent of) [[:en:Template:Cite Q]] (if non-existent, keep empty i.e. "")
					[aliasesP.statedIn]                = "1",
					[aliasesP.pages]                   = "pages",
					[aliasesP.column]                  = "at",
					[aliasesP.chapter]                 = "chapter",
					[aliasesP.sectionVerseOrParagraph] = "section",
					["external-id"]                    = "id",  -- used for any type of database property ID
					[aliasesP.title]                   = "title",
					[aliasesP.publicationDate]         = "date",
					[aliasesP.lastUpdate]              = "date",
					[aliasesP.retrieved]               = "access-date"
				}
			},
			["config"] = {
				-- supported fields:
				--     - template: name of the template used for output
				--     - numbered-params: 
				--         citation params accepting an arbitrary number of values
				--         by numbering the params (e.g. author1, author2)
				--     - raw-value-params:
				--         params taking a raw value (which means the property is
				--         rendered with getValue with raw=true)
				--     - mandatory-params:
				--         params that are required to be in the template call
				--         (after potentially appending numbers
				--         to params listed in numbered-params)
				--     - prioritization:
				--         table associating a list of properties, in the order
				--         in which they are preferred, to template parameters;
				--         properties not mentioned here have the lowest priority;
				--         no key of this table can be from numbered-params
				--     - customRenderers:
				--         functions that override the default way a single
				--         Wikidata value is rendered (converted into a suitable
				--         template argument) for the given template parameter;
				--         these functions receive the following arguments:
				--             snak				--	the Wikidata value to be rendered
				--             refProperty		--	the property with which `snak` is associated;
			    --									this is useful if this custom renderer handles
			    --									multiple properties
				--             defaultRenderer	--	argumentless function that returns a string
				--									containing the default rendering of `snak`
				--			   propertiesFunc	--	the function `_properties`, as defined by the wd module
				--			   getValue			--	the internal module function used for rendering snaks
				-- Leaving out the "template" field causes the output type to be ignored.
				["web"] = {
					["template"] = "Cite web",
					["numbered-params"] = {"author"},
					["mandatory-params"] = {"url"},
					["prioritization"] = {
						["date"] = {aliasesP.lastUpdate, aliasesP.publicationDate},
						["title"] = {aliasesP.title, aliasesP.subjectNamedAs},
						["url"] = {aliasesP.referenceURL, "external-id"}
					},
					["customRenderers"] = {
						["language"] = function (snak, _, defaultRenderer, propertiesFunc, getValue)
							-- Discart the local language.
							local langQID = getValue(snak, true, false)  -- argument explanation: raw, not linked
							if mw.language.getContentLanguage().code == propertiesFunc{aliasesP.wikimediaLanguageCode, ["eid"] = langQID} then 
								return nil
							end
							return defaultRenderer()
						end,
						
						["url"] = function (snak, refProperty, defaultRenderer, propertiesFunc, getValue, snaks)
						    if refProperty == aliasesP.referenceURL then
								-- plain URLs from Wikidata don't need special handling.
								return defaultRenderer()
							end
							-- Now we know that `snak` contains an external ID. We want to convert it into a URL.
							if not snaks[aliasesP.statedIn] then
								-- No source database is cited explicitly. Wikidata discourages this.
								return nil  -- Don't return anything in this case.
							end
							-- Check if the ID indeed refers to the cited source given in the "Stated in" field.
							local citedSourceQID = getValue(snaks[aliasesP.statedIn][1], true, false)  -- argument explanation: raw, not linked
							local sourceAssociatedProps = propertiesFunc{"raw", aliasesP.wikidataProperty, ["eid"] = citedSourceQID}  -- fetch the associated properties for the cited source
							for i, associatedProp in pairs(mw.text.split(sourceAssociatedProps, ", ", true)) do
								if associatedProp == refProperty then
									-- The external ID indeed refers to the source identified by citedSourceQID.
									local renderedSnak = getValue(snak, false, true)  -- not raw, linked
									if mw.ustring.match(renderedSnak, "^%[%Z- %Z+%]$") then
										-- The last getValue call returned a URL in square brackets.
										-- strip link wikisyntax, and return the bare URL
										local url = mw.ustring.gsub(renderedSnak, "^%[(%Z-) %Z+%]$", "%1")  -- gsub returns two values
                                        return url
									end
								end
							end
						end,
					}
				},
				["q"] = {
					["template"] = "Cite Q",
					["raw-value-params"] = {"1"},  -- the first, unnamed parameter of CiteQ takes a QID, not the name of the item cited
					["mandatory-params"] = {"1"},
					["prioritization"] = {
						["date"] = {aliasesP.lastUpdate, aliasesP.publicationDate}
					},
					["customRenderers"] = {
						["id"] = function (_, refProperty, defaultRenderer)
							local output = defaultRenderer()
							if output then
								output = mw.wikibase.getLabel(refProperty) .. " " .. output
							end
							return output
						end,
					}
				}
			}
		}
	}

	p.getOrdinalSuffix = function(num)
		if tostring(num):sub(-2,-2) == '1' then
			return "th"  -- 10th, 11th, 12th, 13th, ... 19th
		end

		num = tostring(num):sub(-1)

		if num == '1' then
			return "st"
		elseif num == '2' then
			return "nd"
		elseif num == '3' then
			return "rd"
		else
			return "th"
		end
	end

	p.addDelimiters = function(n)
		local left, num, right = string.match(n, "^([^%d]*%d)(%d*)(.-)$")

		if left and num and right then
			return left .. (num:reverse():gsub("(%d%d%d)", "%1" .. p['numeric']['delimiter']):reverse()) .. right
		else
			return n
		end
	end

	return p
end

return p