Немає опису редагування
Немає опису редагування
Мітка: Ручний відкіт
 
(Не показані 23 проміжні версії цього користувача)
Рядок 1: Рядок 1:
local p = {}
local p = {}


--- Функція для виведення помилки на сторінку
-- ================================================
local function error_output(context, error_details)
-- КЕШУВАННЯ
    local safe_details = error_details or "N/A"
-- ================================================
    return string.format("<span style='color:red; font-weight:bold;'>[FD2 Error: %s. Details: %s]</span>",
        context or "Unknown Context", safe_details)
end


--- Видаляє вікі-посилання [[link|text]] і [[link]]
local page_cache = {}
local function clean_wikilinks(text)
    if not text then return nil end
    -- [[link|text]] -> text
    text = mw.ustring.gsub(text, "%[%[([^%]|]+)|([^%]]+)%]%]", "%2")
    -- [[link]] -> link
    text = mw.ustring.gsub(text, "%[%[([^%]]+)%]%]", "%1")
    return mw.text.trim(text)
end


----------------------------------------------------------------------
local function get_page_content(page_name)
-- ГОЛОВНИЙ ПАРСЕР ДЛЯ ГОРИЗОНТАЛЬНИХ ТАБЛИЦЬ
     if page_cache[page_name] then
----------------------------------------------------------------------
         return page_cache[page_name]
local function fetch_from_table(page_title, player_name, column_index)
   
     if not player_name or player_name == "" then
         return error_output("No Player Name", page_title)
     end
     end
      
      
     local title = mw.title.new(page_title)
     local title = mw.title.new(page_name)
     if not title or not title.exists then  
     if not title or not title.exists then
         return error_output("Page Missing", page_title)
        page_cache[page_name] = nil
         return nil
     end
     end
      
      
     local content = title:getContent()
     local content = title:getContent()
     if not content then
     page_cache[page_name] = content
        return error_output("Content Read Fail", page_title)
    return content
    end
end
   
 
    -- Знаходимо таблицю
-- ================================================
    local table_start = mw.ustring.find(content, "{|")
-- АВТОМАТИЧНЕ МЕНЮ СЕКЦІЙ
     local table_end = mw.ustring.find(content, "|}", table_start)
-- ================================================
   
 
    if not table_start or not table_end then
function p.section_menu(frame)
        return error_output("Table Missing", page_title)
     local page_name = frame.args.page or mw.title.getCurrentTitle().text
    end
     local content = get_page_content(page_name)
   
    local table_content = mw.ustring.sub(content, table_start, table_end + 1)
   
    -- Екрануємо спеціальні символи в імені гравця
     local escaped = mw.ustring.gsub(player_name, "([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%%1")
    local player_pattern = "%[%[" .. escaped .. "%]%]"
      
      
     -- Шукаємо рядки, які починаються з |-
     if not content then
    local rows = {}
        return ""
    for row in mw.ustring.gmatch(table_content, "|-\n(.-)\n|-") do
        table.insert(rows, row)
     end
     end
      
      
    -- Останній рядок (до |})
     local sections = {}
     local last_row = mw.ustring.match(table_content, "|-\n(.-)%s*|}")
    if last_row then
        table.insert(rows, last_row)
    end
      
      
    -- Обробляємо кожен рядок
     for line in mw.ustring.gmatch(content, "[^\n]+") do
     for _, row in ipairs(rows) do
        -- ТІЛЬКИ заголовки рівня 2: == Назва ==
         if mw.ustring.find(row, player_pattern) then
         if mw.ustring.match(line, "^==[^=]") and mw.ustring.match(line, "[^=]==$") then
            -- Розбиваємо рядок на комірки
             local section_name = mw.ustring.match(line, "^==%s*(.-)%s*==$")
             local cells = {}
           
            -- Видаляємо початковий |
            row = mw.ustring.gsub(row, "^%s*|%s*", "")
              
              
             -- Розбиваємо по ||
             if section_name and section_name ~= "" then
            for cell in mw.ustring.gmatch(row, "([^|]+)") do
                -- Виконуємо шаблони щоб отримати реальний текст
                 -- Пропускаємо порожні комірки від подвійних ||
                local processed = frame:preprocess(section_name)
                 local trimmed = mw.text.trim(cell)
                processed = mw.text.trim(processed)
                 if trimmed ~= "" then
               
                     table.insert(cells, trimmed)
                 -- Anchor
                 local anchor = mw.ustring.gsub(processed, " ", "_")
               
                 if processed ~= "" then
                     table.insert(sections, {
                        display = processed,
                        anchor = anchor
                    })
                 end
                 end
            end
           
            -- Повертаємо потрібну колонку
            if column_index <= #cells then
                return clean_wikilinks(cells[column_index])
            else
                return error_output("Column Out of Range",
                    string.format("Requested col %d, found %d cells", column_index, #cells))
             end
             end
         end
         end
     end
     end
      
      
     return error_output("Player Not Found", player_name)
     if #sections == 0 then
end
         return ""
 
----------------------------------------------------------------------
-- ФУНКЦІЇ, ЩО ВИКЛИКАЮТЬСЯ З ШАБЛОНУ
----------------------------------------------------------------------
function p.recruiter(frame)
    local name = frame.args.player
    -- Don't clean wikilinks - keep them for clickable links
    local title = mw.title.new("Гравці")
    if not title or not title.exists then  
         return error_output("Page Missing", "Гравці")
    end
   
    local content = title:getContent()
    if not content then
        return error_output("Content Read Fail", "Гравці")
     end
     end
      
      
     local table_start = mw.ustring.find(content, "{|")
     -- Будуємо HTML
     local table_end = mw.ustring.find(content, "|}", table_start)
     local html_parts = {}
   
    if not table_start or not table_end then
        return error_output("Table Missing", "Гравці")
    end
      
      
     local table_content = mw.ustring.sub(content, table_start, table_end + 1)
     table.insert(html_parts, '<div class="l-box" style="position:fixed; top:20px; left:20px; z-index:100; border-radius:16px; background-color:#23232c; width:220px; box-sizing:border-box; overflow:hidden;">')
    local escaped = mw.ustring.gsub(name, "([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%%1")
    local player_pattern = "%[%[" .. escaped .. "%]%]"
      
      
     local rows = {}
     table.insert(html_parts, '<div style="padding:15px 20px; font-weight:bold; font-size:15px; color:#fff; border-bottom:1px solid rgba(255,255,255,0.1);">Зміст</div>')
    for row in mw.ustring.gmatch(table_content, "|-\n(.-)\n|-") do
        table.insert(rows, row)
    end
      
      
    local last_row = mw.ustring.match(table_content, "|-\n(.-)%s*|}")
     for i, section in ipairs(sections) do
    if last_row then
         local border = ""
        table.insert(rows, last_row)
        if i < #sections then
    end
             border = "border-bottom:1px solid rgba(255,255,255,0.05);"
   
     for _, row in ipairs(rows) do
         if mw.ustring.find(row, player_pattern) then
            local cells = {}
            row = mw.ustring.gsub(row, "^%s*|%s*", "")
           
             for cell in mw.ustring.gmatch(row, "([^|]+)") do
                local trimmed = mw.text.trim(cell)
                if trimmed ~= "" then
                    table.insert(cells, trimmed)
                end
            end
           
            if 4 <= #cells then
                local raw = mw.text.trim(cells[4])
                if raw == "Відсутній" or raw == "-" then
                    return "Не вказано"
                end
                -- Return with wikilinks intact
                return raw
            end
         end
         end
    end
   
    return "Не вказано"
end
function p.date_added(frame)
    local name = frame.args.player
    local raw = fetch_from_table("Гравці", name, 3)
   
    if type(raw) == "string" and mw.ustring.find(raw, "Error") then
        return raw
    end
   
    if not raw then
        return "Невідомо"
    end
   
    -- Парсимо дату у форматі DD.MM.YYYY
    local day, month, year = mw.ustring.match(raw, "(%d+)%.(%d+)%.(%d+)")
   
    if day and month and year then
        -- Кінцева дата: 25.10.2024
        local end_date = os.time({year=2024, month=10, day=25})
        local start_date = os.time({year=tonumber(year), month=tonumber(month), day=tonumber(day)})
          
          
         local days_diff = math.floor((end_date - start_date) / 86400)
         table.insert(html_parts, string.format(
       
            '<div class="l-box-item" style="padding:12px 20px; %s">[[#%s|%s]]</div>',
        return string.format("%s (%d днів)", raw, days_diff)
            border, section.anchor, section.display
    end
        ))
   
    return raw
end
 
function p.prize_pool(frame)
    local name = frame.args.player
    local raw = fetch_from_table("Призовий_фонд", name, 2)
   
    if type(raw) == "string" and mw.ustring.find(raw, "Error") then
        return "0 ₴"
    end
   
    if raw then
        raw = mw.ustring.gsub(raw, "[^%d%s]", "")
        raw = mw.text.trim(raw)
     end
     end
      
      
     return (raw or "0") .. " ₴"
     table.insert(html_parts, '</div>')
end
 
function p.foundation(frame)
    local name = frame.args.player
    local raw = fetch_from_table("Фундація", name, 3)
   
    if type(raw) == "string" and mw.ustring.find(raw, "Error") then
        return "0 ₴"
    end
   
    if raw then
        raw = mw.ustring.gsub(raw, "[^%d%s]", "")
        raw = mw.text.trim(raw)
    end
   
    return (raw or "0") .. " ₴"
end
 
function p.finalist(frame)
    local name = frame.args.player
    local raw = fetch_from_table("Фіналіст", name, 3)
   
    if type(raw) == "string" and mw.ustring.find(raw, "Error") then
        return "0/9"
    end
      
      
     return raw or "0/9"
     return table.concat(html_parts, '\n')
end
end


return p
return p

Поточна версія на 10:24, 8 грудня 2025

Документацію для цього модуля можна створити у Модуль:FetchData2/документація

local p = {}

-- ================================================
-- КЕШУВАННЯ
-- ================================================

local page_cache = {}

local function get_page_content(page_name)
    if page_cache[page_name] then
        return page_cache[page_name]
    end
    
    local title = mw.title.new(page_name)
    if not title or not title.exists then
        page_cache[page_name] = nil
        return nil
    end
    
    local content = title:getContent()
    page_cache[page_name] = content
    return content
end

-- ================================================
-- АВТОМАТИЧНЕ МЕНЮ СЕКЦІЙ
-- ================================================

function p.section_menu(frame)
    local page_name = frame.args.page or mw.title.getCurrentTitle().text
    local content = get_page_content(page_name)
    
    if not content then
        return ""
    end
    
    local sections = {}
    
    for line in mw.ustring.gmatch(content, "[^\n]+") do
        -- ТІЛЬКИ заголовки рівня 2: == Назва ==
        if mw.ustring.match(line, "^==[^=]") and mw.ustring.match(line, "[^=]==$") then
            local section_name = mw.ustring.match(line, "^==%s*(.-)%s*==$")
            
            if section_name and section_name ~= "" then
                -- Виконуємо шаблони щоб отримати реальний текст
                local processed = frame:preprocess(section_name)
                processed = mw.text.trim(processed)
                
                -- Anchor
                local anchor = mw.ustring.gsub(processed, " ", "_")
                
                if processed ~= "" then
                    table.insert(sections, {
                        display = processed,
                        anchor = anchor
                    })
                end
            end
        end
    end
    
    if #sections == 0 then
        return ""
    end
    
    -- Будуємо HTML
    local html_parts = {}
    
    table.insert(html_parts, '<div class="l-box" style="position:fixed; top:20px; left:20px; z-index:100; border-radius:16px; background-color:#23232c; width:220px; box-sizing:border-box; overflow:hidden;">')
    
    table.insert(html_parts, '<div style="padding:15px 20px; font-weight:bold; font-size:15px; color:#fff; border-bottom:1px solid rgba(255,255,255,0.1);">Зміст</div>')
    
    for i, section in ipairs(sections) do
        local border = ""
        if i < #sections then
            border = "border-bottom:1px solid rgba(255,255,255,0.05);"
        end
        
        table.insert(html_parts, string.format(
            '<div class="l-box-item" style="padding:12px 20px; %s">[[#%s|%s]]</div>',
            border, section.anchor, section.display
        ))
    end
    
    table.insert(html_parts, '</div>')
    
    return table.concat(html_parts, '\n')
end

return p