MediaWiki:Common.js: различия между версиями
Перейти к навигации
Перейти к поиску
Mixailo (обсуждение | вклад) Нет описания правки |
Mixailo (обсуждение | вклад) Нет описания правки |
||
| Строка 310: | Строка 310: | ||
} | } | ||
} | } | ||
Версия от 15:12, 13 февраля 2023
/* Размещённый здесь код JavaScript будет загружаться пользователям при обращении к каждой странице */
/*************************************************************************************************/
/* */
/* Чтобы сразу увидеть работу изменённого скрипта, добавляйте на тестовой странице ?debug=true. */
/* Это отключит кэш. */
/* */
/*************************************************************************************************/
/* Викификатор */
function addWikifButton() {
var toolbar = document.getElementById('toolbar');
var textbox = document.getElementById('wpTextbox1');
if (!textbox || !toolbar) {
return;
}
var i = document.createElement('img');
i.src = 'https://upload.wikimedia.org/wikisource/ru/d/d1/Button-wikifikator.png';
i.alt = i.title = 'Викификатор';
i.onclick = Wikify_Select;
// i.onclick = Wikify
i.style.cursor = 'pointer';
toolbar.appendChild(i);
}
if (document.URL.indexOf('action=edit') > 0 || document.URL.indexOf('action=submit') > 0) {
document.write('<script type="text/javascript" src="https://ru.wikipedia.org/w/index.php?title=MediaWiki:Gadget-wikificator.js&action=raw&ctype=text/javascript"><\/script>');
addOnloadHook(addWikifButton);
}
// Added by Fritz
// Викификатор в какой-то момент отказался работать. Выяснилось, что он работает только в том случае,
// если какой-нибудь текст выделен. Пришлось добавить костыль: при нажатии на кнопку "Викифицировать"
// скрипт сначала выделяет всё в главном окне редактирования, и только потом передаёт управление
// на викификатор (Wikify).
function Wikify_Select() {
if (getSelectedText()) {
Wikify();
} else {
document.getElementById("wpTextbox1").select();
Wikify();
deselectAll();
}
}
// Надеюсь эти две функции работают во всех браузерах
function getSelectedText() {
var text = "";
if (typeof window.getSelection != "undefined") {
text = window.getSelection().toString();
} else if (typeof document.selection != "undefined" && document.selection.type == "Text") {
text = document.selection.createRange().text;
}
return text;
}
function deselectAll() {
if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE?
document.selection.empty();
}
}
wgAction = mw.config.values.wgAction;
wgNamespaceNumber = mw.config.values.wgNamespaceNumber;
wgTitle = mw.config.values.wgTitle;
wgPageName = mw.config.values.wgPageName;
/* Кнопки «Поделиться» от Яндекса */
if (wgAction == 'view') {
$(function () {
if ((wgNamespaceNumber != 0 && wgNamespaceNumber != 6 && wgNamespaceNumber != 100) || wgAction != 'view' || /(oldid|diff)=/.test(window.location)) {
return;
}
$.getScript('https://ruxpert.ru/skins/common/share.js', function (d, h, i) {
new Ya.share({
element: 'sharingbuttons',
elementStyle: {
'type': 'button',
'border': true,
'quickServices': ['lj', 'twitter', 'vkontakte', 'facebook', 'gplus', 'moimir']
},
link: 'https://ruxpert.ru/' + wgPageName,
title: wgTitle,
popupStyle: {
blocks: {
'Поделись-ка!': ['lj', 'twitter', 'vkontakte', 'facebook', 'gplus', 'yaru', 'moimir']
},
copyPasteField: false
},
serviceSpecific: {
lj: {
link: '<a href="https://ruxpert.ru/' + wgPageName + '">' + wgPageName + ' — Русский эксперт</a>'
}
}
});
});
$('#firstHeading').prepend('<div style="font-size: 14px" id="sharingbuttons"></div>');
});
}
/*************************/
/* Реклама Яндекс Директ */
/*************************/
/* Не показываю рекламу на некоторых страницах (в зависимости от адреса) */
ydaCurrentUrl = window.location.href;
ydaServicePage = ydaCurrentUrl.search("%D0%A1%D0%BB%D1%83%D0%B6%D0%B5%D0%B1%D0%BD%D0%B0%D1%8F"); // "Служебная"
ydaDonatePage = ydaCurrentUrl.search("%D0%9F%D0%BE%D0%BC%D0%BE%D1%89%D1%8C_%D0%BF%D1%80%D0%BE%D0%B5%D0%BA%D1%82%D1%83"); // "Помощь_проекту"
ydaEditPage = ydaCurrentUrl.search("index.php");
ydaMediaWiki = ydaCurrentUrl.search("MediaWiki");
if (ydaServicePage == -1 && ydaDonatePage == -1 && ydaEditPage == -1 && ydaMediaWiki == -1) {
ydaAllowAd = true; // Можно показывать рекламу
} else {
ydaAllowAd = false; // Нельзя показывать рекламу
}
/* Рекламный блок 1 */
(function () {
if (ydaAllowAd) {
$('#top').after('<div id="yandex_rtb_R-A-446933-1"></div>');
}
})();
(function (w, d, n, s, t) {
w[n] = w[n] || [];
w[n].push(function () {
Ya.Context.AdvManager.render({
blockId: "R-A-446933-1",
renderTo: "yandex_rtb_R-A-446933-1",
async: true
});
});
t = d.getElementsByTagName("script")[0];
s = d.createElement("script");
s.type = "text/javascript";
s.src = "//an.yandex.ru/system/context.js";
s.async = true;
t.parentNode.insertBefore(s, t);
})(this, this.document, "yandexContextAsyncCallbacks");
/* Рекламный блок 2 */
(function () {
if (ydaAllowAd) {
$('#mw-content-text').after('<div id="yandex_rtb_R-A-446933-2"></div>');
}
})();
(function (w, d, n, s, t) {
w[n] = w[n] || [];
w[n].push(function () {
Ya.Context.AdvManager.render({
blockId: "R-A-446933-2",
renderTo: "yandex_rtb_R-A-446933-2",
async: true
});
});
t = d.getElementsByTagName("script")[0];
s = d.createElement("script");
s.type = "text/javascript";
s.src = "//an.yandex.ru/system/context.js";
s.async = true;
t.parentNode.insertBefore(s, t);
})(this, this.document, "yandexContextAsyncCallbacks");
/****************/
/* Таблификатор */
/****************/
//Форматирует таблицу, скопированную из Excel, по правилам вики-разметки.
//Часть кода позаимствована из httsp://ru.wikipedia.org/wiki/MediaWiki:Wikificator.js
//Автор: X-romix
var XRomix_Tablify_CantWork1 = 'Таблификатор не может работать в вашем браузере.\n\nTablificator cannot work in your browser'; // английский текст для тех, кто не видит русские буквы
var XRomix_Tablify_FullText1 = 'Эта кнопка предназначена для форматирования табличного текста, скопированного из табличного редактора (например, из Excel). Чтобы функция заработала, сначала выделите нужный фрагмент текста в окне редактирования.';
//Добавляет кнопку
function addTablifikatorButton1() {
var toolbar = document.getElementById('toolbar');
var textbox = document.getElementById('wpTextbox1');
if (!textbox || !toolbar) {
return;
}
var i = document.createElement('img');
i.src = 'https://upload.wikimedia.org/wikipedia/ru/c/c1/Button-tablifikator.PNG';
i.alt = i.title = 'Таблификатор';
i.onclick = XRomix_Tablify1;
i.style.cursor = 'pointer';
toolbar.appendChild(i);
}
//Этот код выполняется в начале.
if (wgAction == 'edit' || wgAction == 'submit') {
addOnloadHook(addTablifikatorButton1);
}
//Функция для оформления таблицы
function XRomix_Tablify1() {
//Проверяем, поддерживает ли браузер регулярные выражения (RegExp)
if (('code'.replace(/d/g, 'r') != 'core')
|| (navigator.appName == 'Netscape' && navigator.appVersion.substr(0, 1) < 5)) {
alert(XRomix_Tablify_CantWork1);
return;
}
//setWpSummary();
var txt, hidden = [], hidIdx = 0, wpTextbox1 = document.editform.wpTextbox1;
var winScroll = document.documentElement.scrollTop; //remember window scroll
wpTextbox1.focus();
if (typeof wpTextbox1.selectionStart != 'undefined'
&& (navigator.productSub > 20031000 || is_safari)) { //Mozilla/Opera/Safari3
var textScroll = wpTextbox1.scrollTop;
var startPos = wpTextbox1.selectionStart;
var endPos = wpTextbox1.selectionEnd;
txt = wpTextbox1.value.substring(startPos, endPos);
if (txt == '') {
alert(XRomix_Tablify_FullText1);
return;
} else {
processText();
wpTextbox1.value = wpTextbox1.value.substring(0, startPos) + txt + wpTextbox1.value.substring(endPos);
}
wpTextbox1.selectionStart = startPos;
wpTextbox1.selectionEnd = startPos + txt.length;
wpTextbox1.scrollTop = textScroll;
} else if (document.selection && document.selection.createRange) { //IE
var range = document.selection.createRange();
txt = range.text;
if (txt == '') {
alert(XRomix_Tablify_FullText1);
return;
} else {
processText();
range.text = txt;
//if (!window.opera) txt = txt.replace(/\r/g,'')
if (range.moveStart) {
range.moveStart('character', -txt.length);
}
range.select();
}
} else // Для браузеров, которые не умеют возвращать выделенный фрагмент, выдаем ошибку
{
alert(XRomix_Tablify_CantWork1);
return;
}
document.documentElement.scrollTop = winScroll; // scroll back, for IE/Opera
//Здесь производим замену в переменной txt - это отразится на выделенном фрагменте текста
function processText() {
var col1hdr = 0;
if (confirm('Вы хотите оформить первую колонку как заголовок?')) {
col1hdr = 1;
}
txt = txt.replace(/^\s+|\s+$/g, ''); //Обрезаем пробелы слева и справа
var arr1 = txt.split("\n");
txt = '\n{| class="standard"\n';
for (var i = 0; i < arr1.length; i++) {
txt = txt + "|-\n";
s1 = arr1[i];
var arr2 = s1.split("\t");
for (var j = 0; j < arr2.length; j++) {
var s2 = arr2[j];
if ((col1hdr == 1 && j == 0) || i == 0) {
txt = txt + "! " + s2 + "\n";
} else {
txt = txt + "| " + s2 + "\n";
}
}
}
txt = txt + "|}";
}
function setWpSummary() {
var wpSummary = document.getElementById('wpSummary');
if (wpSummary) {
var temp = wpSummary.value;
temp = temp.replace(/\/\*.*?\*\//, ""); //комментарии
temp = temp.replace(/[\s]*/, ""); //пробелы
if (temp == "") {
wpSummary.value = wpSummary.value + " - [[User talk:X-romix/tablifikator.js|tablifikator.js]] - таблица из Excel/Calc";
}
}
}
}
/*******************/
/* */
/* Cloudpayments */
/* */
/*******************/
document.write('<script src="https://widget.cloudpayments.ru/bundles/cloudpayments"></script>');
$(function () {
$('#cloudpayments').html('<input value="Оформить регулярное пожертвование" type="button">');
}());
var payHandler = function () {
//требуется библиотека jquery
var widget = new cp.CloudPayments();
var data = {};
data.cloudPayments = {recurrent: {interval: 'Month', period: 1}}; //создание ежемесячной подписки
widget.charge(
{ // options
publicId: 'pk_0301af503fe072af06e3e048912fc', //id из личного кабинета
description: 'Ежемесячное пожертвование сайту Ruxpert.ru', //назначение
amount: 300, //сумма
currency: 'RUB', //валюта
invoiceId: '1234567', //номер заказа (необязательно)
accountId: 'user@example.com', //идентификатор плательщика (обязательно для создания подписки)
data: data
},
function (options) { // success
//действие при успешной оплате
},
function (reason, options) { // fail
//действие при неуспешной оплате
}
);
};
$("#cloudpayments").on("click", payHandler); //кнопка "Оплатить"