Module:PersonPaperList

From MaRDI portal
Revision as of 12:25, 6 December 2023 by Tconrad (talk | contribs) (Created page with "-- This example builds a HTML table with the results of a SPARQL query. -- By default one column is used per SPARQL variable. -- If the second parameter is set to "true", the first two columns are combined into one column. local sparql = require('SPARQL') local mwHtml = require('mw.html') local p = {} function p.buildTableFromSparql(frame) -- mw.log("Calling buildTableFromSparql") local target1 = frame.args[1] or 'Q161115' -- Default value if not provided...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Overview

This Lua module is designed for use in a MediaWiki environment. It provides functionality to execute a SPARQL query and present its results in an HTML table format. The module is particularly tailored for generating tables from SPARQL query results, relevant to specific entities identified by a dynamic parameter.

Dependencies

  • SPARQL Module: Used to execute SPARQL queries.
  • mw.html Module: Utilized for generating HTML content, specifically tables.

Module Functions

buildTableFromSparql(frame)

Generates an HTML table based on the results of a SPARQL query.

Parameters
* frame: The frame object containing arguments passed to the module.
Behavior
* Extracts target1 from frame.args[1]. If target1 is not provided or is empty, the function returns "No records found".
* Constructs and executes a SPARQL query using the target1 value. The query retrieves publication dates and work details related to target1.
* Handles errors in SPARQL query execution and logs them.
* Converts the SPARQL query results (JSON format) into a Lua table.
* Generates an HTML table with predefined headers ("Publication", "Date of Publication") and returns it as a string.

trimAndLower(str)

Utility function for string manipulation.

Parameters
* str: The string to be processed.
Returns
* The trimmed and lowercased version of the input string.

convertJsonToTable(jsonResults)

Converts SPARQL query results in JSON format into a Lua table.

Parameters
* jsonResults: JSON object containing SPARQL query results.
Returns
* A Lua table representing the SPARQL query results.

createHtmlTableWithMergedCols(dataTable, headers)

Creates an HTML table from a Lua data table, with specific column handling.

Parameters
* dataTable: The data table from which the HTML table will be generated.
* headers: A table containing header names for the HTML table.
Behavior
* Generates an HTML table with provided headers.
* Merges the first two columns of data into a single column in the resultant HTML table.
* Skips the third column and includes subsequent columns in the HTML table.
* Returns the HTML table as a string.

Return Value

The module returns a table containing the converted information (publication name and date).

Usage Example

{{#invoke:ModuleName|buildTableFromSparql|Arguments}}

Replace ModuleName with the actual name of the module when invoking it in a MediaWiki template or page. Arguments should be replaced with the appropriate arguments as required by the module's functionality.


Note: For the Debug console, you can use this:

local mockFrame = { args = { 'Q161115'} }
p.buildTableFromSparql(mockFrame)

-- This example builds a HTML table with the results of a SPARQL query.
-- By default one column is used per SPARQL variable.
-- If the second parameter is set to "true", the first two columns are combined into one column.

local sparql = require('SPARQL')
local mwHtml = require('mw.html')

local p = {}

function p.buildTableFromSparql(frame)
	
	-- mw.log("Calling buildTableFromSparql")

    local target1 = frame.args[1] or 'Q161115' -- Default value if not provided

    local sparqlQuery = [[
PREFIX target1: <https://portal.mardi4nfdi.de/entity/]] .. target1 .. [[>
PREFIX wdt: <https://portal.mardi4nfdi.de/prop/direct/>
PREFIX wd: <https://portal.mardi4nfdi.de/entity/>

SELECT
  ?publication_date
  ?work ?workLabel (CONCAT("/work/", SUBSTR(STR(?work), 32)) AS ?workUrl)

WHERE {
  ?work wdt:P16 target1: .

  OPTIONAL {
    ?work wdt:P28 ?publication_datetime .
    BIND(xsd:date(?publication_datetime) AS ?publication_date)
  }
  
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}

ORDER BY DESC(?publication_date)
    ]]

	-- PHP function sparql.runQuery(query) is called
	-- mw.log("Executing SPARQL query: " .. sparqlQuery)

	local jsonResults = sparql.runQuery(sparqlQuery)

	if jsonResults and jsonResults.error then
    	mw.log("Error in SPARQL query: " .. tostring(jsonResults.error))
    	return nil
	end
	
	-- logging
	-- mw.log(sparqlQuery)
	-- mw.logObject(jsonResults)
	
	local headers = {}
	if jsonResults and jsonResults.head and jsonResults.head.vars then
		headers = jsonResults.head.vars
	end
	
	-- mw.logObject(headers)

	local dataTable = convertJsonToTable(jsonResults)
	return createHtmlTable(dataTable, headers)
end

function trimAndLower(str)
	if str == nil then return nil end
	str = str:gsub("^%s*(.-)%s*$", "%1")  -- Trim spaces from both ends
	return str:lower()  -- Convert to lowercase
end

function convertJsonToTable(jsonResults)
    local resultsTable = {}
    if jsonResults and jsonResults.results and jsonResults.results.bindings then
        local bindings = jsonResults.results.bindings
        for j = 1, #bindings do
            local row = {}
            for key, value in pairs(bindings[j]) do
                table.insert(row, value.value)
            end
            table.insert(resultsTable, row)
        end
    end
    return resultsTable
end

function createHtmlTable(dataTable, headers)
	local htmlTable = mwHtml.create('table')
	htmlTable:addClass('wikitable'):attr('border', '1')

	local headerRow = htmlTable:tag('tr')
	
    -- Static headers instead of dynamic ones
    -- Comment: Only 2 cols, because 1&2 are combined and 3rd is skipped
    headerRow:tag('th'):wikitext("Publication")
    headerRow:tag('th'):wikitext("Date of Publication")
	
	for _, row in ipairs(dataTable) do
		local dataRow = htmlTable:tag('tr')
		local combinedData = '[' .. row[1] .. ' ' .. row[2] .. ']'
		dataRow:tag('td'):wikitext(combinedData)
		
	-- add col 4 - IMPORTANT: col 3 is skipped
		for j = 4, #row do
			dataRow:tag('td'):wikitext(row[j])
		end
	end

	return tostring(htmlTable)
end

return p