/** StaticVariablesStorage.js **/ //This file contains definition of class StaticVariablesStorage. //IMPORTANT: this file initializes global variable __staticVariablesStorage. function StaticVariablesStorage() { } StaticVariablesStorage.prototype.setNewObject = function StaticVariablesStorageSetNewObject(keyName) { var res = {}; this[keyName] = res; return res; }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// if (window.__staticVariablesStorage === true) { //this is treated as a flag that it's required to make current window a place where static variables storage is kept window.__staticVariablesStorage = new StaticVariablesStorage(); } else { //otherwise we have to find main window and take a reference to __staticVariablesStorage from there. var down = 1; var up = 2; var queue = [{ window: window, direction: up }]; var processUp = function(window) { var nextWindow; var direction; if (window.opener) { nextWindow = window.opener; } else if (window.dialogArguments && window.dialogArguments.opener) { nextWindow = window.dialogArguments.opener; } else if (window !== window.parent) { nextWindow = window.parent; direction = up; } else { return; } queue.push({ window: nextWindow, direction: direction }); }; var processDown = function(window) { var frames = window.frames; for (var i = 0; i < frames.length; i++) { var frame = frames[i]; if (frame !== window) { queue.push({ window: frame, direction: down }); } } }; var node; while (queue.length > 0) { node = queue.shift(); try { if (node.window.__staticVariablesStorage) { break; } } catch (e) { console.log('Access to __staticVariablesStorage denied.'); // maybe permission denied to access property } switch (node.direction) { case up: processUp(node.window); break; case down: processDown(node.window); break; default: processUp(node.window); processDown(node.window); break; } } // expect that node.window contain __staticVariablesStorage if (node.window.closed) { throw new Error(1, 'Main window is closed.'); } if (!node.window.__staticVariablesStorage) { throw new Error(2, 'Main window doesn\'t contain __staticVariablesStorage.'); } window.__staticVariablesStorage = node.window.__staticVariablesStorage; } /** ModulesHelper.js **/ function ModulesHelper() { if (!window.__staticVariablesStorage.__modulesHelperCodeCache) { window.__staticVariablesStorage.__modulesHelperCodeCache = {}; } function using(classes, func, isAsync) { var args = []; var asyncResult; if (isAsync) { asyncResult = this.createAsyncResult(); asyncResult.then(func); } function callFuncIfArgLoaded() { var isComplete = true; for (var argIndex = 0; argIndex < classes.length; argIndex++) { if (!args[argIndex]) { isComplete = false; } } if (isComplete) { if (isAsync) { asyncResult.resolve(args); } else { func.apply(window, args); } } } function ifExistsInCache(i, cache) { return function() { args[i] = cache[classes[i]]; callFuncIfArgLoaded(); }; } function ifNotExistsInCache(i, cache, events, xhr) { return function() { var code; if (xhr) { if (xhr.readyState == 4 && xhr.status == 200) { code = xhr.responseText; } else { return; } } else { code = window.__staticVariablesStorage.__modulesHelperCodeCache[classes[i]]; } var setArg = function() { args[i] = cache[classes[i]]; callFuncIfArgLoaded(); events.removeListener(classes[i], setArg); }; events.addListener(classes[i], setArg); /* jshint ignore:start */ eval(code); /* jshint ignore:end */ }; } for (var classIndex = 0; classIndex < classes.length; classIndex++) { if (this.classCache[classes[classIndex]]) { if (isAsync) { setTimeout(ifExistsInCache(classIndex, this.classCache), 0); } else { ifExistsInCache(classIndex, this.classCache)(); } } else { if (window.__staticVariablesStorage.__modulesHelperCodeCache[classes[classIndex]]) { if (isAsync) { setTimeout(ifNotExistsInCache(classIndex, this.classCache, this.eventHelper), 0); } else { ifNotExistsInCache(classIndex, this.classCache, this.eventHelper)(); } } else { var tmp = classes[classIndex].split('/'); var moduleName = tmp.slice(0, tmp.length - 1).join('/'); // get everything before last segment. var className = tmp.slice(-1)[0]; // class name is last segment var classUrl = aras.getBaseURL() + '/modules/' + moduleName + '/scripts/classes/' + className + '.js'; var xmlHttpRequest = new XMLHttpRequest(); if (isAsync) { xmlHttpRequest.open('GET', classUrl, true); } else { xmlHttpRequest.open('GET', classUrl, false); } xmlHttpRequest.onreadystatechange = ifNotExistsInCache(classIndex, this.classCache, this.eventHelper, xmlHttpRequest); xmlHttpRequest.send(); } } } return asyncResult; } function define(classes, classFullName, func, isAsync) { var args = []; function callFuncIfArgLoaded(cache, events) { var isComplete = true; for (var argIndex = 0, l = (classes ? classes.length : 0); argIndex < l; argIndex++) { if (!args[argIndex]) { isComplete = false; } } if (isComplete) { cache[classFullName] = func.apply(window, args); events.raiseEvent(classFullName); } } function ifExistsInCache(i, cache, events) { return function() { args[i] = cache[classes[i]]; callFuncIfArgLoaded(cache, events); }; } function ifNotExistsInCache(i, cache, events, xhr) { return function() { var code; if (xhr) { if (xhr.readyState == 4 && xhr.status == 200) { code = xhr.responseText; window.__staticVariablesStorage.__modulesHelperCodeCache[classes[i]] = code; } else { return; } } else { code = window.__staticVariablesStorage.__modulesHelperCodeCache[classes[i]]; } var setArg = function() { args[i] = cache[classes[i]]; callFuncIfArgLoaded(cache, events); events.removeListener(classes[i], setArg); }; events.addListener(classes[i], setArg); /* jshint ignore:start */ eval(code); /* jshint ignore:end */ }; } if (!classes || classes.length === 0) { var runWithoutClasses = function(cache, events) { return function() { callFuncIfArgLoaded(cache, events); }; }; if (isAsync) { setTimeout(runWithoutClasses(this.classCache, this.eventHelper), 0); } else { runWithoutClasses(this.classCache, this.eventHelper)(); } return; } for (var classIndex = 0; classIndex < classes.length; classIndex++) { if (this.classCache[classes[classIndex]]) { if (isAsync) { setTimeout(ifExistsInCache(classIndex, this.classCache, this.eventHelper), 0); } else { ifExistsInCache(classIndex, this.classCache, this.eventHelper)(); } } else { if (window.__staticVariablesStorage.__modulesHelperCodeCache[classes[classIndex]]) { if (isAsync) { setTimeout(ifNotExistsInCache(classIndex, this.classCache, this.eventHelper), 0); } else { ifNotExistsInCache(classIndex, this.classCache, this.eventHelper)(); } } else { var tmp = classes[classIndex].split('/'); var moduleName = tmp.slice(0, tmp.length - 1).join('/'); // get everything before last segment. var className = tmp.slice(-1)[0]; // class name is last segment var classUrl = aras.getBaseURL() + '/modules/' + moduleName + '/scripts/classes/' + className + '.js'; var xmlHttpRequest = new XMLHttpRequest(); if (isAsync) { xmlHttpRequest.open('GET', classUrl, true); } else { xmlHttpRequest.open('GET', classUrl, false); } xmlHttpRequest.onreadystatechange = ifNotExistsInCache(classIndex, this.classCache, this.eventHelper, xmlHttpRequest); xmlHttpRequest.send(); } } } } // class format -> ['moduleName/className', 'moduleName2/className2'] this.using = function(classes, isAsync) { var thisModelHelper = this; if (isAsync) { return using.call(thisModelHelper, classes, function() { return arguments; }, true); } else { var usingAsyncResult = this.createAsyncResult(); var resultAsyncResult = usingAsyncResult.then(function(classes) { var types; using.call(thisModelHelper, classes, function() { types = arguments; }); return types; }); usingAsyncResult.resolve([classes]); return resultAsyncResult; } }; this.define = function(classes, classFullName, func, isAsync) { var thisModelHelper = this; define.call(thisModelHelper, classes, classFullName, func, isAsync); }; this.createAsyncResult = function() { var thisModelHelper = this; var AsyncResultType; using.call(thisModelHelper, ['aras.innovator.core.Core/AsyncResult'], function(AsyncResult) { AsyncResultType = AsyncResult; }, false); return new AsyncResultType(); }; } ModulesHelper.prototype.classCache = {}; ModulesHelper.prototype.eventHelper = { _events: {}, addListener: function(eventName, callback) { var events = this._events; var callbacks = events[eventName] = events[eventName] || []; callbacks.push(callback); }, raiseEvent: function(eventName, args) { var callbacks = this._events[eventName]; for (var i = 0; i < callbacks.length; i++) { callbacks[i].apply(null, args); } }, removeListener: function(eventName, callback) { var events = this._events; var callbacks = events[eventName] = events[eventName] || []; var newCallbacks = []; for (var i = 0; i < callbacks.length; i++) { if (callbacks[i] !== callback) { newCallbacks.push(callbacks[i]); } } events[eventName] = newCallbacks; } }; var ModulesManager = new ModulesHelper(); /** BrowserInfo.js **/ function BrowserInfo(userAgent) { userAgent = userAgent || window.navigator.userAgent; //private properties var browserCode; var versionStr; //variables for private properties initialization var knownBrowsers = { 'edge': { certifiedVersions: { 15: true }, getNameToDisplay: function() { return 'Microsoft Edge ' + parseInt(versionStr, 10); }, minimalVersion: 15, patterns: [/Edge\/(\d+)/] }, 'ch': { minCertifiedVersions: 66, getNameToDisplay: function() { return 'Chrome ' + parseInt(versionStr, 10); }, minimalVersion: 66, patterns: [/Chrome\/(\S+)/] }, 'ff': { certifiedVersions: { 38: true, 45: true, 60: true }, getNameToDisplay: function() { return 'FireFox ' + parseInt(versionStr, 10); }, minimalVersion: 60, patterns: [/Firefox\/(\S+)/] }, 'ie': { certifiedVersions: { 11: true }, getNameToDisplay: function() { var declaredIEVersion = parseInt(versionStr, 10); //Trident/X.X appeared in userAgent string in IE 8 //Presence of this string will help us detect IE working in compatibility mode var tridentVersionToIEVersion = { '4.0': 8, '5.0': 9, '6.0': 10, '7.0': 11 }; var res; var matcher = userAgent.match(/Trident\/(\S+);/); var tridentVersion; var realIEVersion; //default result res = 'Internet Explorer ' + declaredIEVersion; //detect for compatibility mode if (matcher) { tridentVersion = matcher[1]; realIEVersion = tridentVersionToIEVersion[tridentVersion]; if (realIEVersion && realIEVersion != declaredIEVersion) { res = 'Internet Explorer ' + realIEVersion + ' in Internet Explorer ' + declaredIEVersion + ' Compatibility View Mode'; } } return res; }, minimalVersion: 11, patterns: [ //for IE 2.0 - 10.0 /MSIE (\S+);/, //for IE 11.0 and perhaps for later versions /Trident\/.*rv:([0-9]{1,}[\.0-9]{0,})/ ] }, 'sa': { certifiedVersions: { }, getNameToDisplay: function() { return 'Safari ' + parseInt(versionStr, 10); }, minimalVersion: Number.POSITIVE_INFINITY, patterns: [/Version\/(\S+).* Safari\/\S+/] } }; var patterns; var regExp; var matcher; var candidateCode; //private properties initialization for (candidateCode in knownBrowsers) { patterns = knownBrowsers[candidateCode].patterns; while (regExp = patterns.shift()) {//jshint ignore:line matcher = userAgent.match(regExp); if (matcher) { browserCode = candidateCode; //we need browser version with not more than two elements of version number. //Browser version in form "11.22" is enough for our needs. versionStr = (matcher[1].match(new RegExp('[^.]+(?:\.[^.]+){0,1}')))[0];//jshint ignore:line break; } } if (browserCode !== undefined) { break; } } //public methods this.isFf = function() { return browserCode === 'ff'; }; this.isIe = function() { return browserCode === 'ie'; }; this.isCh = function() { return browserCode === 'ch'; }; this.isEdge = function() { return browserCode === 'edge'; }; this.isKnown = function() { return Boolean(browserCode); }; this.isSupported = function() { return Boolean(browserCode && parseFloat(versionStr) >= knownBrowsers[browserCode].minimalVersion); }; this.isCertified = function() { var knownBrowser = knownBrowsers[browserCode]; var browserVersion = parseFloat(versionStr); return Boolean(browserCode && ( (knownBrowser.minCertifiedVersions && browserVersion >= knownBrowser.minCertifiedVersions) || (knownBrowser.certifiedVersions && knownBrowser.certifiedVersions[browserVersion]) )); }; this.getBrowserName = function() { var res; if (browserCode) { res = knownBrowsers[browserCode].getNameToDisplay(); } else { res = ''; } return res; }; this.getBrowserCode = function() { return browserCode; }; this.getMajorVersionNumber = function() { return parseInt(versionStr, 10); }; Object.defineProperty(this, 'OSName', { writable: false, configurable: false, enumerable: true, value: (function() { var OSName = 'Unknown'; if (userAgent.indexOf('Win') != -1) { OSName = 'Windows'; } if (userAgent.indexOf('Mac') != -1) { OSName = 'MacOS'; } return OSName; }()) } ); } /** ..\Modules\aras.innovator.core.Core\Scripts\Classes\TopWindowHelper.js **/ var TopWindowHelper; (function(TopWindowHelper) { // Duplicated in dialog.js, PopupMenu.js TopWindowHelper.getMostTopWindowWithAras = function(windowObj) { var win = windowObj ? windowObj : window; var prevWin = win; var winWithAras; while (win !== win.parent) { try { // Try access to any property with permission denied. var t = win.parent.name; } catch (excep) { break; } prevWin = win; win = win.parent; winWithAras = typeof win.aras !== 'undefined' ? win : winWithAras; } return winWithAras ? winWithAras : prevWin; // for work Innovator working in iframe case }; })(TopWindowHelper || (TopWindowHelper = {})); /** CultureInfo\DateTimeFormatInfo.js **/ (function() { function BaseDateTimeFormatInfo() { this.defaultLocale = 'en-us'; this.ISOPattern = /yyyy-MM-ddTHH:mm:ss(\.SSS)?/; Object.defineProperty(this, 'tzInfo', { get: function() { var topWnd = TopWindowHelper.getMostTopWindowWithAras(window); return topWnd.aras.browserHelper.tzInfo; } }); Object.defineProperty(this, '_dateLocale', { get: function() { return dojo.require('dojo.date.locale'); } }); Object.defineProperty(this, '_dateStamp', { get: function() { return dojo.require('dojo.date.stamp'); } }); } var _formatCharMappingArray = [ //http://cldr.unicode.org/translation/date-time-patterns {key: 'z', value: 'Z'}, {key: 'F', value: 's'}, {key: 'K', value: 'vz'}, {key: 'g', value: 'G'}, {key: 'tt', value: 'a'}, {key: 't', value: 'a'}, {key: 'dddd', value: 'EEEE'}, {key: 'ddd', value: 'EEE'} ]; function _convertToCLDRDateFormat(pattern) { var index = 0; var mappingItem; for (index; index < _formatCharMappingArray.length; index += 1) { mappingItem = _formatCharMappingArray[index]; pattern = pattern.replace(mappingItem.key, mappingItem.value); } return pattern; } /** * @return {number} offset between time zones */ BaseDateTimeFormatInfo.prototype.OffsetBetweenTimeZones = function(date, tzname1, tzname2) { tzname1 = tzname1 || 'UTC'; tzname2 = tzname2 || 'UTC'; return Math.round(this.tzInfo.getTimeZoneOffset(date, tzname1) - this.tzInfo.getTimeZoneOffset(date, tzname2)); }; BaseDateTimeFormatInfo.prototype.HasTimeZone = function(tzname) { if (!tzname || tzname.trim().length === 0) { return true; } try { this.tzInfo.getTimeZoneOffset(new Date(), tzname); return true; } catch (ex) { return false; } }; BaseDateTimeFormatInfo.prototype.Parse = function(dateStr, datePattern, locale) { var isoDate = this._dateStamp.fromISOString(dateStr); if (isoDate) { return isoDate; } var options = {}; if (datePattern) { var selector = this.getSelector(datePattern); if (selector !== null) { options.selector = this.getSelector(datePattern); } options.datePattern = _convertToCLDRDateFormat(datePattern); } options.locale = (locale) ? locale : this.defaultLocale; return this._dateLocale.parse(dateStr, options); }; BaseDateTimeFormatInfo.prototype.Format = function(date, datePattern, locale) { var options = {}; if (datePattern) { options.selector = this.getSelector(datePattern); options.datePattern = _convertToCLDRDateFormat(datePattern); } options.locale = (locale) ? locale : this.defaultLocale; if (this.ISOPattern.test(datePattern)) { var isoStr = this.toISOString(date, {selector: ''}); if (isoStr) { return isoStr; } } return this._dateLocale.format(date, options); }; //computes selecter from datePattern (see http://dojotoolkit.org/reference-guide/dojo/date/locale/format.html#dojo-date-locale-format) BaseDateTimeFormatInfo.prototype.getSelector = function(datePattern) { var timeReg = /[hHmstfF]/; var dateReg = /[Mdy]/; var isTime = timeReg.test(datePattern); var isDate = dateReg.test(datePattern); return ((isTime && isDate) || (!isTime && !isDate)) ? 'date' : (isTime) ? 'time' : 'date'; }; BaseDateTimeFormatInfo.prototype.toISOString = function(dateObject, options) { //dateObject - Date, options - dojo.date.stamp.__Options? // summary: // Format a Date object as a string according a subset of the ISO-8601 standard // // description: // When options.selector is omitted, output follows [RFC3339](http://www.ietf.org/rfc/rfc3339.txt) // The local time zone is included as an offset from GMT, except when selector=="time" (time without a date) // Does not check bounds. Only years between 100 and 9999 are supported. // // dateObject: // A Date object var _ = function(n) { return (n < 10) ? '0' + n : n; }; options = options || {}; var formattedDate = []; getter = 'get'; date = ''; if (options.selector !== 'time') { var year = dateObject[getter + 'FullYear'](); date = ['0000'.substr((year + '').length) + year, _(dateObject[getter + 'Month']() + 1), _(dateObject[getter + 'Date']())].join('-'); } formattedDate.push(date); if (options.selector !== 'date') { var time = [_(dateObject[getter + 'Hours']()), _(dateObject[getter + 'Minutes']()), _(dateObject[getter + 'Seconds']())].join(':'); var millis = dateObject[getter + 'Milliseconds'](); if (options.milliseconds) { time += '.' + (millis < 100 ? '0' : '') + _(millis); } formattedDate.push(time); } return formattedDate.join('T'); // String }; DateTimeFormatInfo = function(locale) { if (!(this instanceof BaseDateTimeFormatInfo)) { throw 'The class DateTimeFormatInfo doesn\'t initialize!'; } //var localeBundle = this._dateLocale._getGregorianBundle(locale); this.ShortDatePattern = "yyyy/M/d";// localeBundle['dateFormat-short']; //alert(this.ShortDatePattern); this.LongDatePattern = "yyyy'年'M'月'd'日'";//localeBundle['dateFormat-long']; //alert(this.LongDatePattern); this.ShortTimePattern = "H:mm";// localeBundle['timeFormat-short']; this.LongTimePattern = "H:mm:ss";//localeBundle['timeFormat-long']; // alert(this.ShortTimePattern); // alert(this.LongTimePattern); this.FullDateTimePattern = this.LongDatePattern.concat(' ', this.LongTimePattern); this.UniversalSortableDateTimePattern = 'yyyy-MM-ddTHH:mm:ssZ'; }; DateTimeFormatInfo.initClass = function() { DateTimeFormatInfo.prototype = new BaseDateTimeFormatInfo(); delete DateTimeFormatInfo.initClass; }; window.DateTimeFormatInfo = DateTimeFormatInfo; })(); /** CultureInfo\NumberFormatInfo.js **/ (function() { var NumberFormatInfo = function(locale) { var _locale = locale; var _numberBundle = null; Object.defineProperty(this, 'numberBundle', { get: function() { if (!_numberBundle) { _numberBundle = dojo.i18n.getLocalization('dojo.cldr', 'number', _locale); } return _numberBundle; } }); Object.defineProperty(this, 'exponentSign', { get: function() { return this.numberBundle.exponential; } }); Object.defineProperty(this, 'numberDecimalSeparator', { get: function() { return this.numberBundle.decimal; } }); Object.defineProperty(this, 'positiveSign', { get: function() { return this.numberBundle.plusSign; } }); Object.defineProperty(this, 'negativeSign', { get: function() { return this.numberBundle.minusSign; } }); Object.defineProperty(this, 'groupSign', { get: function() { return this.numberBundle.group; } }); }; window.NumberFormatInfo = NumberFormatInfo; })(); /** CultureInfo\DoubleHelper.js **/ (function() { var stringModule = null; var escapeSpecialSymbols = function(inputString, except) { // used to escape RegExp special characters return inputString.replace(/([\.$?*|{}\(\)\[\]\\\/\+\-^])/g, function(symbol) { if (except && except.indexOf(symbol) !== -1) { return symbol; } return '\\' + symbol; }); }; var convertNumberString = function(inputVal, inputFormatProvider, outputFormatProvider) { stringModule = stringModule || dojo.require('dojo.string'); inputFormatProvider = inputFormatProvider || CultureInfo.InvariantCulture.NumberFormat; outputFormatProvider = outputFormatProvider || CultureInfo.InvariantCulture.NumberFormat; var validNumberRegExp = stringModule.substitute('^(?:([${0}${1}])?)([\\d]*)(${2}?)(\\d*)([${3}]?)([${0}${1}]?)(\\d*)$', [escapeSpecialSymbols(inputFormatProvider.positiveSign), escapeSpecialSymbols(inputFormatProvider.negativeSign), escapeSpecialSymbols(inputFormatProvider.numberDecimalSeparator), escapeSpecialSymbols(inputFormatProvider.exponentSign)]); var numberValidator = new RegExp(validNumberRegExp, 'i'); var numberParts = numberValidator.exec(inputVal); var convertResult = ''; if (numberParts) { // if number has valid structure var octothorpe = numberParts[1]; var decimalPart = numberParts[2]; var decimalSeparator = numberParts[3]; var fractionalPart = numberParts[4]; var expSymbol = numberParts[5]; var posNegExpPart = numberParts[6]; var exponent = numberParts[7]; if (octothorpe) { convertResult += outputFormatProvider[(octothorpe === inputFormatProvider.positiveSign) ? 'positiveSign' : 'negativeSign']; } convertResult += decimalPart; if (decimalSeparator) { convertResult += outputFormatProvider.numberDecimalSeparator; convertResult += fractionalPart; } if (expSymbol) { convertResult += outputFormatProvider.exponentSign; convertResult += outputFormatProvider[(posNegExpPart === inputFormatProvider.positiveSign) ? 'positiveSign' : 'negativeSign']; convertResult += exponent; } } return convertResult; }; window.DoubleHelper = { Parse: function(inputStr, inputFormatProvider) { var res = convertNumberString(inputStr, inputFormatProvider, CultureInfo.InvariantCulture.NumberFormat); return parseFloat(res); }, ToString: function(inputValue, outputFormatProvider) { return convertNumberString(inputValue.toString(), CultureInfo.InvariantCulture.NumberFormat, outputFormatProvider); } }; })(); /** CultureInfo\CultureInfo.js **/ function CultureInfo(locale) { if (!CultureInfo.initialized) { throw 'The class CultureInfo doesn\'t initialize!'; } var _name = locale; var _dateFormat = null; var _numberFormat = null; Object.defineProperty(this, 'Name', {writable: false, configurable: false, enumerable: true, value: locale}); Object.defineProperty(this, 'DateTimeFormat', { get: function() { if (!_dateFormat) { _dateFormat = new DateTimeFormatInfo(_name); } return _dateFormat; } }); Object.defineProperty(this, 'NumberFormat', { get: function() { if (!_numberFormat) { _numberFormat = new NumberFormatInfo(_name); } return _numberFormat; } }); } CultureInfo.initClass = function() { delete CultureInfo.initClass; DateTimeFormatInfo.initClass(); CultureInfo.CreateSpecificCulture = function(name) { return new CultureInfo(name); }; Object.defineProperty(CultureInfo, 'initialized', {writable: false, configurable: false, enumerable: true, value: true}); Object.defineProperty(CultureInfo, 'InvariantCulture', {writable: false, configurable: false, enumerable: true, value: new CultureInfo('en-us')}); }; /** ..\Modules\aras.innovator.core.Core\Scripts\Classes\DragHelper.js **/ var DragAndDrop; (function(DragAndDrop) { var DragEventHelper = (function() { function DragEventHelper(element) { this.element = element; this.dragTimers = []; this.dragEnterHandlers = []; this.dragLeaveHandlers = []; this.onDragEnter = this.onDragEnter.bind(this); this.onDragLeave = this.onDragLeave.bind(this); this.onDragOver = this.onDragOver.bind(this); this.onDrop = this.onDrop.bind(this); element.addEventListener('dragenter', this.onDragEnter, false); element.addEventListener('dragleave', this.onDragLeave, false); element.addEventListener('dragover', this.onDragOver, false); element.addEventListener('drop', this.onDrop, false); } DragEventHelper.prototype.addDragEnterListener = function(handler) { this.dragEnterHandlers.push(handler); }; DragEventHelper.prototype.addDragLeaveListener = function(handler) { this.dragLeaveHandlers.push(handler); }; DragEventHelper.prototype.removeListeners = function() { this.dragEnterHandlers = []; this.dragLeaveHandlers = []; this.element.removeEventListener('dragenter', this.onDragEnter); this.element.removeEventListener('dragleave', this.onDragLeave); this.element.removeEventListener('dragover', this.onDragOver); this.element.removeEventListener('drop', this.onDrop); }; DragEventHelper.prototype.onDragEnter = function(e) { var _this = this; setTimeout(function() { var timers = _this.dragTimers; _this.dragTimers = []; for (var i = 0; i < timers.length; i++) { clearTimeout(timers[i]); } }, 0); if (!this.dragStarted) { this.dragStarted = true; this.dragEnterHandlers.forEach(function(handler) { handler(e); }); } this.stopEvent(e); return false; }; DragEventHelper.prototype.onDragLeave = function(e) { var _this = this; var dragTimer = setTimeout(function() { _this.dragStarted = false; _this.dragLeaveHandlers.forEach(function(handler) { handler(e); }); }, 100); this.dragTimers.push(dragTimer); this.stopEvent(e); return false; }; DragEventHelper.prototype.onDragOver = function(e) { if (e.dataTransfer && e.dataTransfer.dropEffect) { e.dataTransfer.dropEffect = 'none'; } this.stopEvent(e); return false; }; DragEventHelper.prototype.onDrop = function(e) { this.dragStarted = false; this.dragLeaveHandlers.forEach(function(handler) { handler(e); }); this.stopEvent(e); return false; }; DragEventHelper.prototype.stopEvent = function(e) { if (e.preventDefault) { e.preventDefault(); } if (e.stopPropagation) { e.stopPropagation(); } }; return DragEventHelper; })(); DragAndDrop.DragEventHelper = DragEventHelper; })(DragAndDrop || (DragAndDrop = {})); /** ..\Modules\aras.innovator.core.Core\Scripts\Classes\DragManager.js **/ var DragAndDrop; (function(DragAndDrop) { var DragManager = (function() { function DragManager(win) { if (typeof win === 'undefined') { win = window; } this.win = win; this.childs = []; this.dropboxes = []; this.dragHelper = new DragAndDrop.DragEventHelper(win); this.onDragHandler = this.onDragHandler.bind(this); this.dragHelper.addDragEnterListener(this.onDragHandler); this.dragHelper.addDragLeaveListener(this.onDragHandler); this.eventAggregator = new DragEventAggregator(); this.onGlobalDragEnterHandler = this.onGlobalDragEnterHandler.bind(this); this.onGlobalDragLeaveHandler = this.onGlobalDragLeaveHandler.bind(this); this.eventAggregator.addDragEnterListener(this.onGlobalDragEnterHandler); this.eventAggregator.addDragLeaveListener(this.onGlobalDragLeaveHandler); try { if (win.parent.dragManager) { this.parent = win.parent.dragManager; this.parent.addChildManager(this); } } catch (ex) { this.parent = null; } } DragManager.prototype.deinit = function() { if (this.parent) { this.parent.removeChildManager(this); this.parent = null; } this.dragHelper.removeListeners(); this.dragHelper = null; this.eventAggregator.removeListeners(); this.eventAggregator = null; }; DragManager.prototype.addDropbox = function(dropbox) { this.dropboxes.push(dropbox); }; DragManager.prototype.removeDropbox = function(dropbox) { var index = this.dropboxes.indexOf(dropbox); if (index > -1) { this.dropboxes.splice(index, 1); } }; DragManager.prototype.addChildManager = function(child) { this.childs.push(child); }; DragManager.prototype.removeChildManager = function(child) { var index = this.childs.indexOf(child); if (index > -1) { this.childs.splice(index, 1); } }; DragManager.prototype.onDragHandler = function(e) { var topManager = this.findTopManager(); topManager.eventAggregator.onDrag(e); }; DragManager.prototype.onGlobalDragEnterHandler = function(e) { var maxLevels = []; this.childs.forEach(function(child) { var levels = []; child.dropboxes.forEach(function(dropbox) { if (dropbox.dropPriority > 0) { levels.push(dropbox.dropPriority); } }); if (levels.length > 0) { var maxLevel = Math.max.apply(null, levels); if (maxLevel) { maxLevels.push(maxLevel); } } }); this.traverseManagers(function(manager) { var maxPriority = Math.max.apply(null, maxLevels); manager.dropboxes.forEach(function(dropbox) { if (maxLevels.length > 0) { if (dropbox.dropPriority === maxPriority) { dropbox.onDragBrowserEnter(e); } } else { dropbox.onDragBrowserEnter(e); } }); }); }; DragManager.prototype.onGlobalDragLeaveHandler = function(e) { this.traverseManagers(function(manager) { manager.dropboxes.forEach(function(dropbox) { dropbox.onDragBrowserLeave(e); }); }); }; DragManager.prototype.traverseManagers = function(callback) { callback(this); this.childs.forEach(function(child) { try { child.traverseManagers(callback); } catch (ex) { console.error(ex); } }); }; DragManager.prototype.findTopManager = function() { var topManager = this; var parent = this.parent; while (parent) { topManager = parent; parent = topManager.parent; } return topManager; }; return DragManager; })(); DragAndDrop.DragManager = DragManager; var DragEventAggregator = (function() { function DragEventAggregator() { this.status = 0; this.dragEnterHandlers = []; this.dragLeaveHandlers = []; } DragEventAggregator.prototype.addDragEnterListener = function(handler) { this.dragEnterHandlers.push(handler); }; DragEventAggregator.prototype.addDragLeaveListener = function(handler) { this.dragLeaveHandlers.push(handler); }; DragEventAggregator.prototype.removeListeners = function() { this.dragEnterHandlers = []; this.dragLeaveHandlers = []; }; DragEventAggregator.prototype.onDrag = function(e) { switch (e.type) { case 'dragenter': this.onDragEnter(e); break; case 'dragleave': this.onDragLeave(e); break; case 'drop': this.onDrop(e); break; default: break; } }; DragEventAggregator.prototype.onDragEnter = function(e) { if (this.status === 0) { this.dragEnterHandlers.forEach(function(handler) { handler(e); }); } this.status++; }; DragEventAggregator.prototype.onDragLeave = function(e) { this.status--; if (this.status <= 0) { this.status = 0; this.dragLeaveHandlers.forEach(function(handler) { handler(e); }); } }; DragEventAggregator.prototype.onDrop = function(e) { this.status = 0; this.dragLeaveHandlers.forEach(function(handler) { handler(e); }); }; return DragEventAggregator; })(); DragAndDrop.DragEventAggregator = DragEventAggregator; })(DragAndDrop || (DragAndDrop = {})); window.dragManager = window.dragManager || new DragAndDrop.DragManager(window); window.addEventListener('beforeunload', function() { if (window.dragManager) { window.dragManager.deinit(); delete window.dragManager; } }); /** ..\Modules\core\Soap.js **/ (function($) { window.ArasModules = window.ArasModules || $; var globalConfig = { headers: {}, async: false, soapConfig: {}, appendMethodToURL: false, restMethod: 'POST', soap12: false }; $.soap = function(data, options) { var config = {}; options = options || {}; if (data === null) { Object.assign(globalConfig, options); return; } Object.assign(config, globalConfig, options); Object.assign(SOAPTool.settings, config.soap12 ? SOAP12 : SOAP11, globalConfig.soapConfig); if (typeof(options.soapConfig) === 'object') { Object.assign(SOAPTool.settings, options.soapConfig); } if (config.url) { var url = config.url; if (config.appendMethodToURL && !!config.method) { url += config.method; } if (!config.soap12 && (config.method || config.SOAPAction)) { config.headers.SOAPAction = config.SOAPAction || config.method; } var soapMessage = SOAPTool.createSoapMessage(data, config.method, config.methodNm); return SOAPTool.send(soapMessage, { url: url, async: config.async, headers: config.headers, restMethod: config.restMethod }); } }; var SOAP11 = { type: 'text/xml', headers: '', customNS: {}, prefix: 'SOAP-ENV', namespace: 'http://schemas.xmlsoap.org/soap/envelope/' }; var SOAP12 = { type: 'application/soap+xml', headers: '', customNS: {}, prefix: 'env', namespace: 'http://www.w3.org/2003/05/soap-envelope' }; var SOAPTool = { settings: {}, createSoapMessage: function(xml, method, namespace) { var prefix = this.settings.prefix; var customNS = this.settings.customNS; var message = '<' + prefix + ':Envelope xmlns:' + prefix + '="' + this.settings.namespace + '" '; Object.keys(customNS).forEach(function(ns) { message += ns + '="' + customNS[ns] + '" '; }); message += '><' + prefix + ':Body>'; if (method) { message += '<' + method + (namespace ? ' xmlns="' + namespace + '">' : '>'); } message += (typeof(xml) === 'string' ? xml : this.dom2string(xml)); if (method) { message += ''; } message += ''; return message; }, abort: function(xhr) { return function() { xhr.onpropertychange = function() {}; xhr.abort(); }; }, getResult: function(xhr) { // SiteMinder Integration hack // Get first 2000 characters from response for SiteMinder detection without performance degradation var substr = xhr.responseText.substring(0, 2000); if (/SMSESSION=LOGGEDOFF/i.test(xhr.getAllResponseHeaders()) || (//i.test(substr) && /NAME="SMPostPreserve"/i.test(substr))) { return { isFault: true }; } var isFault = false; var resultNode; var xml = this.parseToXml(xhr); if (xml && xml.firstChild && xml.firstChild.firstChild) { var result = xml.firstChild.firstChild.firstChild; isFault = (result && result.nodeName.toLowerCase() === 'soap-env:fault'); resultNode = ((result && result.nodeName.toLowerCase() === 'result') || isFault) ? result : null; } return { isFault: isFault, resultNode: resultNode }; }, parseToXml: function(xhr) { if ('ActiveXObject' in window) { return $.xml.parseString(xhr.responseText); } return xhr.responseXML; }, send: function(data, config) { var promise; var req = new XMLHttpRequest(); req.open(config.restMethod, config.url, config.async); req.setRequestHeader('Content-Type', this.settings.type + '; charset=UTF-8'); Object.keys(config.headers).forEach(function(key) { req.setRequestHeader(key, config.headers[key]); }); var _self = this; if (config.async) { promise = new Promise(function(resolve, reject) { req.onreadystatechange = function() { if (this.readyState === 4 && this.status === 200) { var obj = _self.getResult(req); if (obj.isFault) { reject(req); } else { resolve(obj.resultNode || req.responseText); } } else if (this.readyState === 4) { reject(req); } }; req.send((config.restMethod != null &&config.restMethod.toLowerCase() === 'get') ? null : data); }); } else { promise = new SyncPromise(function(resolve, reject) { try { req.send((config.restMethod!=null&&config.restMethod.toLowerCase() === 'get' )? null : data); } catch (e) { return reject(req); } if (req.status === 200) { var obj = _self.getResult(req); if (obj.isFault) { reject(req); } else { resolve(obj.resultNode || req.responseText); } } else { reject(req); } }); } promise.abort = this.abort(req); return promise; }, dom2string: function(dom) { if (window.XMLSerializer) { return new window.XMLSerializer().serializeToString(dom); } else { return dom.xml; } } }; var SyncPromise = function(func) { var argValue; var isReject = false; func(function(value) { argValue = value; }, function(value) { argValue = value; isReject = true; }); this.then = function(funcResolve, funcReject) { var value; if (!isReject) { value = funcResolve.call(null, argValue); return (value instanceof SyncPromise) ? value : SyncPromise.resolve(value); } else if (funcReject && isReject) { value = funcReject.call(null, argValue); return (value instanceof SyncPromise) ? value : SyncPromise.reject(value); } return this; }; this['catch'] = function(funcReject) { if (isReject) { var value = funcReject.call(null, argValue); return (value instanceof SyncPromise) ? value : SyncPromise.reject(value); } return this; }; }; SyncPromise.resolve = function(value) { return new SyncPromise(function(resolve, reject) { resolve(value); }); }; SyncPromise.reject = function(value) { return new SyncPromise(function(resolve, reject) { reject(value); }); }; $.SyncPromise = SyncPromise; })(window.ArasModules || {}); /** ..\Modules\core\Dialog.js **/ (function(externalParent) { var dialogTypes = { 'WhereUsed': { classList: 'whereUsed' }, 'SearchDialog': { classList: 'searchDialog', content: 'searchDialog.html', title: 'Search dialog' }, 'ImageBrowser': { classList: 'imageBrowser', content: 'ImageBrowser/imageBrowser.html', title: 'Image Browser' }, 'Date': { classList: 'date', title: 'Date Dialog', content: 'dateDialog.html' }, 'HTMLEditorDialog': { content: 'HTMLEditorDialog.html', size: 'max', classList: 'htmlEditorDialog' }, 'RevisionsDialog': { classList: 'revisionsDialog', title: 'Item Versions', content: 'revisionDialog.html' }, 'ManageFileProperty': { title: 'Manage File', content: 'manageFileDialog.html', classList: 'manageFileProperty' }, 'Text': { title: 'Text Dialog', content: 'textDialog.html', classList: 'text' }, 'Color': { title: 'Color Dialog', content: 'colorDialog.html', classList: 'color' } }; var htmlHelper = { buildTemplate: function(template, dialog) { dialog.innerHTML = template; }, setTitle: function(title, dialog) { var titleNode = dialog.querySelector('.arasDialog-titleBar .arasDialog-title'); if (titleNode) { titleNode.textContent = title || ''; } }, setUpOptions: function(options, dialog) { if (options) { dialog.style.width = options.dialogWidth + 'px'; dialog.style.height = options.dialogHeight + 'px'; if (options.classList) { dialog.classList.add(options.classList); } } }, loadContent: function(type, dialog, data) { var contentNode = dialog.querySelector('.arasDialog-content'); if (type === 'iframe' && contentNode && contentNode.querySelector('.arasDialog-iframe')) { contentNode.querySelector('.arasDialog-iframe').src = data; } }, normalizeCoords: function(block, x, y) { var height = block.offsetHeight; var width = block.offsetWidth; var docWidth = document.documentElement.offsetWidth; var docHeight = document.documentElement.offsetHeight; var normalizedX = Math.max(x, 0); var normalizedY = Math.max(y, 0); if (x + width > docWidth) { normalizedX = docWidth - width; } if (y + height > docHeight) { normalizedY = docHeight - height; } return {x: normalizedX, y: normalizedY}; } }; var eventsHelper = { onMouseDown: function(evt) { this.dialogNode.classList.add('arasDialog-moving'); this.offsetX = this.dialogNode.offsetLeft || 0; this.offsetY = this.dialogNode.offsetTop || 0; this.downedX = evt.pageX; this.downedY = evt.pageY; var self = this; var move = eventsHelper.onMouseMove.bind(this); window.addEventListener('mousemove', move, true); window.addEventListener('mouseup', function(evt) { window.removeEventListener('mousemove', move, true); window.removeEventListener('mouseup', arguments.callee, false); self.dialogNode.classList.remove('arasDialog-moving'); var clientX = self.offsetX + (evt.pageX - self.downedX); var clientY = self.offsetY + (evt.pageY - self.downedY); self.move(clientX, clientY); self.dialogNode.style.transform = ''; }, false); evt.preventDefault(); return; }, onMouseMove: function(evt) { var calculatedX = parseInt(evt.pageX) - this.downedX; var calculatedY = parseInt(evt.pageY) - this.downedY; this.dialogNode.style.transform = 'translate(' + calculatedX + 'px, ' + calculatedY + 'px)'; }, onClose: function(data) { // set the focus to the main window, because when you remove an iframe which has focus // in IE doesn't set focus in text fields if (this.type === 'iframe') { var iframe = this.dialogNode.querySelector('.arasDialog-iframe'); iframe.src = 'about:blank'; } this.dialogNode.parentNode.removeChild(this.dialogNode); }, onWindowResize: function() { if (this.dialogNode.classList.contains('arasDialog-moved')) { this.move(this.dialogNode.offsetLeft, this.dialogNode.offsetTop); } else { var scrollTop = document.body.scrollTop || document.documentElement.scrollTop; var topValue = scrollTop + (window.innerHeight - this.dialogNode.offsetHeight) / 2; this.dialogNode.style.top = Math.max(scrollTop, topValue) + 'px'; } }, attachEvents: function(dialog) { dialog.dialogNode.addEventListener('close', dialog._tryResolveOnClose); dialog.attachedEvents.tryResolveOnClose = { 'node': dialog.dialogNode, 'eventName': 'close', 'callback': dialog._tryResolveOnClose }; var onWindowResize = eventsHelper.onWindowResize.bind(dialog); window.addEventListener('resize', onWindowResize); dialog.attachedEvents.onResizeWindow = { 'node': window, 'eventName': 'resize', 'callback': onWindowResize }; }, detachEvents: function(dialog) { var events = Object.keys(dialog.attachedEvents); for (var i = 0; i < events.length; i++) { var event = dialog.attachedEvents[events[i]]; event.node.removeEventListener(event.eventName, event.callback, false); } dialog.attachedEvents = {}; } }; var iframeHelper = { setDialogArguments: function(params, dialog) { params.dialog = dialog; var iframeNode = dialog.dialogNode.querySelector('.arasDialog-iframe'); if (iframeNode) { iframeNode.dialogArguments = params; } } }; function init(type, args) { var dialogType = {}; if (args.type && dialogTypes[args.type]) { dialogType = Object.assign(dialogType, dialogTypes[args.type]); args.classList = dialogType.classList; } var dialog = document.createElement('dialog'); dialog.classList.add('arasDialog'); var self = this; htmlHelper.buildTemplate(this.template, dialog); htmlHelper.setTitle(dialogType.title || args.title, dialog); htmlHelper.loadContent(type, dialog, dialogType.content || args.content); htmlHelper.setUpOptions(args, dialog); if (!dialog.showModal) { dialogPolyfill.registerDialog(dialog); } document.body.appendChild(dialog); this.dialogNode = dialog; this.promise = new Promise(function(resolve, reject) { self._tryResolveOnClose = function() { var returnValue = self.returnValue; if (returnValue === undefined && type === 'iframe') { var iframe = self.dialogNode.querySelector('.arasDialog-iframe'); if (iframe.contentWindow && iframe.contentWindow.returnValue) { returnValue = iframe.contentWindow.returnValue; } } //Chrome prevent opening a new window when popup dialog closes setTimeout(function() { resolve(returnValue); }, 0); eventsHelper.detachEvents(self); eventsHelper.onClose.call(self); self.dialogNode = null; }; }); eventsHelper.attachEvents(this); iframeHelper.setDialogArguments(args, this); } function Dialog(type, args) { this.promise = null; this.dialogNode = null; this.attachedEvents = {}; this.type = type; init.call(this, type, args); this.makeMove(); this.makeClose(); } var staticData = { template: '
' + '' + '' + '
' + '
' + '' + '
', makeMove: function() { var onMouseDownBinded = eventsHelper.onMouseDown.bind(this); this.dialogNode.querySelector('.arasDialog-titleBar .arasDialog-title').addEventListener('mousedown', onMouseDownBinded, true); this.attachedEvents.dragAndDrop = { 'node': this.dialogNode.querySelector('.arasDialog-titleBar .arasDialog-title'), 'eventName': 'mousedown', 'callback': onMouseDownBinded }; }, makeClose: function() { var onCloseButtonBinded = this.close.bind(this, undefined); this.dialogNode.querySelector('.arasDialog-titleBar .arasDialog-closeButton').addEventListener('click', onCloseButtonBinded); this.attachedEvents.onCloseBtn = { 'node': this.dialogNode.querySelector('.arasDialog-titleBar .arasDialog-closeButton'), 'eventName': 'click', 'callback': onCloseButtonBinded }; }, makeAutoresize: function() { var oldBox = {w: window.outerWidth, h: window.outerHeight}; var deltaWidth = 40; var deltaHeight = 45; //this deltas are used for detect a necessity to resize the parent window of the dialog var oldBoxWidthRatio = oldBox.w; var oldBoxHeightRation = oldBox.h; // trick for calculating dialog sizes because // when max-height or max-width less than original sizes // so to get it is not possible this.dialogNode.style.maxWidth = 'none'; this.dialogNode.style.maxHeight = 'none'; var widthWithDelta = this.dialogNode.offsetWidth + deltaWidth; var heightWithDelta = this.dialogNode.offsetHeight + deltaHeight; this.dialogNode.style.maxWidth = '100%'; this.dialogNode.style.maxHeight = '100%'; if (window.TopWindowHelper && window.TopWindowHelper.getMostTopWindowWithAras(window)) { var topWnd = TopWindowHelper.getMostTopWindowWithAras(window); if (oldBoxWidthRatio < widthWithDelta || oldBoxHeightRation < heightWithDelta) { var newHeight = oldBoxHeightRation < heightWithDelta ? parseInt(heightWithDelta) : oldBox.h; var newWidth = oldBoxWidthRatio < widthWithDelta ? parseInt(widthWithDelta) : oldBox.w; topWnd.aras.browserHelper.resizeWindowTo(topWnd, newWidth, newHeight); this.promise.then(function() { // Resize callback for promise which does not allow to correctly define the next chain parts. // This is related with browser performance for async operations setTimeout(function() { topWnd.aras.browserHelper.resizeWindowTo(topWnd, oldBox.w, oldBox.h); }, 0); }); } } }, show: function() { if (this.dialogNode.style.display !== 'none') { this.dialogNode.showModal(); } this.dialogNode.style.display = ''; this.makeAutoresize(); }, hide: function() { this.dialogNode.style.display = 'none'; }, close: function(data) { if (this.dialogNode && this.dialogNode.hasAttribute('open')) { this.returnValue = data; this.dialogNode.close(); } }, move: function(left, top) { var normalized = htmlHelper.normalizeCoords(this.dialogNode, left, top); this.dialogNode.style.left = normalized.x + 'px'; this.dialogNode.style.top = normalized.y + 'px'; if (!this.dialogNode.classList.contains('arasDialog-moved')) { this.dialogNode.classList.add('arasDialog-moved'); } }, setTitle: function(title) { htmlHelper.setTitle(title, this.dialogNode); }, resizeContent: function(width, height) { var titleHeight = Math.floor(this.dialogNode.offsetHeight - this.dialogNode.querySelector('.arasDialog-content').offsetHeight); this.resize(width, height + titleHeight); }, resize: function(width, height) { this.dialogNode.style.width = width + 'px'; this.dialogNode.style.height = height + 'px'; this.makeAutoresize(); eventsHelper.onWindowResize.call(this); } }; Dialog.prototype = staticData; var classData = { show: function(type, args) { var dialog = new Dialog(type, args); dialog.show(); return dialog; } }; Object.assign(Dialog, classData); externalParent = Object.assign(externalParent, {'Dialog': Dialog}); window.ArasModules = window.ArasModules || externalParent; })(window.ArasModules || {}); /** ..\Modules\core\Xml.js **/ (function(arasModules) { var xmlFlags = (function() { var flags = { 'setDeclaretion': false, 'deleteTrashAttr': false }; if ('ActiveXObject' in window) { return flags; } // Chrome not added xml declaretion after transform var xml = (new DOMParser()).parseFromString('', 'text/xml'); var xsl = (new DOMParser()).parseFromString( '' + '

1

' + '
', 'text/xml'); var p = new XSLTProcessor(); p.importStylesheet(xsl); var f = p.transformToDocument(xml); var res = (new XMLSerializer()).serializeToString(f); flags.setDeclaretion = res.indexOf('/, ''); } var processor = new XSLTProcessor(); processor.importStylesheet(stylesheetDoc); var outputNode = this.selectSingleNode(stylesheetDoc, './xsl:stylesheet/xsl:output'); var isHtml = (outputNode && outputNode.getAttribute('method') === 'html'); var resultDoc = processor.transformToDocument(transformDoc); if (!isHtml && xmlFlags.setDeclaretion) { var piElem = resultDoc.createProcessingInstruction('xml', 'version="1.0" encoding="UTF-8"'); resultDoc.insertBefore(piElem, resultDoc.firstChild); } var resultString = isHtml ? resultDoc.documentElement.outerHTML : this.getXml(resultDoc); if (!isHtml && xmlFlags.deleteTrashAttr) { var trashStr = ' xmlns="http://www.w3.org/1999/xhtml"'; resultString = resultString.split(trashStr).join(''); } return resultString; }, createNode: function(xmlDocument, nodeType, nodeName, namespaceUrl) { if (window.ActiveXObject !== undefined) { return xmlDocument.createNode(nodeType, nodeName, namespaceUrl); } return xmlDocument.createElementNS(namespaceUrl, nodeName); }, getText: function(xmlNode) { if (window.ActiveXObject !== undefined) { return xmlNode.text; } return xmlNode.textContent; }, setText: function(xmlNode, value) { value = value || ''; if (window.ActiveXObject !== undefined) { xmlNode.text = value; return; } xmlNode.textContent = value; }, getXml: function(xmlDocument) { if (window.ActiveXObject !== undefined) { return xmlDocument.xml; } var resultString = (new XMLSerializer()).serializeToString(xmlDocument); // Edge can't read declaration if (xmlDocument.firstChild && xmlDocument.firstChild.nodeType === xmlDocument.PROCESSING_INSTRUCTION_NODE && resultString.indexOf('' + resultString; } return resultString; }, getError: function(xmlDocument) { if (window.ActiveXObject !== undefined) { return xmlDocument.parseError; } var documentNode = xmlDocument.documentElement; if (documentNode) { var errorChildNum = 0; // for Chrome browser that return html instead parseerror xml block if (documentNode.nodeName === 'html' && documentNode.firstChild && documentNode.firstChild.firstChild) { documentNode = documentNode.firstChild.firstChild; errorChildNum = 1; } if (documentNode.nodeName === 'parsererror') { return { errorCode: 1, srcText: '', reason: documentNode.childNodes[errorChildNum].nodeValue }; } } return {errorCode: 0}; } }; })(window.ArasModules); /** ..\Modules\core\vault.js **/ (function(arasModules) { var vault = { _downloadHelper: function(url, async) { var frameId = 'downloadFrame'; var download = function() { var frame = document.getElementById(frameId); if (frame === null) { frame = document.createElement('iframe'); frame.id = frameId; frame.style.display = 'none'; document.body.appendChild(frame); } frame.src = url; }; var xhr = new XMLHttpRequest(); xhr.open('HEAD', url, async); xhr.send(); if (async) { return new Promise(function(resolve, reject) { var asyncCallback = function() { if (this.status !== 200) { return reject({ status: this.status, message: 'The file hasn\'t been downloaded!' }); } download(); resolve(); }; var errorCallback = function() { reject({ status: this.status || 500, message: 'Connection error!' }); }; xhr.addEventListener('load', asyncCallback); xhr.addEventListener('error', errorCallback); }); } else { if (xhr.status !== 200) { throw new Error('Server status: ' + xhr.status + '. The file hasn\'t been downloaded!'); } download(); } }, /** * Downloading file using frame. * Create HEAD request to check if file exists and * use frame to download it. * @param {string} url * @return {Promise} */ downloadFile: function(url) { return this._downloadHelper(url, true); }, /** * Opening file select dialog. * @return {Promise} */ selectFile: function() { var previouslyAddedNode = document.getElementById('fileSelector'); if (previouslyAddedNode) { document.body.removeChild(previouslyAddedNode); } var inputNode = document.createElement('input'); inputNode.style.display = 'none'; inputNode.type = 'file'; inputNode.id = 'fileSelector'; document.body.appendChild(inputNode); return new Promise(function(resolve) { inputNode.addEventListener('change', function() { resolve(this.files[0]); document.body.removeChild(this); }, false); inputNode.click(); }); }, /** * Saving Blob object as file. * In IE call msSaveOrOpenBlob method to open window. * If browser don't support msSaveOrOpenBlob method, * create link with download attribute * and trigger click on it to open window. @param {string} blob @param {string} fileName */ saveBlob: function(blob, fileName) { if (window.navigator.msSaveOrOpenBlob) { window.navigator.msSaveOrOpenBlob(blob, fileName); } else { var link = document.createElement('a'); link.style.display = 'none'; link.href = URL.createObjectURL(blob); link.download = fileName; document.body.appendChild(link); link.click(); document.body.removeChild(link); } } }; arasModules.vault = Object.assign(arasModules.vault || {}, vault); })(window.ArasModules || {}); /** ..\Modules\core\vaultUploader.js **/ (function(externalParent) { /** * @typedef {File} ExtendedFile * @property {String} fileItemId - Id from AML Item of file * * Internal module type. */ /** * @typedef {String} FileState * * Internal module type. * Each file have states: * - "pending" - file not uploaded and has waiting for upload; * - "in progress" - some chunks of file currently are in upload; * - "uploaded" - file is uploaded. */ /** * @typedef {Object} Chunk * @property {Blob} data * @property {Number} from - Count of file bytes where starts the chunk range * @property {Number} to - Count of file bytes where ends the chunk range * * Internal module type. * Serves to allow a possibility to upload a chunk multiple times */ /** * Serves to store the states of file uploading * * @param {ExtendedFile} file * @param {Boolean} isAsync * * @property {String} fileName * @property {String} fileItemId * @property {Number} fileSize * @property {File} _file * @property {Boolean} _isAsync - Chunks of file can be uploaded synchronously or not * @property {FileState} _state * @property {Number} _sentBytes - Watch to * @property {Number} _readingPoint * @property {Number} chunkSize * * @constructor */ function FileWrapper(file, isAsync, worker) { this.fileName = file.name; this.fileItemId = file.fileItemId; this.fileSize = file.size; this._file = file; this._isAsync = isAsync; this._state = 'pending'; this._sentBytes = 0; this._readingPoint = 0; if (this.fileSize && worker) { this._hashWaiting = {}; this._hashes = {}; this.initialize(worker); } } FileWrapper.prototype = { chunkSize: 16 * 1024 * 1024, //16 Mb constructor: FileWrapper, /** * Method needs to split file at chunks to upload. * Chunks splits by the schema: * ChunkSize = 16 Mb * * file: [________________36Mb________________] * 1 ch: [0Mb + 16Mb]_________________________ * 2 ch: ____________[16Mb + 16Mb]____________ * 3 ch: _________________________[32Mb + 4Mb] * * @return {Chunk|undefined} undefined if file is empty */ getData: function() { this._state = 'in progress'; if (this.fileSize === 0) { return Promise.resolve(); } var offset = this._readingPoint; this._readingPoint = Math.min(this.fileSize, offset + this.chunkSize); var promise = new Promise((function(resolve, reject) { if (!this._hashes || this._hashes[offset]) { resolve(this._formatPacket(offset)); } else { this._hashWaiting[offset] = resolve; } }).bind(this)); return promise; }, /** * Toggles state of file upload to "uploaded" or "pending" */ endUpload: function() { this._sentBytes = Math.min(this.fileSize, this._sentBytes + this.chunkSize); this._state = (this._sentBytes === this.fileSize) ? 'uploaded' : 'pending'; }, isAllowedUpload: function() { if (this._state === 'uploaded' || (!this._isAsync && this._state === 'in progress')) { return false; } else if (this.fileSize === 0 && this._state === 'pending') { return true; } return this._readingPoint < this.fileSize; }, initialize: function(worker) { var offset = 0; var receiveHash = function(e) { var receivedData = e.data; if (receivedData.fileId === this.fileItemId) { offset = Math.min(this.fileSize, offset + this.chunkSize); this._hashes[receivedData.offset] = receivedData.xxhash; if (this._hashWaiting[receivedData.offset]) { this._hashWaiting[receivedData.offset](this._formatPacket(receivedData.offset)); } if (offset < this.fileSize) { worker.postMessage(this._formatPacket(offset)); } } }; worker.addEventListener('message', receiveHash.bind(this)); worker.postMessage(this._formatPacket(0)); }, _formatPacket: function(offset) { var to = Math.min(this.fileSize, offset + this.chunkSize); return { fileId: this.fileItemId, from: offset, to: to, hash: this._hashes ? this._hashes[offset] : null, data: this._file.slice(offset, to) }; } }; /** * Class is needed for encapsulation of each upload transaction of files * to providing opportunity to send more than 1 set of files to upload and prevent conflicts. * * @param {FileList|File[]} files * @param {{credentials: Object, isAsync: Boolean, serverUrl: String}} options * @param {String} aml * * @property {Object} _credentials * @property {String} _serverUrl * @property {FileWrapper[]} _filesWrappers * @property {Number} attempts - The number of attempts of try to repeat upload chunk * * @constructor */ function FilesUploader(files, options, aml) { this._credentials = Object.assign({}, options.credentials); this._serverUrl = options.serverUrl; this._fileWrappers = []; this.attempts = 10; this._initFileWrappers(files, !!options.isAsync, aml); } FilesUploader.prototype = { constructor: FilesUploader, /** * @param {FileList|File[]} files * @param {Boolean} isAsync * @param {String} aml * @private */ _initFileWrappers: function(files, isAsync, aml) { var doc = externalParent.xml.parseString(aml); var fileItems = externalParent.xml.selectNodes(doc, '//Item[@type=\'File\' and @action=\'add\']'); var fileItem; var file; if (!this._serverUrl.startsWith('https')) { this._xxhWorker = new Worker('../Modules/core/xxhWorker.js'); } fileItems = Array.prototype.slice.call(fileItems); // search item file id for upload transaction for (var i = 0, n = files.length; i < n; i++) { file = files[i]; for (var j = 0, m = fileItems.length; j < m; j++) { fileItem = fileItems[j]; if (file.name === fileItem.selectSingleNode('filename').text && file.size === +fileItem.selectSingleNode('file_size').text ) { file.fileItemId = fileItem.getAttribute('id'); fileItems.splice(j, 1); break; } } this._fileWrappers.push(new FileWrapper(file, isAsync, this._xxhWorker)); } }, /** * Sets the existing transaction id as request header with the other headers. * Thus server can identify a context of uploaded files * * @param {XMLHttpRequest} xhr * @param {Object} [headers] * @private */ _setHeaders: function(xhr, headers) { headers = Object.assign({}, this._credentials, headers || {}); if (this._transactionId) { headers.transactionid = this._transactionId; } Object.keys(headers).forEach(function(header) { xhr.setRequestHeader(header, headers[header]); }); }, /** * @param {String|Node} response * @returns {Node|undefined} * @private */ _selectResultNode: function(response) { if (response.nodeName) { return response; } var xmlModule = externalParent.xml; var doc = xmlModule.parseString(response); return xmlModule.selectSingleNode(doc, '//Result'); }, /** * Serves to beginning of upload transaction on the server and takes its transaction id * * @returns {Promise} Resolves without parameters */ beginTransaction: function() { var self = this; return externalParent.soap('', { async: true, method: 'BeginTransaction', url: self._serverUrl, headers: Object.assign({}, self._credentials) }) .then(function(response) { var node = self._selectResultNode(response); if (!node) { // will caught below to throw an error return Promise.reject({status: 200, responseText: response}); } self._transactionId = node.text; }) .catch(function(xhr) { throw new Error(xhr.status + ' occurred while beginning transaction with text: ' + xhr.responseText); }); }, /** * Serves to rollback of upload transaction on the server which removes earlier uploaded files * * @returns {undefined | Promise} undefined returns if no sense in rollback | Promise resolves with xhr */ rollbackTransaction: function() { if (!this._transactionId) { return; } var headers = Object.assign({ transactionid: this._transactionId }, this._credentials); return externalParent.soap('', { async: true, method: 'RollbackTransaction', url: this._serverUrl, headers: headers }); }, /** * Serves to commit of upload transaction on the server and applies aml as the context of uploaded files * * @param {String} aml * @returns {Promise} Resolves with xml node */ commitTransaction: function(aml) { var self = this; return new Promise(function(resolve, reject) { var formData = new FormData(); var xhr = new XMLHttpRequest(); formData.append('XMLData', aml); xhr.open('POST', self._serverUrl, true); self._setHeaders(xhr, { SOAPAction: 'CommitTransaction' }); xhr.addEventListener('error', function() { reject(xhr); }); xhr.addEventListener('load', function() { if (xhr.status < 200 || xhr.status > 299) { reject(xhr); } else { var node = self._selectResultNode(xhr.responseText); if (!node) { reject(xhr); } resolve(node); } }); xhr.send(formData); }) .catch(function(xhr) { if (xhr.status === 200) { var responseXML = externalParent.xml.parseString(xhr.responseText); throw responseXML; } throw new Error(xhr.status + ' occurred while commit transaction with text: ' + xhr.responseText); }); }, /** * Encodes file name for Content-Disposition * * @returns {String} Encoded string * @private */ _encodeRFC5987ValueChars: function(str) { //noinspection JSDeprecatedSymbols return encodeURIComponent(str) .replace(/['()]/g, escape) // i.e., %27 %28 %29 .replace(/\*/g, '%2A') .replace(/%(?:7C|60|5E)/g, unescape); }, /** * @returns {undefined | FileWrapper} A wrapper of file which is not uploaded fully * @private */ _searchNotUploadedFile: function() { // simple cycle used to avoid unnecessary iterations for (var i = 0, n = this._fileWrappers.length; i < n; i++) { if (this._fileWrappers[i].isAllowedUpload()) { return this._fileWrappers[i]; } } }, /** @private */ _upload: function(fileWrapper, dataObject) { var self = this; return new Promise(function(resolve, reject) { var XmlHttpRequest = fileWrapper._file.Xhr || XMLHttpRequest; var xhr = new XmlHttpRequest(); var url = self._serverUrl + ((self._serverUrl.indexOf('?') > -1) ? '&' : '?') + 'fileId=' + fileWrapper.fileItemId; xhr.open('POST', url, true); xhr.addEventListener('error', function(event) { reject(event.target.statusText); }); xhr.addEventListener('load', function(event) { if (event.target.status !== 200) { reject(event.target.statusText); return; } fileWrapper.endUpload(); resolve(); }); var contentRange = (!dataObject) ? '*/0' : dataObject.from + '-' + (dataObject.to - 1) + '/' + fileWrapper.fileSize; var headers = { 'Content-Type': 'application/octet-stream', 'Content-Range': 'bytes ' + contentRange, 'SOAPAction': 'UploadFile', 'Content-Disposition': 'attachment; filename*=utf-8\'\'' + self._encodeRFC5987ValueChars(fileWrapper.fileName) }; if (self._xxhWorker) { headers['Aras-Content-Range-Checksum'] = dataObject ? dataObject.hash : '46947589'; headers['Aras-Content-Range-Checksum-Type'] = 'xxHashAsUInt32AsDecimalString'; } self._setHeaders(xhr, headers); xhr.send(dataObject ? dataObject.data : null); }).catch(function(message) { if (self.attempts > 0) { self.attempts--; return self._upload(fileWrapper, dataObject); } self.attempts--; return Promise.reject(message); }); }, /** * Serves to filter and send data to the server * * @returns {Promise} undefined returns if no data to send or file already loaded in sync mode * Promise resolves without parameters */ send: function() { var fileWrapper = this._searchNotUploadedFile(); if (!fileWrapper || this.attempts === -1) { return Promise.resolve(); } return fileWrapper.getData() .then((function(data) { return this._upload(fileWrapper, data); }).bind(this)) .then(this.send.bind(this)); }, destroyWorker: function() { if (this._xxhWorker) { this._xxhWorker.terminate(); this._xxhWorker = null; } } }; /** * Serves to control upload queue of data. * For each call of send makes new instance of it to avoid redundant * complexity in cases when exists only one vault instance in application. * * @constructor */ function RequestsManager() {} RequestsManager.prototype = { constructor: RequestsManager, parallelRequests: 3, /** * Serves to start parallel requests * * @param {FilesUploader} filesUploader * @returns {Promise} Resolves without parameters * @private */ _upload: function(filesUploader) { var array = []; for (var i = this.parallelRequests; i--;) { array.push(filesUploader.send()); } return Promise.all(array); }, /** * Serves to control action sequence of upload * * @param {FileList|File[]} files * @param {{credentials: Object, isAsync: Boolean, serverUrl: String}} options * @param {String} aml * @returns {Promise|undefined} Resolves with response after commit transaction */ send: function(files, options, aml) { var self = this; var filesUploader = new FilesUploader(files, options, aml); return filesUploader .beginTransaction() .then(function() { return self._upload(filesUploader); }) .then(function() { filesUploader.destroyWorker(); return filesUploader.commitTransaction(aml); }) .catch(function(error) { filesUploader.destroyWorker(); filesUploader.rollbackTransaction(); return Promise.reject(error); }); } }; var vaultUploader = { options: { serverUrl: 'http://localhost/S11-0-SP8', credentials: {}, isAsync: false }, /** * @param {FileList|File[]} files * @param {String} aml * @returns {Promise} */ send: function(files, aml) { return (new RequestsManager()).send(files, this.options, aml); } }; externalParent.vault = Object.assign(externalParent.vault || {}, vaultUploader); })(window.ArasModules || {}); /** ..\Modules\core\MaximazableDialog.js **/ (function(arasModules) { var Dialog = arasModules.Dialog; function MaximazableDialog(type, args) { Dialog.call(this, type, args); this.makeMaximazable(); this.restoreData = {}; // dialog's attributes in normal state (before maximization) } var privateData = { maximizedClass: 'arasDialog-maximized', maximizedIconClass: 'aras-icon-minimize' }; var instanceData = { constructor: MaximazableDialog, template: '
' + '' + '' + '' + '
' + '
' + '' + '
', makeMaximazable: function() { var maximizeButton = this.dialogNode.querySelector('.arasDialog-titleBar .arasDialog-maximizeButton'); // it's important to bind with the second undefined parameter in order to preserve 'maximize' method's logic var onMaximizeBinded = this.maximize.bind(this, undefined); maximizeButton.addEventListener('click', onMaximizeBinded); this.attachedEvents.onExpand = { 'node': maximizeButton, 'eventName': 'click', 'callback': onMaximizeBinded }; }, maximize: function(needMaximization) { var dialogNode = this.dialogNode; var maximizeButtonNode = dialogNode.querySelector('.arasDialog-titleBar .arasDialog-maximizeButton'); if (needMaximization === undefined) { needMaximization = !dialogNode.classList.contains(privateData.maximizedClass); } dialogNode.classList.toggle(privateData.maximizedClass, needMaximization); maximizeButtonNode.classList.toggle(privateData.maximizedIconClass, needMaximization); if (needMaximization) { this.restoreData = { top: dialogNode.style.top, left: dialogNode.style.left, width: dialogNode.style.width, height: dialogNode.style.height }; maximizeButtonNode.title = 'Normal'; dialogNode.classList.remove('arasDialog-moved'); dialogNode.style.top = ''; dialogNode.style.left = ''; dialogNode.style.width = ''; dialogNode.style.height = ''; } else { maximizeButtonNode.title = 'Maximize'; dialogNode.style.top = this.restoreData.top; dialogNode.style.left = this.restoreData.left; dialogNode.style.width = this.restoreData.width; dialogNode.style.height = this.restoreData.height; if (this.restoreData.left) { // if dialog had nonempty 'left' style than it has been moved. Restore styles // in other case it would centered horizontally automatically without setting any styles dialogNode.classList.add('arasDialog-moved'); } } } }; var staticData = { show: function(type, args) { var dialog = new MaximazableDialog(type, args); dialog.show(); return dialog; } }; MaximazableDialog.prototype = Object.create(Dialog.prototype); Object.assign(MaximazableDialog.prototype, instanceData); Object.assign(MaximazableDialog, staticData); arasModules.MaximazableDialog = MaximazableDialog; })(window.ArasModules); /** ..\Modules\core\SessionSoap.js **/ (function($) { if (!$.soap) { new Error('Need module Soap.'); } $.nativSoap = $.soap; var globalConfig = {}; $.soap = function(data, options) { if (data === null) { Object.assign(globalConfig, options); } var config = {}; Object.assign(config, globalConfig, options); var promise = $.nativSoap(data, options); if (promise) { var result = promise.catch(function(request) { var topWnd; // SiteMinder Integration hack // We need to send a request to SMHelper.aspx to force a reinitialization of SiteMinder session. // If reinitialization failed then show a message that session is expired. // Get first 2000 characters from response for SiteMinder detection without performance degradation var substr = request.responseText.substring(0, 2000); if (/SMSESSION=LOGGEDOFF/i.test(request.getAllResponseHeaders()) || (//i.test(substr) && /NAME="SMPostPreserve"/i.test(substr))) { topWnd = TopWindowHelper.getMostTopWindowWithAras(window); var xmlhttpAuth = new XMLHttpRequest(); var urlAuth = topWnd.aras.getServerBaseURL() + 'SMHelper.aspx?salt=' + Date.now(); xmlhttpAuth.open('GET', urlAuth, false); xmlhttpAuth.send(null); if (xmlhttpAuth.status == 200 && xmlhttpAuth.responseText == 'SMSESSION is reinitialized.') { return $.soap(data, options); } else { (window.SOAP || topWnd.SOAP || window.opener.SOAP).showExitExcuse(topWnd.aras); topWnd.aras.setCommonPropertyValue('exitWithoutSavingInProgress', true); if (topWnd && topWnd.aras.browserHelper) { topWnd.aras.browserHelper.closeWindow(topWnd); } return; } } // SharePoint Integration hack // We need to support windows authorization on sharepoint server // If server side HttpRequest failed with code 401(Unauthorized) then add special header to response, // which tell to client, that it must redirect request to the page with integrated windows authorization // Other bug with XmlHttpRequest ActiveX: if in ASP.NET used Response.Redirect, then POST request transform to the GET // request and redirect it to new url if (request.getResponseHeader('IE.Bug.PostRequestMustRedirectedManualy') === '1') { options.url = config.url.replace('InnovatorServer.aspx', request.getResponseHeader('IE.Bug.RedirectToUrl')); options.headers = options.headers || {}; options.headers.IsRedirected = '1'; return $.nativSoap(data, options).catch(function(request) { // SharePoint Integration hack // Support WindowsAuthenticationPrefered type // When WinAuth failed, then we must to use dedicated user credentials. So send request to the page, which from we redirected before // And force dedicated user authentication by include new request header, which tell server side code then that winauth is failed if (request.status == 401) { options.url = config.url; return $.nativSoap(data, options); } }); } if (request.status === 200) { var obj = $.xmlToJson(request.responseXML.firstChild.firstChild.firstChild); topWnd = TopWindowHelper.getMostTopWindowWithAras(window); if (obj.faultcode === 'SOAP-ENV:Server.Authentication.SessionTimeout' && !sessionStorage.getItem('ArasSessionCheck') && !topWnd.aras.getCommonPropertyValue('ignoreSessionTimeoutInSoapSend')) { $.alertSoapError(request).then(function() { sessionStorage.removeItem('ArasSessionCheck'); (window.SOAP || topWnd.SOAP || window.opener.SOAP).checkIsSessionTimeOut(request.responseText).then(function(res) { if (res === true) { sessionStorage.removeItem('ArasSessionCheck'); } }); }); sessionStorage.setItem('ArasSessionCheck', true); } } return (config.async ? Promise : $.SyncPromise).reject(request); }); result.abort = promise.abort; return result; } }; $.alertSoapError = function(xhr) { var topWnd = TopWindowHelper.getMostTopWindowWithAras(window); var soapRes = (SOAPResults || topWnd.SOAPResults || window.opener.SOAPResults); var aras = (window.aras || topWnd.aras || window.opener.aras); var res = new SOAPResults(aras, xhr.responseText); return aras.AlertError(res); }; })(window.ArasModules || {}); /** ..\Modules\cryptohash\cryptoJS.js **/ /* CryptoJS v3.1.2 code.google.com/p/crypto-js (c) 2009-2013 by Jeff Mott. All rights reserved. code.google.com/p/crypto-js/wiki/License */ /** * CryptoJS core components. */ CryptoJS = (function (Math, undefined) { /** * CryptoJS namespace. */ var C = {}; /** * Library namespace. */ var C_lib = C.lib = {}; /** * Base object for prototypal inheritance. */ var Base = C_lib.Base = (function () { function F() {} return { /** * Creates a new object that inherits from this object. * * @param {Object} overrides Properties to copy into the new object. * * @return {Object} The new object. * * @static * * @example * * var MyType = CryptoJS.lib.Base.extend({ * field: 'value', * * method: function () { * } * }); */ extend: function (overrides) { // Spawn F.prototype = this; var subtype = new F(); // Augment if (overrides) { subtype.mixIn(overrides); } // Create default initializer if (!subtype.hasOwnProperty('init')) { subtype.init = function () { subtype.$super.init.apply(this, arguments); }; } // Initializer's prototype is the subtype object subtype.init.prototype = subtype; // Reference supertype subtype.$super = this; return subtype; }, /** * Extends this object and runs the init method. * Arguments to create() will be passed to init(). * * @return {Object} The new object. * * @static * * @example * * var instance = MyType.create(); */ create: function () { var instance = this.extend(); instance.init.apply(instance, arguments); return instance; }, /** * Initializes a newly created object. * Override this method to add some logic when your objects are created. * * @example * * var MyType = CryptoJS.lib.Base.extend({ * init: function () { * // ... * } * }); */ init: function () { }, /** * Copies properties into this object. * * @param {Object} properties The properties to mix in. * * @example * * MyType.mixIn({ * field: 'value' * }); */ mixIn: function (properties) { for (var propertyName in properties) { if (properties.hasOwnProperty(propertyName)) { this[propertyName] = properties[propertyName]; } } // IE won't copy toString using the loop above if (properties.hasOwnProperty('toString')) { this.toString = properties.toString; } }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = instance.clone(); */ clone: function () { return this.init.prototype.extend(this); } }; }()); /** * An array of 32-bit words. * * @property {Array} words The array of 32-bit words. * @property {number} sigBytes The number of significant bytes in this word array. */ var WordArray = C_lib.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of 32-bit words. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.lib.WordArray.create(); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 4; } }, /** * Converts this word array to a string. * * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex * * @return {string} The stringified word array. * * @example * * var string = wordArray + ''; * var string = wordArray.toString(); * var string = wordArray.toString(CryptoJS.enc.Utf8); */ toString: function (encoder) { return (encoder || Hex).stringify(this); }, /** * Concatenates a word array to this word array. * * @param {WordArray} wordArray The word array to append. * * @return {WordArray} This word array. * * @example * * wordArray1.concat(wordArray2); */ concat: function (wordArray) { // Shortcuts var thisWords = this.words; var thatWords = wordArray.words; var thisSigBytes = this.sigBytes; var thatSigBytes = wordArray.sigBytes; // Clamp excess bits this.clamp(); // Concat if (thisSigBytes % 4) { // Copy one byte at a time for (var i = 0; i < thatSigBytes; i++) { var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); } } else if (thatWords.length > 0xffff) { // Copy one word at a time for (var i = 0; i < thatSigBytes; i += 4) { thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; } } else { // Copy all words at once thisWords.push.apply(thisWords, thatWords); } this.sigBytes += thatSigBytes; // Chainable return this; }, /** * Removes insignificant bits. * * @example * * wordArray.clamp(); */ clamp: function () { // Shortcuts var words = this.words; var sigBytes = this.sigBytes; // Clamp words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); words.length = Math.ceil(sigBytes / 4); }, /** * Creates a copy of this word array. * * @return {WordArray} The clone. * * @example * * var clone = wordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); clone.words = this.words.slice(0); return clone; }, /** * Creates a word array filled with random bytes. * * @param {number} nBytes The number of random bytes to generate. * * @return {WordArray} The random word array. * * @static * * @example * * var wordArray = CryptoJS.lib.WordArray.random(16); */ random: function (nBytes) { var words = []; for (var i = 0; i < nBytes; i += 4) { words.push((Math.random() * 0x100000000) | 0); } return new WordArray.init(words, nBytes); } }); /** * Encoder namespace. */ var C_enc = C.enc = {}; /** * Hex encoding strategy. */ var Hex = C_enc.Hex = { /** * Converts a word array to a hex string. * * @param {WordArray} wordArray The word array. * * @return {string} The hex string. * * @static * * @example * * var hexString = CryptoJS.enc.Hex.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var hexChars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; hexChars.push((bite >>> 4).toString(16)); hexChars.push((bite & 0x0f).toString(16)); } return hexChars.join(''); }, /** * Converts a hex string to a word array. * * @param {string} hexStr The hex string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Hex.parse(hexString); */ parse: function (hexStr) { // Shortcut var hexStrLength = hexStr.length; // Convert var words = []; for (var i = 0; i < hexStrLength; i += 2) { words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); } return new WordArray.init(words, hexStrLength / 2); } }; /** * Latin1 encoding strategy. */ var Latin1 = C_enc.Latin1 = { /** * Converts a word array to a Latin1 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Latin1 string. * * @static * * @example * * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var latin1Chars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; latin1Chars.push(String.fromCharCode(bite)); } return latin1Chars.join(''); }, /** * Converts a Latin1 string to a word array. * * @param {string} latin1Str The Latin1 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); */ parse: function (latin1Str) { // Shortcut var latin1StrLength = latin1Str.length; // Convert var words = []; for (var i = 0; i < latin1StrLength; i++) { words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); } return new WordArray.init(words, latin1StrLength); } }; /** * UTF-8 encoding strategy. */ var Utf8 = C_enc.Utf8 = { /** * Converts a word array to a UTF-8 string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-8 string. * * @static * * @example * * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); */ stringify: function (wordArray) { try { return decodeURIComponent(escape(Latin1.stringify(wordArray))); } catch (e) { throw new Error('Malformed UTF-8 data'); } }, /** * Converts a UTF-8 string to a word array. * * @param {string} utf8Str The UTF-8 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); */ parse: function (utf8Str) { return Latin1.parse(unescape(encodeURIComponent(utf8Str))); } }; /** * Abstract buffered block algorithm template. * * The property blockSize must be implemented in a concrete subtype. * * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 */ var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ /** * Resets this block algorithm's data buffer to its initial state. * * @example * * bufferedBlockAlgorithm.reset(); */ reset: function () { // Initial values this._data = new WordArray.init(); this._nDataBytes = 0; }, /** * Adds new data to this block algorithm's buffer. * * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. * * @example * * bufferedBlockAlgorithm._append('data'); * bufferedBlockAlgorithm._append(wordArray); */ _append: function (data) { // Convert string to WordArray, else assume WordArray already if (typeof data == 'string') { data = Utf8.parse(data); } // Append this._data.concat(data); this._nDataBytes += data.sigBytes; }, /** * Processes available data blocks. * * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. * * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. * * @return {WordArray} The processed data. * * @example * * var processedData = bufferedBlockAlgorithm._process(); * var processedData = bufferedBlockAlgorithm._process(!!'flush'); */ _process: function (doFlush) { // Shortcuts var data = this._data; var dataWords = data.words; var dataSigBytes = data.sigBytes; var blockSize = this.blockSize; var blockSizeBytes = blockSize * 4; // Count blocks ready var nBlocksReady = dataSigBytes / blockSizeBytes; if (doFlush) { // Round up to include partial blocks nBlocksReady = Math.ceil(nBlocksReady); } else { // Round down to include only full blocks, // less the number of blocks that must remain in the buffer nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); } // Count words ready var nWordsReady = nBlocksReady * blockSize; // Count bytes ready var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); // Process blocks if (nWordsReady) { for (var offset = 0; offset < nWordsReady; offset += blockSize) { // Perform concrete-algorithm logic this._doProcessBlock(dataWords, offset); } // Remove processed words var processedWords = dataWords.splice(0, nWordsReady); data.sigBytes -= nBytesReady; } // Return processed words return new WordArray.init(processedWords, nBytesReady); }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = bufferedBlockAlgorithm.clone(); */ clone: function () { var clone = Base.clone.call(this); clone._data = this._data.clone(); return clone; }, _minBufferSize: 0 }); /** * Abstract hasher template. * * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) */ var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ /** * Configuration options. */ cfg: Base.extend(), /** * Initializes a newly created hasher. * * @param {Object} cfg (Optional) The configuration options to use for this hash computation. * * @example * * var hasher = CryptoJS.algo.SHA256.create(); */ init: function (cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Set initial values this.reset(); }, /** * Resets this hasher to its initial state. * * @example * * hasher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-hasher logic this._doReset(); }, /** * Updates this hasher with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {Hasher} This hasher. * * @example * * hasher.update('message'); * hasher.update(wordArray); */ update: function (messageUpdate) { // Append this._append(messageUpdate); // Update the hash this._process(); // Chainable return this; }, /** * Finalizes the hash computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The hash. * * @example * * var hash = hasher.finalize(); * var hash = hasher.finalize('message'); * var hash = hasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Final message update if (messageUpdate) { this._append(messageUpdate); } // Perform concrete-hasher logic var hash = this._doFinalize(); return hash; }, blockSize: 512/32, /** * Creates a shortcut function to a hasher's object interface. * * @param {Hasher} hasher The hasher to create a helper for. * * @return {Function} The shortcut function. * * @static * * @example * * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); */ _createHelper: function (hasher) { return function (message, cfg) { return new hasher.init(cfg).finalize(message); }; }, /** * Creates a shortcut function to the HMAC's object interface. * * @param {Hasher} hasher The hasher to use in this HMAC helper. * * @return {Function} The shortcut function. * * @static * * @example * * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); */ _createHmacHelper: function (hasher) { return function (message, key) { return new C_algo.HMAC.init(hasher, key).finalize(message); }; } }); /** * Algorithm namespace. */ var C_algo = C.algo = {}; return C; }(Math)); /** ..\Modules\cryptohash\md5.js **/ /* CryptoJS v3.1.2 code.google.com/p/crypto-js (c) 2009-2013 by Jeff Mott. All rights reserved. code.google.com/p/crypto-js/wiki/License */ (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Constants table var T = []; // Compute constants (function () { for (var i = 0; i < 64; i++) { T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0; } }()); /** * MD5 hash algorithm. */ var MD5 = C_algo.MD5 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init([ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476 ]); }, _doProcessBlock: function (M, offset) { // Swap endian for (var i = 0; i < 16; i++) { // Shortcuts var offset_i = offset + i; var M_offset_i = M[offset_i]; M[offset_i] = ( (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) ); } // Shortcuts var H = this._hash.words; var M_offset_0 = M[offset + 0]; var M_offset_1 = M[offset + 1]; var M_offset_2 = M[offset + 2]; var M_offset_3 = M[offset + 3]; var M_offset_4 = M[offset + 4]; var M_offset_5 = M[offset + 5]; var M_offset_6 = M[offset + 6]; var M_offset_7 = M[offset + 7]; var M_offset_8 = M[offset + 8]; var M_offset_9 = M[offset + 9]; var M_offset_10 = M[offset + 10]; var M_offset_11 = M[offset + 11]; var M_offset_12 = M[offset + 12]; var M_offset_13 = M[offset + 13]; var M_offset_14 = M[offset + 14]; var M_offset_15 = M[offset + 15]; // Working varialbes var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; // Computation a = FF(a, b, c, d, M_offset_0, 7, T[0]); d = FF(d, a, b, c, M_offset_1, 12, T[1]); c = FF(c, d, a, b, M_offset_2, 17, T[2]); b = FF(b, c, d, a, M_offset_3, 22, T[3]); a = FF(a, b, c, d, M_offset_4, 7, T[4]); d = FF(d, a, b, c, M_offset_5, 12, T[5]); c = FF(c, d, a, b, M_offset_6, 17, T[6]); b = FF(b, c, d, a, M_offset_7, 22, T[7]); a = FF(a, b, c, d, M_offset_8, 7, T[8]); d = FF(d, a, b, c, M_offset_9, 12, T[9]); c = FF(c, d, a, b, M_offset_10, 17, T[10]); b = FF(b, c, d, a, M_offset_11, 22, T[11]); a = FF(a, b, c, d, M_offset_12, 7, T[12]); d = FF(d, a, b, c, M_offset_13, 12, T[13]); c = FF(c, d, a, b, M_offset_14, 17, T[14]); b = FF(b, c, d, a, M_offset_15, 22, T[15]); a = GG(a, b, c, d, M_offset_1, 5, T[16]); d = GG(d, a, b, c, M_offset_6, 9, T[17]); c = GG(c, d, a, b, M_offset_11, 14, T[18]); b = GG(b, c, d, a, M_offset_0, 20, T[19]); a = GG(a, b, c, d, M_offset_5, 5, T[20]); d = GG(d, a, b, c, M_offset_10, 9, T[21]); c = GG(c, d, a, b, M_offset_15, 14, T[22]); b = GG(b, c, d, a, M_offset_4, 20, T[23]); a = GG(a, b, c, d, M_offset_9, 5, T[24]); d = GG(d, a, b, c, M_offset_14, 9, T[25]); c = GG(c, d, a, b, M_offset_3, 14, T[26]); b = GG(b, c, d, a, M_offset_8, 20, T[27]); a = GG(a, b, c, d, M_offset_13, 5, T[28]); d = GG(d, a, b, c, M_offset_2, 9, T[29]); c = GG(c, d, a, b, M_offset_7, 14, T[30]); b = GG(b, c, d, a, M_offset_12, 20, T[31]); a = HH(a, b, c, d, M_offset_5, 4, T[32]); d = HH(d, a, b, c, M_offset_8, 11, T[33]); c = HH(c, d, a, b, M_offset_11, 16, T[34]); b = HH(b, c, d, a, M_offset_14, 23, T[35]); a = HH(a, b, c, d, M_offset_1, 4, T[36]); d = HH(d, a, b, c, M_offset_4, 11, T[37]); c = HH(c, d, a, b, M_offset_7, 16, T[38]); b = HH(b, c, d, a, M_offset_10, 23, T[39]); a = HH(a, b, c, d, M_offset_13, 4, T[40]); d = HH(d, a, b, c, M_offset_0, 11, T[41]); c = HH(c, d, a, b, M_offset_3, 16, T[42]); b = HH(b, c, d, a, M_offset_6, 23, T[43]); a = HH(a, b, c, d, M_offset_9, 4, T[44]); d = HH(d, a, b, c, M_offset_12, 11, T[45]); c = HH(c, d, a, b, M_offset_15, 16, T[46]); b = HH(b, c, d, a, M_offset_2, 23, T[47]); a = II(a, b, c, d, M_offset_0, 6, T[48]); d = II(d, a, b, c, M_offset_7, 10, T[49]); c = II(c, d, a, b, M_offset_14, 15, T[50]); b = II(b, c, d, a, M_offset_5, 21, T[51]); a = II(a, b, c, d, M_offset_12, 6, T[52]); d = II(d, a, b, c, M_offset_3, 10, T[53]); c = II(c, d, a, b, M_offset_10, 15, T[54]); b = II(b, c, d, a, M_offset_1, 21, T[55]); a = II(a, b, c, d, M_offset_8, 6, T[56]); d = II(d, a, b, c, M_offset_15, 10, T[57]); c = II(c, d, a, b, M_offset_6, 15, T[58]); b = II(b, c, d, a, M_offset_13, 21, T[59]); a = II(a, b, c, d, M_offset_4, 6, T[60]); d = II(d, a, b, c, M_offset_11, 10, T[61]); c = II(c, d, a, b, M_offset_2, 15, T[62]); b = II(b, c, d, a, M_offset_9, 21, T[63]); // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000); var nBitsTotalL = nBitsTotal; dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = ( (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) | (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00) ); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) | (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00) ); data.sigBytes = (dataWords.length + 1) * 4; // Hash final blocks this._process(); // Shortcuts var hash = this._hash; var H = hash.words; // Swap endian for (var i = 0; i < 4; i++) { // Shortcut var H_i = H[i]; H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); } // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); function FF(a, b, c, d, x, s, t) { var n = a + ((b & c) | (~b & d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function GG(a, b, c, d, x, s, t) { var n = a + ((b & d) | (c & ~d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function HH(a, b, c, d, x, s, t) { var n = a + (b ^ c ^ d) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function II(a, b, c, d, x, s, t) { var n = a + (c ^ (b | ~d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.MD5('message'); * var hash = CryptoJS.MD5(wordArray); */ C.MD5 = Hasher._createHelper(MD5); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacMD5(message, key); */ C.HmacMD5 = Hasher._createHmacHelper(MD5); }(Math)); /** ..\Modules\cryptohash\cryptohash.js **/ (function(externalParent) { var cryptohash = {}; function hex(buffer) { var hexCodes = []; var view = new DataView(buffer); for (var i = 0; i < view.byteLength; i += 4) { // Using getUint32 reduces the number of iterations needed (we process 4 bytes each time) var value = view.getUint32(i); // toString(16) will give the hex representation of the number without padding var stringValue = value.toString(16); // We use concatenation and slice for padding var padding = '00000000'; var paddedValue = (padding + stringValue).slice(-padding.length); hexCodes.push(paddedValue); } // Join all the hex strings into one return hexCodes.join(''); } function stringToArrayBuffer(str) { return new Uint8Array(str.split('').map(function(sym) { return sym.charCodeAt(); })); } cryptohash.SHA256 = function(str) { var buffer; if (typeof window.crypto !== 'undefined' && crypto.subtle && (!aras.Browser.isCh() || window.protocol === 'https:')) { if (window.TextEncoder) { buffer = new TextEncoder('utf-8').encode(str); } else { buffer = stringToArrayBuffer(str); } return crypto.subtle.digest('SHA-256', buffer).then(function(hash) { return hex(hash); }); } else if (typeof window.msCrypto !== 'undefined') { buffer = stringToArrayBuffer(str); var sha256 = msCrypto.subtle.digest('SHA-256', buffer); return new Promise(function(resolve, reject) { sha256.oncomplete = function(event) { resolve(hex(event.target.result)); }; }); } else { return Promise.resolve(CryptoJS.SHA256(str).toString(CryptoJS.enc.Hex)); } }; cryptohash.MD5 = function(message, config) { return CryptoJS.MD5(message, config); }; cryptohash.xxHash = function() { throw new Exception('Cryptohash.xxHash not implemented'); }; externalParent.cryptohash = cryptohash; window.ArasModules = window.ArasModules || externalParent; })(window.ArasModules || {}); /** ..\Modules\core\XmlToJson.js **/ (function(externalParent) { var xmlToJsonModule = { 'xmlToJson': function(data) { var xml = null; if (typeof (data) == 'string') { xml = xmlToJsonModule.parseStringToXml(data); } else { xml = data; } var parsedXml = xmlToJsonModule.parseXml(xml); return parsedXml; }, 'parseStringToXml': function(data) { var parser = new DOMParser(); var xml = parser.parseFromString(data, 'text/xml'); return xml; }, 'parseXml': function(xml) { var node = {}; var isComplex = false; var nodeValue = xml.nodeValue || ''; for (var i = 0; i < xml.childNodes.length; i++) { var childNode = xml.childNodes[i]; var childNodeValue = childNode.nodeValue; /* 3 for Text nodes, 4 for CData nodes, 1 for common nodes*/ if (childNode.nodeType === 3 || childNode.nodeType === 4) { nodeValue += childNodeValue; } else if (childNode.nodeType === 1) { isComplex = true; if (node[childNode.nodeName] && Array.isArray(node[childNode.nodeName])) { node[childNode.nodeName].push(xmlToJsonModule.parseXml(childNode)); } else if (node[childNode.nodeName] && !Array.isArray(node[childNode.nodeName])) { var temp = node[childNode.nodeName]; node[childNode.nodeName] = [temp, xmlToJsonModule.parseXml(childNode)]; } else { node[childNode.nodeName] = xmlToJsonModule.parseXml(childNode); } } } if (xml.attributes && xml.attributes.length > 0) { isComplex = true; var nodeAttrsObj = {}; for (var j = 0; j < xml.attributes.length; j++) { var attr = xml.attributes.item(j); var attrName = attr.name; var attrValue = attr.value; nodeAttrsObj[attrName] = attrValue; } node['@attrs'] = nodeAttrsObj; if (nodeValue) { node['@value'] = nodeValue; } } return isComplex ? node : nodeValue; } }; var jsonToXmlModule = { 'sanitizer': { 'chars': { '&': '&', '<': '<', '>': '>', '(': '(', ')': ')', '#': '#', '"': '"', '\'': ''' }, 'escapeRegExp': function(string) { return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1'); }, 'sanitize': function(value) { if (typeof value !== 'string') { return value; } Object.keys(this.chars).forEach(function(key) { value = value.replace(new RegExp(jsonToXmlModule.sanitizer.escapeRegExp(key), 'g'), jsonToXmlModule.sanitizer.chars[key]); }); return value; } }, 'buildStringsHelper': { 'openTag': function(key) { return '<' + key; }, 'closeTag': function(key) { return ''; }, 'addAttr': function(key, val) { return ' ' + key + '="' + jsonToXmlModule.sanitizer.sanitize(val) + '"'; }, 'addAttrs': function(obj) { var attrKeys = Object.keys(obj); var tempStr = ''; for (var i = 0; i < attrKeys.length; i++) { tempStr += this.addAttr(attrKeys[i], obj[attrKeys[i]]); } return tempStr; }, 'addTextContent': function(text) { return '>' + text; } }, 'compileNode': function(nodeName, attrs, content) { var tempStr = ''; tempStr += this.buildStringsHelper.openTag(nodeName); if (attrs) { tempStr += this.buildStringsHelper.addAttrs(attrs); } if (typeof content == 'string') { tempStr += this.buildStringsHelper.addTextContent(content); } tempStr += this.buildStringsHelper.closeTag(nodeName); return tempStr; }, 'parseJson': function(obj) { var keys = Object.keys(obj); var tempStr = ''; for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = obj[key]; var isArray = Array.isArray(value); var type = typeof(value); if (key != '@attrs' && key != '@value' && key.indexOf('@') !== 0) { if (type == 'string' || type == 'number' || type == 'boolean') { tempStr += this.compileNode(key, null, this.sanitizer.sanitize(value)); } else if (isArray) { for (var j = 0; j < value.length; j++) { var tempNode = {}; tempNode[key] = value[j]; tempStr += this.parseJson(tempNode); } } else { tempStr += this.compileNode(key, getProperties(value), value['@value'] ? this.sanitizer.sanitize(value['@value']) : this.parseJson(value)); } } } function getProperties(obj) { var attrs = obj['@attrs'] || {}; var attrKeys = Object.keys(obj); for (var i = 0; i < attrKeys.length; i++) { if (attrKeys[i] != '@attrs' && attrKeys[i] != '@value' && attrKeys[i].indexOf('@') === 0) { attrs[attrKeys[i].substring(1)] = obj[attrKeys[i]]; } } return attrs; } return tempStr; }, 'jsonToXml': function(data) { var jsonObj = null; if (typeof(data) == 'string') { jsonObj = JSON.parse(data); } else { jsonObj = data; } return jsonToXmlModule.parseJson(jsonObj); } }; var jsonXmlConverter = { 'xmlToJson': xmlToJsonModule.xmlToJson, 'jsonToXml': jsonToXmlModule.jsonToXml }; externalParent = Object.assign(externalParent, jsonXmlConverter); window.ArasModules = window.ArasModules || externalParent; })(window.ArasModules || {}); /** ..\BrowserCode\common\javascript\XmlHttpRequestManagerCommon.js **/ function XmlRequestImplementation() { this.xhr = new XMLHttpRequest(); this.headers = {}; } XmlRequestImplementation.prototype.open = function(method, url, isAsync) { isAsync = (isAsync === 1 || isAsync === true); this.xhr.open(method, url, isAsync); }; Object.defineProperty(XmlRequestImplementation.prototype, 'onreadystatechange', { set: function(value) { this.xhr.onreadystatechange = value; } }); XmlRequestImplementation.prototype.setRequestHeader = function(name, value) { this.headers[name] = value; }; XmlRequestImplementation.prototype.send = function(body) { for (var key in this.headers) { if (this.headers.hasOwnProperty(key)) { this.xhr.setRequestHeader(key, this.headers[key]); } } //this line is required for IE 10. try { if (navigator.userAgent.indexOf('MSIE') >= 0 || navigator.userAgent.indexOf('Trident') >= 0) { this.xhr.responseType = 'msxml-document'; } } catch (e) { } this.xhr.send(body); }; XmlRequestImplementation.prototype.getResponseHeader = function(header) { return this.xhr.getResponseHeader(header); }; XmlRequestImplementation.prototype.getAllResponseHeaders = function() { return this.xhr.getAllResponseHeaders(); }; Object.defineProperty(XmlRequestImplementation.prototype, 'readyState', { get: function() { return this.xhr.readyState; } }); Object.defineProperty(XmlRequestImplementation.prototype, 'status', { get: function() { return this.xhr.status; } }); Object.defineProperty(XmlRequestImplementation.prototype, 'responseText', { get: function() { return this.xhr.responseText; } }); Object.defineProperty(XmlRequestImplementation.prototype, 'responseXML', { get: function() { return this.xhr.responseXML; } }); function XmlHttpRequestManager() { } XmlHttpRequestManager.prototype.CreateRequest = function() { return new XmlRequestImplementation(); }; /** ..\BrowserCode\common\javascript\XmlDocument.js **/ function XmlDocument() { var xmlDoc; if (window.ActiveXObject !== undefined) { xmlDoc = new ActiveXObject('Msxml2.FreeThreadedDOMDocument.6.0'); xmlDoc.setProperty('AllowXsltScript', true); xmlDoc.async = false; xmlDoc.preserveWhiteSpace = true; xmlDoc.validateOnParse = false; } else { xmlDoc = document.implementation.createDocument('', '', null); xmlDoc.async = false; xmlDoc.preserveWhiteSpace = true; } return xmlDoc; } /** ..\BrowserCode\common\javascript\XmlDocumentCommon.js **/ Document.prototype.loadXML = function XmlDocumentLoadXML(xmlString) { if (!xmlString || typeof (xmlString) !== 'string') { return false; } xmlString = xmlString.replace(/xmlns:i18n="http:\/\/www.w3.org\/XML\/1998\/namespace"/g, 'xmlns:i18n="http://www.aras.com/I18N"'); var parser = new DOMParser(); var doc = parser.parseFromString(xmlString, 'text/xml'); if (!this.documentElement) { this.appendChild(this.createElement('oldTeg')); } this.replaceChild(doc.documentElement, this.documentElement); return (this.parseError.errorCode === 0); }; Document.prototype.loadUrl = function XmlDocumentLoadUrl(filename) { if (!filename || typeof (filename) !== 'string') { return; } if (window.ActiveXObject) { xhttp = new ActiveXObject('Msxml2.XMLHTTP'); } else { xhttp = new XMLHttpRequest(); } xhttp.open('GET', filename, false); try { xhttp.responseType = 'msxml-document'; } catch (err) { } // Helping IE11 xhttp.send(''); this.loadXML(xhttp.response); }; Document.prototype.selectSingleNode = function XmlDocumentSelectSingleNode(xPath) { var xpe = new XPathEvaluator(); var ownerDoc = this.ownerDocument == null ? this.documentElement : this.ownerDocument.documentElement; var nsResolver = xpe.createNSResolver(ownerDoc == null ? this : ownerDoc); return xpe.evaluate(xPath, this, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; }; Element.prototype.selectSingleNode = Document.prototype.selectSingleNode; Document.prototype.selectNodes = function XmlDocumentSelectNodes(xPath) { var xpe = new XPathEvaluator(); var ownerDoc = this.ownerDocument == null ? this.documentElement : this.ownerDocument.documentElement; var nsResolver = xpe.createNSResolver(ownerDoc == null ? this : ownerDoc); var result = xpe.evaluate(xPath, this, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); var res = null; if (result) { res = []; for (var i = 0; i < result.snapshotLength; i++) { res.push(result.snapshotItem(i)); } } return res; }; Element.prototype.selectNodes = Document.prototype.selectNodes; Element.prototype.transformNode = function XmlElementTransformNode(xmlDoc) { var outputNode = xmlDoc.selectSingleNode('./xsl:stylesheet/xsl:output'); var isHtml = (outputNode && outputNode.getAttribute('method') === 'html'); var sourceDoc = document.implementation.createDocument('', '', null); var node = sourceDoc.importNode(this, true); sourceDoc.appendChild(node); var processor = new XSLTProcessor(); processor.importStylesheet(xmlDoc); var resultDoc = processor.transformToDocument(sourceDoc); //Microsoft Edge might not properly pefrom transfomration of XML document and we will have 'null' after transfomration. //In this case we should return an error message instead of 'null'. The error message corresponds to Chrome error message if (!resultDoc) { return '

This page contains the following errors:

' + '
Document parsing error
'; } return isHtml ? resultDoc.documentElement.outerHTML : resultDoc.xml; }; Document.prototype.transformNode = function XmlDocumentTransformNode(xmlDoc) { //In Microsoft Edge when xmlDoc created in other window it's not instance of XMLDocument //So we need to create new instance to avoid 'null' after transformToDocument if (!(xmlDoc instanceof XMLDocument)) { var oldXml = xmlDoc.xml; xmlDoc = new XmlDocument(); xmlDoc.loadXML(oldXml); } var processor = new XSLTProcessor(); processor.importStylesheet(xmlDoc); var outputNode = xmlDoc.selectSingleNode('./xsl:stylesheet/xsl:output'); var isHtml = (outputNode && outputNode.getAttribute('method') === 'html'); var resultDoc = processor.transformToDocument(this); //Microsoft Edge might not properly pefrom transfomration of XML document and we will have 'null' after transfomration. //In this case we should return an error message instead of 'null'. The error message corresponds to Chrome error message if (!resultDoc) { return '

This page contains the following errors:

' + '
Document parsing error
'; } return isHtml ? resultDoc.documentElement.outerHTML : resultDoc.xml; }; Document.prototype.createNode = function XmlDocumentTransformNode(nodeType, name, namespaceUrl) { var newNode = this.createElementNS(namespaceUrl, name); return newNode; }; if (Document.prototype.__defineGetter__) { Document.prototype.__defineGetter__('text', function() { return this.textContent; }); Document.prototype.__defineSetter__('text', function(value) { this.textContent = value; }); Element.prototype.__defineGetter__('text', function() { return this.textContent; }); Element.prototype.__defineSetter__('text', function(value) { this.textContent = value; }); Text.prototype.__defineGetter__('text', function() { return this.textContent; }); Attr.prototype.__defineGetter__('text', function(value) { return this.textContent; }); Document.prototype.__defineGetter__('xml', function() { return (new XMLSerializer()).serializeToString(this); }); Element.prototype.__defineGetter__('xml', function() { return (new XMLSerializer()).serializeToString(this); }); Document.prototype.__defineGetter__('parseError', function() { if (!this.documentElement) { return {errorCode: 0}; } //for Chrome browser that return html instead parsererror xml block var node = this.documentElement; if (node.nodeName === 'html' && node.firstChild && node.firstChild.firstChild) { node = node.firstChild.firstChild; if (node.nodeName === 'parsererror') { return { errorCode: 1, srcText: '', reason: node.childNodes[1].textContent }; } } if (this.documentElement.nodeName == 'parsererror') { return { errorCode: 1, srcText: '', reason: this.documentElement.childNodes[0].nodeValue }; } return {errorCode: 0}; }); } XMLDocument.prototype.load = function(docUrl) { var xmlhttp = new XmlHttpRequestManager().CreateRequest(); xmlhttp.open('GET', docUrl, false); xmlhttp.send(null); this.loadXML(xmlhttp.responseText); }; /** client_cache.js **/ // © Copyright by Aras Corporation, 2004-2009. //////////////+++++++++ CacheResponse +++++++++////////////////////////// function CacheResponse(success, msg, item) { if (success === undefined) { success = false; } if (msg === undefined) { msg = ''; } this.success = success; this.message = msg; this.item = item; } //////////////--------- CacheResponse ---------////////////////////////// //////////////+++++++++ ClientCache +++++++++////////////////////////// function ClientCache(arasObj) { this.arasObj = arasObj; this.dom = Aras.prototype.createXMLDocument(); this.dom.loadXML(''); } ClientCache.prototype.makeResponse = function ClientCacheMakeResponse(success, msg, item) { return (new CacheResponse(success, msg, item)); }; ClientCache.prototype.addItem = function ClientCacheAddItem(item) { if (!item) { return; } this.dom.selectSingleNode('/Innovator/Items').appendChild(item); }; ClientCache.prototype.updateItem = function ClientCacheUpdateItem(item, isMergeItems) { var itemID = item.getAttribute('id'); var prevItem = this.getItem(itemID); if (prevItem) { if (isMergeItems) { this.arasObj.mergeItem(prevItem, item); } else { prevItem.parentNode.replaceChild(item.cloneNode(true), prevItem); } } else { this.addItem(item); } }; ClientCache.prototype.updateItemEx = function ClientCacheUpdateItemEx(oldItm, newItm) { var oldID = oldItm.getAttribute('id'); var newID = newItm.getAttribute('id'); var prevItem = this.dom.selectSingleNode('/Innovator/Items/Item[@id="' + oldID + '"]'); if (prevItem) { prevItem.parentNode.replaceChild(newItm.cloneNode(true), prevItem); } if (!prevItem && (!oldItm || !oldItm.parentNode)) { this.addItem(newItm); } //BUGBUG: Situation when versionable item is in root of cache is not handled. //TODO: Remove update of cache from RefreshWindows if (oldItm.parentNode) { if (oldItm.parentNode.nodeName == 'related_id' && !this.arasObj.isTempEx(oldItm)) { var relNd = oldItm.parentNode.parentNode; var relNdBehaviour = this.arasObj.getItemProperty(relNd, 'behavior'); if (relNdBehaviour && relNdBehaviour != 'float' && relNdBehaviour != 'hard_float') { var strBody = ''; var res = this.arasObj.soapSend('ApplyItem', strBody); if (res.getFaultCode().toString() === '0') { var tmpItm = res.results.selectSingleNode(this.arasObj.XPathResult('/Item/related_id/Item')); if (tmpItm) { newItm = tmpItm; } } } } var newItmCloned = newItm.cloneNode(true); oldItm.parentNode.replaceChild(newItmCloned, oldItm); } var oldItms = oldItm.selectNodes('.//Item[@isTemp="1" or @isDirty="1"]'); for (var i = 0; i < oldItms.length; i++) { var oldItmID = oldItms[i].getAttribute('id'); if (oldItmID == newID) { continue; } var newOldItm = newItm.selectSingleNode('.//Item[@id="' + oldItmID + '"]'); //both updateItem and deleteItem affect only root level of cache. if (newOldItm) { this.updateItem(newOldItm); } else { this.deleteItem(oldItmID); } } //update configurations in cache if (oldID == newID) {//to not touch behaviours of corresponding properties var nodesInsideConfigurations = this.dom.selectNodes('/Innovator/Items/Item/*//Item[ancestor::*[local-name()!="related_id"] and @id="' + oldID + '"]'); for (i = 0, L = nodesInsideConfigurations.length; i < L; i++) { var nd = nodesInsideConfigurations[i]; nd.parentNode.replaceChild(newItm.cloneNode(true), nd); } } }; ClientCache.prototype.deleteItem = function ClientCacheDeleteItem(itemID) { var prevItem = this.getItem(itemID); if (prevItem) { return prevItem.parentNode.removeChild(prevItem); } return null; }; ClientCache.prototype.deleteItems = function ClientCacheDeleteItems(xpath) { var nodes = this.getItemsByXPath(xpath); for (var i = 0; i < nodes.length; i++) { var parentNode = nodes[i].parentNode; if (parentNode) { parentNode.removeChild(nodes[i]); } } }; ClientCache.prototype.getItem = function ClientCacheGetItem(itemID) { var item = this.dom.selectSingleNode('/Innovator/Items/Item[@id="' + itemID + '"]'); return item; }; ClientCache.prototype.getItemByXPath = function ClientCacheGetItemByXPath(xpath) { return this.dom.selectSingleNode(xpath); }; ClientCache.prototype.getItemsByXPath = function ClientCacheGetItemsByXPath(xpath) { return this.dom.selectNodes(xpath); }; ClientCache.prototype.hasItem = function ClientCacheHasItem(itemID) { return (this.getItem(itemID) !== null); }; //////////////--------- ClientCache ---------////////////////////////// /** qry_object.js **/ // © Copyright by Aras Corporation, 2004-2007. function QryItem(arasObj, itemTypeName) { this.arasObj = arasObj; this.dom = arasObj.createXMLDocument(); if (itemTypeName) { this.itemTypeName = itemTypeName; } this.initQry(this.itemTypeName); } QryItem.prototype.dom = null; QryItem.prototype.item = null; QryItem.prototype.itemTypeName = ''; QryItem.prototype.response = null; QryItem.prototype.result = null; /* */ QryItem.prototype.initQry = function QryItemInitQry(itemTypeName, preservePrevResults) { if (preservePrevResults === undefined) { preservePrevResults = false; } this.itemTypeName = itemTypeName; this.dom.loadXML(''); this.item = this.dom.documentElement; if (!preservePrevResults) { var topWnd = this.arasObj.getMostTopWindowWithAras(window); this.response = new topWnd.SOAPResults(this.arasObj, SoapConstants.EnvelopeBodyStart + '' + SoapConstants.EnvelopeBodyEnd); this.result = this.response.getResult(); } }; QryItem.prototype.setItemType = function QryItemSetItemType(itemTypeName) { if (this.itemTypeName == itemTypeName) { return; } this.initQry(itemTypeName, false); }; /* */ QryItem.prototype.setCriteria = function QryItemSetCriteria(propertyName, value, condition) { if (condition === undefined) { condition = 'eq'; } var criteria = this.item.selectSingleNode(propertyName); if (!criteria) { criteria = this.dom.createElement(propertyName); this.item.appendChild(criteria); } criteria.text = value; criteria.setAttribute('condition', condition); }; QryItem.prototype.setCriteriaForMlString = function QryItemSetCriteriaForMlString(criteriaNode, condition) { if (condition === undefined) { condition = 'eq'; } if (!criteriaNode) { return; } var propertyName = criteriaNode.nodeName; var prefix = criteriaNode.prefix; var value = criteriaNode.text; var language = criteriaNode.getAttribute('xml:lang'); var xpath = propertyName; if (prefix == 'i18n') { xpath = '//*[local-name() = \'' + propertyName + '\' and namespace-uri()=\'' + this.arasObj.translationXMLNsURI + '\' and @xml:lang=\'' + language + '\']'; } var criteriaNd = this.item.selectSingleNode(xpath); if (!criteriaNd) { criteriaNd = this.dom.documentElement.appendChild(criteriaNode.cloneNode(false)); } criteriaNd.text = value; criteriaNd.setAttribute('condition', condition); }; QryItem.prototype.setPropertyCriteria = function QryItemSetPropertyCriteria(propertyName, critName, value, condition, typeOfItem) { if (condition === undefined) { condition = 'eq'; } var criteria = this.item.selectSingleNode(propertyName); if (!criteria) { criteria = this.dom.createElement(propertyName); this.item.appendChild(criteria); } var itm = criteria.selectSingleNode('Item'); if (!itm) { itm = this.dom.createElement('Item'); criteria.text = ''; criteria.appendChild(itm); } if (typeOfItem) { itm.setAttribute('type', typeOfItem); } itm.setAttribute('action', 'get'); criteria = itm.selectSingleNode(critName); if (!criteria) { criteria = this.dom.createElement(critName); itm.appendChild(criteria); } criteria.text = value; criteria.setAttribute('condition', condition); }; QryItem.prototype.setRelationshipCriteria = function QryItemSetRelationshipCriteria(relType, propertyName, value, condition) { if (condition === undefined) { condition = 'eq'; } var rels = this.item.selectSingleNode('Relationships'); if (!rels) { rels = this.dom.createElement('Relationships'); this.item.appendChild(rels); } var itm = rels.selectSingleNode('Item[@type="' + relType + '"]'); if (!itm) { itm = this.dom.createElement('Item'); rels.appendChild(itm); itm.setAttribute('type', relType); itm.setAttribute('action', 'get'); } var criteria = itm.selectSingleNode(propertyName); if (!criteria) { criteria = this.dom.createElement(propertyName); itm.appendChild(criteria); } criteria.text = value; criteria.setAttribute('condition', condition); }; QryItem.prototype.setRelationshipPropertyCriteria = function QryItemSetRelationshipPropertyCriteria(relType, propertyName, critName, value, condition) { if (condition === undefined) { condition = 'eq'; } var rels = this.item.selectSingleNode('Relationships'); if (!rels) { rels = this.dom.createElement('Relationships'); this.item.appendChild(rels); } var itm = rels.selectSingleNode('Item[@type="' + relType + '"]'); if (!itm) { itm = this.dom.createElement('Item'); rels.appendChild(itm); itm.setAttribute('type', relType); itm.setAttribute('action', 'get'); } var tmpCrit = itm.selectSingleNode(propertyName); if (!tmpCrit) { tmpCrit = this.dom.createElement(propertyName); itm.appendChild(tmpCrit); } itm = tmpCrit.selectSingleNode('Item'); if (!itm) { itm = this.dom.createElement('Item'); tmpCrit.appendChild(itm); } var criteria = itm.selectSingleNode(critName); if (!criteria) { criteria = this.dom.createElement(critName); itm.appendChild(criteria); } criteria.text = value; criteria.setAttribute('condition', condition); }; QryItem.prototype.setRelationshipSearchOnly = function(relType) { var itm = this.item.selectSingleNode('Relationships/Item[@type="' + relType + '"]'); if (itm) { itm.setAttribute('search_only', 'yes'); } }; QryItem.prototype.setOrderBy = function(orderBy) { this.item.setAttribute('order_by', orderBy); }; QryItem.prototype.setMaxGeneration = function(maxGeneration) { var flag = (maxGeneration) ? '1' : '0'; this.item.setAttribute('max_generation', flag); }; QryItem.prototype.setLevels = function(levels) { this.item.setAttribute('levels', levels); }; QryItem.prototype.getSelect = function() { return this.item.getAttribute('select'); }; QryItem.prototype.setSelect = function(select) { this.item.setAttribute('select', select); }; QryItem.prototype.setConfigPath = function(configPath) { this.item.setAttribute('config_path', configPath); }; QryItem.prototype.setPage = function(page) { this.item.setAttribute('page', page); }; QryItem.prototype.getPage = function(page) { page = this.item.getAttribute('page'); if (page === null) { page = ''; } return page; }; QryItem.prototype.getPageSize = function() { var pagesize = this.item.getAttribute('pagesize'); if (!pagesize) { pagesize = '-1'; } return pagesize; }; QryItem.prototype.setPageSize = function(pageSize) { this.item.setAttribute('pagesize', pageSize); }; QryItem.prototype.getMaxRecords = function() { var maxRecords = this.item.getAttribute('maxRecords'); if (!maxRecords) { maxRecords = '-1'; } return maxRecords; }; QryItem.prototype.setMaxRecords = function(maxRecords) { this.item.setAttribute('maxRecords', maxRecords); }; QryItem.prototype.setItemID = function(id) { this.item.setAttribute('id', id); }; QryItem.prototype.setType = function(itemTypeName) { this.item.setAttribute('type', itemTypeName); }; QryItem.prototype.getType = function() { return this.item.getAttribute('type'); }; QryItem.prototype.getResponse = function() { return this.response; }; QryItem.prototype.getResponseDOM = function() { return this.response.results; }; QryItem.prototype.getResult = function() { return this.result; }; QryItem.prototype.getResultDOM = function() { return this.result.ownerDocument; }; QryItem.prototype.removeCriteria = function QryItemRemoveCriteria(propertyName, languageCode) { if (!propertyName) { return; } var xpath = propertyName; if (languageCode) { xpath = '*[local-name()=\'' + propertyName + '\' and namespace-uri()=\'' + this.arasObj.translationXMLNsURI + '\' and @xml:lang=\'' + languageCode + '\']'; } else { xpath = propertyName; } var criteria = this.item.selectSingleNode(xpath); if (criteria) { criteria.parentNode.removeChild(criteria); } }; QryItem.prototype.removePropertyCriteria = function QryItemRemovePropertyCriteria(propertyName, critName) { var criteria = this.item.selectSingleNode(propertyName + '/Item/' + critName); var itm; if (criteria) { itm = criteria.parentNode; itm.removeChild(criteria); if (!itm.selectSingleNode('.//*[.!="Relationships"]')) { this.removeCriteria(propertyName); } } else { itm = this.item.selectSingleNode(propertyName + '/Item'); if (!itm || !itm.selectSingleNode('.//*[.!="Relationships"]')) { this.removeCriteria(propertyName); } } }; QryItem.prototype.removeRelationshipCriteria = function QryItemRemoveRelationshipCriteria(relType, propertyName) { var criteria = this.item.selectSingleNode('./Relationships/Item[@type="' + relType + '"]/' + propertyName); if (criteria) { var itm = criteria.parentNode; itm.removeChild(criteria); if (!itm.selectSingleNode('.//*[.!="Relationships"]')) { itm.parentNode.removeChild(itm); } } }; QryItem.prototype.removeRelationshipPropertyCriteria = function QryItemRemoveRelationshipPropertyCriteria(relType, propertyName, critName) { var criteria = this.item.selectSingleNode('./Relationships/Item[@type="' + relType + '"]/' + propertyName + '/Item/' + critName); var itm; if (criteria) { itm = criteria.parentNode; itm.removeChild(criteria); if (!itm.selectSingleNode('.//*[.!="Relationships"]')) { var parentCrit = itm.parentNode; parentCrit.removeChild(itm); this.removeRelationshipCriteria(propertyName); } } else { itm = this.item.selectSingleNode('./Relationships/Item[@type="' + relType + '"]/' + propertyName + '/Item'); if (!itm || !itm.selectSingleNode('.//*[.!="Relationships"]')) { this.removeRelationshipCriteria(relType, propertyName); } } }; QryItem.prototype.loadXML = function QryItemLoadXml(xmlToLoad) { this.dom.loadXML(xmlToLoad); this.item = this.dom.documentElement; }; QryItem.prototype.removeAllCriterias = function QryItemRemoveAllCriterias() { this.dom.replaceChild(this.item.cloneNode(false), this.dom.documentElement); this.item = this.dom.documentElement; }; QryItem.prototype.execute = function QryItemExecute(savePrevResults, soapController) { if (savePrevResults === undefined) { savePrevResults = (this.arasObj.getPreferenceItemProperty('Core_GlobalLayout', null, 'core_append_items') == 'true'); } this.savePrevResults = savePrevResults; var res = this.arasObj.soapSend('ApplyItem', this.dom.xml, undefined, undefined, soapController); if (soapController) { return; } this.setResponse(res); return this.result; }; QryItem.prototype.setResponse = function QryItemSetResponse(res) { if (res.getFaultCode().toString() !== '0') { this.arasObj.AlertError(res); this.result = undefined; return; } this.response = res; if (this.savePrevResults) { res = res.getResult(); var fromServer = res.selectNodes('Item'); for (var i = 0; i < fromServer.length; i++) { var oldItm = this.result.selectSingleNode('Item[@id="' + fromServer[i].getAttribute('id') + '"]'); if (oldItm) { oldItm.parentNode.replaceChild(fromServer[i].cloneNode(true), oldItm); } else { this.result.appendChild(fromServer[i].cloneNode(true)); } } } else { this.result = res.getResult(); } }; QryItem.prototype.syncWithClient = function QryItemSyncWithClient() { var res = this.getResult(); var i; var prevResults = res.selectNodes('Item[@isTemp="1" or @isDirty="1"]'); for (i = 0; i < prevResults.length; i++) { res.removeChild(prevResults[i]); } var clientItems = this.arasObj.itemsCache.getItemsByXPath('/Innovator/Items/Item[@type="' + this.itemTypeName + '"]'); for (i = 0; i < clientItems.length; i++) { var clientItem = clientItems[i]; var isTempOrDirty = ((clientItem.getAttribute('isTemp') == '1') || (clientItem.getAttribute('isDirty') == '1')); var fromServer = res.selectSingleNode('Item[@id="' + clientItem.getAttribute('id') + '"]'); if (isTempOrDirty) { if (fromServer) { res.replaceChild(clientItem.cloneNode(true), fromServer); } else { res.appendChild(clientItem.cloneNode(true)); } } else { //item from client cache do not contain unsaved modifications. //to resolve IR-002881: Erroneous caching of the lifecycle state if (fromServer) { //if item in client cache is not locked or item from server is unlocked or locked by someone else then remove item from client cache. var doRemoveClientItem = (!this.arasObj.isLockedByUser(clientItem)) || (!this.arasObj.isLockedByUser(fromServer)); if (doRemoveClientItem) { clientItem.parentNode.removeChild(clientItem); } } } } }; QryItem.prototype.setConditionEverywhere = function(condition) { var conditionTags = this.item.selectNodes('//*[@condition!=\'' + condition + '\']'); for (var i = 0; i < conditionTags.length; i++) { conditionTags.item(i).setAttribute('condition', condition); } }; QryItem.prototype.replaceConditionEverywhere = function(condition1, condition2) { var conditionTags = this.item.selectNodes('//*[@condition=\'' + condition1 + '\']'); for (var i = 0; i < conditionTags.length; i++) { conditionTags.item(i).setAttribute('condition', condition2); } }; QryItem.prototype.getBlock = function(blockName) { return this.dom.documentElement.selectSingleNode(blockName); }; QryItem.prototype.createConditionBlock = function(blockName) { var b = this.dom.createElement(blockName); this.item.appendChild(b); return b; }; QryItem.prototype.setPropertyCriteriaInBlock = function QryItemSetPropertyCriteriaInBlock(block, propertyName, critName, value, condition) { if (condition === undefined) { condition = 'eq'; } if (block) { var criteria = block.selectSingleNode(propertyName + '/Item/' + critName + '[. = \'' + value + '\']'); if (criteria) { return; } else { criteria = this.dom.createElement(propertyName); block.appendChild(criteria); } var itm = criteria.selectSingleNode('Item'); if (!itm) { itm = this.dom.createElement('Item'); criteria.text = ''; criteria.appendChild(itm); } criteria = itm.selectSingleNode(critName); if (!criteria) { criteria = this.dom.createElement(critName); itm.appendChild(criteria); } criteria.text = value; criteria.setAttribute('condition', condition); } }; QryItem.prototype.removePropertyCriteriaFromBlock = function QryItemRemovePropertyCriteriaFromBlock(block, propertyName, critName) { if (!block) { return; } var criterias = block.selectNodes(propertyName); for (var i = 0; i < criterias.length; i++) { criterias[i].parentNode.removeChild(criterias[i]); } }; QryItem.prototype.addCondition2Block = function(block, propertyName, value, condition) { if (condition === undefined) { condition = 'eq'; } if (!block || !propertyName) { return; } var criteria = block.selectSingleNode('*[local-name()=\'' + propertyName + '\' and . = \'' + value + '\']'); if (criteria) { return; } else { criteria = this.dom.createElement(propertyName); block.appendChild(criteria); } criteria.text = value; criteria.setAttribute('condition', condition); }; QryItem.prototype.removeCriteriaFromBlock = function(block, propertyName, languageCode) { if (!block || !propertyName) { return; } var xpath = propertyName; if (languageCode) { xpath = '*[local-name()=\'' + propertyName + '\' and namespace-uri()=\'' + this.arasObj.translationXMLNsURI + '\' and @xml:lang=\'' + languageCode + '\']'; } var criterias = block.selectNodes(xpath); for (var i = 0; i < criterias.length; i++) { criterias[i].parentNode.removeChild(criterias[i]); } }; QryItem.prototype.setItemAttribute = function QryItemSetItemAttribute(name, value) { this.item.setAttribute(name, value); }; QryItem.prototype.removeItemAttribute = function QryItemRemoveItemAttribute(name) { this.item.removeAttribute(name); }; /** clipboard.js **/ // © Copyright by Aras Corporation, 2004-2007. /*---------------------------------------- * FileName: clipboard.js * * */ function Clipboard(arasObj) { this.aras = arasObj; this.clItems = []; /* clipboardItem.source_id = sourceID; clipboardItem.source_itemtype = sourceType; clipboardItem.source_keyedname = sourceKeyedName; clipboardItem.relationship_id = relationshipID; clipboardItem.relationship_itemtype = relationshipType; clipboardItem.related_id = relatedID; clipboardItem.related_itemtype = relatedType; clipboardItem.related_keyedname = relatedKeyedName; */ /* clipboardItem.groupIndex - defines the index of group of copied items */ this.lastCopyIndex = 0; } Clipboard.prototype.copy = function Clipboard_Copy(itemArr) { if (itemArr.length <= 0) { return; } this.lastCopyIndex++; for (var i = 0; i < itemArr.length; i++) { var item = itemArr[i]; item.groupIndex = this.lastCopyIndex; this.clItems.push(item); } }; Clipboard.prototype.paste = function Clipboard_Paste() { var itemArr = []; for (var i = 0; i < this.clItems.length; i++) { if (this.clItems[i].groupIndex == this.lastCopyIndex) { itemArr.push(this.clItems[i]); } } return itemArr; }; Clipboard.prototype.getLastCopyIndex = function Clipboard_GetLastCopyIndex() { return this.lastCopyIndex; }; Clipboard.prototype.isEmpty = function Clipboard_IsEmpty() { return this.clItems.length === 0; }; Clipboard.prototype.getLastCopyCount = function Clipboard_GetLastCopyCount() { var copyCount = 0; for (var i = 0; i < this.clItems.length; i++) { if (this.clItems[i].groupIndex == this.lastCopyIndex) { copyCount++; } } return copyCount; }; Clipboard.prototype.getLastCopyRelatedItemTypeName = function Clipboard_GetLastCopyRelatedItemTypeName() { if (this.isEmpty()) { return ''; } return this.clItems[this.clItems.length - 1].related_itemtype; }; Clipboard.prototype.getLastCopyRTName = function Clipboard_GetLastCopyRTName() { if (this.isEmpty()) { return ''; } return this.clItems[this.clItems.length - 1].relationship_itemtype; }; Clipboard.prototype.getLastCopyItem = function Clipboard_GetLastCopyItem() { if (this.isEmpty()) { return ''; } return this.clItems[this.clItems.length - 1]; }; Clipboard.prototype.clear = function Clipboard_Clear() { this.clItems = []; this.lastCopyIndex = 0; }; Clipboard.prototype.removeItem = function Clipboard_RemoveItem(index) { index = parseInt(index); if (index >= this.clItems.length) { return; } var needUpdateLastIndex = (this.clItems[index].groupIndex == this.lastCopyIndex); var i; for (i = index; i < this.clItems.length - 1; i++) { this.clItems[i] = this.clItems[i + 1]; } this.clItems.pop(); if (needUpdateLastIndex) { this.lastCopyIndex = 0; for (i = 0; i < this.clItems.length; i++) { if (this.clItems[i].groupIndex > this.lastCopyIndex) { this.lastCopyIndex = this.clItems[i].groupIndex; } } } }; Clipboard.prototype.getItem = function Clipboard_GetItem(relId) { for (var i = 0; i < this.clItems.length; i++) { if (this.clItems[i].relationship_id == relId) { return this.clItems[i]; } } return null; }; /** ModalDialogHelper.js **/ function ModalDialogHelper(baseUrl) { this.baseUrl = baseUrl; } ModalDialogHelper.prototype._getOptionsStr = function(options) { options = Object.assign({dialogWidth: 250, dialogHeight: 100, center: true}, options || {}); if (!options.dialogLeft && !options.dialogTop) { options.dialogLeft = (screen.width - options.dialogWidth) / 2; options.dialogTop = (screen.height - options.dialogHeight) / 2; } return ''.concat(options.dialogWidth ? 'dialogWidth:' + options.dialogWidth + 'px;' : '', '', options.dialogHeight ? 'dialogHeight:' + options.dialogHeight + 'px; ' : ' ', options.dialogLeft ? 'dialogLeft:' + options.dialogLeft + 'px;' : '', ' ', options.dialogTop ? 'dialogTop:' + options.dialogTop + 'px;' : '', ' ', 'center:', options.center ? 'yes' : 'no', '; ', 'resizable:', options.resizable ? 'yes' : 'no', '; ', 'status:', options.status ? 'yes' : 'no', '; ', 'scroll:', options.scroll ? 'yes' : 'no', '; ', 'help:', options.help ? 'yes' : 'no', ';'); }; ModalDialogHelper.prototype.show = function(type, aWindow, params, options, file, callbacks) { if (type === 'DefaultModal') { file = file || ''; params = params || {}; params.opener = aWindow; // fix jshint rule scripturl var url = file.indexOf(['javascript', ':'].join('')) === 0 ? file : this.baseUrl + file; return aWindow.showModalDialog(url, params, this._getOptionsStr(options)); } var callback = params.callback || function() {}; params.callback = function() {}; var args = Object.assign({content: file, type: type}, params, options); aWindow.dialogArguments = args; var dialog = aWindow.ArasModules.Dialog.show('iframe', args); if (options && (typeof(options.top) === 'number' || typeof(options.top) === 'string') && (typeof(options.left) === 'number' || typeof(options.left) === 'string')) { dialog.move(options.left, options.top); } dialog.content = dialog.dialogNode.querySelector('.arasDialog-iframe'); dialog.promise.then(function(res) { res = res || dialog.result; dialog.result = res; if (callbacks && callbacks.oncancel) { callbacks.oncancel(dialog); } callback(res); aWindow.dialogArguments = null; }); if (callbacks && callbacks.onload) { callbacks.onload(dialog); } }; /** WebFile.js **/ function WebFile() { /// /// WebFile keeps static methods for working with files on Web. /// Is planned as something like System.IO.File class in .NET Framework. /// /// /// This is summary for constructor. /// } WebFile.Exists = function WebFileExists(url) { /// /// Checks wheather resource under specified URL is availiable or not. /// Sends HEAD request to the server and analyses response. /// /// URL of resource beeeing checked. /// /// /// Returs "true" if resource under specified URL is available and "false" otherwise. var xmlhttp = new XMLHttpRequest(); xmlhttp.open('HEAD', url, false); xmlhttp.send(); return !(xmlhttp.status == 404 || xmlhttp.statusText == 'Not Found'); }; /** enumerations.js **/ var Enums = {}; Enums.UrlType = {'None': 0, 'SecurityToken': 1}; Enums.SortType = {'Ascending': 0, 'Descending': 1}; Enums.CheckinManagerFlags = {'None': 0, 'UnlockAfterCheckin': 1}; Enums.CheckoutManagerFlags = {'None': 0, 'UseTransactions': 1}; /** ClientControlsFactoryHelper.js **/ function ClientControlsFactoryHelper() { } ClientControlsFactoryHelper.prototype.getFactory = function ClientControlsFactoryHelperGetFactory(aWindow) { return new aWindow.ClientControlsFactory(); }; /** ShortcutsHelperFactory.js **/ // jshint ignore:line /*global KeyboardEvent, window*/ (function() { 'use strict'; var ShortcutListener = function(shortcut) { this.callbacks = []; this.shortcut = shortcut; }; ShortcutListener.prototype.addCallback = function(callback) { this.callbacks.push(callback); }; ShortcutListener.prototype.removeCallback = function(callback) { this.callbacks = this.callbacks.filter(function(item) { if (item === callback) { return false; } return true; }); }; ShortcutListener.prototype.preventBlur = function() { return !this.callbacks.some(function(item) { return (true !== item.preventBlur); }); }; ShortcutListener.prototype.stopPropagation = function() { return !this.callbacks.some(function(item) { return (true !== item.stopPropagation); }); }; ShortcutListener.prototype.preventDefault = function() { return this.callbacks.some(function(item) { return (false !== item.preventDefault); }); }; ShortcutListener.prototype.callback = function(state) { var callback; var callbackResult; var index = 0; for (index; index < this.callbacks.length; index += 1) { callback = this.callbacks[index]; if (callback.hasOwnProperty('enabled') && !callback.enabled) { continue; } if (state.useCapture === callback.useCapture) { callbackResult = callback.context ? callback.handler.call(callback.context, state) : callback.handler(state); if (!callbackResult) { return false; } } } return true; }; var specialKeys = { 8: 'backspace', 9: 'tab', 13: 'enter', 19: 'pause', 20: 'capslock', 27: 'esc', 32: 'space', 33: 'pageup', 34: 'pagedown', 35: 'end', 36: 'home', 37: 'left', 38: 'up', 39: 'right', 40: 'down', 45: 'insert', 46: 'delete', 96: '0', 97: '1', 98: '2', 99: '3', 100: '4', 101: '5', 102: '6', 103: '7', 104: '8', 105: '9', 106: '*', 107: '+', // '+' from Num keyboard 109: '-', // '-' from Num keyboard 110: '.', 111: '/', 112: 'f1', 113: 'f2', 114: 'f3', 115: 'f4', 116: 'f5', 117: 'f6', 118: 'f7', 119: 'f8', 120: 'f9', 121: 'f10', 122: 'f11', 123: 'f12', 144: 'numlock', 145: 'scroll', 187: '+', 188: '<', 189: '-', 190: '>', 191: '/', 192: '~', 219: '[', 221: ']' }; var modifierKeys = { 16: 'shift', 17: 'ctrl', 18: 'alt', 224: 'meta', 91: 'windows' }; var shiftNums = { '`': '~', '1': '!', '2': '@', '3': '#', '4': '$', '5': '%', '6': '^', '7': '&', '8': '*', '9': '(', '0': ')', '-': '_', '=': '+', ';': ': ', '\'': '"', ',': '<', '.': '>', '/': '?', '\\': '|' }; var parseEvent = function(event) { var character = specialKeys[event.which] || String.fromCharCode(event.which).toLowerCase(); var modif = ''; var shortcuts = []; // check combinations (alt|ctrl|shift+anything) if (event.altKey) { modif += 'alt+'; } if (event.ctrlKey && aras.Browser.OSName !== 'MacOS') { modif += 'ctrl+'; } // TODO: Need to make sure this works consistently across platforms if (event.metaKey && !event.ctrlKey) { //equate pressing meta to ctrl modif += 'ctrl+'; } if (event.shiftKey) { modif += 'shift+'; } shortcuts.push(modif + character); // "$" can be triggered as "Shift+4" or "Shift+$" or just "$" if ('shift+' === modif) { shortcuts.push(modif + shiftNums[character]); shortcuts.push(shiftNums[character]); } return shortcuts; }; var ShortcutsHelper = function(aWindow) { var shortcutListeners = {}; var isPreventDefault = false; var preventDefaultHandler = function(event) { if (isPreventDefault) { event.preventDefault(); isPreventDefault = false; } }; var getAvailableShortcuts = function(possibleShortcuts) { var signedShorcuts = Object.keys(shortcutListeners); return possibleShortcuts.filter(function(item) { if (-1 === signedShorcuts.indexOf(item)) { return false; } return true; }); }; var eventHandler = function(event, useCapture) { if (modifierKeys[event.which]) { return; } var possibleShortcuts = parseEvent(event); var activeElement = event.currentTarget.document.activeElement; var availableShortcuts = getAvailableShortcuts(possibleShortcuts); if (0 === availableShortcuts.length) { return; } var preventBlur = false; var preventDefault = true; var stopPropagation = false; var index = 0; var shortcutListener; var tmp; for (index; index < availableShortcuts.length; index += 1) { shortcutListener = shortcutListeners[availableShortcuts[index]]; tmp = shortcutListener.preventBlur(); if (tmp && !preventBlur) { preventBlur = true; } tmp = shortcutListener.preventDefault(); if (!tmp && preventDefault) { preventDefault = false; } tmp = shortcutListener.stopPropagation(); if (tmp && !stopPropagation) { stopPropagation = true; } } if (preventDefault) { event.preventDefault(); } if (stopPropagation) { event.stopPropagation(); } var shortcutState = { contentBlurable: activeElement && ['INPUT', 'SELECT', 'TEXTAREA'].indexOf(activeElement.tagName) !== -1, contentEditable: activeElement && ((activeElement.tagName === 'INPUT') ? ['text', 'password'].indexOf(activeElement.type.toLowerCase()) !== -1 : ('TEXTAREA' === activeElement.tagName ? true : false)), useCapture: useCapture }; //if an domNode has the focus then call method blur event to trigger //onchange event (the change event is fired for , ' + '' + ''; htmlPrefix = htmlPrefix.replace(/'/g, '\\\\\\\''); truncateExDetails(); var maxHtmlLen = 2070; var dtls = exNd.xml; dtls = dtls.replace(/'/g, '\\\\\\\''); var maxLen = maxHtmlLen - htmlPrefix.length - htmlSfx.length - 4; if (maxLen > 0 && dtls && dtls.length > maxLen) { dtls = dtls.substr(0, maxLen) + '...'; } if (maxLen <= 0) { dtls = ''; } var html = htmlPrefix + dtls + htmlSfx; if (html.length > maxHtmlLen) { html = html.substr(0, maxHtmlLen); } var options = { dialogWidth: 500, dialogHeight: 450, center: true, resizable: true, content: "javascript:'" + html + "'" }; window.ArasModules.Dialog.show("iframe", options); function getNdVal(nd) { if (!nd) { return ''; } return self.EscapeSpecialChars(nd.text); } function truncateExDetails() { var nd; var nds = exNd.selectNodes('call_stack/function/body'); for (var i = 0; i < nds.length; i++) { nd = nds[i]; if (nd.text && nd.text.length > 80) { nd.text = nd.text.substr(0, 80) + '...'; } } nds = exNd.selectNodes('call_stack/function/call_arguments/argument'); for (var i = 0; i < nds.length; i++) { nd = nds[i]; if (nd.text && nd.text.length > 20) { nd.text = nd.text.substr(0, 30) + '...'; } } } }; Aras.prototype.copyRelationship = function Aras_copyRelationship(relationshipType, relationshipID) { var relResult = this.getItemById(relationshipType, relationshipID, 0, undefined); var sourceType = this.getItemPropertyAttribute(relResult, 'source_id', 'type'); var sourceID = this.getItemProperty(relResult, 'source_id'); var sourceKeyedName = this.getItemPropertyAttribute(relResult, 'source_id', 'keyed_name'); var relatedItem = this.getRelatedItem(relResult); var relatedType = ''; var relatedID = ''; var relatedKeyedName = ''; if (!relatedItem || (relatedItem && '1' == relatedItem.getAttribute('is_polymorphic'))) { var relType = this.getRelationshipType(this.getRelationshipTypeId(relationshipType)); if (!relType || relType.isError()) { return; } relatedType = this.getItemPropertyAttribute(relType.node, 'related_id', 'name'); relatedKeyedName = this.getItemPropertyAttribute(relType.node, 'related_id', 'keyed_name'); } else { relatedID = relatedItem.getAttribute('id'); relatedType = relatedItem.getAttribute('type'); relatedKeyedName = this.getItemProperty(relatedItem, 'keyed_name'); } var clipboardItem = this.newObject(); clipboardItem.source_id = sourceID; clipboardItem.source_itemtype = sourceType; clipboardItem.source_keyedname = sourceKeyedName; clipboardItem.relationship_id = relationshipID; clipboardItem.relationship_itemtype = relationshipType; clipboardItem.related_id = relatedID; clipboardItem.related_itemtype = relatedType; clipboardItem.related_keyedname = relatedKeyedName; return clipboardItem; }; Aras.prototype.pasteRelationship = function Aras_pasteRelationship(parentItem, clipboardItem, as_is, as_new, targetRelationshipTN, targetRelatedTN, showConfirmDlg) { var self = this; function getProperties4ItemType(itemTypeName) { if (!itemTypeName) { return; } var qryItem = new Item('ItemType', 'get'); qryItem.setAttribute('select', 'name'); qryItem.setAttribute('page', 1); qryItem.setAttribute('pagesize', 9999); qryItem.setProperty('name', itemTypeName); var relationshipItem = new Item(); relationshipItem.setType('Property'); relationshipItem.setAction('get'); relationshipItem.setAttribute('select', 'name,data_type'); qryItem.addRelationship(relationshipItem); var results = qryItem.apply(); if (results.isError()) { self.AlertError(result); return; } return results.getRelationships('Property'); } function setRelated(targetItem) { if (relatedType && relatedType !== 'File') { var relatedItemType = self.getItemTypeForClient(relatedType, 'name'); if (relatedItemType.getProperty('is_dependent') == '1') { as_new = true; } if (as_new == true) { var queryItemRelated = new Item(); queryItemRelated.setType(relatedType); queryItemRelated.setID(relatedID); queryItemRelated.setAttribute('do_add', '0'); queryItemRelated.setAttribute('do_lock', '0'); queryItemRelated.setAction('copy'); var newRelatedItem = queryItemRelated.apply(); if (newRelatedItem.isError()) { self.AlertError(self.getResource('', 'aras_object.failed_copy_related_item', newRelatedItem.getErrorDetail()), newRelatedItem.getErrorString(), newRelatedItem.getErrorSource()); return false; } targetItem.setRelatedItem(newRelatedItem); } } } if (as_is == undefined || as_new == undefined) { var qryItem4RelationshipType = new Item(); qryItem4RelationshipType.setType('RelationshipType'); qryItem4RelationshipType.setProperty('name', relationshipType); qryItem4RelationshipType.setAction('get'); qryItem4RelationshipType.setAttribute('select', 'copy_permissions, create_related'); var RelNode = qryItem4RelationshipType.apply(); if (as_is == undefined) { as_is = (RelNode.getProperty('copy_permissions') == '1'); } if (as_new == undefined) { as_new = (RelNode.getProperty('create_related') == '1'); } } var statusId = this.showStatusMessage('status', this.getResource('', 'aras_object.pasting_in_progress'), system_progressbar1_gif); if (!clipboardItem) { return; } var relationshipType = clipboardItem.relationship_itemtype; var relationshipID = clipboardItem.relationship_id; var relatedID = clipboardItem.related_id; var relatedType = clipboardItem.related_itemtype; if (relationshipType == targetRelationshipTN) { var qryItem4CopyRelationship = new Item(); qryItem4CopyRelationship.setType(relationshipType); qryItem4CopyRelationship.setID(relationshipID); qryItem4CopyRelationship.setAction('copy'); qryItem4CopyRelationship.setAttribute('do_add', '0'); qryItem4CopyRelationship.setAttribute('do_lock', '0'); var newRelationship = qryItem4CopyRelationship.apply(); if (newRelationship.isError()) { this.AlertError(this.getResource('', 'aras_object.copy_operation_failed', newRelationship.getErrorDetail()), newRelationship.getErrorString(), newRelationship.getErrorSource()); this.clearStatusMessage(statusId); return false; } newRelationship.removeProperty('source_id'); if (newRelationship.getType() == 'Property' && newRelationship.getProperty('data_type') == 'foreign') { newRelationship.removeProperty('data_source'); newRelationship.removeProperty('foreign_property'); } setRelated(newRelationship); if (!parentItem.selectSingleNode('Relationships')) { parentItem.appendChild(parentItem.ownerDocument.createElement('Relationships')); } var res = parentItem.selectSingleNode('Relationships').appendChild(newRelationship.node.cloneNode(true)); this.clearStatusMessage(statusId); parentItem.setAttribute('isDirty', '1'); return res; } var topWnd = this.getMostTopWindowWithAras(window); var item = new topWnd.Item(relationshipType, 'get'); item.setID(relationshipID); var sourceItem = item.apply(); if (sourceItem.getAttribute('isNew') == '1') { this.AlertError(this.getResource('', 'aras_object.failed_get_source_item'), '', ''); this.clearStatusMessage(statusId); return false; } sourceRelationshipTN = sourceItem.getType(); var targetItem = new Item(); targetItem.setType(sourceRelationshipTN); targetItem.setAttribute('typeId', sourceItem.getAttribute('typeId')); if (targetRelationshipTN == undefined) { targetRelationshipTN = sourceRelationshipTN; } if (sourceRelationshipTN != targetRelationshipTN) { if ((!targetRelatedTN && !relatedType) || targetRelatedTN == relatedType) { if (showConfirmDlg) { var convert = this.confirm(this.getResource('', 'aras_object.you_attempting_paste_different_relationship_types', sourceRelationshipTN, targetRelationshipTN)); if (!convert) { this.clearStatusMessage(statusId); return this.getResource('', 'aras_object.user_abort'); } } targetItem.setType(targetRelationshipTN); } else { this.clearStatusMessage(statusId); return false; } } targetItem.setNewID(); targetItem.setAction('add'); targetItem.setAttribute('isTemp', '1'); parentItem.setAttribute('isDirty', '1'); var sourceProperties = getProperties4ItemType(sourceRelationshipTN); var targetProperties = getProperties4ItemType(targetRelationshipTN); var srcCount = sourceProperties.getItemCount(); var trgCount = targetProperties.getItemCount(); var sysProperties = '^id$|' + '^created_by_id$|' + '^created_on$|' + '^modified_by_id$|' + '^modified_on$|' + '^classification$|' + '^keyed_name$|' + '^current_state$|' + '^state$|' + '^locked_by_id$|' + '^is_current$|' + '^major_rev$|' + '^minor_rev$|' + '^is_released$|' + '^not_lockable$|' + '^css$|' + '^source_id$|' + '^behavior$|' + '^sort_order$|' + '^config_id$|' + '^new_version$|' + '^generation$|' + '^managed_by_id$|' + '^owned_by_id$|' + '^history_id$|' + '^relationship_id$'; if (as_is != true) { sysProperties += '|^permission_id$'; } var regSysProperties = new RegExp(sysProperties, 'ig'); for (var i = 0; i < srcCount; i++) { var sourceProperty = sourceProperties.getItemByIndex(i); var srcPropertyName = sourceProperty.getProperty('name'); var srcPropertyDataType = sourceProperty.getProperty('data_type'); if (srcPropertyName.search(regSysProperties) != -1) { continue; } for (var j = 0; j < trgCount; ++j) { var targetProperty = targetProperties.getItemByIndex(j); var trgPropertyName = targetProperty.getProperty('name'); var trgPropertyDataType = targetProperty.getProperty('data_type'); if ((srcPropertyName == trgPropertyName) && (srcPropertyDataType == trgPropertyDataType)) { var item = sourceItem.getPropertyItem(srcPropertyName); if (!item) { var value = sourceItem.getProperty(srcPropertyName); targetItem.setProperty(srcPropertyName, value); } else { targetItem.setPropertyItem(srcPropertyName, item); } break; } } } setRelated(targetItem); if (!parentItem.selectSingleNode('Relationships')) { parentItem.appendChild(parentItem.ownerDocument.createElement('Relationships')); } var res = parentItem.selectSingleNode('Relationships').appendChild(targetItem.node.cloneNode(true)); this.clearStatusMessage(statusId); return res; }; Aras.prototype.isLCNCompatibleWithRT = function Aras_isLastCopyNodeCompatibleWithRelationshipType(targetRelatedTN) { var sourceRelatedTN = this.clipboard.getLastCopyRelatedItemTypeName(); if (!sourceRelatedTN && !targetRelatedTN) { return true; } if (sourceRelatedTN == targetRelatedTN) { return true; } return false; }; Aras.prototype.isLCNCompatibleWithRTOnly = function Aras_isLastCopyNodeCompatibleWithRelationshipTypeOnly(targetRelationshipTN) { var sourceRelationshipTN = this.clipboard.getLastCopyRTName(); if (!sourceRelationshipTN && !targetRelationshipTN) { return true; } if (sourceRelationshipTN == targetRelationshipTN) { return true; } return false; }; Aras.prototype.isLCNCompatibleWithIT = function Aras_isLastCopyNodeCompatibleWithItemType(itemTypeID) { var clipboardItem = this.clipboard.getLastCopyItem(); return this.isClItemCompatibleWithIT(clipboardItem, itemTypeID); }; Aras.prototype.isClItemCompatibleWithIT = function Aras_IsClipboardItemCompatibleWithItemType(clipboardItem, itemTypeID) { var RelationshipTypeName = clipboardItem.relationship_itemtype; if (!RelationshipTypeName || !itemTypeID) { return false; } return this.getRelationshipTypeId(RelationshipTypeName) != ''; }; Aras.prototype.isClItemCompatibleWithRT = function Aras_IsClipboardItemCompatibleWithRelationshipType(clipboardItem, targetRelatedTN) { var sourceRelatedTN = clipboardItem.related_itemtype; if (!sourceRelatedTN && !targetRelatedTN) { return true; } if (sourceRelatedTN == targetRelatedTN) { return true; } return false; }; /** * Returns the Active and Pending tasks for the user (Workflow Activities, Project Activities, FMEA Action Items). * The users tasks are those assigned to an Identity for which the user is a Member * @param {string} inBasketViewMode * @param {number} workflowTasks boolean AML value. 1 or 0 * @param {number} projectTasks boolean AML value. 1 or 0 * @param {number} actionTasks boolean AML value. 1 or 0 * @returns {} */ Aras.prototype.getAssignedTasks = function(inBasketViewMode, workflowTasks, projectTasks, actionTasks) { var body = '' + inBasketViewMode + ''; body += '' + workflowTasks + ''; body += '' + projectTasks + ''; body += '' + actionTasks + ''; var statusId = this.showStatusMessage('status', this.getResource('', 'workflow_methods.getting_user_activities'), system_progressbar1_gif); var res = this.soapSend('GetAssignedTasks', body); if (statusId != -1) { this.clearStatusMessage(statusId); } if (res.getFaultCode() != 0) { this.AlertError(res); return false; } var r = res.getResult().selectSingleNode('./Item').text; var s1 = r.indexOf(''); var s2 = r.indexOf('', s1); if (r && s1 > -1 && s2 > -1) { var s = '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + ''; r = r.substr(0, s1) + s + r.substr(s2 + 8); } return r; }; Aras.prototype.getFormForDisplay = function Aras_getFormForDisplay(id, mode) { // this function is not a part of public API. please do not use it var criteriaName = mode == 'by-name' ? 'name' : 'id'; var resIOMItem; // if form is new return form from client cache var formNd = this.itemsCache.getItem(id); if (formNd && this.isTempEx(formNd)) { resIOMItem = this.newIOMItem(); resIOMItem.dom = formNd.ownerDocument; resIOMItem.node = formNd; return resIOMItem; } res = this.MetadataCache.GetForm(id, criteriaName); if (res.getFaultCode() != 0) { var resIOMError = this.newIOMInnovator().newError(res.getFaultString()); return resIOMError; } res = res.getResult(); resIOMItem = this.newIOMItem(); resIOMItem.dom = res.ownerDocument; resIOMItem.node = res.selectSingleNode('Item'); // Mark that the item type was requested by main thread in this session var ftypeName; try { ftypeName = resIOMItem.getProperty('name'); } catch (exc) { ftypeName = null; } return resIOMItem; }; Aras.prototype.clearClientMetadataCache = function Aras_resetCachedMetadataOnClient() { this.makeItemsGridBlank(); this.MetadataCache.ClearCache(); }; Aras.prototype.getCacheObject = function Aras_getCacheObject() { //this is private internal function var mainWnd = this.getMainWindow(); var Cache = mainWnd.Cache; if (!Cache) { Cache = this.newObject(); mainWnd.Cache = Cache; } //for now because there are places where cache is accessed directly instead of call to this function if (!Cache.XmlResourcesUrls) { Cache.XmlResourcesUrls = this.newObject(); } if (!Cache.UIResources) { Cache.UIResources = this.newObject(); } return mainWnd.Cache; }; /** * Search item by specific criteria. * @deprecated Use getItemTypeForClient() instead. * @param {string} criteriaValue Value of criteria. * @param {string} [criteriaName] Name of criteria for search. Can be 'id' or 'name'. 'name' by default. * @returns {Object} */ Aras.prototype.getItemTypeDictionary = function Aras_getItemTypeDictionary(criteriaValue, criteriaName) { return this.getItemTypeForClient(criteriaValue, criteriaName); }; /** * Search item by specific criteria. * @param {string} criteriaValue Value of criteria. * @param {string} [criteriaName] Name of criteria for search. Can be 'id' or 'name'. 'name' by default. * @returns {Object} */ Aras.prototype.getItemTypeForClient = function Aras_getItemTypeForClient(criteriaValue, criteriaName) { //this function is a very specific function. please use it only if it is critical for you //and there is no another good way to solve your task. var res = this.getItemTypeForClientFromCache(criteriaValue, criteriaName); if (res.getFaultCode() != 0) { var resIOMError = this.newIOMInnovator().newError(res.getFaultString()); return resIOMError; } res = res.getResult(); var resIOMItem = this.newIOMItem(); resIOMItem.dom = res.ownerDocument; resIOMItem.node = res.selectSingleNode('Item'); return resIOMItem; }; Aras.prototype.getItemTypeForClientFromCache = function Aras_getItemTypeForClientFromCache(criteriaValue, criteriaName) { if (criteriaName === undefined) { criteriaName = 'name'; } if (criteriaName !== 'name' && criteriaName !== 'id') { throw new Error(1, this.getResource('', 'aras_object.not_supported_criteria', criteriaName)); } var res = this.MetadataCache.GetItemType(criteriaValue, criteriaName); if (res.getFaultCode() != 0) { this.AlertError(res); return res; } return res; }; Aras.prototype.getItemTypeNodeForClient = function Aras_getItemTypeNodeForClient(criteriaValue, criteriaName) { var res = this.getItemTypeForClientFromCache(criteriaValue, criteriaName); if (res.getFaultCode() != 0) { var resIOMError = this.newIOMInnovator().newError(res.getFaultString()); return resIOMError.node; } return res.getResult().selectSingleNode('Item'); }; Aras.prototype.getItemTypeId = function Aras_getItemTypeId(name) { return this.MetadataCache.GetItemTypeId(name); }; Aras.prototype.getItemTypeName = function Aras_getItemTypeName(id) { return this.MetadataCache.GetItemTypeName(id); }; Aras.prototype.getRelationshipTypeId = function Aras_getRelationshipTypeId(name) { return this.MetadataCache.GetRelationshipTypeId(name); }; Aras.prototype.getRelationshipTypeName = function Aras_getRelationshipTypeId(id) { return this.MetadataCache.GetRelationshipTypeName(id); }; Aras.prototype.getListId = function Aras_getListId(name) { var key = this.MetadataCache.CreateCacheKey('getListId', name); var result = this.MetadataCache.GetItem(key); if (!result) { var value = this.getItemFromServerByName('List', name, 'name', false); if (!value) { return ''; } result = value.getID(); this.MetadataCache.SetItem(key, result); } return result; }; Aras.prototype.getFormId = function Aras_getFormId(name) { return this.MetadataCache.GetFormId(name); }; Aras.prototype.getRelationshipType = function Aras_getRelationshipType(id) { var res = this.MetadataCache.GetRelationshipType(id, 'id'); if (res.getFaultCode() != 0) { this.AlertError(res); } res = res.getResult(); var resIOMItem = this.newIOMItem(); resIOMItem.dom = res.ownerDocument; resIOMItem.node = res.selectSingleNode('Item'); return resIOMItem; }; Aras.prototype.getLanguagesResultNd = function Aras_getLanguagesResultNd() { var cacheKey = this.MetadataCache.CreateCacheKey('getLanguagesResultNd', 'Language'); var cachedItem = this.MetadataCache.GetItem(cacheKey); if (cachedItem) { return cachedItem.content; } var res = this.getMainWindow().arasMainWindowInfo.getLanguageResult; if (res.getFaultCode() != 0) { return null; } var langs = res.results.selectSingleNode(this.XPathResult('')); cachedItem = aras.IomFactory.CreateCacheableContainer(langs, langs); this.MetadataCache.SetItem(cacheKey, cachedItem); return cachedItem.content; }; Aras.prototype.getLocalesResultNd = function Aras_getLocalesResultNd() { var cacheKey = this.MetadataCache.CreateCacheKey('getLocalesResultNd', 'Locale'); var cachedItem = this.MetadataCache.GetItem(cacheKey); if (cachedItem) { return cachedItem.content; } var res = this.soapSend('ApplyItem', ''); if (res.getFaultCode() != 0) { return null; } var langs = res.results.selectSingleNode(this.XPathResult('')); cachedItem = aras.IomFactory.CreateCacheableContainer(langs, langs); this.MetadataCache.SetItem(cacheKey, cachedItem); return cachedItem.content; }; Aras.prototype.getItemFromServer = function Aras_getItemFromServer(itemTypeName, id, selectAttr, related_expand, language) { if (!related_expand) { related_expand = false; } if (!selectAttr) { selectAttr = ''; } var qry = this.getMostTopWindowWithAras(window).Item(itemTypeName, 'get'); qry.setAttribute('related_expand', (related_expand) ? '1' : '0'); qry.setAttribute('select', selectAttr); qry.setProperty('id', id); if (language) { qry.setAttribute('language', language); } var results = qry.apply(); if (results.isEmpty()) { return false; } if (results.isError()) { this.AlertError(results); return false; } return results.getItemByIndex(0); }; Aras.prototype.getItemFromServerByName = function Aras_getItemFromServer(itemTypeName, name, selectAttr, related_expand) { if (!related_expand) { related_expand = false; } var qry = this.newIOMItem(itemTypeName, 'get'); qry.setAttribute('related_expand', (related_expand) ? '1' : '0'); qry.setAttribute('select', selectAttr); qry.setProperty('name', name); var results = qry.apply(); if (results.isEmpty()) { return false; } if (results.isError()) { this.AlertError(results); return false; } return results.getItemByIndex(0); }; Aras.prototype.getItemFromServerWithRels = function Aras_getItemFromServerWithRels(itemTypeName, id, itemSelect, reltypeName, relSelect, related_expand) { if (!related_expand) { related_expand = false; } var qry = this.getMostTopWindowWithAras(window).Item(itemTypeName, 'get'); qry.setProperty('id', id); qry.setAttribute('select', itemSelect); if (reltypeName) { var topWnd = this.getMostTopWindowWithAras(window); var rel = new topWnd.Item(reltypeName, 'get'); rel.setAttribute('select', relSelect); rel.setAttribute('related_expand', (related_expand) ? '1' : '0'); qry.addRelationship(rel); } var results = qry.apply(); if (results.isEmpty()) { return false; } if (results.isError()) { this.AlertError(results); return false; } return results.getItemByIndex(0); }; /** * @deprecated */ Aras.prototype.getFile = function Aras_getFile(value, fileSelect) { var topWnd = this.getMostTopWindowWithAras(window); var qry = new topWnd.Item('File', 'get'); qry.setAttribute('select', fileSelect); qry.setID(value); var results = qry.apply(); if (results.isEmpty()) { return false; } if (results.isError()) { this.AlertError(results); return false; } return results.getItemByIndex(0); }; Aras.prototype.refreshWindows = function Aras_refreshWindows(message, results, saveChanges) { if (saveChanges == undefined) { saveChanges = true; } // Skip the refresh if this is the unlock portion of the "Save, Unlock and Close" operation. if (!saveChanges) { return; } // If no IDs modified then nothing to refresh. var nodeWithIDs = message.selectSingleNode('event[@name=\'ids_modified\']'); if (!(nodeWithIDs && results)) { return; } // Get list of modified IDs var IDsArray = nodeWithIDs.getAttribute('value').split('|'); // Refresh changed items in main window grid try { var mainWindow = this.getMainWindow(); if (mainWindow.work.isItemsGrid) { var grid = mainWindow.work.grid; for (var chID = 0; chID < IDsArray.length; chID++) { var schID = IDsArray[chID]; //new item var itmNode = results.selectSingleNode('//Item[@id=\'' + schID + '\']'); if (!itmNode || grid.getRowIndex(schID) == -1) { continue; } //old item this.refreshItemsGrid(itmNode.getAttribute('type'), schID, itmNode); } } } catch (excep) { } // Check if there are any other opened windows, that must be refreshed. var doRefresh = false; for (var winId in this.windowsByName) { var win = null; try { if (this.windowsByName.hasOwnProperty(winId)) { win = this.windowsByName[winId]; if (this.isWindowClosed(win)) { this.deletePropertyFromObject(this.windowsByName, winId); continue; } // Item doesn't updated if it was changed by action(Manual Release, Create New Revision) /*if (win.top_ == top_) added "_" to "top" because we removed all the "top" in this file. continue;*/ doRefresh = true; break; } } catch (excep) { continue; } } // Return if there are no windows to refresh. if (!doRefresh) { return; } // Get changed item ID (new Item) or new id=0 if item was deleted. var itemNode = results.selectSingleNode('//Item'); var currentID = 0; if (itemNode) { currentID = itemNode.getAttribute('id'); } var RefreshedRelatedItems = new Array(); var RefreshedItems = new Object(); var alreadyRefreshedWindows = new Object(); var self = this; function refreshWindow(oldItemId, itemNd) { if (alreadyRefreshedWindows[oldItemId]) { return; } var win = self.uiFindWindowEx(oldItemId); if (!win) { return; } alreadyRefreshedWindows[oldItemId] = true; alreadyRefreshedWindows[itemNd.getAttribute('id')] = true; //just fo a case item is versionable self.uiReShowItemEx(oldItemId, itemNd); } var dependency = getTypeIdDependencyForRefreshing(IDsArray); refreshVersionableItem(dependency); function getTypeIdDependencyForRefreshing(IDsArray) { var result = new Object(); for (var i in IDsArray) { var itemID = IDsArray[i]; if (currentID == itemID) { continue; } //not locked items with id=itemID *anywhere* in the cache var nodes = self.itemsCache.getItemsByXPath('//Item[@id=\'' + itemID + '\' and string(locked_by_id)=\'\']'); for (var j = 0; j < nodes.length; j++) { itemFromDom = nodes[j]; var type = itemFromDom.getAttribute('type'); //if type if LCM, Form, WFM, IT or RelshipType or id already refreshed skip adding it to array if (type == 'Life Cycle Map' || type == 'Form' || type == 'Workflow Map' || type == 'ItemType' || type == 'RelationshipType' || RefreshedItems[itemID]) { continue; } var cid = itemFromDom.selectSingleNode('config_id'); var value; if (cid) { value = {id: itemID, config_id: cid.text}; } else { value = {id: itemID, config_id: undefined}; } if (result[type]) { //get structure: type = Array of {id, config_id} result[type].push(value); } else { result[type] = new Array(); result[type].push(value); } } } return result; } function refreshVersionableItem(dependency) { for (var e in dependency) { var element = dependency[e]; //e - type. Type contains multiple ids //create server request for data: /* id1, id2... 1 */ var configIds = getConfigIdsForRequest(element); if (configIds == '') { continue; } var itemsToRefresh = self.loadItems(e, '' + configIds + '' + '1', 0); for (var i = 0; i < itemsToRefresh.length; i++) { var itemNd = itemsToRefresh[i]; var cid = itemNd.selectSingleNode('config_id').text; var id = getOldIdForRefresh(element, cid); refreshWindow(id, itemNd); self.refreshItemsGrid(e, id, itemNd); } } } function getOldIdForRefresh(dependencyArray, configID) { for (var i = 0; i < dependencyArray.length; i++) { if (dependencyArray[i].config_id == configID) { return dependencyArray[i].id; } } } function getConfigIdsForRequest(dependencyArray) { var preResult = new Array(); //create array of ids for request in order to make request string in the end var result = ''; for (var i = 0; i < dependencyArray.length; i++) { if (dependencyArray[i].config_id) { preResult.push('\'' + dependencyArray[i].config_id + '\''); } } if (preResult.length > 0) { while (preResult.length > 1) { result += preResult.pop() + ','; } result += preResult.pop(); } return result; } for (var i in IDsArray) { var itemID = IDsArray[i]; //items with related_id=itemID var nodes1 = this.itemsCache.getItemsByXPath('//Item[count(descendant::Item[@isTemp=\'1\'])=0 and string(@isDirty)!=\'1\' and Relationships/Item/related_id/Item[@id=\'' + itemID + '\']]'); nodes = nodes1; // processing of items with related_id=itemID for (var j = 0; j < nodes.length; j++) { var itemNd = nodes[j]; var id = itemNd.getAttribute('id'); var type = itemNd.getAttribute('type'); var bAlreadyRefreshed = false; for (var k = 0; k < RefreshedRelatedItems.length; k++) { if (id == RefreshedRelatedItems[k]) { bAlreadyRefreshed = true; break; } } if (bAlreadyRefreshed) { continue; } else { RefreshedRelatedItems.push(id); } if (id == currentID) { continue; } if (type == 'Life Cycle Map' || type == 'Form' || type == 'Workflow Map' || type == 'ItemType') { continue; } //IR-006509 if (!this.isDirtyEx(itemNd)) { var related_ids = itemNd.selectNodes('Relationships/Item/related_id[Item/@id="' + currentID + '"]'); //get related_id list with items with id=currentID //update related_id nodes in cache for (var i_r = 0, L = related_ids.length; i_r < L; i_r++) { var relshipItem = related_ids[i_r].parentNode; var relship_id = relshipItem.getAttribute('id'); var relship_type = relshipItem.getAttribute('type'); var res = this.soapSend('GetItem', '', undefined, false); if (res.getFaultCode() == 0) { var res_related_id = res.getResult().selectSingleNode('Item/related_id/Item[@id="' + currentID + '"]'); if (res_related_id == null) { continue; } //update attributes and child nodes var attr; for (var i_att = 0; i_att < res_related_id.attributes.length; i_att++) { attr = res_related_id.attributes[i_att]; related_ids[i_r].setAttribute(attr.nodeName, attr.nodeValue); } //it more safe than replace node. Because it is possible that there are places where reference to releated_id/Item node //is chached in local variable. The replacement would just break the code. //mergeItem does not merge attributes in its current implementation. Thus the attributes are copied with the legacy code above. this.mergeItem(relshipItem.selectSingleNode('related_id/Item[@id="' + currentID + '"]'), res_related_id); } } } refreshWindow(id, itemNd); } // ^^^ processing of items with related_id=itemID } }; Aras.prototype.refreshItemsGrid = function Aras_refreshItemsGrid(itemTypeName, itemID, updatedItem) { var mainWindow = this.getMainWindow(); if (!updatedItem) { return false; } var updatedID = updatedItem.getAttribute('id'); try { if (!mainWindow.work.isItemsGrid) { return false; } } catch (excep) { return false; } if (itemTypeName == 'ItemType') { if (itemID == mainWindow.work.itemTypeID) { mainWindow.work.location.replace('../scripts/blank.html'); return true; } } if (mainWindow.work.itemTypeName != itemTypeName) { return false; } var grid = mainWindow.work.grid; if (grid.getRowIndex(itemID) == -1) { return true; } var wasSelected = (grid.getSelectedItemIds().indexOf(itemID) > -1); if (updatedID != itemID) { //hack to prevent rewrite deleteRow to use typeName and Id instead of node var oldItem = this.createXMLDocument(); oldItem.loadXML(''); oldItem = oldItem.documentElement; mainWindow.work.deleteRow(oldItem); } mainWindow.work.updateRow(updatedItem); if (wasSelected) { if (updatedID == itemID) { mainWindow.work.onSelectItem(itemID); } else { var currSel = grid.getSelectedId(); //if (currSel) mainWindow.work.onSelectItem(currSel); } } //if (wasSelected) return true; }; Aras.prototype.isDirtyItems = function Aras_isDirtyItems() { if (this.getCommonPropertyValue('exitWithoutSavingInProgress')) { return false; } var dirtyExist = ( this.itemsCache.getItemsByXPath( '/Innovator/Items/Item[@action!=\'\' and (@isTemp=\'1\' or (locked_by_id=\'' + this.getUserID() + '\' and (@isDirty=\'1\' or .//Item/@isDirty=\'1\' or .//Item/@isTemp=\'1\')))]').length > 0 ); return dirtyExist ? true : false; }; Aras.prototype.dirtyItemsHandler = function Aras_dirtyItemsHandler(win, readOnly) { if (this.isDirtyItems()) { var param = new Object(); param.aras = this.getMostTopWindowWithAras(window).aras; if (readOnly) { param.mode = 'read_only'; } if (!win) { win = window; } var options = { dialogWidth: 400, dialogHeight: 500, center: true }; return this.modalDialogHelper.show('DefaultModal', win, param, options, 'dirtyItemsList.html'); } }; Aras.prototype.getPreferenceItem = function Aras_getPreferenceItem(prefITName, specificITorRTId) { if (!prefITName) { return null; } var self = this; var prefKey; if (specificITorRTId) { if (prefITName == 'Core_RelGridLayout') { var relType = this.getRelationshipType(specificITorRTId).node; var itID = specificITorRTId; if (relType) { itID = this.getItemProperty(relType, 'relationship_id'); } prefKey = this.MetadataCache.CreateCacheKey('Preference', prefITName, specificITorRTId, itID, this.preferenceCategoryGuid); } else { prefKey = this.MetadataCache.CreateCacheKey('Preference', prefITName, specificITorRTId, this.preferenceCategoryGuid); } } else { prefKey = this.MetadataCache.CreateCacheKey('Preference', prefITName, this.preferenceCategoryGuid); } var res = this.MetadataCache.GetItem(prefKey); if (res) { return res.content; } var findCriteriaPropNm = ''; var findCriteriaPropVal = specificITorRTId; switch (prefITName) { case 'Core_ItemGridLayout': { findCriteriaPropNm = 'item_type_id'; break; } case 'Core_RelGridLayout': { findCriteriaPropNm = 'rel_type_id'; break; } case 'cmf_ContentTypeGridLayout': { findCriteriaPropNm = 'tabular_view_id'; break; } } function getPrefQueryXml(prefCondition) { var xml = ''; xml += prefCondition; xml += ''; xml += ''; if (findCriteriaPropNm) { xml += '<' + findCriteriaPropNm + '>' + findCriteriaPropVal + ''; } xml += ''; xml += ''; return xml; } var xml = getPrefQueryXml(inner_getConditionForUser()); var resDom = this.createXMLDocument(); var prefMainItemID = this.getVariable('PreferenceMainItemID'); var prefMainItemDom = this.createXMLDocument(); var res; if (prefITName === 'Core_GlobalLayout') { res = this.getMainWindow().arasMainWindowInfo.Core_GlobalLayout; } else if (prefITName === 'SSVC_Preferences') { res = this.getMainWindow().arasMainWindowInfo.SSVC_Preferences; } else { res = this.soapSend('ApplyItem', xml); if (res.getFaultCode() != 0) { this.AlertError(res); return null; } } res = res.getResultsBody(); if (res && res.indexOf('Item') > -1) { resDom.loadXML(res); if (!prefMainItemID) { prefMainItemDom.loadXML(res); var tmpNd = prefMainItemDom.selectSingleNode('/*/Relationships'); if (tmpNd) { tmpNd.parentNode.removeChild(tmpNd); } } } if (!resDom.selectSingleNode('//Item[@type=\'' + prefITName + '\']')) { xml = getPrefQueryXml(inner_getConditionForSite()); res = this.soapSend('ApplyItem', xml); if (res.getFaultCode() != 0) { this.AlertError(res); return null; } var newPref = this.newItem(prefITName); var tmp = newPref.cloneNode(true); newPref = tmp; res = res.getResultsBody(); if (res && res.indexOf('Item') > -1) { resDom.loadXML(res); var nds2Copy = resDom.selectNodes('//Item[@type=\'' + prefITName + '\']/*[local-name()!=\'source_id\' and local-name()!=\'permission_id\']'); for (var i = 0; i < nds2Copy.length; i++) { var newNd = newPref.selectSingleNode(nds2Copy[i].nodeName); if (!newNd) { newNd = newPref.appendChild(newPref.ownerDocument.createElement(nds2Copy[i].nodeName)); } newNd.text = nds2Copy[i].text; } } if (findCriteriaPropNm) { var tmpNd = newPref.appendChild(newPref.ownerDocument.createElement(findCriteriaPropNm)); tmpNd.text = findCriteriaPropVal; } resDom.loadXML(newPref.xml); if (!prefMainItemID) { var mainPref = this.newItem('Preference'); var tmp = mainPref.cloneNode(true); mainPref = tmp; var userNd = this.getLoggedUserItem(); identityNd = userNd.selectSingleNode('Relationships/Item[@type=\'Alias\']/related_id/Item[@type=\'Identity\']'); if (!identityNd) { return null; } this.setItemProperty(mainPref, 'identity_id', identityNd.getAttribute('id')); prefMainItemDom.loadXML(mainPref.xml); } } if (!prefMainItemID) { var mainPref = prefMainItemDom.documentElement; var tmpKey = this.MetadataCache.CreateCacheKey('Preference', mainPref.getAttribute('id')); var itm = aras.IomFactory.CreateCacheableContainer(mainPref, mainPref); this.MetadataCache.SetItem(tmpKey, itm); this.setVariable('PreferenceMainItemID', mainPref.getAttribute('id')); } var result = resDom.selectSingleNode('//Item[@type=\'' + prefITName + '\']'); var itm = aras.IomFactory.CreateCacheableContainer(result, result); this.MetadataCache.SetItem(prefKey, itm); return result; function inner_getConditionForSite() { var res = '' + '' + 'World' + '' + ''; return res; } function inner_getConditionForUser() { var res; var userNd = self.getLoggedUserItem(); var identityNd = userNd.selectSingleNode('Relationships/Item[@type=\'Alias\']/related_id/Item[@type=\'Identity\']'); if (!identityNd) { return ''; } res = '' + identityNd.getAttribute('id') + ''; return res; } }; Aras.prototype.getPreferenceItemProperty = function Aras_getPreferenceItemProperty(prefITName, specificITorRTId, propNm, defaultVal) { var prefItm = this.getPreferenceItem(prefITName, specificITorRTId); return this.getItemProperty(prefItm, propNm, defaultVal); }; Aras.prototype.setPreferenceItemProperties = function Aras_setPreferenceItemProperties(prefITName, specificITorRTId, varsHash) { if (!prefITName || !varsHash) { return false; } var prefNode = this.getPreferenceItem(prefITName, specificITorRTId); var varName; for (varName in varsHash) { var varValue = varsHash[varName]; var nd = prefNode.selectSingleNode(varName); if (!nd) { nd = prefNode.appendChild(prefNode.ownerDocument.createElement(varName)); } if (nd.text != varValue) { nd.text = varValue; var params = new Object(); params.type = prefITName; params.specificITorRTId = specificITorRTId; params.propertyName = varName; this.fireEvent('PreferenceValueChanged', params); } } if (varName && !prefNode.getAttribute('action')) { prefNode.setAttribute('action', 'update'); } return true; }; Aras.prototype.savePreferenceItems = function Aras_savePreferenceItems() { var prefArr = this.MetadataCache.GetItemsById(this.preferenceCategoryGuid); if (!prefArr || prefArr.length < 1) { return; } var prefMainItemID = this.getVariable('PreferenceMainItemID'); var prefItem; if (prefMainItemID) { var tmpArr = this.MetadataCache.GetItemsById(prefMainItemID); if (tmpArr.length > 0) { prefItem = tmpArr[0].content; } } if (!prefItem) { return; } if (!prefItem.getAttribute('action')) { prefItem.setAttribute('action', 'edit'); } var rels = prefItem.selectSingleNode('Relationships'); if (!rels) { rels = prefItem.appendChild(prefItem.ownerDocument.createElement('Relationships')); } var prefItemAction = prefItem.getAttribute('action'); var i = 0; while (prefArr[i]) { var nd = prefArr[i].content; var ndAction = nd.getAttribute('action'); if (ndAction) { nd = rels.appendChild(nd.cloneNode(true)); if (ndAction == 'add') { var whereArr = new Array(); switch (nd.getAttribute('type')) { case 'Core_GlobalLayout': whereArr.push('[Core_GlobalLayout].source_id=\'' + prefItem.getAttribute('id') + '\''); break; case 'Core_ItemGridLayout': whereArr.push('[Core_ItemGridLayout].source_id=\'' + prefItem.getAttribute('id') + '\''); whereArr.push('[Core_ItemGridLayout].item_type_id=\'' + this.getItemProperty(nd, 'item_type_id') + '\''); break; case 'Core_RelGridLayout': whereArr.push('[Core_RelGridLayout].source_id=\'' + prefItem.getAttribute('id') + '\''); whereArr.push('[Core_RelGridLayout].rel_type_id=\'' + this.getItemProperty(nd, 'rel_type_id') + '\''); break; } if (whereArr.length) { nd.setAttribute('action', 'merge'); nd.setAttribute('where', whereArr.join(' AND ')); nd.removeAttribute('id'); } } } i++; } if (prefItemAction == 'add') { prefItem.setAttribute('action', 'merge'); prefItem.setAttribute('where', '[Preference].identity_id=\'' + this.getItemProperty(prefItem, 'identity_id') + '\''); prefItem.removeAttribute('id'); } prefItem.setAttribute('doGetItem', '0'); try { this.soapSend('ApplyItem', prefItem.xml); } catch (e) { return; } return true; }; Aras.prototype.mergeItemRelationships = function Aras_mergeItemRelationships(oldItem, newItem) { //this method is for internal purposes only. var newRelationships = newItem.selectSingleNode('Relationships'); if (newRelationships != null) { var oldRelationships = oldItem.selectSingleNode('Relationships'); if (oldRelationships == null) { oldRelationships = oldItem.appendChild(newRelationships.cloneNode(true)); } else if (oldRelationships.childNodes.length === 0) { oldItem.replaceChild(newRelationships.cloneNode(true), oldRelationships); } else { this.mergeItemsSet(oldRelationships, newRelationships); } } }; Aras.prototype.mergeItem = function Aras_mergeItem(oldItem, newItem) { //this method is for internal purposes only. var oldId = oldItem.getAttribute('id'); if (oldId) { var newId = newItem.getAttribute('id'); if (newId && oldId !== newId) { return; //do not merge Items with different ids. } } var allPropsXpath = '*[local-name()!=\'Relationships\']'; var oldAction = oldItem.getAttribute('action'); if (!oldAction) { oldAction = 'skip'; } if (oldAction == 'delete') { //do not merge newItem into oldSet } else if (oldAction == 'add') { //this should never happen because getItem results cannot return not saved Item. do nothing here. } else if (oldAction == 'update' || oldAction == 'edit') { //we can add only missing properties here and merge relationships var newProps = newItem.selectNodes(allPropsXpath); for (var i = 0; i < newProps.length; i++) { var newProp = newProps[i]; var propNm = newProp.nodeName; var oldProp = oldItem.selectSingleNode(propNm); if (!oldProp) { oldItem.appendChild(newProp.cloneNode(true)); } else { var oldPropItem = oldProp.selectSingleNode('Item'); if (oldPropItem) { var newPropItem = newProp.selectSingleNode('Item'); if (newPropItem) { this.mergeItem(oldPropItem, newPropItem); } } } } mergeSpecialAttributes(oldItem, newItem); //merge relationships this.mergeItemRelationships(oldItem, newItem); } else if (oldAction == 'skip') { //all properties not containing Items can be replaced here. //process oldItem properies with * NO * Item inside var oldProps = oldItem.selectNodes(allPropsXpath + '[not(Item)]'); for (var i = 0; i < oldProps.length; i++) { var oldProp = oldProps[i]; var propNm = oldProp.nodeName; var newProp = newItem.selectSingleNode(propNm); if (newProp) { oldItem.replaceChild(newProp.cloneNode(true), oldProp); } } //process oldItem properies with Item inside var oldItemProps = oldItem.selectNodes(allPropsXpath + '[Item]'); for (var i = 0; i < oldItemProps.length; i++) { var oldProp = oldItemProps[i]; var propNm = oldProp.nodeName; var newProp = newItem.selectSingleNode(propNm); if (newProp) { var oldPropItem = oldProp.selectSingleNode('Item'); var newPropItem = newProp.selectSingleNode('Item'); var oldPropItemId = oldPropItem.getAttribute('id'); if (newPropItem) { var newPropItemId = newPropItem.getAttribute('id'); //id of item may be changed in case of versioning or when item is replaced with another item on server-side if (oldPropItemId != newPropItemId) { var oldItemHasUnsavedChanges = Boolean(oldPropItem.selectSingleNode('descendant-or-self::Item[@action!=\'skip\']')); if (oldItemHasUnsavedChanges) { //do nothing. mergeItem will do all it's best. } else { //set the new id on "old" Item tag oldPropItem.setAttribute('id', newPropItemId); //content of "old" Item tag is useless. Remove that. var children = oldPropItem.selectNodes('*'); for (var j = 0, C_L = children.length; j < C_L; j++) { oldPropItem.removeChild(children[j]); } } } this.mergeItem(oldPropItem, newPropItem); } else { var oldPropItemAction = oldPropItem.getAttribute('action'); if (!oldPropItemAction) { oldPropItemAction = 'skip'; } var newPropItemId = newProp.text; if (oldPropItemAction == 'skip') { if (newPropItemId != oldPropItemId) { oldItem.replaceChild(newProp.cloneNode(true), oldProp); } } } } } //process all newItem properties which are missing in oldItem var newProps = newItem.selectNodes(allPropsXpath); for (var i = 0; i < newProps.length; i++) { var newProp = newProps[i]; var propNm = newProp.nodeName; var oldProp = oldItem.selectSingleNode(propNm); if (!oldProp) { oldItem.appendChild(newProp.cloneNode(true)); } } mergeSpecialAttributes(oldItem, newItem); //merge relationships this.mergeItemRelationships(oldItem, newItem); } function mergeSpecialAttributes(oldItem, newItem) { var specialAttrNames = new Array('discover_only', 'type'); for (var i = 0; i < specialAttrNames.length; i++) { if (newItem.getAttribute(specialAttrNames[i])) { oldItem.setAttribute(specialAttrNames[i], newItem.getAttribute(specialAttrNames[i])); } } } }; Aras.prototype.mergeItemsSet = function Aras_mergeItemsSet(oldSet, newSet) { //this method is for internal purposes only. //both oldSet and newSet are nodes with Items inside. (oldSet and newSet normally are AML or Relationships nodes) var oldDoc = oldSet.ownerDocument; //we don't expect action attribute specified on Items from newSet var newItems = newSet.selectNodes('Item[not(@action)]'); for (var i = 0; i < newItems.length; i++) { var newItem = newItems[i]; var newId = newItem.getAttribute('id'); var newType = newItem.getAttribute('type'); var newTypeId = newItem.getAttribute('typeId'); var oldItem = oldSet.selectSingleNode('Item[@id="' + newId + '"][@type="' + newType + '"]'); if (!oldItem) { // oldItem = oldSet.appendChild(oldDoc.createElement('Item')); oldItem.setAttribute('id', newId); oldItem.setAttribute('type', newType); oldItem.setAttribute('typeId', newTypeId); } this.mergeItem(oldItem, newItem); } }; // +++ Export to Office section +++ //this method is for internal purposes only. Aras.prototype.export2Office = function Aras_export2Office(gridXmlCallback, toTool, itemNd, itemTypeName, tabName) { var statusId = this.showStatusMessage('status', this.getResource('', 'aras_object.exporting'), system_progressbar1_gif); var aras = this; var contentCallback = function() { if (toTool == 'export2Excel') { return Export2Excel(typeof (gridXmlCallback) == 'function' ? gridXmlCallback() : gridXmlCallback, itemNd, itemTypeName, tabName); } return Export2Word(typeof (gridXmlCallback) == 'function' ? gridXmlCallback() : gridXmlCallback, itemNd); }; this.clearStatusMessage(statusId); this.saveString2File(contentCallback, toTool); function Export2Excel(gridXml, itemNd, itemTypeName, tabName) { var result; var relatedResult; var itemTypeNd; var gridDoc = aras.createXMLDocument(); if (itemNd) { itemTypeNd = aras.getItemTypeForClient(itemNd.getAttribute('type'), 'name').node; } if (!itemTypeName) { if (itemTypeNd) { itemTypeName = aras.getItemProperty(itemTypeNd, 'name'); } else { itemTypeName = 'Innovator'; } } if (!tabName) { tabName = 'RelationshipsTab'; } if (gridXml != '') { gridDoc.loadXML(gridXml); result = generateXML(gridDoc, (itemNd && itemNd.xml) ? tabName : itemTypeName); } if (itemNd && itemNd.xml && itemTypeNd) { var itemTypeID = itemTypeNd.getAttribute('id'); var resDom = aras.createXMLDocument(); resDom.loadXML('' + itemNd.xml + ''); var xpath = 'Relationships/Item[@type="Property"]'; var propNds = itemTypeNd.selectNodes(xpath); aras.uiPrepareDOM4GridXSLT(resDom); var grid_xml = aras.uiGenerateGridXML(resDom, propNds, null, itemTypeID, {mode: 'forExport2Html'}, true); gridDoc.loadXML(grid_xml); var tableNd = gridDoc.selectSingleNode('//table'); if (tableNd.selectSingleNode('thead').childNodes.length == 0) { generateThs(gridDoc, propNds); } if (tableNd.selectSingleNode('columns').childNodes.length == 0) { generateColumns(gridDoc, propNds); } relatedResult = generateXML(gridDoc, itemTypeName); } //form valid result xml for Excel export if (result) { if (relatedResult) { var relatedDom = aras.createXMLDocument(); relatedDom.loadXML(relatedResult); relatedStyles = relatedDom.documentElement.childNodes[0].childNodes; var resultDom = aras.createXMLDocument(); resultDom.loadXML(result); styles = resultDom.documentElement.childNodes[0].childNodes; result = ''; //merge all styles from from and relationships grid for (var i = 0; i < relatedStyles.length; i++) { result += relatedStyles[i].xml; } for (var j = 0; j < styles.length; j++) { result += styles[j].xml; } result += ''; //merge two worksheets result += relatedDom.documentElement.childNodes[1].xml; result += resultDom.documentElement.childNodes[1].xml; result += ''; } } else { if (relatedResult) { result = relatedResult; } else { result = generateXML(gridDoc); } } return result; function generateThs(dom, propNds) { var parentNode = dom.selectSingleNode('//thead'); for (var i = 0; i < propNds.length; i++) { var pNd = propNds[i]; var lbl = aras.getItemProperty(pNd, 'label'); var nm = aras.getItemProperty(pNd, 'name'); var newTh = parentNode.appendChild(dom.createElement('th')); newTh.setAttribute('align', 'c'); newTh.text = (lbl ? lbl : nm); } return dom; } function generateColumns(dom, propNds) { var parentNode = dom.selectSingleNode('//columns'); for (var i = 0; i < propNds.length; i++) { var pNd = propNds[i]; var lbl = aras.getItemProperty(pNd, 'label'); var nm = aras.getItemProperty(pNd, 'name'); var type = aras.getItemProperty(pNd, 'data_type'); var widthAttr = (lbl ? lbl : nm).length * 8; var newCol = parentNode.appendChild(dom.createElement('column')); if (type == 'date') { newCol.setAttribute('sort', 'DATE'); } else if (type == 'integer' || type == 'float' || type == 'decimal') { newCol.setAttribute('sort', 'NUMERIC'); } newCol.setAttribute('width', widthAttr); newCol.setAttribute('order', i); } return dom; } } function Export2Word(gridXml, itemNd) { function generateThs(propNds) { var res = ''; var tmpDom = aras.createXMLDocument(); tmpDom.loadXML(res); for (var i = 0; i < propNds.length; i++) { var pNd = propNds[i]; var lbl = aras.getItemProperty(pNd, 'label'); var nm = aras.getItemProperty(pNd, 'name'); var newTh = tmpDom.documentElement.appendChild(tmpDom.createElement('th')); newTh.setAttribute('align', 'center'); newTh.setAttribute('style', 'background-color:#d4d0c8;'); newTh.text = (lbl ? lbl : nm); } res = tmpDom.xml; return res; } var html = generateHtml(gridXml); if (itemNd && itemNd.xml) { var itemTypeNd = aras.getItemTypeForClient(itemNd.getAttribute('type'), 'name').node; if (itemTypeNd) { var itemTypeID = itemTypeNd.getAttribute('id'); var resDom = aras.createXMLDocument(); resDom.loadXML('' + itemNd.xml + ''); var xpath = 'Relationships/Item[@type="Property"]'; var propNds = itemTypeNd.selectNodes(xpath); aras.convertFromNeutralAllValues(resDom.selectSingleNode('/Result/Item')); aras.uiPrepareDOM4GridXSLT(resDom); var grid_xml = aras.uiGenerateGridXML(resDom, propNds, null, itemTypeID, {mode: 'forExport2Html'}, true); var tmpHtml = generateHtml(grid_xml); if (tmpHtml.indexOf(''); if (i > 0) { html = html.substr(0, i) + tmpHtml.substr(i2, i3 - i2 + 8) + '
' + html.substr(i); } } } return html; } function generateHtml(gridXml) { var res = ''; var gridDom = aras.createXMLDocument(); if (!gridXml) { gridXml = '
'; } gridDom.loadXML(gridXml); if (gridDom.parseError.errorCode == 0) { var tblNd = gridDom.selectSingleNode('//table'); if (tblNd) { tblNd.setAttribute('base_href', aras.getScriptsURL()); } res = aras.applyXsltFile(gridDom, aras.getScriptsURL() + '../styles/printGrid4Export.xsl'); } return res; } function generateXML(gridDom, workSheetName) { var res = ''; var tblNd = gridDom.selectSingleNode('//table'); if (tblNd) { tblNd.setAttribute('base_href', aras.getScriptsURL()); if (workSheetName) { tblNd.setAttribute('workSheet', workSheetName); } } var xml = ArasModules.xml; var xslt = xml.parseFile(aras.getScriptsURL() + '../styles/printGrid4ExportToExcel.xsl'); return xml.transform(gridDom, xslt); } }; //this method is for internal purposes only. Aras.prototype.saveString2File = function ArasSaveString2File(contentCallback, extension, fileName) { var ext = extension ? extension.toLowerCase() : 'unk'; var fileNamePrefix = fileName || 'export2unknown_type'; var mimeType = ''; if (ext.indexOf('excel') !== -1) { ext = 'xls'; mimeType = 'application/excel'; fileNamePrefix = this.getResource('', 'aras_object.export2excel_file_prefix'); } else if (ext.indexOf('word') !== -1) { ext = 'doc'; mimeType = 'application/msword'; fileNamePrefix = this.getResource('', 'aras_object.export2word_file_prefix'); } var blob = new Blob([contentCallback()], {type: mimeType}); if ('msSaveBlob' in window.navigator) { window.navigator.msSaveBlob(blob, fileNamePrefix + '.' + ext); return; } var link = document.createElement('a'); link.href = URL.createObjectURL(blob); link.download = fileNamePrefix + '.' + ext; link.setAttribute('type', mimeType); var e = document.createEvent('MouseEvents'); e.initEvent('click' ,true ,true); link.dispatchEvent(e); }; // --- Export to Office section --- Aras.prototype.EscapeSpecialChars = function Aras_EscapeSpecialChars(str) { if (!this.utilDoc) { this.utilDoc = this.createXMLDocument(); } var element_t = this.utilDoc.createElement('t'); element_t.text = str; var result = element_t.xml; return result.substr(3, result.length - 7); }; // value returned as xpath function concat(), ie addition quotes aren't needed Aras.prototype.EscapeXPathStringCriteria = function Aras_EscapeXPathStringCriteria(str) { var res = str.replace(/'/g, '\',"\'",\''); if (res != str) { return 'concat(\'' + res + '\')'; } else { return '\'' + res + '\''; } }; /* //unit tests for Aras_isPropertyValueValid function Boolean ? value is 0 or 1. (*) Color ? must satisfy regexp /^#[a-f0-9]{6}$|^btnface$/i. (*) Color List ? must satisfy regexp /^#[a-f0-9]{6}$|^btnface$/i. (*) Date ? input string must represent a date in a supported format. (*) Decimal ? must be a number. (*) Federated ? read-only. No check. Filter List ? string length must be not greater than 64. (*) Float ? must be a number. (*) Foreign ? read-only. No check. Formatted Text ? No check. Image ? string length must be not greater than 128. (*) Qrcode ? string length must be not greater than 128. (*) Integer ? must be an integer number. (*) Item ? must be an item id (32 characters from [0-9A-F] set). (*) List ? string length must be not greater than 64. (*) MD5 ? 32 characters from [0-9A-F] set. (*) Sequence ? read-only. No check. String ? check if length of inputted string is not greater than maximum permissible string length. Verify against property pattern if specified. (*) Text ? No check. Where (*) means: Empty value is not permissible if property is marked as required. Property definition: data_type - string pattern - string is_required - boolean stored_length - integer */ /*common tests part* / var allDataTypes = new Array("boolean", "color", "color list", "date", "decimal", "federated", "filter list", "float", "foreign", "formatted text", "image", "integer", "item", "list", "md5", "sequence", "string", "text"); function RunTest(testDescription, testDataArr, expectedResults) { var failedTests = new Array(); for (var i=0; i 0); }; Aras.prototype.isNegativeInteger = function Aras_isPositiveInteger(propertyValue) { return (this.isInteger(propertyValue) && parseInt(propertyValue) < 0); }; Aras.prototype.isPropertyValueValid = function Aras_isPropertyValueValid(propertyDef, propertyValue, inputLocale) { this.ValidationMsg = ''; var data_type = propertyDef.data_type; if (propertyValue !== '') { switch (data_type) { case 'boolean': if (!propertyValue == '0' && !propertyValue == '1') { this.ValidationMsg = this.getResource('', 'aras_object.value_property _must_be _boolean'); } break; case 'color': case 'color list': if (!/^#[a-f0-9]{6}$|^btnface$/i.test(propertyValue)) { this.ValidationMsg = this.getResource('', 'aras_object.value_property_invalid_contains_incorrect_symbols'); } break; case 'date': var dateFormat = this.getDateFormatByPattern(propertyDef.pattern || 'short_date'), lessStrictFormat = dateFormat, neutralDate, dotNetPattern; propertyValue = typeof (propertyValue) === 'string' ? propertyValue.trim() : propertyValue; while (lessStrictFormat && !neutralDate) { dotNetPattern = this.getClippedDateFormat(lessStrictFormat) || this.getDotNetDatePattern(lessStrictFormat); neutralDate = this.getIomSessionContext().ConvertToNeutral(propertyValue, data_type, dotNetPattern); lessStrictFormat = this.getLessStrictDateFormat(lessStrictFormat); } if (typeof neutralDate !== 'string') { this.ValidationMsg = this.getResource('', 'aras_object.value_property_invalid_must_be_date'); } break; case 'decimal': var decimalNumber = this.getIomSessionContext().ConvertToNeutral(propertyValue, data_type); if (isNaN(parseFloat(decimalNumber))) { this.ValidationMsg = this.getResource('', 'aras_object.value_property_invalid_must_be_decimal'); } break; case 'federated': break; case 'float': var floatNumber = this.getIomSessionContext().ConvertToNeutral(propertyValue, data_type); if (isNaN(parseFloat(floatNumber))) { this.ValidationMsg = this.getResource('', 'aras_object.value_property_invalid_must_be_float'); } break; case 'foreign': case 'formatted text': break; case 'image': if (propertyValue.length > 128) { this.ValidationMsg = this.getResource('', 'aras_object.length_image_property_cannot_be_larger_128_symbols'); } break; case 'qrcode': if (propertyValue.length > 128) { this.ValidationMsg = this.getResource('', 'aras_object.length_qrcode_property_cannot_be_larger_128_symbols'); } break; case 'integer': if (!this.isInteger(propertyValue)) { this.ValidationMsg = this.getResource('', 'aras_object.value_property_invalid_must_be_integer'); } break; case 'item': if (typeof (propertyValue) == 'string' && !/^[0-9a-f]{32}$/i.test(propertyValue)) { this.ValidationMsg = this.getResource('', 'aras_object.value_property_invalid_must_be_item_id'); } break; case 'md5': if (propertyDef.stored_length) { var pattern = new RegExp("^[0-9a-f]{" + propertyDef.stored_length + "}$", "i"); if (!pattern.test(propertyValue)) { this.ValidationMsg = this.getResource('', 'aras_object.length_properties_value_canot_be_larger', propertyDef.stored_length); } } else if (!/^[0-9a-f]{32}$/i.test(propertyValue)) { this.ValidationMsg = this.getResource('', 'aras_object.value_property_invalid_must_be_md5'); } break; case 'sequence': break; case 'filter list': case 'list': case 'ml_string': case 'mv_list': case 'string': if (propertyDef.stored_length < propertyValue.length) { this.ValidationMsg = this.getResource('', 'aras_object.length_properties_value_canot_be_larger', propertyDef.stored_length); break; } if (data_type == 'string' && propertyDef.pattern) { var re = new RegExp(propertyDef.pattern); if (!re.test(propertyValue)) { this.ValidationMsg = this.getResource('', 'aras_object.value_property_invalid_must_correspond_with_pattern', propertyDef.pattern); break; } } break; case 'text': break; default: throw new Error(5, this.getResource('', 'aras_object.invalid_parameter_propertydef_data_type')); break; } } if (this.ValidationMsg != '') { this.ValidationMsg += ' ' + this.getResource('', 'aras_object.edit_again'); } return this.ValidationMsg == ''; }; Aras.prototype.ValidationMsg = ''; Aras.prototype.showValidationMsg = function Aras_showValidationMsg(ownerWindow) { return this.confirm(this.ValidationMsg, ownerWindow); }; /** * Indicate whether window is closed. * Supposition: sometimes invoking of property window.closed launch exception "Permission denied". (After applying patch KB918899) */ Aras.prototype.isWindowClosed = function Aras_isWindowClosed(window) { return this.browserHelper && this.browserHelper.isWindowClosed(window); }; //+++ some api for classification +++ Aras.prototype.isClassPathRoot = function Aras_isClassPathRoot(class_path) { return '' == class_path || !class_path; }; Aras.prototype.areClassPathsEqual = function Aras_areClassPathsEqual(class_path1, class_path2) { //return this.doesClassPath1StartWithClassPath2(class_path1, class_path2, true); return class_path1 == class_path2; }; Aras.prototype.doesClassPath1StartWithClassPath2 = function Aras_doesClassPath1StartWithClassPath2(class_path1, class_path2) { if (class_path2.length > class_path1.length) { return false; } var class_path1Elements = class_path1.split('\/'); var class_path2Elements = class_path2.split('\/'); if (class_path2Elements.length > class_path1Elements.length) { return false; } for (var i = 0; i < class_path2Elements.length; i++) { if (class_path2Elements[i] != class_path1Elements[i]) { return false; } } return true; }; /* Aras.prototype.fireUnitTestsForSelectPropNdsByClassPath = function Aras_fireUnitTestsForSelectPropNdsByClassPath() { var pNms = new Array("simple classpath", "with chars to escape", "root1", "root2", "root3", "child class path", "wrong root"); //!!!before testing remove // and the second occurence of /* in the next code line //var cps = new Array("/test/simple Classpath", "/*/ /*with \\chars\\ \" to escape<<>>[[[[]:-))))B!!!!", "", "/*", "/test", "/test/simple Classpath/its child", "/WRONG ROOT/simple Classpath"); var checkSums = new Array(4, 4, 3, 3, 3, 5, 5);//numbers of nodes returned according to class paths stored in cps array. if (pNms.length!=cps.length || pNms.length!=checkSums.length) { alert("test setup is incorrect"); return; } var xml = "test"+ ""+ ""+ ""+pNms[0]+""+ ""+cps[0]+""+ ""+ ""+ ""+pNms[1]+""+ ""+ ""+ ""+ ""+pNms[2]+""+ ""+cps[2]+""+ ""+ ""+ ""+pNms[3]+""+ ""+cps[3]+""+ ""+ ""+ ""+pNms[4]+""+ ""+cps[4]+""+ ""+ ""+ ""+pNms[5]+""+ ""+cps[5]+""+ ""+ ""+ ""+pNms[6]+""+ ""+cps[6]+""+ ""+ "" var d = this.createXMLDocument(); d.loadXML(xml); var itemTypeNd = d.documentElement; var propNds; var res = "Result:\n"; var class_path; for (var i=0; i'; soapSendCaller(xmlBody, resultHanlder); }; Aras.prototype.arrayToMVListPropertyValue = function Aras_arrayToMVListPropertyValue(arr) { var tmpArr = new Array(); for (var i = 0; i < arr.length; i++) { tmpArr.push(arr[i].replace(/,/g, '\\,')); } return tmpArr.join(','); }; Aras.prototype.mvListPropertyValueToArray = function Aras_mvListPropertyValueToArray(val) { var Delimiter = ','; var EscapeString = '\\'; var tmpDelim = '#'; val = val.replace(/#/g, EscapeString + Delimiter); val = val.replace(/\\,/g, tmpDelim + tmpDelim); var tmpArr = val.split(Delimiter); var retArr = new Array(); for (var i = 0; i < tmpArr.length; i++) { retArr.push(tmpArr[i].replace(/##/g, Delimiter).replace(/\\#/g, tmpDelim)); } return retArr; }; Aras.prototype.ShowContextHelp = function Aras_ShowContextHelp(itemTypeName) { var tophelpurl = this.getTopHelpUrl(); if (tophelpurl) { if (tophelpurl.charAt(tophelpurl.length - 1) != '/') { tophelpurl += '/'; } var currItemType = this.getItemFromServerByName('ItemType', itemTypeName, 'help_item,help_url'); var tmpurl = tophelpurl + this.getSessionContextLanguageCode() + '/index.htm'; tophelpurl = WebFile.Exists(tmpurl) ? tmpurl : tophelpurl + 'en/index.htm'; var urlstring = tophelpurl; if (currItemType) { var thisHelpId = currItemType.getProperty('help_item'); var thisHelpURL = currItemType.getProperty('help_url'); var thisHelp = this.getItemById('Help', thisHelpId, 0); if (thisHelpURL != undefined && thisHelpURL != '') { urlstring += '#' + thisHelpURL; } else { if (thisHelpId != undefined && thisHelpId != '') { this.uiShowItemEx(thisHelp, undefined); return; } else { urlstring = tophelpurl; } } } window.open(urlstring); } }; Aras.prototype.UpdateFeatureTreeIfNeed = function Aras_UpdateFeatureTreeIfNeed() { if (this.isAdminUser()) { if (this.getMainWindow().arasMainWindowInfo.isFeatureTreeExpiredResult === 'True') { var license = new Licensing(this); license.UpdateFeatureTree(function(isSuccess) { if (isSuccess) { license.showState(); } else { license._showErrorPage(); } }); } } }; /** * This function is a wrapper for IomInnovator.ConsumeLicense to handle exсeptions in case when LicenseService has returned "500" http response. * Our IOM controls are hosted in the main window and are shared between other windows. So, if tearoff window calls IomInnovator.ConsumeLicense inside of try catch block and exception is occured then it appears in the main window as script error and only after that will be handled by "catch" block of tearoff window. */ Aras.prototype.ConsumeLicense = function Aras_ConsumeLicense(featureName) { var consumeLicenseResult = { isError: false, errorMessage: undefined, result: undefined }; try { consumeLicenseResult.result = this.IomInnovator.ConsumeLicense(featureName); } catch (e) { consumeLicenseResult.isError = true; consumeLicenseResult.errorMessage = e.message; } return consumeLicenseResult; }; /** * @deprecated Use this.MetadataCache.CreateCacheKey() * @returns {array} */ Aras.prototype.CreateCacheKey = function Aras_CreateCacheKey() { var key = this.IomFactory.CreateArrayList(); for (var i = 0; i < arguments.length; i++) { key.push(arguments[i]); } return key; }; Aras.prototype.ValidateXml = function Aras_ValidateXml(schemas, xml) { var xmlBody = shapeXmlBody(schemas, xml); var url = this.getBaseURL() + '/HttpHandlers/XmlValidatorHandler.ashx'; var xmlhttp = this.XmlHttpRequestManager.CreateRequest(); // search in cache var responseInCache = this.commonProperties.validateXmlCache.filter(function(obj) { return obj.key === xmlBody; }); if (responseInCache.length === 1) { return responseInCache[0].value; } else { xmlhttp.open('POST', url, false); xmlhttp.send(xmlBody); var resText = xmlhttp.responseText; var resDom = this.createXMLDocument(); resDom.loadXML(resText); // we limit the size of the cache by 100 if (this.commonProperties.validateXmlCache.length > 100) { this.commonProperties.validateXmlCache.shift(); } var cacheObject = this.newObject(); cacheObject.key = xmlBody; cacheObject.value = resDom; this.commonProperties.validateXmlCache.push(cacheObject); return resDom; } function shapeXmlBody(schemas, targetXml) { var xmlBody = []; xmlBody.push(''); for (var i = 0; i < schemas.length; i++) { var schema = schemas[i]; xmlBody.push(''); xmlBody.push(''); xmlBody.push(''); } xmlBody.push(''); xmlBody.push(''); xmlBody.push(''); xmlBody.push(''); return xmlBody.join(''); } }; Aras.prototype.getMostTopWindowWithAras = function Aras_getMostTopWindowWithAras(windowObj) { return TopWindowHelper.getMostTopWindowWithAras(windowObj); }; Aras.prototype.SsrEditorWindowId = 'BB91CEC07FF24BE5945F2E5412752E8B'; /** path.js **/ function Path() {} Path.lastException = ''; Path.combinePath = function(dirPath, fileName) { var result = ''; if (this.isMac()) { if (this.isValidFileName(fileName)) { result = dirPath + '/' + fileName; } else { throw this.lastException; } } else if (this.isWindows()) { if (this.isValidFileName(fileName)) { result = dirPath + '\\' + fileName; } else { throw this.lastException; } } return result; }; Path.isValidFileName = function(filename) { if (this.isWindows()) { var cannotStartWithDotRegEx = /^\./; if (cannotStartWithDotRegEx.test(filename)) { this.lastException = 'File name cannot start with dot: ' + filename; return false; } var winReservedNamesRegEx = /^(con|prn|aux|nul|com[0-9]|lpt[0-9]|)(\.|$)/i; if (winReservedNamesRegEx.test(filename)) { this.lastException = 'File name is reserved by OS: ' + filename; return false; } /* The following reserved characters: < (less than) > (greater than) : (colon) " (double quote) / (forward slash) \ (backslash) | (vertical bar or pipe) ? (question mark) * (asterisk) */ var reservedCharactersRegEx = /^[^\\/:\*\?"<>\|]{0,255}$/; if (!reservedCharactersRegEx.test(filename)) { this.lastException = 'Invalid file name for ' + navigator.platform + ' OS: ' + filename; return false; } return true; } else if (this.isMac()) { var fileExp = /^([^:]){1,255}$/; if (fileExp.test(filename)) { return true; } else { this.lastException = 'invalid file name for ' + navigator.platform + ' OS: ' + filename; return false; } } }; Path.isMac = function() { /* Mac - Macintosh Win -Windows X11 -Unix */ var regExp = /^Mac/; if (regExp.test(navigator.platform)) { return true; } else { return false; } }; Path.isWindows = function() { var regExp = /^Win/; if (regExp.test(navigator.platform)) { return true; } else { return false; } }; Path.isMacPath = function(path) { var pathExp = /^(\/{1}[^:]{0,255}[^\:\/]{1})$/; if (pathExp.test(path)) { return true; } else { return false; } }; Path.isWinPath = function(path) { var pathExp = /^[a-zA-Z]{1}:((\\[^:<>\\\/\?\*\|\"\^\s]){1}[^:<>\\\/\?\*\|\"\^]{0,255})*$/; if (pathExp.test(path)) { return true; } else { return false; } }; Path.isValidFilePath = function(path) { if (this.isMac()) { if (this.isMacPath(path)) { return true; } else { return false; } } else if (this.isWindows()) { if (this.isWinPath(path)) { return true; } else { return false; } } else { return false; } }; Path.getInvalidFileNameChars = function() { var result = []; if (this.isMac()) { result.push(':'); } else if (this.isWindows()) { result.push(':'); result.push('\\'); result.push('\/'); result.push('?'); result.push('^'); result.push('"'); result.push('*'); result.push('>'); result.push('<'); result.push('|'); } return result; }; Path.getFileName = function(filePath) { if (filePath) { var pathSeparator = Path.isWindows() ? '\\' : '\/'; return filePath.substring(filePath.lastIndexOf(pathSeparator) + 1, filePath.length); } }; Path.getDirectoryName = function(filePath) { if (filePath) { var pathSeparator = Path.isWindows() ? '\\' : '\/'; return filePath.substring(0, filePath.lastIndexOf(pathSeparator) + 1); } }; /** MetadataCache.js **/ function MetadataCache(aras) { var scopeVariable = {}; scopeVariable.aras = aras; scopeVariable.cache = aras.IomFactory.CreateItemCache(); scopeVariable.cacheVariable = null; scopeVariable.preloadDates = {}; scopeVariable.typeInfo = { ItemType: { typeKey: '3EC33FE3B3C333333E33CF3D33AC33C3', getDatesMethod: 'GetItemTypesMetadata', getMethod: 'GetItemType' }, RelationshipType: { typeKey: '76381576909211E296CE0B586188709B', getDatesMethod: 'GetRelationshipTypesMetadata', getMethod: 'GetRelationshipType' }, Form: { typeKey: '2EC22FE2B2C222222E22CF2D22AC22C2', getDatesMethod: 'GetFormsMetadata', getMethod: 'GetForm' }, Method: { typeKey: '6E02B71E7A6E4FF38A9866C27837906D', getDatesMethod: 'GetClientMethodsMetadata', getMethod: 'GetClientMethod' }, GetAllClientMethodsMetadata: { typeKey: 'F29AC97834104075AA42EE4984AEDC68', getDatesMethod: 'GetAllClientMethodsMetadata', getMethod: 'GetAllClientMethods' }, List: { typeKey: '4EC44FE4B4C444444E44CF4D44AC44C4', getDatesMethod: 'GetListsMetadata', getMethod: 'GetList' }, Identity: { typeKey: '36F92EC1A0CF43C1801F50510D86FEAD', getDatesMethod: 'GetIdentitiesMetadata', getMethod: 'GetIdentity' }, GetLastModifiedSearchModeDate: { typeKey: 'BAD4F21DBF1C41B8B14BD3060FF5E8F5', getDatesMethod: 'GetLastModifiedSearchModeDate', getMethod: 'GetSearchModes' }, ConfigurableUI: { typeKey: '64494CAB13F846A0AD19216DBC3E1980', getDatesMethod: 'GetConfigurableUiMetadata', getMethod: 'GetConfigurableUi' }, PresentationConfiguration: { typeKey: 'BDE98AE974C24A759AF406C526EFD1A7', getDatesMethod: 'GetPresentationConfigurationMetadata', getMethod: 'GetPresentationConfiguration' }, CommandBarSection: { typeKey: '7962E50B66E44BCC9BEDC3ECAE899455', getDatesMethod: 'GetCommandBarSectionMetadata', getMethod: 'GetCommandBarSection' }, // note that it returns zero-filled (GU)ID if there's no cmf_ContentType for given linked_document_type ContentTypeByDocumentItemType: { typeKey: 'E76EC697E76248CC8D08FE56C1DB880B', getDatesMethod: 'GetContentTypeByDocumentItemTypeMetadata', getMethod: 'GetContentTypeByDocumentItemType' } }; scopeVariable.findTypeInfoNameById = function(id) { var res; for (var prop in this.typeInfo) { if (this.typeInfo.hasOwnProperty(prop)) { if (this.typeInfo[prop].typeKey === id) { res = prop; break; } } } return res; }; scopeVariable.getPreloadDate = function(name) { if (!this.preloadDates[name]) { this.updatePreloadDates(); } return this.preloadDates[name]; }; scopeVariable._getMostTopWindowWithAras = function() { return window; }; scopeVariable.extractDateFromCache = function(criteriaValue, criteriaType, itemType) { var id = criteriaType == 'id' ? criteriaValue : this.extractIdByName(criteriaValue, itemType); return this.extractDateById(id, itemType); }; scopeVariable.extractIdByName = function(name, itemType) { var key = this.createCacheKey('MetadataIdsByNameInLowerCase', this.typeInfo[itemType].typeKey); var container = this.getItem(key); if (!container) { this.refreshMetadata(itemType); container = this.getItem(key); } return container ? container.content[name.toLowerCase()] : ''; }; scopeVariable.extractNameById = function(id, itemType) { var key = this.createCacheKey('MetadataNamesById', this.typeInfo[itemType].typeKey); var container = this.getItem(key); if (!container) { this.refreshMetadata(itemType); container = this.getItem(key); } return container ? container.content[id] : ''; }; scopeVariable.extractDateById = function(id, itemType) { var key = this.createCacheKey('MetadataDatesById', this.typeInfo[itemType].typeKey); var container = this.getItem(key); if (!container) { this.refreshMetadata(itemType); container = this.getItem(key); } var date = container ? container.content[id] : ''; if (!date) { var currentTime = new Date(); date = currentTime.getFullYear() + '-' + currentTime.getMonth() + '-' + currentTime.getDate() + 'T' + currentTime.getHours() + ':' + currentTime.getMinutes() + ':' + currentTime.getSeconds() + '.00'; } return date; }; scopeVariable.refreshMetadata = function(itemType, async, callback) { var methodName = this.typeInfo[itemType].getDatesMethod; var typeKey = this.typeInfo[itemType].typeKey; this.removeById(typeKey, true); var self = this; var requestURL = this.generateRequestURL(methodName, '', this.getPreloadDate(itemType)); this.sendSoapInternal(methodName, requestURL, async ? true : false).then(function(res) { var finalRetVal = res; self.refreshMetadataInternal(finalRetVal, typeKey); if (callback) { callback(); } }); }; scopeVariable.refreshMetadataInternal = function(res, typeKey) { if (res.getFaultCode() !== 0) { this.aras.AlertError(res); return; } var evalString = 'var metadataItems=' + res.getResult().text; eval(evalString); // jshint ignore: line var idsByName = {}; var namesById = {}; var datesById = {}; for (var i = 0; i < metadataItems.length; i++) { var m = metadataItems[i]; idsByName[m.name.toLowerCase()] = m.id; namesById[m.id] = m.name; datesById[m.id] = m.modified_on; } var key; var container; key = this.createCacheKey('MetadataIdsByNameInLowerCase', typeKey); container = this._getMostTopWindowWithAras().aras.IomFactory.CreateCacheableContainer(idsByName, idsByName); this.setItem(key, container); key = this.createCacheKey('MetadataNamesById', typeKey); container = this._getMostTopWindowWithAras().aras.IomFactory.CreateCacheableContainer(namesById, namesById); this.setItem(key, container); key = this.createCacheKey('MetadataDatesById', typeKey); container = this._getMostTopWindowWithAras().aras.IomFactory.CreateCacheableContainer(datesById, datesById); this.setItem(key, container); }; scopeVariable.getSoapFromServerOrFromCache = function(methodName, queryParameters) { var requestURL = this.generateRequestURL(methodName, queryParameters); var res = this.getSoapFromCache(methodName, requestURL); if (!res) { res = this.sendSoap(methodName, requestURL); if (res.getFaultCode() === 0) { this.putSoapToCache(methodName, requestURL, res); } } return res; }; scopeVariable.getSoapFromCache = function(methodName, requestURL) { var key = this.createCacheKey('MetadataServiceCache', requestURL); var container = this.getItem(key); return container ? container.content : undefined; }; scopeVariable.putSoapToCache = function(methodName, requestURL, content) { var key = this.createCacheKey('MetadataServiceCache', requestURL); var container = this._getMostTopWindowWithAras().aras.IomFactory.CreateCacheableContainer(content, content); this.setItem(key, container); }; scopeVariable.generateRequestURL = function(methodName, queryParameters, cacheKey) { function appendParameter(param, value) { if (param !== '') { param += '&'; } param += value; return param; } var soapHeaders = this.aras.getHttpHeadersForSoapMessage(); queryParameters = appendParameter(queryParameters, 'database=' + soapHeaders.DATABASE); queryParameters = appendParameter(queryParameters, 'user=' + soapHeaders.AUTHUSER); //Language Code (not Locale!!!) is only necessary value for I18N queryParameters = appendParameter(queryParameters, 'lang=' + this.aras.getSessionContextLanguageCode()); queryParameters = appendParameter(queryParameters, 'cache=' + (cacheKey ? cacheKey : '0')); return this._getMostTopWindowWithAras().aras.getServerBaseURL() + 'MetaData.asmx/' + methodName + (queryParameters ? '?' + queryParameters : ''); }; scopeVariable.sendSoap = function(methodName, requestURL) { var finalRetVal; this.sendSoapInternal(methodName, requestURL, false).then(function(res) { finalRetVal = res; }); return finalRetVal; }; scopeVariable.sendSoapAsync = function(methodName, requestURL) { return this.sendSoapInternal(methodName, requestURL, true); }; scopeVariable.sendSoapInternal = function(methodName, requestURL, async) { var aras = this.aras; var promiseFunction = function(resolve) { var finalRetVal; ArasModules.soap('', { url: requestURL, method: methodName, restMethod: 'GET', async: async }).then(function(resultNode) { var text; if (resultNode.ownerDocument) { var doc = resultNode.ownerDocument; text = doc.xml || (new XMLSerializer()).serializeToString(doc); } else { text = resultNode; } finalRetVal = new SOAPResults(aras, text, false); resolve(finalRetVal); }, function(xhr) { finalRetVal = new SOAPResults(aras, xhr.responseText, false); resolve(finalRetVal); }); }; var promise; if (!async) { promise = new ArasModules.SyncPromise(promiseFunction); } else { promise = new Promise(promiseFunction); } return promise; }; scopeVariable.getItemType = function(criteriaValue, criteriaName) { var itemType = 'ItemType'; var id = criteriaName == 'id' ? criteriaValue : this.extractIdByName(criteriaValue, itemType); var date = this.extractDateById(id, itemType); var queryParameters = 'id=' + id + '&date=' + date; var methodName = this.typeInfo.ItemType.getMethod; var requestURL = this.generateRequestURL(methodName, queryParameters); var res = this.getSoapFromCache(methodName, requestURL); if (!res) { res = this.sendSoap(methodName, requestURL); if (res.getFaultCode() === 0) { this.putSoapToCache(methodName, requestURL, res); var rels = res.results.selectNodes(this.aras.XPathResult() + '/Item/Relationships/Item[@type="RelationshipType"]'); for (var i = 0; i < rels.length; i++) { var rel = rels[i]; var relId = this.aras.getItemProperty(rel, 'id'); var relDate = this.extractDateById(relId, 'RelationshipType'); var relQueryParameters = 'id=' + relId + '&date=' + relDate; var relRequestURL = this.generateRequestURL(this.typeInfo.RelationshipType.getMethod, relQueryParameters); var relRes = new SOAPResults(this.aras, '' + rel.xml + ''); this.putSoapToCache(this.typeInfo.RelationshipType.getMethod, relRequestURL, relRes); } } } return res; }; scopeVariable.stdGet = function(typeInfo, itemType, criteriaValue, criteriaName) { var id = criteriaName == 'id' ? criteriaValue : this.extractIdByName(criteriaValue, itemType); var date = this.extractDateById(id, itemType); var queryParameters = 'id=' + id + '&date=' + date; return this.getSoapFromServerOrFromCache(typeInfo.getMethod, queryParameters); }; scopeVariable.getRelationshipType = function(criteriaValue, criteriaName) { return this.stdGet(this.typeInfo.RelationshipType, 'RelationshipType', criteriaValue, criteriaName); }; scopeVariable.getForm = function(criteriaValue, criteriaName) { return this.stdGet(this.typeInfo.Form, 'Form', criteriaValue, criteriaName); }; scopeVariable.getClientMethod = function(criteriaValue, criteriaName) { var methodNd = this.getClientMethodNd(criteriaValue, criteriaName); if (methodNd) { return new SOAPResults(this.aras,'' + methodNd.xml + ''); } return this.stdGet(this.typeInfo.Method, 'Method', criteriaValue, criteriaName); }; scopeVariable.getClientMethodNd = function(criteriaValue, criteriaName) { var allMethods = this.getAllClientMethods(); var methodId; if (criteriaName != 'id') { var idsByNames = this.getItem(this.createCacheKey('MetadataClientMethodsIdsByNames', '307C85932F514F70A81B7A09376A8D6C')); if (!idsByNames) { return; } methodId = idsByNames[criteriaValue.toLowerCase()]; } else { methodId = criteriaValue; } return allMethods[methodId]; }; scopeVariable.getAllClientMethods = function() { var typeKey = this.typeInfo.GetAllClientMethodsMetadata.typeKey; var dateMethodName = this.typeInfo.GetAllClientMethodsMetadata.getDatesMethod; var methodName = this.typeInfo.GetAllClientMethodsMetadata.getMethod; var date = this.getLastModifiedItemDateFromCache('MetadataLastModifiedClientMethodsDate', typeKey, dateMethodName); var requestURL = this.generateRequestURL(methodName, 'date=' + date); var res = this.getSoapFromCache(methodName, requestURL); if (!res) { res = this.sendSoap(methodName, requestURL); var methodDict = {}; if (res.getFaultCode() === 0) { var nodes = res.getResult().selectNodes(this.aras.XPathResult('/Item[@type=\'Method\']')); if (nodes.length > 0) { var idsByNames = {}; for (var i = 0; i < nodes.length; i++) { var id = nodes[i].getAttribute('id'); idsByNames[nodes[i].selectSingleNode('name').text.toLowerCase()] = id; methodDict[id] = nodes[i]; } this.putSoapToCache(methodName, requestURL, methodDict); var cacheKey = this.createCacheKey('MetadataClientMethodsIdsByNames', '307C85932F514F70A81B7A09376A8D6C'); this.setItem(cacheKey, idsByNames); } } res = methodDict; } return res; }; scopeVariable.getQueryParametersForGetCUI = function(context) { // date is single maximal for all CUI config, no any per id/context division var date = this.extractDateById('83F725B93D9840E7A4B139E40DCDA8C4', 'ConfigurableUI'); var complexId = 'item_type_id=' + context.item_type_id + '&location_name=' + context.location_name + '&item_classification=' + context.item_classification; var queryParameters = 'id=' + escape(complexId) + '&date=' + date; return queryParameters; }; scopeVariable.getConfigurableUi = function(context) { var queryParameters = this.getQueryParametersForGetCUI(context); return this.getSoapFromServerOrFromCache(this.typeInfo.ConfigurableUI.getMethod, queryParameters); }; scopeVariable.getConfigurableUiAsync = function(context) { var queryParameters = this.getQueryParametersForGetCUI(context); var methodName = this.typeInfo.ConfigurableUI.getMethod; var requestURL = this.generateRequestURL(methodName, queryParameters); var res = this.getSoapFromCache(methodName, requestURL); if (!res) { return this.sendSoapAsync(methodName, requestURL).then(function(result) { if (result.getFaultCode() === 0) { this.putSoapToCache(methodName, requestURL, result); } return result; }.bind(this)); } return Promise.resolve(res); }; scopeVariable.stdGetById = function(typeInfo, itemType, id) { var date = this.extractDateById(id, itemType); return this.getSoapFromServerOrFromCache(typeInfo.getMethod, 'id=' + id + '&date=' + date); }; scopeVariable.getPresentationConfiguration = function(id) { return this.stdGetById(this.typeInfo.PresentationConfiguration, 'PresentationConfiguration', id); }; scopeVariable.getCommandBarSection = function(id) { return this.stdGetById(this.typeInfo.CommandBarSection, 'CommandBarSection', id); }; scopeVariable.getContentTypeByDocumentItemType = function(id) { return this.stdGetById(this.typeInfo.ContentTypeByDocumentItemType, 'ContentTypeByDocumentItemType', id); }; scopeVariable.getList = function(listIds, filterListIds) { //listIds - list of ids for which Value type is needed //filterListIds - list of ids for which Filter Value type is needed var queryParameters; //variable for request params var response; //variable with response to check content var methodName = this.typeInfo.List.getMethod; var result = ''; var i; //check if list isn't empty if (listIds.length !== 0) { //for each single element in collection request for metadata to service for (i = 0; i < listIds.length; i++) { queryParameters = 'id=' + listIds[i] + '&valType=value&date=' + this.extractDateById(listIds[i], 'List'); response = this.getSoapFromServerOrFromCache(methodName, queryParameters); //if fault code was returned we return object with this fault if (response.getFaultCode() !== 0) { return response; } result += response.getResultsBody(); } } if (filterListIds.length !== 0) { //for each single element in collection request for metadata to service for (i = 0; i < filterListIds.length; i++) { queryParameters = 'id=' + filterListIds[i] + '&valType=filtervalue&date=' + this.extractDateById(filterListIds[i], 'List'); response = this.getSoapFromServerOrFromCache(methodName, queryParameters); //if fault code was returned we return object with this fault if (response.getFaultCode() !== 0) { return response; } result += response.getResultsBody(); } } result += ''; result = new SOAPResults(this.aras, result); return result; }; scopeVariable.getIdentity = function(criteriaValue, criteriaName) { return this.stdGet(this.typeInfo.Identity, 'Identity', criteriaValue, criteriaName); }; scopeVariable.getSearchModes = function() { var typeKey = this.typeInfo.GetLastModifiedSearchModeDate.typeKey; var dateMethodName = this.typeInfo.GetLastModifiedSearchModeDate.getDatesMethod; var methodName = this.typeInfo.GetLastModifiedSearchModeDate.getMethod; var date = this.getLastModifiedItemDateFromCache('MetadataLastModifiedSearchModeDate', typeKey, dateMethodName); var queryParameters = 'date=' + date; var res = this.getSoapFromServerOrFromCache(methodName, queryParameters); if (res.getFaultCode() !== 0) { this.aras.AlertError(res); var resIOMError = this.aras.newIOMInnovator().newError(res.getFaultString()); return resIOMError; } return res.getResult(); }; scopeVariable.getLastModifiedItemDateFromCache = function(cacheKey, typeKey, dateMethodName) { var keyDateItems = this.createCacheKey(cacheKey, typeKey); var date = this.getItem(keyDateItems); if (!date) { date = this.getLastModifiedItemDateFromServer(dateMethodName); this.removeItemById(typeKey, true); this.setItem(keyDateItems, date); } return date; }; scopeVariable.getLastModifiedItemDateFromServer = function(dateMethodName) { return this.getPreloadDate(dateMethodName); }; scopeVariable.updatePreloadDates = function(metadataDates) { if (!metadataDates) { metadataDates = aras.getMainWindow().arasMainWindowInfo.GetAllMetadataDates; } for (var i = 0; i < metadataDates.childNodes.length; i++) { this.preloadDates[metadataDates.childNodes[i].nodeName] = metadataDates.childNodes[i].text; } }; scopeVariable.deleteListDatesFromCache = function() { this.removeItemById(this.typeInfo.List.typeKey); }; scopeVariable.deleteFormDatesFromCache = function() { this.removeItemById(this.typeInfo.Form.typeKey); }; scopeVariable.deleteClientMethodDatesFromCache = function() { this.removeItemById(this.typeInfo.Method.typeKey); }; scopeVariable.deleteAllClientMethodsDatesFromCache = function() { this.removeItemById(this.typeInfo.GetAllClientMethodsMetadata.typeKey); }; scopeVariable.deleteITDatesFromCache = function() { this.removeItemById(this.typeInfo.ItemType.typeKey); }; scopeVariable.deleteRTDatesFromCache = function() { this.removeItemById(this.typeInfo.RelationshipType.typeKey); }; scopeVariable.deleteIdentityDatesFromCache = function() { this.removeItemById(this.typeInfo.Identity.typeKey); }; scopeVariable.deleteConfigurableUiDatesFromCache = function() { this.removeItemById(this.typeInfo.ConfigurableUI.typeKey); }; scopeVariable.deletePresentationConfigurationDatesFromCache = function() { this.removeItemById(this.typeInfo.PresentationConfiguration.typeKey); }; scopeVariable.deleteCommandBarSectionDatesFromCache = function() { this.removeItemById(this.typeInfo.CommandBarSection.typeKey); }; scopeVariable.deleteContentTypeByDocumentItemTypeDatesFromCache = function() { this.removeItemById(this.typeInfo.ContentTypeByDocumentItemType.typeKey); }; scopeVariable.deleteSearchModeDatesFromCache = function() { this.removeItemById(this.typeInfo.GetLastModifiedSearchModeDate.typeKey); }; scopeVariable.getItem = function(key) { return this.cache.GetItem(key); }; scopeVariable.removeById = function(id, doNotClearDate) { this.cache.RemoveById(id); if (!doNotClearDate) { var typeInfoName = this.findTypeInfoNameById(id); delete this.preloadDates[typeInfoName]; } }; scopeVariable.setItem = function(key, item) { this.cache.SetItem(key, item); }; scopeVariable.getItemsById = function(key) { return this.cache.GetItemsById(key); }; scopeVariable.clearCache = function() { this.cache.ClearCache(); this.preloadDates = {}; this.updatePreloadDates(); }; //This function accepts any number of parameters scopeVariable.createCacheKey = function() { var key = aras.IomFactory.CreateArrayList(); for (var i = 0; i < arguments.length; i++) { key.add(arguments[i]); } return key; }; scopeVariable.removeItemById = function(id) { var mainArasObj = aras.getMainArasObject(); if (mainArasObj && mainArasObj != aras) { mainArasObj.MetadataCache.RemoveItemById(id); } else { this.removeById(id); } }; return { GetItemType: function(criteriaValue, criteriaName) { return scopeVariable.getItemType(criteriaValue, criteriaName); }, GetRelationshipType: function(criteriaValue, criteriaName) { return scopeVariable.getRelationshipType(criteriaValue, criteriaName); }, GetForm: function(criteriaValue, criteriaName) { return scopeVariable.getForm(criteriaValue, criteriaName); }, GetClientMethod: function(criteriaValue, criteriaName) { return scopeVariable.getClientMethod(criteriaValue, criteriaName); }, GetClientMethodNd: function(criteriaValue, criteriaName) { return scopeVariable.getClientMethodNd(criteriaValue, criteriaName); }, GetAllClientMethods: function() { return scopeVariable.getAllClientMethods(); }, GetList: function(listIds, filterListIds) { return scopeVariable.getList(listIds, filterListIds); }, GetApplicationVersion: function() { var requestUrl = scopeVariable.generateRequestURL('GetApplicationVersion', ''); return scopeVariable.sendSoap('GetApplicationVersion', requestUrl); }, GetIdentity: function(criteriaValue, criteriaName) { return scopeVariable.getIdentity(criteriaValue, criteriaName); }, GetSearchModes: function() { return scopeVariable.getSearchModes(); }, GetItemTypeName: function(id) { return scopeVariable.extractNameById(id, 'ItemType'); }, GetRelationshipTypeName: function(id) { return scopeVariable.extractNameById(id, 'RelationshipType'); }, GetFormName: function(id) { return scopeVariable.extractNameById(id, 'Form'); }, GetItemTypeId: function(name) { return scopeVariable.extractIdByName(name, 'ItemType'); }, GetRelationshipTypeId: function(name) { return scopeVariable.extractIdByName(name, 'RelationshipType'); }, GetFormId: function(name) { return scopeVariable.extractIdByName(name, 'Form'); }, ExtractDateFromCache: function(criteriaValue, criteriaType, itemType) { return scopeVariable.extractDateFromCache(criteriaValue, criteriaType, itemType); }, DeleteListDatesFromCache: function() { return scopeVariable.deleteListDatesFromCache(); }, DeleteFormDatesFromCache: function() { return scopeVariable.deleteFormDatesFromCache(); }, DeleteClientMethodDatesFromCache: function() { return scopeVariable.deleteClientMethodDatesFromCache(); }, DeleteAllClientMethodsDatesFromCache: function() { return scopeVariable.deleteAllClientMethodsDatesFromCache(); }, DeleteITDatesFromCache: function() { return scopeVariable.deleteITDatesFromCache(); }, DeleteRTDatesFromCache: function() { return scopeVariable.deleteRTDatesFromCache(); }, DeleteIdentityDatesFromCache: function() { return scopeVariable.deleteIdentityDatesFromCache(); }, DeleteConfigurableUiDatesFromCache: function() { return scopeVariable.deleteConfigurableUiDatesFromCache(); }, DeletePresentationConfigurationDatesFromCache: function() { return scopeVariable.deletePresentationConfigurationDatesFromCache(); }, DeleteCommandBarSectionDatesFromCache: function() { return scopeVariable.deleteCommandBarSectionDatesFromCache(); }, DeleteContentTypeByDocumentItemTypeDatesFromCache: function() { return scopeVariable.deleteContentTypeByDocumentItemTypeDatesFromCache(); }, DeleteSearchModeDatesFromCache: function() { return scopeVariable.deleteSearchModeDatesFromCache(); }, GetItem: function(key) { return scopeVariable.getItem(key); }, RemoveById: function(id) { return scopeVariable.removeById(id); }, SetItem: function(key, item) { return scopeVariable.setItem(key, item); }, GetItemsById: function(key) { return scopeVariable.getItemsById(key); }, ClearCache: function() { return scopeVariable.clearCache(); }, CreateCacheKey: function() { return scopeVariable.createCacheKey.apply(null, arguments); }, RemoveItemById: function(id) { return scopeVariable.removeItemById(id); }, GetConfigurableUi: function(context) { return scopeVariable.getConfigurableUi(context); }, GetConfigurableUiAsync: function(context) { return scopeVariable.getConfigurableUiAsync(context); }, GetPresentationConfiguration: function(id) { return scopeVariable.getPresentationConfiguration(id); }, GetCommandBarSection: function(id) { return scopeVariable.getCommandBarSection(id); }, GetContentTypeByDocumentItemType: function(id) { ///Zero-filled (GU)ID if there's no cmf_ContentType for given linked_document_type return scopeVariable.getContentTypeByDocumentItemType(id); }, RefreshMetadata: function(itemTypeName, async, callback) { return scopeVariable.refreshMetadata(itemTypeName, async, callback); }, UpdatePreloadDates: function(metadataDates) { return scopeVariable.updatePreloadDates(metadataDates); } }; } /** iom.js **/ function IOMCache(parentArasObj) { this.arasObj = parentArasObj; } IOMCache.prototype.apply = function IOMCacheApply(itemNd) { if (!itemNd) { return null; } var itemID = itemNd.getAttribute('id'); var itemTypeName = itemNd.getAttribute('type'); var itemAction = itemNd.getAttribute('action'); if (itemAction === null) { itemAction = ''; } var win = this.arasObj.uiFindWindowEx2(itemNd); //special checks for the item of ItemType type // tag in itemNd required for next call var res; if (itemTypeName == 'ItemType') { res = this.arasObj.checkItemType(itemNd, win); } else { res = true; } if (!res) { return null; } if (itemTypeName) { if (itemAction == 'delete') { this.arasObj.deleteItem(itemTypeName, itemID, true); return null; } else if (itemAction == 'purge') { this.arasObj.purgeItem(itemTypeName, itemID, true); return null; } } //general checks for the item to be saved: all required parameters should be set if (itemTypeName) { res = this.arasObj.checkItem(itemNd, win); } else { res = true; } if (!res) { return null; } res = null; var backupCopy = itemNd; var oldParent = backupCopy.parentNode; itemNd = itemNd.cloneNode(true); this.arasObj.prepareItem4Save(itemNd); var isTemp = this.arasObj.isTempEx(itemNd); if (itemNd.getAttribute('action') == 'add') { if (itemTypeName == 'RelationshipType') { if (!itemNd.selectSingleNode('relationship_id/Item')) { var rsItemNode = itemNd.selectSingleNode('relationship_id'); if (rsItemNode) { var rs = this.arasObj.getItemById('', rsItemNode.text, 0); if (rs) { rsItemNode.text = ''; rsItemNode.appendChild(rs.cloneNode(true)); } } } var tmp001 = itemNd.selectSingleNode('relationship_id/Item'); if (tmp001 && this.arasObj.getItemProperty(tmp001, 'name') === '') { this.arasObj.setItemProperty(tmp001, 'name', this.arasObj.getItemProperty(itemNd, 'name')); } } } var files = itemNd.selectNodes('descendant-or-self::Item[@type="File" and (@action="add" or @action="update")]'); if (files.length === 0) { res = this.arasObj.soapSend('ApplyItem', itemNd.xml); if (res.getFaultCode() !== 0) { return null; } res = res.results.selectSingleNode(this.arasObj.XPathResult('/Item')); } else { res = this.arasObj.sendFilesWithVaultApplet(itemNd, 'Sending of File to Vault...'); }//else if (files.length==0) if (!res) { return null; } res.setAttribute('levels', '0'); var newID = res.getAttribute('id'); this.arasObj.updateInCacheEx(backupCopy, res); if (itemTypeName == 'RelationshipType') { var relationshipId = this.arasObj.getItemProperty(itemNd, 'relationship_id'); if (relationshipId) { this.arasObj.removeFromCache(relationshipId); } this.arasObj.commonProperties.formsCacheById = this.arasObj.newObject(); } else if (itemTypeName == 'ItemType') { var itemName = this.arasObj.getItemProperty(itemNd, 'name'); this.arasObj.deletePropertyFromObject(this.arasObj.sGridsSetups, itemName); this.arasObj.commonProperties.formsCacheById = this.arasObj.newObject(); } if (oldParent) { res = oldParent.selectSingleNode('Item[@id="' + newID + '"]'); } else { res = this.arasObj.getFromCache(newID); } if (!res) { return null; } if (newID != itemID) { var itms = this.arasObj.getAffectedItems(itemNd.getAttribute('type'), newID); if (itms) { for (var i = 0; i < itms.length; i++) { var itm = itms[i]; var itmID = itm.getAttribute('id'); var affectedItm = this.arasObj.getItemById('', itmID, 0); if (affectedItm) { if (affectedItm.getAttribute('levels') === null) { affectedItm.setAttribute('levels', 1); } var tmpRes = this.arasObj.loadItems(itm.getAttribute('type'), 'id="' + itmID + '"', affectedItm.getAttribute('levels')); if (!tmpRes) { continue; } if (this.arasObj.uiFindWindowEx[itmID]) { setTimeout('TopWindowHelper.getMostTopWindowWithAras(window).aras.uiReShowItem(\'' + itmID + '\',\'' + itmID + '\');', 100); } } } } } return res; }; function Innovator() { return top.aras.newIOMInnovator(); } function Item(itemTypeName, action, mode) { return top.aras.IomInnovator.newItem(itemTypeName, action); } function AuthenticationBrokerClient() { } AuthenticationBrokerClient.prototype.GetFileDownloadToken = function AuthenticationBrokerClientGetFileDownloadToken(fileId) { var innovatorUrl = TopWindowHelper.getMostTopWindowWithAras(window).aras.getServerBaseURL(); var result = GetSynchronousJSONResponse(innovatorUrl + 'AuthenticationBroker.asmx/GetFileDownloadToken', '{"param":{"fileId":"' + fileId + '"}}'); var evalMethod = window.eval; result = evalMethod('(' + result + ')'); return result.d; }; AuthenticationBrokerClient.prototype.GetFilesDownloadTokens = function AuthenticationBrokerClientGetFilesDownloadTokens(fileIds) { var body = '{"parameters":['; for (var i = 0; i < fileIds.count; i++) { body += '{"__type":"FileDownloadParameters","fileId":"' + fileIds(i) + '"},'; } body = body.slice(0, body.length - 1) + ']}'; var innovatorUrl = TopWindowHelper.getMostTopWindowWithAras(window).aras.getServerBaseURL(); var result = GetSynchronousJSONResponse(innovatorUrl + 'AuthenticationBroker.asmx/GetFilesDownloadTokens', body); var evalMethod = window.eval; result = evalMethod('(' + result + ')'); result = result.d; var list = TopWindowHelper.getMostTopWindowWithAras(window).aras.IomFactory.CreateArrayList(); for (var j = 0, count = result.length - 1; j < count; j++) { list.Add(result[j]); } return list; }; function LicenseManagerWebServiceClient() { this.aras = TopWindowHelper.getMostTopWindowWithAras(window).aras; this.actionNamespace = this.aras.arasService.actionNamespace; this.iServiceName = this.aras.arasService.serviceName; this.licenseServiceUrl = this.aras.getServerBaseURL() + 'Licensing.asmx/'; } LicenseManagerWebServiceClient.prototype.ConsumeLicense = function(featureName) { // don't used soap because request body isn't XML var xhr = new XMLHttpRequest(); var methodName = 'ConsumeLicense'; var url = this.licenseServiceUrl + methodName; xhr.open('POST', url, false); var additionalHeaders = this.aras.getHttpHeadersForSoapMessage(methodName); Object.keys(additionalHeaders).forEach(function(header) { xhr.setRequestHeader(header, additionalHeaders[header]); }); xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=utf-8'); xhr.send('featureName=' + encodeURIComponent(featureName)); if (xhr.status !== 200) { throw new Error(xhr.responseText); } var doc = this.aras.createXMLDocument(); doc.loadXML(xhr.responseText); return doc.documentElement.text; }; function GetSynchronousJSONResponse(url, postData) { var xmlhttp = new XMLHttpRequest(); url = url + '?rnd=' + Math.random(); // to be ensure non-cached version xmlhttp.open('POST', url, false); xmlhttp.setRequestHeader('Content-Type', 'application/json; charset=utf-8'); var headers = TopWindowHelper.getMostTopWindowWithAras(window).aras.getHttpHeadersForSoapMessage('GetFileDownloadToken'); for (var hName in headers) { xmlhttp.setRequestHeader(hName, headers[hName]); } xmlhttp.send(postData); return xmlhttp.responseText; } /** vars_storage.js **/ function VarsStorageClass() { this.unknownStorage = {}; } VarsStorageClass.prototype.getVariable = function VarsStorageClassGetVariable(varName) { var res = this.unknownStorage[varName]; return res; }; VarsStorageClass.prototype.setVariable = function VarsStorageClassSetVariable(varName, varValue) { if (typeof (varValue) != 'string' && varValue !== null) { varValue = varValue.toString(); } this.unknownStorage[varName] = varValue; }; /** user_notifications.js **/ function UserNotificationContainer(notification_control) { if (!notification_control) { throw new Error(1, 'ArgumentException: notification_control can\'t be undefined'); } this.NotificationControl = notification_control; this.CheckInterval = null; this.CheckTimeout = null; this.constAcknowledge = 'Acknowledge'; this.constClose = 'Close'; this.url = parent.aras.getInnovatorUrl() + 'NotificationServer/UserNotifications/ProxyPage.aspx'; this.UpdateInfoDom = null; this.PopupParametersArray = []; var variable = parent.aras.commonProperties.MessageCheckInterval; if (variable) { this.CheckInterval = variable; } if (!this.CheckInterval) { parent.aras.AlertError(parent.aras.getResource('', 'user_notifications.failed_get_interval_variable'), '', ''); return; } this.CheckTimeout = setTimeout(function() { parent.aras.UserNotification.StartIterativeUpdateMessageCollection(); }, this.CheckInterval); } UserNotificationContainer.prototype.AddMessage = function UserNotificationContainer_AddMessage(id, text, image, messageItem) { this.NotificationControl.AddOrUpdate(id, text, image, messageItem); }; UserNotificationContainer.prototype.RemoveMessage = function UserNotificationContainer_RemoveMessage(id) { return this.NotificationControl.Remove(id); }; UserNotificationContainer.prototype.ClearCollection = function UserNotificationContainer_ClearCollection() { this.NotificationControl.Clear(); }; UserNotificationContainer.prototype.MakeAllMessagesOld = function UserNotificationContainer_MakeAllMessagesOld() { this.NotificationControl.MakeOld(); }; UserNotificationContainer.prototype.ClearOldMessages = function UserNotificationContainer_ClearOldMessages() { this.NotificationControl.ClearOld(); }; UserNotificationContainer.prototype.GetMessageQuery = function UserNotificationContainer_GetMessageQuery() { var query_dom = parent.aras.createXMLDocument(); var dtObj = new Date(); var yyyy = String(dtObj.getFullYear()); var h = { MM: String('0' + (dtObj.getMonth() + 1)), dd: String('0' + dtObj.getDate()), hh: String('0' + dtObj.getHours()), mm: String('0' + dtObj.getMinutes()), ss: String('0' + dtObj.getSeconds()) }; for (var k in h) { h[k] = h[k].substr(h[k].length - 2); } var r = yyyy + '-' + h.MM + '-' + h.dd + 'T' + h.hh + ':' + h.mm + ':' + h.ss; query_dom.loadXML(''); var currentUserIDNode = query_dom.createElement('CurrentUserID'); var dateTimeNode = query_dom.createElement('DateTime'); currentUserIDNode.text = parent.aras.getCurrentUserID(); dateTimeNode.text = r; query_dom.documentElement.appendChild(currentUserIDNode); query_dom.documentElement.appendChild(dateTimeNode); return query_dom.documentElement.xml; }; UserNotificationContainer.prototype.AsyncCheckNewMessages = function UserNotificationContainer_AsyncCheckNewMessages(getCollectionCallback) { var soapController = new SoapController(resultCallbackHandler); soapController.NotificationContainer = this; var query = this.GetMessageQuery(); var soap_res = parent.aras.soapSend('GetNotifications', query, this.url, null, soapController); function resultCallbackHandler(soap_res) { if (this.NotificationContainer) { var message_collection = this.NotificationContainer.ProcessSoapResult(soap_res); getCollectionCallback(this.NotificationContainer, message_collection); } } }; UserNotificationContainer.prototype.SyncGetMessageCollection = function UserNotificationContainer_SyncGetMessageCollection() { var query = this.GetMessageQuery(); var soap_res = parent.aras.soapSend('GetNotifications', query, this.url); return this.ProcessSoapResult(soap_res); }; UserNotificationContainer.prototype.ProcessSoapResult = function UserNotificationContainer_ProcessSoapResult(soap_res) { if (soap_res.getFaultCode() !== 0) { parent.aras.AlertError(soap_res); return null; } var result_dom; if (soap_res.isFault()) { return null; } else { result_dom = soap_res.getResult(); } return result_dom; }; UserNotificationContainer.prototype.RefreshUpdateDom = function UserNotificationContainer_RefreshUpdateDom(result_dom) { if (!result_dom) { return; } this.UpdateInfoDom = result_dom.selectSingleNode('Item[@id=\'UpdateInfoMessage\']'); }; UserNotificationContainer.prototype.FillStandardMessageCollection = function UserNotificationContainer_FillStandardMessageCollection(result_dom, clear_before) { if (clear_before) { this.ClearCollection(); } else { this.MakeAllMessagesOld(); } if (!result_dom) { this.ClearCollection(); return; } var standard_collection = result_dom.selectNodes('Item[type/text()=\'Standard\']') for (var i = 0; i < standard_collection.length; i++) { var messageItem = standard_collection[i]; var message_id = messageItem.getAttribute('id'); var title = parent.aras.getItemProperty(messageItem, 'title'); var image_url = parent.aras.getItemProperty(messageItem, 'icon'); this.AddMessage(message_id, title, image_url, messageItem); } this.ClearOldMessages(); }; UserNotificationContainer.prototype.ShowPopupCollection = function UserNotificationContainer_ShowPopupCollection(result_dom, showAsModeless) { if (!result_dom) { return; } var popup_collection = result_dom.selectNodes('Item[type/text()=\'Popup\']'); var sorted_list = this.SortMessagesByPriority(popup_collection); var i = 0; var nextSortedList = function() { if (i >= sorted_list.length) { return; } var index = showAsModeless ? i : sorted_list.length - i - 1; if (!sorted_list[index]) { i++; nextSortedList(); } else { nextMsgIndex(index, 0); } }.bind(this); var nextMsgIndex = function(index, msg_index) { if (msg_index >= sorted_list[index].length) { i++; nextSortedList(); } else { this.DisplayMessageDialog(sorted_list[index][msg_index], showAsModeless, function() { window.setTimeout(function() { msg_index++; nextMsgIndex(index, msg_index); }, 0); }); } }.bind(this); nextSortedList(); }; UserNotificationContainer.prototype.SortMessagesByPriority = function UserNotificationContainer_SortMessagesByPriority(message_collection) { var sorted_list = []; for (var i = 0; i < message_collection.length; i++) { var priority = parent.aras.getItemProperty(message_collection[i], 'priority'); if (!sorted_list[priority]) { sorted_list[priority] = []; } sorted_list[priority][sorted_list[priority].length] = message_collection[i]; } return sorted_list; }; UserNotificationContainer.prototype.UpdateMessageCollection = function UserNotificationContainer_UpdateMessageCollection(doAsync, callback) { if (!doAsync) { doAsync = false; } if (doAsync) { var fn = function getCollectionCallback(container, message_collection) { container.RefreshUpdateDom(message_collection); container.FillStandardMessageCollection(message_collection); container.ShowPopupCollection(message_collection, true); callback(); }; this.AsyncCheckNewMessages(fn); } else { var message_collection = this.SyncGetMessageCollection(); this.RefreshUpdateDom(message_collection); this.FillStandardMessageCollection(message_collection); this.ShowPopupCollection(message_collection, false); } }; UserNotificationContainer.prototype.StartIterativeUpdateMessageCollection = function UserNotificationContainer_StartIterativeUpdateMessageCollection() { this.UpdateMessageCollection(true, callback); function callback() { this.CheckTimeout = setTimeout(function() { parent.aras.UserNotification.StartIterativeUpdateMessageCollection(); }, parent.aras.UserNotification.CheckInterval); } }; UserNotificationContainer.prototype.DisplayMessageDialogById = function UserNotificationContainer_DisplayMessageDialogById(message_id, showAsModeless) { if ('UpdateInfoMessage' == message_id) { this.DisplayMessageDialog(this.UpdateInfoDom, showAsModeless); } else { var message_item = parent.aras.getItemById('Message', message_id); if (message_item) { this.DisplayMessageDialog(message_item, showAsModeless); } else { parent.aras.AlertError(parent.aras.getResource('', 'user_notifications.message_no_more_available'), '', ''); this.RemoveMessage(message_id); } } }; UserNotificationContainer.prototype.DisplayMessageDialog = function UserNotificationContainer_DisplayMessageDialog(message_item, showAsModeless, callback) { if (message_item == null) { return; } var template_url = parent.aras.getI18NXMLResource('notification_popup_template.xml', parent.aras.getBaseURL()); var template_dom = parent.aras.createXMLDocument(); template_dom.load(template_url); var parameters = this.PopupParametersArray[parent.aras.getItemProperty(message_item, 'id')]; if (!parameters) { parameters = {}; } var opened_message_window = parameters.window; parameters.id = parent.aras.getItemProperty(message_item, 'id'); parameters.default_template = template_dom.selectSingleNode('template/html').text; parameters.custom_html = parent.aras.getItemProperty(message_item, 'custom_html'); parameters.dialogWidth = parent.aras.getItemProperty(message_item, 'width'); parameters.dialogHeight = parent.aras.getItemProperty(message_item, 'height'); parameters.css = parent.aras.getItemProperty(message_item, 'css'); parameters.is_standard_template = parent.aras.getItemProperty(message_item, 'is_standard_template') == '1'; if (!parameters.dialogWidth || parameters.is_standard_template) { parameters.dialogWidth = template_dom.selectSingleNode('template/dialog_width').text; } if (!parameters.dialogHeight || parameters.is_standard_template) { parameters.dialogHeight = template_dom.selectSingleNode('template/dialog_height').text; } parameters.title = parent.aras.getItemProperty(message_item, 'title'); parameters.text = parent.aras.getItemProperty(message_item, 'text'); parameters.url = parent.aras.getItemProperty(message_item, 'url'); parameters.icon = parent.aras.getItemProperty(message_item, 'icon'); parameters.OK_IsVisible = ('1' == parent.aras.getItemProperty(message_item, 'show_ok_button')); parameters.Exit_IsVisible = ('1' == parent.aras.getItemProperty(message_item, 'show_exit_button')); parameters.OK_Label = parent.aras.getItemProperty(message_item, 'ok_button_label'); parameters.Exit_Label = parent.aras.getItemProperty(message_item, 'exit_button_label'); parameters.container = this; parameters.opener = window; parameters.writeContent = writeContent; parameters.aras = parent.aras; this.PopupParametersArray[parameters.id] = parameters; if (!showAsModeless) { parameters.dialogWidth = parameters.dialogWidth; parameters.dialogHeight = parameters.dialogHeight; parameters.content = 'modalDialog.html'; window.ArasModules.Dialog.show('iframe', parameters).promise.then( function(res) { if (res == this.constAcknowledge) { this.AcknowledgeMessage(message_item); } if (callback) { callback(); } }.bind(this) ); } else { var sFeatures = ''; sFeatures += 'height=' + parameters.dialogHeight + ', '; sFeatures += 'width=' + parameters.dialogWidth + ''; if (opened_message_window) { opened_message_window.close(); } var fn = function OnBeforeUnloadHandler() { if (parameters.window.returnValue == parameters.window.parameters.container.constAcknowledge) { parameters.window.parameters.container.AcknowledgeMessage(message_item); } parameters.window = null; }; parameters.window = window.open(parent.aras.getScriptsURL() + 'blank.html', '', sFeatures); parameters.window.focus(); writeContent(parameters.window); parameters.window.parameters = parameters; parameters.window.addEventListener('beforeunload', fn); if (callback) { callback(); } } ////////////////////////////////////////// function writeContent(w) { var doc = w.document, template, title_expr = new RegExp('{TITLE}', 'g'), url_expr = new RegExp('{URL}', 'g'), text_expr = new RegExp('{TEXT}', 'g'), icon_expr = new RegExp('{ICON}', 'g'); if (!parameters.is_standard_template) { template = parameters.custom_html.replace(title_expr, parameters.title); template = template.replace(url_expr, parameters.url); template = template.replace(text_expr, parameters.text); template = template.replace(icon_expr, parameters.icon); doc.write(template); } else { template = parameters.default_template.replace(title_expr, parameters.title); template = template.replace(url_expr, parameters.url); template = template.replace(text_expr, parameters.text); template = template.replace(icon_expr, parameters.icon); doc.write(template); if (parameters.css) { var style = doc.createElement('style'); style.innerHTML = parameters.css; doc.head.appendChild(style); } var notificationTitle = doc.getElementById('notification_title'); var titleElement = notificationTitle.appendChild(doc.createElement('h2')); titleElement.setAttribute('class', 'title'); if (parameters.url) { var urlElement = titleElement.appendChild(doc.createElement('a')); urlElement.setAttribute('href', parameters.url); urlElement.setAttribute('target', '_about'); urlElement.setAttribute('class', 'sys_item_link'); urlElement.textContent = parameters.title; } else { titleElement.textContent = parameters.title; } if (!parameters.icon) { doc.getElementById('message_icon').style.display = 'none'; } } w.returnValue = parameters.container.constClose; w.closeWindow = function(value) { if (w.dialogArguments && w.dialogArguments.dialog) { w.dialogArguments.dialog.close(value); } else { w.returnValue = value || w.returnValue; w.close(); } }; doc.close(); var innerHTML = ''; if (parameters.OK_IsVisible) { innerHTML += parameters.container.uiDrawInputButton('OK_button', parameters.OK_Label, ' window.closeWindow(\'' + parameters.container.constAcknowledge + '\');', 'notification_ok_btn'); } if (parameters.Exit_IsVisible) { innerHTML += parameters.container.uiDrawInputButton('Exit_button', parameters.Exit_Label, ' window.closeWindow(\'' + parameters.container.constClose + '\');', 'cancel_button notification_exit_btn'); } if (innerHTML) { var el = doc.createElement('center'); el.innerHTML = innerHTML; var source = doc.getElementById('btns') || doc.getElementsByTagName('body')[0]; if (source) { source.appendChild(el); } } } }; UserNotificationContainer.prototype.uiDrawInputButton = function UserNotificationContainer_uiDrawInputButton(name, value, handler_code, class_name) { return ''; }; UserNotificationContainer.prototype.AcknowledgeMessage = function UserNotificationContainer_AcknowledgeMessage(message_item) { if (!message_item) { return; } var acknowledge_dom = message_item.selectSingleNode('acknowledge'); if (acknowledge_dom.text == 'Once') { var message_id = message_item.getAttribute('id'); var relsh = '' + '' + ' ' + parent.aras.getCurrentUserID() + '' + ' ' + message_item.getAttribute('id') + '' + ''; var soap_res = parent.aras.soapSend('ApplyItem', relsh); if (soap_res.getFaultCode() !== 0) { parent.aras.AlertError(soap_res); return null; } if (soap_res.isFault()) { return null; } this.RemoveMessage(message_id); } }; UserNotificationContainer.prototype.Dispose = function UserNotificationContainer_Dispose() { if (this.CheckTimeout) { clearTimeout(this.CheckTimeout); } }; /** Licensing.js **/ // © Copyright by Aras Corporation, 2013. Licensing.ActionType = { Activate: 0, Update: 1, Deactivate: 2 }; function Licensing(aras) { this.arasObject = aras; this.actionNamespace = aras.arasService.actionNamespace; this.iServiceName = aras.arasService.serviceName; this.url = aras.arasService.serviceUrl; this.propgressBarImage = '../images/Progress.gif'; this.wnd = window; this.error = {}; this.state = ''; this._getFeatureLicenseSecureId = function(featureLicenseId) { if (featureLicenseId) { var qry = this.arasObject.newIOMItem('Feature License', 'get'); qry.setID(featureLicenseId); qry.setAttribute('select', 'secure_id'); qry = qry.apply(); if (!qry.isError() && qry.getItemCount() === 1) { return qry.getProperty('secure_id'); } } return ''; }; this._validateActivationKey = function(activationKey) { if (!activationKey) { this.arasObject.AlertError(this.arasObject.getResource('', 'licensing.activation_key_is_empty'), '', '', this.wnd); return false; } return true; }; this._getNonFailedDoc = function(arasObject, result) { if (!result) { this.error = { details: arasObject.getResource('', 'licensing.service_not_available'), title: arasObject.getResource('', 'licensing.service_not_available_title') }; return false; } else if (result.search(/'); var envelopeNd = query.dom.selectSingleNode('//*[local-name()=\'Envelope\']'); if (envelopeNd) { query.loadAML(envelopeNd.xml); } if (query.isError()) { this.error = {alert: true, query: query}; return false; } return query; }; this._showErrorPage = function(win, activationKey) { var error = this.error; var params; this.error = null; var mainWindow = this.arasObject.getMainWindow(); if (error && error.customError) { params = { aras: this.arasObject, subjectHide: error.subjectHide, errorDetails: error.details, title: error.title, dialogWidth: 365, dialogHeight: 140, content: 'Licensing/ActivateError.html' }; mainWindow.ArasModules.Dialog.show('iframe', params); } else if (error && error.alert) { this.arasObject.AlertError(error.query, '', '', this.wnd); } else if (error) { var result = this._getRequiredServerInfo(); if (activationKey) { result += '' + activationKey + ''; } params = { title: error.title, aras: this.arasObject, result: result, errorDetails: error.details, dialogWidth: 400, dialogHeight: 295, content: 'Licensing/ServiceError.html' }; mainWindow.ArasModules.Dialog.show('iframe', params); } else { return; } if (win) { win.close(); } }; this._callMethodOnLicensingService = function(methodName, paramName, paramValue) { // don't used soap because request body isn't XML var xhr = new XMLHttpRequest(); var url = this.arasObject.getServerBaseURL() + 'Licensing.asmx/' + methodName; xhr.open('POST', url, false); var additionalHeaders = this.arasObject.getHttpHeadersForSoapMessage(methodName); Object.keys(additionalHeaders).forEach(function(header) { xhr.setRequestHeader(header, additionalHeaders[header]); }); var body = paramName + '=' + encodeURIComponent(paramValue); xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=utf-8'); xhr.send(body); if (xhr.status !== 200) { this._errorCallback(xhr.statusText, xhr.responseText); return false; } return true; }; this._getFrameworkLicenseKey = function() { var serverInfo = this._getRequiredServerInfo(); if (serverInfo) { frameworkLicenseKey = serverInfo.match(/]*>([^<]+)<\/framework_license_key>/)[1]; return frameworkLicenseKey ? frameworkLicenseKey : ''; } return ''; }; this._getRequiredServerInfo = function() { var result; var self = this; ArasModules.soap('', { url: this.arasObject.getServerBaseURL() + 'Licensing.asmx/', appendMethodToURL: true, async: false, method: 'GetServerInfo', methodNm: this.actionNamespace, restMethod: 'POST' }) .then(function(responseText) { result = responseText; }, function(rq) { result = self._errorCallback(rq.statusText, rq.responseText); }); if (!result) { return ''; } var doc = this.arasObject.createXMLDocument(); doc.loadXML(result); return doc.documentElement ? doc.documentElement.text : ''; }; this._displayFeatureRequirementsForms = function(getMetaInfoResult, activationKey, featureLicenseId, action) { var self = this; function showFeatureRequirementDialog(params) { var aras = params.aras; var container = getLicenseActionContainer(self, activationKey); if (container) { var postData = container; var queryParameters = ''; queryParameters = appendParameter(queryParameters, 'actionName=' + params.action); queryParameters = appendParameter(queryParameters, 'activationKey=' + params.activationKey); var topWndAras = aras.getMostTopWindowWithAras(window).aras; var formUrl = 'VirtualGetLicenseForm' + (queryParameters ? '?' + queryParameters : ''); var postUrl = topWndAras.getBaseURL() + '/Modules/aras.innovator.core.License/PostLicenseForm' + (queryParameters ? '?' + queryParameters : ''); var xmlhttp = topWndAras.XmlHttpRequestManager.CreateRequest(); xmlhttp.open('POST', postUrl, false); xmlhttp.send(postData); return formUrl; } else { //false return container; } function getLicenseActionContainer(context) { var result = false; var requestBody = '' + '' + '' + '' + aras.commonProperties.clientRevision + '' + '' + ''; try { var method = 'GetLicenseActionContainer'; var methodNm = context.actionNamespace; var requestResponse; ArasModules.soap(requestBody, { url: context.url, async: false, method: method, methodNm: methodNm, SOAPAction: methodNm + context.iServiceName + '/' + method, headers: {} }) .then(function(responseText) { requestResponse = responseText; }, function(req) { var dialogErrorCallback = context._GenerateActivateErrorCallback( context.arasObject.getResource('', 'licensing.could_not_load_feature_requirements'), activationKey ); dialogErrorCallback(req.statusText, req.responseText, req.status); }); var doc = aras.createXMLDocument(); doc.loadXML(requestResponse); var envelope = doc.selectSingleNode('//*[local-name()=\'Envelope\']'); if (envelope) { result = envelope.text; } } finally { return result; } } function appendParameter(param, value) { if (param !== '') { param += '&'; } param += value; return param; } } var query = this._checkErrors(this.arasObject, getMetaInfoResult); if (!query) { this._showErrorPage(null, activationKey); return false; } var params = this.arasObject.newObject(); params.aras = this.arasObject; var formArray = []; var itemTypeArray = []; var instanceArray = []; var listArray = []; var width = 350; var height = 150; var forms = query.getItemsByXPath('/AML/Item[@type=\'Form\']'); var formsCount = forms.getItemCount(); if (formsCount === 0) { if (action !== Licensing.ActionType.Deactivate) { return featureLicenseId ? this.Update(featureLicenseId) : this.Activate(activationKey); } return this.Deactivate(featureLicenseId); } else { for (var i = 0; i < formsCount; i++) { var formItem = forms.getItemByIndex(i); var w = parseInt(formItem.getProperty('width')); var h = parseInt(formItem.getProperty('height')); width = w > width ? w : width; height = h > height ? h : height; formArray.push(formItem); listArray.push(query.getItemsByXPath('/AML/Item[@type=\'List\']')); itemTypeArray.push(query.getItemsByXPath('/AML/Item[@type=\'ItemType\' and name=\'' + formItem.getProperty('name') + '\']')); instanceArray[i] = query.getItemsByXPath('/AML/Item[@type=\'' + formItem.getProperty('name') + '\']'); } height = parseInt(height) + 66; params.licensingObject = this; params.forms = formArray; params.itemTypes = itemTypeArray; params.listArray = listArray; params.instances = instanceArray; params.activationKey = activationKey; params.featureLicenseId = featureLicenseId; params.action = action; self = this; params.dialogWidth = width; params.dialogHeight = height; var formUrl = showFeatureRequirementDialog(params); if (formUrl) { params.content = formUrl; var mainWindow = this.arasObject.getMainWindow(); mainWindow.ArasModules.Dialog.show('iframe', params); } else { return false; } } return true; }; this._getMetaInfoFromArasService = function(action, activationKey, featureLicenseId) { var methodName; var callbackMethod; var parameterName = 'featureLicenseSecureId'; var parameterValue = this._getFeatureLicenseSecureId(featureLicenseId); if (Licensing.ActionType.Activate === action) { parameterName = 'activationKey'; parameterValue = activationKey; methodName = 'GetMetaInfoForActivate'; callbackMethod = this._GenerateActivateErrorCallback(null, activationKey); } else if (Licensing.ActionType.Update === action) { methodName = 'GetMetaInfoForUpdate'; } else if (Licensing.ActionType.Deactivate === action) { methodName = 'GetMetaInfoForDeactivate'; } var metaInfoResult; var statusId; try { statusId = this.arasObject.showStatusMessage('status', this.arasObject.getResource('', 'licensing.request_aras'), this.propgressBarImage); var methodNamespace = this.actionNamespace; var requestBody = '<' + parameterName + '>' + parameterValue + ''; ArasModules.soap(requestBody, { url: this.url, async: false, method: methodName, methodNm: methodNamespace, SOAPAction: methodNamespace + this.iServiceName + '/' + methodName, headers: {} }) .then(function(responseText) { metaInfoResult = responseText; }, function(req) { callbackMethod(req.statusText, req.responseText, req.status); }); } finally { this.arasObject.clearStatusMessage(statusId); } this._displayFeatureRequirementsForms(metaInfoResult, activationKey, featureLicenseId, action); }; this._showInformationAboutImportedFeatureLicense = function(result, title) { var self = this; var mainWindow = this.arasObject.getMainWindow(); mainWindow.ArasModules.Dialog.show('iframe', { aras: this.arasObject, result: result, title: this.arasObject.getResource('', 'licensing.success_import_title'), dialogWidth: 600, dialogHeight: 270, center: true, content: 'Licensing/SuccessMessage.html' }); }; this._showActivateFeatureDialog = function LicensingShowActivateFeatureDialog(activationKey, action, featureLicenseId) { var aras = this.arasObject; var params = this.arasObject.newObject(); params.aras = aras; params.licensingObject = this; params.action = action; params.activationKey = activationKey; params.featureLicenseId = featureLicenseId; params.dialogWidth = 350; params.dialogHeight = 140; params.center = true; params.content = 'Licensing/ActivateFeature.html'; switch (action || Licensing.ActionType.Activate) { case 0: params.title = aras.getResource('', 'licensing.action_type_activate'); break; case 1: params.title = aras.getResource('', 'licensing.action_type_update'); break; case 2: params.title = aras.getResource('', 'licensing.action_type_deactivate'); break; } var mainWindow = aras.getMainWindow(); mainWindow.ArasModules.Dialog.show('iframe', params); }; this._getFeatureLicenseByLicenseData = function(encryptedFeatureLicense) { var qry = this.arasObject.newIOMItem('Feature License', 'get'); qry.setProperty('license_data', encryptedFeatureLicense); return qry.apply(); }; this._prepareLicenseRequestBody = function(propertyName, propertyValue, additionalData) { var serverInfo = this._getRequiredServerInfo(); additionalData = additionalData ? additionalData : ''; var result = '' + '<' + propertyName + '>' + propertyValue + '' + '' + ' ' + serverInfo + additionalData + ' ' + ''; return result; }; this._getFeatureTreeFromInnovatorServer = function() { var method = 'GetFeatureTree'; var methodNm = this.actionNamespace; var self = this; var res; ArasModules.soap('', { url: this.arasObject.getServerBaseURL() + 'Licensing.asmx/GetFeatureTree', async: false, method: method, methodNm: methodNm, SOAPAction: methodNm + this.iServiceName + '/' + method, headers: this.arasObject.getHttpHeadersForSoapMessage() }) .then(function(result) { res = result; }, function(req) { self._errorCallback(req.statusText, req.responseText, req.status); }); return res; }; this._errorCallback = function(errorMessage, technicalMessage, stackTrace) { technicalMessage = !technicalMessage ? '' : technicalMessage; stackTrace = !stackTrace ? technicalMessage : stackTrace; this.arasObject.AlertError(errorMessage, technicalMessage, stackTrace); return false; }; this._GetResponseFaultstring = function(responseText) { var doc = this.arasObject.createXMLDocument(); doc.loadXML(responseText); var errorDetails = ''; if (doc.selectSingleNode('//faultstring')) { errorDetails = doc.selectSingleNode('//faultstring').text; } return errorDetails; }; this._GenerateActivateErrorCallback = function(messagePrefix, activationKey) { var prefix = messagePrefix; if (!prefix) { prefix = ''; } return function(statusText, responseText, status) { if (status !== 404) { var errorDetails = this._GetResponseFaultstring(responseText); this._ShowActivateErrorDialog(prefix + errorDetails); } }.bind(this); }; this._ShowActivateErrorDialog = function(errorDetails) { var params = this.arasObject.newObject(); params.aras = this.arasObject; params.errorDetails = errorDetails; params.title = this.arasObject.getResource('', 'licensing.activation_error_tilte'); params.dialogWidth = 365; params.dialogHeight = 160; params.content = 'Licensing/ActivateError.html'; var mainWindow = this.arasObject.getMainWindow(); mainWindow.ArasModules.Dialog.show('iframe', params); return false; }; } Licensing.prototype.GetLicenseAgreement = function LicensingGetLicenseAgreement(activationKey) { var requestBody = this._prepareLicenseRequestBody('activationKey', activationKey); var query = false; var statusId = ''; try { statusId = this.arasObject.showStatusMessage('status', this.arasObject.getResource('', 'licensing.request_aras'), this.propgressBarImage); var method = 'GetLicenseAgreement'; var methodNm = this.actionNamespace; var self = this; var requestResponse; ArasModules.soap(requestBody, { url: this.url, async: false, method: method, methodNm: methodNm, SOAPAction: methodNm + this.iServiceName + '/' + method, headers: {} }) .then(function(responseText) { requestResponse = responseText; }, function(req) { self._GenerateActivateErrorCallback(null, activationKey)(req.statusText, req.responseText, req.status); }); query = this._checkErrors(this.arasObject, requestResponse); } finally { this.arasObject.clearStatusMessage(statusId); } return query; }; Licensing.prototype.Activate = function LicensingActivate(activationKey, additionalData, additionalOptions) { if (!this._validateActivationKey(activationKey)) { return false; } var requestBody = this._prepareLicenseRequestBody('activationKey', activationKey, additionalData); var statusId = ''; try { statusId = additionalOptions ? additionalOptions.statusId : this.arasObject.showStatusMessage('status', this.arasObject.getResource('', 'licensing.request_aras'), this.propgressBarImage); var method = 'Activate'; var methodNm = this.actionNamespace; var self = this; var requestResponse; ArasModules.soap(requestBody, { url: this.url, async: false, method: method, methodNm: methodNm, SOAPAction: methodNm + this.iServiceName + '/' + method, headers: {} }) .then(function(responseText) { requestResponse = responseText; }, function(req) { self._GenerateActivateErrorCallback(null, activationKey)(req.statusText, req.responseText, req.status); }); if (!requestResponse) { return false; } var query = this._checkErrors(this.arasObject, requestResponse); if (!query) { this._showErrorPage(additionalOptions ? additionalOptions.win : null); return false; } if (additionalOptions) { additionalOptions.featureAction = 'activate'; } return this.ImportFeatureLicense(query.getResult(), additionalOptions); } finally { this.arasObject.clearStatusMessage(statusId); } }; Licensing.prototype.Update = function LicensingUpdate(featureLicenseId, additionalData, additionalOptions) { var featureLicenseSecureId = this._getFeatureLicenseSecureId(featureLicenseId); var requestBody = this._prepareLicenseRequestBody('featureLicenseSecureId', featureLicenseSecureId, additionalData); var statusId = ''; try { statusId = additionalOptions ? additionalOptions.statusId : this.arasObject.showStatusMessage('status', this.arasObject.getResource('', 'licensing.request_aras'), this.propgressBarImage); var method = 'Update'; var methodNm = this.actionNamespace; var requestResponse; ArasModules.soap(requestBody, { url: this.url, async: false, method: method, methodNm: methodNm, SOAPAction: methodNm + this.iServiceName + '/' + method, headers: {} }) .then(function(responseText) { requestResponse = responseText; }); var query = this._checkErrors(this.arasObject, requestResponse); if (!query) { this._showErrorPage(additionalOptions ? additionalOptions.win : null); return false; } if (additionalOptions) { additionalOptions.win.close(); } var mainWindow = this.arasObject.getMainWindow(); var self = this; mainWindow.ArasModules.Dialog.show('iframe', { aras: this.arasObject, featureAction: 'update', title: arasObject.getResource('', 'licensing.success_update_title'), dialogWidth: 350, dialogHeight: 120, center: true, content: 'Licensing/SuccessMessage.html' }); return true; } finally { this.arasObject.clearStatusMessage(statusId); } }; Licensing.prototype.Deactivate = function LicensingDeactivate(featureLicenseId, additionalData, additionalOptions) { var featureLicenseSecureId = this._getFeatureLicenseSecureId(featureLicenseId); var requestBody = this._prepareLicenseRequestBody('featureLicenseSecureId', featureLicenseSecureId, additionalData); var statusId = ''; try { statusId = additionalOptions ? additionalOptions.statusId : this.arasObject.showStatusMessage('status', this.arasObject.getResource('', 'licensing.request_aras'), this.propgressBarImage); var method = 'Deactivate'; var methodNm = this.actionNamespace; var requestResponse; ArasModules.soap(requestBody, { url: this.url, async: false, method: method, methodNm: methodNm, SOAPAction: methodNm + this.iServiceName + '/' + method, headers: {} }) .then(function(responseText) { requestResponse = responseText; }); var query = this._checkErrors(this.arasObject, requestResponse); if (!query) { this._showErrorPage(additionalOptions ? additionalOptions.win : null); return false; } this.arasObject.deleteItem('Feature License', featureLicenseId, true); } finally { this.arasObject.clearStatusMessage(statusId); } return true; }; Licensing.prototype.showState = function LicensingShowState() { if (this.state) { this.arasObject.AlertSuccess(this.state, window); this.state = null; } }; Licensing.prototype.UpdateFeatureTreeUI = function LicensingUpdateFeatureTreeUI() { var statusId = ''; try { statusId = this.arasObject.showStatusMessage('status', this.arasObject.getResource('', 'licensing.request_aras'), this.propgressBarImage); if (!this.UpdateFeatureTree()) { this._showErrorPage(); return false; } } finally { this.showState(); this.arasObject.clearStatusMessage(statusId); } return true; }; Licensing.prototype.UpdateFeatureTree = function LicensingUpdateFeatureTree(callback) { var self = this; var getResponse = function(responseText) { var arasObject = self.arasObject; if (!responseText) { self.error = { customError: true, subjectHide: true, details: arasObject.getResource('', 'licensing.update_feature_tree_service_not_available'), title: arasObject.getResource('', 'licensing.update_feature_tree_service_not_available_title') }; if (callback) { callback(); } return false; } else if (!self._getNonFailedDoc(arasObject, responseText)) { self.state = arasObject.getResource('', 'licensing.feature_tree_failed_updated_featureTree'); if (callback) { callback(); } return false; } var doc = arasObject.createXMLDocument(); doc.loadXML(responseText); var featureTreeText = doc.documentElement ? doc.documentElement.text : ''; var bResult = self._callMethodOnLicensingService('UpdateFeatureTree', 'encryptedFeatureTree', featureTreeText); bResult = !!bResult; self.state = bResult ? arasObject.getResource('', 'licensing.feature_tree_successfully_updated') : arasObject.getResource('', 'licensing.feature_tree_failed_updated_featureTree'); if (callback) { callback(bResult); } return bResult; }; var data = '' + this._getFrameworkLicenseKey() + ''; var method = 'GetFeatureTree'; var methodNm = this.actionNamespace; var getFeatureTreeResult; ArasModules.soap(data, { async: !!callback, url: this.url, method: method, methodNm: methodNm, SOAPAction: methodNm + this.iServiceName + '/' + method, headers: {} }) .then(function(result) { if (callback) { getResponse(result); } else { getFeatureTreeResult = result; } }, function() { self.state = self.arasObject.getResource('', 'licensing.feature_tree_failed_updated_featureTree'); if (callback) { callback(); } }); if (!callback) { return getResponse(getFeatureTreeResult); } }; Licensing.prototype.ShowLicenseManagerDialog = function LicensingShowLicenseManagerDialog() { var params = { aras: this.arasObject, title: this.arasObject.getResource('', 'licmanager.title'), dialogWidth: 1000, dialogHeight: 420, resizable: true, center: true, content: 'Licensing/LicManager.html' }; var mainWindow = this.arasObject.getMainWindow(); mainWindow.ArasModules.Dialog.show('iframe', params); }; Licensing.prototype.ActivateFeature = function LicensingActivateFeature(activationKey) { return this._showActivateFeatureDialog(activationKey); }; Licensing.prototype.DeactivateFeature = function LicensingDeactivateFeature(activationKey, featureLicenseId) { return this._showActivateFeatureDialog(activationKey, Licensing.ActionType.Deactivate, featureLicenseId); }; Licensing.prototype.ImportFeatureLicense = function LicensingImportFeatureLicense(featureLicenseText, additionalOptions) { var importFeature = function(featureLicenseText) { var bResult = this._callMethodOnLicensingService('ImportFeatureLicense', 'encryptedFeatureLicense', featureLicenseText); if (bResult) { if (additionalOptions) { additionalOptions.win.close(); } var featureLicense = this._getFeatureLicenseByLicenseData(featureLicenseText); if (featureLicense.isError()) { this.arasObject.AlertError(featureLicense, this.wnd); return false; } var self = this; var params = { aras: this.arasObject, result: featureLicense, featureAction: additionalOptions ? additionalOptions.featureAction : '', dialogWidth: 350, dialogHeight: 190, center: true, content: 'Licensing/SuccessMessage.html' }; params.title = this.arasObject.getResource('', (params.featureAction === 'update') ? 'licensing.success_update_title' : 'licensing.success_import_title'); var mainWindow = this.arasObject.getMainWindow(); window.setTimeout(function() { mainWindow.ArasModules.Dialog.show('iframe', params).promise.then(); }.bind(this), 0); } }; if (!featureLicenseText) { var mainWindow = this.arasObject.getMainWindow(); mainWindow.ArasModules.Dialog.show('iframe', { aras: this.arasObject, title: this.arasObject.getResource('', 'licensing.import_feature_license'), dialogWidth: 350, dialogHeight: 140, center: true, content: 'Licensing/ImportLicense.html' }).promise.then( function(res) { if (res) { importFeature.bind(this)(res); } }.bind(this) ); } else { importFeature.call(this, featureLicenseText); } }; Licensing.prototype.PerformActionOverFeature = function LicensingPerformActionOverFeature(action, activationKey, featureLicenseId) { if (!this._validateActivationKey(activationKey)) { return false; } this._getMetaInfoFromArasService(action, activationKey, featureLicenseId); }; Licensing.prototype.ViewFeatureTree = function LicensingViewFeatureTree() { var featureTreeXml = this._getFeatureTreeFromInnovatorServer(); if (!featureTreeXml) { return; } var doc = this.arasObject.createXMLDocument(); doc.loadXML(featureTreeXml); var xmlDocument = this.arasObject.createXMLDocument(); xmlDocument.validateOnParse = true; xmlDocument.loadXML(doc.childNodes[doc.childNodes.length - 1].text); var xslt = this.arasObject.createXMLDocument(); xslt.load(this.arasObject.getScriptsURL() + 'Licensing/FeatureTree.xsl'); featureTreeXml = xmlDocument.transformNode(xslt); var params = { aras: this.arasObject, featureTreeXml: featureTreeXml, title: 'Aras Feature Tree', dialogHeight: 620, dialogWidth: 500, resizable: true, center: true, scroll: true, content: 'Licensing/FeatureTree.html' }; var mainWindow = this.arasObject.getMainWindow(); mainWindow.ArasModules.Dialog.show('iframe', params); }; /** ..\BrowserCode\common\javascript\FileSystemAccess.js **/ var fileSystemAccess = { init: function(parentAras) { this.fileList = {}; this.clientData = {}; this.lastError = ''; if (parentAras.vault) { this.associatedFileList = parentAras.vault.vault.associatedFileList; this.fileToMd5 = parentAras.vault.vault.fileToMd5; } else { this.associatedFileList = {}; this.fileToMd5 = {}; } }, getFileChecksum: function(file) { if (typeof file === 'string') { var parts = file.split(/[\\\/]/); var fileID = parts[0]; return fileSystemAccess.fileToMd5[this.associatedFileList[fileID] || this.fileList[fileID]]; } else { return fileSystemAccess.fileToMd5[file.size + '.' + file.name + '.' + file.lastModified] || ''; } }, getFileSize: function(file) { if (typeof file === 'string') { var parts = file.split(/[\\\/]/); var fileID = parts[0]; return this.associatedFileList[fileID].size; } else { return file.size; } }, sendFiles: function(strUrl) { var fileId; var i; var httpRequest = new XMLHttpRequest(); httpRequest.open('POST', strUrl, false); var form = new FormData(); var keys = Object.keys(this.clientData); for (i = 0; i < keys.length; i++) { var key = keys[i]; form.append(key, this.clientData[key]); } var fileIds = Object.keys(this.fileList); for (i = 0; i < fileIds.length; i++) { fileId = fileIds[i]; form.append(fileId, this.fileList[fileId]); } httpRequest.send(form); if (httpRequest.status !== 200) { Object.assign(this.associatedFileList, this.fileList); this.lastError = 'Cannot upload file. Exception name: "WebException"; Exception message: "The remote server returned an error: ' + httpRequest.status + '"'; return false; } var xml = httpRequest.responseXML; if (xml && xml.firstChild && xml.firstChild.firstChild) { var result = xml.firstChild.firstChild.firstChild; var isFault = (result && result.nodeName.toLowerCase() === 'soap-env:fault'); if (isFault) { Object.assign(this.associatedFileList, this.fileList); } } this.response = httpRequest.responseText; return true; }, sendFilesAsync: function(serverUrl) { var clientData = this.clientData; var res = []; var keys = Object.keys(aras.vault.vault.fileList); for (var i = 0; i < keys.length; i++) { res.push(aras.vault.vault.fileList[keys[i]]); } keys = Object.keys(clientData); var credentials = {}; for (i = 0; i < keys.length; i++) { var key = keys[i]; if (key != 'XMLdata' && key != 'SOAPACTION') { credentials[key] = clientData[key]; } } var vaultModule; var mainWnd; if (window.itemTypeName === 'File' && !window.frameElement) { mainWnd = aras.getMainWindow(); vaultModule = mainWnd.ArasModules.vault; } else { vaultModule = ArasModules.vault; } vaultModule.options.serverUrl = serverUrl; vaultModule.options.credentials = credentials; var finallyCallback = function(res) { this.response = res.xml || res.parentNode.xml; return true; }.bind(this); return vaultModule.send(res, clientData.XMLdata).then(finallyCallback, finallyCallback); }, clearClientData: function() { this.clientData = {}; }, addFileToList: function(fileID, filepath) { if (!filepath) { this.lastError = 'Filename is empty'; return false; } if (this.associatedFileList[fileID]) { this.fileList[fileID] = this.associatedFileList[fileID]; } else if (typeof filepath !== 'string') { if (aras.Browser.isIe()) { filepath.Xhr = XMLHttpRequest; } this.fileList[fileID] = filepath; this.associatedFileList[fileID] = filepath; } return true; }, removeFileFromList: function(fileId) { if (this.associatedFileList[fileId]) { delete this.associatedFileList[fileId]; } if (this.fileList[fileId]) { delete this.fileList[fileId]; } }, selectFile: function() { return ArasModules.vault.selectFile().then(function(file) { //aras.browserHelper.toggleSpinner(document, true, 'dimmer_spinner_whole_window'); return file; }).then(this.calculateMd5).then(function(file) { //aras.browserHelper.toggleSpinner(document, false, 'dimmer_spinner_whole_window'); return file; }); }, clearFileList: function() { this.fileList = {}; }, setClientData: function(name, valueRenamed) { this.clientData[name] = valueRenamed; }, getClientData: function(name) { return this.clientData[name]; }, getResponse: function() { return this.response || ''; }, setLocalFileName: function(filename) { this.localFileName = filename; }, downloadFile: function(strUrl) { var fileId = /fileID=([^&]+)/ig.exec(strUrl); if (!fileId) { return false; } fileId = fileId[1]; strUrl = aras.IomInnovator.getFileUrl(fileId, aras.Enums.UrlType.SecurityToken); if (this.localFileName) { strUrl = strUrl.replace(/fileName=.*?(?=&|$)/, 'fileName=' + this.localFileName); } strUrl += '&contentDispositionAttachment=1'; window.ArasModules.vault.downloadFile(strUrl) .catch(function(err) { var win = aras.getMostTopWindowWithAras(window); win.aras.AlertError('Server status: ' + err.status + '. ' + err.message); }); return true; }, calculateMd5: function(file) { var md5Promise = new Promise(function(resolve, reject) { require(['../browsercode/common/javascript/spark-md5.js'], function(SparkMD5) { var fileReader = new FileReader(); var frOnload = function(e) { spark.append(e.target.result); currentChunk++; if (currentChunk < chunks) { loadNext(); } else { var md5 = spark.end(); fileSystemAccess.fileToMd5[file.size + '.' + file.name + '.' + file.lastModified] = md5; resolve(file); } }; var chunkSize = 2097152; // read in chunks of 2MB var chunks = Math.ceil(file.size / chunkSize); var currentChunk = 0; var spark = new SparkMD5.ArrayBuffer(); function loadNext() { fileReader.onload = frOnload; fileReader.onerror = reject; var start = currentChunk * chunkSize; var end = Math.min(file.size,start + chunkSize); fileReader.readAsArrayBuffer(file.slice(start, end)); } loadNext(); }); }); return md5Promise; }, getLastError: function() { return this.lastError; }, readText: function(file, encoding) { var fileReader = new FileReader(); return new Promise(function(resolve, reject) { fileReader.onload = function() { resolve(this.result); }; fileReader.onerror = reject; fileReader.readAsText(file, encoding); }); }, readBase64: function(file, start, count) { return new Promise(function(resolve, reject) { var fileReader = new FileReader(); fileReader.onload = function() { resolve(this.result); }; fileReader.onerror = reject; fileReader.readAsDataURL(file.slice(start, start + count)); }); } }; /** ..\BrowserCode\common\javascript\BrowserHelper.js **/ function BrowserHelper(aras, aWindow) { 'use strict'; this.window = aWindow; this.aras = aras; } BrowserHelper.prototype.initComponents = function() { var winInetCredentialsCol = {AddFromWinInet: function() { }}; var timeZoneInfo = null; Object.defineProperty(this, 'winInetCredentialsCollection', { get: function() { return winInetCredentialsCol; } }); Object.defineProperty(this, 'tzInfo', { get: function() { if (!timeZoneInfo) { timeZoneInfo = new this.window.TimeZonesInformation(); } return timeZoneInfo; } }); }; BrowserHelper.prototype.adjustHeightTexAreaWithNullableRows = function(textArea) { return this.aras.Browser.isIe() ? textArea.offsetHeight : ((textArea.offsetHeight - 2) / 3 + 2); // There is 3 lines in case of rows == 0 }; BrowserHelper.prototype.getNodeTranslationElement = function(srcNode, nodeName, translationXMLNsURI, lang) { if (this.aras.Browser.isIe()) { return srcNode.selectSingleNode('*[local-name()=\'' + nodeName + '\' and namespace-uri()=\'' + translationXMLNsURI + '\' and @xml:lang=\'' + lang + '\']'); } var nds = srcNode.getElementsByTagNameNS(translationXMLNsURI, nodeName); var i; var resNd; for (i = 0; i < nds.length; i++) { if (nds[i].parentNode == srcNode && nds[i].getAttribute('xml:lang') === lang) { resNd = nds[i]; break; } } return resNd; }; BrowserHelper.prototype.createTranslationNode = function(srcNode, nodeName, translationXMLNsURI, translationXMLNdPrefix) { if (srcNode.ownerDocument.createElementNS) { return srcNode.ownerDocument.createElementNS(translationXMLNsURI, translationXMLNdPrefix + ':' + nodeName); } var resNd = srcNode.ownerDocument.createNode(1, translationXMLNdPrefix + ':' + nodeName, translationXMLNsURI); resNd.setAttribute('xmlns:' + translationXMLNdPrefix, translationXMLNsURI); return resNd; }; BrowserHelper.prototype.getTextContentPropertyName = function() { return 'textContent'; }; BrowserHelper.prototype.getHeightDiffBetweenTearOffAndMainWindow = function() { //Height of Title Bar in Main window is less than in Tear-Off window return this.aras.Browser.isIe() ? 0 : 8; }; BrowserHelper.prototype.isWindowClosed = function(window) { var res = false; try { res = window.closed; } catch (e) { //"Permission denied." // "-2146823281" - "Object expected" - this error sometimes generates by MS edge, when window is closed and reference is corrupted if (e.number != -2146828218 && e.number != -2146823281) { throw e; } else { res = true; } } return res; }; BrowserHelper.prototype.getUserPasswordViaWinAuth = function () { if (document.queryCommandSupported('ClearAuthenticationCache')) { document.execCommand('ClearAuthenticationCache', 'false'); } var urlIOMLogin = this.aras.getScriptsURL() + 'IOMLogin.aspx?redirect_me_to401=1'; var doc = this.aras.createXMLDocument(); var xmlhttp = this.aras.XmlHttpRequestManager.CreateRequest(); xmlhttp.open('GET', urlIOMLogin, false); try { xmlhttp.send(); } catch (e) { //create URL like 'http://123123blablablasalt@namedomain.com/...' //for reset Google Chrome credentials when entered login like 'DOMAIN\username' var urlReset = this.aras.getScriptsURL(); urlReset = urlReset.replace(location.host, Date.now() + 'cache@' + location.host); urlReset = urlReset.replace(/X-cache[a-z0-9_\-\.=]{1,40}\//i, ''); urlReset += 'IOMLogin.aspx'; var xmlhttpReset = this.aras.XmlHttpRequestManager.CreateRequest(); xmlhttp.open('GET', urlReset, false); xmlhttp.send(); return; } var txt = xmlhttp.responseText; //if not xml if (!txt || txt.indexOf('<') < 0) { return; } doc.loadXML(txt); if (!doc.xml) { return; } //+++ the logic below is actually copied from GetMD5PasswordForInnovator function var nd; var pwd; var rNode = doc.selectSingleNode('//Result'); if (!rNode) { return; } nd = rNode.selectSingleNode('password'); if (!nd || !nd.text) { return; } pwd = nd.text; nd = rNode.selectSingleNode('hash'); if (nd.text.toUpperCase() != 'FALSE') { if (this.aras.getVariable('fips_mode')) { pwd = ArasModules.cryptohash.SHA256(pwd); } else { pwd = this.aras.calcMD5(pwd); } } return pwd; }; /*** * Move window to specified coordinates * @param aWindow target window to move * @param x * @param y */ BrowserHelper.prototype.moveWindowTo = function(aWindow, x, y) { if (!this.aras.Browser.isEdge()) { aWindow.moveTo(x, y); } }; /*** * Resize window to specified measurements * @param aWindow window to resize * @param width * @param height */ BrowserHelper.prototype.resizeWindowTo = function(aWindow, width, height) { if (this.aras.Browser.isIe() && aWindow.dialogArguments) { //some dialog shown with a call to showModalDialog or showModelessDialog method //window.resizeTo still doesn't work for dialogs in IE. Tested in IE 9 - IE 11. var frameWidth = aWindow.outerWidth - aWindow.innerWidth; var frameHeight = aWindow.outerHeight - aWindow.innerHeight; //according to MSDN dialogHeight property returns the height of the content area and doesn't include the height of the frame. //http://msdn.microsoft.com/en-us/library/ie/ms533724%28v=vs.85%29.aspx aWindow.dialogHeight = (height - frameHeight) + 'px'; aWindow.dialogWidth = (width - frameWidth) + 'px'; } else if (!this.aras.Browser.isEdge()) { //regular window aWindow.resizeTo(width, height); } }; /*** * Set focus to specified window * @param aWindow Window to focus */ BrowserHelper.prototype.setFocus = function(aWindow) { // window.focus is not working in chrome for parent window. // We need use window.open with empty url as 1-st argument and name of exits window as 2-nd argument. if (aras.Browser.isCh() && aWindow.opener && !aWindow.frameElement) { aWindow.opener.open('', aWindow.name); } //setTimeout to fix window.focus in Mozilla Firefox setTimeout(function() { aWindow.focus(); }, 0); }; /*** * Close specified window * @param aWindow window to close */ BrowserHelper.prototype.closeWindow = function(topWindow) { if (this.aras.Browser.isIe()) { // the "open" method is workaround for IE // proof: https://jeffclayton.wordpress.com/2015/02/13/javascript-window-close-method-that-still-works/ topWindow.open('blank.html', '_top'); } topWindow.close(); }; BrowserHelper.prototype.lockNewWindowOpen = function(aras, lockFlag) { if (this.aras.Browser.isIe()) { aras.commonProperties.lockNewWindowOpen = lockFlag; } }; BrowserHelper.prototype.newWindowCanBeOpened = function(aras) { return !aras.commonProperties.lockNewWindowOpen; }; BrowserHelper.prototype.fixSizeOnModalDialogResize = function(modalDialogWin, idsToResizeWidth, idsToResizeHeight, fixBody, cb) { if (this.aras.Browser.isIe()) { modalDialogWin.addEventListener('resize', function() { var i; var doc = modalDialogWin.document; var w = doc.documentElement.clientWidth; var h = doc.documentElement.clientHeight; var oldw = modalDialogWin['BrowserHelper_oldClientWidth']; var oldh = modalDialogWin['BrowserHelper_oldClientHeight']; if (w != oldw) { if (idsToResizeWidth) { idsToResizeWidth = typeof idsToResizeWidth === 'string' ? [idsToResizeWidth] : idsToResizeWidth; for (i = 0; i < idsToResizeWidth.length; i++) { doc.getElementById(idsToResizeWidth[i]).style.width = w + 'px'; } } if (fixBody) { doc.body.width = w + 'px'; } modalDialogWin['BrowserHelper_oldClientWidth'] = w; } if (idsToResizeHeight && h != oldh) { if (idsToResizeHeight) { idsToResizeHeight = typeof idsToResizeHeight === 'string' ? [idsToResizeHeight] : idsToResizeHeight; for (i = 0; i < idsToResizeHeight.length; i++) { doc.getElementById(idsToResizeHeight[i]).style.height = h + 'px'; } } if (fixBody) { doc.body.height = h + 'px'; } modalDialogWin['BrowserHelper_oldClientHeight'] = h; } if (cb) { cb({'old': {w: oldw, h: oldh}, 'new': {w: w, h: h}}); } }); } }; BrowserHelper.prototype.adjustGridSize = function(aWindow, handler, asFunc) { if (this.aras.Browser.isIe()) { if (asFunc) { aWindow.onresize = handler; } else { aWindow.addEventListener('resize', handler, false); } handler(); } }; /** * Turning on/off class in "spinner" element (classList is required) * * @param {HTMLElement|Document} context - current container object * @param {string} state - turn on/off spinner * @param {string} [spinnerId] - id attribute of spinner element * @return {boolean} spinner found or no */ BrowserHelper.prototype.toggleSpinner = function(context, state, spinnerId) { spinnerId = spinnerId || 'dimmer_spinner'; var spinnerEl = (context.ownerDocument || context).getElementById(spinnerId); if (!spinnerEl) { return false; } spinnerEl.classList.toggle('disabled-spinner', !state); return true; }; // +++++++ Methods for generating XSLT stylesheets for Grids BrowserHelper.prototype.addXSLTCssFunctions = function(container) { container.push('\n'); container.push(' \n'); container.push(' \n'); container.push(' \n'); container.push('\n'); container.push('\n'); container.push(' \n'); container.push(' \n'); container.push(' ;\n'); container.push(' \n'); container.push(' \n'); container.push(' \n'); container.push(' \n'); container.push(' \n'); container.push(' ;\n'); container.push(' \n'); container.push(' \n'); container.push(' \n'); container.push(' \n'); container.push(' \n'); container.push(' \n'); container.push('\n'); }; BrowserHelper.prototype.addXSLTSpecialNamespaces = function(container) {}; BrowserHelper.prototype.addXSLTInitItemCSSCall = function(container, cssValue, fedCssValue) { container.push('\n'); container.push(' \n'); container.push(' \n'); container.push('\n'); }; BrowserHelper.prototype.addXSLTGetPropertyStyleExCall = function(container, nameCSS, cellCSSVariableName1, name) { container.push('\n'); container.push(' \n'); container.push(' \n'); container.push(' ' + name + '\n'); container.push(' \n'); container.push('\n'); }; // ------- Methods for generating XSLT stylesheets for Grids BrowserHelper.prototype.escapeUrl = function(url) { //after xslt transformation of the data for grid in FF need to escape the url on the pictures src if (this.aras.Browser.isFf()) { return url.replace(/&/g, '&'); } else { return url; } }; //IE does not properly set the focus in input fields in the new iframes //We programmatically set the focus on the input field, and then remove the focus //then IE will be able to operate normally with all input fields. BrowserHelper.prototype.restoreFocusForIE = function(window) { if (this.aras.Browser.isIe()) { var document = window.document; var inputTMP = document.createElement('INPUT'); inputTMP.setAttribute('type', 'text'); inputTMP.style.position = 'absolute'; inputTMP.style.top = '-1000px'; document.body.appendChild(inputTMP); inputTMP.focus(); document.body.focus(); document.body.removeChild(inputTMP); } }; /** TimeZonesInformation.js **/ function TimeZonesInformation() { } /*** * @param date Date with respect to which is calculated offset * @param winTzName Name of windows time zone * @returns {*} Time zone offset using olson time zone database */ TimeZonesInformation.prototype.getTimeZoneOffset = function TimeZonesInformationGetTimeZoneOffset(date, winTzName) { var xmlHttp = new XmlHttpRequestManager().CreateRequest(); xmlHttp.open('GET', aras.getBaseURL() + '/TimeZone/GetOlsonTimeZoneName?windowsTimeZoneName=' + winTzName, false); xmlHttp.send(); if (xmlHttp.status == 404) { aras.AlertError('Could not found timeZone: ' + winTzName); return; } // Get olson time zone name by windows time zone name var olsonTzName = xmlHttp.responseText; dojo.require('Aras.Client.Controls.Experimental.TimeZoneInfo'); var tzInfo = Aras.Client.Controls.Experimental.TimeZoneInfo.getTzInfo(date, olsonTzName); return tzInfo.tzOffset; }; /*** * @returns {*} Timezone name in windows format */ TimeZonesInformation.prototype.getTimeZoneLabel = function() { var getZoneNameFromDateString = function(str) { if (!str || (str && (str.indexOf('(') === -1 || str.indexOf(')') === -1))) { return; } var regexp1 = /.*?\((.*).*/; str = regexp1.exec(str)[1]; if (!str) { return; } var regexp2 = /(.*)\)/; str = regexp2.exec(str)[1]; if (str) { return str; } }; var timeZoneName; if ((aras.Browser.isIe() || aras.Browser.isFf()) && aras.Browser.OSName === 'Windows') { var dateString = (new Date()).toString(); timeZoneName = getZoneNameFromDateString(dateString); } if (!timeZoneName) { timeZoneName = jstz.determine().name(); } return timeZoneName || ''; }; /*** * @returns {*} Timezone name in windows format */ TimeZonesInformation.prototype.getWindowsTimeZoneName = function TimeZonesInformation_getWindowsTimeZoneName() { dojo.require("Aras.Client.Controls.Experimental.TimeZoneInfo"); var timeZoneName = aras.utils.systemInfo.currentTimeZoneName; if (timeZoneName.indexOf("/") > 0) { // Olson timezone has {country}/{city} format var xmlHttp = new XmlHttpRequestManager().CreateRequest(); xmlHttp.open("GET", aras.getBaseURL() + "/TimeZone/GetWindowTimeZoneName?olsonTimeZoneName=" + timeZoneName, false); xmlHttp.send(); if (xmlHttp.status == 404) { aras.AlertError("Could not found timeZone: " + timeZoneName); return; } return xmlHttp.responseText; } return timeZoneName; }; TimeZonesInformation.prototype.getWindowsTimeZoneNames = function(tzLabel) { var inputType = tzLabel.indexOf('/') > 0 ? 'iana' : 'windows'; var localTime = (new Date()).toISOString(); var localTimeOffset = (-1 * (new Date()).getTimezoneOffset()).toString(); var url = aras.getBaseURL() + '/TimeZone/GetTimezoneNames?tzlabel=' + encodeURIComponent(tzLabel) + '&inputType=' + encodeURIComponent(inputType) + '&localTime=' + encodeURIComponent(localTime) + '&offsetBetweenLocalTimeAndUTCTime=' + encodeURIComponent(localTimeOffset); var xmlHttp = new XMLHttpRequest(); xmlHttp.open('GET', url, false); xmlHttp.send(); if (xmlHttp.status !== 200) { aras.AlertError('Could not found timeZone: ' + tzLabel); return []; } return JSON.parse(xmlHttp.responseText).map(function(tz) {return tz.id;}); }; TimeZonesInformation.prototype.setTimeZoneNameInLocalStorage = function(tzLabel, tzName) { var tzOffset = -1 * (new Date()).getTimezoneOffset(); var timeZones = {}; timeZones[tzOffset + tzLabel] = tzName; localStorage.setItem('timeZone', JSON.stringify(timeZones)); }; TimeZonesInformation.prototype.getTimeZoneNameFromLocalStorage = function(tzLabel) { var tzOffset = -1 * (new Date()).getTimezoneOffset(); var timeZones = JSON.parse(localStorage.getItem('timeZone')); if (timeZones && timeZones.hasOwnProperty(tzOffset + tzLabel)) { return timeZones[tzOffset + tzLabel]; } }; /** md5.js **/ /* * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as defined in RFC 1321. * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for more info. */ /* * Configurable variables. You may need to tweak these to be compatible with * the server-side, but the defaults work in most cases. */ var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */ var b64pad = ''; /* base-64 pad character. "=" for strict RFC compliance */ var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */ /* * These are the functions you'll usually want to call * They take string arguments and return either hex or base-64 encoded strings */ function hexMd5(s) { return binl2hex(coreMd5(str2binl(s), s.length * chrsz)); } function b64Md5(s) { return binl2b64(coreMd5(str2binl(s), s.length * chrsz)); } function strMd5(s) { return binl2str(coreMd5(str2binl(s), s.length * chrsz)); } function hexHmacMd5(key, data) { return binl2hex(coreHmacMd5(key, data)); } function b64HmacMd5(key, data) { return binl2b64(coreHmacMd5(key, data)); } function strHmacMd5(key, data) { return binl2str(coreHmacMd5(key, data)); } /* * Perform a simple self-test to see if the VM is working */ function md5VmTest() { return hexMd5('abc') == '900150983cd24fb0d6963f7d28e17f72'; } /* * Call hexMd5, adding new param (compatibility with older version) */ function calcMD5(str) { if (!str) { return ''; } return hexMd5(str); } /* * Calculate the MD5 of an array of little-endian words, and a bit length */ function coreMd5(x, len) { /* append padding */ x[len >> 5] |= 0x80 << ((len) % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; var a = 1732584193; var b = -271733879; var c = -1732584194; var d = 271733878; for (var i = 0; i < x.length; i += 16) { var olda = a; var oldb = b; var oldc = c; var oldd = d; a = md5ff(a, b, c, d, x[i + 0], 7, -680876936); d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); c = md5ff(c, d, a, b, x[i + 10], 17, -42063); b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); b = md5gg(b, c, d, a, x[i + 0], 20, -373897302); a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); a = md5hh(a, b, c, d, x[i + 5], 4, -378558); d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); d = md5hh(d, a, b, c, x[i + 0], 11, -358537222); c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); a = md5ii(a, b, c, d, x[i + 0], 6, -198630844); d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); a = safeAdd(a, olda); b = safeAdd(b, oldb); c = safeAdd(c, oldc); d = safeAdd(d, oldd); } return Array(a, b, c, d); } /* * These functions implement the four basic operations the algorithm uses. */ function md5cmn(q, a, b, x, s, t) { return safeAdd(bitRol(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); } function md5ff(a, b, c, d, x, s, t) { return md5cmn((b & c) | ((~b) & d), a, b, x, s, t); } function md5gg(a, b, c, d, x, s, t) { return md5cmn((b & d) | (c & (~d)), a, b, x, s, t); } function md5hh(a, b, c, d, x, s, t) { return md5cmn(b ^ c ^ d, a, b, x, s, t); } function md5ii(a, b, c, d, x, s, t) { return md5cmn(c ^ (b | (~d)), a, b, x, s, t); } /* * Calculate the HMAC-MD5, of a key and some data */ function coreHmacMd5(key, data) { var bkey = str2binl(key); if (bkey.length > 16) { bkey = coreMd5(bkey, key.length * chrsz); } var ipad = Array(16); var opad = Array(16); for (var i = 0; i < 16; i++) { ipad[i] = bkey[i] ^ 0x36363636; opad[i] = bkey[i] ^ 0x5C5C5C5C; } var hash = coreMd5(ipad.concat(str2binl(data)), 512 + data.length * chrsz); return coreMd5(opad.concat(hash), 512 + 128); } /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function safeAdd(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF); var msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } /* * Bitwise rotate a 32-bit number to the left. */ function bitRol(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); } /* * Convert a string to an array of little-endian words * If chrsz is ASCII, characters >255 have their hi-byte silently ignored. */ function str2binl(str) { var bin = Array(); var mask = (1 << chrsz) - 1; for (var i = 0; i < str.length * chrsz; i += chrsz) { bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (i % 32); } return bin; } /* * Convert an array of little-endian words to a string */ function binl2str(bin) { var str = ''; var mask = (1 << chrsz) - 1; for (var i = 0; i < bin.length * 32; i += chrsz) { str += String.fromCharCode((bin[i >> 5] >>> (i % 32)) & mask); } return str; } /* * Convert an array of little-endian words to a hex string. */ function binl2hex(binarray) { var hexTab = hexcase ? '0123456789ABCDEF' : '0123456789abcdef'; var str = ''; for (var i = 0; i < binarray.length * 4; i++) { str += hexTab.charAt((binarray[i >> 2] >> ((i % 4) * 8 + 4)) & 0xF) + hexTab.charAt((binarray[i >> 2] >> ((i % 4) * 8)) & 0xF); } return str; } /* * Convert an array of little-endian words to a base-64 string */ function binl2b64(binarray) { var tab = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var str = ''; for (var i = 0; i < binarray.length * 4; i += 3) { var triplet = (((binarray[i >> 2] >> 8 * (i % 4)) & 0xFF) << 16) | (((binarray[i + 1 >> 2] >> 8 * ((i + 1) % 4)) & 0xFF) << 8) | ((binarray[i + 2 >> 2] >> 8 * ((i + 2) % 4)) & 0xFF); for (var j = 0; j < 4; j++) { if (i * 8 + j * 6 > binarray.length * 32) { str += b64pad; } else { str += tab.charAt((triplet >> 6 * (3 - j)) & 0x3F); } } } return str; } /** cookie.js **/ // // Cookie Functions -- "Night of the Living Cookie" Version (25-Jul-96) // // Written by: Bill Dortch, hIdaho Design // The following functions are released to the public domain. // // This version takes a more aggressive approach to deleting // cookies. Previous versions set the expiration date to one // millisecond prior to the current time; however, this method // did not work in Netscape 2.02 (though it does in earlier and // later versions), resulting in "zombie" cookies that would not // die. DeleteCookie now sets the expiration date to the earliest // usable date (one second into 1970), and sets the cookie's value // to null for good measure. // // Also, this version adds optional path and domain parameters to // the DeleteCookie function. If you specify a path and/or domain // when creating (setting) a cookie**, you must specify the same // path/domain when deleting it, or deletion will not occur. // // The FixCookieDate function must now be called explicitly to // correct for the 2.x Mac date bug. This function should be // called *once* after a Date object is created and before it // is passed (as an expiration date) to SetCookie. Because the // Mac date bug affects all dates, not just those passed to // SetCookie, you might want to make it a habit to call // FixCookieDate any time you create a new Date object: // // var theDate = new Date(); // FixCookieDate (theDate); // // Calling FixCookieDate has no effect on platforms other than // the Mac, so there is no need to determine the user's platform // prior to calling it. // // This version also incorporates several minor coding improvements. // // **Note that it is possible to set multiple cookies with the same // name but different (nested) paths. For example: // // SetCookie ("color","red",null,"/outer"); // SetCookie ("color","blue",null,"/outer/inner"); // // However, GetCookie cannot distinguish between these and will return // the first cookie that matches a given name. It is therefore // recommended that you *not* use the same name for cookies with // different paths. (Bear in mind that there is *always* a path // associated with a cookie; if you don't explicitly specify one, // the path of the setting document is used.) // // Revision History: // // "Toss Your Cookies" Version (22-Mar-96) // - Added FixCookieDate() function to correct for Mac date bug // // "Second Helping" Version (21-Jan-96) // - Added path, domain and secure parameters to SetCookie // - Replaced home-rolled encode/decode functions with Netscape's // new (then) escape and unescape functions // // "Free Cookies" Version (December 95) // // // For information on the significance of cookie parameters, and // and on cookies in general, please refer to the official cookie // spec, at: // // http://www.netscape.com/newsref/std/cookie_spec.html // //****************************************************************** // // "Internal" function to return the decoded value of a cookie // function getCookieVal(offset) { var endstr = document.cookie.indexOf(';', offset); if (endstr == -1) { endstr = document.cookie.length; } return unescape(document.cookie.substring(offset, endstr)); } // // Function to correct for 2.x Mac date bug. Call this function to // fix a date object prior to passing it to SetCookie. // IMPORTANT: This function should only be called *once* for // any given date object! See example at the end of this document. // function FixCookieDate(date) { var base = new Date(0); var skew = base.getTime(); // dawn of (Unix) time - should be 0 if (skew > 0) { // Except on the Mac - ahead of its time date.setTime(date.getTime() - skew); } } // // Function to return the value of the cookie specified by "name". // name - String object containing the cookie name. // returns - String object containing the cookie value, or null if // the cookie does not exist. // function GetCookie(name) { var arg = name + '='; var alen = arg.length; var clen = document.cookie.length; var i = 0; while (i < clen) { var j = i + alen; if (document.cookie.substring(i, j) == arg) { return getCookieVal(j); } i = document.cookie.indexOf(' ', i) + 1; if (i === 0) { break; } } return null; } // // Function to create or update a cookie. // name - String object containing the cookie name. // value - String object containing the cookie value. May contain // any valid string characters. // [expires] - Date object containing the expiration data of the cookie. If // omitted or null, expires the cookie at the end of the current session. // [path] - String object indicating the path for which the cookie is valid. // If omitted or null, uses the path of the calling document. // [domain] - String object indicating the domain for which the cookie is // valid. If omitted or null, uses the domain of the calling document. // [secure] - Boolean (true/false) value indicating whether cookie transmission // requires a secure channel (HTTPS). // // The first two parameters are required. The others, if supplied, must // be passed in the order listed above. To omit an unused optional field, // use null as a place holder. For example, to call SetCookie using name, // value and path, you would code: // // SetCookie ("myCookieName", "myCookieValue", null, "/"); // // Note that trailing omitted parameters do not require a placeholder. // // To set a secure cookie for path "/myPath", that expires after the // current session, you might code: // // SetCookie (myCookieVar, cookieValueVar, null, "/myPath", null, true); // function SetCookie(name, value, expires, path, domain, secure) { document.cookie = name + '=' + escape(value) + ((expires) ? '; expires=' + expires.toUTCString() : '') + ((path) ? '; path=' + path : '') + ((domain) ? '; domain=' + domain : '') + ((secure) ? '; secure' : ''); } // Function to delete a cookie. (Sets expiration date to start of epoch) // name - String object containing the cookie name // path - String object containing the path of the cookie to delete. This MUST // be the same as the path used to create the cookie, or null/omitted if // no path was specified when creating the cookie. // domain - String object containing the domain of the cookie to delete. This MUST // be the same as the domain used to create the cookie, or null/omitted if // no domain was specified when creating the cookie. // function DeleteCookie(name, path, domain) { if (GetCookie(name)) { document.cookie = name + '=' + ((path) ? '; path=' + path : '') + ((domain) ? '; domain=' + domain : '') + '; expires=Thu, 01-Jan-70 00:00:01 GMT'; } } /** soap_object.js **/ // (c) Copyright by Aras Corporation, 2004-2009. /*---------------------------------------- * FileName: soap_object.js * * Purpose: * Provide a way to comminucate with InnovatorServer using SOAP messages * */ /// /// For internal use only. /// Stores a set of Soap related constants. /// /// /// /// /// var SoapConstants = {}; /// /// URI to SOAP 1.1 schema /// /// /// /// /// SoapConstants.SoapEnvUri = 'http://schemas.xmlsoap.org/soap/envelope/'; /// /// Namespace used to return SOAP messages. /// /// /// /// /// SoapConstants.SoapNamespace = 'SOAP-ENV'; /// /// Opening tags Envelope, Body /// /// /// /// /// SoapConstants.EnvelopeBodyStart = '<' + SoapConstants.SoapNamespace + ':Envelope xmlns:' + SoapConstants.SoapNamespace + '="' + SoapConstants.SoapEnvUri + '"><' + SoapConstants.SoapNamespace + ':Body>'; /// /// /// /// /// /// /// SoapConstants.EnvelopeBodyEnd = ''; /// /// Opening tags Envelope, Body, Fault /// /// /// /// /// SoapConstants.EnvelopeBodyFaultStart = SoapConstants.EnvelopeBodyStart + '<' + SoapConstants.SoapNamespace + ':Fault>'; /// /// /// /// /// /// /// SoapConstants.EnvelopeBodyFaultEnd = '' + SoapConstants.EnvelopeBodyEnd; /// /// Check of namespace to be used in XPath /// /// /// /// /// SoapConstants.SoapNamespaceCheck = 'namespace-uri()=\'' + SoapConstants.SoapEnvUri + '\' or namespace-uri()=\'\''; /// /// XPath for Envelope /// /// /// /// /// SoapConstants.EnvelopeXPath = '*[local-name()=\'Envelope\' and (' + SoapConstants.SoapNamespaceCheck + ')]'; /// /// XPath for Body /// /// /// /// /// SoapConstants.BodyXPath = '*[local-name()=\'Body\' and (' + SoapConstants.SoapNamespaceCheck + ')]'; /// /// XPath for Fault /// /// /// /// /// SoapConstants.FaultXPath = '*[local-name()=\'Fault\' and (' + SoapConstants.SoapNamespaceCheck + ')]'; /// /// XPath for Envelope/Body /// /// /// /// /// SoapConstants.EnvelopeBodyXPath = SoapConstants.EnvelopeXPath + '/' + SoapConstants.BodyXPath; /// /// XPath for Envelope/Body/Fault /// /// /// /// /// SoapConstants.EnvelopeBodyFaultXPath = SoapConstants.EnvelopeBodyXPath + '/' + SoapConstants.FaultXPath; /* SoapController is designed to manage asynchronous soap requests. Contains: callback - function which is called when request is finished The parameter is passed to constructor. stop - readonly parameter. Function which can be used to abort request */ function SoapController(callback) { this.isInvalid = false; this.callback = callback; this.stop = null; } //marks soap controller instance as invalid. For example when callback is no longer valid (for example when window is closed) //this will prevent script errors. SoapController.prototype.markInvalid = function SoapController_markInvalid() { this.isInvalid = true; }; function SOAP(parent) { this.parent = parent; //parent aras object if (parent.getCurrentLoginName()) { ArasModules.soap(null, { url: parent.getServerURL(), method: 'ApplyItem', headers: { 'AUTHUSER': encodeURIComponent(parent.getCurrentLoginName()), 'AUTHPASSWORD': parent.getCurrentPassword(), 'DATABASE': encodeURIComponent(parent.getDatabase()), 'LOCALE': parent.getCommonPropertyValue('systemInfo_CurrentLocale'), 'TIMEZONE_NAME': parent.getCommonPropertyValue('systemInfo_CurrentTimeZoneName') } }); } } SOAP.prototype.send = function SOAP_send(methodName, bodyStr, url, saveChanges, soapController, is_bgrequest, authController, skip_empty_pwd) { /*---------------------------------------- * send * * Purpose: * send xml to InovatorServer and return result. * returns SOAPResults object * * Arguments: * methodName - string with Innovator Server method name (ApplyItem, GetItem, ...) * bodyStr - xml string to send * url - url of Innovator Server (by default url is built from this.parent.baseURL) * * soapController - an instance of SoapController */ var self = this; var arasableObj = this.parent; if (!arasableObj || methodName === undefined) { return null; } if (!arasableObj.getCommonPropertyValue('ignoreSessionTimeoutInSoapSend') && arasableObj.getCommonPropertyValue('exitWithoutSavingInProgress')) { return new SOAPResults(arasableObj, getFaultXml('The session is closed.'), saveChanges); } var options = {method: methodName}; if (url) { options.url = url; } var methodXmlns = ''; if (methodName.indexOf('/') !== -1) { methodXmlns = methodName.substring(0, methodName.lastIndexOf('/')); methodName = methodName.substring(methodName.lastIndexOf('/') + 1, methodName.length); } if (methodXmlns) { options.methodNm = methodXmlns; } var soapStr = removeUnchangedPermission(bodyStr || ''); if (soapStr && arasableObj.Browser.isIe()) { soapStr = soapStr.replace(/\r\n/g, '\n'); } SaveRequestToLog(soapStr); var pwd = arasableObj.getCurrentPassword(); var resStr = ''; if (!pwd && !skip_empty_pwd) { var errDescription = arasableObj.getResource('', 'soap_object.pwd_cannot_be_empty'); resStr = getFaultXml(errDescription); return new SOAPResults(arasableObj, resStr, saveChanges); } var async = !!(soapController && soapController.callback); options.async = async; var promise = ArasModules.soap(soapStr, options); if (async) { soapController.stop = promise.abort; } var result; promise.then(function(resultNode) { var text; if (resultNode.ownerDocument) { var doc = resultNode.ownerDocument; text = doc.xml || (new XMLSerializer()).serializeToString(doc); } else { text = resultNode; } var finalRetVal = new SOAPResults(arasableObj, text, saveChanges); if (methodName && methodName.toLowerCase() === 'validateuser') { arasableObj.setCommonPropertyValue('ValidateUserXmlResult', text); } if (async) { if (!soapController.isInvalid) { soapController.callback(finalRetVal); } return; } result = finalRetVal; }).catch(function (xhr) { var res = new SOAPResults(arasableObj, xhr.responseText, saveChanges); if (async) { if (!soapController.isInvalid) { soapController.callback(res); } return; } result = res; }); return result; //function region >>>>>>>>>>>>>>>>>> function removeUnchangedPermission(bodyStr) { //select all permission_id nodes with attribute origPermission where origPermission if (!bodyStr) { return bodyStr; } var workDom = new XmlDocument(); workDom.loadXML(bodyStr); var permissionNodes = workDom.selectNodes('//descendant-or-self::node()[local-name(.) = \'permission_id\' and not(child::Item) and @origPermission]'); if (permissionNodes && permissionNodes.length > 0) { for (var i = 0; i < permissionNodes.length; i++) { if (permissionNodes[i].getAttribute('origPermission') == permissionNodes[i].text) { var parent = permissionNodes[i].parentNode; parent.removeChild(permissionNodes[i]); } else { permissionNodes[i].removeAttribute('origPermission'); } } } return workDom.xml; } function getFaultXml(descr) { var faultRetVal = SoapConstants.EnvelopeBodyFaultStart + '' + SoapConstants.SoapNamespace + ':Server' + descr + '' + SoapConstants.EnvelopeBodyFaultEnd; return faultRetVal; } function SaveRequestToLog(soapStr) { // save soap message to local file system if ('true' === arasableObj.getVariable('SaveRequest')) { arasableObj.saveString2File(function() { return soapStr; }, 'xml', methodName + '_' + self.getDateStamp().replace(/:/g, '_')); } } }; SOAP.showExitExcuse = function(arasableObj) { var p = {}; var mainWnd = arasableObj.getMainWindow(); p.buttons = {}; p.buttons.btnExit = arasableObj.getResource('', 'soap_object.exit_innovator'); p.defaultButton = 'btnExit'; p.btnstyles = {btnExit: ''}; p.message = arasableObj.getResource('', 'soap_object.session_has_expired'); p.message += arasableObj.getResource('', 'soap_object.changes_will_be_lost_warning'); p.aras = arasableObj; mainWnd.focus(); mainWnd.showModalDialog(arasableObj.getScriptsURL() + 'groupChgsDialog.html', p, 'dialogHeight:150px;dialogWidth:300px;center:yes;resizable:no;status:no;help:no;'); }; SOAP.checkIsSessionTimeOut = function(responseText) { var aras = TopWindowHelper.getMostTopWindowWithAras(window).aras || window.opener.aras; var mainWnd = aras.getMainWindow(); if (!mainWnd) { return false; } if (sessionStorage.getItem('ArasSessionCheck')) { mainWnd.DoFocusAfterAlert = true; return false; } sessionStorage.setItem('ArasSessionCheck', true); var data = { title: aras.getResource('', 'soap_object.confirm_password'), md5: aras.getPassword(), fieldName2ReturnMD5: 'oldhash', oldMsg: aras.getResource('', 'soap_object.confirm_password2'), oldPwdOnly: true, aras: aras, dialogWidth: 300, dialogHeight: 120, center: true, content: 'changeMD5Dialog.html' }; var win = TopWindowHelper.getMostTopWindowWithAras(window); var argwin = (win.main || win); mainWnd.focus(); var process = function (password) { if (password === undefined) { var style = 'style="width: 100px; margin: 5px;"'; var dialogParams = { buttons: { btnReturn: aras.getResource('', 'soap_object.return_to_login'), btnExit: aras.getResource('', 'soap_object.exit_innovator') }, defaultButton: 'btnReturn', btnstyles: {btnReturn: style, btnExit: style}, btnclasses: {btnReturn: '', btnExit: 'cancel_button'}, message: aras.getResource('', 'soap_object.changes_will_be_lost_warning'), aras: aras, dialogHeight: 150, content: 'groupChgsDialog.html', dialogWidth: 300, dialogHeight: 120, center: true }; argwin.ArasModules.Dialog.show('iframe', dialogParams).promise.then(function (tmpRes) { if (tmpRes !== 'btnReturn') { aras.setCommonPropertyValue('exitWithoutSavingInProgress', true); if (mainWnd && aras.browserHelper) { aras.browserHelper.closeWindow(mainWnd); } return false; } argwin.ArasModules.Dialog.show('iframe', data).promise.then(process); }); } else if (password !== aras.getPassword()) { mainWnd.DoFocusAfterAlert = true; return aras.AlertError(aras.getResource('', 'soap_object.pwd_is_wrong')).then(function () { return argwin.ArasModules.Dialog.show('iframe', data).promise.then(process); }); } else { var valid = false; return ArasModules.nativSoap('', { method: 'ValidateUser' }).then(function() { return true; }, function(xhr) { return aras.AlertError(new SOAPResults(aras, xhr.responseText, false)); }); } }; var dialog = argwin.ArasModules.Dialog.show('iframe', data).promise.then(process); return dialog; }; SOAP.prototype.parseResponseHeaders = function SOAP_parseResponseHeaders(xmlhttp, arasableObj) { }; SOAP.prototype.getDateStamp = function SOAP_getDateStamp() { var date = new Date(); var now = date.getFullYear() + '-'; if (date.getMonth() < 10) { now += '0'; } now += date.getMonth() + '-'; if (date.getDate() < 10) { now += '0'; } now += date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds() + ':' + date.getMilliseconds(); return now; }; /////////////////////////////////////////////////////////////////////////////////////////// // SOAPResults function SOAPResults(arasableObj, resultsXML, saveChanges) { this.arasableObj = arasableObj; //parent aras object var xmlWithPermissions; if (resultsXML) { xmlWithPermissions = setOriginalPermissionID(resultsXML); this.results = xmlWithPermissions; } else { this.results = arasableObj.createXMLDocument(); } //lazy "xmlWithPermissions.xml" calculating to consume memory (mainly) and cpu only when resultsXML is called Object.defineProperty(this, 'resultsXML', { get: function() { return !xmlWithPermissions ? '' : xmlWithPermissions.xml; } }); var message = this.getMessage(); arasableObj.refreshWindows(message, this.results, saveChanges); function setOriginalPermissionID(resultsXML) { var workDom = arasableObj.createXMLDocument(); workDom.loadXML(resultsXML); //select all nodes "permission_id" var permissionNodes = workDom.selectNodes('//permission_id'); if (permissionNodes && permissionNodes.length > 0) { for (var i = 0; i < permissionNodes.length; i++) { if (permissionNodes[i].selectSingleNode('./Item') === null) { //if it doesn't contain any child nodes - set attribute origPermission = innerText permissionNodes[i].setAttribute('origPermission', permissionNodes[i].text); } else { //else select id of child Item node and set attribute origPermission = id permissionNodes[i].setAttribute('origPermission', permissionNodes[i].selectSingleNode('./Item/@id').value); } } } return workDom; } } SOAPResults.prototype.getResponseText = function() { return this.resultsXML; }; SOAPResults.prototype.getParseError = function() { var res; if (this.results.parseError.errorCode !== 0) { res = '*** Wrong SOAP message! *** ' + '\n\n' + 'Error: ' + this.results.parseError.srcText.replace('H1', 'H3') + '\n' + 'ErrorCode: ' + this.results.parseError.errorCode + '\n' + 'Reason: ' + this.results.parseError.reason; } else { res = undefined; } return res; }; SOAPResults.prototype.isFault = function SOAPResults_isFault() { if (this.results.parseError.errorCode !== 0) { return this.getParseError(); } var fault = this.results.selectSingleNode(TopWindowHelper.getMostTopWindowWithAras(window).aras.XPathFault()); if (fault) { return true; } else { return false; } }; SOAPResults.prototype.getFaultCode = function() { if (this.results.parseError.errorCode !== 0) { return this.getParseError(); } var faultcode = this.results.selectSingleNode(TopWindowHelper.getMostTopWindowWithAras(window).aras.XPathFault('/faultcode')); if (faultcode) { return faultcode.text; } else { return 0; } }; SOAPResults.prototype.getFaultString = function() { if (this.results.parseError.errorCode !== 0) { return this.getParseError(); } var faultstring = this.results.selectSingleNode(TopWindowHelper.getMostTopWindowWithAras(window).aras.XPathFault('/faultstring')); if (faultstring) { return faultstring.text; } else { return ''; } }; SOAPResults.prototype.getFaultActor = function() { if (this.results.parseError.errorCode !== 0) { return this.getParseError(); } var faultactor = this.results.selectSingleNode(TopWindowHelper.getMostTopWindowWithAras(window).aras.XPathFault('/detail/legacy_faultactor')); if (faultactor) { return faultactor.text; } else { return ''; } }; SOAPResults.prototype.getFaultDetails = function() { if (this.results.parseError.errorCode !== 0) { return this.getParseError(); } var detail = this.results.selectSingleNode(TopWindowHelper.getMostTopWindowWithAras(window).aras.XPathFault('/detail')); var msg = ''; if (detail) { msg = detail.text; //.replace(/^.+\]/,''); // msg = msg.replace(/,.+$/,''); } return msg; }; SOAPResults.prototype.getServerMessage = function SOAPResults_getServerMessage() { var faultNd = this.results.selectSingleNode(TopWindowHelper.getMostTopWindowWithAras(window).aras.XPathFault()); if (faultNd && faultNd.parentNode) { var serverMessageNd = faultNd.parentNode.selectSingleNode('server_message'); if (serverMessageNd) { return serverMessageNd.xml; } } }; SOAPResults.prototype.getResultsBody = function() { var res = this.getResult(); var items = res.selectNodes('Item'); return items.length == 1 ? items[0].xml : res.xml; }; SOAPResults.prototype.getResult = function() { var res = null; if (this.results && this.results.documentElement) { res = this.results.selectSingleNode(TopWindowHelper.getMostTopWindowWithAras(window).aras.XPathResult()); } if (!res) { var subst = this.arasableObj.createXMLDocument(); subst.loadXML(SoapConstants.EnvelopeBodyStart + '' + SoapConstants.EnvelopeBodyEnd); res = subst.documentElement.selectSingleNode(TopWindowHelper.getMostTopWindowWithAras(window).aras.XPathResult()); } return res; }; SOAPResults.prototype.getMessage = function() { var res = null; if (this.results && this.results.documentElement) { res = this.results.selectSingleNode(TopWindowHelper.getMostTopWindowWithAras(window).aras.XPathMessage()); } if (!res) { var subst = new XmlDocument(); subst.loadXML(SoapConstants.EnvelopeBodyStart + '' + SoapConstants.EnvelopeBodyEnd); res = subst.documentElement.selectSingleNode(TopWindowHelper.getMostTopWindowWithAras(window).aras.XPathMessage()); } return res; }; SOAPResults.prototype.getMessageValue = function SOAPResults_getMessageValue(key) { var msg; if (this.isFault()) { msg = this.results.selectSingleNode(TopWindowHelper.getMostTopWindowWithAras(window).aras.XPathFault('/detail/message[@key=\'' + key + '\']')); } else { var nd = this.getMessage(); if (nd) { msg = nd.selectSingleNode('event[@name=\'' + key + '\']'); } } return (msg ? msg.getAttribute('value') : undefined); }; /** item_methods.js **/ // © Copyright by Aras Corporation, 2004-2011. /* * The item methods extension for the Aras Object. * most of methods in this file use itemID and itemTypeName as parameters */ /*-- newFileItem * * Method to create a new item of ItemType File * fileNameOrObject = the name of the file or FileObject * */ Aras.prototype.newFileItem = function Aras_newFileItem(fileNameOrObject) { var brief_fileName = ""; if (typeof fileNameOrObject === "string") { var parts = fileNameOrObject.split(/[\\\/]/); brief_fileName = parts[parts.length - 1]; } else { brief_fileName = fileNameOrObject.name; } with (this) { var item = createXmlElement('Item'); item.setAttribute('type', 'File'); item.setAttribute('id', generateNewGUID()); item.setAttribute('action', 'add'); item.setAttribute('loaded', '1'); item.setAttribute('levels', '1'); item.setAttribute('isTemp', '1'); setItemProperty(item, 'filename', brief_fileName); if (typeof fileNameOrObject === "string") { setItemProperty(item, 'checkedout_path', fileNameOrObject.substring(0, fileNameOrObject.length - brief_fileName.length - 1)); } else { setItemProperty(item, 'checkedout_path', ''); aras.vault.addFileToList(item.getAttribute('id'), fileNameOrObject); } var fileSize = aras.vault.getFileSize(fileNameOrObject); setItemProperty(item, 'file_size', fileSize); var locatedItemId = getRelationshipTypeId('Located'); if (!locatedItemId) { AlertError(getResource('', 'item_methods.located_item_type_not_exist')); return null; } var locatedItem = newRelationship(locatedItemId, item, false, null, null); var vaultServerID = getVaultServerID(); if (vaultServerID == '') { AlertError(getResource('', 'item_methods.no_defualt_vault_sever'), window); return null; } setItemProperty(locatedItem, 'related_id', vaultServerID); return item; } }; /*-- newItem * * Method to create a new item * itemTypeName = the name of the ItemType * */ Aras.prototype.newItem = function Aras_newItem(itemTypeName, itemTypeNdOrSpecialArg) { var self = this; function newItem_internal(arasObj, filePath) { var item = null; var typeId = itemType.getAttribute('id'); if (itemTypeName == 'Workflow Map') { item = arasObj.newWorkflowMap(); item.setAttribute('typeId', typeId); return item; } if (itemTypeName === 'File') { var fileName = null; var isFileNameSpecified = itemTypeNdOrSpecialArg; if (isFileNameSpecified) { fileName = itemTypeNdOrSpecialArg; } else { var vault = arasObj.vault; fileName = vault.selectFile(); } if (fileName) { item = arasObj.newFileItem(fileName); item.setAttribute('typeId', typeId); } return item; } item = self.createXmlElement('Item'); item.setAttribute('type', itemTypeName); item.setAttribute('id', arasObj.GUIDManager.GetGUID()); item.setAttribute('action', 'add'); item.setAttribute('loaded', '1'); item.setAttribute('levels', '1'); item.setAttribute('isTemp', '1'); item.setAttribute('typeId', typeId); var properties = itemType.selectNodes('Relationships/Item[@type="Property" and default_value and not(default_value[@is_null="1"])]'); for (var i = 0; i < properties.length; i++) { var property = properties[i]; var propertyName = arasObj.getItemProperty(property, 'name'); var dataType = arasObj.getItemProperty(property, 'data_type'); var defaultValue = arasObj.getItemProperty(property, 'default_value'); if (dataType == 'item') { var dataSource = property.selectSingleNode('data_source'); if (dataSource) { dataSource = dataSource.getAttribute('name'); } if (dataSource) { defaultValue = arasObj.getItemById(dataSource, defaultValue, 0); } } arasObj.setItemProperty(item, propertyName, defaultValue, undefined, itemType); } if (itemTypeName == 'Life Cycle Map') { var stateTypeID = arasObj.getRelationshipTypeId('Life Cycle State'); var newState = arasObj.newRelationship(stateTypeID, item); arasObj.setItemProperty(newState, 'name', 'Start'); arasObj.setItemProperty(newState, 'image', '../images/LifeCycleState.svg'); arasObj.setItemProperty(item, 'start_state', newState.getAttribute('id')); } else if (itemTypeName == 'Form') { arasObj.setItemProperty(item, 'stylesheet', '../styles/default.css'); var relTypeID = arasObj.getRelationshipTypeId('Body'); var bodyRel = arasObj.newRelationship(relTypeID, item); } return item; } var isItemTypeSpecified = itemTypeNdOrSpecialArg && itemTypeNdOrSpecialArg.xml; var itemType = isItemTypeSpecified ? itemTypeNdOrSpecialArg : this.getItemTypeForClient(itemTypeName).node; if (!itemType) { this.AlertError(this.getResource('', 'ui_methods_ex.item_type_not_found', itemTypeName)); return false; } function handleNewItemType(newTypeName) { if (newTypeName) { var new_itemNd = self.newItem(newTypeName); self.itemsCache.addItem(new_itemNd); return new_itemNd; } else { return null; } } if (this.isPolymorphic(itemType)) { var itemTypesList = this.getMorphaeList(itemType); var selectionDialog = this.uiItemTypeSelectionDialog(itemTypesList, arguments[3]); if (selectionDialog && selectionDialog.then) { return selectionDialog.then(handleNewItemType); } else { return handleNewItemType(selectionDialog) } } var onBeforeNewEv = itemType.selectNodes('//Item[client_event="OnBeforeNew"]/related_id/Item'); var onAfterNewEv = itemType.selectNodes('//Item[client_event="OnAfterNew"]/related_id/Item'); var onNewEv = itemType.selectSingleNode('//Item[client_event="OnNew"]/related_id/Item'); var res; var xml = ''; if (onBeforeNewEv.length) { for (var i = 0; i < onBeforeNewEv.length; i++) { try { res = this.evalMethod(this.getItemProperty(onBeforeNewEv[i], 'name'), xml); } catch (exp) { this.AlertError(this.getResource('', 'item_methods.event_handler_failed'), this.getResource('', 'item_methods.event_handler_failed_with_message', exp.description), this.getResource('', 'common.client_side_err')); return null; } if (res === false) { return null; } } } if (onNewEv) { res = this.evalMethod(this.getItemProperty(onNewEv, 'name'), xml); if (res) { res = res.node; } if (!res) { return null; } } else { res = newItem_internal(this); } if (onAfterNewEv.length && res) { for (var i = 0; i < onAfterNewEv.length; i++) { try { res = this.evalMethod(this.getItemProperty(onAfterNewEv[i], 'name'), res.xml); } catch (exp) { this.AlertError(this.getResource('', 'item_methods.event_handler_failed'), this.getResource('', 'item_methods.event_handler_failed_with_message', exp.description), this.getResource('', 'common.client_side_err')); return null; } if (res) { res = res.node; } if (!res) { return null; } } } if (onNewEv) { for (var name in this.windowsByName) { try { var win = this.windowsByName[name]; if (win && win.onRefresh) { win.onRefresh(); } } catch (excep) {} } res = null; } return res; }; /* * this function add item to packageDefinition */ Aras.prototype.addItemToPackageDef = function(strArrOfId, itemTypeName) { //check if items selected in grid if (strArrOfId.length < 1) { return; } var ArasObj = this; var packArray = null; var countOfPacks = 0; var htmlContent = ''; var params = new Object(); var itemTypeLabel = ''; var itemTypeId = this.getItemTypeId(itemTypeName); params.writeContent = writeContent; params.aras = ArasObj; // We need to replace id with config_id. var copyOfIds = new Array(); for (var i = 0; i < strArrOfId.length; i++) { copyOfIds.push('\'' + strArrOfId[i] + '\''); } var aml = '' + copyOfIds.join(',') + ''; var res = this.soapSend('ApplyItem', aml); if (res.getFaultCode() != 0) { this.AlertError(res); return; } res = res.getResultsBody(); var result = this.createXMLDocument(); result.loadXML(res); for (var i = 0; i < result.selectNodes('./Item').length; i++) { strArrOfId[i] = result.selectSingleNode('./Item[id=\'' + strArrOfId[i] + '\']/config_id').text; } //check if PackageDefinition exist var packageDefId = this.getItemTypeId('PackageDefinition'); if (!packageDefId) { ArasObj.AlertError(this.getResource('', 'item_methods.unable_get_package_definition_item_type')); return; } //getting the label of ItemType var itemType = this.getItemTypeForClient(itemTypeName); if (itemType) { //IR-014145 'Problem report with 'Add To Package Definition'' fix: we need only "en" label. var qyItemWithEnLbl = new this.getMostTopWindowWithAras(window).Item(); qyItemWithEnLbl.setAction('get'); qyItemWithEnLbl.setType('ItemType'); qyItemWithEnLbl.setProperty('name', itemTypeName); qyItemWithEnLbl.setAttribute('select', '*'); qyItemWithEnLbl.setAttribute('language', 'en'); resItemWithEnLbl = qyItemWithEnLbl.apply(); itemTypeLabel = resItemWithEnLbl.getProperty('label', undefined, 'en'); if (itemTypeLabel === undefined) { itemTypeLabel = itemTypeName; } } else { ArasObj.AlertError(this.getResource('', 'item_methods.unable_get_item_type', itemTypeName), ArasObj.getFaultString(qry.dom), ArasObj.getFaultActor(qry.dom)); return; } //query all packages existing in DBO getAllpackages(); /* * this function write content to modal window */ function writeContent(w) { w.document.write(htmlContent); } function ApplyItemInternal(action, type, attr, props) { var query = new ArasObj.getMostTopWindowWithAras(window).Item(); query.setAction(action); query.setType(type); query.setAttribute('doGetItem', 0); f(attr, true); f(props); function f(arr, isAttr) { if (arr && arr.length != 0) { for (var i = 0; i < arr.length; i++) { var tmp = arr[i].split('|'); if (isAttr) { query.setAttribute(tmp[0], tmp[1]); } else { query.setProperty(tmp[0], tmp[1]); } } } } return query.apply(); } /* * this function request all packages */ function getAllpackages() { packArray = ApplyItemInternal('get', 'PackageDefinition', new Array('select|name, id'), new Array('is_current|1')); countOfPacks = packArray.getItemCount(); } /*** * Add selected itemtype to package * @param strSelectedPack name of package */ function addItemsToPackage(strSelectedPack) { // Get id of PackageDefinition var strIdOfPackNode = packArray.dom.selectSingleNode('.//Result/Item[name=\'' + strSelectedPack + '\']/id'); // If user didn't checked any package if (!strIdOfPackNode) { return; } var strIdOfPack = strIdOfPackNode.text; // Get id of PackageGroup var qry = ApplyItemInternal('get', 'PackageGroup', new Array('select|id'), new Array('source_id|' + strIdOfPack, 'name|' + itemTypeLabel)); // In case group not exist create new one if (qry.isError()) { qry = ApplyItemInternal('add', 'PackageGroup', null, new Array('source_id|' + strIdOfPack, 'name|' + itemTypeLabel)); if (qry.isError()) { ArasObj.AlertError(ArasObj.getResource('', 'item_methods.unable_add_group', itemTypeLabel), ArasObj.getFaultString(qry.dom), ArasObj.getFaultActor(qry.dom)); return; } } var strIdOfGroup = qry.getAttribute('id'); var bWasError = false; for (var i = 0; i < strArrOfId.length; i++) { var strKeyedName = ArasObj.getKeyedName(strArrOfId[i], itemTypeName); qry = ApplyItemInternal('get', 'PackageElement', new Array('select|id'), new Array('source_id|' + strIdOfGroup, 'element_id|' + strArrOfId[i])); if (qry.isError()) { qry = ApplyItemInternal('add', 'PackageElement', null, new Array('source_id|' + strIdOfGroup, 'element_id|' + strArrOfId[i], 'name|' + strKeyedName, 'element_type|' + itemTypeName)); if (qry.isError()) { bWasError = true; ArasObj.AlertError(ArasObj.getResource('', 'item_methods.unable_add_item', strKeyedName), ArasObj.getFaultString(qry.dom), ArasObj.getFaultActor(qry.dom)); } } else { bWasError = true; ArasObj.AlertError(ArasObj.getResource('', 'item_methods.item_already_exsist_in_package', strKeyedName, strSelectedPack)); } } if (!bWasError) { if (strArrOfId.length > 1) { ArasObj.AlertSuccess(ArasObj.getResource('', 'item_methods.items_added_successfully')); } else { ArasObj.AlertSuccess(ArasObj.getResource('', 'item_methods.item_added_successfully')); } } } /* *param strNameOfPack - name of new package to be created *param strArrdependOns - array of package names to be depended by new package */ function createPackage(strNameOfPack, strArrdependOns) { qry = ArasObj.getItemFromServerByName('PackageDefinition', strNameOfPack, 'id'); if (qry && !qry.isError()) { ArasObj.AlertError(ArasObj.getResource('', 'item_methods.package_with_such_name_already_exist')); return false; } else { qry = ApplyItemInternal('add', 'PackageDefinition', null, new Array('name|' + strNameOfPack)); if (qry.isError()) { ArasObj.AlertError(ArasObj.getResource('', 'item_methods.unable_add_package_with_name', strNameOfPack), ArasObj.getFaultString(qry.dom), ArasObj.getFaultActor(qry.dom)); return false; } var strIdOfpack = qry.node.getAttribute('id'); for (var i = 0; i < strArrdependOns.length; i++) { if ('empty' == strArrdependOns[i]) { continue; } qry = ApplyItemInternal('add', 'PackageDependsOn', null, new Array('name|' + strArrdependOns[i], 'source_id|' + strIdOfpack)); if (qry.isError()) { ArasObj.AlertError(ArasObj.getResource('', 'item_methods.Unable to add dependency', strArrdependOns[i]), ArasObj.getFaultString(qry.dom), ArasObj.getFaultActor(qry.dom)); return false; } } } return true; } htmlContent = ''; htmlContent += ''; htmlContent += '
' + this.getResource('', 'item_methods.selected_package_from_list') + '
'; htmlContent += '
' + '' + firstOption + '
'; htmlContent += '
'; htmlContent += '
'; var win = this.getMostTopWindowWithAras(window); params.title = this.getResource('', 'item_methods.add_selected_items_to_a_package'); var modalCallback = function(packageName) { if (packageName) { if (packageName == 'new') { htmlContent = ''; htmlContent += ''; htmlContent += ''; htmlContent += '
' + this.getResource('', 'item_methods.create_new_package') + '
'; htmlContent += '
' + this.getResource('', 'item_methods.package_name') + '
'; htmlContent += '
'; if (countOfPacks > 0) { htmlContent += '
'; htmlContent += '
' + this.getResource('', 'item_methods.dependency') + '
'; htmlContent += '
'; htmlContent += '
'; } htmlContent += '
'; htmlContent += ''; htmlContent += '
'; params = { aras: this, title: this.getResource('', 'item_methods.create_new_package'), writeContent: writeContent, dialogWidth: 350, dialogHeight: 320, content: 'modalDialog.html' }; window.setTimeout(function() { (win.main || win).ArasModules.Dialog.show('iframe', params).promise.then( function(strNewPack) { if (strNewPack) { var regExp = new RegExp('^(.+)=dep=(.+)$', 'i'); var strNewPackName = strNewPack.match(regExp)[1]; var strDepPackage = strNewPack.match(regExp)[2]; regExp = new RegExp('[^;]+', 'ig'); var bResult = createPackage(strNewPackName, strDepPackage.match(regExp)); if (bResult) { getAllpackages(); addItemsToPackage(strNewPackName); } } } ); }.bind(this), 0); } else { addItemsToPackage(packageName); } } }.bind(this); params.dialogWidth = 300; params.dialogHeight = 200; params.content = 'modalDialog.html'; (win.main || win).ArasModules.Dialog.show('iframe', params).promise.then(modalCallback); }; /*-- newRelationship * * Method to create a new Relationship for an item * relTypeId = the RelatinshpType id * srcItem = the source item in the relationship (may be null:i.e. when created with mainMenu) * searchDialog = true or false : if search dialog to be displayed * wnd = the window from which the dialog is opened * */ Aras.prototype.newRelationship = function(relTypeId, srcItem, searchDialog, wnd, relatedItem, relatedTypeName, bTestRelatedItemArg, bIsDoGetItemArg, descByTypeName) { with (this) { var processAddingRelationship = function(relatedItem) { if (descByTypeName == undefined) { descByTypeName = this.getItemTypeName(descByTypeId); } var descByItem = this.newItem(descByTypeName); this.itemsCache.addItem(descByItem); if (!descByItem) { return null; } if (relatedId != '' && !descByItem.selectSingleNode('related_id')) { this.createXmlElement('related_id', descByItem); } if (relatedItem) { if (srcItem) { if (relatedItem == srcItem) { relatedItem = srcItem.cloneNode(true); var relationshipsNd = relatedItem.selectSingleNode('Relationships'); if (relationshipsNd) { relatedItem.removeChild(relationshipsNd); } relationshipsNd = null; relatedItem.setAttribute('action', 'skip'); } } if (this.isTempID(relatedId)) { descByItem.selectSingleNode('related_id').appendChild(relatedItem); } else { descByItem.selectSingleNode('related_id').appendChild(relatedItem.cloneNode(true)); } } if (relTypeName == 'RelationshipType') { if (srcItem) { this.setItemProperty(descByItem, 'source_id', srcItem.getAttribute('id')); } } if (srcItem) { if (!srcItem.selectSingleNode('Relationships')) { srcItem.appendChild(srcItem.ownerDocument.createElement('Relationships')); } var relationship; try { relationship = srcItem.selectSingleNode('Relationships').appendChild(descByItem); // relationship = srcItem.selectSingleNode('Relationships').appendChild(descByItem.cloneNode(true)); } catch (excep) { if (excep.number == -2147467259) { this.AlertError(this.getResource('', 'item_methods.recursion_not_allowed_here'), wnd); return null; } else { throw excep; } } relationship.setAttribute('typeId', descByTypeId); relationship.setAttribute('action', 'add'); relationship.setAttribute('loaded', '1'); relationship.setAttribute('levels', '0'); if (bIsDoGetItem) { relationship.setAttribute('doGetItem', '0'); } this.setItemProperty(relationship, 'source_id', srcItem.getAttribute('id')); // descByItem.parentNode.removeChild(descByItem); return relationship; } else { return descByItem; } } var bTestRelatedItem; if (bTestRelatedItemArg == undefined) { bTestRelatedItem = false; } else { bTestRelatedItem = bTestRelatedItemArg; } var bIsDoGetItem; if (bIsDoGetItemArg == undefined) { bIsDoGetItem = false; } else { bIsDoGetItem = bIsDoGetItemArg; } var srcItemID; if (srcItem) { srcItemID = srcItem.getAttribute('id'); if (!wnd) { wnd = uiFindWindowEx(srcItemID); if (!wnd) { wnd = window; } } } else if (!wnd) { wnd = window; } relType = getRelationshipType(relTypeId).node; var relTypeName = getItemProperty(relType, 'name'); var relatedTypeId = getItemProperty(relType, 'related_id'); var descByTypeId = getItemProperty(relType, 'relationship_id'); var relatedId = ''; if (relatedItem) { relatedId = relatedItem.getAttribute('id'); } var self = this; if (relatedTypeId) { if (relatedTypeName == undefined) { relatedTypeName = getItemTypeName(relatedTypeId); } if (searchDialog) { var params = { aras: this.getMostTopWindowWithAras(wnd).aras, itemtypeName: relatedTypeName, sourceItemTypeName: ((srcItem && srcItem.xml) ? srcItem.getAttribute('type') : ''), sourcePropertyName: 'related_id', type: 'SearchDialog' }; wnd.ArasModules.MaximazableDialog.show('iframe', params); if (relatedId == undefined) { return null; } relatedId = relatedId.itemID; if (!relatedId) { return null; } // TODO: should be done in memory no need to call the server relatedItem = getItemFromServer(relatedTypeName, relatedId, 'id').node; } else { if ((relatedItem === undefined) || (bTestRelatedItem == true)) { relatedItem = newItem(relatedTypeName, null, wnd); if (relatedItem && relatedItem.then) { return relatedItem.then(function(relatedItem) { this.itemsCache.addItem(relatedItem); if (!relatedItem) { return null; } relatedId = relatedItem.getAttribute('id'); return processAddingRelationship.call(this, relatedItem); }.bind(this)); } else { this.itemsCache.addItem(relatedItem); if (!relatedItem) { return null; } relatedId = relatedItem.getAttribute('id'); return processAddingRelationship.call(this, relatedItem); } } } } return processAddingRelationship.call(this, relatedItem); } }; /*-- copyItem * * Method to copy an item * item = item to be cloned * */ Aras.prototype.copyItem = function(itemTypeName, itemID) { if (itemID == undefined) { return null; } var itemNd = this.getItemById('', itemID, 0); if (itemNd) { return this.copyItemEx(itemNd); } else { if (itemTypeName == undefined) { return null; } var bodyStr = ''); clearStatusMessage(statusId); } if (res.getFaultCode() != 0) { this.AlertError(res); return null; } return res.results.selectNodes('//Item'); }; //function getAffectedItems Aras.prototype.purgeItem = function Aras_purgeItem(itemTypeName, itemID, silentMode) { /*-- purgeItem * * Method to delete the latest version of the item (or the item if it's not versionable) * itemTypeName - * itemID = the id for the item * silentMode - flag to know if user confirmation is NOT needed * */ return this.PurgeAndDeleteItem_CommonPart(itemTypeName, itemID, silentMode, 'purge'); }; Aras.prototype.deleteItem = function Aras_deleteItem(itemTypeName, itemID, silentMode) { /*-- deleteItem * * Method to delete all versions of the item * itemTypeName - * itemID = the id for the item * silentMode - flag to know if user confirmation is NOT needed * */ return this.PurgeAndDeleteItem_CommonPart(itemTypeName, itemID, silentMode, 'delete'); }; Aras.prototype.GetOperationName_PurgeAndDeleteItem = function Aras_GetOperationName_PurgeAndDeleteItem(purgeORdelete) { return purgeORdelete == 'delete' ? 'Deleting' : 'Purge'; }; Aras.prototype.Confirm_PurgeAndDeleteItem = function Aras_Confirm_PurgeAndDeleteItem(itemId, keyedName, purgeORdelete) { var operation = this.GetOperationName_PurgeAndDeleteItem(purgeORdelete); var win = this.uiFindWindowEx(itemId); var options = {dialogWidth: 300, dialogHeight: 180, center: true}, params = { aras: this, message: this.getResource('', 'item_methods.operation_item_name', operation, keyedName), buttons: { btnYes: this.getResource('', 'common.ok'), btnCancel: this.getResource('', 'common.cancel') }, defaultButton: 'btnCancel' }, returnedValue; if (!win) { win = window; } win.focus(); if (this.Browser.isCh()) { returnedValue = 'btnCancel'; if (window.confirm(this.getResource('', 'item_methods.operation_item_name', operation, keyedName))) { returnedValue = 'btnYes'; } } else { returnedValue = this.modalDialogHelper.show('DefaultModal', window, params, options, 'groupChgsDialog.html'); } if(returnedValue === 'btnYes'){ return true; } else { return false; } }; Aras.prototype.SendSoap_PurgeAndDeleteItem = function Aras_SendSoap_PurgeAndDeleteItem(ItemTypeName, ItemId, purgeORdelete) { /*-- SendSoap_PurgeAndDeleteItem * * This method is for ***internal purposes only***. * */ var Operation = this.GetOperationName_PurgeAndDeleteItem(purgeORdelete); var StatusId = this.showStatusMessage('status', this.getResource('', 'item_methods.operation_item', Operation), system_progressbar1_gif); var res = this.soapSend('ApplyItem', '', null, false); this.clearStatusMessage(StatusId); if (res.getFaultCode() != 0) { var win = this.uiFindWindowEx(ItemId); if (!win) { win = window; } this.AlertError(res, win); return false; } return true; }; Aras.prototype.RemoveGarbage_PurgeAndDeleteItem = function Aras_RemoveGarbage_PurgeAndDeleteItem(ItemTypeName, ItemId, DeletedItemTypeName, relationship_id) { /*-- RemoveGarbage_PurgeAndDeleteItem * * This method is for ***internal purposes only***. * */ if (ItemTypeName == 'ItemType' || ItemTypeName == 'RelationshipType') { if (DeletedItemTypeName) { //remove instances of the deleted ItemType this.itemsCache.deleteItems('/Innovator/Items/Item[@type=\'' + DeletedItemTypeName + '\']'); // TODO: remove mainWnd.Cache also. } if (relationship_id) { //remove corresponding ItemType or RelationshipType this.itemsCache.deleteItems('/Innovator/Items/Item[@id=\'' + relationship_id + '\']'); this.itemsCache.deleteItems('/Innovator/Items/Item[@type=\'RelationshipType\'][relationship_id=\'' + relationship_id + '\']'); } } //find and remove all duplicates in dom //this helps to fix IR-006266 for example this.itemsCache.deleteItems('/Innovator/Items//Item[@id=\'' + ItemId + '\']'); }; Aras.prototype.PurgeAndDeleteItem_CommonPart = function Aras_PurgeAndDeleteItem_CommonPart(ItemTypeName, ItemId, silentMode, purgeORdelete) { /*-- PurgeAndDeleteItem_CommonPart * * This method is for ***internal purposes only***. * Is allowed to be called only from inside aras.deleteItem and aras.purgeItem methods. * */ if (silentMode === undefined) { silentMode = false; } var itemNd = this.itemsCache.getItem(ItemId); if (itemNd) { return this.PurgeAndDeleteItem_CommonPartEx(itemNd, silentMode, purgeORdelete); } else { //prepare if (!silentMode) { if (!this.Confirm_PurgeAndDeleteItem(ItemId, this.getKeyedName(ItemId), purgeORdelete)) { return false; } } var DeletedItemTypeName; var relationship_id; if (!this.isTempID(ItemId)) { //save some information if (ItemTypeName == 'ItemType') { var tmpItemTypeNd = this.getItemFromServer('ItemType', ItemId, 'name,is_relationship'); if (tmpItemTypeNd) { tmpItemTypeNd = tmpItemTypeNd.node; //because getItemFromServer returns IOM Item... } if (tmpItemTypeNd) { if (this.getItemProperty(tmpItemTypeNd, 'is_relationship') == '1') { relationship_id = ItemId; } DeletedItemTypeName = this.getItemProperty(tmpItemTypeNd, 'name'); } tmpItemTypeNd = null; } else if (ItemTypeName == 'RelationshipType') { var tmpRelationshipTypeNd = this.getItemFromServer('RelationshipType', ItemId, 'relationship_id,name'); if (tmpRelationshipTypeNd) { tmpRelationshipTypeNd = tmpRelationshipTypeNd.node; //because getItemFromServer returns IOM Item... } if (tmpRelationshipTypeNd) { relationship_id = this.getItemProperty(tmpRelationshipTypeNd, 'relationship_id'); DeletedItemTypeName = this.getItemProperty(tmpRelationshipTypeNd, 'name'); } tmpRelationshipTypeNd = null; } else if (ItemTypeName == 'Preference') { this.deleteSavedSearchesByPreferenceIDs([ItemId]); } //delete if (!this.SendSoap_PurgeAndDeleteItem(ItemTypeName, ItemId, purgeORdelete)) { return false; } } //delete all dependent stuff if (ItemTypeName == 'ItemType' || ItemTypeName == 'RelationshipType') { this.RemoveGarbage_PurgeAndDeleteItem(ItemTypeName, ItemId, DeletedItemTypeName, relationship_id); } this.MetadataCache.RemoveItemById(ItemId); } return true; }; Aras.prototype.deleteSavedSearchesByPreferenceIDs = function Aras_deleteSavedSearchesByPreferenceIDs(preferenceIDs) { var idsString = '\'' + preferenceIDs.join('\',\'') + '\''; var qry = this.newIOMItem('SavedSearch', 'get'); qry.SetAttribute('select', 'id'); qry.SetAttribute('where', '[SavedSearch].owned_by_id in (SELECT identity_id FROM [Preference] WHERE id in (' + idsString + ')) AND [SavedSearch].auto_saved=\'1\''); qry.SetProperty('auto_saved', '1'); var res = qry.apply(); if (!res.isEmpty() && !res.isError()) { var items = res.getItemsByXPath(this.XPathResult('/Item[@type=\'SavedSearch\']')); for (var i = 0; i < items.getItemCount(); i++) { this.MetadataCache.RemoveItemById(items.getItemByIndex(i).getID()); } var deleteSavedSearchesAml = '' + ' ' + ' ' + ''; res = this.applyAML(deleteSavedSearchesAml); } }; Aras.prototype.deletePreferences = function Aras_deletePreferences(preferenceIDs) { var StatusId = this.showStatusMessage('status', this.getResource('', 'item_methods.operation_item', 'Deleting'), system_progressbar1_gif); try { for (var preferenceIndex = 0; preferenceIndex < preferenceIDs.length; preferenceIndex++) { var preferenceId = preferenceIDs[preferenceIndex]; this.MetadataCache.RemoveItemById(preferenceId); } var idsString = '\'' + preferenceIDs.join('\',\'') + '\''; this.deleteSavedSearchesByPreferenceIDs(preferenceIDs); var deletePreferencesAml = '' + ' ' + ''; res = this.applyAML(deletePreferencesAml); allChecked = false; } finally { this.clearStatusMessage(StatusId); } }; /*-- lockItem * * Method to lock the item * id = the id for the item * */ Aras.prototype.lockItem = function Aras_lockItem(itemID, itemTypeName) { if (itemID) { var itemNode = this.getFromCache(itemID); if (itemNode) { return this.lockItemEx(itemNode); } else { if (itemTypeName) { var ownerWindow = this.uiFindWindowEx(itemID) || window, bodyStr = '', statusId = this.showStatusMessage('status', this.getResource('', 'common.locking_item_type', itemTypeName), system_progressbar1_gif), requestResult = this.soapSend('ApplyItem', bodyStr); this.clearStatusMessage(statusId); if (requestResult.getFaultCode() != 0) { this.AlertError(requestResult, ownerWindow); return null; } itemNode = requestResult.results.selectSingleNode(this.XPathResult('/Item')); if (itemNode) { this.updateInCache(itemNode); itemNode = this.getFromCache(itemID); this.fireEvent('ItemLock', { itemID: itemNode.getAttribute('id'), itemNd: itemNode, newLockedValue: this.isLocked(itemNode) }); return itemNode; } else { this.AlertError(this.getResource('', 'item_methods.failed_get_item_type', itemTypeName), this.getResource('', 'item_methods.xpathresult_of_item_returned_null'), 'common.client_side_err', ownerWindow); return null; } } else { return null; } } } return false; }; /*-- unlockItem * * Method to unlock the item * id = the id for the item * */ Aras.prototype.unlockItem = function(itemID, itemTypeName) { if (!itemID) { return null; } with (this) { var itemNd = getFromCache(itemID); if (itemNd) { return unlockItemEx(itemNd); } else { if (!itemTypeName) { return null; } else { var win = uiFindWindowEx(itemID); if (!win) { win = window; } var bodyStr = ''; var statusId = showStatusMessage('status', getResource('', 'item_methods.unlocking_item'), system_progressbar1_gif); var res = soapSend('ApplyItem', bodyStr); clearStatusMessage(statusId); if (res.getFaultCode() != 0) { this.AlertError(res, win); return null; } itemNd = res.results.selectSingleNode(XPathResult('/Item')); if (!itemNd) { return null; } updateInCache(itemNd); updateFilesInCache(itemNd); var params = this.newObject(); params.itemID = itemNd.getAttribute('id'); params.itemNd = itemNd; params.newLockedValue = this.isLocked(itemNd); this.fireEvent('ItemLock', params); return itemNd; } } } //with (this) }; /*-- loadItems * * Method to load an item or items * typeName = the ItemType name * body = the query message to get the items * levels = the levels deep for the returned item configuration * pageSize = the number of rows to return * page = the page number * configPath = the RelationshipType names to include inteh item configuration returned * select = the list of properties to return * */ Aras.prototype.loadItems = function Aras_loadItems(typeName, body, levels, pageSize, page, configPath, select) { if (typeName == undefined || typeName == '') { return false; } if (body == undefined) { body = ''; } if (levels == undefined) { levels = 0; } if (pageSize == undefined) { pageSize = ''; } if (page == undefined) { page = ''; } if (configPath == undefined) { configPath = ''; } if (select == undefined) { select = ''; } levels = parseInt(levels); var attrs = '', innerBody = ''; if (body != '') { if (body.charAt(0) != '<') { attrs = body; } else { innerBody = body; } } var soapBody = '' + innerBody + ''; var res; with (this) { var statusId = showStatusMessage('status', getResource('', 'item_methods.loading', typeName), system_progressbar1_gif); res = soapSend('ApplyItem', soapBody); clearStatusMessage(statusId); } if (res.getFaultCode() != 0) { if (this.DEBUG) { this.AlertError(this.getResource('', 'item_methods.fault_loading'), typeName, res.getFaultCode()); } return null; } if (configPath) { levels--; } var items = res.results.selectNodes(this.XPathResult('/Item')); var itemsRes = new Array(); for (var i = 0; i < items.length; ++i) { var item = items[i]; var currentId = item.getAttribute('id'); item.setAttribute('levels', levels); this.itemsCache.updateItem(item, true); itemsRes.push(this.itemsCache.getItem(currentId)); } return itemsRes; }; /*-- getItem * * Method to load an item * typeName = the ItemType name * xpath = the XPath to teh item in the dom cache * body = the query message to get the items * levels = the levels deep for the returned item configuration * configPath = the RelationshipType names to include inteh item configuration returned * select = the list of properties to return * */ Aras.prototype.getItem = function(itemTypeName, xpath, body, levels, configPath, select) { if (levels == undefined) { levels = 1; } if (typeof (itemTypeName) != 'string') { itemTypeName = ''; } var typeAttr = ''; if (xpath.indexOf('@id=') < 0) { /* POLYITEM: only argument with @type if xpath does not start with @id= */ typeAttr = '[@type="' + itemTypeName + '"]'; } xpath = '/Innovator/Items/Item' + typeAttr + '[' + xpath + ']'; var node = this.itemsCache.getItemByXPath(xpath); var loadItemFromServer = false; // if node was found in cache if (node) { // if node is dirty then retreive node from cache after test for completeness if (this.isDirtyEx(node) || this.isTempEx(node)) { // if requested levels > than node levels attribute then load item from server if ((node.getAttribute('levels') - levels) < 0) { itemTypeName = node.getAttribute('type'); loadItemFromServer = true; } } else {// if node not dirty then drop it from cache and load from server original version if (!itemTypeName) { itemTypeName = node.getAttribute('type'); } loadItemFromServer = true; } } else {// if node not exists in cache then load item from server if (itemTypeName != '') { loadItemFromServer = true; } } if (loadItemFromServer) { this.loadItems(itemTypeName, body, levels, '', '', configPath, select); node = this.itemsCache.getItemByXPath(xpath); } return node; }; /*-- getRelatedItem * * Method to get related item from relationship * item = relationship from which related item will be taken * */ Aras.prototype.getRelatedItem = function(item) { try { var relatedItem = item.selectSingleNode('related_id/Item'); return relatedItem; } catch (excep) { return null; } }; /*-- getItemById * * Method to load an item by id * typeName = the ItemType name * id = the id for the item * levels = the levels deep for the returned item configuration * configPath = the RelationshipType names to include inteh item configuration returned * select = the list of properties to return * */ Aras.prototype.getItemById = function(typeName, id, levels, configPath, select) { if (id == '') { return null; } if (levels == undefined) { levels = 1; } if (configPath == undefined) { configPath = ''; } if (select == undefined) { select = ''; } return this.getItem(typeName, '@id="' + id + '"', 'id="' + id + '"', levels, configPath, select); }; /*-- getItemUsingIdAsParameter * * The same as getItemById. The only difference is that method load an item by id passing id like parameter, * not like attribute. Created because if request item using id as attribute, server will return full item. * typeName = the ItemType name * id = the id for the item * levels = the levels deep for the returned item configuration * configPath = the RelationshipType names to include inteh item configuration returned * select = the list of properties to return * */ Aras.prototype.getItemUsingIdAsParameter = function(typeName, id, levels, configPath, select) { this.getItemById(typeName, id, levels, configPath, select); }; Aras.prototype.getItemById$skipServerCache = function Aras_getItemById$skipServerCache(typeName, id, levels, select, configPath) { /*-- getItemById$skipServerCache * * IMPORTANT: This is internal system method. Never use it. Will be removed in future !!! * * Method to load an item by id * typeName = the ItemType name * id = the id for the item * levels = the levels deep for the returned item configuration * configPath = the RelationshipType names to include inteh item configuration returned * select = the list of properties to return * */ if (!id) { return null; } if (levels === undefined) { levels = 1; } if (select === undefined) { select = ''; } if (configPath === undefined) { configPath = ''; } return this.getItem(typeName, '@id="' + id + '"', '' + id + '', levels, configPath, select); }; /*-- getItemByName * * Method to load an item by name property * typeName = the ItemType name * name = the name for the item * levels = the levels deep for the returned item configuration * configPath = the RelationshipType names to include inteh item configuration returned * select = the list of properties to return * */ Aras.prototype.getItemByName = function(typeName, name, levels, configPath, select) { if (levels == undefined) { levels = 1; } return this.getItem(typeName, 'name="' + name + '"', '' + name + '', levels, configPath, select); }; /*-- getItemByKeyedName * * Method to load an item by keyed_name property * typeName = the ItemType name * keyed_name = the keyed_name for the item * levels = the levels deep for the returned item configuration * configPath = the RelationshipType names to include inteh item configuration returned * select = the list of properties to return * */ Aras.prototype.getItemByKeyedName = function(typeName, keyed_name, levels, configPath, select) { if (levels == undefined) { levels = 0; } return this.getItem(typeName, 'keyed_name="' + keyed_name + '"', '' + keyed_name + '', levels, configPath, select); }; /*-- getRelationships * * Method to get the Relationships for an item * item = the item * typeName = the ItemType name for the Relationships * */ Aras.prototype.getRelationships = function(item, typeName) { with (this) { if (!item) { return false; } return item.selectNodes('Relationships/Item[@type="' + typeName + '"]'); } }; /*-- getKeyedName * * Method to get key field values for an item * id = the id for the item * */ Aras.prototype.getKeyedName = function(id, itemTypeName) { if (arguments.length < 2) { itemTypeName = ''; } if (!id) { return ''; } with (this) { var item = itemsCache.getItem(id); if (!item) { item = getItemById(itemTypeName, id, 0); } if (!item && itemTypeName != '') { item = getItemFromServer(itemTypeName, id, 'keyed_name').node; } if (!item) { return ''; } var res = getItemProperty(item, 'keyed_name'); if (!res) { res = getKeyedNameEx(item); } return res; } }; Aras.prototype.getKeyedNameAttribute = function(node, element) { if (!node) { return; } var value; var tmpNd = node.selectSingleNode(element); if (tmpNd) { value = tmpNd.getAttribute('keyed_name'); if (!value) { value = ''; } } else { value = ''; } return value; }; function keyedNameSorter(a, b) { var s1 = parseInt(a[0]); if (isNaN(s1)) { return 1; } var s2 = parseInt(a[0]); if (isNaN(s2)) { return -1; } if (s1 < s2) { return -1; } else if (s1 == s2) { return 0; } else { return 1; } } Aras.prototype.sortProperties = function sortProperties(ndsCollection) { if (!ndsCollection) { return null; } var tmpArr = new Array(); for (var i = 0; i < ndsCollection.length; i++) { tmpArr.push(ndsCollection[i].cloneNode(true)); } var self = this; function sortPropertiesNodes(propNd1, propNd2) { var sorder1 = self.getItemProperty(propNd1, 'sort_order'); if (sorder1 == '') { sorder1 = 1000000; } sorder1 = parseInt(sorder1); if (isNaN(sorder1)) { return 1; } var sorder2 = self.getItemProperty(propNd2, 'sort_order'); if (sorder2 == '') { sorder2 = 1000000; } sorder2 = parseInt(sorder2); if (isNaN(sorder2)) { return -1; } if (sorder1 < sorder2) { return -1; } else if (sorder1 == sorder2) { sorder1 = self.getItemProperty(propNd1, 'name'); sorder2 = self.getItemProperty(propNd2, 'name'); if (sorder1 < sorder2) { return -1; } else if (sorder1 == sorder2) { return 0; } else { return 1; } } else { return 1; } } return tmpArr.sort(sortPropertiesNodes); }; /*-- getItemAllVersions * * Method to load all the versions of an item * typeName = the ItemType name * id = the id for the item * */ Aras.prototype.getItemAllVersions = function(typeName, id) { with (this) { var statusId = showStatusMessage('status', getResource('', 'item_methods.loading_versions', typeName), system_progressbar1_gif); var res = soapSend('ApplyItem', ''); clearStatusMessage(statusId); if (res.getFaultCode() != 0) { this.AlertError(res); return null; } return res.results.selectNodes(XPathResult('/Item')); } }; /*-- getItemLastVersion * * Method to load the latest version for the item * itemTypeName = the ItemType name * itemId = the id for the item * */ Aras.prototype.getItemLastVersion = function(typeName, itemId) { var res = this.soapSend('ApplyItem', ''); if (res.getFaultCode() != 0) { this.AlertError(res); return null; } return res.results.selectSingleNode(this.XPathResult('/Item')); }; //getItemLastVersion /*-- getItemWhereUsed * * Method to load the where used items for an item * typeName = the ItemType name * id = the id for the item * */ Aras.prototype.getItemWhereUsed = function(typeName, id) { with (this) { var statusId = showStatusMessage('status', getResource('', 'item_methods.loading_where_used'), system_progressbar1_gif); var res = soapSend('ApplyItem', ''); clearStatusMessage(statusId); if (res.getFaultCode() != 0) { this.AlertError(res); return null; } return res.results.selectSingleNode(XPathResult('/Item')); } }; /*-- getClassWhereUsed * * Method to load the where class is referenced * typeId = the ItemType name * classId = the id of class node * scanTypes = for this types dependencies will be tracked * detailed = if true return detailed result, if false return count of dependencies * */ Aras.prototype.getClassWhereUsed = function(typeId, classId, scanTypes, detailed) { with (this) { var statusId = showStatusMessage('status', getResource('', 'statusbar.getting_impact_data'), '../images/Progress.gif'); var methodAML = '' + '' + '' + classId + '+' + (detailed ? 'details' : '') + (scanTypes ? '' + scanTypes + '' : '') + '' + ''; var res = applyMethod('GetClassWhereUsed', methodAML); clearStatusMessage(statusId); var resDom = XmlDocument(); resDom.loadXML(res); return resDom; } }; /*-- getHistoryItems * * Method to load the history items for specified item * typeName = the ItemType name * id = the id for the item * */ Aras.prototype.getHistoryItems = function(typeName, id) { with (this) { var statusId = showStatusMessage('status', getResource('', 'item_methods.loading_history'), system_progressbar1_gif); var res = soapSend('ApplyItem', ''); clearStatusMessage(statusId); if (res.getFaultCode() != 0) { return false; } var items = res.results.selectNodes(XPathResult('/Item')); items = res.results.selectNodes(XPathResult('/Item[@type="History"]')); return items; } }; /*-- getItemNextStates * * Method to load the promote values * typeName = the ItemType name * id = the id for the item * */ Aras.prototype.getItemNextStates = function(typeName, id) { with (this) { var res = soapSend('ApplyItem', ''); if (res.getFaultCode() != 0) { try { var win = windowsByName[id]; this.AlertError(res, win); } catch (excep) {} //callee server is disappeared or ... error return null; } return res.getResult(); } }; /*-- promote * * Method to promote an item to the next state * typeName = the ItemType name * id = the id for the item * stateName = the next state name * */ Aras.prototype.promote = function Aras_promote(itemTypeName, itemID, stateName, comments) { var promoteParams = { typeName: itemTypeName, id: itemID, stateName: stateName, comments: comments }; return this.promoteItem_implementation(promoteParams); }; Aras.prototype.promoteItem_implementation = function Aras_promoteItem_implementation(promoteParams, soapController) { var itemTypeName = promoteParams.typeName; var itemID = promoteParams.id; var stateName = promoteParams.stateName; var comments = promoteParams.comments; var myItem = this.newIOMItem(itemTypeName, 'promoteItem'); myItem.setID(itemID); myItem.setProperty('state', stateName); if (comments) { myItem.setProperty('comments', comments); } //Baseline var msg = itemTypeName + ' to ' + stateName; var xml = myItem.dom.xml; var async = Boolean(soapController && soapController.callback); this.addIdBeingProcessed(itemID, 'promotion of ' + msg); var msgId = this.showStatusMessage('status', this.getResource('', 'item_methods.promoting', msg), system_progressbar1_gif); var self = this; var globalRes = null; function afterSoapSend(res) { if (msgId) { self.clearStatusMessage(msgId); } self.removeIdBeingProcessed(itemID); if (res.getFaultCode() != 0) { var win = self.uiFindWindowEx(itemID); if (!win) { win = window; } self.AlertError(res, win); } self.removeFromCache(itemID); } if (async) { var originalCallBack = soapController.callback; function afterAsyncSoapSend(soapSendRes) { afterSoapSend(soapSendRes); originalCallBack(soapSendRes); } soapController.callback = afterAsyncSoapSend; } globalRes = this.soapSend('ApplyItem', xml, undefined, undefined, soapController); if (async) { return null; } if (globalRes) { afterSoapSend(globalRes); msgId = this.showStatusMessage('status', this.getResource('', 'item_methods.getting_promote_result'), system_progressbar1_gif); globalRes = this.getItemById(itemTypeName, itemID, 0); this.clearStatusMessage(msgId); if (!globalRes) { globalRes = null; } } return globalRes; }; Aras.prototype.getItemRelationship = function Aras_getItemRelationship(item, relTypeName, relID, useServer) { if (!item || !relTypeName || !relID || useServer == undefined) { return null; } var res = item.selectSingleNode('Relationships/Item[@type="' + relTypeName + '" and @id="' + relID + '"]'); if (res) { return res; } if (!useServer) { return null; } var itemID = item.getAttribute('id'); var bodyStr = '' + itemID + '' + '' + relID + ''; var xpath = '@id=\'' + relID + '\' and source_id=\'' + itemID + '\''; res = this.getItem(relTypeName, xpath, bodyStr, 0); with (this) { if (res != null || res != undefined) { if (!item.selectSingleNode('Relationships')) { item.appendChild(item.ownerDocument.createElement('Relationships')); } res = res.selectSingleNode('//Item[@type="' + relTypeName + '" and @id="' + relID + '"]'); if (!res) { return null; } res = item.selectSingleNode('Relationships').appendChild(res); return res; } else { return null; } } }; Aras.prototype.getItemRelationships = function(itemTypeName, itemId, relsName, pageSize, page, body, forceReplaceByItemFromServer) { if (!(itemTypeName && itemId && relsName)) { return null; } if (pageSize == undefined) { pageSize = ''; } if (page == undefined) { page = ''; } if (body == undefined) { body = ''; } if (forceReplaceByItemFromServer == undefined) { forceReplaceByItemFromServer = false; } var res = null; with (this) { var itemNd = getItemById(itemTypeName, itemId, 0); if (!itemNd) { return null; } if (!forceReplaceByItemFromServer && (pageSize == -1 || isTempID(itemId) || (itemNd.getAttribute('levels') && parseInt(itemNd.getAttribute('levels')) > 0))) { if (!isNaN(parseInt(pageSize)) && parseInt(pageSize) > 0 && !isNaN(parseInt(page)) && parseInt(page) > -1) { res = itemNd.selectNodes('Relationships/Item[@type="' + relsName + '" and @page="' + page + '"]'); if (res && res.length == pageSize) { return res; } } else { res = itemNd.selectNodes('Relationships/Item[@type="' + relsName + '"]'); if (res && res.length > 0) { return res; } } } var bodyStr = ''; } var statusId = showStatusMessage('status', getResource('', 'item_methods.loading_relationships', itemTypeName), system_progressbar1_gif); var res = soapSend('ApplyItem', bodyStr); clearStatusMessage(statusId); if (res.getFaultCode() != 0) { this.AlertError(res); return null; } if (!itemNd.selectSingleNode('Relationships')) { createXmlElement('Relationships', itemNd); } var rels = res.results.selectNodes(XPathResult('/Item[@type="' + relsName + '"]')); var itemRels = itemNd.selectSingleNode('Relationships'); var idsStr = ''; for (var i = 0; i < rels.length; i++) { var rel = rels[i].cloneNode(true); var relId = rel.getAttribute('id'); if (i > 0) { idsStr += ' or '; } idsStr += '@id="' + relId + '"'; var prevRel = itemRels.selectSingleNode('Item[@type="' + relsName + '" and @id="' + relId + '"]'); if (prevRel) { if (forceReplaceByItemFromServer == true) { // By some reason the previous implementation did not replaced existing on the node // relationships with the new relationships obtained from the server but rather // just removed some attributes on them (like "pagesize", etc.). From other side those // relationships that don't exist on the 'itemNd' are added to it. This is wrong as // the newly obtained relationships even if they already exist on 'itemNd' might have // some properties that are different in db from what is in the client memory. // NOTE: the fix will break the case when the client changes some relationship properties // in memory and then calls this method expecting that these properties will stay unchanged, // but: a) this method seems to be called only from getFileURLEx(..); b) if the above // behavior is expected then another method is probably required which must be called // something like 'mergeRelationships'. // by Andrey Knourenko itemRels.removeChild(prevRel); } else { this.mergeItem(prevRel, rel); continue; } } itemRels.appendChild(rel); } itemNd.setAttribute('levels', '0'); if (idsStr == '') { return null; } res = itemRels.selectNodes('Item[@type="' + relsName + '" and (' + idsStr + ')]'); } //with (this) return res; }; Aras.prototype.resetLifeCycle = function Aras_resetLifeCycle(itemTypeName, itemID) { if (!itemTypeName || !itemID) { return false; } with (this) { var statusId = showStatusMessage('status', getResource('', 'item_methods.reseting_life_cycle_state'), system_progressbar1_gif); var bodyStr = ''; var res = soapSend('ApplyItem', bodyStr); clearStatusMessage(statusId); if (res.getFaultCode() != 0) { var win = uiFindWindowEx(itemID); if (!win) { win = window; } this.AlertError(res, win); return false; } var itemNd = res.results.selectSingleNode(XPathResult('/Item')); if (!itemNd) { return false; } return true; } }; Aras.prototype.setDefaultLifeCycle = function setDefaultLifeCycle(itemTypeName, itemID) { if (!itemTypeName || !itemID) { return false; } var statusId = this.showStatusMessage('status', this.getResource('', 'item_methods.reseting_life_cycle_state'), system_progressbar1_gif); var bodyStr = ''; var res = this.soapSend('ApplyItem', bodyStr); this.clearStatusMessage(statusId); if (res.getFaultCode() != 0) { var win = this.uiFindWindowEx(itemID); if (!win) { win = window; } this.AlertError(res, win); return false; } var faultStr = res.getFaultString(); if (faultStr != '') { return false; } this.removeFromCache(itemID); var itemNd = this.getItemById(itemTypeName, itemID, 0); if (!itemNd) { return false; } return true; }; Aras.prototype.resetItemAccess = function(itemTypeName, itemId) { if (itemTypeName == undefined || itemId == undefined) { return false; } with (this) { var itemNd = null; if (itemTypeName == '') { itemNd = getItemById('', itemId, 0); if (!itemNd) { return false; } itemTypeName = itemNd.getAttribute('type'); } var statusId = showStatusMessage('status', getResource('', 'item_methods.reseting_item_access'), system_progressbar1_gif); var bodyStr = ''; var res = soapSend('ApplyItem', bodyStr); clearStatusMessage(statusId); try { var winBN = windowsByName[itemId]; if (res.getFaultCode() != 0) { this.AlertError(res, winBN); return false; } } catch (excep) {} //callee server is disappeared or ... error var tempRes = loadItems(itemTypeName, 'id="' + itemId + '"', 0); if (tempRes) { return true; } else { return false; } } }; Aras.prototype.resetAllItemsAccess = function(itemTypeName) { if (!itemTypeName) { return false; } with (this) { var statusId = showStatusMessage('status', getResource('', 'item_methods.reseting_item_access'), system_progressbar1_gif); var bodyStr = ''; var res = soapSend('ApplyItem', bodyStr); clearStatusMessage(statusId); if (res.getFaultCode() != 0) { this.AlertError(res); return false; } return true; } }; Aras.prototype.populateRelationshipsGrid = function Aras_populateRelationshipsGrid(bodyStr) { if (!bodyStr) { return null; } with (this) { var statusId = showStatusMessage('status', getResource('', 'item_methods.populating_relationships_grid'), system_progressbar1_gif); var res = soapSend('PopulateRelationshipsGrid', bodyStr); clearStatusMessage(statusId); if (res.getFaultCode() != 0) { AlertError(res); } return res; } }; Aras.prototype.populateRelationshipsTables = function(bodyStr) { if (!bodyStr) { return null; } with (this) { var statusId = showStatusMessage('status', getResource('', 'item_methods.populating_relationships_tables'), system_progressbar1_gif); var res = soapSend('PopulateRelationshipsTables', bodyStr); clearStatusMessage(statusId); if (res.getFaultCode() != 0) { AlertError(res); return null; } return res.results.selectSingleNode('//tables'); } }; Aras.prototype.getMainTreeItems = function() { with (this) { var statusId = showStatusMessage('status', getResource('', 'item_methods.populating_main_tree'), system_progressbar1_gif); var res = soapSend('GetMainTreeItems', ''); clearStatusMessage(statusId); if (res.getFaultCode() != 0) { AlertError(res); return null; } return res.results.selectSingleNode('//MainTree'); } }; Aras.prototype.getPermissions = function(access_type, itemID, typeID, typeName) { if (!(access_type && itemID)) { return false; } if (access_type === 'can_add') { return this.getItemTypeForClient(itemID, 'id').getAttribute('can_add_for_this_user') === '1'; } with (this) { var bodyStr = ' Aras.prototype.isNew = function(itemNd) { if (!this.isTempEx(itemNd)) { return false; } return ('add' == itemNd.getAttribute('action')); }; Aras.prototype.isTempEx = function(itemNd) { if (!itemNd) { return undefined; } return (itemNd.getAttribute('isTemp') == '1'); }; Aras.prototype.isDirtyEx = function(itemNd) { if (!itemNd) { return undefined; } return (itemNd.selectSingleNode('descendant-or-self::Item[@isDirty="1"]') !== null); }; Aras.prototype.isLocked = function Aras_isLocked(itemNd) { if (this.isTempEx(itemNd)) { return false; } return ('' !== this.getItemProperty(itemNd, 'locked_by_id')); }; Aras.prototype.isLockedByUser = function Aras_isLockedByUser(itemNd) { if (this.isTempEx(itemNd)) { return false; } var locked_by_id = this.getItemProperty(itemNd, 'locked_by_id'); return (locked_by_id == this.getCurrentUserID()); }; /*-- copyItemEx * * Method to copy an item * itemNd = item to be cloned * */ Aras.prototype.copyItemEx = function(itemNd, action, do_add) { if (!itemNd) { return false; } if (!action) { action = 'copyAsNew'; } if (do_add === undefined || do_add === null) { do_add = true; } var itemTypeName = itemNd.getAttribute('type'); var bodyStr = '' + 'InBasket Task' + '' + itemNd.getAttribute('id') + '' + ''); if (tmpRes) { var tmpDoc = arasObj.createXMLDocument(); tmpDoc.loadXML(tmpRes); tmpRes = tmpDoc.selectSingleNode('//Item') ? true : false; } else { tmpRes = false; } isTaskOrItsChildCache = tmpRes; } isTaskOrItsChild = isTaskOrItsChildCache; } if (!propDs && propName != 'related_id' && propName != 'source_id' && !isTaskOrItsChild) { arasObj.AlertError(arasObj.getResource('', 'item_methods_ex.property_data_source_not_specified', propKeyedName), '', '', win); return false; } else { return true; } } var name = this.getItemProperty(itemNd, 'name'); if (name === '') { this.AlertError(this.getResource('', 'item_methods_ex.item_type_name_cannot_be_blank'), '', '', win); return false; } var property, propKeyedName, propDt, propName, propDs, tmpStoredLength, storedLength, pattern; var properties = itemNd.selectNodes('Relationships/Item[@type="Property" and (not(@action) or (@action!="delete" and @action!="purge"))]'); var i; for (i = 0; i < properties.length; i++) { property = properties[i]; propKeyedName = this.getKeyedNameEx(property); propName = this.getItemProperty(property, 'name'); if (!propName) { this.AlertError(this.getResource('', 'item_methods_ex.item_type_has_property_with_no_name', this.getItemProperty(itemNd, 'label')), win); return false; } propDt = this.getItemProperty(property, 'data_type'); propDs = this.getItemProperty(property, 'data_source'); if (propDt == 'string' || propDt == 'ml_string' || propDt == 'mv_list') { tmpStoredLength = this.getItemProperty(property, 'stored_length'); storedLength = parseInt(tmpStoredLength); if (isNaN(storedLength)) { this.AlertError(this.getResource('', 'item_methods_ex.length_of_property_not_specified', propKeyedName), '', '', win); return false; } else if (storedLength <= 0) { this.AlertError(this.getResource('', 'item_methods_ex.length_of_property_invalid', propKeyedName, tmpStoredLength), '', '', win); return false; } if ('mv_list' == propDt && !isDataSourceSpecified(this)) { return false; } } else if ((propDt == 'item' || propDt == 'list' || propDt == 'filter list' || propDt == 'color list' || propDt == 'sequence' || propDt == 'foreign') && !isDataSourceSpecified(this)) { return false; } else if (propDt == 'filter list') { if (!isDataSourceSpecified(this)) { return false; } pattern = this.getItemProperty(property, 'pattern'); if (!pattern) { this.AlertError(this.getResource('', 'item_methods_ex.fliter_list_property_has_to_have_pattern', propKeyedName), '', '', win); return false; } var tmpNd_1 = itemNd.selectSingleNode('Relationships/Item[@type="Property" and name="' + pattern + '" and (not(@action) or (@action!="delete" and @action!="purge"))]'); if (!tmpNd_1) { this.AlertError(this.getResource('', 'item_methods_ex.filter_list_property_has_wrong_pattern', propKeyedName, pattern), win); return false; } else if (this.getItemProperty(tmpNd_1, 'name') == this.getItemProperty(property, 'name')) { this.AlertError(this.getResource('', 'item_methods_ex.property_for_pattern_cannot_property_itself', propKeyedName), '', '', win); return false; } } } var discussionTemplates = itemNd.selectNodes('Relationships/Item[@type="DiscussionTemplate" and (not(@action) or (@action!="delete" and @action!="purge"))]'); if (discussionTemplates.length > 0) { var isRootClassificationExists = false; for (i = 0; i < discussionTemplates.length; i++) { var discussionTemplate = discussionTemplates[i]; if (this.getItemProperty(discussionTemplate, 'class_path') === '') { isRootClassificationExists = true; } } if (!isRootClassificationExists) { this.AlertError(this.getResource('', 'item_methods_ex.item_type_should_have_discussiontemplate_for_root_class_path', propKeyedName, pattern), win); return isRootClassificationExists; } } return true; }; Aras.prototype.checkItemForErrors = function Aras_checkItemForErrors(itemNd, exclusion, itemType, breakOnFirstError, emptyPropertyWithDefaultValueCallback) { var resultErrors = []; var propNd, reqId, isRequired, reqName, reqDataType, itemPropVal, defVal; var typeOfItem = itemNd.getAttribute('type'); if (!typeOfItem) { return resultErrors; } itemType = itemType ? itemType : this.getItemTypeDictionary(typeOfItem).node; if (!itemType) { return resultErrors; } var propertiesXpath = 'Relationships/Item[@type="Property" and (is_required="1" or data_type="string")' + (exclusion ? ' and name!="' + exclusion + '"' : '') + ']'; var requirements = itemType.selectNodes(propertiesXpath); for (var i = 0; i < requirements.length; i++) { propNd = requirements[i]; reqId = propNd.getAttribute('id'); reqName = this.getItemProperty(propNd, 'name'); reqDataType = this.getItemProperty(propNd, 'data_type'); isRequired = (this.getItemProperty(propNd, 'is_required') == '1'); if (!reqName) { var noNameError = this.getResource('', 'item_methods_ex.item_type_has_property_with_no_name', this.getItemProperty(itemType, 'label')); resultErrors.push({ message: noNameError }); if (breakOnFirstError) { return resultErrors; } } var proplabel = this.getItemProperty(propNd, 'label'); if (!proplabel) { proplabel = this.getItemProperty(propNd, 'keyed_name'); } if (!proplabel) { proplabel = ''; } itemPropVal = this.getItemProperty(itemNd, reqName); if (isRequired && itemPropVal === '') { defVal = this.getItemProperty(propNd, 'default_value'); if (defVal) { if (emptyPropertyWithDefaultValueCallback && typeof(emptyPropertyWithDefaultValueCallback) === 'function') { var callbackResult = emptyPropertyWithDefaultValueCallback(itemNd, reqName, proplabel, defVal); if (!callbackResult.result) { if (callbackResult.message) { resultErrors.push({ message: callbackResult.message }); } else { resultErrors.push({}); } if (breakOnFirstError) { return resultErrors; } } } continue; } else if (!this.isPropFilledOnServer(reqName) && (reqDataType != 'md5' || itemNd.getAttribute('action') == 'add' || itemNd.selectSingleNode(reqName))) { var fieldRequiredError = this.getResource('', 'item_methods_ex.field_required_provide_value', proplabel); resultErrors.push({ message: fieldRequiredError }); if (breakOnFirstError) { return resultErrors; } } } if (reqDataType == 'string') { var storedLength = parseInt(this.getItemProperty(propNd, 'stored_length')); if (!isNaN(storedLength) && itemPropVal.length - storedLength > 0) { var maxLengthError = this.getResource('', 'item_methods_ex.maximum_length_characters_for_property', proplabel, storedLength, itemPropVal.length); resultErrors.push({ message: maxLengthError }); if (breakOnFirstError) { return resultErrors; } } } } return resultErrors; }; Aras.prototype.checkItem = function Aras_checkItem(itemNd, win, exclusion, itemType) { var self = this; var defaultFieldCheckCallback = function(itemNode, reqName, proplabel, defVal) { var ask = self.confirm(self.getResource('', 'item_methods_ex.field_required_default_will_be_used', proplabel, defVal)); if (ask) { self.setItemProperty(itemNode, reqName, defVal); } return {result: ask, message: ''}; }; var errors = this.checkItemForErrors(itemNd, exclusion, itemType, true, defaultFieldCheckCallback); if (errors.length > 0) { if (errors[0].message) { this.AlertError(errors[0].message, '', '', win); } } return errors.length === 0; }; Aras.prototype.prepareItem4Save = function Aras_prepareItem4Save(itemNd) { var itemTypeName = itemNd.getAttribute('type'); var itemID, item, items, items2; var i, j, parentNd; itemID = itemNd.getAttribute('id'); items = itemNd.selectNodes('.//Item[@id="' + itemID + '"]'); for (i = 0; i < items.length; i++) { item = items[i]; parentNd = item.parentNode; parentNd.removeChild(item); parentNd.text = itemID; } items = itemNd.selectNodes('.//Item[@action="delete"]'); for (i = 0; i < items.length; i++) { item = items[i]; var childs = item.selectNodes('*[count(descendant::Item[@action])=0]'); for (j = 0; j < childs.length; j++) { var childItem = childs[j]; item.removeChild(childItem); } } items = itemNd.selectNodes('.//Item'); for (i = 0; i < items.length; i++) { item = items[i]; itemID = item.getAttribute('id'); items2 = itemNd.selectNodes('.//Item[@id="' + itemID + '"][@data_type != "foreign"]'); for (j = 1; j < items2.length; j++) { item = items2[j]; parentNd = item.parentNode; parentNd.removeChild(item); parentNd.text = itemID; } } items = itemNd.selectNodes('.//Item[not(@action) and not(.//Item/@action)]'); for (i = 0; i < items.length; i++) { items[i].setAttribute('action', 'get'); } items = itemNd.selectNodes('.//Item[@action="get" and (not(.//Item) or not(.//Item/@action!="get"))]'); for (i = 0; i < items.length; i++) { item = items[i]; itemID = item.getAttribute('id'); parentNd = item.parentNode; if (parentNd.nodeName == 'Relationships') { parentNd.removeChild(item); } else { if (itemID) { parentNd.removeChild(item); parentNd.text = itemID; } } } items = itemNd.selectNodes('.//Item[@action="get"]'); for (i = 0; i < items.length; i++) { items[i].setAttribute('action', 'skip'); } }; function ClearDependenciesInMetadataCache(aras, itemNd) { var items = itemNd.selectNodes('descendant-or-self::Item'); for (var i = 0; i < items.length; i++) { var tmpId = items[i].getAttribute('id'); if (tmpId) { aras.MetadataCache.RemoveItemById(tmpId); } } var srcId = aras.getItemProperty(itemNd, 'source_id'); if (srcId) { aras.MetadataCache.RemoveItemById(srcId); } //calling new method to clear metadata dates in Cache if Item has certain type var NeedClearCache = itemNd.getAttribute('type'); if (NeedClearCache == 'ItemType' || NeedClearCache == 'Property' || NeedClearCache == 'Grid Event' || NeedClearCache == 'View' || NeedClearCache == 'TOC View' || NeedClearCache == 'Item Action' || NeedClearCache == 'Item Report' || NeedClearCache == 'Client Event' || NeedClearCache == 'Morphae' || NeedClearCache == 'RelationshipType' || NeedClearCache == 'Relationship View' || NeedClearCache == 'Relationship Grid Event' || NeedClearCache == 'Can Add' || NeedClearCache == 'History Template' || NeedClearCache == 'History Template Action' || NeedClearCache == 'History Action') { aras.MetadataCache.DeleteITDatesFromCache();// if saving IT - remove all IT dates from cache, form dates can stay } if (NeedClearCache == 'ItemType' || NeedClearCache == 'RelationshipType' || NeedClearCache == 'Relationship View' || NeedClearCache == 'Relationship Grid Event') { aras.MetadataCache.DeleteRTDatesFromCache(); } if (NeedClearCache == 'Identity') { aras.MetadataCache.DeleteITDatesFromCache(); aras.MetadataCache.DeleteIdentityDatesFromCache(); } //If node isn't not part of ItemType, but List - remove List dates from cache if (NeedClearCache == 'List' || NeedClearCache == 'Value' || NeedClearCache == 'Filter Value') { aras.MetadataCache.DeleteListDatesFromCache(); } //If node isn't not part of ItemType nor List but Form - remove Form and IT dates from cache //hack: When new ItemType is being created server creates for it new form using "Create Form for ItemType" server method. To update form cache ItemType variant is being added. if (NeedClearCache == 'Form' || NeedClearCache == 'Form Event' || NeedClearCache == 'Method' || NeedClearCache == 'Body' || NeedClearCache == 'Field' || NeedClearCache == 'Field Event' || NeedClearCache == 'Property' || NeedClearCache == 'List' || NeedClearCache == 'ItemType') { aras.MetadataCache.DeleteFormDatesFromCache(); aras.MetadataCache.DeleteITDatesFromCache();//remove IT dates on saving Form, since it affects IT aras.MetadataCache.DeleteClientMethodDatesFromCache(); aras.MetadataCache.DeleteAllClientMethodsDatesFromCache(); } //If node is searchMode, remove SearchMode dates from cache if (NeedClearCache == 'SearchMode') { aras.MetadataCache.DeleteSearchModeDatesFromCache(); } var _needClearCache = ',' + (NeedClearCache || '').toLowerCase() + ','; if (',globalpresentationconfiguration,itpresentationconfiguration,presentationconfiguration,presentationcommandbarsection,commandbarsection,commandbarsectionitem,commandbaritem,'.indexOf(_needClearCache) > -1) { aras.MetadataCache.DeleteConfigurableUiDatesFromCache(); } if (',presentationconfiguration,presentationcommandbarsection,'.indexOf(_needClearCache) > -1) { aras.MetadataCache.DeletePresentationConfigurationDatesFromCache(); } if (NeedClearCache === 'CommandBarSection') { aras.MetadataCache.DeleteCommandBarSectionDatesFromCache(); } if (NeedClearCache == 'ItemType' || NeedClearCache === 'cmf_ContentType') { aras.MetadataCache.DeleteContentTypeByDocumentItemTypeDatesFromCache(); aras.MetadataCache.DeleteITDatesFromCache();//remove IT dates on saving ContentType, since it affects a lot of IT } } Aras.prototype.calcMD5 = function(s) { return calcMD5(s); }; (function(){ function _sendFilesWithVaultAppletBefore(itemNd, statusMsg, XPath2ReturnedNd) { var win = this.uiFindWindowEx2(itemNd); if (!XPath2ReturnedNd) { XPath2ReturnedNd = this.XPathResult('/Item'); } var vaultServerURL = this.getVaultServerURL(); var vaultServerID = this.getVaultServerID(); if (vaultServerURL === '' || vaultServerID === '') { this.AlertError(this.getResource('', 'item_methods_ex.vault_sever_not_specified'), '', '', win); return null; } var vaultApplet = this.vault; vaultApplet.clearClientData(); vaultApplet.clearFileList(); var headers = this.getHttpHeadersForSoapMessage('ApplyItem'); headers['VAULTID'] = vaultServerID; for (var hName in headers) { vaultApplet.setClientData(hName, headers[hName]); } var fileNds = itemNd.selectNodes('descendant-or-self::Item[@type="File" and (@action="add" or @action="update")]'); for (var i = 0; i < fileNds.length; i++) { var fileNd = fileNds[i]; var fileID = fileNd.getAttribute('id'); if (fileID) { var fileRels = fileNd.selectSingleNode('Relationships'); if (!fileRels) { fileRels = this.createXmlElement('Relationships', fileNd); } else { var all_located = fileRels.selectNodes('Item[@type=\'Located\']'); // If file has more than one 'Located' then remove all of them except the // one that points to the default vault of the current user. // NOTE: it's a FUNDAMENTAL Innovator's approach - file is always // submitted to the default vault of the current user. If this // concept will be changed in the future then this code must be modified. var lcount = all_located.length; for (var j = 0; j < lcount; j++) { var located = all_located[j]; var rNd = located.selectSingleNode('related_id'); if (!rNd) { fileRels.removeChild(located); } else { var rvId = ''; var rItemNd = rNd.selectSingleNode('Item[@type=\'Vault\']'); if (rItemNd) { rvId = rItemNd.getAttribute('id'); } else { rvId = rNd.text; } if (rvId != vaultServerID) { fileRels.removeChild(located); } } } } var fileLocated = fileRels.selectSingleNode('Item[@type=\'Located\']'); if (!fileLocated) { fileLocated = this.createXmlElement('Item', fileRels); fileLocated.setAttribute('type', 'Located'); } if (!fileLocated.getAttribute('action')) { var newLocatedAction = ''; if (fileNd.getAttribute('action') == 'add') { newLocatedAction = 'add'; } else { newLocatedAction = 'merge'; } fileLocated.setAttribute('action', newLocatedAction); } // When file could have only one 'Located' we used on Located the condition 'where="1=1"' which essentially meant // "add if none or replace any existing Located on the File". With ability of a file to reside in multiple // vaults (i.e. item of type 'File' might have several 'Located' relationships) the behavior is "add Located // if file is not there yet; update the Located if the file already in the vault". This is achieved by // specifying on 'Located' condition 'where="related_id='{vault id}'"'. Note that additional condition // 'source_id={file id}' will be added on server when the sub-AML is processed. if (!fileLocated.getAttribute('id') && !fileLocated.getAttribute('where')) { fileLocated.setAttribute('where', 'related_id=\'' + vaultServerID + '\'' /*"AND source_id='"+fileID+"'"*/); } this.setItemProperty(fileLocated, 'related_id', vaultServerID); } //code related to export/import functionality. server_id == donor_id. var server_id = this.getItemProperty(fileNd, 'server_id'); if (server_id === '') { //this File is not exported thus check physical file. var checkedout_path = this.getItemProperty(fileNd, 'checkedout_path'); var filename = this.getItemProperty(fileNd, 'filename'); var FilePath; var itemId = this.getItemProperty(fileNd, 'id'); var isFileSelected = false; if (this.getItemProperty(fileNd, 'file_size')) { isFileSelected = true; } if (!isFileSelected || !filename) { FilePath = vaultApplet.selectFile(); if (!FilePath) { return null; } var parts = FilePath.split(/[\\\/]/); filename = parts[parts.length - 1]; this.setItemProperty(fileNd, 'filename', filename); } else { if (checkedout_path) { if (0 === checkedout_path.indexOf('/')) { FilePath = checkedout_path + '/' + filename; } else { FilePath = checkedout_path + '\\' + filename; } } else { FilePath = aras.vault.vault.associatedFileList[itemId]; } } this.setItemProperty(fileNd, 'checksum', vaultApplet.getFileChecksum(FilePath)); this.setItemProperty(fileNd, 'file_size', vaultApplet.getFileSize(FilePath)); vaultApplet.addFileToList(fileID, FilePath); } } var statusId = this.showStatusMessage('status', statusMsg, system_progressbar1_gif); var XMLdata = SoapConstants.EnvelopeBodyStart + '' + itemNd.xml + '' + SoapConstants.EnvelopeBodyEnd; vaultApplet.setClientData('XMLdata', XMLdata); return { vaultServerURL: vaultServerURL, vaultApplet: vaultApplet, statusId: statusId, win: win }; } function _sendFilesWithVaultAppletAfter(params, XPath2ReturnedNd, boolRes) { if (!XPath2ReturnedNd) { XPath2ReturnedNd = this.XPathResult('/Item'); } this.clearStatusMessage(params.statusId); var resXML = params.vaultApplet.getResponse(); if (!boolRes || !resXML) { this.AlertError(this.getResource('', 'item_methods_ex.failed_upload_file', params.vaultServerURL), '', '', params.win); if (!boolRes) { resXML += params.vaultApplet.getLastError(); } this.AlertError(this.getResource('', 'item_methods_ex.internal_error_occured'), boolRes + '\n' + resXML, this.getResource('', 'common.client_side_err'), params.win); return null; } var soapRes = new SOAPResults(this, resXML); var faultCode = soapRes.getFaultCode(); if (faultCode !== 0 && faultCode !== '0') {//because user can has just add access and no get access this.AlertError(soapRes, params.win); return null; } var resDom = soapRes.results; if (this.hasMessage(resDom)) {// check for message this.refreshWindows(this.getMessageNode(resDom), resDom); } return resDom.selectSingleNode(XPath2ReturnedNd); } Aras.prototype.sendFilesWithVaultApplet = function Aras_sendFilesWithVaultApplet(itemNd, statusMsg, XPath2ReturnedNd) { /*---------------------------------------- * sendFilesWithVaultApplet * * Purpose: * This function is for iternal use only. DO NOT use in User Methods * Checks physical files. * Sets headers and send physical files to Vault * * Arguments: * itemNd - xml node to be processed * statusMsg - string to show in status bar while files being uploaded * XPath2ReturnedNd = xpath to select returned node. Default: aras.XPathResult('/Item') */ var params = _sendFilesWithVaultAppletBefore.call(this, itemNd, statusMsg, XPath2ReturnedNd); if (!params) { return params; } var boolRes = params.vaultApplet.sendFiles(params.vaultServerURL); return _sendFilesWithVaultAppletAfter.call(this, params, XPath2ReturnedNd, boolRes); }; Aras.prototype.sendFilesWithVaultAppletAsync = function Aras_sendFilesWithVaultAppletAsync(itemNd, statusMsg, XPath2ReturnedNd) { var params = _sendFilesWithVaultAppletBefore.call(this, itemNd, statusMsg, XPath2ReturnedNd); if (!params) { return Promise.resolve(params); } return params.vaultApplet.vault.sendFilesAsync(params.vaultServerURL).then(function(boolRes) { return _sendFilesWithVaultAppletAfter.call(this, params, XPath2ReturnedNd, boolRes); }.bind(this)); }; })(); Aras.prototype.clientItemValidation = function Aras_clientItemValidation(itemTypeName, itemNd, breakOnFirstError, emptyPropertyWithDefaultValueCallback) { var resultErrors = []; var checkErrors = []; //general checks for the item to be saved: all required parameters should be set if (itemTypeName) { checkErrors = this.checkItemForErrors(itemNd, null, null, breakOnFirstError, emptyPropertyWithDefaultValueCallback); if (checkErrors.length > 0) { resultErrors = resultErrors.concat(checkErrors); if (breakOnFirstError) { return resultErrors; } } } //special checks for relationships and related items var newRelNodes = itemNd.selectNodes('Relationships/Item[@isDirty=\'1\' or @isTemp=\'1\']'); var iter; for (iter = 0; iter < newRelNodes.length; iter++) { checkErrors = this.checkItemForErrors(newRelNodes[iter], 'source_id', null, breakOnFirstError, emptyPropertyWithDefaultValueCallback); if (checkErrors.length > 0) { resultErrors = resultErrors.concat(checkErrors); if (breakOnFirstError) { return resultErrors; } } } var newRelatedNodes = itemNd.selectNodes('Relationships/Item/related_id/Item[@isDirty=\'1\' or @isTemp=\'1\']'); for (iter = 0; iter < newRelatedNodes.length; iter++) { checkErrors = this.checkItemForErrors(newRelatedNodes[iter], 'source_id', null, breakOnFirstError, emptyPropertyWithDefaultValueCallback); if (checkErrors.length > 0) { resultErrors = resultErrors.concat(checkErrors); if (breakOnFirstError) { return resultErrors; } } } return resultErrors; }; (function() { function _saveItemExBefore(itemNd, confirmSuccess, doVersion) { if (!itemNd) { return null; } if (confirmSuccess === undefined || confirmSuccess === null) { confirmSuccess = true; } if (doVersion === undefined || doVersion === null) { doVersion = false; } var itemTypeName = itemNd.getAttribute('type'); var win = this.uiFindWindowEx2(itemNd); //special checks for the item of ItemType type if (itemTypeName == 'ItemType' && !this.checkItemType(itemNd, win)) { return null; } var self = this; var defaultFieldCheckCallback = function (itemNode, reqName, proplabel, defVal) { var ask = self.confirm(self.getResource('', 'item_methods_ex.field_required_default_will_be_used', proplabel, defVal)); if (ask) { self.setItemProperty(itemNode, reqName, defVal); } return {result: ask, message: ''}; }; var validationErrors = this.clientItemValidation(itemTypeName, itemNd, true, defaultFieldCheckCallback); if (validationErrors.length > 0) { if (validationErrors[0].message) { this.AlertError(validationErrors[0].message, '', '', win); } return null; } var backupCopy = itemNd; var oldParent = backupCopy.parentNode; itemNd = itemNd.cloneNode(true); this.prepareItem4Save(itemNd); var isTemp = this.isTempEx(itemNd); if (isTemp) { itemNd.setAttribute('action', 'add'); this.setItemProperty(itemNd, 'locked_by_id', this.getCurrentUserID()); if (itemTypeName == 'RelationshipType') { if (!itemNd.selectSingleNode('relationship_id/Item')) { var rsItemNode = itemNd.selectSingleNode('relationship_id'); if (rsItemNode) { var rs = this.getItemById('', rsItemNode.text, 0); if (rs) { rsItemNode.text = ''; rsItemNode.appendChild(rs.cloneNode(true)); } } } var tmp001 = itemNd.selectSingleNode('relationship_id/Item'); if (tmp001 && this.getItemProperty(tmp001, 'name') === '') { this.setItemProperty(tmp001, 'name', this.getItemProperty(itemNd, 'name')); } } } else if (doVersion) { itemNd.setAttribute('action', 'version'); } else { itemNd.setAttribute('action', 'update'); } var tempArray = []; this.doCacheUpdate(true, itemNd, tempArray); var statusMsg = ''; if (isTemp) { statusMsg = this.getResource('', 'item_methods_ex.adding', itemTypeName); } else if (doVersion) { statusMsg = this.getResource('', 'item_methods_ex.versioning', itemTypeName); } else { statusMsg = this.getResource('', 'item_methods_ex.updating', itemTypeName); } return { confirmSuccess: confirmSuccess, itemTypeName: itemTypeName, backupCopy: backupCopy, statusMsg: statusMsg, oldParent: oldParent, tempArray: tempArray, itemNd: itemNd, win: win }; } function _saveItemAfter(res, params) { if (!res) { return null; } //alert("a"); var itemTypeName = params.itemTypeName; var win = params.win; var oldParent = params.oldParent; var backupCopy = params.backupCopy; var tempArray = params.tempArray; var confirmSuccess = params.confirmSuccess; var itemNd = params.itemNd; var itemID = itemNd.getAttribute('id'); // alert(itemID); res.setAttribute('levels', '0'); var newID = res.getAttribute('id'); this.updateInCacheEx(backupCopy, res); var topWindow; if (win && win.isTearOff) { if (win.updateItemsGrid) { win.updateItemsGrid(res); } topWindow = window.opener ? this.getMostTopWindowWithAras(window.opener) : null; if (topWindow && topWindow.main) { if (itemTypeName == 'ItemType') { //alert("b"); //alert(itemID.split(';')); //topWindow.updateTree(itemID.split(';')); topWindow.updateTree("Administration"); } else if (itemTypeName == 'Action') { topWindow.UpdateMenuAfterCacheReset(itemTypeName); } else if (itemTypeName == 'Report') { topWindow.UpdateMenuAfterCacheReset(itemTypeName); } else if (itemTypeName == 'SelfServiceReport') { if (topWindow.itemTypeName == 'MyReports') { topWindow.updateReports(); } else { topWindow.UpdateMenuAfterCacheReset(itemTypeName); } } } } else { topWindow = this.getMostTopWindowWithAras(window); if (itemTypeName == 'ItemType') { //alert(itemID.split(';')); topWindow.updateTree(itemID.split(';')); } else if (itemTypeName == 'Action') { topWindow.UpdateMenuAfterCacheReset(itemTypeName); } else if (itemTypeName == 'Report' || itemTypeName == 'SelfServiceReport') { topWindow.UpdateMenuAfterCacheReset(itemTypeName); } } if (itemTypeName == 'RelationshipType') { var relationship_id = this.getItemProperty(itemNd, 'relationship_id'); if (relationship_id) { this.removeFromCache(relationship_id); } } else if (itemTypeName == 'ItemType') { var oldItemTypeName = !this.isTempEx(itemNd) ? this.getItemTypeName(itemID) : null; var item_name = (oldItemTypeName) ? oldItemTypeName : this.getItemProperty(itemNd, 'name'); this.deletePropertyFromObject(this.sGridsSetups, item_name); } if (oldParent) { var tmpRes = oldParent.selectSingleNode('Item[@id="' + newID + '"]'); if (tmpRes === null && newID != itemID && oldParent.selectSingleNode('Item[@id="' + itemID + '"]') !== null) { //possible when related item is versionable and relationship behavior is fixed //when relationship still points to previous generation. tmpRes = this.getFromCache(newID); this.updateInCacheEx(tmpRes, res); res = this.getFromCache(newID); } else { res = tmpRes; } } else { res = this.getFromCache(newID); } if (!res) { return null; } this.doCacheUpdate(false, itemNd, tempArray); ClearDependenciesInMetadataCache(this, itemNd); if (confirmSuccess) { var keyed_name = this.getKeyedNameEx(res); if (keyed_name && '' !== keyed_name) { this.AlertSuccess(this.getResource('', 'item_methods_ex.item_saved_successfully', '\'' + keyed_name + '\' '), win); } else { this.AlertSuccess(this.getResource('', 'item_methods_ex.item_saved_successfully', ''), win); } } params = this.newObject(); params.itemID = itemID; params.itemNd = res; this.fireEvent('ItemSave', params); return res; } /*-- saveItemEx * * Method to save an item * id = the id for the item to be saved * */ Aras.prototype.saveItemEx = function Aras_saveItemEx(itemNd, confirmSuccess, doVersion) { var params = _saveItemExBefore.call(this, itemNd, confirmSuccess, doVersion); if (!params) { return params; } var res = this.applyItemWithFilesCheck(params.itemNd, params.win, params.statusMsg, this.XPathResult('/Item')); return _saveItemAfter.call(this, res, params); }; Aras.prototype.saveItemExAsync = function Aras_saveItemExAsync(itemNd, confirmSuccess, doVersion) { var params = _saveItemExBefore.call(this, itemNd, confirmSuccess, doVersion); if (!params) { return Promise.resolve(params); } return this.applyItemWithFilesCheckAsync(params.itemNd, params.win, params.statusMsg, this.XPathResult('/Item')).then(function (res) { return _saveItemAfter.call(this, res, params); }.bind(this)); }; })(); Aras.prototype.doCacheUpdate = function Aras_doCacheUpdate(prepare, itemNd, tempArray) { var nodes; var i; if (prepare) { nodes = itemNd.selectNodes('descendant-or-self::Item[@id and (@action="add" or @action="create")]'); for (i = 0; i < nodes.length; i++) { tempArray.push(new Array(nodes[i].getAttribute('id'), nodes[i].getAttribute('type'))); } } else { for (i = 0; i < tempArray.length; i++) { nodes = this.itemsCache.getItemsByXPath('/Innovator/Items//Item[@id="' + tempArray[i][0] + '" and (@action="add" or @action="create")]'); for (var o = 0; o < nodes.length; o++) { nodes[o].setAttribute('action', 'skip'); nodes[o].removeAttribute('isTemp'); nodes[o].removeAttribute('isDirty'); } if (i === 0) { continue; } var itemID = tempArray[i][0]; } } }; Aras.prototype.downloadFile = function ArasDownloadFile(fileNd, preferredName) { var fileURL = this.getFileURLEx(fileNd); if (!fileURL) { this.AlertError(this.getResource('', 'item_methods_ex.failed_download_file_url_empty')); return false; } if (preferredName) { this.vault.setLocalFileName(preferredName); } var isSucceeded = this.vault.downloadFile(fileURL); if (!isSucceeded) { this.AlertError(this.getResource('', 'item_methods_ex.failed_download_file')); return false; } return true; }; // === lockItemEx ==== // Method to lock the item passing the item object // itemNode = the item // =================== Aras.prototype.lockItemEx = function Aras_lockItemEx(itemNode) { var ownerWindow = this.uiFindWindowEx2(itemNode), itemID = itemNode.getAttribute('id'), itemTypeName = itemNode.getAttribute('type'), itemType = this.getItemTypeDictionary(itemTypeName), isRelationship = this.getItemProperty(itemType.node, 'is_relationship'), isPolyItem = this.isPolymorphic(itemType.node); if (isRelationship == '1' && this.isDirtyEx(itemNode)) { var sourceNd = itemNode.selectSingleNode('../..'); if (sourceNd && this.isDirtyEx(sourceNd)) { var itLabel = this.getItemProperty(itemType.node, 'label') || this.getItemProperty(itemType.node, 'name'), param = { aras: this, buttons: {btnOK: this.getResource('', 'common.ok'), btnCancel: this.getResource('', 'common.cancel')}, defaultButton: 'btnCancel', message: this.getResource('', 'item_methods_ex.locking_it_lose_changes', itLabel) }, options = {dialogWidth: 300, dialogHeight: 150, center: true}, result; if (window.showModalDialog) { result = this.modalDialogHelper.show('DefaultModal', ownerWindow, param, options, 'groupChgsDialog.html'); } else { result = window.confirm(param.message) ? 'btnYes' : 'btnCancel'; } if (result == 'btnCancel') { return null; } } } var statusId = this.showStatusMessage('status', this.getResource('', 'common.locking_item_type', itemTypeName), system_progressbar1_gif), bodyStr = '', requestResult = this.soapSend('ApplyItem', bodyStr), returnedItem; this.clearStatusMessage(statusId); var faultCode = requestResult.getFaultCode(); if (faultCode !== 0 && faultCode !== '0') { this.AlertError(requestResult, ownerWindow); return null; } returnedItem = requestResult.results.selectSingleNode(this.XPathResult('/Item')); if (returnedItem) { var oldParent = itemNode.parentNode; returnedItem.setAttribute('loadedPartialy', '0'); this.updateInCacheEx(itemNode, returnedItem); if (oldParent) { itemNode = oldParent.selectSingleNode('Item[@id="' + itemID + '"]') || oldParent.selectSingleNode('Item'); } else { itemNode = this.getFromCache(itemID); } this.fireEvent('ItemLock', {itemID: itemNode.getAttribute('id'), itemNd: itemNode, newLockedValue: this.isLocked(itemNode)}); return itemNode; } else { this.AlertError(this.getResource('', 'item_methods_ex.failed_get_item_type_from_sever', itemTypeName), '', '', ownerWindow); return null; } }; // === unlockItemEx ==== // Method to unlock the item passing the item object // itemNode = the item // ===================== Aras.prototype.unlockItemEx = function Aras_unlockItemEx(itemNode, saveChanges) { var itemTypeName = itemNode.getAttribute('type'), ownerWindow = this.uiFindWindowEx2(itemNode); if (this.isTempEx(itemNode)) { this.AlertError(this.getResource('', 'item_methods_ex.failed_unlock_item_type', itemTypeName), '', '', ownerWindow); return null; } var itemType = this.getItemTypeDictionary(itemTypeName), isPolyItem = (itemType && itemType.node) ? this.isPolymorphic(itemType.node) : false; if (saveChanges === undefined) { var isDirty = this.isDirtyEx(itemNode); if (isDirty) { var options = {dialogWidth: 400, dialogHeight: 200, center: true}, params = { aras: this, message: this.getResource('', 'item_methods_ex.unlocking_discard_your_changes', itemTypeName, this.getKeyedNameEx(itemNode)), buttons: { btnYes: this.getResource('', 'common.yes'), btnSaveAndUnlock: this.getResource('', 'item_methods_ex.save_first'), btnCancel: this.getResource('', 'common.cancel') }, defaultButton: 'btnCancel' }, returnedValue; if (window.showModalDialog) { returnedValue = this.modalDialogHelper.show('DefaultModal', ownerWindow, params, options, 'groupChgsDialog.html'); } else { returnedValue = 'btnCancel'; if (window.confirm(this.getResource('', 'item_methods_ex.save_your_changes', itemTypeName, this.getKeyedNameEx(itemNode)))) { returnedValue = 'btnSaveAndUnlock'; } else if (window.confirm(this.getResource('', 'item_methods_ex.unlocking_discard_your_changes', itemTypeName, this.getKeyedNameEx(itemNode)))) { returnedValue = 'btnYes'; } } if (returnedValue == 'btnCancel') { return null; } else { saveChanges = (returnedValue != 'btnYes'); } } } if (saveChanges) { itemNode = this.saveItemEx(itemNode); if (!itemNode) { return null; } } var statusId = this.showStatusMessage('status', this.getResource('', 'item_methods_ex.unlocking_itemtype', itemTypeName), system_progressbar1_gif), itemId = itemNode.getAttribute('id'), lockedById = itemNode.selectSingleNode('locked_by_id'), queryResult; if (!lockedById) { queryResult = this.soapSend('ApplyItem', ''); } else { queryResult = this.soapSend('ApplyItem', '', '', saveChanges); } this.clearStatusMessage(statusId); if (!queryResult.getFaultCode()) { var resultItem = queryResult.results.selectSingleNode(this.XPathResult('/Item')), newResult; if (resultItem) { resultItem.setAttribute('loadedPartialy', '0'); var oldParent = itemNode.parentNode; this.updateInCacheEx(itemNode, resultItem); this.updateFilesInCache(resultItem); newResult = oldParent ? oldParent.selectSingleNode('Item[@id="' + itemId + '"]') : this.getFromCache(itemId); resultItem = newResult || resultItem; this.fireEvent('ItemLock', {itemID: resultItem.getAttribute('id'), itemNd: resultItem, newLockedValue: this.isLocked(resultItem)}); return resultItem; } else { this.AlertError(this.getResource('', 'item_methods_ex.failed_get_item_type_from_server', itemTypeName), '', '', ownerWindow); return null; } } else { this.AlertError(queryResult, ownerWindow); return null; } }; Aras.prototype.updateFilesInCache = function Aras_updateFilesInCache(itemNd) { var itemTypeName = itemNd.getAttribute('type'), isDiscoverOnly = itemNd.getAttribute('discover_only') == '1'; if (itemTypeName != 'File' && !isDiscoverOnly) { var itemType = this.getItemTypeForClient(itemTypeName).node, fileProperties = this.getPropertiesOfTypeFile(itemType), propertyName, fileId, fileNode, queryItem, queryResult, i; for (i = 0; i < fileProperties.length; i++) { propertyName = this.getItemProperty(fileProperties[i], 'name'); fileId = this.getItemProperty(itemNd, propertyName); if (fileId) { this.removeFromCache(fileId); queryItem = new this.getMostTopWindowWithAras(window).Item(); queryItem.setType('File'); queryItem.setAction('get'); queryItem.setID(fileId); queryItem.setAttribute('select', 'filename,file_size,file_type,checkedout_path,comments,checksum,label,mimetype'); queryResult = queryItem.apply(); if (queryResult.isEmpty()) { continue; } else { if (!queryResult.isError()) { fileNode = queryResult.getItemByIndex(0).node; this.updateInCache(fileNode); } else { this.AlertError(queryResult); return; } } } } } }; Aras.prototype.purgeItemEx = function Aras_purgeItemEx(itemNd, silentMode) { /*-- purgeItem * * Method to delete the latest version of the item (or the item if it's not versionable) * itemNd - * silentMode - flag to know if user confirmation is NOT needed * */ return this.PurgeAndDeleteItem_CommonPartEx(itemNd, silentMode, 'purge'); }; Aras.prototype.deleteItemEx = function Aras_deleteItemEx(itemNd, silentMode) { /*-- deleteItem * * Method to delete all versions of the item * itemNd - * silentMode - flag to know if user confirmation is NOT needed * */ return this.PurgeAndDeleteItem_CommonPartEx(itemNd, silentMode, 'delete'); }; Aras.prototype.PurgeAndDeleteItem_CommonPartEx = function Aras_PurgeAndDeleteItem_CommonPartEx(itemNd, silentMode, purgeORdelete) { /*-- PurgeAndDeleteItem_CommonPartEx * * This method is for ***internal purposes only***. * */ if (silentMode === undefined) { silentMode = false; } var ItemId = itemNd.getAttribute('id'); var ItemTypeName = itemNd.getAttribute('type'); //prepare if (!silentMode && !this.Confirm_PurgeAndDeleteItem(ItemId, this.getKeyedNameEx(itemNd), purgeORdelete)) { return false; } var DeletedItemTypeName; var relationship_id; if (!this.isTempEx(itemNd)) { //save some information if (ItemTypeName == 'ItemType') { if (this.getItemProperty(itemNd, 'is_relationship') == '1') { relationship_id = ItemId; } DeletedItemTypeName = this.getItemProperty(itemNd, 'name'); } else if (ItemTypeName == 'RelationshipType') { relationship_id = this.getItemProperty(itemNd, 'relationship_id'); DeletedItemTypeName = this.getItemProperty(itemNd, 'name'); } //delete if (!this.SendSoap_PurgeAndDeleteItem(ItemTypeName, ItemId, purgeORdelete)) { return false; } } itemNd.setAttribute('action', 'skip'); //remove node from parent var tmpNd = itemNd.parentNode; if (tmpNd) { tmpNd.removeChild(itemNd); } //delete all dependent stuff this.RemoveGarbage_PurgeAndDeleteItem(ItemTypeName, ItemId, DeletedItemTypeName, relationship_id); this.MetadataCache.RemoveItemById(ItemId); return true; }; Aras.prototype.getKeyedNameEx = function Aras_getKeyedNameEx(itemNd) { /*---------------------------------------- * getKeyedNameEx * * Purpose: build and return keyed name of an Item. * * Arguments: * itemNd - xml node of Item to get keyed name of. */ var res = ''; if (itemNd.nodeName != 'Item') { return res; } if ((!this.isDirtyEx(itemNd)) && (!this.isTempEx(itemNd))) { res = itemNd.getAttribute('keyed_name'); if (res) { return res; } res = this.getItemProperty(itemNd, 'keyed_name'); if (res !== '') { return res; } } var itemTypeName = itemNd.getAttribute('type'); res = itemNd.getAttribute('id'); var itemType = this.getItemTypeDictionary(itemTypeName); if (!itemType) { return res; } var relationshipItems = itemType.node.selectNodes('Relationships/Item[@type="Property"]'); var tmpArr = []; //pairs keyOrder -> propValue var counter = 0; var i; for (i = 0; i < relationshipItems.length; i++) { var propNd = relationshipItems[i]; var propName = this.getItemProperty(propNd, 'name'); if (propName === '') { continue; } var keyOrder = this.getItemProperty(propNd, 'keyed_name_order'); if (keyOrder === '') { continue; } var node = itemNd.selectSingleNode(propName); if (!node || node.childNodes.length != 1) { continue; } var txt = ''; if (node.firstChild.nodeType == 1) {//if nested Item txt = this.getKeyedNameEx(node.firstChild); } else { txt = node.text; } if (txt !== '') { tmpArr[counter] = new Array(keyOrder, txt); counter++; } } if (tmpArr.length > 0) { tmpArr = tmpArr.sort(keyedNameSorter); res = tmpArr[0][1]; for (i = 1; i < tmpArr.length; i++) { res += ' ' + tmpArr[i][1]; } } return res; }; Aras.prototype.getKeyedNameAttribute = function(node, element) { if (!node) { return; } var value; var tmpNd = node.selectSingleNode(element); if (tmpNd) { value = tmpNd.getAttribute('keyed_name'); if (!value) { value = ''; } } else { value = ''; } return value; }; function keyedNameSorter(a, b) { var s1 = parseInt(a[0]); if (isNaN(s1)) { return 1; } var s2 = parseInt(b[0]); if (isNaN(s2)) { return -1; } if (s1 < s2) { return -1; } else if (s1 == s2) { return 0; } else { return 1; } } /*-- getItemRelationshipsEx * * Method to * * */ Aras.prototype.getItemRelationshipsEx = function(itemNd, relsName, pageSize, page, body, forceReplaceByItemFromServer) { if (!(itemNd && relsName)) { return null; } if (pageSize === undefined || pageSize === null) { pageSize = ''; } if (page === undefined || page === null) { page = ''; } if (body === undefined || body === null) { body = ''; } if (forceReplaceByItemFromServer === undefined || forceReplaceByItemFromServer === null) { forceReplaceByItemFromServer = false; } var itemID = itemNd.getAttribute('id'); var itemTypeName = itemNd.getAttribute('type'); var res = null; if (!forceReplaceByItemFromServer && (pageSize == -1 || this.isTempID(itemID) || (itemNd.getAttribute('levels') && parseInt(itemNd.getAttribute('levels')) > 0))) { if (!isNaN(parseInt(pageSize)) && parseInt(pageSize) > 0 && !isNaN(parseInt(page)) && parseInt(page) > -1) { res = itemNd.selectNodes('Relationships/Item[@type="' + relsName + '" and @page="' + page + '"]'); if (res && res.length == pageSize) { return res; } } else { res = itemNd.selectNodes('Relationships/Item[@type="' + relsName + '"]'); if (res && res.length > 0) { return res; } } } var bodyStr = ''; } res = this.soapSend('ApplyItem', bodyStr); var faultCode = res.getFaultCode(); if (faultCode !== 0 && faultCode !== '0') { this.AlertError(res); return null; } if (!itemNd.selectSingleNode('Relationships')) { this.createXmlElement('Relationships', itemNd); } var rels = res.results.selectNodes(this.XPathResult('/Item[@type="' + relsName + '"]')); var itemRels = itemNd.selectSingleNode('Relationships'); var idsStr = ''; for (var i = 0; i < rels.length; i++) { var rel = rels[i].cloneNode(true); var relId = rel.getAttribute('id'); if (i > 0) { idsStr += ' or '; } idsStr += '@id="' + relId + '"'; var prevRel = itemRels.selectSingleNode('Item[@type="' + relsName + '" and @id="' + relId + '"]'); if (prevRel) { if (forceReplaceByItemFromServer) { // By some reason the previous implementation did not replaced existing on the node // relationships with the new relationships obtained from the server but rather // just removed some attributes on them (like "pagesize", etc.). From other side those // relationships that don't exist on the 'itemNd' are added to it. This is wrong as // the newly obtained relationships even if they already exist on 'itemNd' might have // some properties that are different in db from what is in the client memory. // NOTE: the fix will break the case when the client changes some relationship properties // in memory and then calls this method expecting that these properties will stay unchanged, // but: a) this method seems to be called only from getFileURLEx(..); b) if the above // behavior is expected then another method is probably required which must be called // something like 'mergeRelationships'. // by Andrey Knourenko itemRels.removeChild(prevRel); } else { this.mergeItem(prevRel, rel); continue; } } itemRels.appendChild(rel); } itemNd.setAttribute('levels', '0'); if (idsStr === '') { return null; } res = itemRels.selectNodes('Item[@type="' + relsName + '" and (' + idsStr + ')]'); return res; }; /*-- getItemLastVersionEx * * Method to load the latest version for the item * itemTypeName = the ItemType name * itemId = the id for the item * */ Aras.prototype.getItemLastVersionEx = function(itemNd) { var res = this.soapSend('ApplyItem', ''); var faultCode = res.getFaultCode(); if (faultCode !== 0 && faultCode !== '0') { return null; } res = res.results.selectSingleNode(this.XPathResult('/Item')); if (!res) { return null; } itemNd.parentNode.replaceChild(res, itemNd); return res; }; //getItemLastVersionEx Aras.prototype.downloadItemFiles = function Aras_downloadItemFiles(itemNd) { /* this method is for internal use *** only *** */ if (!itemNd) { return false; } var itemTypeName = itemNd.getAttribute('type'); var itemType = this.getItemTypeForClient(itemTypeName).node; var fileProps = this.getPropertiesOfTypeFile(itemType); for (var i = 0; i < fileProps.length; i++) { var propNm = this.getItemProperty(fileProps[i], 'name'); var fileNd = itemNd.selectSingleNode(propNm + '/Item'); if (!fileNd) { var fileID = this.getItemProperty(itemNd, propNm); if (!fileID) { continue; } fileNd = this.getItemFromServer('File', fileID, 'filename').node; } if (!fileNd) { continue; } this.downloadFile(fileNd); } return true; }; Aras.prototype.promoteEx = function Aras_promoteEx(itemNd, stateName, comments, soapController) { if (!itemNd) { return null; } var itemID = itemNd.getAttribute('id'); var itemTypeName = itemNd.getAttribute('type'); var promoteParams = { typeName: itemTypeName, id: itemID, stateName: stateName, comments: comments }; var res = this.promoteItem_implementation(promoteParams, soapController); if (!res) { return null; } var oldParent = itemNd.parentNode; this.updateInCacheEx(itemNd, res); if (oldParent) { res = oldParent.selectSingleNode('Item[@id="' + itemID + '"]'); } else { res = this.getFromCache(itemID); } var params = this.newObject(); params.itemID = res.getAttribute('id'); params.itemNd = res; this.fireEvent('ItemSave', params); return res; }; Aras.prototype.getFileURLEx = function Aras_getFileURLEx(itemNd) { /* * Private method that returns 'Located' pointing to the vault in which the * specified file resides. The vault is selected by the following algorithm: * - if file is not stale in the default vault of the current user then return this vault * - else return the first vault in which the file is not stale * NOTE: file is called 'not stale' in vault if 'Located' referencing the vault has * the maximum value of property 'file_version' among other 'Located' of the same file. */ function getLocatedForFile(aras, itemNd) { var fitem = aras.newIOMItem(); fitem.loadAML(itemNd.xml); var all_located = fitem.getRelationships('Located'); // First find the max 'file_version' among all 'Located' rels var maxv = 0; var lcount = all_located.getItemCount(); var i; var located; var file_version; for (i = 0; i < lcount; i++) { located = all_located.getItemByIndex(i); file_version = located.getProperty('file_version') * 1; if (file_version > maxv) { maxv = file_version; } } var sorted_located = getSortedLocatedList(aras, fitem, all_located); // Now go through the sorted list and return first non-stale vault for (i = 0; i < sorted_located.length; i++) { located = sorted_located[i]; file_version = located.getProperty('file_version') * 1; if (file_version == maxv) { return located.node; } } // It should never reach this point as at least one of vaults has non-stale file. return null; } // Build a list of 'Located' sorted by the priorities of vaults that they reference. // Sorting is done based on the 'ReadPriority' relationships of the current user + the // default vault of the user + remaining vaults. function getSortedLocatedList(aras, fitem, all_located) { var lcount = all_located.getItemCount(); var sorted_located = []; // Get all required information (default vault; etc.) for the current user var aml = '' + ' ' + aras.getUserID() + '' + ' ' + ' ' + ' ' + ''; var ureq = aras.newIOMItem(); ureq.loadAML(aml); var uresult = ureq.apply(); if (uresult.isError()) { throw new Error(1, uresult.getErrorString()); } // Note that because the above AML has 'orderBy' the 'all_rps' collection is sorted // by ReadPriority.priority. var all_rps = uresult.getRelationships('ReadPriority'); var rpcount = all_rps.getItemCount(); var i; var l; var located; for (i = 0; i < rpcount; i++) { var vault = all_rps.getItemByIndex(i).getRelatedItem(); // If the file is in the vault from the "ReadPriority" then add 'Located' that references // the vault to the sorted list. for (l = 0; l < lcount; l++) { located = all_located.getItemByIndex(l); if (vault.getID() == located.getRelatedItem().getID()) { sorted_located[sorted_located.length] = located; break; } } } // Now append the 'Located' to the default vault to the list if it's not there yet // (providing that the file is in the default vault). var dvfound = false; var default_vault = uresult.getPropertyItem('default_vault'); for (i = 0; i < sorted_located.length; i++) { if (sorted_located[i].getRelatedItem().getID() == default_vault.getID()) { dvfound = true; break; } } if (!dvfound) { for (i = 0; i < lcount; i++) { located = all_located.getItemByIndex(i); if (default_vault.getID() == located.getRelatedItem().getID()) { sorted_located[sorted_located.length] = located; break; } } } // Finally append 'Located' to all remaining vaults that the file resides in but that are // not in the sorted list yet. for (i = 0; i < lcount; i++) { located = all_located.getItemByIndex(i); var vfound = false; for (l = 0; l < sorted_located.length; l++) { if (sorted_located[l].getID() == located.getID()) { vfound = true; break; } } if (!vfound) { sorted_located[sorted_located.length] = located; } } return sorted_located; } /*---------------------------------------- * getFileURLEx * * Purpose: * get file URL using the following algorithm: * - take the default vault of the current user unless the file does not exist or stale in the vault * - otherwise take the first vault in which the file is not stale * * Arguments: * itemNd - xml node of the File to be downloaded * */ this.getItemRelationshipsEx(itemNd, 'Located', undefined, undefined, undefined, true); var locatedNd = getLocatedForFile(this, itemNd); if (!locatedNd) { this.AlertError(this.getResource('', 'item_methods_ex.failed_get_file_vault_could_not_be_located')); return ''; } var vaultNode = locatedNd.selectSingleNode('related_id/Item[@type="Vault"]'); var vault_id = ''; if (!vaultNode) { vault_id = locatedNd.selectSingleNode('related_id').text; vaultNode = this.getItemById('Vault', vault_id, 0); } else { vault_id = vaultNode.getAttribute('id'); } var vaultServerURL = vaultNode.selectSingleNode('vault_url').text; if (vaultServerURL === '') { return ''; } vaultServerURL = this.TransformVaultServerURL(vaultServerURL); var fileID = itemNd.getAttribute('id'); var fileName = this.getItemProperty(itemNd, 'filename'); var fileURL = vaultServerURL + '?dbName=' + encodeURIComponent(this.getDatabase()) + '&fileID=' + encodeURIComponent(fileID) + '&fileName=' + encodeURIComponent(fileName) + '&vaultId=' + vault_id; return fileURL; }; Aras.prototype.replacePolyItemNodeWithNativeItem = function Aras_replacePolyItemNodeWithNativeItem(ritem) { if (!(ritem && ritem.parentNode)) { this.AlertError('Item is null or doesn\'t have parent item.'); return ritem; } var typeId = ritem.getAttribute('typeId'); var relatedItemType = this.getItemTypeForClient(typeId, 'id').node; if (!relatedItemType) { this.AlertError('Can\'t get type of related item.'); return ritem; } if (this.isPolymorphic(relatedItemType)) { var nativeRelatedITID = this.getItemProperty(ritem, 'itemtype'); var relatedItemNd = this.getItemTypeForClient(nativeRelatedITID, 'id').node; if (!relatedItemNd) { this.AlertError('Can\'t get native item type of polymorphic item.'); return ritem; } var nativeRelated = this.getItemFromServer(this.getItemProperty(relatedItemNd, 'name'), ritem.getAttribute('id'), '*').node; if (nativeRelated) { ritem.parentNode.replaceChild(nativeRelated, ritem); return nativeRelated; } } return ritem; }; /** itemtype_methods.js **/ // © Copyright by Aras Corporation, 2004-2008. /* * The ItemType methods extension for the Aras Object. * */ /*-- getItemTypeProperties * * Method to get the properties for the ItemType * itemType = the itemType * */ Aras.prototype.getItemTypeProperties = function(itemType) { if (!itemType) { return; } with (this) { return itemType.selectNodes('Relationships/Item[@type="Property"]'); } }; Aras.prototype.rebuildView = function(viewId) { if (!viewId) { this.AlertError(this.getResource('', 'itemtype_methods.view_to_rebuild_not_specified'), '', ''); return false; } with (this) { var statusId = showStatusMessage('status', this.getResource('', 'itemtype_methods.rebuilding_view'), '../images/Progress.gif'); var res = soapSend('RebuildView', ''); clearStatusMessage(statusId); if (res.getFaultCode() != 0) { this.AlertError(res); return false; } var formNd = res.results.selectSingleNode('//Item[@type="Form"]'); if (!formNd) { return false; } var oldView = itemsCache.getItemByXPath('/Innovator/Items/Item[@type="ItemType"]/Relationships/Item[@type="View" and @id="' + viewId + '"]'); itemsCache.addItem(formNd); var formId = formNd.getAttribute('id'); var newView = getItem('View', 'related_id/Item/@id="' + formId + '"', '' + formId + '', 0); if (oldView) { oldView.parentNode.replaceChild(newView, oldView); } if (uiFindWindowEx(viewId)) { uiReShowItemEx(viewId, newView); } } return true; }; Aras.prototype.isPolymorphic = function(itemType) { var implementationType = this.getItemProperty(itemType, 'implementation_type'); return (implementationType == 'polymorphic'); }; Aras.prototype.getMorphaeList = function(itemType) { var morphae = itemType.selectNodes('Relationships/Item[@type=\'Morphae\']/related_id/Item'); return _fillItemTypeList(morphae, this); }; Aras.prototype.getPolymorphicsWhereUsedAsPolySource = function(itemTypeId) { var polyItems = this.applyItem( '' + '' + '' + '' + itemTypeId + '' + '' + '' + ''); if (polyItems) { var tmpDoc = this.createXMLDocument(); tmpDoc.loadXML(polyItems); polyItems = tmpDoc.selectNodes('Result/Item[@type=\'ItemType\']'); } else { return []; } return _fillItemTypeList(polyItems, this); }; function _fillItemTypeList(nodes, aras) { var result = []; for (var i = 0; i < nodes.length; i++) { var node = nodes[i]; var id = node.getAttribute('id'); var name = aras.getItemProperty(node, 'name'); var label = aras.getItemProperty(node, 'label'); if (label === null || label === '') { label = name; } result.push({id: id, name: name, label: label}); } return result; } /** ui_methods.js **/ // (c) Copyright by Aras Corporation, 2004-2011. ///--- User Interface methods ---/// /* * uiShowItem * * parameters: * 1) itemTypeName - may be empty string if item is in client cache * 2) itemID - obligatory * 3) viewMode - 'tab view' or 'openFile' * if not specified aras.getVariable('viewMode') is used * 4) isTearOff - true or false, if not specified aras.getVariable('TearOff') is used */ Aras.prototype.uiShowItem = function (itemTypeName, itemID, viewMode) { if (!itemID) return false; viewMode = viewMode || "tab view"; var itemNd = this.getItemById(itemTypeName, itemID, 0, undefined, "*"); if (!itemNd) return false; return this.uiShowItemEx(itemNd, viewMode); }; /* * uiReShowItem * * parameters: * 1) oldItemId- old id of item to be shown * 2) itemId - id of item to be shown //usually itemId==oldItemId * 2) editMode - 'view' or 'edit' * 3) viewMode - 'tab view', ' or 'openFile' * 4) isTearOff- true or false. */ Aras.prototype.uiReShowItem = function (oldItemId, itemId, editMode, viewMode) { if (!oldItemId || !itemId) return false; var itemNd = this.getItemById('', itemId, 0); if (!itemNd) return false; if (editMode === undefined || editMode.search(/^view$|^edit$/) === -1) { if (this.isTempID(itemId) || this.getNodeElement(itemNd, 'locked_by_id') === this.getCurrentUserID()) editMode = 'edit'; else editMode = 'view'; } viewMode = viewMode || "tab view"; return this.uiReShowItemEx(oldItemId, itemNd, viewMode); }; Aras.prototype.uiViewXMLInFrame = function Aras_uiViewXMLInFrame(frame, xmldoc, expandNodes) { if (!frame) return; var xsldoc = this.createXMLDocument(); var baseUrl = this.getBaseURL(); xsldoc.load(baseUrl + '/styles/default.xsl'); try { //TODO: there should be a better way to check if method setProperty is supported on xsldoc xsldoc.setProperty("SelectionNamespaces", 'xmlns:xsl="http://www.w3.org/1999/XSL/Transform"'); } catch (excep) { } xsldoc.selectSingleNode("./xsl:stylesheet/xsl:param").setAttribute("select", "boolean('" + expandNodes + "')"); frame.document.write(xmldoc.transformNode(xsldoc)); }; Aras.prototype.uiViewXMLstringInFrame = function Aras_uiViewXMLstringInFrame(frame, string, expandNodes) { if (!frame) return; var xmldoc = this.createXMLDocument(); xmldoc.loadXML(string); this.uiViewXMLInFrame(frame, xmldoc, expandNodes); }; Aras.prototype.uiFieldGetValue = function (uiField) { var uiForm = uiField.form; var name = uiField.name; var type = uiField.type; var value = null, i; if (uiField.field_type === 'item') value = uiField.internal_value; else if (type.search(/^text|^hidden$/) === 0) { if (uiField.internal_value) value = uiField.internal_value; else value = uiField.value; } else if (type === 'password') { if (uiField.pwdChanged === 1) value = calcMD5(uiField.value); else value = uiField.internal_value; } else if (type === 'checkbox') value = (uiField.checked) ? 1 : 0; else if (type === 'select-one') { if (uiField.selectedIndex !== -1) value = uiField.options[uiField.selectedIndex].value; } else if (type === 'radio') {///SNNicky: check!!!!! value = ''; for (i = 0; i < uiForm[name].length; i++) { if (uiForm[name][i].checked) { value = uiForm[name][i].value; break; } } } else if (type === 'checkbox_group') { value = ''; for (i = 0; i < uiForm[name].length; i++) { if (uiForm[name][i].checked) { if (value !== '') value += ','; value += uiForm[name][i].value; } } } this.AlertError(name + ":" + value, "", ""); //what does this do?? return value; }; Aras.prototype.getvisiblePropsForItemType = function Aras_getVisiblePropsForItemType(currItemType) { var itemTypeName = this.getItemProperty(currItemType, 'name'); var itemTypeId = currItemType.getAttribute('id'); var nodes_tmp = []; var cols = this.getPreferenceItemProperty("Core_GlobalLayout", null, "col_order"), i; var visiblePropNds = currItemType.selectNodes(this.getVisiblePropertiesXPath(itemTypeName)); if (cols) { cols = cols.split(';'); if (visiblePropNds.length === cols.length || visiblePropNds.length + 1 === cols.length) { for (i = 0; i < visiblePropNds.length; i++) { var propNm = this.getItemProperty(visiblePropNds[i], 'name'); for (var j = 0; j < cols.length; j++) { if ((propNm + "_D") === cols[j]) { nodes_tmp[j] = visiblePropNds[i]; break; } } if (j === cols.length) { cols = null; break; } } } else { cols = null; } } if (!cols) { visiblePropNds = this.sortProperties(visiblePropNds); } else { visiblePropNds = []; for (i = 0; i < nodes_tmp.length; i++) { if (nodes_tmp[i] !== undefined) visiblePropNds.push(nodes_tmp[i]); } } return visiblePropNds; }; Aras.prototype.uiInitItemsGridSetups = function Aras_uiInitItemsGridSetups(currItemType, visibleProps) { var itemTypeName = this.getItemProperty(currItemType, 'name'); var itemTypeId = currItemType.getAttribute('id'), i; if (!itemTypeName) return null; var self = this; // var _itemTypeName_ = itemTypeName.replace(/\s/g, '_'); var varsHash = {}; var gridSetups = this.sGridsSetups[itemTypeName]; if (!gridSetups) { gridSetups = this.newObject(); this.sGridsSetups[itemTypeName] = gridSetups; } var colWidths = this.getPreferenceItemProperty('Core_ItemGridLayout', itemTypeId, 'col_widths'); var colOrder = this.getPreferenceItemProperty('Core_ItemGridLayout', itemTypeId, 'col_order'); var flg = ((colWidths === null || colWidths === "") || (colOrder === null || colOrder === "") || (colWidths.split(";").length !== colOrder.split(";").length)); function CheckCorrectColumnsInfo(arr, suffix) { if (!arr) return; for (var i = 0; i < arr.length; i++) { var colNm = self.getItemProperty(arr[i], "name") + "_" + suffix; var re = new RegExp("(^|;)" + colNm + "(;|$)"); if (colOrder.search(re) === -1) { flg = true; break; } colOrder = colOrder.replace(re, "$1$2"); } } if (!flg) { //check if already saved setups are valid colOrder = colOrder.replace(/(^|;)L($|;)/, "$1$2"); if (!flg) CheckCorrectColumnsInfo(visibleProps, "D"); if (!flg) { colOrder = colOrder.replace(/;/g, ""); if (colOrder !== "") flg = true; } } if (flg) { colOrder = this.newArray(); colWidths = this.newArray(); colOrder[0] = "L"; colWidths[0] = 24; for (i = 0; i < visibleProps.length; i++) { var prop = visibleProps[i]; var name = this.getItemProperty(prop, "name") + "_D"; var width = parseInt(this.getItemProperty(prop, "column_width")); if (isNaN(width) || width === 0) width = 100; colOrder.push(name); colWidths.push(width); } varsHash.col_widths = colWidths.join(";"); varsHash.col_order = colOrder.join(";"); } else { colWidths = colWidths.split(';'); flg = false; //check for zero-width columns for (i = 0; i < colWidths.length; i++) { var newVal = parseInt(colWidths[i]); if (isNaN(newVal) || newVal < 0) { newVal = (i === 0 ? 24 : parseInt(this.getItemProperty(visibleProps[i - 1], 'column_width'))); if (isNaN(newVal) || newVal <= 0) newVal = 100; colWidths[i] = newVal; flg = true; } } if (flg) { varsHash.col_widths = colWidths.join(";"); } } this.setPreferenceItemProperties("Core_ItemGridLayout", itemTypeId, varsHash); }; Aras.prototype.uiInitRelationshipsGridSetups = function Aras_uiInitRelationshipsGridSetups(relationshiptypeID, Dprops, Rprops, grid_view) { if (!grid_view) { grid_view = "left"; } var self = this, prop, i; var colWidths = this.getPreferenceItemProperty('Core_RelGridLayout', relationshiptypeID, 'col_widths'); var colOrder = this.getPreferenceItemProperty('Core_RelGridLayout', relationshiptypeID, 'col_order'); var flg = ((colWidths === null || colWidths === "") || (colOrder === null || colOrder === "") || (colWidths.split(";").length !== colOrder.split(";").length)); function CheckCorrectColumnsInfo(arr, suffix) { if (!arr) return; for (var i = 0; i < arr.length; i++) { var colNm = self.getItemProperty(arr[i], "name") + "_" + suffix; var re = new RegExp("(^|;)" + colNm + "(;|$)"); if (colOrder.search(re) === -1) { flg = true; break; } colOrder = colOrder.replace(re, "$1$2"); } } function getColumnDefaultWidth(colNum) { var colNm = colOrder[colNum]; if (colNm === "L") return 24; var DR = colNm.substr(colNm.length - 1); var propNm = colNm.substr(0, colNm.length - 2); var propArr = null; if (DR === "D") propArr = Dprops; else if (DR === "R") propArr = Rprops; if (propArr) { for (var i = 0; i < propArr.length; i++) { var prop = propArr[i]; if (self.getItemProperty(prop, "name") === propNm) { var column_width = parseInt(self.getItemProperty(prop, "column_width")); if (isNaN(column_width)) column_width = 100; return column_width; } } } return 100; } if (!flg) { //check if already saved setups are valid if (Rprops) colOrder = colOrder.replace(/(^|;)L($|;)/, "$1$2"); if (!flg) CheckCorrectColumnsInfo(Dprops, "D"); if (!flg) CheckCorrectColumnsInfo(Rprops, "R"); if (!flg) { colOrder = colOrder.replace(/;/g, ""); if (colOrder !== "") flg = true; } if (!flg) { colOrder = this.getPreferenceItemProperty('Core_RelGridLayout', relationshiptypeID, "col_order"); colWidths = colWidths.split(';'); flg = false; //check for zero-width columns for (i = 0; i < colWidths.length; i++) { var newVal = parseInt(colWidths[i]); if (isNaN(newVal) || newVal < 0) { newVal = getColumnDefaultWidth(i); colWidths[i] = newVal; flg = true; } } if (flg) this.setPreferenceItemProperties("Core_RelGridLayout", relationshiptypeID, { col_widths: colWidths.join(";") }); return; } } colOrder = this.newArray(); colWidths = this.newArray(); if (Rprops) { colOrder[0] = "L"; colWidths[0] = 24; } // +++ sort columns var Dpriority = 0, Rpriority = 0; if (grid_view === "left") { //related item goes first Dpriority = 1; Rpriority = 0; } else if (grid_view === "intermix") { Dpriority = 0; Rpriority = 0; } else { Dpriority = 0; Rpriority = 1; } var allPropsInfoArr = []; if (Dprops) { for (i = 0; i < Dprops.length; i++) { prop = Dprops[i]; allPropsInfoArr.push( { name: this.getItemProperty(prop, "name") + "_D", width: this.getItemProperty(prop, "column_width"), sort_order: this.getItemProperty(prop, "sort_order"), default_search: this.getItemProperty(prop, "default_search"), priority: Dpriority }); } } if (Rprops) { for (i = 0; i < Rprops.length; i++) { prop = Rprops[i]; allPropsInfoArr.push( { name: this.getItemProperty(prop, "name") + "_R", width: this.getItemProperty(prop, "column_width"), sort_order: this.getItemProperty(prop, "sort_order"), default_search: this.getItemProperty(prop, "default_search"), priority: Rpriority }); } } function sorterF(p1, p2) { var c1 = parseInt(p1.priority); var c2 = parseInt(p2.priority); if (c1 < c2) return -1; else if (c2 < c1) return 1; else { c1 = parseInt(p1.sort_order); c2 = parseInt(p2.sort_order); if (isNaN(c2)) return -1; if (isNaN(c1)) return 1; if (c1 < c2) return -1; else if (c2 < c1) return 1; else { c1 = p1.name; c2 = p2.name; if (c1 < c2) return -1; else if (c2 < c1) return 1; else return 0; } } } allPropsInfoArr = allPropsInfoArr.sort(sorterF); // --- sort columns for (i = 0; i < allPropsInfoArr.length; i++) { colOrder.push(allPropsInfoArr[i].name); var width = parseInt(allPropsInfoArr[i].width); if (isNaN(width)) width = 100; colWidths.push(width); } this.setPreferenceItemProperties("Core_RelGridLayout", relationshiptypeID, { col_widths: colWidths.join(";"), col_order: colOrder.join(";") }); }; Aras.prototype.uiToggleCheckbox = function (uiField) { uiField.checked = uiField.checked ? false : true; }; Aras.prototype.uiGenerateGridXML = function Aras_uiGenerateGridXML(inDom, Dprops, Rprops, typeID, params, getCached) { var key = this.MetadataCache.CreateCacheKey("uiGenerateGridXML", typeID); if (params) { for (var k in params) { //k can be undefined in IE9 if one of param keyes was empty string, i.e. params[""] = "" //evaluating value by index: params[""] gives right value, but evaluating it with 'for' gives undefined value. if (k) { var additionalParam = k; if (params[k]) additionalParam += "=" + params[k]; key.push(additionalParam); } } } var xsl = this.MetadataCache.GetItem(key); if (xsl) xsl = xsl.content; var mainArasObj = this.findMainArasObject(); if (xsl && (getCached === undefined || getCached === true)) { } else { var sXsl = this.uiGenerateGridXSLT(Dprops, Rprops, params, typeID); xsl = mainArasObj.createXMLDocument(); xsl.loadXML(sXsl); var itemTypeNd = this.getItemTypeNodeForClient(typeID, "id"); this.MetadataCache.SetItem(key, this.IomFactory.CreateCacheableContainer(xsl, itemTypeNd)); } var res = inDom.transformNode(xsl); //replaces VaultURL by FullFileURL var self = this; var FixVaultUrl = function (str, srcTag, vaultPrefix, fileId, fullStr) { var fileUrl = self.IomInnovator.getFileUrl(fileId, self.Enums.UrlType.SecurityToken); fileUrl = self.browserHelper.escapeUrl(fileUrl); return srcTag + fileUrl + '"'; }; //replaces all "src" attributes starting with "vault:///" var FixImageCellSrc = function (str, offsetPos, fullStr) { return str.replace(/(src=")(vault:\/\/\/\?fileid\=)([^"]*)"/i, FixVaultUrl); }; //search all elements with attribute fdt="image" var resultXML = res.replace(/]*?>.*?<\/td>/gi, FixImageCellSrc); //if font-size property exist we should limit cell height by line-height property resultXML = resultXML.replace(/(]*? css=.*?)(font-size)/g, "$1line-height:15px; $2"); return resultXML; }; Aras.prototype.uiPrepareTableWithColumns = function Aras_uiPrepareTableWithColumns(inDom, columnObjects) { //columnObjects: {name, order, width} this.uiPrepareDOM4GridXSLT(inDom); var tableNd = inDom.selectSingleNode(this.XPathResult("/table")); tableNd.setAttribute("editable", "false"); var columns = tableNd.selectSingleNode("columns"); var inputrow = tableNd.selectSingleNode("inputrow"); // make inputrow invisible by default. inputrow.setAttribute("visible", "false"); for (var col in columnObjects) { var columnObject = columnObjects[col]; var column = inDom.createElement("column"); column.setAttribute("name", columnObject.name); column.setAttribute("order", columnObject.order); column.setAttribute("width", columnObject.width); columns.appendChild(column); var td = inDom.createElement("td"); inputrow.appendChild(td); } }; Aras.prototype.uiPrepareDOM4XSLT = function Aras_uiPrepareDOM4XSLT(inDom, itemTypeID, RTorITPrefix, colWidths, colOrder) { var prefTp = GetPrefixItemTypeName(RTorITPrefix); var colWidthsArr = colWidths ? colWidths.split(";") : this.getPreferenceItemProperty(prefTp, itemTypeID, "col_widths").split(";"); var colOrderArr = colOrder ? colOrder.split(";") : this.getPreferenceItemProperty(prefTp, itemTypeID, "col_order").split(";"); var columnObjects = {}; for (var i = 0; i < colOrderArr.length; i++) { columnObjects[i] = { name: colOrderArr[i], order: i, width: colWidthsArr[i] }; } this.uiPrepareTableWithColumns(inDom, columnObjects); function GetPrefixItemTypeName(prefix) { if (!prefix) prefix = 'IT_'; var result; if (prefix === 'IT_') { result = 'Core_ItemGridLayout'; } else { result = 'Core_RelGridLayout'; } return result; } }; Aras.prototype.uiGenerateItemsGridXML = function Aras_uiGenerateItemsGridXML(inDom, props, itemtypeID, params) { return this.uiGenerateGridXML(inDom, props, undefined, itemtypeID, params); }; //uiGenerateItemsGridXML Aras.prototype.uiGenerateRelationshipsGridXML = function Aras_uiGenerateRelationshipsGridXML(inDom, Dprops, Rprops, itemTypeId, params, getCached) { //itemTypeId is id of "is relationship" ItemType return this.uiGenerateGridXML(inDom, Dprops, Rprops, itemTypeId, params, getCached); }; //uiGenerateRelationshipsGridXML Aras.prototype.uiGenerateMainTreeXML = function Aras_uiGenerateMainTreeXML(inDom) { return this.applyXsltFile(inDom, this.getScriptsURL() + '../styles/mainTree.xsl'); }; Aras.prototype.uiGenerateParametersGrid = function Aras_uiGenerateParametersGrid(itemTypeName, classification) { /*---------------------------------------- * uiGenerateParametersGrid * * Purpose: * sends request to Innovator Server to generate xml for parameters grid for * specified ItemType and classification. Returns xml string. * * Arguments: * itemTypeName - name of ItemType * classification - classification of an Item */ var res = null; if (itemTypeName && classification) { var classificationDom = this.createXMLDocument(); classificationDom.loadXML(""); classificationDom.documentElement.setAttribute("type", itemTypeName); classificationDom.selectSingleNode("Item/classification").text = classification; res = this.soapSend("GenerateParametersGrid", classificationDom.xml); res = res.getResult().selectSingleNode("table"); } if (res) { var tmp = res.selectSingleNode("thead"); var pNd = tmp.selectSingleNode("th[.='Property']"); if (pNd) pNd.text = this.getResource("", "advanced_search.property"); var vNd = tmp.selectSingleNode("th[.='Value']"); if (vNd) vNd.text = this.getResource("", "ui_methods.value"); res = res.xml; } else { var emptyTableXML = "" + "" + " " + " " + " " + "" + "" + " " + " " + " " + "" + "
" + this.getResource("", "advanced_search.property") + "" + this.getResource("", "ui_methods.value") + "" + this.getResource("", "parametersgrid.sort_order") + "
"; res = emptyTableXML; } var resDom = this.createXMLDocument(); resDom.loadXML(res); return resDom; }; Aras.prototype.uiIsParamTabVisible = function Aras_uiIsParamTabVisible(itemNd, itemTypeName) { var paramTabProperties = this.uiIsParamTabVisibleEx(itemNd, itemTypeName); return paramTabProperties.show; }; Aras.prototype.uiGenerateRelationshipsTabbar = function Aras_uiGenerateRelationshipsTabbar(itemTypeName, itemID) { var res = null; var itemType; if (itemTypeName) itemType = this.getItemTypeNodeForClient(itemTypeName); if (itemType && itemTypeName && itemID) { var cachedTabbar = this.getItemProperty(itemType, "relationships_tabbar_xml"); if (cachedTabbar && cachedTabbar.indexOf(""); res = res.getResult().selectSingleNode("tabbar"); } } if (res) { res = res.xml; } else { var emptyTableXML = ""; res = emptyTableXML; } var resDom = this.createXMLDocument(); resDom.loadXML(res); return resDom; }; Aras.prototype.uiGenerateRelationshipsTable = function Aras_uiGenerateRelationshipsTable(itemTypeName, itemID, relationshiptypeID) { var res = null; if (itemTypeName && itemID) { res = this.soapSend("GenerateRelationshipsTable", ""); res = res.getResult().xml; } else { res = ""; } var resDom = this.createXMLDocument(); resDom.loadXML(res); return resDom; }; Aras.prototype.uiPrepareDOM4GridXSLT = function Aras_uiPrepareDOM4GridXSLT(dom) { /* adds
to Envelope Body Result. removes previous entry entry */ var res = dom.selectSingleNode(this.XPathResult()); var tableNd = res.selectSingleNode("table"); if (tableNd) res.removeChild(tableNd); tableNd = res.appendChild(dom.createElement("table")); tableNd.appendChild(dom.createElement("columns")); tableNd.appendChild(dom.createElement("inputrow")); }; Aras.prototype.uiGenerateGridXSLT = function Aras_uiGenerateGridXSLT(DescByProps_Arr, RelatedProps_Arr, params, typeID) { var self = this; if (params === undefined) { params = {}; } var itemTypeName = this.getItemTypeName(typeID); var showLockColumn = Boolean((RelatedProps_Arr === undefined) || RelatedProps_Arr); var table_xpath = self.XPathResult("/table"); var enable_links = (params.enable_links === undefined || params.enable_links === true); var enableFileLinks = Boolean(params.enableFileLinks); var generateOnlyRows = (true === params.only_rows); var params_bgInvert = (params.bgInvert === undefined || params.bgInvert === false) ? "false" : "true"; var columnsXSLT = []; var theadXSLT = []; var listsXSLT = []; // +++ create header row function AddHeaderColumn(name, header) { theadXSLT.push(""); theadXSLT.push(" "); theadXSLT.push(""); } function AddHeaderColumns(propsArr, suffix) { var f2Header = ' [...]'; if (!propsArr) return; for (var i = 0; i < propsArr.length; i++) { var prop = propsArr[i]; var propName = self.getItemProperty(prop, "name"); var header = self.getItemProperty(prop, "label"); if (header === "") header = propName; var dataType = self.getItemProperty(prop, "data_type"); if (dataType === 'item') { var propDS = self.getItemProperty(prop, 'data_source'); if (propDS) { var it = self.getItemTypeName(propDS); if (it) header += f2Header; } } else if (dataType === 'date' || dataType === 'text' || dataType === 'image' || dataType === 'formatted text' || dataType === 'color') { header += f2Header; } AddHeaderColumn(propName + suffix, header); } } if (!generateOnlyRows) { theadXSLT.push(""); if (showLockColumn) AddHeaderColumn("L", ""); AddHeaderColumns(DescByProps_Arr, "_D"); AddHeaderColumns(RelatedProps_Arr, "_R"); theadXSLT.push(""); // --- create header row } var lists = this.newObject(); var reservedListsNum = 2; //because we reserve 2 lists for special needs (e.g. build properties list for filter list pattern in relationships grid) var listNum = reservedListsNum - 1; var i; // +++ create columns function AddColumn(name, d_width, edit, align, sortStr, bgInvert, password, textColorInvert, flyWeightType) { columnsXSLT.push(""); columnsXSLT.push(""); columnsXSLT.push(""); columnsXSLT.push(""); columnsXSLT.push(""); columnsXSLT.push(""); columnsXSLT.push(""); columnsXSLT.push(""); columnsXSLT.push(""); columnsXSLT.push(""); columnsXSLT.push(""); columnsXSLT.push(""); } function AddColumns(propsArr, suffix) { if (!propsArr) return; for (var i = 0; i < propsArr.length; i++) { var prop = propsArr[i], propName = self.getItemProperty(prop, "name"), header = self.getItemProperty(prop, "label") || propName, data_type = self.getItemProperty(prop, "data_type"), isForeign = (data_type === "foreign"), isInBasketTask = (typeID === self.getItemTypeId("InBasket Task")), column_width = self.getItemProperty(prop, "column_width") || "100", locale = ' locale="' + self.getSessionContextLocale() + '"', bgInvert, textColorInvert, password, flyWeightType, format = "", sortStr = "", editStr = ""; var column_alignment = self.getItemProperty(prop, "column_alignment"); column_alignment = column_alignment ? column_alignment.charAt(0) : "1"; if (isForeign) { var sourceProperty = self.uiMergeForeignPropertyWithSource(prop, true); if (sourceProperty) { prop = sourceProperty; data_type = self.getItemProperty(prop, "data_type"); } } if (data_type.search(/list$/) != -1) { var listInfo = self.newObject(); listInfo.listID = self.getItemProperty(prop, "data_source"); listInfo.listType = data_type; listNum++; lists[listNum] = listInfo; editStr = ((data_type == "mv_list") ? "MV_LIST:" : "COMBO:") + listNum; } else { editStr = "FIELD"; } switch (data_type) { case "date": format = self.getItemProperty(prop, "pattern"); format = self.getDotNetDatePattern(format) || "MM/dd/yyyy"; editStr = "dateTime"; sortStr = 'sort="DATE" inputformat="' + format + '"' + locale; break; case "decimal": format = self.getDecimalPattern(self.getItemProperty(prop, "prec"), self.getItemProperty(prop, "scale")); sortStr = 'sort="NUMERIC"' + ((format) ? ' inputformat="' + format + '"' : "") + locale; break; case "integer": case "float": sortStr = 'sort="NUMERIC"' + ((format) ? ' inputformat="' + format + '"' : "") + locale; break; case "color list": case "color": bgInvert = "false"; textColorInvert = "true"; break; case "md5": password = "true"; break; case "image": flyWeightType = "IMAGE"; break; case "qrcode": flyWeightType = "QRCODE"; break; case "item": var dataSource = self.getItemProperty(prop, "data_source"), dataSourceName = dataSource ? self.getItemTypeName(dataSource) : ""; if (dataSourceName == "File") { editStr = "File"; } else if (!isForeign) { editStr = "InputHelper"; } break; default: break; } if (isInBasketTask && ("start_date" === propName || "due_date" === propName)) { bgInvert = "false"; textColorInvert = "true"; } AddColumn(propName + suffix, column_width, editStr, column_alignment, sortStr, bgInvert, password, textColorInvert, flyWeightType); } } if (!generateOnlyRows) { var lockColumnListIndex; columnsXSLT.push(""); if (showLockColumn) { lockColumnListIndex = ++listNum; AddColumn("L", "24", "COMBO:" + lockColumnListIndex, "c", ""); } AddColumns(DescByProps_Arr, "_D"); AddColumns(RelatedProps_Arr, "_R"); columnsXSLT.push(""); // --- create columns // +++ create lists //reserve reservedListsNum lists for special needs for (var idx = 0; idx < reservedListsNum; idx++) { listsXSLT.push(""); } if (showLockColumn) { var imageStyle = "margin-right: 4px; height: auto; width: auto; max-width: 20px; max-height: 20px;", iconPrefix = itemTypeName === "InBasket Task" ? "Claimed" : "Locked", resoucePrefix = itemTypeName === "InBasket Task" ? "claimed" : "locked", valuesList = ["", "", "", ""], optionsList = ["" + this.getResource("","itemsgrid.locked_criteria_ppm.clear_criteria") + "", "" + this.getResource("", "itemsgrid.locked_criteria_ppm." + resoucePrefix + "_by_me"), "" + this.getResource("", "itemsgrid.locked_criteria_ppm." + resoucePrefix + "_by_others"), "" + this.getResource("", "itemsgrid.locked_criteria_ppm." + resoucePrefix + "_by_anyone")]; listsXSLT.push(""); for (i = 0; i < optionsList.length; i++) { listsXSLT.push(""); } listsXSLT.push(""); } } //prepare to request all lists values var reqListsArr = this.newArray(); for (var listIdx in lists) { var listInfo = lists[listIdx]; var relType; if (listInfo.listType == "filter list") { relType = "Filter Value"; } else { relType = "Value"; } var listDescr = this.newObject(); listDescr.id = listInfo.listID; listDescr.relType = relType; reqListsArr.push(listDescr); } if (reqListsArr.length > 0) { var resLists = this.getSeveralListsValues(reqListsArr); for (var listNum2 in lists) { var listInfo2 = lists[listNum2]; listsXSLT.push(""); if (listInfo2.listType != "mv_list") { listsXSLT.push(""); } var listVals = resLists[listInfo2.listID]; if (listVals) { for (i = 0; i < listVals.length; i++) { var valNd = listVals[i]; var val = this.getItemProperty(valNd, "value"); var lab = this.getItemProperty(valNd, "label"); if (lab === "") lab = val; val = this.escapeXMLAttribute(val); lab = this.escapeXMLAttribute(lab); listsXSLT.push(""); } } listsXSLT.push(""); } } // --- create lists var resXSLTArr = []; resXSLTArr.push( "\n"); this.browserHelper.addXSLTCssFunctions(resXSLTArr); resXSLTArr.push( "" + "\n" + " \n" + "\n" + "\n" + "
" + self.escapeXMLAttribute(header) + "
" + "\n" + "
\n" + "\n" + "\n" + theadXSLT.join("") + columnsXSLT.join("") + "\n"); if (!generateOnlyRows) { resXSLTArr.push( "\n" + " \n" + " \n" + " \n" + " \n" + " \n" + "\n"); } resXSLTArr.push( "\n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + "\n" + listsXSLT.join("") + "\n" + "\n" + " \n" + "\n" + "\n" + "\n" + " \n" + " \n" + " \n" + " \n"); this.browserHelper.addXSLTInitItemCSSCall(resXSLTArr, "string(css)", "string(fed_css)"); resXSLTArr.push( " \n" + " \n" + " \n" + " \n" + " \n" + " \n"); if (RelatedProps_Arr) { resXSLTArr.push( " \n" + " \n" + " \n"); this.browserHelper.addXSLTInitItemCSSCall(resXSLTArr, "string(related_id/Item/css)", "string(related_id/Item/fed_css)"); resXSLTArr.push( " \n" + " \n" + " \n" + " \n" + " \n" + " \n"); } resXSLTArr.push( "\n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n"); // +++ lock icon if (showLockColumn) { resXSLTArr.push("\n"); resXSLTArr.push(""); if (RelatedProps_Arr) { resXSLTArr.push("<img src='../images/NullRelated.svg'/>"); resXSLTArr.push(""); } var currentUserID = this.getCurrentUserID(); resXSLTArr.push( "\n" + "\n" + "\n" + "\n" + " " + " " + " <img src='../images/Blocked.svg'/>\n" + " \n" + " <img src='../images/New.svg'/>\n" + " " + " <img src='" + (itemTypeName !== "InBasket Task" ? "../images/LockedByMe.svg" : "../images/ClaimedByMe.svg") + "'/>" + " <img src='../images/LockedAndModified.svg'/>" + " " + " <img src='" + (itemTypeName !== "InBasket Task" ? "../images/LockedByOthers.svg" : "../images/ClaimedByOthers.svg") + "'/>" + " " + " " + " " + " <img src=''/>" + ""); if (RelatedProps_Arr) resXSLTArr.push(""); resXSLTArr.push("\n"); resXSLTArr.push(""); } // --- lock icon // ==== grid rows === function GenerateRows(propsArr, xpath_prefix, special_td_attributes, cellCSSVariableName1) { if (!propsArr) return; var propItem, name, xpath, dataType, dataSource, dataSourceName, restrictedMsgCondition, i; for (i = 0; i < propsArr.length; ++i) { propItem = propsArr[i]; name = self.getItemProperty(propItem, "name"); xpath = xpath_prefix + name; dataType = self.getItemProperty(propItem, "data_type"); restrictedMsgCondition = xpath + "[@is_null='0' and string(.)='']" + (xpath_prefix ? " or related_id[@is_null='0' and string(.)='']" : ""); if ("foreign" == dataType) { var sourceProperty = self.uiMergeForeignPropertyWithSource(propItem); if (sourceProperty) { propItem = sourceProperty; dataType = self.getItemProperty(propItem, "data_type"); } } resXSLTArr.push(""); resXSLTArr.push(""); if ("item" == dataType || "color" == dataType || "color list" == dataType) { resXSLTArr.push(""); if ("item" == dataType) { dataSource = propItem.selectSingleNode("data_source"); dataSourceName = dataSource ? dataSource.getAttribute("name") : ""; if (enable_links || (enableFileLinks && dataSourceName == "File")) { var linkItemType = dataSourceName ? "'" + dataSourceName + "'" : "string(" + xpath + "/@type)"; resXSLTArr.push( "\n" + " \n" + " " + " \n" + " '\n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " ','\n" + " \n" + " '\n" + " \n" + " \n" + " '\n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " ','\n" + " \n" + " '\n" + " \n" + " " + " \n" + ""); if (dataSourceName === "File") { resXSLTArr.push( "\n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + ""); } } } else if ("color" == dataType || "color list" == dataType) { resXSLTArr.push( "" + "" + " " + " " + " " + ""); } resXSLTArr.push(""); } var nameCSS = name + "--CSS"; resXSLTArr.push(""); self.browserHelper.addXSLTGetPropertyStyleExCall(resXSLTArr, nameCSS, cellCSSVariableName1, name); resXSLTArr.push( "" + " " + //remove first and last characters "" + " " + " " + " " + " " + " " + " " + "" + "" + " " + " " + " " + " " + " " + " " + " "); switch (dataType) { case "item": var itemNameProperty = (dataSourceName == "File") ? "filename" : "id/@keyed_name"; resXSLTArr.push( "" + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + ""); break; case "image": case "qrcode": resXSLTArr.push(""); break; case "boolean": resXSLTArr.push( "<checkbox state=\"" + "" + " " + " " + " " + " " + " " + " " + "" + "\"/>"); break; case "md5": resXSLTArr.push("***"); break; default: if ("color" != dataType) { resXSLTArr.push(""); } break; } resXSLTArr.push( "" + "" + "\n"); } } var special_td_attributes = RelatedProps_Arr ? " bgColor='#f3f3f3'" : ""; GenerateRows(DescByProps_Arr, "", special_td_attributes, "item-CSS"); GenerateRows(RelatedProps_Arr, "related_id/Item/", "", "rItem-CSS"); // ==== end of grid rows === resXSLTArr.push("\n"); resXSLTArr.push("\n"); resXSLTArr.push(""); return resXSLTArr.join(""); }; /* * uiItemTypeSelectionDialog * * parameters: * 1) itemTypesList - an array of objects like [{id:5, name:'Type5'}] */ Aras.prototype.uiItemTypeSelectionDialog = function Aras_uiItemTypeSelectionDialog(itemTypesList, wnd, callback) { if (!itemTypesList) return; wnd = wnd || window; var args = { title: this.getResource("", "itemtypeselectiondialog.select_item_type"), itemTypesList: itemTypesList, aras: this }; var options = { dialogWidth: 400, dialogHeight: 280 }; var win = this.getMostTopWindowWithAras(wnd); if (window.showModalDialog && !callback) { return this.modalDialogHelper.show("DefaultModal", win.main || win, args, options, "ItemTypeSelectionDialog.html"); } else { args.dialogWidth = 400; args.dialogHeight = 280; args.content = "ItemTypeSelectionDialog.html"; if (callback) { (win.main || win).ArasModules.Dialog.show("iframe", args).promise.then(callback); } else { return (win.main || win).ArasModules.Dialog.show("iframe", args).promise; } } }; Aras.prototype.uiItemCanBeLockedByUser = function Aras_uiItemCanBeLockedByUser(itemNd, isRelationship, useSrcAccess) { /* this function is for internal use *** only ***. ---------------------------------------------- isRelationship - perhaps, this parameter will be removed in future ------------------------------------------ full list of places where function is used: item_window.js: updateMenuState itemsGrid.html: setMenuState relationshipsGrid.html: updateControls, onMenuCreate */ if (itemNd) { if (this.getItemProperty(itemNd, "is_current") == "0") { return false; } var itemTypeName = itemNd.getAttribute("type"); if (itemTypeName != "File" && !this.isTempEx(itemNd)) { var lockedByValue = this.getItemProperty(itemNd, "locked_by_id"), IsMainItemLocked = true; if (isRelationship && useSrcAccess) { var sourceId = this.getItemProperty(itemNd, "source_id"), sourceItem, sourceItemTypeName; if (sourceId) { sourceItem = itemNd.selectSingleNode("parent::Relationships/parent::Item[@id='" + sourceId + "']"); if (!sourceItem) { sourceItemTypeName = this.getItemPropertyAttribute(itemNd, "source_id", "type"); sourceItem = this.getItemById(sourceItemTypeName, sourceId, 0); } } else { sourceItem = itemNd.selectSingleNode("parent::Relationships/parent::Item"); } IsMainItemLocked = sourceItem ? this.isLockedByUser(sourceItem) : false; } return (IsMainItemLocked && lockedByValue === ""); } } return false; }; Aras.prototype.getItemsOfFileProperties = function Aras_getItemsOfFileProperties(itemNode, ItemTypeNode, eachFileCallback) { var filePropNodes = this.getPropertiesOfTypeFile(ItemTypeNode), filePropNodesCount = filePropNodes.length, files = [], propName, prop, file, i; for (i = 0; i < filePropNodesCount; i++) { propName = this.getItemProperty(filePropNodes[i], "name"); prop = null; file = null; if ("id" === propName) { file = itemNode; } if (!file) { file = itemNode.selectSingleNode(propName + "/Item"); } if (!file) { prop = this.getItemProperty(itemNode, propName); if (prop) { if (eachFileCallback) { eachFileCallback(prop); continue; } file = this.getItemById('File', prop, 0); } } if (file) { files.push(file); } } return files; }; Aras.prototype.uiIsCheckOutPossible = function Aras_uiIsCheckOutPossible(fileItems, ItemCanBeLockedByUser, ItemIsLockedByUser) { /* this function is for internal use *** only ***. ---------------------------------------------- ------------------------------------------ full list of places where function is used: item_window.js: updateMenuState itemsGrid.html: setMenuState relationshipsGrid.html: updateControls, onMenuCreate */ if (!(ItemCanBeLockedByUser || ItemIsLockedByUser) || !fileItems) return false; var ThereAreFiles = false; for (var i = 0; i < fileItems.length; i++) { var file = fileItems[i]; if (file) { ThereAreFiles = true; var FileIsLocked = this.isLocked(file); var FileIsTemp = this.isTempEx(file); if (FileIsLocked || FileIsTemp) return false; } } return ThereAreFiles; //because all rules are checked inside loop above }; Aras.prototype.uiIsCopyFilePossible = function Aras_uiIsCopyFilePossible(fileItems) { /* this function is for internal use *** only ***. ---------------------------------------------- */ var ThereAreFiles = false; for (var i = 0; i < fileItems.length; i++) { var file = fileItems[i]; if (file && !this.isTempEx(file)) { ThereAreFiles = true; } } return ThereAreFiles; //because all rules are checked inside loop above }; Aras.prototype.uiWriteObject = function Aras_uiWriteObject(doc, objectHTML) { doc.write(objectHTML); }; // method is obsolete, it should be deleted in the major version Aras.prototype.uiAddConfigLink2Doc4Assembly = function Aras_uiAddConfigLink2Doc4Assembly() { return true; }; Aras.prototype.uiGetFilteredObject4Grid = function Aras_uiGetFilteredObject4Grid(itemTypeID, filteredPropName, filterValue) { var resObj = this.newObject(); resObj.hasError = false; var itemTypeNd; try { itemTypeNd = this.getItemTypeDictionary(this.getItemTypeName(itemTypeID)).node; } catch (ex) { } if (!itemTypeNd) { resObj.hasError = true; return resObj; } var fListNd = itemTypeNd.selectSingleNode("Relationships/Item[@type='Property' and name='" + filteredPropName + "']/data_source"); var fListId = (fListNd) ? fListNd.text : null; if (!fListId) { resObj.hasError = true; return resObj; } var _listVals = [""]; var _listLabels = [""]; var optionNds = this.getListFilterValues(fListId); if (filterValue !== "") optionNds = this.uiGetFilteredListEx(optionNds, "^" + filterValue + "$"); for (var i = 0, L = optionNds.length; i < L; i++) { var optionNd = optionNds[i]; var label = this.getItemProperty(optionNd, "label"); var value = this.getItemProperty(optionNd, "value"); _listVals.push(value); if (label === "") _listLabels.push(value); else _listLabels.push(label); } resObj.values = _listVals; resObj.labels = _listLabels; return resObj; }; /** * Case insensitive check whether exists such keyed_name in the ItemType. * Checks if there is an instance of the specified type with a specified keyed name in the DB. * The check is case insensitive if the DB was setup properly. * If instance cannot be defined uniquely - the first matched is used. * If instance doesn't exists in DB then boolean false is returned. * @param {string} itemTypeName - the ItemType name * @param {string} keyed_name - the keyed name * @param {boolean} skipDialog - skip showing the dialog (default value undefined (false)) * @returns {boolean|Object} */ Aras.prototype.uiGetItemByKeyedName = function Aras_uiGetItemByKeyedName(itemTypeName, keyed_name, skipDialog) { function createCacheKey(arasObj, keyed_name) { return arasObj.CreateCacheKey("uiGetItemByKeyedName", itemTypeName, keyed_name); } var key = createCacheKey(this, keyed_name); var res = this.MetadataCache.GetItem(key); if (!res) { var q = this.newIOMItem(itemTypeName, "get"); q.setAttribute("select", "keyed_name"); q.setProperty("keyed_name", keyed_name); var r = q.apply(); if (r.isError()) { return false; } var putInCache = false; if (r.isCollection()) { var candidates = []; for (var i = 0, L = r.getItemCount(); i < L; i++) { var candidate = r.getItemByIndex(i); if (candidate.getProperty("keyed_name") === keyed_name) //do case sensitive check { candidates.push(candidate); } } if (1 === candidates.length) { r = candidates[0]; putInCache = true; } else { if (candidates.length > 1) { r = candidates[0]; } else { r = r.getItemByIndex(0); } if (!skipDialog) { var param = { buttons: {btnOK: "OK"}, defaultButton: "btnOK", message: this.getResource("", "ui_methods.item_cannot_defined_uniquely"), aras: this, dialogWidth: 300, dialogHeight: 150, center: true, content: "groupChgsDialog.html" }; var win = this.getMostTopWindowWithAras(window); (win.main || win).ArasModules.Dialog.show("iframe", param); } } } else { putInCache = true; } res = r.node; if (putInCache) { this.MetadataCache.SetItem(key, res); var actual_keyed_name = r.getProperty("keyed_name"); if (actual_keyed_name !== keyed_name)//this is possible in a case when the DB is case-insensitive {//cache mapping to correct keyed name also. var newKey = createCacheKey(this, actual_keyed_name); if (!this.MetadataCache.GetItem(newKey)) { this.MetadataCache.SetItem(newKey, res.cloneNode(true)); } } } } res = res.cloneNode(true); return res; }; // Retrieves window body size, the width and the height of the object including padding, // but not including margin, border, or scroll bar. Aras.prototype.getDocumentBodySize = function Aras_GetDocumentBodySize(document) { var res = this.newObject(); res.width = 0; res.height = 0; if (document) { res.width = document.body.clientWidth; res.height = document.body.clientHeight; } return res; }; // Retrieves the width of the rectangle that bounds the text in the text field. Aras.prototype.getFieldTextWidth = function Aras_getFieldTextWidth(field) { if (field) { var r = field.createTextRange(); if (r !== null) return r.boundingWidth; } else return 0; }; // Calculate html element coordinates on a parent window. Aras.prototype.uiGetElementCoordinates = function Aras_uiGetElementCoordinates(oNode) { var oCurrentNode = oNode; var iLeft = 0; var iTop = 0; var iScrollLeft = 0; var iScrollTop = 0; var topWindow = this.getMostTopWindowWithAras(window); var topOfWindow = topWindow.screenY || topWindow.screenTop || 0; var leftOfWindow = topWindow.screenX || topWindow.screenLeft || 0; var titleHeight = window.outerHeight - window.innerHeight; // calculate height of titlebar + menubar + navigation toolbar + bookmarks toolbar + tab bar; http://www.gtalbot.org/BugzillaSection/Bug195867GDR_WindowOpen.html#OuterHeightVersusHeightOrInnerHeight while (oCurrentNode) { iLeft += oCurrentNode.offsetLeft; iTop += oCurrentNode.offsetTop; iScrollLeft += oCurrentNode.scrollLeft; iScrollTop += oCurrentNode.scrollTop; if (!oCurrentNode.offsetParent) { var tmpFrame = null; try { oCurrentNode = oCurrentNode.ownerDocument.defaultView ? oCurrentNode.ownerDocument.defaultView.frameElement : null; } catch (ex) { //access denied case oCurrentNode = null; } } else { oCurrentNode = oCurrentNode.offsetParent; } } //+++ IR-008672 (Date dialog is shown not near date field after scrolling) var readScroll; if (oNode.ownerDocument.compatMode && oNode.ownerDocument.compatMode === 'CSS1Compat') readScroll = oNode.ownerDocument.documentElement; else readScroll = oNode.ownerDocument.body; iScrollLeft += readScroll.scrollLeft; iScrollTop += readScroll.scrollTop; res = {}; res.left = iLeft - (iScrollLeft - leftOfWindow); res.top = iTop - (iScrollTop - topOfWindow) + titleHeight; // add height of browser bars. res.scrollLeft = iScrollLeft; res.scrollTop = iScrollTop; res.screenLeft = leftOfWindow; res.screenTop = topOfWindow; res.barsHeight = titleHeight; //--- IR-008672 (Date dialog is shown not near date field after scrolling) return res; }; // Calculate coordinates of window, that would be shown near element Aras.prototype.uiGetRectangleToShowWindowNearElement = function Aras_uiGetRectangleToShowWindowNearElement(element, windowSize, rectangleInsideElement, eventObject, isGrid) { if (!element) { throw new Error(1, this.getResource("", "ui_methods.parameter_element_not_specified")); } var parentCoords = this.uiGetElementCoordinates(element); var dTop, dLeft, dHeight, dWidth; var boundHeight; var hackForAddProjectDialog = false; if (element.name === "date_start_target" || element.name === "date_due_target") { var isAddProjectForm = element.ownerDocument && element.ownerDocument.formID === "1CF50C86BD1141A9863451B7634B2F04"; if (isAddProjectForm && element.ownerDocument.defaultView) { hackForAddProjectDialog = true; } } if (eventObject && !window.viewMode && !hackForAddProjectDialog) // for dialog windows { var topY = (eventObject.screenY - eventObject.clientY) || 0; var leftX = (eventObject.screenX - eventObject.clientX) || 0; dTop = topY + parentCoords.top - parentCoords.screenTop - parentCoords.barsHeight; dLeft = leftX + parentCoords.left - parentCoords.screenLeft; } else { var keyToAvoidExplicitTopUsage = "top"; dTop = parentCoords[keyToAvoidExplicitTopUsage]; dLeft = parentCoords.left; } if (rectangleInsideElement) { dTop += rectangleInsideElement.y; if (!isGrid) { dTop += rectangleInsideElement.height; dLeft += rectangleInsideElement.x; } boundHeight = rectangleInsideElement.height; } else if (element.offsetHeight !== undefined) { if (!hackForAddProjectDialog) { dTop += element.offsetHeight; } boundHeight = element.offsetHeight; } if (windowSize) { dHeight = windowSize.height !== undefined ? windowSize.height : 200; dWidth = windowSize.width !== undefined ? windowSize.width : 250; var dx = screen.availWidth - (dLeft + dWidth); var dy = screen.availHeight - (dTop + dHeight); if (dx < 0) dLeft += dx; if (dy < 0) dTop -= (dHeight + boundHeight + parentCoords.barsHeight); } return { top: dTop, left: dLeft, width: dWidth, height: dHeight }; }; /// /// Show modal dialog from the specified URL using the specified dialog parameters, options /// from "param" near element "child" of "parent" element /// Aras.prototype.uiShowDialogNearElement = function Aras_uiShowDialogNearElement(element, dialogUrl, dialogParameters, dialogOptions, dialogSize, rectangleInsideElement, eventObject, isGrid) { if (!element) throw new Error(1, this.getResource("", "ui_methods.parameter_element_not_specified")); if (dialogOptions === undefined) dialogOptions = "status:0; help:0; center:no;"; if (dialogSize === undefined) { dialogSize = { width: 250, height: 200 }; if (dialogUrl && dialogUrl.toLowerCase().indexOf("datedialog.html") > -1) dialogSize = { width: 257, height: 270 }; } var wndRect = this.uiGetRectangleToShowWindowNearElement(element, dialogSize, rectangleInsideElement, eventObject, isGrid); var dialogPositionOptions = "dialogHeight:" + wndRect.height + "px; dialogWidth:" + wndRect.width + "px; dialogTop:" + wndRect.top + "px; dialogLeft:" + wndRect.left + "px; "; dialogOptions = dialogPositionOptions + dialogOptions; var wnd = window; if (element.ownerDocument && element.ownerDocument.defaultView) { wnd = element.ownerDocument.defaultView; } var res = wnd.showModalDialog(dialogUrl, dialogParameters, dialogOptions); return res; }; Aras.prototype.uiShowControlsApiReferenceCommand = function Aras_uiShowControlsApiReferenceCommand(isJavaScript) { var topHelpUrl = this.getTopHelpUrl(); var re = /^(.*)[\\\/]([^\\\/]*)$/; //finds the last '\' or '/' if (!topHelpUrl || !re.test(topHelpUrl)) { this.AlertError(this.getResource("", "ui_methods.cannot_determine_tophelpurl")); return; } topHelpUrl = RegExp.$1; var apiReferenceFolder = isJavaScript ? "APIReferenceJavaScript" : "APIReferenceDotNet"; window.open(topHelpUrl + "/" + apiReferenceFolder + "/Html/Index.html"); }; /** ui_methodsEx.js **/ // (c) Copyright by Aras Corporation, 2004-2013. Aras.prototype.uiRegWindowEx = function ArasUiRegWindowEx(itemID, win) { /*-- uiRegWindowEx * * registers window as Innovator window. * All Innovator windows get events notifications. * All Innovator windows are closed when main window is closed. * */ if (!itemID || !win) { return false; } var winName = this.mainWindowName + "_" + itemID; this.windowsByName[winName] = win; return true; }; Aras.prototype.uiUnregWindowEx = function ArasUiUnregWindowEx(itemID) { /*-- uiUnregWindowEx * * unregisters window as Innovator window (should be called when item window is closed). * All Innovator windows get events notifications. * All Innovator windows are closed when main window is closed. * */ if (!itemID) { return false; } var winName = this.mainWindowName + "_" + itemID; this.deletePropertyFromObject(this.windowsByName, winName); return true; }; Aras.prototype.uiFindWindowEx = function ArasUiFindWindowEx(itemID) { /*-- uiUnregWindowEx * * finds registered Innovator window. * */ if (!itemID) { return null; } var winName = this.mainWindowName + "_" + itemID; var res = null; try { res = this.windowsByName[winName]; if (res === undefined) { res = null; } } catch (excep) { } if (res && this.isWindowClosed(res)) { this.uiUnregWindowEx(itemID); return null; } return res; }; Aras.prototype.uiFindWindowEx2 = function (itemNd) { var itemID = itemNd.getAttribute("id"); var win = this.uiFindWindowEx(itemID); if (!win) { try { var parentItemNd = itemNd.selectSingleNode("../../../.."); if (parentItemNd && parentItemNd.nodeType != 9) { var pid = parentItemNd.getAttribute("id"); win = this.uiFindWindowEx(pid); } } catch (exc1) { } } if (!win) { win = window; } return win; }; Aras.prototype.uiOpenWindowEx = function ArasUiOpenWindowEx(itemID, params, alertErrorWin) { if (!itemID) { return null; } if (params === undefined) { params = ""; } var topWindow = this.getMostTopWindowWithAras(window); var isMainWindow = (topWindow.name === this.mainWindowName); var mainArasObject = this.getMainArasObject(); var isMainArasObject = (this === mainArasObject); if (!topWindow.opener && !isMainArasObject) { return mainArasObject.uiOpenWindowEx(itemID, params); } if (!isMainWindow && topWindow.opener && !this.isWindowClosed(topWindow.opener)) { var wnd = topWindow.opener.aras.uiOpenWindowEx(itemID, params, this.getCurrentWindow()); if (!wnd.opener && topWindow.opener) { wnd.opener = topWindow.opener; } return wnd; } else { var winName = this.mainWindowName + "_" + itemID; var win = null; if (this.browserHelper.newWindowCanBeOpened(this)) { this.browserHelper.lockNewWindowOpen(this, true); try { if (!window.arasTabs || params.indexOf("isOpenInTearOff=true") > -1) { win = topWindow.open(this.getScriptsURL() + "../scripts/blank.html", winName, params); } else { win = arasTabs.open(this.getScriptsURL() + "../scripts/blank.html", winName); } } finally { this.browserHelper.lockNewWindowOpen(this, false); } if (!win) { this.AlertError(this.getResource("", "ui_methods_ex.innovator_failed_to_open_new_window"), alertErrorWin, ""); } } else { this.AlertSuccess(this.getResource("", "ui_methods_ex.another_window_opening_is_in_progress")); return false; } if (win) { try {//substitute opener for the new window if (topWindow.opener && !this.isWindowClosed(topWindow.opener) && topWindow.opener.name == this.mainWindowName) { //according to CVS commits this is fix for IR-001690 "Toolbar does not load" (read background). //Something to workaround google popup blocker. win.opener = topWindow.opener; } } catch (excep) { /* security exception may occur */ } } return win; } }; Aras.prototype.uiCloseWindowEx = function (itemID) { if (!itemID) { return false; } var win = this.uiFindWindowEx(itemID); if (win) { win.close(); } return true; }; /* * uiGetFormID4ItemEx - function to get id of form correspondent to the item (itemNd) and mode * (result depends on current user) * * parameters: * itemNd - xml node of item to find correspondent form * formType - string, representing mode: 'add', 'view', 'edit' or 'print' */ Aras.prototype.uiGetFormID4ItemEx = function ArasUiGetFormID4ItemEx(itemNd, formType) { function findMaxPriorityFormID(itemType, roles, formType) { var i; var arasObj = self; var returnNodes; var tryGetClassificationFormWithoutFormType = function () { xp = "Relationships/Item[@type='View' and not(type='complete') and not(type='preview') and " + strRoles + "][not(form_classification[@is_null='1'])]/related_id/Item[@type='Form']"; return itemType.selectNodes(xp); }; if (typeof (roles) == "string") { var tmpRoles = roles; roles = []; roles.push(tmpRoles); } var strRoles = "(role='" + roles.join("' or role='") + "')"; if (classification) { var xp = "Relationships/Item[@type='View' and " + strRoles + " and type='" + formType + "'][not(form_classification[@is_null='1'])]/related_id/Item[@type='Form']"; var formIds = []; var nodes = itemType.selectNodes(xp); var tmpNds = nodes.length > 0 ? nodes : tryGetClassificationFormWithoutFormType(); if (tmpNds.length > 0) { for (i = 0; i < tmpNds.length; i++) { var formClassification = tmpNds[i].parentNode.parentNode.selectSingleNode("form_classification").text; if (arasObj.areClassPathsEqual(formClassification, classification)) { formIds.push(tmpNds[i].getAttribute("id")); } } } else { returnNodes = null; } if (formIds.length > 0) { var additionalXp = "[@id='" + formIds.join("' or @id='") + "']"; xp += additionalXp; returnNodes = itemType.selectNodes(xp); } } if (!(returnNodes && (returnNodes.length !== 0))) { returnNodes = itemType.selectNodes("Relationships/Item[@type='View' and string(form_classification)='' and " + strRoles + " and type='" + formType + "']/related_id/Item[@type='Form']"); } var formNds = returnNodes; if (formNds.length === 0) { return ""; } var currForm = formNds[0]; var currPriority = arasObj.getItemProperty(formNds[0].selectSingleNode("../.."), "display_priority"); if (currPriority === "") { currPriority = Number.POSITIVE_INFINITY; } for (i = 1; i < formNds.length; i++) { var priority = arasObj.getItemProperty(formNds[i].selectSingleNode("../.."), "display_priority"); if (priority === "") { priority = Number.POSITIVE_INFINITY; } if (currPriority > priority) { currPriority = priority; currForm = formNds[i]; } } return currForm.getAttribute("id"); } function findMaxPriorityFormIDForItemType(anItemType, formType) { var res = findMaxPriorityFormID(anItemType, identityId, formType); if (res) { return res; } if (formType != "default" && formType != "complete") { res = findMaxPriorityFormID(anItemType, identityId, "default"); if (res) { return res; } } res = findMaxPriorityFormID(anItemType, userIdentities, formType); if (res) { return res; } if (formType != "default" && formType != "complete") { res = findMaxPriorityFormID(anItemType, userIdentities, "default"); if (res) { return res; } } return undefined; } if (!itemNd) { return ""; } if (!formType || formType.search(/^default$|^add$|^view$|^edit$|^print|^preview$|^search|^complete$/) == -1) { return ""; } var userIdentities = this.getIdentityList().split(","); if (userIdentities.length === 0) { return ""; } var userNd = null; var tmpUserID = this.getCurrentUserID(); if (tmpUserID == this.getUserID()) { userNd = this.getLoggedUserItem(); } else { userNd = this.getItemFromServerWithRels("User", tmpUserID, "id", "Alias", "related_id(id)", true).node; } if (!userNd) { return ""; } var identityNd = userNd.selectSingleNode("Relationships/Item[@type='Alias']/related_id/Item[@type='Identity']"); if (!identityNd) { return ""; } var identityId = identityNd.getAttribute("id"); var itemTypeName = itemNd.getAttribute("type"); var itemTypeNd = this.getItemTypeNodeForClient(itemTypeName, "name"); var classification; var classificationNode = itemNd.selectSingleNode("classification"); if (classificationNode) { classification = classificationNode.text; } var self = this; var formID = findMaxPriorityFormIDForItemType(itemTypeNd, formType); if (!formID && this.getItemProperty(itemTypeNd, "implementation_type") == "polymorphic") { var itemtypeId = this.getItemProperty(itemNd, "itemtype"); if (itemtypeId) { itemTypeNd = this.getItemTypeNodeForClient(itemtypeId, "id"); if (itemTypeNd) { formID = findMaxPriorityFormIDForItemType(itemTypeNd, formType); } } } return formID; }; /* * uiGetRelationshipView4ItemTypeEx - function to get Relationship View of ItemType * (result depends on current user) * * parameters: * itemType - xml node of ItemType */ Aras.prototype.uiGetRelationshipView4ItemTypeEx = function ArasUiGetRelationshipView4ItemTypeEx(itemType) { if (!itemType) { return null; } var userIdentities = this.getIdentityList().split(","); if (userIdentities.length === 0) { return null; } var userNd = null; var tmpUserID = this.getCurrentUserID(); if (tmpUserID == this.getUserID()) { userNd = this.getLoggedUserItem(); } else { userNd = this.getItemFromServerWithRels("User", tmpUserID, "id", "Alias", "related_id(id)", true).node; } if (!userNd) { return null; } var identityNd = userNd.selectSingleNode("Relationships/Item[@type='Alias']/related_id/Item[@type='Identity']"); if (!identityNd) { return null; } var identityId = identityNd.getAttribute("id"); var res = itemType.selectSingleNode("Relationships/Item[@type='Relationship View' and (related_id/Item/@id='" + identityId + "' or related_id='" + identityId + "')]"); if (!res) { for (var i = 0; i < userIdentities.length; i++) { res = itemType.selectSingleNode("Relationships/Item[@type='Relationship View' and (related_id/Item/@id='" + userIdentities[i] + "' or related_id='" + userIdentities[i] + "')]"); if (res) { break; } } } return res; }; /* * uiGetTOCView4ItemTypeEx - function to get TOC View of ItemType * (result depends on current user) * * parameters: * itemType - xml node of ItemType */ Aras.prototype.uiGetTOCView4ItemTypeEx = function ArasUiGetTOCView4ItemTypeEx(itemType) { if (!itemType) { return null; } var userIdentities = this.getIdentityList().split(","); if (userIdentities.length === 0) { return null; } var userNd = null; var tmpUserID = this.getCurrentUserID(); if (tmpUserID == this.getUserID()) { userNd = this.getLoggedUserItem(); } else { userNd = this.getItemFromServerWithRels("User", tmpUserID, "id", "Alias", "related_id(id)", true).node; } if (!userNd) { return null; } var identityNd = userNd.selectSingleNode("Relationships/Item[@type='Alias']/related_id/Item[@type='Identity']"); if (!identityNd) { return null; } var identityId = identityNd.getAttribute("id"); var res = itemType.selectSingleNode("Relationships/Item[@type='TOC View' and (related_id/Item/@id='" + identityId + "' or related_id='" + identityId + "')]"); if (!res) { for (var i = 0; i < userIdentities.length; i++) { res = itemType.selectSingleNode("Relationships/Item[@type='TOC View' and (related_id/Item/@id='" + userIdentities[i] + "' or related_id='" + userIdentities[i] + "')]"); if (res) { break; } } } return res; }; /* * uiGetForm4ItemEx - function to get form xml node correspondent to the item (itemNd) and mode * (result depends on current user) * * parameters: * itemNd - xml node of item to find correspondent form * formType - string, representing mode: 'add', 'view', 'edit' or 'print' */ Aras.prototype.uiGetForm4ItemEx = function (itemNd, formType) { if (!itemNd) { return null; } if (!formType || formType.search(/^default$|^add$|^view$|^edit$|^preview$|^print$|^search|^complete$/) == -1) { return null; } var formID = this.uiGetFormID4ItemEx(itemNd, formType); var formNd = formID ? this.getFormForDisplay(formID).node : null; return formNd; }; /* * uiShowItemEx * * parameters: * 1) itemNd - item to be shown * 2) viewMode - 'tab view' or 'openFile' * 3) isOpenInTearOff - true or false */ Aras.prototype.uiShowItemEx = function ArasUiShowItemEx(itemNd, viewMode, isOpenInTearOff) { function onShowItem(inDom, inArgs) { var itemTypeName = inDom.getAttribute('type'); var itemType = this.getItemTypeNodeForClient(itemTypeName); var onShowItemEv = itemType.selectNodes("Relationships/Item[@type='Client Event' and client_event='OnShowItem']/related_id/Item"); try { if (onShowItemEv.length) { return this.evalMethod(this.getItemProperty(onShowItemEv[0], "name"), inDom, inArgs); } else { return this.evalMethod("OnShowItemDefault", inDom, inArgs); } } catch (exp) { this.AlertError(this.getResource("", "item_methods.event_handler_failed"), this.getResource("", "item_methods.event_handler_failed_with_message", exp.description), this.getResource("", "common.client_side_err")); return false; } } if (!itemNd) { return false; } if (itemNd.getAttribute("discover_only") === "1") { this.AlertError(this.getResource("", "ui_methods_ex.discover_only_item_cannot_be_opened"), "", ""); return false; } var itemTypeName = itemNd.getAttribute("type"); viewMode = viewMode || "tab view"; var asyncResult = onShowItem.call(this, itemNd, { viewMode: viewMode, isOpenInTearOff: isOpenInTearOff }); if (!asyncResult) { asyncResult = ModulesManager.createAsyncResult(); asyncResult.resolve(); } return asyncResult; }; Aras.prototype.uiOpenEmptyWindowEx = function ArasUiOpenEmptyWindowEx(itemNd) { var itemID = itemNd.getAttribute("id"); var win = this.uiFindAndSetFocusWindowEx(itemID); if (win !== null) { return true; } win = this.uiOpenWindowEx(itemID, "scrollbars=no,resizable=yes,status=yes"); if (!win) { return false; } this.uiRegWindowEx(itemID, win); return true; }; Aras.prototype.uiFindAndSetFocusWindowEx = function ArasUiFindAndSetFocusWindowEx(itemID) { var win = this.uiFindWindowEx(itemID); if (win) { if (win.opener === undefined) { this.uiUnregWindowEx(itemID); win = null; } else { this.browserHelper.setFocus(win); } } else { win = null; } return win; }; /* * uiReShowItemEx * * parameters: * 1) oldItemID- old id of item to be shown * 2) itemNd - item to be shown //usually itemId==oldItemId * 3) viewMode - "tab view" or "openFile" */ Aras.prototype.uiReShowItemEx = function ArasUiReShowItemEx(oldItemID, itemNd, viewMode) { if (!oldItemID) { return false; } if (!itemNd) { return false; } viewMode = viewMode || "tab view"; var win = this.uiFindWindowEx(oldItemID); if (!win || this.isWindowClosed(win)) { return this.uiShowItemEx(itemNd, viewMode); } var itemWin; if (win.getItem) { itemWin = win.getItem(); } else { itemWin = win.item; } var itemID = itemNd.getAttribute("id"); var itemTypeName = itemNd.getAttribute("type"); if (itemTypeName == "File" && viewMode == "openFile") { return this.uiShowItemEx(itemNd, viewMode); } var isReloadFrm = false; var oldFormId = this.uiGetFormID4ItemEx(itemWin, win.isEditMode ? "edit" : "view"); var newIsEditMode = (this.isTempEx(itemNd) || this.isLockedByUser(itemNd)) ? true : false; var newFormId = this.uiGetFormID4ItemEx(itemNd, win.isEditMode ? "edit" : "view"); if (!newFormId) { var doc = win.frames.instance.document; doc.open(); doc.write("
" + this.getResource("", "ui_methods_ex.form_not_specified_for_you", win.isEditMode ? "edit" : "view") + "
"); doc.close(); return; } if (oldItemID != itemID) { this.uiUnregWindowEx(oldItemID); this.uiRegWindowEx(itemID, win); isReloadFrm = true; if (newFormId != oldFormId) { if (win.name != "work") { win.close(); isReloadFrm = false; } } } this.RefillWindow(itemNd, win, isReloadFrm); if (win.updateMenu) { win.updateMenu(); } }; Aras.prototype.RefillWindow = function ArasRefillWindow(itemNd, win, isReloadFrm) { var itemWin; if (win.getItem) { itemWin = win.getItem(); } else { itemWin = win.item; } if (itemWin && "update" == itemWin.getAttribute("action") && itemWin.getAttribute("id") != itemNd.getAttribute("id")) { isReloadFrm = true; } var itemID = itemNd.getAttribute("id"); var typeID = itemNd.getAttribute("typeId"); var itemTypeName = this.getItemTypeName(typeID); var winName = this.mainWindowName + "_" + itemID; win.name = winName; if (win.setItem) { win.setItem(itemNd); } else { win.item = itemNd; } win.itemID = itemID; var itemTypeNd = this.getItemTypeNodeForClient(itemTypeName); win.itemType = itemTypeNd; var newIsEditMode = (this.isTempEx(itemNd) || this.isLockedByUser(itemNd)) ? true : false; win.isTearOff = true; win.itemTypeName = itemTypeName; if (win.updateRootItem) { if (!win.isEditModeUnchangeable) { win.isEditMode = newIsEditMode; } var queryString; if (isReloadFrm && win.relationships) { var openTab = win.relationships.relTabbar.GetSelectedTab(); queryString = { db: this.getDatabase(), ITName: itemTypeName, relTypeID: openTab, itemID: itemID, editMode: (win.isEditMode ? 1 : 0), tabbar: "1", toolbar: "1", where: "tabview" }; } win.updateRootItem(itemNd, queryString); if (win.getViewersTabs) { var updateSidebar = function () { setTimeout(function () { var tabsControl = win.getViewersTabs(); var currentTabId = tabsControl.getCurrentTabId(); var callback = function (viewerContainer) { var frame = viewerContainer.getChildren()[0].viewerFrame; if (frame && !frame.contentWindow.SSVCViewer) { frame.contentWindow.onViewerIsReady = function () { var args = frame.contentWindow.VC.Utils.Page.GetParams(); frame.contentWindow.SSVCViewer.displayFile(args.fileUrl); }; } }; tabsControl.selectTab(currentTabId, callback); document.removeEventListener("loadSideBar", updateSidebar); }, 0); }; document.addEventListener("loadSideBar", updateSidebar); } } else { this.AlertError(this.getResource("", "ui_methods_ex.function_update_root_item_not_implemented"), "", "", win); } if (win.document.getElementById("edit") && win.document.getElementById("form_frame")) { this.uiShowItemInFrameEx(win.getElementById("form_frame"), win.item, (win.isEditMode ? "edit" : "view")); } }; Aras.prototype.uiPopulatePropertiesOnWindow = function ArasUiPopulatePropertiesOnWindow(hostWindow, itemNd, itemTypeNd, formNd, isEditMode, mode, userChangeHandler) { var itemID; var itemTypeName; var itemTypeID; var iomItem; var formID = formNd.getAttribute("id"); var winParams = {}; winParams.aras = this; winParams.viewMode = mode; winParams.isEditMode = isEditMode; winParams.formID = formID; winParams.formNd = formNd; //uiShowItemInFrameEx method where current method is called calculate itemTypeNd from itemNd, it is not possible to have itemNd wihtout itemTypeNd calculated if (itemNd && itemTypeNd) { itemID = itemNd.getAttribute("id"); iomItem = this.newIOMItem(); iomItem.dom = itemNd.ownerDocument; iomItem.node = itemNd; winParams.item = itemNd; winParams.itemNd = itemNd; winParams.thisItem = iomItem; //In case of SearchMode form (for example search by criteria @{0}) itemNd exist, but it is query AML which doesn't have id at all, make sure that isTemp in that case //set to true winParams.itemID = itemID; winParams.isTemp = this.isTempEx(itemNd); } //method uiDrawFormEx is not require to have itemNd populated, for example on Form editor. But itemTypeNd in this case should be populated (it will be used to populate list on forms fields) if (itemTypeNd) { itemTypeID = itemTypeNd.getAttribute("id"); itemTypeName = this.getItemProperty(itemTypeNd, "name"); winParams.itemTypeID = itemTypeID; winParams.itemType = itemTypeNd; winParams.itemTypeNd = itemTypeNd; winParams.itemTypeName = itemTypeName; } if (userChangeHandler) { winParams.userChangeHandler = userChangeHandler; } //it is assuming that there is no racing conditions for two or more forms opened in the same time. First form will be loaded, then second form will erase windowArgumentsExchange and setup it again. //In case of error it will be required to fix more than just creating something like hostWindow._<%form_id%>_params, //because it can be situation when two items with the same form is opened simulteneously from the same origin window. //It will be required to pass some guid to the window, but it is not allowed to add it to query string, due to cache issues. //It will be requried to use window.name property which is set up as '; //$('.mainContent').find('iframe.YiSha_iframe').hide().parents('.mainContent').append(ifrmaeStr); topWin.document.body.appendChild(iframe); //topWin.document.body.appendChild(ifrmaeStr); this.selectTab(li); //var iframe = document.getElementById(winName); var win = iframe.contentWindow; win.opener = topWin; win.name = iframe.name = winName; return win; }; Tabs.prototype.getSameDropdownTabItem = function(tab) { return this._dropdownList.querySelector('[list-data-id="' + tab.getAttribute('data-id') + '"]'); }; Tabs.prototype.addDropdownTab = function(tab) { tab.setAttribute('list-data-id', tab.getAttribute('data-id')); tab.removeAttribute('data-id'); tab.innerHTML = ''; this._dropdownList.appendChild(tab); }; Tabs.prototype.removeDropdownTab = function(tab) { var listTab = this.getSameDropdownTabItem(tab); if (listTab.classList.contains('selected')) { var currentTab = listTab.previousElementSibling || listTab.nextElementSibling; if (currentTab) { this.selectDropdownTab(currentTab, true); } } this._dropdownList.removeChild(listTab); }; Tabs.prototype.selectDropdownTab = function(tab, isListTab) { var listTab; if (!isListTab) { listTab = this.getSameDropdownTabItem(tab); } else { listTab = tab; } var currentActive = this._dropdownList.querySelector('.selected'); if (currentActive !== listTab) { if (currentActive) { currentActive.classList.remove('selected'); } if (listTab) { listTab.classList.add('selected'); } } }; Tabs.prototype.makeDropdownSelectable = function() { var select = function(event) { var target = event.target; var listTab = target.closest('li'); if (listTab) { var tab = this._elem.querySelector('[data-id="' + listTab.getAttribute('list-data-id') + '"]'); this.selectTab(tab); } }.bind(this); this._attachedEvents.onDropdownSelect = { source: this._dropdownList, eventType: 'mousedown', callback: select }; this._dropdownList.addEventListener('mousedown', select); }; Tabs.prototype.setDropdownTabContent = function(tab, content) { var listTab = this.getSameDropdownTabItem(tab); listTab.innerHTML = '' + content || ''; }; /** ..\Modules\aras.innovator.core.MainWindow\TimeBanners.js **/ (function() { var todayFieldSetId = 'today'; var todayCorpFieldSetId = 'today_corp'; var updtBnnrsTmout; window.updateBanners = function() { updateBanner(todayFieldSetId); if (document.corporateToLocalOffset) { updateBanner(todayCorpFieldSetId); } var secs = (new Date()).getSeconds(); updtBnnrsTmout = setTimeout(updateBanners, (60 - secs) * 1000 + 1); }; function updateBanner(bannerId) { var longDatePtrn = aras.getDotNetDatePattern('long_date'); var shortTimePtrn = aras.getDotNetDatePattern('short_time'); var date = new Date(); var year; var month; var day; var hours; var minutes; if (bannerId == todayCorpFieldSetId) { year = date.getUTCFullYear(); month = date.getUTCMonth(); day = date.getUTCDate(); hours = date.getUTCHours(); minutes = date.getUTCMinutes(); var UTCMillisecs = Date.UTC(year, month, day, hours, minutes); UTCMillisecs += document.corporateToLocalOffset * 60 * 1000; date = new Date(UTCMillisecs); } year = date.getFullYear().toString(); month = (date.getMonth() + 1).toString(); day = date.getDate().toString(); hours = date.getHours().toString(); minutes = date.getMinutes().toString(); var dtStr = s2(year, 4) + '-' + s2(month) + '-' + s2(day) + 'T' + s2(hours) + ':' + s2(minutes) + ':00'; var todayDate = aras.convertFromNeutral(dtStr, 'date', longDatePtrn); var todayTime = aras.convertFromNeutral(dtStr, 'date', shortTimePtrn); var exp = new RegExp('\\b(am|pm|AM|PM)$'); var match = exp.exec(todayTime); document.getElementById(bannerId + '_date').innerHTML = todayDate; document.getElementById(bannerId + '_time').innerHTML = match && match.length > 0 ? todayTime.replace(match[0], '' + match[0] + '') : todayTime; function s2(s, n) { if (n === undefined) { n = 2; } s = '' + s; while (s.length < n) { s = '0' + s; } return s; } } window.showCorporateTime = function() { var todayLableCrp = document.getElementById('today_lbl_corp'); if (todayLableCrp) { todayLableCrp.style.visibility = document.corporateToLocalOffset ? 'visible' : 'hidden'; } var todayBlockCrp = document.getElementById('today_corp_block'); if (todayBlockCrp) { todayBlockCrp.style.visibility = document.corporateToLocalOffset ? 'visible' : 'hidden'; } var todayLable = document.getElementById('today_lbl'); if (todayLable) { todayLable.style.visibility = document.corporateToLocalOffset ? 'visible' : 'hidden'; } }; window.stopTimeBannersUpdate = function() { if (updtBnnrsTmout !== undefined) { clearTimeout(updtBnnrsTmout); } }; })(); /** ..\Modules\aras.innovator.core.MainWindow\setup.js **/ (function () { var treePaneWidget = null; var containerWidget = null; var rm; var splitter; window.loadToolBar = function(callback) { return clientControlsFactory.createControl('Aras.Client.Controls.Public.ToolBar', { id: 'top_toolbar', connectId: 'maintoolbar'//'header'//toolbar parent container ,by fyc }).then(function (control) { window.toolbar = control; if (callback) { callback(window.toolbar); } }); }; window.loadTree = function(args, callback) { return clientControlsFactory.createControl('Aras.Client.Controls.Experimental.Tree', { id: 'tree', IconPath: '../cbin/', allowEmptyIcon: true }).then(function(mainTreeApplet) { var leadingNode = document.getElementById('leading'); leadingNode.appendChild(mainTreeApplet._tree.domNode); clientControlsFactory.on(mainTreeApplet, { 'GridXmlLoaded': function() { args.GridXmlLoaded(); }, 'menuInit': args.menuInit, 'itemSelect': args.itemSelect }); if (callback) { callback(mainTreeApplet); } }); }; window.loadStatusbar = function() { var resourceUrl = aras.getI18NXMLResource('statusbar.xml', aras.getBaseURL()); return clientControlsFactory.createControl('Aras.Client.Controls.Experimental.StatusBar', { id: 'bottom_statusBar', aras: aras, resourceUrl: resourceUrl }).then(function (statusbarCtrl) { var bottomNode = document.getElementById('bottom'); bottomNode.appendChild(statusbarCtrl.domNode); statusbarCtrl.startup(); return clientControlsFactory.createControl('Aras.Client.Frames.StatusBar', { aras: aras, statusbar: statusbarCtrl }); }).then(function(control) { window.statusbar = control; }); }; window.loadNavigatorMenu = function (args, callback) { return clientControlsFactory.createControl('Aras.Client.Controls.Experimental.MainMenu', { id: 'navigator_mainMenu', XML: args.xml, xmlArgType: args.xmlArgType, aras: args.aras, cuiContext: args.cuiContext }).then(function (menu) { menu.placeAt('Navigatorlayout', 'first'); menu.startup(); if (callback) { callback(menu); } }); }; window.updateTogglePanel = function() { var togglePanel = document.getElementById('togglePanel'); var treeButton = document.getElementById('showTreeButton'); var tree = isMainTreeShown(); if (!tree) { togglePanel.style.display = 'block'; treeButton.style.display = tree ? 'none' : 'block'; } else { treeButton.style.display = togglePanel.style.display = 'none'; } //we update ShowMainTree only and do not update show_properties menu flag. //show_properties menu flag is updated inside MainMenu setControlState('ShowMainTree', treeButton.style.display == 'none'); }; function populateTitlesForTogglePanel() { var treeButton = document.getElementById('showTreeButton'); if (treeButton) { treeButton.setAttribute('title', rm.getString('common.showMainTreeTooltip')); } } window.loadMainMenu = function(args, callback) { return clientControlsFactory.createControl('Aras.Client.Controls.Experimental.MainMenu', { id: 'menulayout_mainMenu', XML: args.xml, xmlArgType: args.xmlArgType, aras: args.aras, cuiContext: args.cuiContext }).then(function(menu) { menu.placeAt('menulayout', 'first'); menu.startup(); if (callback) { callback(menu); } //updateTree(); // onNavigatorClick("Administration/ItemType"); }); }; window.hideOrShowTree = function(bool) { if (bool) { treePaneWidget.style.display = splitter.style.display = 'none'; } else { treePaneWidget.style.display = splitter.style.display = 'block'; } updateTogglePanel(); }; window.isMainTreeShown = function() { return treePaneWidget.style.display === 'block'; }; window.registerShortcutsAtMainWindowLocation = function(settings, itemTypeName, itemType) { if (settings) { var loadParams = { locationName: 'MainWindowShortcuts', 'item_classification': '%all_grouped_by_classification%', itemTypeName: itemTypeName, itemType: itemType }; window.cui.loadShortcutsFromCommandBarsAsync(loadParams, settings).then(function() { window.focus(); }); } }; function checkCachingMechanism() { var checkCachingMechanismUrl = aras.getScriptsURL() + 'CheckCachingMechanism.aspx'; //alert(checkCachingMechanismUrl); var requestSettings = { url: checkCachingMechanismUrl, restMethod: 'GET', async: true }; var firstRequestResponse; return ArasModules.soap('', requestSettings) .then(function (responseText) { firstRequestResponse = responseText; return ArasModules.soap('', requestSettings); }) .then(function(secondRequestResponse) { return firstRequestResponse === secondRequestResponse; }); } function disableFileDrop() { // disable drop file by all iframes in the window var prevent = function(e) { e.preventDefault(); }; [].forEach.call(window.document.querySelectorAll('iframe'), function(elm) { elm.contentWindow.addEventListener('drop', prevent); elm.contentWindow.addEventListener('dragover', prevent); }); // disable drop file by window window.addEventListener('drop', prevent); window.addEventListener('dragover', prevent); } function initializeChildFrames() { [].forEach.call(window.frames, function(win) { if (win.initialize) { win.initialize(); } }); } window.setUserName = function() { var userNameNode = document.getElementById('profileName'); if (userNameNode) { var userData = aras.getLoggedUserItem(); var userKeyedName = aras.getKeyedName(userData.getAttribute('id'), 'User'); userNameNode.textContent = (userKeyedName === userData.getAttribute('id')) ? aras.getLoginName() : userKeyedName; } }; window.setUserImg = function() { var userImgNode = document.getElementById('profileImg'); if (userImgNode) { var userData = aras.getLoggedUserItem(); var pictItem = userData.selectSingleNode('picture'); if (pictItem.getAttribute('is_null') !== '1') { var imgItemId = pictItem.text.replace('vault:///?fileId=', ''); var imgurl = aras.IomInnovator.getFileUrl(imgItemId, aras.Enums.UrlType.SecurityToken); userImgNode.src = imgurl; } } }; function buildMaintreeContextMenu() { var contextMenuXML = ""; contextMenuXML = contextMenuXML + ""; contextMenuXML = contextMenuXML + ""; contextMenuXML = contextMenuXML + ""; contextMenuXML = contextMenuXML + ""; contextMenuXML = contextMenuXML + ""; contextMenuXML = contextMenuXML + ""; mainTreeContextmenu.setSkin(globalUI); mainTreeContextmenu.setIconsPath("../images/"); mainTreeContextmenu.renderAsContextMenu(); mainTreeContextmenu.loadStruct(contextMenuXML); } /** * Initialize main window. Called from onSuccessfulLogin function of login.aspx. * * @returns {boolean} */ window.initialize = function () { fixDojoSettings(); rm = new ResourceManager(new Solution('core'), 'ui_resources.xml', aras.getSessionContextLanguageCode()); aras.setUserReportServiceBaseUrl(window.location.href.replace(/(\/Front?)(\/|$)(.*)/i, '$1') + '/../SelfServiceReporting'); var userNd = aras.getLoggedUserItem(true); if (!userNd) { window.onbeforeunload = ''; window.close(); return false; } if (!document.frames) { document.frames = []; } aras.getPreferenceItemProperty('SSVC_Preferences', null, 'default_bookmark'); // var update = new InnovatorUpdate(); // update.BeginIsNeedCheckUpdates(); /* 增加功能导航菜单开始*/ /* var navigator = new dhtmlXToolbarObject("top_menu"); // var navigator = new dhtmlXMenuObject("Navigatorlayout"); navigator.setSkin("dhx_web"); navigator.setIconsPath("../images/"); var navigatorDom = getMainTreeItems(); globaltreeDom = navigatorDom; var nvaigatorXML = ""; if (navigatorDom) { nvaigatorXML = generateMainmenuXML(navigatorDom); } navigator.loadStruct(nvaigatorXML, function () { // updateTree();//第一次进入系统(没有指定tree id),打开登录用户的默认项,在主工具栏加载后再调用 }); navigator.attachEvent("onClick", function (id, zoneId, casState) { updateTree(id);//点击导航工具栏后传入的是工具栏的ID,也是tree的父ID // onNavigatorClick(id); return true; }); */ var workIframe = document.getElementById('work'); window.work = workIframe.contentWindow; loadStatusbar(); checkCachingMechanism() .then(function(isCachingMechanismWork) { if (!isCachingMechanismWork) { aras.AlertError(rm.getString('setup.cache_is_disabled')); } }) .catch(function (error) { console.error(error); }); // aras.UpdateFeatureTreeIfNeed(); document.corporateToLocalOffset = aras.getCorporateToLocalOffset(); // updateBanners(); //showCorporateTime(); PopulateDocByLabels(); disableFileDrop(); initializeChildFrames(); var navigatorDom = getMainTreeItems(); globaltreeDom = navigatorDom; var nvaigatorXML = ""; if (navigatorDom) { nvaigatorXML = generateMainmenuXML(navigatorDom); } //nvaigatorXML = ""; //alert(nvaigatorXML); nvaigatorXML = nvaigatorXML.substr(4, nvaigatorXML.length - 9); //alert(nvaigatorXML); document.getElementById("top_menu").innerHTML = nvaigatorXML; // initializeNavigatorMenu(); //updateLi(); initializeMainMenuandToolbar(); //updateTree(); var mode = aras.getMainWindow().arasMainWindowInfo.ClientDisplayMode; if (aras.Browser.isEdge() || mode !== 'Windows') { window.arasTabs = new Tabs('main-tab'); } else { document.querySelector('header').classList.add('window-mode'); } setUserName(); var userLogoutNode = document.getElementById('profileLogout'); if (userLogoutNode) { userLogoutNode.addEventListener('click', function () { onLogoutCommand(); }); } setUserImg(); containerWidget = document.getElementById('content-main'); return true; }; })(); /** ..\Modules\aras.innovator.core.MainWindow\deepLinking.js **/ var deepLinking = (function () { var storage; function deepLinkingStorageListener(storageEvent) { var changeMessage = function(frame) { var win = frame.contentWindow; var msg = win.document.getElementById('message'); if (!msg) { frame.addEventListener('load', function() { var msg = win.document.getElementById('message'); msg.textContent = deepLinking.currentMsg; }); } else { msg.textContent = deepLinking.currentMsg; } }; var setDeepLinkingMessage = function (msg) { deepLinking.currentMsg = msg; var deepWindowIframe = document.getElementById('deepLinking'); deepWindowIframe.style.display = 'block'; document.getElementById('dimmer_spinner_whole_window').classList.add('disabled-spinner'); if (!deepWindowIframe.src) { deepWindowIframe.src = 'deepLinking.aspx'; } changeMessage(deepWindowIframe); }; if (storageEvent.key === 'DeepLinkingMainMenu' && storageEvent.newValue === 'opening') { storage.removeItem('DeepLinkingMainMenu'); setDeepLinkingMessage(aras.getResource('', 'deep_link.start_opening_item')); } if (storageEvent.key === 'DeepLinkingResultOpenItem' && storageEvent.newValue) { storage.removeItem('DeepLinkingResultOpenItem'); storage.removeItem('DeepLinkingOpenStartItem'); setDeepLinkingMessage(storageEvent.newValue); window.removeEventListener('storage', deepLinkingStorageListener); } } function mainWindowListener(storageEvent) { if (storageEvent.key !== 'DeepLinkingOpenStartItem' || !storageEvent.newValue) { return; } var item = JSON.parse(storageEvent.newValue); var itemTypeName = item.itemTypeName; var itemID = item.itemID; if (!itemTypeName || !itemID || !aras.getLoginName || aras.getLoginName() === '') { return; } storage.removeItem('DeepLinkingOpenStartItem'); storage.removeItem('DeepLinkingResultOpenItem'); storage.removeItem('DeepLinkingMainMenu'); storage.setItem('DeepLinkingMainMenu', 'opening'); var gottenItem = aras.getItemById(itemTypeName, itemID); if (!gottenItem) { storage.setItem('DeepLinkingResultOpenItem', aras.getResource('', 'deep_link.error_open_item')); return; } var keyedName = aras.getItemProperty(gottenItem, 'keyed_name'); if (aras.uiFindWindowEx(itemID)) { storage.setItem('DeepLinkingResultOpenItem', aras.getResource('', 'deep_link.item_alredy_is_opened', itemTypeName + ' ' + keyedName)); return; } var result = aras.uiShowItemEx(gottenItem, 'tab view', !Boolean(window.arasTabs)); if (!result || !result.then) { storage.setItem('DeepLinkingResultOpenItem', aras.getResource('', 'deep_link.error_open_item')); return; } result.then(function() { var win = aras.uiFindAndSetFocusWindowEx(itemID); storage.setItem('DeepLinkingResultOpenItem', aras.getResource('', 'deep_link.item_is_opened', itemTypeName + ' ' + keyedName)); }); } function getDeepLinkItemData() { var itemData = { 'itemTypeName': null, 'itemID': null }; var StartItemStr = null; if (location && location.search.substr(1, location.search.length)); { var searchParams = new URLSearchParams(location.search.substr(1, location.search.length)); StartItemStr = searchParams.get('StartItem'); } if (StartItemStr) { var arr = StartItemStr.split(':'); itemData.itemTypeName = arr[0]; itemData.itemID = arr[1]; if (itemData.itemTypeName && itemData.itemID) { return itemData; } } } return { /*Constant that determines what time DeepLinkingWindow may look MainWindow*/ SEARCH_TIME_THE_MAIN_WINDOW: 2000, currentMsg: '', onSuccessfulLogin: function () { window.addEventListener('storage', mainWindowListener); window.removeEventListener('storage', deepLinkingStorageListener); }, beforeInitializeLoginForm: function () { storage = this.getStorage(); var startItem = getDeepLinkItemData(); if (startItem) { window.addEventListener('storage', deepLinkingStorageListener); storage.removeItem('DeepLinkingOpenStartItem'); storage.setItem('DeepLinkingOpenStartItem', JSON.stringify(startItem)); } window.addEventListener('beforeunload', function () { storage.removeItem('DeepLinkingOpenStartItem'); storage.removeItem('DeepLinkingResultOpenItem'); storage.removeItem('DeepLinkingMainMenu'); }); return new Promise(function (resolve) { if (getDeepLinkItemData()) { var frame = document.getElementById('main').contentWindow; if (frame.clientConfig.loginOnloadSubmit === 'true') { frame.clientConfig.loginOnloadSubmit = 'false'; setTimeout(function () { if (this.currentMsg === '' && frame.loginPage) { //Open this windows like Main Window frame.clientConfig.loginOnloadSubmit = 'true'; window.removeEventListener('storage', deepLinkingStorageListener); frame.loginPage._afterCompleteLoad(); resolve(true); } resolve(false); }.bind(this), this.SEARCH_TIME_THE_MAIN_WINDOW); } else { resolve(false); } } else { resolve(false); } }.bind(this)); }, getStorage: function () { return window.localStorage; } }; })(); /** pageReturnBlocker.js **/ var PageReturnBlocker = function() { this.completeFlag = 'reloadShortcutsBlocked'; this.loaderFlag = 'blockerLoaderAttached'; this.skipFlag = 'skipReloadShortcutsBlocker'; this.manualStartAttribute = 'startBlockerManually'; return this; }; // for current window, prevent default browser behavior for backspace( load previous page ), F5 ( reload current page) PageReturnBlocker.prototype.attachReloadShortcutsBlocker = function(targetWindow) { if (targetWindow && !targetWindow[this.completeFlag] && !targetWindow[this.skipFlag]) { var shortcutsBlockHandler = function(evt) { var keyCode = evt ? evt.keyCode || evt.which : 0; var preventRequired = false; switch (keyCode) { case 8: //backspace shortcut if (targetWindow.document.hasOwnProperty('isEditMode') && !targetWindow.document.isEditMode) { preventRequired = true; } else { var targetElement = evt.target || evt.srcElement; if (!targetElement.readOnly && !targetElement.disabled) { if (/input/i.test(targetElement.tagName)) { preventRequired = !(/text|password|file/i.test(targetElement.type)); } else if (/textarea/i.test(targetElement.tagName)) { preventRequired = false; } else { preventRequired = !((targetElement.contentEditable === 'true') || (targetElement.ownerDocument.designMode === 'on')); } } } break; case 116: //F5 shortcut preventRequired = true; } if (preventRequired) { evt.preventDefault(); } }; targetWindow.document.addEventListener('keydown', shortcutsBlockHandler, false); targetWindow[this.completeFlag] = true; } }; PageReturnBlocker.prototype.blockInChildFrames = function(targetWindow, blockInChilds) { if (targetWindow) { var frames = targetWindow.document.querySelectorAll('frame, iframe'); var currentFrame = null; var self = this; for (var index = 0; index < frames.length; index++) { currentFrame = frames[index]; if (!currentFrame[this.loaderFlag]) { (function(currentFrame) { // jshint ignore:line var pageLoadHandler = function() { self.attachBlocker(currentFrame.contentWindow, blockInChilds); }; var pageUnloadHandler = function() { currentFrame.removeEventListener('load', pageLoadHandler); targetWindow.removeEventListener('unload', pageUnloadHandler); }; currentFrame.addEventListener('load', pageLoadHandler, false); targetWindow.addEventListener('unload', pageUnloadHandler, false); })(currentFrame); // jshint ignore:line this.attachBlocker(currentFrame.contentWindow, blockInChilds); currentFrame[this.loaderFlag] = true; } } } }; PageReturnBlocker.prototype.attachBlocker = function(targetWindow, blockInChilds) { targetWindow = targetWindow ? targetWindow : window; try { var doc = targetWindow.document; } catch (exe) { return;//access denied } this.attachReloadShortcutsBlocker(targetWindow); if (blockInChilds) { var documentState = targetWindow.document.readyState; if (documentState === 'complete' || documentState === 'interactive') { this.blockInChildFrames(targetWindow, true); } else { var self = this; var DOMContentLoadedHandler = function() { self.blockInChildFrames(targetWindow, true); this.removeEventListener('DOMContentLoaded', DOMContentLoadedHandler); }; targetWindow.document.addEventListener('DOMContentLoaded', DOMContentLoadedHandler, false); } } }; // add returnBlocker object to window var returnBlockerHelper = new PageReturnBlocker(); (function() { var blockerScript = null; var pageScripts = document.getElementsByTagName('script'); var scriptSrc = ''; for (var i = 0; i < pageScripts.length; i++) { scriptSrc = pageScripts[i].src.toUpperCase(); if (scriptSrc.indexOf('PAGERETURNBLOCKER') > -1) { blockerScript = pageScripts[i]; break; } } var startManual = blockerScript.getAttribute(returnBlockerHelper.manualStartAttribute); if (startManual != 'true') { window.document.addEventListener('DOMContentLoaded', function() { returnBlockerHelper.attachBlocker(null, true); }, false); } })(); /** IOM.ScriptSharp.js **/ // IOM.ScriptSharp.js (function(){ window.StringComparison=function(){} window.CompressionType=function(){} window.RegexOptions=function(){} window.HttpUtility=function(){} HttpUtility.urlEncode=function(url){return encodeURIComponent(url);} Type.registerNamespace('Aras.IOM');Aras.IOM.IServerConnection=function(){};Aras.IOM.IServerConnection.registerInterface('Aras.IOM.IServerConnection');Aras.IOM.FetchFileMode=function(){};Aras.IOM.FetchFileMode.prototype = {normal:0,dry:1} Aras.IOM.FetchFileMode.registerEnum('Aras.IOM.FetchFileMode',false);Aras.IOM.UrlType=function(){};Aras.IOM.UrlType.prototype = {none:0,securityToken:1} Aras.IOM.UrlType.registerEnum('Aras.IOM.UrlType',false);Aras.IOM.HttpConnectionParameters=function(){} Aras.IOM.HttpConnectionParameters.prototype={forceWritableSession:false} Aras.IOM.I18NSessionContext=function(validateUsrXmlResult){this.$7=new Aras.I18NUtils._I18NConverter();if(String.isNullOrEmpty(validateUsrXmlResult)){return;}var $0=new XmlDocument();var $1;try{$0.loadXML(validateUsrXmlResult);$1=$0.documentElement.selectSingleNode('/*/*/*/i18nsessioncontext');}catch($2){$1=null;}if($1==null){return;}this.$0=Aras.IOM.I18NSessionContext.$8($1,'locale');this.$1=Aras.IOM.I18NSessionContext.$8($1,'language_code');this.$2=Aras.IOM.I18NSessionContext.$8($1,'language_suffix');this.$3=Aras.IOM.I18NSessionContext.$8($1,'default_language_code');this.$4=Aras.IOM.I18NSessionContext.$8($1,'default_language_suffix');this.$5=Aras.IOM.I18NSessionContext.$8($1,'time_zone');this.$6=Aras.IOM.I18NSessionContext.$9($1,'corporate_to_local_offset');} Aras.IOM.I18NSessionContext.$8=function($p0,$p1){var $0=$p0.selectSingleNode($p1);return ($0==null||!$0.text.trim().length)?null:$0.text.trim();} Aras.IOM.I18NSessionContext.$9=function($p0,$p1){var $0=Aras.IOM.I18NSessionContext.$8($p0,$p1);var $1=Number.MIN_VALUE;if(!String.isNullOrEmpty($0)){try{$1=parseInt($0);}catch($2){$0=null;}}if(String.isNullOrEmpty($0)&&!String.isNullOrEmpty($p1)){var $3=$p1.toLowerCase();switch($3){case 'time_zone':$1=-1;break;case 'corporate_to_local_offset':$1=0;break;}}return $1;} Aras.IOM.I18NSessionContext.prototype={$0:null,$1:null,$2:null,$3:null,$4:null,$5:null,$6:0,ConvertToNeutral:function(svalue,vtype,datePtrn){return this.$7.$A(svalue,vtype,true,datePtrn,this.GetLocale(),this.GetTimeZone());},ConvertFromNeutral:function(svalue,vtype,datePtrn){return this.$7.$A(svalue,vtype,false,datePtrn,this.GetLocale(),this.GetTimeZone());},ConvertUtcDateTimeToNeutral:function(utcStr,inPattern){if(utcStr==null){return null;}var $0;var $1=CultureInfo.InvariantCulture.DateTimeFormat;if(String.isNullOrEmpty(inPattern)){$0=$1.Parse(utcStr,null,null);}else{$0=$1.Parse(utcStr,inPattern,null);}var $2=Date.UTC($0.getFullYear(),$0.getMonth(),$0.getDate(),$0.getHours(),$0.getMinutes(),$0.getSeconds(),$0.getMilliseconds());var $3=$1.OffsetBetweenTimeZones($0,this.GetTimeZone(),null);var $4=new Date($2+$0.getTimezoneOffset()*60000+$3*60000);return $1.Format($4,'yyyy-MM-ddTHH:mm:ss',null);},ConvertNeutralToUtcDateTime:function(neutralStr,outPattern){if(neutralStr==null||!String.isNullOrEmpty(outPattern)&&outPattern.indexOf('z')>-1){return null;}var $0;var $1=CultureInfo.InvariantCulture.DateTimeFormat;$0=$1.Parse(neutralStr,null,null);var $2=Date.UTC($0.getFullYear(),$0.getMonth(),$0.getDate(),$0.getHours(),$0.getMinutes(),$0.getSeconds(),$0.getMilliseconds());var $3=$1.OffsetBetweenTimeZones($0,this.GetTimeZone(),null);var $4=new Date($2+$0.getTimezoneOffset()*60000-$3*60000);return $1.Format($4,outPattern,null);},GetLocale:function(){return this.$0;},GetLanguageCode:function(){return this.$1;},GetLanguageSuffix:function(){return this.$2;},GetDefaultLanguageCode:function(){return this.$3;},GetDefaultLanguageSuffix:function(){return this.$4;},GetTimeZone:function(){return this.$5;},GetCorporateToLocalOffset:function(){return this.$6;},GetUIDatePattern:function(innovatorDatePattern){return Aras.I18NUtils._I18NConverter.$B(innovatorDatePattern,this.GetLocale());}} Aras.IOM.IOMScriptSharp$5=function(userName,passwordOrPasswordHash){this.$1=userName;this.$0=passwordOrPasswordHash;} Aras.IOM.IOMScriptSharp$5.prototype={$0:null,$1:null,get_$2:function(){return this.$1;},get_$3:function(){return this.$0;}} Aras.IOM.InternalUtils=function(){} Aras.IOM.InternalUtils.createXmlDocument=function(){var $0=new XmlDocument();return $0;} Aras.IOM.InternalUtils.createAndLoadXmlDocument=function(xmlValue){var $0=new XmlDocument();$0.loadXML(xmlValue);return $0;} Aras.IOM.InternalUtils.loadXmlFromString=function(xmlDocument,xmlValue){xmlDocument.loadXML(xmlValue);} Aras.IOM.InternalUtils.$0=function($p0,$p1){return (Type.safeCast($p0.getAttribute($p1),String))||'';} Aras.IOM.InternalUtils.$1=function($p0){var $0=$p0.nodeType;return $0;} Aras.IOM.InternalUtils.$2=function($p0,$p1){var $0=$p0.selectSingleNode('./@'+$p1)!=null;return $0;} Aras.IOM.XmlExtension=function(){} Aras.IOM.XmlExtension.getXml=function(node){return node.xml;} Aras.IOM.IomFactory=function(){} Aras.IOM.IomFactory.prototype={CreateInnovator:function(serverConnection){return new Aras.IOM.Innovator(serverConnection);},CreateArrayList:function(){return [];},CreateComISConnection:function(serverConnectionImplementation){return serverConnectionImplementation;},CreateComISConnector:function(serverConnectionImplementation){return serverConnectionImplementation;},CreateItemCache:function(){return new Aras.IOME.ItemCache();},CreateCacheableContainer:function(value,dependenciesSource){return new Aras.IOME.CacheableContainer(value,dependenciesSource);},CreateHttpServerConnection:function(innovatorServerUrl,database,userName,password,culture,timeZone){return new Aras.IOM.HttpServerConnection(innovatorServerUrl,database,userName,password,culture,timeZone);},CreateRestrictedHttpServerConnection:function(innovatorServerUrl){return new Aras.IOM.IOMScriptSharp$6(innovatorServerUrl);},CreateWinAuthHttpServerConnection:function(innovatorServerUrl,database){return new Aras.IOM.WinAuthHttpServerConnection(innovatorServerUrl,database);}} Aras.IOM.HttpServerConnection=function(innovatorServerUrl,database,userName,password,culture,timeZone){Aras.IOM.HttpServerConnection.initializeBase(this);if(!Aras.IOM.HttpServerConnection.$17.test(password)){throw new Error('Not Implemented');}this.Compression='none';if(!String.isNullOrEmpty(culture)){this.set_locale(culture);}if(!String.isNullOrEmpty(timeZone)){this.set_timeZoneName(timeZone);}if(!innovatorServerUrl.endsWith('Server/InnovatorServer.aspx')){innovatorServerUrl+=((!innovatorServerUrl.endsWith('/'))?'/':'')+'Server/';}else if(innovatorServerUrl.endsWith('Server/InnovatorServer.aspx')){innovatorServerUrl=innovatorServerUrl.replace(new RegExp('InnovatorServer.aspx$',RegexOptions.ignoreCase),'');}this.$D=innovatorServerUrl;this.$C=String.format('{0}InnovatorServer.aspx',this.$D);this.$E=database;this.$18=new Aras.IOM.IOMScriptSharp$5(userName,password);} Aras.IOM.HttpServerConnection.$12=function($p0,$p1,$p2){if(String.isNullOrEmpty($p2)){return;}var $0=$p0.ownerDocument.createElement($p1);$0.text=$p2;$p0.appendChild($0);} Aras.IOM.HttpServerConnection.$16=function($p0,$p1){Aras.IOM.InternalUtils.loadXmlFromString($p0,Aras.IOM.HttpServerConnection.$11);var $0=$p0.selectSingleNode('//detail');$0.text=$p1;} Aras.IOM.HttpServerConnection.prototype={$C:null,$D:null,$E:null,$F:null,$10:false,CallAction:function(actionName,inDom,outDom){this.callActionImpl(actionName,inDom,outDom,this.$C,true);},DebugLog:function(reason,msg){throw new Error('Not implemented');},DebugLogP:function(){throw new Error('Not implemented');},getUserID:function(){if(!this.$10){throw new Error('Not logged in');}if(this.cachedUserInfo!=null){return this.cachedUserInfo.getID();}var $0=Aras.IOM.InternalUtils.createAndLoadXmlDocument('');var $1=Aras.IOM.InternalUtils.createAndLoadXmlDocument('');this.CallAction('GetCurrentUserID',$0,$1);var $2=$1.selectSingleNode(Aras.IOM.Item.xPathResult);if($2!=null){return $2.text;}throw new Error('Cannot obtain user id');},GetDatabaseName:function(){return this.$E;},GetOperatingParameter:function(name,defaultvalue){return defaultvalue;},GetSrvContext:function(){return (null);},GetValidateUserXmlResult:function(){return this.$F;},GetLicenseInfo:function(issuer,addonName){var $0=Aras.IOM.InternalUtils.createXmlDocument();var $1=Aras.IOM.InternalUtils.createXmlDocument();Aras.IOM.InternalUtils.loadXmlFromString($0,'');Aras.IOM.InternalUtils.loadXmlFromString($1,'');Aras.IOM.HttpServerConnection.$12($0.documentElement,'issuer',issuer);Aras.IOM.HttpServerConnection.$12($0.documentElement,'name',addonName);this.callActionImpl('GetLicenseInfo',$0,$1,this.$D+'License.aspx',true);return Aras.IOM.XmlExtension.getXml($1.documentElement);},$13:0,get_Timeout:function(){return this.$13;},set_Timeout:function(value){if((value<0)&&(value!==-1)){throw new Error("Timeout can be only be set to 'System.Threading.Timeout.Infinite' or a value >= 0.");}this.$13=value;return value;},$14:0,get_ReadWriteTimeout:function(){return this.$14;},set_ReadWriteTimeout:function(value){if((value<0)&&(value!==-1)){throw new Error("Timeout can be only be set to 'System.Threading.Timeout.Infinite' or a value >= 0.");}this.$14=value;return value;},Login:function(){var $0=Aras.IOM.InternalUtils.createXmlDocument();var $1=Aras.IOM.InternalUtils.createXmlDocument();Aras.IOM.InternalUtils.loadXmlFromString($0,'');Aras.IOM.InternalUtils.loadXmlFromString($1,'');this.CallAction('ValidateUser',$0,$1);var $2=$1.selectSingleNode('//Result/id');if($2==null){var $4=null;var $5=$1.selectSingleNode(Aras.IOM.Item.xPathFault);if($5!=null){$4=$5.text;}else{$4='Failed to login';}var $6=new Aras.IOM.Innovator(this);return $6.newError($4);}this.$10=true;var $3=this.getUserInfo();if($3.isError()){this.$10=false;}return $3;},Logout:function(unlockOnLogout){var $0=new XmlDocument();var $1=new XmlDocument();var $2=(unlockOnLogout)?0:1;Aras.IOM.InternalUtils.loadXmlFromString($0,"");Aras.IOM.InternalUtils.loadXmlFromString($1,'');this.CallAction('Logoff',$0,$1);this.$10=false;this.cachedUserInfo=null;},$15:null,usingParameters:function(parameters,action){this.$15=parameters;try{if(action!=null){action();}}finally{this.$15=null;}},$18:null,get_userName:function(){return this.$18.get_$2();},get_userPassword:function(){return this.$18.get_$3();},callActionImpl:function(actionName,inDom,outDom,url,doSetHeaders){var $0=this.$1A(inDom,url,actionName,doSetHeaders);if($0.status===200){try{Aras.IOM.InternalUtils.loadXmlFromString(outDom,$0.responseText);}catch($1){Aras.IOM.HttpServerConnection.$16(outDom,Type.getInstanceType($1).get_fullName()+': '+$1.message);return;}}else{Aras.IOM.HttpServerConnection.$16(outDom,'no response from Innovator server '+this.$C);return;}if(actionName!=null&&'validateuser'===actionName.toLowerCase()){this.$F=$0.responseText;var $2=new Aras.IOM.I18NSessionContext(this.$F);this.set_locale($2.GetLocale());this.set_timeZoneName($2.GetTimeZone());}},$19:function($p0,$p1,$p2,$p3){var $0=this.$1A($p0,$p1,$p2,$p3);return $0;},$1A:function($p0,$p1,$p2,$p3){if($p0==null||$p0.documentElement==null){throw new Error('inDom');}if(String.isNullOrEmpty($p1)){throw new Error('url');}var $0=TopWindowHelper.getMostTopWindowWithAras(window).aras.XmlHttpRequestManager.CreateRequest();$0.open('POST',$p1,false);var $1="";var $2=$1+$p0.documentElement.xml;$0.setRequestHeader('Content-Type','text/xml');if($p3){$0.setRequestHeader('SOAPAction',$p2);$0.setRequestHeader('AUTHUSER',this.get_userName());$0.setRequestHeader('AUTHPASSWORD',this.get_userPassword());$0.setRequestHeader('DATABASE',this.$E);$0.setRequestHeader('LOCALE',this.get_locale());$0.setRequestHeader('TIMEZONE_NAME',this.get_timeZoneName());}if(this.$15!=null&&this.$15.forceWritableSession){$0.setRequestHeader('Aras-Set-HttpSessionState-Behavior','required');}if($0.timeout>0||$0.timeout===-1){$0.timeout=this.get_Timeout();$0.send($2);}else{$0.send($2);}return $0;},getFileUrl:function(fileId,type){if(fileId==null){throw new Error('fileId');}var $0=Aras.IOM.HttpServerConnection.callBaseMethod(this, 'getFileUrl',[fileId,0]);return $0;},Compression:null,getFileUrls:function(fileIds,type){if(fileIds==null){throw new Error('fileIds');}if(!fileIds.length){throw new Error('List cannot be empty. Parameter name: fileIds');}var $0=Aras.IOM.HttpServerConnection.callBaseMethod(this, 'getFileUrls',[fileIds,0]);return [$0];},GetDatabases:function(){var $0=new ss.StringBuilder(this.$D);$0.append('DBList.aspx');var $1=$0.toString();var $2=TopWindowHelper.getMostTopWindowWithAras(window).aras.XmlHttpRequestManager.CreateRequest();$2.open('GET',$1,false);$2.send(null);var $3=new XmlDocument();Aras.IOM.InternalUtils.loadXmlFromString($3,$2.responseText);var $4=$3.selectNodes('DBList/DB/@id');var $5=new Array($4.length);for(var $6=0;$6<$4.length;$6++){$5[$6]=$4[$6].text;}return $5;}} Aras.IOM.Innovator=function(serverConnection){this.$1={};if(serverConnection==null){throw new Error('serverConnection');}this.$0=serverConnection;} Aras.IOM.Innovator.$3=function(){return TopWindowHelper.getMostTopWindowWithAras(window).aras.GUIDManager.GetGUID();;} Aras.IOM.Innovator.scalcMD5=function(val){return calcMD5(val);} Aras.IOM.Innovator.prototype={$0:null,applyAML:function(AML){var $0=this.newXMLDocument();var $1=this.newXMLDocument();Aras.IOM.InternalUtils.loadXmlFromString($0,AML);Aras.IOM.InternalUtils.loadXmlFromString($1,'');this.$0.CallAction('ApplyAML',$0,$1);return this.$2($1);},applyMethod:function(methodName,body){var $0=this.newXMLDocument();var $1=this.newXMLDocument();Aras.IOM.InternalUtils.loadXmlFromString($0,""+body+'');$0.documentElement.setAttribute('action',methodName);Aras.IOM.InternalUtils.loadXmlFromString($1,'');this.$0.CallAction('ApplyMethod',$0,$1);return this.$2($1);},$2:function($p0){var $0=Aras.IOM.Item.$0(this.$0,'','','simple');if($p0.selectSingleNode(Aras.IOM.Item.xPathFault)!=null){$0.dom=$p0;}else{$0.loadAML(Aras.IOM.XmlExtension.getXml($p0));}return $0;},newXMLDocument:function(){return Aras.IOM.InternalUtils.createXmlDocument();},getConnection:function(){return this.$0;},getI18NSessionContext:function(){var $0=this.$0.GetValidateUserXmlResult();if(String.isNullOrEmpty($0)){$0='';}if(Object.keyExists(this.$1,$0)){return this.$1[$0];}var $1;$1=new Aras.IOM.I18NSessionContext($0);this.$1[$0]=$1;return $1;},getNewID:function(){return Aras.IOM.Innovator.$3();},getNextSequence:function(sequenceName){var $0=this.newXMLDocument();Aras.IOM.InternalUtils.loadXmlFromString($0,'');var $1=$0.selectSingleNode('Item/name');if($1!=null){$1.text=sequenceName;}var $2=this.newXMLDocument();this.$0.CallAction('GetNextSequence',$0,$2);var $3=$2.selectSingleNode(Aras.IOM.Item.xPathResult);return ($3==null)?null:$3.text;},newItem:function(itemTypeName,action){if(ss.isNullOrUndefined(action)){if(ss.isNullOrUndefined(itemTypeName)){return Aras.IOM.Item.$0(this.$0,null,null,'full');}else{return Aras.IOM.Item.$0(this.$0,itemTypeName,null,'full');}}return Aras.IOM.Item.$0(this.$0,itemTypeName,action,'full');},getUserID:function(){return this.$0.getUserID();},getItemById:function(itemTypeName,id){if(itemTypeName==null||!itemTypeName.trim().length){throw new Error('Item type must be specified');}if(id==null||!id.trim().length){throw new Error('ID must be specified');}var $0=this.newXMLDocument();var $1=this.newXMLDocument();Aras.IOM.InternalUtils.loadXmlFromString($0,"");Aras.IOM.InternalUtils.loadXmlFromString($1,'');this.$0.CallAction('GetItem',$0,$1);var $2=this.$2($1);return ($2.isError()&&$2.getErrorCode()==='0')?null:$2;},getItemByKeyedName:function(itemTypeName,keyedName){if(itemTypeName==null||!itemTypeName.trim().length){throw new Error('Item type must be specified');}if(keyedName==null||!keyedName.trim().length){throw new Error('Keyed name must be specified');}var $0=this.newXMLDocument();var $1=this.newXMLDocument();Aras.IOM.InternalUtils.loadXmlFromString($0,"");$0.documentElement.selectSingleNode('//keyed_name').text=keyedName;Aras.IOM.InternalUtils.loadXmlFromString($1,'');this.$0.CallAction('GetItem',$0,$1);var $2=this.$2($1);return ($2.isError()&&$2.getErrorCode()==='0')?null:$2;},getUserAliases:function(){var $0=Aras.IOM.Item.$0(this.$0,'Alias',null,'full');$0.setProperty('source_id',this.getUserID(),null);var $1=$0.apply('get');var $2=$1.dom.selectNodes(Aras.IOM.Item.xPathResult+"/Item[@type='Alias']/related_id/Item[@type='Identity']");var $3=new Array($2.length);for(var $4=0;$4<$2.length;$4++){var $5=Aras.IOM.InternalUtils.$0($2[$4],'id');if(!$5){return '';}$3[$4]=$5;}return $3.join(',');},getFileUrl:function(fileId,type){return this.$0.getFileUrl(fileId,type);},getFileUrls:function(fileIds,type){return this.$0.getFileUrls(fileIds,type);},newError:function(explanation){var $0=Aras.IOM.Item.$0(this.$0,'','','full');var $1=Aras.SoapConstants._Soap.$6+'<'+'SOAP-ENV'+':Fault>\r\n\t\t\t1\r\n\t\t\t\r\n\t\t\t'+Aras.SoapConstants._Soap.$7;var $2=$0.dom;Aras.IOM.InternalUtils.loadXmlFromString($2,$1);var $3=$2.selectSingleNode(Aras.SoapConstants._Soap.$F);var $4=$3.appendChild($2.createElement('faultstring'));$4.text=explanation;return $0;},consumeLicense:function(featureName){var $0=new Aras.IOME.Licensing.LicenseManager(this.$0);return $0.consumeLicense(featureName);},newResult:function(text){var $0=Aras.IOM.Item.$24(this.$0);Aras.IOM.InternalUtils.loadXmlFromString($0.dom,Aras.SoapConstants._Soap.$6+''+Aras.SoapConstants._Soap.$7);$0.node=null;$0.nodeList=null;var $1=$0.dom.selectSingleNode('/'+Aras.SoapConstants._Soap.$D+'/Result');$1.text=text;var $2=new XmlDocument();Aras.IOM.InternalUtils.loadXmlFromString($2,Aras.IOM.XmlExtension.getXml($0.dom));return $0;},applySQL:function(sql){var $0=this.newXMLDocument();var $1=this.newXMLDocument();Aras.IOM.InternalUtils.loadXmlFromString($0,'');$0.documentElement.text=sql;Aras.IOM.InternalUtils.loadXmlFromString($1,'');this.$0.CallAction('ApplySQL',$0,$1);return this.$2($1);},getItemInDom:function(dom){if(dom==null){return null;}var $0=dom.selectSingleNode('//Item');if($0==null){return null;}var $1=Aras.IOM.Item.$24(this.$0);Aras.IOM.InternalUtils.loadXmlFromString($1.dom,Aras.IOM.XmlExtension.getXml(dom));$1.node=$1.dom.selectSingleNode('//Item');return $1;},calcMD5:function(val){throw new Error('Not Implemented');},getAssignedActivities:function(state,userId){throw new Error('Not Implemented');}} Aras.IOM.Item=function(serverConnection,itemTypeName,action,mode){if(String.isNullOrEmpty(mode)||String.equals(mode,'simple',StringComparison.ordinalIgnoreCase)){this.dom=null;this.node=null;this.nodeList=null;this.serverConnection=serverConnection;}else{this.dom=this.newXMLDocument();this.node=this.dom.createElement('Item');this.dom.appendChild(this.node);this.node.setAttribute('isNew','1');this.node.setAttribute('isTemp','1');this.nodeList=null;this.serverConnection=serverConnection;if(itemTypeName!=null&&!!itemTypeName.trim().length){this.setType(itemTypeName);if(action!=null&&!!action.trim().length){this.setAction(action);if(String.equals(action,'add',StringComparison.ordinalIgnoreCase)||String.equals(action,'create',StringComparison.ordinalIgnoreCase)){this.setNewID();}}}}this.$27=new Aras.IOM.Innovator(serverConnection);} Aras.IOM.Item.$0=function($p0,$p1,$p2,$p3){if(ss.isNullOrUndefined($p3)){if(ss.isNullOrUndefined($p2)){if(ss.isNullOrUndefined($p1)){return new Aras.IOM.Item($p0,'','','simple');}else{return new Aras.IOM.Item($p0,$p1,'','simple');}}else{return new Aras.IOM.Item($p0,$p1,$p2,'simple');}}return new Aras.IOM.Item($p0,$p1,$p2,$p3);} Aras.IOM.Item.$1C=function($p0){var $0=$p0.getItemsByXPath("Relationships/Item[@type='Located']");if($0.getItemCount()===1){var $1='';$0=$0.getItemByIndex(0);var $2=$0.getPropertyItem('related_id');if($2!=null){$1=$2.getID();if(!$1.trim().length){if($2.getAction()==='get'){$2=$2.apply();if(!$2.isError()){$1=$2.getID();}}}}else{$1=$0.getProperty('related_id');}if(!$1.trim().length){var $3;$3=String.format("Vault ID is not specified in the following AML fragment: '{0}'",Aras.IOM.XmlExtension.getXml($p0.node));throw new Error($3);}return $1;}return null;} Aras.IOM.Item.$22=function($p0,$p1){var $0='';var $1=0;while(Aras.IOM.InternalUtils.$1($p0)!==9){if($p1&&!$1){$0='';}else{$0=String.format('/*[position()={0}]{1}',Aras.IOM.Item.$23($p0),$0);}$1++;$p0=$p0.parentNode;}return $0;} Aras.IOM.Item.$23=function($p0){var $0=0;var $1=$p0.parentNode.selectNodes('./*');var $enum1=ss.IEnumerator.getEnumerator($1);while($enum1.moveNext()){var $2=$enum1.current;if(Aras.IOM.InternalUtils.$1($2)!==1){continue;}$0++;if($2===$p0){break;}}return $0;} Aras.IOM.Item.$24=function($p0){return Aras.IOM.Item.$0($p0,null,null,'full');} Aras.IOM.Item.prototype={newItem:function(itemTypeName,action){if(ss.isNullOrUndefined(action)){if(ss.isNullOrUndefined(itemTypeName)){return Aras.IOM.Item.$0(this.serverConnection,null,null,'full');}else{return Aras.IOM.Item.$0(this.serverConnection,itemTypeName,null,'full');}}return Aras.IOM.Item.$0(this.serverConnection,itemTypeName,action,'full');},newInnovator:function(){return new Aras.IOM.Innovator(this.serverConnection);},serverConnection:null,dom:null,node:null,nodeList:null,loadAML:function(AML){if(this.dom==null){this.dom=new XmlDocument();}try{Aras.IOM.InternalUtils.loadXmlFromString(this.dom,AML);if(!!this.dom.parseError.errorCode){throw new Error('Data at the root level is invalid. '+this.dom.parseError.reason);}}catch($0){this.dom=null;throw $0;}finally{this.$11();}},clone:function(cloneRelationships){if(!this.$12(4)){throw new Error('Not a single item');}var $0=this.newItem(null,null);Aras.IOM.InternalUtils.loadXmlFromString($0.dom,Aras.IOM.XmlExtension.getXml(this.node));$0.node=$0.dom.selectSingleNode('//Item');$0.setNewID();$0.setAction('add');if(!cloneRelationships){var $1=$0.node.selectSingleNode('Relationships');if($1!=null){$1.parentNode.removeChild($1);}}else{var $2=$0.node.selectNodes('.//Relationships/Item');for(var $3=0;$3<$2.length;$3++){($2[$3]).setAttribute('id',this.getNewID());($2[$3]).setAttribute('action','add');}}return $0;},$11:function(){if(this.dom==null){this.node=null;this.nodeList=null;}else{var $0=this.dom.selectNodes('Item|AML/Item|//Result/Item');if(!$0.length){this.node=null;this.nodeList=null;}else if($0.length>1){this.node=null;this.nodeList=$0;}else{this.node=$0[0];this.nodeList=null;}}},$12:function($p0){if(this.dom==null){return false;}if(!!($p0&1)){if(this.node==null||!this.$13(this.node)){return false;}}if(!!($p0&2)){if(this.nodeList==null||!this.nodeList.length){return false;}else{var $enum1=ss.IEnumerator.getEnumerator(this.nodeList);while($enum1.moveNext()){var $0=$enum1.current;if(!this.$13($0)){return false;}}}}if(!!($p0&4)){if(this.node==null||this.node.nodeName!=='Item'){return false;}}if(!!($p0&8)){if(this.nodeList==null||!this.nodeList.length){return false;}else{var $enum2=ss.IEnumerator.getEnumerator(this.nodeList);while($enum2.moveNext()){var $1=$enum2.current;if(!String.equals($1.nodeName,'Item',StringComparison.ordinalIgnoreCase)){return false;}}}}if(!!($p0&16)){if(this.nodeList==null||!this.nodeList.length){return false;}else if(this.nodeList.length>1){var $2=this.nodeList[0].parentNode;for(var $3=1;$30)){var $enum1=ss.IEnumerator.getEnumerator(Object.keys($p1));while($enum1.moveNext()){var $0=$enum1.current;this.setProperty($0,$p1[$0].toString(),null);}}},$15:function($p0,$p1){var $0=this.$1A();var $1=this.$17($0);var $2=this.$19();var $3='';if(this.node!=null){$3=Aras.IOM.XmlExtension.getXml(this.node);}else{for(var $6=0;$6");var $4=$3.apply();if($4.isError()){throw new Error($4.getErrorString());}$0=$4.getProperty('vault_url');}if(String.isNullOrEmpty($0)){throw new Error("Failed to obtain vault URL for vault with ID='"+$p0+"'");}}return $0;},$18:function(){return this.getItemsByXPath('descendant-or-self::Item['+"@type='File' and "+"(@action='add' or @action='create') and "+"actual_filename and Relationships/Item[@type='Located']/related_id]");},$19:function(){var $0=this.$18();var $1={};for(var $2=0;$2<$0.getItemCount();$2++){var $3=$0.getItemByIndex($2);var $4=$3.getItemsByXPath("Relationships/Item[@type='Located']");if($4.getItemCount()>1){var $6;$6=String.format("Ambigious vaults are specified on the file: '{0}'",Aras.IOM.XmlExtension.getXml($3.node));throw new Error($6);}var $5=$3.getProperty('actual_filename');if(!String.isNullOrEmpty($5)){var $7=$5;var $8=new EasyFileInfo(TopWindowHelper.getMostTopWindowWithAras(window).aras.vault);$3.setProperty('checksum',$8.getFileChecksum($7));$3.setProperty('file_size',$8.getFileSize($3.getID()).toString());var $9=$3.getID();if(String.isNullOrEmpty($9)){var $A=$3.getAttribute('action','').trim();var $B;if(!String.equals($A,'add',StringComparison.ordinalIgnoreCase)&&!String.equals($A,'create',StringComparison.ordinalIgnoreCase)){$B=String.format("File ID is not set in the following AML fragment: '{0}'",Aras.IOM.XmlExtension.getXml($3.node));throw new Error($B);}$9=$3.getNewID();$3.setID($9);}$1[$9]=$7;}}return $1;},$1A:function(){var $0=this.$18();var $1=null;for(var $2=0;$2<$0.getItemCount();$2++){var $3=$0.getItemByIndex($2);var $4=Aras.IOM.Item.$1C($3);if($1==null){$1=$4;}else if($1!==$4){throw new Error("Only one Vault Server may be specified in 'Located' for all Files are submitted in the same transaction.");}}return $1;},$1B:function(){var $0=this.node.selectSingleNode('descendant-or-self::Item['+"@type='File' and "+"(@action='add' or @action='create') and "+"actual_filename and Relationships/Item[@type='Located']/related_id]");return ($0!=null);},getAttribute:function(attributeName,defaultValue){if(!this.$12(4)){throw new Error('Not a single item');}if(Aras.IOM.InternalUtils.$2(this.node,attributeName)){return Aras.IOM.InternalUtils.$0(this.node,attributeName);}else{return defaultValue;}},setAttribute:function(attributeName,attributeValue){if(!this.$12(4)){throw new Error('Not a single item');}this.node.setAttribute(attributeName,attributeValue);},removeAttribute:function(attributeName){if(!this.$12(4)){throw new Error('Not a single item');}if(Aras.IOM.InternalUtils.$2(this.node,attributeName)){this.node.removeAttribute(attributeName);}},getAction:function(){if(!this.$12(4)){throw new Error('Not a single item');}return this.getAttribute('action','');},setAction:function(action){if(!this.$12(4)){throw new Error('Not a single item');}this.setAttribute('action',action);},getInnovator:function(){return this.$27;},getID:function(){if(!this.$12(4)){throw new Error('Not a single item');}var $0=this.getAttribute('id','');if(String.isNullOrEmpty($0)){var $1=this.node.selectSingleNode('id');if($1!=null){var $2=null;if(Aras.IOM.InternalUtils.$2($1,'condition')){$2=Aras.IOM.InternalUtils.$0($1,'condition');}if(String.isNullOrEmpty($2)||String.equals($2,'eq',StringComparison.ordinalIgnoreCase)){$0=$1.text.trim();}}}return $0;},setID:function(id){if(!this.$12(4)){throw new Error('Not a single item');}this.setAttribute('id',id);var $0=this.node.selectSingleNode('id');if($0!=null){$0.text=id;}},getType:function(){if(!this.$12(4)){throw new Error('Not a single item');}return this.getAttribute('type','');},setType:function(itemTypeName){if(!this.$12(4)){throw new Error('Not a single item');}this.setAttribute('type',itemTypeName);},getProperty:function(propertyName,defaultValue,lang){if(!this.$12(4)&&!this.$12(32)){throw new Error('Not a single item');}var $0=null;var $1=this.$2A(propertyName,lang);if($1!=null){var $2=$1.selectSingleNode('Item');if($2!=null){var $3=Aras.IOM.Item.$0(this.serverConnection,null,null,null);$3.dom=this.dom;$3.node=$2;$0=$3.getID();if(String.isNullOrEmpty($0)){$0=defaultValue;}}else{$0=$1.text;if(Aras.IOM.InternalUtils.$2($1,'is_null')&&String.isNullOrEmpty($0)&&String.equals(Aras.IOM.InternalUtils.$0($1,'is_null'),'1',StringComparison.ordinalIgnoreCase)){$0=defaultValue;}}}else{$0=defaultValue;}return $0;},setProperty:function(propertyName,propertyValue,lang){if(ss.isNullOrUndefined(lang)){lang=null;}if(!this.$12(4)&&!this.$12(32)){throw new Error('Not a single item');}var $0=this.$2A(propertyName,lang);if($0==null||String.equals(this.node.nodeName,'or',StringComparison.ordinalIgnoreCase)){$0=this.$29(propertyName,lang);}if(lang!=null){$0.setAttribute('xml:lang',lang);}if(propertyValue==null){$0.setAttribute('is_null','1');$0.text='';}else{if(Aras.IOM.InternalUtils.$2($0,'is_null')&&String.equals(Aras.IOM.InternalUtils.$0($0,'is_null'),'1',StringComparison.ordinalIgnoreCase)){$0.removeAttribute('is_null');}$0.text=propertyValue;}},removeProperty:function(propertyName,lang){if(!this.$12(4)&&!this.$12(32)){throw new Error('Not a single item');}var $0=this.$2A(propertyName,lang);if($0!=null){this.node.removeChild($0);}},getPropertyCondition:function(propertyName,lang){if(!this.$12(4)&&!this.$12(32)){throw new Error('Not a single item');}return this.getPropertyAttribute(propertyName,'condition',lang,null);},setPropertyCondition:function(propertyName,condition,lang){this.setPropertyAttribute(propertyName,'condition',condition,lang);},getPropertyAttribute:function(propertyName,attributeName,defaultValue,lang){if(!this.$12(4)&&!this.$12(32)){throw new Error('Not a single item');}var $0=this.$2A(propertyName,lang);if($0==null){return defaultValue;}if(Aras.IOM.InternalUtils.$2($0,attributeName)){return Aras.IOM.InternalUtils.$0($0,attributeName);}else{return defaultValue;}},setPropertyAttribute:function(propertyName,attributeName,attributeValue,lang){if(!this.$12(4)&&!this.$12(32)){throw new Error('Not a single item');}var $0=this.$2A(propertyName,lang);if($0==null){$0=this.$29(propertyName,lang);}$0.setAttribute(attributeName,attributeValue);if(lang!=null){$0.setAttribute('xml:lang',lang);}},removePropertyAttribute:function(propertyName,attributeName,lang){if(!this.$12(4)&&!this.$12(32)){throw new Error('Not a single item');}var $0=this.$2A(propertyName,lang);if($0!=null){$0.removeAttribute(attributeName);}},getPropertyItem:function(propertyName){if(!this.$12(4)&&!this.$12(32)){throw new Error('Not a single item');}if(propertyName==null){throw new Error('propertyName');}if(String.equals(propertyName,'id',StringComparison.ordinalIgnoreCase)){return this;}else{var $0=this.node.selectSingleNode(propertyName);if($0!=null){var $1=$0.selectSingleNode('Item');if($1!=null){var $2=Aras.IOM.Item.$0(this.serverConnection,null,null,null);$2.dom=this.dom;$2.node=$1;return $2;}else{var $3=Aras.IOM.InternalUtils.$0($0,'type');if(!$3.length){return null;}var $4=Aras.IOM.Item.$0(this.serverConnection,null,null,null);$4.dom=new XmlDocument();Aras.IOM.InternalUtils.loadXmlFromString($4.dom,String.format("{1}",$3,$0.text));$4.node=$4.dom.selectSingleNode('Item');return $4;}}return null;}},setPropertyItem:function(propertyName,item){this.$28(propertyName,item,true);return item;},setFileProperty:function(propertyName,pathToFile){if(String.isNullOrEmpty(propertyName)){throw new Error('propertyName');}var fileItem = this.newItem('File', 'add');fileItem.attachPhysicalFile(pathToFile);fileItem.setProperty("filename", pathToFile.name, null);this.setPropertyItem(propertyName, fileItem);return fileItem;return null;},fetchFileProperty:function(propertyName,targetPath,mode){if(String.isNullOrEmpty(propertyName)){throw new Error('propertyName');}if(String.isNullOrEmpty(targetPath)){throw new Error('targetPath');}var $0=this.getPropertyItem(propertyName);if($0!=null){switch(mode){case 0:$0=$0.$26(targetPath,null,1);break;case 1:$0.$25(targetPath,1);break;default:throw new Error('Agrument "mode" is not a part of FetchFileMode enumeration.');}}return $0;},fetchDefaultPropertyValues:function(overwrite_current){if(!this.$12(4)){throw new Error('Not a single item');}var $0=this.$32();var $1=Aras.IOM.Item.$0(this.serverConnection,null,null,'full');var $2=""+' '+$0+''+' '+" "+' '+'';$1.loadAML($2);var $3=$1.apply(null,null);if($3.isError()){return $3;}var $4=$3.dom.selectNodes("//Item[@type='ItemType']/Relationships/Item[@type='Property']");var $enum1=ss.IEnumerator.getEnumerator($4);while($enum1.moveNext()){var $5=$enum1.current;var $6=$5.selectSingleNode('name').text;var $7=$5.selectSingleNode('default_value');var $8=($7==null)?'':$7.text;if($8.length>0&&(overwrite_current||(!overwrite_current&&this.getProperty($6,null,null)==null))){this.setProperty($6,$8,null);}}return this;},getErrorDetail:function(){return this.$1D('detail');},setErrorDetail:function(detail){this.$1E('detail',detail);},getErrorString:function(){return this.$1D('faultstring');},setErrorString:function(errorMessage){this.$1E('faultstring',errorMessage);},getErrorWho:function(){return this.getErrorCode();},getErrorCode:function(){return this.$1D('faultcode');},getFileName:function(){this.$30();return this.getProperty('filename','',null);},setErrorWho:function(who){this.setErrorCode(who);},setErrorCode:function(errcode){this.$1E('faultcode',errcode);},setFileName:function(filePath){this.attachPhysicalFile(filePath);this.setProperty("filename", filePath.name, null);},getErrorSource:function(){return this.$1D('faultactor');},setErrorSource:function(source){this.$1E('faultactor',source);},$1D:function($p0){var $0='';if(this.dom!=null){var $1=this.dom.selectSingleNode(Aras.IOM.Item.xPathFault+'/'+$p0);if($1!=null){$0=$1.text;}}return $0;},$1E:function($p0,$p1){if(this.dom==null){return;}var $0=this.dom.selectSingleNode(Aras.IOM.Item.xPathFault);if($0!=null){var $1=$0.selectSingleNode($p0);if($1==null){$1=$0.appendChild(this.dom.createElement($p0));}$1.text=$p1;}},getResult:function(){var $0='';if(this.dom!=null){var $1=this.dom.selectSingleNode(Aras.IOM.Item.xPathResult);if($1!=null){$0=$1.text;}}return $0;},email:function(emailItem,identityItem){if(emailItem==null){throw new Error('emailItem');}if(identityItem==null){throw new Error('identityItem');}if(!this.$12(4)){throw new Error('Not a single item');}var $0=this.newXMLDocument();var $1=this.newXMLDocument();Aras.IOM.InternalUtils.loadXmlFromString($0,Aras.IOM.XmlExtension.getXml(this.node));Aras.IOM.InternalUtils.loadXmlFromString($1,'');var $2=$0.selectSingleNode('//Item');$2.setAttribute('action','EmailItem');var $3=$2.appendChild($0.createElement('___aras_email_identity_name___'));$3.text=identityItem.getProperty('name');var $4=$2.appendChild($0.createElement('___aras_email_item___'));$4.appendChild(emailItem.node.cloneNode(true));this.serverConnection.CallAction('ApplyItem',$0,$1);if($1.selectSingleNode(Aras.IOM.Item.xPathFault+'/faultcode')!=null){return false;}else{return true;}},isNew:function(){if(!this.$12(4)){return false;}return String.equals(this.getAttribute('isNew',''),'1',StringComparison.ordinalIgnoreCase);},isRoot:function(){if(!this.$12(4)){return false;}var $0=this.node.selectNodes("ancestor::node()[local-name()='Item']");if($0.length>0){return false;}var $1=this.node.parentNode.selectNodes('Item');if($1.length>1){return false;}return true;},isCollection:function(){if(this.isError()){return false;}return (this.nodeList!=null&&this.node==null);},isLocked:function(){if(!this.$12(4)){throw new Error('Not a single item');}if(this.isNew()){return 0;}var $0='';if(!this.$2B('locked_by_id')){var $1=this.newItem(this.getType(),'get');$1.setAttribute('select','locked_by_id');$1.setID(this.getID());$1=$1.apply(null,null);if($1.isError()){throw new Error('Server returns fault in internal query');}if(!$1.$12(4)){throw new Error('Not a single item');}$0=$1.getProperty('locked_by_id','',null);}else{$0=this.getProperty('locked_by_id','',null);}if(String.isNullOrEmpty($0)){return 0;}else if(String.equals($0,this.serverConnection.getUserID(),StringComparison.ordinalIgnoreCase)){return 1;}else{return 2;}},fetchLockStatus:function(){var $0=this.$31();var $1=this.$32();var $2=this.newItem($1,'get');$2.setAttribute('select','locked_by_id');$2.setID($0);var $3=$2.apply();if($3.isError()){return -1;}var $4=$3.getProperty('locked_by_id','');this.setProperty('locked_by_id',$4);if(String.isNullOrEmpty($4)){return 0;}else if($4===this.serverConnection.getUserID()){return 1;}else{return 2;}},getLockStatus:function(){if(!this.$12(4)){throw new Error('Not a single item');}if(this.isNew()){return 0;}var $0=this.getProperty('locked_by_id','',null);if(!$0.length){return 0;}else if($0===this.serverConnection.getUserID()){return 1;}else{return 2;}},isError:function(){return (this.dom!=null&&this.dom.selectSingleNode(Aras.IOM.Item.xPathFault)!=null);},isEmpty:function(){if(this.isError()){return String.equals(this.getErrorCode(),'0',StringComparison.ordinalIgnoreCase);}else{return false;}},appendItem:function(item){if(item==null){throw new Error(String.format(Aras.IOM.Item.$6,"'this' item"));}var $0;if(this.node!=null){if(!this.$12(4|1)){throw new Error(String.format(Aras.IOM.Item.$6,"'this' item"));}if(item.node!=null){if(!item.$12(4)){throw new Error('The argument passed to the method is not a single item');}$0=this.$1F();$0.add(this.$21(item.node));}else if(item.nodeList!=null){if(!item.$12(8)){throw new Error("Not all elements of the passed item's nodeList are <Item> nodes");}$0=this.$1F();var $enum1=ss.IEnumerator.getEnumerator(item.nodeList);while($enum1.moveNext()){var $2=$enum1.current;$0.add(this.$21($2));}}else{throw new Error(String.format(Aras.IOM.Item.$6,'passed item'));}}else if(this.nodeList!=null){if(!this.$12(8|2)){throw new Error(String.format(Aras.IOM.Item.$6,"'this' item"));}if(!this.$12(16)){throw new Error("Not all nodes of 'this.nodeList' are siblings");}$0=[];this.$20($0);if(item.node!=null){if(!item.$12(4)){throw new Error('The argument passed to the method is not a single item');}$0.add(this.$21(item.node));}else if(item.nodeList!=null){if(!item.$12(8)){throw new Error("Not all elements of the passed item's nodeList are <Item> nodes");}var $enum2=ss.IEnumerator.getEnumerator(item.nodeList);while($enum2.moveNext()){var $3=$enum2.current;$0.add(this.$21($3));}}else{throw new Error(String.format(Aras.IOM.Item.$6,'passed item'));}}else{throw new Error(String.format(Aras.IOM.Item.$6,"'this' item"));}var $1='';var $enum3=ss.IEnumerator.getEnumerator($0);while($enum3.moveNext()){var $4=$enum3.current;if(String.isNullOrEmpty($1)){$1=Aras.IOM.Item.$22($4,true);$1=String.format('{0}/*[position()={1}',$1,Aras.IOM.Item.$23($4));}else{$1=String.format('{0} or position()={1}',$1,Aras.IOM.Item.$23($4));}}$1+=']';this.nodeList=this.dom.selectNodes($1);},removeItem:function(item){if(!this.$12(2|8)){throw new Error('Not a collection of items');}if(item==null){throw new Error('item');}if(this.dom!==item.dom){throw new Error(String.format("{0} and {1} must reference the same ArasXmlDocument through their 'dom' property","'this' item",'item passed to the method'));}var $0=[];if(item.$12(4)){var $2=item.node.selectNodes('descendant-or-self::Item');var $enum1=ss.IEnumerator.getEnumerator($2);while($enum1.moveNext()){var $3=$enum1.current;$0.add($3);}}else if(item.$12(8)){var $enum2=ss.IEnumerator.getEnumerator(item.nodeList);while($enum2.moveNext()){var $4=$enum2.current;var $5=$4.selectNodes('descendant-or-self::Item');var $enum3=ss.IEnumerator.getEnumerator($5);while($enum3.moveNext()){var $6=$enum3.current;if(!$0.contains($6)){$0.add($6);}}}}else{throw new Error(String.format(Aras.IOM.Item.$6,'item passed to the method'));}for(var $7=0;$7<$0.length;$7++){var $8=$0[$7];if(this.node!=null&&$8===this.node){this.node=null;break;}}var $1='';var $enum4=ss.IEnumerator.getEnumerator(this.nodeList);while($enum4.moveNext()){var $9=$enum4.current;if(!$0.contains($9)){if(String.isNullOrEmpty($1)){$1=Aras.IOM.Item.$22($9,true);$1=String.format('{0}/*[position()={1}',$1,Aras.IOM.Item.$23($9));}else{$1=String.format('{0} or position()={1}',$1,Aras.IOM.Item.$23($9));}}}$1+=']';if($1.length>0){var $A=this.dom.selectNodes($1);if($A.length===1){this.node=$A[0];this.nodeList=null;}else{this.nodeList=$A;var $B=this.nodeList.length;}}else{this.nodeList=null;}for(var $C=0;$C<$0.length;$C++){var $D=$0[$C];$D.parentNode.removeChild($D);}},getItemsByXPath:function(xpath){if(this.dom==null){throw new Error(String.format(Aras.IOM.Item.$6,"'this' item"));}var $0;if(this.node!=null){$0=this.node.selectNodes(xpath);}else{$0=this.dom.selectNodes(xpath);}var $1=Aras.IOM.Item.$0(this.serverConnection,null,null,null);$1.dom=this.dom;var $2=true;if($0.length===1){$1.node=$0[0];if(!$1.$12(4)){$2=false;}}else{$1.nodeList=$0;if($1.nodeList.length>0&&!$1.$12(8)){$2=false;}}if(!$2){throw new Error(String.format("Specified XPath '{0}' doesn't resolve to <Item> nodes",xpath));}return $1;},getItemCount:function(){if(this.dom==null){return -1;}if(this.nodeList!=null){return this.nodeList.length;}if(this.isError()){if(this.getErrorCode()==='0'){return 0;}else{return -1;}}else if(this.node==null){return -1;}else{return 1;}},getItemByIndex:function(index){if(this.nodeList==null){if(!!index){throw new Error('Item is not a collection');}else{return this;}}else{if(index>this.nodeList.length-1||index<0){throw new Error('IndexOutOfRangeException');}var $0=Aras.IOM.Item.$0(this.serverConnection,null,null,null);$0.dom=this.dom;$0.node=this.nodeList[index];return $0;}},lockItem:function(){var $0=this.$31();var $1=this.$32();var $2=this.newItem($1,'lock');$2.setID($0);var $3=$2.apply();if(!$3.isError()){this.setProperty('locked_by_id',$3.getProperty('locked_by_id',''));}return $3;},unlockItem:function(){var $0=this.$31();var $1=this.$32();var $2=this.newItem($1,'unlock');$2.setID($0);var $3=$2.apply();if(!$3.isError()){this.removeProperty('locked_by_id');}return $3;},fetchRelationships:function(relationshipTypeName,selectList,orderBy){if(!this.$12(4)){throw new Error('Not a single item');}var $0=this.getID();if(String.isNullOrEmpty($0)){throw new Error('ID is not set');}if(relationshipTypeName==null||!relationshipTypeName.trim().length){throw new Error('Relationship type is not specified');}var $1=""+$0+'';var $2=this.newItem(null,null);$2.loadAML($1);if(selectList!=null&&selectList.trim().length>0){$2.setAttribute('select',selectList);}if(orderBy!=null&&orderBy.trim().length>0){$2.setAttribute('order_by',orderBy);}var $3=$2.apply();if($3.isError()){if($3.getErrorCode()!=='0'){return $3;}}else{var $4=this.node.selectNodes("Relationships/Item[@type='"+relationshipTypeName+"']");if($4!=null){var $enum1=ss.IEnumerator.getEnumerator($4);while($enum1.moveNext()){var $5=$enum1.current;if(this.nodeList==null){$5.parentNode.removeChild($5);}else{var $6=Aras.IOM.Item.$0(this.serverConnection,null,null,null);$6.dom=this.dom;$6.node=$5;this.removeItem($6);}}}if(!$3.isCollection()){this.addRelationship($3);}else{for(var $7=0;$7<$3.getItemCount();$7++){this.addRelationship($3.getItemByIndex($7));}}}return this;},getRelatedItem:function(){if(!this.$12(4)){throw new Error('Not a single item');}var $0=this.node.selectSingleNode('related_id');if($0!=null){var $1=$0.selectSingleNode('Item');if($1!=null){var $2=Aras.IOM.Item.$0(this.serverConnection,null,null,null);$2.dom=this.dom;$2.node=$1;return $2;}else{var $3=Aras.IOM.InternalUtils.$0($0,'type');if(!$3.length){return null;}var $4=Aras.IOM.Item.$0(this.serverConnection,null,null,null);$4.dom=new XmlDocument();Aras.IOM.InternalUtils.loadXmlFromString($4.dom,String.format("{1}",$3,$0.text));$4.node=$4.dom.selectSingleNode('Item');return $4;}}else{return null;}},setRelatedItem:function(ritem){this.$28('related_id',ritem,false);},addRelationship:function(item){if(!this.$12(4)){throw new Error('Not a single item');}if(item==null){throw new Error(String.format(Aras.IOM.Item.$6,"'this' item"));}if(!item.$12(4)){throw new Error('The argument passed to the method is not a single item');}var $0=this.node.selectSingleNode('Relationships');if($0==null){$0=this.node.appendChild(this.dom.createElement('Relationships'));}item.node=$0.appendChild(item.node.cloneNode(true));item.dom=this.dom;},getRelationships:function(itemTypeName){if(!this.$12(4)){throw new Error('Not a single item');}var $0=null;if(itemTypeName==null){$0=this.node.selectNodes('Relationships/Item');}else{$0=this.node.selectNodes("Relationships/Item[@type='"+itemTypeName+"']");}var $1=Aras.IOM.Item.$0(this.serverConnection,null,null,null);$1.dom=this.dom;$1.node=null;$1.nodeList=$0;return $1;},removeRelationship:function(item){if(!this.$12(4)){throw new Error('Not a single item');}if(item==null){throw new Error('item');}if(!item.$12(4)){throw new Error('The argument passed to the method is not a single item');}if(this.dom!==item.dom){throw new Error(String.format("{0} and {1} must reference the same ArasXmlDocument through their 'dom' property","'this' item",'item passed to the method'));}var $0=item.node.parentNode;if(String.equals($0.nodeName,'Relationships',StringComparison.ordinalIgnoreCase)){if(this.nodeList==null){$0.removeChild(item.node);}else{this.removeItem(item);}}else{throw new Error('The item pased to the method is not a relationship item.');}},getRelatedItemID:function(){var $0='';if(!this.$12(4)){throw new Error('Not a single item');}var $1=this.node.selectSingleNode('related_id');if($1!=null){var $2=$1.selectSingleNode('Item');if($2!=null){$0=Aras.IOM.InternalUtils.$0($2,'id');if(String.isNullOrEmpty($0)){$2=$2.selectSingleNode('id');if($2!=null){$0=$2.text;}}return $0;}else{$0=$1.text;}}return $0;},getParentItem:function(){if(!this.$12(4)){throw new Error('Not a single item');}var $0=this.node.selectSingleNode('ancestor::Item');if($0==null){return null;}var $1=Aras.IOM.Item.$0(this.serverConnection,null,null,null);$1.dom=this.dom;$1.node=$0;return $1;},isLogical:function(){return this.$12(32);},newAND:function(){if(!this.$12(4)&&!this.$12(32)){throw new Error('Not a single item');}var $0=Aras.IOM.Item.$0(this.serverConnection,null,null,null);$0.dom=this.dom;$0.node=this.node.appendChild(this.dom.createElement('and'));return $0;},newOR:function(){if(!this.$12(4)&&!this.$12(32)){throw new Error('Not a single item');}var $0=Aras.IOM.Item.$0(this.serverConnection,null,null,null);$0.dom=this.dom;$0.node=this.node.appendChild(this.dom.createElement('or'));return $0;},newNOT:function(){if(!this.$12(4)&&!this.$12(32)){throw new Error('Not a single item');}var $0=Aras.IOM.Item.$0(this.serverConnection,null,null,null);$0.dom=this.dom;$0.node=this.node.appendChild(this.dom.createElement('not'));return $0;},removeLogical:function(logicalItem){if(!this.$12(4)&&!this.$12(32)){throw new Error('Not a single item');}if(logicalItem==null){throw new Error('logicalItem');}if(!logicalItem.$12(32)){throw new Error('Passed item is not a logical item');}this.node.removeChild(logicalItem.node);},promote:function(state,comments){if(!this.$12(4)){throw new Error('Not a single item');}if(state==null||!state.trim().length){throw new Error("'state' is either 'null' or an empty string");}var $0=this.newItem(null,null);$0.loadAML(Aras.IOM.XmlExtension.getXml(this.node));$0.setProperty('state',state,null);if(comments!=null&&comments.trim().length>0){$0.setProperty('comments',comments,null);}return $0.apply('promoteItem');},$1F:function(){var $0=[];var $1=this.node.parentNode;if(Aras.IOM.InternalUtils.$1($1)===9){if(this.nodeList!=null&&(this.nodeList.length>1||this.nodeList.length===1&&this.nodeList[0]!==this.node)){throw new Error("'this.node' is not sibling to items in 'this.nodeList'");}Aras.IOM.InternalUtils.loadXmlFromString(this.dom,String.format('{0}',Aras.IOM.XmlExtension.getXml(this.dom)));this.nodeList=this.dom.selectNodes('/AML/Item');this.node=null;this.$20($0);}else{if(this.nodeList!=null){var $enum1=ss.IEnumerator.getEnumerator(this.nodeList);while($enum1.moveNext()){var $2=$enum1.current;if($2.nodeName!=='Item'){throw new Error(String.format("The following element of 'this.nodeList' is not an 'Item': {0}",Aras.IOM.XmlExtension.getXml($2)));}if($2.parentNode!==$1){throw new Error("'this.node' is not sibling to items in 'this.nodeList'");}}this.$20($0);this.node=null;}else{var $3=Aras.IOM.Item.$22(this.node,false);this.nodeList=this.dom.selectNodes($3);this.node=null;this.$20($0);}}return $0;},$20:function($p0){if(this.node!=null){$p0.add(this.node);}if(this.nodeList!=null){var $enum1=ss.IEnumerator.getEnumerator(this.nodeList);while($enum1.moveNext()){var $0=$enum1.current;$p0.add($0);}}},$21:function($p0){var $0=this.nodeList[0].parentNode;return $0.appendChild($p0.cloneNode(true));},checkout:function(dir){return this.$26(dir,null,0);},$25:function($p0,$p1){if(!this.$12(4)){throw new Error('Not a single item');}this.$30();this.$31();if(this.isNew()){throw new Error("The file was never stored on server ('isNew=1')");}var $0=this.getProperty('filename');if(String.isNullOrEmpty($0)){var $2=this.newItem('File','get');$2.setID(this.getID());$2.setAttribute('select','filename');var $3=$2.apply();if($3.isError()){throw new Error($3.getErrorString());}$0=$3.getProperty('filename');this.setProperty('filename',$0,null);}var $1=(!$p1)||String.isNullOrEmpty(Path.getFileName($p0));if($1){var $4=Path.combinePath($p0,$0);this.setProperty('checkedout_path',$4,null);return $4;}else{this.setProperty('checkedout_path',$p0,null);return $p0;}},$26:function($p0,$p1,$p2){var $0=this.$25($p0,$p2);var $1=Type.safeCast(this.serverConnection,Aras.IOM.ServerConnectionBase);if($1!=null){$1.$8(this,$0,true,$p1);}else{this.serverConnection.DownloadFile(this,$0,true);}return this;},setNewID:function(){this.setID(this.getNewID());},getNewID:function(){return Aras.IOM.Innovator.$3();},$27:null,$28:function($p0,$p1,$p2){if(!this.$12(4)&&($p2&&!this.$12(32))){throw new Error('Not a single item');}if(!this.$12(1)){throw new Error(String.format(Aras.IOM.Item.$6,"'this' item"));}if(!$p1.$12(4)){throw new Error('The argument passed to the method is not a single item');}var $0=this.node.selectSingleNode($p0);if($0==null){$0=this.node.appendChild(this.dom.createElement($p0));}var $1=$0.selectSingleNode('Item');if($1!=null){$p1.node=$p1.node.cloneNode(true);$0.replaceChild($p1.node,$1);}else{$0.text='';$p1.node=$0.appendChild($p1.node.cloneNode(true));}$p1.dom=this.dom;},$29:function($p0,$p1){var $0;if($p1!=null){var $2=this.$27.getI18NSessionContext();if($2!=null&&$p1!==$2.GetLanguageCode()){$0=this.dom.createNode(1,'i18n'+':'+$p0,'http://www.aras.com/I18N');}else{$0=this.dom.createElement($p0);}}else{$0=this.dom.createElement($p0);}var $1=this.node.appendChild($0);return $1;},$2A:function($p0,$p1){var $0;$0=String.format('./{0}',$p0);if($p1!=null){var $2=this.$27.getI18NSessionContext();if($2!=null){$0=String.format(($2.GetLanguageCode()===$p1)?"./*[local-name()='{0}' and (namespace-uri()='{1}' or name()='{0}') and @xml:lang='{2}']":"./*[local-name()='{0}' and namespace-uri()='{1}' and @xml:lang='{2}']",$p0,'http://www.aras.com/I18N',$p1);}}var $1;$1=this.node.selectSingleNode($0);return $1;},$2B:function($p0){if(!this.$12(4)){throw new Error('Not a single item');}if(String.equals($p0,'id',StringComparison.ordinalIgnoreCase)){return true;}return (this.node.selectSingleNode($p0)!=null);},getLogicalChildren:function(){if(!this.$12(4)&&!this.$12(32)){throw new Error('Not a single item');}var $0=Aras.IOM.Item.$0(this.serverConnection,null,null,null);$0.dom=this.dom;$0.node=null;$0.nodeList=this.node.selectNodes("./*[local-name()='and' or local-name()='or' or local-name()='not']");return $0;},instantiateWorkflow:function(workflowMapID){if(workflowMapID==null||!workflowMapID.trim().length){throw new Error(Aras.IOM.Item.$2);}if(!this.$12(4)){throw new Error('Not a single item');}if(this.isNew()){throw new Error(Aras.IOM.Item.$3);}var $0=this.$31();var $1=this.newItem(this.getType(),null);$1.setAction(Aras.IOM.Item.$4);$1.setID($0);$1.setProperty('WorkflowMap',workflowMapID,null);var $2=$1.apply(Aras.IOM.Item.$4);if($2.isError()){return $2;}var $3=$2;$1=this.newItem('Workflow','add');$1.setProperty('locked_by_id',this.serverConnection.getUserID(),null);$1.setProperty('source_id',$0,null);$1.setProperty('related_id',$3.getID(),null);$1.setProperty('source_type',this.getAttribute('typeId'),null);$2=$1.apply();return ($2.isError())?$2:$3;},toString:function(){return Aras.IOM.XmlExtension.getXml(this.dom);},$2C:null,setThisMethodImplementation:function(thisMethodImplemenation){this.$2C=thisMethodImplemenation;},thisMethod:function(inDom,inArgs){if(this.$2C==null){return null;}return this.$2C.call(this,inDom,inArgs);},createRelationship:function(type,action){return this.$2D('Relationships',type,action,false);},createPropertyItem:function(propName,type,action){return this.$2D(propName,type,action,true);},createRelatedItem:function(type,action){return this.$2D('related_id',type,action,true);},$2D:function($p0,$p1,$p2,$p3){if(!this.$12(4)){throw new Error('Not a single item');}if(!this.$12(1)){throw new Error(String.format(Aras.IOM.Item.$6,"'this' item"));}var $0=this.node.selectSingleNode($p0)||this.node.appendChild(this.dom.createElement($p0));var $1;if($p3){$1=$0.selectSingleNode('Item');if($1!=null){$0.removeChild($1);}}$1=$0.appendChild(this.dom.createElement('Item'));$1.setAttribute('isNew','1');$1.setAttribute('isTemp','1');$1.setAttribute('type',$p1);$1.setAttribute('action',$p2);var $2=Aras.IOM.Item.$0(this.serverConnection,null,null,null);$2.dom=this.dom;$2.node=$1;return $2;},$2E:function(){var $0=this.$16();if($0.isError()){throw new Error($0.getErrorDetail());}return $0.getProperty('default_vault');},attachPhysicalFile:function(filePath,vaultServerId){this.$2F(filePath,vaultServerId);},$2F:function($p0,$p1){if(ss.isNullOrUndefined($p1)){$p1=this.$2E();}if(!this.$12(4)){throw new Error('Not a single item');}this.$30();this.$31();if($p1==null||!$p1.trim().length){throw new Error('Specified vault ID is not valid');}aras.vault.addFileToList(this.getID(), arguments[0]);this.setProperty("actual_filename", arguments[0].name, null);var $0=this.node;var $1=$0.selectSingleNode('Relationships');if($1==null){$1=$0.appendChild(this.dom.createElement('Relationships'));}else{var $4=$1.selectNodes("Item[@type='Located' and related_id!='"+$p1+"']");if($4!=null){var $enum1=ss.IEnumerator.getEnumerator($4);while($enum1.moveNext()){var $5=$enum1.current;$1.removeChild($5);}}}var $2=$1.selectSingleNode("Item[@type='Located' and related_id='"+$p1+"']");if($2==null){$2=$1.appendChild(this.dom.createElement('Item'));$2.setAttribute('type','Located');}else{var $6=$2.selectSingleNode('file_version');if($6!=null){$2.removeChild($6);}}if(!Aras.IOM.InternalUtils.$0($2,'action').length){if(Aras.IOM.InternalUtils.$0($0,'action')==='add'){$2.setAttribute('action','add');}else{$2.setAttribute('action','merge');}}if(!Aras.IOM.InternalUtils.$0($2,'id').length&&!Aras.IOM.InternalUtils.$0($2,'where').length){$2.setAttribute('where',"related_id='"+$p1+"'");}var $3=$2.appendChild(this.dom.createElement('related_id'));$3.text=$p1;},$30:function(){var $0=this.$32();if('File'!==$0){throw new Error("The item is not of type 'File'");}return $0;},$31:function(){var $0=this.getID();if(String.isNullOrEmpty($0)){throw new Error('Item ID is not set');}return $0;},$32:function(){var $0=this.getType();if(String.isNullOrEmpty($0)){throw new Error('Item type is not set');}return $0;},getId:function(){return this.getID();},applyStylesheet:function(xslStylesheet,type){if(type==null){throw new Error('type');}var $0=new XmlDocument();var $1=type.trim().toLowerCase();if($1==='url'){var $3=xslStylesheet;$0.load($3);if($0.xml==null||!$0.xml){$0.loadUrl($3);}}else if($1==='text'){Aras.IOM.InternalUtils.loadXmlFromString($0,xslStylesheet);}var $2;$2=new XmlDocument();Aras.IOM.InternalUtils.loadXmlFromString($2,this.dom.xml);return $2.transformNode($0);}} Aras.IOM.InnovatorServerConnector=function(parentArasObj){Aras.IOM.InnovatorServerConnector.initializeBase(this);this.$C=parentArasObj;if(ss.isNullOrUndefined(this.$C)){this.$C=window.aras || parent.aras || parent.parent.aras;}} Aras.IOM.InnovatorServerConnector.createConnection=function(loginName,md5Password){var $0=new Aras.IOM.InnovatorServerConnector(null);$0.loginWithCredentials(loginName,md5Password);return $0;} Aras.IOM.InnovatorServerConnector.prototype={$C:null,getDatabases:function(){var $0=this.$C.XmlHttpRequestManager.CreateRequest();var $1=this.$C.getServerBaseURL();$0.open('GET',$1+'DBList.aspx',false);$0.send(null);var $2=new XmlDocument();Aras.IOM.InternalUtils.loadXmlFromString($2,$0.responseText);var $3=$2.selectNodes('DBList/DB/@id');var $4=new Array($3.length);for(var $5=0;$5<$3.length;$5++){$4[$5]=$3[$5].text;}return $4;},CallAction:function(actionName,inDOM,outDOM){var $0=null;var $1=inDOM.documentElement;if($1.nodeName==='Item'){var $2=$1.getAttribute('action');if($2==='purge'||$2==='delete'||$2==='update'||$2==='version'||$2==='add'){var iomCache = new IOMCache(this.$C);$0=iomCache.apply($1);;}}if($0!=null){Aras.IOM.InternalUtils.loadXmlFromString(outDOM,''+$0.xml+'');}else{var res = this.$C.soapSend(actionName, inDOM.xml);var $3=res.getResponseText();Aras.IOM.InternalUtils.loadXmlFromString(outDOM,$3);}},debugLog:function(reason,msg){throw new Error('NotImplementedException');},debugLogP:function(){throw new Error('NotImplementedException');},getUserID:function(){var $0=this.$C.getUserID();if(ss.isNullOrUndefined($0)){throw new Error('Not logged in');}return $0;},getDatabaseName:function(){return this.$C.getDatabase();},getLicenseInfo:function(issuer,addon_name){var $0=new XmlDocument();var $1=new XmlDocument();Aras.IOM.InternalUtils.loadXmlFromString($0,'');if(!String.isNullOrEmpty(issuer)){var $6=$0.createElement('issuer');$6.text=issuer;$0.documentElement.appendChild($6);}if(String.isNullOrEmpty(addon_name)){var $7=$0.createElement('keyed_name');$7.text=addon_name;$0.documentElement.appendChild($7);}var $2=this.$C.getServerBaseURL();var $3=this.$C.soapSend('GetLicenseInfo', $0.xml, $2+'License.aspx', null, null, null, null, true);var $4=$3.getResponseText();Aras.IOM.InternalUtils.loadXmlFromString($1,$4);var $5=$1.selectSingleNode('//Result/*');if($5==null||!$5.xml){return null;}else{return $5.xml;}},getOperatingParameter:function(name,defaultvalue){throw new Error('NotImplementedException');},getSrvContext:function(){throw new Error('NotImplementedException');},GetValidateUserXmlResult:function(){return this.$C.getCommonPropertyValue('ValidateUserXmlResult');},getUserInfo:function(){var $0=this.$C.IomFactory;var $1=this.getUserID();var $2=this.$C.MetadataCache.CreateCacheKey('getUserInfo', $1);var $3=this.$C.MetadataCache.GetItem($2);if($3==null){var $4=Aras.IOM.InnovatorServerConnector.callBaseMethod(this, 'getUserInfo');$3=$0.CreateCacheableContainer($4,$1);this.$C.MetadataCache.SetItem($2, $3);}return $3.Content();},getFileUrl:function(fileId,type){var $0=Aras.IOM.InnovatorServerConnector.callBaseMethod(this, 'getFileUrl',[fileId,0]);if(type===1){var $1=new AuthenticationBrokerClient();var $2=$1.GetFileDownloadToken(fileId);$0+='&token='+$2;}return $0;},getFileUrls:function(fileIds,type){var $0=Aras.IOM.InnovatorServerConnector.callBaseMethod(this, 'getFileUrls',[fileIds,0]);if(type===1){var $1=new AuthenticationBrokerClient();var $2=$1.GetFilesDownloadTokens(fileIds);for(var $3=0;$3$2){$2=$6;}}var $4=this.$5($p0,$0);for($3=0;$3<$4.length;$3++){var $7=$4[$3];var $8=parseInt($7.getProperty('file_version'));if($8===$2){return $7.getRelatedItem();}}return null;},$5:function($p0,$p1){var $0=$p1.getItemCount();var $1=0;var $2=[];var $3=this.getUserInfo();if($3.isError()){throw new Error('Error getting user info: '+$3.toString());}var $4=$3.getRelationships('ReadPriority');var $5=$4.getItemCount();for($1=0;$1<$5;$1++){var $8=$4.getItemByIndex($1).getRelatedItem();for(var $9=0;$9<$0;$9++){var $A=$p1.getItemByIndex($9);if($8.getID()===$A.getRelatedItem().getID()){$2.add($A);break;}}}var $6=false;var $7=$3.getPropertyItem('default_vault');for($1=0;$1<$2.length;$1++){if($2[$1].getRelatedItem().getID()===$7.getID()){$6=true;break;}}if(!$6){for($1=0;$1<$0;$1++){var $B=$p1.getItemByIndex($1);if($7.getID()===$B.getRelatedItem().getID()){$2.add($B);break;}}}for($1=0;$1<$0;$1++){var $C=$p1.getItemByIndex($1);var $D=false;for(var $E=0;$E<$2.length;$E++){if($2[$E].getID()===$C.getID()){$D=true;break;}}if(!$D){$2.add($C);}}return $2;},$6:function($p0,$p1){var $0=$p1.getProperty('vault_url');if(String.isNullOrEmpty($0)){return null;}$0=this.$7($0);if($0==null){return null;}var $1=$p1.getID();var $2;var $3=String.format('{0}?dbName={1}&fileId={2}&fileName={3}&vaultId={4}',$0,this.GetDatabaseName(),$p0.getID(),HttpUtility.urlEncode($p0.getProperty('filename')),$1);$2=$3;return $2;},$7:function($p0){var $0=$p0;if($p0.indexOf('$[')!==-1){var $1=new XmlDocument();var $2=new XmlDocument();Aras.IOM.InternalUtils.loadXmlFromString($1,''+$p0+'');Aras.IOM.InternalUtils.loadXmlFromString($2,'');this.CallAction('TransformVaultServerURL',$1,$2);if($2.selectSingleNode(Aras.IOM.Item.xPathFault)==null){$0=$2.selectSingleNode(Aras.IOM.Item.xPathResult).text;}}return $0;},DownloadFile:function(fileItem,fileName,overwrite){this.$8(fileItem,fileName,overwrite,null);},$8:function($p0,$p1,$p2,$p3){var $0=$p0.getID();if($p0.getAttribute('__aras_file_has_all_located__')!=='1'){var $5=Aras.IOM.Item.$0(this,'File',null,'full');$5.loadAML(""+''+""+''+""+''+''+''+''+'');$5.setID($0);var $6=$5.apply();if($6.isError()){throw new Error('Error getting file: '+$6.getErrorString());}$p0=$6;}else{$p0.removeAttribute('__aras_file_has_all_located__');}var $1=this.$4($p0);if($1==null){throw new Error('Vault location of the file is unknown');}var $2=this.$6($p0,$1);var $3=this.$A(null);$3.add(new Aras.Utils.HeaderClientData('VAULTID',$1.getID()));if($p3!=null&&$p3.$0===$1.getID()){$3.add(new Aras.Utils.HeaderClientData('TRANSACTIONID',$p3.id));}var $4=this.getFileUrl($0,1);$4+='&contentDispositionAttachment=1';TopWindowHelper.getMostTopWindowWithAras(window).ArasModules.vault._downloadHelper($4, false); return;FileDownload.downloadFile($2,$p1,$3,null);},getUserInfo:function(){if(this.cachedUserInfo!=null){return this.cachedUserInfo;}var $0=Aras.IOM.Item.$0(this,'User',null,'full');var $1=this.getUserID();var $2=""+$1+''+"";$0.loadAML($2);$0=$0.apply();if($0.isError()){$2=""+$1+'';$0.loadAML($2);$0=$0.apply();}this.cachedUserInfo=$0;return $0;},GetFromCache:function(key){throw new Error('Not Implemented');},InsertIntoCache:function(key,value,path){throw new Error('Not Implemented');},getFileUrl:function(fileId,type){if(fileId==null){throw new Error('fileId');}return this.$9([fileId])[0];},getFileUrls:function(fileIds,type){if(fileIds==null){throw new Error('fileIds');}if(!fileIds.length){throw new Error('List cannot be empty. Parameter name: fileIds');}if(!!type){throw new Error(type.toString());}var $0=new Array(fileIds.length);for(var $2=0;$2"+''+""+''+""+''+''+''+''+'');var $1=null;for(var $4=0;$4<$p0.length;$4++){var $5=$p0[$4];if($1==null){$1=$5;}else{$1+=','+$5;}}$0.setProperty('id',$1,null);$0.setPropertyCondition('id','in',null);var $2=$0.apply();if($2.isError()){throw new Error('Error getting files: '+$2.getErrorString());}var $3=new Array($p0.length);for(var $6=0;$6<$p0.length;$6++){var $7=$2.getItemsByXPath(Aras.IOM.Item.xPathResult+'/Item[id="'+$p0[$6]+'"]');var $8=this.$4($7);if($8==null){throw new Error('Vault location of the file is unknown');}$3[$6]=this.$6($7,$8);}return $3;},$A:function($p0){var $0=[];if(!String.isNullOrEmpty($p0)){$0.add(new Aras.Utils.HeaderClientData('SOAPACTION',$p0));}$0.add(new Aras.Utils.HeaderClientData('DATABASE',this.GetDatabaseName()));$0.add(new Aras.Utils.HeaderClientData('AUTHUSER',this.get_userName()));$0.add(new Aras.Utils.HeaderClientData('AUTHPASSWORD',this.get_userPassword()));$0.add(new Aras.Utils.HeaderClientData('LOCALE',this.get_locale()));$0.add(new Aras.Utils.HeaderClientData('TIMEZONE_NAME',this.get_timeZoneName()));return $0;},$B:function($p0,$p1,$p2,$p3,$p4,$p5){var $0=this.$A($p0);if(!ss.isNullOrUndefined($p4)){$0.add(new Aras.Utils.HeaderClientData('VAULTID',$p4));}if(!ss.isNullOrUndefined($p5)){$0.add(new Aras.Utils.HeaderClientData('TRANSACTIONID',$p5.id));}var $1;$1=String.format('{0}{1}{2}',Aras.SoapConstants._Soap.$6,$p2,Aras.SoapConstants._Soap.$7);$0.add(new Aras.Utils.HeaderClientData('XMLdata',$1));$p3=this.$7($p3);var $2=new FileUpload(TopWindowHelper.getMostTopWindowWithAras(window).aras,$p3);var $3=$2.uploadFiles($p1,$0);return $3;}} Aras.IOM.IOMScriptSharp$6=function(innovatorServerUrl){Aras.IOM.IOMScriptSharp$6.initializeBase(this,[innovatorServerUrl,'','','','','']);} Aras.IOM.IOMScriptSharp$6.prototype={getUserID:function(){throw new Error('Operation not supported, create new instance of Aras.IOM.HttpServerConnection and specify db name, login and password');},GetDatabaseName:function(){throw new Error('Operation not supported, create new instance of Aras.IOM.HttpServerConnection and specify db name, login and password');},GetValidateUserXmlResult:function(){throw new Error('Operation not supported, create new instance of Aras.IOM.HttpServerConnection and specify db name, login and password');},Login:function(){throw new Error('Operation not supported, create new instance of Aras.IOM.HttpServerConnection and specify db name, login and password');},Logout:function($p0){throw new Error('Operation not supported, create new instance of Aras.IOM.HttpServerConnection and specify db name, login and password');}} Aras.IOM.WinAuthHttpServerConnection=function(innovatorServerUrl,database){Aras.IOM.WinAuthHttpServerConnection.initializeBase(this,[innovatorServerUrl,database,'','','','']);} Aras.IOM.WinAuthHttpServerConnection.prototype={Login:function(){var $0=Aras.IOM.InternalUtils.createXmlDocument();var $1=Aras.IOM.InternalUtils.createXmlDocument();Aras.IOM.InternalUtils.loadXmlFromString($0,'');Aras.IOM.InternalUtils.loadXmlFromString($1,'');var $2=this.$C.toLowerCase().indexOf('/server/innovatorserver.aspx');var $3=this.$C.substring(0,$2)+'/Front/scripts/IOMLogin.aspx';this.callActionImpl('',$0,$1,$3,false);var $4=$1.selectSingleNode('//Result');if($4==null){var $7='Failed to connect to IOMLogin.aspx. Either IOMLogin.aspx is not setup to use integrated Windows authentication or the authentication failed.';return new Aras.IOM.Innovator(this).newError($7);}var $5=$4.selectSingleNode('user').text;var $6=$4.selectSingleNode('password').text;if(!$6.trim().length){return new Aras.IOM.Innovator(this).newError("Failed to authenticate with Innovator server '"+this.$C+"'. Original error: "+$5);}this.$18=new Aras.IOM.IOMScriptSharp$5($5,$6);return Aras.IOM.WinAuthHttpServerConnection.callBaseMethod(this, 'Login');}} Type.registerNamespace('Aras.Utils');Aras.Utils.IClientData=function(){};Aras.Utils.IClientData.registerInterface('Aras.Utils.IClientData');Aras.Utils.HeaderClientData=function(name,value){this.$1=name;this.$0=value;} Aras.Utils.HeaderClientData.prototype={$0:null,$1:null,get_value:function(){return this.$0;},get_name:function(){return this.$1;}} Type.registerNamespace('Aras.I18NUtils');Aras.I18NUtils._I18NConverter=function(){} Aras.I18NUtils._I18NConverter.$8 = function ($p0) { if ($p0 == null) { $p0 = ''; } $p0 = $p0.replaceAll(' ', '_'); $p0 = String.format('{0}_', $p0); if ($p0 === 32 || $p0 === 'boolean_') { return 32; } if ($p0 === 16384 || $p0 === 'color_') { return 16384; } if ($p0 === 8192 || $p0 === 'color_list_') { return 8192; } if ($p0 === 64 || $p0 === 'date_') { return 64; } if ($p0 === 16 || $p0 === 'decimal_') { return 16; } if ($p0 === 32768 || $p0 === 'federated_') { return 32768; } if ($p0 === 4096 || $p0 === 'filter_list_') { return 4096; } if ($p0 === 8 || $p0 === 'float_') { return 8; } if ($p0 === 131072 || $p0 === 'foreign_') { return 131072; } if ($p0 === 65536 || $p0 === 'formatted_text_') { return 65536; } if ($p0 === 128 || $p0 === 'image_' || $p0 === 'qrcode_') { return 128; } if ($p0 === 4 || $p0 === 'integer_') { return 4; } if ($p0 === 1024 || $p0 === 'item_') { return 1024; } if ($p0 === 2048 || $p0 === 'list_') { return 2048; } if ($p0 === 256 || $p0 === 'md5_') { return 256; } if ($p0 === 262144 || $p0 === 'ml_string_') { return 262144; } if ($p0 === 524288 || $p0 === 'ml_string_') { return 524288; }if($p0===512||$p0==='sequence_'){return 512;}if($p0===1||$p0==='string_'){return 1;}if($p0===2||$p0==='text_'){return 2;}return 0;} Aras.I18NUtils._I18NConverter.$9=function($p0){if($p0==null){$p0='';}if($p0===(4)||$p0==='long_date'){return 4;}if($p0===(8)||$p0==='long_date_time'){return 8;}if($p0===(1)||$p0==='short_date'){return 1;}if($p0===(2)||$p0==='short_date_time'){return 2;}return 0;} Aras.I18NUtils._I18NConverter.$B=function($p0,$p1){var $0;try{$0=CultureInfo.CreateSpecificCulture($p1);}catch($4){$0=CultureInfo.InvariantCulture;}var $1=$0.DateTimeFormat;var $2=$1.ShortDatePattern;var $3=Aras.I18NUtils._I18NConverter.$9($p0);switch($3){case 1:$2=$1.ShortDatePattern;break;case 2:$2=String.format('{0} {1}',$1.ShortDatePattern,$1.LongTimePattern);break;case 4:$2=$1.LongDatePattern;break;case 8:$2=String.format('{0} {1}',$1.LongDatePattern,$1.LongTimePattern);break;default:switch($p0){case 'long_time':$2=$1.LongTimePattern;break;case 'short_time':$2=$1.ShortTimePattern;break;}break;}return $2;} Aras.I18NUtils._I18NConverter.prototype={$3:null,get_$4:function(){return (this.$3==null)?CultureInfo.InvariantCulture:this.$3;},set_$4:function($p0){this.$3=$p0;return $p0;},$6:null,get_$7:function(){return this.$6;},set_$7:function($p0){this.$6=$p0;if(this.$6==null){this.$6='';}this.set_$4(Type.safeCast(Aras.I18NUtils._I18NConverter.$5[this.$6],CultureInfo));if(this.$3==null){try{this.set_$4(CultureInfo.CreateSpecificCulture(this.$6));}catch($0){this.set_$4(CultureInfo.InvariantCulture);this.$6=this.get_$4().Name;}Aras.I18NUtils._I18NConverter.$5[this.$6]=this.get_$4();}return $p0;},$A:function($p0,$p1,$p2,$p3,$p4,$p5){if($p0==null){return null;}var $0=$p0;var $1=CultureInfo.InvariantCulture;this.set_$7($p4);var $2=this.get_$4();var $3=$2.DateTimeFormat;var $4=Aras.I18NUtils._I18NConverter.$8($p1);var $5;switch($4){case 64:var $6=Aras.I18NUtils._I18NConverter.$9($p3);if(!!$6&&!String.isNullOrEmpty($p3)){$p3=Aras.I18NUtils._I18NConverter.$B($p3,$2.Name);}if($p2){var $7;var $8=false;if(String.isNullOrEmpty($p3)){$7=$3.Parse($p0,null,this.get_$7());var $9=new Date(Date.UTC($7.getFullYear(),$7.getMonth(),$7.getDate(),$7.getHours(),$7.getMinutes(),$7.getSeconds(),$7.getMilliseconds()));}else{$7=$3.Parse($p0,$p3,$2.Name);if(ss.isNullOrUndefined($7)){return null;}if($p3.toLowerCase().indexOf('z')>-1){$8=true;}}if($8){$7=new Date(Date.UTC($7.getFullYear(),$7.getMonth(),$7.getDate(),$7.getHours(),$7.getMinutes(),$7.getSeconds(),$7.getMilliseconds()));var $A=$3.OffsetBetweenTimeZones($7,$p5,null);$7.setTime($7.getTime()+$A*1000*60);}$0=$3.Format($7,'yyyy-MM-ddTHH:mm:ss',null);}else{var $B=$3.Parse($p0,'yyyy-MM-ddTHH:mm:ss');if(ss.isNullOrUndefined($B)){$B=$3.Parse($p0,'yyyy-MM-dd');if(ss.isNullOrUndefined($B)){return null;}}$0=$3.Format($B,$p3,this.get_$7());}break;case 16:$5=new ArasNumberHelper();if($p2){var $C=$5.tryParse($p0,null,this.get_$7());if(isNaN($C)){$0=null;}else{$0=$5.format($C,$p3,null);}}else{var $D=parseFloat($p0);$0=$5.format($D,$p3,this.get_$7());}break;case 8:if($p2){var $E=DoubleHelper.Parse($p0,this.get_$4().NumberFormat);$0=DoubleHelper.ToString($E,CultureInfo.InvariantCulture.NumberFormat);}else{var $F=DoubleHelper.Parse($p0,CultureInfo.InvariantCulture.NumberFormat);$0=DoubleHelper.ToString($F,this.get_$4().NumberFormat);}break;}return $0;}} Aras.I18NUtils.I18NSystemInfo=function(){} Aras.I18NUtils.I18NSystemInfo.get_$0=function(){return ss.CultureInfo.CurrentCulture;} Aras.I18NUtils.I18NSystemInfo.get_$1=function(){return ss.CultureInfo.CurrentCulture;} Aras.I18NUtils.I18NSystemInfo.get_$2=function(){return 'Kaliningrad Standard Time';} Type.registerNamespace('Aras.IOME');Aras.IOME.ICacheable=function(){};Aras.IOME.ICacheable.registerInterface('Aras.IOME.ICacheable');Aras.IOME.CacheableContainer=function(value,dependenciesSource){this.set_$0(value);this.$1=Aras.IOME.CacheableContainer.$2(dependenciesSource);} Aras.IOME.CacheableContainer.$2=function($p0){var $0={};Aras.IOME.ItemCache.$3($p0,$0);var $1=0;var $2=new Array(Object.getKeyCount($0)+1);var $enum1=ss.IEnumerator.getEnumerator(Object.keys($0));while($enum1.moveNext()){var $3=$enum1.current;$2[$1]=$3;$1++;}return $2;} Aras.IOME.CacheableContainer.prototype={get_$0:function(){return this.content;},set_$0:function($p0){this.content=$p0;return $p0;},$1:null,content:null,Content:function(){return this.content;},getGuidsItemDependsOn:function(){return this.$1;}} Aras.IOME._KeyComparator=function(){} Aras.IOME._KeyComparator.$0=function($p0){var $0='';var $enum1=ss.IEnumerator.getEnumerator($p0);while($enum1.moveNext()){var $1=$enum1.current;$0+=$1.toString();}return $0;} Aras.IOME._KeyComparator.prototype={$1:function($p0,$p1){if($p0==null){throw new Error('x');}var $0=Type.safeCast($p0,Array);if($0!=null){var $3=$0;var $4=$p1;var $5=Aras.IOME._KeyComparator.$0($3);var $6=Aras.IOME._KeyComparator.$0($4);return String.compare($5,$6,StringComparison.ordinalIgnoreCase);}var $1=$p0.toString();var $2=$p0.toString();return String.compare($1,$2,StringComparison.ordinalIgnoreCase);}} Aras.IOME.ArrayListComparer=function(){} Aras.IOME.ArrayListComparer.prototype={equals:function(x,y){var $0,$1;var $2,$3;$0=x;$1=y;$3=$0.length;if($3<$1.length||$3>$1.length){return false;}for($2=0;$2<$3;++$2){if($0[$2]!==$1[$2]){return false;}}return true;},getHashCode:function(obj){var $0=obj;var $1,$2,$3;$2=$0.length;$3=0;for($1=0;$1<$2;++$1){$3=$3^this.$0($0[$1].toString());}return $3;},$0:function($p0){var $0=0;if(!$p0.length){return $0;}for(var $1=0;$1<$p0.length;$1++){var $2=$p0.charCodeAt($1);$0=(($0<<5)-$0)+$2;$0=$0&$0;}return $0;}} Aras.IOME.ItemCache=function(){this.$0={};this.$1={};} Aras.IOME.ItemCache.$3=function($p0,$p1){if($p0==null){return;}if(typeof($p0)==='object'){if(('getAttribute' in $p0)){Aras.IOME.ItemCache.$4($p0,$p1);return;}if(('innerText' in $p0)){Aras.IOME.ItemCache.$5($p0,$p1);return;}}var $0=Type.safeCast($p0,Aras.IOME.ICacheable);if($0!=null){var $3=$0.getGuidsItemDependsOn();for(var $4=0;$4<$3.length;$4++){if(!String.isNullOrEmpty($3[$4])){$p1[$3[$4]]=true;}}return;}var $1=Type.safeCast($p0,String);if($1!=null){if(Aras.IOME.ItemCache.$7($1)){$p1[$1]=true;}return;}var $2=Type.safeCast($p0,Array);if($2!=null){var $enum1=ss.IEnumerator.getEnumerator($2);while($enum1.moveNext()){var $5=$enum1.current;Aras.IOME.ItemCache.$3($5,$p1);}return;}} Aras.IOME.ItemCache.$4=function($p0,$p1){var $0='';if($p0.getAttribute('id')!=null){$0=$p0.getAttribute('id').toString();if(Aras.IOME.ItemCache.$7($0)){$p1[$0]=true;}}var $enum1=ss.IEnumerator.getEnumerator($p0.selectNodes('.//*/@id'));while($enum1.moveNext()){var $1=$enum1.current;$0=$1.text;if(Aras.IOME.ItemCache.$7($0)){$p1[$0]=true;}}var $enum2=ss.IEnumerator.getEnumerator($p0.selectNodes('descendant::text()[string-length(.)=32]'));while($enum2.moveNext()){var $2=$enum2.current;$0=$2.text;if(Aras.IOME.ItemCache.$7($0)){$p1[$0]=true;}}} Aras.IOME.ItemCache.$5=function($p0,$p1){var $0=$p0.text;if(Aras.IOME.ItemCache.$7($0)){$p1[$0]=true;}} Aras.IOME.ItemCache.$6=function($p0,$p1){var $enum1=ss.IEnumerator.getEnumerator($p0);while($enum1.moveNext()){var $0=$enum1.current;var $1=$0;if(Aras.IOME.ItemCache.$7($0)){$p1[$1]=true;}}} Aras.IOME.ItemCache.$7=function($p0){var $0=Type.safeCast($p0,String);if($0!=null){return Aras.IOME.ItemCache.$2.test($0);}else{return false;}} Aras.IOME.ItemCache.$9=function($p0,$p1){if(!Object.getKeyCount($p1)){return $p0;}var $0={};var $enum1=ss.IEnumerator.getEnumerator(Object.keys($p0));while($enum1.moveNext()){var $1=$enum1.current;var $2=$1;if(!Object.keyExists($p1,$2)){$0[$2]=$p0[$2];}}return $0;} Aras.IOME.ItemCache.$C=function($p0){for(var $0=0;$0<$p0.length;$0++){var $1=$p0[$0];if(!((Type.canCast($1,String))||(Type.canCast($1,Boolean)))){Aras.IOME.ItemCache.$D('key',$1);}}} Aras.IOME.ItemCache.$D=function($p0,$p1){var $0='NULL';if($p1!=null){$0=Type.getInstanceType($p1).get_fullName();}var $1=$0+' is an illegal datatype.';throw new Error($1+$p0);} Aras.IOME.ItemCache.prototype={$0:null,$1:null,ClearCache:function(){this.clear();},RemoveById:function(id){return this.RemoveAllItems(id);},RemoveAllItems:function(itemId){return this.Remove([itemId]);},Remove:function(idlist){if(idlist==null||!idlist.length){return false;}var $0={};for(var $1=0;$10){var $enum2=ss.IEnumerator.getEnumerator(Object.keys($0));while($enum2.moveNext()){var $6=$enum2.current;delete this.$1[$6];var $7=$0[$6];for(var $8=0;$8<$7.length;$8++){this.removeFromHash($7[$8]);}}return true;}return false;},removeFromHash:function(skey){var $0=skey;var $1=[];var $2=$0.split(',');var $enum1=ss.IEnumerator.getEnumerator($2);while($enum1.moveNext()){var $5=$enum1.current;$1.add($5);}if($0==null){throw new Error('key');}var $3={};var $4=null;if(Object.keyExists(this.$0,$0)){$4=this.$0[$0];Aras.IOME.ItemCache.$3($4,$3);Aras.IOME.ItemCache.$6($1,$3);this.$B($3,$1);delete this.$0[$0];return true;}else{return false;}},GetItem:function(key){var $0=(key);return this.$0[$0];},SetItem:function(key,val){return this.$8(key,val);},$8:function($p0,$p1){var $0=($p0);Aras.IOME.ItemCache.$C($p0);var $1={};var $2={};var $3;var $4;var $5=null;Aras.IOME.ItemCache.$3($p1,$1);Aras.IOME.ItemCache.$6($p0,$1);if(Object.keyExists(this.$0,$0)){$5=this.$0[$0];if($5===$p1){$5=null;}else{Aras.IOME.ItemCache.$3($5,$2);Aras.IOME.ItemCache.$6($p0,$2);}}$3=Aras.IOME.ItemCache.$9($1,$2);$4=Aras.IOME.ItemCache.$9($2,$1);this.$A($3,$p0);this.$B($4,$p0);this.$0[$0]=$p1;if($5!=null){return true;}else{return false;}},$A:function($p0,$p1){var $0;var $enum1=ss.IEnumerator.getEnumerator(Object.keys($p0));while($enum1.moveNext()){var $1=$enum1.current;$0=this.$1[$1]||null;if($0==null){$0={};this.$1[$1]=$0;}var $2=($p1);$0[$2]=true;}},$B:function($p0,$p1){var $0;var $enum1=ss.IEnumerator.getEnumerator(Object.keys($p0));while($enum1.moveNext()){var $1=$enum1.current;var $2=($p1);$0=this.$1[$1];if($0!=null){delete $0[$2];}}},clear:function(){Object.clearKeys(this.$0);Object.clearKeys(this.$1);},keys:function(){return Object.keys(this.$0);},dependencies:function(){return Object.keys(this.$1);},describeKey:function(key){if(key==null){throw new Error('key');}var $0,$1,$2=0;var $3;$1=key.length;if(!$1){return '';}for($0=0;$0<$1;++$0){$3=key[$0].toString();$2=$2+$3.length;}var $4=new ss.StringBuilder();for($0=0;$0<$1;++$0){$4.append(key[$0]);if(($0+1)<$1){$4.append(':');}}return $4.toString();},withinlocker:function(fcn,arg){if(fcn==null){throw new Error('fcn');}var $0;$0=fcn(arg);return $0;},containsKey:function(key){var $0=(key);return Object.keyExists(this.$0,$0);},GetItemsById:function(id){var $0=this.$E(id);var $1=[];var $enum1=ss.IEnumerator.getEnumerator($0);while($enum1.moveNext()){var $2=$enum1.current;var $3=($2);if(Object.keyExists(this.$0,$3)){$1.add(this.$0[$3]);}}return $1;},$E:function($p0){var $0=[];if(!ss.isNullOrUndefined(this.$1[$p0])){$0.addRange(Object.keys((this.$1[$p0])));}return $0;},$F:function($p0){var $0=[];var $enum1=ss.IEnumerator.getEnumerator(Object.keys($p0));while($enum1.moveNext()){var $2=$enum1.current;$0.add($2);}var $1=new Aras.IOME._KeyComparator();$0.sort(ss.Delegate.create($1,$1.$1));return $0;}} Type.registerNamespace('Aras.IOME.Licensing');Aras.IOME.Licensing.ILicenseManagerWebService=function(){};Aras.IOME.Licensing.ILicenseManagerWebService.registerInterface('Aras.IOME.Licensing.ILicenseManagerWebService');Aras.IOME.Licensing.IOMScriptSharp$2=function(){};Aras.IOME.Licensing.IOMScriptSharp$2.registerInterface('Aras.IOME.Licensing.IOMScriptSharp$2');Aras.IOME.Licensing.LicenseManager=function(serverConnection){if(serverConnection==null){throw new Error('serverConnection');}try{var $0=(serverConnection);this.$1=$0.getLicenseManagerWebService();}catch($1){throw new Error("Current implementation of Aras.IOM.IServerConnection doesn't implement Aras.IOM.ILicenseManagerWebServiceFactory");}} Aras.IOME.Licensing.LicenseManager.prototype={$1:null,consumeLicense:function(featureName){if(String.isNullOrEmpty(featureName)){throw new Error('Feature name must be specified.');}return this.$1.consumeLicense(featureName);}} Aras.IOME.Licensing.IOMScriptSharp$3=function(){this.$0=new LicenseManagerWebServiceClient();} Aras.IOME.Licensing.IOMScriptSharp$3.prototype={$0:null,consumeLicense:function($p0){return this.$0.ConsumeLicense($p0);},releaseLicense:function($p0){throw new Error('NotImplementedException: ReleaseLicense not implemented');},getServerInfo:function(){throw new Error('NotImplementedException: GetServerInfo not implemented');},getFeatureTree:function(){throw new Error('NotImplementedException: GetFeatureTree not implemented');},updateFeatureTree:function($p0){throw new Error('NotImplementedException: UpdateFeatureTree not implemented');},importFeatureLicense:function($p0){throw new Error('NotImplementedException: ImportFeatureLicense not implemented');}} Type.registerNamespace('Aras.IOM.Vault');Aras.IOM.Vault.IOMScriptSharp$4=function(id,vaultId,vaultUrl){this.id=id;this.$0=vaultId;this.$1=vaultUrl;} Aras.IOM.Vault.IOMScriptSharp$4.prototype={$0:null,$1:null,id:null} Type.registerNamespace('Aras.SoapConstants');Aras.SoapConstants._Soap=function(){} Aras.IOM.InnovatorUser=function(){} Aras.IOM.InnovatorUser.get_Current=function(){return Aras.IOM.InnovatorUser.$0||(Aras.IOM.InnovatorUser.$0=new Aras.IOM.InnovatorUser());} Aras.IOM.InnovatorUser.prototype={Init:function(userName,password,dbName,connection,context){this.UserName=userName;this.Password=password;this.DatabaseName=dbName;this.ISConnection=connection;this.SessionContext=context;},UserName:null,Password:null,DatabaseName:null,ISConnection:null,SessionContext:null} StringComparison.registerClass('StringComparison');CompressionType.registerClass('CompressionType');RegexOptions.registerClass('RegexOptions');HttpUtility.registerClass('HttpUtility');Aras.IOM.HttpConnectionParameters.registerClass('Aras.IOM.HttpConnectionParameters');Aras.IOM.I18NSessionContext.registerClass('Aras.IOM.I18NSessionContext');Aras.IOM.IOMScriptSharp$5.registerClass('Aras.IOM.IOMScriptSharp$5');Aras.IOM.InternalUtils.registerClass('Aras.IOM.InternalUtils');Aras.IOM.XmlExtension.registerClass('Aras.IOM.XmlExtension');Aras.IOM.IomFactory.registerClass('Aras.IOM.IomFactory');Aras.IOM.ServerConnectionBase.registerClass('Aras.IOM.ServerConnectionBase',null,Aras.IOM.IServerConnection);Aras.IOM.HttpServerConnection.registerClass('Aras.IOM.HttpServerConnection',Aras.IOM.ServerConnectionBase);Aras.IOM.Innovator.registerClass('Aras.IOM.Innovator');Aras.IOM.Item.registerClass('Aras.IOM.Item');Aras.IOM.InnovatorServerConnector.registerClass('Aras.IOM.InnovatorServerConnector',Aras.IOM.ServerConnectionBase,Aras.IOME.Licensing.IOMScriptSharp$2);Aras.IOM.IOMScriptSharp$6.registerClass('Aras.IOM.IOMScriptSharp$6',Aras.IOM.HttpServerConnection);Aras.IOM.WinAuthHttpServerConnection.registerClass('Aras.IOM.WinAuthHttpServerConnection',Aras.IOM.HttpServerConnection);Aras.Utils.HeaderClientData.registerClass('Aras.Utils.HeaderClientData',null,Aras.Utils.IClientData);Aras.I18NUtils._I18NConverter.registerClass('Aras.I18NUtils._I18NConverter');Aras.I18NUtils.I18NSystemInfo.registerClass('Aras.I18NUtils.I18NSystemInfo');Aras.IOME.CacheableContainer.registerClass('Aras.IOME.CacheableContainer',null,Aras.IOME.ICacheable);Aras.IOME._KeyComparator.registerClass('Aras.IOME._KeyComparator');Aras.IOME.ArrayListComparer.registerClass('Aras.IOME.ArrayListComparer');Aras.IOME.ItemCache.registerClass('Aras.IOME.ItemCache');Aras.IOME.Licensing.LicenseManager.registerClass('Aras.IOME.Licensing.LicenseManager');Aras.IOME.Licensing.IOMScriptSharp$3.registerClass('Aras.IOME.Licensing.IOMScriptSharp$3',null,Aras.IOME.Licensing.ILicenseManagerWebService);Aras.IOM.Vault.IOMScriptSharp$4.registerClass('Aras.IOM.Vault.IOMScriptSharp$4');Aras.SoapConstants._Soap.registerClass('Aras.SoapConstants._Soap');Aras.IOM.InnovatorUser.registerClass('Aras.IOM.InnovatorUser');StringComparison.ordinalIgnoreCase=false;CompressionType.deflate='deflate';CompressionType.gzip='gzip';CompressionType.none='none';RegexOptions.compiled='';RegexOptions.cultureInvariant='';RegexOptions.ecmaScript='';RegexOptions.explicitCapture='';RegexOptions.ignoreCase='i';RegexOptions.ignorePatternWhitespace='';RegexOptions.multiline='';RegexOptions.none='';RegexOptions.rightToLeft='';RegexOptions.singleline='';Aras.IOM.HttpServerConnection.$11=Aras.SoapConstants._Soap.$6+'<'+'SOAP-ENV'+':Fault>\r\n 999\r\n HTTP Error\r\n HttpServerConnection\r\n unknown error\r\n '+Aras.SoapConstants._Soap.$7;Aras.IOM.HttpServerConnection.$17=new RegExp('^([0-9A-F]{32})|([0-9A-F]{64})$',RegexOptions.compiled+RegexOptions.ignoreCase);Aras.IOM.Item.xPathResult='//Result';Aras.IOM.Item.xPathResultItem=Aras.IOM.Item.xPathResult+'/Item';Aras.IOM.Item.xPathFault="/*[local-name()='Envelope' and (namespace-uri()='http://schemas.xmlsoap.org/soap/envelope/' or namespace-uri()='')]/*[local-name()='Body' and (namespace-uri()='http://schemas.xmlsoap.org/soap/envelope/' or namespace-uri()='')]/*[local-name()='Fault' and (namespace-uri()='http://schemas.xmlsoap.org/soap/envelope/' or namespace-uri()='')]";Aras.IOM.Item.$2="WorkflowMap ID is either 'null' or empty string";Aras.IOM.Item.$3='The item is a new item';Aras.IOM.Item.$4='instantiateWorkflow';Aras.IOM.Item.$6="Wrong internal structure of the {0}; e.g. item's \"dom\" is not set; or item's \"node\" doesn't "+"belong to the item's \"dom\"; or both \"node\" and \"nodeList\" are null; etc.";Aras.IOM.InnovatorServerConnector.$D=new RegExp('^[0-9A-F]{32}$',RegexOptions.ignoreCase);Aras.I18NUtils._I18NConverter.$0='yyyy-MM-ddTHH:mm:ss';Aras.I18NUtils._I18NConverter.$1='yyyy-MM-dd';Aras.I18NUtils._I18NConverter.$2=null;Aras.I18NUtils._I18NConverter.$5={};Aras.IOME.ItemCache.$2=new RegExp('^[0-9A-F]{32}$',RegexOptions.compiled);Aras.SoapConstants._Soap.$6='<'+'SOAP-ENV'+':Envelope xmlns:'+'SOAP-ENV'+'="'+'http://schemas.xmlsoap.org/soap/envelope/'+'" xmlns:'+'i18n'+'="'+'http://www.aras.com/I18N'+'"><'+'SOAP-ENV'+':Body>';Aras.SoapConstants._Soap.$7='';Aras.SoapConstants._Soap.$8="namespace-uri()='"+'http://schemas.xmlsoap.org/soap/envelope/'+"' or namespace-uri()=''";Aras.SoapConstants._Soap.$9="*[local-name()='Envelope' and ("+Aras.SoapConstants._Soap.$8+')]';Aras.SoapConstants._Soap.$A="*[local-name()='Body' and ("+Aras.SoapConstants._Soap.$8+')]';Aras.SoapConstants._Soap.$B="*[local-name()='Result' and ("+Aras.SoapConstants._Soap.$8+')]';Aras.SoapConstants._Soap.$C="*[local-name()='Fault' and ("+Aras.SoapConstants._Soap.$8+')]';Aras.SoapConstants._Soap.$D=Aras.SoapConstants._Soap.$9+'/'+Aras.SoapConstants._Soap.$A;Aras.SoapConstants._Soap.$E=Aras.SoapConstants._Soap.$D+'/'+Aras.SoapConstants._Soap.$B;Aras.SoapConstants._Soap.$F=Aras.SoapConstants._Soap.$D+'/'+Aras.SoapConstants._Soap.$C;Aras.IOM.InnovatorUser.$0=null;})();// This script was generated using Script# v0.7.4.0