main.js 76 KB

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