Subversion Repositories oidplus

Rev

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