MediaWiki:Gadget-blamefinder.js: различия между версиями
Ланселот (обсуждение | вклад) Нет описания правки |
Ланселот (обсуждение | вклад) Нет описания правки |
||
| Строка 1: | Строка 1: | ||
/** | /** | ||
* Gadget: Blame Finder | * Gadget: Blame Finder | ||
* Версия | * Версия 2.0 с поддержкой ночного режима | ||
* Назначение: поиск автора любого текста в статье | * Назначение: поиск автора любого текста в статье | ||
* | * Локализация под wiki.peresvet.artushak.ru, лицензия: CC BY-SA 4.0 | ||
* Использование: | * Использование: | ||
1. Нажимаете кнопку «Кто автор?» в правом нижнем углу | 1. Нажимаете кнопку «Кто автор?» в правом нижнем углу | ||
| Строка 39: | Строка 39: | ||
} | } | ||
function | function escapeText(text, escapeSlash) { | ||
if (text === undefined || text === null) return ''; | if (text === undefined || text === null) return ''; | ||
var s = String(text) | |||
.replace(/&/g, '&') | .replace(/&/g, '&') | ||
.replace(/</g, '<') | .replace(/</g, '<') | ||
.replace(/>/g, '>') | .replace(/>/g, '>') | ||
.replace(/"/g, '"') | .replace(/"/g, '"') | ||
.replace(/'/g, ''') | .replace(/'/g, '''); | ||
.replace(/\//g, '/'); | if (escapeSlash) { | ||
s = s.replace(/\//g, '/'); | |||
} | |||
return s; | |||
} | |||
function escapeHtml(text) { | |||
return escapeText(text, true); | |||
} | } | ||
function escapeForLog(text) { | function escapeForLog(text) { | ||
if ( | return escapeText(text, false); | ||
} | |||
function sanitizeUrl(url) { | |||
if (!url || typeof url !== 'string') return null; | |||
if ( | var trimmed = url.trim(); | ||
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) { | ||
element.textContent = options.html; | |||
} | } | ||
| Строка 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 | var safe = sanitizeUrl(options.attrs[key]); | ||
if ( | if (safe !== null) { | ||
element.setAttribute(key, safe); | |||
} | } | ||
} else { | } else { | ||
| Строка 104: | Строка 116: | ||
function createSafeLink(url, text, title) { | function createSafeLink(url, text, title) { | ||
var safeUrl = | // [FIX 4] Используем sanitizeUrl вместо проверки через includes(). | ||
var safeUrl = sanitizeUrl(url) || '#'; | |||
var link = createSafeElement('a', { | var link = createSafeElement('a', { | ||
| Строка 187: | Строка 192: | ||
function classifyTitle(candidate) { | function classifyTitle(candidate) { | ||
if (!candidate) return; | if (!candidate) return; | ||
if (candidate. | 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. | if (pathname.indexOf('/wiki/') !== -1) { | ||
var pathTitle = pathname.split('/wiki/')[1]; | var pathTitle = pathname.split('/wiki/')[1]; | ||
if (pathTitle) { | if (pathTitle) { | ||
| Строка 262: | Строка 267: | ||
} | } | ||
function | 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 ( | 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; | ||
function activateSelectionMode() { | function activateSelectionMode() { | ||
| Строка 576: | Строка 581: | ||
}); | }); | ||
tooltip.appendChild(document.createTextNode('Выделите текст')); | |||
tooltip.appendChild( | tooltip.appendChild(document.createElement('br')); | ||
var small = createSafeElement('small', { | var small = createSafeElement('small', { | ||
css: { | css: { color: '#ff0' } | ||
}); | }); | ||
small.appendChild(document.createTextNode('осталось ')); | |||
var timerSpan = createSafeElement('span', { | var timerSpan = createSafeElement('span', { | ||
id: 'blame-timer', | id: 'blame-timer', | ||
text: '20', | text: '20', | ||
css: { | css: { color: '#ff0' } | ||
}); | }); | ||
small.appendChild(timerSpan); | small.appendChild(timerSpan); | ||
small.appendChild(document.createTextNode(' секунд')); | |||
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'); | ||
cleanup(); | |||
findAuthor(selectedText); | findAuthor(selectedText); | ||
} else if (selectedText.length > 0) { | } else if (selectedText.length > 0) { | ||
| Строка 640: | Строка 656: | ||
} | } | ||
} | } | ||
document.addEventListener('mouseup', mouseHandler); | document.addEventListener('mouseup', mouseHandler); | ||
document.addEventListener('touchend', touchHandler); | document.addEventListener('touchend', touchHandler); | ||
// [FIX 6] сохраняем id таймера в модульную переменную, cleanup его снимет | |||
selectionTimer = setTimeout(function() { | |||
if (selectionActive) { | if (selectionActive) { | ||
addLog('Время вышло', 'warning'); | addLog('Время вышло', 'warning'); | ||
cleanup(); | |||
addLog('Режим выделения отключён', 'info'); | |||
} | } | ||
}, 20000); | }, 20000); | ||
var origCleanup = cleanup; | |||
cleanup = function() { | |||
origCleanup(); | |||
addLog('Режим выделения отключён', 'info'); | |||
}; | |||
} | } | ||
| Строка 752: | Строка 747: | ||
} | } | ||
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 checkedCount = 0; | var checkedCount = 0; | ||
| Строка 827: | Строка 821: | ||
} | } | ||
if (content.indexOf(text) | if (content.indexOf(text) === -1) { | ||
addLog('Текст найден в ревизии от ' + rev.timestamp + ' (id: ' + rev.revid + ')', 'info'); | continue; | ||
} | |||
addLog('Текст найден в ревизии от ' + rev.timestamp + ' (id: ' + rev.revid + ')', 'info'); | |||
if (i === 0) { | |||
// Текст есть в самой первой ревизии — автор первый. | |||
foundRev = rev; | |||
addLog('Текст есть в самой первой ревизии страницы', 'info'); | |||
break; | |||
} | |||
var previousContent = oldestFirst[i - 1].content || ''; | |||
if (previousContent.indexOf(text) === -1) { | |||
// Текст появился именно в этой правке. | |||
foundRev = rev; | |||
addLog('Найдено первое появление! Ревизия: ' + rev.revid, 'success'); | |||
break; | |||
} | } | ||
addLog('Текст был и в предыдущей ревизии, продолжаем поиск...', 'info'); | |||
} | } | ||
| Строка 854: | Строка 851: | ||
} | } | ||
callback({ rev: foundRev, title: title }); | |||
} | } | ||