Esta página está protegida contra el movimiento.
Esta pagina esta protegida

Forma: Cita

De Wikipedia, la enciclopedia libre.
Saltar a navegación Saltar a búsqueda

Módulo de Lua para la reproducción de las funciones de las distintas plantillas {{ libro Cita }}, {{ Cita web }}, {{ Cita noticia }}, {{ publicación Cita }}, {{ conferencia Cita }} y {{ Cita de vídeo }}.

Las siguientes son las notas técnicas sobre cómo funciona el módulo. Para obtener instrucciones sobre cómo usarlo para insertar citas en las entradas de ver el {{ Cite texto }} manual.

Submódulos

  • Módulo: Cotización / Configuración - Contiene tablas de configuración con los nombres de los parámetros, mensajes de error, caracteres de separación ...
  • Módulo: Cita / Lista Blanca - Contiene las tablas de parámetros aceptados por el módulo con el fin de identificar los parámetros con un nombre incorrecto.
  • Módulo: Cita / Sugerencias - Contiene una tabla en la que es posible introducir los nombres de parámetros que son a menudo mal y sugerir el nombre correcto del parámetro en el mensaje de error.
  • Forma: Cita / Temas - Se utiliza para generar forma: Cotización / Lista blanca y se utiliza en una base de una sola vez.

funciones accesorias

En lo que sigue por el conjunto nos referimos a una variable distinta de la cadena nula y nula

is_set (var)
cierto si se establece una variable
primer set (...)
devuelve el primer conjunto de variables
InArray (aguja, pajar)
escanea el array pajar y devuelve la posición del valor de la aguja. Si no se encuentra la aguja en el pajar o es nula devuelve falso
sustituto (msg, args)
devuelve la cadena msg compilado usando la tabla de valores args. Sobre la base de la mw.message.newRawMessage función, no mucho documentado, por lo visto en la cadena de la $ n se sustituyen por el valor en la posición enésima en args. Si args es nula devuelve nil
envoltura (clave, str, bajar)
formatear el mensaje clave con la cadena str. clave debe ser un índice de la tabla citation_config.messages. Si menor es cierto que el mensaje se pone en minúsculas antes de la inserción str
debug_msg (msg)
coloca un mensaje de depuración en la cola de mensajes de error que se mostrará en la pantalla
debug_value (nombre, valor)
inserta el nombre mensaje de depuración = valor. Se utiliza para la salida el valor de una variable, para ser utilizado por ejemplo como debug_value ( 'nombre', nombre)
argument_wrapper (args)
devuelve una tabla para acceder a los valores de la tabla original, args utilizando una tabla de alias. Instrucción dada A=argument_wrapper(args) llamando A[key] el valor args[first_set(citation_config.aliases[key])] . Esto permite la localización de los parámetros y la creación de alias para el mismo valor. Por ejemplo, si citation_config.aliases['Chapter'] = {'capitolo', 'contributo', 'voce', 'articolo', 'sezione' } la llamada A['Chapter'] devuelve uno de los valores ajustados entre args['capitolo'] , args['contributo'] , args['voce'] , args['articolo'] , args['sezione'] . También agrega el A: origen Método que devuelve el alias en las que se encontró un valor. Los valores encontrados se almacenan en una tabla interna.
Agrega un mensaje a la cola de errores si:
  • clave no está presente en citation_config.aliases
  • clave es una tabla de valores y más de uno de ellos es conjunto
  • si no hay valor que corresponde a uno de los alias clave se encuentra en args, devuelve una cadena vacía ""
Validar (nombre)
vuelve true si el nombre no es nulo y es el nombre de un parámetro aceptado, false de lo contrario
errorcomment (contenido, oculto)
formatear el comentario comentario para su visualización, si oculta es true que se insertará el código pero no es visible, excepto para analizar el código HTML de la página, de lo contrario será formateado de acuerdo con el ajuste del "error" y las clases de "citación-comment" en el css (normalmente un escrito en rojo)
setError (ERROR_ID, argumentos, crudo, prefijo, sufijo)
formatear el comentario con código ERROR_ID con la tabla de argumentos de argumentos. Si prefijo y el sufijo se establecen, se añaden respectivamente antes y después del mensaje. Si prima es true el mensaje se devuelve sin ser aprobada por errorcomment primero.
la clave ERROR_ID se refiere a la tabla de mensajes citation_config.error_conditions que para cada código de error devuelve el mensaje a ser formateado, la categoría de error en la que insertar la entrada y si el mensaje debe ser visible u oculta.

Fragmento

Para administrar la unión de las piezas de citación, un "objeto" Lua se define (en realidad una mesa con un metatabla que define algunos métodos adicionales). Un fragmento se compone de una matriz cuyo primer elemento es una cadena para ser insertado en el comienzo de la secuencia, seguido de una o más cadenas y terminado por una cadena para ser insertado en el extremo de la secuencia. Cuando dos fragmentos F1 y se unen f2 (ver fragment.append y fragment.appends) la prioridad del último separador de f1 y la de la primera de f2 es evaluado y sólo el uno con una prioridad más alta se mantiene. El nuevo fragmento tendrá el separador inicial de f1 y el último de f2.

Fragment.new (texto, sep_key)
crea un pseudo-objeto Lua que almacena la cadena de texto matriz mediante sep_key como separador entre una cadena y la otra. Establecer como separador inicial de la secuencia de la cadena nula y como el sep_key separador final. Devuelve el objeto creado.
Sep_key debe ser una clave de la tabla Fragment.priority que por cada separador indica su prioridad (de modo que prevalece de separación cuando se unen dos fragmentos) y lo que para insertar exactamente (por ejemplo, para "" En realidad, insertos "" - es decir, se añade el espacio). La tabla se carga desde el módulo de configuración, un ejemplo es:
[""] = { order=0, sep = ""},
[" "] = { order=1, sep = " "},
[","] = { order=2, sep = ", "},
["."] = { order=3, sep = ". "},
["in"] = {order=4, sep = " in "},
[" "] = { order=5, sep = " "}, un espacio sencillo que, sin embargo, prevalece sobre otros separadores
["nothing"] = {order=6, sep="" } cadena nula que prevalece sobre todo (para obligar a ningún separador al comienzo de la cita)
Fragmento: inicio (sep_key)
conjunto sep_key como separador inicial
Fragmento: pasado (sep_key)
conjunto sep_key como separador final
Fragmento: empy (sep_key)
devuelve true si el fragmento es un fragmento de vacío (contiene una matriz cadena vacía)
Fragmento: append (TXR)
cuelga el fragmento o strigna TXR al fondo del fragmento (si TXR es una cadena que lo transforma en fragmento con sep_key igual a la del fragmento de los que es colgado)
Fragmento: APPENDs (TXR)
anexa una matriz mixta de fragmentos / cuerdas

 - módulo de gestión de citas, importada originalmente de
- revisión 555909894 de 20/5/2013 de [[: en: Módulo: Cita / CS1]]

- [[============================================ === =============================
Variable donde las condiciones de error registrados durante la ejecución se almacenan
de las funciones del módulo.
================================================ ============================]]
= z locales {
error_categories = {}; - lista de categorías de errores
error_ids = {}; - lista de códigos de error
message_tail = {}; - los mensajes de error que se muestran en la parte final de la cita
}

- [[============================================ === =============================
Cargar la tabla de configuración, corrigiendo el nombre si está cargado de caja de arena
- Nota: aún no está activo por alguna razón no funciona
================================================ ============================]]
load_configuration_table función local (nombre)
marco local = mw. getCurrentFrame ()
real_name locales = nombre
si nil ~ = string.find (frame: getTitle (), 'caja de arena', 1, true) entonces   
real_name = real_name .. '/ caja de arena'
fin
volver mw . loadData (real_name)
fin

- [[============================================ === =============================
Cargar las tablas de configuración del módulo.
================================================ ============================]]
cfg local = mw . loadData ( 'Módulo: Cotización / Configuración')
--local cfg = load_configuration_table ( 'Módulo: Cita / Configuración')

- [[============================================ === =============================
Lista de todos los parámetros reconocidos.
================================================ ============================]]
lista blanca local = mw. loadData ( 'Módulo: Cita / lista blanca')
--local lista blanca = load_configuration_table ( 'Módulo: Cita / lista blanca')

- [[============================================ === =============================
Devuelve true si se ha establecido una variable (diferentes de cero y la cadena vacía)
================================================ ============================]]
is_set función local (var)
No devolver (var == nula o var == '');
fin

- Volver nuestro {{}} un enlace roto
interrupted_url función local ()
volver mw . getCurrentFrame (): expandTemplate {title = 'Enlace roto'}
fin

- [[============================================ === =============================
Devuelve el primer conjunto variable de los pasa a la función
================================================ ============================]]
first_set función local (...)
lista local = {...};
para _, var en pares (lista) hacer
si is_set (var) entonces
var regresar;
fin
fin
fin

- [[============================================ === =============================
Devuelve la posición de la aguja en el pajar lista, de lo contrario devuelve false
================================================ ============================]]
función local in_array (aguja, pajar)
si la aguja == nil luego regresar false; fin
para n, v en ipairs (pajar) hacer
si la aguja v == luego regresar n; fin
fin
devolver falso ;
fin

- [[============================================ === =============================
Complete los argumentos enumerados en la cadena msg utilizando la tabla de argumento args
================================================ ============================]]
sustituto función local (msg, args)
args y volver MW. mensaje . newRawMessage (msg, args): llana () o msg;
fin

- [[============================================ === =============================
Hacer la caja fuerte cadena para marcado en cursiva '' ... ''
Nota: No se puede utilizar <i> cursiva ya que este es el comportamiento esperado de ser así
específica para los títulos es hacerlos no cursiva. También <i> y '' interactúan
mal con la función ordenada HTML de Mediawiki
================================================ ============================]]
función local safe_for_italics ( str )
si no is_set (str), entonces
return str ;
demás
si str : sub ( 1 , 1 ) == "'" entonces str = "<span> </span>" .. str ; fin
si str : sub ( - 1 , - 1 ) == "'" entonces str = str .. "<span> </span>" ; fin

- Elimina los saltos de línea porque se rompen cursiva.
str regresar: gsub ( '\ n', '');
fin
fin

- [[============================================ === =============================
Devuelve verdadero / falso dependiendo de si la cadena es única América
================================================ ============================]]
is_latin función local (str)
retorno require ( 'Forma: IsLatin'). _IsLatin ({str})
fin

- [[============================================ === =============================
Devuelve un mensaje de la mesa cfg.messages en la que se inserta una cadena
- clave: código de mensaje que se mostrará en cfg.messages
- str: una cadena para insertar en el mensaje, si no se define o igual a cuerda
vaciar la función devuelve una cadena vacía
================================================ ============================]]
función local envoltura (clave, str)
si no is_set (str), entonces
volver "";
elseif in_array (clave, { 'cursiva-título', 'trans-cursiva título'}) a continuación,
str = safe_for_italics (str);
fin
sustituto de retorno (CFG mensajes [clave], {} str.);
fin

- [[============================================ === =============================
Inserta un mensaje de depuración que se mostrará al final de la cita
================================================ ============================]]
debug_msg función local (msg)
table.insert (. z message_tail, {set_error ( 'debug_txt', {msg}, true)});
fin

- [[============================================ === =============================
Para propósitos de depuración, se añade la cadena 'name = <valor>' al final de la cita
================================================ ============================]]
función local debug_value (nombre, valor)
si no el valor entonces valor = extremo 'nil'
debug_msg (nombre .. '= "' .. .. valor '"')
fin

- [[============================================ === =============================
Formatear un comentario para identificar los errores mediante la adición de la clase CSS para
que sea visible o no
================================================ ============================]]
error_comment función local (contenido, oculto)
envoltura de retorno (oculto y '-error oculto' o 'visible-error', contenido);
fin

- [[============================================ === =============================
Establecer una condición de error y devolver un mensaje apropiado. la inserción
del mensaje en la salida es la responsabilidad de la función de llamar
- - ERROR_ID: código de error (una clave válida para cfg.error_conditions)
- - argumentos: una lista de argumentos opcionales para formatear el mensaje
- - en bruto: devuelve un par: {mensaje de error, la visibilidad} en lugar del mensaje
- Error de formato
- - prefijo: cadena a añadir a la cabecera del mensaje
- - sufijo: cadena para añadir al final del mensaje
================================================ ============================]]
set_error función local (ERROR_ID, argumentos, crudo, prefijo, sufijo)
ERROR_STATE local = cfg. error_conditions [ERROR_ID];

prefix = prefijo o "";
sufijo = sufijo o "";

Si ERROR_STATE == nil then
error (cfg mensajes [ 'undefined_error'].);
elseif is_set (ERROR_STATE. categoría) entonces
table.insert (.. z error_categories, ERROR_STATE categoría);
fin

de mensajes local = sustituto (. ERROR_STATE de mensajes, argumentos);

mensaje = mw. ustring . formato (
'% S ([[% s% s # |% s]])',
mensaje, CFG. Mensajes [ 'ayuda de enlace de página'], ERROR_STATE. ancla,
cfg. mensajes de ayuda [ ''] de etiquetas página
)

z. error_ids [ERROR_ID] = true;
Si in_array (ERROR_ID, { 'bare_url_missing_title', 'trans_missing_title'})
y z. error_ids [ 'citation_missing_title'] entonces
volver '', falsa;
fin

mensaje = table.concat ({prefijo, mensaje, sufijo});
si prima == true entonces el mensaje de retorno, ERROR_STATE. extremo oculto
error_comment retorno (mensaje, ERROR_STATE oculta.);
fin

- [[============================================ === =============================
Busque el primer conjunto de parámetros de una lista de parámetros y generar un error si
más de un parámetro está establecido.
Devuelve el par (valor, seleccionado) donde el valor es el valor del parámetro encontró y
seleccionado el nombre del parámetro encontrado
================================================ ============================]]
local de la función select_one (args, posible, error_condition, index)
valor local = nil;
local seleccionada = '';
error_list local = {};

si el índice ~ = nil entonces index = toString (index); fin

- Manejar caso especial de "#" sustituida por cadena vacía
si el índice == '1', entonces
para _, v en ipairs (posible) hacer
v = v: gsub ( "#", "");
si is_set (args [v]), entonces
si el valor ~ = nil y seleccionado ~ = v entonces
table.insert (error_list, envoltura ( 'parámetro', v));
demás
valor = args [V];
seleccionado = v;
fin
fin
fin
fin

para _, v en ipairs (posible) hacer
si el índice ~ = nil entonces
v = v: gsub ( "#", index);
fin
si is_set (args [v]), entonces
si el valor ~ = nil y seleccionado ~ = v entonces
table.insert (error_list, envoltura ( 'parámetro', v));
demás
valor = args [V];
seleccionado = v;
fin
fin
fin

si # error_list > 0 entonces
- genera el mensaje de error concatenando los parámetros duplicados
error_str local = "";
si # error_list == 1 entonces
error_str = error_list [1] .. cfg. Mensajes de [ 'parámetro de par-separador'];
demás
error_str = table.concat (error_list, cfg. messages [ 'parámetro-separador']) .. cfg. Mensajes de [ 'parámetro de final-de separación'];
fin
error_str = error_str .. envoltura ( 'parámetro', seleccionado);
table.insert (. z message_tail, {set_error (error_condition, {error_str}, true)});
fin
valor de retorno, seleccionado;
fin

- [[============================================ === =============================
Apoyo a la función de configuración de asignación argumento de archivo,
para que varios nombres se pueden asignar a una sola variable interna
================================================ ============================]]
argument_wrapper función local (args)
origen local = {};

volver setmetatable ({
ORIGEN = función (self, k)
maniquí local = auto [k]; --force la variable a ser cargado.
origen [k] retorno;
fin
},
{
__index = function (TBL, k)
si el origen [k] ~ = nil entonces
nil regresar;
fin

args locales, lista, v = args, CFG. alias [k];

si el tipo (lista) == 'mesa', entonces
v, origen [k] = select_one (args, lista, 'redundant_parameters');
si el origen [k] == nil entonces
origen [k] = ''; - Cadena vacía, por no decir nulas
fin
Lista elseif ~ = nil entonces
v, origen [k] = args [list], lista;
demás
- tal vez dejar pasar en lugar de elevar un error?
- v, origen [k] = args [k], k;
error (cfg mensajes [ 'unknown_argument_map'].);
fin

- Las cadenas vacías, por no decir nulas;
si v == nil then
v = cfg. valores predeterminados [k] o '';
origen [k] = '';
fin

TBL = rawset (TBL, k, v);
v regresar;
terminar,
});
fin

- [[============================================ === =============================
Compruebe que un nombre de parámetro es válido el uso de la lista blanca
================================================ ============================]]
Validar función local (nombre)
name = toString (nombre);
- argumentos normales
si la lista blanca. basic_arguments [nombre] luego regresar verdadero fin
- Los argumentos con números en ellas
name = nombre: gsub ( "% d +", "#");
si la lista blanca. numbered_arguments [nombre] luego regresar verdadero fin
- No es encontrado, el argumento no es compatible.
devolver falso
fin

- [[============================================ === =============================
Objeto para almacenar los elementos de una cotización. Una cita fragmento se
que consta de los siguientes elementos:
- auto [n]: n-ésimo elemento de unirse, es una lista de cadenas intercalados con
separadores a utilizar para unirse a ellos.
- self.last_priority: prioridad separador de cierre
- self.first_priority: Prioridad de apertura del separador
- self.sep_key: código de carácter separador predeterminado de uso
cuando se combina con otro fragmento
================================================ ============================]]
Fragmento locales = {}

Fragmento. precedencia = cfg. estilo. separator_priority
locales Fragment_mt = {} __index = Fragmento

Fragmento. nueva = function (textos, sep_key)
si el tipo (textos) == "cadena", entonces los textos = {} textos finales
si no se Fragmento. precedencia [sep_key] Y = sep_key "" fin
tx locales = {}
tx. last_priority = 0
tx. first_priority = 0
tx. sep_key = sep_key
tx [1] = ""
_ para, en el ipairs (textos) hacer
si el ~ = "", entonces
tx [# tx + 1] = el
tx [# tx + 1] = Fragmento. precedencia [tx. sep_key]. sep
fin
fin
si # tx> 1, entonces
tx. last_priority = Fragmento. precedencia [tx. sep_key]. pedido
demás
tx [1] = ""
fin
setmetatable (tx, Fragment_mt)
volver TX
fin

--- cambiar el separador que lleva un fragmento de cotización
Fragmento función: inicio (sep_key)
si # auto == 0, entonces el retorno final de auto
separador local = Fragmento. precedencia [sep_key] o fragmento. precedencia [ ""]
auto [1] = separador. sep
yo . first_priority = separador. pedido
de retorno automático
fin

- cambiar el separador final de un fragmento de cotización
Fragmento función: pasado (sep_key)
si # auto == 0, entonces el retorno final de auto
separador local = Fragmento. precedencia [sep_key] o fragmento. precedencia [ ""]
auto [# auto] = separador. sep
yo . last_priority = separador. pedido
de retorno automático
fin

- devuelve un fragmento de cotización vacía
función Fragmento: vacío ()
volver # auto == 0
fin

- colgar una cadena o una cita fragmento al final
función Fragmento: append (TXR)
Si TXR == nil entonces retorno auto finales
si el tipo (TXR) == "string" entonces TXR = Fragmento. nueva (TXR, sí. sep_key) final
si # TXR == 0 luego regresar extremo auto
si # auto == 0 auto luego [1] = TXR [1] final
yo . last_priority = Auto. last_priority o 0
si yo . last_priority <TXR. first_priority entonces
auto [# auto] = TXR [1]
fin
para i, EL en ipairs (TXR) hacer
si i> 1 entonces auto [# auto + 1] = el fin
fin
yo . last_priority = TXR. last_priority
--self.sep_key = txr.sep_key
de retorno automático
fin

- colgar una lista de cadenas de cotización o fragmentos
función Fragmento: anexa (fragmentos)
para _, f en ipairs (fragmentos) hacer
auto: append (f)
fin
de retorno automático
fin

- colapsa el fragmento en una cadena y lo devuelve
Fragment_mt. __toString = function (tx)
table.concat retorno (tx, '')
fin
- ============================================== ===================
- Fin de la definición de objeto Fragmento
- ============================================== ===================

- [[============================================ === =============================
Formatear una EnlaceWiki interna o enlace externo a un documento
- options.code_id: código para el enlace externo
- options.id: etiqueta de enlace externo o documento de identidad
- options.encode: si es verdadero o nulo de la URL se codifica (en: Porcentaje-codificación)
- options.link: enlace a la entrada wiki en el código del documento
- options.label: etiqueta del enlace a la entrada wiki en el código del documento
- options.separator: separador entre el código y el enlace (por defecto un espacio de no separación)
- options.pattern: Modelo enlace donde "$ 1" es el identificador normal y "$ 2" el id de la URL externa
================================================ ============================]]
link_id función local (opciones)
URL_STRING local = opciones. code_id u opciones. Identificación;
si las opciones. codificar == true o las opciones. codificar == nil entonces
URL_STRING = mw. uri . encode (URL_STRING);
fin
para w en mw. ustring . GMATCH (opciones. patrón, '$ 1') hacer
Opciones. patrón = mw . ustring . gsub (opciones de patrón, '^ (% [[^% []% S +) $ 1 (.-%])', '% 1 $ 2% 2'.);
Opciones. patrón = mw . ustring . gsub (opciones de patrón, '([^% []% [[^% []% S +) $ 1 (.-%])', '% 1 $ 2% 2'.);
fin
volver mw . ustring . Formato ( '[[% s |% s]]% s% s',
Opciones. vincular, opciones. etiquetar, opciones. separador o "& nbsp;" ,
sustituto (opciones. patrón, {mw. texto. nowiki (opciones. id), URL_STRING})
);
fin

- [[============================================ === =============================
Determina si una URL es correcta. Por el momento, sólo se comprueba la cadena comenzando con
URI prefijo que es válido y no contiene espacios
Controles más estrictos (véase complemento en.wiki): TODO
================================================ ============================]]
check_url función local (URL_STR)
- si contiene espacios no puede ser una dirección URL correcta
cuando fuera nulo == URL_STR: partido ( "^% $ S +") a continuación,
devolver falso ;
fin
- relativas al protocolo o esquema de URL
volver URL_STR: sub (1, 2) == "//" o URL_STR: partido ( "^ [^ /] *:") ~ = nil;
fin

- [[============================================ === =============================
Hacer una caja fuerte cadena que se utiliza como una descripción url
================================================ ============================]]
safe_for_url función local (str)
si str: partido ( "% [% [.-%]%]") ~ = nil entonces
table.insert (. z message_tail, {set_error ( 'wikilink_in_url', {}, true)});
fin

retorno str: gsub ( '[% [%] \ n]', {
[ '['] = '& # 91;' ,
[ ']'] = '& # 93;' ,
[ '\ N'] = ''});
fin

- [[============================================ === =============================
Formatear un enlace externo con la comprobación de errores
- URL: url del enlace externo
- etiqueta: etiqueta del enlace externo (si no insertada se usa
URL como etiqueta y de error mostrados)
- fuente: parámetro en el que está contenido el url
================================================ ============================]]
external_link función local (URL, etiqueta, fuente)
error_str local = "";
si no is_set (etiqueta) entonces
label = URL;
si is_set (fuente), entonces
error_str = set_error ( 'bare_url_missing_title', {envoltura ( 'parámetro', fuente)}, falso, "");
demás
error (cfg mensajes [ "bare_url_no_origin"].);
fin
fin
si no check_url (URL) a continuación,
error_str = set_error ( 'bad_url', {}, falsa, "") .. error_str;
fin
retorno table.concat ({ "[", URL, "", safe_for_url (etiqueta), "]", error_str});
fin

- [[============================================ === =============================
Añadido múltiples enlaces, por ahora sólo se utiliza por el módulo de enlaces externos
================================================ ============================]]
append_links función locales (valor, enlaces)
si el tipo (enlaces) == 'mesa', entonces
para _, t en ipairs (links) hacer
t [2] = is_latin (t [2]) y envoltura ( 'cursiva-título', t [2]) o t [2]
value = valor .. '/' .. external_link (t [1], t [2])
fin
fin
valor de retorno
fin

- [[============================================ === =============================
Formatear un DOI y comprobar si hay errores
================================================ ============================]]
función local doi (id, inactivo)
local del gato = ""
controlador local = cfg. id_handlers [ 'DOI'];

de texto local;
si is_set (inactivo) entonces
inactive_year local = inactivo: partido ( "% d% d% d% d") o ''
--text = "[[" .. .. handler.link "|" .. .. handler.label "]]:" .. Identificación;
si is_set (inactive_year) entonces
table.insert (z. error_categories, "Páginas con DOI inactivo desde" .. inactive_year);
demás
table.insert (. z error_categories "páginas con DOI inactivo"); - cuando inactivas no contiene un año reconocible
fin
inactivos = "(" .. cfg. messages [ 'inactivo'] .. "" .. inactivo .. ")"
fin
text = link_id ({link = manejador. enlace, label = manejador. etiqueta,
patrón = manejador. patrón, ID = id, separador = manejador. separador, codificar = manejador. codificar}) .. (inactivo o '')
cuando fuera nulo == id:. partido ( "^ 10% [^% s -] - / [^% s -] - [. ^%,] $"), entonces - doi debe comenzar con '10', debe contener una barra fwd, no debe contener espacios o endashes, y no debe terminar con punto o una coma
cat = set_error ( 'bad_doi');
fin
texto volver .. gato
fin

- [[============================================ === =============================
Formatear un enlace a la biblioteca abierta y comprobar si hay errores
================================================ ============================]]
open_library función local (id)
código local = id: sub (- 1, - 1)
controlador local = cfg. id_handlers [ 'OL'];
si (== código "A"), entonces
retorno link_id ({link = manejador. enlace, label = manejador. etiqueta,
pattern = "[[OpenLibrary: autores / OL $ 1 | $ 1]]", id = ID, separador = manejador. separador,
encode = manejador. codificar})
elseif (código == "M") entonces
retorno link_id ({link = manejador. enlace, label = manejador. etiqueta,
pattern = "[[OpenLibrary: Libros / OL $ 1 | $ 1]]", id = ID, separador = manejador. separador,
encode = manejador. codificar})
elseif (código == "W"), entonces
retorno link_id ({link = manejador. enlace, label = manejador. etiqueta,
pattern = "[[OpenLibrary: obras / OL $ 1 | $ 1]]", id = ID, separador = manejador. separador,
encode = manejador. codificar})
demás
retorno link_id ({link = manejador. enlace, label = manejador. etiqueta,
pattern = "[[OpenLibrary: OL $ 1 | $ 1]]", id = ID, separador = manejador. separador,
encode = manejador. codificar}) ..
'' .. set_error ( 'bad_ol');
fin
fin

- [[============================================ === =============================
Formatear un enlace a la biblioteca Opac usando SBN y comprobar si hay errores
================================================ ============================]]
SBN función local (id)
controlador local = cfg. id_handlers [ 'SBN']
start_match locales, end_match, CD1, CD2 = string.find (id, '^ TI \\ \\ UCIC (...) \\ (% d +)')
si no (CD1 y CD2), entonces
start_match, end_match, CD1, CD2 = string.find (id, '^ IT \\ UCIC \\ (....) \\ (% d +)')
fin
Si CD1 y CD2 entonces
retorno link_id ({link = manejador. enlace, label = manejador. etiqueta,
pattern = '[http://opac.sbn.it/bid/$1 $ 1]', id = ID, code_id = CD1 CD2 ..,
encode = manejador. codificar})
demás
retorno link_id ({link = manejador. enlace, label = manejador. etiqueta,
pattern = '[http://opac.sbn.it/bid/$1 $ 1]', id = ID,
encode = manejador. codificar}) .. '' .. set_error ( 'bad_sbn')
fin
fin

- [[============================================ === =============================
Opaco agradable Identifiern utilizado en los formatos Arca vierten clé générer une
adaptado de fr: Módulo: Biblio / Referencias
================================================ ============================]]
ark_id función local (base)
base = toString (base)
si la base entonces
xdigits locales = '0123456789bcdfghjkmnpqrstvwxz'
suma local = 0 
la posición local
para i = 1, la base de: len () hacer
posición = xdigits: find (base: sub (i, i), 1, true) o 1
suma = suma + i * (posición - 1)
fin
 índice local = suma% 29 + 1
xdigits de retorno: sub (índice, índice)
fin
fin

- [[============================================ === =============================
Formatear un enlace a la Biblioteca Nacional de Francia y comprobar si hay errores
adaptado de fr: Módulo: Biblio / Referencias
================================================ ============================]]
bnf función local (id)
controlador local = cfg. id_handlers [ 'BNF']
si id entonces
txt locales = id
error_code local = ''
bnf_id local = id: superior (): partido ( 'BNF (% d +% w)') o id: inferior (): partido ( 'cb (% d +% w)') o id: partido ( '^% d +% w ')
		
Si a continuación, bnf_id
- BnF contient une conjunto de chiffres qui peut être ONU arca válida
base local = bnf_id: sub (1, 8)
si bnf_id: len () == 8 entonces 
- il manque La Clé, en Ajoute
id = base de .. ark_id ( 'cb' .. base)
txt = base
elseif bnf_id: len ()> 8 y bnf_id: sub (9, 9) == ark_id ( 'cb' .. base) entonces
- Arca válida
id = bnf_id: sub (1, 9)
txt = base
demás
ARK - aquí no válida semble
id = bnf_id
txt = bnf_id
error_code = set_error ( 'bad_bnf')
fin
demás
- la validez ne pas paramètre semble ONU arca
error_code = set_error ( 'bad_bnf')
fin
		
- dans tous les cas de l'renvoie Aresse, en catégorise Juste pour vérifier ce qui ne va pas
volver link_id ({
link = manejador. enlace,
label = manejador. etiqueta,
patrón = manejador. patrón,
id = txt,
code_id = bnf_id,
separator = manejador. separador
}) .. '' .. código_error
fin
fin

- [[============================================ === =============================
Elimina el texto irrelevante y guiones de un número ISBN
================================================ ============================]]
clean_isbn función local (isbn_str)
return isbn_str : gsub ( "[^-0-9X]" , "" );
end

--[[ ===============================================================================
Determina se una stringa ISBN è valida
 ===============================================================================]]
local function check_isbn ( isbn_str )
isbn_str = clean_isbn ( isbn_str ): gsub ( "-" , "" );

local len = isbn_str : len ();

if len ~= 10 and len ~= 13 then
return false ;
end
local temp = 0 ;
if len == 10 then
if isbn_str : match ( "^%d*X?$" ) == nil then return false ; end
isbn_str = { isbn_str : byte ( 1 , len ) };
for i , v in ipairs ( isbn_str ) do
if v == string.byte ( "X" ) then
temp = temp + 10 * ( 11 - i );
else
temp = temp + tonumber ( string.char ( v ) ) * ( 11 - i );
end
end
return temp % 11 == 0 ;
else
if isbn_str : match ( "^%d*$" ) == nil then return false ; end
isbn_str = { isbn_str : byte ( 1 , len ) };
for i , v in ipairs ( isbn_str ) do
temp = temp + ( 3 - 2 * ( i % 2 )) * tonumber ( string.char ( v ) );
end
return temp % 10 == 0 ;
end
end

--[[ ===============================================================================
Ritorna la sola etichetta visibile di un wikilink
 ===============================================================================]]
local function remove_wikilink ( str )
-- Sia [[A|B]] che [[B]] ritornano B
return ( str : gsub ( "%[%[([^%[%]]*)%]%]" , function ( l )
return l : gsub ( "^[^|]*|(.*)$" , "%1" ): gsub ( "^%s*(.-)%s*$" , "%1" );
end ));
end

--[[ ===============================================================================
Riconosce le date nel formato ISO yyyy-mm-dd e le riformatta in dmy. Si assicura
che 01 e 1 siano resi come 1º qualora indichino il giorno.
 ===============================================================================]]
local function get_date ( str )
if is_set ( str ) then
local try_year , try_month , try_day = string.match ( str , '^(%d%d%d%d)-(%d%d)-(%d%d)$' )
if try_day then
local Month = cfg . months [ tonumber ( try_month )]
if Month then
try_day = try_day == '01' and '1º' or tonumber ( try_day )
return string.format ( "%s %s %s" , try_day , Month , try_year )
end
end
try_day , try_month , try_year = string.match ( str , '^(%d%d?) (%a+) (%d%d%d%d)$' )
if try_day then
try_day = ( try_day == '1' or try_day == '01' ) and '1º' or tonumber ( try_day )
return string.format ( "%s %s %s" , try_day , try_month , try_year )
end
end
return str
end

--[[ ===============================================================================
Unisce year, day e month ritornando la data come un'unica stringa.
month è controllato solo se year è definito, e day è controllato solo se month è definito.
Se month è un numero tenta di convertilo nel nome corrispondente (1->gennaio, 2->febbraio...),
altrimenti non lo modifica
 ===============================================================================]]
local function get_date_yyyy_mm_dd ( year , month , day )
local date = year
if is_set ( date ) then
if is_set ( month ) then
local month = cfg . months [ tonumber ( month )] or month
date = month .. " " .. year
if is_set ( day ) then
if day == "01" or day == "1" then day = "1º" end
date = day .. " " .. date
end
end
return date
end
return ""
end

--[[ ===============================================================================
Suppone che str sia una data ben formata (una delle varianti "gg mm aaaa",
"gg/mm/aaaa" o "gg-mm-aaaa") e restituisce l'articolo da anteporre per citarla
come data di accesso/archivio
 ===============================================================================]]
local function article_date ( str )
local start = mw . ustring . sub ( str , 1 , 2 )
if in_array ( start , { '08' , '8 ' , '8-' , '8/' , '11' } ) then
return " l'"
elseif mw . ustring . find ( str , '^pre ' ) then -- per i valori "pre x/x/x" inseriti da ArchiveBot
return ' in data '
end
return str ~= '' and " il " or ''
end

--[[ ===============================================================================
Controlla che la stringa passata sia in un formato ammesso in caso contrario
 ritorna il codice di errore
 ===============================================================================]]
local function check_time ( str )
local h , m , s = string.match ( str , '^(%d+):(%d+):(%d+)$' )
if not ( h ) then h , m , s = string.match ( str , '^(%d+) h (%d+) min (%d+) s$' ) end
if not ( m ) then m , s = string.match ( str , '^(%d+) min (%d+) s$' ) end
if not ( m ) then m , s = string.match ( str , '^(%d+):(%d+)$' ) end
if not ( m ) then m = string.match ( str , '^(%d+) min$' ) end
if not ( m ) then return 'time_not_valid' end
if tonumber ( m ) >= 60 then return 'minutes_wrong' end
if s and tonumber ( s ) >= 60 then return 'seconds_wrong' end
if h and not ( tonumber ( s )) then return 'hour_wrong' end
return nil
end

--[[ ===============================================================================
Formatta una lista di persone (autori o editori)
 ===============================================================================]]
local function list_people ( control , people )
local sep = control . sep ;
local lastsep = control . lastsep
local text = {}
local etal = control . etal
local coauthors = control . coauthors
local person_list = {}

for i , person in ipairs ( people ) do
local last = person . last
if is_set ( last ) then
local fullname = ""
local first = person . first
if is_set ( first ) then
if invertorder then first , last = last , first end
fullname = table.concat ({ first , person . last }, ' ' )
else
fullname = person . last
end
if is_set ( person . link ) then fullname = table.concat ({ "[[" , person . link , "|" , fullname , "]]" }) end
table.insert ( person_list , fullname )
end
if etal then
break
end
end
local count = # person_list
local result = ""
if count > 0 then
if coauthors then
result = table.concat ( person_list , sep )
elseif etal then
result = person_list [ 1 ] .. cfg . messages [ 'et al' ]
else
result = mw . text . listToText ( person_list , sep , lastsep )
end
end
return result , count
end

--[[ ===============================================================================
Genera un id per un ancora CITEREF
 ===============================================================================]]
local function anchor_id ( options )
return "CITEREF" .. table.concat ( options );
end

--[[ ===============================================================================
Estrae una lista di nomi (autori o editori) dalla lista argomenti
 ===============================================================================]]
local function extract_names ( args , list_name , parent_name )
local names = {};
local i = 1 ;
local last ;
local parameters = {
first = cfg . aliases [ list_name .. '-First' ],
last = cfg . aliases [ list_name .. '-Last' ],
link = cfg . aliases [ list_name .. '-Link' ],
}

if parent_name then
for k , t in pairs ( parameters ) do
local new_values = {}
for _ , v in ipairs ( t ) do
table.insert ( new_values , substitute ( v , parent_name ) )
end
parameters [ k ] = new_values
end
end

while true do
last = select_one ( args , parameters . last , 'redundant_parameters' , i );
if not is_set ( last ) then
local first = select_one ( args , parameters . first , 'redundant_parameters' , i )
if not is_set ( first ) then
break ;
else -- nel caso sia definito "nome" ma non "cognome"
names [ i ] = {
last = first ,
first = '' ,
link = select_one ( args , parameters . link , 'redundant_parameters' , i ),
}
end
else
names [ i ] = {
last = last ,
first = select_one ( args , parameters . first , 'redundant_parameters' , i ),
link = select_one ( args , parameters . link , 'redundant_parameters' , i ),
};
end
i = i + 1 ;
end
return names ;
end

--[[ ===============================================================================
Estrae dagli argomenti i codici bibliografici riconosciuti usando la
tabella cfg.id_handlers
 ===============================================================================]]
local function extract_ids ( args )
local id_list = {};
for k , v in pairs ( cfg . id_handlers ) do
v = select_one ( args , v . parameters , 'redundant_parameters' );
if is_set ( v ) then
if k == 'ISBN' then v = string.gsub ( v , '^ISBN%s*' , '' ) end -- hack per eliminare l'ISBN ripetuto
id_list [ k ] = v ;
end
end
return id_list ;
end

--[[ ===============================================================================
Formatta gli id bibliografici presenti nella tabella id_list
 ===============================================================================]]
local function build_id_list ( id_list , options )
local new_list , handler = {};

local function fallback ( k )
return { __index = function ( t , i ) return cfg . id_handlers [ k ][ i ] end }
end ;

local function comp ( a , b )
return a [ 1 ] < b [ 1 ];
end

for k , v in pairs ( id_list ) do
-- fallback to read-only cfg
local handler = setmetatable ( { [ 'id' ] = v }, fallback ( k ) );

if k == 'DOI' then
table.insert ( new_list , { handler . label , doi ( v , options . DoiBroken ) } );
elseif k == 'OL' then
table.insert ( new_list , { handler . label , open_library ( v ) } );
elseif k == 'SBN' then
table.insert ( new_list , { handler . label , sbn ( v ) } );
elseif k == 'BNF' then
table.insert ( new_list , { handler . label , bnf ( v ) } );
elseif k == 'ISBN' then
local ISBN
if v == 'non esistente' or v == 'no' then --la forma lunga per intercettare il valore ritornato dal template NoIsbn
ISBN = 'ISBN non esistente'
else
ISBN = link_id ( handler );
if not check_isbn ( v ) and not is_set ( options . IgnoreISBN ) then
ISBN = ISBN .. set_error ( 'bad_isbn' , {}, false , "<sup>" , "</sup>" );
end
end
table.insert ( new_list , { handler . label , ISBN } );
else
table.insert ( new_list , { handler . label , link_id ( handler ) } );
end
end
table.sort ( new_list , comp );
for k , v in ipairs ( new_list ) do
new_list [ k ] = v [ 2 ];
end

return new_list ;
end

--[[ ===============================================================================
Genera la stringa per il formato, se format non è definita tenta di ricavarlo dall'url
 ===============================================================================]]
local function get_format ( format , url )
if format : lower () == 'html' then
return ''
elseif not is_set ( format ) then
format = mw . ustring . match ( url , "^.*%.(.+)$" ) or ''
if not cfg . external_link_type [ format : lower ()] then
format = mw . ustring . match ( format , "^(.+)#.+$" ) or ''
if not cfg . external_link_type [ format : lower ()] then
return ''
end
end
end

-- Se il formato esterno è tra quelli previsti imita lo stile dei template {{PDF}} o {{doc}}
local f = cfg . external_link_type [ format : lower ()]
if f then
return mw . ustring . format ( ' (<span style="font-weight: bolder; font-size:80%%"><abbr title="%s">%s</abbr></span>)' , f . text , f . label )
else
table.insert ( z . message_tail , { set_error ( 'unknown_format' , format , true ) } );
return mw . ustring . format ( ' (%s)' , format )
end
end

--[[ ===============================================================================
Genera la citazione
 ===============================================================================]]
local function citation0 ( config , args )
local A = argument_wrapper ( args );
local i

local Stylename = A [ 'Style' ]
local Style = cfg . style
local PPPrefix = ( is_set ( A [ 'NoPP' ] ) and "" ) or Style . ppprefix
local PPrefix = ( is_set ( A [ 'NoPP' ] ) and "" ) or Style . pprefix
-- Pick out the relevant fields from the arguments. Different citation templates
-- define different field names for the same underlying things.
-- local Authors = A['Authors'];
local a = extract_names ( args , 'AuthorList' );

local Coauthors = A [ 'Coauthors' ];
local Others = A [ 'Others' ];
local Editors = A [ 'Editors' ];
local e = extract_names ( args , 'EditorList' );

------------------------------------------------- Get date data
local PublicationDate = A [ 'PublicationDate' ];
local LayDate = A [ 'LayDate' ];
------------------------------------------------- Get title data
local Title = A [ 'Title' ];
local Conference = A [ 'Conference' ];
local Organization = A [ 'Organization' ]
local TransTitle = A [ 'TransTitle' ];
local OriginalTitle = A [ 'OriginalTitle' ]
-- local TitleNote = A['TitleNote'];
local TitleLink = A [ 'TitleLink' ];
local Chapter = A [ 'Chapter' ];
local ChapterLink = A [ 'ChapterLink' ];
local TransChapter = A [ 'TransChapter' ];
local TitleType = A [ 'TitleType' ];
local ArchiveURL = A [ 'ArchiveURL' ];
local URL = A [ 'URL' ]
local URLorigin = A : ORIGIN ( 'URL' );
local ChapterURL = A [ 'ChapterURL' ];
local ChapterURLorigin = A : ORIGIN ( 'ChapterURL' );
local ConferenceURL = A [ 'ConferenceURL' ];
local ConferenceURLorigin = A : ORIGIN ( 'ConferenceURL' );
local Abstract = A [ 'Abstract' ]
local Periodical = A [ 'Periodical' ];
local Illustrator = A [ 'Illustrator' ];
local Translator = A [ 'Translator' ];
local Institution = A [ 'Institution' ];

if is_set ( OriginalTitle ) and not is_set ( TransTitle ) then
TransTitle = OriginalTitle
end

local isPubblicazione = ( config . CitationClass == 'pubblicazione' ) or
( config . CitationClass == 'testo' and is_set ( Periodical ))

------------------------------------------------------------------------------
-- Formattazione di Position - contiene la pagina/posizione o punto del video
-- a cui fa riferimento la fonte
------------------------------------------------------------------------------
local Position = A [ 'Position' ];
local PositionOrigin = A : ORIGIN ( 'Position' )
if is_set ( Position ) then
if PositionOrigin == "p" then
Position = PPrefix .. Position
elseif PositionOrigin == "pp" then
Position = PPPrefix .. Position
elseif PositionOrigin ~= "posizione" then
table.insert ( z . error_categories , 'Voci con modulo citazione e parametro ' .. PositionOrigin )
if PositionOrigin == "pagine" then
if config . CitationClass == "libro" then
if tonumber ( Position ) then
Position = PPrefix .. Position
elseif string.find ( Position , '^%d' ) then
Position = PPPrefix .. Position
end
elseif config . CitationClass == "conferenza" or config . CitationClass == "pubblicazione" then
Position = ( tonumber ( Position ) and PPrefix or PPPrefix ) .. Position
end
elseif PositionOrigin == "pagina" then
Position = PPrefix .. Position
else
Position = PPPrefix .. Position
end
end
end
local Hour = A [ 'Hour' ]
local Minutes = A [ 'Minutes' ]
local Seconds = A [ 'Seconds' ]
local Time = A [ 'Time' ]
if in_array ( config . CitationClass , { "video" , "tv" , "audio" } ) then
local ComposeTime = {}
local TimeError = {}
if is_set ( Hour ) then
if not is_set ( Minutes ) then TimeError [ # TimeError + 1 ] = set_error ( 'need_minutes' , { 'ora' }) end
if not tonumber ( Hour ) then TimeError [ # TimeError + 1 ] = set_error ( 'timepar_must_be_integer' , { 'ora' }) end
ComposeTime [ # ComposeTime + 1 ] = Hour .. '&nbsp;h'
end
if is_set ( Minutes ) then
local check_error = tonumber ( Minutes )
if not check_error then
TimeError [ # TimeError + 1 ] = set_error ( 'timepar_must_be_integer' , { 'minuto' })
elseif check_error > 60 then
TimeError [ # TimeError + 1 ] = set_error ( 'minutes_wrong' )
end 
ComposeTime [ # ComposeTime + 1 ] = Minutes .. '&nbsp;min'
end
if is_set ( Seconds ) then
if not is_set ( Minutes ) then TimeError [ # TimeError + 1 ] = set_error ( 'need_minutes' , { 'secondo' }) end
local check_error = tonumber ( Seconds )
if not check_error then
TimeError [ # TimeError + 1 ] = set_error ( 'timepar_must_be_integer' , { 'ora' })
elseif check_error > 60 then
TimeError [ # TimeError + 1 ] = set_error ( 'seconds_wrong' )
end
ComposeTime [ # ComposeTime + 1 ] = Seconds .. '&nbsp;s'
end
if # ComposeTime > 1 then
if is_set ( Position ) then TimeError [ # TimeError + 1 ] = set_error ( 'time_parameter_conflict' ) end
Position = 'a ' .. table.concat ( ComposeTime , '&nbsp;' )
end
if is_set ( Time ) then
if is_set ( Position ) then TimeError [ # TimeError + 1 ] = set_error ( 'time_parameter_conflict' ) end
local check_error = check_time ( Time )
if check_error then TimeError [ # TimeError + 1 ] = set_error ( check_error ) end
Position = 'a ' .. Time
end
if # TimeError > 0 then Position = Position .. " " .. table.concat ( TimeError , ", " ) end
else
if is_set ( Hour ) or is_set ( Minutes ) or is_set ( Seconds ) or is_set ( Time ) then
table.insert ( z . message_tail , { set_error ( 'not_video_citation' , {}, true ) } );
end
end
if is_set ( Position ) then Position = ' ' .. Position end

------------------------------------------------------------------------------
-- Formattazione di volume/numero/serie/episodio
------------------------------------------------------------------------------
local Series = A [ 'Series' ];
local Volume = A [ 'Volume' ];
local Issue = A [ 'Issue' ];
if config . CitationClass == "tv" then
if is_set ( Issue ) then
if is_set ( Volume ) then
Issue = substitute ( cfg . messages [ 'season_episode' ], { Volume , Issue } )
Volume = ''
else
Issue = substitute ( cfg . messages [ 'episode' ], { Issue })
end
end
else
-- formatta Volume e Issue considerando numeri anche le stringhe del tipo nn on/n
if is_set ( Volume ) then
if tonumber ( Volume : gsub ( '[-/]' , '' ), 10 ) or A : ORIGIN ( 'Volume' ) == "vol" then
Volume = "vol.&nbsp;" .. Volume
end
end
if is_set ( Issue ) then
if tonumber ( Issue : gsub ( '[-/]' , '' ), 10 ) then
Issue = "n.&nbsp;" .. Issue
end
end
end

local Edition = A [ 'Edition' ];
local Place = A [ 'Place' ]
local PublisherName = A [ 'PublisherName' ];
local SubscriptionRequired = A [ 'SubscriptionRequired' ];
local Via = A [ 'Via' ];
-- local Agency = A['Agency'];
local DeadURL = A [ 'DeadURL' ];
local Language = A [ 'Language' ];
local Format = A [ 'Format' ];
local Ref = A [ 'Ref' ];

local DoiBroken = A [ 'DoiBroken' ];
local ID = A [ 'ID' ];
local IgnoreISBN = A [ 'IgnoreISBN' ];
local Quote = A [ 'Quote' ];
local sepc = Style . sep
local sepcspace = sepc .. " "
local PostScript = first_set ( A [ 'PostScript' ], Style [ 'postscript' ]);
local no_tracking_cats = A [ 'NoTracking' ];
local use_lowercase = ( sepc ~= '.' );
local this_page = mw . title . getCurrentTitle (); --Also used for COinS

local ID_list = extract_ids ( args );
if ( isPubblicazione ) then
if not is_set ( URL ) and not is_set ( TitleLink ) then
if is_set ( ID_list [ 'PMC' ]) then
local Embargo = A [ 'Embargo' ];
if is_set ( Embargo ) then
local lang = mw . getContentLanguage ();
local good1 , result1 , good2 , result2 ;
good1 , result1 = pcall ( lang . formatDate , lang , 'U' , Embargo );
good2 , result2 = pcall ( lang . formatDate , lang , 'U' );

if good1 and good2 and tonumber ( result1 ) < tonumber ( result2 ) then
URL = "https://www.ncbi.nlm.nih.gov/pmc/articles/PMC" .. ID_list [ 'PMC' ];
URLorigin = cfg . id_handlers [ 'PMC' ]. parameters [ 1 ];
end
else
URL = "https://www.ncbi.nlm.nih.gov/pmc/articles/PMC" .. ID_list [ 'PMC' ];
URLorigin = cfg . id_handlers [ 'PMC' ]. parameters [ 1 ];
end
elseif is_set ( ID_list [ 'DOI' ]) then
URL = "https://oadoi.org/" .. ID_list [ 'DOI' ];
URLorigin = cfg . id_handlers [ 'DOI' ]. parameters [ 1 ];
end
end
end
ID_list = build_id_list ( ID_list , { DoiBroken = DoiBroken , IgnoreISBN = IgnoreISBN } );

local Station = A [ 'Station' ];
if is_set ( Station ) then
local wkStation = A [ 'StationLink' ]
if is_set ( wkStation ) then
Station = '[[' .. wkStation .. '|' .. Station .. ']]'
end
end
if config . CitationClass == "tv" then
Chapter = Title ;
ChapterLink = TitleLink ;
TransChapter = TransTitle ;
Title = Series ;
TitleLink = A [ 'SeriesLink' ];
TransTitle = '' ;
Series = '' ;
end

------------------------------------------------------------------------------
-- Se url è in realtà un url archiviato, lo tratta come tale
-- (per ora riconosce solo Internet Archive)
------------------------------------------------------------------------------
local formatoIA = '^https?://web%.archive%.org/w?e?b?/?%d+/'
if is_set ( URL ) and is_set ( Title ) and URL : match ( formatoIA ) and not is_set ( ArchiveURL ) then
ArchiveURL = URL
URL = URL : gsub ( formatoIA , '' )
if not URL : match ( '://' ) then
URL = 'http://' .. URL
end
end

------------------------------------------------------------------------------
-- Se opera/sito non è specificata, nel caso dei siti usa il dominio dell'URL
------------------------------------------------------------------------------
local auto_Periodical = false
if in_array ( config . CitationClass , { 'web' }) and not is_set ( Periodical ) and is_set ( URL ) then
Periodical = mw . ustring . match ( URL , "//([^/#%?]*)" ) or ''
-- tolgo anche eventuale www.
if string.find ( Periodical , "^[Ww][Ww][Ww]%." ) then
Periodical = mw . ustring . sub ( Periodical , 5 )
end
-- evito ripetizione se il dominio è stato usato come titolo o editore
if Periodical and mw . ustring . lower ( Title or '' ) == mw . ustring . lower ( Periodical ) then
Periodical = nil
end
if Periodical and mw . ustring . lower ( PublisherName or '' ) == mw . ustring . lower ( Periodical ) then
PublisherName = nil
end
auto_Periodical = true
end
------------------------------------------------------------------------------
-- Per cambiare posizione a collane o serie di libri nella citazione,
-- rispetto a nomi di rivistaed evitare di precederle con un "in"
-- TODO per il momento commentato (da rivedere per chiarire collana/opera)
------------------------------------------------------------------------------
-- local Book_series = ''
-- if is_set(Periodical) and (A:ORIGIN('Periodical') == "opera" or A:ORIGIN('Periodical') == "collana") then
-- Book_series = "collana " .. wrap( 'italic-title', Periodical );
-- Periodical = '';
-- end

------------------------------------------------------------------------------
-- Se compare uno dei parametri legati a una pubblicazione periodica (opera, rivista, ec...)
-- e non è definito capitolo, ma solo titolo sposto titolo a capitolo
------------------------------------------------------------------------------
if is_set ( Periodical ) and not is_set ( Chapter ) and is_set ( Title ) then
Chapter = Title ;
ChapterLink = TitleLink ;
TransChapter = TransTitle ;
Title = '' ;
TitleLink = '' ;
TransTitle = '' ;
end

---------------------------------------------------------------
-- Compone la stringa del linguaggio
---------------------------------------------------------------
local Language_code = ""
local first_language = ""
if is_set ( Language ) then
if Language : sub ( 1 , 1 ) == "(" then
Language_code = Language
else
local frame_lingue = { return_error = 'true' }
for lingua in mw . text . gsplit ( Language , ',' , true ) do
lingua = mw . text . trim ( lingua )
if lingua ~= '' then
frame_lingue [ # frame_lingue + 1 ] = lingua
end
end
if # frame_lingue > 1 or ( # frame_lingue == 1 and frame_lingue [ 1 ]: lower () ~= "it" and frame_lingue [ 1 ]: lower () ~= "it-it" ) then
first_language = frame_lingue [ 1 ]: lower ();
local lg_error ;
Language_code , lg_error = require ( "Modulo:Linguaggi" ). lingue ( frame_lingue )
if lg_error and # lg_error > 0 then
local error_string = mw . text . listToText ( lg_error , ", " , " e " )
table.insert ( z . message_tail , { set_error ( 'unknown_language' , { error_string }, true ) } );
end
end
end
end
if is_set ( Edition ) then
if A : ORIGIN ( 'Edition' ) == "ed" or tonumber ( Edition ) then
Edition = Edition .. "ª&nbsp;ed."
end
end

------------------------------------------------------------------------------
-- Aggiunge il wikilink a Wikisource
------------------------------------------------------------------------------
if is_set ( A [ 'Source' ]) and not in_array ( config . CitationClass , { "web" , "video" , "tv" , "audio" } ) then
local source = A [ 'Source' ]
-- se s=1 usa lo stesso valore di titolo/capitolo
if source == "1" then
source = Title .. ( is_set ( Chapter ) and ( "/" .. Chapter ) or "" )
end
source = "s:" .. ( is_set ( first_language ) and ( first_language .. ":" ) or "" ) .. source
if is_set ( Chapter ) then ChapterLink = source
else TitleLink = source end
end

------------------------------------------------------------------------------
-- Recupero e formatto lista autori
------------------------------------------------------------------------------
local AuthorSeparator = Style . peoplesep
local control = {
sep = AuthorSeparator ,
maximum = Style . maximum_authors ,
lastsep = Style . lastsepauthor ,
invertorder = Style . invertorder ,
etal = false ,
coauthors = false ,
};
local Etal = A [ 'Etal' ]
-- If the coauthor field is also used, prevent adding ''et al.''
if is_set ( Coauthors ) then
table.insert ( z . error_categories , 'Voci con modulo citazione e parametro ' .. A : ORIGIN ( 'Coauthors' ) )
control . coauthors = true
elseif is_set ( Etal ) then
control . etal = true
end
local Authors = list_people ( control , a )
if not is_set ( Authors ) and is_set ( Coauthors ) then -- se non sono stati compilati campi autore, ma solo coautori
Authors = Coauthors
Coauthors = ""
elseif is_set ( Coauthors ) then
Authors = table.concat ({ Authors , AuthorSeparator , Coauthors })
end

------------------------------------------------------------------------------
-- Recupero e formatto lista curatori
------------------------------------------------------------------------------
local EditorCount , msg_editors
local CuratoriEtal = A [ 'Etalcuratori' ]
control . coauthors = false
if is_set ( CuratoriEtal ) then
control . etal = true
else
control . etal = false
end
if is_set ( Editors ) then
msg_editors = 'editors'
else
Editors , EditorCount = list_people ( control , e )
if is_set ( Editors ) then
if EditorCount <= 1 then msg_editors = 'editor' else msg_editors = 'editors' end
end
end
------------------------------------------------------------------------------
-- Se non sono definiti autori sostituisco con curatori
------------------------------------------------------------------------------
if not is_set ( Authors ) and is_set ( Editors ) then
Authors = Editors
Editors = ""
end

------------------------------------------------------------------------------
-- Recupero e formatto lista autori di un singolo capitolo dell'opera citata
------------------------------------------------------------------------------
local Contributors
if is_set ( Chapter ) then
local c = extract_names ( args , 'ContributorList' , A : ORIGIN ( 'Chapter' ) );
control . etal = false
Contributors = list_people ( control , c )
end

------------------------------------------------------------------------------
-- Se conferenza aggiungo il campo Organizzazione
------------------------------------------------------------------------------
if config . CitationClass == 'conferenza' then
if is_set ( Authors ) and is_set ( Organization ) then
Authors = table.concat ({ Authors , ', ' , Organization })
elseif is_set ( Organization ) then
Authors = Organization
end
Organization = ""
end

------------------------------------------------------------------------------
-- Formatto la data
------------------------------------------------------------------------------
local Date = get_date ( A [ 'Date' ])
local Year = A [ 'Year' ]
if not is_set ( Date ) then Date = get_date_yyyy_mm_dd ( Year , A [ 'Month' ], A [ 'Day' ]) end
local OrigDate = get_date ( A [ 'OrigDate' ])
if not is_set ( OrigDate ) then OrigDate = get_date_yyyy_mm_dd ( A [ 'OrigYear' ], A [ 'OrigMonth' ], A [ 'OrigDay' ]) end
local AccessDate = get_date ( A [ 'AccessDate' ])
if not is_set ( AccessDate ) then AccessDate = get_date_yyyy_mm_dd ( A [ 'AccessYear' ], A [ 'AccessMonth' ], A [ 'AccessDay' ]) end
local ArchiveDate = get_date ( A [ 'ArchiveDate' ]);
if is_set ( OrigDate ) and not is_set ( Date ) then
Date = OrigDate
OrigDate = ""
end
OrigDate = is_set ( OrigDate ) and ( " " .. wrap ( 'origdate' , OrigDate )) or "" ;

if in_array ( PublicationDate , { Date , Year }) then PublicationDate = '' end
if not is_set ( Date ) and is_set ( PublicationDate ) then
Date = PublicationDate ;
PublicationDate = '' ;
end

-- Captures the value for Date prior to adding parens or other textual transformations
local DateIn = Date ;
if not is_set ( URL ) and
not is_set ( ChapterURL ) and
not is_set ( ArchiveURL ) and
not is_set ( ConferenceURL ) then
-- Controlla se Cita web viene chiamato senza URL
if in_array ( config . CitationClass , { 'web' }) then
table.insert ( z . message_tail , { set_error ( 'cite_web_url' , {}, true ) } );
end
-- Test if accessdate is given without giving a URL
if is_set ( AccessDate ) then
table.insert ( z . message_tail , { set_error ( 'accessdate_missing_url' , {}, true ) } );
AccessDate = '' ;
end
-- Test if format is given without giving a URL
if is_set ( Format ) then
Format = Format .. set_error ( 'format_missing_url' );
end
end

-- Test if citation has no title
if not is_set ( Chapter ) and
not is_set ( Title ) and
not is_set ( Periodical ) and
not is_set ( Conference ) and
not is_set ( TransTitle ) and
not is_set ( TransChapter ) then
table.insert ( z . message_tail , { set_error ( 'citation_missing_title' , {}, true ) } );
end

-- genera la stringa per il formato
Format = get_format ( Format , ( is_set ( URL ) and URL ) or ChapterURL )

-- In maniera predefinita l'URL non è dichiarato morto
if is_set ( DeadURL ) then
DeadURL = DeadURL : lower () ~= 'no'
else
-- A meno che l'archivio non sia specificato
DeadURL = is_set ( ArchiveURL )
end

local OriginalURL = URL
if is_set ( ArchiveURL ) then
if DeadURL then
URL = ArchiveURL
URLorigin = A : ORIGIN ( 'ArchiveURL' )
end
end

---------------------------------------------------------------
-- se pubblicazione controlla per i parametro abstract
--------------------------------------------------------------
if is_set ( Abstract ) then
if isPubblicazione then
if is_set ( ChapterURL ) then
TitleType = external_link ( ChapterURL , 'abstract' )
ChapterURL = ""
if not is_set ( URL ) then Format = "" end
elseif is_set ( URL ) then
TitleType = external_link ( URL , 'abstract' )
URL = ""
else
Abstract = ''
end
else
Abstract = ""
end
else
Abstract = ""
end
TitleType = is_set ( TitleType ) and ( "(" .. TitleType .. ")" ) or "" ;

---------------------------------------------------------------
-- Format chapter / article title
---------------------------------------------------------------
local TransError = ""
if is_set ( TransChapter ) then
if not is_set ( Chapter ) then
TransError = " " .. set_error ( 'trans_missing_chapter' )
Chapter = TransChapter
TransChapter = ""
else
TransChapter = wrap ( 'trans-italic-title' , TransChapter )
end
end
Chapter = is_latin ( Chapter ) and wrap ( 'italic-title' , Chapter ) or Chapter ;
if is_set ( TransChapter ) then Chapter = Chapter .. " " .. TransChapter end
if is_set ( Chapter ) then
if is_set ( ChapterLink ) then
Chapter = table.concat ({ "[[" , ChapterLink , "|" , Chapter , "]]" })
elseif is_set ( ChapterURL ) then
Chapter = external_link ( ChapterURL , Chapter ) .. TransError ;
if not is_set ( URL ) then --se è settato URL conservo Format per inserirlo dopo questo
Chapter = Chapter .. Format ;
Format = "" ;
end
elseif is_set ( URL ) then
Chapter = external_link ( URL , Chapter ) .. TransError ;
Chapter = append_links ( Chapter , args . altrilink )
Chapter = Chapter .. Format ;
URL = "" ;
Format = "" ;
else
Chapter = Chapter .. TransError ;
end
elseif is_set ( ChapterURL ) then
Chapter = external_link ( ChapterURL , nil , ChapterURLorigin ) .. TransError
end

---------------------------------------------------------------
-- Format main title
---------------------------------------------------------------
TransError = "" ;
if is_set ( TransTitle ) then
if not is_set ( Title ) then
TransError = " " .. set_error ( 'trans_missing_title' )
Title = TransTitle
TransTitle = ""
else
TransTitle = wrap ( 'trans-italic-title' , TransTitle )
end
end
Title = is_latin ( Title ) and wrap ( 'italic-title' , Title ) or Title ;
if is_set ( TransTitle ) then Title = Title .. " " .. TransTitle end
if is_set ( Title ) then
if is_set ( TitleLink ) then
Title = "[[" .. TitleLink .. "|" .. Title .. "]]"
elseif is_set ( URL ) then
Title = external_link ( URL , Title ) .. TransError
Title = append_links ( Title , args . altrilink )
Title = Title .. Format
URL = "" ;
Format = "" ;
else
Title = Title .. TransError ;
end
end
---------------------------------------------------------------
-- Format Conference
---------------------------------------------------------------
if is_set ( Conference ) then
Conference = wrap ( 'italic-title' , Conference )
if is_set ( ConferenceURL ) then
Conference = external_link ( ConferenceURL , Conference );
end
elseif is_set ( ConferenceURL ) then
Conference = external_link ( ConferenceURL , nil , ConferenceURLorigin );
end

-- se URL non è stato consumato da un capitolo/titolo emette errore
if is_set ( URL ) then
URL = " " .. external_link ( URL , nil , URLorigin );
end

--Aggiungo le virgolette alla citazione-
if is_set ( Quote ) then
Quote = wrap ( 'quoted-text' , Quote );
end
---------------------------------------------------------------
-- Parametro via e subscription
---------------------------------------------------------------
if is_set ( Via ) then
if is_set ( SubscriptionRequired ) then
Via = wrap ( 'viasubscription' , Via );
else
Via = wrap ( 'via' , Via );
end
elseif is_set ( SubscriptionRequired ) then
Via = wrap ( 'subscription' )
end

---------------------------------------------------------------
-- Formattazione dati di accesso/url di archivio
---------------------------------------------------------------
if is_set ( AccessDate ) then
AccessDate = substitute ( cfg . messages [ 'retrieved' ], { AccessDate , article_date ( AccessDate )} )
end
local Archived
if is_set ( ArchiveURL ) then
local decodeArchiveDate = require ( 'Modulo:Webarchive' ). decodeArchiveDate
local ArchiveURLDate = decodeArchiveDate ( ArchiveURL )
local ArchiveError , ArchiveOutput = ''
if not is_set ( ArchiveDate ) then
ArchiveDate = ArchiveURLDate or ''
if not ArchiveURLDate then
ArchiveError = set_error ( 'archive_missing_date' , {}, false , ' ' )
end
elseif ArchiveURLDate and ArchiveURLDate ~= ArchiveDate then
ArchiveError = set_error ( 'date_mismatch' , { ArchiveURLDate }, false , ' ' )
end
ArchiveOutput = ArchiveDate .. ArchiveError
local ArchiveURL2 = A [ 'ArchiveURL2' ]
local ArchiveDate2 = get_date ( A [ 'ArchiveDate2' ])
if is_set ( ArchiveURL2 ) then
local ArchiveURLDate2 = decodeArchiveDate ( ArchiveURL2 )
local ArchiveError2 , ArchiveOutput2 = ''
if not is_set ( ArchiveDate2 ) then
ArchiveDate2 = ArchiveURLDate2 or ''
if not ArchiveURLDate2 then
ArchiveError2 = set_error ( 'archive_missing_date2' , {}, false , ' ' )
end
elseif ArchiveURLDate2 and ArchiveURLDate2 ~= ArchiveDate2 then
ArchiveError2 = set_error ( 'date2_mismatch' , { ArchiveURLDate2 }, false , ' ' )
end
ArchiveOutput2 = ArchiveDate2 .. ArchiveError2
ArchiveURL2 = substitute ( cfg . messages [ 'archived-second-copy' ],
{ external_link ( ArchiveURL2 , cfg . messages [ 'archived2' ]), ArchiveOutput2 , article_date ( ArchiveDate2 ) } );
end
if not DeadURL then
Archived = substitute ( cfg . messages [ 'archived-not-dead' ],
{ external_link ( ArchiveURL , cfg . messages [ 'archived' ] ), ArchiveOutput , article_date ( ArchiveDate ), ArchiveURL2 } );
if not is_set ( OriginalURL ) then
Archived = Archived .. set_error ( 'archive_missing_url' , {}, false , ' ' );
end
elseif is_set ( OriginalURL ) then
Archived = substitute ( cfg . messages [ 'archived-dead' ],
{ OriginalURL , ArchiveOutput , article_date ( ArchiveDate ), ArchiveURL2 } );
else
Archived = substitute ( cfg . messages [ 'archived-missing' ],
{ set_error ( 'archive_missing_url' ), ArchiveOutput , article_date ( ArchiveDate ), ArchiveURL2 } );
end
else
Archived = ""
end

---------------------------------------------------------------
-- Data originale se presente (in ordine di preferenza dopo
-- la data di pubblicazione, quindi l'editore, il luogo di pubblicazione, )
---------------------------------------------------------------
if is_set ( OrigDate ) then
if is_set ( Date ) then
Date = Date .. " " .. OrigDate
elseif is_set ( PublisherName ) then
PublisherName = PublisherName .. " " .. OrigDate
elseif is_set ( Plase ) then
Place = Place .. " " .. OrigDate
else
Date = OrigDate
end
end

-- Several of the above rely upon detecting this as nil, so do it last.
if is_set ( Periodical ) then Periodical = wrap ( 'italic-title' , Periodical ) end

-- set translator / illustrator
if is_set ( Translator ) then Translator = wrap ( 'translator' , Translator ) end
if is_set ( Illustrator ) then Illustrator = wrap ( 'illustrator' , Illustrator ) end

---------------------------------------------------------------
-- Combino insieme i vari componenti della citazione
---------------------------------------------------------------

local fragment_Title
local PostTitle = A [ 'PostTitle' ]
if is_set ( Title ) then
if DeadURL and not is_set ( ArchiveURL ) then
-- Report a dead URL without an archived URL
Title = Title .. interrupted_url ()
end
fragment_Title = Fragment . new ({ Title , Format , TitleType , PostTitle }, ' ' ): last ( "," )
else
fragment_Title = Fragment . new ({ })
if is_set ( Chapter ) then
Chapter = DeadURL and not is_set ( ArchiveURL )
and tostring ( Fragment . new ({ Chapter , interrupted_url (), Format , TitleType , PostTitle }, ' ' ): last ( "" ))
or tostring ( Fragment . new ({ Chapter , Format , TitleType , PostTitle }, ' ' ): last ( "" ))
end
end

local fragment_citation
if config . CitationClass == "tv" then
if is_set ( Chapter ) then
fragment_Title : last ( ":" ): append ( Fragment . new ({ Issue , Chapter }, sepc ))
Issue = ""
end
fragment_citation = Fragment . new ({ Authors }, sepc )
fragment_citation : append ( fragment_Title )
else
if is_set ( Authors ) and is_set ( Editors ) and is_set ( Title ) and not is_set ( Chapter ) then
Editors = 'a cura di ' .. Editors
fragment_citation = Fragment . new ({ Authors }, sepc )
fragment_citation : appends ({ fragment_Title , Editors })
else
if is_set ( msg_editors ) then
if is_set ( Editors ) then
Editors = wrap ( msg_editors , Editors )
else
Authors = wrap ( msg_editors , Authors )
end
elseif is_set ( Contributors ) and is_set ( Title ) then
Authors , Editors = Contributors , Authors
end
fragment_citation = Fragment . new ({ Authors , Chapter }, sepc )
if Chapter ~= "" or Editors ~= "" then
if A : ORIGIN ( 'Periodical' ) == 'sito' or auto_Periodical then -- antepone "su" anzichè "in" per i siti web
fragment_citation : last ( "su" )
else
fragment_citation : last ( "in" )
end
end
fragment_citation : appends ({ Editors , fragment_Title })
end
end
fragment_citation : appends ( { Conference , Periodical , Translator , Illustrator , Others , Series , -- Book_series,
Volume , Issue , Edition , Institution , Place , PublisherName , Station , Date , Position } )
local fragment_ID_list = Fragment . new ( ID_list , sepc ): append ( ID ): start ( "," )
local fragment_URL = Fragment . new ( URL ): start ( "," )
local fragment_AccessDate = Fragment . new ( AccessDate ): start ( '.' )
local fragment_Archived = Fragment . new ( Archived ): start ( ' ' )
local fragment_Via = Fragment . new ( Via ): start ( "." )
local fragment_Quote = Fragment . new ({ Quote }): start ( "." )
fragment_citation : appends ({ fragment_ID_list , fragment_URL , fragment_AccessDate , fragment_Archived , fragment_Via , fragment_Quote })
if PostScript == 'nessuno' then
fragment_citation : last ( "nothing" )
else
fragment_citation : last ( ".." )
end
fragment_citation : start ( " " )
local text = Language_code .. tostring ( fragment_citation )
-- aggiungo l'icona per video/audio
if config . CitationClass == "video" then text = cfg . messages [ 'icon_video' ] .. ' ' .. text end
if config . CitationClass == "audio" then text = cfg . messages [ 'icon_audio' ] .. ' ' .. text end

-- Now enclose the whole thing in a <span/> element
local options = {};

if is_set ( config . CitationClass ) and config . CitationClass ~= "citation" then
options . class = "citation " .. config . CitationClass ;
else
options . class = "citation" ;
end

-- if string.len(text:gsub("<span[^>/]*>.-</span>", ""):gsub("%b<>","")) <= 2 then
-- z.error_categories = {};
-- text = set_error('empty_citation');
-- z.message_tail = {};
-- end

if is_set ( Ref ) then
text = table.concat ({ '<cite id="CITEREF' , Ref , --mw.uri.anchorEncode('CITEREF' .. Ref),
'" class="' , mw . text . nowiki ( options . class ), '" style="font-style:normal">' , text , "</cite>" })
else
text = table.concat ({ '<cite class="' , mw . text . nowiki ( options . class ), '" style="font-style:normal">' , text , "</cite>" })
end

local empty_span = '<span style="display:none;">&nbsp;</span>' ;

if # z . message_tail ~= 0 then
text = text .. " " ;
for i , v in ipairs ( z . message_tail ) do
if is_set ( v [ 1 ]) then
if i == # z . message_tail then
text = text .. error_comment ( v [ 1 ], v [ 2 ] );
else
text = text .. error_comment ( v [ 1 ] .. "; " , v [ 2 ] );
end
end
end
end

-- Chek to insert category error
if not is_set ( no_tracking_cats ) then
for k , v in pairs ( cfg . uncategorized_namespaces ) do
if this_page . nsText == v then
no_tracking_cats = "true" ;
break ;
end
end
end
no_tracking_cats = no_tracking_cats : lower ();
if in_array ( no_tracking_cats , { "" , "no" , "false" , "n" }) then
for _ , v in ipairs ( z . error_categories ) do
text = text .. '[[Categoria:' .. v .. ']]' ;
end
end

return text
end

--[[ ===============================================================================
Funzione di interfaccia per la generazione della citazione, usata dai vari template
cita libro, cita news, ecc...
 ===============================================================================]]
function z . citation ( frame )
local pframe = frame : getParent ()

local args = {};
local suggestions = {};
local error_text , error_state ;

local config = {};
for k , v in pairs ( frame . args ) do
config [ k ] = v ;
args [ k ] = v ;
end
if config [ 'ignore_parent' ] == 's' then
pframe . args = {}
end
local ignore_unnamed = ( config [ 'ignore_unnamed' ] == 's' ) or false
-- copy unnamed parameter to named parameter
local lastunnamed = 0
if not ( ignore_unnamed ) and cfg . unnamed_parameter [ config . CitationClass ] then
for i , v in ipairs ( cfg . unnamed_parameter [ config . CitationClass ]) do
if pframe . args [ i ] then
local args_value = mw . text . trim ( pframe . args [ i ])
if args_value ~= "" then
args [ v ] = args_value
end
lastunnamed = i
else
break
end
end
end
for k , v in pairs ( pframe . args ) do
if v ~= '' then
if not validate ( k ) then
error_text = "" ;
if type ( k ) ~= 'string' then
-- Exclude empty numbered parameters
if v : match ( "%S+" ) ~= nil and tonumber ( k ) > lastunnamed and lastunnamed > 0 then
error_text , error_state = set_error ( 'text_ignored' , { v }, true );
end
elseif validate ( k : lower () ) then
error_text , error_state = set_error ( 'parameter_ignored_suggest' , { k , k : lower ()}, true );
else
if # suggestions == 0 then
suggestions = mw . loadData ( 'Modulo:Citazione/Suggerimenti' );
--suggestions = load_configuration_table( 'Modulo:Citazione/Suggerimenti');
end
if suggestions [ k : lower () ] ~= nil then
error_text , error_state = set_error ( 'parameter_ignored_suggest' , { k , suggestions [ k : lower () ]}, true );
else
error_text , error_state = set_error ( 'parameter_ignored' , { k }, true );
end
end
if error_text ~= '' then
table.insert ( z . message_tail , { error_text , error_state } );
end
end
args [ k ] = v ;
elseif args [ k ] ~= nil then
args [ k ] = v ;
end
end

-- hack per l'uso che fanno cita google books e youtube del parametro id
if args . id and args . id ~= '' then
if in_array ( config . CitationClass , { "googlebooks" , "video" }) then
args . id = nil
end
end
return citation0 ( config , args )
end

-- Funzione per generare direttamente una citazione da un altro modulo
function z . cita_da_modulo ( classe , args )
-- mi assicuro che le code messaggi di errore siano vuote per evitare problemi in caso
-- per citazioni multiple dall'interno dello stesso modulo
z . error_categories = {}; -- lista delle categorie di errore
z . error_ids = {}; -- lista dei codici di errore
z . message_tail = {}; -- messaggi di errore da visualizzare in coda alla citazione
return citation0 ( { CitationClass = classe }, args )
end

-- Elenco i formati di documenti gestiti
function z . list_external_links ( frame )
local rows = { '{| class = "wikitable sortable" \n !codice!!Testo popup' }
local keys = {}
for key , _ in pairs ( cfg . external_link_type ) do
keys [ # keys + 1 ] = key
end
table.sort ( keys )
for _ , key in ipairs ( keys ) do
rows [ # rows + 1 ] = mw . ustring . format ( '|- \n |%s||%s' , key , cfg . external_link_type [ key ]. text )
end
rows [ # rows + 1 ] = "|}"
return table.concat ( rows , ' \n ' )
end

-- per formati esterni da altri template
function z . format ( frame )
local getArgs = require ( 'Module:Arguments' ). getArgs
local args = getArgs ( frame , { frameOnly = true })
return get_format ( args [ 1 ])
end

return z