localp={}--[[--------------------------< F O R W A R D D E C L A R A T I O N S >--------------------------------------]]localis_set,in_array;-- imported function from selected Module:Citation/CS1/Utilities--[[-------------------------< I S _ V A L I D _ A C C E S S D A T E >----------------------------------------returns true if: Wikipedia start date <= accessdate < today + 2 daysWikipedia start date is 2001-01-15T00:00:00 UTC which is 979516800 seconds after 1970-01-01T00:00:00 UTC (the start of Unix time)accessdate is the date provided in |accessdate= at time 00:00:00 UTCtoday is the current date at time 00:00:00 UTC plus 48 hours if today is 2015-01-01T00:00:00 then adding 24 hours gives 2015-01-02T00:00:00 – one second more than today adding 24 hours gives 2015-01-03T00:00:00 – one second more than tomorrowThis function does not work if it is fed month names for languages other than English. Wikimedia #time: parserapparently doesn't understand non-Engish date month names. This function will always return false when the datecontains a non-English month name because good1 is false after the call to lang.formatDate(). To get around thatcall this function with YYYY-MM-DD format dates.]]localfunctionis_valid_accessdate(accessdate)locallang=mw.getContentLanguage();localgood1,good2;localaccess_ts,tomorrow_ts;-- to hold unix time stamps representing the datesgood1,access_ts=pcall(lang.formatDate,lang,'U',accessdate);-- convert accessdate value to unix timesatmpgood2,tomorrow_ts=pcall(lang.formatDate,lang,'U','today + 2 days');-- today midnight + 2 days is one second more than all day tomorrowifgood1andgood2thenaccess_ts=tonumber(access_ts);-- convert to numbers for the comparisontomorrow_ts=tonumber(tomorrow_ts);elsereturnfalse;-- one or both failed to convert to unix time stampendif979516800<=access_tsandaccess_ts<tomorrow_tsthen-- Wikipedia start date <= accessdate < tomorrow's datereturntrue;elsereturnfalse;-- accessdate out of rangeendend--[[--------------------------< G E T _ M O N T H _ N U M B E R >----------------------------------------------returns a number according to the month in a date: 1 for January, etc. Capitalization and spelling must be correct. If not a valid month, returns 0]]localfunctionget_month_number(month)localmwl_long_months={janeiro=1,febreiro=2,['márcio']=3,abril=4,maio=5,['júnio']=6,['júlio']=7,agosto=8,setembre=9,outubre=10,nobembre=11,dezembre=12};localmwl_short_months={jan=1,feb=2,['már']=3,abr=4,['jún']=6,['júl']=7,ago=8,set=9,out=10,nob=11,dez=12};-- Retorna o mês correspondente, ou 0 caso mês não existeifmonththenmonth=string.lower(month:sub(1,1))..month:sub(2)endreturnmwl_long_months[month]ormwl_short_months[month]or0;end--[[--------------------------< I S _ V A L I D _ E M B A R G O _ D A T E >------------------------------------returns true and date value if that value has proper dmy, mdy, ymd format.returns false and 9999 (embargoed forever) when date value is not proper format; assumes that when |embargo= isset, the editor intended to embargo a pmc but |embargo= does not hold a single date.]]localfunctionis_valid_embargo_date(v)ifv:match('^%d%d%d%d%-%d%d%-%d%d$')or-- ymdv:match('^%d%d?%s+%a+%s+%d%d%d%d$')or-- dmy -- dmyv:match('^%a+%s+%d%d?%s*,%s*%d%d%d%d$')then--mdy -- mdyreturntrue,v;endreturnfalse,'9999';-- if here not good date so return false and set embargo date to long time in futureend--[[--------------------------< G E T _ S E A S O N _ N U M B E R >--------------------------------------------returns a number according to the sequence of seasons in a year: 1 for Winter, etc. Capitalization and spelling must be correct. If not a valid season, returns 0]]localyear_limit;localfunctionget_season_number(season)-- make sure these numbers do not overlap month numberslocalseason_mwl_list={ambierno=21,purmabera=22,['berano']=23,outonho=24};ifseasonthenseason=string.lower(season:sub(1,1))..season:sub(2)endreturnseason_mwl_list[season]or-- if season is a valid name return its number0;-- misspelled, improper case, or not a season nameend--[[--------------------------< I S _ P R O P E R _ N A M E >--------------------------------------------------returns a non-zero number if date contains a recognized proper name. Capitalization and spelling must be correct.]]localfunctionis_proper_name(name)localname_mwl_list={Natal=31}returnname_mwl_list[name]or-- if name is a valid name return its number0;-- misspelled, improper case, or not a proper nameend--[[--------------------------< I S _ V A L I D _ M O N T H _ O R _ S E A S O N >------------------------------Returns true if month or season is valid (properly spelled, capitalized, abbreviated, (non-)dotted, etc.).]]localfunctionis_valid_month_or_season(month_season)-- se a string não retornar um indíce da tabela de meses, pode representar uma estaçãoif0==get_month_number(month_season)then-- se também não for estação, deverá retornar "false"if0==get_season_number(month_season)thenreturnfalse;endendreturntrue;end--[[--------------------------< I S _ V A L I D _ Y E A R >----------------------------------------------------Function gets current year from the server and compares it to year from a citation parameter. Years more than one year in the future are not acceptable.]]localyear_limit;localfunctionis_valid_year(year)ifnotis_set(year_limit)thenyear_limit=tonumber(os.date("%Y"))+1;-- global variable so we only have to fetch it onceendreturntonumber(year)<=year_limit;-- false if year is in the future more than one yearend--[[--------------------------< I S _ V A L I D _ D A T E >----------------------------------------------------Returns true if day is less than or equal to the number of days in month and year is no farther into the futurethan next year; else returns false.Assumes Julian calendar prior to year 1582 and Gregorian calendar thereafter. Accounts for Julian calendar leapyears before 1582 and Gregorian leap years after 1582. Where the two calendars overlap (1582 to approximately1923) dates are assumed to be Gregorian.]]localfunctionis_valid_date(year,month,day)localdays_in_month={31,28,31,30,31,30,31,31,30,31,30,31};localmonth_length;ifnotis_valid_year(year)then-- no farther into the future than next yearreturnfalse;endmonth=tonumber(month);-- required for YYYY-MM-DD datesif(2==month)then-- if Februarymonth_length=28;-- then 28 days unlessif1582>tonumber(year)then-- Julian calendarif0==(year%4)thenmonth_length=29;endelse-- Gregorian calendarif(0==(year%4)and(0~=(year%100)or0==(year%400)))then-- is a leap year?month_length=29;-- if leap year then 29 days in Februaryendendelsemonth_length=days_in_month[month];endiftonumber(day)>month_lengththenreturnfalse;endreturntrue;end--[[--------------------------< I S _ V A L I D _ M O N T H _ R A N G E _ S T Y L E >--------------------------Espera-se que a informação sobre o intervalo entre meses siga o mesmoformato: "јаneiro—febreiro" ó "јаn—feb" but not "janeiro—feb" etc.Retorna true quando o formato para ambos os meses forem o mesmo.]]localfunctionis_valid_month_range_style(month1,month2)locallen1=month1:len()locallen2=month2:len()-- Ambos os meses são abreviados, ou coincidem na quantidade de letrasiflen1==len2thenreturntrue-- Tratamento especial para 'maio'elseif'maio'==month1or'maio'==month2thenreturntrue-- Apenas um dos meses está abreviado, então retorna falseelseif3==len1or3==len2thenreturnfalseelse-- Ambos os meses não estão abreviados, então retorna truereturntrueendend--[[--------------------------< I S _ V A L I D _ M O N T H _ S E A S O N _ R A N G E >------------------------Check a pair of months or seasons to see if both are valid members of a month or season pair.Month pairs are expected to be left to right, earliest to latest in time.Similarly, seasons are also left to right, earliest to latest in time. There is an oddity with seasons: winter is assigned a value of 1, spring 2, ...,fall and autumn 4. Because winter can follow fall/autumn at the end of a calender year, a special test is made to see if |date=Fall-Winter yyyy (4-1) is the date.]]localfunctionis_valid_month_season_range(range_start,range_end)localrange_start_number=get_month_number(range_start);localrange_end_number;if0==range_start_numberthen-- is this a month range?localrange_start_number=get_season_number(range_start);-- not a month; is it a season? get start season numberrange_end_number=get_season_number(range_end);-- get end season numberif0~=range_start_numberthen-- is start of range a season?ifrange_start_number<range_end_numberthen-- range_start is a seasonreturntrue;-- return true when range_end is also a season and follows start season; else falseendif24==range_start_numberand21==range_end_numberthen-- special case when season range is Fall-Winter or Autumn-Winterreturntrue;endendreturnfalse;-- range_start is not a month or a season; or range_start is a season and range_end is not; or improper season sequenceendrange_end_number=get_month_number(range_end);-- get end month numberifrange_start_number<range_end_numberthen-- range_start is a month; does range_start precede range_end?ifis_valid_month_range_style(range_start,range_end)then-- do months have the same style?returntrue;-- proper order and same styleendendreturnfalse;-- range_start month number is greater than or equal to range end number; or range end isn't a monthend--[[--------------------------< M A K E _ C O I N S _ D A T E >------------------------------------------------This function receives a table of date parts for one or two dates and an empty table reference declared inModule:Citation/CS1. The function is called only for |date= parameters and only if the |date=<value> isdetermined to be a valid date format. The question of what to do with invalid date formats is not answered here.The date parts in the input table are converted to an ISO 8601 conforming date string: single whole dates: yyyy-mm-dd month and year dates: yyyy-mm year dates: yyyy ranges: yyyy-mm-dd/yyyy-mm-dd yyyy-mm/yyyy-mm yyyy/yyyyDates in the Julian calendar are reduced to year or year/year so that we don't have to do calendar conversion fromJulian to Proleptic Gregorian.The input table has: year, year2 – always present; if before 1582, ignore months and days if present month, month2 – 0 if not provided, 1-12 for months, 21-24 for seasons; 31– proper name dates day, day2 – 0 if not provided, 1-31 for daysthe output table receives: rftdate: an IS8601 formatted date rftchron: a free-form version of the date, usually without year which is in rftdate (season ranges and propername dates) rftssn: one of four season keywords: winter, spring, summer, fall (lowercase)]]localfunctionmake_COinS_date(input,tCOinS_date)localdate;-- one date or first date in a rangelocaldate2='';-- end of range dateif1582>tonumber(input.year)or20<tonumber(input.month)then-- Julian calendar or season so &rft.date gets year onlydate=input.year;if0~=input.year2andinput.year~=input.year2then-- if a range, only the second year portion when not the same as range start yeardate=string.format('%.4d/%.4d',tonumber(input.year),tonumber(input.year2))-- assemble the date rangeendif20<tonumber(input.month)then-- if season or propername datelocalseason={[21]='ambierno',[22]='purmabera',[23]='berano',[24]='outonho',[31]='Natal'};-- seasons lowercase, no autumn; proper names use title caseif0==input.month2then-- single season dateif30<tonumber(input.month)thentCOinS_date.rftchron=season[input.month];-- proper name dateselsetCOinS_date.rftssn=season[input.month];-- seasonsendelse-- season range with a second season specifiedifinput.year~=input.year2then-- season year – season year range or season year–yeartCOinS_date.rftssn=season[input.month];-- start of range season; keep this?if0~=input.month2thentCOinS_date.rftchron=string.format('%s %s – %s %s',season[input.month],input.year,season[input.month2],input.year2);endelse-- season–season year rangetCOinS_date.rftssn=season[input.month];-- start of range season; keep this?tCOinS_date.rftchron=season[input.month]..'–'..season[input.month2];-- season–season year rangeendendendtCOinS_date.rftdate=date;return;-- doneendif0~=input.daythendate=string.format('%s-%.2d-%.2d',input.year,tonumber(input.month),tonumber(input.day));-- whole dateelseif0~=input.monththendate=string.format('%s-%.2d',input.year,tonumber(input.month));-- year and monthelsedate=string.format('%s',input.year);-- just yearendif0~=input.year2thenif0~=input.day2thendate2=string.format('/%s-%.2d-%.2d',input.year2,tonumber(input.month2),tonumber(input.day2));-- whole dateelseif0~=input.month2thendate2=string.format('/%s-%.2d',input.year2,tonumber(input.month2));-- year and monthelsedate2=string.format('/%s',input.year2);-- just yearendendtCOinS_date.rftdate=date..date2;-- date2 has the '/' separatorreturn;end--[[--------------------------< C H E C K _ D A T E >----------------------------------------------------------Check date format to see that it is one of the formats approved by WP:DATESNO or WP:DATERANGE. Exception: onlyallowed range separator is endash. Additionally, check the date to see that it is a real date: no 31 in 30-daymonths; no 29 February when not a leap year. Months, both long-form and three character abbreviations, and seasonsmust be spelled correctly. Future years beyond next year are not allowed.If the date fails the format tests, this function returns false and does not return values for anchor_year andCOinS_date. When this happens, the date parameter is used in the COinS metadata and the CITEREF identifier getsits year from the year parameter if present otherwise CITEREF does not get a date value.Inputs: date_string - date string from date-holding parameters (date, year, accessdate, embargo, archivedate, etc.)Returns: false if date string is not a real date; else true, anchor_year, COinS_date anchor_year can be used in CITEREF anchors COinS_date is ISO 8601 format date; see make_COInS_date()!!! DON'T UPDATE MATCH STRINGS ONLY HERE BUT ALSO IN Módulo:Citação/CS1, AND BOTH AT THE SAME TIME !!!]]localfunctioncheck_date(date_string,tCOinS_date,test_accessdate)localyear;-- assume that year2, months, and days are not used;localyear2=0;-- second year in a year rangelocalmonth=0;localmonth2=0;-- second month in a month rangelocalday=0;localday2=0;-- second day in a day rangelocalanchor_year;localcoins_date;date_string=date_string:gsub(" de "," ");-- inclui "de" no formatoifmw.ustring.match(date_string,"^[1-9]%d? +[%a%ç]+%.? +[1-9]%d%d%d%a?$")ormw.ustring.match(date_string,"^[1][%º*%.]* +[%a%ç]+%.? +[1-9]%d%d%d%a?$")then-- day-initial: day month yearday,month,anchor_year,year=mw.ustring.match(date_string,"(%d%d*)[%º%.]*%s*([%a%ç]+)%.?%s*((%d%d%d%d)%a?)")month=get_month_number(month)if12<monthor1>monthor1583>tonumber(year)thenreturnfalse;end-- month number not valid or not Gregorian calendarelseifmw.ustring.match(date_string,"^%d+[/%.%-]%d+[/%.%-]%d%d%d%d$")then-- day-initial day month numerical year formatday,month,year=mw.ustring.match(date_string,"(%d+)[/%.%-](%d+)[/%.%-](%d%d%d%d)");month=tonumber(month);if12<monthor1>monthor1583>tonumber(year)thenreturnfalse;end-- month number not valid or not Gregorian calendaranchor_year=year;elseifmw.ustring.match(date_string,"^%d%d%d%d[/%.%-]%d+[/%.%-]%d+$")then-- year-initial numerical year month day formatyear,month,day=mw.ustring.match(date_string,"(%d%d%d%d)[/%.%-](%d+)[/%.%-](%d+)");month=tonumber(month);if12<monthor1>monthor1583>tonumber(year)thenreturnfalse;end-- month number not valid or not Gregorian calendaranchor_year=year;elseifmw.ustring.match(date_string,"^[%a%ç]+%.? +[1-9]%d?, +[1-9]%d%d%d%a?$")then-- month-initial: month day, yearmonth,day,anchor_year,year=mw.ustring.match(date_string,"([%a%ç]+)%.?%s*(%d%d?),%s*((%d%d%d%d)%a?)");month=get_month_number(month);if0==monththenreturnfalse;end-- return false if month text isn't one of the twelve monthselseifmw.ustring.match(date_string,"^[%a%ç]+%.? +[1-9]%d?[%-–][1-9]%d?, +[1-9]%d%d%d%a?$")then-- month-initial day range: month day–day, year; days are separated by endashmonth,day,day2,anchor_year,year=mw.ustring.match(date_string,"([%a%ç]+)%.? +(%d%d?)[%-–](%d%d?), +((%d%d%d%d)%a?)");iftonumber(day)>=tonumber(day2)thenreturnfalse;end-- date range order is left to right: earlier to later; dates may not be the same;month=get_month_number(month);if0==monththenreturnfalse;end-- return false if month text isn't one of the twelve monthsmonth2=month;-- for metadatayear2=yearelseifmw.ustring.match(date_string,"^[1-9]%d?[%-–][1-9]%d? +[%a%ç]+%.? +[1-9]%d%d%d%a?$")then-- day-range-initial: day–day month year; days are separated by endashday,day2,month,anchor_year,year=mw.ustring.match(date_string,"(%d%d?)[%-–](%d%d?) +([%a%ç]+)%.? +((%d%d%d%d)%a?)");iftonumber(day)>=tonumber(day2)thenreturnfalse;end-- date range order is left to right: earlier to later; dates may not be the same;month=get_month_number(month);if0==monththenreturnfalse;end-- return false if month text isn't one of the twelve monthsmonth2=month;-- for metadatayear2=year;elseifmw.ustring.match(date_string,"^[1-9]%d? +[%a%ç]+%.? [%-–] [1-9]%d? +[%a%ç]+%.? +[1-9]%d%d%d%a?$")then-- day initial month-day-range: day month - day month year; uses spaced endashday,month,day2,month2,anchor_year,year=mw.ustring.match(date_string,"(%d%d?) +([%a%ç]+)%.? [%-–] (%d%d?) +([%a%ç]+)%.? +((%d%d%d%d)%a?)");if(notis_valid_month_season_range(month,month2))ornotis_valid_year(year)thenreturnfalse;end-- date range order is left to right: earlier to later;month=get_month_number(month);-- for metadatamonth2=get_month_number(month2);year2=year;elseifmw.ustring.match(date_string,"^[%a%ç]+%.? +[1-9]%d? [%-–] [%a%ç]+%.? +[1-9]%d?, +[1-9]%d%d%d?%a?$")then-- month initial month-day-range: month day – month day, year; uses spaced endashmonth,day,month2,day2,anchor_year,year=mw.ustring.match(date_string,"([%a%ç]+)%.? +(%d%d?) [%-–] ([%a%ç]+)%.? +(%d%d?), +((%d%d%d%d)%a?)");if(notis_valid_month_season_range(month,month2))ornotis_valid_year(year)thenreturnfalse;endmonth=get_month_number(month);-- for metadatamonth2=get_month_number(month2);year2=year;elseifmw.ustring.match(date_string,"^[1-9]%d? +[%a%ç]+%.? +[1-9]%d%d%d [%-–] [1-9]%d? +[%a%ç]+%.? +[1-9]%d%d%d%a?$")then-- day initial month-day-year-range: day month year - day month year; uses spaced endashday,month,year,day2,month2,anchor_year,year2=mw.ustring.match(date_string,"(%d%d?) +([%a%ç]+)%.? +(%d%d%d%d?) [%-–] (%d%d?) +([%a%ç]+)%.? +((%d%d%d%d?)%a?)");iftonumber(year2)<tonumber(year)thenreturnfalse;end-- must be sequential years, left to right, earlier to laterifnotis_valid_year(year2)ornotis_valid_month_range_style(month,month2)thenreturnfalse;end-- year2 no more than one year in the future; months same stylemonth=get_month_number(month);month2=get_month_number(month2);elseifmw.ustring.match(date_string,"^[%a%ç]+%.? +[1-9]%d?, +[1-9]%d%d%d [%-–] [%a%ç]+%.? +[1-9]%d?, +[1-9]%d%d%d%a?$")then-- month initial month-day-year-range: month day, year – month day, year; uses spaced endashmonth,day,year,month2,day2,anchor_year,year2=mw.ustring.match(date_string,"([%a%ç]+)%.? +(%d%d?), +(%d%d%d%d) [%-–] ([%a%ç]+)%.? +(%d%d?), +((%d%d%d%d)%a?)");iftonumber(year2)<=tonumber(year)thenreturnfalse;end-- must be sequential years, left to right, earlier to laterifnotis_valid_year(year2)ornotis_valid_month_range_style(month,month2)thenreturnfalse;end-- year2 no more than one year in the future; months same stylemonth=get_month_number(month);month2=get_month_number(month2);elseifmw.ustring.match(date_string,"^[%a%ã]+.? +[1-9]%d%d%d[%-–]%d%d%a?$")then-- special case Winter/Summer year-year (YYYY-YY); year separated with unspaced endashlocalcentury;month,year,century,anchor_year,year2=mw.ustring.match(date_string,"([%a%ã]+).? +((%d%d)%d%d)[%-–]((%d%d)%a?)");if'inverno'~=monthand'verão'~=monththenreturnfalseend;-- 'month' can only be Winter or Summeranchor_year=year..'–'..anchor_year;-- assemble anchor_year from both yearsyear2=century..year2;-- add the century to year2 for comparisonsif1~=tonumber(year2)-tonumber(year)thenreturnfalse;end-- must be sequential years, left to right, earlier to laterifnotis_valid_year(year2)thenreturnfalse;end-- no year farther in the future than next yearmonth=get_season_number(month);elseifmw.ustring.match(date_string,"^[%a%ç%ã]+.? +[1-9]%d%d%d[%-–][1-9]%d%d%d%a?$")then-- special case Winter/Summer year-year; year separated with unspaced endashmonth,year,anchor_year,year2=mw.ustring.match(date_string,"([%a%ç%ã]+).? +(%d%d%d%d)[%-–]((%d%d%d%d)%a?)");if'inverno'~=monthand'verão'~=monththenreturnfalseend;-- 'month' can only be Winter or Summeranchor_year=year..'–'..anchor_year;-- assemble anchor_year from both yearsif1~=tonumber(year2)-tonumber(year)thenreturnfalse;end-- must be sequential years, left to right, earlier to laterifnotis_valid_year(year2)thenreturnfalse;end-- no year farther in the future than next yearmonth=get_season_number(month);-- for metadataelseifmw.ustring.match(date_string,"^[%a%ç%ã]+.? +[1-9]%d%d%d +[%-–] +[%a%ç%ã]+.? +[1-9]%d%d%d%a?$")then-- month/season year - month/season year; separated by spaced endashmonth,year,month2,anchor_year,year2=mw.ustring.match(date_string,"([%a%ç%ã]+).? +(%d%d%d%d) +[%-–] +([%a%ç%ã]+).? +((%d%d%d%d)%a?)");anchor_year=year..'–'..anchor_year;-- assemble anchor_year from both yearsiftonumber(year)>=tonumber(year2)thenreturnfalse;end-- left to right, earlier to later, not the sameifnotis_valid_year(year2)thenreturnfalse;end-- no year farther in the future than next yearif0~=get_month_number(month)and0~=get_month_number(month2)andis_valid_month_range_style(month,month2)then-- both must be month year, same month stylemonth=get_month_number(month);month2=get_month_number(month2);elseif0~=get_season_number(month)and0~=get_season_number(month2)then-- both must be or season year, not mixedmonth=get_season_number(month);month2=get_season_number(month2);elsereturnfalse;endelseifmw.ustring.match(date_string,"^[%a%ç%ã]+.?[%-–][%a%ç%ã]+.? +[1-9]%d%d%d%a?$")then-- month/season range year; months separated by endashmonth,month2,anchor_year,year=mw.ustring.match(date_string,"([%a%ç%ã]+).?[%-–]([%a%ç%ã]+).? +((%d%d%d%d)%a?)");if(notis_valid_month_season_range(month,month2))or(notis_valid_year(year))thenreturnfalse;endif0~=get_month_number(month)then-- determined to be a valid range so just check this one to know if month or seasonmonth=get_month_number(month);month2=get_month_number(month2);elsemonth=get_season_number(month);month2=get_season_number(month2);endyear2=year;elseifmw.ustring.match(date_string,"^[%a%ç%ã]+.? +%d%d%d%d%a?$")then-- month/season year or proper-name yearmonth,anchor_year,year=mw.ustring.match(date_string,"([%a%ç%ã]+).? +((%d%d%d%d)%a?)");ifnotis_valid_year(year)thenreturnfalse;endifnotis_valid_month_or_season(month)and0==is_proper_name(month)thenreturnfalse;endif0~=get_month_number(month)then-- determined to be a valid range so just check this one to know if month or seasonmonth=get_month_number(month);elseif0~=get_season_number(month)thenmonth=get_season_number(month);elsemonth=is_proper_name(month);-- must be proper name; not supported in COinSendelseifmw.ustring.match(date_string,"^[1-9]%d%d%d?[%-–][1-9]%d%d%d?%a?$")then-- Year range: YYY-YYY or YYY-YYYY or YYYY–YYYY; separated by unspaced endash; 100-9999year,anchor_year,year2=mw.ustring.match(date_string,"(%d%d%d%d?)[%-–]((%d%d%d%d?)%a?)");anchor_year=year..'–'..anchor_year;-- assemble anchor year from both yearsiftonumber(year)>=tonumber(year2)thenreturnfalse;end-- left to right, earlier to later, not the sameifnotis_valid_year(year2)thenreturnfalse;end-- no year farther in the future than next yearelseifmw.ustring.match(date_string,"^[1-9]%d%d%d[%-–]%d%d%a?$")then-- Year range: YYYY–YY; separated by unspaced endashlocalcentury;year,century,anchor_year,year2=mw.ustring.match(date_string,"((%d%d)%d%d)[%-–]((%d%d)%a?)");anchor_year=year..'–'..anchor_year;-- assemble anchor year from both yearsif13>tonumber(year2)thenreturnfalse;end-- don't allow 2003-05 which might be May 2003year2=century..year2;-- add the century to year2 for comparisonsiftonumber(year)>=tonumber(year2)thenreturnfalse;end-- left to right, earlier to later, not the sameifnotis_valid_year(year2)thenreturnfalse;end-- no year farther in the future than next yearelseifmw.ustring.match(date_string,"^[1-9]%d%d%d?%a?$")then-- year; here accept either YYY or YYYYanchor_year,year=mw.ustring.match(date_string,"((%d%d%d%d?)%a?)");iffalse==is_valid_year(year)thenreturnfalse;endelsereturnfalse;-- date format not one of the MOS:DATE approved formatsendiftest_accessdatethen-- test accessdate here because we have numerical date partsif0~=yearand0~=monthand0~=dayand-- all parts of a single date required0==year2and0==month2and0==day2then-- none of these; accessdate must not be a rangeifnotis_valid_accessdate(year..'-'..month..'-'..day)thenreturnfalse;-- return false when accessdate out of boundsendelsereturnfalse;-- return false when accessdate is a range of two datesendendlocalresult=true;-- check whole dates for validity; assume true because not all dates will go through this testif0~=yearand0~=monthand0~=dayand0==year2and0==month2and0==day2then-- YMD (simple whole date)result=is_valid_date(year,month,day);elseif0~=yearand0~=monthand0~=dayand0==year2and0==month2and0~=day2then-- YMD-d (day range)result=is_valid_date(year,month,day);result=resultandis_valid_date(year,month,day2);elseif0~=yearand0~=monthand0~=dayand0==year2and0~=month2and0~=day2then-- YMD-md (day month range)result=is_valid_date(year,month,day);result=resultandis_valid_date(year,month2,day2);elseif0~=yearand0~=monthand0~=dayand0~=year2and0~=month2and0~=day2then-- YMD-ymd (day month year range)result=is_valid_date(year,month,day);result=resultandis_valid_date(year2,month2,day2);endiffalse==resultthenreturnfalse;endifnil~=tCOinS_datethen-- this table only passed into this function when testing |date= parameter valuesmake_COinS_date({year=year,month=month,day=day,year2=year2,month2=month2,day2=day2},tCOinS_date);-- make an ISO 8601 date string for COinSendreturntrue,anchor_year;-- format is good and date string represents a real dateend--[[--------------------------< D A T E S >--------------------------------------------------------------------Cycle the date-holding parameters in passed table date_parameters_list through check_date() to check compliance with MOS:DATE. For all valid dates, check_date() returnstrue. The |date= parameter test is unique, it is the only date holding parameter from which values for anchor_year (used in CITEREF identifiers) and COinS_date (used inthe COinS metadata) are derived. The |date= parameter is the only date-holding parameter that is allowed to contain the no-date keywords "n.d." or "nd" "n/d" (without quotes).Unlike most error messages created in this module, only one error message is created by this function. Because all of the date holding parameters are processed serially,a single error message is created as the dates are tested.]]localfunctiondates(date_parameters_list,tCOinS_date)localanchor_year;-- will return as nil if the date being tested is not |date=localembargo_date;-- if embargo date is a good dmy, mdy, ymd date then holds original value else reset to 9999localerror_message="";localgood_date=false;fork,vinpairs(date_parameters_list)do-- for each date-holding parameter in the listifk=='ano'then-- ignorar verificação enquanto não há tratamanto adequado quando ano é um século, AC etcfor_,tmpinipairs{'[Ss]éculo','[Ss]éc\.','AC','A%.C%.','AD','A%.D%.','aC','a%.C%.','dC','d%.C%.','DC','D%.C%.','^%d%d?$','^%d%d?[–%-]%d%d?%d?$'}doifv:find(tmp)thenanchor_year=vgood_date=truev=''breakendendendifis_set(v)then-- if the parameter has a valueifv:match("^c%. [1-9]%d%d%d?%a?$")then-- special case for c. year or with or without CITEREF disambiguator - only |date= and |year=localyear=v:match("c%. ([1-9]%d%d%d?)%a?");-- get the year portion so it can be testedanchor_year,tCOinS_date.rftdate=v:match("((c%. [1-9]%d%d%d?)%a?)");-- anchor year and COinS_date only from |date= parametergood_date=is_valid_year(year);elseif'data'==kthen-- if the parameter is |date=ifmw.ustring.match(v,"^n%.?%/?d%.%a?$")then-- if |date=n.d. with or without a CITEREF disambiguatorgood_date,anchor_year,tCOinS_date.rftdate=true,mw.ustring.match(v,"((n%.?%/?d%.)%a?)");--"n.d."; no error when date parameter is set to no dateelseifmw.ustring.match(v,"^nd%a?$")then-- if |date=nd with or without a CITEREF disambiguatorgood_date,anchor_year,tCOinS_date.rftdate=true,mw.ustring.match(v,"((nd)%a?)");--"nd"; no error when date parameter is set to no dateelseifmw.ustring.match(v,"^n/d%a?$")then-- if |date=nd with or without a CITEREF disambiguatorgood_date,anchor_year,tCOinS_date.rftdate=true,mw.ustring.match(v,"((nd)%a?)");--"nd"; no error when date parameter is set to no dateelsegood_date,anchor_year=check_date(v,tCOinS_date);-- go test the dateendelseif'ano'==kthen-- if the parameter is |year= it should hold only a year valueifmw.ustring.match(v,"^[1-9]%d%d%d?%.?%a?$")ormw.ustring.match(v,"^[1-9]%d%d%d?[%-–][1-9]%d%d%d?%a?$")then-- if |year= 3 or 4 digits only with or without a CITEREF disambiguatorgood_date,anchor_year=check_date(v,tCOinS_date);endelseif'acessodata'==kthen-- if the parameter is |date=good_date=check_date(v,nil,true);-- go test the date; nil is a placeholder; true is the test_accessdate flagelseif'embargo'==kthen-- if the parameter is |embargo=good_date=check_date(v);-- go test the dateiftrue==good_datethen-- if the date is a valid dategood_date,embargo_date=is_valid_embargo_date(v);-- is |embargo= date a single dmy, mdy, or ymd formatted date? yes:returns embargo; no: returns 9999endelse-- any other date-holding parametergood_date=check_date(v);-- go test the dateendiffalse==good_datethen-- assemble one error message so we don't add the tracking category multiple timesifis_set(error_message)then-- once we've added the first portion of the error message ...error_message=error_message..", ";-- ... add a comma space separatorenderror_message=error_message.."&#124;"..k.."=";-- add the failed parameterendendendreturnanchor_year,embargo_date,error_message;-- and doneend--[[--------------------------< Y E A R _ D A T E _ C H E C K >------------------------------------------------Compare the value provided in |year= with the year value(s) provided in |date=. This function returns a numeric value: 0 - year value does not match the year value in date 1 - (default) year value matches the year value in date or one of the year values when date contains two years 2 - year value matches the year value in date when date is in the form YYYY-MM-DD and year is disambiguated (|year=YYYYx)]]localfunctionyear_date_check(year_string,date_string)localyear;localdate1;localdate2;localresult=1;-- result of the test; assume that the test passesyear=mw.ustring.match(year_string,'(%d%d%d%d?)%.?');ifmw.ustring.match(date_string,'%d%d%d%d%-%d%d%-%d%d')andmw.ustring.match(year_string,'%d%d%d%d%.?a')then--special case where both date and year are required YYYY-MM-DD and YYYYxdate1=mw.ustring.match(date_string,'(%d%d%d%d)%.?');year=mw.ustring.match(year_string,'(%d%d%d%d)%.?');ifyear~=date1thenresult=0;-- years don't matchelseresult=2;-- years match; but because disambiguated, don't add to maint catendelseifmw.ustring.match(date_string,"%d%d%d%d?.-%d%d%d%d?%.?")then-- any of the standard range formats of date with two three- or four-digit yearsdate1,date2=mw.ustring.match(date_string,"(%d%d%d%d?).-(%d%d%d%d?)%.?");ifyear~=date1andyear~=date2thenresult=0;endelseifmw.ustring.match(date_string,"%d%d%d%d[%-–—]%d%d%.?")then-- YYYY-YY date rangeslocalcentury;date1,century,date2=mw.ustring.match(date_string,"((%d%d)%d%d)[%-–—]+(%d%d)%.?");date2=century..date2;-- convert YY to YYYYifyear~=date1andyear~=date2thenresult=0;endelseifmw.ustring.match(date_string,"%d%d%d%d?%.?")then-- any of the standard formats of date with one yeardate1=mw.ustring.match(date_string,"(%d%d%d%d?)%.?");ifyear~=date1thenresult=0;endelseresult=0;-- no recognizable year in dateendreturnresult;end--[[-------------------------< R E F O R M A T T A B L E S >------------------------------------------------These table are used exclusively for reformatting dates]]localsource_patterns={-- this table holds patterns that match allowed date formats used to extract date components['dmy']='(%d%d?)%.%s+(%a+)%s+(%d%d%d%d)%.?',['mdy']='(%a+)%s+(%d%d?),%s+(%d%d%d%d)',['ymd']='(%d%d%d%d)%-(%d%d)-(%d%d)',}localshort_formats={-- this table holds format strings used by os.date() for short month names['dmy']='%e %b %Y',['mdy']='%b %e, %Y',['ymd']='%F',}locallong_formats={-- this table holds format strings used by os.date() for long month names['dmy']='%e %B %Y',['mdy']='%B %e, %Y',['ymd']='%F',}--[[-------------------------< G E T _ D M Y _ D A T E _ P A R T S >------------------------------------------extracts year, month and day from DMY formatted date, places them in the source_date table, and returns.]]localfunctionget_dmy_date_parts(date,source_date)source_date.day,source_date.month,source_date.year=mw.ustring.match(date,source_patterns['dmy']);-- get date components as stringssource_date.month=get_month_number(source_date.month);-- get month numberend--[[-------------------------< G E T _ M D Y _ D A T E _ P A R T S >------------------------------------------extracts year, month and day from MDY formatted date, places them in the source_date table, and returns.]]localfunctionget_mdy_date_parts(date,source_date)source_date.month,source_date.day,source_date.year=date:match(source_patterns['mdy']);-- get date components as stringssource_date.month=get_month_number(source_date.month);-- get month numberend--[[-------------------------< G E T _ Y M D _ D A T E _ P A R T S >------------------------------------------extracts year, month and day from YMD formatted date, places them in the source_date table, and returns.]]localfunctionget_ymd_date_parts(date,source_date)source_date.year,source_date.month,source_date.day=mw.ustring.match(date,source_patterns['ymd']);-- get date components as stringsend--[[-------------------------< R E F O R M A T _ D A T E S >--------------------------------------------------Reformats existing dates into the format specified by format and short.format is one of several keywords: dmy, dmy-all, mdy, mdy-all, ymd, ymd-all. The all version includes access- andarchive-dates; otherwise these dates are not reformattedDate ranges, season dates, proper name dates are not currently supported.]]localfunctionreformat_dates(date_parameters_list,format,short)localall=false;-- set to false to skip access- and archive-dateslocalformat_str;localsource_date={};ifmw.ustring.match(format,'%a+%-all')thenformat=mw.ustring.match(format,'(%a+)%-all');-- extract the formatall=true;-- set to true to format access- and archive-datesendforparam_name,param_valinpairs(date_parameters_list)do-- for each date-holding parameter in the listifis_set(param_val)then-- if the parameter has a valueifnotallandin_array(param_name,{'acessodata','arquivodata'})then-- if access- or archive-date and format not xxx-allparam_val='';-- set to empty string so we don't process this dateendforsource,patterninpairs(source_patterns)doifmw.ustring.match(param_val,pattern)thenif'ymd'==sourcethenget_ymd_date_parts(param_val,source_date);-- get the date parts into the source_date tableelseif'dmy'==sourcethenget_dmy_date_parts(param_val,source_date);-- get the date parts into the source_date tableelseif'mdy'==sourcethenget_mdy_date_parts(param_val,source_date);-- get the date parts into the source_date tableendif'ymd'==formatand1582>tonumber(source_date.year)then-- ymd format dates not allowed before 1582returnfalse;-- abandon reformattingendifshortthenformat_str=short_formats[format];elseformat_str=long_formats[format];end-- convert date and save;date_parameters_list[param_name]=mw.text.trim(os.date(format_str,os.time(source_date)));-- strip leading space when single digit day and %e is first formatendendendendreturntrue;-- declare success and doneend--[[--------------------------< D A T E _ H Y P H E N _ T O _ D A S H >----------------------------------------Loops through the list of date-holding parameters and converts any hyphen to an ndash. Not called if the cs1|2template has any date errors.Modifies the date_parameters_list and returns true if hyphens are replaced, else returns false.]]localfunctiondate_hyphen_to_dash(date_parameters_list)localresult=false;localn;forparam_name,param_valinpairs(date_parameters_list)do-- for each date-holding parameter in the listifnotparam_val:match('%d%d%d%d%-%d%d%-%d%d')then-- for those that are not ymd datesparam_val,n=param_val:gsub('%-','–');-- replace any hyphen with ndashif0~=nthendate_parameters_list[param_name]=param_val;-- update the listresult=true;endendendreturnresult;-- so we know ifend--[[--------------------------< R E M O V E _ T R A I L I N G _ D O T >----------------------------------------Loops through the list of date-holding parameters and removes any trailing dot that may or may not be entered after year number.Generally speaking, date (alone) is incorrect without a traling dot but two dots or dot and right bracket are incorrect too.While references used to display with templates, it was not possible to allow correct "1. 1. 2016." but only "1. 1. 2016" (example)in order not to have date displayed as "(1. 1. 2016.)" but as correct "(1. 1. 2016)", or not as "1. 1. 2016.." but as "1. 1. 2016."Called even if the cs1|2 template has date error(s) because user might specify dot (to comply alone-date writing norm) or might not(because he knows it should/will not get displayed because ".)" or ".." is incorrect).Not called only if ISO date format as ISO date format does not have a trailing dot.Modifies the date_parameters_list and returns true if trailing dots are replaced, else returns false.]]localfunctionremove_trailing_dot(date_parameters_list)localresult=false;localn;forparam_name,param_valinpairs(date_parameters_list)do-- for each date-holding parameter in the listifnotparam_val:match('%d%d%d%d%-%d%d%-%d%d')then-- for those that are not ymd dates as ISO "2005-05-05." does not existparam_val,n=mw.ustring.gsub(param_val,'%.$','');-- replace any trailing dot with empty stringif0~=nthendate_parameters_list[param_name]=param_val;-- update the listresult=true;endendendreturnresult;-- so we know ifend--[[--------------------------< S E T _ S E L E C T E D _ M O D U L E S >--------------------------------------Sets local imported functions table to same (live or sandbox) as that used by the other modules.]]localfunctionset_selected_modules(utilities_page_ptr)is_set=utilities_page_ptr.is_set;-- import functions from select Module:Citation/CS1/Utilities modulein_array=utilities_page_ptr.in_array;-- import functions from select Module:Citation/CS1/Utilities moduleendreturn{-- return exported functionsdates=dates,year_date_check=year_date_check,reformat_dates=reformat_dates,date_hyphen_to_dash=date_hyphen_to_dash,remove_trailing_dot=remove_trailing_dot,set_selected_modules=set_selected_modules}