Lompat ke isi

Modul:AutoRelated

Dokumentasi untuk modul ini dapat dibuat di Modul:AutoRelated/doc

local p = {}

function p.main(frame)
    local title = mw.title.getCurrentTitle()
    local wikitext = title:getContent() or ""
    
    local validLinks = {}
    local seen = {}
    
    -- Cari semua pola wikilink [[Judul Artikel]] di dalam wikitext
    for link in wikitext:gmatch("%[%[([^%]|#]+)%|?.-%]%]") do
        -- Bersihkan spasi dan pastikan bukan halaman spesial atau halaman diri sendiri
        link = mw.text.trim(link)
        if link ~= title.text and not link:find(":") then
            local targetTitle = mw.title.new(link)
            
            -- Validasi ketat:
            -- 1. Halaman harus ada (exists)
            -- 2. Bukan halaman pengalihan (not isRedirect) -> Mencegah redirect page terpilih!
            -- 3. Belum pernah dimasukkan (not seen)
            if targetTitle and targetTitle.exists and not targetTitle.isRedirect and not seen[link] then
                seen[link] = true
                table.insert(validLinks, link)
            end
        end
    end
    
    -- Jika tidak ada link valid, kembalikan kosong
    if #validLinks == 0 then
        return ""
    end
    
    -- Acak (shuffle) array secara stabil berdasarkan ID halaman
    math.randomseed(os.time() + title.id)
    for i = #validLinks, 2, -1 do
        local j = math.random(i)
        validLinks[i], validLinks[j] = validLinks[j], validLinks[i]
    end
    
    -- Ambil maksimal 3 link
    local result = ""
    local count = math.min(3, #validLinks)
    for i = 1, count do
        result = result .. "{{#related:" .. validLinks[i] .. "}}\n"
    end
    
    return frame:preprocess(result)
end

return p