Дакументацыю да гэтага модуля можна стварыць у Модуль:Wikidata/media/Дакументацыя

local p = {}

-- Канстанты
local contentLanguageCode = mw.getContentLanguage():getCode();

function p.formatCommonsCategory( context, options, value )
    local link = 'commons:Category:' .. value
    local title = value .. ' на Вікісховішчы'
    if ( options['text'] and options['text'] ~= '' ) then
    	title = options['text']
    end

	commons = '[[' .. link .. '|' .. title .. ']]'

	--Commons icon
    if ( not options['icon'] or options['icon'] ~= '-' ) then
    	local icon_size = '15px'
    	if ( options['icon_size'] and options['icon_size'] ~= '' ) then
    		icon_size = options['icon_size']
    	end
    	commons = '[[File:Commons-logo.svg|' .. icon_size .. '|link=' .. link .. '|alt=Лагатып Вікісховішча]] ' .. commons
    end

	--Text before and after link
    if ( options['text_before'] and options['text_before'] ~= '' ) then
    	if ( options['text_before'] ~= '-' ) then
	    	commons = options['text_before'] .. ' ' .. commons
	    end
    end

    if ( options['text_after'] and options['text_after'] ~= '' ) then
    	if ( options['text_after'] ~= '-' ) then
	    	commons =  commons .. ' ' .. options['text_after']
	    end
    end
	
    return commons
end

local config;

local function getCategoryByCode( code, sortkey )
	if config == nil then
		config = require( 'Module:Wikidata/config' );
	end;

	local value = config[ 'categories' ][ code ];
	if not value or value == '' then
		return '';
	end
	
	return '[[Category:' .. value .. ']]';
end

local function getLabelWithLink( entityId, label, options, labelLanguageCode  )
	local category = ''
	-- атрыманне спасылкі па ідэнтыфікатары
	local link = mw.wikibase.sitelink( entityId )
	if link then
		if mw.ustring.match( link, '^' .. mw.site.namespaces[ 14 ].name .. ':' ) then
			link = ':' .. link
		end
		if label and not options.rawArticle then
			local a = link == label and ('[[' .. link .. ']]') or '[[' .. link .. '|' .. label .. ']]';
			if ( contentLanguageCode ~= labelLanguageCode ) then
				return a .. getCategoryByCode( 'links-to-entities-with-missing-local-language-label' ) .. category;
			else
				return a .. category;
			end
		else
			return '[[' .. link .. ']]' .. category;
		end
	end

	if label then
		-- чырвоная спасылка
		-- TODO: разабрацца, чаму не заўсёды ёсць options.frame
		local title = mw.title.new( label );
		if title and not title.exists and options.frame then
			if ( contentLanguageCode ~= labelLanguageCode and 'mul' ~= labelLanguageCode ) then
				category = category .. getCategoryByCode( 'links-to-entities-with-missing-local-language-label' );
			end
			return '[[' .. label .. ']]<sup>[[:d:' .. entityId .. '|[d]]]</sup>' .. category;
		end

		-- TODO: перанесці да праверкі на існаванне артыкула
		local sup = '';
		if ( not options.format or options.format ~= 'text' )
				and entityId ~= 'Q6581072' and entityId ~= 'Q6581097' -- TODO: перапісаць на format=text
				then
			sup = '<sup class="plainlinks noprint">[//www.wikidata.org/wiki/' .. entityId .. '?uselang=' .. contentLanguageCode .. ' [d&#x5d;]</sup>'
		end

		-- аднайменны артыкул ужо існуе - выводзіцца тэкст і спасылка на ВД
		return '<span class="iw" data-title="' .. label .. '">' .. label
			.. sup
			.. '</span>' .. category
	end
	-- паведамленне пры адсутнасці лакалізаванай назвы
	-- not good, but better than nothing
	return '[[:d:' .. entityId .. '|' .. entityId .. ']]<span style="border-bottom: 1px dotted; cursor: help; white-space: nowrap" title="У Вікіданых няма беларускага подпісу да элемента. Вы можаце дапамагчы, паказаўшы беларускі варыянт подпісу.">?</span>' .. getCategoryByCode( 'links-to-entities-with-missing-label' ) .. category;
end
	
local function getCaption( context, options )
	local caption = ''
	local labelLanguageCode = contentLanguageCode;
	if options.qualifiers and options.qualifiers.P2096 then
		for i, qualifier in pairs( options.qualifiers.P2096 ) do
			if ( qualifier
					and qualifier.datavalue
					and qualifier.datavalue.type == 'monolingualtext'
					and qualifier.datavalue.value
					and qualifier.datavalue.value.language == contentLanguageCode ) then
				caption = qualifier.datavalue.value.text
				break
			end
		end
	end
	if (options.property == 'p94') then
		if (options.entity and options.entity.claims.P237) then
			local entityId = options.entity.claims.P237[1].mainsnak.datavalue.value.id
         	if not (caption and caption ~= '') then
         	    local locallabel, locallabelLanguageCode =  mw.wikibase.getLabelWithLang( entityId )
         		caption = locallabel
         		labelLanguageCode = locallabelLanguageCode
         	end	
	        caption = getLabelWithLink( entityId, caption, options, labelLanguageCode )
		end
	end
	if options['appendTimestamp'] and options.qualifiers and options.qualifiers.P585 and options.qualifiers.P585[1] then
		local moment = context.formatValueDefault( context, options, options.qualifiers.P585[1].datavalue )
		if not caption or caption == ''  then 
			caption = moment
		else
			caption = caption .. ', ' .. moment
		end
	end

	local localValue = '';
	if options[ 'value' ] and options[ 'value' ] ~= '' then
		localValue = options[ 'value' ];
	end
	
	local localCaption = '';
	if options[ 'caption' ] and options[ 'caption' ] ~= '' then
		localCaption = options[ 'caption' ];
	end
	
	if options[ 'nocaption' ] and options[ 'nocaption' ] ~= '' then
		caption = '';
	end
	
	if localValue ~= '' then
		caption = localCaption;
	end
	
	local formattedCaption = ''
	if caption ~= '' then
		formattedCaption = context.wrapQualifier( caption, 'P2096', { class = 'media-caption', style = 'display:block' } );
	end

	if localValue == '' and localCaption ~= '' then
		formattedCaption = formattedCaption .. getCategoryByCode( 'media-contains-local-caption' )
		if options.frame:preprocess('{{REVISIONID}}') == '' then
			formattedCaption = formattedCaption .. '<span class="error" style="font-size:94%;">Лакальны подпіс не ўжываецца, бо выява бярэцца з Вікіданых</span>'
		end
	end

	return caption, formattedCaption
end

function p.formatCommonsMediaValue( context, options, value )
	local image = value;
	local caption, formattedCaption = getCaption( context, options )
	
	if not string.find( value, '[%[%]%{%}]' ) and not string.find( value, 'UNIQ%-%-imagemap' ) then
		image = '[[File:' .. value .. '|frameless';
		if options[ 'border' ] and options[ 'border' ] ~= '' then
			image = image .. '|border';
		end

		local size = options[ 'size' ];
		if size and size ~= '' then
			if not string.match( size, 'px$' )
				and not string.match( size, 'пкс$' )
			then
				size = size .. 'px'
			end
			
			if string.match( size, 'pxpx' ) then
				image = '[[Катэгорыя:Вікіпедыя:Выява з pxpx у памеры]]' .. image
			end
		else
			size = fileDefaultSize;
		end
		image = image .. '|' .. size;

		if options[ 'alt' ] and options[ 'alt' ] ~= '' then
			image = image .. '|alt=' .. options[ 'alt' ];
		end
		
		if caption ~= '' then
			image = image .. '|' .. caption
		end
		image = image .. ']]';

		if formattedCaption ~= '' then
			image = image .. '<br>' .. formattedCaption;
		end
	else
		image = image .. formattedCaption .. getCategoryByCode( 'media-contains-markup' );
	end
	
	if options.entity and options.fixdouble then
		local page = mw.title.getCurrentTitle()
		local txt = page:getContent()
		if txt and txt:match(':' .. value) and mw.title.getCurrentTitle():inNamespace(0) then
			if options.frame:preprocess('{{REVISIONID}}') == '' then
				image = image .. '<span class="error">Гэта выява сустракаецца ніжэй па тэксце артыкула; калі ласка, прыбярыце адну з копій (не згубіўшы пры гэтым подпіс)</span>'
			end
			image = image .. getCategoryByCode( 'media-contains-local-double' )
		end
	end
	
	return image
end

return p