Subversion Repositories oidplus

Rev

Rev 327 | Rev 356 | Go to most recent revision | View as "text/javascript" | Blame | Compare with Previous | Last modification | View Log | RSS feed

  1. /*
  2.  * OIDplus 2.0
  3.  * Copyright 2019 Daniel Marschall, ViaThinkSoft
  4.  *
  5.  * Licensed under the Apache License, Version 2.0 (the "License");
  6.  * you may not use this file except in compliance with the License.
  7.  * You may obtain a copy of the License at
  8.  *
  9.  *     http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17.  
  18. /*jshint esversion: 6 */
  19.  
  20. // $('#html').jstree();
  21.  
  22. var current_node = "";
  23. var popstate_running = false;
  24. var DEFAULT_LANGUAGE = "enus";
  25.  
  26. function oidplus_loadScript(src) {
  27.         var js = document.createElement('script');
  28.         js.src = src;
  29.         js.onload = function() {
  30.         };
  31.         js.onerror = function() {
  32.         };
  33.         document.head.appendChild(js);
  34. }
  35.  
  36. function oidplus_external_polyfill() {
  37.         // Disable this code by adding following line to userdata/baseconfig/config.inc.php
  38.         // define('RECAPTCHA_ENABLED', false);
  39.         var ua = window.navigator.userAgent;
  40.         if ((ua.indexOf("MSIE ") > 0) || (ua.indexOf("Trident/") > 0)) {
  41.                 // Compatibility with Internet Explorer
  42.                 oidplus_loadScript('https://polyfill.io/v3/polyfill.min.js?features=fetch%2CURL');
  43.         }
  44. }
  45.  
  46. function oidplus_external_recaptcha() {
  47.         // Disable this code by adding following lines to userdata/baseconfig/config.inc.php
  48.         // define('DISABLE_MSIE_COMPAT', true);
  49.         oidplus_loadScript('https://www.google.com/recaptcha/api.js');
  50. }
  51.  
  52. String.prototype.explode = function (separator, limit) {
  53.         // https://stackoverflow.com/questions/4514323/javascript-equivalent-to-php-explode
  54.         const array = this.split(separator);
  55.         if (limit !== undefined && array.length >= limit) {
  56.                 array.push(array.splice(limit - 1).join(separator));
  57.         }
  58.         return array;
  59. };
  60.  
  61. String.prototype.htmlentities = function () {
  62.         return this.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  63. };
  64.  
  65. String.prototype.html_entity_decode = function () {
  66.         return $('<textarea />').html(this).text();
  67. };
  68.  
  69. function getMeta(metaName) {
  70.         const metas = document.getElementsByTagName('meta');
  71.  
  72.         for (let i = 0; i < metas.length; i++) {
  73.                 if (metas[i].getAttribute('name') === metaName) {
  74.                         return metas[i].getAttribute('content');
  75.                 }
  76.         }
  77.  
  78.         return '';
  79. }
  80.  
  81. function getOidPlusSystemTitle() {
  82.         return getMeta('OIDplus-SystemTitle');
  83. }
  84.  
  85. function combine_systemtitle_and_pagetitle(systemtitle, pagetitle) {
  86.         // Please also change the function in index.php
  87.         if (systemtitle == pagetitle) {
  88.                 return systemtitle;
  89.         } else {
  90.                 return pagetitle + ' - ' + systemtitle;
  91.         }
  92. }
  93.  
  94. function getTreeLoadURL() {
  95.         var url = new URL(window.location.href);
  96.         var goto = url.searchParams.get("goto");
  97.         return (goto != null) ? "ajax.php?action=tree_load&goto="+encodeURIComponent(goto)
  98.                               : "ajax.php?action=tree_load";
  99. }
  100.  
  101. function reloadContent() {
  102.         // window.location.href = "?goto="+encodeURIComponent(current_node);
  103.         openOidInPanel(current_node, false);
  104.         $('#oidtree').jstree("refresh");
  105. }
  106.  
  107. function x_rec(x_data, i) {
  108.         $('#oidtree').jstree('open_node', x_data[i], function(e, data) {
  109.                 if (i+1 < x_data.length) {
  110.                         x_rec(x_data, i+1);
  111.                 } else {
  112.                         popstate_running = true; // don't call openOidInPanel again
  113.                         try {
  114.                                 $('#oidtree').jstree('select_node', x_data[i]);
  115.                         } catch (err) {
  116.                                 popstate_running = false;
  117.                         } finally {
  118.                                 popstate_running = false;
  119.                         }
  120.                 }
  121.         });
  122. }
  123.  
  124. function openOidInPanel(id, reselect/*=false*/, anchor/*=''*/) {
  125.         reselect = (typeof reselect === 'undefined') ? false : reselect;
  126.         anchor = (typeof anchor === 'undefined') ? '' : anchor;
  127.  
  128.         if (reselect) {
  129.                 $('#oidtree').jstree('deselect_all');
  130.  
  131.                 popstate_running = true; // don't call openOidInPanel during tree selection
  132.                 try {
  133.                         // If the node is already loaded in the tree, select it
  134.                         if (!$('#oidtree').jstree('select_node', id)) {
  135.                                 // If the node is not loaded, then we try to search it.
  136.                                 // If it can be found, then open all parent nodes and select the node
  137.                                 $.ajax({
  138.                                         url:"ajax.php",
  139.                                         method:"POST",
  140.                                         data:{
  141.                                                 action:"tree_search",
  142.                                                 search:id
  143.                                         },
  144.                                         error:function(jqXHR, textStatus, errorThrown) {
  145.                                                 console.error("Error: " + errorThrown);
  146.                                         },
  147.                                         success:function(data) {
  148.                                                 if ("error" in data) {
  149.                                                         console.error(data);
  150.                                                 } else if ((data instanceof Array) && (data.length > 0)) {
  151.                                                         x_rec(data, 0);
  152.                                                 } else {
  153.                                                         console.error(data);
  154.                                                 }
  155.                                         }
  156.                                 });
  157.                         }
  158.                 } catch (err) {
  159.                         popstate_running = false;
  160.                 } finally {
  161.                         popstate_running = false;
  162.                 }
  163.         }
  164.  
  165.         // This loads the actual content
  166.  
  167.         document.title = "";
  168.         $('#real_title').html("&nbsp;");
  169.         $('#real_content').html(_L("Loading..."));
  170.         $('#static_link').attr("href", "index.php?goto="+encodeURIComponent(id));
  171.         $("#gotoedit").val(id);
  172.  
  173.         // Normal opening of a description
  174.         fetch('ajax.php?action=get_description&id='+encodeURIComponent(id))
  175.         .then(function(response) {
  176.                 response.json()
  177.                 .then(function(data) {
  178.                         if ("error" in data) {
  179.                                 alert(_L("Failed to load content") + ": " + data.error);
  180.                                 console.error(data.error);
  181.                                 return;
  182.                         }
  183.  
  184.                         data.id = id;
  185.  
  186.                         document.title = combine_systemtitle_and_pagetitle(getOidPlusSystemTitle(), data.title);
  187.                         var state = {
  188.                                 "node_id":id,
  189.                                 "titleHTML":(data.icon ? '<img src="'+data.icon+'" width="48" height="48" alt="'+data.title.htmlentities()+'"> ' : '') + data.title.htmlentities(),
  190.                                 "textHTML":data.text,
  191.                                 "staticlinkHREF":"index.php?goto="+encodeURIComponent(id),
  192.                         };
  193.                         if (current_node != id) {
  194.                                 window.history.pushState(state, data.title, "?goto="+encodeURIComponent(id));
  195.                         } else {
  196.                                 window.history.replaceState(state, data.title, "?goto="+encodeURIComponent(id));
  197.                         }
  198.  
  199.                         if (data.icon) {
  200.                                 $('#real_title').html('<img src="'+data.icon+'" width="48" height="48" alt="'+data.title.htmlentities()+'"> ' + data.title.htmlentities());
  201.                         } else {
  202.                                 $('#real_title').html(data.title.htmlentities());
  203.                         }
  204.                         $('#real_content').html(data.text);
  205.                         document.title = combine_systemtitle_and_pagetitle(getOidPlusSystemTitle(), data.title);
  206.                         current_node = id;
  207.  
  208.                         if (anchor != '') {
  209.                                 jumpToAnchor(anchor);
  210.                         }
  211.                 })
  212.                 .catch(function(error) {
  213.                         alert(_L("Failed to load content") + ": " + error);
  214.                         console.error(error);
  215.                 });
  216.         })
  217.         .catch(function(error) {
  218.                 alert(_L("Failed to load content") + ": " + error);
  219.                 console.error(error);
  220.         });
  221. }
  222.  
  223. // This function opens the "parentID" node, and then selects the "childID" node (which should be beneath the parent node)
  224. function openAndSelectNode(childID, parentID) {
  225.         if ($('#oidtree').jstree(true).get_node(parentID)) {
  226.                 $('#oidtree').jstree('open_node', parentID, function(e, data) { // open parent node
  227.                         if ($('#oidtree').jstree(true).get_node(childID)) { // is the child there?
  228.                                 $('#oidtree').jstree('deselect_all').jstree('select_node', childID); // select it
  229.                         } else {
  230.                                 // This can happen if the content page contains brand new items which are not in the treeview yet
  231.                                 $("#gotoedit").val(childID);
  232.                                 window.location.href = "?goto="+encodeURIComponent(childID);
  233.                         }
  234.                 }, true);
  235.         } else {
  236.                 // This should usually not happen
  237.                 $("#gotoedit").val(childID);
  238.                 window.location.href = "?goto="+encodeURIComponent(childID);
  239.         }
  240. }
  241.  
  242. $(window).on("popstate", function(e) {
  243.         popstate_running = true;
  244.         try {
  245.                 var data = e.originalEvent.state;
  246.  
  247.                 current_node = data.node_id;
  248.                 $("#gotoedit").val(current_node);
  249.                 $('#oidtree').jstree('deselect_all').jstree('select_node', data.node_id);
  250.                 $('#real_title').html(data.titleHTML);
  251.                 $('#real_content').html(data.textHTML);
  252.                 $('#static_link').attr("href", data.staticlinkHREF);
  253.                 document.title = combine_systemtitle_and_pagetitle(getOidPlusSystemTitle(), data.titleHTML.html_entity_decode());
  254.         } catch (err) {
  255.                 popstate_running = false;
  256.         } finally {
  257.                 popstate_running = false;
  258.         }
  259. });
  260.  
  261. $(document).ready(function () {
  262.  
  263.         // --- JsTree
  264.  
  265.         $('#oidtree')
  266.         .jstree({
  267.                 plugins: ['massload','search','conditionalselect'],
  268.                 'core' : {
  269.                         'data' : {
  270.                                 "url" : getTreeLoadURL(),
  271.                                 "data" : function (node) {
  272.                                         return { "id" : node.id };
  273.                                 }
  274.                         },
  275.                         "multiple": false
  276.                 },
  277.                 'conditionalselect' : function (node) {
  278.                         if (node.original.conditionalselect !== undefined) {
  279.                                 return eval(node.original.conditionalselect);
  280.                         } else {
  281.                                 return true; // allow select
  282.                         }
  283.                 },
  284.         })
  285.         .on('ready.jstree', function (e, data) {
  286.                 var url = new URL(window.location.href);
  287.                 var goto = url.searchParams.get("goto");
  288.                 if (goto == null) goto = "oidplus:system"; // the page was not called with ?goto=...
  289.                 $("#gotoedit").val(goto);
  290.  
  291.                 // By setting current_node, select_node() will not cause ajax.php?action=get_description to load (since we already loaded the first static content via PHP, for search engines mainly)
  292.                 // But then we need to set the history state manually
  293.                 current_node = goto;
  294.                 window.history.replaceState({
  295.                         "node_id":goto,
  296.                         "titleHTML":$('#real_title').html(),
  297.                         "textHTML":$('#real_content').html(),
  298.                         "staticlinkHREF":"index.php?goto="+encodeURIComponent(goto),
  299.                 }, $('#real_title').html(), "?goto="+encodeURIComponent(goto));
  300.  
  301.                 if (goto != null) data.instance.select_node([goto]);
  302.  
  303.                 setTimeout(glayoutWorkaroundA, 100);
  304.                 setTimeout(glayoutWorkaroundB, 100);
  305.         })
  306.         .on('select_node.jstree', function (node, selected, event) {
  307.                 mobileNavClose();
  308.  
  309.                 var id = selected.node.id;
  310.                 if ((!popstate_running) && (current_node != id)) {
  311.                         openOidInPanel(id, false);
  312.                 }
  313.         });
  314.  
  315.         // --- Layout
  316.  
  317.         document.getElementById('system_title_menu').style.display = "block";
  318.  
  319.         var tmpObjectTree = _L("OBJECT TREE").replace(/(.{1})/g,"$1<br>");
  320.         tmpObjectTree = tmpObjectTree.substring(0, tmpObjectTree.length-"<br>".length);
  321.  
  322.         $('#oidtree').addClass('ui-layout-west');
  323.         $('#content_window').addClass('ui-layout-center');
  324.         $('#system_title_bar').addClass('ui-layout-north');
  325.         glayout = $('#frames').layout({
  326.                 north__size:                  40,
  327.                 north__slidable:              false,
  328.                 north__closable:              false,
  329.                 north__resizable:             false,
  330.                 west__size:                   450,
  331.                 west__spacing_closed:         20,
  332.                 west__togglerLength_closed:   230,
  333.                 west__togglerAlign_closed:    "top",
  334.                 west__togglerContent_closed:  tmpObjectTree,
  335.                 west__togglerTip_closed:      _L("Open & Pin Menu"),
  336.                 west__sliderTip:              _L("Slide Open Menu"),
  337.                 west__slideTrigger_open:      "mouseover",
  338.                 center__maskContents:         true // IMPORTANT - enable iframe masking
  339.         });
  340.  
  341.         $("#gotobox").addClass("mobilehidden");
  342.         $("#languageBox").addClass("mobilehidden");
  343.         document.getElementById('gotobox').style.display = "block";
  344.         document.getElementById('languageBox').style.display = "block";
  345.         $('#gotoedit').keypress(function(event) {
  346.                 var keycode = (event.keyCode ? event.keyCode : event.which);
  347.                 if (keycode == '13') {
  348.                         gotoButtonClicked();
  349.                 }
  350.         });
  351. });
  352.  
  353. function glayoutWorkaroundA() {
  354.         // "Bug A": Sometimes, the design is completely destroyed after reloading the page. It does not help when glayout.resizeAll()
  355.         //          is called at the beginning (e.g. during the ready function), and it does not help if we wait 500ms.
  356.         //          So we do it all the time. It has probably something to do with slow loading times, since the error
  357.         //          does only appear when the page is "blank" for a short while while it is loading.
  358.         glayout.resizeAll();
  359.         setTimeout(glayoutWorkaroundA, 100);
  360.  
  361.         // "Bug C": With Firefox (And sometimes with Chrome), there is a gap between the content-window (including scroll bars)
  362.         //          and the right corner of the screen. Removing the explicit width solves this problem.
  363.         document.getElementById("content_window").style.removeProperty("width");
  364. }
  365.  
  366. function glayoutWorkaroundB() {
  367.         // "Bug B": Sometimes, after reload, weird space between oidtree and content window, because oidtree has size of 438px
  368.         document.getElementById("oidtree").style.width = "450px";
  369. }
  370.  
  371. function mobileNavClose() {
  372.         if ($("#system_title_menu").is(":hidden")) {
  373.                 return;
  374.         }
  375.  
  376.         $("#oidtree").slideUp("medium").promise().done(function() {
  377.                 $("#oidtree").addClass("ui-layout-west");
  378.                 $("#oidtree").show();
  379. //              $("#gotobox").hide();
  380. //              $("#languageBox").hide();
  381.                 $("#gotobox").addClass("mobilehidden");
  382.                 $("#languageBox").addClass("mobilehidden");
  383.         });
  384.         $("#system_title_menu").removeClass("active");
  385. }
  386.  
  387. function mobileNavOpen() {
  388.         $("#oidtree").hide();
  389.         $("#oidtree").removeClass("ui-layout-west");
  390.         $("#oidtree").slideDown("medium");
  391. //      $("#gotobox").show();
  392. //      $("#languageBox").show();
  393.         $("#gotobox").removeClass("mobilehidden");
  394.         $("#languageBox").removeClass("mobilehidden");
  395.         $("#system_title_menu").addClass("active");
  396. }
  397.  
  398. function mobileNavButtonClick(sender) {
  399.         if ($("#oidtree").hasClass("ui-layout-west")) {
  400.                 mobileNavOpen();
  401.         } else {
  402.                 mobileNavClose();
  403.         }
  404. }
  405.  
  406. function mobileNavButtonHover(sender) {
  407.         sender.classList.toggle("hover");
  408. }
  409.  
  410. function gotoButtonClicked() {
  411.         openOidInPanel($("#gotoedit").val(), 1);
  412. }
  413.  
  414. function jumpToAnchor(anchor) {
  415.         window.location.href = "#" + anchor;
  416. }
  417.  
  418. function getCookie(cname) {
  419.         // Source: https://www.w3schools.com/js/js_cookies.asp
  420.         var name = cname + "=";
  421.         var decodedCookie = decodeURIComponent(document.cookie);
  422.         var ca = decodedCookie.split(';');
  423.         for(var i = 0; i <ca.length; i++) {
  424.                 var c = ca[i];
  425.                 while (c.charAt(0) == ' ') {
  426.                         c = c.substring(1);
  427.                 }
  428.                 if (c.indexOf(name) == 0) {
  429.                         return c.substring(name.length, c.length);
  430.                 }
  431.         }
  432.         return undefined;
  433. }
  434.  
  435. function setLanguage(lngid) {
  436.         $.ajax({
  437.                 url:"ajax.php",
  438.                 method:"POST",
  439.                 data:{
  440.                         action:"set_language",
  441.                         language:lngid
  442.                 },
  443.                 error:function(jqXHR, textStatus, errorThrown) {
  444.                         console.error("Error: " + errorThrown);
  445.                 },
  446.                 success:function(data) {
  447.                         if ("error" in data) {
  448.                                 console.error(data);
  449.                         } else if (data.status == 0) {
  450.                                 $(".lng_flag").each(function(){
  451.                                         $(this).addClass("picture_grayout");
  452.                                 });
  453.                                 $("#lng_flag_"+lngid).removeClass("picture_grayout");
  454.                                 openOidInPanel(current_node, false);
  455.                         } else {
  456.                                 console.error(data);
  457.                         }
  458.                 }
  459.         });
  460. }
  461.  
  462. function getCurrentLang() {
  463.         var lang = getCookie('LANGUAGE');
  464.         return (typeof lang != "undefined") ? lang : DEFAULT_LANGUAGE;
  465. }
  466.  
  467. function _L(str) {
  468.         if (typeof language_messages[getCurrentLang()] == "undefined") return str;
  469.         var msg = language_messages[getCurrentLang()][str];
  470.         return (typeof msg != "undefined") ? msg : str;
  471. }
  472.