// Licensed Materials - Property of IBM
//
// IBM Cognos Products: cpscrn
//
// (C) Copyright IBM Corp. 2005, 2011
//
// US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
//
//
(function () {
// Define the sharepoint namespace
if (!com_ibm_cognos_cps.sp) {
com_ibm_cognos_cps.sp = {};
}
// Make sure we only define the CPSCollaboration object once
if (com_ibm_cognos_cps.sp.CPSCollaboration) {
return;
}
com_ibm_cognos_cps.sp.executeWhenLoaded = function (f) {
if (ExecuteOrDelayUntilScriptLoaded) {
ExecuteOrDelayUntilScriptLoaded(f, 'sp.js');
}
}
// Metadata
var REPORT_TYPE_FORMATS = [
{
name: 'Excel 2002',
value: 'XLWA',
icon: 'ps/portal/images/icon_result_excel_web_arch.gif'
},
{
name: 'Excel 2007',
value: 'spreadsheetML',
icon: 'ps/portal/images/icon_result_excel_2007.gif'
},
{
name: 'PDF',
value: 'PDF',
icon: 'ps/portal/images/icon_result_pdf.gif'
}
];
var PUBLISH_OBJECT_TYPES = {
'dashboard': {
},
'reportView': {
runFormats: REPORT_TYPE_FORMATS
},
'report': {
runFormats: REPORT_TYPE_FORMATS
},
'query': {
runFormats: REPORT_TYPE_FORMATS
},
'analysis': {
runFormats: REPORT_TYPE_FORMATS
}
}
var ConfirmationDialog = function (options) {
this.message = options.message;
this.hint = options.hint;
this.title = options.title;
this.buttons = options.buttons;
}
ConfirmationDialog.prototype = {
getNode: function () {
if (!this.node) {
this.node = document.createElement('div');
var html = '
';
this.node.innerHTML = html;
// attach behavior
var _self = this;
this.form = this.node.getElementsByTagName('form')[0];
for (var i = 0, l = this.buttons.length; i < l; i++) {
if (this.form[this.buttons[i].name]) {
this.attachButtonOnClick(this.form[this.buttons[i].name], this.buttons[i].callback);
}
}
}
return this.node;
},
attachButtonOnClick: function (button, callback) {
button.onclick = function () {
SP.UI.ModalDialog.commonModalDialogClose();
if (callback) {
callback();
}
};
},
show: function () {
var self = this;
var node = this.getNode();
var options = {
html: node,
title: this.title,
allowMaximize: false,
showClose: true
};
SP.UI.ModalDialog.showModalDialog(options);
if (this.form[this.buttons[0].name]) {
this.form[this.buttons[0].name].focus();
}
}
}
com_ibm_cognos_cps.sp.ObjectTree = function (options) {
this.listType = options.listType;
this.selectionSpec = options.selectionSpec;
this.isShowRootWeb = options.isShowRootWeb;
this.autoErrorRecovery = options.autoErrorRecovery
this.isHideListFolders = options.isHideListFolders;
this.allowNoWriteItems = options.allowNoWriteItems;
this.selectedNode = null;
this.initialized = false;
}
com_ibm_cognos_cps.sp.ObjectTree.prototype = {
initialize: function (callback) {
if (!this.initialized) {
var node = this._createEmptyNode();
this.context = new SP.ClientContext();
// If we have a selection spec, create the nodes based on the information we have
if (this.selectionSpec) {
var nodes = this.selectionSpec.split(',');
for (var i = 0, l = nodes.length; i < l; i++) {
if (i > 0) {
var parent = node;
node = this._createEmptyNode();
node.parent = parent;
}
var values = nodes[i].split('|');
node.type = values[0];
node.title = values[1];
node.url = values[2];
node.webUrl = values[3];
node.listId = values[4];
if (node.type === 'web') {
node.object = this.context.get_site().openWeb(node.url);
} else if (node.type === 'folder') {
var web = this.context.get_site().openWeb(node.webUrl);
node.object = web.getFolderByServerRelativeUrl(node.url);
} else if (node.type === 'list') {
var w = this.context.get_site().openWeb(node.webUrl);
node.object = w.get_lists().getById(node.listId);
}
}
if (!this.isShowRootWeb) {
node.parent = null;
}
} else {
node.type = 'web';
node.object = this.isShowRootWeb ? this.context.get_site().get_rootWeb() : this.context.get_web();
if (this.isShowRootWeb) {
node.isRootWeb = true;
}
}
this.setNode(node, false, callback);
this.initialized = true;
}
else {
callback();
}
},
_createEmptyNode: function () {
return {
loaded: false,
title: null,
type: null,
image: null,
url: null,
object: null,
parent: null,
nodes: null
};
},
getNode: function () {
if (!this.initialized) {
return null;
}
return this.selectedNode;
},
setNode: function (node, fetchChildren, callback) {
this.selectedNode = node;
if (node.nodes !== null) {
callback();
return;
}
if (node.type == 'web') {
this.getWebChildrenCallback(node, fetchChildren, callback);
} else if (node.type == 'list') {
this.getListChildrenCallback(node, fetchChildren, callback);
} else if (node.type == 'folder') {
this.getFolderChildrenCallback(node, fetchChildren, callback);
}
},
getWebChildrenCallback: function (container, fetchChildren, callback) {
// used in retries ..
var originalArguments = { 'callback': callback, 'fetchChildren': fetchChildren };
var obj = container.object;
if (!container.loaded) {
this.context.load(obj);
}
var listCollection = null;
if (fetchChildren) {
listCollection = obj.get_lists();
this.context.load(listCollection);
}
var getListSuccess = Function.createDelegate(this, function () {
if (!container.loaded) {
container.loaded = true;
container.title = obj.get_title();
container.url = obj.get_serverRelativeUrl();
container.image = '/_layouts/images/SharePointFoundation16.png';
}
if (fetchChildren) {
container.nodes = [];
// get lists permissions
var webLists = [];
var webListsRootFolders = [];
for (var i = 0, l = listCollection.get_count(); i < l; i++) {
var list = listCollection.get_item(i);
this.context.load(list, 'Title', 'ImageUrl', 'EffectiveBasePermissions');
webLists.push(list);
// root folder is needed to get the list url
var folder = list.get_rootFolder();
this.context.load(folder);
webListsRootFolders.push(folder);
}
var getListDetailSuccess = function () {
for (var i = 0, l = webLists.length; i < l; i++) {
var list = webLists[i];
var rootFolder = webListsRootFolders[i];
if (!list.get_hidden() && list.get_baseTemplate() === this.listType && (this.allowNoWriteItems || list.get_effectiveBasePermissions().has(SP.PermissionKind.addListItems))) {
var node = {
loaded: true,
title: list.get_title(),
parent: container,
nodes: null,
type: 'list',
object: list,
image: list.get_imageUrl(),
url: rootFolder.get_serverRelativeUrl()
};
container.nodes.push(node);
}
}
// Now get subwebs
var webs = obj.getSubwebsForCurrentUser();
this.context.load(webs);
var getSubwebSuccess = Function.createDelegate(this, function () {
// add sub webs
var webNodes = [];
for (var i = 0, l = webs.get_count(); i < l; i++) {
var web = webs.get_item(i);
var node = {
loaded: true,
title: web.get_title(),
parent: container,
nodes: null,
type: 'web',
object: web,
image: '/_layouts/images/SharePointFoundation16.png',
url: web.get_serverRelativeUrl()
};
webNodes.push(node);
}
container.nodes = webNodes.concat(container.nodes);
callback();
});
this.executeQuery(getSubwebSuccess, originalArguments, function () {
// No access for subwebs .. simply ignore
callback();
return true;
});
}
this.executeQuery(getListDetailSuccess, originalArguments);
} else {
callback();
}
});
this.executeQuery(getListSuccess, originalArguments);
},
getListChildrenCallback: function (container, fetchChildren, callback) {
// used in retries ..
var originalArguments = { 'callback': callback, 'fetchChildren': fetchChildren };
var obj = container.object;
var rootFolder;
if (!container.loaded) {
this.context.load(obj, 'Title', 'ImageUrl', 'EffectiveBasePermissions');
rootFolder = obj.get_rootFolder();
this.context.load(rootFolder);
}
if (!this.isHideListFolders && fetchChildren) {
var items = obj.getItems([]);
var folders = obj.get_rootFolder().get_folders();
this.context.load(items);
this.context.load(folders);
}
var onSuccess = Function.createDelegate(this, function () {
if (!container.loaded) {
container.loaded = true;
container.title = obj.get_title();
container.image = obj.get_imageUrl();
container.url = rootFolder.get_serverRelativeUrl();
}
if (fetchChildren) {
container.nodes = [];
if (!this.isHideListFolders) {
for (var i = 0, l = items.get_count(); i < l; i++) {
var item = items.get_item(i);
if (item.get_fileSystemObjectType() === 1) {
// lookup the folder
var folder = null;
var name = item.get_item('Title');
for (var j = 0, jlen = folders.get_count(); j < jlen; j++) {
if (folders.itemAt(j).get_name() == name) {
folder = folders.itemAt(j);
break;
}
}
if (folder) {
var node = {
loaded: true,
title: name,
parent: container,
nodes: null,
type: 'folder',
object: folder,
item: item,
image: '/_layouts/images/folder.gif',
url: folder.get_serverRelativeUrl()
};
container.nodes.push(node);
}
}
}
}
}
callback();
});
this.executeQuery(onSuccess, originalArguments);
},
getFolderChildrenCallback: function (container, fetchChildren, callback) {
// used in retries ..
var originalArguments = { 'callback': callback, 'fetchChildren': fetchChildren };
var obj = container.object;
if (!container.loaded) {
this.context.load(obj);
}
if (fetchChildren) {
var folders = obj.get_folders();
this.context.load(folders);
}
var onSuccess = Function.createDelegate(this, function () {
if (!container.loaded) {
container.loaded = true;
container.title = obj.get_name();
container.url = obj.get_serverRelativeUrl();
container.image = '/_layouts/images/folder.gif';
}
if (fetchChildren) {
container.nodes = [];
for (var i = 0, l = folders.get_count(); i < l; i++) {
var f = folders.itemAt(i);
var node = {
loaded: true,
title: f.get_name(),
parent: container,
nodes: null,
type: 'folder',
object: f,
image: '/_layouts/images/folder.gif',
url: f.get_serverRelativeUrl()
};
container.nodes.push(node);
}
}
callback();
});
this.executeQuery(onSuccess, originalArguments);
},
executeQuery: function (successCallback, originalArguments, errorHandler) {
this.context.executeQueryAsync(
Function.createDelegate(this, successCallback),
Function.createDelegate(this, function (request, error) {
this.onFail(request, error, originalArguments, errorHandler);
}));
},
getSelectionData: function (node) {
var data = {};
var selectionSpec = '';
var n = node;
var fullName = '';
while (n) {
fullName = n.title + (fullName !== '' ? ' > ' : '') + fullName;
var s = n.type + '|' + n.title + '|' + n.url + '|' + this.getWebUrl(n) + '|' + this.getListId(n);
selectionSpec = s + (selectionSpec !== '' ? ',' : '') + selectionSpec;
n = n.parent;
}
data.fullName = fullName;
data.selectionSpec = selectionSpec;
data.type = node.type;
data.title = node.title;
data.image = node.image;
data.url = node.url;
data.webUrl = this.getWebUrl(node);
data.listId = this.getListId(node);
return data;
},
getListId: function (container) {
var n = container;
while (n) {
if (n.listId) {
return n.listId;
} else if (n.type === 'list') {
return n.object.get_id().toString();
}
n = n.parent;
}
return '';
},
getWebUrl: function (container) {
var n = container;
while (n) {
if (n.webUrl) {
return n.webUrl;
} else if (n.type === 'web') {
return n.object.get_serverRelativeUrl();
}
n = n.parent;
}
return '';
},
canWriteToNode: function (node) {
return ((node.type === 'list' && node.object.get_effectiveBasePermissions().has(SP.PermissionKind.addListItems)) || node.type === 'folder')
},
onFail: function (request, error, originalArguments, errorHandler) {
if (errorHandler) {
// caller special handler.
if (errorHandler()) {
return;
}
}
var originalCallback = (originalArguments && originalArguments.callback) ? originalArguments.callback : null;
if (this.autoErrorRecovery && originalCallback) {
// try to recover
if (error.get_errorTypeName() === 'System.UnauthorizedAccessException') {
if (this.selectionSpec) {
this.ignoredUserSelection = this.selectedNode;
// retry with root web
this.selectionSpec = null;
var node = this._createEmptyNode();
node.object = this.context.get_site().get_rootWeb();
node.type = 'web';
node.isRootWeb = true;
this.setNode(node, originalArguments.fetchChildren, originalCallback)
return;
}
if (this.selectedNode.isRootWeb) {
// retry with current web
var node = this._createEmptyNode();
node.object = this.context.get_web();
node.type = 'web';
this.setNode(node, originalArguments.fetchChildren, originalCallback)
return;
}
}
}
this.error = error;
if (error.get_errorTypeName() !== 'System.UnauthorizedAccessException') {
var status = SP.UI.Status.addStatus(error.get_errorTypeName(), '', false);
SP.UI.Status.setStatusPriColor(status, 'red');
SP.UI.Status.updateStatus(status, error.get_message());
}
if (originalCallback) {
// it's up to the called to check error state.
originalCallback();
}
}
}
com_ibm_cognos_cps.sp.SelectDialog = function (options) {
this.options = options;
this.messages = this.options.messages;
this.height = this.options.height ? this.options.height : 500;
this.width = this.options.width ? this.options.width : 500;
this.objectTree = options.objectTree;
this.title = this.options.title;
this.okCallback = this.options.okCallback;
this.selection = null;
this.canSelectReadOnly = this.options.canSelectReadOnly;
}
com_ibm_cognos_cps.sp.SelectDialog.prototype = {
getString: function (id, args) {
if (this.messages && this.messages[id]) {
var msg = this.messages[id];
if (args) {
for (var i = 0, l = args.length; i < l; i++) {
msg = msg.replace('$' + (i + 1), args[i]);
}
}
return msg;
}
return id + ' [' + (args ? args.toString() : '') + ']';
},
addClass: function (element, className) {
if (!element.className) {
element.className = className;
} else {
element.className = element.className + ' ' + className;
}
return element;
},
removeClass: function (element, className) {
if (element.className) {
element.className = element.className.replace(className, '').trim();
}
return element;
},
createDomNode: function () {
if (!this.domNode) {
this.domNode = document.createElement('div');
this.domNode.style.height = this.height + 'px';
this.domNode.style.width = this.width + 'px';
// header
var div = document.createElement('div');
div.className = 's4-title';
this.domNode.appendChild(div);
var table = document.createElement('table');
table.className = 's4-titletable';
div.appendChild(table);
var tr = document.createElement('tr');
table.appendChild(tr);
this.header = document.createElement('td');
tr.appendChild(this.header);
this.header.className = 's4-titletext';
var divider = document.createElement('div');
divider.className = 'ms-partline';
div.appendChild(divider);
//content
this.content = document.createElement('div');
this.content.style.paddingLeft = '5px';
this.content.style.overflow = 'auto';
this.content.appendChild(this.createTable());
this.domNode.appendChild(this.content);
//footer
this.footer = document.createElement('div');
this.footer.innerHTML = '';
this.domNode.appendChild(this.footer);
this.form = this.domNode.getElementsByTagName('form')[0];
this.fileNameTable = this.form.elements[0];
this.fileNameTable.width = '100%';
// Attach behavior
var _self = this;
this.form['ok'].onclick = function () {
_self.updateSelectionInfo();
SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK, _self.selection);
}
this.form['cancel'].onclick = function () {
SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel);
}
this.form['fileName'].onchange = Function.createDelegate(this, function () {
this.setValidSelection(this.fileNameTable.style.display === 'none' || this.form['fileName'].value !== '');
});
}
return this.domNode;
},
createTable: function () {
if (!this.table) {
var table, tbody, tr, th;
table = document.createElement('table');
table.className = 'ms-listviewtable';
table.style.borderSpacing = '0px';
table.border = '0';
table.width = '100%';
tbody = document.createElement('tbody');
table.appendChild(tbody);
this.tbody = tbody;
this.table = table;
}
return this.table;
},
createRow: function (container, index) {
var title = container.title;
var table = this.tbody;
var tr, td, a, div;
tr = document.createElement('tr');
tr.onclick = Function.createDelegate(this, function () { this.selectRow(tr, container) });
tr.className = 'ms-itmhover';
if (index % 2 == 1) {
this.addClass(tr, 'ms-alternating');
}
table.appendChild(tr);
td = document.createElement('td');
td.className = 'ms-vb-icon ms-vb-firstCell';
tr.appendChild(td);
var type = this.getObjectTypeLabel(container);
td.innerHTML = '
';
td = document.createElement('td');
td.height = '100%';
td.width = '99%';
td.className = 'ms-vb-title ms-vb-lastCell';
tr.appendChild(td);
div = document.createElement('div');
div.className = 'ms-vb itx';
td.appendChild(div);
a = document.createElement('a');
a.onclick = Function.createDelegate(this, function () { this.drill(container) });
a.href = 'javascript:';
a.title = a.alt = title;
a.innerHTML = title;
div.appendChild(a);
},
setNameInput: function (filename) {
this.fileNameTable.style.display = '';
this.form['fileName'].value = filename;
},
setValidSelection: function (isValid) {
if (isValid) {
this.form['ok'].disabled = false;
} else {
this.form['ok'].disabled = true;
}
},
setSelection: function (node) {
this.selection = this.objectTree.getSelectionData(node);
this.selection.typeLabel = this.getObjectTypeLabel(this.selection);
this.setValidSelection(this.canSelectReadOnly || this.objectTree.canWriteToNode(node));
},
updateSelectionInfo: function () {
this.selection.fileName = this.form['fileName'].value;
},
selectRow: function (row, folder) {
if (this.selectedRow) {
this.removeClass(this.selectedRow, 's4-itm-selected');
}
this.selectedRow = row;
this.addClass(row, 's4-itm-selected');
this.setSelection(folder);
},
drill: function (node) {
this.updateContent(node);
},
updateBreadCrumbs: function (container) {
this.header.innerHTML = '';
var node = container;
while (node != null) {
var nodeText = document.createElement('h2');
var a = document.createElement('a');
a.onclick = this.createBreadCrumbOnclick(node);
a.href = 'javascript:';
a.title = a.alt = container.title;
a.innerHTML = node.title;
nodeText.appendChild(a);
this.header.insertBefore(nodeText, this.header.firstChild);
node = node.parent;
if (node != null) {
var sep = document.createElement('span');
sep.style.padding = '3px';
sep.innerHTML = '
';
this.header.insertBefore(sep, this.header.firstChild);
}
}
// add the image
var img = document.createElement('img');
img.src = container.image;
img.title = img.alt = this.getObjectTypeLabel(container)
img.style.marginRight = '5px';
img.style.paddingBottom = '3px';
img.style.verticalAlign = 'middle';
this.header.insertBefore(img, this.header.firstChild);
},
createBreadCrumbOnclick: function (node) {
return Function.createDelegate(this, function () { this.drill(node) });
},
updateContent: function (container, callback) {
this.objectTree.setNode(container, true, Function.createDelegate(this, function () {
var selected = this.objectTree.getNode();
this.setSelection(selected);
var nodes = selected.nodes;
var rows = this.tbody.childNodes;
for (var i = rows.length - 1; i >= 0; i--) {
this.tbody.removeChild(rows[i]);
}
for (var i = 0, l = nodes.length; i < l; i++) {
this.createRow(nodes[i], i);
}
this.updateBreadCrumbs(selected);
//this.domNode.focus(); // causes the dialog not to show the second time .. after domNode was created..
if (callback) {
callback();
}
}));
},
getObjectTypeLabel: function (container) {
var type;
if (container.type === 'web') {
type = this.getString('IDS_SP_OBJECT_TYPE_SITE');
} else if (container.type === 'folder') {
type = this.getString('IDS_SP_OBJECT_TYPE_FOLDER');
} else if (container.type === 'list') {
if (this.objectTree.listType === SP.ListTemplateType.documentLibrary) {
type = this.getString('IDS_SP_OBJECT_TYPE_DOCUMENT_LIBRARY');
} else if (this.objectTree.listType === SP.ListTemplateType.discussionBoard) {
type = this.getString('IDS_SP_OBJECT_TYPE_DISCUSSION_LIST');
}
}
return type;
},
resize: function () {
this.content.style.height = (this.domNode.clientHeight - this.header.clientHeight - this.footer.clientHeight - 20) + 'px';
},
initialize: function (callback) {
ExecuteOrDelayUntilScriptLoaded(
Function.createDelegate(this, function () {
if (!this.initialized) {
this.objectTree.initialize(Function.createDelegate(this, function () {
if (this.objectTree.error) {
callback();
return;
}
if (this.objectTree.ignoredUserSelection) {
this.ignoredSelection = this.objectTree.getSelectionData(this.objectTree.ignoredUserSelection);
this.ignoredSelection.typeLabel = this.getObjectTypeLabel(this.ignoredSelection);
}
this.createDomNode();
this.setSelection(this.objectTree.getNode());
this.initialized = true;
callback();
}));
}
}), 'core.js');
},
show: function (allowAutoSelection) {
if (!this.initialized) {
this.initialize(Function.createDelegate(this, this.show));
return;
}
this.updateContent(this.objectTree.getNode(), Function.createDelegate(this, function () {
var node = this.objectTree.getNode();
var isPromptNotRequiredHint = this.objectTree.canWriteToNode(node);
if (allowAutoSelection && isPromptNotRequiredHint && (this.isPrompted === undefined || !this.isPrompted)) {
this.updateSelectionInfo();
this.okCallback(this.selection);
} else {
var self = this;
var options = {
html: this.domNode,
title: this.title,
height: this.height,
width: this.width,
allowMaximize: false,
showClose: true,
dialogReturnValueCallback: function (result, data) {
if (result === SP.UI.DialogResult.OK && self.okCallback) {
self.okCallback(data);
}
}
};
this.isPrompted = true;
this.dialogSP = SP.UI.ModalDialog.showModalDialog(options);
this.domNode.focus();
this.resize();
}
}));
}
}
com_ibm_cognos_cps.sp.CPSCollaboration = function (context, id, messages) {
this.context = context;
this.id = id
this.messages = messages;
// start the initialization once the sp.js is loaded.
ExecuteOrDelayUntilScriptLoaded(Function.createDelegate(this, this.initialize), 'sp.js');
com_ibm_cognos_cps.sp.CPSCollaboration.prototype.instances[id] = this;
}
com_ibm_cognos_cps.sp.CPSCollaboration.prototype = {
instances: {},
initialize: function () {
var initializeMenus = Function.createDelegate(this, function () {
this.discussionSelectionDlg = new com_ibm_cognos_cps.sp.SelectDialog({
title: this.getString('IDS_SP_EDT_SELECT_DLG_DISCUSSION_TITLE'),
height: 350,
width: 500,
messages: this.messages,
objectTree: new com_ibm_cognos_cps.sp.ObjectTree({
listType: SP.ListTemplateType.discussionBoard,
isShowRootWeb: false,
isHideListFolders: true,
selectionSpec: this.context.getProperty('parameters')['discussionSpec']
})
});
this.discussionSelectionDlg.initialize(Function.createDelegate(this, function () {
// hide discussion menu if we have security exception
if (!this.discussionSelectionDlg.objectTree.error) {
this.showDiscussMenu();
}
}));
this.publishSelectionDlg = new com_ibm_cognos_cps.sp.SelectDialog({
title: this.getString('IDS_SP_EDT_SELECT_DLG_PUBLISH_TITLE'),
height: 350,
width: 500,
messages: this.messages,
objectTree: new com_ibm_cognos_cps.sp.ObjectTree({
listType: SP.ListTemplateType.documentLibrary,
isShowRootWeb: false,
selectionSpec: this.context.getProperty('parameters')['publishSpec']
})
});
var _self = this;
this.publishSelectionDlg.initialize(Function.createDelegate(this, function () {
if (!this.publishSelectionDlg.objectTree.error) {
_self.initializePublishMenu();
}
}));
});
this.getFeedEntry(initializeMenus);
},
/* Return a unique Id */
getId: function (id) {
return this.id + '.' + id;
},
/* Return the localized string */
getString: function (id, args) {
if (this.messages && this.messages[id]) {
var msg = this.messages[id];
if (args) {
for (var i = 0, l = args.length; i < l; i++) {
msg = msg.replace('$' + (i + 1), args[i]);
}
}
return msg;
}
return id + ' [' + (args ? args.toString() : '') + ']';
},
/* Returns the href value of the feed entry link */
getLink: function (entry, rel, type, location) {
var links = this.insureArray(entry.link);
for (var i = 0, l = links.length; i < l; i++) {
if (links[i].rel === rel && links[i].type === type) {
if (location === 'webcontent') {
return this.context.getWebContentResource(links[i].href);
} else {
return this.context.getGatewayResource(links[i].href);
}
}
}
},
/* Returns the text content of an xml node*/
getElementText: function (document, path) {
return com_ibm_cognos_cps._F_DOM.text(com_ibm_cognos_cps._F_DOM.selectSingleNode(document, path));
},
/* Returns the CM object id */
getObjectId: function () {
return this.context.getProperty('parameters')['reportStoreId'];
},
getObjectPath: function () {
return this.context.getProperty('parameters')['searchPath'];
},
getObjectUrl: function () {
return this.context.getProperty('parameters')['objectUrl'];
},
isPublishWithoutPrompt: function () {
return this.context.getProperty('parameters')['publishWithoutPrompt'] === 'true';
},
isRunSupported: function () {
return this.context.getProperty('parameters')['canRun'];
},
getSessionId: function () {
return this.context.getProperty('parameters')['sessionId'];
},
/* Returns the gateway url */
getGateway: function () {
return this.context.getProperty('gateway');
},
/* Returns the webcontent url */
getWebcontent: function () {
return this.context.getProperty('webcontent');
},
/* Returns the content locale */
getContentLocale: function () {
return this.context.getProperty('contentLocale')
},
getSessionInfo: function () {
var sessionController = this.context.getProperty('sessionController');
return sessionController ? sessionController.sessionInfo : null;
},
toAbsolute: function (relativeUrl) {
return document.location.protocol + '//' + document.location.host + (document.location.port ? (':' + document.location.port) : '') + relativeUrl;
},
/* Returns a string that can be evaluated to run a this.method(parameters) */
createFunctionCall: function (functionName) {
var call = 'com_ibm_cognos_cps.sp.CPSCollaboration.prototype.instances["' + this.id.replace(/"/g, '\\"') + '"].' + functionName + '(';
for (var i = 1, l = arguments.length; i < l; i++) {
if (i > 1) {
call += ', ';
}
var arg = arguments[i];
if (arg === undefined || arg === null) {
call += 'null';
} else if (typeof arg === 'boolean' || typeof arg === 'number') {
call += arg;
} else {
call += '"' + arg.toString().replace(/"/g, '\\"') + '"';
}
}
call += ')';
return call;
},
/* Show a sharepoint notification */
showNotification: function (notification, sticky) {
this.removeNotification();
var notificationId = SP.UI.Notify.addNotification(notification, sticky);
if (!sticky) {
this.notificationId = notificationId;
}
return notificationId;
},
/* Hide a sharepoint notification */
removeNotification: function (id) {
if (id) {
SP.UI.Notify.removeNotification(id);
} else if (this.notificationId) {
SP.UI.Notify.removeNotification(this.notificationId);
this.notificationId = null;
}
},
/* Insure that the object is an array, if not an array with the object will be returned */
insureArray: function (obj) {
if (!obj || obj.length) {
return obj;
} else {
return [obj];
}
},
handleError: function (e, htmlErrorPage) {
if (this.errorStatus) {
SP.UI.Status.removeStatus(this.errorStatus);
}
var message = e.message ? e.message : e.toString();
if (message === 'cps.invalidCredentials') {
message = this.getString('IDS_SP_ERROR_SESSION_EXPIRED');
} else if (htmlErrorPage) {
// open up that HTML markup and let the end-user deal with it
message = this.extractTagText(htmlErrorPage, 'ERROR_MSG');
var w = window.open('', '_blank', 'width=700,height=600,resizable,status=no,menubar=no,toolbar=no,location=no');
w.document.open();
w.document.write(htmlErrorPage);
w.document.close();
w.focus();
}
this.errorStatus = SP.UI.Status.addStatus(this.getString('IDS_SP_ERROR_LABEL'), '', false);
SP.UI.Status.setStatusPriColor(this.errorStatus, 'red');
message = message + ' ' + this.getString('IDS_SP_ERROR_CLEAR') + '';
SP.UI.Status.updateStatus(this.errorStatus, message);
},
extractTagText: function (text, tagName) {
var lowerText = text.toLowerCase();
tagName = tagName.toLowerCase();
var fromIndex = lowerText.indexOf('<' + tagName);
if (fromIndex == -1) {
return '';
}
// skip attributes
fromIndex = lowerText.indexOf('>', fromIndex + tagName.length + 1);
if (fromIndex == -1) {
return '';
}
fromIndex++;
var toIndex = lowerText.indexOf('' + tagName + '>', fromIndex);
if (toIndex == -1) {
return '';
}
return text.substring(fromIndex, toIndex);
},
showPublishMenu: function () {
// show the publish menu
document.getElementById(this.getId('id.toolbar')).style.display = '';
document.getElementById(this.getId('id.publish_menulink')).style.display = '';
},
showDiscussMenu: function () {
// show the publish menu
document.getElementById(this.getId('id.toolbar')).style.display = '';
document.getElementById(this.getId('id.discuss_menulink')).style.display = '';
},
/* helper function that sends an ajax request */
sendRequest: function (url, xhrOptions) {
try {
var xhr = this.context.getXHR();
var method = xhrOptions.method ? xhrOptions.method : 'GET';
xhr.open(method, xhrOptions.noProxy ? url : this.context.getProxiedResource(url), true);
if (method === 'POST') {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
if (xhrOptions.includeSessionHeader) {
xhr.setRequestHeader('com-ibm-congos-cps-session', this.getSessionInfo());
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status >= 200 && xhr.status < 300) {
if (xhrOptions.callback) {
xhrOptions.callback(xhr);
}
} else {
if (xhrOptions.callbackOnFailure) {
xhrOptions.callbackOnFailure(null);
}
}
}
}
xhr.send(xhrOptions.data ? xhrOptions.data : null);
} catch (e) {
this.handleError(e);
}
},
/* Get the CM object feed entry */
getFeedEntry: function (callback) {
var objId = this.getObjectId();
var url = this.getGateway() + '/icd/feeds/cm/id/' + objId + '?entry=&json=';
var self = this;
this.sendRequest(url, {
method: 'GET',
callback: Function.createDelegate(this, function (xhr) { this.getFieldEntryCallback(xhr, callback); })
});
},
/* feed entry ajax callback. Used to add the list of reports/outputs to the "publish" menu */
getFieldEntryCallback: function (xhr, callback) {
this.reports = [];
this.atomEntry = eval('(' + xhr.responseText + ')');
this.versionMap = {};
if (this.atomEntry.entry) {
this.objectTitle = this.atomEntry.entry.title._text;
}
if (callback) {
callback();
}
},
initializePublishMenu: function () {
var type = this.atomEntry.entry['cm$targetObjectClass'] ? this.atomEntry.entry['cm$targetObjectClass'] : this.atomEntry.entry['cm$objectClass'];
if (!PUBLISH_OBJECT_TYPES[type]) {
// object type does not support publishing.
return;
}
this.showPublishMenu();
if (this.atomEntry.entry.dashboard) {
this.isDashboard = true;
var cl = this.getContentLocale();
// find all reports in the dashboard and get version.
var pageArr = this.insureArray(this.atomEntry.entry.dashboard.page);
var i, l = pageArr.length;
for (i = 0; i < l; i++) {
var instanceArr = {};
if (pageArr[i].widgetInstance !== undefined) {
instanceArr = this.insureArray(pageArr[i].widgetInstance);
}
for (var z = 0; z < instanceArr.length; z++) {
var instance = instanceArr[z];
if (instance.url.indexOf('ViewerIWidget.xml') != -1) {
var report = {};
report.title = instance.title;
// Try to find localized custom title
if (instance.customTitles) {
if (instance.customTitles.title) {
var titleArray = this.insureArray(instance.customTitles.title);
for (var j = 0, jlength = titleArray.length; j < jlength; j++) {
if (titleArray[j].locale === cl) {
report.title = titleArray[j].value;
break;
}
}
}
}
this.reports.push(report);
if (instance.contentItemSet && instance.contentItemSet.item) {
var j, k = instance.contentItemSet.item.length;
for (j = 0; j < k; j++) {
var item = instance.contentItemSet.item[j];
if (item.id === 'savedReportId') {
report.id = item.value;
} else if (item.id === 'savedReportName') {
report.name = item.value;
} else if (item.id === 'objectClass') {
report.type = item.value;
}
}
}
var reportSubMenu = CASubM(this.getPublishMenu(), report.title);
this.getVersions(report, reportSubMenu);
}
}
}
} else {
var report = { id: this.getObjectId(), title: this.objectTitle, type: type };
this.reports.push(report);
this.getVersions(report, this.getPublishMenu());
}
},
/* Get the output feed of a report and add the outputs to the "publish* menu */
getVersions: function (report, publishMenu) {
var url = this.getGateway() + '/atom/cm/id/' + report.id + '?filter=content-version&json';
this.sendRequest(url, {
method: 'GET',
callback: Function.createDelegate(this, function (xhr) {
var response = eval('(' + xhr.responseText + ')');
report.versionsFeed = response.feed;
this.createReportMenu(report, publishMenu);
})
});
},
/* Return the publish menu object */
getPublishMenu: function () {
if (this.publishMenu == null) {
this.publishMenu = CMenu(this.getId('id.publish_menu'));
}
return this.publishMenu;
},
/* Open the "publish" menu item */
publishMenuClick: function () {
OMenu(this.getPublishMenu(), document.getElementById(this.getId('id.publish_menulink')), true, null, -1);
},
/* Populate the "publish" menu with the menu items associated with a report */
createReportMenu: function (report, parentMenu) {
if (this.isRunSupported()) {
if (PUBLISH_OBJECT_TYPES[report.type].runFormats) {
var formats = PUBLISH_OBJECT_TYPES[report.type].runFormats;
var l = formats.length;
if (l > 0) {
// add the formats menu
var formatsSubMenu = CASubM(parentMenu, this.getString('IDS_SP_MENU_RUN_PUBLISH')); // 'Run and publish');
for (var i = 0; i < l; i++) {
CAMOpt(formatsSubMenu, formats[i].name, this.createFunctionCall('runAndPublish', report.id, formats[i].value, report.title), this.getWebcontent() + formats[i].icon);
}
}
}
}
if (report.versionsFeed) {
var versions = this.insureArray(report.versionsFeed.entry);
if (versions && versions.length > 0) {
var subMenu = CASubM(parentMenu, this.getString('IDS_SP_MENU_VERSIONS')); // 'Versions'
var versionResponseArr = [];
for (var i = 0, l = versions.length; i < l; i++) {
var version = versions[i];
var name = version.title._text;
versionResponseArr.push({ name: name, received: false, text: null });
//call to build the version submenu
var outputUrl = this.getLink(version, 'alternate', 'application/atom+xml');
this.createReportOutputVersionSubMenu(report, subMenu, outputUrl, versionResponseArr, i, versions.length);
}
}
}
},
createReportOutputVersionSubMenu: function (report, subMenu, outputUrl, versionResponseArr, versionResponseIndex, expectedVersionCount) {
// do an ajax to get the outputs..
this.sendRequest(outputUrl, {
method: 'GET',
callback: Function.createDelegate(this, function (xhr) {
var name = versionResponseArr[versionResponseIndex].name;
versionResponseArr[versionResponseIndex] = { name: name, received: true, text: xhr.responseText };
this.tryPopulateOutputVersionSubMenu(report, subMenu, versionResponseArr, expectedVersionCount);
}),
callbackOnFailure: Function.createDelegate(this, function (xhr) {
var name = versionResponseArr[versionResponseIndex].name;
versionResponseArr[versionResponseIndex] = { name: name, received: true, text: null };
this.tryPopulateOutputVersionSubMenu(report, subMenu, versionResponseArr, expectedVersionCount, subMenu);
})
});
},
tryPopulateOutputVersionSubMenu: function (report, subMenu, versionResponseArr, expectedVersionCount) {
var responseCount = 0; // count the version outputs received so far
for (var i = 0; i < versionResponseArr.length; i++) {
if (versionResponseArr[i] != null && versionResponseArr[i].received) {
responseCount += 1;
}
}
var receivedAllVersionResponses = (responseCount == expectedVersionCount);
if (receivedAllVersionResponses) {
for (var i = 0; i < versionResponseArr.length; i++) {
var name = versionResponseArr[i].name;
var responseText = versionResponseArr[i].text;
if (responseText != null) {
try {
var output = eval('(' + responseText + ')');
this.createOutputMenu(subMenu, name, output.feed, report);
} catch (e) {
//ignore bad response
}
}
}
}
},
/* Create the output sub-menu */
createOutputMenu: function (versionsMenu, versionName, outputFeed, report) {
var versionMenu = null;
var outputs = this.insureArray(outputFeed.entry);
if (outputs && outputs.length > 0) {
var j, k = outputs.length;
for (j = 0; j < k; j++) {
var output = outputs[j];
var outputFormatName = output.title._text
var icon = this.getLink(output, 'icon', 'image/gif', 'webcontent');
var url = this.getLink(output, 'action.download', 'application/octet-stream');
if (url) {
if (versionMenu === null) {
versionMenu = CASubM(versionsMenu, versionName);
}
CAMOpt(versionMenu, outputFormatName, this.createFunctionCall('publishUrlContent', url, report.title), icon);
}
}
}
},
/* Do an Ajax request to run a report, then publish the content to the document library */
runAndPublish: function (reportId, format, title) {
if (this.getSessionInfo() == null) {
this.showNotification(this.getString('IDS_SP_PUBLISH_NO_SESSION'), false);
return;
}
var notification = null;
var runFunction = Function.createDelegate(this, function (runUrl, docLibUrl, filename, postData) {
if (!notification) {
notification = this.showNotification(this.getString('IDS_SP_RUNNING_REPORT'), true); // 'Running report ..'
}
this.sendRequest(runUrl, {
method: postData ? 'POST' : 'GET',
includeSessionHeader: true,
data: postData,
callback: Function.createDelegate(this, function (xhr) {
var response = eval('(' + xhr.responseText + ')');
if (response.status === 'complete') {
this.removeNotification(notification);
this.publishDocument(docLibUrl, this.getGateway() + '?' + response.url, filename);
} else if (response.status.indexOf('working') !== -1) {
// build the run url and poll..
var postParams = '';
for (var name in response.parameters) {
if (postParams !== '') {
postParams += '&';
}
postParams += name + '=' + encodeURIComponent(response.parameters[name]);
}
runFunction(this.getGateway(), docLibUrl, filename, postParams);
}
else if (response.status === 'prompting') {
this.removeNotification(notification);
this.handleError(this.getString('IDS_SP_PUBLISH_MISSING_PROMPTS'));
}
else if (response.fault) {
this.removeNotification(notification);
var error;
if (response.status === 'authenticationFault') {
error = this.getString('IDS_SP_ERROR_SESSION_EXPIRED');
} else {
var faultElement = com_ibm_cognos_cps._F_DOM.parseXml(response.fault);
var messageNode = com_ibm_cognos_cps._F_DOM.selectSingleNode(faultElement, '/SOAP-ENV:Envelope/SOAP-ENV:Body/SOAP-ENV:Fault/SOAP-ENV:detail/bus:exception/bus:message');
if (!messageNode) {
var messageNode = com_ibm_cognos_cps._F_DOM.selectSingleNode(faultElement, '/SOAP-ENV:Envelope/SOAP-ENV:Body/SOAP-ENV:Fault/detail/bus:exception/bus:message');
}
if (!messageNode) {
messageNode = com_ibm_cognos_cps._F_DOM.selectSingleNode(faultElement, '/SOAP-ENV:Envelope/SOAP-ENV:Body/SOAP-ENV:Fault/faultstring');
}
if (messageNode) {
error = com_ibm_cognos_cps._F_DOM.text(messageNode);
} else {
error = this.getString('IDS_SP_CANNOT_RUN_REPORT');
}
}
// conversation object does not exist. It must be because the report didn't run
if (error.indexOf('RSV-BBP-0028') != -1) {
this.showNotification(this.getString('IDS_SP_PUBLISH_NO_SESSION'), false);
return;
}
this.handleError(error);
}
})
});
});
var dlg = this.publishSelectionDlg;
dlg.okCallback = Function.createDelegate(this, function (data) {
var runUrl;
if (this.isDashboard) {
// if it's a dashboard we simply run the reports
runUrl = this.getGateway() + '?b_action=cognosViewer&ui.action=run&run.prompt=false&ui.object=storeID("' + reportId + '")&cv.responseFormat=downloadObjectJSON&run.outputFormat=' + format;
} else {
// Otherwise we use the render action to re-use existing conversation saved by the viewer
runUrl = this.getGateway() + '?b_action=cognosViewer&ui.action=render&cv.responseFormat=downloadObjectJSON&run.outputFormat=' + format + '&m_sessionConv=' + encodeURIComponent(this.getSessionId());
}
runFunction(runUrl, data.url, data.fileName);
});
dlg.setNameInput(title);
dlg.show(this.isPublishWithoutPrompt());
},
/* Publish a url content to the document library */
publishUrlContent: function (downloadUrl, title) {
var dlg = this.publishSelectionDlg;
dlg.okCallback = Function.createDelegate(this, function (data) {
this.publishDocument(data.url, downloadUrl, data.fileName);
});
dlg.setNameInput(title);
dlg.show(this.isPublishWithoutPrompt());
},
publishDocument: function (docLibUrl, downloadUrl, fileName, update) {
// we calcualte the the ajax service url from the proxy url.. otherwise, the session cookies will not be used in the request.
var ajaxUrl = this.context.getProxiedResource('').replace('/CognosResources/resource.axd', '/CognosServices/collaboration.axd');
ajaxUrl += '&op=addFile';
ajaxUrl += '&outputUrl=' + encodeURIComponent(downloadUrl);
ajaxUrl += '&documentLibrary=' + encodeURIComponent(this.toAbsolute(docLibUrl));
ajaxUrl += '&nameOverride=' + encodeURIComponent(fileName);
if (update) {
ajaxUrl += '&writeMode=update';
}
this.sendRequest(ajaxUrl, {
method: 'POST',
includeSessionHeader: true,
noProxy: true,
callback: Function.createDelegate(this, function (xhr) {
var response = xhr.responseXML;
var savedFileName = this.getElementText(response, './result/savedFilename');
var error = this.getElementText(response, './result/error');
if (error && error.length > 0) {
if (error === 'cps.file.exists') {
// prompt
var confirm = new ConfirmationDialog({
title: this.getString('IDS_SP_EDT_SELECT_DLG_PUBLISH_TITLE'),
buttons: [
{ name: this.getString('IDS_SP_YES'),
accessKey: 'y',
callback: Function.createDelegate(this, function () {
this.publishDocument(docLibUrl, downloadUrl, fileName, true);
})
},
{ name: this.getString('IDS_SP_NO'),
accessKey: 'n',
callback: Function.createDelegate(this, function () {
var dlg = this.publishSelectionDlg;
dlg.setNameInput(fileName);
dlg.okCallback = Function.createDelegate(this, function (data) {
this.publishDocument(data.url, downloadUrl, data.fileName, update);
});
dlg.show();
})
},
{ name: this.getString('IDS_SP_CANCEL'),
accessKey: 'c'
}
],
message: this.getString('IDS_SP_DOCUMENT_PUBLISH_EXISTS', [savedFileName]),
hint: this.getString('IDS_SP_DOCUMENT_PUBLISH_EXISTS_HINT', [savedFileName])
});
confirm.show();
} else {
var htmlErrorPage = this.getElementText(response, './result/htmlResponse');
this.handleError(error, htmlErrorPage);
}
} else {
var addUrl = this.getElementText(response, './result/addUrl');
var docLibTitle = this.publishSelectionDlg.selection.title;
var fileNameHtml = '' + savedFileName + '';
var docLibHtml = '' + docLibTitle + '';
var notification = this.getString('IDS_SP_DOCUMENT_PUBLISHED', [fileNameHtml, docLibHtml]);
this.showNotification(notification);
}
})
});
},
/*
Discussion board support
*/
discussMenuClick: function () {
if (this.discussMenu == null) {
this.discussMenu = CMenu(this.getId('id.discuss_menu'));
CAMOpt(this.discussMenu, this.getString('IDS_SP_MENU_DISCUSS_START'), this.createFunctionCall('createDiscussion'));
CAMOpt(this.discussMenu, this.getString('IDS_SP_MENU_DISCUSS_SHOW_RELATED'), this.createFunctionCall('getRelatedDiscussion'));
}
OMenu(this.discussMenu, document.getElementById(this.getId('id.discuss_menulink')), true, null, -1);
},
createDiscussion: function () {
var createDiscussionFunction = Function.createDelegate(this, function (listUrl, listId, webUrl) {
var context = new SP.ClientContext(webUrl);
var web = context.get_web();
var discussionList = web.get_lists().getById(listId);
var itemCreationInfo = new SP.ListItemCreationInformation();
itemCreationInfo.set_leafName(this.objectTitle);
var listItem = discussionList.addItem(itemCreationInfo);
listItem.set_item('Title', this.objectTitle);
// fix the url to show the banner and the toolbar, also remove the backurl.
var url = this.getObjectUrl().replace('cv.header=false', 'cv.header=true').replace('cv.toolbar=false', 'cv.toolbar=true').replace(/&ui.backURL=[^&]*/, "");
listItem.set_item('Body', this.getString('IDS_SP_DISCUSSION_BODY', ['' + this.objectTitle + '']));
listItem.set_item('ThreadTopic', this.getObjectPath());
listItem.update();
context.load(listItem);
context.load(discussionList);
context.executeQueryAsync(Function.createDelegate(this, function () {
var myCallback = Function.createDelegate(this, function (response) {
if (response == 1) {
this.showNotification(
'' + this.getString('IDS_SP_DISCUSSION_STARTED') + '', false);
} else {
listItem.deleteObject();
context.executeQueryAsync(function () { }, function () { });
}
});
var runUrl = '/_layouts/listform.aspx?PageType=6&ListId=' + listId + '&id=' + listItem.get_id();
if (webUrl && webUrl != '/') {
runUrl = webUrl + runUrl;
}
var options = { url: runUrl, width: 650, dialogReturnValueCallback: myCallback };
SP.UI.ModalDialog.showModalDialog(options);
}),
Function.createDelegate(this, function (request, error) { this.handleError(error.get_message()) })
);
});
var dlg = this.discussionSelectionDlg;
dlg.okCallback = function (data) {
createDiscussionFunction(data.url, data.listId, data.webUrl);
}
dlg.show(true);
},
getRelatedDiscussion: function () {
var callback = Function.createDelegate(this, function (listUrl) {
var url = listUrl + '?FilterField1=ThreadTopic&FilterValue1=' + encodeURIComponent(this.getObjectPath());
var myCallback = function () { /*nothing*/ };
var options = { url: url, width: 650, height: 500, dialogReturnValueCallback: myCallback };
SP.UI.ModalDialog.showModalDialog(options);
});
var dlg = this.discussionSelectionDlg;
dlg.okCallback = function (data) {
callback(data.url);
}
dlg.show(true);
}
};
})();