Module:Age: Difference between revisions

3,791 bytes added ,  6 years ago
update from sandbox: sortable=table; ranges of more time units; no default sort key in Template:Age in years and days; implement Template:Birth date and age; experimental range=no
m (Protected "Module:Age": High-risk Lua module; 1,000+ transclusions ([Edit=Require autoconfirmed or confirmed access] (indefinite)))
(update from sandbox: sortable=table; ranges of more time units; no default sort key in Template:Age in years and days; implement Template:Birth date and age; experimental range=no)
Line 1:
-- Implement various "age of" and other date-related templates.
 
local _Date, _current_date_currentDate
local function get_exportsgetExports(frame)
-- Return objects exported from the date module or its sandbox.
if not _Date then
Line 8:
local datemod = require('Module:Date' .. sandbox)
_Date = datemod._Date
_current_date_currentDate = datemod._current
end
return _Date, _current_date_currentDate
end
 
local Collection -- a table to hold items
local function collection()
Collection = {
-- Return a table to hold items.
add = function (self, item)
return {
nif item ~= 0,nil then
add = function (self, item)
self.n = self.n + 1
self[self.n] = item
end,
end,
join = function (self, sep)
return join = function table.concat(self, sep)
return table.concat(self, sep)
end,
end,
}
remove = function (self, pos)
end
if self.n > 0 and (pos == nil or (0 < pos and pos <= self.n)) then
self.n = self.n - 1
return table.remove(self, pos)
end
end,
sort = function (self, comp)
table.sort(self, comp)
end,
new = function ()
return setmetatable({n = 0}, Collection)
end
}
Collection.__index = Collection
 
local function strip_to_nilstripToNil(text)
-- If text is a string, return its trimmed content, or nil if empty.
-- Otherwise return text (which may, for example, be nil).
Line 43 ⟶ 55:
end
 
local function message(msg, nocatid)
-- Return formatted message text for an error or warning.
local categories = {
-- Can append "#FormattingError" to URL of a page with a problem to find it.
error = '[[Category:Age error]]',
local anchor = '<span id="FormattingError"></span>'
warning = '[[Category:Age error]]', -- same as error until determine whether 'Age warning' would be worthwhile
local category
}
if not nocat and mw.title.getCurrentTitle():inNamespaces(0, 10) then
local a, b, category
-- Category only in namespaces: 0=article, 10=template.
if id == 'warning' then
category = '[[Category:Age error]]'
a = '<sup>[<i>'
b = '</i>]</sup>'
else
a = '<strong class="error">Error: '
category = ''
b = '</strong>'
end
if mw.title.getCurrentTitle():inNamespaces(0) then
return anchor ..
-- Category only in namespaces: 0=article.
'<strong class="error">Error: ' ..
category = categories[id or 'error']
end
return
a ..
mw.text.nowiki(msg) ..
'</strong>'b ..
(category or '')
end
 
local function formatnumberformatNumber(number)
-- Return the given number formatted with commas as group separators,
-- given that the number is an integer.
local numstr = tostring(number)
local length = #numstr
local places = collectionCollection.new()
local pos = 0
repeat
Line 73 ⟶ 92:
until pos >= length
places:add(length)
local groups = collectionCollection.new()
for i = places.n, 2, -1 do
local p1 = length - places[i] + 1
Line 82 ⟶ 101:
end
 
local function make_sortmakeSort(value, sortable)
-- Return a sort key in a span if specifiedrequested.
-- Assume value is a valid number which has not overflowed.
if sortable == 'sortable_table' or sortable == 'sortable_on' or sortable == 'sortable_debug' then
local sortkey
if value == 0 then
Line 100 ⟶ 119:
sortkey = string.format('%d', prefix) .. string.format('%015.0f', math.floor(value * 10^(14-mag)))
end
local lhs, = sortable == 'sortable_debug' andrhs
if sortable == 'sortable_table' then
'<span style="border:1px solid;display:inline;" class="sortkey">' or
lhs = 'data-sort-value="'
'<span style="display:none" class="sortkey">'
rhs = '"|'
return lhs .. sortkey .. '♠</span>'
else
lhs = sortable == 'sortable_debug' and
'<span style="border:1px solid;display:inline;" class="sortkey">' or
'<span style="display:none" class="sortkey">'
rhs = '♠</span>'
end
return lhs .. sortkey .. rhs
end
end
 
local translate_parameterstranslateParameters = {
abbr = {
off = 'abbr_off',
Line 141 ⟶ 167:
ymw = { 'y', 'm', 'w', id = 'ymw' },
ymwd = { 'y', 'm', 'w', 'd', id = 'ymwd' },
yd = { 'y', 'd', id = 'yd', keepzerokeepZero = true },
m = { 'm', id = 'm' },
md = { 'm', 'd', id = 'md' },
Line 161 ⟶ 187:
off = false,
on = 'sortable_on',
table = 'sortable_table',
debug = 'sortable_debug',
},
}
 
local function date_extractdateExtract(frame)
-- Return part of a date after performing an optional operation.
local Date = get_exportsgetExports(frame)
local args = frame:getParent().args
local parms = {}
Line 183 ⟶ 210:
return message('Need valid date')
end
local add = strip_to_nilstripToNil(args.add)
if add then
for item in add:gmatch('%S+') do
Line 193 ⟶ 220:
end
local prefix, result
local sortable = translate_parameterstranslateParameters.sortable[args.sortable]
if sortable then
local value = (date.partial and date.partial.first or date).jdz
prefix = make_sortmakeSort(value, sortable)
end
local show = strip_to_nilstripToNil(args.show) or 'dmy'
if show ~= 'hide' then
result = date[show]
Line 212 ⟶ 239:
end
 
local function make_textmakeText(values, components, names, options)
-- Return wikitext representing an age or duration.
local text = collectionCollection.new()
local count = #values
local sep = names.sep or ''
Line 220 ⟶ 247:
-- v is a number (say 4 for 4 years), or a table ({4,5} for 4 or 5 years).
local islist = type(v) == 'table'
if (islist or v > 0) or (text.n == 0 and i == count) or (text.n > 0 and components.keepzerokeepZero) then
local fmt, vstr
if i == 1 and options.format == 'format_commas' then
-- Numbers after the first should be small and not need formatting.
fmt = formatnumberformatNumber
else
fmt = tostring
Line 283 ⟶ 310:
end
 
local function date_differencedateDifference(parms)
-- Return a formatted date difference using the given parameters
-- which have been validated.
Line 323 ⟶ 350:
local show = parms.show -- may be nil; default is set below
local abbr = parms.abbr or 'abbr_off'
local default_joindefaultJoin
if abbr ~= 'abbr_off' then
default_joindefaultJoin = 'sep_space'
end
if not show then
Line 331 ⟶ 358:
if parms.disp == 'disp_age' then
if diff.years < 3 then
default_joindefaultJoin = 'sep_space'
if diff.years >= 1 then
show = 'ym'
Line 343 ⟶ 370:
end
if type(show) ~= 'table' then
show = translate_parameterstranslateParameters.show[show]
end
if parms.disp == 'disp_raw' then
default_joindefaultJoin = 'sep_space'
abbr = 'abbr_raw'
elseif parms.want_scwantSc then
default_joindefaultJoin = 'sep_serialcomma'
end
local diff_optionsdiffOptions = {
round = parms.round,
duration = parms.want_durationwantDuration,
range = parms.range and true or nil,
}
local prefix
if parms.sortable then
local value = diff.age_days + (parms.want_durationwantDuration and 1 or 0) -- days and fraction of a day
if diff.isnegative then
value = -value
end
prefix = make_sortmakeSort(value, parms.sortable)
end
local text_optionstextOptions = {
prefix = prefix,
suffix = parms.suffix, -- not currently used
format = parms.format,
join = parms.sep or default_joindefaultJoin,
isnegative = diff.isnegative,
range = parms.range,
Line 375 ⟶ 402:
return prefix or ''
end
local values = { diff:age(show.id, diff_optionsdiffOptions) }
if values[1] then
return make_textmakeText(values, show, names[abbr], text_optionstextOptions)
end
if diff.partial then
-- Handle a more complex range such as
-- {{age_yd|20 Dec 2001|2003|range=yes}} → 1 year, 12 days or 2 years, 11 days
local opt = {
format = textOptions.format,
join = textOptions.join,
isnegative = textOptions.isnegative,
}
return
(textOptions.prefix or '') ..
makeText({ diff.partial.mindiff:age(show.id, diffOptions) }, show, names[abbr], opt) ..
(textOptions.range == 'dash' and '–' or '&nbsp;or ') ..
makeText({ diff.partial.maxdiff:age(show.id, diffOptions) }, show, names[abbr], opt) ..
(textOptions.suffix or '')
end
return message('Parameter show=' .. show.id .. ' is not supported here')
end
 
local function get_datesgetDates(frame, getopt)
-- Parse template parameters and return one of:
-- * date (a date table, if single)
Line 388 ⟶ 430:
-- * text (a string error message)
-- A missing date is replaced with the current date.
-- If want_mixturewantMixture is true, a missing date component is replaced
-- from the current date, so can get a bizarre mixture of
-- specified/current y/m/d as has been done by some "age" templates.
-- Some results may be placed in table getopt.
local Date, current_datecurrentDate = get_exportsgetExports(frame)
getopt = getopt or {}
local fix = getopt.fix and 'fix' or ''
local partial = getopt.rangepartial and 'partial' or ''
local args = frame:getParent().args
local fields = {}
local is_namedisNamed = args.year or args.year1 or args.year2 or
args.month or args.month1 or args.month2 or
args.day or args.day1 or args.day2
if is_namedisNamed then
fields[1] = args.year1 or args.year
fields[2] = args.month1 or args.month
Line 415 ⟶ 457:
local imax = 0
for i = 1, 6 do
fields[i] = strip_to_nilstripToNil(fields[i])
if fields[i] then
imax = i
end
end
local singlenoDefault = imax == 0 and getopt.singlenoMissing
local dates = {}
if is_namedisNamed or imax >= 23 then
local nr_datesnrDates = getopt.single and 1 or 2
if getopt.want_mixturewantMixture then
-- Cannot be partial since empty fields are set from current.
local components = { 'year', 'month', 'day' }
for i = 1, nr_datesnrDates * 3 do
fields[i] = fields[i] or current_datecurrentDate[components[i > 3 and i - 3 or i]]
end
for i = 1, nr_datesnrDates do
local index = i == 1 and 1 or 4
dates[i] = Date(fields[index], fields[index+1], fields[index+2])
end
else
for i = 1, nr_datesnrDates do
local index = i == 1 and 1 or 4
local y, m, d = fields[index], fields[index+1], fields[index+2]
if (partial and y) or (y and m and d) then
dates[i] = Date(fix, partial, y, m, d)
elseif not (y orand not m orand not d) and not noDefault then
dates[i] = Date('currentdate')
end
end
end
elseif not noDefault then
else
getopt.textdates = true -- have parsed each date from a single text field
dates[1] = Date(fix, partial, fields[1] or 'currentdate')
if not getopt.single then
dates[2] = Date(fix, partial, fields[2] or 'currentdate')
end
Line 455 ⟶ 497:
return message('Need valid year, month, day')
end
if getopt.single then
return dates[1]
end
Line 464 ⟶ 506:
end
 
local function age_genericageGeneric(frame)
-- Return the result required by the specified template.
-- Can use sortable=x where x = on/table/off/debug in any supported template.
-- Some templates default to sortable=on but can be overridden with sortable=off.
local name = frame.args.template
if not name then
Line 542 ⟶ 584:
format = 'format_commas',
sep = args.sep ~= 'and' and 'sep_comma' or nil,
sortable = 'on', -- temporarily use sortable for compatibility with old template; talk proposes removing this
},
age_yd_nts = { -- {{age in years and days nts}}
Line 560 ⟶ 601:
age_ymwd = { -- {{age in years, months, weeks and days}}
show = 'ymwd',
want_mixturewantMixture = true,
},
}
Line 568 ⟶ 609:
end
if name == 'age_days' then
local su = strip_to_nilstripToNil(args['show unit'])
if su then
if su == 'abbr' or su == 'full' then
Line 576 ⟶ 617:
end
end
local partial
local range = spec.range or yes(args.range) or (args.range == 'dash' and 'dash' or nil)
local range = stripToNil(args.range) or spec.range
if range then
-- Suppose partial dates are used and age could be 11 or 12 years.
-- "|range=" (empty value) has no effect (spec is used).
-- "|range=yes" or spec.range == true sets range = true (gives "11 or 12")
-- "|range=dash" sets range = 'dash' (gives "11–12").
-- "|range=no" sets range = nil (gives "12").
-- Above gives a good result with age in years, but is probably unhelpful for other cases.
-- {{age in years|year1=1900|year2=1910|range=no}} → 10
-- {{age in days|year1=1900|year2=1910|range=no}} → 4016 (from 1900-01-01 to 1910-12-31)
-- "|range=OTHER" sets range = nil and rejects partial dates.
range = ({ dash = 'dash', no = 'no', [true] = true })[range] or yes(range)
if range then
partial = true -- accept partial dates with a possible age range for the result
if range == 'no' then
range = nil
end
end
end
local getopt = {
fix = yes(args.fix),
rangepartial = rangepartial,
want_mixturewantMixture = spec.want_mixturewantMixture,
}
local date1, date2 = get_datesgetDates(frame, getopt)
if type(date1) == 'string' then
return date1
end
local format = strip_to_nilstripToNil(args.format)
if format then
format = 'format_' .. format
Line 594 ⟶ 654:
local parms = {
diff = date2 - date1,
want_durationwantDuration = spec.duration or yes(args.duration),
range = range,
want_scwantSc = yes(args.sc),
show = args.show == 'hide' and 'hide' or spec.show,
abbr = spec.abbr,
Line 603 ⟶ 663:
round = yes(args.round),
sep = spec.sep,
sortable = translate_parameterstranslateParameters.sortable[args.sortable or spec.sortable],
}
if (spec.negative or frame.args.negative) == 'error' and parms.diff.isnegative then
return message('The second date should not be before the first date')
end
return date_differencedateDifference(parms)
end
 
local function bda(frame)
-- Implement [[Template:Birth date and age]].
local args = frame:getParent().args
local options = { noMissing=true, single=true }
local date = getDates(frame, options)
if type(date) == 'string' then
return date -- error text
end
local Date = getExports(frame)
local diff = Date('currentdate') - date
if diff.isnegative or diff.years > 150 then
return message('Invalid birth date for calculating age')
end
local disp, show = 'disp_raw', 'y'
if diff.years < 2 then
disp = 'disp_age'
if diff.years == 0 and diff.months == 0 then
show = 'd'
else
show = 'm'
end
end
local df = stripToNil(args.df) -- day first (dmy); default is month first (mdy)
local result = df and
'%-d %B %-Y' or
'%B %-d, %-Y'
result = '(<span class="bday">%-Y-%m-%d</span>) </span>' .. result
result = '<span style="display:none"> ' ..
date:text(result) ..
'<span class="noprint ForceAgeToShow"> ' ..
'(age&nbsp;' ..
dateDifference({
diff = diff,
show = show,
abbr = 'abbr_off',
disp = disp,
sep = 'sep_space',
}) ..
')</span>'
local warnings = tonumber(frame.args.warnings)
if warnings and warnings > 0 then
local good = {
df = true,
mf = true,
template = true,
day = true,
day1 = true,
month = true,
month1 = true,
year = true,
year1 = true,
}
local invalid
local imax = options.textdates and 1 or 3
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('invalid parameter ' .. invalid, 'warning')
end
end
return result
end
 
local function date_to_gsddateToGsd(frame)
-- ThisImplement implements {{gregorian[[Template:Gregorian serial date}}]].
-- Return Gregorian serial date of the given date, or the current date.
-- The returned value is negative for dates before 1 January 1 AD
-- despite the fact that GSD is not defined for such dates.
local date = get_datesgetDates(frame, { want_mixturewantMixture=true, single=true })
if type(date) == 'string' then
return date
Line 623 ⟶ 757:
end
 
local function jd_to_datejdToDate(frame)
-- Return formatted date from a Julian date.
-- The result includes a time if the input includes a fraction.
-- The word 'Julian' is accepted for the Julian calendar.
local Date = get_exportsgetExports(frame)
local args = frame:getParent().args
local date = Date('juliandate', args[1], args[2])
Line 636 ⟶ 770:
end
 
local function date_to_jddateToJd(frame)
-- Return Julian date (a number) from a date which may include a time,
-- or the current date ('currentdate') or current date and time ('currentdatetime').
-- The word 'Julian' is accepted for the Julian calendar.
local Date = get_exportsgetExports(frame)
local args = frame:getParent().args
local date = Date(args[1], args[2], args[3], args[4], args[5], args[6], args[7])
Line 649 ⟶ 783:
end
 
local function time_intervaltimeInterval(frame)
-- ThisImplement implements {{time[[Template:Time interval}}]].
-- There are two positional arguments: date1, date2.
-- The default for each is the current date and time.
-- Result is date2 - date1 formatted.
local Date = get_exportsgetExports(frame)
local args = frame:getParent().args
local parms = {
want_durationwantDuration = yes(args.duration),
range = yes(args.range) or (args.range == 'dash' and 'dash' or nil),
want_scwantSc = yes(args.sc),
}
local fix = yes(args.fix) and 'fix' or ''
local date1 = Date(fix, 'partial', strip_to_nilstripToNil(args[1]) or 'currentdatetime')
if not date1 then
return message('Invalid start date in first parameter')
end
local date2 = Date(fix, 'partial', strip_to_nilstripToNil(args[2]) or 'currentdatetime')
if not date2 then
return message('Invalid end date in second parameter')
end
parms.diff = date2 - date1
for argname, translate in pairs(translate_parameterstranslateParameters) do
local parm = strip_to_nilstripToNil(args[argname])
if parm then
parm = translate[parm]
Line 690 ⟶ 824:
end
else
parms.show = translate_parameterstranslateParameters.show[round]
end
end
parms.round = true
end
return date_differencedateDifference(parms)
end
 
return {
age_generic = age_genericageGeneric, -- can emulate several age templates
gsdbirth_date_and_age = date_to_gsdbda, -- Template:Gregorian_serial_dateBirth_date_and_age
extractgsd = date_extractdateToGsd, -- Template:ExtractGregorian_serial_date
jd_to_dateextract = jd_to_datedateExtract, -- Template:?Extract
JULIANDAYjd_to_date = date_to_jdjdToDate, -- Template:JULIANDAY?
time_intervalJULIANDAY = time_intervaldateToJd, -- Template:Time_intervalJULIANDAY
time_interval = timeInterval, -- Template:Time_interval
}
Anonymous user