وحدة:Header

من ويكي مصدر، المكتبة الحرة
local p = {}
local Wikidata = require('وحدة:WikidataIB')
local Entity  = mw.wikibase.getEntityObject() or ''

local lang = mw.language.new('ar')
local categorys = ''
local params ={['عنوان']=1,['عنوان فرعي']=1, ['سنة']=1, ['مؤلف']=1, ['سابقة المؤلف']=1, ['معلومات إضافية']=1,['سابق']=1,
	['مترجم'] = 1,  ['رسام'] = 1, ["ثنائي اللغة"] = 1, ['روابط']=1, ['ملاحظات'] = 1 , ['حقوق'] = 1 ,
	['بدون سنة'] = 1 , ['فصل']=1,['باب']=1,['مؤلف الباب']=1,['تالي']=1,['آخر وفاة']=1,['توضيح']=1,
	['تاريخي']=1,['كتالوج']=0,['ويكيبيديا'] = 1 , ['كومنز'] = 1 , ['تصنيف كومنز'] = 1 ,
	['ويكي الاقتباس'] = 1 , ['ويكي الأخبار'] = 1 , ['ويكاموس'] = 1 , ['ويكي الكتب'] = 1 ,
	['ويكي الجامعة'] =1, ['ويكي أنواع'] =1 , ['ميتا'] = 1 , ['ويكي بيانات'] =1, ['مصدر']=1}

local page_title = mw.title.getCurrentTitle().text
local encoded_page_title= mw.uri.encode(page_title, QUERY)

local altparams= {
	['العنوان'] = 'عنوان',
	['المؤلف'] ='مؤلف',
	['السابق'] = 'سابق',
	['المترجم'] = 'مترجم',
	['الملاحظات'] = 'ملاحظات',
	['الباب'] = 'باب',
	['باب فرعي'] = 'فصل',
	['التالي'] = 'تالي',
	['لاحق'] = 'تالي',
	['اللاحق'] = 'تالي',
	['المصدر'] = 'مصدر'
	}

local function errorMessage(text)
	-- Función que entrega un mensaje de error formateado como tal
	local html = mw.html.create('div')
	html:addClass('error')
		:wikitext(text)
	categorys=categorys..'[[تصنيف:ويكي مصدر:صفحات تحوي أخطاء في قالب ترويسة]]'
	return tostring(html)
end

local function link(s)
	if s:match("%[") then
		return s
	else
		return '[[مؤلف:'..s..'|'..s..']]'
	end
end

local function delink(s)
	if not s:match("%[") then
		return s
	end
	local result = s
	
	result = mw.uri.decode(result, "PATH") -- decode percent-encoded entities. Leave underscores and plus signs.
	result = mw.text.decode(result, true) -- decode HTML entities.
  
	-- Remove the colon if the link is using the [[Help:Colon trick]].
	if result:match("%[%[:") then
		result = "[[" .. result:match("%[%[:(.*%]%])")
	end
   
	-- Find the display area of the wikilink
	if result:match("|") then -- Find if we're dealing with a pipecd link.
		result = result:match("%[%[.-%|(.+)%]%]")
		-- Remove new lines from the display of multiline piped links,
		-- where the pipe is before the first new line.
		result = result:gsub("\n", "")
	else	 
		result = result:match("%[%[(.-)%]%]")

	end

	return result
end

local function createlink(args, number, image, text1, text2)
	local text=''
	local site =''
	local sites ={ --esta variable contiene los sites reconocidos con posibles enlaces, y su number técnico
		['ويكيبيديا']= {'ويكيبيديا','w:'},
		['ويكي الاقتباس']={'ويكي الاقتباس','q:'},
		['تصنيف كومنز']={'كومنز','commons:'},
		['ويكي أنواع']={'ويكي أنواع','species:'},
		['ويكي بيانات']={'ويكي بيانات','d:'},
		['ويكاموس']={'ويكاموس','wikt:'},
		}
	
	if args[number] == 'none' then
		return ''
	end
	if sites[number] then
		site = sites[number]
	end
	if args[number] and args[number] ~= '' then
		if image == '' then
			text = '[['..text1..'|'..text2..']].   '
		else
			text = '[[ملف:'..image..'|16px]] '..'[['..text1..'|'..text2..']].   '	
		end
	elseif site~='' and Entity ~= '' then
		if site[1] == 'ويكي بيانات' then
			args[number] = site[2]..mw.wikibase.getEntityIdForCurrentPage()
			text =  '[[ملف:'..image..'|16px]] '..'[['..args[number]..'|'..text2..']].   '	
		elseif Entity:getSitelink(site[1]) ~= nil and Entity:getSitelink(site[1]) ~= '' then
			args[number] = site[2]..Entity:getSitelink(site[1])
			text =  '[[ملف:'..image..'|16px]] '..'[['..args[number]..'|'..text2..']].   '	
		elseif site[1] =='commonswiki' and propiedad('p373') ~= '' then --categoría en commons
			text =  '[[ملف:'..image..'|16px]] '..'[[commons:Category:'..propiedad('p373')..'|'..text2..']].   '	
		end
	end
	return text
end

local function linkMicroformat(param, value)
	if value~= nil and value ~= '' then
		return mw.html.create('span')
		:addClass('ws-' .. param)
		:wikitext(delink(value))	
	else 
		return ''
	end
end

function p.header( frame ) 
	local title = mw.title.getCurrentTitle()
	local issub = title.isSubpage
	
	local args={}
	for k,v in pairs(frame:getParent().args) do -- crea una tabla con los parámetros incluídos en la plantilla, y elimina parámetros vacíos
		if v ~= '' then
			args[mw.ustring.lower(tostring(k))] = v -- todos los parámetros en minúsculas por defecto: 
		end
	end

	-- HTML
	local html = mw.html.create()

	for k,v in pairs(altparams) do
		if args[k] and not args[v] then
			args[v] = args[k]
		elseif args[k] and args[v] then
			if frame:preprocess( "{{REVISIONID}}" ) == "" then
				html:wikitext(errorMessage('خطأ: الوسائط |'.. k ..' = '.. v ..' زائة عن الحاجة.'))
			end
			categorys=categorys..'[[تصنيف:ويكي مصدر:صفحات تستخدم وسائط زائدة في قالب ترويسة]]'
		end
	end

	--variables matemática derechos de autor
	local death_year
	local pub_year
	if args['سنة'] and tonumber(args['سنة']) ~= nil  then
		pub_year = tonumber(lang:formatDate('Y')) - tonumber(args['سنة'])
	end
	if args['آخر وفاة'] and tonumber(args['آخر وفاة']) ~= nil then
		death_year = tonumber(lang:formatDate('Y')) - tonumber(args['آخر وفاة'])
	end
	
	
	local divgrande = html:tag('div'):attr('id','headertemplate'):addClass('noprint ws-noexport') -- div principal que contiene al resto
	local prev = divgrande:tag('div'):attr('id','headerprevious')
	if args['سابق'] and args['سابق'] ~= '' then
		local anteriorspan = prev:tag('span'):addClass('prev-span')
		if not mw.ustring.find(args['سابق'],"→") then
			anteriorspan:tag('span'):addClass('prev-span-arrow'):wikitext(' →')
		end
		anteriorspan:wikitext(' '..args['سابق'])
		if args['روابط'] and mw.ustring.lower(args['روابط']) == 'no' then
			anteriorspan:cssText('display:none')
		end
	end
	
	local medio = divgrande:tag('div'):addClass('middle-div')
	if args['عنوان'] then
		medio:wikitext("'''''​"..args['عنوان'].."​'''''")
		if args['عنوان فرعي'] then
			medio:wikitext('<br/>'..'<small>'..args['عنوان فرعي']..'</small>')	
		end
		if args['سنة'] and not args['بدون سنة'] then
			medio:wikitext('&nbsp;('..args['سنة']..')')
			categorys = categorys..'[[تصنيف:P'..args['سنة']..']]'
		end
	end
	
	if args['مؤلف'] then
		local pre_author=args['سابقة المؤلف'] or "المؤلف"
		medio:wikitext('&nbsp;' .. pre_author .. '&nbsp;')
		local i = #mw.text.split(args['مؤلف'], '[/,]')
		for _,v in ipairs(mw.text.split(args['مؤلف'], '[/,]')) do
			i = i-1
			medio:wikitext(link(v))
			if i >0 then medio:wikitext(',&nbsp;') end
		end
	end
	medio:tag('br')
	if args['مترجم'] and args['مترجم'] ~= '' then
		if args['مترجم'] == 'ويكي مصدر' then
			medio:wikitext('ترجمة [[مساعدة:إرشادات للترجمات| ويكي مصدر]]')
		else 
			medio:wikitext('ترجمة')
			local i = #mw.text.split(args['مترجم'], '[/,]')
			for _,v in ipairs(mw.text.split(args['مترجم'], '[/,]')) do
				i = i-1
				medio:wikitext(link(v))
				if delink(v) == 'مجهول' then
					v = 'مؤلف مجهول'
				end
				categorys = categorys..'[[تصنيف:ترجمات '..delink(v)..']]'
				if i >0 then medio:wikitext(',&nbsp;') end
			end
		end
		medio:tag('br')
	end
	if args['رسام'] and args['رسام'] ~= '' then
		medio:wikitext('رسومات '..link(args['رسام']))
		medio:tag('br')
	end
	if args['معلومات إضافية'] then
		medio:wikitext(args['معلومات إضافية'])
		medio:tag('br')
	end
	
	if args['فصل'] and not args['باب'] then
		args['باب'] = args['فصل']
		args['فصل'] = nil
	end

	if args['باب'] then
		medio:wikitext("''"..args['باب'].."''")
		if args['مؤلف الباب'] then
			medio:wikitext('&nbsp;de&nbsp;')
			local i = #mw.text.split(args['مؤلف الباب'], '[/,]')
			for _,v in ipairs(mw.text.split(args['مؤلف الباب'], '[/,]')) do
				i = i-1
				medio:wikitext(link(v))
				if i >0 then medio:wikitext(',&nbsp;') end
			end
		end
   		if args['فصل'] then
   			medio:tag('br')
   			medio:tag('span'):cssText('font-size: 83%;'):wikitext(args['فصل'])
   		end
	end
	local proximo = divgrande:tag('div'):attr('id','headernext')
	if args['تالي'] and args['تالي']~= '' then
		local proximospan = proximo:tag('span'):addClass('next-span')
			:wikitext(' '..args['تالي'])
		if not mw.ustring.find(args['تالي'],"←") then
			proximospan:tag('span'):addClass('next-span-arrow'):wikitext('← ')
		end
				
		if args['روابط'] and mw.ustring.lower(args['روابط']) == 'no' then
			proximospan:cssText('display:none')
		end
	end
	--enlaces pequeños en la parte inferior
	
	inferior = medio:tag('div'):addClass('noprint plainlinks lower-div')
	
	--matematica y manejo derechos de autor
	if args['حقوق'] then
		inferior:wikitext('[[ملف:PD-icon.svg|14px]]&nbsp;[[ويكي مصدر:Duración de derechos de autor por país#'..args['حقوق']..'|'..args['حقوق']..']]&nbsp;&nbsp;&nbsp;') 
		if args['آخر وفاة'] == 'اسم مستعار' then
			num = math.floor((pub_year - 1)/10)
			if num > 10 then num = 10 end
			inferior:wikitext(', [[ويكي مصدر:مدة حقوق الطبع والنشر حسب البلد#'..tostring(num*10)..' p.a.p.|'..tostring(num*10)..' p.a.p. o menos]].&nbsp;&nbsp;&nbsp;')
			categorys = categorys..'[[تصنيف:'..tostring(num*10)..' p.a.p.]]'
		elseif args['آخر وفاة'] then
			num = math.floor((death_year - 1)/10)
			if num > 4 then --a partir de 50 p.m.a.
				if num > 10 then num = 10 end
				inferior:wikitext(', [[ويكي مصدر:مدة حقوق الطبع والنشر حسب البلد#'..tostring(num*10)..' p.m.a.|'..tostring(num*10)..' p.m.a. o menos]].&nbsp;&nbsp;&nbsp;')
				categorys = categorys..'[[تصنيف:'..tostring(num*10)..' p.m.a.]]'
			end
		end
		categorys = categorys..'[[تصنيف:نشر في '..args['حقوق']..']]'
	end

	--enlaces parte inferior
	inferior:wikitext(createlink(args, 'ويكي بيانات', 'Wikidata-logo.svg', 'd:' .. (args['ويكي بيانات'] or ''),'ويكي بيانات'))
	inferior:wikitext(createlink(args, 'توضيح', 'Disambiguation.svg', args['توضيح'],'إصدارات أخرى أو عناوين مشابهة'))
	inferior:wikitext(createlink(args, 'ويكيبيديا','Wikipedia-logo.svg','w:'..(args['ويكيبيديا'] or ''),'مقالة ويكيبيديا'))
	inferior:wikitext(createlink(args, 'تصنيف كومنز','Commons-logo.svg','commons:Category:'..(args['تصنيف كومنز'] or ''),'تصنيف وسائط'))
	inferior:wikitext(createlink(args, 'ويكي الاقتباس','Wikiquote-logo.svg','q:'..(args['ويكي الاقتباس'] or ''),'اقتباس'))
	inferior:wikitext(createlink(args, 'ويكي الكتب','Wikibooks-logo.svg','b:'..(args['ويكي الكتب'] or ''),'كتاب'))
	inferior:wikitext(createlink(args, 'ويكي الجامعة','Wikiversity-logo.svg','v:'..(args['ويكي الجامعة'] or ''),'جامعة'))
	inferior:wikitext(createlink(args, 'ويكي أنواع','Wikispecies-logo.svg','species:'..(args['ويكي أنواع'] or ''),'النوع'))
	inferior:wikitext(createlink(args, 'ويكاموس','Wiktionary_small-es.svg','wikt:'..(args['ويكاموس'] or ''),'ويكاموس'))
	
	if args['ثنائي اللغة'] and args['ثنائي اللغة'] ~= '' then
		inferior:wikitext('['..title:fullUrl({['match']=args['ثنائي اللغة']})..' نص ثنائي اللغة]')
	end
	
	--Enlaces de descarga
	if not issub then
		inferior:wikitext("<div style=\"font-size:80%\">تحميل بصيغة &nbsp;[[ملف:EPUB silk icon.svg|12px|link=https://wsexport.toolforge.org/tool/book.php?lang=ar&format=epub&page=" .. encoded_page_title .."|تحميل بصيغة epub]]&nbsp;[[ملف:Document-pdf.svg|15px|link=https://wsexport.toolforge.org/tool/book.php?lang=ar&page=" .. encoded_page_title .. "&format=pdf-a5|تحميل بصيغة pdf]]&nbsp;[[ملف:Mobi_icon.svg|22px|link=https://wsexport.toolforge.org/tool/book.php?lang=ar&page=" .. encoded_page_title .. "&format=mobi|تحميل بصيغة mobi]]</div>")
	end 

	if args['مصدر'] and args['مصدر'] ~= '' then
		html:tag('div'):addClass('notes noprint ws-noexport'):wikitext("'''المصدر:''' "..args['مصدر']):tag('hr')
	end
	if args['ملاحظات'] and args['ملاحظات'] ~= '' then
		html:tag('div'):addClass('notes noprint ws-noexport'):wikitext("'''ملاحظات:''' "..args['ملاحظات']):tag('hr')
	end
	--categorías automáticas
	

	-- if not issub then
	-- 	categorys = categorys..'[[تصنيف:ES-'..Str.CaracterParaOrdenar(title.subpageText)..']]'
	-- else
	-- 	categorys = '[[تصنيف:'..title.rootText..']]'
	-- end
	--palabra mágica, subpáginas no deben estar conectadas normalmente a Wikidata
	if issub then
		html:wikitext('__EXPECTED_UNCONNECTED_PAGE__')
	end
	
	for k,v in pairs(args) do
		if params[k] or altparams[k] then
			if params[k] == 0 then
				categorys = categorys..'[[تصنيف:ويكي مصدر:صفحات تستخدم وسائط قديمة في قالب ترويسة ]]' --añade categoría de seguimiento a parámetros obsoletos (declarados arriba)
			end
		else
			html:wikitext(errorMessage('خطأ: الوسيط '..k..' غير معروف'))
			categorys=categorys..'[[تصنيف:ويكي مصدر:صفحات تستخدم وسائط قديمة في قالب ترويسة]]'
		end
	end
	if title.namespace ~= 0 then --solo categorías en el espacio principal
		categorys = ''	
	end
	
	divgrande:wikitext(categorys)

	--microformato
	local microformato = html:tag('div'):cssText('display:none'):attr('id', 'ws-data'):addClass('ws-noexport')
	microformato:node( linkMicroformat( 'title', args['عنوان'] ) )
	if args['مؤلف'] and args['مؤلف'] ~= '' then
		microformato:node( linkMicroformat( 'author', args['مؤلف'] ) )
	end
	if args['مترجم'] and args['مترجم'] ~= '' then
		microformato:node( linkMicroformat( 'translator', args['مترجم'] ) )
	end
	if args.illustrador and args.illustrador ~= '' then
		microformato:node( linkMicroformat( 'illustrator', args.illustrador ) )
	end
	--if args.school and args.school ~= '' then
	--	microformato:node( linkMicroformat( 'school', args.school ) )
	--end
	--if args.editeur and args.editeur ~= '' then
	--	microformato:node( linkMicroformat( 'publisher', args.editeur ) )
	--end
	if args['سنة'] and args['سنة'] ~= '' then
		microformato:node( linkMicroformat( 'year', args['سنة'] ) )
	end
	--if args.lieu and args.lieu ~= '' then
	--	microformato:node( linkMicroformat( 'place', args.lieu ) )
	--end
	if args.progreso and args.progreso ~= '' then
		microformato:node( linkMicroformat( 'progress', args.progreso ) )
	end
	--if args.volume and args.volume ~= '' then
	--	microformato:node( linkMicroformat( 'volume', args.volume ) )
	--end
	if args.current and args.current ~= '' then
		microformato:node( linkMicroformat( 'chapter', args.current ) )
	end
	if args.index then
		microformato:node( linkMicroformat( 'scan', args.index ) )
		if args.image and mw.ustring.match(args.image, '^%d+$') ~= nil then
			microformato:node( linkMicroformat( 'cover', args.index .. '/' .. args.image ) )
		end
	end
	if from ~= '' and to ~= '' then
		if from == to then
			microformato:node( linkMicroformat( 'pages', from ) )
		else
			microformato:node( linkMicroformat( 'pages', from .. '-' .. to ) )
		end
	end
	if args.wikipedia and args.wikipedia ~= '' then
		microformato:node( linkMicroformat( 'wikipedia', args.wikipedia ) )
	end
	if args.wikiquote and args.wikiquote ~= '' then
		microformato:node( linkMicroformat( 'wikiquote', args.wikiquote ) )
	end
	if args.commonscat and args.commonscat ~= '' then
		microformato:node( linkMicroformat( 'commons', args.commons ) )
	end
	


	return tostring(html)

end

-- Función que devuelve la lista de los valores de una propiedad en Wikidata formateados
function propiedad(idPropiedad,opciones)
	
	if Entity and Entity.claims   then --and Entity.claims[idPropiedad] then
		if not opciones then
			opciones = {}
		end
		opciones['propiedad'] = idPropiedad

		valorPropiedad = Wikidata.getPropiedad(opciones,Entity.claims[idPropiedad])
		
		if not valorPropiedad or valorPropiedad == '' then
			return ''
		end
		return valorPropiedad
	else return ''
	end
end

return p