processmaker-builder
Version:
The gulp task runner for ProcessMaker building
1,614 lines (1,539 loc) • 885 kB
JavaScript
/**
* @class PMDynaform
* Base class PMDynaform
* @singleton
*/
/**
* @feature support for ie8
* functions
*/
function getScrollTop() {
if (typeof pageYOffset != 'undefined') {
//most browsers except IE before #9
return pageYOffset;
}
else {
var B = document.body; //IE 'quirks'
var D = document.documentElement; //IE with doctype
D = (D.clientHeight) ? D : B;
return D.scrollTop;
}
};
//.trim to support ie8
if (!Array.prototype.filter) {
Array.prototype.filter = function (fun/*, thisArg*/) {
'use strict';
if (this === void 0 || this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== 'function') {
throw new TypeError();
}
var res = [];
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i];
// NOTA: Tecnicamente este Object.defineProperty deben en
// el indice siguiente, como push puede ser
// afectado por la propiedad en object.prototype y
// Array.prototype.
// Pero estos metodos nuevos, y colisiones deben ser
// raro, así que la alternativas mas compatible.
if (fun.call(thisArg, val, i, t)) {
res.push(val);
}
}
}
return res;
};
}
if (!String.prototype.trim) {
(function () {
// Make sure we trim BOM and NBSP
var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
String.prototype.trim = function () {
return this.replace(rtrim, '');
};
})();
}
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (elt /*, from*/) {
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++) {
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
if (!document.getElementsByClassName) {
document.getElementsByClassName = function (classname) {
var a = [];
var re = new RegExp('(^| )' + classname + '( |$)');
var els = this.getElementsByTagName("*");
for (var i = 0, j = els.length; i < j; i++)
if (re.test(els[i].className))
a.push(els[i]);
return a;
};
}
if (!Array.prototype.find) {
Array.prototype.find = function (callback, thisArg) {
"use strict";
var arr = this,
arrLen = arr.length,
i;
for (i = 0; i < arrLen; i += 1) {
if (callback.call(thisArg, arr[i], i, arr)) {
return arr[i];
}
}
return undefined;
};
}
var PMDynaform = {
VERSION: "0.1.0",
view: {},
model: {},
collection: {},
Extension: {},
restData: {},
activeProject: null,
FLashMessage: null,
PATH_RTL_CSS: "css/PMDynaform-rtl.css"
};
/**
* Extends the PMDynaform namespace with the given `path` and making a pointer
* from `path` to the given `class` (note that the `path`'s last token will be the pointer visible from outside
* the definition of the class).
*
* // e.g.
* // let's define a class inside an anonymous function
* // so that the global scope is not polluted
* (function () {
* var Class = function () {...};
*
* // let's extend the namespace
* PMDynaform.extendNamespace('PMDynaform.package.Class', Class);
*
* }());
*
* // now PMDynaform.package.Class is a pointer to the class defined above
*
* @param {string} path
* @param {Object} newClass
* @return {Object} The argument `newClass`
*/
PMDynaform.extendNamespace = function (path, newClass) {
var current,
pathArray,
extension,
i;
if (arguments.length !== 2) {
throw new Error("Dynaform.extendNamespace(): method needs 2 arguments");
}
pathArray = path.split('.');
if (pathArray[0] === 'PMDynaform') {
pathArray = pathArray.slice(1);
}
current = PMDynaform;
// create the 'path' namespace
for (i = 0; i < pathArray.length - 1; i += 1) {
extension = pathArray[i];
if (typeof current[extension] === 'undefined') {
current[extension] = {};
}
current = current[extension];
}
extension = pathArray[pathArray.length - 1];
if (current[extension]) {
}
current[extension] = newClass;
return newClass;
};
/**
* Creates an object whose [[Prototype]] link points to an object's prototype (the object is gathered using the
* argument `path` and it's the last token in the string), since `subClass` is given it will also mimic the
* creation of the property `constructor` and a pointer to its parent called `superclass`:
*
* // constructor pointer
* subClass.prototype.constructor === subClass // true
*
* // let's assume that superClass is the last token in the string 'path'
* subClass.superclass === superClass // true
*
* An example of use:
*
* (function () {
* var Class = function () {...};
*
* // extending the namespace
* PMDynaform.extendNamespace('PMDynaform.package.Class', Class);
*
* }());
*
* (function () {
* var NewClass = function () {...};
*
* // this class inherits from PMDynaform.package.Class
* PMDynaform.inheritFrom('PMDynaform.package.Class', NewClass);
*
* // extending the namespace
* PMDynaform.extendNamespace('PMDynaform.package.NewClass', NewClass);
*
* }());
*
* @param {string} path
* @param {Object} subClass
* @return {Object}
*/
PMDynaform.inheritFrom = function (path, subClass) {
var current,
extension,
pathArray,
i,
prototype;
if (arguments.length !== 2) {
throw new Error("PMDynaform.inheritFrom(): method needs 2 arguments");
}
// function used to create an object whose [[Prototype]] link
// points to `object`
function clone(object) {
var F = function () {
};
F.prototype = object;
return new F();
}
pathArray = path.split('.');
if (pathArray[0] === 'PMDynaform') {
pathArray = pathArray.slice(1);
}
current = PMDynaform;
// find that class the 'path' namespace
for (i = 0; i < pathArray.length; i += 1) {
extension = pathArray[i];
if (typeof current[extension] === 'undefined') {
throw new Error("PMDynaform.inheritFrom(): object " + extension + " not found, full path was " + path);
}
current = current[extension];
}
prototype = clone(current.prototype);
prototype.constructor = subClass;
subClass.prototype = prototype;
subClass.superclass = current;
};
/**
* Get the keys from active project
* @returns {*}
*/
PMDynaform.getProjectKeys = function () {
var resp = null,
options;
if (this.activeProject) {
options = this.activeProject.webServiceManager.options;
resp = _.extend(options.keys, options.token);
}
return resp;
};
/**
* Set the instance of an active project pmdynaform
* @param project
* @returns { null | PMDynaform.core.ProjectMobile | PMDynaform.core.Project }
*/
PMDynaform.setActiveProject = function (project) {
if ((PMDynaform.core.ProjectMobile && project instanceof PMDynaform.core.ProjectMobile) || project instanceof PMDynaform.core.Project) {
this.activeProject = project;
return project;
}
return null;
};
/**
* Get the active project instance of pmdynaform
* @returns { PMDynaform.core.ProjectMobile | PMDynaform.core.Project }
*/
PMDynaform.getActiveProject = function () {
return this.activeProject;
};
/**
* Get the workspace from the project
* @returns {*}
*/
PMDynaform.getWorkspaceName = function () {
var resp = null;
if (this.activeProject) {
resp = this.activeProject.webServiceManager.getKey("workspace");
}
return resp;
};
/**
* Get the Accestoken from the project
* @returns {*}
*/
PMDynaform.getAccessToken = function () {
var resp = null;
if (this.activeProject) {
resp = this.activeProject.webServiceManager.getToken()["accessToken"];
}
return resp;
};
/**
* Get the hostName from the project
* @returns {*}
*/
PMDynaform.getHostName = function () {
var resp = null;
if (this.activeProject) {
resp = this.activeProject.webServiceManager.getKey("server");
}
return resp;
};
/**
* Get the enviroment (desktop, webkit android or iOS)
* @returns {string}
*/
PMDynaform.getEnvironment = function () {
var nav = navigator.userAgent,
resp;
resp = nav;
if (nav === 'formslider-ios') {
resp = "iOS";
}
if (nav === 'formslider-android') {
resp = "android";
}
return resp;
};
String.prototype.capitalize = function () {
return this.toLowerCase().replace(/(^|\s)([a-z])/g, function (m, p1, p2) {
return p1 + p2.toUpperCase();
});
};
jQuery.fn.extend({
setLabel: function (newLabel, col) {
var field = getFieldById(this.attr("id")) || null;
if (typeof newLabel === "string" && field) {
field.setLabel(newLabel, col);
}
return this;
},
getLabel: function (col) {
var field = getFieldById(this.attr("id")) || null;
if (field) {
return field.getLabel(col);
}
return null;
},
/**
* Sets a field's value into a form or grid
* @param value
* @param row
* @param col
* @returns {jQuery}
*/
setValue: function (value, row, col) {
var field = getFieldById(this.attr("id")) || null;
if (field) {
if (field.model.get("type") === "grid") {
field.setValue(value, row, col);
} else {
field.setValue(value);
}
}
return this;
},
setText: function (value, row, col) {
var field = getFieldById(this.attr("id")) || null;
if (field) {
if (field.model.get("type") === "grid") {
field.setText(value, row, col);
} else {
field.setText(value);
}
}
return this;
},
/**
* Helper for get the value of a Field or Grid
* @param row
* @param col
* @returns {*}
*/
getValue: function (row, col) {
var field = getFieldById(this.attr("id")) || null,
val = "",
type;
if (field) {
type = field.model.get("type");
if (type === "grid") {
val = field.getValue(row, col);
} else {
val = field.getValue();
}
}
return val;
},
/**
* helper getAppDocUID function to get app document uid as reference to a document
* @returns {array} val
*/
getAppDocUID: function () {
var item,
val = null;
if (getFieldById(this.attr("id"))) {
item = getFieldById(this.attr("id"));
if (typeof item.model.getAppDocUID === 'function'
&& item.model.getAppDocUID()) {
val = item.model.getAppDocUID();
}
}
return val;
},
/**
* Helper setOnChange
* @param handler
* @returns {jQuery}
*/
setOnchange: function (handler) {
var item = this.getIntanceById(this.attr("id"));
if (item && typeof item.setOnChange === "function") {
item.setOnChange(handler);
}
return this;
},
getInfo: function () {
var field = getFieldById(this.attr("id")) || null;
if (field) {
return field.getInfo();
}
return null;
},
setHref: function (value) {
var field = getFieldById(this.attr("id")) || null;
if (field.model.get("type") === "link") {
field.setHref(value);
}
return this;
},
getHref: function () {
var field = getFieldById(this.attr("id")) || null;
if (field.model.get("type") === "link") {
return field.getHref();
}
return this;
},
setRequired: function (field) {
},
required: function (field) {
},
getText: function (row, col) {
var field = getFieldById(this.attr("id")) || null,
typeField,
val = null;
if (field) {
typeField = field.model.get("type");
if (typeField === "grid") {
val = field.getText(row, col);
} else {
val = field.getText();
}
}
return val;
},
disableValidation: function (col) {
var field = getFieldById(this.attr("id")) || null, val;
if (field && field.disableValidation) {
field.disableValidation(col);
}
return this;
},
enableValidation: function (col) {
var field = getFieldById(this.attr("id")) || null, val;
if (field && field.enableValidation) {
field.enableValidation(col);
}
return this;
},
/**
* Helper for get the control of a Field
* @param row
* @param col
* @returns {Array}
*/
getControl: function (row, col) {
var field = getFieldById(this.attr("id")) || null,
control = [],
type;
if (field) {
type = field.model.get("type");
if (type === "grid") {
control = field.getControl(row, col);
} else {
control = field.getControl();
}
}
return control;
},
getLabelControl: function () {
var field = getFieldById(this.attr("id")) || null, val;
if (field) {
field.getLabelControl();
}
return this;
},
getHintHtml: function () {
var field = getFieldById(this.attr("id")) || null, html = [];
if (field) {
html = field.$el.find(".glyphicon-info-sign");
}
return $(html);
},
getSummary: function (col) {
var field = getFieldById(this.attr("id")) || null, html = [];
if (field && field.model.get("type") == "grid") {
return field.getSummary(col);
}
return this;
},
getNumberRows: function () {
var field = getFieldById(this.attr("id")) || null, html = [];
if (field && field.model.get("type") === "grid") {
return field.getNumberRows();
}
return this;
},
addRow: function (data) {
var field = getFieldById(this.attr("id")) || null, html = [];
if (field && field.model.get("type") == "grid") {
field.addRow(data);
}
return this;
},
deleteRow: function (row) {
var field = getFieldById(this.attr("id")) || null, html = [];
if (field && field.model.get("type") == "grid") {
if (!row) {
row = field.getNumberRows();
}
field.deleteRow(row);
}
return this;
},
onBeforeAdd: function () {
var field = getFieldById(this.attr("id")) || null, html = [];
if (field && field.model.get("type") == "grid") {
if (typeof handler === "function") {
field.setOnBeforeAddCallback(handler);
}
}
},
onAddRow: function (handler) {
var field = getFieldById(this.attr("id")) || null, html = [];
if (field && field.model.get("type") == "grid") {
if (typeof handler === "function") {
field.setOnAddRowCallback(handler);
}
}
},
onShowRowDialog: function (handler) {
var field = getFieldById(this.attr("id")) || null, html = [];
if (field && field.model.get("type") == "grid" && PMDynaform.core.ProjectMobile) {
if (typeof handler === "function") {
field.setOnShowRowDialog(handler);
}
}
},
onDeleteRow: function (handler) {
var field = getFieldById(this.attr("id")) || null, html = [];
if (field && field.model.get("type") == "grid") {
if (typeof handler === "function") {
field.setOnDeleteRowCallback(handler);
}
}
},
hideColumn: function (col) {
var field = getFieldById(this.attr("id")) || null;
if (field && field.model.get("type") === "grid") {
field.hideColumn(parseInt(col, 10));
}
},
showColumn: function (col) {
var field = getFieldById(this.attr("id")) || null;
if (field && field.model.get("type") === "grid") {
field.showColumn(parseInt(col, 10));
}
},
getData: function () {
var field = getFieldById(this.attr("id")) || null, val;
if (field && field.getData) {
return field.getData();
}
return this;
},
getDataLabel: function () {
var field = getFieldById(this.attr("id")) || null, val;
if (field && field.getDataLabel) {
return field.getDataLabel();
}
return this;
},
getForm: function () {
var form;
if (this.length) {
form = getFormById(this.attr('id') || '') || null;
return form;
}
},
submitForm: function () {
var project,
form = this.getForm();
if (form) {
project = form.project;
if (project && !project.isMobile()) {
if (form.isValid()) {
form.submitNextStep();
}
} else {
form.onSubmit();
}
}
},
saveForm: function () {
var form;
form = getFormById(this.attr("id"));
if (form) {
form.saveForm();
}
return this;
},
/**
* Set a callback in submit action
* @param callback
* @returns {jQuery}
*/
setOnSubmit: function (callback) {
var form;
form = getFormById(this.attr("id"));
if (form) {
form.setOnSubmit(callback);
}
return this;
},
_getJSONFormValues: function (elements) {
var i;
var data = {};
if (elements.length > 0) {
for (i = 0; i < elements.length; i += 1) {
data[elements[i].name] = elements[i].value;
}
}
return data;
},
/**
* This is a help function to close the form, supported for mobile version
* @returns {jQuery}
*/
closeForm: function () {
var form = getFormById(this.attr("id"));
if (form && form instanceof PMDynaform.view.FormPanel) {
form.close();
}
return this;
},
/**
* Show Modal Loading
* @returns {jQuery}
*/
showFormModal: function () {
var form = this.getForm(), modal;
if (form) {
modal = form.project.modalProgress;
modal.render();
}
return this;
},
/**
* Hide Modal Loading
* @returns {jQuery}
*/
hideFormModal: function () {
var form = this.getForm(), modal;
if (form) {
modal = form.project.modalProgress;
modal.hide();
}
return this;
},
/**
* Hide New Button of the Grid
* @returns {jQuery}
*/
hideNewButton: function () {
var field = getFieldById(this.attr("id")) || null,
actionButton = "add";
if (field && field.model.get("type") === "grid") {
field.hideButton(actionButton);
}
return this;
},
/**
* Show New Button of the Grid
* @returns {jQuery}
*/
showNewButton: function () {
var field = getFieldById(this.attr("id")) || null,
actionButton = "add";
if (field && field.model.get("type") === "grid") {
field.showButton(actionButton);
}
return this;
},
/**
* Clear Content File
* @param row
* @param col
* @returns {jQuery}
*/
clear: function (row, col) {
var field = getFieldById(this.attr("id")) || null,
type;
if (field) {
type = field.model.get("type");
if (type === "grid") {
field.clearContent(row, col);
} else {
field.clearContent();
}
}
return this;
},
/**
* Get Instance by Id (Form or Field)
* @returns {*}
*/
getIntanceById: function (idItem) {
var idInstance = idItem || null,
instanceResult = getFormById(idInstance) || getFieldById(idInstance);
return instanceResult || null;
},
/**
* Returns all the forms fields, including the ones in any nested subform.
* @param id The form's id.
* @returns {Array<T>PMDynaform.view.Field}
*/
getFields: function (id) {
var form = getFormById(this.attr("id"))
|| getFieldById(this.attr("id"));
return (form && form.getAllFields()) || [];
}
});
(function () {
var InputsValidation = function () {
var config = {
"data": {
"name": "",
"description": "",
"items": [
{
"type": "form",
"variable": "",
"var_uid": "",
"dataType": "",
"id": "",
"name": "",
"description": "",
"mode": "edit",
"script": "",
"language": "en",
"externalLibs": "",
"printable": false,
"items": [],
"variables": []
}
]
},
"delIndex": 0,
"dynaformUid": "",
"keys": {
"server": (location.protocol + "//" + window.location.host),
"projectId": "",
"workspace": "workflow"
},
"token": {
"accessToken": "",
"expiresIn": 0,
"tokenType": "bearer",
"scope": "",
"refreshToken": "",
"clientId": "",
"clientSecret": ""
},
isPreview : false,
isRTL: false,
language: null,
formAction: null,
formAjax: null,
submitRest: false,
globalMode: null,
externalLibs: "",
renderTo: document.body,
onLoad: new Function()
};
return {
getDefaultData : function(){
return config;
}
};
};
PMDynaform.extendNamespace("PMDynaform.util.InputsValidation", InputsValidation);
}());
/**
* Singleton for implement the flow Case independent
* @type {{VERSION: string, view: {}, model: {}, collection: {}, Extension: {}, restData: {}, activeProject: null, FLashMessage: null}}
*/
var xCase = {
VERSION: "0.1.0",
view: {},
model: {},
collection: {},
Extension: {},
restData: {},
activeProject: null,
FLashMessage: null
};
xCase.extendNamespace = function (path, newClass) {
var current,
pathArray,
extension,
i;
if (arguments.length !== 2) {
throw new Error("xCase.extendNamespace(): method needs 2 arguments");
}
pathArray = path.split('.');
if (pathArray[0] === 'xCase') {
pathArray = pathArray.slice(1);
}
current = xCase;
// create the 'path' namespace
for (i = 0; i < pathArray.length - 1; i += 1) {
extension = pathArray[i];
if (typeof current[extension] === 'undefined') {
current[extension] = {};
}
current = current[extension];
}
extension = pathArray[pathArray.length - 1];
if (current[extension]) {
}
current[extension] = newClass;
return newClass;
};
(function () {
/*
* @param {String}
* The following key selectors are availables for the
* getField and getGridField methods
* - Using '#', is possible select a field with the identifier of the field
* - Using ''. is possible select a field with the className of the field
* - Putting 'attr[name="my-name"]' is possible select fields with the same name attribute
**/
var Selector = function (options) {
this.onSupportSelectorFields = null;
this.fields = {};
this.queries = [];
this.form = {};
Selector.prototype.init.call(this, options);
};
/**
* Initializes properties of the selector
* @param options
*/
Selector.prototype.init = function (options) {
var defaults = {
fields: {},
queries: [],
form: {},
onSupportSelectorFields: {
text: "onTextField",
textarea: "onTextAreaField"
}
};
$.extend(true, defaults, options);
this.setOnSupportSelectorFields(defaults.onSupportSelectorFields)
.setFields(defaults.fields)
.setForms(defaults.form)
.applyGlobalSelectors();
};
Selector.prototype.addQuery = function (query) {
if (typeof query === "string") {
this.queries.push(query);
} else {
throw new Error("The query selector must be a string");
}
return this;
};
Selector.prototype.setOnSupportSelectorFields = function (support) {
if (typeof support === "object") {
this.onSupportSelectorFields = support;
} else {
throw new Error("The parameter for the support fields is wrong");
}
return this;
};
/**
* Sets fields
* @param fields
* @returns {Selector}
*/
Selector.prototype.setFields = function (fields) {
if (typeof fields === "object") {
this.fields = fields;
}
return this;
};
/**
* Sets form
* @param form
* @returns {Selector}
*/
Selector.prototype.setForms = function (form) {
if (typeof form === "object") {
this.form = form;
}
return this;
};
Selector.prototype.onTextField = function () {
return this;
};
Selector.prototype.onTextAreaField = function () {
return this;
};
/**
* Gets field instance searched
* @param selectorId
* @returns {object || null}
*/
Selector.prototype.findFieldById = function (selectorId) {
return selectorId && this.fields.hasOwnProperty(selectorId) ?
this.fields[selectorId] : null;
};
/**
* Gets form instance by id
* @param selectorId
* @returns {object || null}
*/
Selector.prototype.findFormById = function (selectorId) {
return selectorId && this.form.model.get("id") === selectorId ?
this.form : null;
};
/**
* Gets fields searched by name
* @param selectorAttr
* @returns {Array}
*/
Selector.prototype.findFieldByName = function (selectorAttr) {
var prop,
fieldFinded = [];
for (prop in this.fields) {
if (this.fields[prop].model.get("name") === selectorAttr) {
fieldFinded.push(this.fields[prop]);
}
}
return fieldFinded;
};
/**
* Gets fields by attribute
* @param parameter
* @param value
* @returns {Array}
*/
Selector.prototype.findFieldByAttribute = function (parameter, value) {
var prop,
fieldFinded = [],
modelField;
for (prop in this.fields) {
modelField = this.fields[prop].model;
if (value && modelField.attributes.hasOwnProperty(parameter) && modelField.get(parameter) === value) {
fieldFinded.push(this.fields[prop]);
}
}
return fieldFinded;
};
/**
* findFieldByVariable: Gets a field considering the variable name as a parameter
* @returns {object}
*/
Selector.prototype.findFieldByVariable = function(selectorAttr) {
var prop,
fieldFinded;
for (prop in this.fields) {
if (this.fields[prop].model.get("variable") === selectorAttr) {
fieldFinded = this.fields[prop];
break;
}
}
return fieldFinded;
};
Selector.prototype.applyGlobalSelectors = function () {
var that = this;
window.getFieldByAttribute = function (attr, value) {
that.addQuery(attr + ": " + value);
return that.findFieldByAttribute(attr, value);
};
window.getFieldById = function (query) {
that.addQuery("id: " + query);
return that.findFieldById(query);
};
window.getFieldByName = function (query) {
that.addQuery("name: " + query);
return that.findFieldByName(query);
};
window.getFormById = function (query) {
that.addQuery("id: " + query);
return that.findFormById(query);
};
/**
* getFieldByVariable :Gets a field searched by the variable
* @returns {object|undefined}
*/
window.getFieldByVariable = function(query) {
that.addQuery("name: " + query);
return that.findFieldByVariable(query);
};
/**
* get the subform with the supplied id
* @param id
* @returns {PMDynaform.view.SubForm|null}
*/
window.getSubformById = function (id) {
return that.findFieldById(id);
};
return this;
};
PMDynaform.extendNamespace("PMDynaform.core.Selector", Selector);
}());
(function () {
var Utils = {
generateID: function () {
var rand = function (min, max) {
// Returns a random number
//
// version: 1109.2015
// discuss at: http://phpjs.org/functions/rand
// + original by: Leslie Hoare
// + bugfixed by: Onno Marsman
// % note 1: See the commented out code below for a
// version which will work with our experimental
// (though probably unnecessary) srand() function)
// * example 1: rand(1, 1);
// * returns 1: 1
// fix for jsLint
// from: var argc = arguments.length;
if (typeof min === "undefined") {
min = 0;
}
if (typeof max === "undefined") {
max = 999999999;
}
return Math.floor(Math.random() * (max - min + 1)) + min;
},
uniqid = function (prefix, more_entropy) {
var php_js = {},
retId,
formatSeed;
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + revised by: Kankrelune (http://www.webfaktory.info/)
// % note 1: Uses an internal counter (in php_js global) to avoid collision
// * example 1: uniqid();
// * returns 1: 'a30285b160c14'
// * example 2: uniqid('foo');
// * returns 2: 'fooa30285b1cd361'
// * example 3: uniqid('bar', true);
// * returns 3: 'bara20285b23dfd1.31879087'
if (typeof prefix === 'undefined') {
prefix = "";
}
formatSeed = function (seed, reqWidth) {
var tempString = "",
i;
seed = parseInt(seed, 10).toString(16); // to hex str
if (reqWidth < seed.length) { // so long we split
return seed.slice(seed.length - reqWidth);
}
if (reqWidth > seed.length) { // so short we pad
// jsLint fix
tempString = "";
for (i = 0; i < 1 + (reqWidth - seed.length); i += 1) {
tempString += "0";
}
return tempString + seed;
}
return seed;
};
// BEGIN REDUNDANT
if (!php_js) {
php_js = {};
}
// END REDUNDANT
if (!php_js.uniqidSeed) { // init seed with big random int
php_js.uniqidSeed = Math.floor(Math.random() * 0x75bcd15);
}
php_js.uniqidSeed += 1;
retId = prefix; // start with prefix, add current milliseconds hex string
retId += formatSeed(parseInt(new Date().getTime() / 1000, 10), 8);
retId += formatSeed(php_js.uniqidSeed, 5); // add seed hex string
if (more_entropy) {
// for more entropy we add a float lower to 10
retId += (Math.random() * 10).toFixed(8).toString();
}
return retId;
},
sUID;
do {
sUID = uniqid(rand(0, 999999999), true);
sUID = sUID.replace('.', '0');
} while (sUID.length !== 32);
return "PMD-" + sUID;
},
generateName: function (type) {
return type + "[" + PMDynaform.core.Utils.generateID() + "]";
},
/**
* validate JSON parse
* @param str
* @returns {boolean}
*/
isJsonAndParse: function (str) {
var result;
try {
result = JSON.parse(str);
} catch (e) {
result = str.split(',');
}
return result;
},
/**
* check if it is a valid version of Internet Explorer for pmdynaform
*/
checkValidIEVersion: function () {
var version = false,
appName = navigator.appName,
appVersion = navigator.appVersion;
if (appName == "Netscape") {
if (appVersion.indexOf('Trident') !== -1){
version = 11;
}
if(appVersion.indexOf('Edge') !== -1){
version = 12;
}
}
return version;
}
};
PMDynaform.extendNamespace("PMDynaform.core.Utils", Utils);
}());
(function () {
/**
* @class PMDynaform.util.ExternalLibraries
* Class that manages all external resources used and presented in json definition.
*
* The external libraries are used into a form as a externalLib property.
*
* The external library has the following types:
* - Regular js files
* - Regular css files
* - Images
* Example to use:
* // e.g.
* // let's assume that there are an arroy of external resources
* // let's assume that callback is callback function to render after all resources has been load
*
* this.externalLibraries = new PMDynaform.util.ExternalLibraries({
* "libs": libs,
* "afterLoad": callback
* });
* @param options
* @constructor
*/
var ExternalLibraries = function (options) {
this.libs = [];
this.cachedLibs = [];
this.afterLoad = null;
ExternalLibraries.prototype.init.call(this, options);
};
/**
* This function init the class External libraries
* * @param options
* @returns {CaseManager}
*/
ExternalLibraries.prototype.init = function (options) {
var defaults = {
"libs": [],
"afterLoad": null
};
defaults = _.extend(defaults, options);
this.setLibs(defaults.libs)
.setAfterLoad(defaults.afterLoad);
return this;
};
/**
* Loads all scripts, an arroy of all libraries is used to do that
* after has been load completly all libraries the collback afterLoad is executed
* @returns {ExternalLibraries}
*/
ExternalLibraries.prototype.setExternalLibreries = function (i) {
var that = this, link;
if (that.libs && i < that.libs.length) {
link = that.onLoadScript(that.libs[i]);
if (link) {
link.onload = function () {
that.setExternalLibreries(i + 1);
};
link.onerror = function () {
console.error('invalid link :' + that.libs[i].url);
that.setExternalLibreries(i + 1);
};
} else {
that.setExternalLibreries(i + 1);
}
} else {
this.afterLoad();
}
};
/**
* Hook to execute all scripts and call loadjscssfile method
* to load the external libraries and that is stored in cachedLibs property
* @param lib
* @returns {ExternalLibraries}
*/
ExternalLibraries.prototype.onLoadScript = function (lib) {
var type = lib.url.substring(lib.url.lastIndexOf(".") + 1);
this.cachedLibs.push(lib);
return this.loadjscssfile(lib.url, type);
};
/**
* Append css or js external libraries to html head
* if filetype is not js or css return null,
* @param filename
* @param filetype
* @returns {*}
*/
ExternalLibraries.prototype.loadjscssfile = function (filename, filetype) {
var fileref = null;
if (filetype === "js") { //if filename is a external JavaScript file
fileref = document.createElement('script');
fileref.setAttribute("type", "text/javascript");
fileref.setAttribute("src", filename);
} else if (filetype === "css") { //if filename is an external CSS file
fileref = document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", filename);
}
if (fileref && fileref !== "undefined") {
document.getElementsByTagName("head")[0].appendChild(fileref);
}
return fileref;
};
/**
* Sets the array libs property
* @param libs
* @returns {ExternalLibraries}
*/
ExternalLibraries.prototype.setLibs = function (libs) {
if (_.isArray(libs)) {
this.libs = libs;
}
return this;
};
/**
* Sets the afterLoad callback as a external library property
* @param callback
* @returns {ExternalLibraries}
*/
ExternalLibraries.prototype.setAfterLoad = function (callback) {
if (_.isFunction(callback)) {
this.afterLoad = callback;
}
return this;
};
/**
* Gets the External library cachedLibs property
* @returns {Array}
*/
ExternalLibraries.prototype.getCachedLibs = function () {
return this.cachedLibs;
};
/**
* Clean the External library cachedLibs property
*/
ExternalLibraries.prototype.clearCachedLibs = function () {
this.cachedLibs = [];
};
PMDynaform.extendNamespace("PMDynaform.util.ExternalLibraries", ExternalLibraries);
}());
(function () {
var Validators = {
requiredText: {
message: "This field is required",
fn: function (val) {
var value = val;
if (_.isNumber(val)) {
value = val.toString();
}
value = value.trim();
if (value === null || value.length === 0 || /^\s+$/.test(value)) {
return false;
}
return true;
}
},
requiredDropDown: {
message: "This field is required",
fn: function (value) {
value = typeof value === 'string' ? value.trim() : value;
return !!value || typeof value === 'number';
}
},
requiredCheckBox: {
message: "This field is required",
fn: function (value) {
if (typeof value === "number") {
var bool = (value > 0) ? true : false;
} else {
bool = false;
}
return bool;
}
},
requiredCheckGroup: {
message: "This field is required",
fn: function (value) {
if (typeof value === "number") {
var bool = (value > 0) ? true : false;
} else {
bool = false;
}
return bool;
}
},
requiredFile: {
message: "This field is required",
fn: function (value) {
value = value.trim();
if (value === null || value.length === 0 || /^\s+$/.test(value)) {
return false;
}
return true;
}
},
requiredRadioGroup: {
message: "This field is required",
fn: function (value) {
value = typeof value === 'string' ? value.trim() : value;
return !!value || typeof value === 'number';
}
},
integer: {
message: "Invalid value for the integer field",
mask: /[\d\.]/i,
fn: function (n) {
return (typeof n === 'string') ? /^-?\d+$/.test(n) : !isNaN(n = parseFloat(n, 10) && n % 1 === 0);
}
},
float: {
message: "Invalid value for the float field",
fn: function (n) {
return /^-?\d+\.?\d*$/.test(n);
}
},
string: {
fn: function (string) {
return true;
}
},
boolean: {
fn: function (string) {
return true;
}
},
maxLength: {
message: "The maximum length are ",
fn: function (value, maxLength) {
var maxLen;
if (typeof maxLength !== "number") {
throw new Error("The parameter maxlength is not a number");
}
maxLen = (value.toString().length <= maxLength) ? true : false;
return maxLen;
}
},
/**
* validate that there is at least one row on the grid
* return [boolean]
*/
requiredGrid: {
message: "Information Required",
fn: function (value) {
if (value === null || value === 0) {
return false;
}
return true;
}
}
};
PMDynaform.extendNamespace("PMDynaform.core.Validators", Validators);
}());
(function () {
var ModalProgressBar = Backbone.View.extend({
timeHide: 1000,
template: _.template($("#tpl-modal-global").html()),
initialize: function () {
//TODO: no need params.
},
render: function () {
if ($('#modalProgressBar').length) {
$('#modalProgressBar').remove();
}
$('body').append(this.template());
this.show();
return this;
},
show: function () {
$('#modalProgressBar').modal({backdrop: 'static', keyboard: false}, 'show');
return this;
},
hide: function () {
if ($('#modalProgressBar').length) {
setTimeout(function () {
$('#modalProgressBar').modal('hide');
}, this.timeHide);
}
return this;
},
setTimeHide: function (timeHide) {
this.timeHide = timeHide;
return this;
},
getTimeHide: function () {
return this.timeHide;
}
});
PMDynaform.extendNamespace("PMDynaform.view.ModalProgressBar", ModalProgressBar);
}());
(function () {
var Project = function (options) {
this.model = null;
this.modalProgress = null;
this.view = null;
this.data = null;
this.delIndex = null;
this.fields = null;
this.keys = null;
this.token = null;
this.renderTo = null;
this.urlFormat = null;
this.endPointsPath = null;
this.forms = null;
this.externalLibs = null;
this.externalLibsArray = [];
this.dependentLibraries = null;
this.submitRest = null;
this.formAjax = null;
this.globalMode = null;
this.onSubmitForm = new Function();
this.language = "";
this.onBeforePrintHandler = null;
this.onAfterPrintHanlder = null;
this.flashView = null;
this.isRTL = false;
this.isPreview = false;
this.dynaformUid = null;
Project.prototype.init.call(this, options);
};
Project.prototype.init = function (options) {
var defaults = new PMDynaform.util.InputsValidation(),
that = this;
defaults = jQuery.extend(true, defaults.getDefaultData(), options);
defaults.endPointsPath = {
project: "",
createVariable: "process-variable",
variableList: "process-variable",
/**
* @key {var_uid} Defines the identifier of the variable
* The Endpoint is for get all information about Variable
**/
variableInfo: "process-variable/{var_uid}",
/**
* @key {var_name} Defines the variable name
* The Endpoint executes the query associated to variable
**/
executeQuery: "process-variable/{var_name}/execute-query",
/**
*
* @key {field_name} Defines the field name
* The Endpoint uploads a file
**/
uploadFile: "uploadfile/{field_name}",
executeQuerySuggest: "process-variable/{var_name}/execute-query-suggest",
fileStreaming: "en/neoclassic/cases/casesStreamingFile?actionAjax=streaming&a={caseID}&d={fileId}",
getAllDataCase: "case/{caseID}/variables",
imageDownload: 'light/case/{caseID}/download64',
fileDownload: "case/{caseID}/file/{fileID}",
imageInfo: "light/case/{caseID}/download64",
getImageGeo: "light/case/{caseID}/download64"
};
defaults.urlFormatMobile = "{server}/api/1.0/{workspace}/{endPointPath}";
defaults.urlFormat = "{server}/{apiName}/{apiVersion}/{workspace}/{keyProject}/{projectId}/{endPointPath}";
this.urlFormatStreaming = "{server}/sys{workspace}/{endPointPath}";
that.setIsRTL(defaults.isRTL);
that.setIsPreview(defaults.isPreview);
$("body").append("<div class='pmDynaformLoading'></div>");
this.loadExternalLibs(defaults.data, defaults.keys.server, function () {
that.delIndex = defaults.delIndex;
that.setDynaformUID(defaults.dynaformUid);
that.setFormAjax(defaults.formAjax);
that.setBeforePrintHandler(defaults.onBeforePrintHandler);
that.setAfterPrintHandler(defaults.onAfterPrintHandler);
that.setData(defaults.data);
that.setLanguage();
that.initModalProgress();
that.setUrlFormat(defaults.urlFormat);
that.setUrlFormatMobile(defaults.urlFormatMobile);
that.setKeys(defaults.keys);
that.setToken(defaults.token);
that.setRenderTo(defaults.renderTo);
that.setEndPointsPath(defaults.endPointsPath);
that.createWebServiceManager();
PMDynaform.setActiveProject(that);
that.checkMobileData();
that.submitRest = defaults.submitRest;
if (!PMDynaform.core.ProjectMobile) {
that.checkGeoMapsLibraries(defaults.onLoad);
} else {
that.checkGeoMapsLibraries();
}
//stop loading
$("body").find(".pmDynaformLoading").remove();
});
};
Project.prototype.setDynaformUID = function (dynUid) {
var dyn_uid = null;
if (dynUid || dynUid === null) {
dyn_uid = dynUid;
}
this.dynaformUid = dyn_uid;
return this;
};
/**
* sets the value true if the project is a preview of processmaker
*