Content deleted Content added
experiment with dateToJd (for JULIANDAY) to see if can accept simple expressions as well as single-parameter dates; accept fix=on and/or partial=on |
strict checking of df=xxx parameter value to reduce wikitext junk; see Module talk:Age#df and mf with bad values |
||
(31 intermediate revisions by 6 users not shown) | |||
Line 1:
-- Implement various "age of" and other date-related templates.
local mtext = {
-- Message and other text that should be localized.
-- Also need to localize text in table names in function dateDifference.
['mt-bad-param2'] = 'Parameter $1=$2 is invalid',
['mt-bad-show'] = 'Parameter show=$1 is not supported here',
['mt-cannot-add'] = 'Cannot add "$1"',
['mt-conflicting-show'] = 'Parameter show=$1 conflicts with round=$2',
['mt-date-wrong-order'] = 'The second date must be later in time than the first date',
['mt-dd-future'] = 'Death date (first date) must not be in the future',
['mt-dd-wrong-order'] = 'Death date (first date) must be later in time than the birth date (second date)',
['mt-invalid-bd-age'] = 'Invalid birth date for calculating age',
['mt-invalid-dates-age'] = 'Invalid dates for calculating age',
['mt-invalid-end'] = 'Invalid end date in second parameter',
['mt-invalid-start'] = 'Invalid start date in first parameter',
['mt-need-jdn'] = 'Need valid Julian date number',
['mt-need-valid-bd'] = 'Need valid birth date: year, month, day',
['mt-need-valid-bd2'] = 'Need valid birth date (second date): year, month, day',
['mt-need-valid-date'] = 'Need valid date',
['mt-need-valid-dd'] = 'Need valid death date (first date): year, month, day',
['mt-need-valid-ymd'] = 'Need valid year, month, day',
['mt-need-valid-ymd-current'] = 'Need valid year|month|day or "currentdate"',
['mt-need-valid-ymd2'] = 'Second date should be year, month, day',
['mt-template-bad-name'] = 'The specified template name is not valid',
['mt-template-x'] = 'The template invoking this must have "|template=x" where x is the wanted operation',
['mt-warn-param1'] = 'Invalid parameter $1',
['mt-warn-param2'] = 'Parameter $1=$2 is invalid',
['txt-affirmative'] = { y = true, yes = true, Y = true, Yes = true, YES = true }, -- valid values for df + mf parameters
['txt-yes'] = { y = true, yes = true, on = true }, -- valid values for parameters introduced with this module
['txt-and'] = ' and ',
['txt-or'] = ' or ',
['txt-category'] = 'Category:Age error',
['txt-comma-and'] = ', and ',
['txt-error'] = 'Error: ',
['txt-format-default'] = 'mf', -- 'df' (day first = dmy) or 'mf' (month first = mdy)
['txt-module-convertnumeric'] = 'Module:ConvertNumeric',
['txt-module-date'] = 'Module:Date',
['txt-sandbox'] = 'sandbox',
['txt-bda'] = '<span style="display:none"> (<span class="bday">$1</span>) </span>$2<span class="noprint ForceAgeToShow"> (age $3)</span>',
['txt-dda'] = '$2<span style="display:none">($1)</span> (aged $3)',
['txt-bda-disp'] = 'disp_raw', -- disp_raw → age is a number only; disp_age → age is a number and unit (normally years but months or days if very young)
['txt-dda-disp'] = 'disp_raw',
['txt-dmy'] = '%-d %B %-Y',
['txt-mdy'] = '%B %-d, %-Y',
}
local isWarning = {
['mt-warn-param1'] = true,
['mt-warn-param2'] = true,
}
-- yes[parameter] is true if parameter should be interpreted as "yes".
-- Do not want to accept mixed upper/lowercase unless done by previously used templates.
-- Need to accept "on" because "round=on" is wanted.
local yes = mtext['txt-yes']
local translate, from_en, to_en, isZero
if translate then
-- Functions to translate from en to local language and reverse go here.
-- See example at [[:bn:Module:বয়স]].
else
from_en = function (text)
return text
end
isZero = function (text)
return tonumber(text) == 0
end
end
local _Date, _currentDate
Line 5 ⟶ 73:
-- Return objects exported from the date module or its sandbox.
if not _Date then
local sandbox = frame:getTitle():find(mtext['txt-sandbox'], 1, true) and ('/' .. mtext['txt-sandbox']) or ''
local datemod = require(mtext['
_currentDate = datemod._current
if to_en then
_Date = function (...)
local args = {}
for i, v in ipairs({...}) do
args[i] = to_en(v)
end
return realDate(unpack(args))
end
else
_Date = realDate
end
end
return _Date, _currentDate
Line 48 ⟶ 127:
end
local function
-- Return
return mw.message.newRawMessage(text, ...):plain()
end
local function message(msg,
-- Return formatted message text for an error or warning.
local function getText(msg)
return mtext[msg] or error('Bug: message "' .. tostring(msg) .. '" not defined')
end
local categories = {
error = mtext['txt-category'
warning = mtext['txt-category'],
}
local a, b, k, category
local text = substituteParameters(getText(msg), ...)
if isWarning[msg] then
a = '<sup>[<i>'
b = '</i>]</sup>'
k = 'warning'
else
a = '<strong class="error">
b = '</strong>'
k = 'error'
end
if mw.title.getCurrentTitle():inNamespaces(0) then
-- Category only in namespaces: 0=article.
category = '[[' .. categories[
end
return
a ..
mw.text.nowiki(
b ..
(category or '')
end
local function dateFormat(args)
-- Return
-- nil, f if parameter is valid
-- m, f otherwise
-- where
-- m = string for warning message with category
-- f = string for wanted date format
local problem
local wanted = mtext['txt-format-default']
local other = wanted == 'df' and 'mf' or 'df'
local parm = args[other] or ''
if mtext['txt-affirmative'][parm] then
wanted = other
elseif parm ~= '' then
problem = message('mt-warn-param2', other, parm)
end
return problem, wanted == 'df' and mtext['txt-dmy'] or mtext['txt-mdy']
end
Line 106 ⟶ 208:
-- i == 1 for the first number which can optionally start with an uppercase letter.
number = tostring(number)
return require(mtext['
number,
nil, -- fraction numerator
Line 115 ⟶ 217:
options.ordinal -- true: 'first' instead of 'one'
) or number
end
local function makeExtra(args, flagCurrent)
-- Return extra text that will be inserted before the visible result
-- but after any sort key.
local extra = args.prefix or ''
if mw.ustring.len(extra) > 1 then
-- Parameter "~" gives "~3" whereas "over" gives "over 3".
if extra:sub(-6, -1) ~= ' ' then
extra = extra .. ' '
end
end
if flagCurrent then
extra = '<span class="currentage"></span>' .. extra
end
return extra
end
Line 121 ⟶ 239:
-- Assume value is a valid number which has not overflowed.
if sortable == 'sortable_table' or sortable == 'sortable_on' or sortable == 'sortable_debug' then
local
if value == 0 then
else
local mag = math.floor(math.log10(math.abs(value)) + 1e-14)
if value > 0 then
else
value = value + 10^(mag+1)
end
end
local
if sortable == 'sortable_table' then
elseif sortable == 'sortable_debug' then
result = '<span data-sort-value="_SORTKEY_♠"><span style="border:1px solid">_SORTKEY_♠</span></span>'
else
result = '<span data-sort-value="_SORTKEY_♠"></span>'
end
return (result:gsub('_SORTKEY_', sortKey))
end
end
Line 191 ⟶ 306:
hm = { 'H', 'M', id = 'hm' },
hms = { 'H', 'M', 'S', id = 'hms' },
M = { 'M', id = 'M' },
s = { 'S', id = 's' },
d = { 'd', id = 'd' },
dh = { 'd', 'H', id = 'dh' },
Line 227 ⟶ 344:
parms[i] = v
end
if yes
table.insert(parms, 'fix')
end
if yes
table.insert(parms, 'partial')
end
Line 239 ⟶ 356:
return 'error'
end
return message('
end
local add = stripToNil(args.add)
Line 246 ⟶ 363:
date = date + item
if not date then
return message('
end
end
end
local
local sortable = translateParameters.sortable[args.sortable]
if sortable then
local value = (date.partial and date.partial.first or date).jdz
end
if show ~= 'hide' then
result = date[show]
if result == nil then
result = from_en(date:text(show))
elseif type(result) == 'boolean' then
result = result and '1' or '0'
else
result = from_en(tostring(result))
end
end
return (
end
local function rangeJoin(range)
-- Return text to be used between a range of ages.
return range == 'dash' and '–' or mtext['
end
Line 303 ⟶ 420:
local name = names[components[i]]
if name then
if type(name) == 'table' then
end
text:add(vstr .. sep .. name
else
text:add(vstr)
Line 322 ⟶ 438:
elseif options.join == 'sep_serialcomma' and text.n > 2 then
first = ', '
last = mtext['
else
first = ', '
last = mtext['
end
for i, v in ipairs(text) do
Line 344 ⟶ 460:
end
return
(options.
(options.extra or '') ..
sign ..
Line 355 ⟶ 471:
-- which have been validated.
local names = {
-- Each name is:
-- * a string if no plural form of the name is used; or
-- * a table of strings, one of which is selected using the rules at
-- https://translatewiki.net/wiki/Plural/Mediawiki_plural_rules
abbr_off = {
sep = ' ',
y = {'year', 'years'},
m = {'month', 'months'},
w = {'week', 'weeks'},
d = {'day', 'days'},
H = {'hour', 'hours'},
M = {'minute', 'minutes'},
S = {'second', 'seconds'},
},
abbr_on = {
Line 376 ⟶ 495:
},
abbr_infant = { -- for {{age for infant}}
sep = ' ',
y = {'yr', 'yrs'},
m = {'mo', 'mos'},
w = {'wk', 'wks'},
d = {'day', 'days'},
H = {'hr', 'hrs'},
M = {'min', 'mins'},
S = {'sec', 'secs'},
},
abbr_raw = {},
Line 424 ⟶ 542:
range = parms.range and true or nil,
}
local
if parms.sortable then
local value = diff.age_days + (parms.wantDuration and 1 or 0) -- days and fraction of a day
Line 430 ⟶ 548:
value = -value
end
end
local textOptions = {
extra = parms.extra,
format = parms.format,
Line 440 ⟶ 556:
isnegative = diff.isnegative,
range = parms.range,
sortKey = sortKey,
spell = parms.spell,
suffix = parms.suffix, -- not currently used
}
if show.id == 'hide' then
return
end
local values = { diff:age(show.id, diffOptions) }
Line 459 ⟶ 577:
}
return
(textOptions.
makeText({ diff.partial.mindiff:age(show.id, diffOptions) }, show, names[abbr], opt) ..
rangeJoin(textOptions.range) ..
Line 465 ⟶ 583:
(textOptions.suffix or '')
end
return message('
end
Line 486 ⟶ 604:
-- Don't bother detecting if wantMixture is used because not needed and it is a poor option.
if not text then
if getopt.noMissing then
return nil -- this gives a nil date which gives an error
end
text = 'currentdate'
if getopt.flag == 'usesCurrent' then
Line 517 ⟶ 638:
end
if getopt.omitZero and i % 3 ~= 1 then -- omit zero months and days as unknown values but keep year 0 which is 1 BCE
if
fields[i] = nil
getopt.partial = true
Line 524 ⟶ 645:
end
local fix = getopt.fix and 'fix' or ''
local partialText = getopt.partial and 'partial' or ''
local dates = {}
Line 537 ⟶ 657:
for i = 1, nrDates do
local index = i == 1 and 1 or 4
if (m == 2 or m == '2') and (d == 29 or d == '29') then
-- Workaround error with following which attempt to use invalid date 2001-02-29.
-- {{age_ymwd|year1=2001|year2=2004|month2=2|day2=29}}
-- {{age_ymwd|year1=2001|month1=2|year2=2004|month2=1|day2=29}}
-- TODO Get rid of wantMixture because even this ugly code does not handle
-- 'Feb' or 'February' or 'feb' or 'february'.
if not ((y % 4 == 0 and y % 100 ~= 0) or y % 400 == 0) then
d = 28
end
end
dates[i] = Date(y, m, d)
end
else
Line 550 ⟶ 681:
if (getopt.partial and y and (m or not d)) or (y and m and d) then
dates[i] = Date(fix, partialText, y, m, d)
elseif not y and not m and not d
dates[i] = Date(flagCurrent())
end
end
end
else
getopt.textdates = true -- have parsed each date from a single text field
dates[1] = Date(fix, partialText, flagCurrent(fields[1]))
Line 563 ⟶ 694:
end
if not dates[1] then
return message(getopt.missing1 or '
end
if getopt.single then
Line 569 ⟶ 700:
end
if not dates[2] then
return message(
end
return dates[1], dates[2]
Line 580 ⟶ 711:
local name = frame.args.template
if not name then
return message('
end
local args = frame:getParent().args
Line 611 ⟶ 742:
flag = 'usesCurrent',
omitZero = true,
range = '
},
age_full_years_nts = { -- {{age nts}}
Line 635 ⟶ 766:
age_infant = { -- {{age for infant}}
-- Do not set show because special processing is done later.
abbr = yes
disp = 'disp_age',
sep = 'sep_space',
Line 677 ⟶ 808:
local spec = specs[name]
if not spec then
return message('
end
if name == 'age_days' then
Line 698 ⟶ 829:
-- ("on" is equivalent to "yes", and "off" is equivalent to "no").
-- "|range=OTHER" sets range = nil and rejects partial dates.
range = ({ dash = 'dash', off = 'no', no = 'no', [true] = true })[range] or yes
if range then
partial = true -- accept partial dates with a possible age range for the result
Line 708 ⟶ 839:
end
local getopt = {
fix = yes
flag = stripToNil(args.flag) or spec.flag,
omitZero = spec.omitZero,
Line 727 ⟶ 858:
local parms = {
diff = date2:subtract(date1, { fill = autofill }),
wantDuration = spec.duration or yes
range = range,
wantSc = yes
show = args.show == 'hide' and 'hide' or spec.show,
abbr = spec.abbr,
disp = spec.disp,
extra = makeExtra(args, getopt.usesCurrent and format ~= 'format_raw')
format = format or spec.format,
round = yes
sep = spec.sep,
sortable = translateParameters.sortable[args.sortable or spec.sortable],
Line 741 ⟶ 872:
}
if (spec.negative or frame.args.negative) == 'error' and parms.diff.isnegative then
return message('
end
return from_en(dateDifference(parms))
end
local function isFake(args)
-- Some templates have TemplateData with an auto value like "{{Birth date and age|YYYY|MM|DD}}".
-- Return true if that appears to be the case so the caller can output nothing rather than an error.
return args[1] == 'YYYY'
end
Line 749 ⟶ 886:
-- Implement [[Template:Birth date and age]].
local args = frame:getParent().args
if isFake(args) then
return ''
end
local options = {
missing1 = 'mt-need-valid-bd',
noMissing = true,
single = true,
}
local date = getDates(frame, options)
if type(date) == 'string' then
Line 757 ⟶ 901:
local diff = Date('currentdate') - date
if diff.isnegative or diff.years > 150 then
return message('
end
local disp
local show = 'y'
if diff.years < 2 then
disp = 'disp_age'
Line 768 ⟶ 913:
end
end
local problem, format = dateFormat(args)
local result =
mtext['txt-bda'],
date:text('
from_en(date:text(format)),
from_en(dateDifference({
diff = diff,
show = show,
Line 783 ⟶ 924:
disp = disp,
sep = 'sep_space',
})
) .. (problem or '')
local warnings = tonumber(frame.args.warnings)
if warnings and warnings > 0 then
Line 813 ⟶ 954:
end
if invalid then
result = result .. message('
end
end
return result
end
local function dda(frame)
-- Implement [[Template:Death date and age]].
local args = frame:getParent().args
if isFake(args) then
return ''
end
local options = {
missing1 = 'mt-need-valid-dd',
missing2 = 'mt-need-valid-bd2',
noMissing = true,
partial = true,
}
local date1, date2 = getDates(frame, options)
if type(date1) == 'string' then
return date1
end
local diff = date1 - date2
if diff.isnegative then
return message('mt-dd-wrong-order')
end
local Date = getExports(frame)
local today = Date('currentdate') + 1 -- one day in future allows for timezones
if date1 > today then
return message('mt-dd-future')
end
local years
if diff.partial then
years = diff.partial.years
years = type(years) == 'table' and years[2] or years
else
years = diff.years
end
if years > 150 then
return message('mt-invalid-dates-age')
end
local fmt_date, fmt_ymd, problem
if date1.day then -- y, m, d known
problem, fmt_date = dateFormat(args)
fmt_ymd = '%-Y-%m-%d'
elseif date1.month then -- y, m known; d unknown
fmt_date = '%B %-Y'
fmt_ymd = '%-Y-%m-00'
else -- y known; m, d unknown
fmt_date = '%-Y'
fmt_ymd = '%-Y-00-00'
end
local sortKey
local sortable = translateParameters.sortable[args.sortable]
if sortable then
local value = (date1.partial and date1.partial.first or date1).jdz
sortKey = makeSort(value, sortable)
end
local result = (sortKey or '') .. substituteParameters(
mtext['txt-dda'],
date1:text(fmt_ymd),
from_en(date1:text(fmt_date)),
from_en(dateDifference({
diff = diff,
show = 'y',
abbr = 'abbr_off',
disp = mtext['txt-dda-disp'],
range = 'dash',
sep = 'sep_space',
}))
) .. (problem or '')
local warnings = tonumber(frame.args.warnings)
if warnings and warnings > 0 then
local good = {
df = true,
mf = true,
}
local invalid
local imax = options.textdates and 2 or 6
for k, _ in pairs(args) do
if type(k) == 'number' then
if k > imax then
invalid = tostring(k)
break
end
else
if not good[k] then
invalid = k
break
end
end
end
if invalid then
result = result .. message('mt-warn-param1', invalid)
end
end
Line 839 ⟶ 1,073:
local date = Date('juliandate', args[1], args[2])
if date then
return from_en(date:text())
end
return message('
end
Line 850 ⟶ 1,084:
local Date = getExports(frame)
local args = frame:getParent().args
local date = Date(args[1], args[2], args[3], args[4], args[5], args[6], args[7])
if date then
return tostring
end
return message('
end
Line 880 ⟶ 1,099:
local args = frame:getParent().args
local parms = {
wantDuration = yes[args.duration],
range = yes wantSc = yes
}
local fix = yes
local date1 = Date(fix, 'partial', stripToNil(args[1]) or 'currentdatetime')
if not date1 then
return message('
end
local date2 = Date(fix, 'partial', stripToNil(args[2]) or 'currentdatetime')
if not date2 then
return message('
end
parms.diff = date2 - date1
Line 899 ⟶ 1,119:
parm = translate[parm]
if parm == nil then -- test for nil because false is a valid setting
return message('
end
parms[argname] = parm
Line 910 ⟶ 1,130:
if show then
if show.id ~= round then
return message('
end
else
Line 918 ⟶ 1,138:
parms.round = true
end
return from_en(dateDifference(parms))
end
local function templateGeneric(frame)
local name = frame.args.template
if not name then
return message('mt-template-x')
end
return ageGeneric(frame:newChild{title = mw.title.new(name, 10), args = frame.args})
end
Line 924 ⟶ 1,152:
age_generic = ageGeneric, -- can emulate several age templates
birth_date_and_age = bda, -- Template:Birth_date_and_age
death_date_and_age = dda, -- Template:Death_date_and_age
gsd = dateToGsd, -- Template:Gregorian_serial_date
extract = dateExtract, -- Template:Extract
Line 929 ⟶ 1,158:
JULIANDAY = dateToJd, -- Template:JULIANDAY
time_interval = timeInterval, -- Template:Time_interval
[''] = templateGeneric, -- same as age_generic, but can be invoked directly
}
|