main.js 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958
  1. /*
  2. * Password Management Servlets (PWM)
  3. * http://code.google.com/p/pwm/
  4. *
  5. * Copyright (c) 2006-2009 Novell, Inc.
  6. * Copyright (c) 2009-2015 The PWM Project
  7. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 2 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program; if not, write to the Free Software
  20. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  21. */
  22. "use strict";
  23. var PWM_GLOBAL = PWM_GLOBAL || {};
  24. var PWM_MAIN = PWM_MAIN || {};
  25. var PWM_VAR = PWM_VAR || {};
  26. PWM_MAIN.ajaxTimeout = 120 * 1000;
  27. PWM_MAIN.pageLoadHandler = function() {
  28. PWM_GLOBAL['localeBundle']=PWM_GLOBAL['localeBundle'] || [];
  29. PWM_GLOBAL['url-context']=PWM_MAIN.getObject('application-info').getAttribute('data-url-context');
  30. PWM_GLOBAL['pwmFormID']=PWM_MAIN.getObject('application-info').getAttribute('data-pwmFormID');
  31. PWM_GLOBAL['clientEtag']=PWM_MAIN.getObject('application-info').getAttribute('data-clientEtag');
  32. PWM_GLOBAL['restClientKey']=PWM_MAIN.getObject('application-info').getAttribute('data-restClientKey');
  33. require(["dojo/_base/array","dojo/_base/Deferred","dojo/promise/all"], function(array,Deferred,all){
  34. var promises = [];
  35. {
  36. var clientLoadDeferred = new Deferred();
  37. PWM_MAIN.loadClientData(function(){clientLoadDeferred.resolve()});
  38. promises.push(clientLoadDeferred.promise);
  39. }
  40. if (typeof PWM_CONFIG !== 'undefined') {
  41. PWM_GLOBAL['localeBundle'].push('Config');
  42. }
  43. if (typeof PWM_SETTINGS !== 'undefined' && typeof PWM_CFGEDIT !== 'undefined') {
  44. var clientConfigLoadDeferred = new Deferred();
  45. PWM_CFGEDIT.initConfigSettingsDefinition(function(){clientConfigLoadDeferred.resolve()});
  46. promises.push(clientConfigLoadDeferred.promise);
  47. }
  48. if (typeof PWM_ADMIN !== 'undefined') {
  49. PWM_GLOBAL['localeBundle'].push('Admin');
  50. var adminLoadDeferred = new Deferred();
  51. PWM_ADMIN.initAdminPage(function(){adminLoadDeferred.resolve()});
  52. promises.push(adminLoadDeferred.promise);
  53. }
  54. {
  55. var seenBundles = [];
  56. PWM_GLOBAL['localeBundle'].push('Display');
  57. array.forEach(PWM_GLOBAL['localeBundle'], function(bundleName){
  58. if (array.indexOf(seenBundles, bundleName) == -1) {
  59. var displayLoadDeferred = new Deferred();
  60. PWM_MAIN.loadLocaleBundle(bundleName,function(){displayLoadDeferred.resolve()});
  61. promises.push(displayLoadDeferred.promise);
  62. seenBundles.push(bundleName);
  63. }
  64. });
  65. }
  66. all(promises).then(function () {
  67. PWM_MAIN.initPage();
  68. });
  69. });
  70. };
  71. PWM_MAIN.loadClientData=function(completeFunction) {
  72. PWM_GLOBAL['app-data-client-retry-count'] = PWM_GLOBAL['app-data-client-retry-count'] + 1;
  73. var url = PWM_GLOBAL['url-context'] + "/public/rest/app-data/client?etag=" + PWM_GLOBAL['clientEtag'];
  74. var loadFunction = function(data) {
  75. for (var globalProp in data['data']['PWM_GLOBAL']) {
  76. PWM_GLOBAL[globalProp] = data['data']['PWM_GLOBAL'][globalProp];
  77. }
  78. console.log('loaded client data');
  79. if (completeFunction) completeFunction();
  80. };
  81. var errorFunction = function(error) {
  82. var errorMsg = 'unable to read app-data: ' + error;;
  83. console.log(errorMsg);
  84. if (!PWM_VAR['initError']) PWM_VAR['initError'] = errorMsg;
  85. if (completeFunction) completeFunction();
  86. };
  87. PWM_MAIN.ajaxRequest(url, loadFunction, {errorFunction:errorFunction,method:'GET',preventCache:false,addPwmFormID:false});
  88. };
  89. PWM_MAIN.loadLocaleBundle = function(bundleName, completeFunction) {
  90. var clientConfigUrl = PWM_GLOBAL['url-context'] + "/public/rest/app-data/strings/" + bundleName;
  91. clientConfigUrl = PWM_MAIN.addParamToUrl(clientConfigUrl,'etag',PWM_GLOBAL['clientEtag']);
  92. var loadFunction = function(data){
  93. if (data['error'] == true) {
  94. console.error('unable to load locale bundle from ' + clientConfigUrl + ', error: ' + data['errorDetail'])
  95. } else {
  96. PWM_GLOBAL['localeStrings'] = PWM_GLOBAL['localeStrings'] || {};
  97. PWM_GLOBAL['localeStrings'][bundleName] = {};
  98. for (var settingKey in data['data']) {
  99. PWM_GLOBAL['localeStrings'][bundleName][settingKey] = data['data'][settingKey];
  100. }
  101. }
  102. console.log('loaded locale bundle data for ' + bundleName);
  103. if (completeFunction) completeFunction();
  104. };
  105. var errorFunction = function(){
  106. var errorMsg = 'unable to load locale bundle from , please reload page (' + error + ')';
  107. console.log(errorMsg);
  108. if (!PWM_VAR['initError']) PWM_VAR['initError'] = errorMsg;
  109. if (completeFunction) completeFunction();
  110. };
  111. PWM_MAIN.ajaxRequest(clientConfigUrl,loadFunction,{errorFunction:errorFunction,method:'GET',preventCache:false,addPwmFormID:false});
  112. };
  113. PWM_MAIN.initPage = function() {
  114. PWM_MAIN.applyFormAttributes();
  115. try {
  116. PWM_MAIN.autofocusSupportExtension();
  117. } catch(e) {
  118. console.log('error during autofocus support extension: ' + e);
  119. }
  120. require(["dojo", "dojo/on"], function (dojo, on) {
  121. on(document, "keypress", function (event) {
  122. PWM_MAIN.checkForCapsLock(event);
  123. });
  124. require(["dojo/query","dojo/on"], function(query,on){
  125. var results = query('.pwm-link-print');
  126. for (var i = 0; i < results.length; i++) {
  127. (function(formIter){
  128. var element = results[formIter];
  129. on(element, "click", function(){ window.print(); });
  130. })(i);
  131. }
  132. });
  133. });
  134. if (PWM_MAIN.getObject('button_cancel')) {
  135. PWM_MAIN.getObject('button_cancel').style.visibility = 'visible';
  136. PWM_MAIN.addEventHandler('button_cancel', 'click', function () {
  137. PWM_MAIN.showWaitDialog({loadFunction:function() {
  138. PWM_MAIN.goto(PWM_GLOBAL['url-command'] + '?processAction=continue');
  139. }});
  140. });
  141. }
  142. if (PWM_MAIN.getObject('select-updateLoginContexts')) {
  143. PWM_MAIN.addEventHandler('select-updateLoginContexts', 'click', function () {
  144. PWM_MAIN.updateLoginContexts()
  145. });
  146. }
  147. PWM_MAIN.showTooltip({
  148. id: ['header-warning-message'],
  149. position: ['below', 'above'],
  150. text: '<pwm:display key="HealthMessage_Config_ConfigMode" bundle="Health"/>',
  151. width: 500
  152. });
  153. PWM_MAIN.addEventHandler('icon-configModeHelp','click',function(){
  154. PWM_MAIN.showDialog({title:'Notice - Configuration Status: Open',text:PWM_CONFIG.showString('Display_ConfigOpenInfo')});
  155. });
  156. if (PWM_GLOBAL['pageLeaveNotice'] > 0) {
  157. require(["dojo","dojo/on"], function(dojo,on){
  158. on(document, "beforeunload", function(){
  159. dojo.xhrPost({
  160. url: PWM_GLOBAL['url-command'] + "?processAction=pageLeaveNotice&pwmFormID=" + PWM_GLOBAL['pwmFormID'],
  161. preventCache: true,
  162. sync: true
  163. });
  164. });
  165. });
  166. }
  167. if (PWM_MAIN.getObject('message')) {
  168. PWM_GLOBAL['message_originalStyle'] = PWM_MAIN.getObject('message').style;
  169. require(["dojo","dojo/on"], function(dojo,on){
  170. if(dojo.isIE <= 8){
  171. return;
  172. }
  173. on(window, "resize", function(){ PWM_MAIN.messageDivFloatHandler() });
  174. on(window, "scroll", function(){ PWM_MAIN.messageDivFloatHandler() });
  175. });
  176. }
  177. require(["dojo/domReady!"],function(){
  178. if (PWM_GLOBAL['enableIdleTimeout']) {
  179. PWM_MAIN.IdleTimeoutHandler.initCountDownTimer(PWM_GLOBAL['MaxInactiveInterval']);
  180. }
  181. PWM_MAIN.initLocaleSelectorMenu('localeSelectionMenu');
  182. });
  183. if (PWM_MAIN.getObject('LogoutButton')) {
  184. PWM_MAIN.showTooltip({
  185. id: 'LogoutButton',
  186. position: ['below', 'above'],
  187. text: PWM_MAIN.showString("Long_Title_Logout"),
  188. width: 500
  189. });
  190. }
  191. for (var i = 0; i < PWM_GLOBAL['startupFunctions'].length; i++) {
  192. try {
  193. PWM_GLOBAL['startupFunctions'][i]();
  194. } catch(e) {
  195. console.error('error executing startup function: ' + e);
  196. }
  197. }
  198. PWM_MAIN.TimestampHandler.initAllElements();
  199. ShowHidePasswordHandler.initAllForms();
  200. PWM_MAIN.preloadResources();
  201. console.log('initPage completed');
  202. };
  203. PWM_MAIN.closeHeaderWarningPanel = function() {
  204. console.log('action closeHeader');
  205. PWM_MAIN.setStyle('header-warning','display','none');
  206. PWM_MAIN.setStyle('button-openHeader','display','inherit');
  207. require(["dojo/cookie"], function(cookie){
  208. cookie('headerVisibility', 'hide', {});
  209. });
  210. };
  211. PWM_MAIN.openHeaderWarningPanel = function() {
  212. console.log('action openHeader');
  213. PWM_MAIN.setStyle('header-warning','display','inherit');
  214. PWM_MAIN.setStyle('button-openHeader','display','none');
  215. require(["dojo/cookie"], function(cookie){
  216. cookie('headerVisibility', 'show', {});
  217. });
  218. };
  219. PWM_MAIN.applyFormAttributes = function() {
  220. require(["dojo/_base/array", "dojo/query", "dojo/on"], function(array, query, on){
  221. array.forEach(
  222. query("form"),
  223. function(formElement){
  224. formElement.setAttribute('autocomplete', 'off');
  225. //ios/webkit
  226. formElement.setAttribute('autocapitalize', 'none');
  227. formElement.setAttribute('autocorrect', 'off');
  228. }
  229. );
  230. array.forEach(
  231. query(".pwm-form"),
  232. function(formElement){
  233. on(formElement, "submit", function(event){
  234. PWM_MAIN.handleFormSubmit(formElement, event);
  235. });
  236. }
  237. );
  238. array.forEach(
  239. query("a:not([target])"),
  240. function(linkElement){
  241. var hrefValue = linkElement.getAttribute('href');
  242. if (hrefValue && hrefValue.charAt(0) != '#') {
  243. on(linkElement, "click", function (event) {
  244. event.preventDefault();
  245. PWM_MAIN.showWaitDialog({loadFunction: function () {
  246. PWM_MAIN.goto(hrefValue);
  247. }});
  248. });
  249. linkElement.removeAttribute('href');
  250. }
  251. }
  252. );
  253. });
  254. };
  255. PWM_MAIN.preloadAll = function(nextFunction) {
  256. require(["dijit/Dialog","dijit/ProgressBar","dijit/registry","dojo/_base/array","dojo/on","dojo/data/ObjectStore",
  257. "dojo/store/Memory","dijit/Tooltip","dijit/Menu","dijit/MenuItem","dijit/MenuSeparator"],function(){
  258. PWM_MAIN.preloadResources(nextFunction);
  259. });
  260. };
  261. PWM_MAIN.preloadResources = function(nextFunction) {
  262. var prefix = PWM_GLOBAL['url-resources'] + '/dojo/dijit/themes/';
  263. var images = [
  264. prefix + 'a11y/indeterminate_progress.gif',
  265. prefix + 'nihilo/images/progressBarAnim.gif',
  266. prefix + 'nihilo/images/progressBarEmpty.png',
  267. prefix + 'nihilo/images/spriteRoundedIconsSmall.png',
  268. prefix + 'nihilo/images/titleBar.png'
  269. ];
  270. PWM_MAIN.preloadImages(images);
  271. if (nextFunction) {
  272. nextFunction();
  273. }
  274. };
  275. PWM_MAIN.showString = function (key, options) {
  276. options = options === undefined ? {} : options;
  277. var bundle = ('bundle' in options) ? options['bundle'] : 'Display';
  278. PWM_GLOBAL['localeStrings'] = PWM_GLOBAL['localeStrings'] || {};
  279. if (!PWM_GLOBAL['localeStrings'][bundle]) {
  280. return "UNDEFINED BUNDLE: " + bundle;
  281. }
  282. if (PWM_GLOBAL['localeStrings'][bundle][key]) {
  283. var returnStr = PWM_GLOBAL['localeStrings'][bundle][key];
  284. for (var i = 0; i < 10; i++) {
  285. if (options['value' + i]) {
  286. returnStr = returnStr.replace('%' + i + '%',options['value' + i]);
  287. }
  288. }
  289. return returnStr;
  290. } else {
  291. return "UNDEFINED STRING-" + key;
  292. }
  293. };
  294. PWM_MAIN.addEventHandler = function(nodeId,eventType,functionToAdd) {
  295. var element = PWM_MAIN.getObject(nodeId);
  296. if (element) {
  297. require(["dojo", "dojo/on"], function (dojo, on) {
  298. if (dojo.isIE <= 9 && eventType == 'input') {
  299. on(element, 'change', functionToAdd);
  300. on(element, 'keyup', functionToAdd);
  301. }
  302. on(element, eventType, functionToAdd);
  303. });
  304. }
  305. };
  306. PWM_MAIN.goto = function(url,options) {
  307. PWM_VAR['dirtyPageLeaveFlag'] = false;
  308. options = options === undefined ? {} : options;
  309. if (!('noContext' in options) && url.indexOf(PWM_GLOBAL['url-context']) != 0) {
  310. if (url.substring(0,1) == '/') {
  311. url = PWM_GLOBAL['url-context'] + url;
  312. }
  313. }
  314. if ('addFormID' in options) {
  315. if (url.indexOf('pwmFormID') == -1) {
  316. url = PWM_MAIN.addPwmFormIDtoURL(url);
  317. }
  318. }
  319. var executeGoto = function() {
  320. if (options['delay']) {
  321. setTimeout(function () {
  322. console.log('redirecting to new url: ' + url);
  323. window.location = url;
  324. }, options['delay']);
  325. } else {
  326. console.log('redirecting to new url: ' + url);
  327. window.location = url;
  328. }
  329. };
  330. var hideDialog = options['hideDialog'] = true;
  331. if (hideDialog) {
  332. executeGoto();
  333. } else {
  334. PWM_MAIN.showWaitDialog({loadFunction:function () {
  335. executeGoto();
  336. }});
  337. }
  338. };
  339. PWM_MAIN.handleLoginFormSubmit = function(form, event) {
  340. console.log('entering handleLoginFormSubmit');
  341. PWM_MAIN.cancelEvent(event);
  342. require(["dojo","dojo/dom-form"], function(dojo, domForm) {
  343. PWM_MAIN.showWaitDialog({loadFunction: function () {
  344. var options = {};
  345. options['content'] = domForm.toObject(form);
  346. delete options['content']['processAction'];
  347. delete options['content']['pwmFormID'];
  348. var url = 'Login?processAction=restLogin';
  349. var loadFunction = function(data) {
  350. if (data['error'] == true) {
  351. PWM_MAIN.showErrorDialog(data,{
  352. okAction:function(){
  353. PWM_MAIN.getObject('password').value = '';
  354. PWM_MAIN.getObject('password').focus();
  355. }
  356. });
  357. return;
  358. }
  359. console.log('authentication success');
  360. var nextURL = data['data']['nextURL'];
  361. if (nextURL) {
  362. PWM_MAIN.goto(nextURL, {noContext: true});
  363. }
  364. };
  365. PWM_MAIN.ajaxRequest(url,loadFunction,options);
  366. }});
  367. });
  368. };
  369. PWM_MAIN.handleFormSubmit = function(form, event) {
  370. console.log('entering handleFormSubmit');
  371. PWM_MAIN.cancelEvent(event);
  372. PWM_GLOBAL['idle_suspendTimeout'] = true;
  373. var formElements = form.elements;
  374. for (var i = 0; i < formElements.length; i++) {
  375. formElements[i].readOnly = true;
  376. if (formElements[i].type == 'button' || formElements[i].type == 'submit') {
  377. formElements[i].disabled = true;
  378. }
  379. }
  380. PWM_MAIN.showWaitDialog({loadFunction:function(){
  381. form.submit();
  382. }});
  383. return false;
  384. };
  385. PWM_MAIN.handleFormClear = function() {
  386. var focusSet = false;
  387. var clearableFields = ['text','email','number','password','random','tel','hidden','date','datetime','time','week','month','url','select'];
  388. require(["dojo/_base/array"],function(array){
  389. for (var j = 0; j < document.forms.length; j++) {
  390. for (var i = 0; i < document.forms[j].length; i++) {
  391. var current = document.forms[j].elements[i];
  392. if (current.type && array.indexOf(clearableFields,current.type.toLowerCase()) >= 0) {
  393. current.value = '';
  394. if (!focusSet) {
  395. current.focus();
  396. focusSet = true;
  397. }
  398. } else if (current.type == 'select') {
  399. current.selectedIndex = -1;
  400. }
  401. }
  402. }
  403. });
  404. return false;
  405. };
  406. PWM_MAIN.checkForCapsLock = function(e) {
  407. require(["dojo","dojo/_base/fx","dojo/domReady!"],function(dojo,fx){
  408. var capsLockWarningElement = PWM_MAIN.getObject('capslockwarning');
  409. if (capsLockWarningElement == null) {
  410. return;
  411. }
  412. var capsLockKeyDetected = false;
  413. {
  414. var elementTarget = null;
  415. if (e.target != null) {
  416. elementTarget = e.target;
  417. } else if (e.srcElement != null) {
  418. elementTarget = e.srcElement;
  419. }
  420. if (elementTarget != null) {
  421. if (elementTarget.nodeName == 'input' || elementTarget.nodeName == 'INPUT') {
  422. var kc = e.keyCode ? e.keyCode : e.which;
  423. var sk = e.shiftKey ? e.shiftKey : ((kc == 16));
  424. if (((kc >= 65 && kc <= 90) && !sk) || ((kc >= 97 && kc <= 122) && sk)) {
  425. capsLockKeyDetected = true;
  426. }
  427. }
  428. }
  429. }
  430. var displayDuration = 5 * 1000;
  431. var fadeOutArgs = { node: "capslockwarning", duration: 3 * 1000 };
  432. var fadeInArgs = { node: "capslockwarning", duration: 200 };
  433. if(dojo.isIE){
  434. if (capsLockKeyDetected) {
  435. capsLockWarningElement.style.display = 'block';
  436. PWM_GLOBAL['lastCapsLockErrorTime'] = (new Date().getTime());
  437. setTimeout(function(){
  438. if ((new Date().getTime() - PWM_GLOBAL['lastCapsLockErrorTime'] > displayDuration)) {
  439. capsLockWarningElement.style.display = 'none';
  440. }
  441. },displayDuration + 500);
  442. } else {
  443. capsLockWarningElement.style.display = 'none';
  444. }
  445. } else {
  446. if (capsLockKeyDetected) {
  447. capsLockWarningElement.style.display = null;
  448. fx.fadeIn(fadeInArgs).play();
  449. PWM_GLOBAL['lastCapsLockErrorTime'] = (new Date().getTime());
  450. setTimeout(function(){
  451. if ((new Date().getTime() - PWM_GLOBAL['lastCapsLockErrorTime'] > displayDuration)) {
  452. dojo.fadeOut(fadeOutArgs).play();
  453. setTimeout(function(){
  454. if ((new Date().getTime() - PWM_GLOBAL['lastCapsLockErrorTime'] > displayDuration)) {
  455. capsLockWarningElement.style.display = 'none';
  456. }
  457. },5 * 1000);
  458. }
  459. },displayDuration + 500);
  460. } else {
  461. fx.fadeOut(fadeOutArgs).play();
  462. }
  463. }
  464. });
  465. };
  466. PWM_MAIN.getObject = function(name) {
  467. if (name == null) {
  468. return null;
  469. }
  470. if (name.tagName) { // argument is already a dom element
  471. return name;
  472. }
  473. var ns4 = document.layers;
  474. var w3c = document.getElementById;
  475. var ie4 = document.all;
  476. if (ns4) {
  477. return eval('document.' + name);
  478. }
  479. if (w3c) {
  480. return document.getElementById(name);
  481. }
  482. if (ie4) {
  483. return eval('document.all.' + name);
  484. }
  485. return false;
  486. };
  487. PWM_MAIN.trimString = function(sInString) {
  488. sInString = sInString.replace(/^\s+/g, "");
  489. // strip leading
  490. return sInString.replace(/\s+$/g, "");
  491. // strip trailing
  492. };
  493. PWM_MAIN.showTooltip = function(options){
  494. options = options === undefined ? {} : options;
  495. if (!options['id']) {
  496. return;
  497. }
  498. var id = options['id'] instanceof Array ? options['id'] : [options['id']];
  499. var position = options['position'] instanceof Array ? options['position'] : null;
  500. var dojoOptions = {};
  501. dojoOptions['connectId'] = id;
  502. dojoOptions['id'] = id[0];
  503. dojoOptions['label'] = 'text' in options ? options['text'] : "missing text option";
  504. if (position) {
  505. dojoOptions['position'] = position;
  506. }
  507. if (options['width']) {
  508. dojoOptions['label'] = '<div style="max-width:' + options['width'] + 'px">' + dojoOptions['label'] + '</div>'
  509. }
  510. require(["dijit/Tooltip","dijit/registry"],function(Tooltip){
  511. PWM_MAIN.clearDijitWidget(id[0]);
  512. new Tooltip(dojoOptions);
  513. });
  514. };
  515. PWM_MAIN.clearDijitWidget = function (widgetName) {
  516. require(["dojo","dijit/registry"],function(dojo, registry){
  517. var oldDijitNode = registry.byId(widgetName);
  518. if (oldDijitNode != null) {
  519. try {
  520. oldDijitNode.destroyRecursive();
  521. } catch (error) {
  522. console.log('error destroying old widget: ' + error);
  523. }
  524. try {
  525. oldDijitNode.destroy();
  526. } catch (error) {
  527. console.log('error destroying old widget: ' + error);
  528. }
  529. }
  530. });
  531. };
  532. PWM_MAIN.initLocaleSelectorMenu = function(attachNode) {
  533. if (PWM_MAIN.getObject(attachNode) == null) {
  534. return;
  535. }
  536. require(["dojo","dijit/Menu","dijit/MenuItem","dijit/MenuSeparator","dojo/domReady!"],function(dojo,dijitMenu,dijitMenuItem,dijitMenuSeparator){
  537. if(dojo.isIE <= 8){ // IE8 and below cant handle the css associated with the locale select menu
  538. dojo.connect(PWM_MAIN.getObject(attachNode),"click",function(){
  539. PWM_MAIN.goto("/public/localeselect.jsp");
  540. });
  541. } else {
  542. for (var iter in PWM_GLOBAL['localeFlags']) {
  543. (function(localeKey){
  544. var flagCode = PWM_GLOBAL['localeFlags'][localeKey];
  545. if (flagCode && flagCode.length > 0) {
  546. var cssBody = 'background-image: url(' + PWM_GLOBAL['url-context'] + '/public/resources/flags/png/' + flagCode + '.png)';
  547. var cssSelector = '.flagLang_' + localeKey;
  548. PWM_MAIN.createCSSClass(cssSelector, cssBody);
  549. }
  550. })(iter);
  551. }
  552. var localeData = PWM_GLOBAL['localeInfo'];
  553. var pMenu = new dijitMenu({
  554. targetNodeIds: [attachNode],
  555. leftClickToOpen: true
  556. });
  557. pMenu.startup();
  558. var loopFunction = function(pMenu, localeKey, localeDisplayName, localeIconClass) {
  559. pMenu.addChild(new dijitMenuItem({
  560. label: localeDisplayName,
  561. iconClass: localeIconClass,
  562. onClick: function() {
  563. var nextUrl = window.location.toString();
  564. if (window.location.toString().indexOf('?') > 0) {
  565. var params = dojo.queryToObject(window.location.search.substring(1,window.location.search.length));
  566. params['locale'] = localeKey;
  567. nextUrl = window.location.toString().substring(0, window.location.toString().indexOf('?') + 1)
  568. + dojo.objectToQuery(params);
  569. } else {
  570. nextUrl = PWM_MAIN.addParamToUrl(nextUrl, 'locale', localeKey)
  571. }
  572. PWM_MAIN.goto(nextUrl);
  573. }
  574. }));
  575. };
  576. for (var localeKey in localeData) {
  577. var loopDisplayName = localeData[localeKey];
  578. var loopIconClass = "flagLang_" + (localeKey == '' ? 'en' : localeKey);
  579. var loopKey = localeKey == '' ? 'default' : localeKey;
  580. loopFunction(pMenu, loopKey, loopDisplayName, loopIconClass);
  581. }
  582. pMenu.addChild(new dijitMenuSeparator());
  583. pMenu.addChild(new dijitMenuItem({
  584. label: PWM_MAIN.showString('Title_LocaleSelect'),
  585. onClick: function() {
  586. PWM_MAIN.showWaitDialog({loadFunction:function() {
  587. window.location = PWM_GLOBAL['url-context'] + '/public/localeselect.jsp'
  588. }});
  589. }
  590. }));
  591. }
  592. });
  593. };
  594. PWM_MAIN.showErrorDialog = function(error, options) {
  595. options = options === undefined ? {} : options;
  596. var forceReload = false;
  597. var body = '';
  598. var logMsg = '';
  599. var titleMsg = PWM_MAIN.showString('Title_Error');
  600. if ('text' in options) {
  601. body += options['text'];
  602. body += '<br/><br/>';
  603. logMsg += options['text'];
  604. }
  605. if (error && error['error']) {
  606. var code = error['errorCode'];
  607. if (code == 5028 || code == 5035) {
  608. forceReload = true;
  609. }
  610. titleMsg += ' ' + error['errorCode'];
  611. logMsg += ' ' + error['errorCode'];
  612. body += error['errorMessage'];
  613. logMsg += error['errorCode'] + "," + error['errorMessage'];
  614. if (error['errorDetail']) {
  615. body += "<br/><br/><div style='max-height: 250px; overflow-y: auto'>" + error['errorDetail'] + '</div>';
  616. logMsg += ", detail: " + error['errorDetail'];
  617. }
  618. } else {
  619. body += error;
  620. logMsg += error;
  621. }
  622. if (forceReload) {
  623. logMsg += 'due to error code type, reloading page.';
  624. }
  625. console.log('displaying error message: ' + logMsg);
  626. options['title'] = titleMsg;
  627. options['text'] = body;
  628. options['okAction'] = function() {
  629. if (forceReload) { // incorrect page sequence;
  630. var newURL = window.location.pathname;
  631. PWM_MAIN.goto(newURL);
  632. PWM_MAIN.showWaitDialog();
  633. }
  634. };
  635. PWM_MAIN.showDialog(options);
  636. };
  637. PWM_MAIN.showWaitDialog = function(options) {
  638. require(["dojo","dijit/Dialog","dijit/ProgressBar"],function(dojo,Dialog,ProgressBar){
  639. options = options || {};
  640. var requestedLoadFunction = options['loadFunction'];
  641. options['loadFunction'] = function() {
  642. PWM_MAIN.clearDijitWidget('progressBar');
  643. var progressBar = new ProgressBar({
  644. style: '',
  645. indeterminate:true
  646. },"progressBar");
  647. PWM_MAIN.preloadResources(function(){
  648. if (requestedLoadFunction) {
  649. requestedLoadFunction();
  650. }
  651. });
  652. };
  653. options['title'] = options['title'] || PWM_MAIN.showString('Display_PleaseWait');
  654. var supportsProgress = (document.createElement('progress').max !== undefined);
  655. if (supportsProgress) {
  656. options['text'] = options['text'] || '<progress id="wait">';
  657. } else {
  658. options['text'] = options['text'] || '<div id="progressBar" style="margin: 8px; width: 100%"/>';
  659. }
  660. options['dialogClass'] = 'narrow';
  661. options['showOk'] = false;
  662. PWM_MAIN.showDialog(options);
  663. });
  664. };
  665. PWM_MAIN.html5DialogSupport = function() {
  666. if (PWM_GLOBAL['client.js.enableHtml5Dialog']) {
  667. var testdialog = document.createElement("dialog");
  668. testdialog.setAttribute("open", "");
  669. return (testdialog.open == true);
  670. }
  671. return false;
  672. };
  673. PWM_MAIN.showDialog = function(options) {
  674. var html5Dialog = PWM_MAIN.html5DialogSupport();
  675. options = options === undefined ? {} : options;
  676. var title = options['title'] || 'DialogTitle';
  677. var text = 'text' in options ? options['text'] : 'DialogBody';
  678. var closeOnOk = 'closeOnOk' in options ? options['closeOnOk'] : true;
  679. var showOk = 'showOk' in options ? options['showOk'] : true;
  680. var showCancel = 'showCancel' in options ? options['showCancel'] : false;
  681. var showClose = 'showClose' in options ? options['showClose'] : false;
  682. var allowMove = 'allowMove' in options ? options['allowMove'] : false;
  683. var idName = 'id' in options ? options['id'] : 'dialogPopup';
  684. var dialogClass = 'dialogClass' in options ? options['dialogClass'] : null;
  685. var okAction = function(){
  686. if (closeOnOk) {
  687. PWM_MAIN.closeWaitDialog(idName);
  688. }
  689. if ('okAction' in options) {
  690. options['okAction']();
  691. } else {
  692. console.log('dialog okAction is empty')
  693. }
  694. };
  695. var cancelAction = 'cancelAction' in options ? options['cancelAction'] : function(){
  696. PWM_MAIN.closeWaitDialog(idName);
  697. console.log('no-dialog-cancelaction')
  698. };
  699. var loadFunction = 'loadFunction' in options ? options['loadFunction'] : function(){
  700. console.log('no-dialog-loadfunction')
  701. };
  702. PWM_VAR['dialog_loadFunction'] = loadFunction;
  703. var bodyText = '';
  704. bodyText += text;
  705. if (showOk || showCancel) {
  706. bodyText += '<div class="buttonbar">';
  707. }
  708. if (showOk) {
  709. bodyText += '<button class="btn" id="dialog_ok_button">'
  710. + '<span class="btn-icon fa fa-check-square-o"></span>'
  711. + PWM_MAIN.showString('Button_OK') + '</button> ';
  712. }
  713. if (showCancel) {
  714. bodyText += '<button class="btn" id="dialog_cancel_button">'
  715. + '<span class="btn-icon fa fa-times"></span>'
  716. + PWM_MAIN.showString('Button_Cancel') + '</button> ';
  717. }
  718. var dialogClassText = 'dialogBody';
  719. if (dialogClass) {
  720. dialogClassText += ' ' + dialogClass;
  721. }
  722. if (showOk || showCancel) {
  723. bodyText += '</div>';
  724. }
  725. bodyText = '<div class="' + dialogClassText + '">' + bodyText + '</div>';
  726. if (html5Dialog) {
  727. PWM_MAIN.closeWaitDialog();
  728. var dialogElement = document.createElement("dialog");
  729. dialogElement.setAttribute("id", 'html5Dialog');
  730. //dialogElement.setAttribute("draggable","true");
  731. var html5DialogHtml = '<div class="titleBar">' + title;
  732. if (showClose) {
  733. html5DialogHtml += '<div id="icon-closeDialog" class="closeIcon fa fa-times"></div>'
  734. }
  735. html5DialogHtml += '</div><div class="body">' + bodyText + '</div>';
  736. dialogElement.innerHTML = html5DialogHtml;
  737. document.body.appendChild(dialogElement);
  738. dialogElement.showModal();
  739. setTimeout(function () {
  740. if (showOk) {
  741. PWM_MAIN.addEventHandler('dialog_ok_button', 'click', function () {
  742. okAction()
  743. });
  744. }
  745. if (showClose) {
  746. PWM_MAIN.addEventHandler('icon-closeDialog', 'click', function () {
  747. PWM_MAIN.closeWaitDialog();
  748. });
  749. }
  750. if (showCancel) {
  751. PWM_MAIN.addEventHandler('dialog_cancel_button', 'click', function () {
  752. cancelAction()
  753. });
  754. }
  755. setTimeout(loadFunction, 100);
  756. }, 100);
  757. } else {
  758. require(["dojo", "dijit/Dialog"], function (dojo, Dialog) {
  759. PWM_MAIN.clearDijitWidget(idName);
  760. var theDialog = new Dialog({
  761. id: idName,
  762. closable: showClose,
  763. draggable: allowMove,
  764. title: title,
  765. content: bodyText
  766. });
  767. if (!showClose) {
  768. dojo.style(theDialog.closeButtonNode, "display", "none");
  769. }
  770. dojo.connect(theDialog, "onShow", null, function () {
  771. if (showOk) {
  772. PWM_MAIN.addEventHandler('dialog_ok_button', 'click', function () {
  773. okAction()
  774. });
  775. }
  776. if (showCancel) {
  777. PWM_MAIN.addEventHandler('dialog_cancel_button', 'click', function () {
  778. cancelAction()
  779. });
  780. }
  781. setTimeout(loadFunction, 100);
  782. });
  783. theDialog.show();
  784. });
  785. }
  786. };
  787. PWM_MAIN.showEula = function(requireAgreement, agreeFunction) {
  788. if (agreeFunction && PWM_GLOBAL['eulaAgreed']) {
  789. agreeFunction();
  790. return;
  791. }
  792. var eulaLocation = PWM_GLOBAL['url-resources'] + '/text/eula.html';
  793. PWM_GLOBAL['dialog_agreeAction'] = agreeFunction ? agreeFunction : function(){};
  794. var bodyText = '<iframe width="600" height="400" src="' + eulaLocation + '">';
  795. bodyText += '</iframe>';
  796. bodyText += '<div style="width: 100%; text-align: center">';
  797. if (requireAgreement) {
  798. bodyText += '<input type="button" class="btn" value="' + PWM_MAIN.showString('Button_Agree') + '" onclick="PWM_GLOBAL[\'eulaAgreed\']=true;PWM_MAIN.clearDijitWidget(\'dialogPopup\');PWM_GLOBAL[\'dialog_agreeAction\']()"/>';
  799. bodyText += '<input type="button" class="btn" value="' + PWM_MAIN.showString('Button_Cancel') + '" onclick="PWM_MAIN.closeWaitDialog()"/>';
  800. } else {
  801. bodyText += '<input type="button" class="btn" value="' + PWM_MAIN.showString('Button_OK') + '" onclick="PWM_MAIN.closeWaitDialog()"/>';
  802. }
  803. bodyText += '</div>'
  804. PWM_MAIN.clearDijitWidget('dialogPopup');
  805. require(["dijit/Dialog"], function(Dialog){
  806. new Dialog({
  807. title: "End User License Agreement",
  808. id: 'dialogPopup',
  809. content: bodyText
  810. }).show();
  811. });
  812. };
  813. PWM_MAIN.showConfirmDialog = function(options) {
  814. options = options == undefined ? {} : options;
  815. options['showCancel'] = true;
  816. options['title'] = 'title' in options ? options['title'] : PWM_MAIN.showString('Button_Confirm');
  817. options['text'] = 'text' in options ? options['text'] : PWM_MAIN.showString('Confirm');
  818. PWM_MAIN.showDialog(options);
  819. };
  820. PWM_MAIN.closeWaitDialog = function(idName) {
  821. var html5Mode = PWM_MAIN.html5DialogSupport();
  822. if (html5Mode) {
  823. if (PWM_MAIN.getObject('html5Dialog')) {
  824. PWM_MAIN.getObject('html5Dialog').parentNode.removeChild(PWM_MAIN.getObject('html5Dialog'));
  825. }
  826. return;
  827. }
  828. idName = idName == undefined ? 'dialogPopup' : idName;
  829. PWM_MAIN.clearDijitWidget(idName);
  830. };
  831. PWM_MAIN.clearError=function() {
  832. PWM_GLOBAL['messageStatus'] = '';
  833. PWM_MAIN.doShow('messageStatus','\u00a0');
  834. };
  835. PWM_MAIN.showInfo=function(infoMsg) {
  836. PWM_GLOBAL['messageStatus'] = 'message-info';
  837. PWM_MAIN.doShow('message-info',infoMsg);
  838. };
  839. PWM_MAIN.showError=function(errorMsg) {
  840. PWM_GLOBAL['messageStatus'] = 'message-error';
  841. PWM_MAIN.doShow('message-error',errorMsg);
  842. };
  843. PWM_MAIN.showSuccess=function(successMsg) {
  844. PWM_GLOBAL['messageStatus'] = 'message-success';
  845. PWM_MAIN.doShow('message-success',successMsg);
  846. };
  847. PWM_MAIN.doShow = function(destClass, message, fromFloatHandler) {
  848. var messageElement = PWM_MAIN.getObject("message");
  849. if (messageElement == null || messageElement.firstChild == null || messageElement.firstChild.nodeValue == null) {
  850. return;
  851. }
  852. if (destClass == '') {
  853. require(["dojo/dom", "dojo/_base/fx"],function(dom, fx){
  854. var fadeArgs = { node: "message", duration: 500 };
  855. fx.fadeOut(fadeArgs).play();
  856. });
  857. return;
  858. }
  859. messageElement.firstChild.nodeValue = message;
  860. try {
  861. messageElement.style.display = 'inherit'; // doesn't work in older ie browsers
  862. } catch (e) {
  863. messageElement.style.display = 'block';
  864. }
  865. messageElement.style.opacity = '1';
  866. require(["dojo","dojo/dom-style"],function(dojo,domStyle){
  867. if(dojo.isIE <= 8){ // only IE7 and below
  868. messageElement.className = "message " + destClass;
  869. } else {
  870. try {
  871. // create a temp element and place it on the page to figure out what the destination color should be
  872. var tempDivElement = document.createElement('div');
  873. tempDivElement.className = "message " + destClass;
  874. tempDivElement.style.display = "none";
  875. tempDivElement.id = "tempDivElement";
  876. messageElement.appendChild(tempDivElement);
  877. var destStyle = window.getComputedStyle(tempDivElement, null);
  878. var destBackground = destStyle.backgroundColor;
  879. var destColor = destStyle.color;
  880. messageElement.removeChild(tempDivElement);
  881. dojo.animateProperty({
  882. node:"message",
  883. duration: 500,
  884. properties: {
  885. backgroundColor: destBackground,
  886. color: destColor
  887. }
  888. }).play();
  889. } catch (e) {
  890. messageElement.className = "message " + destClass;
  891. }
  892. if (!fromFloatHandler) {
  893. PWM_MAIN.messageDivFloatHandler();
  894. }
  895. }
  896. });
  897. };
  898. PWM_MAIN.createCSSClass = function(selector, style) {
  899. // using information found at: http://www.quirksmode.org/dom/w3c_css.html
  900. // doesn't work in older versions of Opera (< 9) due to lack of styleSheets support
  901. if(!document.styleSheets) return;
  902. if(document.getElementsByTagName("head").length == 0) return;
  903. var styleSheet;
  904. var mediaType;
  905. if(document.styleSheets.length > 0)
  906. {
  907. for(var i = 0; i<document.styleSheets.length; i++)
  908. {
  909. if(document.styleSheets[i].disabled) continue;
  910. var media = document.styleSheets[i].media;
  911. mediaType = typeof media;
  912. // IE
  913. if(mediaType == "string")
  914. {
  915. if(media == "" || media.indexOf("screen") != -1)
  916. {
  917. styleSheet = document.styleSheets[i];
  918. }
  919. }
  920. else if(mediaType == "object")
  921. {
  922. try {
  923. if(media.mediaText == "" || media.mediaText.indexOf("screen") != -1)
  924. {
  925. styleSheet = document.styleSheets[i];
  926. }
  927. } catch (e) { /* noop */ }
  928. }
  929. // stylesheet found, so break out of loop
  930. if(typeof styleSheet != "undefined") break;
  931. }
  932. }
  933. // if no style sheet is found
  934. if(typeof styleSheet == "undefined")
  935. {
  936. // create a new style sheet
  937. var styleSheetElement = document.createElement("style");
  938. styleSheetElement.type = "text/css";
  939. // add to <head>
  940. document.getElementsByTagName("head")[0].appendChild(styleSheetElement);
  941. // select it
  942. for(i = 0; i<document.styleSheets.length; i++)
  943. {
  944. if(document.styleSheets[i].disabled) continue;
  945. styleSheet = document.styleSheets[i];
  946. }
  947. // read media type
  948. var media = styleSheet.media;
  949. mediaType = typeof media;
  950. }
  951. // IE
  952. if(mediaType == "string")
  953. {
  954. for(i = 0;i<styleSheet.rules.length;i++)
  955. {
  956. // if there is an existing rule set up, replace it
  957. try {
  958. if(styleSheet.cssRules[i].selectorText && styleSheet.rules[i].selectorText.toLowerCase() == selector.toLowerCase())
  959. {
  960. styleSheet.rules[i].style.cssText = style;
  961. return;
  962. }
  963. } catch (e) {
  964. console.log('error while checking existing rules during cssCreate:' + e);
  965. }
  966. }
  967. // or add a new rule
  968. styleSheet.addRule(selector,style);
  969. }
  970. else if(mediaType == "object")
  971. {
  972. for(i = 0;i<styleSheet.cssRules.length;i++)
  973. {
  974. // if there is an existing rule set up, replace it
  975. if(styleSheet.cssRules[i].selectorText && styleSheet.cssRules[i].selectorText.toLowerCase() == selector.toLowerCase())
  976. {
  977. styleSheet.cssRules[i].style.cssText = style;
  978. return;
  979. }
  980. }
  981. // or insert new rule
  982. styleSheet.insertRule(selector + "{" + style + "}", styleSheet.cssRules.length);
  983. }
  984. };
  985. PWM_MAIN.flashDomElement = function(flashColor,elementName,durationMS) {
  986. if (!PWM_MAIN.getObject(elementName)) {
  987. console.log('cant flash non-existing element id ' + elementName);
  988. return;
  989. }
  990. console.log('will flash element id ' + elementName);
  991. require(["dojo","dojo/window","dojo/domReady!"],function(dojo) {
  992. var originalBGColor = PWM_MAIN.getRenderedStyle(elementName,'background-color');
  993. PWM_MAIN.getObject(elementName).style.backgroundColor = flashColor;
  994. dojo.animateProperty({
  995. node:elementName,
  996. duration: durationMS,
  997. properties: { backgroundColor: originalBGColor}
  998. }).play();
  999. });
  1000. };
  1001. PWM_MAIN.getRenderedStyle = function(el,styleProp) {
  1002. var x = document.getElementById(el);
  1003. if (x.currentStyle) {
  1004. return x.currentStyle[styleProp];
  1005. }
  1006. if (window.getComputedStyle) {
  1007. return document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
  1008. }
  1009. return null;
  1010. };
  1011. PWM_MAIN.elementInViewport = function(el, includeWidth) {
  1012. var top = el.offsetTop;
  1013. var left = el.offsetLeft;
  1014. var width = el.offsetWidth;
  1015. var height = el.offsetHeight;
  1016. while(el.offsetParent) {
  1017. el = el.offsetParent;
  1018. top += el.offsetTop;
  1019. left += el.offsetLeft;
  1020. }
  1021. var pageY = (typeof(window.pageYOffset)=='number') ? window.pageYOffset : document.documentElement.scrollTop;
  1022. var pageX = (typeof(window.pageXOffset)=='number') ? window.pageXOffset : document.documentElement.scrollLeft;
  1023. return includeWidth ? (
  1024. top >= pageY && (top + height) <= (pageY + window.innerHeight) &&
  1025. left >= pageX &&
  1026. (left + width) <= (pageX + window.innerWidth)
  1027. ) : (
  1028. top >= pageY && (top + height) <= (pageY + window.innerHeight)
  1029. );
  1030. };
  1031. PWM_MAIN.messageDivFloatHandler = function() {
  1032. var messageObj = PWM_MAIN.getObject('message');
  1033. var messageWrapperObj = PWM_MAIN.getObject('message_wrapper');
  1034. if (!messageObj || !messageWrapperObj) {
  1035. return;
  1036. }
  1037. if (messageObj.style.display == 'none') {
  1038. return;
  1039. }
  1040. var doFloatDisplay = !(PWM_MAIN.elementInViewport(messageWrapperObj,false) || PWM_GLOBAL['messageStatus'] == '');
  1041. if (PWM_GLOBAL['setting_alwaysFloatMessages']) {
  1042. doFloatDisplay = PWM_GLOBAL['messageStatus'] != '';
  1043. }
  1044. if (PWM_GLOBAL['message_scrollToggle'] != doFloatDisplay) {
  1045. PWM_GLOBAL['message_scrollToggle'] = doFloatDisplay;
  1046. if (doFloatDisplay) {
  1047. messageObj.style.position = 'fixed';
  1048. messageObj.style.top = '-3px';
  1049. messageObj.style.left = '0';
  1050. messageObj.style.width = '100%';
  1051. messageObj.style.zIndex = "100";
  1052. messageObj.style.textAlign = "center";
  1053. messageObj.style.backgroundColor = 'black';
  1054. PWM_MAIN.doShow(PWM_GLOBAL['messageStatus'],messageObj.innerHTML,true);
  1055. } else {
  1056. messageObj.style.cssText = '';
  1057. PWM_MAIN.doShow(PWM_GLOBAL['messageStatus'],messageObj.innerHTML,true);
  1058. }
  1059. }
  1060. };
  1061. PWM_MAIN.pwmFormValidator = function(validationProps, reentrant) {
  1062. var CONSOLE_DEBUG = false;
  1063. var serviceURL = validationProps['serviceURL'];
  1064. var readDataFunction = validationProps['readDataFunction'];
  1065. var processResultsFunction = validationProps['processResultsFunction'];
  1066. var messageWorking = validationProps['messageWorking'] ? validationProps['messageWorking'] : PWM_MAIN.showString('Display_PleaseWait');
  1067. var typeWaitTimeMs = validationProps['typeWaitTimeMs'] ? validationProps['typeWaitTimeMs'] : PWM_GLOBAL['client.ajaxTypingWait'];
  1068. var ajaxTimeout = validationProps['ajaxTimeout'] ? validationProps['ajaxTimeout'] : PWM_GLOBAL['client.ajaxTypingTimeout'];
  1069. var showMessage = 'showMessage' in validationProps ? validationProps['showMessage'] : true;
  1070. var completeFunction = 'completeFunction' in validationProps ? validationProps['completeFunction'] : function(){};
  1071. if (CONSOLE_DEBUG) console.log("pwmFormValidator: beginning...");
  1072. //init vars;
  1073. if (!PWM_VAR['validationCache']) {
  1074. PWM_VAR['validationCache'] = {};
  1075. }
  1076. // check if data is in cache, if it is just process it.
  1077. var formData = readDataFunction();
  1078. var formKey = "";
  1079. for (var key in formData) {formKey += formData[key] + "-";}
  1080. {
  1081. var cachedResult = PWM_VAR['validationCache'][formKey];
  1082. if (cachedResult != null) {
  1083. processResultsFunction(cachedResult);
  1084. if (CONSOLE_DEBUG) console.log('pwmFormValidator: processed cached data, exiting');
  1085. completeFunction();
  1086. return;
  1087. }
  1088. }
  1089. if (!reentrant) {
  1090. PWM_VAR['validationLastType'] = new Date().getTime();
  1091. }
  1092. // check to see if user is still typing. if yes, then come back later.
  1093. if (new Date().getTime() - PWM_VAR['validationLastType'] < typeWaitTimeMs) {
  1094. if (showMessage) {
  1095. PWM_MAIN.showInfo(PWM_MAIN.showString('Display_TypingWait'));
  1096. }
  1097. setTimeout(function(){PWM_MAIN.pwmFormValidator(validationProps, true)}, typeWaitTimeMs + 1);
  1098. if (CONSOLE_DEBUG) console.log('pwmFormValidator: sleeping while waiting for typing to finish, will retry...');
  1099. return;
  1100. }
  1101. if (CONSOLE_DEBUG) console.log('pwmFormValidator: user no longer typing, continuing..');
  1102. //check to see if a validation is already in progress, if it is then ignore keypress.
  1103. if (PWM_VAR['validationInProgress'] == true) {
  1104. if (CONSOLE_DEBUG) console.log('pwmFormValidator: waiting for a previous validation to complete, exiting...');
  1105. return;
  1106. }
  1107. PWM_VAR['validationInProgress'] = true;
  1108. // show in-progress message if load takes too long.
  1109. if (showMessage) {
  1110. setTimeout(function () {
  1111. if (PWM_VAR['validationInProgress'] == true) {
  1112. PWM_MAIN.showInfo(messageWorking);
  1113. }
  1114. }, 5);
  1115. }
  1116. require(["dojo"],function(dojo){
  1117. var formDataString = dojo.toJson(formData);
  1118. if (CONSOLE_DEBUG) console.log('FormValidator: sending form data to server... ' + formDataString);
  1119. var loadFunction = function(data) {
  1120. PWM_VAR['validationInProgress'] = false;
  1121. delete PWM_VAR['validationLastType'];
  1122. PWM_VAR['validationCache'][formKey] = data;
  1123. if (CONSOLE_DEBUG) console.log('pwmFormValidator: successful read, data added to cache');
  1124. PWM_MAIN.pwmFormValidator(validationProps, true);
  1125. };
  1126. var options = {};
  1127. options['content'] = formData;
  1128. options['ajaxTimeout'] = ajaxTimeout;
  1129. options['errorFunction'] = function(error) {
  1130. PWM_VAR['validationInProgress'] = false;
  1131. if (showMessage) {
  1132. PWM_MAIN.showInfo(PWM_MAIN.showString('Display_CommunicationError'));
  1133. }
  1134. if (CONSOLE_DEBUG) console.log('pwmFormValidator: error connecting to service: ' + errorObj);
  1135. processResultsFunction(null);
  1136. completeFunction();
  1137. };
  1138. PWM_MAIN.ajaxRequest(serviceURL,loadFunction,options);
  1139. });
  1140. };
  1141. PWM_MAIN.preloadImages = function(imgArray){
  1142. var newimages=[];
  1143. var arr=(typeof imgArray!="object")? [imgArray] : imgArray; //force arr parameter to always be an array
  1144. for (var i=0; i<arr.length; i++){
  1145. newimages[i]=new Image();
  1146. newimages[i].src=arr[i];
  1147. }
  1148. };
  1149. PWM_MAIN.isEmpty = function(o) {
  1150. return PWM_MAIN.itemCount(o) < 1;
  1151. };
  1152. PWM_MAIN.itemCount = function(o) {
  1153. var i = 0;
  1154. for (var key in o) if (o.hasOwnProperty(key)) i++;
  1155. return i;
  1156. };
  1157. PWM_MAIN.toggleFullscreen = function(iconObj,divName) {
  1158. var obj = PWM_MAIN.getObject(divName);
  1159. var storedStyleName = 'fullscreen-style-' + divName;
  1160. if (PWM_GLOBAL[storedStyleName]) {
  1161. iconObj.className = "icon-fullscreen";
  1162. obj.style = PWM_GLOBAL[storedStyleName];
  1163. delete PWM_GLOBAL[storedStyleName];
  1164. } else {
  1165. PWM_GLOBAL[storedStyleName] = obj.style;
  1166. iconObj.className = "icon-resize-full";
  1167. obj.style.position = 'fixed';
  1168. obj.style.top = '0';
  1169. obj.style.left = '0';
  1170. obj.style.bottom = '0';
  1171. obj.style.right = '0';
  1172. obj.style.zIndex = '100';
  1173. obj.style.background = 'white';
  1174. }
  1175. if (PWM_GLOBAL['displayGrid']) {
  1176. PWM_GLOBAL['displayGrid'].resize();
  1177. }
  1178. };
  1179. PWM_MAIN.updateLoginContexts = function() {
  1180. var ldapProfileElement = PWM_MAIN.getObject('ldapProfile');
  1181. var contextElement = PWM_MAIN.getObject('context');
  1182. if (contextElement && ldapProfileElement) {
  1183. var selectedProfile = ldapProfileElement.options[ldapProfileElement.selectedIndex].value;
  1184. var contextList = PWM_GLOBAL['ldapProfiles'][selectedProfile];
  1185. if (PWM_MAIN.isEmpty(contextList)) {
  1186. PWM_MAIN.getObject('contextSelectorWrapper').style.display = 'none';
  1187. } else {
  1188. PWM_MAIN.getObject('contextSelectorWrapper').style.display = 'inherit';
  1189. for (var key in contextList) {
  1190. (function (key) {
  1191. var display = contextList[key];
  1192. var optionElement = document.createElement('option');
  1193. optionElement.setAttribute('value', key);
  1194. optionElement.appendChild(document.createTextNode(display));
  1195. contextElement.appendChild(optionElement);
  1196. }(key));
  1197. }
  1198. }
  1199. }
  1200. };
  1201. //---------- show/hide password handler
  1202. var ShowHidePasswordHandler = {};
  1203. ShowHidePasswordHandler.idSuffix = '-eye-icon';
  1204. ShowHidePasswordHandler.state = {};
  1205. ShowHidePasswordHandler.toggleRevertTimeout = 30 * 1000; //default value, overriden by settings.
  1206. ShowHidePasswordHandler.debugOutput = false;
  1207. ShowHidePasswordHandler.initAllForms = function() {
  1208. if (!PWM_GLOBAL['setting-showHidePasswordFields']) {
  1209. return;
  1210. }
  1211. require(["dojo/query"], function(query){
  1212. var inputFields = query('.passwordfield');
  1213. for (var i = 0; i < inputFields.length; i++) {
  1214. var field = inputFields[i];
  1215. if (field.id) {
  1216. if (ShowHidePasswordHandler.debugOutput) console.log('adding show/hide option on fieldID=' + field.id);
  1217. ShowHidePasswordHandler.init(field.id);
  1218. }
  1219. }
  1220. });
  1221. };
  1222. ShowHidePasswordHandler.init = function(nodeName) {
  1223. if (!PWM_GLOBAL['setting-showHidePasswordFields']) {
  1224. return;
  1225. }
  1226. var node = PWM_MAIN.getObject(nodeName);
  1227. if (!node) {
  1228. return;
  1229. }
  1230. ShowHidePasswordHandler.toggleRevertTimeout = PWM_GLOBAL['client.pwShowRevertTimeout'] || ShowHidePasswordHandler.toggleRevertTimeout;
  1231. var eyeId = nodeName + ShowHidePasswordHandler.idSuffix;
  1232. if (PWM_MAIN.getObject(eyeId)) {
  1233. return;
  1234. }
  1235. require(["dojo/dom-construct", "dojo/on", "dojo/dom-attr"], function(domConstruct, on, attr){
  1236. var defaultType = attr.get(node, "type");
  1237. attr.set(node, "data-originalType", defaultType);
  1238. var divElement = document.createElement('div');
  1239. divElement.id = eyeId;
  1240. divElement.onclick = function(){ShowHidePasswordHandler.toggle(nodeName)};
  1241. divElement.style.cursor = 'pointer';
  1242. divElement.style.visibility = 'hidden';
  1243. domConstruct.place(divElement,node,'after');
  1244. ShowHidePasswordHandler.state[nodeName] = (defaultType == "password");
  1245. ShowHidePasswordHandler.setupTooltip(nodeName, false);
  1246. on(node, "keyup, input", function(){
  1247. if (ShowHidePasswordHandler.debugOutput) console.log("keypress event on node " + nodeName)
  1248. ShowHidePasswordHandler.renderIcon(nodeName);
  1249. ShowHidePasswordHandler.setupTooltip(nodeName);
  1250. });
  1251. });
  1252. };
  1253. ShowHidePasswordHandler.renderIcon = function(nodeName) {
  1254. if (ShowHidePasswordHandler.debugOutput) console.log("calling renderIcon on node " + nodeName);
  1255. var node = PWM_MAIN.getObject(nodeName);
  1256. var eyeId = nodeName + ShowHidePasswordHandler.idSuffix;
  1257. var eyeNode = PWM_MAIN.getObject(eyeId);
  1258. if (node && node.value && node.value.length > 0) {
  1259. eyeNode.style.visibility = 'visible';
  1260. } else {
  1261. eyeNode.style.visibility = 'hidden';
  1262. }
  1263. eyeNode.className = eyeNode.className; //ie8 force-rendering hack
  1264. };
  1265. ShowHidePasswordHandler.toggle = function(nodeName) {
  1266. if (ShowHidePasswordHandler.state[nodeName]) {
  1267. ShowHidePasswordHandler.show(nodeName);
  1268. } else {
  1269. ShowHidePasswordHandler.hide(nodeName);
  1270. }
  1271. };
  1272. ShowHidePasswordHandler.hide = function(nodeName) {
  1273. ShowHidePasswordHandler.state[nodeName] = true;
  1274. ShowHidePasswordHandler.changeInputTypeField(PWM_MAIN.getObject(nodeName),'password');
  1275. ShowHidePasswordHandler.setupTooltip(nodeName);
  1276. ShowHidePasswordHandler.renderIcon(nodeName);
  1277. };
  1278. ShowHidePasswordHandler.show = function(nodeName) {
  1279. ShowHidePasswordHandler.state[nodeName] = false;
  1280. ShowHidePasswordHandler.changeInputTypeField(PWM_MAIN.getObject(nodeName),'text');
  1281. ShowHidePasswordHandler.setupTooltip(nodeName);
  1282. ShowHidePasswordHandler.renderIcon(nodeName);
  1283. var node = PWM_MAIN.getObject(nodeName);
  1284. require(["dojo/dom-construct", "dojo/on", "dojo/dom-attr"], function(domConstruct, on, attr) {
  1285. var defaultType = attr.set(node, "data-originalType");
  1286. if (defaultType == 'password') {
  1287. setTimeout(function () {
  1288. if (!ShowHidePasswordHandler.state[nodeName]) {
  1289. ShowHidePasswordHandler.toggle(nodeName);
  1290. }
  1291. }, ShowHidePasswordHandler.toggleRevertTimeout);
  1292. }
  1293. });
  1294. };
  1295. ShowHidePasswordHandler.changeInputTypeField = function(object, type) {
  1296. require(["dojo","dojo/_base/lang", "dojo/dom", "dojo/dom-attr"], function(dojo, lang, dom, attr){
  1297. var newObject = null;
  1298. if(dojo.isIE <= 8){ // IE doesn't support simply changing the type of object
  1299. newObject = document.createElement(object.nodeName);
  1300. newObject.type = type;
  1301. if (object.size) newObject.size = object.size;
  1302. if (object.value) newObject.value = object.value;
  1303. if (object.name) newObject.name = object.name;
  1304. if (object.id) newObject.id = object.id;
  1305. if (object.className) newObject.className = object.className;
  1306. if (object.onclick) newObject.onclick = object.onclick;
  1307. if (object.onkeyup) newObject.onkeyup = object.onkeyup;
  1308. if (object.onkeydown) newObject.onkeydown = object.onkeydown;
  1309. if (object.onkeypress) newObject.onkeypress = object.onkeypress;
  1310. if (object.onchange) newObject.onchange = object.onchange;
  1311. if (object.disabled) newObject.disabled = object.disabled;
  1312. if (object.readonly) newObject.readonly = object.readonly;
  1313. if (object.data) newObject.data = object.data;
  1314. } else {
  1315. newObject = lang.clone(object);
  1316. attr.set(newObject, "type", type);
  1317. }
  1318. object.parentNode.replaceChild(newObject, object);
  1319. return newObject;
  1320. });
  1321. };
  1322. ShowHidePasswordHandler.setupTooltip = function(nodeName) {
  1323. if (ShowHidePasswordHandler.debugOutput) console.log('begin setupTooltip');
  1324. var state = ShowHidePasswordHandler.state[nodeName];
  1325. var eyeNodeId = nodeName + ShowHidePasswordHandler.idSuffix;
  1326. PWM_MAIN.clearDijitWidget(eyeNodeId );
  1327. require(["dojo","dijit","dijit/Tooltip"],function(dojo,dijit,Tooltip){
  1328. if (state) {
  1329. new Tooltip({
  1330. connectId: [eyeNodeId],
  1331. label: PWM_MAIN.showString('Button_Show')
  1332. });
  1333. dojo.removeClass(eyeNodeId);
  1334. dojo.addClass(eyeNodeId,["fa","fa-eye"]);
  1335. if (ShowHidePasswordHandler.debugOutput) console.log('set class to fa-eye');
  1336. } else {
  1337. new Tooltip({
  1338. connectId: [eyeNodeId],
  1339. label: PWM_MAIN.showString('Button_Hide')
  1340. });
  1341. dojo.removeClass(eyeNodeId);
  1342. dojo.addClass(eyeNodeId,["fa","fa-eye-slash"]);
  1343. if (ShowHidePasswordHandler.debugOutput) console.log('set class to fa-slash');
  1344. }
  1345. });
  1346. };
  1347. //---------- idle timeout handler
  1348. PWM_MAIN.IdleTimeoutHandler = {};
  1349. PWM_MAIN.IdleTimeoutHandler.SETTING_LOOP_FREQUENCY = 1000; // milliseconds
  1350. PWM_MAIN.IdleTimeoutHandler.SETTING_WARN_SECONDS = 30; // seconds
  1351. PWM_MAIN.IdleTimeoutHandler.SETTING_POLL_SERVER_SECONDS = 10; //
  1352. PWM_MAIN.IdleTimeoutHandler.timeoutSeconds = 0; // idle timeout time permitted
  1353. PWM_MAIN.IdleTimeoutHandler.lastActivityTime = new Date(); // time at which we are "idled out"
  1354. PWM_MAIN.IdleTimeoutHandler.lastPingTime = new Date(); // date at which the last ping occured
  1355. PWM_MAIN.IdleTimeoutHandler.realWindowTitle = "";
  1356. PWM_MAIN.IdleTimeoutHandler.warningDisplayed = false;
  1357. PWM_MAIN.IdleTimeoutHandler.initCountDownTimer = function(secondsRemaining) {
  1358. PWM_MAIN.IdleTimeoutHandler.timeoutSeconds = secondsRemaining;
  1359. PWM_MAIN.IdleTimeoutHandler.lastPingTime = new Date();
  1360. PWM_MAIN.IdleTimeoutHandler.realWindowTitle = document.title;
  1361. PWM_MAIN.IdleTimeoutHandler.resetIdleCounter();
  1362. setInterval(function(){PWM_MAIN.IdleTimeoutHandler.pollActivity()}, PWM_MAIN.IdleTimeoutHandler.SETTING_LOOP_FREQUENCY); //poll scrolling
  1363. require(["dojo/on"], function(on){
  1364. on(document, "click", function(){PWM_MAIN.IdleTimeoutHandler.resetIdleCounter()});
  1365. on(document, "keypress", function(){PWM_MAIN.IdleTimeoutHandler.resetIdleCounter()});
  1366. on(document, "scroll", function(){PWM_MAIN.IdleTimeoutHandler.resetIdleCounter()});
  1367. });
  1368. };
  1369. PWM_MAIN.IdleTimeoutHandler.resetIdleCounter = function() {
  1370. PWM_MAIN.IdleTimeoutHandler.lastActivityTime = new Date();
  1371. PWM_MAIN.IdleTimeoutHandler.closeIdleWarning();
  1372. PWM_MAIN.IdleTimeoutHandler.pollActivity();
  1373. };
  1374. PWM_MAIN.IdleTimeoutHandler.pollActivity = function() {
  1375. var secondsRemaining = PWM_MAIN.IdleTimeoutHandler.calcSecondsRemaining();
  1376. var idleDisplayString = PWM_MAIN.IdleTimeoutHandler.makeIdleDisplayString(secondsRemaining);
  1377. var idleStatusFooter = PWM_MAIN.getObject("idle_status");
  1378. if (idleStatusFooter != null) {
  1379. idleStatusFooter.firstChild.nodeValue = idleDisplayString;
  1380. }
  1381. var warningDialogText = PWM_MAIN.getObject("IdleDialogWindowIdleText");
  1382. if (warningDialogText != null) {
  1383. warningDialogText.firstChild.nodeValue = idleDisplayString;
  1384. }
  1385. if (secondsRemaining < 0) {
  1386. if (!PWM_GLOBAL['idle_suspendTimeout']) {
  1387. PWM_VAR['dirtyPageLeaveFlag'] = false;
  1388. PWM_GLOBAL['idle_suspendTimeout'] = true;
  1389. window.location = PWM_GLOBAL['url-logout'];
  1390. } else {
  1391. try { PWM_MAIN.getObject('idle_wrapper').style.visibility = 'none'; } catch(e) { /* noop */ }
  1392. }
  1393. return;
  1394. }
  1395. var pingAgoMs = (new Date()).getTime() - PWM_MAIN.IdleTimeoutHandler.lastPingTime.getTime();
  1396. if (pingAgoMs > (PWM_MAIN.IdleTimeoutHandler.timeoutSeconds - PWM_MAIN.IdleTimeoutHandler.SETTING_POLL_SERVER_SECONDS) * 1000) {
  1397. PWM_MAIN.IdleTimeoutHandler.pingServer();
  1398. }
  1399. if (secondsRemaining < PWM_MAIN.IdleTimeoutHandler.SETTING_WARN_SECONDS) {
  1400. if (!PWM_GLOBAL['idle_suspendTimeout']) {
  1401. PWM_MAIN.IdleTimeoutHandler.showIdleWarning();
  1402. if (secondsRemaining % 2 == 0) {
  1403. document.title = PWM_MAIN.IdleTimeoutHandler.realWindowTitle;
  1404. } else {
  1405. document.title = idleDisplayString;
  1406. }
  1407. }
  1408. }
  1409. };
  1410. PWM_MAIN.IdleTimeoutHandler.pingServer = function() {
  1411. PWM_MAIN.IdleTimeoutHandler.lastPingTime = new Date();
  1412. var pingURL = PWM_GLOBAL['url-command'] + "?processAction=idleUpdate&time=" + new Date().getTime() + "&pwmFormID=" + PWM_GLOBAL['pwmFormID'];
  1413. require(["dojo"], function(dojo){
  1414. dojo.xhrPost({url:pingURL,sync:false});
  1415. });
  1416. };
  1417. PWM_MAIN.IdleTimeoutHandler.calcSecondsRemaining = function() {
  1418. var timeoutTime = PWM_MAIN.IdleTimeoutHandler.lastActivityTime.getTime() + (PWM_MAIN.IdleTimeoutHandler.timeoutSeconds * 1000)
  1419. var amount = timeoutTime - (new Date()).getTime();
  1420. amount = Math.floor(amount / 1000);
  1421. return amount;
  1422. };
  1423. PWM_MAIN.IdleTimeoutHandler.makeIdleDisplayString = function(amount) {
  1424. var output = PWM_MAIN.convertSecondsToDisplayTimeDuration(amount);
  1425. output = PWM_MAIN.showString('Display_IdleTimeout') + " " + output;
  1426. return output;
  1427. };
  1428. PWM_MAIN.IdleTimeoutHandler.showIdleWarning = function() {
  1429. if (!PWM_MAIN.IdleTimeoutHandler.warningDisplayed) {
  1430. PWM_MAIN.IdleTimeoutHandler.warningDisplayed = true;
  1431. var dialogBody = PWM_MAIN.showString('Display_IdleWarningMessage') + '<br/><br/><span id="IdleDialogWindowIdleText">&nbsp;</span>';
  1432. require(["dijit/Dialog"],function(){
  1433. var theDialog = new dijit.Dialog({
  1434. title: PWM_MAIN.showString('Display_IdleWarningTitle'),
  1435. style: "width: 260px; border: 2px solid #D4D4D4;",
  1436. content: dialogBody,
  1437. closable: true,
  1438. draggable: false,
  1439. id: "idleDialog"
  1440. });
  1441. theDialog.show();
  1442. });
  1443. }
  1444. };
  1445. PWM_MAIN.IdleTimeoutHandler.closeIdleWarning = function() {
  1446. PWM_MAIN.clearDijitWidget('idleDialog');
  1447. document.title = PWM_MAIN.IdleTimeoutHandler.realWindowTitle;
  1448. PWM_MAIN.IdleTimeoutHandler.warningDisplayed = false;
  1449. };
  1450. PWM_MAIN.TimestampHandler = PWM_MAIN.TimestampHandler || {};
  1451. PWM_MAIN.TimestampHandler.Key_ToggleState = false;
  1452. PWM_MAIN.TimestampHandler.ElementList = [];
  1453. PWM_MAIN.TimestampHandler.initAllElements = function() {
  1454. require(["dojo/query", "dojo/NodeList-dom"], function(query){
  1455. query(".timestamp").forEach(function(node){
  1456. PWM_MAIN.TimestampHandler.initElement(node);
  1457. });
  1458. });
  1459. };
  1460. PWM_MAIN.TimestampHandler.testIfStringIsTimestamp = function(input, trueFunction) {
  1461. if (input && input.length > 0) {
  1462. require(["dojo", "dojo/date/stamp"], function (dojo, IsoDate) {
  1463. input = dojo.trim(input);
  1464. var dateObj = IsoDate.fromISOString(input);
  1465. if (dateObj) {
  1466. trueFunction(dateObj);
  1467. }
  1468. });
  1469. }
  1470. };
  1471. PWM_MAIN.TimestampHandler.initElement = function(element) {
  1472. if (!element) {
  1473. return
  1474. }
  1475. if (element.getAttribute('data-timestamp-init') === 'true') {
  1476. return;
  1477. }
  1478. require(["dojo"], function(dojo) {
  1479. var innerText = dojo.attr(element, 'innerHTML');
  1480. innerText = dojo.trim(innerText);
  1481. PWM_MAIN.TimestampHandler.testIfStringIsTimestamp(innerText, function (dateObj) {
  1482. element.setAttribute('data-timestamp-original', innerText);
  1483. require(["dojo", "dojo/on"], function (dojo, on) {
  1484. on(element, "click", function (event) {
  1485. PWM_MAIN.TimestampHandler.toggleAllElements();
  1486. });
  1487. });
  1488. if (!dojo.hasClass(element,"timestamp")) {
  1489. dojo.addClass(element,"timestamp");
  1490. }
  1491. element.setAttribute('data-timestamp-init', 'true');
  1492. PWM_MAIN.TimestampHandler.ElementList.push(element);
  1493. PWM_MAIN.TimestampHandler.toggleElement(element);
  1494. });
  1495. });
  1496. };
  1497. PWM_MAIN.TimestampHandler.toggleAllElements = function() {
  1498. for (var el in PWM_MAIN.TimestampHandler.ElementList) {
  1499. var element = PWM_MAIN.TimestampHandler.ElementList[el];
  1500. if (document.body.contains(element)) {
  1501. PWM_MAIN.TimestampHandler.toggleElement(element);
  1502. } else {
  1503. delete PWM_MAIN.TimestampHandler.ElementList[el];
  1504. }
  1505. }
  1506. };
  1507. PWM_MAIN.TimestampHandler.toggleElement = function(element) {
  1508. require(["dojo","dojo/date/stamp","dojo/date/locale"], function(dojo,IsoDate,LocaleDate) {
  1509. var localized = element.getAttribute('data-timestamp-state') === 'localized';
  1510. if (localized) {
  1511. dojo.attr(element,'innerHTML',element.getAttribute('data-timestamp-original'));
  1512. element.setAttribute('data-timestamp-state','iso');
  1513. } else {
  1514. var isoDateStr = element.getAttribute('data-timestamp-original');
  1515. var date = IsoDate.fromISOString(isoDateStr);
  1516. var localizedStr = LocaleDate.format(date,{formatLength:'long'});
  1517. dojo.attr(element,'innerHTML',localizedStr);
  1518. element.setAttribute('data-timestamp-state','localized');
  1519. }
  1520. })
  1521. };
  1522. PWM_MAIN.addPwmFormIDtoURL = function(url) {
  1523. return PWM_MAIN.addParamToUrl(url,'pwmFormID',PWM_GLOBAL['pwmFormID']);
  1524. };
  1525. PWM_MAIN.addParamToUrl = function(url,paramName,paramValue) {
  1526. if (!url || url.length < 1) {
  1527. return url;
  1528. }
  1529. if (
  1530. url.indexOf('?' + paramName + '=') > -1
  1531. || url.indexOf('&' + paramName + '=') > -1)
  1532. {
  1533. console.warn('ignoring request to append duplicate param "' + paramName + '" to url ' + url);
  1534. return url;
  1535. }
  1536. var encodedName = encodeURIComponent(paramName);
  1537. var encodedValue = encodeURIComponent(paramValue);
  1538. url += url.indexOf('?') > 0 ? '&' : '?';
  1539. url += encodedName + "=" + encodedValue;
  1540. return url;
  1541. };
  1542. PWM_MAIN.ajaxRequest = function(url,loadFunction,options) {
  1543. options = options === undefined ? {} : options;
  1544. var content = 'content' in options ? options['content'] : null;
  1545. var method = 'method' in options ? options['method'] : 'POST';
  1546. var errorFunction = 'errorFunction' in options ? options['errorFunction'] : function(error){
  1547. PWM_MAIN.showErrorDialog(error);
  1548. };
  1549. var preventCache = 'preventCache' in options ? options['preventCache'] : true;
  1550. var addPwmFormID = 'addPwmFormID' in options ? options['addPwmFormID'] : true;
  1551. var ajaxTimeout = options['ajaxTimeout'] ? options['ajaxTimeout'] : PWM_MAIN.ajaxTimeout;
  1552. var requestHeaders = {};
  1553. requestHeaders['Accept'] = "application/json";
  1554. requestHeaders['X-RestClientKey'] = PWM_GLOBAL['restClientKey'];
  1555. if (content != null) {
  1556. requestHeaders['Content-Type'] = "application/json";
  1557. }
  1558. require(["dojo/request/xhr","dojo","dojo/json"], function (xhr,dojo,dojoJson) {
  1559. loadFunction = loadFunction != undefined ? loadFunction : function (data) {
  1560. alert('missing load function, return results:' + dojo.toJson(data))
  1561. };
  1562. if (addPwmFormID) {
  1563. url = PWM_MAIN.addPwmFormIDtoURL(url);
  1564. }
  1565. if (preventCache) {
  1566. url = PWM_MAIN.addParamToUrl(url, 'preventCache', (new Date).valueOf());
  1567. }
  1568. var postOptions = {
  1569. headers: requestHeaders,
  1570. //encoding: "utf-8",
  1571. method: method,
  1572. preventCache: false,
  1573. handleAs: "json",
  1574. timeout: ajaxTimeout
  1575. };
  1576. if (content != null) {
  1577. postOptions['data'] = dojoJson.stringify(content);
  1578. }
  1579. xhr(url, postOptions).then(loadFunction, errorFunction, function(evt){});
  1580. });
  1581. };
  1582. PWM_MAIN.convertSecondsToDisplayTimeDuration = function(amount, fullLength) {
  1583. if (amount < 1) {
  1584. return "";
  1585. }
  1586. var output = "";
  1587. var days = Math.floor(amount / 86400);
  1588. amount = amount % 86400;
  1589. var hours = Math.floor(amount / 3600);
  1590. amount = amount % 3600;
  1591. var mins = Math.floor(amount / 60);
  1592. amount = amount % 60;
  1593. var secs = Math.floor(amount);
  1594. // write number of days
  1595. var positions = 0;
  1596. if (days != 0) {
  1597. output += days + " ";
  1598. if (days != 1) {
  1599. output += PWM_MAIN.showString('Display_Days');
  1600. } else {
  1601. output += PWM_MAIN.showString('Display_Day');
  1602. }
  1603. positions++;
  1604. }
  1605. // write number of hours
  1606. if (days != 0 || hours != 0) {
  1607. if (output.length > 0) {
  1608. output += ", ";
  1609. }
  1610. output += hours + " ";
  1611. if (hours != 1) {
  1612. output += PWM_MAIN.showString('Display_Hours');
  1613. } else {
  1614. output += PWM_MAIN.showString('Display_Hour');
  1615. }
  1616. positions ++;
  1617. }
  1618. // write number of minutes
  1619. if (positions < 2 || fullLength) {
  1620. if (days != 0 || hours != 0 || mins != 0 || fullLength) {
  1621. if (output.length > 0) {
  1622. output += ", ";
  1623. }
  1624. output += mins + " ";
  1625. if (mins != 1) {
  1626. output += PWM_MAIN.showString('Display_Minutes');
  1627. } else {
  1628. output += PWM_MAIN.showString('Display_Minute');
  1629. }
  1630. positions++;
  1631. }
  1632. }
  1633. // write number of seconds
  1634. if (positions < 2 || fullLength) {
  1635. if (mins < 4 || fullLength) {
  1636. if (output.length > 0) {
  1637. output += ", ";
  1638. }
  1639. output += secs + " ";
  1640. if (secs != 1) {
  1641. output += PWM_MAIN.showString('Display_Seconds');
  1642. } else {
  1643. output += PWM_MAIN.showString('Display_Second');
  1644. }
  1645. }
  1646. }
  1647. return output;
  1648. };
  1649. PWM_MAIN.setStyle = function(elementID, property, value) {
  1650. try {
  1651. var element = PWM_MAIN.getObject(elementID);
  1652. if (element) {
  1653. element.style.setProperty(property, value, null);
  1654. }
  1655. } catch (e) {
  1656. console.error('error while setting style, elementID=' + elementID + ", property=" + property + ", value=" + value + ", error: " + e);
  1657. }
  1658. };
  1659. PWM_MAIN.addCssClass = function(elementID, className) {
  1660. require(["dojo"], function (dojo) { dojo.addClass(elementID, className); });
  1661. };
  1662. PWM_MAIN.removeCssClass = function(elementID, className) {
  1663. require(["dojo"], function (dojo) { dojo.removeClass(elementID, className) });
  1664. };
  1665. PWM_MAIN.newWindowOpen=function(windowUrl,windowName) {
  1666. var windowParams = 'status=0,toolbar=0,location=0,menubar=0,scrollbars=1,resizable=1';
  1667. var viewLog = window.open(windowUrl,windowName,windowParams).focus();
  1668. };
  1669. PWM_MAIN.autofocusSupportExtension = function() {
  1670. var supportAutofocus = 'autofocus' in (document.createElement('input'));
  1671. if (!supportAutofocus) {
  1672. console.log("no browser support for autofocus, implementing manual dom check for focused item");
  1673. require(["dojo/query"], function(query){
  1674. var found = false;
  1675. var results = query('form *');
  1676. for (var i = 0; i < results.length; i++) {
  1677. if (found) {
  1678. break
  1679. }
  1680. (function (itemIterator) {
  1681. var element = results[itemIterator];
  1682. if (element.hasAttribute('autofocus')) {
  1683. element.focus();
  1684. found = true;
  1685. }
  1686. })(i);
  1687. }
  1688. });
  1689. }
  1690. };
  1691. PWM_MAIN.cancelEvent = function(event) {
  1692. if (event) {
  1693. if (event.preventDefault) {
  1694. event.preventDefault();
  1695. } else if (event.returnValue) {
  1696. event.returnValue = false;
  1697. }
  1698. }
  1699. };
  1700. PWM_MAIN.submitPostAction = function(buttonID,actionUrl,actionValue) {
  1701. PWM_MAIN.addEventHandler(buttonID,'click',function(){
  1702. var formElement = document.createElement('form');
  1703. formElement.setAttribute('id','form-sendReset');
  1704. formElement.setAttribute('action',actionUrl);
  1705. formElement.setAttribute('method','post');
  1706. formElement.innerHTML = '<input type="hidden" name="processAction" value="' + actionValue + '"> </input>'
  1707. + '<input type="hidden" name="pwmFormID" value="' + PWM_GLOBAL['pwmFormID'] + '"> </input>';
  1708. document.body.appendChild(formElement);
  1709. PWM_MAIN.handleFormSubmit(formElement);
  1710. });
  1711. };
  1712. PWM_MAIN.doQuery = function(queryString, resultFunction) {
  1713. require(["dojo/query"], function (query) {
  1714. var results = query(queryString);
  1715. for (var i = 0; i < results.length; i++) {
  1716. (function(iterator){
  1717. var result = results[iterator];
  1718. resultFunction(result)
  1719. })(i);
  1720. }
  1721. });
  1722. };
  1723. PWM_MAIN.doIfQueryHasResults = function(queryString, trueFunction) {
  1724. require(["dojo/query"], function (query) {
  1725. var results = query(queryString);
  1726. if (results && results.length > 0) {
  1727. trueFunction();
  1728. }
  1729. });
  1730. };
  1731. PWM_MAIN.pageLoadHandler();