Modulo:Bozza: differenze tra le versioni

Contenuto cancellato Contenuto aggiunto
nome parametro più chiaro
codice riscritto e documentato
 
(8 versioni intermedie di uno stesso utente non sono mostrate)
Riga 1:
--[[
require('Modulo:No globals')
* Modulo che implementa il template Bozza.
*
* Legge i template Richiesta revisione bozza presenti nel wikitesto della pagina e
* determina quali argomenti passare al sottotemplate Bozza/avviso.
]]
 
require('strict')
 
local p = {}
local getArgs = require('Module:Arguments').getArgs
 
-- =============================================================================
-- Funzioni di utilità
-- =============================================================================
 
-- Verifica se una data stringa contiene categorie da disabilitare e in tal caso
-- restituisce la categoria di servizio pertinente in cui va inserita la pagina.
--
-- @param {string} str
-- @return {string}
local function checkForCategories(str)
for colonprefix
local catpattern = "[Cc][Aa][Tt][Ee][Gg][Oo][Rr][YyIi][Aa]?"
in str:gmatch('%[%[ *([Cc][Aa][Tt][Ee][Gg][Oo][Rr][YyIi][Aa]?) *: *[^%s][^\n]-%]%]')
 
do
for colonprefix in str:gmatch('%[%[ *(' .. catpattern .. ') *: *[^%s][^\n]-%]%]') do
local ns = mw.site.namespaces[colonprefix]
 
Line 14 ⟶ 29:
end
end
end
 
return ''
local function createRow(text1, text2)
return mw.html.create('div')
:addClass('bozza-history-row')
:tag('div')
:wikitext(text1)
:done()
:tag('div')
:wikitext(text2)
:done()
:done()
end
 
-- Restituisce un iteratore che consente di accedere agli elementi di una data
-- tabella in ordine decrescente delle sue chiavi.
-- Si assume che le chiavi della tabella siano valori timestamp.
--
-- @param {table} t
-- @return {function}
local function pairsByTimestamp(t)
local a = {}
Line 46 ⟶ 57:
return
else
return a[i], t[a[i]], i
end
end
Line 53 ⟶ 64:
end
 
-- Restituisce una data stringa dopo aver rimosso i commenti <!-- ... -->,
-- le porzioni di testo fra i tag nowiki e i template Categorie bozza.
--
-- @param {string} str
-- @return {string}
local function removeFalsePositives(str)
return str
:gsub('<!%-%-.-%-%->', '')
:gsub('<nowiki>.-</nowiki>', '')
:gsub('%f[%{]%{%f[^%{]', '\r')
:gsub('%{%{ *[Cc]ategorie *bozza *%|.-%}%}', '')
end
 
-- =============================================================================
local function replace(str, pattern, replace)
-- classe Submission
local i, j = str:find(pattern, 1, true)
-- =============================================================================
str = str:sub(0, i - 1) .. replace .. str:sub(j + 1)
return str
end
 
local Submission = {}
local function getSubmissions(stored_submissions, text)
local new_text = text
 
-- Costruttore della classe Submission.
for tmp in text:gmatch('%{(%b{})%}') do
--
local pattern = tmp
-- @param {string} wikitext Wikitesto del template Richiesta revisione bozza
stored_submissions, tmp = getSubmissions(stored_submissions, tmp)
-- @return {table} self
new_text = replace(new_text, pattern, tmp)
function Submission:new(wikitext)
local self = {}
setmetatable(self, { __index = Submission })
 
-- elenco degli attributi privati
if tmp:find('^%{ *[Rr]ichiesta *revisione *bozza *[%|%}]') then
self._formattedDate = nil
local submission = string.format('{%s}', tmp)
self._reviewer = nil
new_text = replace(new_text, submission, '')
self._status = nil
tmp = tmp:gsub('%{%b{}%}', '{{')
self._submitter = nil
submission = submission:gsub('\r', '{')
self._ts = nil
self._wikitext = wikitext
 
return self
local ts = tmp:match('%| *ts *= *(%d%d%d%d%d%d%d%d%d%d%d%d%d%d) *[%|%}]')
end
local key = tmp:find('%| *esito *= *[^%s%|%}]') and 'old' or 'current'
 
-- Espande il template Richiesta revisione bozza se la richiesta è stata già
if ts then
-- evasa e restituisce il testo espanso.
stored_submissions[key][ts] = stored_submissions[key][ts] or {}
--
table.insert(stored_submissions[key][ts], submission)
-- @param {boolean} showInfoButton Determina se mostrare il pulsante
end
-- 'Chiedi chiarimenti' accanto all'esito dell'ultima richiesta di revisione
-- @return {string}
function Submission:expand(showInfoButton)
if self:getStatus() == 'pending' then return '' end
local wikitext = self._wikitext:gsub('%}%}$', '|mostra esito=x}}')
if showInfoButton then
wikitext = wikitext:gsub('%}%}$', '|mostra pulsante=x}}')
end
return mw.getCurrentFrame():preprocess(wikitext)
end
 
-- Restituisce la data formattata della richiesta di revisione.
--
-- @return {string}
function Submission:getFormattedDate()
if self:getTimestamp() and not self._formattedDate then
local lang = mw.language.getContentLanguage()
local success, jFY = pcall(lang.formatDate, lang, 'j F Y', self:getTimestamp())
if success then
self._formattedDate = jFY
end
end
return self._formattedDate
end
 
-- Restituisce il nome dell'utente che ha pubblicato l'esito.
return stored_submissions, new_text
--
-- @return {string}
function Submission:getReviewer()
self._reviewer = self._reviewer or self:_parseArg('revisore', '.-') or
self:_parseArg('utente', '.-') -- temporaneo per rinomina parametro
return self._reviewer
end
 
-- Restituisce lo stato della richiesta di revisione (evasa o in sospeso).
function p.main(frame)
--
local current_title = mw.title.getCurrentTitle()
-- @return {string}
local ns = current_title.namespace
function Submission:getStatus()
local text = current_title:getContent()
self._status = self._status or
self._wikitext:find('%| *esito *= *[^%s%|%}]') and 'old' or 'pending'
return self._status
end
 
-- Restituisce il nome dell'utente che ha avanzato la richiesta di revisione.
if ns == 0 then
--
return '[[Categoria:Rimuovere template Bozza]]'
-- @return {string}
elseif not text then
function Submission:getSubmitter()
return
self._submitter = self._submitter or self:_parseArg('richiedente', '.-')
return self._submitter
end
 
-- Restituisce il timestamp della richiesta di revisione.
--
-- @return {string}
function Submission:getTimestamp()
self._ts = self._ts or self:_parseArg('ts', '%d%d%d%d%d%d%d%d%d%d%d%d%d%d')
return self._ts
end
 
-- Determina se la richiesta di revisione è valida.
--
-- @return {boolean}
function Submission:getValidity()
return self:getFormattedDate() and true or false
end
 
-- Parsifica un dato parametro del template Richiesta revisione bozza e
-- ne restituisce il valore.
--
-- @return {string}
function Submission:_parseArg(arg, subpattern)
local pattern = '%| *' .. arg .. ' *= *(' .. subpattern .. ') *[%|%}]'
return self._wikitext:match(pattern)
end
 
-- =============================================================================
-- classe SubmissionHistory
-- =============================================================================
 
local SubmissionHistory = {}
 
-- Costruttore della classe SubmissionHistory.
--
-- @param {table} submissions Array contenente tutte le richieste di revisione
-- della bozza già evase
-- @param {boolean} hideLastSubmission Determina se inserire anche l'esito dell'ultima
-- richiesta di revisione nel div compresso che contiene le richieste più vecchie
-- @param {boolean} showInfoButton Determina se mostrare il pulsante
-- 'Chiedi chiarimenti' accanto all'esito dell'ultima richiesta di revisione
-- @return {table} self
function SubmissionHistory:new(submissions, hideLastSubmission, showInfoButton)
local self = {}
setmetatable(self, { __index = SubmissionHistory })
 
-- elenco degli attributi privati
self._collapsedDiv = nil
self._header = nil
self._hideLastSubmission = hideLastSubmission
self._root = nil
self._showInfoButton = showInfoButton
self._submissionRows = {}
self._submissions = submissions
 
return self
end
 
-- Costruisce la cronologia di tutte le richieste di revisione della bozza già
-- evase e ne restituisce il codice HTML.
--
-- @return {string}
function SubmissionHistory:getHTML()
self
:_buildRoot()
:_buildHeader()
:_buildSubmissionRows()
:_buildCollapsedDiv()
:_appendChildNodes()
 
return tostring(self._root)
end
 
-- Appende tutti gli elementi della cronologia ai rispettivi elementi padre.
--
-- @return {table} self
function SubmissionHistory:_appendChildNodes()
if self._hideLastSubmission then
self._collapsedDiv:node(self._header)
else
self._root:node(self._header)
text = removeFalsePositives(text)
end
 
for i, row in ipairs(self._submissionRows) do
if i > (self._hideLastSubmission and 0 or 1) then
self._collapsedDiv:node(row)
else
self._root:node(row)
end
end
 
if self._collapsedDiv then
self._root:node(self._collapsedDiv)
end
 
return self
end
 
-- Crea l'elemento div che mostra le richieste di revisione più vecchie,
-- qualora ve ne siano. È compresso di default.
--
-- @return {table} self
function SubmissionHistory:_buildCollapsedDiv()
if #self._submissionRows >= (self._hideLastSubmission and 1 or 2) then
self._collapsedDiv = mw.html.create('div')
:addClass('nomobile mw-collapsible mw-collapsed')
:attr('data-expandtext', 'mostra richieste precedenti')
:attr('data-collapsetext', 'nascondi richieste precedenti')
end
return self
end
 
-- Crea l'elemento div che costituisce l'header della cronologia.
--
-- @return {table} self
function SubmissionHistory:_buildHeader()
self._header = mw.html.create('div')
:addClass('bozza-history-row nomobile bozza-history-header')
:tag('div')
:wikitext('Data richiesta')
:done()
:tag('div')
:wikitext('Esito revisione')
:done()
:done()
return self
end
 
-- Crea l'elemento div che costituisce la radice HTML della cronologia.
--
-- @return {table} self
function SubmissionHistory:_buildRoot()
self._root = mw.html.create('div'):addClass('bozza-history')
return self
end
 
-- Crea un elemento div per ciascuna richiesta di revisione da inserire
-- nella cronologia.
--
-- @return {table} self
function SubmissionHistory:_buildSubmissionRows()
for ts, submission, i in pairsByTimestamp(self._submissions) do
local row = mw.html.create('div')
:addClass('bozza-history-row')
:tag('div')
:wikitext(submission:getFormattedDate())
:done()
:tag('div')
:wikitext(submission:expand(i == 1 and self._showInfoButton))
:done()
:done()
table.insert(self._submissionRows, row)
end
return self
end
 
-- =============================================================================
-- Funzioni esportate
-- =============================================================================
 
local p = {}
 
-- Funzione per il template {{Bozza}}.
function p.main(frame)
local currentTitle = mw.title.getCurrentTitle()
local ns = currentTitle.namespace
local text = removeFalsePositives(currentTitle:getContent())
local args = getArgs(frame, { parentOnly = true })
local editedByReviewer = false
local lang = mw.language.getContentLanguage()
local revisionUser = frame:preprocess('{{REVISIONUSER}}')
local submissions = getSubmissions({ current = {}, old = {} }, text)
local submissions = { pending = {}, old = {} }
local edited_by_reviewer = false
 
-- cerca i template nel wikitesto della pagina dopo aver rimosso
if ns == 118 then
-- temporaneamente le graffe { singole che causano falsi positivi
for tmp in text:gsub('%f[%{]%{%f[^%{]', '\r'):gmatch('%{%b{}%}') do
-- scarta i template che non siano i template Richiesta revisione bozza
if tmp:find('^%{%{ *[Rr]ichiesta *revisione *bozza *[%|%}]') then
-- ripristina le graffe { singole nella porzione di testo trovata e
-- crea un oggetto Submission per ciascun template Richiesta revisione bozza
local submission = Submission:new(tmp:gsub('\r', '{'))
-- scarta l'oggetto Submission se la richiesta di revisione è mal compilata
if submission:getValidity() == true then
submissions[submission:getStatus()][submission:getTimestamp()] = submission
if submission:getStatus() == 'old' then
-- mantiene il conto delle richieste di revisione già evase nel
-- parametro 'numero richieste respinte' del sottotemplate Bozza/avviso
local k = 'numero richieste respinte'
args[k] = args[k] and args[k] + 1 or 1
-- verifica se l'ultima modifica della pagina è stata fatta
-- da uno dei revisori
if not editedByReviewer then
editedByReviewer = revisionUser == submission:getReviewer()
end
end
end
end
end
 
local pendingSubmission = select(2, next(submissions.pending))
 
-- conditional statement finalizzato a impostare lo stato (parametro
-- posizionale 1) del sottotemplate Bozza/avviso
if ns == 0 or ns == 118 then
if args.sposta then
args[1] = 'S'
elseif next(submissions.current)pendingSubmission then
args[1] = 'R'
-- se c'è una richiesta di revisione in sospeso, passa il suo timestamp e
-- il nome utente del richiedente al sottotemplate Bozza/avviso
if pendingSubmission:getSubmitter() then
args['ts ultima richiesta revisione'] = pendingSubmission:getTimestamp()
args['autore richiesta revisione'] = pendingSubmission:getSubmitter()
end
elseif args.proroga then
args[1] = 'A'
Line 125 ⟶ 374:
end
else
args[1] = langmw.language.getContentLanguage():ucfirst(args[1] or args.stato or '')
end
 
local hideLastSubmission = args[1] == 'S' or args[1] == 'R'
 
if next(submissions.old) then
-- determina se una bozza può essere sottoposta a revisione in base al
local i = 0
-- namespace in cui si trova la pagina e alla presenza di richieste inevase
local revision_user = frame:preprocess('{{REVISIONUSER}}')
local canBeSubmitted = ns == 118 and not hideLastSubmission
local header = createRow('Data richiesta', 'Esito revisione')
:addClass('nomobile bozza-history-header')
local history_table = mw.html.create('div')
:addClass('bozza-history')
local collapsed_submissions = mw.html.create('div')
:addClass('nomobile mw-collapsible mw-collapsed')
:attr('data-expandtext', 'mostra richieste precedenti')
:attr('data-collapsetext', 'nascondi richieste precedenti')
local hide_last_submission = args[1] == 'S' or args[1] == 'R'
 
-- crea un oggetto SubmissionHistory che contiene la cronologie delle
if hide_last_submission then
-- richieste di revisione della bozza già evase e passa il suo codice HTML
collapsed_submissions:node(header)
-- al sottotemplate Bozza/avviso
else
args['cronologia revisioni'] = SubmissionHistory
history_table:node(header)
:new(submissions.old, hideLastSubmission, canBeSubmitted)
end
:getHTML()
 
-- passa il timestamp dell'ultima richiesta evasa al sottotemplate Bozza/avviso
for ts, a in pairsByTimestamp(submissions.old) do
if canBeSubmitted then
local success, jFY = pcall(lang.formatDate, lang, 'j F Y', ts)
local lastSubmission
 
for _, submission in pairsByTimestamp(submissions.old) do
if success then
forlastSubmission _,= submission in ipairs(a) do
local reviewerbreak
if not edited_by_reviewer then
reviewer = submission:match('%| *utente *= *(.-) *[%|%}]')
edited_by_reviewer = revision_user == reviewer
end
local root = history_table
i = i + 1
submission = submission:gsub('%}%}$', '|mostra esito=x}}')
if i == (hide_last_submission and 1 or 2) then
history_table:node(collapsed_submissions)
end
if i > (hide_last_submission and 0 or 1) then
root = collapsed_submissions
end
if i == 1 and not hide_last_submission then
args['ts ultima revisione'] = ts
submission = submission:gsub('%}%}$', '|mostra pulsante=x}}')
end
root:node(createRow(jFY, frame:preprocess(submission)))
end
end
args['ts ultima revisione'] = lastSubmission:getTimestamp()
end
 
args['numero richieste respinte'] = i
args['cronologia revisioni'] = tostring(history_table)
end
 
-- controlla la visibilità del pulsante 'Richiedi revisione' che
if edited_by_reviewer or args[1] == 'R' or args[1] == 'S' then
-- viene creato dal sottotemplate Bozza/avviso
if ns ~= 118 or editedByReviewer or hideLastSubmission then
args['mostra pulsante'] = 'no'
else