Módulo:Identificadores

De Bioeticawiki

La documentación para este módulo puede ser creada en Módulo:Identificadores/doc

local p = {}

--[[
ISBN-10 and ISSN validator code calculates checksum across all isbn/issn digits including the check digit. ISBN-13 is checked in checkisbn().
If the number is valid the result will be 0. Before calling this function, issbn/issn must be checked for length and stripped of dashes,
spaces and other non-isxn characters.
]]
-- Función traída de en:Module:Citation/CS1

function p.esValidoISXN (isxn_str, len)
	local temp = 0;
	isxn_str = { isxn_str:byte(1, len) };	-- make a table of bytes
	len = len+1;							-- adjust to be a loop counter
	for i, v in ipairs( isxn_str ) do		-- loop through all of the bytes and calculate the checksum
		if v == string.byte( "X" ) then		-- if checkdigit is X
			temp = temp + 10*( len - i );	-- it represents 10 decimal
		else
			temp = temp + tonumber( string.char(v) )*(len-i);
		end
	end
	return temp % 11 == 0;					-- returns true if calculation result is zero
end

-- Adaptación de la función checkisbn de en:Module:Citation/CS1
function p.esValidoISBN(isbn)
	-- El isbn solo contiene números, guiones, espacios en blanco y el dígito de 
	-- control X.
	
	if not isbn or isbn:match("[^%s-0-9X]")  then
		return false
	end
	
	-- Eliminar los guiones y espacios en blanco
	
	isbn = isbn:gsub( "-", "" ):gsub( " ", "" )
	local longitud = isbn:len()
 
	if longitud == 10 then
		-- La X solo puede ir al final.
		if not isbn:match( "^%d*X?$" ) then
			return false
		end
		return p.esValidoISXN(isbn, 10);
	elseif longitud == 13 then -- isbn13
		local temp = 0;
		-- Debe comenzar por 978 o 979
		if not isbn:match( "^97[89]%d*$" ) then 
			return false
		end
		
		-- Comprobar el dígito de control
		isbn = { isbn:byte(1, longitud) };
		for i, v in ipairs( isbn ) do
			temp = temp + (3 - 2*(i % 2)) * tonumber( string.char(v) );
		end
		return temp % 10 == 0;
	else
		return false
	end
	
end

-- Función que devuelve un enlace al ISBN si es correcto y si no (por ejemplo si
-- ya está enlazado) lo devuelve sin más.
-- Por defecto no se incluye el literal ISBN delante.

function p.enlazarISBN(isbn, opciones)
    if p.esValidoISBN(isbn) then
        return '[[Especial:FuentesDeLibros/' .. isbn .. '|' .. isbn .. ']]'
    else
    	return isbn
    end
end

function p.enlazarOCLC(oclc, opciones)
    if tonumber(oclc) then
        return '[http://www.worldcat.org/oclc/' .. oclc .. ' ' .. oclc .. ']'
    else
    	return oclc
    end
end

return p