MediaWiki:Gadget-blamefinder.js: различия между версиями

Нет описания правки
Нет описания правки
Строка 1: Строка 1:
/**
/**
  * Gadget: Blame Finder
  * Gadget: Blame Finder
  * Версия 1.5 с поддержкой ночного режима
  * Версия 2.0 с поддержкой ночного режима
  * Назначение: поиск автора любого текста в статье
  * Назначение: поиск автора любого текста в статье
  * Локализовано под Тестовую Вики
  * Локализация под wiki.peresvet.artushak.ru, лицензия: CC BY-SA 4.0
  * Использование:
  * Использование:
   1. Нажимаете кнопку «Кто автор?» в правом нижнем углу
   1. Нажимаете кнопку «Кто автор?» в правом нижнем углу
Строка 39: Строка 39:
     }
     }


     function escapeHtml(text) {
     function escapeText(text, escapeSlash) {
         if (text === undefined || text === null) return '';
         if (text === undefined || text === null) return '';
         return String(text)
         var s = String(text)
             .replace(/&/g, '&')
             .replace(/&/g, '&')
             .replace(/</g, '&lt;')
             .replace(/</g, '&lt;')
             .replace(/>/g, '&gt;')
             .replace(/>/g, '&gt;')
             .replace(/"/g, '&quot;')
             .replace(/"/g, '&quot;')
             .replace(/'/g, '&#039;')
             .replace(/'/g, '&#039;');
             .replace(/\//g, '&#x2F;');
        if (escapeSlash) {
             s = s.replace(/\//g, '&#x2F;');
        }
        return s;
    }
 
    function escapeHtml(text) {
        return escapeText(text, true);
     }
     }


     function escapeForLog(text) {
     function escapeForLog(text) {
         if (text === undefined || text === null) return '';
        return escapeText(text, false);
         return String(text).replace(/[<>"']/g, function(match) {
    }
            if (match === '<') return '&lt;';
 
            if (match === '>') return '&gt;';
    function sanitizeUrl(url) {
            if (match === '"') return '&quot;';
         if (!url || typeof url !== 'string') return null;
             if (match === "'") return '&#39;';
         var trimmed = url.trim();
             return match;
        if (trimmed === '') return null;
         });
 
        // Разрешаем только относительные пути, якоря и абсолютные http(s).
        if (trimmed.charAt(0) === '/' || trimmed.charAt(0) === '#') {
            return trimmed;
        }
 
        try {
            var parsed = new URL(trimmed, window.location.origin);
             if (parsed.protocol === 'https:' || parsed.protocol === 'http:') {
                return trimmed;
             }
         } catch (e) {
        }
        return null;
     }
     }


Строка 69: Строка 89:
         if (options.id) element.id = options.id;
         if (options.id) element.id = options.id;
         if (options.text) element.textContent = options.text;
         if (options.text) element.textContent = options.text;
         if (options.html) {
         if (options.html) {
             var tempDiv = document.createElement('div');
             element.textContent = options.html;
            tempDiv.textContent = options.html;
            element.innerHTML = tempDiv.innerHTML;
         }
         }


Строка 85: Строка 102:
             Object.keys(options.attrs).forEach(function(key) {
             Object.keys(options.attrs).forEach(function(key) {
                 if (key === 'href' || key === 'src') {
                 if (key === 'href' || key === 'src') {
                     var value = options.attrs[key];
                     var safe = sanitizeUrl(options.attrs[key]);
                     if (value && typeof value === 'string') {
                     if (safe !== null) {
                         if (value.startsWith('/') ||
                         element.setAttribute(key, safe);
                            value.startsWith('https://') ||
                            value.startsWith('http://') ||
                            value.startsWith('#')) {
                            element.setAttribute(key, value);
                        }
                     }
                     }
                 } else {
                 } else {
Строка 104: Строка 116:


     function createSafeLink(url, text, title) {
     function createSafeLink(url, text, title) {
         var safeUrl = '';
        // [FIX 4] Используем sanitizeUrl вместо проверки через includes().
        if (url && typeof url === 'string') {
         var safeUrl = sanitizeUrl(url) || '#';
            if (url.startsWith('/') || url.startsWith('#') ||
                url.includes('wiki.peresvet.artushak.ru')) {
                safeUrl = url;
            } else {
                safeUrl = '#';
            }
        }


         var link = createSafeElement('a', {
         var link = createSafeElement('a', {
Строка 187: Строка 192:
         function classifyTitle(candidate) {
         function classifyTitle(candidate) {
             if (!candidate) return;
             if (!candidate) return;
             if (candidate.includes(':')) {
             if (candidate.indexOf(':') !== -1) {
                 var prefix = candidate.split(':')[0].toLowerCase();
                 var prefix = candidate.split(':')[0].toLowerCase();
                 if (excludedNamespaces.indexOf(prefix) !== -1) {
                 if (excludedNamespaces.indexOf(prefix) !== -1) {
Строка 215: Строка 220:
                 }
                 }


                 if (pathname.includes('/wiki/')) {
                 if (pathname.indexOf('/wiki/') !== -1) {
                     var pathTitle = pathname.split('/wiki/')[1];
                     var pathTitle = pathname.split('/wiki/')[1];
                     if (pathTitle) {
                     if (pathTitle) {
Строка 262: Строка 267:
     }
     }


     function cycApiRequest(params, callback, errorCallback) {
     function absApiRequest(params, callback, errorCallback) {
         var apiUrl = scriptPath + '/api.php';
         var apiUrl = scriptPath + '/api.php';
         params.format = 'json';
         params.format = 'json';
Строка 303: Строка 308:
                 if (xhr.status === 200) {
                 if (xhr.status === 200) {
                     var contentType = xhr.getResponseHeader('Content-Type') || '';
                     var contentType = xhr.getResponseHeader('Content-Type') || '';
                     if (!contentType.includes('application/json') && !contentType.includes('text/javascript')) {
                     if (contentType.indexOf('application/json') === -1 &&
                        contentType.indexOf('text/javascript') === -1) {
                         clearTimeout(timeoutId);
                         clearTimeout(timeoutId);
                         completed = true;
                         completed = true;
Строка 545: Строка 551:
     var selectionActive = false;
     var selectionActive = false;
     var selectionTimer = null;
     var selectionTimer = null;
    var selectionHandlers = {};


     function activateSelectionMode() {
     function activateSelectionMode() {
Строка 576: Строка 581:
         });
         });


         var mainText = document.createTextNode('Выделите текст');
         tooltip.appendChild(document.createTextNode('Выделите текст'));
         tooltip.appendChild(mainText);
         tooltip.appendChild(document.createElement('br'));
 
        var br = document.createElement('br');
        tooltip.appendChild(br);


         var small = createSafeElement('small', {
         var small = createSafeElement('small', {
             css: {
             css: { color: '#ff0' }
                color: '#ff0'
            }
         });
         });
 
         small.appendChild(document.createTextNode('осталось '));
         var smallText = document.createTextNode('осталось ');
        small.appendChild(smallText);


         var timerSpan = createSafeElement('span', {
         var timerSpan = createSafeElement('span', {
             id: 'blame-timer',
             id: 'blame-timer',
             text: '20',
             text: '20',
             css: {
             css: { color: '#ff0' }
                color: '#ff0'
            }
         });
         });
         small.appendChild(timerSpan);
         small.appendChild(timerSpan);
 
         small.appendChild(document.createTextNode(' секунд'));
         var secondsText = document.createTextNode(' секунд');
        small.appendChild(secondsText);


         tooltip.appendChild(small);
         tooltip.appendChild(small);
Строка 612: Строка 606:
             if (timerSpanEl) timerSpanEl.textContent = seconds;
             if (timerSpanEl) timerSpanEl.textContent = seconds;
         }, 1000);
         }, 1000);
        function cleanup() {
            selectionActive = false;
            document.removeEventListener('mouseup', mouseHandler);
            document.removeEventListener('touchend', touchHandler);
            if (timer) {
                clearInterval(timer);
                timer = null;
            }
            // [FIX 6] очищаем и setTimeout
            if (selectionTimer) {
                clearTimeout(selectionTimer);
                selectionTimer = null;
            }
            var tip = document.getElementById('blame-tooltip');
            if (tip && tip.parentNode) {
                tip.parentNode.removeChild(tip);
            }
        }


         function mouseHandler() {
         function mouseHandler() {
Строка 634: Строка 650:
                             (selectedText.length > 50 ? '..."' : '"');
                             (selectedText.length > 50 ? '..."' : '"');
                 addLog(logText, 'success');
                 addLog(logText, 'success');
                 deactivateSelectionMode();
                 cleanup();
                 findAuthor(selectedText);
                 findAuthor(selectedText);
             } else if (selectedText.length > 0) {
             } else if (selectedText.length > 0) {
Строка 640: Строка 656:
             }
             }
         }
         }
        function deactivateSelectionMode() {
            if (!selectionActive) return;
            selectionActive = false;
            document.removeEventListener('mouseup', mouseHandler);
            document.removeEventListener('touchend', touchHandler);
            if (timer) {
                clearInterval(timer);
                timer = null;
            }
            var tip = document.getElementById('blame-tooltip');
            if (tip && tip.parentNode) {
                tip.parentNode.removeChild(tip);
            }
            addLog('Режим выделения отключён', 'info');
        }
        selectionHandlers = {
            mouse: mouseHandler,
            touch: touchHandler,
            deactivate: deactivateSelectionMode
        };


         document.addEventListener('mouseup', mouseHandler);
         document.addEventListener('mouseup', mouseHandler);
         document.addEventListener('touchend', touchHandler);
         document.addEventListener('touchend', touchHandler);


         var timeoutId = setTimeout(function() {
         // [FIX 6] сохраняем id таймера в модульную переменную, cleanup его снимет
        selectionTimer = setTimeout(function() {
             if (selectionActive) {
             if (selectionActive) {
                 addLog('Время вышло', 'warning');
                 addLog('Время вышло', 'warning');
                 deactivateSelectionMode();
                 cleanup();
                addLog('Режим выделения отключён', 'info');
             }
             }
         }, 20000);
         }, 20000);


         selectionTimer = timeoutId;
         var origCleanup = cleanup;
        cleanup = function() {
            origCleanup();
            addLog('Режим выделения отключён', 'info');
        };
     }
     }


Строка 752: Строка 747:
             }
             }


             cycApiRequest(params, function(data) {
             absApiRequest(params, function(data) {
                 if (data.error) {
                 if (data.error) {
                     addLog('Ошибка API: ' + escapeForLog(data.error.info), 'error');
                     addLog('Ошибка API: ' + escapeForLog(data.error.info), 'error');
Строка 815: Строка 810:


         var foundRev = null;
         var foundRev = null;
        var previousContent = null;
         var checkedCount = 0;
         var checkedCount = 0;


Строка 827: Строка 821:
             }
             }


             if (content.indexOf(text) !== -1) {
             if (content.indexOf(text) === -1) {
                 addLog('Текст найден в ревизии от ' + rev.timestamp + ' (id: ' + rev.revid + ')', 'info');
                 continue;
            }
 
            addLog('Текст найден в ревизии от ' + rev.timestamp + ' (id: ' + rev.revid + ')', 'info');


                if (i > 0) {
            if (i === 0) {
                    previousContent = oldestFirst[i - 1].content || '';
                // Текст есть в самой первой ревизии — автор первый.
                    if (previousContent.indexOf(text) !== -1) {
                foundRev = rev;
                        addLog('Текст был и в предыдущей ревизии, продолжаем поиск...', 'info');
                addLog('Текст есть в самой первой ревизии страницы', 'info');
                        continue;
                break;
                    } else {
            }
                        foundRev = rev;
 
                        addLog('Найдено первое появление! Ревизия: ' + rev.revid, 'success');
            var previousContent = oldestFirst[i - 1].content || '';
                        break;
            if (previousContent.indexOf(text) === -1) {
                    }
                // Текст появился именно в этой правке.
                 } else {
                foundRev = rev;
                    foundRev = rev;
                addLog('Найдено первое появление! Ревизия: ' + rev.revid, 'success');
                    addLog('Текст есть в самой первой ревизии страницы', 'info');
                 break;
                    break;
                }
             }
             }
            addLog('Текст был и в предыдущей ревизии, продолжаем поиск...', 'info');
         }
         }


Строка 854: Строка 851:
         }
         }


         if (previousContent !== null) {
         callback({ rev: foundRev, title: title });
            addLog('Выполняю дополнительную проверку...', 'info');
 
            var appearsInNew = (foundRev.content || '').indexOf(text) !== -1;
            var appearsInOld = (previousContent || '').indexOf(text) !== -1;
 
            if (appearsInNew && !appearsInOld) {
                addLog('Проверка пройдена: текст появился именно в этой правке', 'success');
                callback({ rev: foundRev, title: title });
            } else {
                addLog('Проверка не пройдена: текст изменялся позже', 'warning');
 
                var index = -1;
                for (var j = 0; j < revisions.length; j++) {
                    if (revisions[j].revid === foundRev.revid) {
                        index = j;
                        break;
                    }
                }
 
                if (index !== -1) {
                    revisions.splice(index, 1);
                    addLog('Перезапускаю поиск...', 'info');
                    findTextAppearance(revisions, text, title, callback);
                } else {
                    callback(null);
                }
            }
        } else {
            callback({ rev: foundRev, title: title });
        }
     }
     }