Hoppa till innehållet

Modul:Referenshantering

Från Plutten

Dokumentationen för denna modul kan skapas på Modul:Referenshantering/dok

localisation = require( 'Modul:Localisation' )
require('Modul:Utility')

local d={}
local t={}

edit_message = mw.message.new('vector-view-edit'):plain()

rm.iSourcesMissing=0;

--Adds a pen with a link to the relevant wikidata item 
function txtEditPen(qid,pid,txtOtherVersion)
	if (txtOtherVersion) then
		txtFile=txtOtherVersion
		else
		txtFile='Arbcom_ru_editing.svg'
		end
	return '<sup class="noprint Inline-Template">[[File:'..txtFile..'|' 
	                   	.. edit_message .. '|8px|baseline|class=noviewer|link=https://www.wikidata.org/wiki/' 
	                   	.. qid .. '#' .. pid .. ']]</sup>'
end

function txtaddWikiData(txtPropertyName,txtName,txtSupportText)
	return localisation.txtBeginning .. txtPropertyName .. localisation.txtSelect .. txtName .. txtSupportText .. localisation.txtSave
end

-- Function to read all statements/values for a given property. It will return those values (and sources) in a structure that can later on be 
-- used to present the data. That structure always have the following items, but can have more
--	qid - qid of the object
--	pid - property id of the property
--  data - the relevant content. Can be preprocessed from the stored values in various ways depending on the value of txtAlternative
--	bHasRef - whether the statement has sources
--  ref - the sources

-- Input variables:
--	qid - qid of the object
--	pid - property id of the property
-- txtAlternative - how the data will be preprocessed (see useOneStatement below)
-- arrayAllowedQualifiers - qualifiers that will be read if they exist

function useStatement(qid,pid,txtAlternative,arrayAllowedQualifiers,funcprocessing,onlyallowone)
	local claim=mw.wikibase.getBestStatements(qid, pid )
	if #claim==0 then
		return
		end
	if onlyallowone or (#claim==1) then
		firstClaim=claim[1]
		return useOneStatement(firstClaim,qid,txtAlternative,arrayAllowedQualifiers,funcprocessing)
		end
	if #claim>1 then
		statements={}
		for key,value in pairs(claim) do
			table.insert(statements,useOneStatement(value,qid,txtAlternative,arrayAllowedQualifiers,funcprocessing))
		end
		return statements
	end
end

-- txtAlternative - how the data will be preprocessed
--    not set or "formatValue" - uses in the inbuilt formatValue function to process the data
--    "location" - sets latitude and longitude
--    "time" - sets time (including precision and year)
--    "function" - processes the raw information with the supplied function
--    "raw" - do not process the data att all (apart from retrieving it)
function useOneStatement(claim,qid,txtAlternative,arrayAllowedQualifiers,funcprocessing)
	local objOutput={}
	objOutput.id=read(claim,'id')
	objOutput.from,objOutput.to=readDates(claim)
	if ((not txtAlternative) or (txtAlternative=="formatValue")) then
		objOutput.data=mw.wikibase.formatValue(claim.mainsnak)
		end
	if (txtAlternative=="location") then
		objOutput.data=mw.wikibase.formatValue(claim.mainsnak)
		objOutput.latitude= claim.mainsnak.datavalue.value.latitude
		objOutput.longitude= claim.mainsnak.datavalue.value.longitude
		end
	if (txtAlternative=="time") then
		tmpTable=claim.mainsnak.datavalue.value
		objOutput.raw=tmpTable.time
		objOutput.precision=tmpTable.precision
		if (objOutput.raw) then
			objOutput.year=string.sub(objOutput.raw,2,5)
			end
		objOutput.formatted=mw.wikibase.formatValue(claim.mainsnak)
		end
	if (txtAlternative=="wikilink") then
		objOutput.data=txtWikilink(read(claim,'id'))
		end
	if (txtAlternative=="raw") then
		objOutput.data=claim.mainsnak.datavalue.value
		end
	if arrayAllowedQualifiers then
		for i=1,#arrayAllowedQualifiers do
			local qfid=arrayAllowedQualifiers[i]
			objOutput[qfid]=getQualifierId(claim,qfid)
			end
		end
	if (txtAlternative=="function") then
		objOutputProcessed=funcprocessing(objOutput,claim)
		objOutput=merge(objOutputProcessed,objOutput)
		end	
	objOutput.bHasRef,objOutput.ref=processAllRefsForWDItem_model(claim.references,qid)
	objOutput.qid=qid
	objOutput.pid=claim.id
	return objOutput 
end

function readDates(value)
	local startdate=readDate(value,'P580')
	local enddate=readDate(value,'P582')
	if not (startdate or enddate) then
		startdate=readDate(value,'P585')
		enddate=startdate
		end
	return startdate,enddate
end

function readDate(value,pid)
	if value['qualifiers'] then
		if value['qualifiers'][pid] then
			if value['qualifiers'][pid][1] then
				local date={}
				datesnak=value['qualifiers'][pid][1]
				date.raw=readQualifier(datesnak,'time')
				date.precision=readQualifier(datesnak,'precision')
				if (date.raw) then
					date.year=string.sub(date.raw,2,5)
					else
					return nil
					end
				date.formatted=mw.wikibase.formatValue(datesnak)
				return date
			end
		end
	end
	return nil
end


function processAllRefsForWDItem_model(tblReferences,qid)
local tmpResult={}
local bHasSource=0;
--Only add references if there are any 
if (tblReferences) then
	for keyRef, valueRef in pairs(tblReferences) do
		-- Process individual reference
		local isok,refparts=tblProcessIndividualReference_model(valueRef,qid)
		-- Act if reference is ok
		if (isok==1) then
			bHasSource=1
		    -- Add reference to table
		    table.insert(tmpResult,refparts)
		    end
		end
		-- If no valid references (valid = not using wikipedia as a source) return a string composed of the template that says source needed (in wikidata)
	end
	return bHasSource,tmpResult
end

function tblProcessIndividualReference_model(thisref,idMainEntity)
	local refparts=thisref.snaks
	table.sort(refparts)

	local isok=1 --is regarded as a source (imported from other wikipedia is not consieder a source)
	local bKeyProcessed=false
	local txtUrlLocal=''
	local txt
	local templateFillArray={}
	templateFillArray['error'] = false -- No error to start with :-)
	for key, value in orderedPairs( refparts) do
		bKeyProcessed=false;
		if (key=='P1065') then -- archive-url
			templateFillArray[localisation.txtArchiveUrl] = value[1].datavalue.value
			bKeyProcessed=true;
		end
 		if (key=='P123') then -- publisher
			iPublisher=readQualifier(value[1],'id')
			templateFillArray[localisation.txtPublisher]='[[' ..  getLabelFundamental( iPublisher ) .. ']]'
			bKeyProcessed=true;
			end
		if (key=='P143') then -- imported from a wikipedia language version
			txt=localisation.txtFromADifferentLanguageVersion
			isok=0
			bKeyProcessed=true;
			end
		if (key=='P1476') then 
			txtTitleLocal=readQualifier(value[1],'text')
			if not (isP248) then
				templateFillArray[localisation.txtLanguage]= readQualifier(value[1],'language')
				templateFillArray[localisation.txtTitle] = string.gsub(txtTitleLocal,"|"," - ")
				end
			bKeyProcessed=true;
			end
		if (key=='P1810') then 
			txtTitleLocal=value[1].datavalue.value
			templateFillArray[localisation.txtTitle] = string.gsub(txtTitleLocal,"|"," - ")
			bKeyProcessed=true;
			end
		if (key=='P2093') then
			templateFillArray[localisation.txtAuthor] = value[1].datavalue.value
			bKeyProcessed=true;
		end
		if (key=='P248') then 
			txtSource=readQualifier(value[1],'id')
			templateFillArray=processDatabaseSource_model(templateFillArray,idMainEntity,txtSource)
			bKeyProcessed=true
			end
		if (key=='P2960') then
			templateFillArray[localisation.txtArchiveDate] = string.sub(readQualifier(value[1],'time'),2,11) 
			bKeyProcessed=true;
		end
		if (key=='P304') then
			templateFillArray[localisation.txtPage]=value[1].datavalue.value
			bKeyProcessed=true;
		end
		if (key=='P3452') then 
--			txt="Härlett från"
			isok=0
			bKeyProcessed=true
			end
		if	(key=='P407') then
			-- Do not process (take language from P1476 instead)
			bKeyProcessed=true
			end
		if (key=='P4656') then 
--			txt="Från språkversion"
			isok=0
			bKeyProcessed=true
			end
 		if (key=='P50') then 
			iAuthor=readQualifier(value[1],'id')
			tmp=rm.tblWikilink(iAuthor)
			templateFillArray[localisation.txtAuthorLabel]=tmp.txtLabel
			bKeyProcessed=true;
			end
		if (key=='P577') then 
			templateFillArray[localisation.txtDateTemplate] = string.sub(readQualifier(value[1],'time'),2,11) 
			bKeyProcessed=true
			end
		if (key=='P813') then 
			templateFillArray[localisation.txtAccessdate] = string.sub(readQualifier(value[1],'time'),2,11)
			bKeyProcessed=true
			end
		if (key=='P854') then 
			txtUrlLocal=string.gsub(value[1].datavalue.value,"|","{{!}}")
			templateFillArray[localisation.txtUrl] = txtUrlLocal
			bKeyProcessed=true
			end
		if (key=='P98') then 
			iAuthor=readQualifier(value[1],'id')
			templateFillArray[localisation.txtAuthor]='[[' ..  getLabelFundamental( iAuthor ) .. ']]'
			bKeyProcessed=true
			end
		if (not (bKeyProcessed)) then
			-- If not found by the keys above, assume it is from a database
			-- Test for common database qids to show data
			local subjectobject=mw.wikibase.getBestStatements(key,'P1629')
			if (not(next(subjectobject))) then
				local subjectobject=mw.wikibase.getBestStatements(key,'P2378')
				end
			if (not(next(subjectobject))) then
				local subjectobject=mw.wikibase.getBestStatements(key,'P10476')
				end
			if (not(next(subjectobject))) then
				local subjectobject=mw.wikibase.getBestStatements(key,'P10726')
				end
			-- If from a database try to add url-link if possible
			if (next(subjectobject)) then
				iSubjectobject=read(subjectobject[1],'id')
				templateFillArray[localisation.txtTitle]=getLabelFundamental( iSubjectobject )
				keyentity=mw.wikibase.getEntity( key )
				urlsnak=mw.wikibase.getBestStatements(key,'P1630' )
				if (next(urlsnak)) then
					url=urlsnak[1].mainsnak.datavalue.value
					thisid=value[1].datavalue.value
					templateFillArray[localisation.txtUrl] = string.gsub(url,"$1",thisid)
					else
					templateFillArray[localisation.txtUrl] = 'No Url!'
					end
				else
	 			templateFillArray[localisation.txtTitle] = getLabelFundamental(key)
				answers=mw.wikibase.getBestStatements(key, 'P1630' )
				if (answers[1]) then								-- Only add url if the key has a url-format property
					url=answers[1].mainsnak.datavalue.value
					templateFillArray[localisation.txtUrl] = url_encode(string.gsub(url,"$1",url_decode(value[1].datavalue.value)))
					end
				end
			end
	end
	return isok,templateFillArray 
end

function processDatabaseSource_model(templateFillArray,idMainEntity,qid_Source)
	local txtLabelStatedIn=getLabelFundamental(qid_Source)
	local databaseproperty=mw.wikibase.getBestStatements(qid_Source,'P1687')
	local bHasDatabase=false
    local bFoundInDatabase=false
    local idDatabase=nil
    for keyDatabase, valueDatabase in pairs( databaseproperty ) do
    	bHasDatabase=true
		idDatabase=read(valueDatabase,'id')
		if not (idDatabase==nil) then
			databaseentity=mw.wikibase.getEntity( idDatabase )
			mainsnak=mw.wikibase.getBestStatements(idMainEntity,idDatabase )
			if (next(mainsnak)) then
				bFoundInDatabase=true
				thisid=mainsnak[1].mainsnak.datavalue.value
				thisid=url_decode(thisid)
				
				urlsnak=databaseentity:getBestStatements( 'P1630' )
				url=urlsnak[1].mainsnak.datavalue.value
				templateFillArray[localisation.txtUrl] = url_encode(string.gsub(url,"$1",thisid))

				if (templateFillArray[localisation.txtTitle]~=nil) then
					templateFillArray[localisation.txtTitle] = txtLabelStatedIn .. ': ' .. templateFillArray[localisation.txtTitle]
					else
					templateFillArray[localisation.txtTitle] = txtLabelStatedIn
					end
--				else
				break
				end
			end
    end
    if ((bHasDatabase==true) and (bFoundInDatabase==false)) then
		templateFillArray['error'] = true
		templateFillArray['error_text']=localisation.txtNoDataBaseId .. '[[' .. localisation.txtCategory .. ':' .. localisation.txtDBreferenceWithoutId .. ']]'
    end
	if (bHasDatabase==false) then
		templateFillArray[localisation.txtTitle] = txtLabelStatedIn 
		end
	return templateFillArray
end

function txtUnpackReference_model(frame,refs,qid,pid)
-- If there is no source then tbl is a string
	local txt=''
	local bNoRef=true
    for key, templateFillArray in pairs( refs ) do
    	bNoRef=false
    	-- Create a reference tag based on the content in the table
		--Increase reference counter
		p.iRefcounter=p.iRefcounter+1
		if (templateFillArray['error'] == true) then
				txtOneReference='<span style="color:#ff0000">' .. templateFillArray['error_text'] .. '</span>'
			else
			templateFillArray['error']=nil
			templateFillArray['error_text']=nil
			if ((templateFillArray[localisation.txtTitle] ~= nil)) then
				if (templateFillArray[localisation.txtUrl] ~= nil) then
					txtOneReference = frame:expandTemplate{ title = localisation.txtCiteweb , args =templateFillArray}
					else
					txtOneReference = frame:expandTemplate{ title = localisation.txtBookweb , args =templateFillArray}
					end
				else
				if (templateFillArray[localisation.txtUrl] ~= nil) then
					txtOneReference=templateFillArray[localisation.txtUrl]
					else 
					txtOneReference=txtNoTitleorUrl
					end
				end
			end

		if (frame['id']) then
			txtScopeIdentifier=frame['id'] .. frame:getTitle() .. '__' ..  p.objectMainId
			else
			txtScopeIdentifier=frame:getTitle() .. '__' ..  p.objectMainId
			end
	    if d[txtOneReference]~=nil then
	    	-- If reference already has been added
	    	result={name='wikidatabox'..txtScopeIdentifier .. '_' .. d[txtOneReference], content=txtOneReference}
		    else
	    	-- If reference not already added
	    	result={name='wikidatabox'..txtScopeIdentifier .. '_' .. p.iRefcounter, content=txtOneReference}
			d[txtOneReference]=p.iRefcounter
	    	end
    	txt=txt..frame:extensionTag("ref", result.content,{ name = result.name}) 
    end
    if (bNoRef) then
		rm.iSourcesMissing=rm.iSourcesMissing+1
		end

    if (qid and pid) then
    	txt= txt .. txtEditPen(qid,pid)
    	end
	return txt
end


return rm