MediaWiki:Common.js

Материал из Абсурдопедии
Перейти к навигации Перейти к поиску

Замечание: Возможно, после публикации вам придётся очистить кэш своего браузера, чтобы увидеть изменения.

  • Firefox / Safari: Удерживая клавишу Shift, нажмите на панели инструментов Обновить либо нажмите Ctrl+F5 или Ctrl+R (⌘+R на Mac)
  • Google Chrome: Нажмите Ctrl+Shift+R (⌘+Shift+R на Mac)
  • Edge: Удерживая Ctrl, нажмите Обновить либо нажмите Ctrl+F5
  • Opera: Нажмите Ctrl+F5.
/* Нигилистические фокусы (см. шаблон {{Нигилизм}}) */
$(function () {
    var nihilism = $('#nihilism');
    if (nihilism[0] && !document.location.href.match("diff")) {
        var msg = nihilism.html();
        if (!nihilism.hasClass('nihilism-no-white')) {
        	$('body').css('background-color', 'white');
        }
        var scripts = $('script');
        var bodyNihilism = $('body').html('');
        var divNihilism = $('<div class="mw-parser-output"></div>').html(msg);
        if (nihilism.css('top') == '0px') {
        	bodyNihilism.css('top', '0px').css('left', '0px');
        }
        bodyNihilism.append(divNihilism).append(scripts);
        $(document).dblclick(function () {
        	window.location = mw.util.getUrl(null, {'action': 'edit'});
        });
    }
});

/* Стирание памяти для [[MIB]] («Людей в чёрном») */
$(function () {
    if ($("#erase_memory")[0])
        setTimeout(function () { $("#erase_memory").hide(); }, 20000);
});

/* Ссылка «править» для нулевой секции */
$(function () {
    var zeroSectionTip = "Править введение";

    if (!mw.config.get("wgArticleId")) {
        return;
    }

    var action = mw.config.get("wgAction");
    if (action != "view" && action != "purge")
        return;

    mw.util.$content.find("h2").children(".mw-editsection:first").clone().prependTo("#bodyContent").css("float", "right").find("a").each(function (index) {
        $(this).attr("title", zeroSectionTip);
        if ($(this).attr("class") === "mw-editsection-visualeditor") {
            $(this).attr("href", mw.config.get("wgScript") + "?title=" + mw.util.wikiUrlencode(mw.config.get("wgPageName")) + "&veaction=edit&vesection=0&summary=/*%20Преамбула%20*/%20");
        } else {
            $(this).attr("href", mw.config.get("wgScript") + "?title=" + mw.util.wikiUrlencode(mw.config.get("wgPageName")) + "&action=edit&section=0&summary=/*%20Преамбула%20*/%20");
        }
    });
});

/* Вставка юзернейма с помощью <span class="insertusername"></span> */
$(function () {
    if ((typeof (disableUsernameReplace) == "undefined" || !disableUsernameReplace) && mw.config.get("wgUserName") !== null) {
        var username = mw.config.get("wgUserName");
        $("span.insertusername").text(username);
    }
});


/* Замена категорий для шаблона {{Cats}} */
$(function () {
    var categoriesAlternative = $("#categories_alternative");
    if (categoriesAlternative[0]) {
        $('#mw-normal-catlinks').html(categoriesAlternative.html());
        categoriesAlternative.hide();
    }
});


/* Функция для вставки VK-видео на страницу для шаблона {{VKVideo}} */
(function() {
    'use strict';
    
    function initVKVideo() {
        var containers = document.querySelectorAll('.vk-video-js');
        
        for (var i = 0; i < containers.length; i++) {
            var container = containers[i];
            var oid = container.getAttribute('data-oid');
            var id = container.getAttribute('data-id');
            var width = container.getAttribute('data-width') || '560';
            var height = container.getAttribute('data-height') || '315';
            
            if (oid && id && oid !== 'null' && id !== 'null' && 
                /^[-_a-zA-Z0-9]+$/.test(oid) && /^[-_a-zA-Z0-9]+$/.test(id)) {
                
                var iframe = document.createElement('iframe');
                iframe.src = 'https://vk.com/video_ext.php?oid=' + encodeURIComponent(oid) + '&id=' + encodeURIComponent(id);
                iframe.width = width;
                iframe.height = height;
                iframe.frameBorder = '0';
                iframe.allowFullscreen = true;
                iframe.style.border = 'none';
                
                while (container.firstChild) {
                    container.removeChild(container.firstChild);
                }
                container.appendChild(iframe);
                
            } else {
                var errorDiv = document.createElement('div');
                errorDiv.style.cssText = 'color: red; padding: 10px; text-align: center; border: 1px solid red;';
                errorDiv.textContent = 'Ошибка: неверные параметры видео';
                
                while (container.firstChild) {
                    container.removeChild(container.firstChild);
                }
                container.appendChild(errorDiv);
            }
        }
    }
    
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initVKVideo);
    } else {
        initVKVideo();
    }
})();


/* Функция для вставки Rutube-видео на страницу для шаблона {{Rutube}} */
(function() {
    'use strict';

    function sanitizeVideoId(videoId) {
        if (typeof videoId !== 'string') return null;
        // Разрешаем только буквы, цифры и дефисы/подчеркивания
        return videoId.match(/^[a-zA-Z0-9_-]+$/) ? videoId : null;
    }
    
    function sanitizeDimension(dim, defaultValue, maxValue) {
        if (typeof dim !== 'string') return defaultValue;
        const cleanDim = dim.match(/^(100|\d{1,2})%$|^\d+$/) ? dim : defaultValue;
        
        if (cleanDim.match(/^\d+$/)) {
            const numValue = parseInt(cleanDim, 10);
            return numValue <= maxValue ? cleanDim : defaultValue;
        }
        
        return cleanDim;
    }
    
    function initRutubeEmbeds() {
        var embeds = document.querySelectorAll('.rutube-video-embed:not([data-processed])');
        
        embeds.forEach(function(embed) {
            var rawVideoId = embed.getAttribute('data-video-id');
            var videoId = sanitizeVideoId(rawVideoId);
            
            if (!videoId) {
                console.warn('Invalid video ID:', rawVideoId);
                embed.setAttribute('data-processed', 'true');
                return;
            }
            
            var width = sanitizeDimension(embed.getAttribute('data-width'), '560', 2000);
            var height = sanitizeDimension(embed.getAttribute('data-height'), '315', 2000);
            
            var iframe = document.createElement('iframe');
            
            iframe.src = 'https://rutube.ru/play/embed/' + encodeURIComponent(videoId);
            iframe.width = width;
            iframe.height = height;
            iframe.frameBorder = '0';
            iframe.allow = 'autoplay; fullscreen; picture-in-picture';
            iframe.allowFullscreen = true;
            iframe.style.border = 'none';
            iframe.style.display = 'block';
            iframe.style.maxWidth = '100%';
            
            iframe.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-presentation allow-popups');
            iframe.setAttribute('referrerpolicy', 'strict-origin-when-cross-origin');
            
            while (embed.firstChild) {
                embed.removeChild(embed.firstChild);
            }
            
            embed.appendChild(iframe);
            embed.setAttribute('data-processed', 'true');
        });
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initRutubeEmbeds);
    } else {
        initRutubeEmbeds();
    }
    
    if (typeof mw !== 'undefined' && mw.hook) {
        mw.hook('wikipage.content').add(initRutubeEmbeds);
    }
})();