לדלג לתוכן

משתמש:מוטי בוט/הפניות.js

מתוך המכלול, האנציקלופדיה היהודית

לתשומת ליבך: לאחר הפרסום, ייתכן שיהיה צורך לנקות את זיכרון המטמון (cache) של הדפדפן כדי להבחין בשינויים.

  • פיירפוקס / ספארי: להחזיק את המקש Shift בעת לחיצה על טעינה מחדש (Reload) או ללחוץ על צירוף המקשים Ctrl-F5 או Ctrl-R (במחשב מק: ⌘-R).
  • גוגל כרום: ללחוץ על צירוף המקשים Ctrl-Shift-R (במחשב מק: ⌘-Shift-R).
  • אדג': להחזיק את המקש Ctrl בעת לחיצה על רענן (Refresh) או ללחוץ על צירוף המקשים Ctrl-F5.
//העתק מ[[משתמש:בוט גאון הירדן/הפניות.js]] מותאם לעורך ממשק
mw.loader
  .using(["jquery.spinner", "mediawiki.diff.styles", "mediawiki.api"])
  .then(() => {


    function getProperties(result) {
      var parit = " ";
      if (!result.parse.properties[0]) {
        parit = " ";
      } else if (result.parse.properties[0]["name"] == "wikibase_item") {
        parit = result.parse.properties[0]["*"];
      } else if (
        result.parse.properties[0]["name"] != "wikibase_item" &&
        result.parse.properties.length <= 1
      ) {
        parit = " ";
      } else if (
        result.parse.properties[0]["name"] != "wikibase_item" &&
        result.parse.properties.length > 1
      ) {
        for (let pa = 0; pa < result.parse.properties.length; pa++) {
          if (result.parse.properties[pa]["name"] == "wikibase_item") {
            parit = result.parse.properties[pa]["*"];
          } else continue;
        }
      }
      return parit;
    }

    $(function () {
      var steps = 0;

      function getAll() {
        if (steps > 10) return;
        var PageNameLocal = mw.config.get("wgPageName");

        var checkParams = {
          action: "query",
          format: "json",
          prop: "linkshere",
          indexpageids: 1,
          lhprop: "title",
          lhshow: "redirect",
          lhnamespace: "0",
          lhlimit: "max",
          titles: decodeURIComponent(PageNameLocal),
        };
        var apiEndpoint = "/import/get_wik1i.php";
        $.ajax({
          url: apiEndpoint,
          data: checkParams,
          dataType: "json",
        })
          .done(function (result) {
            if (!result || !result.query) return;

            var pages = result.query.pages[result.query.pageids[0]];

            if (!pages.linkshere) return;

            for (var l of pages.linkshere) {
              var oneRedirect = l.title;

              checkHamichlol(oneRedirect);
            }
          })
          .fail(function (e) {
            console.log(e);
            steps++;
            getAll(steps);
          });
      }
      function saveHamichlol(page) {
        var apiEndpoint =
          "https://import.hamichlol.org.il/?action=parse&page=" +
          encodeURIComponent(page) +
          "&format=json&prop=wikitext|revid&origin=*";
        fetch(apiEndpoint)
          .then((response) => response.json())
          .then(function (result) {
            if (result && result.parse) {
              var textpage = result.parse.wikitext["*"];
              var red = decodeURIComponent(result.parse.title);
              //שמירה
              if (
                confirm("ההפניה הבאה קיימת בויקיפדיה:\n " + red + "\nלייבא?")
              ) {
                $.post(
                  mw.util.wikiScript("api"),
                  {
                    action: "edit",
                    format: "json",
                    tags: "ייבוא-הפניות",
                    bot: 1,
                    watchlist: "unwatch",
                    recreate: false,
                    title: result.parse.title,
                    text: textpage,
                    token: mw.user.tokens.get("csrfToken"),
                  },
                  function (data) {
                    if (data && data.edit) {
                      mw.notify(
                        "ייבוא ההפניה: " +
                          decodeURIComponent(data.edit["title"]) +
                          " הושלם בהצלחה"
                      );
                    } else {
                      console.log(data);
                    }
                  }
                );
              }
            }
          })
          .catch((error) =>
            mw.notify("אירעה שגיאה בייבוא ההפניה. תיאור השגיאה הוא: " + error)
          );
      }
      function checkHamichlol(oneRedirect) {
        fetch(
          "/w/api.php?action=query&prop=info|revisions&titles=" +
            encodeURIComponent(oneRedirect) +
            "&indexpageids= true&rvlimit=1&rvprop=size|ids&list=logevents&inprop=protection&letype=delete&letitle=" +
            encodeURIComponent(oneRedirect) +
            "&format=json"
        )
          .then((response) => response.json())
          .then(function (result) {
            if (result && result.query) {
              var logevent = result.query.logevents;
              if (result.query.pageids[0] == "-1" && !logevent[0]) {
                var protect = result.query.pages["-1"].protection;
                if (!protect[0]) {
                  var page = result.query.pages[result.query.pageids]["title"];
                  //console.log('ההפניה ' + page + ' לא קיימת במכלול');
                  saveHamichlol(page);
                }
              } else if (
                result.query.pageids[0] != "-1" &&
                result.query.pages[result.query.pageids[0]].redirect ===
                  undefined
              ) {
                var pageExist =
                  result.query.pages[result.query.pageids[0]].title;
                var href =
                  "https://www.hamichlol.org.il/w/index.php?title=" +
                  encodeURIComponent(pageExist);
                var $a = $("<a>");
                $a.attr("href", href)
                  .attr("style", "display: inline-block")
                  .attr("target", "_blank")
                  .attr("title", pageExist)
                  .text(pageExist);

                var message =
                  ": קיים במכלול כערך נפרד, והוא קיים בוויקיפדיה כהפניה.";

                $("#bodyContent").prepend($a, message);
              }
            }
          });
      }

      if (
        mw.config.get("wgArticleId") > 0 &&
        mw.config.get("wgNamespaceNumber") === 0 &&
        mw.config.get("wgPageName") != "עמוד_ראשי" &&
        mw.config.get("wgAction") === "view" &&
        location.href.indexOf("&diff") == -1
      ) {
        getAll();
      }
    });
    mw.loader.load("ext.gadget.redLinksForImport");

    function getsAll() {
      var PageNameLocal = mw.config.get("wgPageName");

      var checkParams = {
        action: "query",
        format: "json",
        prop: "linkshere",
        indexpageids: 1,
        lhprop: "title",
        lhshow: "redirect",
        lhnamespace: "0",
        lhlimit: "max",
        titles: decodeURIComponent(PageNameLocal),
      };
      var apiEndpoint = "/import/get_wik1i.php";
      $.ajax({
        url: apiEndpoint,
        data: checkParams,
        dataType: "json",
      })
        .done(function (result) {
          if (!result || !result.query) return;

          var pages = result.query.pages[result.query.pageids[0]];

          if (!pages.linkshere) return;

          for (var l of pages.linkshere) {
            var oneRedirect = l.title;

            checkHam(oneRedirect);
          }
        })
        .fail(function (e) {
          console.log(e);
        });
    }
    function checkHam(oneRedirect) {
      fetch(
        "/w/api.php?action=query&prop=info|revisions&titles=" +
          encodeURIComponent(oneRedirect) +
          "&indexpageids= true&rvlimit=1&rvprop=size|ids&format=json"
      )
        .then((response) => response.json())
        .then(function (result) {
          if (result && result.query) {
            if (result.query.pageids[0] == "-1") {
              console.log("Page not found: " + oneRedirect);
            } else if (
              result.query.pageids[0] != "-1" &&
              result.query.pages[result.query.pageids[0]].redirect === undefined
            ) {
              var pageExist = result.query.pages[result.query.pageids[0]].title;
              var href =
                "https://www.hamichlol.org.il/w/index.php?title=" +
                encodeURIComponent(pageExist);
              var $a = $("<a>");
              $a.attr("href", href)
                .attr("target", "_blank")
                .attr("title", pageExist)
                .text(pageExist);
              var div = $(
                '<div  class="warningbox mw-warning-with-logexcerpt mw-content-rtl" dir="rtl" lang="he"><div>נראה שהערך קיים כבר בשם אחר: <a href ="' +
                  href +
                  '">' +
                  pageExist +
                  "</a></div></div>"
              );
              $("#bodyContent").prepend(div);
              if (
                confirm("נראה שהערך כבר קיים בשם אחר; האם ברצונך לתייג מנטרים?")
              ) {
                var title = "talk:" + pageExist;
                var param = {
                  action: "edit",
                  section: "new",
                  sectiontitle: "השוואה",
                  title: title,
                  text: "{{ס:הלוק" + "}}",
                  token: mw.user.tokens.get("csrfToken"),
                  format: "json",
                };
                $.post(mw.util.wikiScript("api"), param, function (data) {
                  if (data && data.error) {
                    $.ajax({
                      url: mw.util.wikiScript("api"),
                      aync: false,
                      type: "post",
                      data: {
                        action: "flow",
                        submodule: "new-topic",
                        page: title,
                        nttopic: "השוואה",
                        token: mw.user.tokens.get("csrfToken"),
                        ntcontent: "{{ס:הלוק" + "}}",
                        format: "json",
                      },
                      success: function (data) {
                        if (data && data.flow)
                          alert("ההודעה נשמרה בדף :" + title);
                      },
                      error: function () {
                        alert("תקלה. ההודעה לא נשמרה");
                      },
                    });
                  } else if (
                    data &&
                    data.edit &&
                    data.edit.result == "Success"
                  ) {
                    alert("ההודעה נשמרה בדף: " + title);
                  }
                });
              } else {
                window.open(href);
              }
            }
          }
        });
    }
    if (
      mw.config.get("wgNamespaceNumber") == 0 &&
      mw.config.get("wgArticleId") < 1
    ) {
      getsAll();
    }

    $(function () {
      if (
        mw.config.get("wgUserGroups").indexOf("editinterface") == -1 ||
        mw.config.get("wgUserGroups").indexOf("aspaklaryaEditor") == -1
      )
        return;

      var bt = $('<button id= "show-hide" type="button">הצג/הסתר</button>');

      var page = mw.config
        .get("wgPageName")
        .replace(/^רבי_/, "")
        .replace("הרב_", "")
        .replace("_", " ")
        .replace(/ה"קדושה"/g, "הקדושה")
        .replace(/ה"קדוש"/g, "הקדוש")
        .replace(/ה"קדושים"/g, "הקדושים")
        .replace(/א-ל/g, "אל")
        .replace("המכלול", "ויקיפדיה");

      var $spinner = $.createSpinner({
        size: "small",
        type: "inline",
        id: "diff-btn-spinner",
      });

      $(bt).click(function () {
        var mydiv = document.getElementById("mytable");

        if (mydiv) {
          $(mydiv).toggle();
        } else {
          appendDiff();
        }
      });

      function appendDiff() {
        $(bt).after($spinner);
        var point = "https://import.hamichlol.org.il/?";

        if (window.PageName != undefined) page = window.PageName;

        var dataWi = {
          action: "parse",
          page: page,
          format: "json",
          prop: "images|revid|properties|wikitext",
          utf8: "1",
          origin: "*",
        };

        $.ajax({
          url: point,
          data: dataWi,
          dataType: "json",
        })
          .done(function (result) {
            if (result && result.parse) {
              var textpage = result.parse.wikitext["*"];

              var girsa = result.parse.revid;
              var parit = getProperties(result);

              var added = "";

              var rating = [
                "מיון ויקיפדיה",
                "דף=" + result.parse.title,
                "גרסה=" + girsa,
                "פריט=" + parit,
              ];
              added = "\n{{וח}}\n" + "{{" + rating.join("|") + "}}";
              textpage = textpage + added;

              getLocl(textpage);
            } else if (result && result.error) {
              var error = result.error.code;
              mw.notify(error);
              $.removeSpinner("diff-btn-spinner");
            }
          })
          .fail(function (request, exception) {
            // Our error logic here
            var msg = "";
            if (request.status === 0) {
              msg = "Not connect.\n Verify Network.";
            } else if (request.status == 404) {
              msg = "Requested page not found. [404]";
            } else if (request.status == 418) {
              msg = "שגיאת סינון";
            } else if (request.status == 500) {
              msg = "Internal Server Error [500].";
            } else if (exception === "parsererror") {
              msg = "Requested JSON parse failed.";
            } else if (exception === "timeout") {
              msg = "Time out error.";
            } else if (exception === "abort") {
              msg = "Ajax request aborted.";
            } else {
              msg = "Uncaught Error.\n" + request.responseText;
            }

            mw.notify(msg);
            $.removeSpinner("diff-btn-spinner");
          });
      }

      function getLocl(textpage) {
        var page = mw.config.get("wgPageName");
        var point = "w/api.php?";
        var data = {
          action: "query",
          format: "json",
          prop: "info|revisions",
          indexpageids: true,
          titles: page,
          rvlimit: "1",
          rvdifftotext: textpage,
        };
        $.ajax({
          data: data,
          dataType: "json",
          url: mw.config.get("wgScriptPath") + "/api.php",
          type: "POST",
        })
          .done(function (result) {
            var diffString =
              result.query.pages[result.query.pageids[0]].revisions[0].diff[
                "*"
              ];
            var pageParse = '<table id = "mytable">' + diffString + "</table>";
            if (diffString === "") {
              mw.notify("אין הבדלים");
            } else {
              $("#bodyContent").prepend(pageParse);
            }
            $.removeSpinner("diff-btn-spinner");
          })
          .fail(function (error) {
            mw.notify(error);
            $.removeSpinner("diff-btn-spinner");
          });
      }

      if (
        mw.config.get("wgPageName") != "עמוד_ראשי" &&
        mw.config.get("wgPageContentModel") != "flow-board" &&
        mw.config.get("wgArticleId") != "0" &&
        mw.config.get("wgAction") === "view"
      ) {
        $("#firstHeading").after(bt);
      }
    });

    $(function () {
      if (mw.config.get("wgNamespaceNumber") != 0) return;
      var aa = mw.util.addPortletLink(
        "p-views",
        "#",
        "פתיח",
        "div2",
        null,
        null,
        "#ca-history"
      );
      $(aa).click(function () {
        var thispage = mw.config.get("wgPageName");
        var link = thispage
          .replace("המכלול", "ויקיפדיה")
          .replace(/^רבי_/, "")
          .replace("הרב_", "")
          .replace("_", " ")
          .replace(/ה"קדושה"/g, "הקדושה")
          .replace(/ה"קדוש"/g, "הקדוש")
          .replace(/ה"קדושים"/g, "הקדושים")
          .replace(/א-ל/g, "אל");
        var apiEndpoint1 =
          "https://import.hamichlol.org.il/?action=parse&page=" +
          encodeURIComponent(link) +
          "&format=json&section=0&prop=text|revid&disablelimitreport=1&utf8=1&origin=*";

        /**
         * Send the request to get the text
         */
        fetch(apiEndpoint1)
          .then(function (response) {
            if (response.status == 418) {
              mw.notify("שגיאת סינון");
              return false;
            }
            response
              .json()
              .then(function (result) {
                if (result && result.parse) {
                  console.log(result);
                  var imgalt =
                    /(<a href="\/wiki\/)(.*)(" class="mw-file-description")/;

                  if (imgalt.test(result.parse.text["*"])) {
                    var imageMain = imgalt.exec(result.parse.text["*"])[2];
                    imageMain = decodeURIComponent(imageMain).replace(
                      /_/g,
                      " "
                    );
                    console.log(imageMain);
                    var image1 = imageMain.split("קובץ:")[1];
                    var text = "\n| תמונה = " + image1 + " \n";
                    copyToClipboard(text);
                    function copyToClipboard(text) {
                      if (
                        window.clipboardData &&
                        window.clipboardData.setData
                      ) {
                        return window.clipboardData.setData("Text", text);
                        mw.notify("הועתקה תמונה ללוח");
                      } else if (
                        document.queryCommandSupported &&
                        document.queryCommandSupported("copy")
                      ) {
                        var textarea = document.createElement("textarea");
                        textarea.textContent = text;
                        textarea.style.position = "fixed";
                        document.body.appendChild(textarea);
                        textarea.select();
                        mw.notify("הועתקה תמונה ללוח");
                        try {
                          return document.execCommand("copy"); // Security exception may be thrown by some browsers.
                          mw.notify("הועתקה תמונה ללוח");
                        } catch (ex) {
                          console.warn("Copy to clipboard failed.", ex);
                          return false;
                        } finally {
                          document.body.removeChild(textarea);
                        }
                      }
                    }
                  }

                  var rawa = result.parse.text["*"].replace(/\/wiki\//g, "/");
                  //rawa=$.parseHTML(rawa);
                  var box2 = $(
                    '<table class="wikitable mw-collapsible mw-collapsed" dir="rtl" lang="he"><tbody><p>הפתיח של הערך בוויקיפדיה העברית</p></tbody></table>'
                  ).html(rawa);
                  $("#bodyContent").prepend(rawa);
                } else if (
                  result &&
                  result.error &&
                  result.error.code == "missingtitle"
                ) {
                  mw.notify("לא קיים");
                }
              })
              .catch((error) =>
                mw.notify(
                  "אירעה שגיאה בשאיבת התוכן. תיאור השגיאה הוא: " + error
                )
              );
          })
          .catch((error) =>
            mw.notify("אירעה שגיאה בשאיבת התוכן. תיאור השגיאה הוא: " + error)
          );
      });
    });
  });