مستخدم:Gerges/Gadget-WikiReplacer.js

ملاحظة: بعد الحفظ، قد يلزمك محو الاختزان لرؤية التغييرات (محو الاختزان الآن).

$(document).ready(function() {
  function init() {
    $("#mw-content-text > p").remove();
    $("#firstHeading").text("مستبدل ويكي");
    var AsRegex, AsMinor, AsBot;
    var mwConfig = mw.config.get(['wgUserLanguage']);
    var listofPages = new OO.ui.MultilineTextInputWidget({
        placeholder: "قائمة الصفحات",
        autosize: true,
        rows: 10
      }),
      findInput = new OO.ui.TextInputWidget({
        placeholder: "بحث"
      });
    replaceInput = new OO.ui.TextInputWidget({
        placeholder: "استبدال"
      }),
      summaryInput = new OO.ui.TextInputWidget({
        placeholder: "سبب التعديل"
      }),
      msInput = new OO.ui.TextInputWidget({
        placeholder: "مللي ثانية",
        type: "number",
        value: 1000
      }),
      treatAsRegex = new OO.ui.FieldLayout(
        treatAsRegexInside = new OO.ui.CheckboxInputWidget({
          selected: false

        }), {
          label: "استخدام التعبير النمطي فى البحث",
          align: "inline"
        }),
      replaceStart = new OO.ui.ButtonWidget({
        label: "بدأ",
        icon: "alert",
        flags: ["primary", "progressive"]
      }),
      cancelBtn = new OO.ui.ButtonWidget({
        label: "إلغاء",
        flags: ["primary", "destructive"],
        href: "https:" + mw.config.get("wgServer")
      }),
      cancelLoop = false,
      logHeading = $("<div>").hide();

    label1 = $("<p>").text("قائمة الصفحات:").css("font-weight", "bold");

    label2 = $("<p>").text("بحث:").css("font-weight", "bold");

    label3 = $("<p>").text("استبدال:").css("font-weight", "bold");

    label4 = $("<p>").text("سبب:").css("font-weight", "bold");

    label5 = $("<p>").text("زمن التأخير (مللي ثانية):").css("font-weight", "bold");


    $("#mw-content-text").append(
      label1, listofPages.$element,
      label2, findInput.$element,
      label3, replaceInput.$element,
      label4, summaryInput.$element,
      label5, msInput.$element,
      treatAsRegex.$element,
      "<br/>",
      replaceStart.$element,
      cancelBtn.$element,
      "<br/>",
      logHeading
    );


    function edit_page(page, find, replace, summary, callback) {
      var _api = new mw.Api({ ajax: { async: false } });
      _api.edit(page, function(revision) {
          return {
            text: revision.content.replace(find, replace),
            summary: summary,
            errorformat: 'html',
            errorlang: mwConfig.wgUserLanguage,
            errorsuselocal: true
          }
        })
        .done(function(data) {
          callback(data, page, "");
        })
        .fail(function(code, error) {
          callback(code, page, error);
        });
    }

    function escapeRegExp(str) {
      // From MDN
      return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
    }

    function missingAlertMsg(str) {
      return OO.ui.alert("لم يتم إدخال " + str + " :(", {
        size: "small",
        actions: [{
          action: "save",
          label: "حسنا",
          flags: ["primary", "progressive"]
                }]
      });
    }

    function responeHanddler(data, page, error) {
      var orderedList = $("<ul>").appendTo(logHeading);

      if (error == "") {
        orderedList.append("<li><b>تم تنفيذ على صفحة " + page + "</b>.</li>");
      } else {
        orderedList.append("<li><b>فشل تنفيذ على صفحة " + page + ":" + error.info + "</b>.</li>");
        console.error(data);
      }
    }

    replaceStart.on("click", function() {
      cancelLoop = false;
      pagesList = listofPages.getValue().replace(/^\s*[\r\n]/gm, "").split("\n");

      var find = findInput.getValue();
      var replace = replaceInput.getValue();
      var summary = summaryInput.getValue().trim();
      var timeoutMS = msInput.getValue();
      AsRegex = treatAsRegexInside.isSelected();
      
      if (pagesList[0].trim() !== "" && find !== "") {
        logHeading.empty();
        $("<h1>").wrapInner("<span class='mw-headline'>السجل</span>").appendTo(logHeading);
        logHeading.show();
      } else {
        missingAlertMsg("أى صفحة");
        return;
      }

      if (find === "") {
        missingAlertMsg("بحث");
        return;
      }

      if (timeoutMS === "") {
        missingAlertMsg("زمن التأخير (مللي ثانية)");
        return;
      }


      pagesList.forEach(function(page) {
        if (cancelLoop) {
          return;
        }
        setTimeout(function() {
          // Lengthy name to aviod override in the global variable
          window.page = page.trim();

          // Simple find/replace without Regex
          if (!AsRegex) {
            find = escapeRegExp(find);
            edit_page(page, find, replace, summary, responeHanddler);
          }
          // Find/replace with Regex
          else {

            // Check whether the Regex is correct or not
            try {
              find = new RegExp(find, "ugi");
            } catch (e) {
              OO.ui.alert("التعبير النمطي غير صحيح: " + e, {
                size: "small",
                actions: [{
                  action: "save",
                  label: "حسنا",
                  flags: ["primary", "progressive"]
                                }]
              });
              // Hack to break the loop
              pagesList.length = 0;
              return;
            }

             edit_page(page, find, replace, summary, responeHanddler);
          }
        }, timeoutMS);
      });

    });
    cancelBtn.on("click", function() {
      cancelLoop = true;
    });
  }

  // On every page
  $.when(mw.loader.using("mediawiki.util"), $.ready).then(function() {
    mw.util.addPortletLink(
      "p-tb",
      mw.util.getUrl("Special:BlankPage/WikiReplacer"),
      "مستبدل ويكي"
    );
  });

  if (mw.config.get("wgCanonicalSpecialPageName") === "Blankpage" && mw.config.get("wgTitle").split("/", 2)[1] === "WikiReplacer") {

    $.when(mw.loader.using("oojs-ui-core"), $.ready).then(function() {
      init();
    });
  }
});