code
stringlengths
2
1.05M
'use strict'; // The error overlay is inspired (and mostly copied) from Create React App (https://github.com/facebookincubator/create-react-app) // They, in turn, got inspired by webpack-hot-middleware (https://github.com/glenjamin/webpack-hot-middleware). const ansiHTML = require('ansi-html'); const Entities = require('html-entities').AllHtmlEntities; const entities = new Entities(); const colors = { reset: ['transparent', 'transparent'], black: '181818', red: 'E36049', green: 'B3CB74', yellow: 'FFD080', blue: '7CAFC2', magenta: '7FACCA', cyan: 'C3C2EF', lightgrey: 'EBE7E3', darkgrey: '6D7891' }; ansiHTML.setColors(colors); function createOverlayIframe(onIframeLoad) { const iframe = document.createElement('iframe'); iframe.id = 'webpack-dev-server-client-overlay'; iframe.src = 'about:blank'; iframe.style.position = 'fixed'; iframe.style.left = 0; iframe.style.top = 0; iframe.style.right = 0; iframe.style.bottom = 0; iframe.style.width = '100vw'; iframe.style.height = '100vh'; iframe.style.border = 'none'; iframe.style.zIndex = 9999999999; iframe.onload = onIframeLoad; return iframe; } function addOverlayDivTo(iframe) { const div = iframe.contentDocument.createElement('div'); div.id = 'webpack-dev-server-client-overlay-div'; div.style.position = 'fixed'; div.style.boxSizing = 'border-box'; div.style.left = 0; div.style.top = 0; div.style.right = 0; div.style.bottom = 0; div.style.width = '100vw'; div.style.height = '100vh'; div.style.backgroundColor = 'rgba(0, 0, 0, 0.85)'; div.style.color = '#E8E8E8'; div.style.fontFamily = 'Menlo, Consolas, monospace'; div.style.fontSize = 'large'; div.style.padding = '2rem'; div.style.lineHeight = '1.2'; div.style.whiteSpace = 'pre-wrap'; div.style.overflow = 'auto'; iframe.contentDocument.body.appendChild(div); return div; } let overlayIframe = null; let overlayDiv = null; let lastOnOverlayDivReady = null; function ensureOverlayDivExists(onOverlayDivReady) { if (overlayDiv) { // Everything is ready, call the callback right away. onOverlayDivReady(overlayDiv); return; } // Creating an iframe may be asynchronous so we'll schedule the callback. // In case of multiple calls, last callback wins. lastOnOverlayDivReady = onOverlayDivReady; if (overlayIframe) { // We're already creating it. return; } // Create iframe and, when it is ready, a div inside it. overlayIframe = createOverlayIframe(function cb() { overlayDiv = addOverlayDivTo(overlayIframe); // Now we can talk! lastOnOverlayDivReady(overlayDiv); }); // Zalgo alert: onIframeLoad() will be called either synchronously // or asynchronously depending on the browser. // We delay adding it so `overlayIframe` is set when `onIframeLoad` fires. document.body.appendChild(overlayIframe); } function showMessageOverlay(message) { ensureOverlayDivExists(function cb(div) { // Make it look similar to our terminal. div.innerHTML = '<span style="color: #' + colors.red + '">Failed to compile.</span><br><br>' + ansiHTML(entities.encode(message)); }); } function destroyErrorOverlay() { if (!overlayDiv) { // It is not there in the first place. return; } // Clean up and reset internal state. document.body.removeChild(overlayIframe); overlayDiv = null; overlayIframe = null; lastOnOverlayDivReady = null; } // Successful compilation. exports.clear = function handleSuccess() { destroyErrorOverlay(); }; // Compilation with errors (e.g. syntax error or missing modules). exports.showMessage = function handleMessage(messages) { showMessageOverlay(messages[0]); };
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'format', 'th', { label: 'รูปแบบ', panelTitle: 'รูปแบบ', tag_address: 'Address', tag_div: 'Paragraph (DIV)', tag_h1: 'Heading 1', tag_h2: 'Heading 2', tag_h3: 'Heading 3', tag_h4: 'Heading 4', tag_h5: 'Heading 5', tag_h6: 'Heading 6', tag_p: 'Normal', tag_pre: 'Formatted' } );
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ 'use strict'; /** * Postroll plugin * * This feature allows the injection of any HTML content in an independent layer once the media finished. * To activate it, one of the nodes contained in the `<video>` tag must be * `<link href="/path/to/action_to_display_content" rel="postroll">` */ // Feature configuration Object.assign(mejs.MepDefaults, { /** * @type {?String} */ postrollCloseText: null }); Object.assign(MediaElementPlayer.prototype, { /** * Feature constructor. * * Always has to be prefixed with `build` and the name that will be used in MepDefaults.features list * @param {MediaElementPlayer} player * @param {$} controls * @param {$} layers * @param {HTMLElement} media */ buildpostroll: function buildpostroll(player, controls, layers) { var t = this, postrollTitle = mejs.Utils.isString(t.options.postrollCloseText) ? t.options.postrollCloseText : mejs.i18n.t('mejs.close'), postrollLink = t.container.find('link[rel="postroll"]').attr('href'); if (postrollLink !== undefined) { player.postroll = $('<div class="' + t.options.classPrefix + 'postroll-layer ' + t.options.classPrefix + 'layer">' + ('<a class="' + t.options.classPrefix + 'postroll-close" onclick="$(this).parent().hide();return false;">') + ('' + postrollTitle) + '</a>' + ('<div class="' + t.options.classPrefix + 'postroll-layer-content"></div>') + '</div>').prependTo(layers).hide(); t.media.addEventListener('ended', function () { $.ajax({ dataType: 'html', url: postrollLink, success: function success(data) { layers.find('.' + t.options.classPrefix + 'postroll-layer-content').html(data); } }); player.postroll.show(); }, false); } } }); },{}]},{},[1]);
var _ = require('lodash'), config = require('../../../config/index'), // private doRawAndFlatten, // public getTables, getIndexes, getColumns, checkPostTable; doRawAndFlatten = function doRaw(query, flattenFn) { return config.database.knex.raw(query).then(function (response) { return _.flatten(flattenFn(response)); }); }; getTables = function getTables() { return doRawAndFlatten('show tables', function (response) { return _.map(response[0], function (entry) { return _.values(entry); }); }); }; getIndexes = function getIndexes(table) { return doRawAndFlatten('SHOW INDEXES from ' + table, function (response) { return _.pluck(response[0], 'Key_name'); }); }; getColumns = function getColumns(table) { return doRawAndFlatten('SHOW COLUMNS FROM ' + table, function (response) { return _.pluck(response[0], 'Field'); }); }; // This function changes the type of posts.html and posts.markdown columns to mediumtext. Due to // a wrong datatype in schema.js some installations using mysql could have been created using the // data type text instead of mediumtext. // For details see: https://github.com/TryGhost/Ghost/issues/1947 checkPostTable = function checkPostTable() { return config.database.knex.raw('SHOW FIELDS FROM posts where Field ="html" OR Field = "markdown"').then(function (response) { return _.flatten(_.map(response[0], function (entry) { if (entry.Type.toLowerCase() !== 'mediumtext') { return config.database.knex.raw('ALTER TABLE posts MODIFY ' + entry.Field + ' MEDIUMTEXT'); } })); }); }; module.exports = { checkPostTable: checkPostTable, getTables: getTables, getIndexes: getIndexes, getColumns: getColumns };
const webpack = require('webpack'); const WebpackDevServer = require('webpack-dev-server'); const config = require('../webpack.config'); const host = '0.0.0.0'; // allows connection from external devices const portNum = 3000; new WebpackDevServer(webpack(config), { publicPath: config.output.publicPath, hot: true, historyApiFallback: true, contentBase: 'src/', stats: { colors: true } }).listen(portNum, host, function (err, result) { if (err) { return console.log(err); } console.log('Listening at http://' + host + ':' + portNum + '/'); });
/** * @license Angulartics v0.17.2 * (c) 2014 Luis Farzati http://luisfarzati.github.io/angulartics * Localytics plugin contributed by http://github.com/joehalliwell * License: MIT */ (function(angular) { 'use strict'; /** * @ngdoc overview * @name angulartics.localytics * Enables analytics support for Localytics (http://localytics.com/) */ angular.module('angulartics.localytics', ['angulartics']) .config(['$analyticsProvider', function ($analyticsProvider) { $analyticsProvider.settings.trackRelativePath = true; /** * Register the page tracking function. */ $analyticsProvider.registerPageTrack(function (path) { if (!window.localytics) return; window.localytics.tagScreen(path); }); /** * Reigster the Localytics event tracking function with the following parameters: * @param {string} action Required 'action' (string) associated with the event * this becomes the event name * @param {object} properties Additional attributes to be associated with the * event. See http://support.localytics.com/Integration_Overview#Event_Attributes * */ $analyticsProvider.registerEventTrack(function (action, properties) { if (!window.localytics) return; if (!action) return; window.localytics.tagEvent(action, properties); }); }]); })(angular);
loadIonicon('<svg width="1em" height="1em" xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512"><path d="M96 96v320h79V274.2L416 416V96L175 237.8V96H96z"/></svg>','ios-skip-backward');
var tape = require('tape'); var levelup = require('levelup'); var memdown = require('memdown'); var blobs = function() { return require('../')(levelup('mem', {db:memdown})); }; tape('write + read', function(t) { var bl = blobs(); bl.write('test', 'hello world', function(err) { t.ok(!err); bl.read('test', function(err, buf) { t.ok(!err); t.same(buf.toString(), 'hello world'); t.end(); }); }); }); tape('streams', function(t) { var bl = blobs(); var ws = bl.createWriteStream('test'); ws.on('finish', function() { var rs = bl.createReadStream('test'); var buffer = []; rs.on('data', function(data) { buffer.push(data); }); rs.on('end', function() { t.same(Buffer.concat(buffer).toString(), 'hello world'); t.end(); }); }); ws.write('hello '); ws.end('world'); }); tape('random access', function(t) { var bl = blobs(); bl.write('test', 'hello world', function() { bl.read('test', {start:6}, function(err, buf) { t.ok(!err); t.same(buf.toString(), 'world'); t.end(); }); }); }); tape('append', function(t) { var bl = blobs(); bl.write('test', 'hello ', function() { bl.write('test', 'world', {append:true}, function() { bl.read('test', {start:6}, function(err, buf) { t.ok(!err); t.same(buf.toString(), 'world'); t.end(); }); }); }); }); tape('write read write read', function(t) { var bl = blobs(); bl.write('test', 'hello', function() { bl.read('test', function(err, buf) { t.same(buf.toString(), 'hello'); bl.write('test', 'world', function() { bl.read('test', function(err, buf) { t.same(buf.toString(), 'world'); t.end(); }); }); }); }); }); tape('write + size', function(t) { var bl = blobs(); bl.size('bar', function(err, size) { t.same(size, 0); bl.write('bar', 'world', function() { bl.size('bar', function(err, size) { t.same(size, 5); bl.size('foo', function(err, size) { t.same(size, 0); bl.write('baz', 'hi', function() { bl.size('baz', function(err, size) { t.same(size, 2); bl.size('bar', function(err, size) { t.same(size, 5); t.end(); }); }); }); }); }); }); }); });
Clazz.declarePackage ("javajs.awt"); Clazz.load (null, "javajs.awt.Component", ["JU.CU"], function () { c$ = Clazz.decorateAsClass (function () { this.visible = false; this.enabled = true; this.text = null; this.name = null; this.width = 0; this.height = 0; this.id = null; this.parent = null; this.mouseListener = null; this.bgcolor = null; this.minWidth = 30; this.minHeight = 30; this.renderWidth = 0; this.renderHeight = 0; Clazz.instantialize (this, arguments); }, javajs.awt, "Component"); Clazz.defineMethod (c$, "setParent", function (p) { this.parent = p; }, "~O"); Clazz.makeConstructor (c$, function (type) { this.id = javajs.awt.Component.newID (type); if (type == null) return; { SwingController.register(this, type); }}, "~S"); c$.newID = Clazz.defineMethod (c$, "newID", function (type) { return type + ("" + Math.random ()).substring (3, 10); }, "~S"); Clazz.defineMethod (c$, "setBackground", function (color) { this.bgcolor = color; }, "javajs.api.GenericColor"); Clazz.defineMethod (c$, "setText", function (text) { this.text = text; { SwingController.setText(this); }}, "~S"); Clazz.defineMethod (c$, "setName", function (name) { this.name = name; }, "~S"); Clazz.defineMethod (c$, "getName", function () { return this.name; }); Clazz.defineMethod (c$, "getParent", function () { return this.parent; }); Clazz.defineMethod (c$, "setPreferredSize", function (dimension) { this.width = dimension.width; this.height = dimension.height; }, "javajs.awt.Dimension"); Clazz.defineMethod (c$, "addMouseListener", function (listener) { this.mouseListener = listener; }, "~O"); Clazz.defineMethod (c$, "getText", function () { return this.text; }); Clazz.defineMethod (c$, "isEnabled", function () { return this.enabled; }); Clazz.defineMethod (c$, "setEnabled", function (enabled) { this.enabled = enabled; { SwingController.setEnabled(this); }}, "~B"); Clazz.defineMethod (c$, "isVisible", function () { return this.visible; }); Clazz.defineMethod (c$, "setVisible", function (visible) { this.visible = visible; { SwingController.setVisible(this); }}, "~B"); Clazz.defineMethod (c$, "getHeight", function () { return this.height; }); Clazz.defineMethod (c$, "getWidth", function () { return this.width; }); Clazz.defineMethod (c$, "setMinimumSize", function (d) { this.minWidth = d.width; this.minHeight = d.height; }, "javajs.awt.Dimension"); Clazz.defineMethod (c$, "getSubcomponentWidth", function () { return this.width; }); Clazz.defineMethod (c$, "getSubcomponentHeight", function () { return this.height; }); Clazz.defineMethod (c$, "getCSSstyle", function (defaultPercentW, defaultPercentH) { var width = (this.renderWidth > 0 ? this.renderWidth : this.getSubcomponentWidth ()); var height = (this.renderHeight > 0 ? this.renderHeight : this.getSubcomponentHeight ()); return (width > 0 ? "width:" + width + "px;" : defaultPercentW > 0 ? "width:" + defaultPercentW + "%;" : "") + (height > 0 ? "height:" + height + "px;" : defaultPercentH > 0 ? "height:" + defaultPercentH + "%;" : "") + (this.bgcolor == null ? "" : "background-color:" + JU.CU.toCSSString (this.bgcolor) + ";"); }, "~N,~N"); Clazz.defineMethod (c$, "repaint", function () { }); });
/** * @ngdoc directive * @function * @name umbraco.directives.directive:umbEditor * @requires formController * @restrict E **/ angular.module("umbraco.directives") .directive('umbEditor', function (umbPropEditorHelper) { return { scope: { model: "=", isPreValue: "@" }, require: "^form", restrict: 'E', replace: true, templateUrl: 'views/directives/umb-editor.html', link: function (scope, element, attrs, ctrl) { //we need to copy the form controller val to our isolated scope so that //it get's carried down to the child scopes of this! //we'll also maintain the current form name. scope[ctrl.$name] = ctrl; if(!scope.model.alias){ scope.model.alias = Math.random().toString(36).slice(2); } scope.propertyEditorView = umbPropEditorHelper.getViewPath(scope.model.view, scope.isPreValue); } }; });
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorDragHandle = (props) => ( <SvgIcon {...props}> <path d="M20 9H4v2h16V9zM4 15h16v-2H4v2z"/> </SvgIcon> ); EditorDragHandle = pure(EditorDragHandle); EditorDragHandle.displayName = 'EditorDragHandle'; EditorDragHandle.muiName = 'SvgIcon'; export default EditorDragHandle;
/*globals svgEditor */ svgEditor.readLang({ lang: "sv", dir : "ltr", common: { "ok": "Spara", "cancel": "Avbryt", "key_backspace": "backspace", "key_del": "delete", "key_down": "down", "key_up": "up", "more_opts": "More Options", "url": "URL", "width": "Width", "height": "Height" }, misc: { "powered_by": "Powered by" }, ui: { "toggle_stroke_tools": "Show/hide more stroke tools", "palette_info": "Klicka för att ändra fyllningsfärg, shift-klicka för att ändra färgar", "zoom_level": "Ändra zoomnivå", "panel_drag": "Drag left/right to resize side panel" }, properties: { "id": "Identify the element", "fill_color": "Ändra fyllningsfärg", "stroke_color": "Ändra färgar", "stroke_style": "Ändra stroke Dash stil", "stroke_width": "Ändra stroke bredd", "pos_x": "Change X coordinate", "pos_y": "Change Y coordinate", "linecap_butt": "Linecap: Butt", "linecap_round": "Linecap: Round", "linecap_square": "Linecap: Square", "linejoin_bevel": "Linejoin: Bevel", "linejoin_miter": "Linejoin: Miter", "linejoin_round": "Linejoin: Round", "angle": "Ändra rotationsvinkel", "blur": "Change gaussian blur value", "opacity": "Ändra markerat objekt opacitet", "circle_cx": "Ändra cirkeln cx samordna", "circle_cy": "Ändra cirkeln samordna cy", "circle_r": "Ändra cirkelns radie", "ellipse_cx": "Ändra ellips&#39;s cx samordna", "ellipse_cy": "Ändra ellips&#39;s samordna cy", "ellipse_rx": "Ändra ellips&#39;s x radie", "ellipse_ry": "Ändra ellips&#39;s y radie", "line_x1": "Ändra Lines startar x samordna", "line_x2": "Ändra Lines slutar x samordna", "line_y1": "Ändra Lines startar Y-koordinat", "line_y2": "Ändra Lines slutar Y-koordinat", "rect_height": "Ändra rektangel höjd", "rect_width": "Ändra rektangel bredd", "corner_radius": "Ändra rektangel hörnradie", "image_width": "Ändra bild bredd", "image_height": "Ändra bildhöjd", "image_url": "Ändra URL", "node_x": "Change node's x coordinate", "node_y": "Change node's y coordinate", "seg_type": "Change Segment type", "straight_segments": "Straight", "curve_segments": "Curve", "text_contents": "Ändra textinnehållet", "font_family": "Ändra Typsnitt", "font_size": "Ändra textstorlek", "bold": "Fet text", "italic": "Kursiv text" }, tools: { "main_menu": "Main Menu", "bkgnd_color_opac": "Ändra bakgrundsfärg / opacitet", "connector_no_arrow": "No arrow", "fitToContent": "Fit to Content", "fit_to_all": "Passar till allt innehåll", "fit_to_canvas": "Anpassa till duk", "fit_to_layer_content": "Anpassa till lager innehåll", "fit_to_sel": "Anpassa till val", "align_relative_to": "Justera förhållande till ...", "relativeTo": "jämfört:", "sida": "sida", "largest_object": "största objekt", "selected_objects": "valda objekt", "smallest_object": "minsta objektet", "new_doc": "New Image", "open_doc": "Öppna bild", "export_img": "Export", "save_doc": "Save Image", "import_doc": "Import Image", "align_to_page": "Align Element to Page", "align_bottom": "Align Bottom", "align_center": "Centrera", "align_left": "Vänsterjustera", "align_middle": "Justera Middle", "align_right": "Högerjustera", "align_top": "Justera Top", "mode_select": "Markeringsverktyget", "mode_fhpath": "Pennverktyget", "mode_line": "Linjeverktyg", "mode_connect": "Connect two objects", "mode_rect": "Rectangle Tool", "mode_square": "Square Tool", "mode_fhrect": "Fri hand rektangel", "mode_ellipse": "Ellips", "mode_circle": "Circle", "mode_fhellipse": "Fri hand Ellipse", "mode_path": "Path Tool", "mode_shapelib": "Shape library", "mode_text": "Textverktyg", "mode_image": "Bildverktyg", "mode_zoom": "Zoomverktyget", "mode_eyedropper": "Eye Dropper Tool", "no_embed": "NOTE: This image cannot be embedded. It will depend on this path to be displayed", "undo": "Ångra", "redo": "Redo", "tool_source": "Redigera källa", "wireframe_mode": "Wireframe Mode", "toggle_grid": "Show/Hide Grid", "clone": "Clone Element(s)", "del": "Delete Element(s)", "group_elements": "Group Elements", "make_link": "Make (hyper)link", "set_link_url": "Set link URL (leave empty to remove)", "to_path": "Convert to Path", "reorient_path": "Reorient path", "ungroup": "Dela Elements", "docprops": "Dokumentegenskaper", "imagelib": "Image Library", "move_bottom": "Move to Bottom", "move_top": "Flytta till början", "node_clone": "Clone Node", "node_delete": "Delete Node", "node_link": "Link Control Points", "add_subpath": "Add sub-path", "openclose_path": "Open/close sub-path", "source_save": "Spara", "cut": "Cut", "copy": "Copy", "paste": "Paste", "paste_in_place": "Paste in Place", "delete": "Delete", "group": "Group", "move_front": "Bring to Front", "move_up": "Bring Forward", "move_down": "Send Backward", "move_back": "Send to Back" }, layers: { "layer":"Layer", "layers": "Layers", "del": "Radera Layer", "move_down": "Flytta Layer Down", "new": "New Layer", "rename": "Byt namn på Layer", "move_up": "Flytta Layer Up", "dupe": "Duplicate Layer", "merge_down": "Merge Down", "merge_all": "Merge All", "move_elems_to": "Move elements to:", "move_selected": "Move selected elements to a different layer" }, config: { "image_props": "Image Properties", "doc_title": "Title", "doc_dims": "Canvas Dimensions", "included_images": "Included Images", "image_opt_embed": "Embed data (local files)", "image_opt_ref": "Use file reference", "editor_prefs": "Editor Preferences", "icon_size": "Icon size", "language": "Language", "background": "Editor Background", "editor_img_url": "Image URL", "editor_bg_note": "Note: Background will not be saved with image.", "icon_large": "Large", "icon_medium": "Medium", "icon_small": "Small", "icon_xlarge": "Extra Large", "select_predefined": "Välj fördefinierad:", "units_and_rulers": "Units & Rulers", "show_rulers": "Show rulers", "base_unit": "Base Unit:", "grid": "Grid", "snapping_onoff": "Snapping on/off", "snapping_stepsize": "Snapping Step-Size:", "grid_color": "Grid color" }, shape_cats: { "basic": "Basic", "object": "Objects", "symbol": "Symbols", "arrow": "Arrows", "flowchart": "Flowchart", "animal": "Animals", "game": "Cards & Chess", "dialog_balloon": "Dialog balloons", "electronics": "Electronics", "math": "Mathematical", "music": "Music", "misc": "Miscellaneous", "raphael_1": "raphaeljs.com set 1", "raphael_2": "raphaeljs.com set 2" }, imagelib: { "select_lib": "Select an image library", "show_list": "Show library list", "import_single": "Import single", "import_multi": "Import multiple", "open": "Open as new document" }, notification: { "invalidAttrValGiven":"Invalid value given", "noContentToFitTo":"No content to fit to", "dupeLayerName":"There is already a layer named that!", "enterUniqueLayerName":"Please enter a unique layer name", "enterNewLayerName":"Please enter the new layer name", "layerHasThatName":"Layer already has that name", "QmoveElemsToLayer":"Move selected elements to layer '%s'?", "QwantToClear":"Do you want to clear the drawing?\nThis will also erase your undo history!", "QwantToOpen":"Do you want to open a new file?\nThis will also erase your undo history!", "QerrorsRevertToSource":"There were parsing errors in your SVG source.\nRevert back to original SVG source?", "QignoreSourceChanges":"Ignore changes made to SVG source?", "featNotSupported":"Feature not supported", "enterNewImgURL":"Enter the new image URL", "defsFailOnSave": "NOTE: Due to a bug in your browser, this image may appear wrong (missing gradients or elements). It will however appear correct once actually saved.", "loadingImage":"Loading image, please wait...", "saveFromBrowser": "Select \"Save As...\" in your browser to save this image as a %s file.", "noteTheseIssues": "Also note the following issues: ", "unsavedChanges": "There are unsaved changes.", "enterNewLinkURL": "Enter the new hyperlink URL", "errorLoadingSVG": "Error: Unable to load SVG data", "URLloadFail": "Unable to load from URL", "retrieving": "Retrieving \"%s\"..." }, confirmSetStorage: { message: "By default and where supported, SVG-Edit can store your editor "+ "preferences and SVG content locally on your machine so you do not "+ "need to add these back each time you load SVG-Edit. If, for privacy "+ "reasons, you do not wish to store this information on your machine, "+ "you can change away from the default option below.", storagePrefsAndContent: "Store preferences and SVG content locally", storagePrefsOnly: "Only store preferences locally", storagePrefs: "Store preferences locally", storageNoPrefsOrContent: "Do not store my preferences or SVG content locally", storageNoPrefs: "Do not store my preferences locally", rememberLabel: "Remember this choice?", rememberTooltip: "If you choose to opt out of storage while remembering this choice, the URL will change so as to avoid asking again." } });
/** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * Facebook, Inc. ("Facebook") owns all right, title and interest, including * all intellectual property and other proprietary rights, in and to the React * Native CustomComponents software (the "Software"). Subject to your * compliance with these terms, you are hereby granted a non-exclusive, * worldwide, royalty-free copyright license to (1) use and copy the Software; * and (2) reproduce and distribute the Software as part of your own software * ("Your Software"). Facebook reserves all rights not expressly granted to * you in this license agreement. * * THE SOFTWARE AND DOCUMENTATION, IF ANY, ARE PROVIDED "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. * IN NO EVENT SHALL FACEBOOK OR ITS AFFILIATES, OFFICERS, DIRECTORS OR * EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THE SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @providesModule NavigationCardStackStyleInterpolator * @flow */ 'use strict'; const I18nManager = require('I18nManager'); import type { NavigationSceneRendererProps, } from 'NavigationTypeDefinition'; /** * Utility that builds the style for the card in the cards stack. * * +------------+ * +-+ | * +-+ | | * | | | | * | | | Focused | * | | | Card | * | | | | * +-+ | | * +-+ | * +------------+ */ /** * Render the initial style when the initial layout isn't measured yet. */ function forInitial(props: NavigationSceneRendererProps): Object { const { navigationState, scene, } = props; const focused = navigationState.index === scene.index; const opacity = focused ? 1 : 0; // If not focused, move the scene to the far away. const translate = focused ? 0 : 1000000; return { opacity, transform: [ { translateX: translate }, { translateY: translate }, ], }; } function forHorizontal(props: NavigationSceneRendererProps): Object { const { layout, position, scene, } = props; if (!layout.isMeasured) { return forInitial(props); } const index = scene.index; const inputRange = [index - 1, index, index + 0.99, index + 1]; const width = layout.initWidth; const outputRange = I18nManager.isRTL ? ([-width, 0, 10, 10]: Array<number>) : ([width, 0, -10, -10]: Array<number>); const opacity = position.interpolate({ inputRange, outputRange: ([1, 1, 0.3, 0]: Array<number>), }); const scale = position.interpolate({ inputRange, outputRange: ([1, 1, 0.95, 0.95]: Array<number>), }); const translateY = 0; const translateX = position.interpolate({ inputRange, outputRange, }); return { opacity, transform: [ { scale }, { translateX }, { translateY }, ], }; } function forVertical(props: NavigationSceneRendererProps): Object { const { layout, position, scene, } = props; if (!layout.isMeasured) { return forInitial(props); } const index = scene.index; const inputRange = [index - 1, index, index + 0.99, index + 1]; const height = layout.initHeight; const opacity = position.interpolate({ inputRange, outputRange: ([1, 1, 0.3, 0]: Array<number>), }); const scale = position.interpolate({ inputRange, outputRange: ([1, 1, 0.95, 0.95]: Array<number>), }); const translateX = 0; const translateY = position.interpolate({ inputRange, outputRange: ([height, 0, -10, -10]: Array<number>), }); return { opacity, transform: [ { scale }, { translateX }, { translateY }, ], }; } function canUseNativeDriver(isVertical: boolean): boolean { // The native driver can be enabled for this interpolator because the scale, // translateX, and translateY transforms are supported with the native // animation driver. return true; } module.exports = { forHorizontal, forVertical, canUseNativeDriver, };
var EOF = 0; // https://drafts.csswg.org/css-syntax-3/ // § 4.2. Definitions // digit // A code point between U+0030 DIGIT ZERO (0) and U+0039 DIGIT NINE (9). function isDigit(code) { return code >= 0x0030 && code <= 0x0039; } // hex digit // A digit, or a code point between U+0041 LATIN CAPITAL LETTER A (A) and U+0046 LATIN CAPITAL LETTER F (F), // or a code point between U+0061 LATIN SMALL LETTER A (a) and U+0066 LATIN SMALL LETTER F (f). function isHexDigit(code) { return ( isDigit(code) || // 0 .. 9 (code >= 0x0041 && code <= 0x0046) || // A .. F (code >= 0x0061 && code <= 0x0066) // a .. f ); } // uppercase letter // A code point between U+0041 LATIN CAPITAL LETTER A (A) and U+005A LATIN CAPITAL LETTER Z (Z). function isUppercaseLetter(code) { return code >= 0x0041 && code <= 0x005A; } // lowercase letter // A code point between U+0061 LATIN SMALL LETTER A (a) and U+007A LATIN SMALL LETTER Z (z). function isLowercaseLetter(code) { return code >= 0x0061 && code <= 0x007A; } // letter // An uppercase letter or a lowercase letter. function isLetter(code) { return isUppercaseLetter(code) || isLowercaseLetter(code); } // non-ASCII code point // A code point with a value equal to or greater than U+0080 <control>. function isNonAscii(code) { return code >= 0x0080; } // name-start code point // A letter, a non-ASCII code point, or U+005F LOW LINE (_). function isNameStart(code) { return isLetter(code) || isNonAscii(code) || code === 0x005F; } // name code point // A name-start code point, a digit, or U+002D HYPHEN-MINUS (-). function isName(code) { return isNameStart(code) || isDigit(code) || code === 0x002D; } // non-printable code point // A code point between U+0000 NULL and U+0008 BACKSPACE, or U+000B LINE TABULATION, // or a code point between U+000E SHIFT OUT and U+001F INFORMATION SEPARATOR ONE, or U+007F DELETE. function isNonPrintable(code) { return ( (code >= 0x0000 && code <= 0x0008) || (code === 0x000B) || (code >= 0x000E && code <= 0x001F) || (code === 0x007F) ); } // newline // U+000A LINE FEED. Note that U+000D CARRIAGE RETURN and U+000C FORM FEED are not included in this definition, // as they are converted to U+000A LINE FEED during preprocessing. // TODO: we doesn't do a preprocessing, so check a code point for U+000D CARRIAGE RETURN and U+000C FORM FEED function isNewline(code) { return code === 0x000A || code === 0x000D || code === 0x000C; } // whitespace // A newline, U+0009 CHARACTER TABULATION, or U+0020 SPACE. function isWhiteSpace(code) { return isNewline(code) || code === 0x0020 || code === 0x0009; } // § 4.3.8. Check if two code points are a valid escape function isValidEscape(first, second) { // If the first code point is not U+005C REVERSE SOLIDUS (\), return false. if (first !== 0x005C) { return false; } // Otherwise, if the second code point is a newline or EOF, return false. if (isNewline(second) || second === EOF) { return false; } // Otherwise, return true. return true; } // § 4.3.9. Check if three code points would start an identifier function isIdentifierStart(first, second, third) { // Look at the first code point: // U+002D HYPHEN-MINUS if (first === 0x002D) { // If the second code point is a name-start code point or a U+002D HYPHEN-MINUS, // or the second and third code points are a valid escape, return true. Otherwise, return false. return ( isNameStart(second) || second === 0x002D || isValidEscape(second, third) ); } // name-start code point if (isNameStart(first)) { // Return true. return true; } // U+005C REVERSE SOLIDUS (\) if (first === 0x005C) { // If the first and second code points are a valid escape, return true. Otherwise, return false. return isValidEscape(first, second); } // anything else // Return false. return false; } // § 4.3.10. Check if three code points would start a number function isNumberStart(first, second, third) { // Look at the first code point: // U+002B PLUS SIGN (+) // U+002D HYPHEN-MINUS (-) if (first === 0x002B || first === 0x002D) { // If the second code point is a digit, return true. if (isDigit(second)) { return 2; } // Otherwise, if the second code point is a U+002E FULL STOP (.) // and the third code point is a digit, return true. // Otherwise, return false. return second === 0x002E && isDigit(third) ? 3 : 0; } // U+002E FULL STOP (.) if (first === 0x002E) { // If the second code point is a digit, return true. Otherwise, return false. return isDigit(second) ? 2 : 0; } // digit if (isDigit(first)) { // Return true. return 1; } // anything else // Return false. return 0; } // // Misc // // detect BOM (https://en.wikipedia.org/wiki/Byte_order_mark) function isBOM(code) { // UTF-16BE if (code === 0xFEFF) { return 1; } // UTF-16LE if (code === 0xFFFE) { return 1; } return 0; } // Fast code category // // https://drafts.csswg.org/css-syntax/#tokenizer-definitions // > non-ASCII code point // > A code point with a value equal to or greater than U+0080 <control> // > name-start code point // > A letter, a non-ASCII code point, or U+005F LOW LINE (_). // > name code point // > A name-start code point, a digit, or U+002D HYPHEN-MINUS (-) // That means only ASCII code points has a special meaning and we define a maps for 0..127 codes only var CATEGORY = new Array(0x80); charCodeCategory.Eof = 0x80; charCodeCategory.WhiteSpace = 0x82; charCodeCategory.Digit = 0x83; charCodeCategory.NameStart = 0x84; charCodeCategory.NonPrintable = 0x85; for (var i = 0; i < CATEGORY.length; i++) { switch (true) { case isWhiteSpace(i): CATEGORY[i] = charCodeCategory.WhiteSpace; break; case isDigit(i): CATEGORY[i] = charCodeCategory.Digit; break; case isNameStart(i): CATEGORY[i] = charCodeCategory.NameStart; break; case isNonPrintable(i): CATEGORY[i] = charCodeCategory.NonPrintable; break; default: CATEGORY[i] = i || charCodeCategory.Eof; } } function charCodeCategory(code) { return code < 0x80 ? CATEGORY[code] : charCodeCategory.NameStart; }; module.exports = { isDigit: isDigit, isHexDigit: isHexDigit, isUppercaseLetter: isUppercaseLetter, isLowercaseLetter: isLowercaseLetter, isLetter: isLetter, isNonAscii: isNonAscii, isNameStart: isNameStart, isName: isName, isNonPrintable: isNonPrintable, isNewline: isNewline, isWhiteSpace: isWhiteSpace, isValidEscape: isValidEscape, isIdentifierStart: isIdentifierStart, isNumberStart: isNumberStart, isBOM: isBOM, charCodeCategory: charCodeCategory };
/*global process */ var fs = require('fs'); var envfile = require('envfile'); module.exports = function(grunt) { var pkg = grunt.file.readJSON('package.json'); if (pkg.devDependencies) { Object.keys(pkg.devDependencies).filter(function(pkgname) { if (pkgname.indexOf('grunt-') === 0) { grunt.loadNpmTasks(pkgname); } }); } grunt.initConfig({ pkg: pkg, watch: { scripts: { files: ["lib/**/*.js" ], tasks: ['build'] } }, browserify: { options: { ignore: [ "request", "lib/**/cli/*.js", "test/**/node/*.js" ] }, lib: { files: { 'build/jsforce.js': [ 'lib/jsforce.js' ] }, options: { standalone: 'jsforce' } }, test: { files: [ { expand: true, cwd: 'test/', src: [ '**/*.test.js' ], dest: 'build/test/' } ], options: { preBundleCB: function(b) { var filePath = "./test/config/browser/env.js"; var env = process.env; try { env = envfile.parseFileSync('./.env'); } catch(e) {} var data = "module.exports=" + JSON.stringify(env) + ";"; fs.writeFileSync(filePath, data); } } } }, uglify: { options: { sourceMap: true, sourceMapIncludeSources: true, banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %> */' }, lib: { files: { 'build/jsforce.min.js': ['build/jsforce.js'], } } }, jsdoc : { dist : { src: ['lib/'], options: { destination: 'doc', private: false, recurse: true, lenient: true } } }, clean: { lib: { src: [ "build/*.js", "build/*.map" ] }, test: { src: [ "build/test/**.test.js" ] }, doc: { src: [ "doc/" ] } } }); grunt.registerTask('build', ['browserify:lib', 'uglify']); grunt.registerTask('default', ['build']); };
/*! * sweetalert2 v4.1.2 * Released under the MIT License. */ 'use strict'; var swalPrefix = 'swal2-'; var prefix = function(items) { var result = {}; for (var i in items) { result[items[i]] = swalPrefix + items[i]; } return result; }; var swalClasses = prefix([ 'container', 'modal', 'overlay', 'close', 'content', 'spacer', 'confirm', 'cancel', 'icon', 'image', 'input', 'select', 'radio', 'checkbox', 'textarea', 'validationerror' ]); var iconTypes = prefix([ 'success', 'warning', 'info', 'question', 'error' ]); var defaultParams = { title: '', text: '', html: '', type: null, customClass: '', animation: true, allowOutsideClick: true, allowEscapeKey: true, showConfirmButton: true, showCancelButton: false, preConfirm: null, confirmButtonText: 'OK', confirmButtonColor: '#3085d6', confirmButtonClass: null, cancelButtonText: 'Cancel', cancelButtonColor: '#aaa', cancelButtonClass: null, buttonsStyling: true, reverseButtons: false, showCloseButton: false, showLoaderOnConfirm: false, imageUrl: null, imageWidth: null, imageHeight: null, imageClass: null, timer: null, width: 500, padding: 20, background: '#fff', input: null, // 'text' | 'email' | 'password' | 'select' | 'radio' | 'checkbox' | 'textarea' | 'file' inputPlaceholder: '', inputValue: '', inputOptions: {}, inputAutoTrim: true, inputClass: null, inputAttributes: {}, inputValidator: null, onOpen: null, onClose: null, }; var sweetHTML = '<div class="' + swalClasses.overlay + '" tabIndex="-1"></div>' + '<div class="' + swalClasses.modal + '" style="display: none" tabIndex="-1">' + '<div class="' + swalClasses.icon + ' ' + iconTypes.error + '">' + '<span class="x-mark"><span class="line left"></span><span class="line right"></span></span>' + '</div>' + '<div class="' + swalClasses.icon + ' ' + iconTypes.question + '">?</div>' + '<div class="' + swalClasses.icon + ' ' + iconTypes.warning + '">!</div>' + '<div class="' + swalClasses.icon + ' ' + iconTypes.info + '">i</div>' + '<div class="' + swalClasses.icon + ' ' + iconTypes.success + '">' + '<span class="line tip"></span> <span class="line long"></span>' + '<div class="placeholder"></div> <div class="fix"></div>' + '</div>' + '<img class="' + swalClasses.image + '">' + '<h2></h2>' + '<div class="' + swalClasses.content + '"></div>' + '<input class="' + swalClasses.input + '">' + '<select class="' + swalClasses.select + '"></select>' + '<div class="' + swalClasses.radio + '"></div>' + '<label for="' + swalClasses.checkbox + '" class="' + swalClasses.checkbox + '">' + '<input type="checkbox" id="' + swalClasses.checkbox + '">' + '</label>' + '<textarea class="' + swalClasses.textarea + '"></textarea>' + '<div class="' + swalClasses.validationerror + '"></div>' + '<hr class="' + swalClasses.spacer + '">' + '<button class="' + swalClasses.confirm + '">OK</button>' + '<button class="' + swalClasses.cancel + '">Cancel</button>' + '<span class="' + swalClasses.close + '">&times;</span>' + '</div>'; var extend = function(a, b) { for (var key in b) { if (b.hasOwnProperty(key)) { a[key] = b[key]; } } return a; }; /* * Set hover, active and focus-states for buttons (source: http://www.sitepoint.com/javascript-generate-lighter-darker-color) */ var colorLuminance = function(hex, lum) { // Validate hex string hex = String(hex).replace(/[^0-9a-f]/gi, ''); if (hex.length < 6) { hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]; } lum = lum || 0; // Convert to decimal and change luminosity var rgb = '#'; for (var i = 0; i < 3; i++) { var c = parseInt(hex.substr(i * 2, 2), 16); c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16); rgb += ('00' + c).substr(c.length); } return rgb; }; /* * check if variable is function type. http://stackoverflow.com/questions/5999998/how-can-i-check-if-a-javascript-variable-is-function-type */ var isFunction = function(functionToCheck) { return typeof functionToCheck === "function"; }; var mediaqueryId = swalPrefix + 'mediaquery'; // Remember state in cases where opening and handling a modal will fiddle with it. var states = { previousWindowKeyDown: null, previousActiveElement: null }; /* * Manipulate DOM */ var elementByClass = function(className) { return document.querySelector('.' + className); }; var getModal = function() { return elementByClass(swalClasses.modal); }; var getOverlay = function() { return elementByClass(swalClasses.overlay); }; var getConfirmButton = function() { return elementByClass(swalClasses.confirm); }; var getCancelButton = function() { return elementByClass(swalClasses.cancel); }; var getCloseButton = function() { return elementByClass(swalClasses.close); }; var getFocusableElements = function() { return [getConfirmButton(), getCancelButton()].concat(Array.prototype.slice.call( getModal().querySelectorAll('button:not([class^=' + swalPrefix + ']), input:not([type=hidden]), textarea, select') )); }; var hasClass = function(elem, className) { return elem.classList.contains(className); }; var focusInput = function(input) { input.focus(); // http://stackoverflow.com/a/2345915/1331425 var val = input.value; input.value = ''; input.value = val; }; var addClass = function(elem, className) { if (!elem || !className) { return; } var classes = className.split(/\s+/); classes.forEach(function (className) { elem.classList.add(className) }); }; var removeClass = function(elem, className) { if (!elem || !className) { return; } var classes = className.split(/\s+/); classes.forEach(function (className) { elem.classList.remove(className); }); }; var getChildByClass = function(elem, className) { for (var i = 0; i < elem.childNodes.length; i++) { if (hasClass(elem.childNodes[i], className)) { return elem.childNodes[i]; } } }; var _show = function(elem) { elem.style.opacity = ''; elem.style.display = 'block'; }; var show = function(elems) { if (elems && !elems.length) { return _show(elems); } for (var i = 0; i < elems.length; ++i) { _show(elems[i]); } }; var _hide = function(elem) { elem.style.opacity = ''; elem.style.display = 'none'; }; var hide = function(elems) { if (elems && !elems.length) { return _hide(elems); } for (var i = 0; i < elems.length; ++i) { _hide(elems[i]); } }; var removeStyleProperty = function(elem, property) { if (elem.style.removeProperty) { elem.style.removeProperty(property); } else { elem.style.removeAttribute(property); } }; var getTopMargin = function(elem) { var elemDisplay = elem.style.display; elem.style.left = '-9999px'; elem.style.display = 'block'; var height = elem.clientHeight; elem.style.left = ''; elem.style.display = elemDisplay; return ('-' + parseInt(height / 2, 10) + 'px'); }; var fadeIn = function(elem, interval) { if (+elem.style.opacity < 1) { interval = interval || 16; elem.style.opacity = 0; elem.style.display = 'block'; var last = +new Date(); var tick = function() { var newOpacity = +elem.style.opacity + (new Date() - last) / 100; elem.style.opacity = (newOpacity > 1) ? 1 : newOpacity; last = +new Date(); if (+elem.style.opacity < 1) { setTimeout(tick, interval); } }; tick(); } }; var fadeOut = function(elem, interval) { if (+elem.style.opacity > 0) { interval = interval || 16; var opacity = elem.style.opacity; var last = +new Date(); var tick = function() { var change = new Date() - last; var newOpacity = +elem.style.opacity - change / (opacity * 100); elem.style.opacity = newOpacity; last = +new Date(); if (+elem.style.opacity > 0) { setTimeout(tick, interval); } else { _hide(elem); } }; tick(); } }; var fireClick = function(node) { // Taken from http://www.nonobtrusive.com/2011/11/29/programatically-fire-crossbrowser-click-event-with-javascript/ // Then fixed for today's Chrome browser. if (typeof MouseEvent === 'function') { // Up-to-date approach var mevt = new MouseEvent('click', { view: window, bubbles: false, cancelable: true }); node.dispatchEvent(mevt); } else if (document.createEvent) { // Fallback var evt = document.createEvent('MouseEvents'); evt.initEvent('click', false, false); node.dispatchEvent(evt); } else if (document.createEventObject) { node.fireEvent('onclick'); } else if (typeof node.onclick === 'function') { node.onclick(); } }; var stopEventPropagation = function(e) { // In particular, make sure the space bar doesn't scroll the main window. if (typeof e.stopPropagation === 'function') { e.stopPropagation(); e.preventDefault(); } else if (window.event && window.event.hasOwnProperty('cancelBubble')) { window.event.cancelBubble = true; } }; var animationEndEvent = (function() { var testEl = document.createElement('div'), transEndEventNames = { 'WebkitAnimation': 'webkitAnimationEnd', 'MozAnimation': 'animationend', 'OAnimation': 'oAnimationEnd oanimationend', 'msAnimation': 'MSAnimationEnd', 'animation': 'animationend' }; for (var i in transEndEventNames) { if (transEndEventNames.hasOwnProperty(i) && testEl.style[i] !== undefined) { return transEndEventNames[i]; } } return false; })(); // Reset the page to its previous state var resetPrevState = function() { var modal = getModal(); window.onkeydown = states.previousWindowKeyDown; if (states.previousActiveElement && states.previousActiveElement.focus) { states.previousActiveElement.focus(); } clearTimeout(modal.timeout); // Remove dynamically created media query var head = document.getElementsByTagName('head')[0]; var mediaquery = document.getElementById(mediaqueryId); if (mediaquery) { head.removeChild(mediaquery); } }; var modalParams = extend({}, defaultParams); /* * Set type, text and actions on modal */ var setParameters = function(params) { var modal = getModal(); for (var param in params) { if (!defaultParams.hasOwnProperty(param) && param !== 'extraParams') { console.warn('SweetAlert2: Unknown parameter "' + param + '"'); } } // set modal width, padding and margin-left modal.style.width = params.width + 'px'; modal.style.padding = params.padding + 'px'; modal.style.marginLeft = -params.width / 2 + 'px'; modal.style.background = params.background; // add dynamic media query css var head = document.getElementsByTagName('head')[0]; var cssNode = document.createElement('style'); cssNode.type = 'text/css'; cssNode.id = mediaqueryId; var margin = 5; // % var mediaQueryMaxWidth = params.width + parseInt(params.width * (margin/100) * 2, 10); cssNode.innerHTML = '@media screen and (max-width: ' + mediaQueryMaxWidth + 'px) {' + '.' + swalClasses.modal + ' {' + 'width: auto !important;' + 'left: ' + margin + '% !important;' + 'right: ' + margin + '% !important;' + 'margin-left: 0 !important;' + '}' + '}'; head.appendChild(cssNode); var $title = modal.querySelector('h2'); var $content = modal.querySelector('.' + swalClasses.content); var $confirmBtn = getConfirmButton(); var $cancelBtn = getCancelButton(); var $spacer = modal.querySelector('.' + swalClasses.spacer); var $closeButton = modal.querySelector('.' + swalClasses.close); // Title $title.innerHTML = params.title.split('\n').join('<br>'); // Content if (params.text || params.html) { if (typeof params.html === 'object') { $content.innerHTML = ''; if (0 in params.html) { for (var i = 0; i in params.html; i++) { $content.appendChild(params.html[i]); } } else { $content.appendChild(params.html); } } else { $content.innerHTML = params.html || (params.text.split('\n').join('<br>')); } show($content); } else { hide($content); } // Close button if (params.showCloseButton) { show($closeButton); } else { hide($closeButton); } // Custom Class modal.className = swalClasses.modal; if (params.customClass) { addClass(modal, params.customClass); } // Icon hide(modal.querySelectorAll('.' + swalClasses.icon)); if (params.type) { var validType = false; for (var iconType in iconTypes) { if (params.type === iconType) { validType = true; break; } } if (!validType) { console.error('SweetAlert2: Unknown alert type: ' + params.type); return false; } var $icon = modal.querySelector('.' + swalClasses.icon + '.' + iconTypes[params.type]); show($icon); // Animate icon switch (params.type) { case 'success': addClass($icon, 'animate'); addClass($icon.querySelector('.tip'), 'animate-success-tip'); addClass($icon.querySelector('.long'), 'animate-success-long'); break; case 'error': addClass($icon, 'animate-error-icon'); addClass($icon.querySelector('.x-mark'), 'animate-x-mark'); break; case 'warning': addClass($icon, 'pulse-warning'); break; default: break; } } // Custom image var $customImage = modal.querySelector('.' + swalClasses.image); if (params.imageUrl) { $customImage.setAttribute('src', params.imageUrl); show($customImage); if (params.imageWidth) { $customImage.setAttribute('width', params.imageWidth); } else { $customImage.removeAttribute('width'); } if (params.imageHeight) { $customImage.setAttribute('height', params.imageHeight); } else { $customImage.removeAttribute('height'); } if (params.imageClass) { addClass($customImage, params.imageClass); } } else { hide($customImage); } // Cancel button if (params.showCancelButton) { $cancelBtn.style.display = 'inline-block'; } else { hide($cancelBtn); } // Confirm button if (params.showConfirmButton) { removeStyleProperty($confirmBtn, 'display'); } else { hide($confirmBtn); } // Buttons spacer if (!params.showConfirmButton && !params.showCancelButton) { hide($spacer); } else { show($spacer); } // Edit text on cancel and confirm buttons $confirmBtn.innerHTML = params.confirmButtonText; $cancelBtn.innerHTML = params.cancelButtonText; // Set buttons to selected background colors if (params.buttonsStyling) { $confirmBtn.style.backgroundColor = params.confirmButtonColor; $cancelBtn.style.backgroundColor = params.cancelButtonColor; } // Add buttons custom classes $confirmBtn.className = swalClasses.confirm; addClass($confirmBtn, params.confirmButtonClass); $cancelBtn.className = swalClasses.cancel; addClass($cancelBtn, params.cancelButtonClass); // Buttons styling if (params.buttonsStyling) { addClass($confirmBtn, 'styled'); addClass($cancelBtn, 'styled'); } else { removeClass($confirmBtn, 'styled'); removeClass($cancelBtn, 'styled'); $confirmBtn.style.backgroundColor = $confirmBtn.style.borderLeftColor = $confirmBtn.style.borderRightColor = ''; $cancelBtn.style.backgroundColor = $cancelBtn.style.borderLeftColor = $cancelBtn.style.borderRightColor = ''; } // CSS animation if (params.animation === true) { removeClass(modal, 'no-animation'); } else { addClass(modal, 'no-animation'); } }; /* * Animations */ var openModal = function(animation, onComplete) { var modal = getModal(); if (animation) { fadeIn(getOverlay(), 10); addClass(modal, 'show-swal2'); removeClass(modal, 'hide-swal2'); } else { show(getOverlay()); } show(modal); states.previousActiveElement = document.activeElement; addClass(modal, 'visible'); if (onComplete !== null && typeof onComplete === 'function') { onComplete.call(this, modal); } }; /* * Set 'margin-top'-property on modal based on its computed height */ var fixVerticalPosition = function() { var modal = getModal(); modal.style.marginTop = getTopMargin(modal); }; function modalDependant() { if (arguments[0] === undefined) { console.error('SweetAlert2 expects at least 1 attribute!'); return false; } var params = extend({}, modalParams); switch (typeof arguments[0]) { case 'string': params.title = arguments[0]; params.text = arguments[1] || ''; params.type = arguments[2] || ''; break; case 'object': extend(params, arguments[0]); params.extraParams = arguments[0].extraParams; if (params.input === 'email' && params.inputValidator === null) { params.inputValidator = function(email) { return new Promise(function(resolve, reject) { var emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/; if (emailRegex.test(email)) { resolve(); } else { reject('Invalid email address'); } }); }; } break; default: console.error('SweetAlert2: Unexpected type of argument! Expected "string" or "object", got ' + typeof arguments[0]); return false; } setParameters(params); // Modal interactions var modal = getModal(); return new Promise(function(resolve, reject) { // Close on timer if (params.timer) { modal.timeout = setTimeout(function() { sweetAlert.closeModal(params.onClose); reject('timer'); }, params.timer); } var getInput = function() { switch (params.input) { case 'select': return getChildByClass(modal, swalClasses.select); case 'radio': return modal.querySelector('.' + swalClasses.radio + ' input:checked') || modal.querySelector('.' + swalClasses.radio + ' input:first-child'); case 'checkbox': return modal.querySelector('#' + swalClasses.checkbox); case 'textarea': return getChildByClass(modal, swalClasses.textarea); default: return getChildByClass(modal, swalClasses.input); } }; var getInputValue = function() { var input = getInput(); switch (params.input) { case 'checkbox': return input.checked ? 1 : 0; case 'radio': return input.checked ? input.value : null; case 'file': return input.files.length ? input.files[0] : null; default: return params.inputAutoTrim? input.value.trim() : input.value; } }; if (params.input) { setTimeout(function() { var input = getInput(); if (input) { focusInput(input); } }, 0); } var confirm = function(value) { if (params.showLoaderOnConfirm) { sweetAlert.showLoading(); } if (params.preConfirm) { params.preConfirm(value, params.extraParams).then( function(preConfirmValue) { sweetAlert.closeModal(params.onClose); resolve(preConfirmValue || value); }, function(error) { sweetAlert.hideLoading(); if (error) { sweetAlert.showValidationError(error); } } ); } else { sweetAlert.closeModal(params.onClose); resolve(value); } }; // Mouse interactions var onButtonEvent = function(event) { var e = event || window.event; var target = e.target || e.srcElement; var confirmBtn = getConfirmButton(); var cancelBtn = getCancelButton(); var targetedConfirm = confirmBtn === target || confirmBtn.contains(target); var targetedCancel = cancelBtn === target || cancelBtn.contains(target); var modalIsVisible = hasClass(modal, 'visible'); switch (e.type) { case 'mouseover': case 'mouseup': if (params.buttonsStyling) { if (targetedConfirm) { confirmBtn.style.backgroundColor = colorLuminance(params.confirmButtonColor, -0.1); } else if (targetedCancel) { cancelBtn.style.backgroundColor = colorLuminance(params.cancelButtonColor, -0.1); } } break; case 'mouseout': if (params.buttonsStyling) { if (targetedConfirm) { confirmBtn.style.backgroundColor = params.confirmButtonColor; } else if (targetedCancel) { cancelBtn.style.backgroundColor = params.cancelButtonColor; } } break; case 'mousedown': if (params.buttonsStyling) { if (targetedConfirm) { confirmBtn.style.backgroundColor = colorLuminance(params.confirmButtonColor, -0.2); } else if (targetedCancel) { cancelBtn.style.backgroundColor = colorLuminance(params.cancelButtonColor, -0.2); } } break; case 'click': // Clicked 'confirm' if (targetedConfirm && modalIsVisible) { if (params.input) { var inputValue = getInputValue(); if (params.inputValidator) { sweetAlert.disableInput(); params.inputValidator(inputValue, params.extraParams).then( function() { sweetAlert.enableInput(); confirm(inputValue); }, function(error) { sweetAlert.enableInput(); if (error) { sweetAlert.showValidationError(error); } } ); } else { confirm(inputValue); } } else { confirm(true); } // Clicked 'cancel' } else if (targetedCancel && modalIsVisible) { sweetAlert.closeModal(params.onClose); reject('cancel'); } break; default: } }; var $buttons = modal.querySelectorAll('button'); var i; for (i = 0; i < $buttons.length; i++) { $buttons[i].onclick = onButtonEvent; $buttons[i].onmouseover = onButtonEvent; $buttons[i].onmouseout = onButtonEvent; $buttons[i].onmousedown = onButtonEvent; } // Closing modal by close button getCloseButton().onclick = function() { sweetAlert.closeModal(params.onClose); reject('close'); }; // Closing modal by overlay click getOverlay().onclick = function() { if (params.allowOutsideClick) { sweetAlert.closeModal(params.onClose); reject('overlay'); } }; var $confirmButton = getConfirmButton(); var $cancelButton = getCancelButton(); // Reverse buttons if neede d if (params.reverseButtons) { $confirmButton.parentNode.insertBefore($cancelButton, $confirmButton); } // Focus handling function setFocus(index, increment) { var focusableElements = getFocusableElements(); // search for visible elements and select the next possible match for (var i = 0; i < focusableElements.length; i++) { index = index + increment; // rollover to first item if (index === focusableElements.length) { index = 0; // go to last item } else if (index === -1) { index = focusableElements.length - 1; } // determine if element is visible, the following is borrowed from jqeury $(elem).is(':visible') implementation var el = focusableElements[index]; if (el.offsetWidth || el.offsetHeight || el.getClientRects().length) { return el.focus(); } } } function handleKeyDown(event) { var e = event || window.event; var keyCode = e.keyCode || e.which; if ([9, 13, 32, 27].indexOf(keyCode) === -1) { // Don't do work on keys we don't care about. return; } var $targetElement = e.target || e.srcElement; var focusableElements = getFocusableElements(); var btnIndex = -1; // Find the button - note, this is a nodelist, not an array. for (var i = 0; i < focusableElements.length; i++) { if ($targetElement === focusableElements[i]) { btnIndex = i; break; } } // TAB if (keyCode === 9) { if (!e.shiftKey) { // Cycle to the next button setFocus(btnIndex, 1); } else { // Cycle to the prev button setFocus(btnIndex, -1); } stopEventPropagation(e); } else { if (keyCode === 13 || keyCode === 32) { if (btnIndex === -1) { // ENTER/SPACE clicked outside of a button. fireClick($confirmButton, e); } } else if (keyCode === 27 && params.allowEscapeKey === true) { sweetAlert.closeModal(params.onClose); reject('esc'); } } } states.previousWindowKeyDown = window.onkeydown; window.onkeydown = handleKeyDown; // Loading state if (params.buttonsStyling) { $confirmButton.style.borderLeftColor = params.confirmButtonColor; $confirmButton.style.borderRightColor = params.confirmButtonColor; } /** * Show spinner instead of Confirm button and disable Cancel button */ sweetAlert.showLoading = sweetAlert.enableLoading = function() { addClass($confirmButton, 'loading'); addClass(modal, 'loading'); $confirmButton.disabled = true; $cancelButton.disabled = true; }; /** * Show spinner instead of Confirm button and disable Cancel button */ sweetAlert.hideLoading = sweetAlert.disableLoading = function() { removeClass($confirmButton, 'loading'); removeClass(modal, 'loading'); $confirmButton.disabled = false; $cancelButton.disabled = false; }; sweetAlert.enableButtons = function() { $confirmButton.disabled = false; $cancelButton.disabled = false; }; sweetAlert.disableButtons = function() { $confirmButton.disabled = true; $cancelButton.disabled = true; }; sweetAlert.enableConfirmButton = function() { $confirmButton.disabled = false; }; sweetAlert.disableConfirmButton = function() { $confirmButton.disabled = true; }; sweetAlert.enableInput = function() { var input = getInput(); if (input.type === 'radio') { var radiosContainer = input.parentNode.parentNode; var radios = radiosContainer.querySelectorAll('input'); for (var i = 0; i < radios.length; i++) { radios[i].disabled = false; } } else { input.disabled = false; } }; sweetAlert.disableInput = function() { var input = getInput(); if (input.type === 'radio') { var radiosContainer = input.parentNode.parentNode; var radios = radiosContainer.querySelectorAll('input'); for (var i = 0; i < radios.length; i++) { radios[i].disabled = true; } } else { input.disabled = true; } }; sweetAlert.showValidationError = function(error) { var $validationError = modal.querySelector('.' + swalClasses.validationerror); $validationError.innerHTML = error; show($validationError); var input = getInput(); focusInput(input); addClass(input, 'error'); }; sweetAlert.resetValidationError = function() { var $validationError = modal.querySelector('.' + swalClasses.validationerror); hide($validationError); var input = getInput(); if (input) { removeClass(input, 'error'); } }; sweetAlert.enableButtons(); sweetAlert.hideLoading(); sweetAlert.resetValidationError(); // input, select var inputTypes = ['input', 'select', 'radio', 'checkbox', 'textarea']; var input; for (i = 0; i < inputTypes.length; i++) { var inputClass = swalClasses[inputTypes[i]]; input = getChildByClass(modal, inputClass); // set attributes while (input.attributes.length > 0) { input.removeAttribute(input.attributes[0].name); } for (var attr in params.inputAttributes) { input.setAttribute(attr, params.inputAttributes[attr]); } // set class input.className = inputClass; if (params.inputClass) { addClass(input, params.inputClass); } _hide(input); } var populateInputOptions; switch (params.input) { case 'text': case 'email': case 'password': case 'file': input = getChildByClass(modal, swalClasses.input); input.value = params.inputValue; input.placeholder = params.inputPlaceholder; input.type = params.input; _show(input); break; case 'select': var select = getChildByClass(modal, swalClasses.select); select.innerHTML = ''; if (params.inputPlaceholder) { var placeholder = document.createElement('option'); placeholder.innerHTML = params.inputPlaceholder; placeholder.value = ''; placeholder.disabled = true; placeholder.selected = true; select.appendChild(placeholder); } populateInputOptions = function(inputOptions) { for (var optionValue in inputOptions) { var option = document.createElement('option'); option.value = optionValue; option.innerHTML = inputOptions[optionValue]; if (params.inputValue === optionValue) { option.selected = true; } select.appendChild(option); } _show(select); select.focus(); }; break; case 'radio': var radio = getChildByClass(modal, swalClasses.radio); radio.innerHTML = ''; populateInputOptions = function(inputOptions) { for (var radioValue in inputOptions) { var id = 1; var radioInput = document.createElement('input'); var radioLabel = document.createElement('label'); var radioLabelSpan = document.createElement('span'); radioInput.type = 'radio'; radioInput.name = swalClasses.radio; radioInput.value = radioValue; radioInput.id = swalClasses.radio + '-' + (id++); if (params.inputValue === radioValue) { radioInput.checked = true; } radioLabelSpan.innerHTML = inputOptions[radioValue]; radioLabel.appendChild(radioInput); radioLabel.appendChild(radioLabelSpan); radioLabel.for = radioInput.id; radio.appendChild(radioLabel); } _show(radio); var radios = radio.querySelectorAll('input'); if (radios.length) { radios[0].focus(); } }; break; case 'checkbox': var checkbox = getChildByClass(modal, swalClasses.checkbox); var checkboxInput = modal.querySelector('#' + swalClasses.checkbox); checkboxInput.value = 1; checkboxInput.checked = Boolean(params.inputValue); var label = checkbox.getElementsByTagName('span'); if (label.length) { checkbox.removeChild(label[0]); } label = document.createElement('span'); label.innerHTML = params.inputPlaceholder; checkbox.appendChild(label); _show(checkbox); break; case 'textarea': var textarea = getChildByClass(modal, swalClasses.textarea); textarea.value = params.inputValue; textarea.placeholder = params.inputPlaceholder; _show(textarea); break; case null: break; default: console.error('SweetAlert2: Unexpected type of input! Expected "text" or "email" or "password", "select", "checkbox", "textarea" or "file", got "' + params.input + '"'); break; } if (params.input === 'select' || params.input === 'radio') { if (params.inputOptions instanceof Promise) { sweetAlert.showLoading(); params.inputOptions.then(function(inputOptions) { sweetAlert.hideLoading(); populateInputOptions(inputOptions); }); } else if (typeof params.inputOptions === 'object') { populateInputOptions(params.inputOptions); } else { console.error('SweetAlert2: Unexpected type of inputOptions! Expected object or Promise, got ' + typeof params.inputOptions); } } fixVerticalPosition(); openModal(params.animation, params.onOpen); // Focus the first element (input or button) setFocus(-1, 1); }); } // SweetAlert function function sweetAlert() { // Copy arguments to the local args variable var args = arguments; var modal = getModal(); if (modal === null) { sweetAlert.init(); modal = getModal(); } if (hasClass(modal, 'visible')) { resetPrevState(); } return modalDependant.apply(this, args); } /* * Global function for chaining sweetAlert modals */ sweetAlert.queue = function(steps) { return new Promise(function(resolve, reject) { (function step(i, callback) { var nextStep = null; if (isFunction(steps)) { nextStep = steps(i); } else if (i < steps.length) { nextStep = steps[i]; } if (nextStep) { sweetAlert(nextStep).then(function() { step(i+1, callback); }, function(dismiss) { reject(dismiss); }); } else { resolve(); } })(0); }); }; /* * Global function to close sweetAlert */ sweetAlert.close = sweetAlert.closeModal = function(onComplete) { var modal = getModal(); removeClass(modal, 'show-swal2'); addClass(modal, 'hide-swal2'); removeClass(modal, 'visible'); // Reset icon animations var $successIcon = modal.querySelector('.' + swalClasses.icon + '.' + iconTypes.success); removeClass($successIcon, 'animate'); removeClass($successIcon.querySelector('.tip'), 'animate-success-tip'); removeClass($successIcon.querySelector('.long'), 'animate-success-long'); var $errorIcon = modal.querySelector('.' + swalClasses.icon + '.' + iconTypes.error); removeClass($errorIcon, 'animate-error-icon'); removeClass($errorIcon.querySelector('.x-mark'), 'animate-x-mark'); var $warningIcon = modal.querySelector('.' + swalClasses.icon + '.' + iconTypes.warning); removeClass($warningIcon, 'pulse-warning'); resetPrevState(); if (animationEndEvent && !hasClass(modal, 'no-animation')) { modal.addEventListener(animationEndEvent, function swalCloseEventFinished() { modal.removeEventListener(animationEndEvent, swalCloseEventFinished); if (hasClass(modal, 'hide-swal2')) { _hide(modal); fadeOut(getOverlay(), 0); } }); } else { _hide(modal); _hide(getOverlay()); } if (onComplete !== null && typeof onComplete === 'function') { onComplete.call(this, modal); } }; /* * Global function to click 'Confirm' button */ sweetAlert.clickConfirm = function() { getConfirmButton().click(); }; /* * Global function to click 'Cancel' button */ sweetAlert.clickCancel = function() { getCancelButton().click(); }; /* * Add modal + overlay to DOM */ sweetAlert.init = function() { if (typeof document === 'undefined') { console.log('SweetAlert2 requires document to initialize'); return; } else if (document.getElementsByClassName(swalClasses.container).length) { return; } var sweetWrap = document.createElement('div'); sweetWrap.className = swalClasses.container; sweetWrap.innerHTML = sweetHTML; document.body.appendChild(sweetWrap); var modal = getModal(); var $input = getChildByClass(modal, swalClasses.input); var $select = getChildByClass(modal, swalClasses.select); var $checkbox = modal.querySelector('#' + swalClasses.checkbox); var $textarea = getChildByClass(modal, swalClasses.textarea); $input.oninput = function() { sweetAlert.resetValidationError(); }; $input.onkeyup = function(event) { event.stopPropagation(); if (event.keyCode === 13) { sweetAlert.clickConfirm(); } }; $select.onchange = function() { sweetAlert.resetValidationError(); }; $checkbox.onchange = function() { sweetAlert.resetValidationError(); }; $textarea.oninput = function() { sweetAlert.resetValidationError(); }; window.addEventListener('resize', fixVerticalPosition, false); }; /** * Set default params for each popup * @param {Object} userParams */ sweetAlert.setDefaults = function(userParams) { if (!userParams) { throw new Error('userParams is required'); } if (typeof userParams !== 'object') { throw new Error('userParams has to be a object'); } extend(modalParams, userParams); }; /** * Reset default params for each popup */ sweetAlert.resetDefaults = function() { modalParams = extend({}, defaultParams); }; sweetAlert.version = '4.1.2'; window.sweetAlert = window.swal = sweetAlert; /* * If library is injected after page has loaded */ (function() { if (document.readyState === 'complete' || document.readyState === 'interactive' && document.body) { sweetAlert.init(); } else { document.addEventListener('DOMContentLoaded', function onDomContentLoaded() { document.removeEventListener('DOMContentLoaded', onDomContentLoaded, false); sweetAlert.init(); }, false); } })(); if (typeof Promise === 'function') { Promise.prototype.done = function() { return this.catch(function() { // Catch promise rejections silently. // https://github.com/limonte/sweetalert2/issues/177 }); }; } else { console.warn('SweetAlert2: Please inlude Promise polyfill BEFORE including sweetalert2.js if IE10+ support needed.'); } module.exports = sweetAlert;
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is phery. * * The Initial Developer of the Original Code is * Paulo Cesar <https://github.com/pocesar/phery>. * Portions created by the Initial Developer are Copyright (C) 2011 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** */ /*jshint smarttabs:true,jquery:true,sub:true,evil:true,undef:true,latedef:true,immed:true,forin:false,browser:true,devel:true */ /*global _:true,Backbone:true */ (function($,window,undefined){ /** * @class * @version 1.0 */ "use strict"; var str_is_function, call_cache = [], old_isFunction = $.isFunction, old_sync_libraries = { backbone: null, datatables: null }, phery = window.phery = window.phery || {}; function append_args(args) { this.data('args.phery', $.extend(true, args, this.data('args.phery'))); } function set_args(args) { this.data('args.phery', $.extend(true, {}, args)); } function string_callbacks(enable) { switch (enable) { case true: str_is_function = function(str) { if (!str || typeof str['toString'] !== 'function') { return false; } str = str.toString(); if (! /^[\s;]*function\(/im.test(str) || ! /\};?$/m.test(str)) { return false; } return true; }; String.prototype.apply = function(obj) { if ( ! str_is_function(this) ) { return false; } var str = this.toString(), cache_len = call_cache.length, fn = null, i, args; for(i = 0; i < cache_len; i++) { if (call_cache[i].str === str) { fn = call_cache[i].fn; break; } } if (typeof fn !== 'function') { var f_args = str.match(/function\s*\(([^\)]*)\)/im)[1], f_body = str.slice(str.indexOf('{') + 1, str.lastIndexOf('}')); if (!f_body) { return false; } fn = new Function(f_args, f_body); call_cache.push({ 'str': str, 'fn': fn }); cache_len = call_cache.length; } args = Array.prototype.slice.call(arguments, 1); if (typeof args[0] !== 'undefined' && args[0].constructor === Array) { args = args[0]; } try { return fn.apply(obj, args); } catch (exception) { } return null; }; String.prototype.call = function(obj) { return this.apply(obj, Array.prototype.slice.call(arguments, 1)); }; $.isFunction = function( obj ) { return $.type(obj) === "function" || str_is_function(obj); }; break; case false: str_is_function = function(){ return false; }; if (typeof String.prototype['call'] === 'function') { delete String.prototype['call']; } if (typeof String.prototype['apply'] === 'function') { delete String.prototype['apply']; } $.isFunction = old_isFunction; break; } } var options = {}, defaults = { 'cursor': true, 'default_href': false, 'ajax': { 'retries': 0 }, 'enable': { 'log': false, 'log_history': false, 'php_string_callbacks': false, 'per_element': { 'events': true, 'options': false } }, 'debug': { 'enable': false, 'display': { 'events': true, 'remote': true, 'config': true } }, 'delegate':{ 'confirm': 'click', 'form': 'submit', 'select_multiple': 'blur', 'select': 'change', 'tags': 'click' } }, _callbacks = { 'before': function() { return true; }, 'beforeSend': function() { return true; }, 'params': function() { return true; }, 'always': function() { return true; }, 'fail': function() { return true; }, 'done': function() { return true; }, 'after': function() { return true; }, 'exception': function() { return true; }, 'json': function() { return true; } }, callbacks = $('<div/>'), _log = [], $original_cursor, $body_html, $container = null; function debug(data, type){ if (options.debug.enable) { if (typeof console !== 'undefined' && typeof console['dir'] !== 'undefined') { if (typeof options.debug.display[type] !== 'undefined' && options.debug.display[type] === true) { console.dir(data); } } } } function do_cursor(cursor) { if (options.cursor) { if (!cursor) { $body_html.css('cursor', $original_cursor); } else { $body_html.css('cursor', cursor); } } } function triggerAndReturn(el, name, data, context) { context = context || null; var event = $.Event(name), res; if (context) { event.target = context; } el.triggerHandler(event, data); res = (event.result !== false); debug(['event triggered', { 'name': name, 'event result': res, 'element': el, 'data': data }], 'events'); return res; } function triggerPheryEvent(el, event_name, data, triggerData) { data = data || []; triggerData = triggerData || false; if (triggerData) { triggerAndReturn(callbacks, event_name, data, el); if (options.enable.per_element.events) { triggerAndReturn(el, 'phery:' + event_name, data); } return true; } else { if (triggerAndReturn(callbacks, event_name, data, el) === false) { return false; } if (options.enable.per_element.events) { return triggerAndReturn(el, 'phery:' + event_name, data); } return true; } } function countProperties(obj) { var count = 0; if (typeof obj === 'object') { for (var prop in obj) { if(obj.hasOwnProperty(prop)){ ++count; } } } else { if (typeof obj['length'] !== 'undefined'){ count = obj.length; } } return count; } function clean_up(el) { if (el.data('temp.phery')) { el.off(); el.removeProp(); $.removeData(el); el.remove(); } } function form_submit($this) { if($this.data('confirm.phery')){ if (!confirm($this.data('confirm.phery'))) { return false; } } $this.find('input[name="phery[remote]"]').remove(); return ajax_call.call($this); } function ajax_call() { /*jshint validthis:true*/ if (triggerPheryEvent(this, 'before') === false) { clean_up(this); return false; } var _headers = { 'X-Requested-With': 'XMLHttpRequest', 'X-Phery': 1 }, el = this, url = el.attr('action') || el.attr('href') || el.data('target.phery') || options.default_href || window.location.href, type = el.data('type.phery') || 'json', submit_id = el.attr('id') || null, requested, ajax, data = { 'phery': {} }; if (el.data('args.phery')) { try { if (typeof el.data('args.phery') === 'object') { data['args'] = $.extend(true, {}, el.data('args.phery')); } else { /* integers, strings */ data['args'] = el.data('args.phery'); } } catch (exception) { triggerPheryEvent(el, 'exception', [phery.log(exception)]); } } else { if (el.is('input')) { if (el.attr('name')) { var _obj = {}; if (!el.is('[type="checkbox"],[type="radio"]')) { _obj[el.attr('name')] = el.val(); } else { _obj[el.attr('name')] = { 'checked': el.prop('checked')?1:0, 'value': el.val() }; } data['args'] = $.extend(true, {}, _obj); } } } if (el.is('form')) { try { data['args'] = $.extend( true, {}, data['args'], el.serializeForm(el.data('submit.phery')?el.data('submit.phery'):{}) ); } catch (exception) { triggerPheryEvent(el, 'exception', [phery.log(exception)]); } } if (el.is('select')) { if (el.attr('multiple')) { if (el.attr('name')) { data['args'] = $.extend(true, {}, data['args']); data['args'][el.attr('name')] = $.extend({}, el .find('option') .filter(':selected') .map(function(){ return $(this).val(); }).get() ); } else { data['args'] = $.extend(true, {}, el .find('option') .filter(':selected') .map(function(){ return $(this).val(); }).get() ); } } else { if (el.attr('name')) { data['args'] = $.extend(true, {}, data['args']); data['args'][el.attr('name')] = el.val(); } else { data['args'] = el.val(); } } } if (submit_id) { data['phery']['submit_id'] = submit_id; } if (el.data('view.phery')) { data['phery']['view'] = '#' + el.attr('id'); } else if (el.data('remote.phery')) { data['phery']['remote'] = el.data('remote.phery'); } var _tmp = {}; triggerPheryEvent(el, 'params', _tmp, true); data['phery'] = $.extend(_tmp, data['phery']); requested = new Date(); debug(['remote call', { 'data': data, 'timestamp': requested.getTime(), 'time': requested.toLocaleString() }], 'remote'); requested = requested.getTime(); var opt = { url: ( url.indexOf('_=') === -1? (url + (url.indexOf('?') > -1?'&':'?') + '_=' + requested) : (url.replace(/\_\=(\d+)/, '_=' + requested)) ), data: data, dataType: type, type: "POST", el: el, global: false, try_count: 0, retry_limit: options.ajax.retries, cache: false, processData: true, headers: _headers, 'beforeSend': function (xhr, settings) { do_cursor('wait'); if (triggerPheryEvent(this.el, 'beforeSend', [xhr, settings]) === false) { return false; } return true; } }; var _fail = function (xhr, status, error) { if (this.retry_limit && status === 'timeout') { this.try_count++; if (this.try_count <= this.retry_limit) { this.dataType = "text " + type; this.url = this.url.indexOf('_try_count=') === -1? (this.url + '&_try_count=' + this.try_count) : (this.url.replace(/_try_count=(\d+)/, '_try_count=' + this.try_count)); this.url = this.url.replace(/_=(\d+)/, '_=' + new Date().getTime()); set_ajax_opts(this); return false; } } do_cursor(false); if (triggerPheryEvent(this.el, 'fail', [xhr, status, error]) === false) { clean_up(this.el); return false; } clean_up(this.el); return true; }, _done = function (data, text, xhr) { if (triggerPheryEvent(this.el, 'done', [data, text, xhr]) === false) { return false; } processRequest.call(this.el, data); return true; }, _always = function (data, text, xhr) { if (xhr.readyState !== 4 && this.try_count && this.try_count <= this.retry_limit) { return false; } do_cursor(false); if (triggerPheryEvent(this.el,'always', [xhr]) === false) { clean_up(this.el); return false; } clean_up(this.el); return true; }; var set_ajax_opts = function(opt){ var ajax = $.ajax(opt); ajax .done(_done) .always(_always) .fail(_fail); return ajax; }; ajax = set_ajax_opts(opt); return ajax; } function set_events() { $(document) .off('.phery'); $(document) .on(options.delegate.confirm + '.phery', '[data-confirm]:not(form)', function (e) { if (!confirm($(this).data('confirm.phery'))) { e.stopImmediatePropagation(); } else { e.preventDefault(); } }) .on(options.delegate.form + '.phery', 'form[data-remote]', function (e) { var $this = $(this); form_submit($this); return false; }) .on(options.delegate.tags + '.phery', '[data-remote]:not(form,select)', function (e) { var $this = $(this); ajax_call.call($this); if (!$this.is('input[type="text"],input[type="checkbox"],input[type="radio"],input[type="image"]')) { e.preventDefault(); } }) .on(options.delegate.select + '.phery', 'select[data-remote]:not([multiple])', function (e) { ajax_call.call($(this)); }) .on(options.delegate.select_multiple + '.phery', 'select[data-remote][multiple]', function (e) { ajax_call.call($(this)); }); } function processRequest(data){ /*jshint validthis:true */ if( ! this.data('remote.phery') && ! this.data('view.phery')){ triggerPheryEvent(this, 'after', []); return; } var $jq, x, i, argv, argc, func_name, $this = this, is_selector, funct, _data, _argv; if (data && countProperties(data)) { for(x in data){ is_selector = (x.toString().search(/^[0-9]+$/) === -1); /* check if it has a selector */ if (is_selector){ if (data[x].length){ if (x.toLowerCase() === 'window') { $jq = $(window); } else if (x.toLowerCase() === 'document') { $jq = $(document); } else { $jq = $(x); } if ($jq.size()){ for (i in data[x]){ argv = data[x][i]['a']; try { func_name = argv.shift(); if (typeof $jq[func_name] === 'function'){ if (typeof argv[0] !== 'undefined' && argv[0].constructor === Array) { $jq = $jq[func_name].apply($jq, argv[0] || null); } else if (argv.constructor === Array) { $jq = $jq[func_name].apply($jq, argv || null); } else { $jq = $jq[func_name].call($jq, argv || null); } } else{ throw 'no function "' + func_name + '" found in jQuery object'; } } catch (exception) { triggerPheryEvent($this, 'exception', [phery.log(exception, argv)]); } } } } else { triggerPheryEvent($this, 'exception', [phery.log('no commands to issue, 0 length')]); } } else { argc = data[x]['a'].length; argv = data[x]['a']; switch (Number(data[x]['c'])) { /* alert */ case 1: if (typeof argv[0] !== 'undefined' && typeof argv[0] === 'string') { alert(argv[0]); } else { triggerPheryEvent($this, 'exception', [phery.log('missing message for alert()', argv)]); } break; /* call */ case 2: try { funct = argv.shift(); if (typeof window[funct] === 'function') { window[funct].apply(null, argv[0] || []); } else { throw 'no global function "' + funct + '" found'; } } catch (exception) { triggerPheryEvent($this, 'exception', [phery.log(exception, argv)]); } break; /* script */ case 3: try { eval('(function(){ ' + argv[0] + '})();'); } catch (exception) { triggerPheryEvent($this, 'exception', [phery.log(exception, argv[0])]); } break; /* JSON */ case 4: try { triggerPheryEvent($this, 'json', [$.parseJSON(argv[0])]); } catch (exception) { triggerPheryEvent($this, 'exception', [phery.log(exception, argv[0])]); } break; /* Render View */ case 5: _data = $this.data('view.phery'); _argv = $.extend(true, {}, { 'url': $this.data('target') }, argv[1]); if (typeof _data['beforeHtml'] === 'function') { _data['beforeHtml'].call($this, _argv); } if (typeof _data['render'] !== 'function') { $this.html('').html(argv[0]); } else { _data['render'].call($this, argv[0], _argv); } if (typeof _data['afterHtml'] === 'function') { _data['afterHtml'].call($this, _argv); } break; /* Dump var */ case 6: try { if (typeof console !== 'undefined' && typeof console['log'] !== 'undefined') { for (var l = 0; l < argc; l++) { console.log(argv[l]); } } } catch (exception) { triggerPheryEvent($this, 'exception', [phery.log(exception, argv[0])]); } break; /* Trigger Exception */ case 7: if (argc > 1) { _argv = [argv.shift()]; do { _argv.push(argv.shift()); } while (argv.length); triggerPheryEvent($this, 'exception', _argv); } else { triggerPheryEvent($this, 'exception', [argv[0]]); } break; default: triggerPheryEvent($this, 'exception', [phery.log('invalid command "' + data[x]['c'] + '" issued')]); break; } } } } triggerPheryEvent(this, 'after', []); } var dot_notation_option = function(val, step, set) { if (val.indexOf('.') !== -1) { var initial = val.split('.'); if (initial && initial[0] && typeof step[initial[0]] !== 'undefined') { return dot_notation_option(initial.slice(1).join('.'), step[initial[0]], set); } } else if (typeof step[val] !== 'undefined') { if (typeof set !== 'undefined') { step[val] = set; return step; } else { return step[val]; } } return null; }; function _apply(original, force) { force = force || false; for(var x in original) { if (typeof original[x] === 'object') { if (_apply(original[x], force) === false) { return false; } } else { debug(['config', { 'name': x, 'value': original[x] }], 'config'); switch (x) { case 'php_string_callbacks': if (original[x] !== options.enable.php_string_callbacks || force) { string_callbacks(options.enable.php_string_callbacks); } break; case 'confirm': case 'form': case 'select_multiple': case 'select': case 'tags': if (original[x] !== options.delegate[x] || force) { set_events(); return false; } break; } } } return true; } function refresh_changes(key, value) { var original = $.extend(true, {}, options); if (typeof value === 'undefined') { for (var x in key) { dot_notation_option(x, options, key[x]); } } else { dot_notation_option(key, options, value); } _apply(original); } options = $.extend(true, {}, defaults, options); $(function(){ $body_html = $('body,html'); $original_cursor = $body_html.css('cursor'); _apply(options, true); }); /** * Config phery singleton * @param {String|Object} key name using dot notation (group.subconfig) * @param {String|Boolean} value * @return {phery} */ phery.config = function(key, value){ if (typeof key === 'object' && key.constructor === Object) { refresh_changes(key); return phery; } else if (typeof key === 'string' && typeof value !== 'undefined') { refresh_changes(key, value); return phery; } else if (typeof key === 'string' && typeof value === 'undefined') { if (key in options) { return options[key]; } return dot_notation_option(key, options); } else if (arguments.length === 0) { return $.extend(true, {}, options); } return phery; }; /** * Reset everything to the defaults * @return {phery} */ phery.reset_to_defaults = function(){ options = $.extend(true, {}, defaults); _apply(options, true); return phery; }; /** * Log function * @param ... Any type of data * @return {Array} */ phery.log = function(){ var args = Array.prototype.slice.call(arguments); if (args.length) { if (options.enable.log) { if (options.enable.log_history) { _log.push(args); } if (typeof console !== 'undefined' && typeof console['log'] !== 'undefined'){ if(typeof console['log'] === 'object') { /* IE is still a malign force */ console.log(args); } else { /* Good browsers */ console.log.apply(console, args); } } } return args.join("\n"); } else { if (options.enable.log_history) { return _log; } } return []; }; /** * Function to call remote * @param {String} function_name Name of the PHP function set through * <pre> * phery::instance()->set() * </pre> * @param {Object} args Object containing arguments to be sent over * @param {Object} attr Attributes to append to the created element * @param {Boolean} direct_call Default, call the AJAX function directly. If set to false, it * will return the created object that will further need the remote() call, like after binding * events to it. * @return {jQuery} */ phery.remote = function(function_name, args, attr, direct_call){ if (this === phery && !function_name) { phery.log('first argument "function_name" on phery.remote() must be specified when calling directly'); return phery; } direct_call = direct_call || true; if (this !== phery) { return ajax_call.call(this); } var $a = $('<a/>'); $a.data({ 'remote.phery': function_name }); if (direct_call) { $a.data('temp.phery', true); } if (typeof args !== 'undefined' && args !== null) { $a.phery('set_args', args); } if (typeof attr !== 'undefined') { $a.attr(attr); } if (!direct_call) { $a.extend({ 'remote': ajax_call }); } return (direct_call?ajax_call.call($a):$a); }; /** * Set the global callbacks * @param {Array|String} event Key:value containing events or string. * <pre> * phery.on('always', fn); // or * phery.on({'always': fn}); * </pre> * @param {Function} cb Callback for the event. * @return {phery} */ phery.on = function(event, cb){ if (typeof event === 'object') { for(var x in event){ phery.on(x, event[x]); } } else if (typeof event === 'string' && typeof cb === 'function') { if (event in _callbacks) { debug(['phery.on', { event: event, callback: cb }], 'events'); callbacks.bind(event + '.phery', cb); } } return phery; }; /** * Unset the callback * @param {String} event Name of the event or space separated event names * @return {phery} */ phery.off = function(event) { debug(['phery.off', { event: event }], 'events'); callbacks.off(event + '.phery'); return phery; }; var _containers = {}; /** * Enable AJAX partials for the site. Disable links that responds * to it using the <code>.no-phery</code> class * @param {Object} config containing the #id references to containers and respective configs. * <pre> * { * '#container': { * // Optional, function to call before the * // HTML was set, can interact with existing elements on page * // The context of the callback is the container * 'beforeHtml': function(data), * // Optional, function to call to render the HTML, * // in a custom way. This overwrites the original function, * // so you might set this.html(html) manually. * // The context of the callback is the container * 'render': function(html, data), * // Optional, function to call after the HTML was set, * // can interact with the new contents of the page * // The context of the callback is the container. * 'afterHtml': function(data), * // Optional, defaults to a[href]:not(.no-phery,[target],[data-remote],[href*=":"],[rel~="nofollow"]). * // Setting the selector manually will make it 'local' to the #container, like '#container a' * // Links like <a rel="#nameofcontainer">click me!</a>, using the rel attribute will trigger too * 'selector': 'a', * // Optional, array containing conditions for links NOT to follow, * // can be string, regex and function (that returns boolean, receives the url clicked, return true to exclude) * 'exclude': ['/contact', /\d$/, function] * // any other phery event, like beforeSend, params, etc * } * } * </pre> * If you provide a string as the name of previously * set container, it will return an object associated * with the container as follows: * <pre> * { * 'data': container.data, // selector, callbacks, etc * 'container': $(container), // jquery container itself * 'remote': function(url) // function to navigate to url set * } * </pre> * @return {phery} */ phery.view = function(config){ if (typeof config === 'string') { if (config[0] !== '#') { config = '#' + config; } if (typeof _containers[config] !== 'undefined') { return { 'data': _containers[config].data('view.phery'), 'container': _containers[config], 'remote': function(url){ if (url) { _containers[config].data('target', url); } ajax_call.call(_containers[config]); } } } } if (typeof config === 'object' && $.isEmptyObject(config)) { debug(['phery.view needs config'], 'config'); return phery; } var _container, _bound, $container, selector; $(document) .off('click.view'); for (_container in config) { $container = $(_container); if ($container.size() === 1) { _bound = _container.replace(/[#\.\s]/g, ''); if (config[_container] === false) { /* Remove the view */ $container.off('.phery.view'); $(document).off('click.view.' + _bound); debug(['phery.view uninstalled and events unbound', $container], 'config'); continue; } if (typeof config[_container]['selector'] === 'string' && /(^|\s)a($|\s|\.)/i.test(config[_container]['selector'])) { selector = _container + ' ' + config[_container]['selector']; } else { selector = 'a[href]:not(.no-phery,[target],[data-remote],[href*=":"],[rel~="nofollow"])'; } selector = selector + ',a[href][rel="' + (_container) + '"]'; $container.data('view.phery', $.extend(true, {}, config[_container], { 'selector': selector })); _containers[_container] = $container; $(document) .on('click.view.' + _bound, selector, { 'container': $container }, function(e){ /* Prepare */ var $this = $(this), href = $this.attr('href'), data = e.data.container.data('view.phery'); /* Continue as normal for cmd clicks etc */ if ( e.which == 2 || e.metaKey ) { return true; } if (typeof data['exclude'] !== 'undefined') { for (var x = 0; x < data['exclude'].length; x++) { switch (typeof data['exclude'][x]) { case 'string': if (href.indexOf(data['exclude'][x]) !== -1) { return true; } break; case 'object': if (data['exclude'][x].test(href)) { return true; } break; case 'function': if (data['exclude'][x].call(e.data.container, href, $this) === true) { return true; } } } } debug([ 'phery.view link clicked, loading content', e.data.container, $this.attr('href') ], 'events'); e.data.container.data('target', $this.attr('href')); ajax_call.call(e.data.container, true); e.stopPropagation(); e.preventDefault(); return false; }); for(var _x in config[_container]) { if (config[_container].hasOwnProperty(_x) && typeof _callbacks[_x] !== 'undefined') { $container.on('phery:' + (_x) + '.phery.view', config[_container][_x]); } } debug(['phery.view installed', $container], 'config'); } else { debug(['phery.view container', $container, 'isnt unique or does not exist'], 'config'); } } return phery; }; $.fn.extend({ reset: function() { return this.each(function() { if ($(this).is('form')) { this.reset(); } }); }, phery: function(name, value) { var $this = this, _out = { 'exception': function(msg, data){ triggerPheryEvent($this, 'exception', [msg, data]); return $this.phery(); }, 'remote': function(){ if ($this.is('form')) { return form_submit($this); } else { return ajax_call.call($this); } }, 'append_args': function(){ append_args.apply($this, arguments); return $this.phery(); }, 'set_args': function(){ set_args.apply($this, arguments); return $this.phery(); }, 'get_args': function(){ return this.data('args.phery'); }, 'remove': function(){ $this.data('temp.phery', true); clean_up($this); } }; if (name && (name in _out)) { return _out[name].apply($this, Array.prototype.slice.call(arguments, 1)); } return _out; }, serializeForm:function(opt) { opt = $.extend({}, opt); if (typeof opt['disabled'] === 'undefined' || opt['disabled'] === null) { opt['disabled'] = false; } if (typeof opt['all'] === 'undefined' || opt['all'] === null) { opt['all'] = false; } if (typeof opt['empty'] === 'undefined' || opt['empty'] === null) { opt['empty'] = true; } var $form = $(this), result = {}, formValues = $form .find('input,textarea,select,keygen') .filter(function(){ var ret = true; if (!opt['disabled']) { ret = !this.disabled; } return ret && $.trim(this.name); }) .map(function(){ var $this = $(this), radios, options, value = null; if ($this.is('[type="radio"]') || $this.is('[type="checkbox"]')) { if ($this.is('[type="radio"]')) { radios = $form.find('[type="radio"][name="' + this.name + '"]'); if (radios.filter('[checked]').size()) { value = radios.filter('[checked]').val(); } } else if ($this.prop('checked')) { value = $this.val(); } } else if ($this.is('select')) { options = $this.find('option').filter(':selected'); if($this.prop('multiple')) { value = options.map(function() { return this.value || this.innerHTML; }).get(); } else { value = options.val(); } } else { value = $this.val(); } return { 'name': this.name || null, 'value': value }; }).get(); if (formValues) { var i, value, name, res, $matches, len, j, x, fields, _count = 0, last_name, strpath; var create_obj = function(create_array, res, path) { var field = fields.shift(); if (field){ if (typeof res[field] === "undefined" || !res[field]) { res[field] = (create_array?[]:{}); } path.push("['"+field+"']"); create_obj(create_array, res[field], path); } else { if (typeof field === 'string') { var count = (_count++).toString(); path.push("['"+(count)+"']"); if (typeof res[count] === "undefined" || !res[count]) { res[count] = {}; } create_obj(create_array, res[count], path); } } }; for (i = 0; i < formValues.length; i++) { name = formValues[i].name; value = formValues[i].value; if (!opt['all']) { if (value === null) { continue; } } else { if (value === null) { value = ''; } } if (value === '' && !opt['empty']) { continue; } if (!name) { continue; } $matches = name.split(/\[/); len = $matches.length; for(j = 1; j < len; j++) { $matches[j] = $matches[j].replace(/\]/g, ''); } fields = []; strpath = []; for(j = 0; j < len; j++) { if ($matches[j] || j < len-1) { fields.push($matches[j].replace("'", '')); } } if ($matches[len-1] === '') { if ($matches[0] !== last_name) { last_name = $matches[0]; _count = 0; } create_obj(true, result, strpath); eval('res=result' + strpath.join('') + ';'); if(value.constructor === Array) { for(x = 0; x < value.length; x++) { res.push(value[x]); } } else { res.push(value); } } else { create_obj(false, result, strpath); eval('result' + strpath.join('') + '=value;'); } } } return result; } }); })(jQuery, window);
(function(window,undefined){var Globalize;if(typeof require!=="undefined"&&typeof exports!=="undefined"&&typeof module!=="undefined"){Globalize=require("globalize")}else{Globalize=window.Globalize}Globalize.addCultureInfo("fil-PH","default",{name:"fil-PH",englishName:"Filipino (Philippines)",nativeName:"Filipino (Pilipinas)",language:"fil",numberFormat:{currency:{symbol:"PhP"}},calendars:{standard:{days:{names:["Linggo","Lunes","Martes","Mierkoles","Huebes","Biernes","Sabado"],namesAbbr:["Lin","Lun","Mar","Mier","Hueb","Bier","Saba"],namesShort:["L","L","M","M","H","B","S"]},months:{names:["Enero","Pebrero","Marso","Abril","Mayo","Hunyo","Hulyo","Agosto","Septyembre","Oktubre","Nobyembre","Disyembre",""],namesAbbr:["En","Peb","Mar","Abr","Mayo","Hun","Hul","Agos","Sept","Okt","Nob","Dis",""]},eras:[{name:"Anno Domini",start:null,offset:0}]}}})})(this);
/* jshint ignore:start */ require('{{MODULE_PREFIX}}/tests/test-helper'); EmberENV.TESTS_FILE_LOADED = true; /* jshint ignore:end */
/*! /support/test/css/boxshadow 1.0.2 | http://nucleus.qoopido.com | (c) 2015 Dirk Lueth */ !function(){"use strict";function e(e,r){var d=e.defer(),o=r("box-shadow");return o?d.resolve(o):d.reject(),d.pledge}provide(["/demand/pledge","../../css/property"],e)}(); //# sourceMappingURL=boxshadow.js.map
module.exports = { prefix: 'fab', iconName: 'gofore', icon: [400, 512, [], "f3a7", "M324 319.8h-13.2v34.7c-24.5 23.1-56.3 35.8-89.9 35.8-73.2 0-132.4-60.2-132.4-134.4 0-74.1 59.2-134.4 132.4-134.4 35.3 0 68.6 14 93.6 39.4l62.3-63.3C335 55.3 279.7 32 220.7 32 98 32 0 132.6 0 256c0 122.5 97 224 220.7 224 63.2 0 124.5-26.2 171-82.5-2-27.6-13.4-77.7-67.7-77.7zm-12.1-112.5H205.6v89H324c33.5 0 60.5 15.1 76 41.8v-30.6c0-65.2-40.4-100.2-88.1-100.2z"] };
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ 'use strict'; function appendSaveAsDialog (index, output) { var div; var menu; function closeMenu(e) { var left = parseInt(menu.style.left, 10); var top = parseInt(menu.style.top, 10); if ( e.x < left || e.x > (left + menu.offsetWidth) || e.y < top || e.y > (top + menu.offsetHeight) ) { menu.parentNode.removeChild(menu); document.body.removeEventListener('mousedown', closeMenu, false); } } div = document.getElementById(output + index); div.childNodes[0].addEventListener('contextmenu', function (e) { var list, savePng, saveSvg; menu = document.createElement('div'); menu.className = 'wavedromMenu'; menu.style.top = e.y + 'px'; menu.style.left = e.x + 'px'; list = document.createElement('ul'); savePng = document.createElement('li'); savePng.innerHTML = 'Save as PNG'; list.appendChild(savePng); saveSvg = document.createElement('li'); saveSvg.innerHTML = 'Save as SVG'; list.appendChild(saveSvg); //var saveJson = document.createElement('li'); //saveJson.innerHTML = 'Save as JSON'; //list.appendChild(saveJson); menu.appendChild(list); document.body.appendChild(menu); savePng.addEventListener('click', function () { var html, firstDiv, svgdata, img, canvas, context, pngdata, a; html = ''; if (index !== 0) { firstDiv = document.getElementById(output + 0); html += firstDiv.innerHTML.substring(166, firstDiv.innerHTML.indexOf('<g id="waves_0">')); } html = [div.innerHTML.slice(0, 166), html, div.innerHTML.slice(166)].join(''); svgdata = 'data:image/svg+xml;base64,' + btoa(html); img = new Image(); img.src = svgdata; canvas = document.createElement('canvas'); canvas.width = img.width; canvas.height = img.height; context = canvas.getContext('2d'); context.drawImage(img, 0, 0); pngdata = canvas.toDataURL('image/png'); a = document.createElement('a'); a.href = pngdata; a.download = 'wavedrom.png'; a.click(); menu.parentNode.removeChild(menu); document.body.removeEventListener('mousedown', closeMenu, false); }, false ); saveSvg.addEventListener('click', function () { var html, firstDiv, svgdata, a; html = ''; if (index !== 0) { firstDiv = document.getElementById(output + 0); html += firstDiv.innerHTML.substring(166, firstDiv.innerHTML.indexOf('<g id="waves_0">')); } html = [div.innerHTML.slice(0, 166), html, div.innerHTML.slice(166)].join(''); svgdata = 'data:image/svg+xml;base64,' + btoa(html); a = document.createElement('a'); a.href = svgdata; a.download = 'wavedrom.svg'; a.click(); menu.parentNode.removeChild(menu); document.body.removeEventListener('mousedown', closeMenu, false); }, false ); menu.addEventListener('contextmenu', function (ee) { ee.preventDefault(); }, false ); document.body.addEventListener('mousedown', closeMenu, false); e.preventDefault(); }, false ); } module.exports = appendSaveAsDialog; /* eslint-env browser */ },{}],2:[function(require,module,exports){ 'use strict'; var // obj2ml = require('./obj2ml'), jsonmlParse = require('./jsonml-parse'); // function createElement (obj) { // var el; // // el = document.createElement('g'); // el.innerHTML = obj2ml(obj); // return el.firstChild; // } module.exports = jsonmlParse; // module.exports = createElement; /* eslint-env browser */ },{"./jsonml-parse":15}],3:[function(require,module,exports){ 'use strict'; var eva = require('./eva'), lane = require('./lane'), renderWaveForm = require('./render-wave-form'); function editorRefresh () { // var svg, // ser, // ssvg, // asvg, // sjson, // ajson; renderWaveForm(0, eva('InputJSON_0'), 'WaveDrom_Display_', lane); /* svg = document.getElementById('svgcontent_0'); ser = new XMLSerializer(); ssvg = '<?xml version='1.0' standalone='no'?>\n' + '<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>\n' + '<!-- Created with WaveDrom -->\n' + ser.serializeToString(svg); asvg = document.getElementById('download_svg'); asvg.href = 'data:image/svg+xml;base64,' + window.btoa(ssvg); sjson = localStorage.waveform; ajson = document.getElementById('download_json'); ajson.href = 'data:text/json;base64,' + window.btoa(sjson); */ } module.exports = editorRefresh; },{"./eva":4,"./lane":17,"./render-wave-form":28}],4:[function(require,module,exports){ 'use strict'; function eva (id) { var TheTextBox, source; function erra (e) { return { signal: [{ name: ['tspan', ['tspan', {class:'error h5'}, 'Error: '], e.message] }]}; } TheTextBox = document.getElementById(id); /* eslint-disable no-eval */ if (TheTextBox.type && TheTextBox.type === 'textarea') { try { source = eval('(' + TheTextBox.value + ')'); } catch (e) { return erra(e); } } else { try { source = eval('(' + TheTextBox.innerHTML + ')'); } catch (e) { return erra(e); } } /* eslint-enable no-eval */ if (Object.prototype.toString.call(source) !== '[object Object]') { return erra({ message: '[Semantic]: The root has to be an Object: "{signal:[...]}"'}); } if (source.signal) { if (Object.prototype.toString.call(source.signal) !== '[object Array]') { return erra({ message: '[Semantic]: "signal" object has to be an Array "signal:[]"'}); } } else if (source.assign) { if (Object.prototype.toString.call(source.assign) !== '[object Array]') { return erra({ message: '[Semantic]: "assign" object hasto be an Array "assign:[]"'}); } } else { return erra({ message: '[Semantic]: "signal:[...]" or "assign:[...]" property is missing inside the root Object'}); } return source; } module.exports = eva; /* eslint-env browser */ },{}],5:[function(require,module,exports){ 'use strict'; function findLaneMarkers (lanetext) { var gcount = 0, lcount = 0, ret = []; lanetext.forEach(function (e) { if ( (e === 'vvv-2') || (e === 'vvv-3') || (e === 'vvv-4') || (e === 'vvv-5') ) { lcount += 1; } else { if (lcount !== 0) { ret.push(gcount - ((lcount + 1) / 2)); lcount = 0; } } gcount += 1; }); if (lcount !== 0) { ret.push(gcount - ((lcount + 1) / 2)); } return ret; } module.exports = findLaneMarkers; },{}],6:[function(require,module,exports){ 'use strict'; function genBrick (texts, extra, times) { var i, j, R = []; if (texts.length === 4) { for (j = 0; j < times; j += 1) { R.push(texts[0]); for (i = 0; i < extra; i += 1) { R.push(texts[1]); } R.push(texts[2]); for (i = 0; i < extra; i += 1) { R.push(texts[3]); } } return R; } if (texts.length === 1) { texts.push(texts[0]); } R.push(texts[0]); for (i = 0; i < (times * (2 * (extra + 1)) - 1); i += 1) { R.push(texts[1]); } return R; } module.exports = genBrick; },{}],7:[function(require,module,exports){ 'use strict'; var genBrick = require('./gen-brick'); function genFirstWaveBrick (text, extra, times) { var tmp; tmp = []; switch (text) { case 'p': tmp = genBrick(['pclk', '111', 'nclk', '000'], extra, times); break; case 'n': tmp = genBrick(['nclk', '000', 'pclk', '111'], extra, times); break; case 'P': tmp = genBrick(['Pclk', '111', 'nclk', '000'], extra, times); break; case 'N': tmp = genBrick(['Nclk', '000', 'pclk', '111'], extra, times); break; case 'l': case 'L': case '0': tmp = genBrick(['000'], extra, times); break; case 'h': case 'H': case '1': tmp = genBrick(['111'], extra, times); break; case '=': tmp = genBrick(['vvv-2'], extra, times); break; case '2': tmp = genBrick(['vvv-2'], extra, times); break; case '3': tmp = genBrick(['vvv-3'], extra, times); break; case '4': tmp = genBrick(['vvv-4'], extra, times); break; case '5': tmp = genBrick(['vvv-5'], extra, times); break; case 'd': tmp = genBrick(['ddd'], extra, times); break; case 'u': tmp = genBrick(['uuu'], extra, times); break; case 'z': tmp = genBrick(['zzz'], extra, times); break; default: tmp = genBrick(['xxx'], extra, times); break; } return tmp; } module.exports = genFirstWaveBrick; },{"./gen-brick":6}],8:[function(require,module,exports){ 'use strict'; var genBrick = require('./gen-brick'); function genWaveBrick (text, extra, times) { var x1, x2, x3, y1, y2, x4, x5, x6, xclude, atext, tmp0, tmp1, tmp2, tmp3, tmp4; x1 = {p:'pclk', n:'nclk', P:'Pclk', N:'Nclk', h:'pclk', l:'nclk', H:'Pclk', L:'Nclk'}; x2 = { '0':'0', '1':'1', 'x':'x', 'd':'d', 'u':'u', 'z':'z', '=':'v', '2':'v', '3':'v', '4':'v', '5':'v' }; x3 = { '0': '', '1': '', 'x': '', 'd': '', 'u': '', 'z': '', '=':'-2', '2':'-2', '3':'-3', '4':'-4', '5':'-5' }; y1 = { 'p':'0', 'n':'1', 'P':'0', 'N':'1', 'h':'1', 'l':'0', 'H':'1', 'L':'0', '0':'0', '1':'1', 'x':'x', 'd':'d', 'u':'u', 'z':'z', '=':'v', '2':'v', '3':'v', '4':'v', '5':'v' }; y2 = { 'p': '', 'n': '', 'P': '', 'N': '', 'h': '', 'l': '', 'H': '', 'L': '', '0': '', '1': '', 'x': '', 'd': '', 'u': '', 'z': '', '=':'-2', '2':'-2', '3':'-3', '4':'-4', '5':'-5' }; x4 = { 'p': '111', 'n': '000', 'P': '111', 'N': '000', 'h': '111', 'l': '000', 'H': '111', 'L': '000', '0': '000', '1': '111', 'x': 'xxx', 'd': 'ddd', 'u': 'uuu', 'z': 'zzz', '=': 'vvv-2', '2': 'vvv-2', '3': 'vvv-3', '4': 'vvv-4', '5': 'vvv-5' }; x5 = { p:'nclk', n:'pclk', P:'nclk', N:'pclk' }; x6 = { p: '000', n: '111', P: '000', N: '111' }; xclude = { 'hp':'111', 'Hp':'111', 'ln': '000', 'Ln': '000', 'nh':'111', 'Nh':'111', 'pl': '000', 'Pl':'000' }; atext = text.split(''); //if (atext.length !== 2) { return genBrick(['xxx'], extra, times); } tmp0 = x4[atext[1]]; tmp1 = x1[atext[1]]; if (tmp1 === undefined) { tmp2 = x2[atext[1]]; if (tmp2 === undefined) { // unknown return genBrick(['xxx'], extra, times); } else { tmp3 = y1[atext[0]]; if (tmp3 === undefined) { // unknown return genBrick(['xxx'], extra, times); } // soft curves return genBrick([tmp3 + 'm' + tmp2 + y2[atext[0]] + x3[atext[1]], tmp0], extra, times); } } else { tmp4 = xclude[text]; if (tmp4 !== undefined) { tmp1 = tmp4; } // sharp curves tmp2 = x5[atext[1]]; if (tmp2 === undefined) { // hlHL return genBrick([tmp1, tmp0], extra, times); } else { // pnPN return genBrick([tmp1, tmp0, tmp2, x6[atext[1]]], extra, times); } } } module.exports = genWaveBrick; },{"./gen-brick":6}],9:[function(require,module,exports){ 'use strict'; module.exports = { processAll: require('./process-all'), renderWaveForm: require('./render-wave-form'), editorRefresh: require('./editor-refresh') }; },{"./editor-refresh":3,"./process-all":21,"./render-wave-form":28}],10:[function(require,module,exports){ 'use strict'; var jsonmlParse = require('./create-element'), w3 = require('./w3'); function insertSVGTemplateAssign (index, parent) { var node, e; // cleanup while (parent.childNodes.length) { parent.removeChild(parent.childNodes[0]); } e = ['svg', {id: 'svgcontent_' + index, xmlns: w3.svg, 'xmlns:xlink': w3.xlink, overflow:'hidden'}, ['style', '.pinname {font-size:12px; font-style:normal; font-variant:normal; font-weight:500; font-stretch:normal; text-align:center; text-anchor:end; font-family:Helvetica} .wirename {font-size:12px; font-style:normal; font-variant:normal; font-weight:500; font-stretch:normal; text-align:center; text-anchor:start; font-family:Helvetica} .wirename:hover {fill:blue} .gate {color:#000; fill:#ffc; fill-opacity: 1;stroke:#000; stroke-width:1; stroke-opacity:1} .gate:hover {fill:red !important; } .wire {fill:none; stroke:#000; stroke-width:1; stroke-opacity:1} .grid {fill:#fff; fill-opacity:1; stroke:none}'] ]; node = jsonmlParse(e); parent.insertBefore(node, null); } module.exports = insertSVGTemplateAssign; /* eslint-env browser */ },{"./create-element":2,"./w3":30}],11:[function(require,module,exports){ 'use strict'; var jsonmlParse = require('./create-element'), w3 = require('./w3'), waveSkin = require('./wave-skin'); function insertSVGTemplate (index, parent, source, lane) { var node, first, e; // cleanup while (parent.childNodes.length) { parent.removeChild(parent.childNodes[0]); } for (first in waveSkin) { break; } e = waveSkin.default || waveSkin[first]; if (source && source.config && source.config.skin && waveSkin[source.config.skin]) { e = waveSkin[source.config.skin]; } if (index === 0) { lane.xs = Number(e[3][1][2][1].width); lane.ys = Number(e[3][1][2][1].height); lane.xlabel = Number(e[3][1][2][1].x); lane.ym = Number(e[3][1][2][1].y); } else { e = ['svg', { id: 'svg', xmlns: w3.svg, 'xmlns:xlink': w3.xlink, height: '0' }, ['g', { id: 'waves' }, ['g', {id: 'lanes'}], ['g', {id: 'groups'}] ] ]; } e[e.length - 1][1].id = 'waves_' + index; e[e.length - 1][2][1].id = 'lanes_' + index; e[e.length - 1][3][1].id = 'groups_' + index; e[1].id = 'svgcontent_' + index; e[1].height = 0; node = jsonmlParse(e); parent.insertBefore(node, null); } module.exports = insertSVGTemplate; /* eslint-env browser */ },{"./create-element":2,"./w3":30,"./wave-skin":32}],12:[function(require,module,exports){ 'use strict'; //attribute name mapping var ATTRMAP = { rowspan : 'rowSpan', colspan : 'colSpan', cellpadding : 'cellPadding', cellspacing : 'cellSpacing', tabindex : 'tabIndex', accesskey : 'accessKey', hidefocus : 'hideFocus', usemap : 'useMap', maxlength : 'maxLength', readonly : 'readOnly', contenteditable : 'contentEditable' // can add more attributes here as needed }, // attribute duplicates ATTRDUP = { enctype : 'encoding', onscroll : 'DOMMouseScroll' // can add more attributes here as needed }, // event names EVTS = (function (/*string[]*/ names) { var evts = {}, evt; while (names.length) { evt = names.shift(); evts['on' + evt.toLowerCase()] = evt; } return evts; })('blur,change,click,dblclick,error,focus,keydown,keypress,keyup,load,mousedown,mouseenter,mouseleave,mousemove,mouseout,mouseover,mouseup,resize,scroll,select,submit,unload'.split(',')); /*void*/ function addHandler(/*DOM*/ elem, /*string*/ name, /*function*/ handler) { if (typeof handler === 'string') { handler = new Function('event', handler); } if (typeof handler !== 'function') { return; } elem[name] = handler; } /*DOM*/ function addAttributes(/*DOM*/ elem, /*object*/ attr) { if (attr.name && document.attachEvent) { try { // IE fix for not being able to programatically change the name attribute var alt = document.createElement('<' + elem.tagName + ' name=\'' + attr.name + '\'>'); // fix for Opera 8.5 and Netscape 7.1 creating malformed elements if (elem.tagName === alt.tagName) { elem = alt; } } catch (ex) { console.log(ex); } } // for each attributeName for (var name in attr) { if (attr.hasOwnProperty(name)) { // attributeValue var value = attr[name]; if ( name && value !== null && typeof value !== 'undefined' ) { name = ATTRMAP[name.toLowerCase()] || name; if (name === 'style') { if (typeof elem.style.cssText !== 'undefined') { elem.style.cssText = value; } else { elem.style = value; } // } else if (name === 'class') { // elem.className = value; // // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // elem.setAttribute(name, value); // // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! } else if (EVTS[name]) { addHandler(elem, name, value); // also set duplicated events if (ATTRDUP[name]) { addHandler(elem, ATTRDUP[name], value); } } else if ( typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ) { elem.setAttribute(name, value); // also set duplicated attributes if (ATTRDUP[name]) { elem.setAttribute(ATTRDUP[name], value); } } else { // allow direct setting of complex properties elem[name] = value; // also set duplicated attributes if (ATTRDUP[name]) { elem[ATTRDUP[name]] = value; } } } } } return elem; } module.exports = addAttributes; /* eslint-env browser */ /* eslint no-new-func:0 */ },{}],13:[function(require,module,exports){ 'use strict'; /*void*/ function appendChild(/*DOM*/ elem, /*DOM*/ child) { if (child) { // if ( // elem.tagName && // elem.tagName.toLowerCase() === 'table' && // elem.tBodies // ) { // if (!child.tagName) { // // must unwrap documentFragment for tables // if (child.nodeType === 11) { // while (child.firstChild) { // appendChild(elem, child.removeChild(child.firstChild)); // } // } // return; // } // // in IE must explicitly nest TRs in TBODY // var childTag = child.tagName.toLowerCase();// child tagName // if (childTag && childTag !== "tbody" && childTag !== "thead") { // // insert in last tbody // var tBody = elem.tBodies.length > 0 ? elem.tBodies[elem.tBodies.length - 1] : null; // if (!tBody) { // tBody = document.createElement(childTag === "th" ? "thead" : "tbody"); // elem.appendChild(tBody); // } // tBody.appendChild(child); // } else if (elem.canHaveChildren !== false) { // elem.appendChild(child); // } // } else if ( elem.tagName && elem.tagName.toLowerCase() === 'style' && document.createStyleSheet ) { // IE requires this interface for styles elem.cssText = child; } else if (elem.canHaveChildren !== false) { elem.appendChild(child); } // else if ( // elem.tagName && // elem.tagName.toLowerCase() === 'object' && // child.tagName && // child.tagName.toLowerCase() === 'param' // ) { // // IE-only path // try { // elem.appendChild(child); // } catch (ex1) { // // } // try { // if (elem.object) { // elem.object[child.name] = child.value; // } // } catch (ex2) {} // } } } module.exports = appendChild; /* eslint-env browser */ },{}],14:[function(require,module,exports){ 'use strict'; var trimWhitespace = require('./jsonml-trim-whitespace'); /*DOM*/ function hydrate(/*string*/ value) { var wrapper = document.createElement('div'); wrapper.innerHTML = value; // trim extraneous whitespace trimWhitespace(wrapper); // eliminate wrapper for single nodes if (wrapper.childNodes.length === 1) { return wrapper.firstChild; } // create a document fragment to hold elements var frag = document.createDocumentFragment ? document.createDocumentFragment() : document.createElement(''); while (wrapper.firstChild) { frag.appendChild(wrapper.firstChild); } return frag; } module.exports = hydrate; /* eslint-env browser */ },{"./jsonml-trim-whitespace":16}],15:[function(require,module,exports){ 'use strict'; var hydrate = require('./jsonml-hydrate'), w3 = require('./w3'), appendChild = require('./jsonml-append-child'), addAttributes = require('./jsonml-add-attributes'), trimWhitespace = require('./jsonml-trim-whitespace'); var patch, parse, onerror = null; /*bool*/ function isElement (/*JsonML*/ jml) { return (jml instanceof Array) && (typeof jml[0] === 'string'); } /*DOM*/ function onError (/*Error*/ ex, /*JsonML*/ jml, /*function*/ filter) { return document.createTextNode('[' + ex + '-' + filter + ']'); } patch = /*DOM*/ function (/*DOM*/ elem, /*JsonML*/ jml, /*function*/ filter) { for (var i = 1; i < jml.length; i++) { if ( (jml[i] instanceof Array) || (typeof jml[i] === 'string') ) { // append children appendChild(elem, parse(jml[i], filter)); // } else if (jml[i] instanceof Unparsed) { } else if ( jml[i] && jml[i].value ) { appendChild(elem, hydrate(jml[i].value)); } else if ( (typeof jml[i] === 'object') && (jml[i] !== null) && elem.nodeType === 1 ) { // add attributes elem = addAttributes(elem, jml[i]); } } return elem; }; parse = /*DOM*/ function (/*JsonML*/ jml, /*function*/ filter) { var elem; try { if (!jml) { return null; } if (typeof jml === 'string') { return document.createTextNode(jml); } // if (jml instanceof Unparsed) { if (jml && jml.value) { return hydrate(jml.value); } if (!isElement(jml)) { throw new SyntaxError('invalid JsonML'); } var tagName = jml[0]; // tagName if (!tagName) { // correctly handle a list of JsonML trees // create a document fragment to hold elements var frag = document.createDocumentFragment ? document.createDocumentFragment() : document.createElement(''); for (var i = 2; i < jml.length; i++) { appendChild(frag, parse(jml[i], filter)); } // trim extraneous whitespace trimWhitespace(frag); // eliminate wrapper for single nodes if (frag.childNodes.length === 1) { return frag.firstChild; } return frag; } if ( tagName.toLowerCase() === 'style' && document.createStyleSheet ) { // IE requires this interface for styles patch(document.createStyleSheet(), jml, filter); // in IE styles are effective immediately return null; } elem = patch(document.createElementNS(w3.svg, tagName), jml, filter); // trim extraneous whitespace trimWhitespace(elem); // return (elem && (typeof filter === 'function')) ? filter(elem) : elem; return elem; } catch (ex) { try { // handle error with complete context var err = (typeof onerror === 'function') ? onerror : onError; return err(ex, jml, filter); } catch (ex2) { return document.createTextNode('[' + ex2 + ']'); } } }; module.exports = parse; /* eslint-env browser */ /* eslint yoda:1 */ },{"./jsonml-add-attributes":12,"./jsonml-append-child":13,"./jsonml-hydrate":14,"./jsonml-trim-whitespace":16,"./w3":30}],16:[function(require,module,exports){ 'use strict'; /*bool*/ function isWhitespace(/*DOM*/ node) { return node && (node.nodeType === 3) && (!node.nodeValue || !/\S/.exec(node.nodeValue)); } /*void*/ function trimWhitespace(/*DOM*/ elem) { if (elem) { while (isWhitespace(elem.firstChild)) { // trim leading whitespace text nodes elem.removeChild(elem.firstChild); } while (isWhitespace(elem.lastChild)) { // trim trailing whitespace text nodes elem.removeChild(elem.lastChild); } } } module.exports = trimWhitespace; /* eslint-env browser */ },{}],17:[function(require,module,exports){ 'use strict'; var lane = { xs : 20, // tmpgraphlane0.width ys : 20, // tmpgraphlane0.height xg : 120, // tmpgraphlane0.x // yg : 0, // head gap yh0 : 0, // head gap title yh1 : 0, // head gap yf0 : 0, // foot gap yf1 : 0, // foot gap y0 : 5, // tmpgraphlane0.y yo : 30, // tmpgraphlane1.y - y0; tgo : -10, // tmptextlane0.x - xg; ym : 15, // tmptextlane0.y - y0 xlabel : 6, // tmptextlabel.x - xg; xmax : 1, scale : 1, head : {}, foot : {} }; module.exports = lane; },{}],18:[function(require,module,exports){ 'use strict'; function parseConfig (source, lane) { var hscale; function tonumber (x) { return x > 0 ? Math.round(x) : 1; } lane.hscale = 1; if (lane.hscale0) { lane.hscale = lane.hscale0; } if (source && source.config && source.config.hscale) { hscale = Math.round(tonumber(source.config.hscale)); if (hscale > 0) { if (hscale > 100) { hscale = 100; } lane.hscale = hscale; } } lane.yh0 = 0; lane.yh1 = 0; lane.head = source.head; if (source && source.head) { if ( source.head.tick || source.head.tick === 0 || source.head.tock || source.head.tock === 0 ) { lane.yh0 = 20; } if (source.head.text) { lane.yh1 = 46; lane.head.text = source.head.text; } } lane.yf0 = 0; lane.yf1 = 0; lane.foot = source.foot; if (source && source.foot) { if ( source.foot.tick || source.foot.tick === 0 || source.foot.tock || source.foot.tock === 0 ) { lane.yf0 = 20; } if (source.foot.text) { lane.yf1 = 46; lane.foot.text = source.foot.text; } } } module.exports = parseConfig; },{}],19:[function(require,module,exports){ 'use strict'; var genFirstWaveBrick = require('./gen-first-wave-brick'), genWaveBrick = require('./gen-wave-brick'); function parseWaveLane (text, extra, lane) { var Repeats, Top, Next, Stack = [], R = [], i; Stack = text.split(''); Next = Stack.shift(); Repeats = 1; while (Stack[0] === '.' || Stack[0] === '|') { // repeaters parser Stack.shift(); Repeats += 1; } R = R.concat(genFirstWaveBrick(Next, extra, Repeats)); while (Stack.length) { Top = Next; Next = Stack.shift(); Repeats = 1; while (Stack[0] === '.' || Stack[0] === '|') { // repeaters parser Stack.shift(); Repeats += 1; } R = R.concat(genWaveBrick((Top + Next), extra, Repeats)); } for (i = 0; i < lane.phase; i += 1) { R.shift(); } return R; } module.exports = parseWaveLane; },{"./gen-first-wave-brick":7,"./gen-wave-brick":8}],20:[function(require,module,exports){ 'use strict'; var parseWaveLane = require('./parse-wave-lane'); function data_extract (e) { var tmp; tmp = e.data; if (tmp === undefined) { return null; } if (typeof (tmp) === 'string') { return tmp.split(' '); } return tmp; } function parseWaveLanes (sig, lane) { var x, sigx, content = [], tmp0 = []; for (x in sig) { sigx = sig[x]; lane.period = sigx.period ? sigx.period : 1; lane.phase = sigx.phase ? sigx.phase * 2 : 0; content.push([]); tmp0[0] = sigx.name || ' '; tmp0[1] = sigx.phase || 0; content[content.length - 1][0] = tmp0.slice(0); content[content.length - 1][1] = sigx.wave ? parseWaveLane(sigx.wave, lane.period * lane.hscale - 1, lane) : null; content[content.length - 1][2] = data_extract(sigx); } return content; } module.exports = parseWaveLanes; },{"./parse-wave-lane":19}],21:[function(require,module,exports){ 'use strict'; var eva = require('./eva'), lane = require('./lane'), appendSaveAsDialog = require('./append-save-as-dialog'), renderWaveForm = require('./render-wave-form'); function processAll () { var points, i, index, node0; // node1; // first pass index = 0; // actual number of valid anchor points = document.querySelectorAll('*'); for (i = 0; i < points.length; i++) { if (points.item(i).type && points.item(i).type === 'WaveDrom') { points.item(i).setAttribute('id', 'InputJSON_' + index); node0 = document.createElement('div'); // node0.className += 'WaveDrom_Display_' + index; node0.id = 'WaveDrom_Display_' + index; points.item(i).parentNode.insertBefore(node0, points.item(i)); // WaveDrom.InsertSVGTemplate(i, node0); index += 1; } } // second pass for (i = 0; i < index; i += 1) { renderWaveForm(i, eva('InputJSON_' + i), 'WaveDrom_Display_', lane); appendSaveAsDialog(i, 'WaveDrom_Display_'); } // add styles document.head.innerHTML += '<style type="text/css">div.wavedromMenu{position:fixed;border:solid 1pt#CCCCCC;background-color:white;box-shadow:0px 10px 20px #808080;cursor:default;margin:0px;padding:0px;}div.wavedromMenu>ul{margin:0px;padding:0px;}div.wavedromMenu>ul>li{padding:2px 10px;list-style:none;}div.wavedromMenu>ul>li:hover{background-color:#b5d5ff;}</style>'; } module.exports = processAll; /* eslint-env browser */ },{"./append-save-as-dialog":1,"./eva":4,"./lane":17,"./render-wave-form":28}],22:[function(require,module,exports){ 'use strict'; function rec (tmp, state) { var i, name, old = {}, delta = {'x':10}; if (typeof tmp[0] === 'string' || typeof tmp[0] === 'number') { name = tmp[0]; delta.x = 25; } state.x += delta.x; for (i = 0; i < tmp.length; i++) { if (typeof tmp[i] === 'object') { if (Object.prototype.toString.call(tmp[i]) === '[object Array]') { old.y = state.y; state = rec(tmp[i], state); state.groups.push({'x':state.xx, 'y':old.y, 'height':(state.y - old.y), 'name':state.name}); } else { state.lanes.push(tmp[i]); state.width.push(state.x); state.y += 1; } } } state.xx = state.x; state.x -= delta.x; state.name = name; return state; } module.exports = rec; },{}],23:[function(require,module,exports){ 'use strict'; var tspan = require('tspan'), jsonmlParse = require('./create-element'), w3 = require('./w3'); function renderArcs (root, source, index, top, lane) { var gg, i, k, text, Stack = [], Edge = {words: [], from: 0, shape: '', to: 0, label: ''}, Events = {}, pos, eventname, // labeltext, label, underlabel, from, to, dx, dy, lx, ly, gmark, lwidth; function t1 () { if (from && to) { gmark = document.createElementNS(w3.svg, 'path'); gmark.id = ('gmark_' + Edge.from + '_' + Edge.to); gmark.setAttribute('d', 'M ' + from.x + ',' + from.y + ' ' + to.x + ',' + to.y); gmark.setAttribute('style', 'fill:none;stroke:#00F;stroke-width:1'); gg.insertBefore(gmark, null); } } if (source) { for (i in source) { lane.period = source[i].period ? source[i].period : 1; lane.phase = source[i].phase ? source[i].phase * 2 : 0; text = source[i].node; if (text) { Stack = text.split(''); pos = 0; while (Stack.length) { eventname = Stack.shift(); if (eventname !== '.') { Events[eventname] = { 'x' : lane.xs * (2 * pos * lane.period * lane.hscale - lane.phase) + lane.xlabel, 'y' : i * lane.yo + lane.y0 + lane.ys * 0.5 }; } pos += 1; } } } gg = document.createElementNS(w3.svg, 'g'); gg.id = 'wavearcs_' + index; root.insertBefore(gg, null); if (top.edge) { for (i in top.edge) { Edge.words = top.edge[i].split(' '); Edge.label = top.edge[i].substring(Edge.words[0].length); Edge.label = Edge.label.substring(1); Edge.from = Edge.words[0].substr(0, 1); Edge.to = Edge.words[0].substr(-1, 1); Edge.shape = Edge.words[0].slice(1, -1); from = Events[Edge.from]; to = Events[Edge.to]; t1(); if (from && to) { if (Edge.label) { label = tspan.parse(Edge.label); label.unshift( 'text', { style: 'font-size:10px;', 'text-anchor': 'middle' } ); label = jsonmlParse(label); label.setAttributeNS(w3.xmlns, 'xml:space', 'preserve'); underlabel = jsonmlParse(['rect', { height: 9, style: 'fill:#FFF;' } ]); gg.insertBefore(underlabel, null); gg.insertBefore(label, null); lwidth = label.getBBox().width; underlabel.setAttribute('width', lwidth); } dx = to.x - from.x; dy = to.y - from.y; lx = ((from.x + to.x) / 2); ly = ((from.y + to.y) / 2); switch (Edge.shape) { case '-' : { break; } case '~' : { gmark.setAttribute('d', 'M ' + from.x + ',' + from.y + ' c ' + (0.7 * dx) + ', 0 ' + (0.3 * dx) + ', ' + dy + ' ' + dx + ', ' + dy); break; } case '-~' : { gmark.setAttribute('d', 'M ' + from.x + ',' + from.y + ' c ' + (0.7 * dx) + ', 0 ' + dx + ', ' + dy + ' ' + dx + ', ' + dy); if (Edge.label) { lx = (from.x + (to.x - from.x) * 0.75); } break; } case '~-' : { gmark.setAttribute('d', 'M ' + from.x + ',' + from.y + ' c ' + 0 + ', 0 ' + (0.3 * dx) + ', ' + dy + ' ' + dx + ', ' + dy); if (Edge.label) { lx = (from.x + (to.x - from.x) * 0.25); } break; } case '-|' : { gmark.setAttribute('d', 'm ' + from.x + ',' + from.y + ' ' + dx + ',0 0,' + dy); if (Edge.label) { lx = to.x; } break; } case '|-' : { gmark.setAttribute('d', 'm ' + from.x + ',' + from.y + ' 0,' + dy + ' ' + dx + ',0'); if (Edge.label) { lx = from.x; } break; } case '-|-': { gmark.setAttribute('d', 'm ' + from.x + ',' + from.y + ' ' + (dx / 2) + ',0 0,' + dy + ' ' + (dx / 2) + ',0'); break; } case '->' : { gmark.setAttribute('style', 'marker-end:url(#arrowhead);stroke:#0041c4;stroke-width:1;fill:none'); break; } case '~>' : { gmark.setAttribute('style', 'marker-end:url(#arrowhead);stroke:#0041c4;stroke-width:1;fill:none'); gmark.setAttribute('d', 'M ' + from.x + ',' + from.y + ' ' + 'c ' + (0.7 * dx) + ', 0 ' + 0.3 * dx + ', ' + dy + ' ' + dx + ', ' + dy); break; } case '-~>': { gmark.setAttribute('style', 'marker-end:url(#arrowhead);stroke:#0041c4;stroke-width:1;fill:none'); gmark.setAttribute('d', 'M ' + from.x + ',' + from.y + ' ' + 'c ' + (0.7 * dx) + ', 0 ' + dx + ', ' + dy + ' ' + dx + ', ' + dy); if (Edge.label) { lx = (from.x + (to.x - from.x) * 0.75); } break; } case '~->': { gmark.setAttribute('style', 'marker-end:url(#arrowhead);stroke:#0041c4;stroke-width:1;fill:none'); gmark.setAttribute('d', 'M ' + from.x + ',' + from.y + ' ' + 'c ' + 0 + ', 0 ' + (0.3 * dx) + ', ' + dy + ' ' + dx + ', ' + dy); if (Edge.label) { lx = (from.x + (to.x - from.x) * 0.25); } break; } case '-|>' : { gmark.setAttribute('style', 'marker-end:url(#arrowhead);stroke:#0041c4;stroke-width:1;fill:none'); gmark.setAttribute('d', 'm ' + from.x + ',' + from.y + ' ' + dx + ',0 0,' + dy); if (Edge.label) { lx = to.x; } break; } case '|->' : { gmark.setAttribute('style', 'marker-end:url(#arrowhead);stroke:#0041c4;stroke-width:1;fill:none'); gmark.setAttribute('d', 'm ' + from.x + ',' + from.y + ' 0,' + dy + ' ' + dx + ',0'); if (Edge.label) { lx = from.x; } break; } case '-|->': { gmark.setAttribute('style', 'marker-end:url(#arrowhead);stroke:#0041c4;stroke-width:1;fill:none'); gmark.setAttribute('d', 'm ' + from.x + ',' + from.y + ' ' + (dx / 2) + ',0 0,' + dy + ' ' + (dx / 2) + ',0'); break; } case '<->' : { gmark.setAttribute('style', 'marker-end:url(#arrowhead);marker-start:url(#arrowtail);stroke:#0041c4;stroke-width:1;fill:none'); break; } case '<~>' : { gmark.setAttribute('style', 'marker-end:url(#arrowhead);marker-start:url(#arrowtail);stroke:#0041c4;stroke-width:1;fill:none'); gmark.setAttribute('d', 'M ' + from.x + ',' + from.y + ' ' + 'c ' + (0.7 * dx) + ', 0 ' + (0.3 * dx) + ', ' + dy + ' ' + dx + ', ' + dy); break; } case '<-~>': { gmark.setAttribute('style', 'marker-end:url(#arrowhead);marker-start:url(#arrowtail);stroke:#0041c4;stroke-width:1;fill:none'); gmark.setAttribute('d', 'M ' + from.x + ',' + from.y + ' ' + 'c ' + (0.7 * dx) + ', 0 ' + dx + ', ' + dy + ' ' + dx + ', ' + dy); if (Edge.label) { lx = (from.x + (to.x - from.x) * 0.75); } break; } case '<-|>' : { gmark.setAttribute('style', 'marker-end:url(#arrowhead);marker-start:url(#arrowtail);stroke:#0041c4;stroke-width:1;fill:none'); gmark.setAttribute('d', 'm ' + from.x + ',' + from.y + ' ' + dx + ',0 0,' + dy); if (Edge.label) { lx = to.x; } break; } case '<-|->': { gmark.setAttribute('style', 'marker-end:url(#arrowhead);marker-start:url(#arrowtail);stroke:#0041c4;stroke-width:1;fill:none'); gmark.setAttribute('d', 'm ' + from.x + ',' + from.y + ' ' + (dx / 2) + ',0 0,' + dy + ' ' + (dx / 2) + ',0'); break; } default : { gmark.setAttribute('style', 'fill:none;stroke:#F00;stroke-width:1'); } } if (Edge.label) { label.setAttribute('x', lx); label.setAttribute('y', ly + 3); underlabel.setAttribute('x', lx - lwidth / 2); underlabel.setAttribute('y', ly - 5); } } } } for (k in Events) { if (k === k.toLowerCase()) { if (Events[k].x > 0) { underlabel = jsonmlParse(['rect', { y: Events[k].y - 4, height: 8, style: 'fill:#FFF;' } ]); gg.insertBefore(underlabel, null); label = jsonmlParse(['text', { style: 'font-size:8px;', x: Events[k].x, y: Events[k].y + 2, 'text-anchor': 'middle' }, (k + '') ]); gg.insertBefore(label, null); lwidth = label.getBBox().width + 2; underlabel.setAttribute('x', Events[k].x - lwidth / 2); underlabel.setAttribute('width', lwidth); } } } } } module.exports = renderArcs; /* eslint-env browser */ },{"./create-element":2,"./w3":30,"tspan":34}],24:[function(require,module,exports){ 'use strict'; var jsonmlParse = require('./create-element'); function render (tree, state) { var y, i, ilen; state.xmax = Math.max(state.xmax, state.x); y = state.y; ilen = tree.length; for (i = 1; i < ilen; i++) { if (Object.prototype.toString.call(tree[i]) === '[object Array]') { state = render(tree[i], {x: (state.x + 1), y: state.y, xmax: state.xmax}); } else { tree[i] = {name:tree[i], x: (state.x + 1), y: state.y}; state.y += 2; } } tree[0] = {name: tree[0], x: state.x, y: Math.round((y + (state.y - 2)) / 2)}; state.x--; return state; } function draw_body (type, ymin, ymax) { var e, iecs, circle = ' M 4,0 C 4,1.1 3.1,2 2,2 0.9,2 0,1.1 0,0 c 0,-1.1 0.9,-2 2,-2 1.1,0 2,0.9 2,2 z', gates = { '~': 'M -11,-6 -11,6 0,0 z m -5,6 5,0' + circle, '=': 'M -11,-6 -11,6 0,0 z m -5,6 5,0', '&': 'm -16,-10 5,0 c 6,0 11,4 11,10 0,6 -5,10 -11,10 l -5,0 z', '~&': 'm -16,-10 5,0 c 6,0 11,4 11,10 0,6 -5,10 -11,10 l -5,0 z' + circle, '|': 'm -18,-10 4,0 c 6,0 12,5 14,10 -2,5 -8,10 -14,10 l -4,0 c 2.5,-5 2.5,-15 0,-20 z', '~|': 'm -18,-10 4,0 c 6,0 12,5 14,10 -2,5 -8,10 -14,10 l -4,0 c 2.5,-5 2.5,-15 0,-20 z' + circle, '^': 'm -21,-10 c 1,3 2,6 2,10 m 0,0 c 0,4 -1,7 -2,10 m 3,-20 4,0 c 6,0 12,5 14,10 -2,5 -8,10 -14,10 l -4,0 c 1,-3 2,-6 2,-10 0,-4 -1,-7 -2,-10 z', '~^': 'm -21,-10 c 1,3 2,6 2,10 m 0,0 c 0,4 -1,7 -2,10 m 3,-20 4,0 c 6,0 12,5 14,10 -2,5 -8,10 -14,10 l -4,0 c 1,-3 2,-6 2,-10 0,-4 -1,-7 -2,-10 z' + circle, '+': 'm -8,5 0,-10 m -5,5 10,0 m 3,0 c 0,4.418278 -3.581722,8 -8,8 -4.418278,0 -8,-3.581722 -8,-8 0,-4.418278 3.581722,-8 8,-8 4.418278,0 8,3.581722 8,8 z', '*': 'm -4,4 -8,-8 m 0,8 8,-8 m 4,4 c 0,4.418278 -3.581722,8 -8,8 -4.418278,0 -8,-3.581722 -8,-8 0,-4.418278 3.581722,-8 8,-8 4.418278,0 8,3.581722 8,8 z' }, iec = { BUF: 1, INV: 1, AND: '&', NAND: '&', OR: '\u22651', NOR: '\u22651', XOR: '=1', XNOR: '=1', box: '' }, circled = { INV: 1, NAND: 1, NOR: 1, XNOR: 1 }; if (ymax === ymin) { ymax = 4; ymin = -4; } e = gates[type]; iecs = iec[type]; if (e) { return ['path', {class:'gate', d: e}]; } else { if (iecs) { return [ 'g', [ 'path', { class:'gate', d: 'm -16,' + (ymin - 3) + ' 16,0 0,' + (ymax - ymin + 6) + ' -16,0 z' + (circled[type] ? circle : '') }], [ 'text', [ 'tspan', {x: '-14', y: '4', class: 'wirename'}, iecs + '' ] ] ]; } else { return ['text', ['tspan', {x: '-14', y: '4', class: 'wirename'}, type + '']]; } } } function draw_gate (spec) { // ['type', [x,y], [x,y] ... ] var i, ret = ['g'], ys = [], ymin, ymax, ilen = spec.length; for (i = 2; i < ilen; i++) { ys.push(spec[i][1]); } ymin = Math.min.apply(null, ys); ymax = Math.max.apply(null, ys); ret.push( ['g', {transform:'translate(16,0)'}, ['path', { d: 'M ' + spec[2][0] + ',' + ymin + ' ' + spec[2][0] + ',' + ymax, class: 'wire' }] ] ); for (i = 2; i < ilen; i++) { ret.push( ['g', ['path', { d: 'm ' + spec[i][0] + ',' + spec[i][1] + ' 16,0', class: 'wire' } ] ] ); } ret.push( ['g', { transform: 'translate(' + spec[1][0] + ',' + spec[1][1] + ')' }, ['title', spec[0]], draw_body(spec[0], ymin - spec[1][1], ymax - spec[1][1]) ] ); return ret; } function draw_boxes (tree, xmax) { var ret = ['g'], i, ilen, fx, fy, fname, spec = []; if (Object.prototype.toString.call(tree) === '[object Array]') { ilen = tree.length; spec.push(tree[0].name); spec.push([32 * (xmax - tree[0].x), 8 * tree[0].y]); for (i = 1; i < ilen; i++) { if (Object.prototype.toString.call(tree[i]) === '[object Array]') { spec.push([32 * (xmax - tree[i][0].x), 8 * tree[i][0].y]); } else { spec.push([32 * (xmax - tree[i].x), 8 * tree[i].y]); } } ret.push(draw_gate(spec)); for (i = 1; i < ilen; i++) { ret.push(draw_boxes(tree[i], xmax)); } } else { fname = tree.name; fx = 32 * (xmax - tree.x); fy = 8 * tree.y; ret.push( ['g', { transform: 'translate(' + fx + ',' + fy + ')'}, ['title', fname], ['path', {d:'M 2,0 a 2,2 0 1 1 -4,0 2,2 0 1 1 4,0 z'}], ['text', ['tspan', { x:'-4', y:'4', class:'pinname'}, fname ] ] ] ); } return ret; } function renderAssign (index, source) { var tree, state, xmax, svg = ['g'], grid = ['g'], svgcontent, width, height, i, ilen, j, jlen; ilen = source.assign.length; state = { x: 0, y: 2, xmax: 0 }; tree = source.assign; for (i = 0; i < ilen; i++) { state = render(tree[i], state); state.x++; } xmax = state.xmax + 3; for (i = 0; i < ilen; i++) { svg.push(draw_boxes(tree[i], xmax)); } width = 32 * (xmax + 1) + 1; height = 8 * (state.y + 1) - 7; ilen = 4 * (xmax + 1); jlen = state.y + 1; for (i = 0; i <= ilen; i++) { for (j = 0; j <= jlen; j++) { grid.push(['rect', { height: 1, width: 1, x: (i * 8 - 0.5), y: (j * 8 - 0.5), class: 'grid' }]); } } svgcontent = document.getElementById('svgcontent_' + index); svgcontent.setAttribute('viewBox', '0 0 ' + width + ' ' + height); svgcontent.setAttribute('width', width); svgcontent.setAttribute('height', height); svgcontent.insertBefore(jsonmlParse(['g', {transform:'translate(0.5, 0.5)'}, grid, svg]), null); } module.exports = renderAssign; /* eslint-env browser */ },{"./create-element":2}],25:[function(require,module,exports){ 'use strict'; var w3 = require('./w3'); function renderGaps (root, source, index, lane) { var i, gg, g, b, pos, Stack = [], text; if (source) { gg = document.createElementNS(w3.svg, 'g'); gg.id = 'wavegaps_' + index; root.insertBefore(gg, null); for (i in source) { lane.period = source[i].period ? source[i].period : 1; lane.phase = source[i].phase ? source[i].phase * 2 : 0; g = document.createElementNS(w3.svg, 'g'); g.id = 'wavegap_' + i + '_' + index; g.setAttribute('transform', 'translate(0,' + (lane.y0 + i * lane.yo) + ')'); gg.insertBefore(g, null); text = source[i].wave; if (text) { Stack = text.split(''); pos = 0; while (Stack.length) { if (Stack.shift() === '|') { b = document.createElementNS(w3.svg, 'use'); // b.id = 'guse_' + pos + '_' + i + '_' + index; b.setAttributeNS(w3.xlink, 'xlink:href', '#gap'); b.setAttribute('transform', 'translate(' + (lane.xs * ((2 * pos + 1) * lane.period * lane.hscale - lane.phase)) + ')'); g.insertBefore(b, null); } pos += 1; } } } } } module.exports = renderGaps; /* eslint-env browser */ },{"./w3":30}],26:[function(require,module,exports){ 'use strict'; var tspan = require('tspan'); function renderGroups (groups, index, lane) { var x, y, res = ['g'], ts; groups.forEach(function (e, i) { res.push(['path', { id: 'group_' + i + '_' + index, d: ('m ' + (e.x + 0.5) + ',' + (e.y * lane.yo + 3.5 + lane.yh0 + lane.yh1) + ' c -3,0 -5,2 -5,5 l 0,' + (e.height * lane.yo - 16) + ' c 0,3 2,5 5,5'), style: 'stroke:#0041c4;stroke-width:1;fill:none' } ]); if (e.name === undefined) { return; } x = (e.x - 10); y = (lane.yo * (e.y + (e.height / 2)) + lane.yh0 + lane.yh1); ts = tspan.parse(e.name); ts.unshift( 'text', { 'text-anchor': 'middle', class: 'info', 'xml:space': 'preserve' } ); res.push(['g', {transform: 'translate(' + x + ',' + y + ')'}, ['g', {transform: 'rotate(270)'}, ts]]); }); return res; } module.exports = renderGroups; /* eslint-env browser */ },{"tspan":34}],27:[function(require,module,exports){ 'use strict'; var tspan = require('tspan'), jsonmlParse = require('./create-element'), w3 = require('./w3'); function renderMarks (root, content, index, lane) { var i, g, marks, mstep, mmstep, gy; // svgns function captext (cxt, anchor, y) { var tmark; if (cxt[anchor] && cxt[anchor].text) { tmark = tspan.parse(cxt[anchor].text); tmark.unshift( 'text', { x: cxt.xmax * cxt.xs / 2, y: y, 'text-anchor': 'middle', fill: '#000' } ); tmark = jsonmlParse(tmark); tmark.setAttributeNS(w3.xmlns, 'xml:space', 'preserve'); g.insertBefore(tmark, null); } } function ticktock (cxt, ref1, ref2, x, dx, y, len) { var tmark, step = 1, offset, dp = 0, val, L = [], tmp; if (cxt[ref1] === undefined || cxt[ref1][ref2] === undefined) { return; } val = cxt[ref1][ref2]; if (typeof val === 'string') { val = val.split(' '); } else if (typeof val === 'number' || typeof val === 'boolean') { offset = Number(val); val = []; for (i = 0; i < len; i += 1) { val.push(i + offset); } } if (Object.prototype.toString.call(val) === '[object Array]') { if (val.length === 0) { return; } else if (val.length === 1) { offset = Number(val[0]); if (isNaN(offset)) { L = val; } else { for (i = 0; i < len; i += 1) { L[i] = i + offset; } } } else if (val.length === 2) { offset = Number(val[0]); step = Number(val[1]); tmp = val[1].split('.'); if ( tmp.length === 2 ) { dp = tmp[1].length; } if (isNaN(offset) || isNaN(step)) { L = val; } else { offset = step * offset; for (i = 0; i < len; i += 1) { L[i] = (step * i + offset).toFixed(dp); } } } else { L = val; } } else { return; } for (i = 0; i < len; i += 1) { tmp = L[i]; // if (typeof tmp === 'number') { tmp += ''; } tmark = tspan.parse(tmp); tmark.unshift( 'text', { x: i * dx + x, y: y, 'text-anchor': 'middle', class: 'muted' } ); tmark = jsonmlParse(tmark); tmark.setAttributeNS(w3.xmlns, 'xml:space', 'preserve'); g.insertBefore(tmark, null); } } mstep = 2 * (lane.hscale); mmstep = mstep * lane.xs; marks = lane.xmax / mstep; gy = content.length * lane.yo; g = jsonmlParse(['g', {id: ('gmarks_' + index)}]); root.insertBefore(g, root.firstChild); for (i = 0; i < (marks + 1); i += 1) { g.insertBefore( jsonmlParse([ 'path', { id: 'gmark_' + i + '_' + index, d: 'm ' + (i * mmstep) + ',' + 0 + ' 0,' + gy, style: 'stroke:#888;stroke-width:0.5;stroke-dasharray:1,3' } ]), null ); } captext(lane, 'head', (lane.yh0 ? -33 : -13)); captext(lane, 'foot', gy + (lane.yf0 ? 45 : 25)); ticktock(lane, 'head', 'tick', 0, mmstep, -5, marks + 1); ticktock(lane, 'head', 'tock', mmstep / 2, mmstep, -5, marks); ticktock(lane, 'foot', 'tick', 0, mmstep, gy + 15, marks + 1); ticktock(lane, 'foot', 'tock', mmstep / 2, mmstep, gy + 15, marks); } module.exports = renderMarks; /* eslint-env browser */ },{"./create-element":2,"./w3":30,"tspan":34}],28:[function(require,module,exports){ 'use strict'; var rec = require('./rec'), onmlStringify = require('onml/lib/stringify'), parseConfig = require('./parse-config'), parseWaveLanes = require('./parse-wave-lanes'), renderMarks = require('./render-marks'), renderGaps = require('./render-gaps'), renderGroups = require('./render-groups'), renderWaveLane = require('./render-wave-lane'), renderAssign = require('./render-assign'), renderArcs = require('./render-arcs'), insertSVGTemplate = require('./insert-svg-template'), insertSVGTemplateAssign = require('./insert-svg-template-assign'); function renderWaveForm (index, source, output, lane) { var ret, root, groups, svgcontent, content, width, height, glengths, xmax = 0, i; if (source.signal) { insertSVGTemplate(index, document.getElementById(output + index), source, lane); parseConfig(source, lane); ret = rec(source.signal, {'x':0, 'y':0, 'xmax':0, 'width':[], 'lanes':[], 'groups':[]}); root = document.getElementById('lanes_' + index); groups = document.getElementById('groups_' + index); content = parseWaveLanes(ret.lanes, lane); glengths = renderWaveLane(root, content, index, lane); for (i in glengths) { xmax = Math.max(xmax, (glengths[i] + ret.width[i])); } renderMarks(root, content, index, lane); renderArcs(root, ret.lanes, index, source, lane); renderGaps(root, ret.lanes, index, lane); groups.innerHTML = onmlStringify(renderGroups(ret.groups, index, lane)); lane.xg = Math.ceil((xmax - lane.tgo) / lane.xs) * lane.xs; width = (lane.xg + (lane.xs * (lane.xmax + 1))); height = (content.length * lane.yo + lane.yh0 + lane.yh1 + lane.yf0 + lane.yf1); svgcontent = document.getElementById('svgcontent_' + index); svgcontent.setAttribute('viewBox', '0 0 ' + width + ' ' + height); svgcontent.setAttribute('width', width); svgcontent.setAttribute('height', height); svgcontent.setAttribute('overflow', 'hidden'); root.setAttribute('transform', 'translate(' + (lane.xg + 0.5) + ', ' + ((lane.yh0 + lane.yh1) + 0.5) + ')'); } else if (source.assign) { insertSVGTemplateAssign(index, document.getElementById(output + index), source); renderAssign(index, source); } } module.exports = renderWaveForm; /* eslint-env browser */ },{"./insert-svg-template":11,"./insert-svg-template-assign":10,"./parse-config":18,"./parse-wave-lanes":20,"./rec":22,"./render-arcs":23,"./render-assign":24,"./render-gaps":25,"./render-groups":26,"./render-marks":27,"./render-wave-lane":29,"onml/lib/stringify":33}],29:[function(require,module,exports){ 'use strict'; var tspan = require('tspan'), jsonmlParse = require('./create-element'), w3 = require('./w3'), findLaneMarkers = require('./find-lane-markers'); function renderWaveLane (root, content, index, lane) { var i, j, k, g, gg, title, b, labels = [1], name, xoffset, xmax = 0, xgmax = 0, glengths = []; for (j = 0; j < content.length; j += 1) { name = content[j][0][0]; if (name) { // check name g = jsonmlParse(['g', { id: 'wavelane_' + j + '_' + index, transform: 'translate(0,' + ((lane.y0) + j * lane.yo) + ')' } ]); root.insertBefore(g, null); title = tspan.parse(name); title.unshift( 'text', { x: lane.tgo, y: lane.ym, class: 'info', 'text-anchor': 'end' } ); title = jsonmlParse(title); title.setAttributeNS(w3.xmlns, 'xml:space', 'preserve'); g.insertBefore(title, null); // scale = lane.xs * (lane.hscale) * 2; glengths.push(title.getBBox().width); xoffset = content[j][0][1]; xoffset = (xoffset > 0) ? (Math.ceil(2 * xoffset) - 2 * xoffset) : (-2 * xoffset); gg = jsonmlParse(['g', { id: 'wavelane_draw_' + j + '_' + index, transform: 'translate(' + (xoffset * lane.xs) + ', 0)' } ]); g.insertBefore(gg, null); if (content[j][1]) { for (i = 0; i < content[j][1].length; i += 1) { b = document.createElementNS(w3.svg, 'use'); // b.id = 'use_' + i + '_' + j + '_' + index; b.setAttributeNS(w3.xlink, 'xlink:href', '#' + content[j][1][i]); // b.setAttribute('transform', 'translate(' + (i * lane.xs) + ')'); b.setAttribute('transform', 'translate(' + (i * lane.xs) + ')'); gg.insertBefore(b, null); } if (content[j][2] && content[j][2].length) { labels = findLaneMarkers(content[j][1]); if (labels.length !== 0) { for (k in labels) { if (content[j][2] && (typeof content[j][2][k] !== 'undefined')) { title = tspan.parse(content[j][2][k]); title.unshift( 'text', { x: labels[k] * lane.xs + lane.xlabel, y: lane.ym, 'text-anchor': 'middle' } ); title = jsonmlParse(title); title.setAttributeNS(w3.xmlns, 'xml:space', 'preserve'); gg.insertBefore(title, null); } } } } if (content[j][1].length > xmax) { xmax = content[j][1].length; } } } } lane.xmax = xmax; lane.xg = xgmax + 20; return glengths; } module.exports = renderWaveLane; /* eslint-env browser */ },{"./create-element":2,"./find-lane-markers":5,"./w3":30,"tspan":34}],30:[function(require,module,exports){ 'use strict'; module.exports = { svg: 'http://www.w3.org/2000/svg', xlink: 'http://www.w3.org/1999/xlink', xmlns: 'http://www.w3.org/XML/1998/namespace' }; },{}],31:[function(require,module,exports){ 'use strict'; window.WaveDrom = window.WaveDrom || {}; var index = require('./'); window.WaveDrom.ProcessAll = index.processAll; window.WaveDrom.RenderWaveForm = index.renderWaveForm; window.WaveDrom.EditorRefresh = index.editorRefresh; /* eslint-env browser */ },{"./":9}],32:[function(require,module,exports){ 'use strict'; module.exports = window.WaveSkin; /* eslint-env browser */ },{}],33:[function(require,module,exports){ 'use strict'; function isObject (o) { return o && Object.prototype.toString.call(o) === '[object Object]'; } function indent (txt) { var arr, res = []; if (typeof txt !== 'string') { return txt; } arr = txt.split('\n'); if (arr.length === 1) { return ' ' + txt; } arr.forEach(function (e) { if (e.trim() === '') { res.push(e); return; } res.push(' ' + e); }); return res.join('\n'); } function clean (txt) { var arr = txt.split('\n'); var res = []; arr.forEach(function (e) { if (e.trim() === '') { return; } res.push(e); }); return res.join('\n'); } function stringify (a) { var res, body, isEmpty, isFlat; body = ''; isFlat = true; isEmpty = a.some(function (e, i, arr) { if (i === 0) { res = '<' + e; if (arr.length === 1) { return true; } return; } if (i === 1) { if (isObject(e)) { Object.keys(e).forEach(function (key) { res += ' ' + key + '="' + e[key] + '"'; }); if (arr.length === 2) { return true; } res += '>'; return; } else { res += '>'; } } switch (typeof e) { case 'string': case 'number': case 'boolean': body += e + '\n'; return; } isFlat = false; body += stringify(e); }); if (isEmpty) { return res + '/>\n'; // short form } else { if (isFlat) { return res + clean(body) + '</' + a[0] + '>\n'; } else { return res + '\n' + indent(body) + '</' + a[0] + '>\n'; } } } module.exports = stringify; },{}],34:[function(require,module,exports){ 'use strict'; var token = /<o>|<ins>|<s>|<sub>|<sup>|<b>|<i>|<tt>|<\/o>|<\/ins>|<\/s>|<\/sub>|<\/sup>|<\/b>|<\/i>|<\/tt>/; function update (s, cmd) { if (cmd.add) { cmd.add.split(';').forEach(function (e) { var arr = e.split(' '); s[arr[0]][arr[1]] = true; }); } if (cmd.del) { cmd.del.split(';').forEach(function (e) { var arr = e.split(' '); delete s[arr[0]][arr[1]]; }); } } var trans = { '<o>' : { add: 'text-decoration overline' }, '</o>' : { del: 'text-decoration overline' }, '<ins>' : { add: 'text-decoration underline' }, '</ins>' : { del: 'text-decoration underline' }, '<s>' : { add: 'text-decoration line-through' }, '</s>' : { del: 'text-decoration line-through' }, '<b>' : { add: 'font-weight bold' }, '</b>' : { del: 'font-weight bold' }, '<i>' : { add: 'font-style italic' }, '</i>' : { del: 'font-style italic' }, '<sub>' : { add: 'baseline-shift sub;font-size .7em' }, '</sub>' : { del: 'baseline-shift sub;font-size .7em' }, '<sup>' : { add: 'baseline-shift super;font-size .7em' }, '</sup>' : { del: 'baseline-shift super;font-size .7em' }, '<tt>' : { add: 'font-family monospace' }, '</tt>' : { del: 'font-family monospace' } }; function dump (s) { return Object.keys(s).reduce(function (pre, cur) { var keys = Object.keys(s[cur]); if (keys.length > 0) { pre[cur] = keys.join(' '); } return pre; }, {}); } function parse (str) { var state, res, i, m, a; if (str === undefined) { return []; } if (typeof str === 'number') { return [str + '']; } if (typeof str !== 'string') { return [str]; } res = []; state = { 'text-decoration': {}, 'font-weight': {}, 'font-style': {}, 'baseline-shift': {}, 'font-size': {}, 'font-family': {} }; while (true) { i = str.search(token); if (i === -1) { res.push(['tspan', dump(state), str]); return res; } if (i > 0) { a = str.slice(0, i); res.push(['tspan', dump(state), a]); } m = str.match(token)[0]; update(state, trans[m]); str = str.slice(i + m.length); if (str.length === 0) { return res; } } } exports.parse = parse; },{}]},{},[31]);
/*! * angular-datatables - v0.5.2 * https://github.com/l-lin/angular-datatables * License: MIT */ if (typeof module !== "undefined" && typeof exports !== "undefined" && module.exports === exports) { module.exports = 'datatables.fixedcolumns'; } (function (window, document, $, angular) { 'use strict'; // See https://datatables.net/extensions/fixedcolumns/ angular.module('datatables.fixedcolumns', ['datatables']) .config(dtFixedColumnsConfig); /* @ngInject */ function dtFixedColumnsConfig($provide) { $provide.decorator('DTOptionsBuilder', dtOptionsBuilderDecorator); function dtOptionsBuilderDecorator($delegate) { var newOptions = $delegate.newOptions; var fromSource = $delegate.fromSource; var fromFnPromise = $delegate.fromFnPromise; $delegate.newOptions = function() { return _decorateOptions(newOptions); }; $delegate.fromSource = function(ajax) { return _decorateOptions(fromSource, ajax); }; $delegate.fromFnPromise = function(fnPromise) { return _decorateOptions(fromFnPromise, fnPromise); }; return $delegate; function _decorateOptions(fn, params) { var options = fn(params); options.withFixedColumns = withFixedColumns; return options; /** * Add fixed columns support * @param fixedColumnsOptions the plugin options * @returns {DTOptions} the options */ function withFixedColumns(fixedColumnsOptions) { options.fixedColumns = true; if (fixedColumnsOptions) { options.fixedColumns = fixedColumnsOptions; } return options; } } } dtOptionsBuilderDecorator.$inject = ['$delegate']; } dtFixedColumnsConfig.$inject = ['$provide']; })(window, document, jQuery, angular);
export default function _asyncIterator(iterable) { var method; if (typeof Symbol !== "undefined") { if (Symbol.asyncIterator) { method = iterable[Symbol.asyncIterator]; if (method != null) return method.call(iterable); } if (Symbol.iterator) { method = iterable[Symbol.iterator]; if (method != null) return method.call(iterable); } } throw new TypeError("Object is not async iterable"); }
!function(t){t.datepick.regional.uk={monthNames:["Січень","Лютий","Березень","Квітень","Травень","Червень","Липень","Серпень","Вересень","Жовтень","Листопад","Грудень"],monthNamesShort:["Січ","Лют","Бер","Кві","Тра","Чер","Лип","Сер","Вер","Жов","Лис","Гру"],dayNames:["неділя","понеділок","вівторок","середа","четвер","п'ятниця","субота"],dayNamesShort:["нед","пнд","вів","срд","чтв","птн","сбт"],dayNamesMin:["Нд","Пн","Вт","Ср","Чт","Пт","Сб"],dateFormat:"dd/mm/yyyy",firstDay:1,renderer:t.datepick.defaultRenderer,prevText:"&#x3c;",prevStatus:"",prevJumpText:"&#x3c;&#x3c;",prevJumpStatus:"",nextText:"&#x3e;",nextStatus:"",nextJumpText:"&#x3e;&#x3e;",nextJumpStatus:"",currentText:"Сьогодні",currentStatus:"",todayText:"Сьогодні",todayStatus:"",clearText:"Очистити",clearStatus:"",closeText:"Закрити",closeStatus:"",yearStatus:"",monthStatus:"",weekText:"Не",weekStatus:"",dayStatus:"D, M d",defaultStatus:"",isRTL:!1},t.datepick.setDefaults(t.datepick.regional.uk)}(jQuery); //# sourceMappingURL=jquery.datepick-uk.min.js.map
/** @module ember @submodule ember-htmlbars */ import Stream from 'ember-metal/streams/stream'; import ProxyStream from 'ember-metal/streams/proxy-stream'; export default function bindLocal(env, scope, key, value) { var isExisting = scope.locals.hasOwnProperty(key); if (isExisting) { var existing = scope.locals[key]; if (existing !== value) { existing.setSource(value); } } else { var newValue = Stream.wrap(value, ProxyStream, key); scope.locals[key] = newValue; } }
/* * jQuery throttle / debounce - v1.0 - 3/6/2010 * http://benalman.com/projects/jquery-throttle-debounce-plugin/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */ (function(b,c){var $=b.jQuery||b.Cowboy||(b.Cowboy={}),a;$.throttle=a=function(e,f,j,i){var h,d=0;if(typeof f!=="boolean"){i=j;j=f;f=c}function g(){var l=+new Date(),n=this,k=arguments;function m(){j.apply(n,k)}if(i&&!h){m()}if(i===c&&l-d>e){d=l;m()}else{if(f!==true){h&&clearTimeout(h);h=setTimeout(i?function(){h=c}:m,e)}}}if($.guid){g.guid=j.guid=j.guid||$.guid++}return g};$.debounce=function(d,e,f){return f===c?a(d,e,false):a(d,f,e!==false)}})(this);
this is file 385
/** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } var resultSelector = args.pop(); if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } } function done (i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { values[i] = x; next(i); }, function(e) { observer.onError(e); }, function () { done(i); } )); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }, this); };
CKEDITOR.plugins.setLang("print","mn",{toolbar:"Хэвлэх"});
/*! * # Semantic UI 2.2.6 - Checkbox * http://github.com/semantic-org/semantic-ui/ * * * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ($, window, document, undefined) { "use strict"; window = (typeof window != 'undefined' && window.Math == Math) ? window : (typeof self != 'undefined' && self.Math == Math) ? self : Function('return this')() ; $.fn.checkbox = function(parameters) { var $allModules = $(this), moduleSelector = $allModules.selector || '', time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), returnedValue ; $allModules .each(function() { var settings = $.extend(true, {}, $.fn.checkbox.settings, parameters), className = settings.className, namespace = settings.namespace, selector = settings.selector, error = settings.error, eventNamespace = '.' + namespace, moduleNamespace = 'module-' + namespace, $module = $(this), $label = $(this).children(selector.label), $input = $(this).children(selector.input), input = $input[0], initialLoad = false, shortcutPressed = false, instance = $module.data(moduleNamespace), observer, element = this, module ; module = { initialize: function() { module.verbose('Initializing checkbox', settings); module.create.label(); module.bind.events(); module.set.tabbable(); module.hide.input(); module.observeChanges(); module.instantiate(); module.setup(); }, instantiate: function() { module.verbose('Storing instance of module', module); instance = module; $module .data(moduleNamespace, module) ; }, destroy: function() { module.verbose('Destroying module'); module.unbind.events(); module.show.input(); $module.removeData(moduleNamespace); }, fix: { reference: function() { if( $module.is(selector.input) ) { module.debug('Behavior called on <input> adjusting invoked element'); $module = $module.closest(selector.checkbox); module.refresh(); } } }, setup: function() { module.set.initialLoad(); if( module.is.indeterminate() ) { module.debug('Initial value is indeterminate'); module.indeterminate(); } else if( module.is.checked() ) { module.debug('Initial value is checked'); module.check(); } else { module.debug('Initial value is unchecked'); module.uncheck(); } module.remove.initialLoad(); }, refresh: function() { $label = $module.children(selector.label); $input = $module.children(selector.input); input = $input[0]; }, hide: { input: function() { module.verbose('Modifying <input> z-index to be unselectable'); $input.addClass(className.hidden); } }, show: { input: function() { module.verbose('Modifying <input> z-index to be selectable'); $input.removeClass(className.hidden); } }, observeChanges: function() { if('MutationObserver' in window) { observer = new MutationObserver(function(mutations) { module.debug('DOM tree modified, updating selector cache'); module.refresh(); }); observer.observe(element, { childList : true, subtree : true }); module.debug('Setting up mutation observer', observer); } }, attachEvents: function(selector, event) { var $element = $(selector) ; event = $.isFunction(module[event]) ? module[event] : module.toggle ; if($element.length > 0) { module.debug('Attaching checkbox events to element', selector, event); $element .on('click' + eventNamespace, event) ; } else { module.error(error.notFound); } }, event: { click: function(event) { var $target = $(event.target) ; if( $target.is(selector.input) ) { module.verbose('Using default check action on initialized checkbox'); return; } if( $target.is(selector.link) ) { module.debug('Clicking link inside checkbox, skipping toggle'); return; } module.toggle(); $input.focus(); event.preventDefault(); }, keydown: function(event) { var key = event.which, keyCode = { enter : 13, space : 32, escape : 27 } ; if(key == keyCode.escape) { module.verbose('Escape key pressed blurring field'); $input.blur(); shortcutPressed = true; } else if(!event.ctrlKey && ( key == keyCode.space || key == keyCode.enter) ) { module.verbose('Enter/space key pressed, toggling checkbox'); module.toggle(); shortcutPressed = true; } else { shortcutPressed = false; } }, keyup: function(event) { if(shortcutPressed) { event.preventDefault(); } } }, check: function() { if( !module.should.allowCheck() ) { return; } module.debug('Checking checkbox', $input); module.set.checked(); if( !module.should.ignoreCallbacks() ) { settings.onChecked.call(input); settings.onChange.call(input); } }, uncheck: function() { if( !module.should.allowUncheck() ) { return; } module.debug('Unchecking checkbox'); module.set.unchecked(); if( !module.should.ignoreCallbacks() ) { settings.onUnchecked.call(input); settings.onChange.call(input); } }, indeterminate: function() { if( module.should.allowIndeterminate() ) { module.debug('Checkbox is already indeterminate'); return; } module.debug('Making checkbox indeterminate'); module.set.indeterminate(); if( !module.should.ignoreCallbacks() ) { settings.onIndeterminate.call(input); settings.onChange.call(input); } }, determinate: function() { if( module.should.allowDeterminate() ) { module.debug('Checkbox is already determinate'); return; } module.debug('Making checkbox determinate'); module.set.determinate(); if( !module.should.ignoreCallbacks() ) { settings.onDeterminate.call(input); settings.onChange.call(input); } }, enable: function() { if( module.is.enabled() ) { module.debug('Checkbox is already enabled'); return; } module.debug('Enabling checkbox'); module.set.enabled(); settings.onEnable.call(input); // preserve legacy callbacks settings.onEnabled.call(input); }, disable: function() { if( module.is.disabled() ) { module.debug('Checkbox is already disabled'); return; } module.debug('Disabling checkbox'); module.set.disabled(); settings.onDisable.call(input); // preserve legacy callbacks settings.onDisabled.call(input); }, get: { radios: function() { var name = module.get.name() ; return $('input[name="' + name + '"]').closest(selector.checkbox); }, otherRadios: function() { return module.get.radios().not($module); }, name: function() { return $input.attr('name'); } }, is: { initialLoad: function() { return initialLoad; }, radio: function() { return ($input.hasClass(className.radio) || $input.attr('type') == 'radio'); }, indeterminate: function() { return $input.prop('indeterminate') !== undefined && $input.prop('indeterminate'); }, checked: function() { return $input.prop('checked') !== undefined && $input.prop('checked'); }, disabled: function() { return $input.prop('disabled') !== undefined && $input.prop('disabled'); }, enabled: function() { return !module.is.disabled(); }, determinate: function() { return !module.is.indeterminate(); }, unchecked: function() { return !module.is.checked(); } }, should: { allowCheck: function() { if(module.is.determinate() && module.is.checked() && !module.should.forceCallbacks() ) { module.debug('Should not allow check, checkbox is already checked'); return false; } if(settings.beforeChecked.apply(input) === false) { module.debug('Should not allow check, beforeChecked cancelled'); return false; } return true; }, allowUncheck: function() { if(module.is.determinate() && module.is.unchecked() && !module.should.forceCallbacks() ) { module.debug('Should not allow uncheck, checkbox is already unchecked'); return false; } if(settings.beforeUnchecked.apply(input) === false) { module.debug('Should not allow uncheck, beforeUnchecked cancelled'); return false; } return true; }, allowIndeterminate: function() { if(module.is.indeterminate() && !module.should.forceCallbacks() ) { module.debug('Should not allow indeterminate, checkbox is already indeterminate'); return false; } if(settings.beforeIndeterminate.apply(input) === false) { module.debug('Should not allow indeterminate, beforeIndeterminate cancelled'); return false; } return true; }, allowDeterminate: function() { if(module.is.determinate() && !module.should.forceCallbacks() ) { module.debug('Should not allow determinate, checkbox is already determinate'); return false; } if(settings.beforeDeterminate.apply(input) === false) { module.debug('Should not allow determinate, beforeDeterminate cancelled'); return false; } return true; }, forceCallbacks: function() { return (module.is.initialLoad() && settings.fireOnInit); }, ignoreCallbacks: function() { return (initialLoad && !settings.fireOnInit); } }, can: { change: function() { return !( $module.hasClass(className.disabled) || $module.hasClass(className.readOnly) || $input.prop('disabled') || $input.prop('readonly') ); }, uncheck: function() { return (typeof settings.uncheckable === 'boolean') ? settings.uncheckable : !module.is.radio() ; } }, set: { initialLoad: function() { initialLoad = true; }, checked: function() { module.verbose('Setting class to checked'); $module .removeClass(className.indeterminate) .addClass(className.checked) ; if( module.is.radio() ) { module.uncheckOthers(); } if(!module.is.indeterminate() && module.is.checked()) { module.debug('Input is already checked, skipping input property change'); return; } module.verbose('Setting state to checked', input); $input .prop('indeterminate', false) .prop('checked', true) ; module.trigger.change(); }, unchecked: function() { module.verbose('Removing checked class'); $module .removeClass(className.indeterminate) .removeClass(className.checked) ; if(!module.is.indeterminate() && module.is.unchecked() ) { module.debug('Input is already unchecked'); return; } module.debug('Setting state to unchecked'); $input .prop('indeterminate', false) .prop('checked', false) ; module.trigger.change(); }, indeterminate: function() { module.verbose('Setting class to indeterminate'); $module .addClass(className.indeterminate) ; if( module.is.indeterminate() ) { module.debug('Input is already indeterminate, skipping input property change'); return; } module.debug('Setting state to indeterminate'); $input .prop('indeterminate', true) ; module.trigger.change(); }, determinate: function() { module.verbose('Removing indeterminate class'); $module .removeClass(className.indeterminate) ; if( module.is.determinate() ) { module.debug('Input is already determinate, skipping input property change'); return; } module.debug('Setting state to determinate'); $input .prop('indeterminate', false) ; }, disabled: function() { module.verbose('Setting class to disabled'); $module .addClass(className.disabled) ; if( module.is.disabled() ) { module.debug('Input is already disabled, skipping input property change'); return; } module.debug('Setting state to disabled'); $input .prop('disabled', 'disabled') ; module.trigger.change(); }, enabled: function() { module.verbose('Removing disabled class'); $module.removeClass(className.disabled); if( module.is.enabled() ) { module.debug('Input is already enabled, skipping input property change'); return; } module.debug('Setting state to enabled'); $input .prop('disabled', false) ; module.trigger.change(); }, tabbable: function() { module.verbose('Adding tabindex to checkbox'); if( $input.attr('tabindex') === undefined) { $input.attr('tabindex', 0); } } }, remove: { initialLoad: function() { initialLoad = false; } }, trigger: { change: function() { var events = document.createEvent('HTMLEvents'), inputElement = $input[0] ; if(inputElement) { module.verbose('Triggering native change event'); events.initEvent('change', true, false); inputElement.dispatchEvent(events); } } }, create: { label: function() { if($input.prevAll(selector.label).length > 0) { $input.prev(selector.label).detach().insertAfter($input); module.debug('Moving existing label', $label); } else if( !module.has.label() ) { $label = $('<label>').insertAfter($input); module.debug('Creating label', $label); } } }, has: { label: function() { return ($label.length > 0); } }, bind: { events: function() { module.verbose('Attaching checkbox events'); $module .on('click' + eventNamespace, module.event.click) .on('keydown' + eventNamespace, selector.input, module.event.keydown) .on('keyup' + eventNamespace, selector.input, module.event.keyup) ; } }, unbind: { events: function() { module.debug('Removing events'); $module .off(eventNamespace) ; } }, uncheckOthers: function() { var $radios = module.get.otherRadios() ; module.debug('Unchecking other radios', $radios); $radios.removeClass(className.checked); }, toggle: function() { if( !module.can.change() ) { if(!module.is.radio()) { module.debug('Checkbox is read-only or disabled, ignoring toggle'); } return; } if( module.is.indeterminate() || module.is.unchecked() ) { module.debug('Currently unchecked'); module.check(); } else if( module.is.checked() && module.can.uncheck() ) { module.debug('Currently checked'); module.uncheck(); } }, setting: function(name, value) { module.debug('Changing setting', name, value); if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { if($.isPlainObject(settings[name])) { $.extend(true, settings[name], value); } else { settings[name] = value; } } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(!settings.silent && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(!settings.silent && settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { if(!settings.silent) { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); } }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { module.error(error.method, query); return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } }; if(methodInvoked) { if(instance === undefined) { module.initialize(); } module.invoke(query); } else { if(instance !== undefined) { instance.invoke('destroy'); } module.initialize(); } }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; $.fn.checkbox.settings = { name : 'Checkbox', namespace : 'checkbox', silent : false, debug : false, verbose : true, performance : true, // delegated event context uncheckable : 'auto', fireOnInit : false, onChange : function(){}, beforeChecked : function(){}, beforeUnchecked : function(){}, beforeDeterminate : function(){}, beforeIndeterminate : function(){}, onChecked : function(){}, onUnchecked : function(){}, onDeterminate : function() {}, onIndeterminate : function() {}, onEnable : function(){}, onDisable : function(){}, // preserve misspelled callbacks (will be removed in 3.0) onEnabled : function(){}, onDisabled : function(){}, className : { checked : 'checked', indeterminate : 'indeterminate', disabled : 'disabled', hidden : 'hidden', radio : 'radio', readOnly : 'read-only' }, error : { method : 'The method you called is not defined' }, selector : { checkbox : '.ui.checkbox', label : 'label, .box', input : 'input[type="checkbox"], input[type="radio"]', link : 'a[href]' } }; })( jQuery, window, document );
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } var Rx = { internals: {}, config: { Promise: root.Promise // Detect if promise exists }, helpers: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; }, identity = Rx.helpers.identity = function (x) { return x; }, pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, just = Rx.helpers.just = function (value) { return function () { return value; }; }, defaultNow = Rx.helpers.defaultNow = Date.now, defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, defaultError = Rx.helpers.defaultError = function (err) { throw err; }, isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function' && p.then !== Rx.Observable.prototype.then; }, asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, not = Rx.helpers.not = function (a) { return !a; }; // Errors var sequenceContainsNoElements = 'Sequence contains no elements.'; var argumentOutOfRange = 'Argument out of range'; var objectDisposed = 'Object has been disposed'; function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } // Shim in iterator support var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || '_es6shim_iterator_'; // Bug for mozilla version if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = { done: true, value: undefined }; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 suportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch(e) { suportNodeClass = true; } var shadowedProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.io/#x8 // and avoid a V8 bug // https://code.google.com/p/v8/issues/detail?id=2291 var type = typeof value; return value && (type == 'function' || type == 'object') || false; } function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = shadowedProps.length; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = shadowedProps[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } function isArguments(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } function isFunction(value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFunction(/x/)) { isFunction = function(value) { return typeof value == 'function' && toString.call(value) == funcClass; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (a == null || b == null || (type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) { return false; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b // but treat `-0` vs. `+0` as not equal : (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result) { // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly internalForIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB)); } }); if (result) { // ensure both objects have the same number of properties internalForIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } } stackA.pop(); stackB.pop(); return result; } var slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var hasProp = {}.hasOwnProperty; /** @private */ var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; /** @private */ var addProperties = Rx.internals.addProperties = function (obj) { var sources = slice.call(arguments, 1); for (var i = 0, len = sources.length; i < len; i++) { var source = sources[i]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; // Collection polyfills function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } // Collections var IndexedItem = function (id, value) { this.id = id; this.value = value; }; IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); if (c === 0) { c = this.id - other.id; } return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { if (index === undefined) { index = 0; } if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; delete this.items[this.length]; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { this.disposables = argsOrArray(arguments, 0); this.isDisposed = false; this.length = this.disposables.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. */ CompositeDisposablePrototype.clear = function () { var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } }; /** * Determines whether the CompositeDisposable contains a specific disposable. * @param {Mixed} item Disposable to search for. * @returns {Boolean} true if the disposable was found; otherwise, false. */ CompositeDisposablePrototype.contains = function (item) { return this.disposables.indexOf(item) !== -1; }; /** * Converts the existing CompositeDisposable to an array of disposables * @returns {Array} An array of disposable objects. */ CompositeDisposablePrototype.toArray = function () { return this.disposables.slice(0); }; /** * Provides a set of static methods for creating Disposables. * * @constructor * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; var BooleanDisposable = (function () { function BooleanDisposable (isSingle) { this.isSingle = isSingle; this.isDisposed = false; this.current = null; } var booleanDisposablePrototype = BooleanDisposable.prototype; /** * Gets the underlying disposable. * @return The underlying disposable. */ booleanDisposablePrototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ booleanDisposablePrototype.setDisposable = function (value) { if (this.current && this.isSingle) { throw new Error('Disposable has already been assigned'); } var shouldDispose = this.isDisposed, old; if (!shouldDispose) { old = this.current; this.current = value; } if (old) { old.dispose(); } if (shouldDispose && value) { value.dispose(); } }; /** * Disposes the underlying disposable as well as all future replacements. */ booleanDisposablePrototype.dispose = function () { var old; if (!this.isDisposed) { this.isDisposed = true; old = this.current; this.current = null; } if (old) { old.dispose(); } }; return BooleanDisposable; }()); /** * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. */ var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) { inherits(SingleAssignmentDisposable, super_); function SingleAssignmentDisposable() { super_.call(this, true); } return SingleAssignmentDisposable; }(BooleanDisposable)); /** * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. */ var SerialDisposable = Rx.SerialDisposable = (function (super_) { inherits(SerialDisposable, super_); function SerialDisposable() { super_.call(this, false); } return SerialDisposable; }(BooleanDisposable)); /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed) { if (!this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed) { if (!this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } ScheduledDisposable.prototype.dispose = function () { var parent = this; this.scheduler.schedule(function () { if (!parent.isDisposed) { parent.isDisposed = true; parent.disposable.dispose(); } }); }; var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { /** * @constructor * @private */ function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function invokeRecImmediate(scheduler, pair) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. */ schedulerProto.catchException = schedulerProto['catch'] = function (handler) { return new CatchScheduler(this, handler); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ schedulerProto.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, function () { action(); }); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ schedulerProto.schedulePeriodicWithState = function (state, period, action) { var s = state, id = setInterval(function () { s = action(s); }, period); return disposableCreate(function () { clearInterval(id); }); }; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, function (_action, self) { _action(function () { self(_action); }); }); }; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState({ first: state, second: action }, function (s, p) { return invokeRecImmediate(s, p); }); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { if (timeSpan < 0) { timeSpan = 0; } return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize; var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); /** * Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } function scheduleRelative(state, dueTime, action) { var dt = normalizeTime(dt); while (dt - this.now() > 0) { } return action(this, state); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline (q) { var item; while (q.length > 0) { item = q.dequeue(); if (!item.isCancelled()) { // Note, do not schedule blocking work! while (item.dueTime - Scheduler.now() > 0) { } if (!item.isCancelled()) { item.invoke(); } } } } function scheduleNow(state, action) { return this.scheduleWithRelativeAndState(state, 0, action); } function scheduleRelative(state, dueTime, action) { var dt = this.now() + Scheduler.normalize(dueTime), si = new ScheduledItem(this, state, action, dt), t; if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); try { runTrampoline(queue); } catch (e) { throw e; } finally { queue = null; } } else { queue.enqueue(si); } return si.disposable; } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); currentScheduler.scheduleRequired = function () { return queue === null; }; currentScheduler.ensureTrampoline = function (action) { if (queue === null) { return this.schedule(action); } else { return action(); } }; return currentScheduler; }()); var scheduleMethod, clearMethod = noop; (function () { var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate, clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && !reNative.test(clearImmediate) && clearImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('','*'); root.onmessage = oldHandler; return isAsync; } // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } else if (typeof setImmediate === 'function') { scheduleMethod = setImmediate; clearMethod = clearImmediate; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), tasks = {}, taskId = 0; function onGlobalPostMessage(event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { var handleId = event.data.substring(MSG_PREFIX.length), action = tasks[handleId]; action(); delete tasks[handleId]; } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else { root.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var currentId = taskId++; tasks[currentId] = action; root.postMessage(MSG_PREFIX + currentId, '*'); }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(), channelTasks = {}, channelTaskId = 0; channel.port1.onmessage = function (event) { var id = event.data, action = channelTasks[id]; action(); delete channelTasks[id]; }; scheduleMethod = function (action) { var id = channelTaskId++; channelTasks[id] = action; channel.port2.postMessage(id); }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); scriptElement.onreadystatechange = function () { action(); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); }; } else { scheduleMethod = function (action) { return setTimeout(action, 0); }; clearMethod = clearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = setTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { clearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** @private */ var CatchScheduler = (function (_super) { function localNow() { return this._scheduler.now(); } function scheduleNow(state, action) { return this._scheduler.scheduleWithState(state, this._wrap(action)); } function scheduleRelative(state, dueTime, action) { return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); } function scheduleAbsolute(state, dueTime, action) { return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); } inherits(CatchScheduler, _super); /** @private */ function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } /** @private */ CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; /** @private */ CatchScheduler.prototype._wrap = function (action) { var parent = this; return function (self, state) { try { return action(parent._getRecursiveWrapper(self), state); } catch (e) { if (!parent._handler(e)) { throw e; } return disposableEmpty; } }; }; /** @private */ CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { if (this._recursiveOriginal !== scheduler) { this._recursiveOriginal = scheduler; var wrapper = this._clone(scheduler); wrapper._recursiveOriginal = scheduler; wrapper._recursiveWrapper = wrapper; this._recursiveWrapper = wrapper; } return this._recursiveWrapper; }; /** @private */ CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { var self = this, failed = false, d = new SingleAssignmentDisposable(); d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { if (failed) { return null; } try { return action(state1); } catch (e) { failed = true; if (!self._handler(e)) { throw e; } d.dispose(); return null; } })); return d; }; return CatchScheduler; }(Scheduler)); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, hasValue) { this.hasValue = hasValue == null ? false : hasValue; this.kind = kind; } /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { return observerOrOnNext && typeof observerOrOnNext === 'object' ? this._acceptObservable(observerOrOnNext) : this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notifications * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ Notification.prototype.toObservable = function (scheduler) { var notification = this; isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { notification._acceptObservable(observer); notification.kind === 'N' && observer.onCompleted(); }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept (onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString () { return 'OnNext(' + this.value + ')'; } return function (value) { var notification = new Notification('N', true); notification.value = value; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (exception) { var notification = new Notification('E'); notification.exception = exception; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { var notification = new Notification('C'); notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); var Enumerator = Rx.internals.Enumerator = function (next) { this._next = next; }; Enumerator.prototype.next = function () { return this._next(); }; Enumerator.prototype[$iterator$] = function () { return this; } var Enumerable = Rx.internals.Enumerable = function (iterator) { this._iterator = iterator; }; Enumerable.prototype[$iterator$] = function () { return this._iterator(); }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var currentItem; if (isDisposed) { return; } try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { observer.onCompleted(); return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { self(); }) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchException = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } var currentItem; try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { if (lastException) { observer.onError(lastException); } else { observer.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), function (exn) { lastException = exn; self(); }, observer.onCompleted.bind(observer))); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount == null) { repeatCount = -1; } return new Enumerable(function () { var left = repeatCount; return new Enumerator(function () { if (left === 0) { return doneEnumerator; } if (left > 0) { left--; } return { done: false, value: value }; }); }); }; var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { selector || (selector = identity); return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: selector.call(thisArg, source[index], index, source) } : doneEnumerator; }); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * * @param observer Observer object. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. * If a violation is detected, an Error is thrown from the offending observer method call. * * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. */ Observer.prototype.checked = function () { return new CheckedObserver(this); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * * @static * @memberOf Observer * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * * @static * @memberOf Observer * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler) { return new AnonymousObserver(function (x) { return handler(notificationCreateOnNext(x)); }, function (exception) { return handler(notificationCreateOnError(exception)); }, function () { return handler(notificationCreateOnCompleted()); }); }; /** * Schedules the invocation of observer methods on the given scheduler. * @param {Scheduler} scheduler Scheduler to schedule observer messages on. * @returns {Observer} Observer whose messages are scheduled on the given scheduler. */ Observer.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { inherits(AbstractObserver, _super); /** * Creates a new observer in a non-stopped state. * * @constructor */ function AbstractObserver() { this.isStopped = false; _super.call(this); } /** * Notifies the observer of a new element in the sequence. * * @memberOf AbstractObserver * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * * @memberOf AbstractObserver * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { inherits(AnonymousObserver, _super); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { _super.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (exception) { this._onError(exception); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var CheckedObserver = (function (_super) { inherits(CheckedObserver, _super); function CheckedObserver(observer) { _super.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); try { this._observer.onNext(value); } catch (e) { throw e; } finally { this._state = 0; } }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); try { this._observer.onError(err); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); try { this._observer.onCompleted(); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) { inherits(ScheduledObserver, _super); function ScheduledObserver(scheduler, observer) { _super.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (exception) { var self = this; this.queue.push(function () { self.observer.onError(exception); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { _super.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); /** @private */ var ObserveOnObserver = (function (_super) { inherits(ObserveOnObserver, _super); /** @private */ function ObserveOnObserver() { _super.apply(this, arguments); } /** @private */ ObserveOnObserver.prototype.next = function (value) { _super.prototype.next.call(this, value); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.error = function (e) { _super.prototype.error.call(this, e); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.completed = function () { _super.prototype.completed.call(this); this.ensureActive(); }; return ObserveOnObserver; })(ScheduledObserver); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { this._subscribe = subscribe; } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * * @example * 1 - source.subscribe(); * 2 - source.subscribe(observer); * 3 - source.subscribe(function (x) { console.log(x); }); * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { var subscriber = typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted); return this._subscribe(subscriber); }; return Observable; })(); var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { if (typeof subscriber === 'undefined') { subscriber = disposableEmpty; } else if (typeof subscriber === 'function') { subscriber = disposableCreate(subscriber); } return subscriber; } function AnonymousObservable(subscribe) { if (!(this instanceof AnonymousObservable)) { return new AnonymousObservable(subscribe); } function s(observer) { var setDisposable = function () { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } }; var autoDetachObserver = new AutoDetachObserver(observer); if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(setDisposable); } else { setDisposable(); } return autoDetachObserver; } __super__.call(this, s); } return AnonymousObservable; }(Observable)); /** @private */ var AutoDetachObserver = (function (_super) { inherits(AutoDetachObserver, _super); function AutoDetachObserver(observer) { _super.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var noError = false; try { this.observer.onNext(value); noError = true; } catch (e) { throw e; } finally { if (!noError) { this.dispose(); } } }; AutoDetachObserverPrototype.error = function (exn) { try { this.observer.onError(exn); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.completed = function () { try { this.observer.onCompleted(); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; /* @private */ AutoDetachObserverPrototype.disposable = function (value) { return arguments.length ? this.getDisposable() : setDisposable(value); }; AutoDetachObserverPrototype.dispose = function () { _super.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); /** @private */ var GroupedObservable = (function (_super) { inherits(GroupedObservable, _super); function subscribe(observer) { return this.underlyingObservable.subscribe(observer); } /** * @constructor * @private */ function GroupedObservable(key, underlyingObservable, mergedDisposable) { _super.call(this, subscribe); this.key = key; this.underlyingObservable = !mergedDisposable ? underlyingObservable : new AnonymousObservable(function (observer) { return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); }); } return GroupedObservable; }(Observable)); /** @private */ var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; /** * @private * @memberOf InnerSubscription */ InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.exception) { observer.onError(this.exception); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, _super); /** * Creates a subject. * @constructor */ function Subject() { _super.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; } addProperties(Subject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } var ex = this.exception, hv = this.hasValue, v = this.value; if (ex) { observer.onError(ex); } else if (hv) { observer.onNext(v); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, _super); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { _super.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.value = null; this.hasValue = false; this.observers = []; this.exception = null; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed.call(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var o, i, len; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var os = this.observers.slice(0), v = this.value, hv = this.hasValue; if (hv) { for (i = 0, len = os.length; i < len; i++) { o = os[i]; o.onNext(v); o.onCompleted(); } } else { for (i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { this.value = value; this.hasValue = true; } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); /** @private */ var AnonymousSubject = (function (_super) { inherits(AnonymousSubject, _super); function subscribe(observer) { return this.observable.subscribe(observer); } /** * @private * @constructor */ function AnonymousSubject(observer, observable) { _super.call(this, subscribe); this.observer = observer; this.observable = observable; } addProperties(AnonymousSubject.prototype, Observer, { /** * @private * @memberOf AnonymousSubject# */ onCompleted: function () { this.observer.onCompleted(); }, /** * @private * @memberOf AnonymousSubject# */ onError: function (exception) { this.observer.onError(exception); }, /** * @private * @memberOf AnonymousSubject# */ onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } }.call(this));
Plotly.register({moduleType:"locale",name:"gl",dictionary:{},format:{days:["Domingo","Luns","Martes","M\xe9rcores","Xoves","Venres","S\xe1bado"],shortDays:["Dom","Lun","Mar","M\xe9r","Xov","Ven","S\xe1b"],months:["Xaneiro","Febreiro","Marzo","Abril","Maio","Xu\xf1o","Xullo","Agosto","Setembro","Outubro","Novembro","Decembro"],shortMonths:["Xan","Feb","Mar","Abr","Mai","Xu\xf1","Xul","Ago","Set","Out","Nov","Dec"],date:"%d/%m/%Y"}});
/** * @license Highcharts JS v4.0.0 (2014-04-22) * Exporting module * * (c) 2010-2014 Torstein Honsi * * License: www.highcharts.com/license */ // JSLint options: /*global Highcharts, document, window, Math, setTimeout */ (function (Highcharts) { // encapsulate // create shortcuts var Chart = Highcharts.Chart, addEvent = Highcharts.addEvent, removeEvent = Highcharts.removeEvent, createElement = Highcharts.createElement, discardElement = Highcharts.discardElement, css = Highcharts.css, merge = Highcharts.merge, each = Highcharts.each, extend = Highcharts.extend, math = Math, mathMax = math.max, doc = document, win = window, isTouchDevice = Highcharts.isTouchDevice, M = 'M', L = 'L', DIV = 'div', HIDDEN = 'hidden', NONE = 'none', PREFIX = 'highcharts-', ABSOLUTE = 'absolute', PX = 'px', UNDEFINED, symbols = Highcharts.Renderer.prototype.symbols, defaultOptions = Highcharts.getOptions(), buttonOffset; // Add language extend(defaultOptions.lang, { printChart: 'Print chart', downloadPNG: 'Download PNG image', downloadJPEG: 'Download JPEG image', downloadPDF: 'Download PDF document', downloadSVG: 'Download SVG vector image', contextButtonTitle: 'Chart context menu' }); // Buttons and menus are collected in a separate config option set called 'navigation'. // This can be extended later to add control buttons like zoom and pan right click menus. defaultOptions.navigation = { menuStyle: { border: '1px solid #A0A0A0', background: '#FFFFFF', padding: '5px 0' }, menuItemStyle: { padding: '0 10px', background: NONE, color: '#303030', fontSize: isTouchDevice ? '14px' : '11px' }, menuItemHoverStyle: { background: '#4572A5', color: '#FFFFFF' }, buttonOptions: { symbolFill: '#E0E0E0', symbolSize: 14, symbolStroke: '#666', symbolStrokeWidth: 3, symbolX: 12.5, symbolY: 10.5, align: 'right', buttonSpacing: 3, height: 22, // text: null, theme: { fill: 'white', // capture hover stroke: 'none' }, verticalAlign: 'top', width: 24 } }; // Add the export related options defaultOptions.exporting = { //enabled: true, //filename: 'chart', type: 'image/png', url: 'http://export.highcharts.com/', //width: undefined, //scale: 2 buttons: { contextButton: { menuClassName: PREFIX + 'contextmenu', //x: -10, symbol: 'menu', _titleKey: 'contextButtonTitle', menuItems: [{ textKey: 'printChart', onclick: function () { this.print(); } }, { separator: true }, { textKey: 'downloadPNG', onclick: function () { this.exportChart(); } }, { textKey: 'downloadJPEG', onclick: function () { this.exportChart({ type: 'image/jpeg' }); } }, { textKey: 'downloadPDF', onclick: function () { this.exportChart({ type: 'application/pdf' }); } }, { textKey: 'downloadSVG', onclick: function () { this.exportChart({ type: 'image/svg+xml' }); } } // Enable this block to add "View SVG" to the dropdown menu /* ,{ text: 'View SVG', onclick: function () { var svg = this.getSVG() .replace(/</g, '\n&lt;') .replace(/>/g, '&gt;'); doc.body.innerHTML = '<pre>' + svg + '</pre>'; } } // */ ] } } }; // Add the Highcharts.post utility Highcharts.post = function (url, data, formAttributes) { var name, form; // create the form form = createElement('form', merge({ method: 'post', action: url, enctype: 'multipart/form-data' }, formAttributes), { display: NONE }, doc.body); // add the data for (name in data) { createElement('input', { type: HIDDEN, name: name, value: data[name] }, null, form); } // submit form.submit(); // clean up discardElement(form); }; extend(Chart.prototype, { /** * Return an SVG representation of the chart * * @param additionalOptions {Object} Additional chart options for the generated SVG representation */ getSVG: function (additionalOptions) { var chart = this, chartCopy, sandbox, svg, seriesOptions, sourceWidth, sourceHeight, cssWidth, cssHeight, options = merge(chart.options, additionalOptions); // copy the options and add extra options // IE compatibility hack for generating SVG content that it doesn't really understand if (!doc.createElementNS) { /*jslint unparam: true*//* allow unused parameter ns in function below */ doc.createElementNS = function (ns, tagName) { return doc.createElement(tagName); }; /*jslint unparam: false*/ } // create a sandbox where a new chart will be generated sandbox = createElement(DIV, null, { position: ABSOLUTE, top: '-9999em', width: chart.chartWidth + PX, height: chart.chartHeight + PX }, doc.body); // get the source size cssWidth = chart.renderTo.style.width; cssHeight = chart.renderTo.style.height; sourceWidth = options.exporting.sourceWidth || options.chart.width || (/px$/.test(cssWidth) && parseInt(cssWidth, 10)) || 600; sourceHeight = options.exporting.sourceHeight || options.chart.height || (/px$/.test(cssHeight) && parseInt(cssHeight, 10)) || 400; // override some options extend(options.chart, { animation: false, renderTo: sandbox, forExport: true, width: sourceWidth, height: sourceHeight }); options.exporting.enabled = false; // hide buttons in print // prepare for replicating the chart options.series = []; each(chart.series, function (serie) { seriesOptions = merge(serie.options, { animation: false, // turn off animation showCheckbox: false, visible: serie.visible }); if (!seriesOptions.isInternal) { // used for the navigator series that has its own option set options.series.push(seriesOptions); } }); // generate the chart copy chartCopy = new Highcharts.Chart(options, chart.callback); // reflect axis extremes in the export each(['xAxis', 'yAxis'], function (axisType) { each(chart[axisType], function (axis, i) { var axisCopy = chartCopy[axisType][i], extremes = axis.getExtremes(), userMin = extremes.userMin, userMax = extremes.userMax; if (axisCopy && (userMin !== UNDEFINED || userMax !== UNDEFINED)) { axisCopy.setExtremes(userMin, userMax, true, false); } }); }); // get the SVG from the container's innerHTML svg = chartCopy.container.innerHTML; // free up memory options = null; chartCopy.destroy(); discardElement(sandbox); // sanitize svg = svg .replace(/zIndex="[^"]+"/g, '') .replace(/isShadow="[^"]+"/g, '') .replace(/symbolName="[^"]+"/g, '') .replace(/jQuery[0-9]+="[^"]+"/g, '') .replace(/url\([^#]+#/g, 'url(#') .replace(/<svg /, '<svg xmlns:xlink="http://www.w3.org/1999/xlink" ') .replace(/ href=/g, ' xlink:href=') .replace(/\n/, ' ') .replace(/<\/svg>.*?$/, '</svg>') // any HTML added to the container after the SVG (#894) /* This fails in IE < 8 .replace(/([0-9]+)\.([0-9]+)/g, function(s1, s2, s3) { // round off to save weight return s2 +'.'+ s3[0]; })*/ // Replace HTML entities, issue #347 .replace(/&nbsp;/g, '\u00A0') // no-break space .replace(/&shy;/g, '\u00AD') // soft hyphen // IE specific .replace(/<IMG /g, '<image ') .replace(/height=([^" ]+)/g, 'height="$1"') .replace(/width=([^" ]+)/g, 'width="$1"') .replace(/hc-svg-href="([^"]+)">/g, 'xlink:href="$1"/>') .replace(/id=([^" >]+)/g, 'id="$1"') .replace(/class=([^" >]+)/g, 'class="$1"') .replace(/ transform /g, ' ') .replace(/:(path|rect)/g, '$1') .replace(/style="([^"]+)"/g, function (s) { return s.toLowerCase(); }); // IE9 beta bugs with innerHTML. Test again with final IE9. svg = svg.replace(/(url\(#highcharts-[0-9]+)&quot;/g, '$1') .replace(/&quot;/g, "'"); return svg; }, /** * Submit the SVG representation of the chart to the server * @param {Object} options Exporting options. Possible members are url, type, width and formAttributes. * @param {Object} chartOptions Additional chart options for the SVG representation of the chart */ exportChart: function (options, chartOptions) { options = options || {}; var chart = this, chartExportingOptions = chart.options.exporting, svg = chart.getSVG(merge( { chart: { borderRadius: 0 } }, chartExportingOptions.chartOptions, chartOptions, { exporting: { sourceWidth: options.sourceWidth || chartExportingOptions.sourceWidth, sourceHeight: options.sourceHeight || chartExportingOptions.sourceHeight } } )); // merge the options options = merge(chart.options.exporting, options); // do the post Highcharts.post(options.url, { filename: options.filename || 'chart', type: options.type, width: options.width || 0, // IE8 fails to post undefined correctly, so use 0 scale: options.scale || 2, svg: svg }, options.formAttributes); }, /** * Print the chart */ print: function () { var chart = this, container = chart.container, origDisplay = [], origParent = container.parentNode, body = doc.body, childNodes = body.childNodes; if (chart.isPrinting) { // block the button while in printing mode return; } chart.isPrinting = true; // hide all body content each(childNodes, function (node, i) { if (node.nodeType === 1) { origDisplay[i] = node.style.display; node.style.display = NONE; } }); // pull out the chart body.appendChild(container); // print win.focus(); // #1510 win.print(); // allow the browser to prepare before reverting setTimeout(function () { // put the chart back in origParent.appendChild(container); // restore all body content each(childNodes, function (node, i) { if (node.nodeType === 1) { node.style.display = origDisplay[i]; } }); chart.isPrinting = false; }, 1000); }, /** * Display a popup menu for choosing the export type * * @param {String} className An identifier for the menu * @param {Array} items A collection with text and onclicks for the items * @param {Number} x The x position of the opener button * @param {Number} y The y position of the opener button * @param {Number} width The width of the opener button * @param {Number} height The height of the opener button */ contextMenu: function (className, items, x, y, width, height, button) { var chart = this, navOptions = chart.options.navigation, menuItemStyle = navOptions.menuItemStyle, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, cacheName = 'cache-' + className, menu = chart[cacheName], menuPadding = mathMax(width, height), // for mouse leave detection boxShadow = '3px 3px 10px #888', innerMenu, hide, hideTimer, menuStyle, docMouseUpHandler = function (e) { if (!chart.pointer.inClass(e.target, className)) { hide(); } }; // create the menu only the first time if (!menu) { // create a HTML element above the SVG chart[cacheName] = menu = createElement(DIV, { className: className }, { position: ABSOLUTE, zIndex: 1000, padding: menuPadding + PX }, chart.container); innerMenu = createElement(DIV, null, extend({ MozBoxShadow: boxShadow, WebkitBoxShadow: boxShadow, boxShadow: boxShadow }, navOptions.menuStyle), menu); // hide on mouse out hide = function () { css(menu, { display: NONE }); if (button) { button.setState(0); } chart.openMenu = false; }; // Hide the menu some time after mouse leave (#1357) addEvent(menu, 'mouseleave', function () { hideTimer = setTimeout(hide, 500); }); addEvent(menu, 'mouseenter', function () { clearTimeout(hideTimer); }); // Hide it on clicking or touching outside the menu (#2258, #2335, #2407) addEvent(document, 'mouseup', docMouseUpHandler); addEvent(chart, 'destroy', function () { removeEvent(document, 'mouseup', docMouseUpHandler); }); // create the items each(items, function (item) { if (item) { var element = item.separator ? createElement('hr', null, null, innerMenu) : createElement(DIV, { onmouseover: function () { css(this, navOptions.menuItemHoverStyle); }, onmouseout: function () { css(this, menuItemStyle); }, onclick: function () { hide(); item.onclick.apply(chart, arguments); }, innerHTML: item.text || chart.options.lang[item.textKey] }, extend({ cursor: 'pointer' }, menuItemStyle), innerMenu); // Keep references to menu divs to be able to destroy them chart.exportDivElements.push(element); } }); // Keep references to menu and innerMenu div to be able to destroy them chart.exportDivElements.push(innerMenu, menu); chart.exportMenuWidth = menu.offsetWidth; chart.exportMenuHeight = menu.offsetHeight; } menuStyle = { display: 'block' }; // if outside right, right align it if (x + chart.exportMenuWidth > chartWidth) { menuStyle.right = (chartWidth - x - width - menuPadding) + PX; } else { menuStyle.left = (x - menuPadding) + PX; } // if outside bottom, bottom align it if (y + height + chart.exportMenuHeight > chartHeight && button.alignOptions.verticalAlign !== 'top') { menuStyle.bottom = (chartHeight - y - menuPadding) + PX; } else { menuStyle.top = (y + height - menuPadding) + PX; } css(menu, menuStyle); chart.openMenu = true; }, /** * Add the export button to the chart */ addButton: function (options) { var chart = this, renderer = chart.renderer, btnOptions = merge(chart.options.navigation.buttonOptions, options), onclick = btnOptions.onclick, menuItems = btnOptions.menuItems, symbol, button, symbolAttr = { stroke: btnOptions.symbolStroke, fill: btnOptions.symbolFill }, symbolSize = btnOptions.symbolSize || 12; if (!chart.btnCount) { chart.btnCount = 0; } // Keeps references to the button elements if (!chart.exportDivElements) { chart.exportDivElements = []; chart.exportSVGElements = []; } if (btnOptions.enabled === false) { return; } var attr = btnOptions.theme, states = attr.states, hover = states && states.hover, select = states && states.select, callback; delete attr.states; if (onclick) { callback = function () { onclick.apply(chart, arguments); }; } else if (menuItems) { callback = function () { chart.contextMenu( button.menuClassName, menuItems, button.translateX, button.translateY, button.width, button.height, button ); button.setState(2); }; } if (btnOptions.text && btnOptions.symbol) { attr.paddingLeft = Highcharts.pick(attr.paddingLeft, 25); } else if (!btnOptions.text) { extend(attr, { width: btnOptions.width, height: btnOptions.height, padding: 0 }); } button = renderer.button(btnOptions.text, 0, 0, callback, attr, hover, select) .attr({ title: chart.options.lang[btnOptions._titleKey], 'stroke-linecap': 'round' }); button.menuClassName = options.menuClassName || PREFIX + 'menu-' + chart.btnCount++; if (btnOptions.symbol) { symbol = renderer.symbol( btnOptions.symbol, btnOptions.symbolX - (symbolSize / 2), btnOptions.symbolY - (symbolSize / 2), symbolSize, symbolSize ) .attr(extend(symbolAttr, { 'stroke-width': btnOptions.symbolStrokeWidth || 1, zIndex: 1 })).add(button); } button.add() .align(extend(btnOptions, { width: button.width, x: Highcharts.pick(btnOptions.x, buttonOffset) // #1654 }), true, 'spacingBox'); buttonOffset += (button.width + btnOptions.buttonSpacing) * (btnOptions.align === 'right' ? -1 : 1); chart.exportSVGElements.push(button, symbol); }, /** * Destroy the buttons. */ destroyExport: function (e) { var chart = e.target, i, elem; // Destroy the extra buttons added for (i = 0; i < chart.exportSVGElements.length; i++) { elem = chart.exportSVGElements[i]; // Destroy and null the svg/vml elements if (elem) { // #1822 elem.onclick = elem.ontouchstart = null; chart.exportSVGElements[i] = elem.destroy(); } } // Destroy the divs for the menu for (i = 0; i < chart.exportDivElements.length; i++) { elem = chart.exportDivElements[i]; // Remove the event handler removeEvent(elem, 'mouseleave'); // Remove inline events chart.exportDivElements[i] = elem.onmouseout = elem.onmouseover = elem.ontouchstart = elem.onclick = null; // Destroy the div by moving to garbage bin discardElement(elem); } } }); symbols.menu = function (x, y, width, height) { var arr = [ M, x, y + 2.5, L, x + width, y + 2.5, M, x, y + height / 2 + 0.5, L, x + width, y + height / 2 + 0.5, M, x, y + height - 1.5, L, x + width, y + height - 1.5 ]; return arr; }; // Add the buttons on chart load Chart.prototype.callbacks.push(function (chart) { var n, exportingOptions = chart.options.exporting, buttons = exportingOptions.buttons; buttonOffset = 0; if (exportingOptions.enabled !== false) { for (n in buttons) { chart.addButton(buttons[n]); } // Destroy the export elements at chart destroy addEvent(chart, 'destroy', chart.destroyExport); } }); }(Highcharts));
YUI.add("lang/datatype-date-format_ro-RO",function(e){e.Intl.add("datatype-date-format","ro-RO",{a:["Du","Lu","Ma","Mi","Jo","Vi","Sâ"],A:["duminică","luni","marți","miercuri","joi","vineri","sâmbătă"],b:["ian.","feb.","mar.","apr.","mai","iun.","iul.","aug.","sept.","oct.","nov.","dec."],B:["ianuarie","februarie","martie","aprilie","mai","iunie","iulie","august","septembrie","octombrie","noiembrie","decembrie"],c:"%a, %d %b %Y, %H:%M:%S %Z",p:["AM","PM"],P:["am","pm"],x:"%d.%m.%Y",X:"%H:%M:%S"})},"@VERSION@")
/*! * jQuery Lazy - v0.3.6 * http://jquery.eisbehr.de/lazy/ * http://eisbehr.de * * Copyright 2014, Daniel 'Eisbehr' Kern * * Dual licensed under the MIT and GPL-2.0 licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl-2.0.html * * jQuery("img.lazy").lazy(); */ (function($, window, document, undefined) { $.fn.lazy = function(settings) { "use strict"; /** * settings and configuration data * @access private * @type {*} */ var _configuration = { // general bind : "load", threshold : 500, fallbackWidth : 2000, fallbackHeight : 2000, visibleOnly : false, appendScroll : window, scrollDirection : "both", // delay delay : -1, combined : false, // attribute attribute : "data-src", removeAttribute : true, handledName : "handled", // effect effect : "show", effectTime : 0, // throttle enableThrottle : false, throttle : 250, // queue enableQueueing : true, // callbacks beforeLoad : null, onLoad : null, afterLoad : null, onError : null, onFinishedAll : null }, /** * all given items by jQuery selector * @access private * @type {*} */ _items = this, /** * a helper to trigger the onFinishedAll after all other events * @access private * @type {number} */ _awaitingAfterLoad = 0, /** * visible content width * @access private * @type {number} */ _actualWidth = -1, /** * visible content height * @access private * @type {number} */ _actualHeight = -1, /** * queue timer instance * @access private * @type {null|number} */ _queueTimer = null, /** * array of items in queue * @access private * @type {Array} */ _queueItems = [], /** * identifies if queue actually contains the lazy magic * @access private * @type {boolean} */ _queueContainsMagic = false; /** * initialize plugin - bind loading to events or set delay time to load all images at once * @access private * @return void */ function _init() { // if delay time is set load all images at once after delay time if( _configuration.delay >= 0 ) setTimeout(function() { _lazyLoadImages(true); }, _configuration.delay); // if no delay is set or combine usage is active bind events if( _configuration.delay < 0 || _configuration.combined ) { // load initial images _lazyLoadImages(false); // bind lazy load functions to scroll event _addToQueue(function() { $(_configuration.appendScroll).bind("scroll", _throttle(_configuration.throttle, function() { _addToQueue(function() { _lazyLoadImages(false) }, this, true); })); }, this); // bind lazy load functions to resize event _addToQueue(function() { $(_configuration.appendScroll).bind("resize", _throttle(_configuration.throttle, function() { _actualWidth = _actualHeight = -1; _addToQueue(function() { _lazyLoadImages(false) }, this, true); })); }, this); } } /** * the 'lazy magic' - check all items * @access private * @param {boolean} allImages * @return void */ function _lazyLoadImages(allImages) { // stop if no items where left if( !_items.length ) return; // helper to see if something was changed var loadedImages = false; for( var i = 0; i < _items.length; i++ ) { (function() { var item = _items[i], element = $(item); if( _isInLoadableArea(item) || allImages ) { var tag = _items[i].tagName.toLowerCase(); if( // image source attribute is available element.attr(_configuration.attribute) && // and is image tag where attribute is not equal source ((tag == "img" && element.attr(_configuration.attribute) != element.attr("src")) || // or is non image tag where attribute is not equal background ((tag != "img" && element.attr(_configuration.attribute) != element.css("background-image"))) ) && // and is not actually loaded just before !element.data(_configuration.handledName) && // and is visible or visibility doesn't matter (element.is(":visible") || !_configuration.visibleOnly) ) { loadedImages = true; // mark element always as handled as this point to prevent double loading element.data(_configuration.handledName, true); // add item to loading queue _addToQueue(function() { _handleItem(element, tag) }, this); } } })(); } // when something was loaded remove them from remaining items if( loadedImages ) _addToQueue(function() { _items = $(_items).filter(function() { return !$(this).data(_configuration.handledName); }); }, this); } /** * load the given element the lazy way * @access private * @param {object} element * @param {string} tag * @return void */ function _handleItem(element, tag) { // create image object var imageObj = $(new Image()); // increment count of items waiting for after load ++_awaitingAfterLoad; // bind error event if wanted, otherwise only reduce waiting count if( _configuration.onError ) imageObj.error(function() { _triggerCallback(_configuration.onError, element); _reduceAwaiting(); }); else imageObj.error(function() { _reduceAwaiting(); }); // bind after load callback to image var onLoad = false; imageObj.one("load", function() { var callable = function() { if( !onLoad ) { window.setTimeout(callable, 100); return; } // remove element from view element.hide(); // set image back to element if( tag == "img" ) element.attr("src", imageObj.attr("src")); else element.css("background-image", "url(" + imageObj.attr("src") + ")"); // bring it back with some effect! element[_configuration.effect](_configuration.effectTime); // remove attribute from element if( _configuration.removeAttribute ) element.removeAttr(_configuration.attribute); // call after load event _triggerCallback(_configuration.afterLoad, element); // unbind event and remove image object imageObj.unbind("load").remove(); // remove item from waiting cue and possible trigger finished event _reduceAwaiting(); }; callable(); }); // trigger function before loading image _triggerCallback(_configuration.beforeLoad, element); // set source imageObj.attr("src", element.attr(_configuration.attribute)); // trigger function before loading image _triggerCallback(_configuration.onLoad, element); onLoad = true; // call after load even on cached image if( imageObj.complete ) imageObj.load(); } /** * check if the given element is inside the current view or threshold * @access private * @param {object} element * @return {boolean} */ function _isInLoadableArea(element) { var viewedWidth = _getActualWidth(), viewedHeight = _getActualHeight(), elementBound = element.getBoundingClientRect(), vertical = // check if element is in loadable area from top ((viewedHeight + _configuration.threshold) > elementBound.top) && // check if element is even in loadable are from bottom (-_configuration.threshold < elementBound.bottom), horizontal = // check if element is in loadable area from left ((viewedWidth + _configuration.threshold) > elementBound.left) && // check if element is even in loadable are from right (-_configuration.threshold < elementBound.right); if( _configuration.scrollDirection == "vertical" ) return vertical; else if( _configuration.scrollDirection == "horizontal" ) return horizontal; return vertical && horizontal; } /** * try to allocate current viewed width of the browser * uses fallback option when no height is found * @access private * @return {number} */ function _getActualWidth() { if( _actualWidth >= 0 ) return _actualWidth; _actualWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth || document.body.offsetWidth || _configuration.fallbackWidth; return _actualWidth; } /** * try to allocate current viewed height of the browser * uses fallback option when no height is found * @access private * @return {number} */ function _getActualHeight() { if( _actualHeight >= 0 ) return _actualHeight; _actualHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight || document.body.offsetHeight || _configuration.fallbackHeight; return _actualHeight; } /** * helper function to throttle down event triggering * @access private * @param {number} delay * @param {function} call * @return {function} */ function _throttle(delay, call) { var _timeout, _exec = 0; function callable() { var elapsed = +new Date() - _exec; function run() { _exec = +new Date(); call.apply(undefined); } _timeout && clearTimeout(_timeout); if( elapsed > delay || !_configuration.enableThrottle ) run(); else _timeout = setTimeout(run, delay - elapsed); } return callable; } /** * reduce count of awaiting elements to 'afterLoad' event and fire 'onFinishedAll' if reached zero * @access private * @return void */ function _reduceAwaiting() { --_awaitingAfterLoad; // if no items were left trigger finished event if( !_items.size() && !_awaitingAfterLoad ) _triggerCallback(_configuration.onFinishedAll, null); } /** * single implementation to handle callbacks and pass parameter * @access private * @param {function} callback * @param {object} [element] * @return void */ function _triggerCallback(callback, element) { if( callback ) { if( element ) _addToQueue(function() { callback(element); }, this); else _addToQueue(callback, this); } } /** * set next timer for queue execution * @access private * @return void */ function _setQueueTimer() { _queueTimer = setTimeout(function() { _addToQueue(); if( _queueItems.length ) _setQueueTimer(); }, 2); } /** * add new execution to queue * @access private * @param {object} [callable] * @param {object} [context] * @param {boolean} [isLazyMagic] * @returns {number} */ function _addToQueue(callable, context, isLazyMagic) { if( callable ) { // execute directly when queue is disabled if( _configuration.enableQueueing ) callable.call(context || window); // let the lazy magic only be once in queue if( !isLazyMagic || (isLazyMagic && !_queueContainsMagic) ) { _queueItems.push([callable, context, isLazyMagic]); if( isLazyMagic ) _queueContainsMagic = true; } if( _queueItems.length == 1 ) _setQueueTimer(); return 0; } var next = _queueItems.shift(); if( !next ) return 0; if( next[2] ) _queueContainsMagic = false; next[0].call(next[1] || window); return 0; } // set up lazy (function() { // overwrite configuration with custom user settings if( settings ) $.extend(_configuration, settings); // late-bind error callback to images if set if( _configuration.onError ) _items.each(function() { var item = this; _addToQueue(function() { $(item).bind("error", function() { _triggerCallback(_configuration.onError, $(this)); }); }, item); }); // on first page load get initial images if( _configuration.bind == "load" ) $(window).load(_init); // if event driven don't wait for page loading else if( _configuration.bind == "event" ) _init(); })(); return this; }; // make lazy a bit more case-insensitive :) $.fn.Lazy = $.fn.lazy; })(jQuery, window, document);
require('./angular-locale_en-bb'); module.exports = 'ngLocale';
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "\u4e0a\u5348", "\u4e0b\u5348" ], "DAY": [ "\u661f\u671f\u65e5", "\u661f\u671f\u4e00", "\u661f\u671f\u4e8c", "\u661f\u671f\u4e09", "\u661f\u671f\u56db", "\u661f\u671f\u4e94", "\u661f\u671f\u516d" ], "ERANAMES": [ "\u897f\u5143\u524d", "\u897f\u5143" ], "ERAS": [ "\u897f\u5143\u524d", "\u897f\u5143" ], "FIRSTDAYOFWEEK": 0, "MONTH": [ "1\u6708", "2\u6708", "3\u6708", "4\u6708", "5\u6708", "6\u6708", "7\u6708", "8\u6708", "9\u6708", "10\u6708", "11\u6708", "12\u6708" ], "SHORTDAY": [ "\u9031\u65e5", "\u9031\u4e00", "\u9031\u4e8c", "\u9031\u4e09", "\u9031\u56db", "\u9031\u4e94", "\u9031\u516d" ], "SHORTMONTH": [ "1\u6708", "2\u6708", "3\u6708", "4\u6708", "5\u6708", "6\u6708", "7\u6708", "8\u6708", "9\u6708", "10\u6708", "11\u6708", "12\u6708" ], "STANDALONEMONTH": [ "1\u6708", "2\u6708", "3\u6708", "4\u6708", "5\u6708", "6\u6708", "7\u6708", "8\u6708", "9\u6708", "10\u6708", "11\u6708", "12\u6708" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "y\u5e74M\u6708d\u65e5 EEEE", "longDate": "y\u5e74M\u6708d\u65e5", "medium": "y\u5e74M\u6708d\u65e5 ah:mm:ss", "mediumDate": "y\u5e74M\u6708d\u65e5", "mediumTime": "ah:mm:ss", "short": "y/M/d ah:mm", "shortDate": "y/M/d", "shortTime": "ah:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "$", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-\u00a4", "negSuf": "", "posPre": "\u00a4", "posSuf": "" } ] }, "id": "yue", "localeID": "yue", "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
/*! * jQuery UI Datepicker 1.9.2 * http://jqueryui.com * * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/datepicker/ * * Depends: * jquery.ui.core.js */ (function( $, undefined ) { $.extend($.ui, { datepicker: { version: "1.9.2" } }); var PROP_NAME = 'datepicker'; var dpuuid = new Date().getTime(); var instActive; /* Date picker manager. Use the singleton instance of this class, $.datepicker, to interact with the date picker. Settings for (groups of) date pickers are maintained in an instance object, allowing multiple different settings on the same page. */ function Datepicker() { this.debug = false; // Change this to true to start debugging this._curInst = null; // The current instance in use this._keyEvent = false; // If the last event was a key event this._disabledInputs = []; // List of date picker inputs that have been disabled this._datepickerShowing = false; // True if the popup picker is showing , false if not this._inDialog = false; // True if showing within a "dialog", false if not this._mainDivId = 'ui-datepicker-div'; // The ID of the main datepicker division this._inlineClass = 'ui-datepicker-inline'; // The name of the inline marker class this._appendClass = 'ui-datepicker-append'; // The name of the append marker class this._triggerClass = 'ui-datepicker-trigger'; // The name of the trigger marker class this._dialogClass = 'ui-datepicker-dialog'; // The name of the dialog marker class this._disableClass = 'ui-datepicker-disabled'; // The name of the disabled covering marker class this._unselectableClass = 'ui-datepicker-unselectable'; // The name of the unselectable cell marker class this._currentClass = 'ui-datepicker-current-day'; // The name of the current day marker class this._dayOverClass = 'ui-datepicker-days-cell-over'; // The name of the day hover marker class this.regional = []; // Available regional settings, indexed by language code this.regional[''] = { // Default regional settings closeText: 'Done', // Display text for close link prevText: 'Prev', // Display text for previous month link nextText: 'Next', // Display text for next month link currentText: 'Today', // Display text for current month link monthNames: ['January','February','March','April','May','June', 'July','August','September','October','November','December'], // Names of months for drop-down and formatting monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], // For formatting dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // For formatting dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], // For formatting dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'], // Column headings for days starting at Sunday weekHeader: 'Wk', // Column header for week of the year dateFormat: 'mm/dd/yy', // See format options on parseDate firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ... isRTL: false, // True if right-to-left language, false if left-to-right showMonthAfterYear: false, // True if the year select precedes month, false for month then year yearSuffix: '' // Additional text to append to the year in the month headers }; this._defaults = { // Global defaults for all the date picker instances showOn: 'focus', // 'focus' for popup on focus, // 'button' for trigger button, or 'both' for either showAnim: 'fadeIn', // Name of jQuery animation for popup showOptions: {}, // Options for enhanced animations defaultDate: null, // Used when field is blank: actual date, // +/-number for offset from today, null for today appendText: '', // Display text following the input box, e.g. showing the format buttonText: '...', // Text for trigger button buttonImage: '', // URL for trigger button image buttonImageOnly: false, // True if the image appears alone, false if it appears on a button hideIfNoPrevNext: false, // True to hide next/previous month links // if not applicable, false to just disable them navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links gotoCurrent: false, // True if today link goes back to current selection instead changeMonth: false, // True if month can be selected directly, false if only prev/next changeYear: false, // True if year can be selected directly, false if only prev/next yearRange: 'c-10:c+10', // Range of years to display in drop-down, // either relative to today's year (-nn:+nn), relative to currently displayed year // (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n) showOtherMonths: false, // True to show dates in other months, false to leave blank selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable showWeek: false, // True to show week of the year, false to not show it calculateWeek: this.iso8601Week, // How to calculate the week of the year, // takes a Date and returns the number of the week for it shortYearCutoff: '+10', // Short year values < this are in the current century, // > this are in the previous century, // string value starting with '+' for current year + value minDate: null, // The earliest selectable date, or null for no limit maxDate: null, // The latest selectable date, or null for no limit duration: 'fast', // Duration of display/closure beforeShowDay: null, // Function that takes a date and returns an array with // [0] = true if selectable, false if not, [1] = custom CSS class name(s) or '', // [2] = cell title (optional), e.g. $.datepicker.noWeekends beforeShow: null, // Function that takes an input field and // returns a set of custom settings for the date picker onSelect: null, // Define a callback function when a date is selected onChangeMonthYear: null, // Define a callback function when the month or year is changed onClose: null, // Define a callback function when the datepicker is closed numberOfMonths: 1, // Number of months to show at a time showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0) stepMonths: 1, // Number of months to step back/forward stepBigMonths: 12, // Number of months to step back/forward for the big links altField: '', // Selector for an alternate field to store selected dates into altFormat: '', // The date format to use for the alternate field constrainInput: true, // The input is constrained by the current date format showButtonPanel: false, // True to show button panel, false to not show it autoSize: false, // True to size the input for the date format, false to leave as is disabled: false // The initial disabled state }; $.extend(this._defaults, this.regional['']); this.dpDiv = bindHover($('<div id="' + this._mainDivId + '" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>')); } $.extend(Datepicker.prototype, { /* Class name added to elements to indicate already configured with a date picker. */ markerClassName: 'hasDatepicker', //Keep track of the maximum number of rows displayed (see #7043) maxRows: 4, /* Debug logging (if enabled). */ log: function () { if (this.debug) console.log.apply('', arguments); }, // TODO rename to "widget" when switching to widget factory _widgetDatepicker: function() { return this.dpDiv; }, /* Override the default settings for all instances of the date picker. @param settings object - the new settings to use as defaults (anonymous object) @return the manager object */ setDefaults: function(settings) { extendRemove(this._defaults, settings || {}); return this; }, /* Attach the date picker to a jQuery selection. @param target element - the target input field or division or span @param settings object - the new settings to use for this date picker instance (anonymous) */ _attachDatepicker: function(target, settings) { // check for settings on the control itself - in namespace 'date:' var inlineSettings = null; for (var attrName in this._defaults) { var attrValue = target.getAttribute('date:' + attrName); if (attrValue) { inlineSettings = inlineSettings || {}; try { inlineSettings[attrName] = eval(attrValue); } catch (err) { inlineSettings[attrName] = attrValue; } } } var nodeName = target.nodeName.toLowerCase(); var inline = (nodeName == 'div' || nodeName == 'span'); if (!target.id) { this.uuid += 1; target.id = 'dp' + this.uuid; } var inst = this._newInst($(target), inline); inst.settings = $.extend({}, settings || {}, inlineSettings || {}); if (nodeName == 'input') { this._connectDatepicker(target, inst); } else if (inline) { this._inlineDatepicker(target, inst); } }, /* Create a new instance object. */ _newInst: function(target, inline) { var id = target[0].id.replace(/([^A-Za-z0-9_-])/g, '\\\\$1'); // escape jQuery meta chars return {id: id, input: target, // associated target selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection drawMonth: 0, drawYear: 0, // month being drawn inline: inline, // is datepicker inline or not dpDiv: (!inline ? this.dpDiv : // presentation div bindHover($('<div class="' + this._inlineClass + ' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>')))}; }, /* Attach the date picker to an input field. */ _connectDatepicker: function(target, inst) { var input = $(target); inst.append = $([]); inst.trigger = $([]); if (input.hasClass(this.markerClassName)) return; this._attachments(input, inst); input.addClass(this.markerClassName).keydown(this._doKeyDown). keypress(this._doKeyPress).keyup(this._doKeyUp). bind("setData.datepicker", function(event, key, value) { inst.settings[key] = value; }).bind("getData.datepicker", function(event, key) { return this._get(inst, key); }); this._autoSize(inst); $.data(target, PROP_NAME, inst); //If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665) if( inst.settings.disabled ) { this._disableDatepicker( target ); } }, /* Make attachments based on settings. */ _attachments: function(input, inst) { var appendText = this._get(inst, 'appendText'); var isRTL = this._get(inst, 'isRTL'); if (inst.append) inst.append.remove(); if (appendText) { inst.append = $('<span class="' + this._appendClass + '">' + appendText + '</span>'); input[isRTL ? 'before' : 'after'](inst.append); } input.unbind('focus', this._showDatepicker); if (inst.trigger) inst.trigger.remove(); var showOn = this._get(inst, 'showOn'); if (showOn == 'focus' || showOn == 'both') // pop-up date picker when in the marked field input.focus(this._showDatepicker); if (showOn == 'button' || showOn == 'both') { // pop-up date picker when button clicked var buttonText = this._get(inst, 'buttonText'); var buttonImage = this._get(inst, 'buttonImage'); inst.trigger = $(this._get(inst, 'buttonImageOnly') ? $('<img/>').addClass(this._triggerClass). attr({ src: buttonImage, alt: buttonText, title: buttonText }) : $('<button type="button"></button>').addClass(this._triggerClass). html(buttonImage == '' ? buttonText : $('<img/>').attr( { src:buttonImage, alt:buttonText, title:buttonText }))); input[isRTL ? 'before' : 'after'](inst.trigger); inst.trigger.click(function() { if ($.datepicker._datepickerShowing && $.datepicker._lastInput == input[0]) $.datepicker._hideDatepicker(); else if ($.datepicker._datepickerShowing && $.datepicker._lastInput != input[0]) { $.datepicker._hideDatepicker(); $.datepicker._showDatepicker(input[0]); } else $.datepicker._showDatepicker(input[0]); return false; }); } }, /* Apply the maximum length for the date format. */ _autoSize: function(inst) { if (this._get(inst, 'autoSize') && !inst.inline) { var date = new Date(2009, 12 - 1, 20); // Ensure double digits var dateFormat = this._get(inst, 'dateFormat'); if (dateFormat.match(/[DM]/)) { var findMax = function(names) { var max = 0; var maxI = 0; for (var i = 0; i < names.length; i++) { if (names[i].length > max) { max = names[i].length; maxI = i; } } return maxI; }; date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ? 'monthNames' : 'monthNamesShort')))); date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ? 'dayNames' : 'dayNamesShort'))) + 20 - date.getDay()); } inst.input.attr('size', this._formatDate(inst, date).length); } }, /* Attach an inline date picker to a div. */ _inlineDatepicker: function(target, inst) { var divSpan = $(target); if (divSpan.hasClass(this.markerClassName)) return; divSpan.addClass(this.markerClassName).append(inst.dpDiv). bind("setData.datepicker", function(event, key, value){ inst.settings[key] = value; }).bind("getData.datepicker", function(event, key){ return this._get(inst, key); }); $.data(target, PROP_NAME, inst); this._setDate(inst, this._getDefaultDate(inst), true); this._updateDatepicker(inst); this._updateAlternate(inst); //If disabled option is true, disable the datepicker before showing it (see ticket #5665) if( inst.settings.disabled ) { this._disableDatepicker( target ); } // Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements // http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height inst.dpDiv.css( "display", "block" ); }, /* Pop-up the date picker in a "dialog" box. @param input element - ignored @param date string or Date - the initial date to display @param onSelect function - the function to call when a date is selected @param settings object - update the dialog date picker instance's settings (anonymous object) @param pos int[2] - coordinates for the dialog's position within the screen or event - with x/y coordinates or leave empty for default (screen centre) @return the manager object */ _dialogDatepicker: function(input, date, onSelect, settings, pos) { var inst = this._dialogInst; // internal instance if (!inst) { this.uuid += 1; var id = 'dp' + this.uuid; this._dialogInput = $('<input type="text" id="' + id + '" style="position: absolute; top: -100px; width: 0px;"/>'); this._dialogInput.keydown(this._doKeyDown); $('body').append(this._dialogInput); inst = this._dialogInst = this._newInst(this._dialogInput, false); inst.settings = {}; $.data(this._dialogInput[0], PROP_NAME, inst); } extendRemove(inst.settings, settings || {}); date = (date && date.constructor == Date ? this._formatDate(inst, date) : date); this._dialogInput.val(date); this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null); if (!this._pos) { var browserWidth = document.documentElement.clientWidth; var browserHeight = document.documentElement.clientHeight; var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft; var scrollY = document.documentElement.scrollTop || document.body.scrollTop; this._pos = // should use actual width/height below [(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY]; } // move input on screen for focus, but hidden behind dialog this._dialogInput.css('left', (this._pos[0] + 20) + 'px').css('top', this._pos[1] + 'px'); inst.settings.onSelect = onSelect; this._inDialog = true; this.dpDiv.addClass(this._dialogClass); this._showDatepicker(this._dialogInput[0]); if ($.blockUI) $.blockUI(this.dpDiv); $.data(this._dialogInput[0], PROP_NAME, inst); return this; }, /* Detach a datepicker from its control. @param target element - the target input field or division or span */ _destroyDatepicker: function(target) { var $target = $(target); var inst = $.data(target, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return; } var nodeName = target.nodeName.toLowerCase(); $.removeData(target, PROP_NAME); if (nodeName == 'input') { inst.append.remove(); inst.trigger.remove(); $target.removeClass(this.markerClassName). unbind('focus', this._showDatepicker). unbind('keydown', this._doKeyDown). unbind('keypress', this._doKeyPress). unbind('keyup', this._doKeyUp); } else if (nodeName == 'div' || nodeName == 'span') $target.removeClass(this.markerClassName).empty(); }, /* Enable the date picker to a jQuery selection. @param target element - the target input field or division or span */ _enableDatepicker: function(target) { var $target = $(target); var inst = $.data(target, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return; } var nodeName = target.nodeName.toLowerCase(); if (nodeName == 'input') { target.disabled = false; inst.trigger.filter('button'). each(function() { this.disabled = false; }).end(). filter('img').css({opacity: '1.0', cursor: ''}); } else if (nodeName == 'div' || nodeName == 'span') { var inline = $target.children('.' + this._inlineClass); inline.children().removeClass('ui-state-disabled'); inline.find("select.ui-datepicker-month, select.ui-datepicker-year"). prop("disabled", false); } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value == target ? null : value); }); // delete entry }, /* Disable the date picker to a jQuery selection. @param target element - the target input field or division or span */ _disableDatepicker: function(target) { var $target = $(target); var inst = $.data(target, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return; } var nodeName = target.nodeName.toLowerCase(); if (nodeName == 'input') { target.disabled = true; inst.trigger.filter('button'). each(function() { this.disabled = true; }).end(). filter('img').css({opacity: '0.5', cursor: 'default'}); } else if (nodeName == 'div' || nodeName == 'span') { var inline = $target.children('.' + this._inlineClass); inline.children().addClass('ui-state-disabled'); inline.find("select.ui-datepicker-month, select.ui-datepicker-year"). prop("disabled", true); } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value == target ? null : value); }); // delete entry this._disabledInputs[this._disabledInputs.length] = target; }, /* Is the first field in a jQuery collection disabled as a datepicker? @param target element - the target input field or division or span @return boolean - true if disabled, false if enabled */ _isDisabledDatepicker: function(target) { if (!target) { return false; } for (var i = 0; i < this._disabledInputs.length; i++) { if (this._disabledInputs[i] == target) return true; } return false; }, /* Retrieve the instance data for the target control. @param target element - the target input field or division or span @return object - the associated instance data @throws error if a jQuery problem getting data */ _getInst: function(target) { try { return $.data(target, PROP_NAME); } catch (err) { throw 'Missing instance data for this datepicker'; } }, /* Update or retrieve the settings for a date picker attached to an input field or division. @param target element - the target input field or division or span @param name object - the new settings to update or string - the name of the setting to change or retrieve, when retrieving also 'all' for all instance settings or 'defaults' for all global defaults @param value any - the new value for the setting (omit if above is an object or to retrieve a value) */ _optionDatepicker: function(target, name, value) { var inst = this._getInst(target); if (arguments.length == 2 && typeof name == 'string') { return (name == 'defaults' ? $.extend({}, $.datepicker._defaults) : (inst ? (name == 'all' ? $.extend({}, inst.settings) : this._get(inst, name)) : null)); } var settings = name || {}; if (typeof name == 'string') { settings = {}; settings[name] = value; } if (inst) { if (this._curInst == inst) { this._hideDatepicker(); } var date = this._getDateDatepicker(target, true); var minDate = this._getMinMaxDate(inst, 'min'); var maxDate = this._getMinMaxDate(inst, 'max'); extendRemove(inst.settings, settings); // reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided if (minDate !== null && settings['dateFormat'] !== undefined && settings['minDate'] === undefined) inst.settings.minDate = this._formatDate(inst, minDate); if (maxDate !== null && settings['dateFormat'] !== undefined && settings['maxDate'] === undefined) inst.settings.maxDate = this._formatDate(inst, maxDate); this._attachments($(target), inst); this._autoSize(inst); this._setDate(inst, date); this._updateAlternate(inst); this._updateDatepicker(inst); } }, // change method deprecated _changeDatepicker: function(target, name, value) { this._optionDatepicker(target, name, value); }, /* Redraw the date picker attached to an input field or division. @param target element - the target input field or division or span */ _refreshDatepicker: function(target) { var inst = this._getInst(target); if (inst) { this._updateDatepicker(inst); } }, /* Set the dates for a jQuery selection. @param target element - the target input field or division or span @param date Date - the new date */ _setDateDatepicker: function(target, date) { var inst = this._getInst(target); if (inst) { this._setDate(inst, date); this._updateDatepicker(inst); this._updateAlternate(inst); } }, /* Get the date(s) for the first entry in a jQuery selection. @param target element - the target input field or division or span @param noDefault boolean - true if no default date is to be used @return Date - the current date */ _getDateDatepicker: function(target, noDefault) { var inst = this._getInst(target); if (inst && !inst.inline) this._setDateFromField(inst, noDefault); return (inst ? this._getDate(inst) : null); }, /* Handle keystrokes. */ _doKeyDown: function(event) { var inst = $.datepicker._getInst(event.target); var handled = true; var isRTL = inst.dpDiv.is('.ui-datepicker-rtl'); inst._keyEvent = true; if ($.datepicker._datepickerShowing) switch (event.keyCode) { case 9: $.datepicker._hideDatepicker(); handled = false; break; // hide on tab out case 13: var sel = $('td.' + $.datepicker._dayOverClass + ':not(.' + $.datepicker._currentClass + ')', inst.dpDiv); if (sel[0]) $.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]); var onSelect = $.datepicker._get(inst, 'onSelect'); if (onSelect) { var dateStr = $.datepicker._formatDate(inst); // trigger custom callback onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); } else $.datepicker._hideDatepicker(); return false; // don't submit the form break; // select the value on enter case 27: $.datepicker._hideDatepicker(); break; // hide on escape case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, 'stepBigMonths') : -$.datepicker._get(inst, 'stepMonths')), 'M'); break; // previous month/year on page up/+ ctrl case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, 'stepBigMonths') : +$.datepicker._get(inst, 'stepMonths')), 'M'); break; // next month/year on page down/+ ctrl case 35: if (event.ctrlKey || event.metaKey) $.datepicker._clearDate(event.target); handled = event.ctrlKey || event.metaKey; break; // clear on ctrl or command +end case 36: if (event.ctrlKey || event.metaKey) $.datepicker._gotoToday(event.target); handled = event.ctrlKey || event.metaKey; break; // current on ctrl or command +home case 37: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), 'D'); handled = event.ctrlKey || event.metaKey; // -1 day on ctrl or command +left if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, 'stepBigMonths') : -$.datepicker._get(inst, 'stepMonths')), 'M'); // next month/year on alt +left on Mac break; case 38: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, -7, 'D'); handled = event.ctrlKey || event.metaKey; break; // -1 week on ctrl or command +up case 39: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), 'D'); handled = event.ctrlKey || event.metaKey; // +1 day on ctrl or command +right if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, 'stepBigMonths') : +$.datepicker._get(inst, 'stepMonths')), 'M'); // next month/year on alt +right break; case 40: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, +7, 'D'); handled = event.ctrlKey || event.metaKey; break; // +1 week on ctrl or command +down default: handled = false; } else if (event.keyCode == 36 && event.ctrlKey) // display the date picker on ctrl+home $.datepicker._showDatepicker(this); else { handled = false; } if (handled) { event.preventDefault(); event.stopPropagation(); } }, /* Filter entered characters - based on date format. */ _doKeyPress: function(event) { var inst = $.datepicker._getInst(event.target); if ($.datepicker._get(inst, 'constrainInput')) { var chars = $.datepicker._possibleChars($.datepicker._get(inst, 'dateFormat')); var chr = String.fromCharCode(event.charCode == undefined ? event.keyCode : event.charCode); return event.ctrlKey || event.metaKey || (chr < ' ' || !chars || chars.indexOf(chr) > -1); } }, /* Synchronise manual entry and field/alternate field. */ _doKeyUp: function(event) { var inst = $.datepicker._getInst(event.target); if (inst.input.val() != inst.lastVal) { try { var date = $.datepicker.parseDate($.datepicker._get(inst, 'dateFormat'), (inst.input ? inst.input.val() : null), $.datepicker._getFormatConfig(inst)); if (date) { // only if valid $.datepicker._setDateFromField(inst); $.datepicker._updateAlternate(inst); $.datepicker._updateDatepicker(inst); } } catch (err) { $.datepicker.log(err); } } return true; }, /* Pop-up the date picker for a given input field. If false returned from beforeShow event handler do not show. @param input element - the input field attached to the date picker or event - if triggered by focus */ _showDatepicker: function(input) { input = input.target || input; if (input.nodeName.toLowerCase() != 'input') // find from button/image trigger input = $('input', input.parentNode)[0]; if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput == input) // already here return; var inst = $.datepicker._getInst(input); if ($.datepicker._curInst && $.datepicker._curInst != inst) { $.datepicker._curInst.dpDiv.stop(true, true); if ( inst && $.datepicker._datepickerShowing ) { $.datepicker._hideDatepicker( $.datepicker._curInst.input[0] ); } } var beforeShow = $.datepicker._get(inst, 'beforeShow'); var beforeShowSettings = beforeShow ? beforeShow.apply(input, [input, inst]) : {}; if(beforeShowSettings === false){ //false return; } extendRemove(inst.settings, beforeShowSettings); inst.lastVal = null; $.datepicker._lastInput = input; $.datepicker._setDateFromField(inst); if ($.datepicker._inDialog) // hide cursor input.value = ''; if (!$.datepicker._pos) { // position below input $.datepicker._pos = $.datepicker._findPos(input); $.datepicker._pos[1] += input.offsetHeight; // add the height } var isFixed = false; $(input).parents().each(function() { isFixed |= $(this).css('position') == 'fixed'; return !isFixed; }); var offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]}; $.datepicker._pos = null; //to avoid flashes on Firefox inst.dpDiv.empty(); // determine sizing offscreen inst.dpDiv.css({position: 'absolute', display: 'block', top: '-1000px'}); $.datepicker._updateDatepicker(inst); // fix width for dynamic number of date pickers // and adjust position before showing offset = $.datepicker._checkOffset(inst, offset, isFixed); inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ? 'static' : (isFixed ? 'fixed' : 'absolute')), display: 'none', left: offset.left + 'px', top: offset.top + 'px'}); if (!inst.inline) { var showAnim = $.datepicker._get(inst, 'showAnim'); var duration = $.datepicker._get(inst, 'duration'); var postProcess = function() { var cover = inst.dpDiv.find('iframe.ui-datepicker-cover'); // IE6- only if( !! cover.length ){ var borders = $.datepicker._getBorders(inst.dpDiv); cover.css({left: -borders[0], top: -borders[1], width: inst.dpDiv.outerWidth(), height: inst.dpDiv.outerHeight()}); } }; inst.dpDiv.zIndex($(input).zIndex()+1); $.datepicker._datepickerShowing = true; // DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed if ( $.effects && ( $.effects.effect[ showAnim ] || $.effects[ showAnim ] ) ) inst.dpDiv.show(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess); else inst.dpDiv[showAnim || 'show']((showAnim ? duration : null), postProcess); if (!showAnim || !duration) postProcess(); if (inst.input.is(':visible') && !inst.input.is(':disabled')) inst.input.focus(); $.datepicker._curInst = inst; } }, /* Generate the date picker content. */ _updateDatepicker: function(inst) { this.maxRows = 4; //Reset the max number of rows being displayed (see #7043) var borders = $.datepicker._getBorders(inst.dpDiv); instActive = inst; // for delegate hover events inst.dpDiv.empty().append(this._generateHTML(inst)); this._attachHandlers(inst); var cover = inst.dpDiv.find('iframe.ui-datepicker-cover'); // IE6- only if( !!cover.length ){ //avoid call to outerXXXX() when not in IE6 cover.css({left: -borders[0], top: -borders[1], width: inst.dpDiv.outerWidth(), height: inst.dpDiv.outerHeight()}) } inst.dpDiv.find('.' + this._dayOverClass + ' a').mouseover(); var numMonths = this._getNumberOfMonths(inst); var cols = numMonths[1]; var width = 17; inst.dpDiv.removeClass('ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4').width(''); if (cols > 1) inst.dpDiv.addClass('ui-datepicker-multi-' + cols).css('width', (width * cols) + 'em'); inst.dpDiv[(numMonths[0] != 1 || numMonths[1] != 1 ? 'add' : 'remove') + 'Class']('ui-datepicker-multi'); inst.dpDiv[(this._get(inst, 'isRTL') ? 'add' : 'remove') + 'Class']('ui-datepicker-rtl'); if (inst == $.datepicker._curInst && $.datepicker._datepickerShowing && inst.input && // #6694 - don't focus the input if it's already focused // this breaks the change event in IE inst.input.is(':visible') && !inst.input.is(':disabled') && inst.input[0] != document.activeElement) inst.input.focus(); // deffered render of the years select (to avoid flashes on Firefox) if( inst.yearshtml ){ var origyearshtml = inst.yearshtml; setTimeout(function(){ //assure that inst.yearshtml didn't change. if( origyearshtml === inst.yearshtml && inst.yearshtml ){ inst.dpDiv.find('select.ui-datepicker-year:first').replaceWith(inst.yearshtml); } origyearshtml = inst.yearshtml = null; }, 0); } }, /* Retrieve the size of left and top borders for an element. @param elem (jQuery object) the element of interest @return (number[2]) the left and top borders */ _getBorders: function(elem) { var convert = function(value) { return {thin: 1, medium: 2, thick: 3}[value] || value; }; return [parseFloat(convert(elem.css('border-left-width'))), parseFloat(convert(elem.css('border-top-width')))]; }, /* Check positioning to remain on screen. */ _checkOffset: function(inst, offset, isFixed) { var dpWidth = inst.dpDiv.outerWidth(); var dpHeight = inst.dpDiv.outerHeight(); var inputWidth = inst.input ? inst.input.outerWidth() : 0; var inputHeight = inst.input ? inst.input.outerHeight() : 0; var viewWidth = document.documentElement.clientWidth + (isFixed ? 0 : $(document).scrollLeft()); var viewHeight = document.documentElement.clientHeight + (isFixed ? 0 : $(document).scrollTop()); offset.left -= (this._get(inst, 'isRTL') ? (dpWidth - inputWidth) : 0); offset.left -= (isFixed && offset.left == inst.input.offset().left) ? $(document).scrollLeft() : 0; offset.top -= (isFixed && offset.top == (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0; // now check if datepicker is showing outside window viewport - move to a better place if so. offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ? Math.abs(offset.left + dpWidth - viewWidth) : 0); offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ? Math.abs(dpHeight + inputHeight) : 0); return offset; }, /* Find an object's position on the screen. */ _findPos: function(obj) { var inst = this._getInst(obj); var isRTL = this._get(inst, 'isRTL'); while (obj && (obj.type == 'hidden' || obj.nodeType != 1 || $.expr.filters.hidden(obj))) { obj = obj[isRTL ? 'previousSibling' : 'nextSibling']; } var position = $(obj).offset(); return [position.left, position.top]; }, /* Hide the date picker from view. @param input element - the input field attached to the date picker */ _hideDatepicker: function(input) { var inst = this._curInst; if (!inst || (input && inst != $.data(input, PROP_NAME))) return; if (this._datepickerShowing) { var showAnim = this._get(inst, 'showAnim'); var duration = this._get(inst, 'duration'); var postProcess = function() { $.datepicker._tidyDialog(inst); }; // DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed if ( $.effects && ( $.effects.effect[ showAnim ] || $.effects[ showAnim ] ) ) inst.dpDiv.hide(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess); else inst.dpDiv[(showAnim == 'slideDown' ? 'slideUp' : (showAnim == 'fadeIn' ? 'fadeOut' : 'hide'))]((showAnim ? duration : null), postProcess); if (!showAnim) postProcess(); this._datepickerShowing = false; var onClose = this._get(inst, 'onClose'); if (onClose) onClose.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ''), inst]); this._lastInput = null; if (this._inDialog) { this._dialogInput.css({ position: 'absolute', left: '0', top: '-100px' }); if ($.blockUI) { $.unblockUI(); $('body').append(this.dpDiv); } } this._inDialog = false; } }, /* Tidy up after a dialog display. */ _tidyDialog: function(inst) { inst.dpDiv.removeClass(this._dialogClass).unbind('.ui-datepicker-calendar'); }, /* Close date picker if clicked elsewhere. */ _checkExternalClick: function(event) { if (!$.datepicker._curInst) return; var $target = $(event.target), inst = $.datepicker._getInst($target[0]); if ( ( ( $target[0].id != $.datepicker._mainDivId && $target.parents('#' + $.datepicker._mainDivId).length == 0 && !$target.hasClass($.datepicker.markerClassName) && !$target.closest("." + $.datepicker._triggerClass).length && $.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI) ) ) || ( $target.hasClass($.datepicker.markerClassName) && $.datepicker._curInst != inst ) ) $.datepicker._hideDatepicker(); }, /* Adjust one of the date sub-fields. */ _adjustDate: function(id, offset, period) { var target = $(id); var inst = this._getInst(target[0]); if (this._isDisabledDatepicker(target[0])) { return; } this._adjustInstDate(inst, offset + (period == 'M' ? this._get(inst, 'showCurrentAtPos') : 0), // undo positioning period); this._updateDatepicker(inst); }, /* Action for current link. */ _gotoToday: function(id) { var target = $(id); var inst = this._getInst(target[0]); if (this._get(inst, 'gotoCurrent') && inst.currentDay) { inst.selectedDay = inst.currentDay; inst.drawMonth = inst.selectedMonth = inst.currentMonth; inst.drawYear = inst.selectedYear = inst.currentYear; } else { var date = new Date(); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); } this._notifyChange(inst); this._adjustDate(target); }, /* Action for selecting a new month/year. */ _selectMonthYear: function(id, select, period) { var target = $(id); var inst = this._getInst(target[0]); inst['selected' + (period == 'M' ? 'Month' : 'Year')] = inst['draw' + (period == 'M' ? 'Month' : 'Year')] = parseInt(select.options[select.selectedIndex].value,10); this._notifyChange(inst); this._adjustDate(target); }, /* Action for selecting a day. */ _selectDay: function(id, month, year, td) { var target = $(id); if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) { return; } var inst = this._getInst(target[0]); inst.selectedDay = inst.currentDay = $('a', td).html(); inst.selectedMonth = inst.currentMonth = month; inst.selectedYear = inst.currentYear = year; this._selectDate(id, this._formatDate(inst, inst.currentDay, inst.currentMonth, inst.currentYear)); }, /* Erase the input field and hide the date picker. */ _clearDate: function(id) { var target = $(id); var inst = this._getInst(target[0]); this._selectDate(target, ''); }, /* Update the input field with the selected date. */ _selectDate: function(id, dateStr) { var target = $(id); var inst = this._getInst(target[0]); dateStr = (dateStr != null ? dateStr : this._formatDate(inst)); if (inst.input) inst.input.val(dateStr); this._updateAlternate(inst); var onSelect = this._get(inst, 'onSelect'); if (onSelect) onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback else if (inst.input) inst.input.trigger('change'); // fire the change event if (inst.inline) this._updateDatepicker(inst); else { this._hideDatepicker(); this._lastInput = inst.input[0]; if (typeof(inst.input[0]) != 'object') inst.input.focus(); // restore focus this._lastInput = null; } }, /* Update any alternate field to synchronise with the main field. */ _updateAlternate: function(inst) { var altField = this._get(inst, 'altField'); if (altField) { // update alternate field too var altFormat = this._get(inst, 'altFormat') || this._get(inst, 'dateFormat'); var date = this._getDate(inst); var dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst)); $(altField).each(function() { $(this).val(dateStr); }); } }, /* Set as beforeShowDay function to prevent selection of weekends. @param date Date - the date to customise @return [boolean, string] - is this date selectable?, what is its CSS class? */ noWeekends: function(date) { var day = date.getDay(); return [(day > 0 && day < 6), '']; }, /* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition. @param date Date - the date to get the week for @return number - the number of the week within the year that contains this date */ iso8601Week: function(date) { var checkDate = new Date(date.getTime()); // Find Thursday of this week starting on Monday checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); var time = checkDate.getTime(); checkDate.setMonth(0); // Compare with Jan 1 checkDate.setDate(1); return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1; }, /* Parse a string value into a date object. See formatDate below for the possible formats. @param format string - the expected format of the date @param value string - the date in the above format @param settings Object - attributes include: shortYearCutoff number - the cutoff year for determining the century (optional) dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) dayNames string[7] - names of the days from Sunday (optional) monthNamesShort string[12] - abbreviated names of the months (optional) monthNames string[12] - names of the months (optional) @return Date - the extracted date value or null if value is blank */ parseDate: function (format, value, settings) { if (format == null || value == null) throw 'Invalid arguments'; value = (typeof value == 'object' ? value.toString() : value + ''); if (value == '') return null; var shortYearCutoff = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff; shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff : new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10)); var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort; var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames; var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort; var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames; var year = -1; var month = -1; var day = -1; var doy = -1; var literal = false; // Check whether a format character is doubled var lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match); if (matches) iFormat++; return matches; }; // Extract a number from the string value var getNumber = function(match) { var isDoubled = lookAhead(match); var size = (match == '@' ? 14 : (match == '!' ? 20 : (match == 'y' && isDoubled ? 4 : (match == 'o' ? 3 : 2)))); var digits = new RegExp('^\\d{1,' + size + '}'); var num = value.substring(iValue).match(digits); if (!num) throw 'Missing number at position ' + iValue; iValue += num[0].length; return parseInt(num[0], 10); }; // Extract a name from the string value and convert to an index var getName = function(match, shortNames, longNames) { var names = $.map(lookAhead(match) ? longNames : shortNames, function (v, k) { return [ [k, v] ]; }).sort(function (a, b) { return -(a[1].length - b[1].length); }); var index = -1; $.each(names, function (i, pair) { var name = pair[1]; if (value.substr(iValue, name.length).toLowerCase() == name.toLowerCase()) { index = pair[0]; iValue += name.length; return false; } }); if (index != -1) return index + 1; else throw 'Unknown name at position ' + iValue; }; // Confirm that a literal character matches the string value var checkLiteral = function() { if (value.charAt(iValue) != format.charAt(iFormat)) throw 'Unexpected literal at position ' + iValue; iValue++; }; var iValue = 0; for (var iFormat = 0; iFormat < format.length; iFormat++) { if (literal) if (format.charAt(iFormat) == "'" && !lookAhead("'")) literal = false; else checkLiteral(); else switch (format.charAt(iFormat)) { case 'd': day = getNumber('d'); break; case 'D': getName('D', dayNamesShort, dayNames); break; case 'o': doy = getNumber('o'); break; case 'm': month = getNumber('m'); break; case 'M': month = getName('M', monthNamesShort, monthNames); break; case 'y': year = getNumber('y'); break; case '@': var date = new Date(getNumber('@')); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); break; case '!': var date = new Date((getNumber('!') - this._ticksTo1970) / 10000); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); break; case "'": if (lookAhead("'")) checkLiteral(); else literal = true; break; default: checkLiteral(); } } if (iValue < value.length){ var extra = value.substr(iValue); if (!/^\s+/.test(extra)) { throw "Extra/unparsed characters found in date: " + extra; } } if (year == -1) year = new Date().getFullYear(); else if (year < 100) year += new Date().getFullYear() - new Date().getFullYear() % 100 + (year <= shortYearCutoff ? 0 : -100); if (doy > -1) { month = 1; day = doy; do { var dim = this._getDaysInMonth(year, month - 1); if (day <= dim) break; month++; day -= dim; } while (true); } var date = this._daylightSavingAdjust(new Date(year, month - 1, day)); if (date.getFullYear() != year || date.getMonth() + 1 != month || date.getDate() != day) throw 'Invalid date'; // E.g. 31/02/00 return date; }, /* Standard date formats. */ ATOM: 'yy-mm-dd', // RFC 3339 (ISO 8601) COOKIE: 'D, dd M yy', ISO_8601: 'yy-mm-dd', RFC_822: 'D, d M y', RFC_850: 'DD, dd-M-y', RFC_1036: 'D, d M y', RFC_1123: 'D, d M yy', RFC_2822: 'D, d M yy', RSS: 'D, d M y', // RFC 822 TICKS: '!', TIMESTAMP: '@', W3C: 'yy-mm-dd', // ISO 8601 _ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) + Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000), /* Format a date object into a string value. The format can be combinations of the following: d - day of month (no leading zero) dd - day of month (two digit) o - day of year (no leading zeros) oo - day of year (three digit) D - day name short DD - day name long m - month of year (no leading zero) mm - month of year (two digit) M - month name short MM - month name long y - year (two digit) yy - year (four digit) @ - Unix timestamp (ms since 01/01/1970) ! - Windows ticks (100ns since 01/01/0001) '...' - literal text '' - single quote @param format string - the desired format of the date @param date Date - the date value to format @param settings Object - attributes include: dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) dayNames string[7] - names of the days from Sunday (optional) monthNamesShort string[12] - abbreviated names of the months (optional) monthNames string[12] - names of the months (optional) @return string - the date in the above format */ formatDate: function (format, date, settings) { if (!date) return ''; var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort; var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames; var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort; var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames; // Check whether a format character is doubled var lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match); if (matches) iFormat++; return matches; }; // Format a number, with leading zero if necessary var formatNumber = function(match, value, len) { var num = '' + value; if (lookAhead(match)) while (num.length < len) num = '0' + num; return num; }; // Format a name, short or long as requested var formatName = function(match, value, shortNames, longNames) { return (lookAhead(match) ? longNames[value] : shortNames[value]); }; var output = ''; var literal = false; if (date) for (var iFormat = 0; iFormat < format.length; iFormat++) { if (literal) if (format.charAt(iFormat) == "'" && !lookAhead("'")) literal = false; else output += format.charAt(iFormat); else switch (format.charAt(iFormat)) { case 'd': output += formatNumber('d', date.getDate(), 2); break; case 'D': output += formatName('D', date.getDay(), dayNamesShort, dayNames); break; case 'o': output += formatNumber('o', Math.round((new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000), 3); break; case 'm': output += formatNumber('m', date.getMonth() + 1, 2); break; case 'M': output += formatName('M', date.getMonth(), monthNamesShort, monthNames); break; case 'y': output += (lookAhead('y') ? date.getFullYear() : (date.getYear() % 100 < 10 ? '0' : '') + date.getYear() % 100); break; case '@': output += date.getTime(); break; case '!': output += date.getTime() * 10000 + this._ticksTo1970; break; case "'": if (lookAhead("'")) output += "'"; else literal = true; break; default: output += format.charAt(iFormat); } } return output; }, /* Extract all possible characters from the date format. */ _possibleChars: function (format) { var chars = ''; var literal = false; // Check whether a format character is doubled var lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match); if (matches) iFormat++; return matches; }; for (var iFormat = 0; iFormat < format.length; iFormat++) if (literal) if (format.charAt(iFormat) == "'" && !lookAhead("'")) literal = false; else chars += format.charAt(iFormat); else switch (format.charAt(iFormat)) { case 'd': case 'm': case 'y': case '@': chars += '0123456789'; break; case 'D': case 'M': return null; // Accept anything case "'": if (lookAhead("'")) chars += "'"; else literal = true; break; default: chars += format.charAt(iFormat); } return chars; }, /* Get a setting value, defaulting if necessary. */ _get: function(inst, name) { return inst.settings[name] !== undefined ? inst.settings[name] : this._defaults[name]; }, /* Parse existing date and initialise date picker. */ _setDateFromField: function(inst, noDefault) { if (inst.input.val() == inst.lastVal) { return; } var dateFormat = this._get(inst, 'dateFormat'); var dates = inst.lastVal = inst.input ? inst.input.val() : null; var date, defaultDate; date = defaultDate = this._getDefaultDate(inst); var settings = this._getFormatConfig(inst); try { date = this.parseDate(dateFormat, dates, settings) || defaultDate; } catch (event) { this.log(event); dates = (noDefault ? '' : dates); } inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); inst.currentDay = (dates ? date.getDate() : 0); inst.currentMonth = (dates ? date.getMonth() : 0); inst.currentYear = (dates ? date.getFullYear() : 0); this._adjustInstDate(inst); }, /* Retrieve the default date shown on opening. */ _getDefaultDate: function(inst) { return this._restrictMinMax(inst, this._determineDate(inst, this._get(inst, 'defaultDate'), new Date())); }, /* A date may be specified as an exact value or a relative one. */ _determineDate: function(inst, date, defaultDate) { var offsetNumeric = function(offset) { var date = new Date(); date.setDate(date.getDate() + offset); return date; }; var offsetString = function(offset) { try { return $.datepicker.parseDate($.datepicker._get(inst, 'dateFormat'), offset, $.datepicker._getFormatConfig(inst)); } catch (e) { // Ignore } var date = (offset.toLowerCase().match(/^c/) ? $.datepicker._getDate(inst) : null) || new Date(); var year = date.getFullYear(); var month = date.getMonth(); var day = date.getDate(); var pattern = /([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g; var matches = pattern.exec(offset); while (matches) { switch (matches[2] || 'd') { case 'd' : case 'D' : day += parseInt(matches[1],10); break; case 'w' : case 'W' : day += parseInt(matches[1],10) * 7; break; case 'm' : case 'M' : month += parseInt(matches[1],10); day = Math.min(day, $.datepicker._getDaysInMonth(year, month)); break; case 'y': case 'Y' : year += parseInt(matches[1],10); day = Math.min(day, $.datepicker._getDaysInMonth(year, month)); break; } matches = pattern.exec(offset); } return new Date(year, month, day); }; var newDate = (date == null || date === '' ? defaultDate : (typeof date == 'string' ? offsetString(date) : (typeof date == 'number' ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : new Date(date.getTime())))); newDate = (newDate && newDate.toString() == 'Invalid Date' ? defaultDate : newDate); if (newDate) { newDate.setHours(0); newDate.setMinutes(0); newDate.setSeconds(0); newDate.setMilliseconds(0); } return this._daylightSavingAdjust(newDate); }, /* Handle switch to/from daylight saving. Hours may be non-zero on daylight saving cut-over: > 12 when midnight changeover, but then cannot generate midnight datetime, so jump to 1AM, otherwise reset. @param date (Date) the date to check @return (Date) the corrected date */ _daylightSavingAdjust: function(date) { if (!date) return null; date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0); return date; }, /* Set the date(s) directly. */ _setDate: function(inst, date, noChange) { var clear = !date; var origMonth = inst.selectedMonth; var origYear = inst.selectedYear; var newDate = this._restrictMinMax(inst, this._determineDate(inst, date, new Date())); inst.selectedDay = inst.currentDay = newDate.getDate(); inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth(); inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear(); if ((origMonth != inst.selectedMonth || origYear != inst.selectedYear) && !noChange) this._notifyChange(inst); this._adjustInstDate(inst); if (inst.input) { inst.input.val(clear ? '' : this._formatDate(inst)); } }, /* Retrieve the date(s) directly. */ _getDate: function(inst) { var startDate = (!inst.currentYear || (inst.input && inst.input.val() == '') ? null : this._daylightSavingAdjust(new Date( inst.currentYear, inst.currentMonth, inst.currentDay))); return startDate; }, /* Attach the onxxx handlers. These are declared statically so * they work with static code transformers like Caja. */ _attachHandlers: function(inst) { var stepMonths = this._get(inst, 'stepMonths'); var id = '#' + inst.id.replace( /\\\\/g, "\\" ); inst.dpDiv.find('[data-handler]').map(function () { var handler = { prev: function () { window['DP_jQuery_' + dpuuid].datepicker._adjustDate(id, -stepMonths, 'M'); }, next: function () { window['DP_jQuery_' + dpuuid].datepicker._adjustDate(id, +stepMonths, 'M'); }, hide: function () { window['DP_jQuery_' + dpuuid].datepicker._hideDatepicker(); }, today: function () { window['DP_jQuery_' + dpuuid].datepicker._gotoToday(id); }, selectDay: function () { window['DP_jQuery_' + dpuuid].datepicker._selectDay(id, +this.getAttribute('data-month'), +this.getAttribute('data-year'), this); return false; }, selectMonth: function () { window['DP_jQuery_' + dpuuid].datepicker._selectMonthYear(id, this, 'M'); return false; }, selectYear: function () { window['DP_jQuery_' + dpuuid].datepicker._selectMonthYear(id, this, 'Y'); return false; } }; $(this).bind(this.getAttribute('data-event'), handler[this.getAttribute('data-handler')]); }); }, /* Generate the HTML for the current state of the date picker. */ _generateHTML: function(inst) { var today = new Date(); today = this._daylightSavingAdjust( new Date(today.getFullYear(), today.getMonth(), today.getDate())); // clear time var isRTL = this._get(inst, 'isRTL'); var showButtonPanel = this._get(inst, 'showButtonPanel'); var hideIfNoPrevNext = this._get(inst, 'hideIfNoPrevNext'); var navigationAsDateFormat = this._get(inst, 'navigationAsDateFormat'); var numMonths = this._getNumberOfMonths(inst); var showCurrentAtPos = this._get(inst, 'showCurrentAtPos'); var stepMonths = this._get(inst, 'stepMonths'); var isMultiMonth = (numMonths[0] != 1 || numMonths[1] != 1); var currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) : new Date(inst.currentYear, inst.currentMonth, inst.currentDay))); var minDate = this._getMinMaxDate(inst, 'min'); var maxDate = this._getMinMaxDate(inst, 'max'); var drawMonth = inst.drawMonth - showCurrentAtPos; var drawYear = inst.drawYear; if (drawMonth < 0) { drawMonth += 12; drawYear--; } if (maxDate) { var maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(), maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate())); maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw); while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) { drawMonth--; if (drawMonth < 0) { drawMonth = 11; drawYear--; } } } inst.drawMonth = drawMonth; inst.drawYear = drawYear; var prevText = this._get(inst, 'prevText'); prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText, this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)), this._getFormatConfig(inst))); var prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ? '<a class="ui-datepicker-prev ui-corner-all" data-handler="prev" data-event="click"' + ' title="' + prevText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>' : (hideIfNoPrevNext ? '' : '<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+ prevText +'"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>')); var nextText = this._get(inst, 'nextText'); nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText, this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)), this._getFormatConfig(inst))); var next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ? '<a class="ui-datepicker-next ui-corner-all" data-handler="next" data-event="click"' + ' title="' + nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>' : (hideIfNoPrevNext ? '' : '<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+ nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>')); var currentText = this._get(inst, 'currentText'); var gotoDate = (this._get(inst, 'gotoCurrent') && inst.currentDay ? currentDate : today); currentText = (!navigationAsDateFormat ? currentText : this.formatDate(currentText, gotoDate, this._getFormatConfig(inst))); var controls = (!inst.inline ? '<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" data-handler="hide" data-event="click">' + this._get(inst, 'closeText') + '</button>' : ''); var buttonPanel = (showButtonPanel) ? '<div class="ui-datepicker-buttonpane ui-widget-content">' + (isRTL ? controls : '') + (this._isInRange(inst, gotoDate) ? '<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" data-handler="today" data-event="click"' + '>' + currentText + '</button>' : '') + (isRTL ? '' : controls) + '</div>' : ''; var firstDay = parseInt(this._get(inst, 'firstDay'),10); firstDay = (isNaN(firstDay) ? 0 : firstDay); var showWeek = this._get(inst, 'showWeek'); var dayNames = this._get(inst, 'dayNames'); var dayNamesShort = this._get(inst, 'dayNamesShort'); var dayNamesMin = this._get(inst, 'dayNamesMin'); var monthNames = this._get(inst, 'monthNames'); var monthNamesShort = this._get(inst, 'monthNamesShort'); var beforeShowDay = this._get(inst, 'beforeShowDay'); var showOtherMonths = this._get(inst, 'showOtherMonths'); var selectOtherMonths = this._get(inst, 'selectOtherMonths'); var calculateWeek = this._get(inst, 'calculateWeek') || this.iso8601Week; var defaultDate = this._getDefaultDate(inst); var html = ''; for (var row = 0; row < numMonths[0]; row++) { var group = ''; this.maxRows = 4; for (var col = 0; col < numMonths[1]; col++) { var selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay)); var cornerClass = ' ui-corner-all'; var calender = ''; if (isMultiMonth) { calender += '<div class="ui-datepicker-group'; if (numMonths[1] > 1) switch (col) { case 0: calender += ' ui-datepicker-group-first'; cornerClass = ' ui-corner-' + (isRTL ? 'right' : 'left'); break; case numMonths[1]-1: calender += ' ui-datepicker-group-last'; cornerClass = ' ui-corner-' + (isRTL ? 'left' : 'right'); break; default: calender += ' ui-datepicker-group-middle'; cornerClass = ''; break; } calender += '">'; } calender += '<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix' + cornerClass + '">' + (/all|left/.test(cornerClass) && row == 0 ? (isRTL ? next : prev) : '') + (/all|right/.test(cornerClass) && row == 0 ? (isRTL ? prev : next) : '') + this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate, row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers '</div><table class="ui-datepicker-calendar"><thead>' + '<tr>'; var thead = (showWeek ? '<th class="ui-datepicker-week-col">' + this._get(inst, 'weekHeader') + '</th>' : ''); for (var dow = 0; dow < 7; dow++) { // days of the week var day = (dow + firstDay) % 7; thead += '<th' + ((dow + firstDay + 6) % 7 >= 5 ? ' class="ui-datepicker-week-end"' : '') + '>' + '<span title="' + dayNames[day] + '">' + dayNamesMin[day] + '</span></th>'; } calender += thead + '</tr></thead><tbody>'; var daysInMonth = this._getDaysInMonth(drawYear, drawMonth); if (drawYear == inst.selectedYear && drawMonth == inst.selectedMonth) inst.selectedDay = Math.min(inst.selectedDay, daysInMonth); var leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7; var curRows = Math.ceil((leadDays + daysInMonth) / 7); // calculate the number of rows to generate var numRows = (isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows); //If multiple months, use the higher number of rows (see #7043) this.maxRows = numRows; var printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays)); for (var dRow = 0; dRow < numRows; dRow++) { // create date picker rows calender += '<tr>'; var tbody = (!showWeek ? '' : '<td class="ui-datepicker-week-col">' + this._get(inst, 'calculateWeek')(printDate) + '</td>'); for (var dow = 0; dow < 7; dow++) { // create date picker days var daySettings = (beforeShowDay ? beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, '']); var otherMonth = (printDate.getMonth() != drawMonth); var unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] || (minDate && printDate < minDate) || (maxDate && printDate > maxDate); tbody += '<td class="' + ((dow + firstDay + 6) % 7 >= 5 ? ' ui-datepicker-week-end' : '') + // highlight weekends (otherMonth ? ' ui-datepicker-other-month' : '') + // highlight days from other months ((printDate.getTime() == selectedDate.getTime() && drawMonth == inst.selectedMonth && inst._keyEvent) || // user pressed key (defaultDate.getTime() == printDate.getTime() && defaultDate.getTime() == selectedDate.getTime()) ? // or defaultDate is current printedDate and defaultDate is selectedDate ' ' + this._dayOverClass : '') + // highlight selected day (unselectable ? ' ' + this._unselectableClass + ' ui-state-disabled': '') + // highlight unselectable days (otherMonth && !showOtherMonths ? '' : ' ' + daySettings[1] + // highlight custom dates (printDate.getTime() == currentDate.getTime() ? ' ' + this._currentClass : '') + // highlight selected day (printDate.getTime() == today.getTime() ? ' ui-datepicker-today' : '')) + '"' + // highlight today (if different) ((!otherMonth || showOtherMonths) && daySettings[2] ? ' title="' + daySettings[2] + '"' : '') + // cell title (unselectable ? '' : ' data-handler="selectDay" data-event="click" data-month="' + printDate.getMonth() + '" data-year="' + printDate.getFullYear() + '"') + '>' + // actions (otherMonth && !showOtherMonths ? '&#xa0;' : // display for other months (unselectable ? '<span class="ui-state-default">' + printDate.getDate() + '</span>' : '<a class="ui-state-default' + (printDate.getTime() == today.getTime() ? ' ui-state-highlight' : '') + (printDate.getTime() == currentDate.getTime() ? ' ui-state-active' : '') + // highlight selected day (otherMonth ? ' ui-priority-secondary' : '') + // distinguish dates from other months '" href="#">' + printDate.getDate() + '</a>')) + '</td>'; // display selectable date printDate.setDate(printDate.getDate() + 1); printDate = this._daylightSavingAdjust(printDate); } calender += tbody + '</tr>'; } drawMonth++; if (drawMonth > 11) { drawMonth = 0; drawYear++; } calender += '</tbody></table>' + (isMultiMonth ? '</div>' + ((numMonths[0] > 0 && col == numMonths[1]-1) ? '<div class="ui-datepicker-row-break"></div>' : '') : ''); group += calender; } html += group; } html += buttonPanel + ($.ui.ie6 && !inst.inline ? '<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>' : ''); inst._keyEvent = false; return html; }, /* Generate the month and year header. */ _generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate, secondary, monthNames, monthNamesShort) { var changeMonth = this._get(inst, 'changeMonth'); var changeYear = this._get(inst, 'changeYear'); var showMonthAfterYear = this._get(inst, 'showMonthAfterYear'); var html = '<div class="ui-datepicker-title">'; var monthHtml = ''; // month selection if (secondary || !changeMonth) monthHtml += '<span class="ui-datepicker-month">' + monthNames[drawMonth] + '</span>'; else { var inMinYear = (minDate && minDate.getFullYear() == drawYear); var inMaxYear = (maxDate && maxDate.getFullYear() == drawYear); monthHtml += '<select class="ui-datepicker-month" data-handler="selectMonth" data-event="change">'; for (var month = 0; month < 12; month++) { if ((!inMinYear || month >= minDate.getMonth()) && (!inMaxYear || month <= maxDate.getMonth())) monthHtml += '<option value="' + month + '"' + (month == drawMonth ? ' selected="selected"' : '') + '>' + monthNamesShort[month] + '</option>'; } monthHtml += '</select>'; } if (!showMonthAfterYear) html += monthHtml + (secondary || !(changeMonth && changeYear) ? '&#xa0;' : ''); // year selection if ( !inst.yearshtml ) { inst.yearshtml = ''; if (secondary || !changeYear) html += '<span class="ui-datepicker-year">' + drawYear + '</span>'; else { // determine range of years to display var years = this._get(inst, 'yearRange').split(':'); var thisYear = new Date().getFullYear(); var determineYear = function(value) { var year = (value.match(/c[+-].*/) ? drawYear + parseInt(value.substring(1), 10) : (value.match(/[+-].*/) ? thisYear + parseInt(value, 10) : parseInt(value, 10))); return (isNaN(year) ? thisYear : year); }; var year = determineYear(years[0]); var endYear = Math.max(year, determineYear(years[1] || '')); year = (minDate ? Math.max(year, minDate.getFullYear()) : year); endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear); inst.yearshtml += '<select class="ui-datepicker-year" data-handler="selectYear" data-event="change">'; for (; year <= endYear; year++) { inst.yearshtml += '<option value="' + year + '"' + (year == drawYear ? ' selected="selected"' : '') + '>' + year + '</option>'; } inst.yearshtml += '</select>'; html += inst.yearshtml; inst.yearshtml = null; } } html += this._get(inst, 'yearSuffix'); if (showMonthAfterYear) html += (secondary || !(changeMonth && changeYear) ? '&#xa0;' : '') + monthHtml; html += '</div>'; // Close datepicker_header return html; }, /* Adjust one of the date sub-fields. */ _adjustInstDate: function(inst, offset, period) { var year = inst.drawYear + (period == 'Y' ? offset : 0); var month = inst.drawMonth + (period == 'M' ? offset : 0); var day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + (period == 'D' ? offset : 0); var date = this._restrictMinMax(inst, this._daylightSavingAdjust(new Date(year, month, day))); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); if (period == 'M' || period == 'Y') this._notifyChange(inst); }, /* Ensure a date is within any min/max bounds. */ _restrictMinMax: function(inst, date) { var minDate = this._getMinMaxDate(inst, 'min'); var maxDate = this._getMinMaxDate(inst, 'max'); var newDate = (minDate && date < minDate ? minDate : date); newDate = (maxDate && newDate > maxDate ? maxDate : newDate); return newDate; }, /* Notify change of month/year. */ _notifyChange: function(inst) { var onChange = this._get(inst, 'onChangeMonthYear'); if (onChange) onChange.apply((inst.input ? inst.input[0] : null), [inst.selectedYear, inst.selectedMonth + 1, inst]); }, /* Determine the number of months to show. */ _getNumberOfMonths: function(inst) { var numMonths = this._get(inst, 'numberOfMonths'); return (numMonths == null ? [1, 1] : (typeof numMonths == 'number' ? [1, numMonths] : numMonths)); }, /* Determine the current maximum date - ensure no time components are set. */ _getMinMaxDate: function(inst, minMax) { return this._determineDate(inst, this._get(inst, minMax + 'Date'), null); }, /* Find the number of days in a given month. */ _getDaysInMonth: function(year, month) { return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate(); }, /* Find the day of the week of the first of a month. */ _getFirstDayOfMonth: function(year, month) { return new Date(year, month, 1).getDay(); }, /* Determines if we should allow a "next/prev" month display change. */ _canAdjustMonth: function(inst, offset, curYear, curMonth) { var numMonths = this._getNumberOfMonths(inst); var date = this._daylightSavingAdjust(new Date(curYear, curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1)); if (offset < 0) date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth())); return this._isInRange(inst, date); }, /* Is the given date in the accepted range? */ _isInRange: function(inst, date) { var minDate = this._getMinMaxDate(inst, 'min'); var maxDate = this._getMinMaxDate(inst, 'max'); return ((!minDate || date.getTime() >= minDate.getTime()) && (!maxDate || date.getTime() <= maxDate.getTime())); }, /* Provide the configuration settings for formatting/parsing. */ _getFormatConfig: function(inst) { var shortYearCutoff = this._get(inst, 'shortYearCutoff'); shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff : new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10)); return {shortYearCutoff: shortYearCutoff, dayNamesShort: this._get(inst, 'dayNamesShort'), dayNames: this._get(inst, 'dayNames'), monthNamesShort: this._get(inst, 'monthNamesShort'), monthNames: this._get(inst, 'monthNames')}; }, /* Format the given date for display. */ _formatDate: function(inst, day, month, year) { if (!day) { inst.currentDay = inst.selectedDay; inst.currentMonth = inst.selectedMonth; inst.currentYear = inst.selectedYear; } var date = (day ? (typeof day == 'object' ? day : this._daylightSavingAdjust(new Date(year, month, day))) : this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay))); return this.formatDate(this._get(inst, 'dateFormat'), date, this._getFormatConfig(inst)); } }); /* * Bind hover events for datepicker elements. * Done via delegate so the binding only occurs once in the lifetime of the parent div. * Global instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker. */ function bindHover(dpDiv) { var selector = 'button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a'; return dpDiv.delegate(selector, 'mouseout', function() { $(this).removeClass('ui-state-hover'); if (this.className.indexOf('ui-datepicker-prev') != -1) $(this).removeClass('ui-datepicker-prev-hover'); if (this.className.indexOf('ui-datepicker-next') != -1) $(this).removeClass('ui-datepicker-next-hover'); }) .delegate(selector, 'mouseover', function(){ if (!$.datepicker._isDisabledDatepicker( instActive.inline ? dpDiv.parent()[0] : instActive.input[0])) { $(this).parents('.ui-datepicker-calendar').find('a').removeClass('ui-state-hover'); $(this).addClass('ui-state-hover'); if (this.className.indexOf('ui-datepicker-prev') != -1) $(this).addClass('ui-datepicker-prev-hover'); if (this.className.indexOf('ui-datepicker-next') != -1) $(this).addClass('ui-datepicker-next-hover'); } }); } /* jQuery extend now ignores nulls! */ function extendRemove(target, props) { $.extend(target, props); for (var name in props) if (props[name] == null || props[name] == undefined) target[name] = props[name]; return target; }; /* Invoke the datepicker functionality. @param options string - a command, optionally followed by additional parameters or Object - settings for attaching new datepicker functionality @return jQuery object */ $.fn.datepicker = function(options){ /* Verify an empty collection wasn't passed - Fixes #6976 */ if ( !this.length ) { return this; } /* Initialise the date picker. */ if (!$.datepicker.initialized) { $(document).mousedown($.datepicker._checkExternalClick). find(document.body).append($.datepicker.dpDiv); $.datepicker.initialized = true; } var otherArgs = Array.prototype.slice.call(arguments, 1); if (typeof options == 'string' && (options == 'isDisabled' || options == 'getDate' || options == 'widget')) return $.datepicker['_' + options + 'Datepicker']. apply($.datepicker, [this[0]].concat(otherArgs)); if (options == 'option' && arguments.length == 2 && typeof arguments[1] == 'string') return $.datepicker['_' + options + 'Datepicker']. apply($.datepicker, [this[0]].concat(otherArgs)); return this.each(function() { typeof options == 'string' ? $.datepicker['_' + options + 'Datepicker']. apply($.datepicker, [this].concat(otherArgs)) : $.datepicker._attachDatepicker(this, options); }); }; $.datepicker = new Datepicker(); // singleton instance $.datepicker.initialized = false; $.datepicker.uuid = new Date().getTime(); $.datepicker.version = "1.9.2"; // Workaround for #4055 // Add another global to avoid noConflict issues with inline event handlers window['DP_jQuery_' + dpuuid] = $; })(jQuery);
require({cache:{ 'sbt/connections/BlogService':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * The Blogs API allows application programs to retrieve blog information, subscribe to blog updates, and create or modify blogs. * * @module sbt.connections.BlogService */ define([ "../declare", "../config", "../lang", "../stringUtil", "../Promise", "./BlogConstants", "./ConnectionsService", "../base/AtomEntity", "../base/XmlDataHandler", "./Tag", "./BlogPost"], function(declare,config,lang,stringUtil,Promise,consts,ConnectionsService,AtomEntity,XmlDataHandler, Tag, BlogPost) { var BlogTmpl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><entry xmlns=\"http://www.w3.org/2005/Atom\" xmlns:app=\"http://www.w3.org/2007/app\" xmlns:thr=\"http://purl.org/syndication/thread/1.0\" xmlns:snx=\"http://www.ibm.com/xmlns/prod/sn\"><title type=\"text\">${getTitle}</title><snx:timezone>${getTimezone}</snx:timezone><snx:handle>${getHandle}</snx:handle><summary type=\"html\">${getSummary}</summary>${getTags}</entry>"; var BlogPostTmpl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><entry xmlns=\"http://www.w3.org/2005/Atom\" xmlns:app=\"http://www.w3.org/2007/app\" xmlns:thr=\"http://purl.org/syndication/thread/1.0\" xmlns:snx=\"http://www.ibm.com/xmlns/prod/sn\"><title type=\"text\">${getTitle}</title><content type=\"html\">${getContent}</content>${getTags}</entry>"; var BlogCommentTmpl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><entry xmlns=\"http://www.w3.org/2005/Atom\" xmlns:app=\"http://www.w3.org/2007/app\" xmlns:thr=\"http://purl.org/syndication/thread/1.0\" xmlns:snx=\"http://www.ibm.com/xmlns/prod/sn\"><content type=\"html\">${getContent}</content></entry>"; CategoryTmpl = "<category term=\"${tag}\"></category>"; var CategoryBlog = "<category term=\"blog\" scheme=\"http://www.ibm.com/xmlns/prod/sn/type\"></category>"; var CategoryPerson = "<category term=\"person\" scheme=\"http://www.ibm.com/xmlns/prod/sn/type\"></category>"; /** * Blog class represents an entry for a Blogs feed returned by the * Connections REST API. * * @class Blog * @namespace sbt.connections */ var Blog = declare(AtomEntity, { xpath : consts.BlogXPath, namespaces : consts.BlogNamespaces, categoryScheme : CategoryBlog, /** * Construct a Blog entity. * * @constructor * @param args */ constructor : function(args) { }, /** * Return the value of IBM Connections blog handle from blog ATOM * entry document. * * @method getHandle * @return {String} handle of the blog */ getHandle : function() { return this.getAsString("handle"); }, /** * Sets Handle of IBM Connections blog. * * @method setHandle * @param {String} setHandle of the blog */ setHandle : function(handle) { return this.setAsString("handle", handle); }, /** * Return the value of IBM Connections blog ID from blog ATOM * entry document. * * @method getBlogUuid * @return {String} ID of the blog */ getBlogUuid : function() { var blogUuidPrefix = "urn:lsid:ibm.com:blogs:blog-"; var blogUuid = this.getAsString("blogUuid"); if(blogUuid && blogUuid.indexOf(blogUuidPrefix) != -1){ blogUuid = blogUuid.substring(blogUuidPrefix.length, blogUuid.length); } return blogUuid; }, /** * Sets id of IBM Connections blog. * * @method setBlogUuid * @param {String} blogUuid of the blog */ setBlogUuid : function(blogUuid) { return this.setAsString("blogUuid", blogUuid); }, /** * Return the value of IBM Connections blog URL from blog ATOM * entry document. * * @method getBlogUrl * @return {String} Blog URL of the blog */ getBlogUrl : function() { return this.getAsString("alternateUrl"); }, /** * Return tags of IBM Connections blog * document. * * @method getTags * @return {Object} Array of tags of the blog */ getTags : function() { return this.getAsArray("tags"); }, /** * Set new tags to be associated with this IBM Connections blog. * * @method setTags * @param {Object} Array of tags to be added to the blog */ setTags : function(tags) { return this.setAsArray("tags", tags); }, /** * Return the value of IBM Connections blog's community id from blog ATOM * entry document. Only valid for Ideation Blog and community blog * * @method getCommunityUuid * @return {String} Blog Container URL of the blog */ getCommunityUuid : function() { return this.getAsString("communityUuid"); }, /** * Return the value of IBM Connections blog's container url from blog ATOM * entry document. Only valid for Ideation Blog * * @method getContainerUrl * @return {String} Blog Container URL of the blog */ getContainerUrl : function() { return this.getAsString("containerUrl"); }, /** * Return the value of IBM Connections blog's container type from blog ATOM * entry document. Only valid for Ideation Blog * * @method getContainerType * @return {String} Blog Container type of the blog */ getContainerType : function() { return this.getAsString("containerType"); }, /** * Return all flags of IBM Connections blog ATOM entry document. Only valid * for Ideation Blog * * @method getCategoryFlags * @return {Object} Array of all flags of the blog */ getCategoryFlags : function() { return this.getAsArray("categoryFlags"); }, /** * Loads the blog object with the atom entry associated with the * blog. By default, a network call is made to load the atom entry * document in the blog object. * * @method load * @param {Object} [args] Argument object */ load : function(args) { // detect a bad request by validating required arguments var blogUuid = this.getBlogUuid(); var promise = this.service._validateBlogUuid(blogUuid); if (promise) { return promise; } var self = this; var callbacks = { createEntity : function(service,data,response) { self.setDataHandler(new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.BlogXPath })); return self; } }; var requestArgs = lang.mixin({}, args || {}); var options = { handleAs : "text", query : requestArgs }; var url = null; url = this.service._constructBlogsUrl(consts.AtomBlogInstance, { blogUuid : blogUuid }); return this.service.getEntity(url, options, blogUuid, callbacks); }, /** * Remove this blog * * @method remove * @param {Object} [args] Argument object */ remove : function(args) { return this.service.deleteBlog(this.getBlogUuid(), args); }, /** * Update this blog * * @method update * @param {Object} [args] Argument object */ update : function(args) { return this.service.updateBlog(this, args); }, /** * Save this blog * * @method save * @param {Object} [args] Argument object */ save : function(args) { if (this.getBlogUuid()) { return this.service.updateBlog(this, args); } else { return this.service.createBlog(this, args); } } }); /** * Comment class represents a comment on a Blogs post returned by the * Connections REST API. * * @class Comment * @namespace sbt.connections */ var Comment = declare(AtomEntity, { xpath : consts.CommentXPath, namespaces : consts.BlogNamespaces, /** * Construct a Blog Post Comment. * * @constructor * @param args */ constructor : function(args) { }, /** * Return the value of IBM Connections blog post comment id * entry document. * * @method getCommentUuid * @return {String} id of the blog post comment */ getCommentUuid : function() { var commentUuidPrefix = "urn:lsid:ibm.com:blogs:comment-"; var commentUuid = this.getAsString("commentUuid"); if(commentUuid && commentUuid.indexOf(commentUuidPrefix) != -1){ commentUuid = commentUuid.substring(commentUuidPrefix.length, commentUuid.length); } return commentUuid; }, /** * Sets id of IBM Connections blog post comment. * * @method setCommentUuid * @param {String} CommentUuid of the blog post */ setCommentUuid : function(CommentUuid) { return this.setAsString("CommentUuid", CommentUuid); }, /** * Return the last updated dateRecommendations URL of the IBM Connections blog post comment from * blog ATOM entry document. * * @method getRecommendationsURL * @return {String} Recommendations URL of the Blog Post comment */ getRecommendationsURL : function() { return this.getAsString("recommendationsUrl"); }, /** * Return the Recommendations count of the IBM Connections blog post comment from * blog ATOM entry document. * * @method getRecommendationsCount * @return {String} Number of recommendations for the Blog post comment */ getRecommendationsCount : function() { return this.getAsString("rankRecommendations"); }, /** * Return the get-reply-to of the IBM Connections blog post comment from * blog ATOM entry document. * * @method getReplyTo * @return {String} Entity Id of the entity in reply to which comment was created */ getReplyTo : function() { return this.getAsString("replyTo"); }, /** * Return the postUuid of the blog post on which comment was created. * * @method getPostUuid * @return {String} Blog post Id of the entity in reply to which comment was created */ getPostUuid : function() { var postUuid = this.getAsString("blogPostUuid"); if(postUuid){ return postUuid; } var postUuidPrefix = "urn:lsid:ibm.com:blogs:entry-"; postUuid = this.getAsString("replyTo"); if(postUuid && postUuid.indexOf(postUuidPrefix) != -1){ postUuid = postUuid.substring(postUuidPrefix.length, postUuid.length); } return postUuid; }, /** * Sets blog post id of IBM Connections blog post comment. * * @method setPostUuid * @param {String} blogPostUuid of the comment's blog post */ setPostUuid : function(blogPostUuid) { return this.setAsString("blogPostUuid", blogPostUuid); }, /** * Return the bloghandle of the blog post on which comment was created. * * @method getBlogHandle * @return {String} Blog handle of the entity in reply to which comment was created */ getBlogHandle : function() { var blogHandle = this.getAsString("blogHandle"); if(blogHandle){ return blogHandle; } var commentUrlAlternate = this.getAsString("alternateUrl"); var blogHandle = this.service._extractBlogHandle(commentUrlAlternate); return blogHandle; }, /** * Sets blog handle of IBM Connections blog post comment. * * @method setBlogHandle * @param {String} blogHandle of the comments's blog */ setBlogHandle : function(blogHandle) { this.setAsString("blogHandle", blogHandle); return this.setAsString("blogHandle", blogHandle); }, /** * Return the Trackback Title of the IBM Connections blog post comment from * blog ATOM entry document. * * @method getTrackbackTitle * @return {String} TrackbackTitle of the Blog post comment */ getTrackbackTitle : function() { return this.getAsDate("trackbacktitle"); }, /** * Gets an source of IBM Connections Blog post. * * @method getSource * @return {Object} Source of the blog post */ getSource : function() { return this.getAsObject([ "sourceId", "sourceTitle", "sourceLink", "sourceLinkAlternate" ]); }, /** * Loads the blog comment object associated with the * blog. By default, a network call is made to load the atom entry * document in the comment object. * * @method load * @param {Object} [args] Argument object */ load : function(blogHandle, commentUuid, args) { var promise = this.service._validateUuid(commentUuid); if (promise) { return promise; } var self = this; var callbacks = { createEntity : function(service,data,response) { self.setDataHandler(new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.CommentXPath })); return self; } }; var requestArgs = lang.mixin({}, args || {}); var options = { handleAs : "text", query : requestArgs }; var url = null; url = this.service.constructUrl(consts.AtomBlogCommentEditRemove, null, { blogHandle : blogHandle, commentUuid : commentUuid }); return this.service.getEntity(url, options, commentUuid, callbacks); }, /** * Remove this blog post comment * * @method remove * @param {Object} [args] Argument object */ remove : function(args) { return this.service.deleteComment(this.getCommentUuid(), args); }, /** * Save this blog post comment * * @method save * @param {Object} [args] Argument object */ save : function(args) { return this.service.createPost(this, args); } }); /** * Recommender class represents a recommender of a Blogs post returned by the * Connections REST API. * * @class Recommender * @namespace sbt.connections */ var Recommender = declare(AtomEntity, { xpath : consts.RecommendersXPath, categoryScheme : CategoryPerson, namespaces : consts.BlogNamespaces, /** * Construct a Blog Post Recommender. * * @constructor * @param args */ constructor : function(args) { }, /** * Return the value of IBM Connections blog post recommender id * * @method getRecommenderUuid * @return {String} id of the blog post recommender */ getRecommenderUuid : function() { var recommenderUuidPrefix = "urn:lsid:ibm.com:blogs:person-"; var recommenderUuid = this.getAsString("recommenderUuid"); if(recommenderUuid && recommenderUuid.indexOf(recommenderUuidPrefix) != -1){ recommenderUuid = recommenderUuid.substring(recommenderUuidPrefix.length, recommenderUuid.length); } return recommenderUuid; } }); /* * Callbacks used when reading a feed that contains blog entries. */ var ConnectionsBlogFeedCallbacks = { createEntities : function(service,data,response) { return new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.BlogFeedXPath }); }, createEntity : function(service,data,response) { return new Blog({ service : service, data : data }); } }; /* * Callbacks used when reading a feed that contains forum recommendation entries. */ var RecommendBlogPostCallbacks = { createEntities : function(service,data,response) { return new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.ForumsFeedXPath }); }, createEntity : function(service,data,response) { return new BlogPost({ service : service, data : data }); } }; /* * Callbacks used when reading a feed that contains blog entries. */ var ConnectionsTagsFeedCallbacks = { createEntities : function(service,data,response) { return new XmlDataHandler({ data : data, namespaces : consts.Namespaces, xpath : consts.TagsXPath }); }, createEntity : function(service,data,response) { var entryHandler = new XmlDataHandler({ data : data, namespaces : consts.Namespaces, xpath : consts.TagsXPath }); return new Tag({ service : service, id : entryHandler.getEntityId(), dataHandler : entryHandler }); } }; /* * Callbacks used when reading a feed that contains blog entries. */ var ConnectionsBlogPostsCallbacks = { createEntities : function(service,data,response) { return new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.BlogFeedXPath }); }, createEntity : function(service,data,response) { return new BlogPost({ service : service, data : data }); } }; /* * Callbacks used when reading a feed that contains blog entries. */ var ConnectionsBlogPostRecommendersCallbacks = { createEntities : function(service,data,response) { return new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, // xpath : consts.RecommendersFeedXpath xpath : consts.BlogFeedXPath }); }, createEntity : function(service,data,response) { return new Recommender({ service : service, data : data }); } }; /* * Callbacks used when reading a feed that contains blog entries. */ var ConnectionsBlogPostCommentsCallbacks = { createEntities : function(service,data,response) { return new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.BlogFeedXPath }); }, createEntity : function(service,data,response) { return new Comment({ service : service, data : data }); } }; /** * BlogService class. * * @class BlogService * @namespace sbt.connections */ var BlogService = declare(ConnectionsService, { contextRootMap: { blogs : "blogs" }, serviceName : "blogs", /** * Default blog homepage handle name if there is not one specified in sbt.properties. * @returns {String} */ handle : "homepage", /** * Constructor for BlogService * * @constructor * @param args */ constructor : function(args) { if (!this.endpoint) { this.endpoint = config.findEndpoint(this.getDefaultEndpointName()); } this.handle = this.endpoint.serviceMappings.blogHomepageHandle?this.endpoint.serviceMappings.blogHomepageHandle:this.handle; }, /** * Get the All Blogs feed to see a list of all blogs to which the * authenticated user has access. * * @method getAllBlogs * * @param {Object} [args] Object representing various parameters * that can be passed to get a feed of all blogs. The * parameters must be exactly as they are supported by IBM * Connections like ps, sortBy etc. */ getAllBlogs : function(args) { var options = { method : "GET", handleAs : "text", query : args || {} }; var url = null; url = this._constructBlogsUrl(consts.AtomBlogsAll); return this.getEntities(url, options, this.getBlogFeedCallbacks()); }, /** * Get the My Blogs feed to see a list of the blogs to which the * authenticated user is a member. * * @method getMyBlogs * @param {Object} [args] Object representing various parameters * that can be passed to get a feed of my blogs. The * parameters must be exactly as they are supported by IBM * Connections like ps, sortBy etc. */ getMyBlogs : function(args) { var options = { method : "GET", handleAs : "text", query : args || {} }; var url = null; url = this._constructBlogsUrl(consts.AtomBlogsMy); return this.getEntities(url, options, this.getBlogFeedCallbacks()); }, /** * Get the featured posts feed to find the blog posts that have had the most activity across * all of the blogs hosted by the Blogs application within the past two weeks * * @method getFeaturedBlogs * @param {Object} [args] Object representing various parameters * that can be passed to get a feed of my blogs. The * parameters must be exactly as they are supported by IBM * Connections like ps, sortBy etc. */ getFeaturedBlogs : function(args) { var options = { method : "GET", handleAs : "text", query : args || {} }; var url = null; url = this._constructBlogsUrl(consts.AtomBlogsFeatured); return this.getEntities(url, options, this.getBlogFeedCallbacks()); }, /** * Get the featured posts feed to find the blog posts that have had the most activity across * all of the blogs hosted by the Blogs application within the past two weeks * * @method getFeaturedPosts * @param {Object} [args] Object representing various parameters * that can be passed to get a feed of my blogs. The * parameters must be exactly as they are supported by IBM * Connections like ps, sortBy etc. */ getFeaturedPosts : function(args) { var options = { method : "GET", handleAs : "text", query : args || {} }; var url = null; url = this._constructBlogsUrl(consts.AtomBlogsPostsFeatured); return this.getEntities(url, options, this.getBlogPostsCallbacks()); }, /** * Get a feed that includes all of the recommended blog posts * in all of the blogs hosted by the Blogs application. * * @method getRecommendedPosts * @param {Object} [args] Object representing various parameters * that can be passed to get a feed of my blogs. The * parameters must be exactly as they are supported by IBM * Connections like ps, sortBy etc. */ getRecommendedPosts : function(args) { var options = { method : "GET", handleAs : "text", query : args || {} }; var url = null; url = this._constructBlogsUrl(consts.AtomBlogsPostsRecommended); return this.getEntities(url, options, this.getBlogPostsCallbacks()); }, /** * Get the blog posts feed to see a list of posts for all blog . * * @method getAllBlogPosts * @param {Object} [args] Object representing various parameters * that can be passed to get a feed of all blogs posts. The * parameters must be exactly as they are supported by IBM * Connections like ps, sortBy etc. */ getAllBlogPosts : function(args) { var options = { method : "GET", handleAs : "text", query : args || {} }; var url = null; url = this._constructBlogsUrl(consts.AtomEntriesAll); return this.getEntities(url, options, this.getBlogPostsCallbacks()); }, /** * Get the blog posts feed to see a list of posts for a blog . * * @method getBlogPosts * @param {String} blogHandle Handle of the blog of which posts are to be get. * @param {Object} [args] Object representing various parameters * that can be passed to get a feed of posts of a blog . The * parameters must be exactly as they are supported by IBM * Connections like ps, sortBy etc. */ getBlogPosts : function(blogHandle, args) { var options = { method : "GET", handleAs : "text", query : args || {} }; var url = null; url = this.constructUrl(consts.AtomBlogEntries, null, { blogHandle : blogHandle }); return this.getEntities(url, options, this.getBlogPostsCallbacks()); }, /** * Get the blog posts recommenders feed to see a list of recommenders of a blog post. * * @method getBlogPostRecommenders * @param {Object} object representing a blog post. * @param {Object} [args] Object representing various parameters * that can be passed to get a feed of posts of a blog . The * parameters must be exactly as they are supported by IBM * Connections like ps, sortBy etc. */ getBlogPostRecommenders : function(blogPost, args) { var post = this._toBlogPost(blogPost); var promise = this._validateBlogPost(post); if (promise) { return promise; } var options = { method : "GET", handleAs : "text", query : args || {} }; var url = null; url = this.constructUrl(consts.AtomRecommendBlogPost, null, { postUuid : post.getBlogPostUuid(), blogHandle : post.getBlogHandle() }); return this.getEntities(url, options, this.getBlogPostRecommendersCallbacks()); }, /** * Get the blog comments feed to see a list of comments for all blogs . * * @method getAllBlogComments * @param {Object} [args] Object representing various parameters * that can be passed to get a feed of posts of a blog . The * parameters must be exactly as they are supported by IBM * Connections like ps, sortBy etc. */ getAllBlogComments : function(args) { var options = { method : "GET", handleAs : "text", query : args || {} }; var url = null; url = this._constructBlogsUrl(consts.AtomBlogCommentsAll); return this.getEntities(url, options, this.getBlogPostCommentsCallbacks()); }, /** * Get the blog comments feed to see a list of comments for a blog post . * * @method getBlogPostComments * @param {blogHandle} Handle of the blog of which Comments are to be get * @param {Object} [args] Object representing various parameters * that can be passed to get a feed of posts of a blog . The * parameters must be exactly as they are supported by IBM * Connections like ps, sortBy etc. */ getBlogComments : function(blogHandle, args) { var options = { method : "GET", handleAs : "text", query : args || {} }; var url = null; url = this.constructUrl(consts.AtomBlogComments, null, { blogHandle : blogHandle }); return this.getEntities(url, options, this.getBlogPostCommentsCallbacks()); }, /** * Retrieve a blog instance. * * @method getBlog * @param {String } blogUuid * @param {Object} args Object containing the query arguments to be * sent (defined in IBM Connections Blogs REST API) */ getBlog : function(blogUuid, args) { var blog = new Blog({ service : this, _fields : { blogUuid : blogUuid } }); return blog.load(args); }, /** * Create a blog by sending an Atom entry document containing the * new blog. * * @method createBlog * @param {String/Object} blogOrJson Blog object which denotes the blog to be created. * @param {Object} [args] Argument object */ createBlog : function(blogOrJson,args) { var blog = this._toBlog(blogOrJson); var promise = this._validateBlog(blog, false, args); if (promise) { return promise; } var callbacks = {}; callbacks.createEntity = function(service,data,response) { if (data) { var dataHandler = new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.BlogXPath }); blog.setDataHandler(dataHandler); } blog.setData(data); return blog; }; var options = { method : "POST", query : args || {}, headers : consts.AtomXmlHeaders, data : this._constructBlogPostData(blog) }; var url = null; url = this._constructBlogsUrl(consts.AtomBlogCreate); return this.updateEntity(url, options, callbacks, args); }, /** * Update a blog by sending a replacement blog entry document * to the existing blog's edit web address. * All existing blog entry information will be replaced with the new data. To avoid * deleting all existing data, retrieve any data you want to retain first, and send it back * with this request. For example, if you want to add a new tag to a blog entry, retrieve * the existing tags, and send them all back with the new tag in the update request. * * @method updateBlog * @param {String/Object} blogOrJson Blog object * @param {Object} [args] Argument object */ updateBlog : function(blogOrJson,args) { var blog = this._toBlog(blogOrJson); var promise = this._validateBlog(blog, true, args); if (promise) { return promise; } var callbacks = {}; callbacks.createEntity = function(service,data,response) { var blogUuid = blog.getBlogUuid(); if (data) { var dataHandler = new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.BlogXPath }); blog.setDataHandler(dataHandler); } blog.setBlogUuid(blogUuid); return blog; }; var requestArgs = lang.mixin({}, args || {}); var options = { method : "PUT", query : requestArgs, headers : consts.AtomXmlHeaders, data : this._constructBlogPostData(blog) }; var blogUuid = blog.getBlogUuid(); var url = null; url = this._constructBlogsUrl(consts.AtomBlogEditDelete, { blogUuid : blogUuid }); return this.updateEntity(url, options, callbacks, args); }, /** * Delete a blog, use the HTTP DELETE method. * * @method deleteBlog * @param {String} blogUuid blog id of the blog or the blog object (of the blog to be deleted) * @param {Object} [args] Argument object */ deleteBlog : function(blogUuid,args) { var promise = this._validateBlogUuid(blogUuid); if (promise) { return promise; } var requestArgs = lang.mixin({}, args || {}); var options = { method : "DELETE", query : requestArgs, handleAs : "text" }; var url = null; url = this._constructBlogsUrl(consts.AtomBlogEditDelete, { blogUuid : blogUuid }); return this.deleteEntity(url, options, blogUuid); }, /** * Retrieve a blog post instance. * * @method getBlogPost * @param {String} blogPostUuid blog post id * @param {Object} args Object containing the query arguments to be * sent (defined in IBM Connections Blogs REST API) */ getBlogPost : function(blogPostUuid, args) { var blogPost = new BlogPost({ service : this, _fields : { postUuid : blogPostUuid } }); return blogPost.load(args); }, /** * Retrieve a list of comments for the specified entry in the specified blog. * * @method getEntryComments * @param {String} blogHandle blog handle * @param {String} entryAnchor entry anchor * @param {Object} args Object containing the query arguments to be * sent (defined in IBM Connections Blogs REST API) */ getEntryComments : function(blogHandle, entryAnchor, args) { var options = { method : "GET", handleAs : "text", query : args || {} }; var url = null; url = this.constructUrl(consts.AtomBlogEntryComments, null, { blogHandle : blogHandle, entryAnchor : entryAnchor }); return this.getEntities(url, options, this.getBlogPostCommentsCallbacks()); }, /** * Create a blog post by sending an Atom entry document containing the * new blog post. * * @method createPost * @param {String/Object} postOrJson Blog post object which denotes the blog post to be created. * @param {Object} [args] Argument object */ createPost : function(postOrJson, args) { var post = this._toBlogPost(postOrJson); var promise = this._validateBlog(post, false, args); if (promise) { return promise; } var callbacks = {}; callbacks.createEntity = function(service,data,response) { if (data) { var dataHandler = new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.BlogPostXPath }); post.setDataHandler(dataHandler); } post.setData(data); return post; }; var options = { method : "POST", query : args || {}, headers : consts.AtomXmlHeaders, data : this._constructBlogPostPostData(post) }; var url = null; url = this.constructUrl(consts.AtomBlogPostCreate, null, { blogHandle : postOrJson.getBlogHandle() }); return this.updateEntity(url, options, callbacks, args); }, /** * Update a post by sending a replacement post entry document * to the existing post's edit web address. * All existing post entry information will be replaced with the new data. To avoid * deleting all existing data, retrieve any data you want to retain first, and send it back * with this request. For example, if you want to add a new tag to a post entry, retrieve * the existing tags, and send them all back with the new tag in the update request. * * @method updateBost * @param {String/Object} BlogPost object * @param {Object} [args] Argument object */ updatePost : function(postOrJson, args) { var post = this._toBlogPost(postOrJson); var promise = this._validateBlogPost(post, true, args); if (promise) { return promise; } var callbacks = {}; callbacks.createEntity = function(service,data,response) { var postUuid = post.getBlogPostUuid(); if (data) { var dataHandler = new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.BlogPostXPath }); post.setDataHandler(dataHandler); } post.setBlogPostUuid(postUuid); return post; }; var requestArgs = lang.mixin({}, args || {}); var options = { method : "PUT", query : requestArgs, headers : consts.AtomXmlHeaders, data : this._constructBlogPostPostData(post) }; var url = null; url = this.constructUrl(consts.AtomBlogPostEditDelete, null, { postUuid : post.getBlogPostUuid(), blogHandle : post.getBlogHandle() }); return this.updateEntity(url, options, callbacks, args); }, /** * Recommend a post * * @method recommendPost * @param {String/Object} BlogPost object * @param {String} blogHandle Id of post */ recommendPost : function(blogPost) { var post = this._toBlogPost(blogPost); var promise = this._validateBlogPost(post); if (promise) { return promise; } var options = { method : "POST", headers : consts.AtomXmlHeaders }; var url = null; url = this.constructUrl(consts.AtomRecommendBlogPost, null, { postUuid : post.getBlogPostUuid(), blogHandle : post.getBlogHandle() }); return this.updateEntity(url, options, this.getRecommendBlogPostCallbacks()); }, /** * Unrecommend a post * * @method unRecommendPost * @param {String/Object} blogPost object * @param {String} blogHandle Id of post */ unrecommendPost : function(blogPost) { var post = this._toBlogPost(blogPost); var promise = this._validateBlogPost(post); if (promise) { return promise; } var options = { method : "DELETE", headers : consts.AtomXmlHeaders }; var url = null; url = this.constructUrl(consts.AtomRecommendBlogPost, null, { postUuid : post.getBlogPostUuid(), blogHandle : post.getBlogHandle() }); return this.deleteEntity(url, options, blogPost.getBlogPostUuid()); }, /** * Delete a blog post, use the HTTP DELETE method. * * @method deletePost * @param {String/Object} blogHandle handle of the blog(of which the post is to be deleted) * @param {String/Object} postUuid post id of the blog post(of the blog post to be deleted) * @param {Object} [args] Argument object */ deletePost : function(blogHandle, postUuid, args) { var promise = this._validateUuid(postUuid); if (promise) { return promise; } var requestArgs = lang.mixin({}, args || {}); var options = { method : "DELETE", query : requestArgs, handleAs : "text" }; var url = null; url = this.constructUrl(consts.AtomBlogPostEditDelete, null, { blogHandle : blogHandle, postUuid : postUuid }); return this.deleteEntity(url, options, postUuid); }, /** * Delete a blog comment, use the HTTP DELETE method. * * @method deleteComment * @param {String/Object} blogHandle handle of the blog(of which the post is to be deleted) * @param {String/Object} comment id of the blog comment(of the blog comment to be deleted) * @param {Object} [args] Argument object */ deleteComment : function(blogHandle, commentUuid, args) { var promise = this._validateUuid(commentUuid); if (promise) { return promise; } var requestArgs = lang.mixin({}, args || {}); var options = { method : "DELETE", query : requestArgs, handleAs : "text" }; var url = null; url = this.constructUrl(consts.AtomBlogCommentEditRemove, null, { blogHandle : blogHandle, commentUuid : commentUuid }); return this.deleteEntity(url, options, commentUuid); }, /** * Create a comment post by sending an Atom entry document containing the * new blog comment. * * @method createComment * @param {String/Object} commentOrJson Blog comment object. * @param {Object} [args] Argument object */ createComment : function(commentOrJson, args) { var comment = this._toComment(commentOrJson); var promise = this._validateComment(comment); if (promise) { return promise; } var callbacks = {}; callbacks.createEntity = function(service,data,response) { if (data) { var dataHandler = new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.CommentXPath }); comment.setDataHandler(dataHandler); } comment.setData(data); return comment; }; var options = { method : "POST", query : args || {}, headers : consts.AtomXmlHeaders, data : this._constructCommentBlogPostData(comment) }; var url = null; url = this.constructUrl(consts.AtomBlogCommentCreate, null, { blogHandle : commentOrJson.getBlogHandle(), postUuid : commentOrJson.getPostUuid() }); return this.updateEntity(url, options, callbacks, args); }, /** * Retrieve a blog comment, use the edit link for the blog entry * which can be found in the my blogs feed. * * @method getComment * @param {String } blogHandle * @param {String } commentUuid * @param {Object} args Object containing the query arguments to be * sent (defined in IBM Connections Blogs REST API) */ getComment : function(blogHandle, commentUuid, args) { var comment = new Comment({ service : this, _fields : { commentUuid : commentUuid } }); return comment.load(blogHandle, commentUuid, args); }, /** * Get the tags feed to see a list of the tags for all blogs. * * @method getAllBlogTags * @param {Object} [args] Object representing various parameters. * The parameters must be exactly as they are supported by IBM * Connections. */ getAllBlogTags : function(args) { var options = { method : "GET", handleAs : "text", query : args || {} }; var url = null; url = this._constructBlogsUrl(consts.AtomBlogsTags); return this.getEntities(url, options, this.getTagsFeedCallbacks(), args); }, /** * Get the tags feed to see a list of the tags for a perticular blog. * * @method getBlogTags * @param {String} blogHandle handle of the blog * @param {Object} [args] Object representing various parameters * that can be passed to get a feed of blog tags. The * parameters must be exactly as they are supported by IBM * Connections. */ getBlogTags : function(blogHandle, args) { var options = { method : "GET", handleAs : "text", query : args || {} }; var url = null; url = this.constructUrl(consts.AtomBlogTags, null, { blogHandle : blogHandle }); return this.getEntities(url, options, this.getTagsFeedCallbacks(), args); }, /** * Create a Blog object with the specified data. * * @method newBlog * @param {Object} args Object containing the fields for the * new blog */ newBlog : function(args) { return this._toBlog(args); }, /** * Create a Blog Post object with the specified data. * * @method newBlogPost * @param {Object} args Object containing the fields for the * new post */ newBlogPost : function(args) { return this._toBlogPost(args); }, /** * Create a Blog Post comment object with the specified data. * * @method newComment * @param {Object} args Object containing the fields for the * new comment */ newComment : function(args) { return this._toComment(args); }, /* * Callbacks used when reading a feed that contains Blog entries. */ getBlogFeedCallbacks: function() { return ConnectionsBlogFeedCallbacks; }, /* * Callbacks used when reading a feed that contains Blog entries. */ getTagsFeedCallbacks: function() { return ConnectionsTagsFeedCallbacks; }, /* * Callbacks used when reading a feed that contains Blog entries. */ getRecommendBlogPostCallbacks: function() { return RecommendBlogPostCallbacks; }, /* * Callbacks used when reading a feed that contains Blog entries. */ getBlogPostsCallbacks: function() { return ConnectionsBlogPostsCallbacks; }, /* * Callbacks used when reading a feed that contains Blog entries. */ getBlogPostRecommendersCallbacks: function() { return ConnectionsBlogPostRecommendersCallbacks; }, /* * Callbacks used when reading a feed that contains Blog post comments. */ getBlogPostCommentsCallbacks: function() { return ConnectionsBlogPostCommentsCallbacks; }, /* * Return a Blog instance from Blog or JSON or String. Throws * an error if the argument was neither. */ _toBlog : function(blogOrJsonOrString) { if (blogOrJsonOrString instanceof Blog) { return blogOrJsonOrString; } else { if (lang.isString(blogOrJsonOrString)) { blogOrJsonOrString = { blogUuid : blogOrJsonOrString }; } return new Blog({ service : this, _fields : lang.mixin({}, blogOrJsonOrString) }); } }, /* * Return a BlogPost instance from BlogPost or JSON or String. Throws * an error if the argument was neither. */ _toBlogPost : function(postOrJsonOrString) { if (postOrJsonOrString instanceof BlogPost) { return postOrJsonOrString; } else { if (lang.isString(postOrJsonOrString)) { postOrJsonOrString = { postUuid : postOrJsonOrString }; } return new BlogPost({ service : this, _fields : lang.mixin({}, postOrJsonOrString) }); } }, /* * Return a Comment instance from Comment or JSON or String. Throws * an error if the argument was neither. */ _toComment : function(commentOrJsonOrString) { if (commentOrJsonOrString instanceof Comment) { return commentOrJsonOrString; } else { if (lang.isString(commentOrJsonOrString)) { commentOrJsonOrString = { commentUuid : commentOrJsonOrString }; } return new Comment({ service : this, _fields : lang.mixin({}, commentOrJsonOrString) }); } }, /* * Validate a blog UUID, and return a Promise if invalid. */ _validateBlogUuid : function(blogUuid) { if (!blogUuid || blogUuid.length == 0) { return this.createBadRequestPromise("Invalid argument, expected blogUuid."); } }, /* * Validate a post, and return a Promise if invalid. */ _validateUuid : function(postUuid) { if (!postUuid) { return this.createBadRequestPromise("Invalid argument, blog post id must be specified."); } }, /* * Validate a post, and return a Promise if invalid. */ _validateBlogPost : function(post) { if (!post || !post.getTitle()) { return this.createBadRequestPromise("Invalid argument, blog post with title must be specified."); } }, /* * Validate a comment, and return a Promise if invalid. */ _validateComment : function(comment,checkUuid) { if (!comment || !comment.getContent()) { return this.createBadRequestPromise("Invalid argument, blog comment with content must be specified."); } }, /* * Validate a blog, and return a Promise if invalid. */ _validateBlog : function(blog,checkUuid) { if (!blog || !blog.getTitle()) { return this.createBadRequestPromise("Invalid argument, blog with title must be specified."); } if (checkUuid && !blog.getBlogUuid()) { return this.createBadRequestPromise("Invalid argument, blog with UUID must be specified."); } }, /* * Construct a post data for a Blog */ _constructBlogPostData : function(blog) { var transformer = function(value,key) { if (key == "getTags") { var tags = value; value = ""; for (var tag in tags) { value += stringUtil.transform(CategoryTmpl, { "tag" : tags[tag] }); } } return value; }; var postData = stringUtil.transform(BlogTmpl, blog, transformer, blog); return stringUtil.trim(postData); }, /* * Construct a post data for a Blog Post */ _constructBlogPostPostData : function(post) { var transformer = function(value,key) { if (key == "getTags") { var tags = value; value = ""; for (var tag in tags) { value += stringUtil.transform(CategoryTmpl, { "tag" : tags[tag] }); } } return value; }; var postData = stringUtil.transform(BlogPostTmpl, post, transformer, post); return stringUtil.trim(postData); }, /* * Construct a post data for a Blog Post */ _constructCommentBlogPostData : function(comment) { var transformer = function(value,key) { return value; }; var postData = stringUtil.transform(BlogCommentTmpl, comment, transformer, comment); return stringUtil.trim(postData); }, /* * Extract Blog handle from comment source url */ _extractBlogHandle : function(source) { var urlSuffix = "/entry/"; source = source.substring(0,source.indexOf(urlSuffix)); var bloghandle = source.substring(source.lastIndexOf("/")+1,source.length); return bloghandle; }, /* * Extract Blog handle from comment source url */ _constructBlogsUrl : function(url, urlParams) { urlParams = lang.mixin({blogHomepageHandle : this.handle}, urlParams || {}); return this.constructUrl(url, null, urlParams); } }); return BlogService; }); }, 'sbt/json':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Implements some JSON helpers. Will uses the browser version * if available else it will delegate to the Javascript library being used. * * @module sbt.json */ define(['./_bridge/json', './_bridge/lang', './log', './stringUtil'], function(jsonLib, lang, log, stringUtil) { /** * @static */ return { /** * Parses a String of JSON and returns a JSON Object. * @param {String} jsonString A String of JSON. * @returns {Object} A JSON Object. * @static * @method parse */ parse : function(jsonString) { var jsonImpl = JSON || jsonLib; return jsonImpl.parse(jsonString); }, /** * Returns the JSON object represented as a String. * @param {Object} jsonObj A JSON Object. * @returns {String} The JSON Object represented as a String. * @method stringify */ stringify : function(jsonObj) { var jsonImpl = JSON || jsonLib; return jsonImpl.stringify(jsonObj); }, /** * @method jsonBeanStringify * @param theObj * @returns */ jsonBeanStringify: function(theObj) { if (lang.isArray(theObj)) { var jsonObjs = "["; for (var i=0; i<theObj.length; i++) { jsonObjs += this._jsonBeanStringify(theObj[i]); if ((i+1)<theObj.length) { jsonObjs += ",\n"; } } jsonObjs += "]"; return jsonObjs; } else { return this._jsonBeanStringify(theObj); } }, /** * @method jsonBean * @param theObj * @returns */ jsonBean: function(theObj) { if (lang.isArray(theObj)) { var jsonObjs = []; for (var i=0; i<theObj.length; i++) { jsonObjs.push(this._jsonBean(theObj[i])); } return jsonObjs; } else { return this._jsonBean(theObj); } }, // Internals _jsonBeanStringify: function(theObj) { var jsonObj = this.jsonBean(theObj); return this._stringifyCyclicCheck(jsonObj, 4); }, _stringifyCyclicCheck: function(jsonObj, indent) { var jsonImpl = JSON || jsonLib; var seen = []; var self = this; return jsonImpl.stringify(jsonObj, function(key, val) { if(self._isDomNode(val)){ return {}; } if (lang.isObject(val)) { if (seen.indexOf(val) >= 0 && !self._isBuiltin(val)) return undefined; seen.push(val); } else if(lang.isFunction(val)){ return undefined; } return val; }, indent); }, _jsonBean: function(theObj, seen) { // first check for cyclic references if (!seen) { seen = []; } if (seen.indexOf(theObj) >= 0) { return undefined; } seen.push(theObj); var jsonObj = {}; for (var property in theObj) { var value = this._getObjectValue(theObj, property, seen); if (value || !isNaN(value)) { jsonObj[property] = value; } } return jsonObj; }, _notReserved: function(property) { return property!=='isInstanceOf' && property!=='getInherited'; }, _getObjectValue: function(theObj, property, seen) { var self = this; if (lang.isFunction(theObj[property])) { if ((stringUtil.startsWith(property, "get") || stringUtil.startsWith(property, "is")) && self._notReserved(property)) { try { var value = theObj[property].apply(theObj); if (value && !this._isBuiltin(value) && lang.isObject(value)) { return this._jsonBean(value, seen); } return value; } catch(error) { //log.error("Error {0}.{1} caused {2}", theObj, property, error); } } } else { if (!stringUtil.startsWith(property, "_") && !stringUtil.startsWith(property, "-")) { return theObj[property]; } } return undefined; }, _isBuiltin: function(value) { return ((value instanceof Date) || (value instanceof Number) || (value instanceof Boolean) || lang.isArray(value)); }, _isDomNode : function(value) { return (value && value.nodeName && value.nodeType && typeof value.nodeType === "number" && typeof value.nodeName === "string"); } }; }); }, 'sbt/connections/FileConstants':function(){ /* * © Copyright IBM Corp. 2012,2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. Definition of constants for FileService. */ define([ "../lang", "./ConnectionsConstants" ], function(lang,conn) { return lang.mixin({ /** * XPath expressions used when parsing a Connections Files ATOM feed */ FileFeedXPath : conn.ConnectionsFeedXPath, /** * XPath expressions used when parsing a Connections Comments ATOM feed */ CommentFeedXPath : conn.ConnectionsFeedXPath, /** * XPath expressions to be used when reading a File Entry */ FileXPath : { // used by getEntityData entry : "/a:entry", id : "a:id", // used by getEntityId uid : "td:uuid", label : "td:label", selfUrl : "a:link[@rel='self']/@href", alternateUrl : "a:link[@rel='alternate']/@href", downloadUrl : "a:link[@rel='enclosure']/@href", type : "a:link[@rel='enclosure']/@type", length : "a:link[@rel='enclosure']/@length", editLink : "a:link[@rel='edit']/@href", editMediaLink : "a:link[@rel='edit-media']/@href", thumbnailUrl : "a:link[@rel='thumbnail']/@href", commentsUrl : "a:link[@rel='replies']/@href", fileSize : "td:totalMediaSize", content : "a:content[@type='html']", shareCount : "snx:rank[@scheme='http://www.ibm.com/xmlns/prod/sn/share']", authorName : "a:author/a:name", authorUserId : "a:author/snx:userid", authorEmail : "a:author/a:email", authorUserState : "a:author/snx:userState", title: "a:title", published : "a:published", updated : "a:updated", created: "td:created", modified: "td:modified", lastAccessed : "td:lastAccessed", modifierName : "td:modifier/td:name", modifierUserId : "td:modifier/snx:userid", modifierEmail : "td:modifier/td:email", modifierUserState : "td:modifier/snx:userState", visibility : "td:visibility", libraryId : "td:libraryId", libraryType : "td:libraryType", versionUuid : "td:versionUuid", versionLabel : "td:versionLabel", propagation : "td:propagation", recommendationsCount : "snx:rank[@scheme='http://www.ibm.com/xmlns/prod/sn/recommendations']", commentsCount : "snx:rank[@scheme='http://www.ibm.com/xmlns/prod/sn/comment']", sharesCount : "snx:rank[@scheme='http://www.ibm.com/xmlns/prod/sn/share']", foldersCount : "snx:rank[@scheme='http://www.ibm.com/xmlns/prod/sn/collections']", attachmentsCount : "snx:rank[@scheme='http://www.ibm.com/xmlns/prod/sn/attachments']", versionsCount : "snx:rank[@scheme='http://www.ibm.com/xmlns/prod/sn/versions']", referencesCount : "snx:rank[@scheme='http://www.ibm.com/xmlns/prod/sn/references']", totalMediaSize : "td:totalMediaSize", summary : "a:summary", contentUrl : "a:content/@src", contentType : "a:content/@type", objectTypeId : "td:objectTypeId", lock : "td:lock/@type", acls : "td:permissions", hitCount : "snx:rank[@scheme='http://www.ibm.com/xmlns/prod/sn/hit']", anonymousHitCount : "snx:rank[@scheme='http://www.ibm.com/xmlns/prod/sn/anonymous_hit']", tags : "a:category[not(@scheme)]/@term", category : "a:category/@label" }, /** * XPath expression for parsing folder informartion from the File ATOM Feed. */ FolderXPath : { id : "id", uid : "td:uuid", title : "a:title", label : "td:label", folderUrl : "a:link[@rel='alternate']/@href", logoUrl : "a:link[@rel='http://www.ibm.com/xmlns/prod/sn/logo']/@href", tags : "a:category/@term", summary : "a:summary[@type='text']", content : "a:content[@type='html']", visibility : "td:visibility", notification : "td:notification", versionUuid : "td:versionUuid", versionLabel : "td:versionLabel", documentVersionUuid : "td:documentVersionUuid", documentVersionLabel : "td:documentVersionLabel", itemCount : "snx:rank[@scheme='http://www.ibm.com/xmlns/prod/sn/item']", shareCount : "snx:rank[@scheme='http://www.ibm.com/xmlns/prod/sn/user']", groupShareCount : "snx:rank[@scheme='http://www.ibm.com/xmlns/prod/sn/group']", modified : "td:modified", created : "td:created", updated : "a:updated", authorName : "a:author/a:name", authorUserId : "a:author/snx:userid", authorEmail : "a:author/a:email", content : "a:content[@type='text']", modifierName : "a:modifier/a:name", modifierId : "a:modifier/snx:userid", modifierEmail : "a:modifier/a:email" }, /** * XPath expressions to be used when reading a Comment */ CommentXPath : { entry : "a:entry", id : "a:id", uid : "td:uuid", title : "a:title", content : "a:content[@type='text']", created : "td:created", modified : "td:modified", versionLabel : "td:versionLabel", updated : "a:updated", published : "a:published", modifierName : "td:modifier/td:name", modifierUserId : "td:modifier/snx:userid", modifierEmail : "td:modifier/td:email", modifierUserState : "td:modifier/snx:userState", authorName : "a:author/a:name", authorUserId : "a:author/snx:userid", authorEmail : "a:author/a:email", authorUserState : "a:author/snx:userState", language : "td:language", deleteWithRecord : "td:deleteWithRecord" }, /** * XPath expressions used for parsing information on shared files and folders. */ SharesXPath : { id : "id", uuid : "td:uuid", title : "a:title", summary : "a:summary[@type='text']", sharedResourceType : "td:sharedResourceType", // always set to document, but will add the attribute anyway sharePermission : "td:sharePermission", sharedWhat : "td:sharedWhat", sharedWithName : "a:sharedWith/a:name", sharedWithId : "a:sharedWith/snx:userid", sharedWithEmail : "a:sharedWith/a:email", documentOwner : "td:documentOwner", updated : "a:updated", published : "a:published", authorName : "a:author/a:name", authorUid : "a:author/snx:userid", authorEmail : "a:author/a:email" }, /** * XPath expressions used for parsing information on user library. */ LibraryXPath : { entry : "a:feed", id : "a:id", uuid : "td:uuid", librarySize : "td:librarySize", totalRemovedSize : "td:totalRemovedSize", libraryQuota : "td:libraryQuota", totalResults : "opensearch:totalResults" }, /** * Get a Feed for a File */ AtomFileInstance : "${files}/basic/api/myuserlibrary/document/{documentId}/entry", /** * */ AtomFileInstancePublic : "${files}/basic/anonymous/api/library/{libraryId}/document/{documentId}/entry", /** * A feed of files of which the authenticated user owns. * * Get the My Files feed to see a list of the files which the authenticated owns. * Supports: acls , includePath , includeQuota , includeTags , page , ps , shared , sI , since , sortBy , sortOrder , tag , visibility */ AtomFilesMy : "/${files}/basic/api/myuserlibrary/feed", /** * A feed of files with are shared by or with the authenticated user. * * Get the My Files feed to see a list of the files which the authenticated owns. * Supports: direction (default inbound : with me, outbound : by me), acls , includePath , includeQuota , includeTags , page , ps , shared , sI , since , sortBy , sortOrder , tag , visibility */ AtomFilesShared : "/${files}/basic/api/documents/shared/feed", /** * Get a feed that lists all public files. * * Supports: acls , includePath , includeQuota , includeTags , page , ps , shared , sI , since , sortBy , sortOrder , tag , visibility */ AtomFilesPublic : "/${files}/basic/anonymous/api/documents/feed?visibility=public", /** * Get feed of recycled files */ AtomFilesRecycled : "/${files}/basic/api/myuserlibrary/view/recyclebin/feed", /** * Get a feed that lists your folders * * Supports: access(editor or manager), creator, page, ps, shared, sharedWithMe, sI, sortBy, sortOrder, title, visibility */ AtomFoldersMy : "/${files}/basic/api/collections/feed", /** * Feed of public folders */ AtomFoldersPublic : "/${files}/basic/anonymous/api/collections/feed", /** * Feed of folders you recently added files to */ AtomFoldersActive : "/${files}/basic/api/collections/addedto/feed", /** * A feed of comments associated with all public files. Do not authenticate this request. * * Supports: acls, category Note: This parameter is required., commentId, identifier, page, ps, sI, sortBy, sortOrder */ AtomFileCommentsPublic : "/${files}/basic/anonymous/api/userlibrary/{userId}/document/{documentId}/feed?category=comment", /** * A feed of comments associated with files to which you have access. You must authenticate this request. * * Supports: acls, category Note: This parameter is required., commentId, identifier, page, ps, sI, sortBy, sortOrder */ AtomFileCommentsMy : "/${files}/basic/api/userlibrary/{userId}/document/{documentId}/feed?category=comment", /** * Adds a comment to the specified file. * * Supports : identifier - Indicates how the document is identified in the {document-id} variable segment of the web address. By default, look up is performed with the expectation that the URL contains the value from the <td:uuid> element of a File Atom entry. Specify "label" if the URL instead contains the value from the <td:label> element of a File Atom entry. */ AtomAddCommentToFile : "/${files}/basic/api/userlibrary/{userId}/document/{documentId}/feed", /** * Adds a comment to the specified file for logged in user. * * Supports : identifier - Indicates how the document is identified in the {document-id} variable segment of the web address. By default, look up is performed with the expectation that the URL contains the value from the <td:uuid> element of a File Atom entry. Specify "label" if the URL instead contains the value from the <td:label> element of a File Atom entry. */ AtomAddCommentToMyFile : "/${files}/basic/api/myuserlibrary/document/{documentId}/feed", /** * Update the Atom document representation of the metadata for a file from logged in user's library. * * supports : * propagate Indicates if users that are shared with can share this document. The default value is true. * sendEmail Indicates if an email notification is sent when sharing with the specified user. The default value is true. */ AtomUpdateFileMetadata : "/${files}/basic/api/myuserlibrary/document/{documentId}/entry", /** * Get pinned files from my my favorites feed. * */ AtomFilesMyPinned : "/${files}/basic/api/myfavorites/documents/feed", /** * Add a file to my favorites feed of logged in user * */ AtomPinFile : "/${files}/basic/api/myfavorites/documents/feed", /** * Add file of list of files to folder */ AtomAddFilesToFolder : "/${files}/basic/api/collection/{collectionId}/feed", /** * Delete a file and the Atom document representation of its associated metadata from logged in user's collection. */ AtomDeleteFile : "/${files}/basic/api/myuserlibrary/document/{documentId}/entry", /** * Lock or unlock a file */ AtomLockUnlockFile : "/${files}/basic/api/document/{documentId}/lock", /** * Add the document to collections specified by atom entry or feed. */ AtomAddFileToFolders : "/${files}/basic/api/userlibrary/{userId}/document/{documentId}/feed", /** * Add the document of logged in user to collections specified by atom entry or feed. */ AtomAddMyFileToFolders : "/${files}/basic/api/myuserlibrary/document/{documentId}/feed", /** * Create a file folder programmatically. */ AtomCreateFolder : "/${files}/basic/api/collections/feed", /** * Delete all files from recycle bin of specified user */ AtomDeleteAllFilesFromRecyclebBin : "/${files}/basic/api/userlibrary/{userId}/view/recyclebin/feed", /** * Delete all files from recycle bin of logged in user */ AtomDeleteMyFilesFromRecyclebBin : "/${files}/basic/api/myuserlibrary/view/recyclebin/feed", /** * Delete All Versions of a File */ AtomDeleteAllVersionsOfAFile : "/${files}/basic/api/myuserlibrary/document/{documentId}/feed", /** * Delete a Comment for a File */ AtomDeleteComment : "/${files}/basic/api/userlibrary/{userId}/document/{documentId}/comment/{commentId}/entry", /** * Delete a comment on file for logged in user */ AtomDeleteMyComment : "/${files}/basic/api/myuserlibrary/document/{documentId}/comment/{commentId}/entry", /** * Purge a file from Recycle Bin */ AtomDeleteFileFromRecycleBin : "/${files}/basic/api/userlibrary/{userId}/view/recyclebin/{documentId}/entry", /** * Purge a file from REcycle Bin for Logged in user */ AtomDeleteMyFileFromRecycleBin : "/${files}/basic/api/myuserlibrary/view/recyclebin/{documentId}/entry", /** * Remove a file Share */ AtomDeleteFileShare : "/${files}/basic/api/shares/feed", /** * Delete a Folder */ AtomDeleteFolder : "/${files}/basic/api/collection/{collectionId}/entry", /** * Get Files for a user */ AtomGetAllUsersFiles : "/${files}/basic/anonymous/api/userlibrary/{userId}/feed", /** * Get a comment for a file */ AtomGetFileComment : "/${files}/basic/api/userlibrary/{userId}/document/{documentId}/comment/{commentId}/entry", /** * Get a comment for a File for logged in user */ AtomGetMyFileComment : "/${files}/basic/api/myuserlibrary/document/{documentId}/comment/{commentId}/entry", /** * Get File from Recycle Bin */ AtomGetFileFromRecycleBin : "/${files}/basic/api/userlibrary/{userId}/view/recyclebin/{documentId}/entry", /** * Get Files Awaiting Approval */ AtomGetFilesAwaitingApproval : "/${files}/basic/api/approval/documents", /** * Get File Shares */ AtomGetFileShares : "/${files}/basic/api/documents/shared/feed", /** * Get All Files in a Folder */ AtomGetFilesInFolder : "/${files}/basic/api/collection/{collectionId}/feed", /** * Get Files in Recycle Bin of logged in user */ AtomGetFilesInMyRecycleBin : "/${files}/basic/api/myuserlibrary/view/recyclebin/feed", /** * Get file with given version */ AtomGetFileWithGivenVersion : "/${files}/basic/api/myuserlibrary/document/{documentId}/version/{versionId}/entry", /** * Get a folder */ AtomGetFolder : "/${files}/basic/api/collection/{collectionId}/entry", /** * Get Folder with Recenty Added Files */ AtomGetFoldersWithRecentlyAddedFiles : "/${files}/basic/api/collections/addedto/feed", /** * Get Pinned Folders */ AtomGetPinnedFolders : "/${files}/basic/api/myfavorites/collections/feed", /** * Get Public Folders */ AtomGetPublicFolders : "/${files}/basic/anonymous/api/collections/feed", /** * Pin/unpin a Folder */ AtomPinFolder : "/${files}/basic/api/myfavorites/collections/feed", /** * Remove File from Folder */ AtomRemoveFileFromFolder : "/${files}/basic/api/collection/{collectionId}/feed", /** * Restore File from Recycle Bin */ AtomRestoreFileFromRecycleBin : "/${files}/basic/api/userlibrary/{userId}/view/recyclebin/{documentId}/entry", /** * Share File with Community or communities */ AtomShareFileWithCommunities : "/${files}/basic/api/myuserlibrary/document/{documentId}/feed", /** * Update a Comment */ AtomUpdateComment : "/${files}/basic/api/userlibrary/{userId}/document/{documentId}/comment/{commentId}/entry", /** * Update comment of logged in user */ AtomUpdateMyComment : "/${files}/basic/api/myuserlibrary/document/{documentId}/comment/{commentId}/entry", /** * Add Comment To Community File */ AtomAddCommentToCommunityFile : "/${files}/basic/api/communitylibrary/{communityId}/document/{documentId}/feed", /** * Get All Community Files, Shows only files with with a libraryType of communityFiles * TODO This should be renamed */ AtomGetAllFilesInCommunity : "/${files}/basic/api/communitylibrary/{communityId}/feed", /** * Get all files in a community, Shows public, private, communityFiles etc. */ AtomGetAllCommunityFiles : "/${files}/basic/api/communitycollection/{communityId}/feed", /** * Get Community File */ AtomGetCommunityFile : "/${files}/basic/api/communitylibrary/{communityId}/document/{documentId}/entry", /** * Update metadata of community File */ AtomUpdateCommunityFileMetadata : "/${files}/basic/api/library/{libraryId}/document/{documentId}/entry" }, conn); }); }, 'sbt/authenticator/templates/login':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ function submitOnClick(contentForm) { if (contentForm.username.value == "" || contentForm.password.value == "") { document.getElementById("wrongCredsMessage").style.display = "block"; return; } var argsMap = getArgsMap();// get map of query string arguments var actionURL = decodeURIComponent(argsMap.actionURL); var loginUi = decodeURIComponent(argsMap.loginUi); if (loginUi.length == 0) { loginUi = "mainWindow"; } if (loginUi == "popup") { contentForm.action = actionURL + "?loginUi=popup&redirectURLToLogin=" + encodeURIComponent(document.URL)+"&endpointAlias="+opener.globalEndpointAlias; } else if (loginUi == "mainWindow") { var redirectURL = argsMap.redirectURL; contentForm.action = actionURL + "?loginUi=mainWindow&redirectURLToLogin=" + encodeURIComponent(document.URL) + "&redirectURL=" + encodeURIComponent(redirectURL); } contentForm.submit(); } function cancelOnClick() { var argsMap = getArgsMap();// get map of query string arguments var redirectURL = decodeURIComponent(argsMap.redirectURL); var loginUi = decodeURIComponent(argsMap.loginUi); if (loginUi == "popup") { if(window.cancel){ window.cancel(); delete window.cancel; } window.close(); } else { window.location.href = redirectURL; } } function onLoginPageLoad() { var argsMap = getArgsMap();// get map of query string arguments var showWrongCredsMessage = argsMap.showWrongCredsMessage; if (showWrongCredsMessage == "true") { document.getElementById("wrongCredsMessage").style.display = "block"; } if(opener && opener.globalLoginFormStrings){ var loginForm = opener.globalLoginFormStrings; document.getElementById('wrongCredsMessage').appendChild(document.createTextNode(loginForm.wrong_creds_message)); document.getElementById('basicLoginFormUsername').appendChild(document.createTextNode(loginForm.username)); document.getElementById('basicLoginFormPassword').appendChild(document.createTextNode(loginForm.password)); document.getElementById('basicLoginFormOK').value = loginForm.login_ok; document.getElementById('basicLoginFormCancel').value = loginForm.login_cancel; }else{ document.getElementById('wrongCredsMessage').appendChild(document.createTextNode(decodeURIComponent(argsMap.wrong_creds_message))); document.getElementById('basicLoginFormUsername').appendChild(document.createTextNode(decodeURIComponent(argsMap.username))); document.getElementById('basicLoginFormPassword').appendChild(document.createTextNode(decodeURIComponent(argsMap.password))); document.getElementById('basicLoginFormOK').value = decodeURIComponent(argsMap.login_ok); document.getElementById('basicLoginFormCancel').value = decodeURIComponent(argsMap.login_cancel); } } function getArgsMap() { try { var qString = location.search.substring(1);// getting query string args var qStringParams = qString.split("&");// getting array of all query // string arg key value pairs var argsMap = {}; var i; for (i = 0; i < qStringParams.length; i++) { var argArray = qStringParams[i].split("="); argsMap[argArray[0]] = argArray[1]; } return argsMap; } catch (err) { console.log("Error making agrs map in login.js " + err); } } }, 'sbt/pathUtil':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK - URL utilities */ define(['./stringUtil'],function(stringUtil) { return { concat: function(path1,path2) { if(!path1) { return path2; } if(!path2) { return path1; } if(stringUtil.endsWith(path1,"/")) { path1 = path1.substring(0,path1.length-1); } if(stringUtil.startsWith(path2,"/")) { path2 = path2.substring(1); } return path1 + "/" + path2; }, isAbsolute: function(url) { return url.indexOf("://")>=0; } } }); }, 'sbt/base/BaseService':function(){ /* * © Copyright IBM Corp. 2012, 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Javascript Base APIs for IBM Connections * * @module sbt.base.BaseService * @author Carlos Manias */ define(["../config", "../declare", "../lang", "../log", "../stringUtil", "../Cache", "../Promise", "../util" ], function(config, declare,lang,log,stringUtil,Cache,Promise, util) { // TODO sbt/config is required here to solve module loading // issues with jquery until we remove the global sbt object var BadRequest = 400; var requests = {}; /** * BaseService class. * * @class BaseService * @namespace sbt.base */ var BaseService = declare(null, { /** * The Endpoint associated with the service. */ endpoint : null, /* * The Cache associated with the service. */ _cache : null, /* * Regular expression used to remove // from url's */ _regExp : new RegExp("/{2}"), /** * A map of default context roots to custom, if any. This will be implemented in subClasses of BaseService. */ contextRootMap: {}, /** * Constructor for BaseService * * An endpoint is required so subclasses must check if one * was created here and if not set the default endpoint. * * @constructor * @param {Object} args Arguments for this service. */ constructor : function(args) { args = args || {}; // set endpoint if specified in args if (args.endpoint) { if (lang.isString(args.endpoint)) { this.endpoint = config.findEndpoint(args.endpoint); } else { this.endpoint = args.endpoint; } } // optionally create a cache if (args.cacheSize) { this._cache = new Cache(args.cacheSize); } }, /** * Construct a url using the specified parameters * * @method constructUrl * @param url Base part of the URL to construct * @param params Params to be encoded in the URL * @param urlParams Params to be encoded in the URL query * @returns The constructed URL */ constructUrl : function(url,params,urlParams) { if (!url) { throw new Error("BaseService.constructUrl: Invalid argument, url is undefined or null."); } if(this.endpoint){ lang.mixin(this.contextRootMap, this.endpoint.serviceMappings); url = stringUtil.transform(url, this.contextRootMap, function(value, key){ if(!value){ return key; } else{ return value; } }, this); } if (urlParams) { url = stringUtil.replace(url, urlParams); if (url.indexOf("//") != -1) { // handle empty values url = url.replace(this._regExp, "/"); } } if (params) { for (param in params) { if (url.indexOf("?") == -1) { url += "?"; } else if (url.indexOf("&") != (url.length - 1)) { url += "&"; } var value = encodeURIComponent(params[param]); if (value) { url += param + "=" + value; } } } return url; }, /** * Get a collection of entities. * * @method getEntities * @param url The URL to get the entities. * @param options Optional. Options for the request. * @param callbacks Callbacks used to parse the response and create the entities. * @returns {sbt/Promise} */ getEntities : function(url,options,callbacks) { url = this.constructUrl(url); var self = this; var promise = new Promise(); this.request(url,options,null,promise).response.then( function(response) { promise.response = response; try { var feedHandler = callbacks.createEntities.apply(self, [ self, response.data, response ]); var entitiesArray = feedHandler.getEntitiesDataArray(); var entities = []; for ( var i = 0; i < entitiesArray.length; i++) { var entity = callbacks.createEntity.apply(self, [ self, entitiesArray[i], response ]); entities.push(entity); } promise.summary = feedHandler.getSummary(); promise.fulfilled(entities); } catch (cause) { var error = new Error("Error parsing response caused by: "+cause); error.cause = cause; promise.rejected(error); } }, function(error) { promise.rejected(error); } ); return promise; }, /** * Get a single entity. * * @method getEntity * @param url The URL to get the entity. * @param options Options for the request. * @param callbacks Callbacks used to parse the response and create the entity. * @returns {sbt/Promise} */ getEntity : function(url,options,entityId,callbacks) { url = this.constructUrl(url); var promise = this._validateEntityId(entityId); if (promise) { return promise; } // check cache var promise = new Promise(); var data = this.getFromCache(entityId); if (data) { promise.fulfilled(data); return promise; } var self = this; this.request(url,options,entityId,promise).response.then( function(response) { promise.response = response; try { var entity = callbacks.createEntity.apply(self, [ self, response.data, response ]); if (self._cache && entityId) { self.fullFillOrRejectPromises.apply(self, [ entityId, entity, response ]); } else { promise.fulfilled(entity); } } catch (cause) { var error = new Error("Invalid response"); error.cause = cause; if (self._cache && entityId) { self.fullFillOrRejectPromises.apply(self, [ entityId, error ]); } else { promise.rejected(error); } } }, function(error) { if (self._cache && entityId) { self.fullFillOrRejectPromises.apply(self, [ entityId, error ]); } else { promise.rejected(error); } } ); return promise; }, /** * Update the specified entity. * * @method updateEntity * @param url The URL to update the entity. * @param options Options for the request. * @param callbacks Callbacks used to parse the response. * @param sbt/Promise */ updateEntity : function(url, options, callbacks) { url = this.constructUrl(url); var self = this; var promise = new Promise(); this.endpoint.request(url,options,null,promise).response.then( function(response) { promise.response = response; var entity = callbacks.createEntity.apply(self, [ self, response.data, response ]); // callback can return a promise if an additional // request is required to load the associated entity if (entity instanceof Promise) { entity.then( function(response) { // it is the responsibility of the createEntity callback to clear the cache in this case. promise.fulfilled(response); }, function(error) { promise.rejected(error); } ); } else { if(entity.id){ self.removeFromCache(entity.id); } if(entity.id && entity.data){ self.addToCache(entity.id, entity); } promise.fulfilled(entity); } }, function(error) { promise.rejected(error); } ); return promise; }, /** * Delete the specified entity. * * @method deleteEntity * @param url The URL to delete the entity. * @param options Options for the request. * @param entityId Id of the entity to delete. * @param sbt/Promise */ deleteEntity : function(url,options,entityId) { url = this.constructUrl(url); var promise = this._validateEntityId(entityId); if (promise) { return promise; } var self = this; var promise = new Promise(); this.endpoint.request(url,options,entityId,promise).response.then( function(response) { promise.response = response; promise.fulfilled(entityId); self.removeFromCache(entityId); }, function(error) { promise.rejected(error); } ); return promise; }, /** * Perform an XML HTTP Request with cache support. * * @method request * @param url URL to request * @param options Options for the request. * @param entityId Id of the rntity associated with the request. * @param promise Promise being returned * @param sbt/Promise */ request : function(url,options,entityId,promise) { url = this.constructUrl(url); if (this._cache && entityId) { this.pushPromise(entityId, promise); } return this.endpoint.request(url,options); }, /** * Push set of promise onto stack for specified request id. * * @method pushPromise * @param id Id of the request. * @param promise Promise to push. */ pushPromise : function(id,promise) { log.debug("pushPromise, id : {0}, promise : {1}", id, promise); if (!requests[id]) { requests[id] = []; } requests[id].push(promise); }, /** * Notify set of promises and pop from stack for specified request id. * * @method fullFillOrRejectPromises * @param id * @param data * @param response */ fullFillOrRejectPromises : function(id,data,response) { log.debug("fullFillOrRejectPromises, id : {0}, data : {1}, response : {2}", id, data, response); this.addToCache(id, data); var r = requests[id]; if (r) { delete requests[id]; for ( var i = 0; i < r.length; i++) { var promise = r[i]; this.fullFillOrReject.apply(this, [ promise, data, response ]); } } }, /** * Fullfill or reject specified promise. * * @method fullFillOrReject * @param promise * @param data * @param response */ fullFillOrReject : function(promise,data,response) { if (promise) { try { promise.response = response; if (data instanceof Error) { promise.rejected(data); } else { promise.fulfilled(data); } } catch (error) { log.debug("fullFillOrReject: " + error.message); } } }, /** * Add the specified data into the cache. * * @method addToCache * @param id * @param data */ addToCache : function(id, data) { if (this._cache && !(data instanceof Error)) { this._cache.put(id, data); } }, /** * Remove the cached data for the specified id. * * @method removeFromCache * @param id */ removeFromCache : function(id) { if (this._cache) { this._cache.remove(id); } }, /** * Get the cached data for the specified id. * * @method getFromCache * @param id */ getFromCache : function(id) { if (this._cache) { return this._cache.get(id); } }, /** * Create a bad request Error. * * @method createBadRequestError * @param message * @returns {Error} */ createBadRequestError : function(message) { var error = new Error(); error.code = BadRequest; error.message = message; return error; }, /** * Create a bad request Promise. * * @method createBadRequestPromise * @param message * @returns {sbt/Promise} */ createBadRequestPromise : function(message) { return new Promise(this.createBadRequestError(message)); }, /** * Return true if the specified id is an email. * * @method isEmail * @param id * @returns {Boolean} */ isEmail : function(id) { return id && id.indexOf('@') >= 0; }, /** * Extract the Location parameter from a URL. * * @method getLocationParameter * @param ioArgs * @param name * @returns {String} */ getLocationParameter: function (response, name) { var location = response.getHeader("Location") || undefined; if (location) { return this.getUrlParameter(location, name); } }, /** * Extract the specified parameter from a URL. * * @mehtod getUrlParameter * @param url * @param name * @returns {Boolean} */ getUrlParameter : function (url, name) { return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(url)||[,""])[1].replace(/\+/g, '%20'))||null; }, /** * Validate a string field, and return a Promise if invalid. * * @param fieldName * @param fieldValue */ validateField : function(fieldName, fieldValue) { if (!fieldValue) { var message = "Invalid value {0} for field {1}, the field must not be empty or undefined."; message = stringUtil.substitute(message, [ fieldValue || "'undefined'", fieldName ]); return this.createBadRequestPromise(message); } }, /** * Validate a map of fields, and return a Promise for first invalid field found. * * @param fieldMap */ validateFields : function(fieldMap) { for(var name in fieldMap){ var value = fieldMap[name]; var promise = this.validateField(name, value); if (promise) { return promise; } } }, /** * Validate HTML5 File API Support for browser and JS Library */ validateHTML5FileSupport : function() { if (!window.File || !window.FormData) { var message = "HTML 5 File API is not supported by the Browser."; return this.createBadRequestPromise(message); } // Dojo 1.4.3 does not support HTML5 FormData if(util.getJavaScriptLibrary().indexOf("Dojo 1.4") != -1) { return this.createBadRequestPromise("Dojo 1.4.* is not supported for Update Profile Photo"); } }, /* * Validate the entityId and if invalid notify callbacks */ _validateEntityId : function(entityId) { if (!entityId || !lang.isString(entityId)) { var message = "Invalid argument {0}, expected valid entity identifier."; message = stringUtil.substitute(message, [ entityId || "'undefined'" ]); return this.createBadRequestPromise(message); } }, /** * Returns HTML5 File Control object * @param {Object} fileControlOrId FileControl or ID of File Control * @returns {Object} FileControl */ getFileControl : function(fileControlOrId) { var fileControl = null; if (typeof fileControlOrId == "string") { fileControl = document.getElementById(fileControlOrId); } else if (typeof fileControlOrId == "object") { fileControl = fileControlOrId; } return fileControl; } }); return BaseService; }); }, 'sbt/base/VCardDataHandler':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * JavaScript API for IBM Connections Profile Service. * * @module sbt.connections.ProfileService */ define([ "../declare", "../lang", "../config", "../stringUtil", "./XmlDataHandler" ], function(declare,lang,config,stringUtil,XmlDataHandler) { /** * VCardDataHandler class. * * @class ProfileDataHandler * @namespace sbt.connections */ var VCardDataHandler = declare(XmlDataHandler, { lineDelim : "\n", itemDelim : ":", _vcard : null, /** * @constructor * @param {Object} * args Arguments for this data handler. */ constructor : function(args) { this.parseVCard(); }, /** * Parse the vcard data from the specified element. * * @method parseVCard */ parseVCard : function() { var content = stringUtil.trim(this.getAsString("vcard")); var lines = content.split(this.lineDelim); this._vcard = {}; for (var i=1; i<lines.length-1; i++) { var line = stringUtil.trim(lines[i]); var index = line.indexOf(this.itemDelim); var key = line.substring(0, index); var value = line.substring(index+1); this._vcard[key] = value; } }, /* * Override this method to handle VCard properties. */ _selectText : function(property) { var xpath = this._getXPath(property); if (this._vcard && this._vcard.hasOwnProperty(xpath)) { return this._vcard[xpath]; } else { try { return this.inherited(arguments, [ property ]); } catch (error) { // vcard expressions may cause an error // if they are treated as xpath expressions return null; } } } }); return VCardDataHandler; }); }, 'sbt/_bridge/declare':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. * * declare() function. */ define(['dojo/_base/declare'],function(declare) { return declare; }); }, 'sbt/smartcloud/SmartcloudConstants':function(){ /* * © Copyright IBM Corp. 2012,2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. Definition of constants for IBM Connections. * * @module sbt.connections.ConnectionsConstants */ define([ "../lang", "../base/BaseConstants" ], function(lang, base) { return lang.mixin(base, { /** * XPath expressions used when parsing a Connections ATOM feed */ SmartcloudFeedXPath : { // used by getEntitiesDataArray entries : "/a:feed/a:entry", // used by getSummary totalResults : "/a:feed/opensearch:totalResults", startIndex : "/a:feed/opensearch:startIndex", itemsPerPage : "/a:feed/opensearch:itemsPerPage" } }); }); }, 'sbt/i18n':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. * @module sbt.i18n */ define(['./_bridge/i18n'],function(i18n) { var nls = { todayAt : "Today at ", on : "on " }; i18n.getUpdatedLabel = function(dateStr) { var date = new Date(dateStr); var dateClone = new Date(date.getTime()); var now = new Date(); if (dateClone.setHours(0,0,0,0) == now.setHours(0,0,0,0)) { return nls.todayAt + this.getLocalizedTime(date); } else { return nls.on + this.getLocalizedDate(date); } }; i18n.getSearchUpdatedLabel = function(dateStr) { var date = new Date(dateStr); var dateClone = new Date(date.getTime()); var now = new Date(); if (dateClone.setHours(0,0,0,0) == now.setHours(0,0,0,0)) { return nls.todayAt + this.getLocalizedTime(date); } else { return this.getLocalizedDate(date); } }; return i18n; }); }, 'sbt/DebugTransport':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. * * Implementation of a transport which writes the response to the DOM. */ define([ "./declare", "./lang", "./dom", "./json", "./stringUtil", "sbt/_bridge/Transport" ], function(declare, lang, dom, json, stringUtil, Transport) { return declare(Transport, { responseMap : {}, index : 0, /* * Create a response object */ createResponse: function(url, options, response, ioargs) { var retval = this.inherited(arguments, [ url, options, response, ioargs ]); var mockNode = dom.byId("mockData"); if (mockNode) { if (options.handleAs == "json") { response = json.jsonBeanStringify(response); } var pre = document.createElement("pre"); mockNode.appendChild(pre); var status = retval.status || 0; var handleAs = options.handleAs || "text"; var method = options.method || "GET"; var data = options.data || ""; var location = retval.getHeader("Location") || ""; var isError = (response instanceof Error); if (isError) { response = retval.data.responseText || retval.data.response.text || response; } var id = url; var hash = stringUtil.hashCode(id); if (this.responseMap[hash]) { this.responseMap[hash] = this.responseMap[hash] + 1; id += "#" + this.responseMap[hash]; } else { this.responseMap[hash] = 1; } var text = "<script type='text/template' status='"+status+ "' id='"+id+ "' index='"+this.index+ "' handleAs='"+handleAs+ "' method='"+method+ "' location='"+location+ "' error='"+isError+ "'>\n"+response+"\n</script>"; pre.appendChild(dom.createTextNode(text)); this.index++; } return retval; } }); }); }, 'sbt/connections/ProfileConstants':function(){ /* * © Copyright IBM Corp. 2012,2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. Definition of constants for CommunityService. */ define([ "../lang", "./ConnectionsConstants" ], function(lang,conn) { return lang.mixin({ /** * Default size for the profile cache */ DefaultCacheSize : 10, /** * Fields used to populate the Address object */ AddressFields : [ "streetAddress", "extendedAddress", "locality", "region", "postalCode", "countryName" ], /** * XPath expressions used when parsing a Connections Profiles ATOM feed */ ProfileFeedXPath : conn.ConnectionsFeedXPath, /** * Namespace expressions used when parsing a Connections Profiles ATOM feed */ ProfileNamespaces : conn.Namespaces, /** * Connection type colleague */ TypeColleague : "colleague", /** * Status flag */ StatusPending : "pending", /** * XPath expressions to be used when reading a Profile Entry */ ProfileXPath : lang.mixin({},conn.AtomEntryXPath,{ uid : "a:contributor/snx:userid",// overwriting this for ProfileService entry : "/a:feed/a:entry",// overwriting this for ProfileService userid : "a:contributor/snx:userid", name : "a:contributor/a:name", email : "a:contributor/a:email", altEmail : "a:content/h:div/h:span/h:div[@class='x-groupwareMail']", // TODO do we need this? it's a dupe of groupwareMail photoUrl : "a:link[@rel='http://www.ibm.com/xmlns/prod/sn/image']/@href", fnUrl : "a:content/h:div/h:span/h:div/h:a[@class='fn url']/@href", soundUrl : "a:content/h:div/h:span/h:div/h:a[@class='sound url']/@href", jobTitle : "a:content/h:div/h:span/h:div[@class='title']", organizationUnit : "a:content/h:div/h:span/h:div[@class='org']/h:span[@class='organization-unit']", telephoneNumber : "a:content/h:div/h:span/h:div[@class='tel']/h:span[@class='value']", building : "a:content/h:div/h:span/h:div/h:span[@class='x-building']", floor : "a:content/h:div/h:span/h:div/h:span[@class='x-floor']", officeNumber : "a:content/h:div/h:span/h:div/h:span[@class='x-office-number']", streetAddress : "a:content/h:div/h:span/h:div/h:div[@class='street-address']", extendedAddress : "a:content/h:div/h:span/h:div/h:div[@class='extended-address x-streetAddress2']", locality : "a:content/h:div/h:span/h:div/h:span[@class='locality']", postalCode : "a:content/h:div/h:span/h:div/h:span[@class='postal-code']", region : "a:content/h:div/h:span/h:div/h:span[@class='region']", countryName : "a:content/h:div/h:span/h:div/h:div[@class='country-name']", groupwareMail : "a:content/h:div/h:span/h:div[@class='x-groupwareMail']", blogUrl : "a:content/h:div/h:span/h:div/h:a[@class='x-blog-url url']/@href", role : "a:content/h:div/h:span/h:div[@class='role']", managerUid : "a:content/h:div/h:span/h:div[@class='x-manager-uid']", isManager : "a:content/h:div/h:span/h:div[@class='x-is-manager']" }), /** * XPath expressions to be used when reading a ColleagueConnection Entry */ ColleagueConnectionXPath : lang.mixin({}, conn.AtomEntryXPath, { entry : "/a:feed/a:entry" }), /** * XPath expressions to be used when reading a Community Entry with VCard content */ ProfileVCardXPath : lang.mixin({}, conn.AtomEntryXPath, { // used by getEntityData entry : "/a:feed/a:entry", // used by getEntityId uid : "a:contributor/snx:userid", // used by parseVCard vcard : "a:content", userid : "a:contributor/snx:userid", name : "a:contributor/a:name", email : "a:contributor/a:email", altEmail : "EMAIL;X_GROUPWARE_MAIL", // TODO do we need this? it's a dupe of groupwareMail photoUrl : "a:link[@rel='http://www.ibm.com/xmlns/prod/sn/image']/@href", fnUrl : "URL", soundUrl : "SOUND;VALUE=URL", jobTitle : "TITLE", organizationUnit : "a:content/h:div/h:span/h:div[@class='org']/h:span[@class='organization-unit']", telephoneNumber : "TEL;WORK", building : "X_BUILDING", floor : "X_FLOOR", officeNumber : "X_OFFICE_NUMBER", workLocation : "ADR;WORK", streetAddress : "a:content/h:div/h:span/h:div/h:div[@class='street-address']", extendedAddress : "a:content/h:div/h:span/h:div/h:div[@class='extended-address x-streetAddress2']", locality : "a:content/h:div/h:span/h:div/h:span[@class='locality']", postalCode : "a:content/h:div/h:span/h:div/h:span[@class='postal-code']", region : "a:content/h:div/h:span/h:div/h:span[@class='region']", countryName : "a:content/h:div/h:span/h:div/h:div[@class='country-name']", groupwareMail : "EMAIL;X_GROUPWARE_MAIL" }), /** * XPath expressions to be used when reading a Profile Tag feed */ ProfileTagsXPath : { // used by getEntitiesDataArray entries : "/app:categories/a:category", // used to access data from the feed targetEmail : "app:categories/snx:targetEmail", numberOfContributors : "@snx:numberOfContributors", // used by getEntityData entry : "/app:categories/a:category", // used by getEntityId uid : "@term", // used by getters id : "@term", term : "@term", frequency : "@snx:frequency", intensity : "@snx:intensityBin", visibility : "@snx:visibilityBin", contributorName : "a:name", contributorUserid : "a:userid", contributorEmail : "a:email" }, /** * XPath expressions to be used when reading an invite entry */ InviteXPath : lang.mixin({}, conn.AtomEntryXPath, { connectionType: "a:category[@scheme='http://www.ibm.com/xmlns/prod/sn/connection/type']/@term", status: "a:category[@scheme='http://www.ibm.com/xmlns/prod/sn/status']/@term" }), /** * XML elements to be used when creating a Profile Entry * **/ profileCreateAttributes : { guid : "com.ibm.snx_profiles.base.guid", email : "com.ibm.snx_profiles.base.email", uid : "com.ibm.snx_profiles.base.uid", distinguishedName : "com.ibm.snx_profiles.base.distinguishedName", displayName : "com.ibm.snx_profiles.base.displayName", givenNames : "com.ibm.snx_profiles.base.givenNames", surname : "com.ibm.snx_profiles.base.surname", userState :"com.ibm.snx_profiles.base.userState" }, /** * Retrieve a profile entry. */ AtomProfileDo : "/${profiles}{authType}/atom/profile.do", /** * Update a profile entry. */ AtomProfileEntryDo : "/${profiles}{authType}/atom/profileEntry.do", /** * Retrieve a feed that lists the contacts that a person has designated as colleagues. */ AtomConnectionsDo : "/${profiles}{authType}/atom/connections.do", /** * Retrieve the profiles of the people who comprise a specific user's report-to chain. */ AtomReportingChainDo : "/${profiles}{authType}/atom/reportingChain.do", /** * Retrieve the people managed by a specified person. */ AtomPeopleManagedDo : "/${profiles}{authType}/atom/peopleManaged.do", /** * Retrieve status updates for a specified person. */ AtomConnectionsInCommonDo : "/${profiles}{authType}/atom/connectionsInCommon.do", /** * Search for a set of profiles that match a specific criteria and return them in a feed. */ AtomSearchDo : "/${profiles}{authType}/atom/search.do", /** * Retrieve the profiles of the people who report to a specific user. */ AtomPeopleManagedDo : "/${profiles}{authType}/atom/peopleManaged.do", /** * Retrieve the tags assigned to a profile from the Profiles tag collection. */ AtomTagsDo : "/${profiles}{authType}/atom/profileTags.do", /** * Admin API - create a new profile. */ AdminAtomProfileDo : "/${profiles}/admin/atom/profiles.do", /** * Admin API - delete a profile. */ AdminAtomProfileEntryDo : "/${profiles}/admin/atom/profileEntry.do" },conn); }); }, 'sbt/base/AtomEntity':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * AtomEntity class represents an entry from an IBM Connections ATOM feed. * * @module sbt.base.AtomEntity */ define([ "../declare", "../lang", "../stringUtil", "./BaseConstants", "./BaseEntity", "./XmlDataHandler" ], function(declare,lang,stringUtil,BaseConstants,BaseEntity,XmlDataHandler) { var EntryTmpl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<entry xmlns=\"http://www.w3.org/2005/Atom\" ${createNamespaces}>" + "${categoryScheme}${createTitle}${createContent}${createSummary}${createContributor}${createTags}${createEntryData}" + "</entry>"; var TitleTmpl = "<title type=\"text\">${title}</title>"; var ContentTmpl = "<content type=\"${contentType}\">${content}</content>"; var SummaryTmpl = "<summary type=\"text\">${summary}</summary>"; var ContributorTmpl = "<contributor>${contributor}</contributor>"; var EmailTmpl = "<email>${email}</email>"; var UseridTmpl = "<snx:userid xmlns:snx=\"http://www.ibm.com/xmlns/prod/sn\">${userid}</snx:userid>"; var CategoryTmpl = "<category term=\"${tag}\"></category>"; /** * AtomEntity class represents an entry from an IBM Connections ATOM feed. * * @class AtomEntity * @namespace sbt.base */ var AtomEntity = declare(BaseEntity, { contentType : "html", categoryScheme : null, /** * Construct an AtomEntity. * * @constructor * @param args */ constructor : function(args) { if (args.data) { // create XML data handler this.dataHandler = this.createDataHandler( args.service, args.data || null, args.response || null, args.namespaces || this.namespaces || BaseConstants.Namespaces, args.xpath || this.xpath || BaseConstants.AtomEntryXPath ); } else { this.service = args.service || this.service; this.namespaces = args.namespaces || this.namespaces || BaseConstants.Namespaces; this.xpath = args.xpath || this.xpath || BaseConstants.AtomEntryXPath; } }, /** * Create the DataHandler for this entity. * * @method createDataHandler */ createDataHandler : function(service, data, response, namespaces, xpath) { return new XmlDataHandler({ service : service, data : data, namespaces : namespaces, xpath : xpath }); }, /** * Called to set the entity data after the entity * was loaded. This will cause the existing fields to be cleared. * * @param data */ setData : function(data, response) { // create XML data handler this.dataHandler = this.createDataHandler( this.service, data, response || null, this.namespaces || BaseConstants.Namespaces, this.xpath || BaseConstants.AtomEntryXPath ); this.inherited(arguments); }, /** * Return the value of id from ATOM entry document. * * @method getId * @return {String} ID of the ATOM entry */ getId : function() { return this.getAsString("id"); }, /** * Return the value of title from ATOM entry document. * * @method getTitle * @return {String} ATOM entry title */ getTitle : function() { return this.getAsString("title"); }, /** * Sets title of ATOM entry. * * @method setTitle * @param {String} title ATOM entry title */ setTitle : function(title) { return this.setAsString("title", title); }, /** * Return the value of summary from ATOM entry document. * * @method getSummary * @return {String} ATOM entry summary */ getSummary : function() { return this.getAsString("summary"); }, /** * Sets summary of ATOM entry. * * @method setSummary * @param {String} title ATOM entry summary */ setSummary : function(summary) { return this.setAsString("summary", summary); }, /** * Return the content from ATOM entry document. * * @method getContent * @return {Object} Content */ getContent : function() { return this.getAsString("content"); }, /** * Sets content of ATOM entry. * * @method setContent * @param {String} content */ setContent : function(content) { return this.setAsString("content", content); }, /** * Return array of category terms from ATOM entry document. * * @method getCategoryTerms * @return {Object} Array of categories of the ATOM entry */ getCategoryTerms : function() { return this.getAsArray("categoryTerm"); }, /** * Set new category terms to be associated with this ATOM entry document. * * @method setCategories * @param {Object} Array of categories to be added to the ATOM entry */ setCategoryTerms : function(categoryTerms) { return this.setAsArray("categoryTerm", categoryTerms); }, /** * Gets an author of the ATOM entry * * @method getAuthor * @return {Object} author Author of the ATOM entry */ getAuthor : function() { return this.getAsObject( [ "authorUserid", "authorName", "authorEmail", "authorUserState" ], [ "userid", "name", "email", "userState" ]); }, /** * Gets a contributor of the ATOM entry * * @method getContributor * @return {Object} contributor Contributor of the ATOM entry */ getContributor : function() { return this.getAsObject( [ "contributorUserid", "contributorName", "contributorEmail", "contributorUserState" ], [ "userid", "name", "email", "userState" ]); }, /** * Sets the contributor of the ATOM entry * * @method setContributor * @return {Object} contributor Contributor of the ATOM entry */ setContributor : function(contributor) { return this.setAsObject(contributor); }, /** * Return the published date of the ATOM entry document. * * @method getPublished * @return {Date} Published date of the entry */ getPublished : function() { return this.getAsDate("published"); }, /** * Return the last updated date of the ATOM entry document. * * @method getUpdated * @return {Date} Last updated date of the entry */ getUpdated : function() { return this.getAsDate("updated"); }, /** * Return the alternate url of the ATOM entry document. * * @method getAlternateUrl * @return {String} Alternate url */ getAlternateUrl : function() { return this.getAsString("alternateUrl"); }, /** * Return the self url of the ATOM entry document. * * @method getSelfUrl * @return {String} Self url */ getSelfUrl : function() { return this.getAsString("selfUrl"); }, /** * Return the edit url of the ATOM entry document. * * @method getEditUrl * @return {String} Edit url */ getEditUrl : function() { return this.getAsString("editUrl"); }, /** * Create ATOM entry XML * * @method createPostData * @returns */ createPostData : function() { var postData = stringUtil.transform(EntryTmpl, this, function(v,k) { return v; }, this); return stringUtil.trim(postData); }, /** * Return title element to be included in post data for this ATOM entry. * * @method createTitle * @returns {String} */ createTitle : function() { var title = this.getTitle(); if (title) { return stringUtil.transform(TitleTmpl, { "title" : stringUtil.htmlEntity(title) }); } return ""; }, /** * Return content element to be included in post data for this ATOM entry. * * @method createContent * @returns {String} */ createContent : function() { var content = this.getContent(); if (content) { if (this.contentType == "html") { content = (content && lang.isString(content)) ? content.replace(/</g,"&lt;").replace(/>/g,"&gt;") : content; } return stringUtil.transform(ContentTmpl, { "contentType" : this.contentType, "content" : content }); } return ""; }, /** * Return summary element to be included in post data for this ATOM entry. * * @method createSummary * @returns {String} */ createSummary : function() { var summary = this.getSummary(); if (summary) { return stringUtil.transform(SummaryTmpl, { "summary" : summary }); } return ""; }, /** * Return contributor element to be included in post data for this ATOM entry. * * @method createContributor * @returns {String} */ createContributor : function() { var contributor = this.getContributor(); if (contributor) { var value = ""; var email = contributor.email || ((this.getEmail) ? this.getEmail() : null); if (email) { value += stringUtil.transform(EmailTmpl, { "email" : email }); } var userid = contributor.userid || ((this.getUserid) ? this.getUserid() : null); if (userid) { value += stringUtil.transform(UseridTmpl, { "userid" : userid }); } if (value.length > 0) { value = stringUtil.transform(ContributorTmpl, { "contributor" : value }); } return value; } return ""; }, /** * Return tags elements to be included in post data for this ATOM entry. * * @method createTags * @returns {String} */ createTags : function() { if (this.getTags && this.getTags()) { var value = ""; var tags = this.getTags(); for (var tag in tags) { value += stringUtil.transform(CategoryTmpl, { "tag" : tags[tag] }); } return value; } return ""; }, /** * Return extra entry data to be included in post data for this ATOM entry. * * @method createEntryData * @returns {String} */ createEntryData : function() { return ""; }, /** * return namespaces for this ATOM entry. * * @method createNamespaces */ createNamespaces : function() { var namespaceData = ""; var namespaces = this.dataHandler ? this.dataHandler.namespaces : this.namespaces; for (prefix in namespaces) { if (prefix != "a") { // ATOM automatically included namespaceData += (namespaceData.length > 0) ? " " : ""; namespaceData += "xmlns:"+prefix+"=\"" + namespaces[prefix] + "\""; } } return namespaceData; } }); return AtomEntity; }); }, 'sbt/connections/FollowConstants':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. * Definition of constants for FollowService. */ define([ "../lang", "./ConnectionsConstants" ], function(lang,conn) { return lang.mixin(conn, { /** * Activities Source * * @property ActivitiesSource * @type String * @for sbt.connections.FollowedResource */ ActivitiesSource : "activities", /** * Activity Resource Type * * @property ActivityResourceType * @type String * @for sbt.connections.FollowedResource */ ActivityResourceType : "activity", /** * Blogs Source * * @property BlogsSource * @type String * @for sbt.connections.FollowedResource */ BlogsSource : "blogs", /** * Blog Resource Type * * @property BlogResourceType * @type String * @for sbt.connections.FollowedResource */ BlogResourceType : "blog", /** * Communities Source * * @property CommunitiesSource * @type String * @for sbt.connections.FollowedResource */ CommunitiesSource : "communities", /** * Community Resource Type * * @property CommunitiesResourceType * @type String * @for sbt.connections.FollowedResource */ CommunitiesResourceType : "community", /** * Files Source * * @property FilesSource * @type String * @for sbt.connections.FollowedResource */ FilesSource : "files", /** * File Resource Type * * @property FileResourceType * @type String * @for sbt.connections.FollowedResource */ FileResourceType : "file", /** * FileFolder Resource Type * * @property FileFolderResourceType * @type String * @for sbt.connections.FollowedResource */ FileFolderResourceType : "file_folder", /** * Forums Source * * @property ForumsSource * @type String * @for sbt.connections.FollowedResource */ ForumsSource : "forums", /** * Forum Resource Type * * @property ForumResourceType * @type String * @for sbt.connections.FollowedResource */ ForumResourceType : "forum", /** * ForumTopic Resource Type * * @property ForumTopicResourceType * @type String * @for sbt.connections.FollowedResource */ ForumTopicResourceType : "forum_topic", /** * Profile Source * * @property ProfilesSource * @type String * @for sbt.connections.FollowedResource */ ProfilesSource : "profiles", /** * Profile Resource Type * * @property ProfilesResourceType * @type String * @for sbt.connections.FollowedResource */ ProfilesResourceType : "profile", /** * Wikis Source * * @property WikisSource * @type String * @for sbt.connections.FollowedResource */ WikisSource : "wikis", /** * Wiki Resource Type * * @property WikiResourceType * @type String * @for sbt.connections.FollowedResource */ WikiResourceType : "wiki", /** * WikiPage Resource Type * * @property WikiPageResourceType * @type String * @for sbt.connections.FollowedResource */ WikiPageResourceType : "wiki_page", /** * Tags Source * * @property TagsSource * @type String * @for sbt.connections.FollowedResource */ TagsSource : "tags", /** * Tag Resource Type * * @property TagResourceType * @type String * @for sbt.connections.FollowedResource */ TagResourceType : "tag", /** * Get the followed resources feed * * @method getFollowedResources * @param {String} source String specifying the resource. Options are: * * activities * blogs * communities * files * forums * profiles * wikis * tags * * @param {String} resourceType String representing the resource type. Options are: * * If source=activities * activity * * If source=blogs * blog * * If source=communities * community * * If source=files * file * file_folder * * * If source=forums * forum * forum_topic * * * If source=profiles * profile * * If source=wikis * wiki * wiki_page * * * If source=tags * tag * * @param {Object} [args] Object representing various parameters * that can be passed to get a feed of members of a * community. The parameters must be exactly as they are * supported by IBM Connections like ps, sortBy etc. */ FollowedResourceFeedXPath : conn.ConnectionsFeedXPath, /** * XPath expressions to be used when reading a followed resource entry */ FollowedResourceXPath : lang.mixin({}, conn.AtomEntryXPath, { followedResourceUuid : "a:id", categoryType : "a:category[@scheme='http://www.ibm.com/xmlns/prod/sn/type']/@term", source : "a:category[@scheme='http://www.ibm.com/xmlns/prod/sn/source']/@term", resourceType : "a:category[@scheme='http://www.ibm.com/xmlns/prod/sn/resource-type']/@term", resourceId : "a:category[@scheme='http://www.ibm.com/xmlns/prod/sn/resource-id']/@term", relatedUrl : "a:link[@rel='related']/@href" }), /** * XPath expressions to be used when reading a followed resource entry */ OneFollowedResourceXPath : lang.mixin({}, conn.AtomEntryXPath, { entry : "/a:feed/a:entry", followedResourceUuid : "a:id", categoryType : "a:category[@scheme='http://www.ibm.com/xmlns/prod/sn/type']/@term", source : "a:category[@scheme='http://www.ibm.com/xmlns/prod/sn/source']/@term", resourceType : "a:category[@scheme='http://www.ibm.com/xmlns/prod/sn/resource-type']/@term", resourceId : "a:category[@scheme='http://www.ibm.com/xmlns/prod/sn/resource-id']/@term", relatedUrl : "a:link[@rel='related']/@href" }), /** * Get, follow or stop following a resource. */ AtomFollowAPI : "/{service}/follow/atom/resources", /** * Get, follow or stop following a resource. */ AtomStopFollowAPI : "/{service}/follow/atom/resources/{resourceId}" }); }); }, 'sbt/defer':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Defer plugin. * @author Carlos Manias */ define([], function(text) { return { load: function (id, require, load) { require([id], function (value) { load(value); }); } }; }); }, 'sbt/nls/Endpoint':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK - Default resource bundle for validate module. */ define({ root: ({ cannot_find_endpoint:"Unable to find endpoint named {0}, creating it now with an error transport." }) }); }, 'sbt/nls/ErrorTransport':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK - Default resource bundle for validate module. */ define({ root: ({ endpoint_not_available:"Required endpoint is not available: {0}" }) }); }, 'sbt/connections/ForumConstants':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. * Definition of constants for ForumService. */ define([ "../lang", "./ConnectionsConstants" ], function(lang,conn) { return lang.mixin(conn, { /** * Term value with a forum recommendation */ FlagAnswer : "recommendation", /** * Term value when a forum reply is an accepted answer */ FlagAnswer : "answer", /** * Term value when a forum topic is pinned */ FlagPinned : "pinned", /** * Term value when a forum topic is locked */ FlagLocked : "locked", /** * Term value when a forum topic is a question */ FlagQuestion : "question", /** * Term value when a forum topic is an answered question */ FlagAnswered : "answered", /** * Category term and scheme to lock a topic */ setLocked: "locked scheme=\"http://www.ibm.com/xmlns/prod/sn/flags\"", /** * Category term and scheme to pin a topic */ setPinned: "pinned scheme=\"http://www.ibm.com/xmlns/prod/sn/flags\"", /** * Category term and scheme to mark a topic as a question */ markAsQuestion: "question scheme=\"http://www.ibm.com/xmlns/prod/sn/flags\"", /** * XPath expressions used when parsing a Connections Forums ATOM feed */ ForumsFeedXPath : conn.ConnectionsFeedXPath, /** * XPath expressions to be used when reading an forum entry */ ForumXPath : lang.mixin({ forumUuid : "a:id", content : "a:content[@type='text']", tags : "a:category[not(@scheme)]/@term", moderation : "snx:moderation/@status", threadCount: "a:link[@rel='replies']/@thr:count", forumUrl : "a:link[@rel='alternate']/@href", communityUuid : "snx:communityUuid" }, conn.AtomEntryXPath), /** * XPath expressions to be used when reading an forum topic entry */ ForumTopicXPath : lang.mixin({ topicUuid : "a:id", topicTitle: "a:title", forumUuid : "thr:in-reply-to/@ref", tags : "a:category[not(@scheme)]/@term", permissions : "snx:permissions", communityUuid : "snx:communityUuid", threadCount: "a:link[@rel='replies']/@thr:count", locked: "a:category[@term='locked' and @scheme='http://www.ibm.com/xmlns/prod/sn/flags']", pinned: "a:category[@term='pinned' and @scheme='http://www.ibm.com/xmlns/prod/sn/flags']", question: "a:category[@term='question' and @scheme='http://www.ibm.com/xmlns/prod/sn/flags']", answered: "a:category[@term='answered' and @scheme='http://www.ibm.com/xmlns/prod/sn/flags']", notRecommendedByCurrentUser: "a:category[@term='NotRecommendedByCurrentUser']", threadRecommendationCount: "a:category[@term='ThreadRecommendationCount']/@label", recommendationsUrl : "a:link[@rel='recommendations']/@href" }, conn.AtomEntryXPath), /** * XPath expressions to be used when reading an forum reply entry */ ForumReplyXPath : lang.mixin({ replyUuid : "a:id", topicUuid : "thr:in-reply-to/@ref", permissions : "snx:permissions", communityUuid : "snx:communityUuid", answer: "a:category[@term='answer' and @scheme='http://www.ibm.com/xmlns/prod/sn/flags']", replyTo: "thr:in-reply-to/@ref", notRecommendedByCurrentUser: "a:category[@term='NotRecommendedByCurrentUser']", recommendationsUrl : "a:link[@rel='recommendations']/@href" }, conn.AtomEntryXPath), /** * XPath expressions to be used when reading an forum recommendation entry */ ForumRecommendationXPath : lang.mixin({ postUuid : "a:link[@rel='self']/@href" }, conn.AtomEntryXPath), /** * Edit link for a forum entry. */ AtomForum : "${forums}/atom/forum", /** * Edit link for a forum topic entry. */ AtomTopic : "/${forums}/atom/topic", /** * Edit link for a forum reply entry. */ AtomReply : "/${forums}/atom/reply", /** * Get a feed that includes all stand-alone and community forums created in the enterprise. */ AtomForums : "/${forums}/atom/forums", /** * Get a feed that includes all of the forums hosted by the Forums application. */ AtomForumsPublic : "/${forums}/atom/forums/public", /** * Get a feed that includes forums created by the authenticated user or associated with communities to which the user belongs. */ AtomForumsMy : "/${forums}/atom/forums/my", /** * Get a feed that includes the topics in a specific stand-alone forum. */ AtomTopics : "/${forums}/atom/topics", /** * Get a feed that includes the topics that the authenticated user created in stand-alone forums and in forums associated * with communities to which the user belongs. */ AtomTopicsMy : "/${forums}/atom/topics/my", /** * Get a feed that includes all of the replies for a specific forum topic. */ AtomReplies : "/${forums}/atom/replies", /** * Get a category document that lists the tags that have been assigned to forums. */ AtomTagsForum : "/atom/tags/forums", /** * Get a category document that lists the tags that have been assigned to forum topics. */ AtomTagsTopics : "/atom/tags/topics", /** * Get a feed that includes all of the recommendations for a specific forum post. */ AtomRecommendationEntries : "/${forums}/atom/recommendation/entries" }); }); }, 'sbt/stringUtil':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Defination of some string Utilities * * @module sbt.stringUtil */ define(['./xml'], function(xml) { var _regex = new RegExp("{-?[0-9]+}", "g"); return { /** * Substitutes the String with pattern {<<number>>} with argument array provided. {-1} is for printing '{' and {-2} is for printing '}' in the text * * @param {String} [str] String to be formatted * @param {Array} [args] arguments Array * @param {Boolean} [useBlankForUndefined = false] optional flag to indicate to user blank String in case index is not found in args. * @static * @method substitute */ substitute : function(str, args, useBlankForUndefined) { if (str && args) { return str.replace(_regex, function(item) { var intVal = parseInt(item.substring(1, item.length - 1)); var replace; if (intVal >= 0) { replace = args[intVal] ? args[intVal] : useBlankForUndefined ? "" : "undefined"; } else if (intVal == -1) { replace = "{"; } else if (intVal == -2) { replace = "}"; } else { replace = ""; } return replace; }); } return str; }, /** * Replaces the String with pattern {<<string>>} with argument map provided. Replaces blank if key to be replaces is not found in argsMap. * * @param {String} [str] String to be formatted * @param {Array} [argsMap] arguments Map * @static * @method replace */ replace : function(str, argsMap) { if (str && argsMap) { return str.replace(/{(\w*)}/g, function(m, key) { var replace; replace = argsMap.hasOwnProperty(key) ? xml.encodeXmlEntry(argsMap[key]) : ""; return replace; }); } return str; }, trim: function x_trim(s) { return s ? s.replace(/^\s+|\s+$/g,"") : s; }, startsWith: function x_sw(s,prefix) { return s.length>=prefix.length && s.substring(0,prefix.length)==prefix; }, endsWith: function x_ew(s,suffix) { return s.length>=suffix.length && s.substring(s.length-suffix.length)==suffix; }, transform: function(template, map, transformer, thisObject) { return template.replace(/\$\{([^\s\:\}]+)(?:\:([^\s\:\}]+))?\}/g, function(match, key, format){ var value = map[key] || ""; if (typeof value == 'function') { // invoke function to return the value try { value = value.apply(thisObject, [ map ]); } catch (ex) { value = "ERROR:" + key + " " + ex; } } if (transformer) { value = transformer.call(thisObject, value, key); } if (typeof value == "undefined" || value == null) { return ""; } return value.toString(); } ); }, hashCode: function(str) { if (str.length == 0) { return 0; } var hash = 0, i, charStr; for (i = 0, l = str.length; i < l; i++) { charStr = str.charCodeAt(i); hash = ((hash<<5)-hash)+charStr; hash |= 0; } return hash; }, htmlEntity : function(htmlContent){ return htmlContent.replace(/[\u00A0-\u9999<>\&]/gim, function(c) { return '&#'+c.charCodeAt(0)+';'; }); } }; }); }, 'sbt/base/XmlDataHandler':function(){ /* * © Copyright IBM Corp. 2012,2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. Helpers for the base capabilities of data * handlers. * * @module sbt.base.DataHandler */ define([ "../declare", "../lang", "../stringUtil", "../xml", "../xpath", "./DataHandler" ], function(declare,lang,stringUtil,xml,xpath,DataHandler) { /** * XmlDataHandler class * * @class XmlDataHandler * @namespace sbt.base */ var XmlDataHandler = declare(DataHandler, { /** * Data type for this DataHandler is 'xml' */ dataType : "xml", /** * Set of XPath expressions used by this handler. Required for entity: * uid, entry Required for summary: totalResults, startIndex, * itemsPerPage */ xpath : null, /** * Set of namespaces used by this handler. */ namespaces : null, /** * Set of values that have already been read. */ _values : null, /** * Summary of a feed. */ _summary : null, /** * @constructor * @param {Object} * args Arguments for this data handler. */ constructor : function(args) { lang.mixin(this, args); this._values = {}; // TODO option to disable cache this.data = this._fromNodeOrString(args.data); }, /** * Called to set the handler data. * * @param data */ setData : function(data) { this._values = {}; // TODO option to disable cache this.data = this._fromNodeOrString(data); }, /** * @method getAsString * @param property * @returns */ getAsString : function(property) { this._validateProperty(property, "getAsString"); if (this._values) { if (!this._values.hasOwnProperty(property)) { this._values[property] = this._selectText(property); } return this._values[property]; } else { return _selectText(property); } }, /** * @method getAsNumber * @param property * @returns */ getAsNumber : function(property) { this._validateProperty(property, "getAsNumber"); if (this._values) { if (!this._values.hasOwnProperty(property)) { this._values[property] = this._selectNumber(property); } return this._values[property]; } else { return this._selectNumber(property); } }, /** * @method getAsDate * @param property * @returns */ getAsDate : function(property) { this._validateProperty(property, "getAsDate"); if (this._values) { if (!this._values.hasOwnProperty(property)) { this._values[property] = this._selectDate(property); } return this._values[property]; } else { return this._selectDate(property); } }, /** * @method getAsBoolean * @param property * @returns */ getAsBoolean : function(property) { this._validateProperty(property, "getAsBoolean"); if (this._values) { if (!this._values.hasOwnProperty(property)) { this._values[property] = this._selectBoolean(property); } return this._values[property]; } else { return this._selectBoolean(property); } }, /** * @method getAsArray * @param property * @returns */ getAsArray : function(property) { this._validateProperty(property, "getAsArray"); if (this._values) { if (!this._values.hasOwnProperty(property)) { this._values[property] = this._selectArray(property); } return this._values[property]; } else { return this._selectArray(property); } }, /** * @method getNodesArray * @param property * @returns */ getAsNodesArray : function(property) { this._validateProperty(property, "getNodesArray"); if (this._values) { if (!this._values.hasOwnProperty(property)) { this._values[property] = this._selectNodesArray(property); } return this._values[property]; } else { return this._selectNodesArray(property); } }, /** * @method getEntityId * @returns */ getEntityId : function() { return stringUtil.trim(this.getAsString("uid")); }, /** * getEntityData * * @returns */ getEntityData : function(document) { var entry = this.xpath["entry"]; if (!entry) { return document; } if (!this._values["entry"]) { var nodes = xpath.selectNodes(document, entry, this.namespaces); this._values["entry"] = nodes[0] || null; } return this._values["entry"]; }, /** * @method getSummary * @returns */ getSummary : function() { if (!this._summary && this._getXPath("totalResults")) { this._summary = { totalResults : xpath.selectNumber(this.data, this._getXPath("totalResults"), this.namespaces), startIndex : xpath.selectNumber(this.data, this._getXPath("startIndex"), this.namespaces), itemsPerPage : xpath.selectNumber(this.data, this._getXPath("itemsPerPage"), this.namespaces) }; } return this._summary; }, /** * @method getEntitiesDataArray * @returns {Array} */ getEntitiesDataArray : function() { var entries = this.xpath["entries"]; if (!entries) { return this.data; } if (!this._values["entries"]) { this._values["entries"] = xpath.selectNodes(this.data, entries, this.namespaces); } return this._values["entries"]; }, /** * @method toJson * @returns {Object} */ toJson : function() { var jsonObj = {}; for (var name in this.xpath) { if (this.xpath.hasOwnProperty(name)) { jsonObj[name] = this.getAsString(name); } } return jsonObj; }, /* * Convert the input to a node by parsing as string and using * getEntityData, if not already one */ _fromNodeOrString : function(nodeOrString) { if (lang.isString(nodeOrString)) { nodeOrString = stringUtil.trim(nodeOrString); var document = xml.parse(nodeOrString); return this.getEntityData(document); } return nodeOrString; }, /* * Return xpath expression from the set or the property itself (assume * it's already xpath) */ _getXPath : function(property) { return this.xpath[property] || property; }, /* * Validate that the property is valid */ _validateProperty : function(property, method) { if (!property) { var msg = stringUtil.substitute("Invalid argument for XmlDataHandler.{1} {0}", [ property, method ]); throw new Error(msg); } }, /* * Select xpath as string */ _selectText : function(property) { if (!this.data) { return null; } return stringUtil.trim(xpath.selectText(this.data, this._getXPath(property), this.namespaces)); }, /* * Select xpath as number */ _selectNumber : function(property) { if (!this.data) { return null; } return xpath.selectNumber(this.data, this._getXPath(property), this.namespaces); }, /* * Select xpath as date */ _selectDate : function(property) { if (!this.data) { return null; } var text = this._selectText(property); return text ? new Date(Date.parse(text)) : null; }, /* * Select xpath as boolean */ _selectBoolean : function(property) { if (!this.data) { return false; } var nodes = xpath.selectNodes(this.data, this._getXPath(property), this.namespaces); var ret = false; if (nodes) { if (nodes.length == 1) { // handle case were node has text value equal true/false var text = stringUtil.trim(nodes[0].text || nodes[0].textContent); if (text) { text = text.toLowerCase(); if ("false" == text) { return false; } if ("true" == text) { return true; } } } ret = (nodes.length > 0); } return ret; }, /* * Select xpath as array */ _selectArray : function(property) { if (!this.data) { return null; } var nodes = xpath.selectNodes(this.data, this._getXPath(property), this.namespaces); var ret = null; if (nodes) { ret = []; for ( var i = 0; i < nodes.length; i++) { ret.push(stringUtil.trim(nodes[i].text || nodes[i].textContent)); } } return ret; }, /* * Select xpath as nodes array */ _selectNodesArray : function(property) { if (!this.data) { return null; } return xpath.selectNodes(this.data, this._getXPath(property), this.namespaces); } }); return XmlDataHandler; }); }, 'sbt/base/BaseEntity':function(){ /* * © Copyright IBM Corp. 2012, 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Javascript Base APIs for IBM Connections * * @module sbt.base.BaseEntity */ define([ "../declare", "../lang", "../log", "../stringUtil" ], function(declare,lang,log,stringUtil) { var BadRequest = 400; var requests = {}; /** * BaseEntity class * * @class BaseEntity * @namespace sbt.base */ var BaseEntity = declare(null, { /** * The identifier for this entity. */ id : null, /** * The service associated with the entity. */ service : null, /** * The DataHandler associated with this entity. */ dataHandler : null, /** * The fields which have been updated in this entity. * * @private */ _fields : null, /** * Constructor for BaseEntity * * @constructor * @param {Object} args Arguments for this entity. */ constructor : function(args) { lang.mixin(this, args); if (!this._fields) { this._fields = {}; } if (!this.service) { var msg = "Invalid BaseEntity, an associated service must be specified."; throw new Error(msg); } }, /** * Called to set the entity DataHandler after the entity * was loaded. This will cause the existing fields to be cleared. * * @param datahandler */ setDataHandler : function(dataHandler) { this._fields = {}; this.dataHandler = dataHandler; }, /** * Called to set the entity data after the entity * was loaded. This will cause the existing fields to be cleared. * * @param data */ setData : function(data, response) { this._fields = {}; this.dataHandler.setData(data); }, /** * Return true if this entity has been loaded. * * @returns true if this entity has been loaded */ isLoaded : function() { if (this.dataHandler) { return this.dataHandler.getData() ? true : false; } return false; }, /** * Get the string value of the specified field. * * @method getAsString * @param fieldName * @returns */ getAsString : function(fieldName) { this._validateFieldName(fieldName, "getAsString"); if (this._fields.hasOwnProperty(fieldName)) { return this._fields[fieldName]; } else if (this.dataHandler) { return this.dataHandler.getAsString(fieldName); } else { return null; } }, /** * Get the number value of the specified field. * * @method getAsNumber * @param fieldName * @returns */ getAsNumber : function(fieldName) { this._validateFieldName(fieldName, "getAsNumber"); if (this._fields.hasOwnProperty(fieldName)) { return this._fields[fieldName]; } else if (this.dataHandler) { return this.dataHandler.getAsNumber(fieldName); } else { return null; } }, /** * Get the date value of the specified field. * * @method getAsDate * @param fieldName * @returns */ getAsDate : function(fieldName) { this._validateFieldName(fieldName, "getAsDate"); if (this._fields.hasOwnProperty(fieldName)) { return this._fields[fieldName]; } else if (this.dataHandler) { return this.dataHandler.getAsDate(fieldName); } else { return null; } }, /** * Get the boolean value of the specified field. * * @method getAsBoolean * @param fieldName * @returns */ getAsBoolean : function(fieldName) { this._validateFieldName(fieldName, "getAsBoolean"); if (this._fields.hasOwnProperty(fieldName)) { return this._fields[fieldName]; } else if (this.dataHandler) { return this.dataHandler.getAsBoolean(fieldName); } else { return false; } }, /** * Get the array value of the specified field. * * @method getAsArray * @param fieldName * @returns */ getAsArray : function(fieldName) { this._validateFieldName(fieldName, "getAsArray"); if (this._fields.hasOwnProperty(fieldName)) { return this._fields[fieldName]; } else if (this.dataHandler) { return this.dataHandler.getAsArray(fieldName); } else { return null; } }, /** * Get the nodes array value of the specified field. * * @method getAsNodesArray * @param fieldName * @returns */ getAsNodesArray : function(fieldName) { this._validateFieldName(fieldName, "getAsNodesArray"); if (this._fields.hasOwnProperty(fieldName)) { return this._fields[fieldName]; } else if (this.dataHandler) { return this.dataHandler.getAsNodesArray(fieldName); } else { return null; } }, /** * Get an object containing the values of the specified fields. * * @method getAsObject * @param fieldNames * @returns */ getAsObject : function(fieldNames, objectNames) { var obj = {}; for (var i=0; i<fieldNames.length; i++) { this._validateFieldName(fieldNames[i], "getAsObject"); var fieldValue = this.getAsString(fieldNames[i]); if (fieldValue) { if (objectNames) { obj[objectNames[i]] = fieldValue; } else { obj[fieldNames[i]] = fieldValue; } } } return obj; }, /** * @method setAsString * @param data * @returns */ setAsString : function(fieldName,string) { this._validateFieldName(fieldName, "setAsString", string); if (string === null || string === undefined) { delete this._fields[fieldName]; } else { this._fields[fieldName] = string.toString(); } return this; }, /** * @method setAsNumber * @returns */ setAsNumber : function(fieldName,numberOrString) { this._validateFieldName(fieldName, "setAsNumber", numberOrString); if (numberOrString instanceof Number) { this._fields[fieldName] = numberOrString; } else { if (numberOrString) { var n = new Number(numberOrString); if (isNaN(n)) { var msg = stringUtil.substitute("Invalid argument for BaseService.setAsNumber {0},{1}", [ fieldName, numberOrString ]); throw new Error(msg); } else { this._fields[fieldName] = n; } } else { delete this._fields[fieldName]; } } return this; }, /** * @method setAsDate * @returns */ setAsDate : function(fieldName,dateOrString) { this._validateFieldName(fieldName, "setAsDate", dateOrString); if (dateOrString instanceof Date) { this._fields[fieldName] = dateOrString; } else { if (dateOrString) { var d = new Date(dateOrString); if (isNaN(d.getDate())) { var msg = stringUtil.substitute("Invalid argument for BaseService.setAsDate {0},{1}", [ fieldName, dateOrString ]); throw new Error(msg); } else { this._fields[fieldName] = d; } } else { delete this._fields[fieldName]; } } return this; }, /** * @method setAsBoolean * @returns */ setAsBoolean : function(fieldName,booleanOrString) { this._validateFieldName(fieldName, "setAsBoolean", booleanOrString); if (booleanOrString != null) { this._fields[fieldName] = booleanOrString ? true : false; } else { delete this._fields[fieldName]; } return this; }, /** * @method setAsArray * @returns */ setAsArray : function(fieldName,arrayOrString) { this._validateFieldName(fieldName, "setAsArray", arrayOrString); if (lang.isArray(arrayOrString)) { this._fields[fieldName] = arrayOrString.slice(0); } else if (lang.isString(arrayOrString)) { if (arrayOrString.length > 0) { this._fields[fieldName] = arrayOrString.split(/[ ,]+/); } else { this._fields[fieldName] = []; } } else { if (arrayOrString) { this._fields[fieldName] = [ arrayOrString ]; } else { delete this._fields[fieldName]; } } return this; }, /** * Set an object containing the values of the specified fields. * * @method setAsObject * @param theObject * @returns */ setAsObject : function(theObject) { for (var property in theObject) { if (theObject.hasOwnProperty(property)) { var value = theObject[property]; if (value) { this._fields[property] = value; } else { delete this._fields[property]; } } } }, /** * Remove the value of the specified field. * * @method remove * @param fieldName */ remove : function(fieldName) { delete this._fields[fieldName]; }, /** * Return the json representation of the entity * * @method toJson * @returns {Object} */ toJson : function() { return (this.dataHandler) ? this.dataHandler.toJson() : {}; }, /* * Validate there is a valid field name */ _validateFieldName : function(fieldName, method, value) { if (!fieldName) { var msg = stringUtil.substitute("Invalid argument for BaseService.{1} {0},{2}", [ fieldName, method, value || "" ]); throw new Error(msg); } } }); return BaseEntity; }); }, 'sbt/smartcloud/ProfileConstants':function(){ /* * © Copyright IBM Corp. 2012,2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. Definition of constants for ProfileService. */ define([ "../lang" ], function(lang) { return lang.mixin( {} , { /** * Default size for the profile cache */ DefaultCacheSize : 10, /** * Retrieve the profile entry of the logged in user. */ GetProfile : "/lotuslive-shindig-server/social/rest/people/@me/@self", /** * Retrieve the logged in user's profile connections. */ GetMyConnections : "/lotuslive-shindig-server/social/rest/people/@me/@friends", /** * Retrieve a profile's user Identity. */ GetUserIdentity : "/manage/oauth/getUserIdentity", /** * Retrieve a Contact's Profile. */ GetContactByGUID : "/lotuslive-shindig-server/social/rest/people/lotuslive:contact:{idToBeReplaced}/@self", /** * Retrieve a profiles entry using GUID. */ GetProfileByGUID : "/lotuslive-shindig-server/social/rest/people/lotuslive:user:{idToBeReplaced}/@self", /** * Retrieve the logged in user's profile contacts. */ GetMyContacts : "/lotuslive-shindig-server/social/rest/people/@me/@all", /** * JsonPath expressions to be used when reading a Profile Entry */ ProfileJsonPath : { thumbnailUrl : "$..photo", address : "$..address", department : "$..name", jobTitle : "$..jobtitle", telephone : "$..telephone", about : "$..aboutMe", id : "$..id", objectId : "$..objectId", displayName : "$..displayName", emailAddress : "$..emailAddress", profileUrl : "$..profileUrl", country : "$..country", orgId : "$..orgId", org : "$..org.name", global : "$..", firstElement : "$[0]", totalResults : "totalResults", startIndex : "startIndex", itemsPerPage : "itemsPerPage" } }); }); }, 'sbt/MockTransport':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. * * Implementation of a transport which returns mock data. */ define([ "./declare", "./lang", "./dom", "./xml", "./json", "./stringUtil", "./Promise" ], function(declare, lang, dom, xml, json, stringUtil, Promise) { return declare(null, { requestMap : {}, /** * Provides mock data if available in the DOM. */ request : function(url, options) { var query = this.createQuery(options.query); if(url && query){ url += (~url.indexOf('?') ? '&' : '?') + query; } var promise = new Promise(); promise.response = new Promise(); var id = url; var hash = stringUtil.hashCode(id); if (this.requestMap[hash]) { this.requestMap[hash] = this.requestMap[hash] + 1; id += "#" + this.requestMap[hash]; } else { this.requestMap[hash] = 1; } var domNode = dom.byId(id); if (domNode) { var response = domNode.text || domNode.textContent; var handleAs = domNode.getAttribute("handleAs"); if (handleAs == "json") { response = json.parse(response); } var status = domNode.getAttribute("status"); var error = domNode.getAttribute("error"); if (error == "true") { var error = new Error(); error.code = Number(status || 400); error.message = this.getErrorText(response); error.response = this.createResponse(url, options, response, Number(status || 400), {}); promise.rejected(error); promise.response.rejected(error); } else { var location = domNode.getAttribute("location"); var headers = { Location : location }; promise.fulfilled(response); promise.response.fulfilled(this.createResponse(url, options, response, Number(status || 200), headers)); } } else { var message = "Unable to find mock response for: "+url; var error = new Error(message); error.response = { status : 400 , message : message }; promise.rejected(error); promise.response.rejected(error); } return promise; }, /* * Create a response object */ createResponse: function(url, options, response, status, headers) { var handleAs = options.handleAs || "text"; return { url : url, options : options, data : response, text : (handleAs == "text") ? response : null, status : status, getHeader : function(headerName) { return headers[headerName]; } }; }, /* * Create a query string from an object */ createQuery: function(queryMap) { if (!queryMap) { return null; } var pairs = []; for(var name in queryMap){ var value = queryMap[name]; pairs.push(encodeURIComponent(name) + "=" + encodeURIComponent(value)); } return pairs.join("&"); }, getErrorText: function(text) { if (text) { try { var dom = xml.parse(text); var messages = dom.getElementsByTagName("message"); if (messages && messages.length != 0) { text = messages[0].text || messages[0].textContent; text = lang.trim(text); } } catch(ex) {} return text.replace(/(\r\n|\n|\r)/g,""); } else { return text; } } }); }); }, 'sbt/lang':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK - Some language utilities. */ define(['./_bridge/lang'],function(lang) { // The actual implementation is library dependent return lang; }); }, 'sbt/Endpoint':function(){ /* * (C) Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Definition of the endpoint module * @module sbt.Endpoint */ /** * Endpoint which defines a connection to a back-end server. * * @module sbt.Endpoint */ define(['./declare','./lang','./ErrorTransport','./Promise','./pathUtil','./compat','./log', './stringUtil', 'sbt/i18n!sbt/nls/Endpoint', './xml'], function(declare,lang,ErrorTransport,Promise,pathUtil,compat,log,stringUtil,nls,xml) { /** * This class encapsulates an actual endpoint, with its URL, proxy and its authentication mechanism. * * @class sbt.Endpoint */ var Endpoint = declare(null, { /** * URL of the server used to connect to the endpoint * @property baseUrl * @type String */ baseUrl: null, /** * Proxy to be used * @property proxy * @type String */ proxy: null, /** * Path to be added to the proxy url, if any * @property proxyPath * @type String */ proxyPath: null, /** * Transport to be used * @property transport * @type String */ transport: null, /** * Authenticator to be used * @property authenticator * @type String */ authenticator: null, /** * Auth Type to be used * @property authType * @type String */ authType: null, /** * UI Login mode: mainWindow, dialog or popup * @property loginUi * @type String */ loginUi: "", /** * Page for login form for mainWindow and popup * @property loginPage * @type String */ loginPage: null, /** * Page for login form for dialog * @property dialogLoginPage * @type String */ dialogLoginPage: null, /** * Whether auth dialog should come up automatically or not. In case of not 401 would be propagated to user. * @property autoAuthenticate * @type String */ autoAuthenticate: null, /** * Whether user is authenticated to endpoint or not. * @property isAuthenticated * @type String */ isAuthenticated: false, /** * The error code that is returned from the endpoint on authentication failure. * @property authenticationErrorCode * @type String */ authenticationErrorCode: null, /** * Simple constructor that mixes in its parameters as object properties * @constructor * @param {Array} args */ constructor: function(args) { lang.mixin(this, args || {}); }, /** * Provides an asynchronous request using the associated Transport. * * @method request * @param {String) * url The URL the request should be made to. * @param {String) * loginUi The type of UI to use when authenticating, * valid values are: mainWindow, popup, dialog. * @param {Boolean) * authAuthenticate if true the Endpoint with authenticate * when a 401 (or associated authenication code) is received. * @param {Object} * [options] Optional A hash of any options for the provider. * @param {String|Object} * [options.data=null] Data, if any, that should be sent with * the request. * @param {String|Object} * [options.query=null] The query string, if any, that should * be sent with the request. * @param {Object} * [options.headers=null] The headers, if any, that should * be sent with the request. * @param {Boolean} * [options.preventCache=false] If true will send an extra * query parameter to ensure the the server won't supply * cached values. * @param {String} * [options.method=GET] The HTTP method that should be used * to send the request. * @param {Integer} * [options.timeout=null] The number of milliseconds to wait * for the response. If this time passes the request is * canceled and the promise rejected. * @param {String} * [options.handleAs=text] The content handler to process the * response payload with. * @return {sbt.Promise} */ request : function(url, options) { // rewrite the url if needed var qurl = url; if (qurl.indexOf("http") != 0) { if (this.proxy) { qurl = this.proxy.rewriteUrl(this.baseUrl, url, this.proxyPath); } else { qurl = pathUtil.concat(this.baseUrl, url); } } if (!options) { options = { method : "GET", handleAs : "text" }; } options.name = this.name; var promise = new Promise(); promise.response = new Promise(); var self = this; this.transport.request(qurl, options).response.then(function(response) { // Check for form based authentication if(self.authType == "form"){ var authRequiredFlag = self._isAuthRequiredFormBasedEP(response, options); if(authRequiredFlag){ self._authenticate(url, options, promise); } } promise.fulfilled(response.data); promise.response.fulfilled(response); }, function(error) { if (!error.message) { error.message = self.getErrorMessage(error.cause); } var authRequiredPromise = self._isAuthRequired(error, options); authRequiredPromise.then( function(response) { if (response) { self._authenticate(url, options, promise); } else { promise.rejected(error); promise.response.rejected(error); } }, function(error) { promise.rejected(error); promise.response.rejected(error); } ); }); return promise; }, /* * Sends a request using XMLHttpRequest with the given URL and options. * * @method xhr * @param {String} [method] The HTTP method to use to make the request. Must be uppercase. Default is 'GET'. * @param {Object} [args] * @param {String} [args.url] * @param {Function} [args.handle] * @param {Function} [args.load] * @param {Function} [args.error] * @param {Boolean} [hasBody] */ xhr: function(method,args,hasBody) { var self = this; var _args = lang.mixin({},args); // We make sure that args has a 'url' member, with or without a proxy if(!_args.url) { if(this.proxy) { _args.url = this.proxy.rewriteUrl(this.baseUrl,_args.serviceUrl,this.proxyPath); } else { _args.url = pathUtil.concat(this.baseUrl,_args.serviceUrl); } } // Make sure the initial methods are not called // seems that Dojo still call error(), even when handle is set delete _args.load; delete _args.error; _args.handle = function(data,ioArgs) { if(data instanceof Error) { var error = data; if(!error.message){ error.message = self.getErrorMessage(error.cause); } var isForbiddenErrorButAuthenticated = false; // check for if authentication is required if(error.code == 403 && self.authenticationErrorCode == 403){ // case where 403 is configured to be treated similar to 401 (unAuthorized) // checking if we are getting 403 inspite of being already authenticated (eg. Get Public Files/Folders API on Smartcloud if(self.isAuthenticated){ isForbiddenErrorButAuthenticated = true; } } if ((error.code == 401)|| (!isForbiddenErrorButAuthenticated && error.code == self.authenticationErrorCode)) { var autoAuthenticate = _args.autoAuthenticate || self.autoAuthenticate; if(autoAuthenticate == undefined){ autoAuthenticate = true; } if(autoAuthenticate){ if(self.authenticator) { options = { dialogLoginPage:self.loginDialogPage, loginPage:self.loginPage, transport:self.transport, proxy: self.proxy, proxyPath: self.proxyPath, loginUi: _args.loginUi || self.loginUi, name: self.name, callback: function() { self.xhr(method,args,hasBody); } }; if(self.authenticator.authenticate(options)) { return; } } } } // notify handle and error callbacks is available self._notifyError(args, error, ioArgs); } else { // notify handle and load callbacks is available self._notifyResponse(args, data, ioArgs); } }; this.transport.xhr(method, _args, hasBody); }, /* * @method xhrGet * @param args */ xhrGet: function(args) { this.xhr("GET",args); }, /* * @method xhrPost * @param args */ xhrPost: function(args){ this.xhr("POST", args, true); }, /* * @method xhrPut * @param args */ xhrPut: function(args){ this.xhr("PUT", args, true); }, /* * @method xhrDelete * @param args */ xhrDelete: function(args){ this.xhr("DELETE", args); }, /** * authenticate to an endpoint * * @method authenticate * @param {Object} [args] Argument object * @param {boolean} [args.forceAuthentication] Whether authentication is to be forced in case user is already authenticated. * @param {String} [args.loginUi] LoginUi to be used for authentication. possible values are: 'popup', 'dialog' and 'mainWindow' * @param {String} [args.loginPage] login page to be used for authentication. this property should be used in case default * login page is to be overridden. This only applies to 'popup' and 'mainWindow' loginUi * @param {String} [args.dialogLoginPage] dialog login page to be used for authentication. this property should be used in * case default dialog login page is to be overridden. This only applies to 'dialog' loginUi. */ authenticate : function(args) { var promise = new Promise(); args = args || {}; if (args.forceAuthentication || !this.isAuthenticated) { var options = { dialogLoginPage : this.loginDialogPage, loginPage : this.loginPage, transport : this.transport, proxy : this.proxy, proxyPath : this.proxyPath, loginUi : args.loginUi || this.loginUi, name: this.name, callback: function(response) { promise.fulfilled(response); }, cancel: function(response) { promise.rejected(response); } }; this.authenticator.authenticate(options); } else { promise.fulfilled(true); } return promise; }, /** * Logout from an endpoint * * @method logout * @param {Object} [args] Argument object */ logout : function(args) { var promise = new Promise(); args = args || {}; var self = this; var actionURL = ""; if (!args.actionUrl) { var proxy = this.proxy.proxyUrl; actionURL = proxy.substring(0, proxy.lastIndexOf("/")) + "/authHandler/" + this.proxyPath + "/logout"; } else { actionURL = args.actionUrl; } this.transport.xhr('POST',{ handleAs : "json", url : actionURL, load : function(response) { self.isAuthenticated = false; promise.fulfilled(response); }, error : function(response) { self.isAuthenticated = false; promise.rejected(response); } }, true); return promise; }, /** * Find whether endpoint is authenticated or not. * * @method isAuthenticated * @param {Object} [args] Argument object */ isAuthenticated : function(args) { var promise = new Promise(); args = args || {}; var self = this; var actionURL = ""; if (!args.actionUrl) { var proxy = this.proxy.proxyUrl; actionURL = proxy.substring(0, proxy.lastIndexOf("/")) + "/authHandler/" + this.proxyPath + "/isAuth"; } else { actionURL = args.actionUrl; } this.transport.xhr('POST',{ handleAs : "json", url : actionURL, load : function(response) { self.isAuthenticated = true; promise.fulfilled(response); }, error : function(response) { promise.rejected(response); } }, true); return promise; }, /** Find whether endpoint authentication is valid or not. @method isAuthenticationValid @param {Object} [args] Argument object @param {Function} [args.load] This is the function which isAuthenticationValid invokes when authentication information is retrieved. @param {Function} [args.error] This is the function which isAuthenticationValid invokes if an error occurs. result property in response object returns true/false depending on whether authentication is valid or not. */ isAuthenticationValid : function(args) { var promise = new Promise(); args = args || {}; var self = this; var actionURL = ""; if (!args.actionUrl) { var proxy = this.proxy.proxyUrl; actionURL = proxy.substring(0, proxy.lastIndexOf("/")) + "/authHandler/" + this.proxyPath + "/isAuthValid"; } else { actionURL = args.actionUrl; } this.transport.xhr('POST',{ handleAs : "json", url : actionURL, load : function(response) { self.isAuthenticated = response.result; promise.fulfilled(response); }, error : function(response) { promise.rejected(response); } }, true); return promise; }, // Internal stuff goes here and should not be documented /* * Invoke error function with the error */ _notifyError: function(args, error, ioArgs) { if (args.handle) { try { args.handle(error, ioArgs); } catch (ex) { // TODO log an error var msg = ex.message; } } if (args.error) { try { args.error(error, ioArgs); } catch (ex) { // TODO log an error var msg = ex.message; } } }, /* * Invoke handle and/or load function with the response */ _notifyResponse: function(args, data, ioArgs) { if (args.handle) { try { args.handle(data, ioArgs); } catch (ex) { // TODO log an error var msg = ex.message; } } if (args.load) { try { args.load(data, ioArgs); } catch (ex) { // TODO log an error var msg = ex.message; } } }, /* * Invoke automatic authentication for the specified request. */ _authenticate: function(url, options, promise) { var self = this; var authOptions = { dialogLoginPage: this.loginDialogPage, loginPage: this.loginPage, transport: this.transport, proxy: this.proxy, proxyPath: this.proxyPath, actionUrl: options.actionUrl, loginUi: options.loginUi || this.loginUi, name: this.name, callback: function() { self.request(url, options).response.then( function(response) { promise.fulfilled(response.data); promise.response.fulfilled(response); }, function(error) { promise.rejected(error); promise.response.rejected(error); } ); }, cancel: function() { self._authRejected = true; var error = new Error(); error.message = "Authentication is required and has failed or has not yet been provided."; error.code = 401; promise.rejected(error); promise.response.rejected(error); } }; return this.authenticator.authenticate(authOptions); }, /* * Return true if automatic authentication is required. This method returns a promise with the success callback returning * a boolean whether authentication is required. It first checks if the client is already authenticated * and if yes, whether the authentication is valid. Else, it checks for the status code and other * configuration paramters to decide if authentication is required. */ _isAuthRequired : function(error, options) { var promise = new Promise(); var status = error.response.status || null; var isAuthErr = status == 401 || status == this.authenticationErrorCode; if (this.isAuthenticated) { if (!isAuthErr) { promise.fulfilled(false); } else { this.isAuthenticationValid().then( function(response) { promise.fulfilled(!response.result); }, function(response) { promise.rejected(response); } ); } } else { // User can mention autoAuthenticate as part service wrappers call that is the args json variable or // as a property of endpoint in managed-beans.xml. // isAutoAuth variable is true when autoAuthenticate property is true in args json variable or // autoAuthenticate property in endpoint defination in managed-beans.xml is true. It is false otherwise. var isAutoAuth = options.autoAuthenticate || this.autoAuthenticate; if (isAutoAuth == undefined) { isAutoAuth = true; } // The response is returned as a boolean value as an argument to the success callback of the promise. This // value is true when the error code is 401 or any authentication error code for a particular endpoint // (isAuthErr variable) and autoAuthenticate parameter is mentioned true (based on isAutoAuth variable) // and authenticator property the endpoint (could be js object of type Basic or OAuth)is defined and the // authentication was not rejected earlier. // It is false otherwise. The true value of this expression triggers the authentication process from the client. promise.fulfilled(isAuthErr && isAutoAuth && this.authenticator && !this._authRejected); } return promise; }, /* * Method ensures we trigger authentication for Smartcloud when response code is 200 and content is login page */ _isAuthRequiredFormBasedEP : function (response, options){ if(response.status == 200 && response.getHeader("Content-Type") == "text/html"){ return true; }else{ return false; } }, getErrorMessage: function(error) { var text = error.responseText || (error.response&&error.response.text) ; if (text) { try { var dom = xml.parse(text); var messages = dom.getElementsByTagName("message"); if (messages && messages.length != 0) { text = messages[0].text || messages[0].textContent; text = lang.trim(text); } } catch(ex) { } var trimmedText = text.replace(/(\r\n|\n|\r)/g,""); if(!(trimmedText)){ return error.message; }else{ return text; } } else { return error; } }, getProxyUrl: function(){ return this.proxy.proxyUrl + "/" + this.proxyPath; }, /** * Takes a url with a context root to replace, and returns a url with the context root replaced. * * e.g. url: 'http://example.com/${replaceMe}' * If this endpoint has serviceMappings like: * { * replaceMe: 'replacement' * } * * returns 'http://example.com/replacement' * * If there is no replacement available, the replacement will be the string inside the braces. e.g. 'http://example.com/replaceMe' will be returned. * * @method modifyUrlContextRoot * * @param {String} url * @param {Object} [defaultContextRootMap] If specified, this object will be used for replacements in the event there is no equivalent serviceMapping object. */ modifyUrlContextRoot: function(url, defaultContextRootMap){ var defaultMap = defaultContextRootMap ? {} : lang.mixin({}, defaultContextRootMap); var map = lang.mixin(defaultMap, this.serviceMapping); return stringUtil.transform(url, map, function(value, key){ if(!value){ return key; } else{ return value; } }, this); } }); return Endpoint; }); }, 'sbt/Portlet':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK - Portlet specific helpers. */ define([],function() { sbt.getUserPref = function(ns,name) { } }); }, 'sbt/connections/CommunityService':function(){ /* * (C) Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * The Communities API allows application programs to retrieve community information, subscribe to community updates, and create or modify communities. * * @module sbt.connections.CommunityService */ define([ "../declare", "../config", "../lang", "../stringUtil", "../Promise", "./CommunityConstants", "./ConnectionsService", "../base/AtomEntity", "../base/XmlDataHandler", "./ForumService", "./BookmarkService", "../pathUtil" ], function(declare,config,lang,stringUtil,Promise,consts,ConnectionsService,AtomEntity,XmlDataHandler,ForumService,BookmarkService,pathUtil) { var CategoryCommunity = "<category term=\"community\" scheme=\"http://www.ibm.com/xmlns/prod/sn/type\"></category>"; var CategoryMember = "<category term=\"person\" scheme=\"http://www.ibm.com/xmlns/prod/sn/type\"></category>"; var CategoryInvite = "<category term=\"invite\" scheme=\"http://www.ibm.com/xmlns/prod/sn/type\"></category>"; var CategoryEvent = "<category term=\"event\" scheme=\"http://www.ibm.com/xmlns/prod/sn/type\"></category>"; var IsExternalTmpl = "<snx:isExternal>${isExternal}</snx:isExternal>"; var parentLinkTmpl = "<link href=\"${getParentCommunityUrl}\" rel=\"http://www.ibm.com/xmlns/prod/sn/parentcommunity\" type=\"application/atom+xml\"> </link>"; var CommunityTypeTmpl = "<snx:communityType>${getCommunityType}</snx:communityType>"; var CommunityUuidTmpl = "<snx:communityUuid xmlns:snx=\"http://www.ibm.com/xmlns/prod/sn\">${getCommunityUuid}</snx:communityUuid><id>instance?communityUuid=${getCommunityUuid}</id> "; var CommunityThemeTmpl = "<snx:communityTheme xmlns:snx=\"http://www.ibm.com/xmlns/prod/sn\" snx:uuid=\"default\">${getCommunityTheme}</snx:communityTheme>"; var RoleTmpl = "<snx:role xmlns:snx=\"http://www.ibm.com/xmlns/prod/sn\" component=\"http://www.ibm.com/xmlns/prod/sn/communities\">${getRole}</snx:role>"; /* * CommunityDataHandler class. */ var CommunityDataHandler = declare(XmlDataHandler, { /** * @method getEntityId * @returns */ getEntityId : function() { var entityId = stringUtil.trim(this.getAsString("uid")); return extractCommunityUuid(this.service, entityId); } }); /** * Community class represents an entry for a Community feed returned by the * Connections REST API. * * @class Community * @namespace sbt.connections */ var Community = declare(AtomEntity, { xpath : consts.CommunityXPath, namespaces : consts.CommunityNamespaces, categoryScheme : CategoryCommunity, /** * Construct a Community entity. * * @constructor * @param args */ constructor : function(args) { }, /** * Create the DataHandler for this entity. * * @method createDataHandler */ createDataHandler : function(service, data, response, namespaces, xpath) { return new CommunityDataHandler({ service : service, data : data, namespaces : namespaces, xpath : xpath }); }, /** * Return extra entry data to be included in post data for this entity. * * @returns {String} */ createEntryData : function() { var postData = ""; var transformer = function(value,key) { return value; }; postData += stringUtil.transform(CommunityTypeTmpl, this, transformer, this); postData += stringUtil.transform(IsExternalTmpl, this, transformer, this); if (this.getCommunityUuid()) { postData += stringUtil.transform(CommunityUuidTmpl, this, transformer, this); } if(this.isSubCommunity()){ postData += stringUtil.transform(parentLinkTmpl, this, transformer, this); } if (this.getCommunityTheme()) { postData += stringUtil.transform(CommunityThemeTmpl, this, transformer, this); } return stringUtil.trim(postData); }, /** * Return the value of IBM Connections community ID from community ATOM * entry document. * * @method getCommunityUuid * @return {String} Community ID of the community */ getCommunityUuid : function() { var communityUuid = this.getAsString("communityUuid"); return extractCommunityUuid(this.service, communityUuid); }, /** * Sets id of IBM Connections community. * * @method setCommunityUuid * @param {String} communityUuid Id of the community */ setCommunityUuid : function(communityUuid) { return this.setAsString("communityUuid", communityUuid); }, /** * Return the community type of the IBM Connections community from * community ATOM entry document. * * @method getCommunityType * @return {String} Type of the Community */ getCommunityType : function() { var type = this.getAsString("communityType"); if (!type) { type = consts.Restricted; } return type; }, /** * Set the community type of the IBM Connections community. * * @method setCommunityType * @param {String} Type of the Community */ setCommunityType : function(communityType) { return this.setAsString("communityType", communityType); }, /** * Return the community theme of the IBM Connections community from * community ATOM entry document. * * @method getCommunityTheme * @return {String} Theme of the Community */ getCommunityTheme : function() { return this.getAsString("communityTheme"); }, /** * Set the community theme of the IBM Connections community. * * @method setCommunityTheme * @param {String} Theme of the Community */ setCommunityTheme : function(communityTheme) { return this.setAsString("communityTheme", communityTheme); }, /** * Return the external of the IBM Connections community from * community ATOM entry document. * * @method isExternal * @return {Boolean} External flag of the Community */ isExternal : function() { return this.getAsBoolean("isExternal"); }, /** * Set the external flag of the IBM Connections community. * * @method setExternal * @param {Boolean} External flag of the Community */ setExternal : function(external) { return this.setAsBoolean("isExternal", external); }, /** * function to check if a community is a sub community of another community * * @method isSubCommunity * @return Returns true if this community is a sub community */ isSubCommunity : function(){ var parentUrl = this.getParentCommunityUrl(); if(parentUrl != null && parentUrl != ""){ return true; }else{ return false; } }, /** * If this community is a sub community this function gets the url of the parent community * else it returns null. * @method getParentCommunityUrl * @returns The Url of the parent community if the community is a sub community else returns null */ getParentCommunityUrl: function(){ return this.getAsString("parentCommunityUrl"); }, /** * Return tags of IBM Connections community from community ATOM entry * document. * * @method getTags * @return {Object} Array of tags of the community */ getTags : function() { return this.getAsArray("tags"); }, /** * Set new tags to be associated with this IBM Connections community. * * @method setTags * @param {Object} Array of tags to be added to the community */ setTags : function(tags) { return this.setAsArray("tags", tags); }, /** * Return the value of IBM Connections community URL from community ATOM * entry document. * * @method getCommunityUrl * @return {String} Community URL of the community * @deprecated Use getAlternateUrl instead */ getCommunityUrl : function() { return this.getAlternateUrl(); }, /** * Return the value of IBM Connections community Logo URL from community * ATOM entry document. * * @method getLogoUrl * @return {String} Community Logo URL of the community */ getLogoUrl : function() { return this.getAsString("logoUrl"); }, /** * Return the member count of the IBM Connections community from * community ATOM entry document. * * @method getMemberCount * @return {Number} Member count for the Community */ getMemberCount : function() { return this.getAsNumber("memberCount"); }, /** * Get a list for forum topics that includes the topics in this community. * * @method getForumTopics * @param {Object} args */ getForumTopics : function(args) { return this.service.getForumTopics(this.getCommunityUuid(), args); }, /** * Create a forum topic by sending an Atom entry document containing the * new forum to the forum replies resource. * * @method createForumTopic * @param {Object} forumTopic Forum topic object which denotes the forum topic to be created. * @param {Object} [args] Argument object */ createForumTopic : function(communityUuid, topicOrJson, args) { if(!lang.isString(communityUuid)){ args = topicOrJson; topicOrJson = communityUuid; } return this.service.createForumTopic(topicOrJson, args); }, /** * Get sub communities of a community. * * @method getSubCommunities * @param {Object} [args] Object representing various parameters * that can be passed to get a feed of members of a * community. The parameters must be exactly as they are * supported by IBM Connections like ps, sortBy etc. */ getSubCommunities : function(args) { return this.service.getSubCommunities(this.getCommunityUuid(), args); }, /** * Get members of this community. * * @method getMembers * @param {Object} [args] Object representing various parameters * that can be passed to get a feed of members of a * community. The parameters must be exactly as they are * supported by IBM Connections like ps, sortBy etc. */ getMembers : function(args) { return this.service.getMembers(this.getCommunityUuid(), args); }, /** * Add member to a community * * @method addMember * @param {Object} [args] Argument object * @param {Object} [args.member] Object representing the member to be added * @param {String} [args.email] Object representing the email of the memeber to be added * @param {String} [args.id] String representing the id of the member to be added */ addMember : function(member,args) { return this.service.addMember(this.getCommunityUuid(), member, args); }, /** * Remove member of a community * * @method removeMember * @param {String} Member id of the member * @param {Object} [args] Argument object */ removeMember : function(memberId,args) { return this.service.removeMember(this.getCommunityUuid(), memberId, args); }, /** * Loads a member object with the atom entry associated with the * member of the community. By default, a network call is made to load the atom entry * document in the member object. * * @method getMember * @param {String} member id of the member. * @param {Object} [args] Argument object */ getMember : function(memberId, args) { return this.service.getMember(this.getCommunityUuid(), memberId, args); }, /** * Get a list of the outstanding community invitations for the specified community. * The currently authenticated user must be an owner of the community. * * @method getAllInvites * @param {Object} [args] */ getAllInvites : function(args) { return this.service.getAllInvites(this.getCommunityUuid(), args); }, /** * Get the list of community forums. * * @method getForums * @param {Object} [args] Argument object */ getForums : function(args) { var forumService = this.service.getForumService(); var requestArgs = lang.mixin(args || {}, { communityUuid : this.getCommunityUuid() }); return forumService.getForums(requestArgs); }, /** * Loads the community object with the atom entry associated with the * community. By default, a network call is made to load the atom entry * document in the community object. * * @method load * @param {Object} [args] Argument object */ load : function(args) { // detect a bad request by validating required arguments var communityUuid = this.getCommunityUuid(); var promise = this.service._validateCommunityUuid(communityUuid); if (promise) { return promise; } var self = this; var callbacks = { createEntity : function(service, data, response) { self.setData(data, response); return self; } }; var requestArgs = lang.mixin( { communityUuid : communityUuid }, args || {}); var options = { handleAs : "text", query : requestArgs }; return this.service.getEntity(consts.AtomCommunityInstance, options, communityUuid, callbacks); }, /** * Remove this community * * @method remove * @param {Object} [args] Argument object */ remove : function(args) { return this.service.deleteCommunity(this.getCommunityUuid(), args); }, /** * Update this community * * @method remove * @param {Object} [args] Argument object */ update : function(args) { return this.service.updateCommunity(this, args); }, /** * Save this community * * @method remove * @param {Object} [args] Argument object */ save : function(args) { if (this.getCommunityUuid()) { return this.service.updateCommunity(this, args); } else { return this.service.createCommunity(this, args); } } }); /** * Member class represents an entry for a Member feed returned by the * Connections REST API. * * @class Member * @namespace sbt.connections */ var Member = declare(AtomEntity, { xpath : consts.MemberXPath, namespaces : consts.CommunityNamespaces, categoryScheme : CategoryMember, /** * The UUID of the community associated with this Member */ communityUuid : null, /** * Constructor for Member entity * * @constructor * @param args */ constructor : function(args) { if (!this.getRole()) { this.setRole(consts.Member); } }, /** * Return extra entry data to be included in post data for this entity. * * @returns {String} */ createEntryData : function() { var postData = ""; var transformer = function(value,key) { return value; }; postData += stringUtil.transform(RoleTmpl, this, transformer, this); return stringUtil.trim(postData); }, /** * Return the community UUID. * * @method getCommunityUuid * @return {String} communityUuid */ getCommunityUuid : function() { return this.communityUuid; }, /** * Return the community member name. * * @method getName * @return {String} Community member name */ getName : function() { return this.getAsString("contributorName"); }, /** * Set the community member name. * * @method setName * @param {String} Community member name */ setName : function(name) { return this.setAsString("contributorName", name); }, /** * Return the community member userId. * * @method getUserid * @return {String} Community member userId */ getUserid : function() { return this.getAsString("contributorUserid"); }, /** * Set the community member userId. * * @method getId * @return {String} Community member userId */ setUserid : function(userid) { return this.setAsString("contributorUserid", userid); }, /** * Return the community member email. * * @method getName * @return {String} Community member email */ getEmail : function() { return this.getAsString("contributorEmail"); }, /** * Return the community member email. * * @method getName * @return {String} Community member email */ setEmail : function(email) { return this.setAsString("contributorEmail", email); }, /** * Return the value of community member role from community member ATOM * entry document. * * @method getRole * @return {String} Community member role */ getRole : function() { return this.getAsString("role"); }, /** * Sets role of a community member * * @method setRole * @param {String} role Role of the community member. */ setRole : function(role) { return this.setAsString("role", role); }, /** * Loads the member object with the atom entry associated with the * member. By default, a network call is made to load the atom entry * document in the member object. * * @method load * @param {Object} [args] Argument object */ load : function(args) { // detect a bad request by validating required arguments var communityUuid = this.communityUuid; var promise = this.service._validateCommunityUuid(communityUuid); if (promise) { return promise; } var self = this; var callbacks = { createEntity : function(service, data, response) { self.setData(data, response); return self; } }; var requestArgs = { communityUuid : communityUuid }; var memberId = null; if (this.getUserid()) { memberId = requestArgs.userid = this.getUserid(); } else { memberId = requestArgs.email = this.getEmail(); } requestArgs = lang.mixin(requestArgs, args || {}); var options = { handleAs : "text", query : requestArgs }; return this.service.getEntity(consts.AtomCommunityMembers, options, memberId, callbacks); }, /** * Remove this member from the community. * * @method remove * @param {Object} [args] Argument object */ remove : function(args) { var memberId = this.getUserid() || this.getEmail(); return this.service.removeMember(this.getCommunityUuid(), memberId, args); } }); /** * Invite class represents an entry for a Invite feed returned by the * Connections REST API. * * @class Invite * @namespace sbt.connections */ var Invite = declare(AtomEntity, { xpath : consts.InviteXPath, namespaces : consts.CommunityNamespaces, categoryScheme : CategoryInvite, /** * The UUID of the community associated with this Invite */ communityUuid : null, /** * The UUID if the invitee associated with this Invite */ inviteeUuid : null, /** * Constructor for Invite * * @constructor * @param args */ constructor : function(args) { this.inherited(arguments, [ args ]); }, /** * Return the value of IBM Connections invite ID from invite ATOM * entry document. * * @method getInviteUuid * @return {String} Invite ID of the invite */ getInviteUuid : function() { var inviteUuid = this.getAsString("inviteUuid"); return extractInviteUuid(inviteUuid); }, /** * Sets id of IBM Connections invite. * * @method setInviteUuid * @param {String} inviteUuid Id of the invite */ setInviteUuid : function(inviteUuid) { return this.setAsString("inviteUuid", inviteUuid); }, /** * Set the community UUID. * * @method setCommunityUuid * @return {String} communityUuid */ setCommunityUuid : function(communityUuid) { this.communityUuid = communityUuid; return this; }, /** * Return the community UUID. * * @method getCommunityUuid * @return {String} communityUuid */ getCommunityUuid : function() { if (!this.communityUuid) { this.communityUuid = this.service.getUrlParameter(this.getAsString("communityUrl"), "communityUuid"); } return this.communityUuid; }, /** * Set the invitee UUID. * * @method setInviteeUuid * @return {String} inviteeUuid */ setInviteeUuid : function(inviteeUuid) { this.inviteeUuid = inviteeUuid; return this; }, /** * Return the value of IBM Connections invitee ID from invite ATOM * entry document. * * @method getInviteeUuid * @return {String} Invitee ID of the invite */ getInviteeUuid : function() { if (!this.inviteeUuid) { var inviteUuid = this.getInviteUuid(); this.inviteeUuid = extractInviteeUuid(inviteUuid, this.getCommunityUuid()); } return this.inviteeUuid; }, /** * Set the user id of the invitee. * * @method setUserid * @return {String} userid */ setUserid : function(userid) { return this.setAsString("contributorUserid", userid); }, /** * Return the user id of the invitee. * * @method getUserid * @return {String} userid */ getUserid : function() { return this.getAsString("contributorUserid"); }, /** * Set the email of the invitee. * * @method setEmail * @return {String} email */ setEmail : function(email) { return this.setAsString("contributorEmail", email); }, /** * Return the email of the invitee. * * @method getEmail * @return {String} email */ getEmail : function() { return this.getAsString("contributorEmail"); }, /** * Loads the invite object with the atom entry associated with the * invite. By default, a network call is made to load the atom entry * document in the invite object. * * @method load * @param {Object} [args] Argument object */ load : function(args) { // detect a bad request by validating required arguments var communityUuid = this.getCommunityUuid(); var promise = this.service._validateCommunityUuid(communityUuid); if (promise) { return promise; } var userid = this.getInviteeUuid(); promise = this.service._validateUserid(userid); if (promise) { return promise; } var self = this; var callbacks = { createEntity : function(service, data, response) { self.setData(data, response); return self; } }; var requestArgs = lang.mixin({ communityUuid : communityUuid, userid : userid }, args || {}); var options = { handleAs : "text", query : requestArgs }; return this.service.getEntity(consts.AtomCommunityInvites, options, communityUuid + "-" + userid, callbacks); }, /** * Remove this invite * * @method remove * @param {Object} [args] Argument object */ remove : function(args) { return this.service.removeInvite(this, args); }, /** * Update this invite * * @method remove * @param {Object} [args] Argument object */ update : function(args) { return this.service.updateInvite(this, args); }, /** * Save this invite * * @method remove * @param {Object} [args] Argument object */ save : function(args) { if (this.getInviteUuid()) { return this.service.updateInvite(this, args); } else { return this.service.createInvite(this, args); } } }); /** * Event class represents an entry from an Events feed returned by the Connections REST API. * * An Event may repeat and have multiple EventInsts (instances of the event). * * e.g. If an event has repeats set so that it happens on 5 different days it has 5 EventInsts, but the Event is still the same. * * @class Event * @namespace sbt.connections */ var Event = declare(AtomEntity, { /** * Constructor for Event. * * @constructor * @param args */ constructor : function(args) { }, /** * The Uuid of the event. This is per event rather than per event instance. * * e.g. if an event spans multiple days it will have multiple instances, yet each even will have the same Uuid. * @method getEventUuid * @return {String} Uuid of the event. */ getEventUuid : function(){ return this.getAsString("eventUuid"); }, /** * @method getLocation * @return {String} The location of the event */ getLocation : function(){ return this.getAsString("location"); }, /** * @method getAllDay * @return {Boolean} True if event lasts entire day, false otherwise. */ getAllDay : function(){ return this.getAsString("allDay") !== 0; }, /** * * @method getSelfLink * @return {String} Link to the atom representation of this object */ getSelfLink : function(){ return this.getAsString("selfLink"); }, /** * Gets the source, usually the community it was created in. * Contains id of source, title and a link to the web representation of the source. * {id:"", title: "", link:""} * * @method getSource * @return {Object} */ getSource : function(){ return this.getAsObject( [ "id", "title", "link"], [ "id", "title", "link"]); }, /** * Gets the recurrence information of the event. This information is not available in individual event instances. * * Recurrence information object consists of: * frequency - 'daily' or 'weekly' * interval - Week interval. Value is int between 1 and 5. (e.g. repeats every 2 weeks). null if daily. * until - The end date of the repeating event. * allDay - 1 if an all day event, 0 otherwise. * startDate - Start time of the event * endDate - End time of the event * byDay - Days of the week this event occurs, possible values are: SU,MO,TU,WE,TH,FR,SA * * @method getRecurrence * @return {Object} An object containing the above recurrence information of the community event. */ getRecurrence : function() { return this.getAsObject( [ "frequency", "interval", "until", "allDay", "startDate", "endDate", "byDay" ], [ "frequency", "interval", "until", "allDay", "startDate", "endDate", "byDay" ]); }, /** * @method getContainerLink * @return {String} Link to the container on the web, i.e. the community */ getCommunityLink : function(){ this.getAsString("communityLink"); }, /** * Return the community UUID. * * @method getCommunityUuid * @return {String} communityUuid */ getCommunityUuid : function() { return this.getAsString("communityUuid"); } }); /** * EventInst class represents an entry for an EventInsts feed returned by the Connections REST API. EventInsts all have a parent Event. * * @class EventInst * @namespace sbt.connections */ var EventInst = declare(Event, { /** * Constructor for Event instance. * * @constructor * @param args */ constructor : function(args) { }, /** * The event instance uuid. This is per event instance, rather than per event. * e.g. if an event spans multiple days each day will have its own eventInstUuid. * * Can be used with the{{#crossLink "CommunityService/getEvent:method"}}{{/crossLink}} method to retrieve event instances. * @method getEventInstUuid * @return {String} Uuid of the event instance. */ getEventInstUuid : function(){ return this.getAsString("eventInstUuid"); }, /** * @method getFollowed * @return {Boolean} True if the current authenticated user is following this event Instance */ getFollowed : function(){ return this.getAsString("followed"); }, /** * @method getAttended * @return {Boolean} True if the current authenticated user is attending this event Instance */ getAttended : function(){ return this.getAsString("attended"); }, /** * @method getParentEventId * @return {String} The id of the parent event of this event instance. */ getParentEventId : function(){ return this.getAsString("parentEventId"); }, /** * @method getParentEventLink * @return {String} The link to the parent event's atom representation. */ getParentEventLink : function(){ return this.getAsString("parentEventLink"); }, /** * @method getStartDate * @return The date the event instance starts */ getStartDate : function(){ return this.getAsString("instStartDate"); }, /** * @method getEndDate * @return The date the event instance ends */ getEndDate : function(){ return this.getAsString("instEndDate"); } }); /* * Method used to extract the community uuid for an id url. */ var extractCommunityUuid = function(service, uid) { if (uid && uid.indexOf("http") == 0) { return service.getUrlParameter(uid, "communityUuid"); } else { return uid; } }; /* * Method used to extract the invite uuid for an id url. */ var extractInviteUuid = function(uid) { if (uid && uid.indexOf("urn:lsid:ibm.com:communities:invite-") == 0) { return uid.substring("urn:lsid:ibm.com:communities:invite-".length); } else { return uid; } }; /* * Method used to extract the invitee uuid for an id url. */ var extractInviteeUuid = function(uid, communityUuid) { if (uid && uid.indexOf(communityUuid) == 0) { return uid.substring(communityUuid.length + 1); } else { return uid; } }; /* * Callbacks used when reading a feed that contains Community entries. */ var CommunityFeedCallbacks = { createEntities : function(service,data,response) { return new CommunityDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.CommunityFeedXPath }); }, createEntity : function(service,data,response) { return new Community({ service : service, data : data, response: response }); } }; /* * Callbacks used when reading a feed that contains Member entries. */ var MemberFeedCallbacks = { createEntities : function(service,data,response) { return new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.CommunityFeedXPath }); } }; /* * Callbacks used when reading a feed that contains Invite entries. */ var InviteFeedCallbacks = { createEntities : function(service,data,response) { return new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.CommunityFeedXPath }); }, createEntity : function(service,data,response) { return new Invite({ service : service, data : data, response: response }); } }; /* * Callbacks used when reading a feed that contains Event entries. */ var ConnectionsEventFeedCallbacks = { createEntities : function(service,data,response) { return new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.CommunityFeedXPath }); }, createEntity : function(service,data,response) { var entryHandler = new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.EventXPath }); return new Event({ service : service, id : entryHandler.getEntityId(), dataHandler : entryHandler }); } }; /* * Callbacks used when reading a feed that contains EventInst entries. */ var ConnectionsEventInstFeedCallbacks = { createEntities : function(service,data,response) { return new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.CommunityFeedXPath }); }, createEntity : function(service,data,response) { var entryHandler = new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.EventXPath }); return new EventInst({ service : service, id : entryHandler.getEntityId(), dataHandler : entryHandler }); } }; var ConnectionsEventInstCallbacks = { createEntity : function(service,data,response) { var entryHandler = new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.EventXPath }); return new EventInst({ service : service, id : entryHandler.getEntityId(), dataHandler : entryHandler }); } }; /* * Callbacks used when reading an entry that contains a Community. */ var CommunityCallbacks = { createEntity : function(service,data,response) { return new Community({ service : service, data : data, response: response }); } }; /* * Callbacks used when reading an feed that contains community forum topics. */ var ForumTopicFeedCallbacks = { createEntities : function(service,data,response) { return new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.CommunityFeedXPath }); }, createEntity : function(service, data, response) { var forumService = service.getForumService(); var forumTopic = forumService.newForumTopic({}); forumTopic.setData(data, response); return forumTopic; } }; /** * CommunityService class. * * @class CommunityService * @namespace sbt.connections */ var CommunityService = declare(ConnectionsService, { forumService : null, bookmarkService : null, contextRootMap: { communities: "communities" }, serviceName : "communities", /** * Constructor for CommunityService * * @constructor * @param args */ constructor : function(args) { if (!this.endpoint) { this.endpoint = config.findEndpoint(this.getDefaultEndpointName()); } }, /** * Return a ForumService instance * * @method getForumService * @returns {ForumService} */ getForumService : function() { if (!this.forumService) { this.forumService = new ForumService(); this.forumService.endpoint = this.endpoint; } return this.forumService; }, /** * Return a BookmarkService instance * * @method getBookmarkService * @returns {BookmarkService} */ getBookmarkService : function() { if (!this.bookmarkService) { this.bookmarkService = new BookmarkService(); this.bookmarkService.endpoint = this.endpoint; } return this.bookmarkService; }, /** * Get the All Communities feed to see a list of all public communities to which the * authenticated user has access or pass in parameters to search for communities that * match a specific criteria. * * @method getPublicCommunities * * @param {Object} [args] Object representing various parameters * that can be passed to get a feed of my communities. The * parameters must be exactly as they are supported by IBM * Connections like ps, sortBy etc. */ getPublicCommunities : function(args) { var options = { method : "GET", handleAs : "text", query : args || {} }; return this.getEntities(consts.AtomCommunitiesAll, options, CommunityFeedCallbacks); }, /** * Get the My Communities feed to see a list of the communities to which the * authenticated user is a member or pass in parameters to search for a subset * of those communities that match a specific criteria. * * @method getMyCommunities * @param {Object} [args] Object representing various parameters * that can be passed to get a feed of my communities. The * parameters must be exactly as they are supported by IBM * Connections like ps, sortBy etc. */ getMyCommunities : function(args) { var options = { method : "GET", handleAs : "text", query : args || {} }; return this.getEntities(consts.AtomCommunitiesMy, options, CommunityFeedCallbacks); }, /** * Retrieve the members feed to view a list of the members who belong * to a given community. * * @method getMembers * @param {Object} [args] Object representing various parameters * that can be passed to get a feed of members of a * community. The parameters must be exactly as they are * supported by IBM Connections like ps, sortBy etc. */ getMembers : function(communityUuid,args) { var promise = this._validateCommunityUuid(communityUuid); if (promise) { return promise; } var requestArgs = lang.mixin({ communityUuid : communityUuid }, args || {}); var options = { method : "GET", handleAs : "text", query : requestArgs }; var callbacks = lang.mixin({ createEntity : function(service,data,response) { return new Member({ service : service, communityUuid : communityUuid, data : data, response: response }); } }, MemberFeedCallbacks); return this.getEntities(consts.AtomCommunityMembers, options, callbacks); }, /** * Retrieve the member entry to view a member who belongs to a given community. * * @method getMember * @param {Object} [args] Object representing various parameters * that can be passed to get a feed of members of a * community. The parameters must be exactly as they are * supported by IBM Connections like ps, sortBy etc. */ getMember : function(communityUuid,memberId,args) { var member = new Member({ service : this, communityUuid : communityUuid }); if (this.isEmail(memberId)) { member.setEmail(memberId); } else { member.setUserid(memberId); } return member.load(args); }, /** * Given the eventUuid, get the instances of that event. * * @param eventUuid The uuid of the Event * @return {Object} Promise which resolves with the array of event Instances. */ getEventInsts : function(eventUuid){ var promise = this._validateEventUuid(eventUuid); if (promise) { return promise; } var options = { method : "GET", handleAs : "text", query : { eventUuid : eventUuid, mode : "list" } }; return this.getEntities(consts.AtomCommunityEvents, options, ConnectionsEventInstFeedCallbacks); }, /* * here since getCommunityEvents and getCommunityEventInsts use the same logic. */ _getCommunityEvents : function(communityUuid, startDate, endDate, args, callbacks){ var promise = this._validateCommunityUuid(communityUuid) || this._validateDateTimes(startDate, endDate); if (promise) { return promise; } var requiredArgs = { calendarUuid : communityUuid }; if(startDate){ lang.mixin(requiredArgs, { startDate : startDate }); } if(endDate){ lang.mixin(requiredArgs, { endDate : endDate }); } args = lang.mixin(args, requiredArgs); var options = { method : "GET", handleAs : "text", query : args || {} }; return this.getEntities(consts.AtomCommunityEvents, options, callbacks); }, /** * Get the Event instances for a community. See {{#crossLink "CommunityConstants/AtomCommunityEvents:attribute"}}{{/crossLink}} for a complete listing of parameters. * * These results do not include all details of the event instance, such as the full description. A summary is available in that case. UseEventInst.getFullEvent to get the full details. * * @param communityId The uuid of the Community. * @param startDate Include events that end after this date. * @param endDate Include events that end before this date. * @param args url parameters. * * @return {Object} Promise which resolves with the array of event instances. */ getCommunityEventInsts : function(communityUuid, startDate, endDate, args){ return this._getCommunityEvents(communityUuid, startDate, endDate, args, ConnectionsEventInstFeedCallbacks); }, /** * Get the events of a community. Each event can have multiple event instances. * * @method getCommunityEvents * @return {Object} Promise which resolves with the array of event instances. */ getCommunityEvents : function(communityUuid, startDate, endDate, args){ return this._getCommunityEvents(communityUuid, startDate, endDate, lang.mixin(args, {type: "event"}), ConnectionsEventFeedCallbacks); }, /** * Used to get the event Inst with the given eventInstUuid. * * This will include all details of the event, including its content. * * @param eventInstUuid - The id of the event, also used as an identifier when caching the response * @returns */ getEventInst : function(eventInstUuid){ var options = { method : "GET", handleAs : "text", query : { eventInstUuid: eventInstUuid } }; return this.getEntity(consts.AtomCommunityEvents, options, eventInstUuid, ConnectionsEventInstCallbacks); }, /** * Get a list of the outstanding community invitations of the currently authenticated * user or provide parameters to search for a subset of those invitations. * * @method getMyInvites * @param {Object} [args] */ getMyInvites : function(args) { var options = { method : "GET", handleAs : "text", query : args || {} }; return this.getEntities(consts.AtomCommunityInvitesMy, options, InviteFeedCallbacks); }, /** * Get a list of the outstanding community invitations for the specified community. * The currently authenticated user must be an owner of the community. * * @method getAllInvites * @param communityUuid * @param {Object} [args] */ getAllInvites : function(communityUuid, args) { var promise = this._validateCommunityUuid(communityUuid); if (promise) { return promise; } var requestArgs = lang.mixin({ communityUuid : communityUuid }, args || {}); var options = { method : "GET", handleAs : "text", query : requestArgs }; return this.getEntities(consts.AtomCommunityInvites, options, InviteFeedCallbacks); }, /** * Get a list of subcommunities associated with a community. * * @method getSubCommunities * @param {Object} [args] Object representing various parameters * that can be passed to get a feed of members of a * community. The parameters must be exactly as they are * supported by IBM Connections like ps, sortBy etc. */ getSubCommunities : function(communityUuid,args) { var promise = this._validateCommunityUuid(communityUuid); if (promise) { return promise; } var requestArgs = lang.mixin({ communityUuid : communityUuid }, args || {}); var options = { method : "GET", handleAs : "text", query : requestArgs }; return this.getEntities(consts.AtomCommunitySubCommunities, options, CommunityFeedCallbacks); }, /** * Get a list for forum topics for the specified community. * * @method getForumTopics * @param communityUuid * @param args * @returns */ getForumTopics: function(communityUuid, args) { return this.getForumService().getCommunityForumTopics(communityUuid, args); }, /** * Create a Community object with the specified data. * * @method newCommunity * @param {Object} args Object containing the fields for the * new Community */ newCommunity : function(args) { return this._toCommunity(args); }, /** * Create a Member object with the specified data. * * @method newMember * @param {Object} args Object containing the fields for the * new Member */ newMember : function(args) { return this._toMember(args); }, /** * Create a Invite object with the specified data. * * @method newInvite * @param {String} communityUuid * @param {Object} args Object containing the fields for the * new Invite */ newInvite : function(communityUuid,args) { return this._toInvite(communityUuid,args); }, /** * Retrieve a community entry, use the edit link for the community entry * which can be found in the my communities feed. * * @method getCommunity * @param {String } communityUuid * @param {Object} args Object containing the query arguments to be * sent (defined in IBM Connections Communities REST API) */ getCommunity : function(communityUuid, args) { var community = new Community({ service : this, _fields : { communityUuid : communityUuid } }); return community.load(args); }, /** * Create a community by sending an Atom entry document containing the * new community to the My Communities resource. * * @method createCommunity * @param {Object} community Community object which denotes the community to be created. * @param {Object} [args] Argument object */ createCommunity : function(communityOrJson,args) { var community = this._toCommunity(communityOrJson); var promise = this._validateCommunity(community, false, args); if (promise) { return promise; } var callbacks = {}; callbacks.createEntity = function(service,data,response) { var communityUuid = this.getLocationParameter(response, "communityUuid"); community.setCommunityUuid(communityUuid); return community; }; var options = { method : "POST", query : args || {}, headers : consts.AtomXmlHeaders, data : community.createPostData() }; return this.updateEntity(consts.AtomCommunitiesMy, options, callbacks, args); }, /** * Update a community by sending a replacement community entry document in Atom format * to the existing community's edit web address. * All existing community entry information will be replaced with the new data. To avoid * deleting all existing data, retrieve any data you want to retain first, and send it back * with this request. For example, if you want to add a new tag to a community entry, retrieve * the existing tags, and send them all back with the new tag in the update request. * * @method updateCommunity * @param {Object} community Community object * @param {Object} [args] Argument object */ updateCommunity : function(communityOrJson,args) { var community = this._toCommunity(communityOrJson); var promise = this._validateCommunity(community, true, args); if (promise) { return promise; } var callbacks = {}; callbacks.createEntity = function(service, data, response) { // preserve the communityUuid var communityUuid = community.getCommunityUuid(); if (data) { community.setData(data, response); } community.setCommunityUuid(communityUuid); return community; }; var requestArgs = lang.mixin({ communityUuid : community.getCommunityUuid() }, args || {}); var options = { method : "PUT", query : requestArgs, headers : consts.AtomXmlHeaders, data : community.createPostData() }; return this.updateEntity(consts.AtomCommunityInstance, options, callbacks, args); }, /** * Delete a community, use the HTTP DELETE method. * Only the owner of a community can delete it. Deleted communities cannot be restored * * @method deleteCommunity * @param {String/Object} community id of the community or the community object (of the community to be deleted) * @param {Object} [args] Argument object */ deleteCommunity : function(communityUuid,args) { var promise = this._validateCommunityUuid(communityUuid); if (promise) { return promise; } var requestArgs = lang.mixin({ communityUuid : communityUuid }, args || {}); var options = { method : "DELETE", query : requestArgs, handleAs : "text" }; return this.deleteEntity(consts.AtomCommunityInstance, options, communityUuid); }, /** * Add member to a community * * @method addMember * @param {String/Object} community id of the community or the community object. * @param {Object} member member object representing the member of the community to be added * @param {Object} [args] Argument object */ addMember : function(communityUuid,memberOrId,args) { var promise = this._validateCommunityUuid(communityUuid); if (promise) { return promise; } var member = this._toMember(memberOrId); promise = this._validateMember(member); if (promise) { return promise; } var callbacks = {}; callbacks.createEntity = function(service,data,response) { var userid = this.getLocationParameter(response, "userid"); member.setUserid(userid); member.communityUuid = communityUuid; return member; }; var requestArgs = lang.mixin({ communityUuid : communityUuid }, args || {}); var options = { method : "POST", query : requestArgs, headers : consts.AtomXmlHeaders, data : member.createPostData() }; return this.updateEntity(consts.AtomCommunityMembers, options, callbacks, args); }, /** * Updates a member in the access control list for an application, sends a replacement member entry document in Atom format to the existing ACL * node's edit web address. * @method updateMember * @param {String} activityUuid * @param {Object} memberOrJson */ updateMember : function(communityUuid, memberOrJson, args) { var promise = this.validateField("communityUuid", communityUuid); if (promise) { return promise; } var member = this._toMember(memberOrJson); promise = this._validateMember(member, true, true); if (promise) { return promise; } var requestArgs = { communityUuid : communityUuid }; var key = member.getEmail() ? "email" : "userid"; var value = member.getEmail() ? member.getEmail() : member.getUserid(); requestArgs[key] = value; requestArgs = lang.mixin(requestArgs, args || {}); var options = { method : "PUT", headers : consts.AtomXmlHeaders, query : requestArgs, data : member.createPostData() }; var callbacks = { createEntity : function(service, data, response) { return response; } }; return this.updateEntity(consts.AtomCommunityMembers, options, callbacks); }, /** * Remove member of a community * * @method * @param {String/Object} community id of the community or the community object. * @param {String} memberId id of the member * @param {Object} [args] Argument object */ removeMember : function(communityUuid,memberId,args) { var promise = this._validateCommunityUuid(communityUuid); if (promise) { return promise; } var member = this._toMember(memberId); promise = this._validateMember(member); if (promise) { return promise; } var requestArgs = { communityUuid : communityUuid }; var key = member.getEmail() ? "email" : "userid"; var value = member.getEmail() ? member.getEmail() : member.getUserid(); requestArgs[key] = value; requestArgs = lang.mixin(requestArgs, args || {}); var options = { method : "DELETE", query : requestArgs, handleAs : "text" }; return this.deleteEntity(consts.AtomCommunityMembers, options, value); }, /** * Retrieve a community invite. * * @method getInvite * @param {String} communityUuid * @param (String} userid */ getInvite : function(communityUuid, userid) { var invite = new Invite({ service : this, _fields : { communityUuid : communityUuid, userid : userid } }); return invite.load(); }, /** * Create an invite to be a member of a community. * * @method createInvite * @param {Object} inviteOrJson * @param {Object} [args] Argument object */ createInvite: function(inviteOrJson, args) { var invite = this._toInvite(inviteOrJson); var promise = this._validateInvite(invite, true); if (promise) { return promise; } var callbacks = {}; callbacks.createEntity = function(service, data, response) { invite.setData(data, response); return invite; }; var requestArgs = lang.mixin({ communityUuid : invite.getCommunityUuid() }, args || {}); var options = { method : "POST", query : requestArgs, headers : consts.AtomXmlHeaders, data : invite.createPostData() }; return this.updateEntity(consts.AtomCommunityInvites, options, callbacks, args); }, /** * Decline or revoke an invite to be a member of a community * * @method removeInvite * @param {Object} inviteOrJson * @param {Object} [args] Argument object */ removeInvite: function(inviteOrJson, args) { var invite = this._toInvite(inviteOrJson); var promise = this._validateInvite(invite, true); if (promise) { return promise; } var requestArgs = lang.mixin({ communityUuid : invite.getCommunityUuid(), userid : invite.getInviteeUuid() }, args || {}); var options = { method : "DELETE", query : requestArgs, handleAs : "text" }; var entityId = invite.getCommunityUuid() + "-" + invite.getInviteeUuid(); return this.deleteEntity(consts.AtomCommunityInvites, options, entityId); }, /** * Accept an invite to be a member of a community. * * @method acceptInvite * @param {Object} inviteOrJson. * @param {Object} [args] Argument object */ acceptInvite: function(inviteOrJson, args) { var invite = this._toInvite(inviteOrJson); var promise = this._validateInvite(invite, true); if (promise) { return promise; } var requestArgs = lang.mixin({ communityUuid : invite.getCommunityUuid() }, args || {}); var options = { method : "POST", query : requestArgs, headers : consts.AtomXmlHeaders, data : invite.createPostData() }; // return the community id for the community whose invite is accepted in the argument of the success promise. var callbacks = {}; callbacks.createEntity = function(service, data, response) { invite.setData(data, response); return invite; }; return this.updateEntity(consts.AtomCommunityMembers, options, callbacks, args); }, /** * Create a forum topc by sending an Atom entry document containing the * new forum to the forum replies resource. * * @method createForumTopic * @param {String} communityUuid This argument is deprecated and has no effect if provided. * @param {Object} forumTopic Forum topic object which denotes the forum topic to be created. * @param {Object} [args] Argument object */ createForumTopic : function(communityUuid, topicOrJson, args) { if(!lang.isString(communityUuid)){ args = topicOrJson; topicOrJson = communityUuid; } return this.getForumService().createForumTopic(topicOrJson, args); }, /** * Updates the Logo picture of a community * @method updateCommunityLogo * @param {Object} fileControlOrId The Id of html control or the html control * @param {String} communityUuid the Uuid of community */ updateCommunityLogo : function(fileControlOrId, communityUuid) { var promise = this.validateField("File Control Or Id", fileControlOrId); if (promise) { return promise; } promise = this.validateHTML5FileSupport(); if (promise) { return promise; } promise = this.validateField("CommunityUuid", communityUuid); if (promise) { return promise; } var files = null; var fileControl = this.getFileControl(fileControlOrId); if(!fileControl){ return this.createBadRequestPromise("File Control or ID is required"); } var filePath = fileControl.value; var files = fileControl.files; if (files.length != 1) { return this.createBadRequestPromise("Only one file can be upload as a community logo."); } var file = files[0]; var formData = new FormData(); formData.append("file", file); var requestArgs = { "communityUuid" : communityUuid }; var url = this.constructUrl(consts.AtomUpdateCommunityLogo, null, { endpointName : this.endpoint.proxyPath, fileName : encodeURIComponent(file.name) }); if (this.endpoint.proxy) { url = config.Properties.serviceUrl + url; } else { return this.createBadRequestPromise("File Proxy is required to upload a community logo"); } var headers = { "Content-Type" : false, "Process-Data" : false //processData = false is reaquired by jquery }; var options = { method : "PUT", headers : headers, query : requestArgs, data : formData }; var callbacks = { createEntity : function(service, data, response) { return data; // Since this API does not return any response in case of success, returning empty data } }; return this.updateEntity(url, options, callbacks); }, /** * Updates the Logo picture of a community * @method updateCommunityLogo * @param {Object} fileControlOrId The Id of html control or the html control * @param {String} communityUuid the Uuid of community */ uploadCommunityFile : function(fileControlOrId, communityUuid) { var promise = this.validateField("File Control Or Id", fileControlOrId); if (promise) { return promise; } promise = this.validateHTML5FileSupport(); if (promise) { return promise; } promise = this.validateField("CommunityUuid", communityUuid); if (promise) { return promise; } var files = null; var fileControl = this.getFileControl(fileControlOrId); if(!fileControl){ return this.createBadRequestPromise("File Control or ID is required"); } var filePath = fileControl.value; var files = fileControl.files; if (files.length != 1) { return this.createBadRequestPromise("Only one file can be uploaded to a community at a time"); } var file = files[0]; var formData = new FormData(); formData.append("file", file); var requestArgs = { }; var url = this.constructUrl(consts.AtomUploadCommunityFile, null, { endpointName : this.endpoint.proxyPath, communityUuid : communityUuid }); if (this.endpoint.proxy) { url = config.Properties.serviceUrl + url; } else { return this.createBadRequestPromise("File proxy is required to upload a community file"); } var headers = { "Content-Type" : false, "Process-Data" : false, //processData = false is reaquired by jquery "X-Endpoint-name" : this.endpoint.name }; var options = { method : "POST", headers : headers, query : requestArgs, data : formData }; var callbacks = { createEntity : function(service, data, response) { return data; } }; return this.updateEntity(url, options, callbacks); }, /** * Create a bookmark by sending an Atom entry document containing the * new bookmark. * * @method createBookmark * @param {String/Object} bookmarkOrJson Bookmark object which denotes the bookmark to be created. * @param {Object} [args] Argument object */ createBookmark : function(communityUuid, bookmarkOrJson, args) { args = lang.mixin({ url : consts.AtomCommunityBookmarks, communityUuid : communityUuid }, args || {}); return this.getBookmarkService().createBookmark(bookmarkOrJson, args); }, // // Internals // /* * Return a Community instance from Community or JSON or String. Throws * an error if the argument was neither. */ _toCommunity : function(communityOrJsonOrString) { if (communityOrJsonOrString instanceof Community) { return communityOrJsonOrString; } else { if (lang.isString(communityOrJsonOrString)) { communityOrJsonOrString = { communityUuid : communityOrJsonOrString }; } return new Community({ service : this, _fields : lang.mixin({}, communityOrJsonOrString) }); } }, /* * Return as Invite instance from Invite or JSON or String. Throws * an error if the argument was neither. */ _toInvite : function(inviteOrJsonOrString, args){ if (inviteOrJsonOrString instanceof Invite) { return inviteOrJsonOrString; } else { if (lang.isString(inviteOrJsonOrString)) { inviteOrJsonOrString = { communityUuid : inviteOrJsonOrString }; } return new Invite({ service : this, _fields : lang.mixin({}, inviteOrJsonOrString) }); } }, /* * Return a Community UUID from Community or communityUuid. Throws an * error if the argument was neither or is invalid. */ _toCommunityUuid : function(communityOrUuid) { var communityUuid = null; if (communityOrUuid) { if (lang.isString(communityOrUuid)) { communityUuid = communityOrUuid; } else if (communityOrUuid instanceof Community) { communityUuid = communityOrUuid.getCommunityUuid(); } } return communityUuid; }, /* * Return a Community Member from Member or memberId. Throws an error if * the argument was neither or is invalid. */ _toMember : function(idOrJson) { if (idOrJson) { if (idOrJson instanceof Member) { return idOrJson; } var member = new Member({ service : this }); if (lang.isString(idOrJson)) { if (this.isEmail(idOrJson)) { member.setEmail(idOrJson); } else { member.setUserid(idOrJson); } } else { if(idOrJson.id && !idOrJson.userid && !idOrJson.email){ this.isEmail(idOrJson.id) ? idOrJson.email = idOrJson.id : idOrJson.userid = idOrJson.id; delete idOrJson.id; } member._fields = lang.mixin({}, idOrJson); } return member; } }, /* * Validate a community UUID, and return a Promise if invalid. */ _validateCommunityUuid : function(communityUuid) { if (!communityUuid || communityUuid.length == 0) { return this.createBadRequestPromise("Invalid argument, expected communityUuid."); } }, /* * Validate a userid, and return a Promise if invalid. */ _validateUserid : function(userid) { if (!userid || userid.length == 0) { return this.createBadRequestPromise("Invalid argument, expected userid."); } }, /* * Validate that the date-time is not empty, return a promise if invalid */ _validateDateTimes : function(startDate, endDate){ if ((!startDate || startDate.length === 0) && (!endDate || endDate.length === 0)) { return this.createBadRequestPromise("Invalid date arguments, expected either a startDate, endDate or both as parameters."); } }, /* * Validate contributor id */ _validateContributorId : function(contributorId) { if (!contributorId || contributorId.length == 0) { return this.createBadRequestPromise("Invalid argument, expected contributorId."); } }, /* * Validate a community, and return a Promise if invalid. */ _validateCommunity : function(community,checkUuid) { if (!community || !community.getTitle()) { return this.createBadRequestPromise("Invalid argument, community with title must be specified."); } if (checkUuid && !community.getCommunityUuid()) { return this.createBadRequestPromise("Invalid argument, community with UUID must be specified."); } }, /* * Validate an invite, and return a Promise if invalid. */ _validateInvite : function(invite, checkCommunityUuid) { if (!invite || (!invite.getEmail() && !invite.getUserid() && !invite.getInviteeUuid())) { return this.createBadRequestPromise("Invalid argument, invite with email or userid or invitee must be specified."); } if (checkCommunityUuid && !invite.getCommunityUuid()) { return this.createBadRequestPromise("Invalid argument, invite with community UUID must be specified."); } }, /* * Validate a member, and return a Promise if invalid. */ _validateMember : function(member) { if (!member || (!member.getUserid() && !member.getEmail())) { return this.createBadRequestPromise("Invalid argument, member with userid or email must be specified."); } }, /* * Validate an event inst uuid, and return a Promise if invalid. */ _validateEventInstUuid : function(eventInstUuid) { if (!eventInstUuid || eventInstUuid.length == 0) { return this.createBadRequestPromise("Invalid argument, expected event inst uuid."); } }, /* * Validate an event UUID, and return a Promise if invalid. */ _validateEventUuid : function(eventUuid) { if (!eventUuid || eventUuid.length == 0) { return this.createBadRequestPromise("Invalid argument, expected eventUuid."); } } }); return CommunityService; }); }, 'sbt/smartcloud/Subscriber':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. * * @author Vimal Dhupar * Definition of a Subscriber Helper for getting the Subscriber ID for a SmartCloud User. */ define([ "../declare", "../Endpoint" ], function(declare, Endpoint) { /** * Subscriber Helper Class for getting the Subscriber ID for a SmartCloud User. * @class Subscriber * @namespace sbt.smartcloud */ var Subscriber = declare(null, { endpoint : null, /** * @constructor * @param endpoint * @param callback */ constructor : function(endpoint, callback) { this.endpoint = endpoint; if (callback) this.load(callback); }, /** * Load method is responsible for making the network call to fetch the user identity * @method load * @param callback */ load : function(callback) { var _self = this; this.endpoint.xhrGet({ serviceUrl : "/manage/oauth/getUserIdentity", loginUi : this.endpoint.loginUi, handleAs : "json", load : function(response) { callback(_self, response); }, error : function(error) { callback(_self, null); console.log("Error fetching feed for getUserIdentity"); } }); }, /** * Method to get the Subscriber Id of the user. * @method getSubscriberId * @param response * @returns */ getSubscriberId : function(response) { if (response && response.subscriberid) { return response.subscriberid; } return null; } }); return Subscriber; }); }, 'sbt/connections/WikiConstants':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. * Definition of constants for WikiService. */ define([ "../lang", "./ConnectionsConstants" ], function(lang,conn) { /** * XPath expressions to be used when reading a wiki or wiki page entry */ var BaseWikiXPath = lang.mixin({ uuid : "td:uuid", label : "td:label", permissions : "td:permissions", tags : "a:category[not(@scheme)]/@term", modifierName : "td:modifier/a:name", modifierEmail : "td:modifier/a:email", modifierUserid : "td:modifier/snx:userid", modifierUserState : "td:modifier/snx:userState", created : "td:created", modified : "td:modified", member : "ca:member", memberId : "ca:member/@ca:id", memberType : "ca:member/@ca:type", memberRole : "ca:member/@ca:role" }, conn.AtomEntryXPath); return lang.mixin(conn, { /** * XPath expressions used when parsing a Connections Wiki ATOM feed */ WikiFeedXPath : conn.ConnectionsFeedXPath, /** * XPath expressions to be used when reading a wiki entry */ WikiXPath : lang.mixin({ communityUuid : "snx:communityUuid", themeName : "td:themeName", librarySize : "td:librarySize", libraryQuota : "td:libraryQuota", totalRemovedSize : "td:totalRemovedSize" }, BaseWikiXPath, conn.AtomEntryXPath), /** * XPath expressions to be used when reading a wiki page entry */ WikiPageXPath : lang.mixin({ lastAccessed : "td:lastAccessed", versionUuid : "td:versionUuid", versionLabel : "td:versionLabel", propagation : "td:propagation", totalMediaSize : "td:totalMediaSize", recommendations : "snx:rank[@scheme='http://www.ibm.com/xmlns/prod/sn/recommendations']", comment : "snx:rank[@scheme='http://www.ibm.com/xmlns/prod/sn/comment']", hit : "snx:rank[@scheme='http://www.ibm.com/xmlns/prod/sn/hit']", anonymous_hit : "snx:rank[@scheme='http://www.ibm.com/xmlns/prod/sn/anonymous_hit']", share : "snx:rank[@scheme='http://www.ibm.com/xmlns/prod/sn/share']", collections : "snx:rank[@scheme='http://www.ibm.com/xmlns/prod/sn/collections']", attachments : "snx:rank[@scheme='http://www.ibm.com/xmlns/prod/sn/attachments']", versions : "snx:rank[@scheme='http://www.ibm.com/xmlns/prod/sn/versions']" }, BaseWikiXPath, conn.AtomEntryXPath), /** * This returns a feed of wikis to which the authenticated user has access. */ WikisAll : "/{wikis}/{authType}/api/wikis/feed", /** * This returns a feed of wikis to which everyone who can log into the Wikis application has access. */ WikisPublic : "/{wikis}/{authType}/api/wikis/public", /** * This returns a feed of wikis of which the authenticated user is a member. */ WikisMy : "/{wikis}/{authType}/api/mywikis/feed", /** * This returns a feed of wikis to which everyone who can log into the Wikis application has access. */ WikisMostCommented : "/{wikis}/{authType}/anonymous/api/wikis/mostcommented", /** * This returns a feed of wikis to which everyone who can log into the Wikis application has access. */ WikisMostRecommended : "/{wikis}/{authType}/api/wikis/mostrecommended", /** * This returns a feed of wikis to which everyone who can log into the Wikis application has access. */ WikisMostVisited : "/{wikis}/{authType}/api/wikis/mostvisited", /** * This returns a feed of the pages in a given wiki. */ WikiPages : "/{wikis}/{authType}/anonymous/api/wiki/{wikiLabel}/feed", /** * Get a feed that lists all of the pages in a specific wiki that have been added or edited by the authenticated user. */ WikiMyPages : "/{wikis}/{authType}/api/wiki/{wikiLabel}/mypages", /** * This returns a feed that lists the pages that have been deleted from wikis and are currently stored in the trash. */ WikiRecycleBin : "/{wikis}/{authType}/anonymous/api/wiki/{wikiLabelOrId}/recyclebin/feed", /** * Retrieve an Atom document of a wiki. */ WikiEntry : "/{wikis}/{authType}/api/wiki/{wikiLabel}/entry", /** * Returns a wiki page after authenticating the request. */ WikiPageEntry : "/{wikis}/{authType}/api/wiki/{wikiLabel}/page/{pageLabel}/entry", /** * Post to this feed to create a wiki page. */ WikiFeed : "/{wikis}/{authType}/api/wiki/{wikiLabel}/feed" }); }); }, 'sbt/_bridge/text':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. */ define([ "dojo/text" ], function(text) { var load = function(id,require,load) { text.load(id, require, load); }; return { load : load }; }); }, 'sbt/_bridge/Transport':function(){ /* * © Copyright IBM Corp. 2014 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. * * Implementation of a transport using the Dojo XHR API. */ define([ 'dojo/_base/declare', 'dojo/_base/xhr', 'dojo/_base/lang', '../util', '../Promise' ], function(declare, xhr, lang, util, Promise) { return declare(null, { /** * Provides an asynchronous request using the associated Transport. * * @method request * @param {String) * url The URL the request should be made to. * @param {Object} * [options] Optional A hash of any options for the provider. * @param {String|Object} * [options.data=null] Data, if any, that should be sent with * the request. * @param {String|Object} * [options.query=null] The query string, if any, that should * be sent with the request. * @param {Object} * [options.headers=null] The headers, if any, that should * be sent with the request. * @param {Boolean} * [options.preventCache=false] If true will send an extra * query parameter to ensure the the server won©t supply * cached values. * @param {String} * [options.method=GET] The HTTP method that should be used * to send the request. * @param {Integer} * [options.timeout=null] The number of milliseconds to wait * for the response. If this time passes the request is * canceled and the promise rejected. * @param {String} * [options.handleAs=text] The content handler to process the * response payload with. * @return {sbt.Promise} */ request : function(url, options) { var method = options.method || "GET"; method = method.toUpperCase(); var query = this.createQuery(options.query); var qurl = url; if(qurl && query){ qurl += (~qurl.indexOf('?') ? '&' : '?') + query; } var args = { url : qurl, handleAs : options.handleAs || "text" }; //if (options.query) { // args.content = options.query; //} if (options.headers) { args.headers = options.headers; } var hasBody = false; if (method == "PUT") { args.putData = options.data || null; hasBody = true; } else if (method == "POST") { args.postData = options.data || null; hasBody = true; } else if(method == "GET") { // to ensure each time fresh feed is retrieved with network call args.preventCache = true; } var promise = new Promise(); promise.response = new Promise(); var self = this; args.handle = function(response, ioargs) { if (response instanceof Error) { var error = response; error.response = self.createResponse(url, options, response, ioargs); promise.rejected(error); promise.response.rejected(error); } else { promise.fulfilled(response); promise.response.fulfilled(self.createResponse(url, options, response, ioargs)); } }; this.xhr(method, args, hasBody); return promise; }, /* * Create a response object */ createResponse: function(url, options, response, ioargs) { var xhr = ioargs._ioargs.xhr; var handleAs = options.handleAs || "text"; return { url : url, options : options, data : response, text : (handleAs == "text") ? response : null, status : xhr.status, getHeader : function(headerName) { return xhr.getResponseHeader(headerName); }, xhr : xhr, _ioargs : ioargs._ioargs }; }, /* * Create a query string from an object */ createQuery: function(queryMap) { if (!queryMap) { return null; } var pairs = []; for(var name in queryMap){ var value = queryMap[name]; if (lang.isArray(value)) { name = encodeURIComponent(name); for (var i=0; i<value.length; i++) { pairs.push(name + "=" + encodeURIComponent(value[i])); } } else { pairs.push(encodeURIComponent(name) + "=" + encodeURIComponent(value)); } } return pairs.join("&"); }, xhr: function(method, args, hasBody) { var _args = lang.mixin({}, args); // override the handle callback to normalise the Error var self = this; _args.handle = function(data, ioArgs) { self.handleResponse(data, ioArgs, args); }; // dojo.xhr(method, _args, hasBody); xhr(method, _args, hasBody); }, handleResponse: function(data, ioArgs, args) { var _data = data; if (data instanceof Error) { _data = this.createError(data, ioArgs); } try { var _ioArgs = { 'args' : args, 'headers' : util.getAllResponseHeaders(ioArgs.xhr), '_ioargs' : ioArgs }; args.handle(_data, _ioArgs); } catch (ex) { console.log(ex); } }, createError: function(error, ioArgs) { var _error = new Error(); _error.code = error.status || (error.response&&error.response.status) || 400; _error.cause = error; if (error.response) { _error.response = lang.mixin({}, error.response); } return _error; } }); }); }, 'sbt/connections/WikiService':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * The Wikis application of IBM© Connections enables teams to create a shared repository of information. * The Wikis API allows application programs to create new wikis, and to read and modify existing wikis. * * @module sbt.connections.WikiService */ define([ "../declare", "../config", "../lang", "../stringUtil", "../Promise", "./WikiConstants", "./ConnectionsService", "../base/AtomEntity", "../base/XmlDataHandler" ], function(declare,config,lang,stringUtil,Promise,consts,ConnectionsService,AtomEntity,XmlDataHandler) { var CategoryWiki = "<category scheme=\"http://www.ibm.com/xmlns/prod/sn/type\" term=\"wiki\" label=\"wiki\"></category>"; var CategoryWikiPage = "<category term=\"page\" scheme=\"tag:ibm.com,2006:td/type\" label=\"page\"/>"; var LabelTmpl = "<td:label>${getLabel}</td:label>"; var PermissionsTmpl = "<td:permissions>${getPermissions}</td:permissions>"; var CategoryTmpl = "<category term=\"${tag}\" label=\"${tag}\"></category>"; /** * Wiki class represents an entry for a Wiki or Wiki Page feed returned by the * Connections REST API. * * @class BaseWikiEntity * @namespace sbt.connections */ var BaseWikiEntity = declare(AtomEntity, { /** * Set to true to include the label in the post data when * performing an update or create operation. By default the * label is not sent which will keep it in synch with the * Wiki or WikiPage title. */ includeLabelInPost : false, /** * Construct a BaseWikiEntity entity. * * @constructor * @param args */ constructor : function(args) { }, /** * Return extra entry data to be included in post data for this entity. * * @returns {String} */ createEntryData : function() { var postData = ""; var transformer = function(value,key) { return value; }; if (this.getLabel() && this.includeLabelInPost) { postData += stringUtil.transform(LabelTmpl, this, transformer, this); } if (this.getPermissions()) { postData += stringUtil.transform(PermissionsTmpl, this, transformer, this); } return stringUtil.trim(postData); }, /** * Return an array containing the tags for this wiki. * * @method getTags * @return {Array} */ getTags : function() { var tags = this.getAsArray("tags"); return this.getAsArray("tags"); }, /** * Return an array containing the tags for this wiki. * * @method setTags * @param {Array} */ setTags : function(tags) { return this.setAsArray("tags", tags); }, /** * Return the value of id from Wiki ATOM * entry document. * * @method getWikiUuid * @return {String} Id of the Wiki */ getUuid : function() { var uid = this.getAsString("uuid"); return extractWikiUuid(uid); }, /** * Sets id of IBM Connections Wiki ATOM * entry document. * * @method setWikiUuid * @param {String} Id of the Wiki */ setUuid : function(uuid) { return this.setAsString("uuid", uuid); }, /** * Return short text label used to identify the Wiki Entry in API operation resource addresses. * * @method getLabel * @return {String} short text label used to identify the Wiki Entry in API operation resource addresses. */ getLabel : function() { return this.getAsString("label"); }, /** * Set the short text label used to identify the Wiki Entry in API operation resource addresses. * * @method setLabel * @param label short text label used to identify the Wiki Entry in API operation resource addresses. */ setLabel : function(label) { return this.setAsString("label", label); }, /** * Return the set of permissions available for the Wiki Entry. * * @method getPermissions * @return {String} Permissions available for the Wiki Entry */ getPermissions : function() { return this.getAsString("permissions"); }, /** * Set the permissions available for the Wiki Entry. * * @method setPermissions * @param permissions Permissions available for the Wiki Entry */ setPermissions : function(permissions) { return this.setAsString("permissions", permissions); }, /** * Return modifier of the Wiki Entry. * * @method getModifier * @return {Object} Modifier of the Wiki Entry */ getModifier : function() { return this.getAsObject( [ "modifierUserid", "modifierName", "modifierEmail", "modifierUserState" ], [ "userid", "name", "email", "userState" ]); }, /** * Return the date the wiki was created. * * @method getCreated * @return {Date} Date the wiki was created */ getCreated : function() { return this.getAsDate("created"); }, /** * Return the date the wiki was modified. * * @method getModified * @return {Date} Date the wiki was modified */ getModified : function() { return this.getAsDate("modified"); } }); /** * Wiki class represents an entry for a Wiki feed returned by the * Connections REST API. * * @class Wiki * @namespace sbt.connections */ var Wiki = declare(BaseWikiEntity, { xpath : consts.WikiXPath, contentType : "html", categoryScheme : CategoryWiki, /** * Construct a Wiki entity. * * @constructor * @param args */ constructor : function(args) { }, /** * Return the community©s unique ID if this wiki belongs to a community. * * @method getCommunityUuid * @return {String} Uuid of the Community */ getCommunityUuid : function() { return this.getAsString("communityUuid"); }, /** * Set the community©s unique ID if this wiki belongs to a community. * * @method setCommunityUuid * @param {String} communityUuid Community Uuid of the forum * @return {Wiki} */ setCommunityUuid : function(communityUuid) { return this.setAsString("communityUuid", communityUuid); }, /** * return the wiki theme name. * * @method getThemeName * @return {String} Wiki theme name */ getThemeName : function() { return this.getAsString("themeName"); }, /** * Return the library size. * * @method getLibrarySize * @return {Number} the library size */ getLibrarySize : function() { return this.getAsNumber("librarySize"); }, /** * Return the library quota. * * @method getLibraryQuota * @return {Number} the library quota */ getLibraryQuota : function() { return this.getAsNumber("libraryQuota"); }, /** * Return the total removed size. * * @method getTotalRemovedSize * @return {Number} the total removed size */ getTotalRemovedSize : function() { return this.getAsNumber("totalRemovedSize"); }, /** * Get a list for wiki pages from this wiki. * * @method getPages * @param {Object} args */ getPages : function(args) { return this.service.getWikiPages(this.getLabel(), args); }, /** * Loads the wiki object with the atom entry associated with the * wiki. By default, a network call is made to load the atom entry * document in the wiki object. * * @method load * @param {Object} [args] Argument object */ load : function(args) { // detect a bad request by validating required arguments var label = this.getLabel(); var promise = this.service._validateWikiLabel(label); if (promise) { return promise; } var self = this; var callbacks = { createEntity : function(service,data,response) { self.setData(data); return self; } }; var options = { method : "GET", handleAs : "text", query : args || {} }; var url = this.service.constructUrl(consts.WikiEntry, null, { "wikiLabel" : encodeURIComponent(label) }); return this.service.getEntity(url, options, label, callbacks); }, /** * Remove this wiki * * @method remove * @param {Object} [args] Argument object */ remove : function(args) { return this.service.deleteWiki(this.getLabel(), args); }, /** * Update this wiki * * @method update * @param {Object} [args] Argument object */ update : function(args) { return this.service.updateWiki(this, args); }, /** * Save this wiki * * @method save * @param {Object} [args] Argument object */ save : function(args) { if (this.getWikiUuid()) { return this.service.updateWiki(this, args); } else { return this.service.createWiki(this, args); } } }); /** * WikiPage class represents an entry for a Wiki Page feed returned by the * Connections REST API. * * @class WikiPage * @namespace sbt.connections */ var WikiPage = declare(BaseWikiEntity, { xpath : consts.WikiPageXPath, contentType : "html", categoryScheme : CategoryWikiPage, wikiLabel : null, /** * Construct a Wiki entity. * * @constructor * @param args */ constructor : function(args) { }, /** * Return the wiki label associated with this Wiki Page. * * @method getWikiLabel * @return {String} wiki label */ getWikiLabel : function() { if (this.wikiLabel) { return this.wikiLabel; } else { return this.getAsString("label"); } }, /** * Set the wiki label associated with this Wiki Page. * * @method setWikiLabel * @param {String} wiki label * @return {WikiPage} */ setWikiLabel : function(wikiLabel) { this.wikiLabel = wikiLabel; return this; }, /** * Return the last accessed date/time. * * @method getLastAccessed * @return {Date} the last accessed date/time */ getLastAccessed : function() { return this.getAsDate("lastAccessed"); }, /** * Return the version uuid. * * @method getVersionUuid * @return {String} the version uuid */ getVersionUuid : function() { return this.getAsString("versionUuid"); }, /** * Return the version label. * * @method getVersionLabel * @return {String} the version label */ getVersionLabel : function() { return this.getAsString("versionLabel"); }, /** * Return the propagation. * * @method getPropagation * @return {Boolean} the propagation */ getPropagation : function() { return this.getAsBoolean("propagation"); }, /** * Return the total media size. * * @method getTotalMediaSize * @return {Number} the total media size */ getTotalMediaSize : function() { return this.getAsNumber("totalMediaSize"); }, /** * Return the number of recommendations. * * @method getRecommendations * @return {Number} the number of recommendations */ getRecommendations : function() { return this.getAsNumber("recommendations"); }, /** * Return the number of comments. * * @method getComments * @return {Number} the number of comments */ getComments : function() { return this.getAsNumber("comment"); }, /** * Return the number of hits. * * @method getHits * @return {Number} the number of hits */ getHits : function() { return this.getAsNumber("hit"); }, /** * Return the number of anonymous hits. * * @method getAnonymousHits * @return {Number} the number of anonymous hits */ getAnonymousHits : function() { return this.getAsNumber("anonymous_hit"); }, /** * Return the number of shares. * * @method getShare * @return {Number} the number of shares */ getShare : function() { return this.getAsNumber("share"); }, /** * Return the number of collections. * * @method getCollections * @return {Number} the number of collections */ getCollections : function() { return this.getAsNumber("collections"); }, /** * Return the number of attachments. * * @method getAttachments * @return {Number} the number of attachments */ getAttachments : function() { return this.getAsNumber("attachments"); }, /** * Return the number of versions. * * @method getVersions * @return {Number} the number of versions */ getVersions : function() { return this.getAsNumber("versions"); }, /** * Loads the Wiki Page object with the atom entry associated with the * wiki. By default, a network call is made to load the atom entry * document in the Wiki Page object. * * @method load * @param {Object} [args] Argument object */ load : function(args) { // detect a bad request by validating required arguments var label = this.getLabel(); var promise = this.service._validatePageLabel(label); if (promise) { return promise; } var wikiLabel = this.getWikiLabel(); promise = this.service._validateWikiLabel(wikiLabel); if (promise) { return promise; } var self = this; var callbacks = { createEntity : function(service,data,response) { self.setData(data); return self; } }; var options = { method : "GET", handleAs : "text", query : args || {} }; var urlParams = { "pageLabel" : encodeURIComponent(label), "wikiLabel" : encodeURIComponent(wikiLabel) }; var url = this.service.constructUrl(consts.WikiPageEntry, null, urlParams); return this.service.getEntity(url, options, label, callbacks); }, /** * Remove this Wiki Page * * @method remove * @param {Object} [args] Argument object */ remove : function(args) { return this.service.deleteWikiPage(this.getLabel(), args); }, /** * Update this Wiki Page * * @method update * @param {Object} [args] Argument object */ update : function(args) { return this.service.updateWikiPage(this, args); }, /** * Save this Wiki Page * * @method save * @param {Object} [args] Argument object */ save : function(args) { if (this.getWikiUuid()) { return this.service.updateWikiPage(this, args); } else { return this.service.createWikiPage(this, args); } } }); /* * Method used to extract the wiki uuid for an id string. */ var extractWikiUuid = function(uid) { if (uid && uid.indexOf("urn:lsid:ibm.com:td:") == 0) { return uid.substring("urn:lsid:ibm.com:td:".length); } else { return uid; } }; /* * Callbacks used when reading a feed that contains wiki entries. */ var WikiFeedCallbacks = { createEntities : function(service,data,response) { return new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.WikiFeedXPath }); }, createEntity : function(service,data,response) { return new Wiki({ service : service, data : data }); } }; /* * Callbacks used when reading a feed that contains wiki page entries. */ var WikiPageFeedCallbacks = { createEntities : function(service,data,response) { return new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.WikiFeedXPath }); } }; /* * Callbacks used when reading an entry that contains wiki. */ var WikiCallbacks = { createEntity : function(service,data,response) { return new Wiki({ service : service, data : data }); } }; /** * WikisService class. * * @class WikisService * @namespace sbt.connections */ var WikiService = declare(ConnectionsService, { contextRootMap: { wikis: "wikis" }, serviceName : "wikis", /** * Constructor for WikisService * * @constructor * @param args */ constructor : function(args) { if (!this.endpoint) { this.endpoint = config.findEndpoint(this.getDefaultEndpointName()); } }, /** * Create a Wiki object with the specified data. * * @method newWiki * @param {Object} args Object containing the fields for the new Wiki */ newWiki : function(args) { return this._toWiki(args); }, /** * Create a Wiki Page object with the specified data. * * @method newWikiPage * @param {Object} args Object containing the fields for the new Wiki Page */ newWikiPage : function(args) { return this._toWikiPage(args); }, /** * This retrieves a list of wikis to which the authenticated user has access. * * @method getAllWikis * @param requestArgs */ getAllWikis: function(requestArgs) { var options = { method : "GET", handleAs : "text", query : requestArgs || {} }; return this.getEntities(consts.WikisAll, options, WikiFeedCallbacks); }, /** * This retrieves a list of wikis to which everyone who can log into the Wikis application has access. * * @method getPublicWikis * @param requestArgs */ getPublicWikis: function(requestArgs) { var options = { method : "GET", handleAs : "text", query : requestArgs || {} }; return this.getEntities(consts.WikisPublic, options, WikiFeedCallbacks); }, /** * This retrieves a list of wikis of which the authenticated user is a member. * * @method getMyWikis * @param requestArgs */ getMyWikis: function(requestArgs) { var options = { method : "GET", handleAs : "text", query : requestArgs || {} }; return this.getEntities(consts.WikisMy, options, WikiFeedCallbacks); }, /** * This retrieves a list all wikis sorted by wikis with the most comments first. * This returns a list of wikis to which everyone who can log into the Wikis application has access. * * @method getMostCommentedWikis * @param requestArgs */ getMostCommentedWikis: function(requestArgs) { var options = { method : "GET", handleAs : "text", query : requestArgs || {} }; return this.getEntities(consts.WikisMostCommented, options, WikiFeedCallbacks); }, /** * This retrieves a list all wikis sorted by wikis with the most recommendations first. * This returns a list of wikis to which everyone who can log into the Wikis application has access. * * @method getMostRecommendedWikis * @param requestArgs */ getMostRecommendedWikis: function(requestArgs) { var options = { method : "GET", handleAs : "text", query : requestArgs || {} }; return this.getEntities(consts.WikisMostRecommended, options, WikiFeedCallbacks); }, /** * This retrieves a list all wikis sorted by wikis with the most visits first. * This returns a list of wikis to which everyone who can log into the Wikis application has access. * * @method getMostVisitedWikis * @param requestArgs */ getMostVisitedWikis: function(requestArgs) { var options = { method : "GET", handleAs : "text", query : requestArgs || {} }; return this.getEntities(consts.WikisMostVisited, options, WikiFeedCallbacks); }, /** * This retrieves a list all of the pages in a specific wiki. * * @method getWikiPages * @param wikiLabel Value of the <td:label> element of the wiki. * @param requestArgs */ getWikiPages: function(wikiLabel, requestArgs) { var promise = this._validateWikiLabel(wikiLabel); if (promise) { return promise; } var options = { method : "GET", handleAs : "text", query : requestArgs || {} }; var callbacks = lang.mixin(WikiPageFeedCallbacks, { createEntity : function(service,data,response) { return new WikiPage({ service : service, wikiLabel : wikiLabel, data : data }); } }); var url = this.constructUrl(consts.WikiPages, null, { "wikiLabel" : encodeURIComponent(wikiLabel) }); return this.getEntities(url, options, callbacks); }, /** * This retrieves a list all of the pages in a specific wiki that have been added or edited by the authenticated user. * * @method geMyWikiPages * @param wikiLabel Value of the <td:label> element of the wiki. * @param requestArgs */ getMyWikiPages: function(wikiLabel, requestArgs) { var promise = this._validateWikiLabel(wikiLabel); if (promise) { return promise; } var options = { method : "GET", handleAs : "text", query : requestArgs || {} }; var callbacks = lang.mixin(WikiPageFeedCallbacks, { createEntity : function(service,data,response) { return new WikiPage({ service : service, wikiLabel : wikiLabel, data : data }); } }); var url = this.constructUrl(consts.WikiMyPages, null, { "wikiLabel" : encodeURIComponent(wikiLabel) }); return this.getEntities(url, options, callbacks); }, /** * This retrieves a list of the pages that have been deleted from wikis and are currently stored in the trash. * * @method getRecycledPages * @param wikiLabel Value of the <td:label> element or the <id> element of the wiki. * @param requestArgs */ getRecycledWikiPages: function(wikiLabelOrId, requestArgs) { var promise = this._validateWikiLabel(wikiLabelOrId); if (promise) { return promise; } var options = { method : "GET", handleAs : "text", query : requestArgs || {} }; var callbacks = lang.mixin(WikiPageFeedCallbacks, { createEntity : function(service,data,response) { return new WikiPage({ service : service, wikiLabelOrId : wikiLabelOrId, data : data }); } }); var url = this.constructUrl(consts.WikiRecycleBin, null, { "wikiLabelOrId" : encodeURIComponent(wikiLabelOrId) }); return this.getEntities(url, options, callbacks); }, /** * Retrieve a wiki. * * @method getWiki * @param wikiLabel Value of the <td:label> element or the <id> element of the wiki. * @param requestArgs */ getWiki: function(wikiLabel, requestArgs) { var wiki = new Wiki({ service : this, _fields : { label : wikiLabel } }); return wiki.load(requestArgs); }, /** * Create a wiki. * * @method createWiki * @param wikiOrJson * @param requestArgs */ createWiki: function(wikiOrJson, requestArgs) { var wiki = this._toWiki(wikiOrJson); var promise = this._validateWiki(wiki, false, requestArgs); if (promise) { return promise; } var callbacks = {}; callbacks.createEntity = function(service,data,response) { wiki.setData(data); return wiki; }; var options = { method : "POST", query : requestArgs || {}, headers : consts.AtomXmlHeaders, data : wiki.createPostData() }; return this.updateEntity(consts.WikisAll, options, callbacks, requestArgs); }, /** * Update a wiki. * All existing wiki information will be replaced with the new data. To avoid deleting all existing data, * retrieve any data you want to retain first, and send it back with this request. For example, if you want * to add a new tag to a wiki definition entry, retrieve the existing tags, and send them all back with the * new tag in the update request. * * @method updateWiki * @param wikiOrJson * @param requestArgs */ updateWiki: function(wikiOrJson, requestArgs) { var wiki = this._toWiki(wikiOrJson); var promise = this._validateWiki(wiki, true, requestArgs); if (promise) { return promise; } var callbacks = {}; callbacks.createEntity = function(service,data,response) { wiki.setData(data); return wiki; }; var options = { method : "PUT", query : requestArgs || {}, headers : consts.AtomXmlHeaders, data : wiki.createPostData() }; var url = this.constructUrl(consts.WikiEntry, null, { "wikiLabel" : encodeURIComponent(wiki.getLabel()) }); return this.updateEntity(url, options, callbacks, requestArgs); }, /** * Delete a wiki. * * @method deleteWiki * @param wikiLabel * @param requestArgs */ deleteWiki: function(wikiLabel, requestArgs) { var promise = this._validateWikiLabel(wikiLabel); if (promise) { return promise; } var options = { method : "DELETE", query : requestArgs || {}, handleAs : "text" }; var url = this.constructUrl(consts.WikiEntry, null, { "wikiLabel" : encodeURIComponent(wikiLabel) }); return this.deleteEntity(url, options, wikiLabel); }, /** * Retrieve a wiki page. * * @method getWikiPage * @param wikiLabel Value of the <td:label> element or the <id> element of the wiki. * @param requestArgs */ getWikiPage: function(wikiLabel, pageLabel, requestArgs) { var wikiPage = new WikiPage({ service : this, wikiLabel : wikiLabel, _fields : { label : pageLabel } }); return wikiPage.load(requestArgs); }, /** * Create a wiki page. * * @method createWikiPage * @param pageOrJson * @param requestArgs */ createWikiPage: function(pageOrJson, requestArgs) { var wikiPage = this._toWikiPage(pageOrJson); var promise = this._validateWikiPage(wikiPage, false, requestArgs); if (promise) { return promise; } var callbacks = {}; callbacks.createEntity = function(service,data,response) { wiki.setData(data); return wiki; }; var options = { method : "POST", query : requestArgs || {}, headers : consts.AtomXmlHeaders, data : wikiPage.createPostData() }; var url = this.constructUrl(consts.WikiFeed, null, { "wikiLabel" : encodeURIComponent(wikiPage.getWikiLabel()) }); return this.updateEntity(url, options, callbacks, requestArgs); }, /** * Update a wiki page. * * @method updateWikiPage * @param pageOrJson * @param requestArgs */ updateWikiPage: function(pageOrJson, requestArgs) { var wikiPage = this._toWikiPage(pageOrJson); var promise = this._validateWikiPage(wikiPage, true, requestArgs); if (promise) { return promise; } var callbacks = {}; callbacks.createEntity = function(service,data,response) { wikiPage.setData(data); return wikiPage; }; var options = { method : "PUT", query : requestArgs || {}, headers : consts.AtomXmlHeaders, data : wikiPage.createPostData() }; var urlParams = { "pageLabel" : encodeURIComponent(wikiPage.getLabel()), "wikiLabel" : encodeURIComponent(wikiPage.getWikiLabel()) }; var url = this.constructUrl(consts.WikiPageEntry, null, urlParams); return this.updateEntity(url, options, callbacks, requestArgs); }, /** * Delete a wiki page. * * @method deleteWikiPage * @param wikiLabel * @param pageLabel * @param requestArgs */ deleteWikiPage: function(wikiLabel, pageLabel, requestArgs) { var promise = this._validateWikiLabel(wikiLabel); if (promise) { return promise; } promise = this._validatePageLabel(pageLabel); if (promise) { return promise; } var options = { method : "DELETE", query : requestArgs || {}, handleAs : "text" }; var urlParams = { "pageLabel" : encodeURIComponent(label), "wikiLabel" : encodeURIComponent(wikiLabel) }; var url = this.constructUrl(consts.WikiPageEntry, null, urlParams); return this.deleteEntity(url, options, wikiLabel); }, // // Internals // /** * Move this to BaseService */ constructUrl : function(url,params,urlParams) { if (!url) { throw new Error("BaseService.constructUrl: Invalid argument, url is undefined or null."); } var _urlParams = lang.mixin( { authType: this.endpoint.authType }, this.contextRootMap, this.endpoint.serviceMappings, urlParams || {}); url = stringUtil.replace(url, _urlParams); if (params) { for (param in params) { if (url.indexOf("?") == -1) { url += "?"; } else if (url.indexOf("&") != (url.length - 1)) { url += "&"; } var value = encodeURIComponent(params[param]); if (value) { url += param + "=" + value; } } } return url; }, /* * Validate a Wiki and return a Promise if invalid. */ _validateWiki : function(wiki,checkLabel) { if (!wiki || !wiki.getTitle()) { return this.createBadRequestPromise("Invalid argument, wiki with title must be specified."); } if (checkLabel && !wiki.getLabel()) { return this.createBadRequestPromise("Invalid argument, wiki with label must be specified."); } }, /* * Validate a WikiPage and return a Promise if invalid. */ _validateWikiPage : function(wikiPage,checkLabels) { if (!wikiPage || !wikiPage.getTitle()) { return this.createBadRequestPromise("Invalid argument, wiki page with title must be specified."); } if (checkLabels && !wikiPage.getLabel()) { return this.createBadRequestPromise("Invalid argument, wiki page with label must be specified."); } if (checkLabels && !wikiPage.getWikiLabel()) { return this.createBadRequestPromise("Invalid argument, wiki page with wiki label must be specified."); } }, /* * Validate a wiki label, and return a Promise if invalid. */ _validateWikiLabel : function(wikiLabel) { if (!wikiLabel || wikiLabel.length == 0) { return this.createBadRequestPromise("Invalid argument, expected wiki label."); } }, /* * Validate a wiki page label, and return a Promise if invalid. */ _validatePageLabel : function(pageLabel) { if (!pageLabel || pageLabel.length == 0) { return this.createBadRequestPromise("Invalid argument, expected wiki page label."); } }, /* * Validate a wiki UUID, and return a Promise if invalid. */ _validateWikiUuid : function(wikiUuid) { if (!wikiUuid || wikiUuid.length == 0) { return this.createBadRequestPromise("Invalid argument, expected wikiUuid."); } }, /* * Return a Wiki instance from Wiki or JSON or String. Throws * an error if the argument was neither. */ _toWiki : function(wikiOrJsonOrString) { if (wikiOrJsonOrString instanceof Wiki) { return wikiOrJsonOrString; } else { if (lang.isString(wikiOrJsonOrString)) { wikiOrJsonOrString = { handle : wikiOrJsonOrString }; } return new Wiki({ service : this, _fields : lang.mixin({}, wikiOrJsonOrString) }); } }, /* * Return a WikiPage instance from WikiPage or JSON or String. Throws * an error if the argument was neither. */ _toWikiPage : function(pageOrJsonOrString) { if (pageOrJsonOrString instanceof WikiPage) { return pageOrJsonOrString; } else { if (lang.isString(pageOrJsonOrString)) { pageOrJsonOrString = { handle : pageOrJsonOrString }; } return new WikiPage({ service : this, _fields : lang.mixin({}, pageOrJsonOrString) }); } } }); return WikiService; }); }, 'sbt/Jsonpath':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK * JSONPath 0.8.0 - XPath for JSON * Would be replaced with JsonPath version of Github */ define(['./declare'],function(declare){ return function(obj, expr, arg) { var P = { resultType: arg && arg.resultType || "VALUE", result: [], normalize: function(expr) { var subx = []; return expr.replace(/[\['](\??\(.*?\))[\]']/g, function($0,$1){return "[#"+(subx.push($1)-1)+"]";}) .replace(/'?\.'?|\['?/g, ";") .replace(/;;;|;;/g, ";..;") .replace(/;$|'?\]|'$/g, "") .replace(/#([0-9]+)/g, function($0,$1){return subx[$1];}); }, asPath: function(path) { var x = path.split(";"), p = "$"; for (var i=1,n=x.length; i<n; i++) p += /^[0-9*]+$/.test(x[i]) ? ("["+x[i]+"]") : ("['"+x[i]+"']"); return p; }, store: function(p, v) { if (p) P.result[P.result.length] = P.resultType == "PATH" ? P.asPath(p) : v; return !!p; }, trace: function(expr, val, path) { if (expr) { var x = expr.split(";"), loc = x.shift(); x = x.join(";"); if (val && val.hasOwnProperty(loc)) P.trace(x, val[loc], path + ";" + loc); else if (loc === "*") P.walk(loc, x, val, path, function(m,l,x,v,p) { P.trace(m+";"+x,v,p); }); else if (loc === "..") { P.trace(x, val, path); P.walk(loc, x, val, path, function(m,l,x,v,p) { typeof v[m] === "object" && P.trace("..;"+x,v[m],p+";"+m); }); } else if (/,/.test(loc)) { // [name1,name2,...] for (var s=loc.split(/'?,'?/),i=0,n=s.length; i<n; i++) P.trace(s[i]+";"+x, val, path); } else if (/^\(.*?\)$/.test(loc)) // [(expr)] P.trace(P.eval(loc, val, path.substr(path.lastIndexOf(";")+1))+";"+x, val, path); else if (/^\?\(.*?\)$/.test(loc)) // [?(expr)] P.walk(loc, x, val, path, function(m,l,x,v,p) { if (P.eval(l.replace(/^\?\((.*?)\)$/,"$1"),v[m],m)) P.trace(m+";"+x,v,p); }); else if (/^(-?[0-9]*):(-?[0-9]*):?([0-9]*)$/.test(loc)) // [start:end:step] phyton slice syntax P.slice(loc, x, val, path); } else P.store(path, val); }, walk: function(loc, expr, val, path, f) { if (val instanceof Array) { for (var i=0,n=val.length; i<n; i++) if (i in val) f(i,loc,expr,val,path); } else if (typeof val === "object") { for (var m in val) if (val.hasOwnProperty(m)) f(m,loc,expr,val,path); } }, slice: function(loc, expr, val, path) { if (val instanceof Array) { var len=val.length, start=0, end=len, step=1; loc.replace(/^(-?[0-9]*):(-?[0-9]*):?(-?[0-9]*)$/g, function($0,$1,$2,$3){start=parseInt($1||start);end=parseInt($2||end);step=parseInt($3||step);}); start = (start < 0) ? Math.max(0,start+len) : Math.min(len,start); end = (end < 0) ? Math.max(0,end+len) : Math.min(len,end); for (var i=start; i<end; i+=step) P.trace(i+";"+expr, val, path); } }, eval: function(x, _v, _vname) { try { return $ && _v && eval(x.replace(/@/g, "_v")); } catch(e) { throw new SyntaxError("jsonPath: " + e.message + ": " + x.replace(/@/g, "_v").replace(/\^/g, "_a")); } } }; var $ = obj; if (expr && obj && (P.resultType == "VALUE" || P.resultType == "PATH")) { P.trace(P.normalize(expr).replace(/^\$;/,""), obj, "$"); return P.result.length ? P.result : false; } }; }); }, 'sbt/Gadget':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK - OpenSocial specific helpers. */ define(function() { //sbt.getUserPref = function(ns,name) { // //}; }); }, 'sbt/IWidget':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK - iWidget specific helpers. */ define([],function() { sbt.getUserPref = function(ns,name) { }; }); }, 'sbt/connections/ProfileService':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * JavaScript API for IBM Connections Profile Service. * * @module sbt.connections.ProfileService */ define([ "../declare", "../lang", "../config", "../stringUtil", "./ProfileConstants", "./ConnectionsService", "../base/BaseEntity", "../base/AtomEntity", "../base/XmlDataHandler", "../base/VCardDataHandler", "../Cache", "../util" ], function( declare,lang,config,stringUtil,consts,ConnectionsService,BaseEntity,AtomEntity,XmlDataHandler, VCardDataHandler, Cache, util) { var CategoryProfile = "<category term=\"profile\" scheme=\"http://www.ibm.com/xmlns/prod/sn/type\"></category>"; var updateProfileXmlTemplate = "\nBEGIN:VCARD\nVERSION:2.1\n${jobTitle}${address}${telephoneNumber}${building}${floor}END:VCARD\n"; var updateProfileAttributeTemplate = "${attributeName}:${attributeValue}\n"; var updateProfileAddressTemplate = "ADR;WORK:;;${streetAddress},${extendedAddress};${locality};${region};${postalCode};${countryName}\n"; var ContentTmpl = "<content type=\"${contentType}\">${content}</content>"; var createProfileTemplate = "<person xmlns=\"http://ns.opensocial.org/2008/opensocial\"><com.ibm.snx_profiles.attrib>${guid}${email}${uid}${distinguishedName}${displayName}${givenNames}${surname}${userState}</com.ibm.snx_profiles.attrib></person>"; var createProfileAttributeTemplate = "<entry><key>${attributeName}</key><value><type>text</type><data>${attributeValue}</data></value></entry>"; var createProfileTagsTemplate = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><app:categories xmlns:snx=\"http://www.ibm.com/xmlns/prod/sn\" xmlns:atom=\"http://www.w3.org/2005/Atom\" xmlns:app=\"http://www.w3.org/2007/app\">${createTags}</app:categories>" var CategoryTmpl = "<atom:category term=\"${tag}\"></atom:category>"; var CategoryConnection = "<category term=\"connection\" scheme=\"http://www.ibm.com/xmlns/prod/sn/type\" />"; var CategoryConnectionType = "<category term=\"${getConnectionType}\" scheme=\"http://www.ibm.com/xmlns/prod/sn/connection/type\" />"; var CategoryStatus = "<category term=\"${getStatus}\" scheme=\"http://www.ibm.com/xmlns/prod/sn/status\" />"; var OAuthString = "/oauth"; var basicAuthString = ""; var defaultAuthString = ""; /** * Profile class. * * @class Profile * @namespace sbt.connections */ /* * ProfileDataHandler class. */ var Profile = declare(AtomEntity, { xpath : consts.ProfileXPath, namespaces : consts.ProfileNamespaces, categoryScheme : CategoryProfile, _update : false, /** * * @constructor * @param args */ constructor : function(args) { }, /** * Data handler for profile object based on the query paramter - "output", used to get the profile. * If the value of output paramter is "vcard", the VCardDataHandler is associated with * the profile object else, by default, XmlDataHandler is associated with the object. * * @param {Object} service ProfileService instance associated with the profile object * @param {Object} data Profile document associated with the profile object * @response {Object} response Response object returned after the operation for get/create/update * of the profile * @namespaces {Object} namespace NameSpace object associated with the profile * @xpath {Object} xpath XPath object associated with the profile */ createDataHandler : function(service, data, response, namespaces, xpath) { if (response.options && response.options.query && response.options.query.output == "vcard") { return new VCardDataHandler({ service: service, data : data, namespaces : namespaces, xpath : consts.ProfileVCardXPath }); } else { return new XmlDataHandler({ service: service, data : data, namespaces : namespaces, xpath : xpath }); } }, /** * Get id of the profile * * @method getUserid * @return {String} id of the profile * */ getUserid : function() { return this.getAsString("userid"); }, /** * Get name of the profile * * @method getName * @return {String} name of the profile * */ getName : function() { return this.getAsString("name"); }, /** * Get email of the profile * * @method getEmail * @return {String} email of the profile */ getEmail : function() { return this.getAsString("email"); }, /** * Get groupware mail of the profile * * @method getGroupwareMail * @return {String} groupware mail of the profile */ getGroupwareMail : function() { return this.getAsString("groupwareMail"); }, /** * Get thumbnail URL of the profile * * @method getThumbnailUrl * @return {String} thumbnail URL of the profile */ getThumbnailUrl : function() { return this.getAsString("photoUrl"); }, /** * Get job title of the profile * * @method getJobTitle * @return {String} job title of the profile */ getJobTitle : function() { return this.getAsString("jobTitle"); }, /** * Get department of the profile * * @method getDepartment * @return {String} department of the profile */ getDepartment : function() { return this.getAsString("organizationUnit"); }, /** * Get address of the profile * * @method getAddress * @return {Object} Address object of the profile */ getAddress : function() { return this.getAsObject(consts.AddressFields); }, /** * Get telephone number of the profile * * @method getTelephoneNumber * @return {String} Phone number of the profile */ getTelephoneNumber : function() { return this.getAsString("telephoneNumber"); }, /** * Get profile URL of the profile * * @method getProfileUrl * @return {String} profile URL of the profile */ getProfileUrl : function() { return this.getAsString("fnUrl"); }, /** * Get building name of the profile * * @method getBuilding * @return {String} building name of the profile */ getBuilding : function() { return this.getAsString("building"); }, /** * Get floor address of the profile * * @method getFloor * @return {String} floor address of the profile */ getFloor : function() { return this.getAsString("floor"); }, /** * Get Pronunciation URL of the profile * * @method getPronunciationUrl * @return {String} Pronunciation URL of the profile */ getPronunciationUrl : function() { return this.getAsString("soundUrl"); }, /** * Get summary of the profile * * @method getSummary * @return {String} description of the profile */ getSummary : function() { return this.getAsString("summary"); }, /** * Set work phone number of the profile in the field object * * @method setTelephoneNumber * @param {String} telephoneNumber work phone number of the profile */ setTelephoneNumber : function(telephoneNumber) { this.setAsString("telephoneNumber", telephoneNumber); }, /** * Set building of the profile in the field object * * @method setBuilding * @param {String} building building name of the profile */ setBuilding : function(building) { this.setAsString("building", building); }, /** * Set floor number of the profile in the field object * * @method setFloor * @param {String} floor floor number of the profile */ setFloor : function(floor) { this.setAsString("floor", floor); }, /** * Set job title of the profile in the field object * * @method setJobTitle * @param {String} title job title of the profile */ setJobTitle : function(title) { this.setAsString("jobTitle", title); }, /** * Set the location of the file input element in the markup for editing * profile photo in the field object * * @method setPhotoLocation * @param {String} imgLoc location of the file input element */ setPhotoLocation : function(imgLoc) { this.setAsString("imageLocation", imgLoc); }, /** * Set the address of the profile in the field object * * @method setAddress * @param {Object} address Address object of the profile. */ setAddress : function(address) { this.setAsObject(address); }, /** * Loads the profile object with the profile entry document associated * with the profile. By default, a network call is made to load the * profile entry document in the profile object. * * @method load * @param {Object} [args] Object representing various query parameters * that can be passed. The parameters must be exactly as they are * supported by IBM Connections. * */ load : function(args) { var profileId = this.getUserid() || this.getEmail(); var promise = this.service._validateProfileId(profileId); if (promise) { return promise; } var self = this; var callbacks = { createEntity : function(service,data,response) { self.setData(data, response); return self; } }; var requestArgs = {}; if (this.service.isEmail(profileId)) { requestArgs.email = profileId; } else { requestArgs.userid = profileId; } lang.mixin(requestArgs, args || {}); var options = { handleAs : "text", query : requestArgs }; var url = this.service.constructUrl(consts.AtomProfileDo, {}, {authType : this.service._getProfileAuthString()}); return this.service.getEntity(url, options, profileId, callbacks, args); }, /** * Updates the profile of a user. * * @method update * @param {Object} [args] Object representing various query parameters * that can be passed. The parameters must be exactly as they are * supported by IBM Connections. */ update : function(args) { return this.service.updateProfile(this, args); }, /** * Get colleagues of the profile. * * @method getColleagues * @param {Object} [args] Object representing various query parameters * that can be passed. The parameters must be exactly as they are * supported by IBM Connections. */ getColleagues : function(args){ return this.service.getColleagues(this, args); }, /** * Get colleague connections of the profile. * * @method getColleagueConnections * @param {Object} [args] Object representing various query parameters * that can be passed. The parameters must be exactly as they are * supported by IBM Connections. */ getColleagueConnections : function(args){ return this.service.getColleagueConnections(this, args); }, /** * Return content element to be included in post data for the creation or updaton of new profile entry. * * @method createContent * @returns {String} */ createContent : function() { if(this._update){ this._update = false; var transformer = function(value,key) { if (key == "address") { value = this.service._isAddressSet(this) ? stringUtil.transform(updateProfileAddressTemplate, {"streetAddress" : this._fields["streetAddress"], "extendedAddress" : this._fields["extendedAddress"], "locality" : this._fields["locality"], "region" : this._fields["region"], "postalCode" : this._fields["postalCode"], "countryName" : this._fields["countryName"]}) : null; } else{ value = (this._fields[key])? stringUtil.transform(updateProfileAttributeTemplate, {"attributeName" : consts.ProfileVCardXPath[key], "attributeValue" : this._fields[key]}) : null; } return value; }; var content = stringUtil.transform(updateProfileXmlTemplate, this, transformer, this); if (content) { return stringUtil.transform(ContentTmpl, { "contentType" : "text", "content" : content }); } return ""; }else{ var transformer = function(value,key) { if(this._fields[key]){ value = stringUtil.transform(createProfileAttributeTemplate, {"attributeName" : consts.profileCreateAttributes[key], "attributeValue" : this._fields[key]}); return value; } }; var content = stringUtil.transform(createProfileTemplate, this, transformer, this); if(content){ return stringUtil.transform(ContentTmpl, { "contentType" : "application/xml", "content" : content }); } return ""; } }, /** * Return tags elements to be included in post data for creation and updation of profile entry. * * @method createTags * @returns {String} */ createTags : function() { return ""; } }); /** * ColleagueConnection class. * * @class ConnectionEntry * @namespace sbt.connections */ var ColleagueConnection = declare(AtomEntity, { /** * * @constructor * @param args */ constructor : function(args) { } }); /** * ProfileTag class. * * @class ProfileTag * @namespace sbt.connections */ var ProfileTag = declare(BaseEntity, { /** * * @constructor * @param args */ constructor : function(args) { }, /** * Get term of the profile tag * * @method getTerm * @return {String} term of the profile tag * */ getTerm : function() { return this.getAsString("term"); }, /** * Get frequency of the profile tag * * @method getFrequency * @return {Number} frequency of the profile tag * */ getFrequency : function() { return this.getAsNumber("frequency"); }, /** * Get intensity of the profile tag * * @method getIntensity * @return {Number} intensity of the profile tag * */ getIntensity : function() { return this.getAsNumber("intensity"); }, /** * Get visibility of the profile tag * * @method getVisibility * @return {Number} visibility of the profile tag * */ getVisibility : function() { return this.getAsNumber("visibility"); } }); /** * Invite class. * * @class Invite * @namespace sbt.connections */ var Invite = declare(AtomEntity, { xpath : consts.InviteXPath, contentType : "html", categoryScheme : CategoryConnection, /** * * @constructor * @param args */ constructor : function(args) { }, /** * Return extra entry data to be included in post data for this entity. * * @returns {String} */ createEntryData : function() { var entryData = ""; entryData += stringUtil.transform(CategoryConnectionType, this, function(v,k) { return v; }, this); entryData += stringUtil.transform(CategoryStatus, this, function(v,k) { return v; }, this); return stringUtil.trim(entryData); }, /** * Return tags elements to be included in post data for creation and updation of invite entry. * * @method createTags * @returns {String} */ createTags : function() { return ""; }, /** * Return the connection type associated with this invite. * * @method getConnectionType * @return {String} status */ getConnectionType : function() { var connectionType = this.getAsString("connectionType"); return connectionType || consts.TypeColleague; }, /** * Set the connection type associated with this invite. * * @method setConnectionType * @param {String} status */ setConnectionType : function(connectionType) { return this.setAsString("connectionType", connectionType); }, /** * Return the status associated with this invite. * * @method getStatus * @return {String} status */ getStatus : function() { var status = this.getAsString("status"); return status || consts.StatusPending; }, /** * Set the status associated with this invite. * * @method setStatus * @param {String} status */ setStatus : function(status) { return this.setAsString("status", status); }, /** * Return the connection id associated with this invite. * * @method getConnectionId * @return {String} connectionId */ getConnectionId : function() { return this.getAsString("connectionId"); }, /** * Set connection id associated with this invite. * * @method setConnectionId * @param connectionId * @return {Invite} */ setConnectionId : function(connectionId) { return this.setAsString("connectionId", connectionId); } }); /** * Callbacks used when reading an entry that contains a Profile. */ var ProfileCallbacks = { createEntity : function(service,data,response) { return new Profile({ service : service, data : data, response: response }); } }; /** * Callbacks used when reading a feed that contains Profile entries. */ var ProfileFeedCallbacks = { createEntities : function(service,data,response) { return new XmlDataHandler({ data : data, namespaces : consts.Namespaces, xpath : consts.ProfileFeedXPath }); }, createEntity : function(service,data,response) { return new Profile({ service : service, data: data, response: response }); } }; /** * Callbacks used when reading a feed that contains ColleagueConnections */ var ColleagueConnectionFeedCallbacks = { createEntities : function(service,data,response) { return new XmlDataHandler({ data : data, namespaces : consts.Namespaces, xpath : consts.ProfileFeedXPath }); }, createEntity : function(service,data,response) { return new ColleagueConnection({ service : service, data: data, response: response }); } }; /** * Callbacks used when reading a feed that contains Profile Tag entries. */ var ProfileTagFeedCallbacks = { createEntities : function(service,data,response) { return new XmlDataHandler({ data : data, namespaces : consts.Namespaces, xpath : consts.ProfileTagsXPath }); }, createEntity : function(service,data,response) { var entryHandler = new XmlDataHandler({ data : data, namespaces : consts.Namespaces, xpath : consts.ProfileTagsXPath }); return new ProfileTag({ service : service, id : entryHandler.getEntityId(), dataHandler : entryHandler }); } }; /** * ProfileService class. * * @class ProfileService * @namespace sbt.connections */ var ProfileService = declare(ConnectionsService, { contextRootMap: { profiles: "profiles" }, serviceName : "profiles", /** * * @constructor * @param args */ constructor : function(args) { if (!this.endpoint) { this.endpoint = config.findEndpoint(this.getDefaultEndpointName()); } if(!this._cache){ if(config.Properties.ProfileCacheSize || consts.DefaultCacheSize){ this._cache = new Cache(config.Properties.ProfileCacheSize || consts.DefaultCacheSize); } } }, /** * Create a Profile object with the specified data. * * @method newProfile * @param {Object} args Object containing the fields for the * new Profile */ newProfile : function(args) { return this._toProfile(args); }, /** * Create a Invite object with the specified data. * * @method newInvite * @param {Object} args Object containing the fields for the * new Invite */ newInvite : function(args) { return this._toInvite(args); }, /** * Get the profile of a user. * * @method getProfile * @param {String} userIdOrEmail Userid or email of the profile * @param {Object} [args] Object representing various query parameters * that can be passed. The parameters must be exactly as they are * supported by IBM Connections. */ getProfile : function(userIdOrEmail, args) { var profile = this._toProfile(userIdOrEmail); var promise = this._validateProfile(profile); if (promise) { return promise; } return profile.load(args); }, /** * Update an existing profile * * @method updateProfile * @param {Object} profileOrJson Profile object to be updated * @param {Object} [args] Object representing various query parameters * that can be passed. The parameters must be exactly as they are * supported by IBM Connections. */ updateProfile : function(profileOrJson,args) { var profile = this._toProfile(profileOrJson); profile._update = true; var promise = this._validateProfile(profile); if (promise) { return promise; } var requestArgs = {}; profile.getUserid() ? requestArgs.userid = profile.getUserid() : requestArgs.email = profile.getEmail(); lang.mixin(requestArgs, args || {}); var callbacks = {}; callbacks.createEntity = function(service,data,response) { return profile; }; var options = { method : "PUT", query : requestArgs, headers : consts.AtomXmlHeaders, data : profile.createPostData() }; var url = this.constructUrl(consts.AtomProfileEntryDo, {}, {authType : this._getProfileAuthString()}); return this.updateEntity(url, options, callbacks, args); }, /** * Get the tags for the specified profile * * @method getTags * @param {String} id userId/email of the profile * @param {Object} args Object representing various query parameters that can be passed. The parameters must * be exactly as they are supported by IBM Connections. */ getTags : function(id, args) { // detect a bad request by validating required arguments var idObject = this._toTargetObject(id); var promise = this._validateTargetObject(idObject); if (promise) { return promise; } var options = { method : "GET", handleAs : "text", query : lang.mixin(idObject, args || {}) }; var url = this.constructUrl(consts.AtomTagsDo, {}, {authType : this._getProfileAuthString()}); return this.getEntities(url, options, this.getProfileTagFeedCallbacks(), args); }, /** * Get the colleagues for the specified profile * * @method getColleagues * @param {String} id userId/email of the profile * @param {Object} args Object representing various query parameters * that can be passed. The parameters must be exactly as they are * supported by IBM Connections. */ getColleagues : function(id, args) { // detect a bad request by validating required arguments var idObject = this._toIdObject(id); var promise = this._validateIdObject(idObject); if (promise) { return promise; } var requestArgs = lang.mixin(idObject, { connectionType : "colleague", outputType : "profile" }, args || {}); var options = { method : "GET", handleAs : "text", query : requestArgs }; var url = this.constructUrl(consts.AtomConnectionsDo, {}, {authType : this._getProfileAuthString()}); return this.getEntities(url, options, this.getProfileFeedCallbacks(), args); }, /** * Get the colleagues for the specified profile as Collegue Connection entries * * @method getColleagueConnections * @param {String} id userId/email of the profile * @param {Object} args Object representing various query parameters * that can be passed. The parameters must be exactly as they are * supported by IBM Connections. */ getColleagueConnections : function(id, args) { // detect a bad request by validating required arguments var idObject = this._toIdObject(id); var promise = this._validateIdObject(idObject); if (promise) { return promise; } var requestArgs = lang.mixin(idObject, { connectionType : "colleague", outputType : "connection" }, args || {}); var options = { method : "GET", handleAs : "text", query : requestArgs }; var url = this.constructUrl(consts.AtomConnectionsDo, {}, {authType : this._getProfileAuthString()}); return this.getEntities(url, options, this.getColleagueConnectionFeedCallbacks(), args); }, /** * Get the reporting chain for the specified person. * * @method getReportingChain * @param {String} id userId/email of the profile * @param {Object} args Object representing various query parameters * that can be passed. The parameters must be exactly as they are * supported by IBM Connections. */ getReportingChain : function(id, args) { // detect a bad request by validating required arguments var idObject = this._toIdObject(id); var promise = this._validateIdObject(idObject); if (promise) { return promise; } var requestArgs = lang.mixin(idObject, args || {}); var options = { method : "GET", handleAs : "text", query : requestArgs }; var url = this.constructUrl(consts.AtomReportingChainDo, {}, {authType : this._getProfileAuthString()}); return this.getEntities(url, options, this.getProfileFeedCallbacks(), args); }, /** * Get the people managed for the specified person. * * @method getPeopleManaged * @param {String} id userId/email of the profile * @param {Object} args Object representing various query parameters * that can be passed. The parameters must be exactly as they are * supported by IBM Connections. */ getPeopleManaged : function(id, args) { // detect a bad request by validating required arguments var idObject = this._toIdObject(id); var promise = this._validateIdObject(idObject); if (promise) { return promise; } var requestArgs = lang.mixin(idObject, args || {}); var options = { method : "GET", handleAs : "text", query : requestArgs }; var url = this.constructUrl(consts.AtomPeopleManagedDo, {}, {authType : this._getProfileAuthString()}); return this.getEntities(url, options, this.getProfileFeedCallbacks(), args); }, /** * Search for a set of profiles that match a specific criteria and return them in a feed. * * @method search * @param {Object} args Object representing various query parameters * that can be passed. The parameters must be exactly as they are * supported by IBM Connections. */ search : function(args) { // detect a bad request by validating required arguments if (!args) { return this.createBadRequestPromise("Invalid arguments, one or more of the input parameters to narrow the search must be specified."); } var options = { method : "GET", handleAs : "text", query : args }; var url = this.constructUrl(consts.AtomSearchDo, {}, {authType : this._getProfileAuthString()}); return this.getEntities(url, options, this.getProfileFeedCallbacks(), args); }, /** * Updates the profile photo of a user. * @method updateProfilePhoto * @param {Object} fileControlOrId The Id of html control or the html control * @param @param {String} id userId/email of the profile * @param {Object} [args] The additional parameters */ updateProfilePhoto: function (fileControlOrId, id, args) { var promise = this.validateField("File Control Or Id", fileControlOrId); if (promise) { return promise; } promose = this.validateHTML5FileSupport(); if(promise){ return promise; } var idObject = this._toIdObject(id); var files = null; if (typeof fileControlOrId == "string") { var fileControl = document.getElementById(fileControlOrId); filePath = fileControl.value; files = fileControl.files; } else if (typeof fileControlOrId == "object") { filePath = fileControlOrId.value; files = fileControlOrId.files; } else { return this.createBadRequestPromise("File Control or ID is required"); } if(files.length != 1){ return this.createBadRequestPromise("Only one file needs to be provided to this API"); } var file = files[0]; var formData = new FormData(); formData.append("file", file); var requestArgs = lang.mixin(idObject, args || {}); var url = this.constructUrl(config.Properties.serviceUrl + "/files/" + this.endpoint.proxyPath + "/" + "connections" + "/" + "UpdateProfilePhoto" + "/" + encodeURIComponent(file.name), args && args.parameters ? args.parameters : {}); var headers = { "Content-Type" : false, "Process-Data" : false // processData = false is reaquired by jquery }; var options = { method : "PUT", headers : headers, query : requestArgs || {}, data : formData }; var callbacks = { createEntity : function(service, data, response) { return data; // Since this API does not return any response in case of success, returning empty data } }; return this.updateEntity(url, options, callbacks); }, /** * Invite a person to become your colleague. * * @method inviteColleague * @param id * @param inviteOrJson * @param args */ createInvite : function(id, inviteOrJson, args) { // detect a bad request by validating required arguments var idObject = this._toIdObject(id); var promise = this._validateIdObject(idObject); if (promise) { return promise; } var invite = this._toInvite(inviteOrJson); var callbacks = {}; callbacks.createEntity = function(service,data,response) { invite.setData(data); var connectionId = this.getLocationParameter(response, "connectionId"); invite.setConnectionId(connectionId); return invite; }; var requestArgs = lang.mixin(idObject, args || {}); var options = { method : "POST", query : requestArgs, headers : consts.AtomXmlHeaders, data : invite.createPostData() }; var url = this.constructUrl(consts.AtomConnectionsDo, {}, {authType : this._getProfileAuthString()}); return this.updateEntity(url, options, callbacks, args); }, /** * Update profile tags. When you update profile tags, the existing tag information added by you is replaced with the new tag information. * To avoid this, retrieve the tags that you want to retain first, and send them back with this request. * * @method updateTags * @param {Array} tags * @param {String} targetEmailOrUserId email address or userid of the person whose profile you want to apply the tags to * @param {String} sourceEmailOrUserId email address or useridof the creator of the tags * @param args */ updateTags : function(tags, targetEmailOrUserId, sourceEmailOrUserId, args) { // detect a bad request by validating required arguments var promise = this._validateProfileId(targetEmailOrUserId); if (promise) { return promise; } promise = this._validateProfileId(sourceEmailOrUserId); if (promise) { return promise; } var requestArgs = {}; if (this.isEmail(targetEmailOrUserId)) { requestArgs.targetEmail = targetEmailOrUserId; } else { requestArgs.targetKey = targetEmailOrUserId; } if (this.isEmail(sourceEmailOrUserId)) { requestArgs.sourceEmail = sourceEmailOrUserId; } else { requestArgs.sourceKey = sourceEmailOrUserId; } lang.mixin(requestArgs, args || {}); var callbacks = { createEntity : function(service, data, response) { return data; // Since this API does not return any response in case of success, returning empty data } }; var options = { method : "PUT", query : requestArgs, headers : consts.AtomXmlHeaders, data : this._createTagsPostData(tags) }; var url = this.constructUrl(consts.AtomTagsDo, {}, {authType : this._getProfileAuthString()}); return this.updateEntity(url, options, callbacks, args); }, // // Internals // /* * Return callbacks for a profile feed */ getProfileFeedCallbacks : function() { return ProfileFeedCallbacks; }, /* * Return callbacks for a ColleagueConnection feed */ getColleagueConnectionFeedCallbacks : function() { return ColleagueConnectionFeedCallbacks; }, /* * Return callbacks for a profile entry */ getProfileCallbacks : function() { return ProfileCallbacks; }, /* * Return callbacks for a profile tag feed */ getProfileTagFeedCallbacks : function() { return ProfileTagFeedCallbacks; }, /* * Convert profile or key to id object */ _toIdObject : function(profileOrId) { var idObject = {}; if (lang.isString(profileOrId)) { var userIdOrEmail = profileOrId; if (this.isEmail(userIdOrEmail)) { idObject.email = userIdOrEmail; } else { idObject.userid = userIdOrEmail; } } else if (profileOrId instanceof Profile) { if (profileOrId.getUserid()) { idObject.userid = profileOrId.getUserid(); } else if (profileOrId.getEmail()) { idObject.email = profileOrId.getEmail(); } } return idObject; }, /* * Convert profile or key to target object */ _toTargetObject : function(profileOrId) { var targetObject = {}; if (lang.isString(profileOrId)) { var userIdOrEmail = profileOrId; if (this.isEmail(userIdOrEmail)) { targetObject.targetEmail = userIdOrEmail; } else { targetObject.targetKey = userIdOrEmail; } } else if (profileOrId instanceof Profile) { if (profileOrId.getUserid()) { targetObject.targetKey = profileOrId.getUserid(); } else if (profileOrId.getEmail()) { targetObject.targetEmail = profileOrId.getEmail(); } } return targetObject; }, /* * Validate an ID object */ _validateIdObject : function(idObject) { if (!idObject.userid && !idObject.email) { return this.createBadRequestPromise("Invalid argument, userid or email must be specified."); } }, /* * Validate an Target object */ _validateTargetObject : function(idObject) { if (!idObject.targetKey && !idObject.targetEmail) { return this.createBadRequestPromise("Invalid argument, userid or email must be specified."); } }, /* * Return a Profile instance from Profile or JSON or String. Throws * an error if the argument was neither. */ _toProfile : function(profileOrJsonOrString,args) { if (profileOrJsonOrString instanceof Profile) { return profileOrJsonOrString; } else { var profileJson = profileOrJsonOrString; if (lang.isString(profileOrJsonOrString)) { profileJson = {}; if(this.isEmail(profileOrJsonOrString)){ profileJson.email = profileOrJsonOrString; }else{ profileJson.userid = profileOrJsonOrString; } }else{ // handle the case when the profileJson has id attribute. id can take either userid or email. if(profileJson && profileJson.id && !profileJson.userid && !profileJson.email){ this.isEmail(profileJson.id) ? profileJson.email = profileJson.id : profileJson.userid = profileJson.id; delete profileJson.id; } } return new Profile({ service : this, _fields : lang.mixin({}, profileJson) }); } }, /* * Return a Invite instance from Invite or JSON or String. Throws * an error if the argument was neither. */ _toInvite : function(inviteOrJsonOrString,args) { if (inviteOrJsonOrString instanceof Invite) { return inviteOrJsonOrString; } else { if (lang.isString(inviteOrJsonOrString)) { inviteOrJsonOrString = { content : inviteOrJsonOrString }; } return new Invite({ service : this, _fields : lang.mixin({}, inviteOrJsonOrString) }); } }, /* * Returns true if an address field has been set. */ _isAddressSet : function(profile){ return (profile._fields["streetAddress"] || profile._fields["extendedAddress"] || profile._fields["locality"] || profile._fields["region"] || profile._fields["postalCode"] || profile._fields["countryName"]); }, /* * Validate a Profile object */ _validateProfile : function(profile) { if (!profile || (!profile.getUserid() && !profile.getEmail())) { return this.createBadRequestPromise("Invalid argument, profile with valid userid or email must be specified."); } }, /* * Validate a Profile id */ _validateProfileId : function(profileId) { if (!profileId || profileId.length == 0) { return this.createBadRequestPromise("Invalid argument, expected userid or email"); } }, _getProfileAuthString : function(){ if (this.endpoint.authType == consts.AuthTypes.Basic) { return basicAuthString; } else if (this.endpoint.authType == consts.AuthTypes.OAuth) { return OAuthString; } else { return defaultAuthString; } }, _createTagsPostData : function(tags) { var value = ""; for (var i=0; i< tags.length;i++) { value += stringUtil.transform(CategoryTmpl, { "tag" : tags[i] }); } var postData = stringUtil.transform(createProfileTagsTemplate, {"createTags" : value}); return stringUtil.trim(postData); } }); return ProfileService; }); }, 'sbt/Cache':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * The cache implements the Least Recently Used (LRU)Algorithm by doubly linked list. Every node has 4 variables - key, value, next and previous. * The key stores the key of the node and value stores the actual data for the key. The next and previous variables point to the * next and previous nodes in the cache. * The cache has a head variable pointing to the top cache node and a tail variable pointing to the last cache node. * * Head -> A ---> B ---> C ---> D <-- Tail * <--- <--- <--- * * Suppose the cache has 4 entries and its max size limit is 4 (the cache is full right now). The structure of the cache would be as described by figure above. * The entries are listed as per their order of recent access. * So when a new entry E is added to the cache, the new order of the cache entries would be EABC. D would be deleted from the cache. * * @module sbt.Cache */ define(['./declare'],function(declare) { var Cache = declare(null, { constructor: function(max) { this.limit = max;// This is the maximum limit of the cache. this._cache = {};//Variable to hold the items in the cache. this.head = null;// Pointer to the head of the cache this.tail = null;// Pointer to the tail of the cache this.count = 0;// Counter for number of items in the cache }, get: function _cg(key) { //Retrieves a cached item. var k = this._cache[key]; if(k){//Item found in the cache. Move the accessed node to the top of the cache. if(this.head == k){return k.value;} // the node is already at the top, no need to shift, just return the value. else{// shift the node to the top and return the value if(k.prev)k.prev.next = k.next; if(k.next){k.next.prev = k.prev;} else {this.tail=k.prev;} k.next = this.head; this.head.prev = k; k.prev = null; this.head = k; } return k.value; } return null; // the node is not in the cache }, put: function _cp(key,value) {// puts a node in the cache if the node is not present in the cache. The node is put at the top of the cache. if(this._cache[key])//remove the asked node {this.remove(key); this.count --;} var k = this._cache[key] ={key:key, value:value}; if(this.count==this.limit) //if the cache is full, remove the last node {this.remove(this.tail.key);this.count --;} //add the asked node to the top of the list. k.next = this.head; if(k.next)k.next.prev = k;else this.tail = k; this.head = k; k.prev = null; this.count ++; }, remove: function _cr(key) {//removes a node from the cache and updates the next and prev attributes of the surrounding nodes. var k = this._cache[key]; if(k){ if(k.next)k.next.prev = k.prev;else this.tail = k.prev; if(k.prev)k.prev.next = k.next; else this.head = k.next; k.next = k.prev = null; delete this._cache[key]; this.count -- ; } }, /** * Function that browse the content of the cache and call a call back method for each entry. * * @param callback the callback method to invoke for each entry */ browse: function(callback) { if(callback) { for(var i in this._cache) { var e = this._cache[i]; var r = callback(e.key,e.value); if(r) { return r; } } return null; } return null; } }); return Cache; }); }, 'sbt/GadgetTransport':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Implements a transport for when the SDK is used from a gadget. * @module */ define(['./declare','./lang'],function(declare,lang) { var MethodTypes = { 'POST': gadgets.io.MethodType.POST, 'PUT': gadgets.io.MethodType.PUT, 'DELETE': gadgets.io.MethodType.DELETE, 'GET': gadgets.io.MethodType.GET }; var ContentTypes = { 'XML': gadgets.io.ContentType.DOM, 'JSON': gadgets.io.ContentType.JSON, 'TEXT': gadgets.io.ContentType.TEXT, 'JSON-COMMENT-OPTIONAL': gadgets.io.ContentType.JSON, 'JSON-COMMENT-FILTERED': gadgets.io.ContentType.JSON, 'JAVASCRIPT': gadgets.io.ContentType.JSON }; var AuthorizationTypes = { 'NONE': gadgets.io.AuthorizationType.NONE, 'OAUTH': gadgets.io.AuthorizationType.OAUTH, 'OAUTH2': gadgets.io.AuthorizationType.OAUTH2, 'SIGNED': gadgets.io.AuthorizationType.SIGNED }; return declare(null, { serviceName: null, constructor: function(args) { this.serviceName = args.serviceName || null; }, /** * Performs an XHR request using the gadget APIs. * Warning this is not a final module. Not everything is supported as of yet. * @param {String} method The HTTP method to use. * @param {Object} args The arguments for the XHR request. * @param {boolean} hasBody Indicates whether there is a request body. */ xhr: function(method,args,hasBody) { //TODO OAuth support if(args.sync) { throw new Error('Gadget transport does not support synchronous requests.'); } var params = {}; params[gadgets.io.RequestParameters.METHOD] = MethodTypes[method.toUpperCase()] || gadgets.io.MethodType.GET; params[gadgets.io.RequestParameters.CONTENT_TYPE] = ContentTypes[args.handleAs ? args.handleAs.toUpperCase() : 'TEXT']; params[gadgets.io.RequestParameters.HEADERS] = args.headers || {}; params[gadgets.io.RequestParameters.POST_DATA] = this.getPostData(params[gadgets.io.RequestParameters.METHOD], args.postData || args.putData); if(args.preventCache) { params[gadgets.io.RequestParameters.REFRESH_INTERVAL] = 0; } if(this.serviceName || args.serviceName) { params[gadgets.io.RequestParameters.OAUTH_SERVICE_NAME] = this.serviceName || args.serviceName; } if(args.authType) { var authorization = args.authType.toUpperCase(); params[gadgets.io.RequestParameters.AUTHORIZATION] = AuthorizationTypes[authorization] || AuthorizationTypes['NONE']; } var self = this; var callback = function(response) { self.handleResponse(args, response); }; var url = this.buildUrl(args); gadgets.io.makeRequest(url, callback, params); }, handleResponse: function(args, response) { if(response.errors && response.errors.length > 0) { if (args.error || args.handle) { var error = this.createError(response); this.notifyError(args, error); } } else { if (response.oauthApprovalUrl) { this.handleApproval(args, response); } else { this.notifyResponse(args, response); } } }, handleApproval: function(args, response) { var error = new Error(); error.code = 401; error.response = lang.mixin({}, response); this.notifyError(args, error); }, notifyResponse: function(args, response) { if (args.load || args.handle) { var ioArgs = { 'args' : args, 'headers' : response.headers, '_ioargs' : response }; if (args.handle) { args.handle(response.data || response.text, ioArgs); } if (args.load) { args.load(response.data || response.text, ioArgs); } } }, notifyError: function(args, error) { if (args.handle) { args.handle(error); } if (args.error) { args.error(error); } }, createError: function(response) { var error = new Error(); error.code = response.rc; error.message = response.errors[0]; error.response = lang.mixin({}, response); return error; }, getPostData: function(method, postData) { if (method == gadgets.io.MethodType.POST || method == gadgets.io.MethodType.PUT) { return postData; } return ''; }, buildUrl: function(args) { var params = []; var url = args.url; if (args.content) { for (name in args.content) { var param = encodeURIComponent(name) + "=" + encodeURIComponent(args.content[name]); params.push(param); } if (params.length > 0) { var query = params.join("&"); url += (~url.indexOf('?') ? '&' : '?') + query; } } return url; } }); }); }, 'sbt/connections/BlogPost':function(){ /* * © Copyright IBM Corp. 2012, 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * * @module sbt.connections.BlogPost * @author Rajmeet Bal */ define(["../declare", "../lang", "../base/AtomEntity", "./BlogConstants", "../base/XmlDataHandler" ], function(declare, lang, AtomEntity, consts, XmlDataHandler) { /** * BlogPost class represents a post for a Blogs feed returned by the * Connections REST API. * * @class BlogPost * @namespace sbt.connections */ var BlogPost = declare(AtomEntity, { xpath : consts.BlogPostXPath, namespaces : consts.BlogPostNamespaces, /** * Construct a Blog Post. * * @constructor * @param args */ constructor : function(args) { }, /** * Return the value of IBM Connections blog post ID * entry document. * * @deprecated Use getPostUuid instead. * @method getBlogPostUuid * @return {String} ID of the blog post */ getBlogPostUuid : function() { var postUuidPrefix = "urn:lsid:ibm.com:blogs:entry-"; var postUuid = this.getAsString("postUuid"); if(postUuid && postUuid.indexOf(postUuidPrefix) != -1){ postUuid = postUuid.substring(postUuidPrefix.length, postUuid.length); } return postUuid; }, /** * Sets id of IBM Connections blog post Id. * * @deprecated Use setPostUuid instead * @method setBlogPostUuid * @param {String} BlogPostUuid of the blog post */ setBlogPostUuid : function(postUuid) { return this.setAsString("postUuid", postUuid); }, /** * Return the value of IBM Connections blog post ID. * * @method getPostUuid * @return {String} Unique id of the blog post */ getPostUuid : function() { var postUuidPrefix = "urn:lsid:ibm.com:blogs:entry-"; var postUuid = this.getAsString("postUuid"); if(postUuid && postUuid.indexOf(postUuidPrefix) != -1){ postUuid = postUuid.substring(postUuidPrefix.length, postUuid.length); } return postUuid; }, /** * Sets id of IBM Connections blog post Id. * * @method setPostUuid * @param {String} Unique id of the blog post */ setPostUuid : function(postUuid) { return this.setAsString("postUuid", postUuid); }, /** * Return the entry anchor for this blog post. * * @method getEntryAnchor * @return {String} Entry anchor for this blog post */ getEntryAnchor : function() { var entry = this.dataHandler.getData(); if (entry) { var base = entry.getAttribute("xml:base"); if (base) { var n = base.lastIndexOf("/"); return base.substring(n+1); } } }, /** * Return the bloghandle of the blog post. * * @method getBlogHandle * @return {String} Blog handle of the blog post */ getBlogHandle : function() { var blogHandle = this.getAsString("blogHandle"); if(blogHandle){ return blogHandle; } var blogEntryUrlAlternate = this.getAsString("alternateUrl"); blogHandle = this.service._extractBlogHandle(blogEntryUrlAlternate); return blogHandle; }, /** * Sets blog handle of IBM Connections blog post. * * @method setBlogHandle * @param {String} blogHandle of the blog post's blog */ setBlogHandle : function(blogHandle) { return this.setAsString("blogHandle", blogHandle); }, /** * Return the value of IBM Connections blog post replies URL from blog ATOM * entry document. * * @method getRepliesUrl * @return {String} Blog replies URL for the blog post */ getRepliesUrl : function() { return this.getAsString("replies"); }, /** * Return tags of IBM Connections blog post * document. * * @method getTags * @return {Object} Array of tags of the blog post */ getTags : function() { return this.getAsArray("tags"); }, /** * Set new tags to be associated with this IBM Connections blog post. * * @method setTags * @param {Object} Array of tags to be added to the blog post */ setTags : function(tags) { return this.setAsArray("tags", tags); }, /** * Return the replies url of the ATOM entry document. * * @method getRepliesUrl * @return {String} Replies url */ getRepliesUrl : function() { return this.getAsString("repliesUrl"); }, /** * Return the last updated dateRecommendations URL of the IBM Connections blog post from * blog ATOM entry document. * * @method getRecommendationsURL * @return {String} Recommendations URL of the Blog Post */ getRecommendationsURL : function() { return this.getAsString("recommendationsUrl"); }, /** * Return the Recommendations count of the IBM Connections blog post from * blog ATOM entry document. * * @method getRecommendationsCount * @return {String} Last updated date of the Blog post */ getRecommendationsCount : function() { return this.getAsNumber("rankRecommendations"); }, /** * Return the comment count of the IBM Connections blog post from * blog ATOM entry document. * * @method getCommentCount * @return {String} Last updated date of the Blog post */ getCommentCount : function() { return this.getAsNumber("rankComment"); }, /** * Return the hit count of the IBM Connections blog post from * blog ATOM entry document. * * @method getHitCount * @return {String} Last updated date of the Blog post */ getHitCount : function() { return this.getAsNumber("rankHit"); }, /** * Gets an source of IBM Connections Blog post. * * @method getSource * @return {Object} Source of the blog post */ getSource : function() { return this.getAsObject([ "sourceId", "sourceTitle", "sourceLink", "sourceLinkAlternate", "sourceUpdated", "sourceCategory" ]); }, /** * Loads the blog post object with the atom entry associated with the * blog post. By default, a network call is made to load the atom entry * document in the blog post object. * * @method load * @param {Object} [args] Argument object */ load : function(args) { // detect a bad request by validating required arguments var blogPostUuid = this.getBlogPostUuid(); var promise = this.service._validateBlogUuid(blogPostUuid); if (promise) { return promise; } var self = this; var callbacks = { createEntity : function(service,data,response) { self.setDataHandler(new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.BlogPostXPath })); return self; } }; var requestArgs = lang.mixin({}, args || {}); var options = { handleAs : "text", query : requestArgs }; var url = null; url = this.service.constructUrl(consts.AtomBlogPostInstance, null, { blogHomepageHandle : this.service.handle, postUuid : blogPostUuid }); return this.service.getEntity(url, options, blogPostUuid, callbacks); }, /** * Remove this blog post * * @method remove * @param {Object} [args] Argument object */ remove : function(args) { return this.service.deletePost(this.getBlogPostUuid(), args); }, /** * Update this blog post * * @method update * @param {Object} [args] Argument object */ update : function(args) { return this.service.updatePost(this, args); }, /** * Save this blog post * * @method save * @param {Object} [args] Argument object */ save : function(args) { if (this.getBlogPostUuid()) { return this.service.updatePost(this, args); } else { return this.service.createPost(this, args); } }, /** * Return comments associated with this blog post. * * @method getComments * @param {Object} [args] Argument object */ getComments : function(args) { var blogHandle = this.getBlogHandle(); var entryAnchor = this.getEntryAnchor(); return this.service.getEntryComments(blogHandle, entryAnchor, args); } }); return BlogPost; }); }, 'sbt/connections/ActivityService':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * The Activities application of IBM© Connections enables a team to collect, organize, share, and reuse work related to a project goal. The Activities API * allows application programs to create new activities, and to read and modify existing activities. * * @module sbt.connections.ActivityService */ define( [ "../declare", "../config", "../lang", "../stringUtil", "../Promise", "./ActivityConstants", "./ConnectionsService", "../base/AtomEntity", "../base/BaseEntity", "../base/XmlDataHandler", "../xml" ], function(declare, config, lang, stringUtil, Promise, consts, ConnectionsService, AtomEntity, BaseEntity, XmlDataHandler, xml) { var ActivityCategory = "<category scheme=\"http://www.ibm.com/xmlns/prod/sn/type\" term=\"${getType}\" label=\"${getType}\" />"; var PositionTmpl = "<snx:position>${getPosition}</snx:position>"; var CommunityTmpl = "<category scheme=\"http://www.ibm.com/xmlns/prod/sn/type\" term=\"community_activity\" label=\"Community Activity\"/><snx:communityUuid>${getCommunityUuid}</communityUuid>" + "<link rel=\"http://www.ibm.com/xmlns/prod/sn/container\" type=\"application/atom+xml\" href=\"${getCommunityUrl}\"/>"; var CompletedTmpl = "<category scheme=\"http://www.ibm.com/xmlns/prod/sn/flags\" term=\"completed\" label=\"Completed\"/>"; var TemplateTmpl = "<category scheme=\"http://www.ibm.com/xmlns/prod/sn/flags\" term=\"template\"/>"; var DueDateTmpl = "<snx:duedate>${getDueDate}</duedate>"; var InReplytoTmpl = "<thr:in-reply-to ref=\"${getInReplyToId}\" type=\"application/atom+xml\" href=\"${getInReplyToUrl}\" source=\"${getActivityUuid}\" />"; var FieldTmpl = "<snx:field name=\"${name}\" fid=\"${fid}\" position=\"${position}\" type=\"${type}\">${getText}${getPerson}${getDate}${getLink}${getFile}</snx:field>"; var TextFieldTmpl = "<summary type=\"text\">${summary}</summary>"; var PersonFieldTmpl = "<name>${personName}</name> <email>{email}</email> <snx:userid>${userId}</snx:userid>"; var LinkFieldTmpl = "<link href=\"${url\}\" title=\"${title}\" />"; var DateFieldTmpl = "${date}"; var IconTmpl = "<snx:icon>${getIconUrl}</snx:icon>"; var AssignedToTmpl = "<snx:assignedto name=\"${getAssignedToName}\" userid=\"${getAssignedToUserId}\">${getAssignedToEmail}</snx:assignedto>"; var RoleTmpl = "<snx:role xmlns:snx=\"http://www.ibm.com/xmlns/prod/sn\" component=\"http://www.ibm.com/xmlns/prod/sn/activities\">${getRole}</snx:role>"; var MemberCategory = "<category scheme=\"http://www.ibm.com/xmlns/prod/sn/type\" term=\"${getCategory}\" label=\"${getCategory}\" />"; var ActivityIdTmpl = "<snx:activity>${getActivityUuid}</snx:activity>"; var ActivityNodeIdTmpl = "<id>urn:lsid:ibm.com:oa:${getActivityNodeUuid}</id>"; var extractId = function(id, token) { //decode uri component returns "null" for null input if(id) id = decodeURIComponent(id); // to make sure the Id doesnt contain encoded characters if (id) { var index = id.indexOf(token); if (index != -1) { var len = token.length; id = id.substring(index + len); } } return id; }; var transformer = function(value, key) { if (value) { return value; } }; /** * Field class represents a Field in an Activity Node. * * @class Field * @namespace sbt.connections */ var Field = declare(null, { name : null, fid : null, position : null, type : null, /** * Returns Field Name * @method getName * @returns {String} field name */ getName : function() { return this.name; }, /** * Sets Field Name * @method setName * @param {String} field name */ setName : function(newName) { this.name = newName; }, /** * Returns Field ID * @method getFid * @returns {String} field ID */ getFid : function() { return this.fid; }, /** * Returns Field Position * @method getPosition * @returns {String} field position */ getPosition : function() { return this.position; }, /** * Returns Field Type * @method getType * @returns {String} field type */ getType : function() { return this.type; } }); /** * TextField class represents a Text Field in an Activity Node. * * @class TextField * @namespace sbt.connections */ var TextField = declare(Field, { summary : null, /** * Returns Field Summary * @method getSummary * @returns {String} field summary */ getSummary : function() { return this.summary; }, /** * Sets Field Summary * @method setSummary * @param {String} field summary */ setSummary : function(newSumamry) { this.summary = newSummary; } }); /** * DateField class represents a Date Field in an Activity Node. * * @class DateField * @namespace sbt.connections */ var DateField = declare(Field, { date : null, /** * Returns Field Date * @method getDate * @returns {Date} field date */ getDate : function() { return this.date; }, /** * Sets Field Date * @method setDate * @param {Date} field date */ setDate : function(newDate) { this.date = newDate; } }); /** * LinkField class represents a Link Field in an Activity Node. * * @class LinkField * @namespace sbt.connections */ var LinkField = declare(Field, { url : null, title : null, /** * Returns Link Field URL * @method getUrl * @returns {String} field Url */ getUrl : function() { return this.url; }, /** * Sets Link Field URL * @method setUrl * @param {String} field Url */ setUrl : function(newUrl) { this.url = newUrl; }, /** * Returns Link Field Title * @method getTitle * @returns {String} field Title */ getTitle : function() { return this.title; }, /** * Sets Link Field Title * @method setTitle * @param {String} field Title */ setTitle : function(title) { this.title = title; } }); /** * FileField class represents a File Field in an Activity Node. * * @class FileField * @namespace sbt.connections */ var FileField = declare(Field, { url : null, fileType : null, size : null, length : null, /** * Returns File Field URL * @method getUrl * @returns {String} field URL */ getUrl : function() { return this.url; }, /** * Returns File Field File Type * @method getFileType * @returns {String} File Type */ getFileType : function() { return this.type; }, /** * Returns File Field File Size * @method getSize * @returns {String} File Size */ getSize : function() { return this.size; }, /** * Returns File Field File Length * @method getLength * @returns {String} File Length */ getLength : function() { return this.length; } }); /** * PersonField class represents a Person Field in an Activity Node. * * @class PersonField * @namespace sbt.connections */ var PersonField = declare(Field, { personName : null, userId : null, email : null, /** * Returns Person Name * @method getPersonName * @returns {String} Person Name */ getPersonName : function() { return this.personName; }, /** * Sets Person Name * @method setPersonName * @param {String} Person Name */ setPersonName : function(newName) { this.personName = newName; }, /** * Returns Person User ID * @method getUserId * @returns {String} Person User ID */ getUserId : function() { return this.userId; }, /** * Sets Person User ID * @method setUserId * @param {String} Person User ID */ setUserId : function(newUserId) { this.userId = newUserId; }, /** * Returns Person Email * @method getEmail * @returns {String} Person Email */ getEmail : function() { return this.email; }, /** * Sets Person Email * @method setEmail * @param {String} Person Email */ setEmail : function(newEmail) { this.email = newEmail; } }); /** * Tag class represents an entry for a Tag feed returned by the Connections REST API. * * @class Tag * @namespace sbt.connections */ var Tag = declare(BaseEntity, { /** * Construct a Tag entity. * * @constructor * @param args */ constructor : function(args) { }, /** * Returns tag term * @method getTerm * @returns {String} tag term */ getTerm : function() { return this.getAsString("term"); }, /** * Returns tag frequency * @method getFrequency * @returns {String} tag frequency */ getFrequency : function() { return this.getAsString("frequency"); }, /** * Returns tag bin * @method getBin * @returns {String} tag bin */ getBin : function() { return this.getAsString("bin"); } }); /** * Activity class represents an entry for a activities feed returned by the Connections REST API. * * @class Activity * @namespace sbt.connections */ var Activity = declare(AtomEntity, { xpath : consts.ActivityNodeXPath, namespaces : consts.ActivityNamespaces, contentType : "html", categoryScheme : null, /** * Construct an Activity entity. * * @constructor * @param args */ constructor : function(args) { }, /** * Sets template for category Scheme */ setCategoryScheme : function() { this.categoryScheme = stringUtil.transform(ActivityCategory, this, transformer, this); }, /** * Returns the ID * @method getUuid * @returns {String} Uuid */ getUuid : function() { var _id = this.id || this._fields.id || this.getId(); this.id = _id; this._fields.id = _id; return _id; }, /** * Return the value of id from result ATOM entry document. * * @method getActivityUuid * @return {String} ID of the activity */ getActivityUuid : function() { return extractId(this.getUuid(), "urn:lsid:ibm.com:oa:"); }, /** * Returns the Author LdapId * * @method getAuthorLdapId * @returns {Stirng} authorLdapId */ getAuthorLdapId : function() { return this.getAsString("authorLdapid"); }, /** * Returns the contributor LdapId * * @method getContributorLdapId * @returns {Object} contributor */ getContributorLdapId : function() { return this.getAsString("contributorLdapid"); }, /** * Returns Activity Node Type * * @method getType * @returns {String} type */ getType : function() { return this.getAsString("type"); }, /** * Sets Activity Node Type * @method setType * @param {String} type */ setType : function(type) { return this.setAsString("type", type); }, /** * Returns Activity Node Priority * * @method getPriority * @returns {String} priority */ getPriority : function() { return this.getAsString("priority"); }, /** * Return tags of IBM Connections activity from activity ATOM entry document. * * @method getTags * @return {Object} Array of tags of the activity */ getTags : function() { return this.getAsArray("tags"); }, /** * Set new tags to be associated with this IBM Connections activity. * * @method setTags * @param {Object} Array of tags to be added to the activity */ setTags : function(tags) { return this.setAsArray("tags", tags); }, /** * Returns the dueDate Date * * @method getDueDate * @returns {Date} DueDate */ getDueDate : function() { return this.getAsDate("dueDate"); }, /** * Sets the Due Date of Activity * @method setDueDate * @param {Date} dueDate */ setDueDate : function(dueDate) { return this.setAsDate("dueDate", dueDate); }, /** * Returns Activity Node Members Url * * @method getMembersUrl * @returns {String} membersUrl */ getMembersUrl : function() { return this.getAsString("membersUrl"); }, /** * Returns Activity Node History Url * * @method getHistoryUrl * @returns {String} historyUrl */ getHistoryUrl : function() { return this.getAsString("historyUrl"); }, /** * Returns Activity Node Templates Url * * @method getTemplatesUrl * @returns {String} templatesUrl */ getTemplatesUrl : function() { return this.getAsString("templatesUrl"); }, /** * Returns Activity Position * * @method getPosition * @returns {String} position */ getPosition : function() { return this.getAsString("position"); }, /** * Sets Activity Position * @method setPosition * @param position */ setPosition : function(position) { return this.setAsString("position", position); }, /** * Returns Completed Flag for Activity * @method isCompleted * @returns {Boolean} completed flag */ isCompleted : function() { return this.getAsBoolean("categoryFlagCompleted"); }, /** * Set Completed Flag * @param {Boolean} completed * @returns */ setCompleted : function(completed) { return this.setAsBoolean("categoryFlagCompleted", completed); }, /** * Get Delete Flag * * @returns {Boolean} isDelete */ isDeleted : function() { return this.getAsBoolean("categoryFlagDelete"); }, /** * Gets Teplate Flag * * @returns {Boolean} template */ isTemplate : function() { return this.getAsBoolean("categoryFlagTemplate"); }, /** * Sets Template Flag * * @param {Boolean} templateFlag */ setTemplate : function(templateFlag) { return this.setAsBoolean("categoryFlagTemplate", templateFlag); }, /** * Returns Activity Node Depth * * @method getDepth * @returns {String} depth */ getDepth : function() { return this.getAsString("depth"); }, /** * Returns Activity Node Permissions * * @method getPermissions * @returns {String} permissions */ getPermissions : function() { return this.getAsString("permissions"); }, /** * Returns Activity Node IconUrl * * @method getIconUrl * @returns {String} iconUrl */ getIconUrl : function() { return this.getAsString("iconUrl"); }, /** * setIconUrl * @param iconUrl */ setIconUrl : function(iconUrl) { return this.setAsString("iconUrl", iconUrl); }, /** * getCommunityUuid * @method getCommunityUuid * @returns {String} communityUuid */ getCommunityUuid : function() { return this.getAsString("communityUuid"); }, /** * setCommunityUuid * @method setCommunityUuid * @param communityUuid */ setCommunityUuid : function(communityUuid) { return this.setAsString("communityUuid", communityUuid); }, /** * getCommunityUrl * @method getCommunityUrl * @returns {String} communityUrl */ getCommunityUrl : function() { return this.getAsString("communityUrl"); }, /** * setCommunityUrl * @method setCommunityUrl * @param communityUrl */ setCommunityUrl : function(communityUrl) { return this.setAsString("communityUrl", communityUrl); }, /** * Loads the Activity object with the atom entry associated with the activity. By default, a network call is made to load the atom entry * document in the activity object. * * @method load */ load : function() { var promise = this.service.validateField("activityUuid", this.getActivityUuid()); if (promise) { return promise; } var requestArgs = { "activityNodeUuid" : this.getActivityUuid() }; var options = { method : "GET", handleAs : "text", query : requestArgs }; var self = this; var callbacks = { createEntity : function(service, data, response) { self.setData(data, response); return self; } }; return this.service.getEntity(consts.AtomActivityNode, options, this.getActivityUuid(), callbacks); }, /** * Creates an activity, sends an Atom entry document containing the new activity to the user's My Activities feed. * * @method create * @returns {Object} Activity */ create : function() { return this.service.createActivity(this); }, /** * updates an activity, send a replacement Atom Entry document containing the modified activity to the existing activity's edit URL * @method update * @returns {Object} activity */ update : function() { return this.service.updateActivity(this); }, /** * Deletes an activity entry, sends an HTTP DELETE method to the edit web address specified for the node. * * @method deleteActivity */ deleteActivity : function() { return this.service.deleteActivity(this.getActivityUuid()); }, /** * Restores a deleted activity, use a HTTP PUT request. This moves the activity from the trash feed to the user's My Activities feed. * * @method restore */ restore : function() { return this.service.restoreActivity(this.getActivityUuid()); }, /** * Adds a member to the access control list of an activity, sends an Atom entry document containing the new member to the access control list * feed. You can only add one member per post. * @method addMember * @param {Object} memberOrJson */ addMember : function(memberOrJson) { return this.service.addMember(this.getActivityUuid(), memberOrJson); }, /** * Removes a member from the acl list for an application, use the HTTP DELETE method. * @method removeMember * @param {String} memberId */ removeMember : function(memberId) { return this.service.deleteMember(this.getActivityUuid(), memberId); }, /** * Updates a member in the access control list for an application, sends a replacement member entry document in Atom format to the existing ACL * node's edit web address. * @method updateMember * @param {Object} memberOrJson */ updateMember : function(memberOrJson) { return this.service.updateMember(this.getActivityUuid(), memberOrJson); }, /** * Retrieves a member from the access control list for a application, use the edit link found in the member entry in the ACL list feed. * @method getMember * @param {String} memberId * @returns {Object} Member */ getMember : function(memberId) { return this.service.getMember(this.getActivityUuid(), memberId); }, /** * Retrieves activity members from the access control list for a application, use the edit link found in the member entry in the ACL list feed. * @method getMembers * @param {Object} [requestArgs] the optional arguments * @returns {Array} members */ getMembers : function(requestArgs) { return this.service.getMembers(this.getActivityUuid(), requestArgs); }, /** * Creats an entry in an activity, such as a to-do item or to add a reply to another entry, send an Atom entry document containing the new * activity node of the appropriate type to the parent activity's node list. * * @mehtod createActivityNode * @param {Object} activityNodeOrJson * @returns {Object} ActivityNode */ createActivityNode : function(activityNodeOrJson) { return this.service.createActivityNode(this.getActivityUuid(), activityNodeOrJson); }, /** * Returns the tags for given actiivity * @method getActivityTags * @param {Object} [requestArgs] the optional arguments * @returns {Array} tags */ getActivityTags : function(requestArgs) { return this.service.getActivityTags(this.getActivityUuid(), requestArgs); }, /** * Return contributor element to be included in post data for this ATOM entry. * * @method createContributor * @returns {String} */ createContributor : function() { return ""; }, /** * Return extra entry data to be included in post data for this ATOM entry. * * @method createEntryData * @returns {String} */ createEntryData : function() { var postData = ""; if (this.getPosition && this.getPosition()) { postData += stringUtil.transform(PositionTmpl, this, transformer, this); } if (this.getCommunityUuid && this.getCommunityUuid()) { postData += stringUtil.transform(CommunityTmpl, this, transformer, this); } if (this.getActivityUuid && this.getActivityUuid()) { postData += stringUtil.transform(ActivityIdTmpl, this, transformer, this); } if (this.getActivityNodeUuid && this.getActivityNodeUuid()) { postData += stringUtil.transform(ActivityNodeIdTmpl, this, transformer, this); } if (this.isCompleted && this.isCompleted()) { postData += CompletedTmpl; } if (this.getDueDate && this.getDueDate()) { postData += stringUtil.transform(DueDateTmpl, this, transformer, this); } if (this.getInReplyToId && this.getInReplyToId()) { postData += stringUtil.transform(InReplytoTmpl, this, transformer, this); } if (this.getAssignedToUserId && this.getAssignedToUserId()) { postData += stringUtil.transform(AssignedToTmpl, this, transformer, this); } if (this.getIconUrl && this.getIconUrl()) { postData += stringUtil.transform(IconTmpl, this, transformer, this); } if (this.isTemplate && this.isTemplate()) { postData += TemplateTmpl; } if (this.getFields && this.getFields().length > 0) { var fields = this.getFields(); for ( var counter in fields) { var field = fields[counter]; var innerXml = ""; var trans = function(value, key) { if (field[key]) { value = xml.encodeXmlEntry(field[key]); } else if (innerXml != "") { value = innerXml; } return value; }; var tmpl = TextFieldTmpl; if (field.type == "person") { tmpl = PersonFieldTmpl; } else if (field.type == "link") { tmpl = LinkFieldTmpl; } else if (field.type == "date") { tmpl = DateFieldTmpl; } innerXml = stringUtil.transform(tmpl, this, trans, this); postData += stringUtil.transform(FieldTmpl, this, trans, this); } } return postData; } }); /** * Activity Node class represents an entry for a activities Node feed returned by the Connections REST API. * * @class ActivityNode * @namespace sbt.connections */ var ActivityNode = declare(Activity, { /** * Construct a Result entity. * * @constructor * @param args */ constructor : function(args) { }, /** * Return the value of id from result ATOM entry document. * * @method getActivityNodeUuid * @return {String} ID of the result */ getActivityNodeUuid : function() { return extractId(this.getUuid(), "urn:lsid:ibm.com:oa:"); }, /** * Return the value of activity uuid from result ATOM entry document. * * @method getActivityUuid * @return {String} cctivityUuid of the result */ getActivityUuid : function() { return this.getAsString("activityUuid"); }, /** * * @param activityUuid * @returns */ setActivityUuid : function(activityUuid) { return this.setAsString("activityUuid", activityUuid); }, /** * getInReplyToId * @returns {String} getInReplyToId */ getInReplyToId : function() { return this.getAsString("inReplyToId"); }, /** * getInReplyToUrl * @returns {String} getInReplyToUrl */ getInReplyToUrl : function() { return this.getAsString("inReplyToUrl"); }, /** * * @param inReplytoId * @param inReplyToUrl * @param inReplyToActivity */ setInReplyTo : function(inReplyToId, inReplyToUrl) { var id = "urn:lsid:ibm.com:oa:" + inReplyToId; var inReplyTo = { "inReplyToId" : id, "inReplyToUrl" : inReplyToUrl }; return this.setAsObject(inReplyTo); }, /** * getAssignedToUserId * @returns {String} getAssignedToUserId */ getAssignedToUserId : function() { return this.getAsString("assignedToUserId"); }, /** * getAssignedToName * @returns {String} getAssignedToName */ getAssignedToName : function() { return this.getAsString("assignedToName"); }, /** * getAssignedToEmail * @returns {String} getAssignedToEmail */ getAssignedToEmail : function() { return this.getAsString("assignedToEmail"); }, /** * Sets Assigned to in fields for creating playload * @method setAssignedTo * @param {String} assignedToUserId * @param {String} assignedToName * @param {String} assignedToEmail * @returns */ setAssignedTo : function(assignedToUserId, assignedToName, assignedToEmail) { var assignedTo = { "assignedToUserId" : assignedToUserId, "assignedToName" : assignedToName, "assignedToEmail" : assignedToEmail }; return this.setAsObject(assignedTo); }, /** * returns Text Fields in Activity node feed * @returns {Array} textFields */ getTextFields : function() { var nodes = this.getAsNodesArray("textFields"); var textFields = []; for ( var counter in nodes) { var node = nodes[counter]; var textField = new TextField(); for ( var i = 0; i < node.attributes.length; i++) { var attr = node.attributes[i]; var attrName = attr.name; var attrValue = attr.value; textField[attrName] = attrValue; } var dataHandler = new XmlDataHandler({ service : this.service, data : node, namespaces : consts.Namespaces, xpath : consts.TextFieldXPath }); textField.summary = dataHandler.getAsString("summary"); textFields.push(textField); this.addTextField(textField); } return textFields; }, /** * Adds a test field * @param {Object} textField * @returns */ addTextField : function(textField) { if (this._fields["fields"]) { this._fields["fields"].push(textField); return this; } else { return this.setAsArray("fields", [ textField ]); } }, /** * returns Date Fields in Activity node feed * @returns {Array} dateFields */ getDateFields : function() { var nodes = this.getAsNodesArray("dateFields"); var dateFields = []; for ( var counter in nodes) { var node = nodes[counter]; var dateField = new DateField; for ( var i = 0; i < node.attributes.length; i++) { var attr = node.attributes[i]; var attrName = attr.name; var attrValue = attr.value; dateField[attrName] = attrValue; } dateField["date"] = new Date(stringUtil.trim(node.textContent)); dateFields.push(dateField); this.addDateField(dateField); } return dateFields; }, /** * adds a DateField * @param {Object} DateField * @returns */ addDateField : function(dateField) { if (this._fields["fields"]) { this._fields["fields"].push(dateField); return this; } else { return this.setAsArray("fields", [ dateField ]); } }, /** * returns Link Fields in Activity node feed * @returns {Array} linkFields */ getLinkFields : function() { var nodes = this.getAsNodesArray("linkFields"); var linkFields = []; for ( var counter in nodes) { var node = nodes[counter]; var linkField = new LinkField; for ( var i = 0; i < node.attributes.length; i++) { var attr = node.attributes[i]; var attrName = attr.name; var attrValue = attr.value; linkField[attrName] = attrValue; } var dataHandler = new XmlDataHandler({ service : this.service, data : node, namespaces : consts.Namespaces, xpath : consts.LinkFieldXPath }); linkField.url = dataHandler.getAsString("url"); linkField.title = dataHandler.getAsString("title"); linkFields.push(linkField); this.addLinkField(linkField); } return linkFields; }, /** * Adds a LinkField * @param {Object} LinkField * @returns */ addLinkField : function(linkField) { if (this._fields["fields"]) { this._fields["fields"].push(linkField); return this; } else { return this.setAsArray("fields", [ linkField ]); } }, /** * returns Person Fields in Activity node feed * @returns {Array} personFields */ getPersonFields : function() { var nodes = this.getAsNodesArray("personFields"); var personFields = []; for ( var counter in nodes) { var node = nodes[counter]; var personField = new PersonField; for ( var i = 0; i < node.attributes.length; i++) { var attr = node.attributes[i]; var attrName = attr.name; var attrValue = attr.value; personField[attrName] = attrValue; } var dataHandler = new XmlDataHandler({ service : this.service, data : node, namespaces : consts.Namespaces, xpath : consts.PersonFieldXPath }); personField.personName = dataHandler.getAsString("name"); personField.userId = dataHandler.getAsString("userId"); personField.email = dataHandler.getAsString("email"); personFields.push(personField); this.addPersonField(personField); } return personFields; }, /** * adds a person fields to activity node * @param {Object} PersonField * @returns */ addPersonField : function(personField) { if (this._fields["fields"]) { this._fields["fields"].push(personField); return this; } else { return this.setAsArray("fields", [ personField ]); } }, /** * returns File Fields in Activity node feed * @returns {Array} fileFields */ getFileFields : function() { var nodes = this.getAsNodesArray("fileFields"); var fileFields = []; for ( var counter in nodes) { var node = nodes[counter]; var fileField = new FileField; for ( var i = 0; i < node.attributes.length; i++) { var attr = node.attributes[i]; var attrName = attr.name; var attrValue = attr.value; fileField[attrName] = attrValue; } var dataHandler = new XmlDataHandler({ service : this.service, data : node, namespaces : consts.Namespaces, xpath : consts.FileFieldXPath }); fileField.url = dataHandler.getAsString("url"); fileField.size = dataHandler.getAsString("size"); fileField.type = dataHandler.getAsString("type"); fileField.length = dataHandler.getAsString("length"); fileFields.push(fileField); } return fileFields; }, /** * returns all fields in activity nodes feed * @returns {Array} fields */ getFields : function() { if (this._fields.fields && this._fields.fields.length > 0) { return this._fields.fields; } var fields = []; var textFields = this.getTextFields(); var personFields = this.getPersonFields(); var linkFields = this.getLinkFields(); var fileFields = this.getFileFields(); var dateFields = this.getDateFields(); for ( var counter in textFields) { var field = textFields[counter]; feilds.push(field); } for ( var counter in personFields) { var field = personFields[counter]; feilds.push(field); } for ( var counter in linkFields) { var field = linkFields[counter]; feilds.push(field); } for ( var counter in fileFields) { var field = fileFields[counter]; feilds.push(field); } for ( var counter in dateFields) { var field = dateFields[counter]; feilds.push(field); } return fields; }, setFields : function(fields) { this._fields["fields"] = fields; }, /** * Loads the ActivityNode object with the atom entry associated with the activity node. By default, a network call is made to load the atom * entry document in the ActivityNode object. * * @method load */ load : function() { var promise = this.service.validateField("activityNodeUuid", this.getActivityNodeUuid()); if (promise) { return promise; } var requestArgs = { "activityNodeUuid" : this.getActivityNodeUuid() }; var options = { method : "GET", handleAs : "text", query : requestArgs }; var self = this; var callbacks = { createEntity : function(service, data, response) { self.setData(data, response); return self; } }; return this.service.getEntity(consts.AtomActivityNode, options, this.getActivityNodeUuid(), callbacks); }, /** * Creats an entry in an activity, such as a to-do item or to add a reply to another entry, send an Atom entry document containing the new * activity node of the appropriate type to the parent activity's node list. * * @mehtod create * @param {String} activityUuid * @returns {Object} ActivityNode */ create : function(activityUuid) { return this.service.createActivityNode(activityUuid, this); }, /** * updates an activity node entry, sends a replacement Atom entry document containing the modified activity node to the existing activity's edit * web address. * @method update * @returns {Object} activityNode */ update : function() { return this.service.updateActivityNode(this); }, /** * Deletes an activity node entry, sends an HTTP DELETE method to the edit web address specified for the node. * * @method deleteActivityNode */ deleteActivityNode : function() { return this.service.deleteActivityNode(this.getActivityNodeUuid()); }, /** * Restores a deleted entry to an activity, sends a HTTP PUT request to the edit web address for the node defined in the trash feed. This moves * the entry from the trash feed to the user's activity node list. * * @method restoreActivityNode */ restore : function() { return this.service.restoreActivityNode(this.getActivityNodeUuid()); }, /** * Changes certain activity entries from one type to another. * * <pre> * <b>The following types of entries can be changed to other types:</b> * chat * email * entry * reply * todo< * </pre> * * @method changeEntryType * @param {String} newType * @returns {Object} ActivityNode */ changeEntryType : function(newType) { this.setType(newType); return this.service.changeEntryType(this); }, /** * Moves a standard entry or a to-do entry to a section in an activity, send an updated Atom entry document to the parent activity's node list. * * @method moveToSection * @param {String} sectionId * @param {String} [newTitle] * @returns {Object} ActivityNode */ moveToSection : function(sectionId, newTitle) { return this.service.moveEntryToSection(this, sectionId); } }); /** * Member class represents an entry for a members feed returned by the Connections REST API. * * @class Member * @namespace sbt.connections */ var Member = declare(AtomEntity, { xpath : consts.MemberXPath, namespaces : consts.ActivityNamespaces, categoryScheme : null, /** * Sets template for category Scheme */ setCategoryScheme : function() { this.categoryScheme = stringUtil.transform(MemberCategory, this, transformer, this); }, /** * Return the member Id * * @method getMemberId * @return {String} ID of the result */ getMemberId : function() { return extractId(this.getId(), "&memberid="); }, /** * Get role * @method getRole * @returns {String} role */ getRole : function() { return this.getAsString("role"); }, /** * Set role * @method setRole * @param {String} role * @returns */ setRole : function(role) { return this.setAsString("role", role); }, /** * getPermissions * @method getPermissions * @returns {Array} permissions */ getPermissions : function() { var permissions = this.getAsString("permissions"); if (permissions) { return permissions.split(", "); } return permissions; }, /** * getCategory * @method getCategory * @returns {String} category */ getCategory : function() { this.getAsString("category"); }, /** * setCategory * @method setCategory * @param {String} category */ setCategory : function(category) { this.setAsString("category", category); }, /** * get contributor user ID * @method getUserId * @returns {String} userId */ getUserId : function() { return this.getContributor().userid; }, /** * Sets the contributor user ID * @method setUserId * @param {String} userId */ setUserId : function(userId) { return this.setAsString("contributorUserid", userId); }, // Overriding the below methods since they are not relevant for Activity Member Entity in Post Data /** * Return title element to be included in post data for this ATOM entry. * * @method createTitle * @returns {String} */ createTitle : function() { return ""; }, /** * Return content element to be included in post data for this ATOM entry. * * @method createContent * @returns {String} */ createContent : function() { return ""; }, /** * Return summary element to be included in post data for this ATOM entry. * * @method createSummary * @returns {String} */ createSummary : function() { return ""; }, // Overriding the above methods since they are not relevant for Activity Member Entity in Post Data /** * Return extra entry data to be included in post data for this entity. * * @returns {String} */ createEntryData : function() { var postData = ""; postData += stringUtil.transform(RoleTmpl, this, transformer, this); return stringUtil.trim(postData); }, /** * Loads the Member object with the atom entry part with the activity. By default, a network call is made to load the atom entry document in the * Member object. * * @method load * @param {Stirng} activityUuid The Activity ID */ load : function(activityUuid) { var promise = this.service.validateField("memberId", this.getMemberId()); if (!promise) { promise = this.service.validateField("activityUuid", activityUuid); } if (promise) { return promise; } var options = { method : "GET", handleAs : "text" }; var url = this.service.constructUrl(consts.AtomActivitiesMember, null, { "activityUuid" : activityUuid, "memberId" : this.getMemberId() }); var self = this; var callbacks = { createEntity : function(service, data, response) { // This is required because the feed starts from <feed> insttead of <entry> var feedHandler = new XmlDataHandler({ data : data, namespaces : consts.ActivityNamespaces, xpath : consts.MemberXPath }); var entry = feedHandler.data; self.setData(entry, response); return self; } }; return this.service.getEntity(url, options, this.getMemberId(), callbacks); }, /** * Adds a member to the access control list of an activity, sends an Atom entry document containing the new member to the access control list * feed. You can only add one member per post. * @method addToActivity * @param {String} activityUuid */ addToActivity : function(actvitiyUuid) { return this.service.addMember(actvitiyUuid, this); }, /** * Removes a member from the acl list for an application, use the HTTP DELETE method. * @method removeFromActivity * @param {String} activityUuid */ removeFromActivity : function(activityUuid) { return this.service.deleteMember(activityUuid, this.getMemberId()); }, /** * Updates a member in the access control list for an application, sends a replacement member entry document in Atom format to the existing ACL * node's edit web address. * @method updateInActivity * @param {String} activityUuid */ updateInActivity : function(activityUuid) { return this.service.updateMember(activityUuid, this); } }); /* * Callbacks used when reading a feed that contains Tag entries. */ var TagFeedCallbacks = { createEntities : function(service, data, response) { return new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.TagXPath }); }, createEntity : function(service, data, response) { var entryHandler = new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.TagXPath }); return new Tag({ service : service, dataHandler : entryHandler }); } }; /* * Callbacks used when reading a feed that contains activities entries. */ var MemberFeedCallbacks = { createEntities : function(service, data, response) { return new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.ActivitiesFeedXPath }); }, createEntity : function(service, data, response) { var entry = null; if (typeof data == "object") { entry = data; } else { var feedHandler = new XmlDataHandler({ data : data, namespaces : consts.Namespaces, xpath : consts.MemberXPath }); entry = feedHandler.data; } var entryHandler = new XmlDataHandler({ data : entry, namespaces : consts.Namespaces, xpath : consts.MemberXPath }); return new Member({ service : service, dataHandler : entryHandler }); } }; /* * Callbacks used when reading a feed that contains activities entries. */ var ActivityFeedCallbacks = { createEntities : function(service, data, response) { return new XmlDataHandler({ service : service, data : data, namespaces : consts.ActivityNamespaces, xpath : consts.ActivitiesFeedXPath }); }, createEntity : function(service, data, response) { return new Activity({ service : service, data : data }); } }; /* * Callbacks used when reading a feed that contains activities nodes and activity entries. */ var ActivityNodeFeedCallbacks = { createEntities : function(service, data, response) { return new XmlDataHandler({ service : service, data : data, namespaces : consts.ActivityNamespaces, xpath : consts.ActivitiesFeedXPath }); }, createEntity : function(service, data, response) { var entry = null; if (typeof data == "object") { entry = data; } else { var feedHandler = new XmlDataHandler({ data : data, namespaces : consts.ActivityNamespaces, xpath : consts.ActivityNodeXPath }); entry = feedHandler.data; } return new ActivityNode({ service : service, data : entry }); } }; /** * ActivityService class which provides wrapper APIs to the Activities application of IBM© Connections which enables a team to collect, organize, * share, and reuse work related to a project goal. The Activities API allows application programs to create new activities, and to read and modify * existing activities. * * @class ActivityService * @namespace sbt.connections */ var ActivityService = declare(ConnectionsService, { contextRootMap : { activities : "activities" }, serviceName : "activities", /** * Constructor for ActivitiesService * * @constructor * @param args */ constructor : function(args) { if (!this.endpoint) { this.endpoint = config.findEndpoint(this.getDefaultEndpointName()); } }, /** * Get a list of all active activities that match a specific criteria. * * @method getMyActivitiesU * @param {Object} [requestArgs] Optional arguments like ps, page, asc etc. * @returns {Array} Activity array */ getMyActivities : function(requestArgs) { var options = { method : "GET", handleAs : "text", query : requestArgs || {} }; return this.getEntities(consts.AtomActivitiesMy, options, ActivityFeedCallbacks); }, /** * Get a list of all active activity nodes that match a specific criteria in an activity. * * @method getActivityNodes * @param {String} activityUuid The Activity I * @param {Object} [requestArgs] Optional arguments like ps, page, asc etc. * @returns {Array} ActivityNode array */ getActivityNodes : function(activityUuid, requestArgs) { var args = lang.mixin(requestArgs || {}, { "nodeUuid" : activityUuid }); var options = { method : "GET", handleAs : "text", query : args }; return this.getEntities(consts.AtomActivityNodes, options, ActivityNodeFeedCallbacks); }, /** * Search for content in all of the activities, both completed and active, that matches a specific criteria. * * @method getAllActivities * @param requestArgs * @returns {Array} Activity array */ getAllActivities : function(requestArgs) { var options = { method : "GET", handleAs : "text", query : requestArgs || {} }; return this.getEntities(consts.AtomActivitiesEverything, options, ActivityFeedCallbacks); }, /** * Search for a set of completed activities that match a specific criteria. * * @method getCompletedActivities * @param {Object} [requestArgs] The optional arguments * @returns {Array} Activity array */ getCompletedActivities : function(requestArgs) { var options = { method : "GET", handleAs : "text", query : requestArgs || {} }; return this.getEntities(consts.AtomActivitiesCompleted, options, ActivityFeedCallbacks); }, /** * Retrieve an activity node entry, uses the edit link found in the corresponding activity node in the user's My Activities feed. * * @method getActivityNode * @param {String} activityNodeUuid the ID of Activity Node * @returns {Object} ActivityNode */ getActivityNode : function(activityNodeUuid) { var promise = this.validateField("activityNodeUuid", activityNodeUuid); if (promise) { return promise; } var activityNode = this.newActivityNode(activityNodeUuid); return activityNode.load(); }, /** * Retrieve an activity entry, uses the edit link found in the corresponding activity node in the user's My Activities feed. * * @method getActivity * @param {String} activityUuid the ID of Activity * @returns {Object} Activity */ getActivity : function(activityUuid) { var promise = this.validateField("activityUuid", activityUuid); if (promise) { return promise; } var activity = this.newActivity(activityUuid); return activity.load(); }, /** * Creats an entry in an activity, such as a to-do item or to add a reply to another entry, send an Atom entry document containing the new * activity node of the appropriate type to the parent activity's node list. * * @mehtod createActivityNode * @param {String} activityUuid * @param {Object} activityNodeOrJson * @returns {Object} ActivityNode */ createActivityNode : function(activityUuid, activityNodeOrJson) { var promise = this.validateField("activityUuid", activityUuid); if (!promise) { promise = this.validateField("activityNodeOrJson", activityNodeOrJson); } if (promise) { return promise; } var activityNode = this.newActivityNode(activityNodeOrJson); activityNode.setActivityUuid(activityUuid); activityNode.setCategoryScheme(); var payload = activityNode.createPostData(); var requestArgs = { "activityUuid" : activityUuid }; var options = { method : "POST", headers : consts.AtomXmlHeaders, query : requestArgs, data : payload }; return this.updateEntity(consts.AtomCreateActivityNode, options, ActivityNodeFeedCallbacks); }, /** * Creates an activity, sends an Atom entry document containing the new activity to the user's My Activities feed. * * @method createActivity * @param {Object} activityOrJson * @returns {Object} Activity */ createActivity : function(activityOrJson) { var promise = this.validateField("activityOrJson", activityOrJson); if (promise) { return promise; } var activity = this.newActivity(activityOrJson); activity.setType(consts.ActivityNodeTypes.Activity); activity.setCategoryScheme(); var payload = activity.createPostData(); var options = { method : "POST", headers : consts.AtomXmlHeaders, data : payload }; return this.updateEntity(consts.AtomActivitiesMy, options, ActivityFeedCallbacks); }, _validateActivityNode : function(activityNode, checkUuid, checkType) { if (checkUuid && !activityNode.getActivityNodeUuid()) { return this.createBadRequestPromise("Invalid argument, activity node with UUID must be specified."); } if (checkType && !activityNode.getType()) { return this.createBadRequestPromise("Invalid argument, activity node with Type must be specified."); } }, _validateActivity : function(activity, checkUuid) { if (checkUuid && !activity.getActivityUuid()) { return this.createBadRequestPromise("Invalid argument, activity with UUID must be specified."); } }, /** * updates an activity node entry, sends a replacement Atom entry document containing the modified activity node to the existing activity's edit * web address. * @method updateActivityNode * @param {Object} activityNodeOrJson ActivityNode or Json Object with Uuid populated * @returns {Object} ActivityNode */ updateActivityNode : function(activityNodeOrJson) { var promise = this.validateField("activityNodeOrJson", activityNodeOrJson); if (promise) { return promise; } var newActivityNode = this.newActivityNode(activityNodeOrJson); promise = this._validateActivityNode(newActivityNode, true); if (promise) { return promise; } return this._update(newActivityNode, ActivityNodeFeedCallbacks); }, /** * Updates an activity, send a replacement Atom Entry document containing the modified activity to the existing activity's edit URL * @method updateActivity * @param {Object} activityOrJson Activity or Json Object * @returns {Object} Activity */ updateActivity : function(activityOrJson) { var promise = this.validateField("activityOrJson", activityOrJson); if (promise) { return promise; } var newActivity = this.newActivity(activityOrJson); promise = this._validateActivity(newActivity, true); if (promise) { return promise; } return this._update(activityOrJson, ActivityFeedCallbacks); }, _update : function(activityOrActivityNode, callbacks) { var promise = new Promise(); var _this = this; var uuid = extractId(activityOrActivityNode.getUuid()); var update = function() { activityOrActivityNode.setCategoryScheme(); var payload = activityOrActivityNode.createPostData(); var requestArgs = { "activityNodeUuid" : uuid }; var options = { method : "PUT", headers : consts.AtomXmlHeaders, query : requestArgs, data : payload }; _this.updateEntity(consts.AtomActivityNode, options, callbacks).then(function(node) { promise.fulfilled(node); }, function(error) { promise.rejected(error); }); }; if (activityOrActivityNode.isLoaded()) { update(); } else { var fields = activityOrActivityNode._fields; activityOrActivityNode.load().then(function() { activityOrActivityNode._fields = fields; update(); }, function(error) { promise.rejected(error); }); } return promise; }, /** * Changes certain activity entries from one type to another. * * <pre> * <b>The following types of entries can be changed to other types:</b> * chat * email * entry * reply * todo< * /pre> * * @method changeEntryType * @param {Object} activityNodeOrJson ActivityNode or Json object with Uuid and type populated * @returns {Object} ActivityNode */ changeEntryType : function(activityNodeOrJson) { var promise = this.validateField("activityNodeOrJson", activityNodeOrJson); if (promise) { return promise; } var activityNode = this.newActivityNode(activityNodeOrJson); promise = this._validateActivityNode(activityNode, true, true); return this.updateActivityNode(activityNode); }, /** * Moves a standard entry or a to-do entry to a section in an activity, send an updated Atom entry document to the parent activity's node list. * * @method moveEntryToSection * @param {Object} activityNodeOrJson * @param {Object} sectionNodeOrJsonOrId section activityNode or Json Object or Section ID * @returns {Object} ActivityNode */ moveEntryToSection : function(activityNodeOrJson, sectionNodeOrJsonOrId) { var _this = this; var promise = this.validateField("activityNodeOrJson", activityNodeOrJson); if (!promise) { promise = this.validateField("sectionNodeOrJsonOrId", sectionNodeOrJsonOrId); } if (promise) { return promise; } var activityNode = this.newActivityNode(activityNodeOrJson); var sectionNode = this.newActivityNode(sectionNodeOrJsonOrId); promise = new Promise(); var update = function() { activityNode.setInReplyTo(sectionNode.getActivityNodeUuid(), sectionNode.getSelfUrl()); _this.updateActivityNode(activityNode).then(function(activityNode) { promise.fulfilled(activityNode); }, function(error) { promise.rejected(error); }); }; if (sectionNode.isLoaded()) { update(); } else { sectionNode.load().then(function() { update(); }, function(error) { promise.rejected(error); }); } return promise; }, /** * Deletes an activity node entry, sends an HTTP DELETE method to the edit web address specified for the node. * * @method deleteActivityNode * @param {String} activityNodeUuid */ deleteActivityNode : function(activityNodeUuid) { var promise = this.validateField("activityNodeUuid", activityNodeUuid); if (promise) { return promise; } var requestArgs = { "activityNodeUuid" : activityNodeUuid }; var options = { method : "DELETE", headers : consts.AtomXmlHeaders, query : requestArgs }; return this.deleteEntity(consts.AtomActivityNode, options, activityNodeUuid); }, /** * Deletes an activity entry, sends an HTTP DELETE method to the edit web address specified for the node. * * @method deleteActivity * @param {String} activityUuid */ deleteActivity : function(activityUuid) { var promise = this.validateField("activityUuid", activityUuid); if (promise) { return promise; } return this.deleteActivityNode(activityUuid); }, /** * Restores a deleted activity, use a HTTP PUT request. This moves the activity from the trash feed to the user's My Activities feed. * * @method restoreActivity * @param {String} activityUuid */ restoreActivity : function(activityUuid) { var promise = this.validateField("activityUuid", activityUuid); if (promise) { return promise; } var _this = this; promise = new Promise(); this.getActivityNodeFromTrash(activityUuid).then(function(deleted) { return deleted; }).then(function(activity) { if (!activity.isDeleted()) { promise.rejected("Activity is not in Trash"); } else { var requestArgs = { "activityNodeUuid" : activityUuid }; activity.setCategoryScheme(); var options = { method : "PUT", headers : consts.AtomXmlHeaders, query : requestArgs, data : activity.createPostData() }; var callbacks = { createEntity : function(service, data, response) { return response; } }; _this.updateEntity(consts.AtomActivityNodeTrash, options, callbacks).then(function(response) { promise.fulfilled(response); }, function(error) { promise.rejected(error); }); } }); return promise; }, /** * Restores a deleted entry to an activity, sends a HTTP PUT request to the edit web address for the node defined in the trash feed. This moves * the entry from the trash feed to the user's activity node list. * * @method restoreActivityNode * @param {String} activityNodeUuid */ restoreActivityNode : function(activityNodeUuid) { var promise = this.validateField("activityNodeUuid", activityNodeUuid); if (promise) { return promise; } var _this = this; var promise = new Promise(); this.getActivityNodeFromTrash(activityNodeUuid).then(function(deletedNode) { return deletedNode; }).then(function(activityNode) { if (!activityNode.isDeleted()) { promise.rejected("Activity Node is not in Trash"); } else { var requestArgs = { "activityNodeUuid" : activityNodeUuid }; activityNode.setCategoryScheme(); var options = { method : "PUT", headers : consts.AtomXmlHeaders, query : requestArgs, data : activityNode.createPostData() }; var callbacks = { createEntity : function(service, data, response) { return response; } }; _this.updateEntity(consts.AtomActivityNodeTrash, options, callbacks).then(function(response) { promise.fulfilled(response); }, function(error) { promise.rejected(error); }); } }); return promise; }, /** * Retrieves and activity node from trash * * @method getActivityNodeFromTrash * @param {String} activityNodeUuid * @returns {Object} ActivityNode */ getActivityNodeFromTrash : function(activityNodeUuid) { var promise = this.validateField("activityNodeUuid", activityNodeUuid); if (promise) { return promise; } var requestArgs = { "activityNodeUuid" : activityNodeUuid }; var options = { method : "GET", handleAs : "text", query : requestArgs }; return this.getEntity(consts.AtomActivityNodeTrash, options, activityNodeUuid, ActivityNodeFeedCallbacks); }, /** * Returns a ActivityNode instance from ActivityNode or JSON or String. Throws an error if the argument was neither. * * @method newActivityNode * @param {Object} activityNodeOrJsonOrString The ActivityNode Object or json String for ActivityNode */ newActivityNode : function(activityNodeOrJsonOrString) { if (activityNodeOrJsonOrString instanceof ActivityNode || activityNodeOrJsonOrString instanceof Activity) { return activityNodeOrJsonOrString; } else { if (lang.isString(activityNodeOrJsonOrString)) { activityNodeOrJsonOrString = { id : activityNodeOrJsonOrString }; } return new ActivityNode({ service : this, _fields : lang.mixin({}, activityNodeOrJsonOrString) }); } }, /** * Gets All activity nodes in trash which match given criteria * @method getActivityNodesInTrash * @param {String} activityUuid * @param {Object} [requestArgs] optional arguments * @returns {Array} ActivityNode list */ getActivityNodesInTrash : function(activityUuid, requestArgs) { var promise = this.validateField("activityUuid", activityUuid); if (promise) { return promise; } var args = lang.mixin(requestArgs || {}, { "activityUuid" : activityUuid }); var options = { method : "GET", handleAs : "text", query : args || {} }; return this.getEntities(consts.AtomActivitiesTrash, options, ActivityNodeFeedCallbacks); }, /** * Returns a Activity instance from Activity or JSON or String. Throws an error if the argument was neither. * @method newActivity * @param {Object} activityOrJsonOrString The Activity Object or json String for Activity */ newActivity : function(activityOrJsonOrString) { if (activityOrJsonOrString instanceof Activity) { return activityOrJsonOrString; } else { if (lang.isString(activityOrJsonOrString)) { activityOrJsonOrString = { id : activityOrJsonOrString }; } return new Activity({ service : this, _fields : lang.mixin({}, activityOrJsonOrString) }); } }, /** * Search for a set of to-do items that match a specific criteria. * * @method getAllToDos * @param {Object} [requestArgs] the optional arguments * @returns {Array} ActivityNode Array */ getAllToDos : function(requestArgs) { var options = { method : "GET", handleAs : "text", query : requestArgs || {} }; return this.getEntities(consts.AtomActivitiesToDos, options, ActivityFeedCallbacks); }, /** * Search for a set of tags that match a specific criteria. * @method getAllTags * @param {Object} [requestArgs] the optional arguments * @returns {Array} */ getAllTags : function(requestArgs) { var options = { method : "GET", handleAs : "text", query : requestArgs || {} }; return this.getEntities(consts.AtomActivitiesTags, options, TagFeedCallbacks); }, /** * Search for sctivities in trash which math a specif criteria * * @method getActivitiesInTrash * @param {Object} [requestArgs] the optional arguments * @returns {Array} activities */ getActivitiesInTrash : function(requestArgs) { var options = { method : "GET", handleAs : "text", query : requestArgs || {} }; return this.getEntities(consts.AtomActivitiesTrash, options, ActivityFeedCallbacks); }, /** * Returns the tags for given actiivity * @method getActivityTags * @param {String} activityUuid * @param {Object} [requestArgs] the optional arguments * @returns {Array} tags */ getActivityTags : function(activityUuid, requestArgs) { var promise = this.validateField("activityUuid", activityUuid); if (promise) { return promise; } var args = lang.mixin(requestArgs || {}, { "activityUuid" : activityUuid }); var options = { method : "GET", handleAs : "text", query : args || {} }; return this.getEntities(consts.AtomActivitiesTags, options, TagFeedCallbacks); }, /** * Returns the tags for given actiivity node. * @method getActivityNodeTags * @param activityNodeUuid * @param {Object} [requestArgs] the optional arguments * @returns {Array} tags */ getActivityNodeTags : function(activityNodeUuid, requestArgs) { var promise = this.validateField("activityNodeUuid", activityNodeUuid); if (promise) { return promise; } var args = lang.mixin(requestArgs || {}, { "activityNodeUuid" : activityNodeUuid }); var options = { method : "GET", handleAs : "text", query : args || {} }; return this.getEntities(consts.AtomActivitiesTags, options, TagFeedCallbacks); }, /** * Retrieves activity members from the access control list for a application, use the edit link found in the member entry in the ACL list feed. * @method getMembers * @param {String} activityUuid * @param {Object} [requestArgs] the optional arguments * @returns {Array} members */ getMembers : function(activityUuid, requestArgs) { var promise = this.validateField("activityUuid", activityUuid); if (promise) { return promise; } var args = lang.mixin(requestArgs || {}, { "activityUuid" : activityUuid }); var options = { method : "GET", handleAs : "text", query : args || {} }; return this.getEntities(consts.AtomActivitiesMembers, options, MemberFeedCallbacks); }, _validateMember : function(member, checkId, checkUserIdOrEmail) { if (checkId && !member.getMemberId()) { return this.createBadRequestPromise("Invalid argument, member with ID must be specified."); } if (checkUserIdOrEmail) { var id = member.getContributor().userid || member.getContributor().email; if (!id) { return this.createBadRequestPromise("Invalid argument, member with User ID or Email must be specified."); } } }, /** * Retrieves a member from the access control list for a application, use the edit link found in the member entry in the ACL list feed. * @method getMember * @param {String} activityUuid * @param {String} memberId * @returns {Object} Member */ getMember : function(activityUuid, memberId) { var promise = this.validateField("memberId", memberId); if (!promise) { promise = this.validateField("activityUuid", activityUuid); } if (promise) { return promise; } var member = this._toMember(memberId); return member.load(activityUuid); }, /** * Adds a member to the access control list of an activity, sends an Atom entry document containing the new member to the access control list * feed. You can only add one member per post. * @method addMember * @param {String} activityUuid * @param {Object} memberOrJson */ addMember : function(activityUuid, memberOrJson) { var promise = this.validateField("memberOrJson", memberOrJson); if (!promise) { promise = this.validateField("activityUuid", activityUuid); } if (promise) { return promise; } var member = this._toMember(memberOrJson); promise = this._validateMember(member, false, true); if (promise) { return promise; } if (!member.getRole()) { member.setRole("member"); } member.setCategoryScheme(); var payload = member.createPostData(); var requestArgs = { "activityUuid" : activityUuid }; var options = { method : "POST", headers : consts.AtomXmlHeaders, query : requestArgs, data : payload }; var callbacks = { createEntity : function(service, data, response) { return response; } }; return this.updateEntity(consts.AtomActivitiesMembers, options, callbacks); }, /** * Updates a member in the access control list for an application, sends a replacement member entry document in Atom format to the existing ACL * node's edit web address. * @method updateMember * @param {String} activityUuid * @param {Object} memberOrJson */ updateMember : function(activityUuid, memberOrJson) { var promise = this.validateField("memberOrJson", memberOrJson); if (!promise) { promise = this.validateField("activityUuid", activityUuid); } if (promise) { return promise; } var member = this._toMember(memberOrJson); promise = this._validateMember(member, true, true); if (promise) { return promise; } member.setCategoryScheme(); var payload = member.createPostData(); var requestArgs = { "activityUuid" : activityUuid, "memberid" : member.getMemberId() }; var options = { method : "PUT", headers : consts.AtomXmlHeaders, query : requestArgs, data : payload }; var callbacks = { createEntity : function(service, data, response) { return response; } }; return this.updateEntity(consts.AtomActivitiesMembers, options, callbacks); }, /** * Removes a member from the acl list for an application, use the HTTP DELETE method. * @method deleteMember * @param {String} activityUuid * @param {String} memberId */ deleteMember : function(activityUuid, memberId) { var promise = this.validateField("activityUuid", activityUuid); if (!promise) { promise = this.validateField("memberId", memberId); } if (promise) { return promise; } var requestArgs = { "activityUuid" : activityUuid, "memberid" : memberId }; var options = { method : "DELETE", headers : consts.AtomXmlHeaders, query : requestArgs }; return this.deleteEntity(consts.AtomActivitiesMembers, options, memberId); }, _toMember : function(memberOrJsonOrString) { if (memberOrJsonOrString) { if (memberOrJsonOrString instanceof Member) { return memberOrJsonOrString; } var member = new Member({ service : this }); if (lang.isString(memberOrJsonOrString)) { memberOrJsonOrString = { id : memberOrJsonOrString }; } member._fields = lang.mixin({}, memberOrJsonOrString); if(member._fields.userId) { member._fields.contributorUserid = member._fields.userId; } return member; } }, /** * Returns a Member instance from Member or JSON or String. Throws an error if the argument was neither. * @method newMember * @param {Object} memberOrJsonOrString The Member Object or json String for Member */ newMember : function(memberOrJsonOrString) { return this._toMember(memberOrJsonOrString); } }); return ActivityService; }); }, 'sbt/base/JsonDataHandler':function(){ /* * © Copyright IBM Corp. 2012,2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. * Helpers for the base capabilities of data handlers. * * @module sbt.base.JsonDataHandler */ define(["../declare", "../lang", "../json", "./DataHandler", "../Jsonpath", "../stringUtil"], function(declare, lang, json, DataHandler, jsonPath, stringUtil) { /** * JsonDataHandler class * * @class JsonDataHandler * @namespace sbt.base */ var JsonDataHandler = declare(DataHandler, { /** * Data type for this DataHandler is 'json' */ dataType : "json", /** * Set of jsonpath expressions used by this handler. */ jsonpath : null, /** * Set of values that have already been read. */ _values : null, /** * @constructor * @param {Object} args Arguments for this data handler. */ constructor : function(args) { lang.mixin(this, args); this._values = {}; this.data = args.data; }, /** * @method getAsString * @param data * @returns */ getAsString : function(property) { this._validateProperty(property, "getAsString"); if (this._values) { if (!this._values.hasOwnProperty(property)) { this._values[property] = this._get(property).toString(); } return this._values[property]; } else { return _get(property); } }, /** * @method getAsNumber * @returns */ getAsNumber : function(property) { this._validateProperty(property, "getAsNumber"); if (this._values) { if (!this._values.hasOwnProperty(property)) { this._values[property] = this._getNumber(property); } return this._values[property]; } else { return _getNumber(property); } }, /** * @method getAsDate * @returns */ getAsDate : function(property) { this._validateProperty(property, "getAsDate"); if (this._values) { if (!this._values.hasOwnProperty(property)) { this._values[property] = this._getDate(property); } return this._values[property]; } else { return _getDate(property); } }, /** * @method getAsBoolean * @returns */ getAsBoolean : function(property) { this._validateProperty(property, "getAsBoolean"); if (this._values) { if (!this._values.hasOwnProperty(property)) { this._values[property] = this._getBoolean(property); } return this._values[property]; } else { return _getBoolean(property); } }, /** * @method getAsArray * @returns */ getAsArray : function(property) { this._validateProperty(property, "getAsArray"); if (this._values) { if (!this._values.hasOwnProperty(property)) { this._values[property] = this._get(property); } return this._values[property]; } else { return _get(property); } }, /** * @method getEntityId * @returns */ getEntityId : function(data) { return stringUtil.trim(this.getAsString(this.jsonpath["id"])); }, /** * getEntityData * @returns */ getEntityData : function() { return this.data; }, /** * @method getSummary * @returns */ getSummary : function() { if (!this._summary && this._get("totalResults")[0]) { this._summary = { totalResults : this.getAsNumber("totalResults"), startIndex : this.getAsNumber("startIndex"), itemsPerPage : this.getAsNumber("itemsPerPage") }; } return this._summary; }, /** * @method getEntitiesDataArray * @returns {Array} */ getEntitiesDataArray : function() { var entityJPath = this._getJPath("entry"); var resultingArray = this._get(entityJPath); return resultingArray[0]; }, /** * @method toJson * @returns {Object} */ toJson : function() { return this.data; }, // // Internals // _getDate : function(property) { var text = this._get(property)[0]; if(text instanceof Date) { return text; } else { return new Date(text); } }, _getBoolean : function(property) { var text = this._get(property)[0]; return text ? true : false; }, _getNumber : function(property) { var text = this._get(property)[0]; // if it is a Number if(typeof text === 'number') return text; //if its an array, we return the length of the array else if(lang.isArray(text)) return text.length; //if its a string or any other data type, we convert to number and return. Invalid data would throw an error here. else return Number(text); }, /** Validate that the property is valid **/ _validateProperty : function(property, method) { if (!property) { var msg = stringUtil.substitute("Invalid argument for JsonDataHandler.{1} {0}", [ property, method ]); throw new Error(msg); } }, /** Validate that the object is valid **/ _validateObject : function(object) { if (!object) { var msg = stringUtil.substitute("Invalid argument for JsonDataHandler.{0}", [ object ]); throw new Error(msg); } }, _evalJson: function(jsonQuery){ return jsonPath(this.data,jsonQuery); }, _evalJsonWithData: function(jsonQuery, data){ return jsonPath(data,jsonQuery); }, _get: function(property){ this._validateObject(this.data); var jsonQuery = this._getJPath(property); var result = this._evalJson(jsonQuery); return result; }, _getJPath: function(property) { return this.jsonpath[property] || property; }, extractFirstElement: function(result){ return this._evalJsonWithData("$[0]", result); } }); return JsonDataHandler; }); }, 'sbt/connections/Tag':function(){ /* * © Copyright IBM Corp. 2012, 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * * @module sbt.connections.Tag * @author Rajmeet Bal */ define(["../declare", "../base/BaseEntity" ], function(declare, BaseEntity) { /** * Tag class. * * @class Tag * @namespace sbt.connections */ var Tag = declare(BaseEntity, { /** * * @constructor * @param args */ constructor : function(args) { }, /** * Get term of the tag * * @method getTerm * @return {String} term of the tag * */ getTerm : function() { return this.getAsString("term"); }, /** * Get frequency of the tag * * @method getFrequency * @return {Number} frequency of the tag * */ getFrequency : function() { return this.getAsNumber("frequency"); } }); return Tag; }); }, 'sbt/connections/FileService':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * JavaScript API for IBM Connections File Service. * * @module sbt.connections.FileService */ define( [ "../declare", "../lang", "../stringUtil", "../Promise", "./FileConstants", "./ConnectionsService", "../base/BaseEntity", "../base/XmlDataHandler", "../config", "../util", "../xml" ], function(declare, lang, stringUtil, Promise, consts, ConnectionsService, BaseEntity, XmlDataHandler, config, util, xml) { var FolderTmpl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><entry xmlns=\"http://www.w3.org/2005/Atom\">${getCategory}${getId}${getFolderLabel}${getTitle}${getSummary}${getVisibility}${getVisibilityShare}</entry>"; var FolderLabelTmpl = "<label xmlns=\"urn:ibm.com/td\" makeUnique=\"true\">${label}</label>"; var FileVisibilityShareTmpl = "<sharedWith xmlns=\"urn:ibm.com/td\"> <member xmlns=\"http://www.ibm.com/xmlns/prod/composite-applications/v1.0\" ca:type=\"${shareWithWhat}\" xmlns:ca=\"http://www.ibm.com/xmlns/prod/composite-applications/v1.0\" ca:id=\"${shareWithId}\" ca:role=\"${shareWithRole}\"/> </sharedWith>"; var FileFeedTmpl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><feed xmlns=\"http://www.w3.org/2005/Atom\">${getEntries}</feed>"; var FileEntryTmpl = "<entry xmlns=\"http://www.w3.org/2005/Atom\">${getCategory}${getId}${getUuid}${getLabel}${getTitle}${getSummary}${getVisibility}${getItem}${getTags}${getNotification}</entry>"; var FileItemEntryTmpl = "<entry>${getCategory}${getItem}</entry>"; var FileCommentsTmpl = "<entry xmlns=\"http://www.w3.org/2005/Atom\">${getCategory}${getDeleteComment}${getContent}</entry>"; var FileCategoryTmpl = "<category term=\"${category}\" label=\"${category}\" scheme=\"tag:ibm.com,2006:td/type\"/>"; var FileContentTmpl = "<content type=\"text/plain\">${content}</content>"; var FileDeleteCommentTmpl = "<deleteWithRecord xmlns=\"urn:ibm.com/td\">${deleteWithRecord}</deleteWithRecord>"; var FileIdTmpl = "<id>${id}</id>"; var FileUuidTmpl = "<uuid xmlns=\"urn:ibm.com/td\">${uuid}</uuid>"; var FileLabelTmpl = "<label xmlns=\"urn:ibm.com/td\">${label}</label>"; var FileTitleTmpl = "<title>${title}</title>"; var FileSummaryTmpl = "<summary type=\"text\">${summary}</summary>"; var FileVisibilityTmpl = "<visibility xmlns=\"urn:ibm.com/td\">${visibility}</visibility>"; var FileItemIdTmpl = "<itemId xmlns=\"urn:ibm.com/td\">${fileId}</itemId>"; var TagsTmpl = "<category term=\"${tag}\" /> "; var NotificationTmpl = "<td:notification>${notification}</td:notification>"; /** * Library class associated with a library. * * @class Library * @namespace sbt.connections */ var Library = declare(BaseEntity, { /** * Returned the Library Id * * @method getId * @returns {String} Id */ getId : function() { return this.getAsString("id"); }, /** * Returned the Library Uuid * * @method getLibrrayUuid * @returns {String} Uuid */ getLibraryUuid : function() { return this.getAsString("uuid"); }, /** * Returned the library size * * @method getLibrarySize * @returns {Number} library size */ getLibrarySize : function() { return this.getAsNumber("librarySize"); }, /** * Returned the library quota * * @method getLibraryQuota * @returns {Number} library quota */ getLibraryQuota : function() { return this.getAsNumber("libraryQuota"); }, /** * Returned the total removed size * * @method getTotalRemovedSize * @returns {Number} total removed size */ getTotalRemovedSize : function() { return this.getAsNumber("totalRemovedSize"); }, /** * Returned the total results * * @method getTotalResults * @returns {Number} total results */ getTotalResults : function() { return this.getAsNumber("totalResults"); } }); /** * Comment class associated with a file comment. * * @class Comment * @namespace sbt.connections */ var Comment = declare(BaseEntity, { /** * Returned the Comment Id * * @method getCommentId * @returns {String} File Id */ getCommentId : function() { return this.id || this.getAsString("uid"); }, /** * Returns Comment Title * * @method getTitle * @returns {String} title */ getTitle : function() { return this.getAsString("title"); }, /** * Returns the Comment Content * * @method getContent * @returns {String} content */ getContent : function() { return this.getAsString("content"); }, /** * Returns The create Date * * @method getCreated * @returns {Date} create Date */ getCreated : function() { return this.getAsDate("created"); }, /** * Returns The modified Date * * @method getModified * @returns {Date} modified Date */ getModified : function() { return this.getAsDate("modified"); }, /** * Returns the version label * * @method getVersionLabel * @returns {String} version label */ getVersionLabel : function() { return this.getAsString("versionLabel"); }, /** * Returns the updated Date * * @method getModified * @returns {Date} modified Date */ getUpdated : function() { return this.getAsDate("updated"); }, /** * Returns the published Date * * @method getPublished * @returns {Date} modified Date */ getPublished : function() { return this.getAsDate("published"); }, /** * Returns the modifier * * @method getModifier * @returns {Object} modifier */ getModifier : function() { return this.getAsObject([ "modifierName", "modifierUserId", "modifierEmail", "modifierUserState" ]); }, /** * Returns the author * * @method getAuthor * @returns {Object} author */ getAuthor : function() { return this.getAsObject([ "authorName", "authorUserId", "authorEmail", "authorUserState" ]); }, /** * Returns the language * * @method getLanguage * @returns {String} language */ getLanguage : function() { return this.getAsString("language"); }, /** * Returns the flag for delete with record * * @method getDeleteWithRecord * @returns {Boolean} delete with record */ getDeleteWithRecord : function() { return this.getAsBoolean("deleteWithRecord"); } }); /** * File class associated with a file. * * @class File * @namespace sbt.connections */ var File = declare(BaseEntity, { /** * Returns the file Id * * @method getFileId * @returns {String} file Id */ getFileId : function() { return this.id || this.getAsString("uid") || this._fields.id; }, /** * Returns the label * * @method getLabel * @returns {String} label */ getLabel : function() { return this.getAsString("label"); }, /** * Returns the self URL * * @method getSelfUrl * @returns {String} self URL */ getSelfUrl : function() { return this.getAsString("selfUrl"); }, /** * Returns the alternate URL * * @method getAlternateUrl * @returns {String} alternate URL */ getAlternateUrl : function() { return this.getAsString("alternateUrl"); }, /** * Returns the download URL * * @method getDownloadUrl * @returns {String} download URL */ getDownloadUrl : function() { return config.Properties.serviceUrl + "/files/" + this.service.endpoint.proxyPath + "/" + "connections" + "/" + "DownloadFile" + "/" + this.getFileId() + "/" + this.getLibraryId(); ; }, /** * Returns the type * * @method getType * @returns {String} type */ getType : function() { return this.getAsString("type"); }, /** * Returns the Category * * @method getCategory * @returns {String} category */ getCategory : function() { return this.getAsString("category"); }, /** * Returns the size * * @method getSize * @returns {Number} length */ getSize : function() { return this.getAsNumber("length"); }, /** * Returns the Edit Link * * @method getEditLink * @returns {String} edit link */ getEditLink : function() { return this.getAsString("editLink"); }, /** * Returns the Edit Media Link * * @method getEditMediaLink * @returns {String} edit media link */ getEditMediaLink : function() { return this.getAsString("editMediaLink"); }, /** * Returns the Thumbnail URL * * @method getThumbnailUrl * @returns {String} thumbnail URL */ getThumbnailUrl : function() { return this.getAsString("thumbnailUrl"); }, /** * Returns the Comments URL * * @method getCommentsUrl * @returns {String} comments URL */ getCommentsUrl : function() { return this.getAsString("commentsUrl"); }, /** * Returns the author * * @method getAuthor * @returns {Object} author */ getAuthor : function() { return this.getAsObject([ "authorName", "authorUserId", "authorEmail", "authorUserState" ]); }, /** * Returns the Title * * @method getTitle * @returns {String} title */ getTitle : function() { return this.getAsString("title"); }, /** * Returns the published date * * @method getPublished * @returns {Date} published date */ getPublished : function() { return this.getAsDate("published"); }, /** * Returns the updated date * * @method getUpdated * @returns {Date} updated date */ getUpdated : function() { return this.getAsDate("updated"); }, /** * Returns the created date * * @method getCreated * @returns {Date} created date */ getCreated : function() { return this.getAsDate("created"); }, /** * Returns the modified date * * @method getModified * @returns {Date} modified date */ getModified : function() { return this.getAsDate("modified"); }, /** * Returns the last accessed date * * @method getLastAccessed * @returns {Date} last accessed date */ getLastAccessed : function() { return this.getAsDate("lastAccessed"); }, /** * Returns the modifier * * @method getModifier * @returns {Object} modifier */ getModifier : function() { return this.getAsObject([ "modifierName", "modifierUserId", "modifierEmail", "modifierUserState" ]); }, /** * Returns the visibility * * @method getVisibility * @returns {String} visibility */ getVisibility : function() { return this.getAsString("visibility"); }, /** * Returns the library Id * * @method getLibraryId * @returns {String} library Id */ getLibraryId : function() { return this.getAsString("libraryId"); }, /** * Sets the library Id * * @method setLibraryId * @param libaryId */ setLibraryId : function(libraryId) { return this.setAsString("libraryId", libraryId); }, /** * Returns the library Type * * @method getLibraryType * @returns {String} library Type */ getLibraryType : function() { return this.getAsString("libraryType"); }, /** * Returns the version Id * * @method getVersionUuid * @returns {String} version Id */ getVersionUuid : function() { return this.getAsString("versionUuid"); }, /** * Returns the version label * * @method getVersionLabel * @returns {String} version label */ getVersionLabel : function() { return this.getAsString("versionLabel"); }, /** * Returns the propagation * * @method getPropagation * @returns {String} propagation */ getPropagation : function() { return this.getAsString("propagation"); }, /** * Returns the recommendations Count * * @method getRecommendationsCount * @returns {Number} recommendations Count */ getRecommendationsCount : function() { return this.getAsNumber("recommendationsCount"); }, /** * Returns the comments Count * * @method getCommentsCount * @returns {Number} comments Count */ getCommentsCount : function() { return this.getAsNumber("commentsCount"); }, /** * Returns the shares Count * * @method getSharesCount * @returns {Number} shares Count */ getSharesCount : function() { return this.getAsNumber("sharesCount"); }, /** * Returns the folders Count * * @method getFoldersCount * @returns {Number} folders Count */ getFoldersCount : function() { return this.getAsNumber("foldersCount"); }, /** * Returns the attachments Count * * @method getAttachmentsCount * @returns {Number} attachments Count */ getAttachmentsCount : function() { return this.getAsNumber("attachmentsCount"); }, /** * Returns the versions Count * * @method getVersionsCount * @returns {Number} versions Count */ getVersionsCount : function() { return this.getAsNumber("versionsCount"); }, /** * Returns the references Count * * @method getReferencesCount * @returns {Number} references Count */ getReferencesCount : function() { return this.getAsNumber("referencesCount"); }, /** * Returns the total Media Size * * @method getTotalMediaSize * @returns {Number} total Media Size */ getTotalMediaSize : function() { return this.getAsNumber("totalMediaSize"); }, /** * Returns the Summary * * @method getSummary * @returns {String} Summary */ getSummary : function() { return this.getAsString("summary"); }, /** * Returns the Content URL * * @method getContentUrl * @returns {String} Content URL */ getContentUrl : function() { return this.getAsString("contentUrl"); }, /** * Returns the Content Type * * @method getContentType * @returns {String} Content Type */ getContentType : function() { return this.getAsString("contentType"); }, /** * Returns the objectTypeId * * @method getObjectTypeId * @returns {String} objectTypeId */ getObjectTypeId : function() { return this.getAsString("objectTypeId"); }, /** * Returns the lock state * * @method getLockType * @returns {String} lock state */ getLockType : function() { return this.getAsString("lock"); }, /** * Returns the permission ACLs * * @method getAcls * @returns {String} ACLs */ getAcls : function() { return this.getAsString("acls"); }, /** * Returns the hit count * * @method getHitCount * @returns {Number} hit count */ getHitCount : function() { return this.getAsNumber("hitCount"); }, /** * Returns the anonymous hit count * * @method getAnonymousHitCount * @returns {Number} anonymous hit count */ getAnonymousHitCount : function() { return this.getAsNumber("anonymousHitCount"); }, /** * Returns the tags * * @method getTags * @returns {Array} tags */ getTags : function() { return this.getAsArray("tags"); }, /** * Returns the tags * * @method setTags * @param {Array} tags */ setTags : function(tags) { return this.setAsArray("tags", tags); }, /** * Sets the label * * @method setLabel * @param {String} label */ setLabel : function(label) { return this.setAsString("label", label); }, /** * Sets the summary * * @method setSummary * @param {String} summary */ setSummary : function(summary) { return this.setAsString("summary", summary); }, /** * Sets the visibility * * @method setVisibility * @param {String} visibility */ setVisibility : function(visibility) { return this.setAsString("visibility", visibility); }, /** * Sets Indicator whether the currently authenticated user wants to receive notifications as people edit the document. Options are on or off. * @param {Boolean} notification * @returns */ setNotification : function(notification) { return this.setAsBoolean("notification", notification ? "on" : "off"); }, /** * Loads the file object with the atom entry associated with the file. By default, a network call is made to load the atom entry document in the * file object. * * @method load * @param {Object} [args] Argument object * @param {Boolean} [isPublic] Optinal flag to indicate whether to load public file which does not require authentication */ load : function(args, isPublic, url) { // detect a bad request by validating required arguments var fileUuid = this.getFileId(); var promise = this.service.validateField("fileId", fileUuid); if (promise) { return promise; } if(isPublic) { promise = this.service.validateField("libraryId", this.getLibraryId()); if (promise) { return promise; } } var self = this; var callbacks = { createEntity : function(service, data, response) { self.dataHandler = new XmlDataHandler({ data : data, namespaces : consts.Namespaces, xpath : consts.FileXPath }); return self; } }; var requestArgs = lang.mixin({ fileUuid : fileUuid }, args || {}); var options = { // handleAs : "text", query : requestArgs }; if (!url) { if (isPublic) { url = this.service.constructUrl(consts.AtomFileInstancePublic, null, { "documentId" : fileUuid, "libraryId" : this.getLibraryId() }); } else { url = this.service.constructUrl(consts.AtomFileInstance, null, { "documentId" : fileUuid }); } } return this.service.getEntity(url, options, fileUuid, callbacks); }, /** * Save this file * * @method save * @param {Object} [args] Argument object */ save : function(args) { if (this.getFileId()) { return this.service.updateFileMetadata(this, args); } }, /** * Adds a comment to the file. * * @method addComment * @param {String} comment the comment to be added * @param {Object} [args] Argument object. Object representing various parameters that can be passed. The parameters must be exactly as they are * supported by IBM Connections like ps, sortBy etc. */ addComment : function(comment, args) { return this.service.addCommentToFile(this.getAuthor().authorUserId, this.getFileId(), comment, args); }, /** * Pin th file, by sending a POST request to the myfavorites feed. * * @method pin * @param {Object} [args] Argument object. */ pin : function(args) { return this.service.pinFile(this.getFileId(), args); }, /** * Unpin the file, by sending a DELETE request to the myfavorites feed. * * @method unPin * @param {Object} [args] Argument object. */ unpin : function(args) { return this.service.unpinFile(this.getFileId(), args); }, /** * Lock the file * * @method lock * @param {Object} [args] Argument object */ lock : function(args) { return this.service.lockFile(this.getFileId(), args); }, /** * UnLock the file * * @method unlock * @param {Object} [args] Argument object */ unlock : function(args) { return this.service.unlockFile(this.getFileId(), args); }, /** * Deletes the file. * * @method remove * @param {Object} [args] Argument object */ remove : function(args) { return this.service.deleteFile(this.getFileId(), args); }, /** * Update the Atom document representation of the metadata for the file * * @method update * @param {Object} [args] Argument object. Object representing various parameters that can be passed. The parameters must be exactly as they are * supported by IBM Connections like ps, sortBy etc. */ update : function(args) { return this.service.updateFileMetadata(this, args); }, /** * Downloads the file * * @method download */ download : function() { return this.service.downloadFile(this.getFileId(), this.getLibraryId()); } }); /** * Callbacks used when reading a feed that contains File entries. */ var FileFeedCallbacks = { createEntities : function(service, data, response) { return new XmlDataHandler({ data : data, namespaces : consts.Namespaces, xpath : consts.FileFeedXPath }); }, createEntity : function(service, data, response) { var entry = null; if (typeof data == "object") { entry = data; } else { var feedHandler = new XmlDataHandler({ data : data, namespaces : consts.Namespaces, xpath : consts.FileXPath }); entry = feedHandler.data; } var entryHandler = new XmlDataHandler({ data : entry, namespaces : consts.Namespaces, xpath : consts.FileXPath }); return new File({ service : service, dataHandler : entryHandler }); } }; /** * Callbacks used when reading a feed that contains File Comment entries. */ var CommentCallbacks = { createEntities : function(service, data, response) { return new XmlDataHandler({ data : data, namespaces : consts.Namespaces, xpath : consts.CommentFeedXPath }); }, createEntity : function(service, data, response) { var entry = null; if (typeof data == "object") { entry = data; } else { var feedHandler = new XmlDataHandler({ data : data, namespaces : consts.Namespaces, xpath : consts.CommentXPath }); entry = feedHandler.data; } var entryHandler = new XmlDataHandler({ data : entry, namespaces : consts.Namespaces, xpath : consts.CommentXPath }); return new Comment({ service : service, dataHandler : entryHandler }); } }; /** * FileService class. * * @class FileService * @namespace sbt.connections */ var FileService = declare(ConnectionsService, { contextRootMap : { files : "files" }, serviceName : "files", /** * Constructor for FileService * * @constructor * @param args */ constructor : function(args) { var endpointName = args ? (args.endpoint ? args.endpoint : this.getDefaultEndpointName()) : this.getDefaultEndpointName(); if (!this.endpoint) { this.endpoint = config.findEndpoint(endpointName); } }, /** * Returns information about the current users library. * */ getMyLibrary : function(args) { var options = { method : "GET", handleAs : "text", query : { ps:1, includeQuota:true } || args || {} }; var self = this; var callbacks = { createEntity : function(service, data, response) { var entryHandler = new XmlDataHandler({ data : data, namespaces : consts.Namespaces, xpath : consts.LibraryXPath }); return new Library({ service : self, dataHandler : entryHandler }); } }; return this.getEntity(consts.AtomFilesMy, options, "my", callbacks); }, /** * Returns a File instance from File or JSON or String. Throws an error if the argument was neither. * * @param {Object} fileOrJsonOrString The file Object or json String for File */ newFile : function(fileOrJsonOrString) { if (fileOrJsonOrString instanceof File) { return fileOrJsonOrString; } else { if (lang.isString(fileOrJsonOrString)) { fileOrJsonOrString = { id : fileOrJsonOrString }; } return new File({ service : this, _fields : lang.mixin({}, fileOrJsonOrString) }); } }, /** * Loads File with the ID passed * * @method getFile * @param {String} fileId the Id of the file to be loaded * @param {Object} [args] Argument object */ getFile : function(fileId, args) { var promise = this.validateField("fileId", fileId); if (promise) { return promise; } var file = this.newFile({ id : fileId }); return file.load(args); }, /** * Loads Community File * * @method getFile * @param {String} fileId the Id of the file to be loaded * @param {String} communityId the Id of the community to which it belongs * @param {Object} [args] Argument object */ getCommunityFile : function(fileId, communityId, args) { var promise = this.validateField("fileId", fileId); if (!promise) { promise = this.validateField("communityId", communityId); } if (promise) { return promise; } var file = this.newFile({ id : fileId }); var url = this.constructUrl(consts.AtomGetCommunityFile, null, { communityId : communityId, documentId : file.getFileId() }); return file.load(args, null, url); }, /** * Get my files from IBM Connections * * @method getMyFiles * @param {Object} [args] Argument object. Object representing various parameters that can be passed. The parameters must be exactly as they are * supported by IBM Connections like ps, sortBy etc. */ getMyFiles : function(args) { var options = { method : "GET", handleAs : "text", query : args || {} }; return this.getEntities(consts.AtomFilesMy, options, this.getFileFeedCallbacks()); }, /** * Get community files from IBM Connections (community files refer to * files which the user uploaded to the community. Calling this function * will not list files that have been shared with this community). * * @method getCommunityFiles * @param {Object} [args] Argument object. Object representing various parameters that can be passed. The parameters must be exactly as they are * supported by IBM Connections like ps, sortBy etc. */ getCommunityFiles : function(communityId, args) { var options = { method : "GET", handleAs : "text", query : args || {} }; var url = this.constructUrl(consts.AtomGetAllFilesInCommunity, null, { communityId : communityId }); return this.getEntities(url, options, this.getFileFeedCallbacks()); }, /** * Get files shared with logged in user from IBM Connections * * @method getFilesSharedWithMe * @param {Object} [args] Argument object. Object representing various parameters that can be passed. The parameters must be exactly as they are * supported by IBM Connections like ps, sortBy etc. */ getFilesSharedWithMe : function(args) { var options = { method : "GET", handleAs : "text", query : lang.mixin({ direction : "inbound" }, args ? args : {}) }; return this.getEntities(consts.AtomFilesShared, options, this.getFileFeedCallbacks()); }, /** * Get files shared by the logged in user from IBM Connections * * @method getFilesSharedByMe * @param {Object} [args] Argument object. Object representing various parameters that can be passed. The parameters must be exactly as they are * supported by IBM Connections like ps, sortBy etc. */ getFilesSharedByMe : function(args) { var options = { method : "GET", handleAs : "text", query : lang.mixin({ direction : "outbound" }, args ? args : {}) }; return this.getEntities(consts.AtomFilesShared, options, this.getFileFeedCallbacks()); }, /** * Get public files from IBM Connections * * @method getPublicFiles * @param {Object} [args] Argument object. Object representing various parameters that can be passed. The parameters must be exactly as they are * supported by IBM Connections like ps, sortBy etc. */ getPublicFiles : function(args) { var options = { method : "GET", handleAs : "text", query : args || {}, headers : {} }; return this.getEntities(consts.AtomFilesPublic, options, this.getFileFeedCallbacks()); }, /** * Get my folders from IBM Connections * * @method getMyFolders * @param {Object} [args] Argument object. Object representing various parameters that can be passed. The parameters must be exactly as they are * supported by IBM Connections like ps, sortBy etc. */ getMyFolders : function(args) { var options = { method : "GET", handleAs : "text", query : args || {} }; return this.getEntities(consts.AtomFoldersMy, options, this.getFileFeedCallbacks()); }, /** * A feed of comments associated with files to which you have access. You must authenticate this request. * * @method getMyFileComments * @param {Object} [args] Argument object. Object representing various parameters that can be passed. The parameters must be exactly as they are * supported by IBM Connections like ps, sortBy etc. */ getMyFileComments : function(userId, fileId, args) { return this.getFileComments(fileId, userId, false, null, args); }, /** * A feed of comments associated with all public files. Do not authenticate this request. * * @method getPublicFileComments * @param {Object} [args] Argument object. Object representing various parameters that can be passed. The parameters must be exactly as they are * supported by IBM Connections like ps, sortBy etc. */ getPublicFileComments : function(userId, fileId, args) { return this.getFileComments(fileId, userId, true, null, args); }, /** * Adds a comment to the specified file. * * @method addCommentToFile * @param {String} [userId] the userId for the author * @param {String} fileId the ID of the file * @param {String} comment the comment to be added * @param {Object} [args] Argument object. Object representing various parameters that can be passed. The parameters must be exactly as they are * supported by IBM Connections like ps, sortBy etc. */ addCommentToFile : function(userId, fileId, comment, url, args) { var promise = this.validateField("fileId", fileId); if (!promise) { promise = this.validateField("comment", comment); } if (promise) { return promise; } var options = { method : "POST", query : args || {}, headers : consts.AtomXmlHeaders, data : this._constructPayloadForComment(false, comment) }; if (!url) { if (!userId) { url = this.constructUrl(consts.AtomAddCommentToMyFile, null, { documentId : fileId }); } else { url = this.constructUrl(consts.AtomAddCommentToFile, null, { userId : userId, documentId : fileId }); } } return this.updateEntity(url, options, this.getCommentFeedCallbacks()); }, /** * Adds a comment to the specified file of logged in user. * * @method addCommentToMyFile * @param {String} fileId the ID of the file * @param {String} comment the comment to be added * @param {Object} [args] Argument object. Object representing various parameters that can be passed. The parameters must be exactly as they are * supported by IBM Connections like ps, sortBy etc. */ addCommentToMyFile : function(fileId, comment, args) { return this.addCommentToFile(null, fileId, comment, null, args); }, /** * Method to add comments to a Community file <p> Rest API used : /files/basic/api/communitylibrary/<communityId>/document/<fileId>/feed * * @method addCommentToCommunityFile * @param {String} fileId * @param {String} comment * @param {String} communityId * @param {Object} [args] * @return {Comment} comment */ addCommentToCommunityFile : function(fileId, comment, communityId, args) { var url = this.constructUrl(consts.AtomAddCommentToCommunityFile, null, { communityId : communityId, documentId : fileId }); return this.addCommentToFile(null, fileId, comment, url, args); }, /** * Update the Atom document representation of the metadata for a file from logged in user's library. * * @method updateFileMetadata * @param {Object} fileOrJson file or json representing the file to be updated * @param {Object} [args] Argument object. Object representing various parameters that can be passed. The parameters must be exactly as they are * supported by IBM Connections like ps, sortBy etc. */ updateFileMetadata : function(fileOrJson, url, args) { var promise = this.validateField("fileOrJson", fileOrJson); if (promise) { return promise; } var file = this.newFile(fileOrJson); var options = { method : "PUT", query : args || {}, headers : consts.AtomXmlHeaders, data : this._constructPayload(file._fields, file.getFileId()) }; if (!url) { url = this.constructUrl(consts.AtomUpdateFileMetadata, null, { documentId : file.getFileId() }); } return this.updateEntity(url, options, this.getFileFeedCallbacks()); }, /** * Method to update Community File's Metadata <p> Rest API used : /files/basic/api/library/<libraryId>/document/<fileId>/entry <p> * @method updateCommunityFileMetadata * @param {Object} fileOrJson * @param {String} libraryId * @param {Object} [args] * @return {File} */ updateCommunityFileMetadata : function(fileOrJson, communityId, args) { var promise = this.validateField("fileOrJson", fileOrJson); if (promise) { return promise; } var file = this.newFile(fileOrJson); promise = new Promise(); var _this = this; var update = function() { var url = _this.constructUrl(consts.AtomUpdateCommunityFileMetadata, null, { libraryId : file.getLibraryId(), documentId : file.getFileId() }); _this.updateFileMetadata(file, url, args).then(function(file) { promise.fulfilled(file); }, function(error) { promise.rejected(error); }); }; if (file.isLoaded()) { update(); } else { var url = _this.constructUrl(consts.AtomGetCommunityFile, null, { communityId : communityId, documentId : file.getFileId() }); file.load(null, null, url).then(function() { update(); }, function(error) { promise.rejected(error); }); } return promise; }, /** * Pin a file, by sending a POST request to the myfavorites feed. * * @method pinFile * @param {String} fileId ID of file which needs to be pinned * @param {Object} [args] Argument object. */ pinFile : function(fileId, args) { var promise = this.validateField("fileId", fileId); if (promise) { return promise; } var parameters = args ? lang.mixin({}, args) : {}; parameters["itemId"] = fileId; var options = { method : "POST", headers : { "X-Update-Nonce" : "{X-Update-Nonce}" }, query : parameters }; var callbacks = { createEntity : function(service, data, response) { return "Success"; } }; return this.updateEntity(consts.AtomPinFile, options, callbacks); }, /** * Unpin a file, by sending a DELETE request to the myfavorites feed. * * @method unpinFile * @param {String} fileId ID of file which needs to be unpinned * @param {Object} [args] Argument object. */ unpinFile : function(fileId, args) { var promise = this.validateField("fileId", fileId); if (promise) { return promise; } var parameters = args ? lang.mixin({}, args) : {}; parameters["itemId"] = fileId; var options = { method : "DELETE", headers : { "X-Update-Nonce" : "{X-Update-Nonce}" }, query : parameters }; return this.deleteEntity(consts.AtomPinFile, options, fileId); }, /** * Add a file or files to a folder. * * You cannot add a file from your local directory to a folder; the file must already have been uploaded to the Files application. To add a file * to a folder you must be an editor of the folder. * * @method addFilesToFolder * @param {String} folderId the Id of the folder * @param {List} fileIds list of file Ids to be added to the folder * @param {Object} [args] Argument object. */ addFilesToFolder : function(fileIds, folderId, args) { var promise = this.validateField("fileIds", fileIds); if (!promise) { promise = this.validateField("folderId", folderId); } var options = { method : "POST", headers : { "X-Update-Nonce" : "{X-Update-Nonce}" } }; var url = this.constructUrl(consts.AtomAddFilesToFolder, null, { collectionId : folderId }); var separatorChar = "?"; for ( var counter in fileIds) { url += separatorChar + "itemId=" + fileIds[counter]; separatorChar = "&"; } var callbacks = { createEntity : function(service, data, response) { return "Success"; } }; return this.updateEntity(url, options, callbacks); }, /** * Gets the files pinned by the logged in user. * * @method getPinnedFiles * @param {Object} [args] Argument object for the additional parameters like pageSize etc. */ getPinnedFiles : function(args) { var options = { method : "GET", handleAs : "text", query : args || {} }; return this.getEntities(consts.AtomFilesMyPinned, options, this.getFileFeedCallbacks()); }, /** * Delete a file. * * @method deleteFile * @param {String} fileId Id of the file which needs to be deleted * @param {Object} [args] Argument object */ deleteFile : function(fileId, args) { var promise = this.validateField("fileId", fileId); if (promise) { return promise; } var options = { method : "DELETE", headers : { "X-Update-Nonce" : "{X-Update-Nonce}" } }; var url = this.constructUrl(consts.AtomDeleteFile, null, { documentId : fileId }); return this.deleteEntity(url, options, fileId); }, /** * Lock a file * * @method lockFile * @param {String} fileId Id of the file which needs to be locked * @param {Object} [args] Argument object */ lockFile : function(fileId, args) { var parameters = args ? lang.mixin({}, args) : {}; parameters["type"] = "HARD"; var options = { method : "POST", headers : { "X-Update-Nonce" : "{X-Update-Nonce}" }, query : args || {} }; var url = this.constructUrl(consts.AtomLockUnlockFile, parameters, { documentId : fileId }); var callbacks = { createEntity : function(service, data, response) { return "Success"; } }; return this.updateEntity(url, options, callbacks, args); }, /** * unlock a file * * @method lockFile * @param {String} fileId Id of the file which needs to be unlocked * @param {Object} [args] Argument object */ unlockFile : function(fileId, args) { var parameters = args ? lang.mixin({}, args) : {}; parameters["type"] = "NONE"; var options = { method : "POST", headers : { "X-Update-Nonce" : "{X-Update-Nonce}" }, query : args || {} }; var url = this.constructUrl(consts.AtomLockUnlockFile, parameters, { documentId : fileId }); var callbacks = { createEntity : function(service, data, response) { return "Success"; } }; return this.updateEntity(url, options, callbacks, args); }, /** * Uploads a new file for logged in user. * * @method uploadFile * @param {Object} fileControlOrId The Id of html control or the html control * @param {Object} [args] The additional parameters for upload */ uploadFile : function(fileControlOrId, args) { var promise = this.validateField("File Control Or Id", fileControlOrId); if (promise) { return promise; } promise = this.validateHTML5FileSupport(); if (promise) { return promise; } var files = null; if (typeof fileControlOrId == "string") { var fileControl = document.getElementById(fileControlOrId); files = fileControl.files; } else if (typeof fileControlOrId == "object") { files = fileControlOrId.files; } else { return this.createBadRequestPromise("File Control or ID is required"); } if (files.length == 0) { return this.createBadRequestPromise("No files selected for upload"); } var file = files[0]; var data = new FormData(); data.append("file", file); return this.uploadFileBinary(data, file.name, args); }, /** * Uploads a new file for logged in user. * * @method uploadFile * @param {Object} binaryContent The binary content of the file * @param {String} filename The name of the file * @param {Object} [args] The additional parameters of metadata of file for upload like visibility, tag, etc. */ uploadFileBinary : function(binaryContent, fileName, args) { var promise = this.validateField("Binary Content", binaryContent); if (promise) { return promise; } promise = this.validateField("File Name", fileName); if (promise) { return promise; } if (util.getJavaScriptLibrary().indexOf("Dojo 1.4.3") != -1) { return this.createBadRequestPromise("Dojo 1.4.3 is not supported for File upload"); } // /files/<<endpointName>>/<<serviceType>>/<<operation>>/fileName eg. /files/smartcloud/connections/UploadFile/fileName?args var url = this.constructUrl(config.Properties.serviceUrl + "/files/" + this.endpoint.proxyPath + "/" + "connections" + "/" + "UploadFile" + "/" + encodeURIComponent(fileName), args && args.parameters ? args.parameters : {}); var headers = { "Content-Type" : false, "Process-Data" : false // processData = false is reaquired by jquery }; var options = { method : "POST", headers : headers, query : args || {}, data : binaryContent }; return this.updateEntity(url, options, this.getFileFeedCallbacks()); }, /** * Upload new version of a file. * * @method uploadNewVersion * @param {Object} fileId The ID of the file * @param {Object} fileControlOrId The Id of html control or the html control * @param {Object} [args] The additional parameters ffor updating file metadata */ uploadNewVersion : function(fileId, fileControlOrId, args) { var promise = this.validateField("File Control Or Id", fileControlOrId); if (!promise) { promise = this.validateField("File ID", fileId); } if (promise) { return promise; } promise = this.validateHTML5FileSupport(); if (promise) { return promise; } var files = null; if (typeof fileControlOrId == "string") { var fileControl = document.getElementById(fileControlOrId); filePath = fileControl.value; files = fileControl.files; } else if (typeof fileControlOrId == "object") { filePath = fileControlOrId.value; files = fileControlOrId.files; } else { return this.createBadRequestPromise("File Control or ID is required"); } var file = files[0]; var data = new FormData(); data.append("file", file); return this.uploadNewVersionBinary(data, fileId, file.name, args); }, /** * Uploads new Version of a File. * * @method uploadNewVersionBinary * @param {Object} binaryContent The binary content of the file * @param {String} fileId The ID of the file * @param {Object} [args] The additional parameters for upding file metadata */ uploadNewVersionBinary : function(binaryContent, fileId, fileName, args) { var promise = this.validateField("Binary Content", binaryContent); if (promise) { return promise; } promise = this.validateField("File ID", fileId); if (promise) { return promise; } promise = this.validateField("File Name", fileName); if (promise) { return promise; } if (util.getJavaScriptLibrary().indexOf("Dojo 1.4.3") != -1) { return this.createBadRequestPromise("Dojo 1.4.3 is not supported for File Upload"); } // /files/<<endpointName>>/<<serviceType>>/<<operation>>/fileId?args eg./files/smartcloud/connections/UpdateFile/fileId/fileName?args var url = this.constructUrl(config.Properties.serviceUrl + "/files/" + this.endpoint.proxyPath + "/" + "connections" + "/" + "UploadNewVersion" + "/" + encodeURIComponent(fileId) + "/" + encodeURIComponent(fileName), args && args.parameters ? args.parameters : {}); var headers = { "Content-Type" : false, "Process-Data" : false // processData = false is reaquired by jquery }; var options = { method : "PUT", headers : headers, data : binaryContent }; var promise = new Promise(); var _this = this; this.updateEntity(url, options, this.getFileFeedCallbacks()).then(function(file) { if (args) { _this.updateFile(file.getFileId(), args).then(function(updatedFile) { promise.fulfilled(updatedFile); }); } else { promise.fulfilled(file); } }, function(error) { promise.rejected(error); }); return promise; }, /** * Updates metadata of a file programatically using a PUT call * @param [String] fileId the File ID * @param [Object] args The parameters for update. Supported Input parameters are commentNotification, created, identifier, includePath, * mediaNotification, modified, recommendation, removeTag, sendNotification, sharePermission, shareSummary, shareWith, tag and visibility * @returns */ updateFile : function(fileId, args) { var promise = this.validateField("File ID", fileId); if (promise) { return promise; } var url = this.constructUrl(consts.AtomFileInstance, null, { documentId : fileId }); var separatorChar = "?"; if (args && args.tags) { var tags = args.tags.split(","); for ( var counter in tags) { url += separatorChar + "tag=" + stringUtil.trim(tags[counter]); separatorChar = "&"; } delete args.tags; } if (args && args.removeTags) { var removeTags = args.removeTags.split(","); for ( var counter in removeTags) { url += separatorChar + "removeTag=" + stringUtil.trim(removeTags[counter]); separatorChar = "&"; } delete args.removeTags; } var options = { method : "PUT", headers : { "X-Update-Nonce" : "{X-Update-Nonce}" }, query : args || {} }; return this.updateEntity(url, options, this.getFileFeedCallbacks()); }, /** * Downloads a file. * * @method downloadFile * @param {String} fileId The ID of the file * @param {String} libraryId The library ID of the file */ downloadFile : function(fileId, libraryId) { var url = config.Properties.serviceUrl + "/files/" + this.endpoint.proxyPath + "/" + "connections" + "/" + "DownloadFile" + "/" + fileId + "/" + libraryId; window.open(url); }, actOnCommentAwaitingApproval : function(commentId, action, actionReason) { }, actOnFileAwaitingApproval : function(fileId, action, actionReason) { }, /** * Add a file to a folder or list of folders. * * You cannot add a file from your local directory to a folder; the file must already have been uploaded to the Files application. To add a file * to a folder you must be an editor of the folder. * * @method addFilesToFolder * @param {String} fileId the Id of the file * @param {List} folderIds list of folder Ids * @param {String} [userId] the userId of the user in case of own file * @param {Object} [args] Argument object. */ addFileToFolders : function(fileId, folderIds, userId, args) { var promise = this.validateField("fileId", fileId); if (!promise) { promise = this.validateField("folderIds", folderIds); } if (promise) { return promise; } var url = null; if (!userId) { url = this.constructUrl(consts.AtomAddMyFileToFolders, null, { documentId : fileId }); } else { url = this.constructUrl(consts.AtomAddFileToFolders, null, { userId : userId, documentId : fileId }); } var payload = this._constructPayloadForMultipleEntries(folderIds, "itemId", "collection"); var options = { method : "POST", headers : consts.AtomXmlHeaders, data : payload }; var callbacks = { createEntity : function(service, data, response) { } }; return this.updateEntity(url, options, callbacks); }, /** * Create a new Folder * * @method createFolder <p> Rest API used : /files/basic/api/collections/feed * * @param {String} name name of the folder to be created * @param {String} [description] description of the folder * @param {String} [shareWith] If the folder needs to be shared, specify the details in this parameter. <br> Pass Coma separated List of id, * (person/community/group) or role(reader/Contributor/owner) in order * @return {Object} Folder */ createFolder : function(name, description, shareWith) { var promise = this.validateField("folderName", name); if (promise) { return promise; } var url = consts.AtomCreateFolder; var payload = this._constructPayloadFolder(name, description, shareWith, "create"); var options = { method : "POST", headers : lang.mixin(consts.AtomXmlHeaders, { "X-Update-Nonce" : "{X-Update-Nonce}" }), data : payload }; return this.updateEntity(url, options, this.getFileFeedCallbacks()); }, /** * Delete Files From Recycle Bin * * @param {String} userId The ID of user */ deleteAllFilesFromRecycleBin : function(userId) { var url = null; if (!userId) { url = consts.AtomDeleteMyFilesFromRecyclebBin; } else { url = this.constructUrl(consts.AtomDeleteAllFilesFromRecyclebBin, null, { userId : userId }); } var options = { method : "DELETE" }; return this.deleteEntity(url, options, ""); }, /** * Delete all Versions of a File before the given version * * @param {String} fileId the ID of the file * @param {String} [versionLabel] The version from which all will be deleted * @param {Object} [args] additional arguments */ deleteAllVersionsOfFile : function(fileId, versionLabel, args) { var promise = this.validateField("fileId", fileId); if (!promise) { promise = this.validateField("versionLabel", versionLabel); } if (promise) { return promise; } var requestArgs = lang.mixin({ category : "version", deleteFrom : versionLabel }, args || {}); var options = { method : "DELETE", query : requestArgs, headers : { "X-Update-Nonce" : "{X-Update-Nonce}" } }; var url = this.constructUrl(consts.AtomDeleteAllVersionsOfAFile, null, { documentId : fileId }); return this.deleteEntity(url, options, fileId); }, /** * Delete a Comment for a file * * @param {String} fileId the ID of the file * @param {String} commentId the ID of comment * @param {String} [userId] the ID of the user, if not provided logged in user is assumed * @param {Object} [args] the additional arguments */ deleteComment : function(fileId, commentId, userId, args) { var promise = this.validateField("fileId", fileId); if (!promise) { promise = this.validateField("commentId", commentId); } if (promise) { return promise; } var url = null; if (userId) { url = this.constructUrl(consts.AtomDeleteComment, null, { userId : userId, documentId : fileId, commentId : commentId }); } else { url = this.constructUrl(consts.AtomDeleteMyComment, null, { documentId : fileId, commentId : commentId }); } var options = { method : "DELETE", query : args || {}, headers : { "X-Update-Nonce" : "{X-Update-Nonce}" } }; return this.deleteEntity(url, options, commentId); }, /** * Delete File from RecycleBin of a user * @param {String} fileId the Id of the file * @param {String} [userId] the Id of the user * @param {Object} args the additional arguments * @returns */ deleteFileFromRecycleBin : function(fileId, userId, args) { var promise = this.validateField("fileId", fileId); if (promise) { return promise; } var url = null; if (userId) { url = this.constructUrl(consts.AtomDeleteFileFromRecycleBin, null, { userId : userId, documentId : fileId }); } else { url = this.constructUrl(consts.AtomDeleteMyFileFromRecycleBin, null, { documentId : fileId }); } var options = { method : "DELETE", query : args || {}, headers : { "X-Update-Nonce" : "{X-Update-Nonce}" } }; return this.deleteEntity(url, options, fileId); }, /** * deletes a File Share * @param {String} fileId the ID of the file * @param {String} userId the ID of the user * @param {Object} args the additional arguments */ deleteFileShare : function(fileId, userId, args) { var promise = this.validateField("fileId", fileId); if (promise) { return promise; } var requestArgs = lang.mixin({ sharedWhat : fileId }, args || {}); if (userId) { requestArgs.sharedWith = userId; } var url = consts.AtomDeleteFileShare; var options = { method : "DELETE", query : requestArgs, headers : { "X-Update-Nonce" : "{X-Update-Nonce}" } }; return this.deleteEntity(url, options, fileId); }, /** * Deletes a Folder * @param {String} folderId the ID of the folder */ deleteFolder : function(folderId) { var promise = this.validateField("folderId", folderId); if (promise) { return promise; } var options = { method : "DELETE", headers : { "X-Update-Nonce" : "{X-Update-Nonce}" } }; var url = this.constructUrl(consts.AtomDeleteFFolder, null, { collectionId : folderId }); return this.deleteEntity(url, options, folderId); }, /** * Get all user Files * @param {String} userId the ID of the user * @param {Object} args the addtional arguments * @returns {Object} Files */ getAllUserFiles : function(userId, args) { var promise = this.validateField("userId", userId); if (promise) { return promise; } var options = { method : "GET", handleAs : "text", query : args || {} }; var url = this.constructUrl(consts.AtomGetAllUsersFiles, null, { userId : userId }); return this.getEntities(url, options, this.getFileFeedCallbacks()); }, /** * Get file Comments * @param {String} fileId the ID of the file * @param {String} [userId] the ID of the user * @param {Boolean} [isAnnonymousAccess] flag to indicate annonymous access * @param {String} [commentId] the ID of the comment * @param {String} [communityId] required in case the file in a community file * @param {Object} args the additional arguments * @returns {Array} Comments List */ getFileComments : function(fileId, userId, isAnnonymousAccess, commentId, communityId, args) { var promise = this.validateField("fileId", fileId); if (promise) { return promise; } var url = null; if(communityId){ url = this.constructUrl(consts.AtomAddCommentToCommunityFile, null, { communityId : communityId, documentId : fileId }); } else if (commentId) { if (userId) { url = this.constructUrl(consts.AtomGetFileComment, null, { userId : userId, documentId : fileId, commentId : commentId }); } else { url = this.constructUrl(consts.AtomGetMyFileComment, null, { documentId : fileId, commentId : commentId }); } } else { var promise = this.validateField("userId", userId); if (promise) { return promise; } if (isAnnonymousAccess) { url = this.constructUrl(consts.AtomFileCommentsPublic, null, { userId : userId, documentId : fileId }); } else { url = this.constructUrl(consts.AtomFileCommentsMy, null, { userId : userId, documentId : fileId }); } } var options = { method : "GET", handleAs : "text", query : args || {} }; return this.getEntities(url, options, this.getCommentFeedCallbacks()); }, /** * Method to get All comments of a Community File * <p> * Rest API Used : * /files/basic/api/communitylibrary/<communityId>/document/<fileId>/feed * <p> * @method getAllCommunityFileComments * @param {String} fileId * @param {String} communityId * @param {Object} [args] * @returns {Array} comments */ getAllCommunityFileComments : function(fileId, communityId, args) { var promise = this.validateField("fileId", fileId); if(!promise){ promise = this.validateField("communityId", communityId); } if (promise) { return promise; } return this.getFileComments(fileId, null, null, null, communityId, args); }, /** * Get Files from recycle bin * @param {Object} [args] the additional arguments * @returns {Object} Files */ getFileFromRecycleBin : function(fileId, userId, args) { var promise = this.validateField("fileId", fileId); if (promise) { return promise; } var options = { method : "GET", handleAs : "text", query : args || {} }; var url = this.constructUrl(consts.AtomGetFileFromRecycleBin, null, { userId : userId, documentId : fileId }); var callbacks = { createEntity : function(service, data, response) { self.dataHandler = new XmlDataHandler({ data : data, namespaces : consts.Namespaces, xpath : consts.FileXPath }); return self; } }; return this.getEntity(url, options, callbacks); }, /** * Get Files awaiting approval * @param {Object} [args] the additional arguments * @returns {Object} Files */ getFilesAwaitingApproval : function(args) { var options = { method : "GET", handleAs : "text", query : args || {} }; return this.getEntities(consts.AtomGetFilesAwaitingApproval, options, this.getFileFeedCallbacks()); }, /** * Get File Shares * @param {Object} [args] the additional arguments * @returns {Object} Files */ getFileShares : function(args) { var options = { method : "GET", handleAs : "text", query : args || {} }; return this.getEntities(consts.AtomGetFileShares, options, this.getFileFeedCallbacks()); }, /** * Get Files in a folder * @param {String} folderId the ID of the folder * @param {Object} [args] the additional arguments * @returns {Object} Files */ getFilesInFolder : function(folderId, args) { var url = this.constructUrl(consts.AtomGetFilesInFolder, null, { collectionId : folderId }); var options = { method : "GET", handleAs : "text", query : args || {} }; return this.getEntities(url, options, this.getFileFeedCallbacks()); }, /** * Get Files in my recycle bin * @param {Object} [args] the addtional arguments * @returns */ getFilesInMyRecycleBin : function(args) { var options = { method : "GET", handleAs : "text", query : args || {} }; return this.getEntities(consts.AtomGetFilesInMyRecycleBin, options, this.getFileFeedCallbacks()); }, /** * Get a file with given version * @param {String} fileId the ID of the file * @param {String} versionId the ID of the version * @param {Object} [args] the additional arguments * @returns {Object} File */ getFileWithGivenVersion : function(fileId, versionId, args) { var promise = this.validateField("fileId", fileId); if (promise) { return promise; } if (!versionId) { return this.getFile(fileId, args); } var options = { method : "GET", handleAs : "text", query : args || {} }; var url = this.constructUrl(consts.AtomGetFileWithGivenVersion, null, { documentId : fileId, versionId : versionId }); var callbacks = { createEntity : function(service, data, response) { self.dataHandler = new XmlDataHandler({ data : data, namespaces : consts.Namespaces, xpath : consts.FileXPath }); return self; } }; return this.getEntity(url, options, callbacks); }, /** * Get a folder * @param {String} folderId the ID of the folder * @returns */ getFolder : function(folderId) { var promise = this.validateField("folderId", folderId); if (promise) { return promise; } var options = { method : "GET", handleAs : "text" }; var url = this.constructUrl(consts.AtomGetFolder, null, { collectionId : folderId }); var callbacks = { createEntity : function(service, data, response) { self.dataHandler = new XmlDataHandler({ data : data, namespaces : consts.Namespaces, xpath : consts.FileXPath }); return self; } }; return this.getEntity(url, options, callbacks); }, /** * Get Folders With Recently Added Files * @param {Object} [args] the additional arguents * @returns {Object} List of Files */ getFoldersWithRecentlyAddedFiles : function(args) { var options = { method : "GET", handleAs : "text", query : args || {} }; return this.getEntities(consts.AtomGetFoldersWithRecentlyAddedFiles, options, this.getFileFeedCallbacks()); }, /** * Gets the folders pinned by the logged in user. * * @method getPinnedFolders * @param {Object} [args] Argument object for the additional parameters like pageSize etc. */ getPinnedFolders : function(args) { var options = { method : "GET", handleAs : "text", query : args || {} }; return this.getEntities(consts.AtomGetPinnedFolders, options, this.getFileFeedCallbacks()); }, /** * Get public folders * * @param {Object} [args] Additional arguments like ps, sort by, etc */ getPublicFolders : function(args) { var options = { method : "GET", handleAs : "text", query : args || {} }; return this.getEntities(consts.AtomGetPublicFolders, options, this.getFileFeedCallbacks()); }, /** * Pin a folder, by sending a POST request to the myfavorites feed. * * @method pinFolder * @param {String} folderId ID of folder which needs to be pinned * @param {Object} [args] Argument object. */ pinFolder : function(folderId, args) { var promise = this.validateField("folderId", folderId); if (promise) { return promise; } var parameters = args ? lang.mixin({}, args) : {}; parameters["itemId"] = folderId; var options = { method : "POST", headers : { "X-Update-Nonce" : "{X-Update-Nonce}" }, query : parameters }; var callbacks = { createEntity : function(service, data, response) { } }; return this.updateEntity(consts.AtomPinFolder, options, callbacks); }, /** * Remove a File from a Folder * * @param {String} folderId the ID of the folder * @param {Stirng} fileId The ID of the File */ removeFileFromFolder : function(folderId, fileId) { var promise = this.validateField("folderId", folderId); if (promise) { return promise; } promise = this.validateField("fileId", fileId); if (promise) { return promise; } var parameters = args ? lang.mixin({}, args) : {}; parameters["itemId"] = fileId; var url = this.constructUrl(consts.AtomRemoveFileFromFolder, null, { collectionId : folderId }); var options = { method : "DELETE", headers : { "X-Update-Nonce" : "{X-Update-Nonce}" }, query : parameters }; return this.deleteEntity(url, options, fileId); }, /** * Restore a File from Recycle Bin (trash) * * @param {String} fileId the ID of the file * @param {String} userId the ID of the user */ restoreFileFromRecycleBin : function(fileId, userId) { var promise = this.validateField("fileId", fileId); if (promise) { return promise; } promise = this.validateField("userId", userId); if (promise) { return promise; } var parameters = args ? lang.mixin({}, args) : {}; parameters["undelete"] = "true"; var options = { method : "POST", headers : { "X-Update-Nonce" : "{X-Update-Nonce}" }, query : parameters }; var callbacks = { createEntity : function(service, data, response) { self.dataHandler = new XmlDataHandler({ data : data, namespaces : consts.Namespaces, xpath : consts.FileXPath }); return self; } }; var url = this.constructUrl(consts.AtomRestoreFileFromRecycleBin, null, { userId : userId, documentId : fileId }); return this.updateEntity(url, options, callbacks); }, /** * Share a File with community(ies) * * @param {String} fileId the ID of the file * @param {Object} communityIds The list of community IDs * @param {Object} args the additional arguments */ shareFileWithCommunities : function(fileId, communityIds, args) { var promise = this.validateField("fileId", fileId); if (!promise) { promise = this.validateField("communityIds", communityIds); } if (promise) { return promise; } var url = this.constructUrl(consts.AtomShareFileWithCommunities, null, { documentId : fileId }); var payload = this._constructPayloadForMultipleEntries(communityIds, "itemId", "community"); var options = { method : "POST", headers : consts.AtomXmlHeaders, data : payload }; var callbacks = { createEntity : function(service, data, response) { return response; } }; return this.updateEntity(url, options, callbacks); }, /** * Unpin a folder, by sending a DELETE request to the myfavorites feed. * * @method unpinFolder * @param {String} folderId ID of folder which needs to be unpinned * @param {Object} [args] Argument object. */ unpinFolder : function(folderId, args) { var promise = this.validateField("folderId", folderId); if (promise) { return promise; } var parameters = args ? lang.mixin({}, args) : {}; parameters["itemId"] = folderId; var options = { method : "DELETE", headers : { "X-Update-Nonce" : "{X-Update-Nonce}" }, query : parameters }; return this.deleteEntity(consts.AtomPinFolder, options, folderId); }, /** * Update comment created by logged in user * @param {String} fileId the ID of the file * @param {String}commentId the ID of the comment * @param {String} comment the updated comment * @param {Object} args the additional arguments * @returns */ updateMyComment : function(fileId, commentId, comment, args) { return updateComment(fileId, commentId, comment, null, args); }, /** * updates a comment * @param {String} fileId the ID of the file * @param {String} commentId the ID of the comment * @param {String} comment the comment * @param {String} [userId] the ID of the user * @param {Object} [args] the additional arguments * @returns {Object} the updated Comment */ updateComment : function(fileId, commentId, comment, userId, args) { var promise = this.validateField("fileId", fileId); if (!promise) { promise = this.validateField("comment", comment); } if (promise) { return promise; } if (!promise) { promise = this.validateField("commentId", commentId); } if (promise) { return promise; } var options = { method : "POST", query : args || {}, headers : consts.AtomXmlHeaders, data : this._constructPayloadForComment(false, comment) }; var url = null; if (!userId) { url = this.constructUrl(consts.AtomUpdateMyComment, null, { documentId : fileId, commentId : commentId }); } else { url = this.constructUrl(consts.AtomUpdateComment, null, { userId : userId, documentId : fileId, commentId : commentId }); } return this.updateEntity(url, options, this.getCommentFeedCallbacks()); }, /** * Add a file to a folder. * * You cannot add a file from your local directory to a folder; the file must already have been uploaded to the Files application. To add a file * to a folder you must be an editor of the folder. * * @method addFileToFolder * @param {String} fileId the Id of the file * @param {String} folderId the ID of the folder * @param {String} [userId] the userId of the user in case of own file * @param {Object} [args] Argument object. */ addFileToFolder : function(fileId, folderId, userId, args) { return this.addFileToFolders(fileId, [ folderId ], userId, args); }, /* * Callbacks used when reading a feed that contains File entries. */ getFileFeedCallbacks : function() { return FileFeedCallbacks; }, /* * Callbacks used when reading a feed that contains File Comment entries. */ getCommentFeedCallbacks : function() { return CommentCallbacks; }, _constructPayloadFolder : function(name, description, shareWith, operation, entityId) { var _this = this; var shareWithId = null; var shareWithWhat = null; var shareWithRole = null; if (shareWith && stringUtil.trim(shareWith) != "") { var parts = shareWith.split(","); if (parts.length == 3) { shareWithId = parts[0]; shareWithWhat = parts[1]; shareWithRole = parts[2]; } } var trans = function(value, key) { if (key == "category") { value = xml.encodeXmlEntry("collection"); } else if (key == "id") { value = xml.encodeXmlEntry(entityId); } else if (key == "label") { value = xml.encodeXmlEntry(name); } else if (key == "title") { value = xml.encodeXmlEntry(name); } else if (key == "summary") { value = xml.encodeXmlEntry(description); } else if (key == "visibility") { value = xml.encodeXmlEntry("private"); } else if (key == "shareWithId" && shareWithId) { value = xml.encodeXmlEntry(shareWithId); } else if (key == "shareWithWhat" && shareWithWhat) { value = xml.encodeXmlEntry(shareWithWhat); } else if (key == "shareWithRole" && shareWithRole) { value = xml.encodeXmlEntry(shareWithRole); } return value; }; var transformer = function(value, key) { if (key == "getCategory") { value = stringUtil.transform(FileCategoryTmpl, _this, trans, _this); } else if (key == "getId" && entityId) { value = stringUtil.transform(FileIdTmpl, _this, trans, _this); } else if (key == "getFolderLabel") { value = stringUtil.transform(FolderLabelTmpl, _this, trans, _this); } else if (key == "getTitle") { value = stringUtil.transform(FileTitleTmpl, _this, trans, _this); } else if (key == "getSummary") { value = stringUtil.transform(FileSummaryTmpl, _this, trans, _this); } else if (key == "getVisibility") { value = stringUtil.transform(FileVisibilityTmpl, _this, trans, _this); } else if (key == "getVisibilityShare" && shareWithId) { value = stringUtil.transform(FileVisibilityShareTmpl, _this, trans, _this); } return value; }; var postData = stringUtil.transform(FolderTmpl, this, transformer, this); return stringUtil.trim(postData); }, _constructPayloadForMultipleEntries : function(listOfIds, multipleEntryId, category) { var payload = FileFeedTmpl; var entriesXml = ""; var categoryXml = ""; var itemXml = ""; var currentId = ""; var transformer = function(value, key) { if (key == "category") { value = xml.encodeXmlEntry(category); } else if (key == "getCategory") { value = categoryXml; } else if (key == "fileId") { value = xml.encodeXmlEntry(currentId); } else if (key == "getItem") { value = itemXml; } else if (key == "getEntries") { value = entriesXml; } return value; }; var _this = this; for ( var counter in listOfIds) { currentId = listOfIds[counter]; var entryXml = FileItemEntryTmpl; if (category) { categoryXml = stringUtil.transform(FileCategoryTmpl, _this, transformer, _this); } itemXml = stringUtil.transform(FileItemIdTmpl, _this, transformer, _this); entryXml = stringUtil.transform(entryXml, _this, transformer, _this); entriesXml = entriesXml + entryXml; } if (entriesXml != "") { payload = stringUtil.transform(payload, _this, transformer, _this); } return payload; }, _constructPayloadForComment : function(isDelete, comment) { var payload = FileCommentsTmpl; var categoryXml = ""; var contentXml = ""; var deleteXml = ""; var _this = this; var transformer = function(value, key) { if (key == "category") { value = xml.encodeXmlEntry("comment"); } else if (key == "content") { value = xml.encodeXmlEntry(comment); } else if (key == "deleteWithRecord") { value = "true"; } else if (key == "getCategory" && categoryXml != "") { value = categoryXml; } else if (key == "getContent" && contentXml != "") { value = contentXml; } else if (key == "getDeleteComment" && deleteXml != "") { value = deleteXml; } return value; }; categoryXml = stringUtil.transform(FileCategoryTmpl, _this, transformer, _this); contentXml = stringUtil.transform(FileContentTmpl, _this, transformer, _this); if (isDelete) { deleteXml = stringUtil.transform(FileDeleteCommentTmpl, _this, transformer, _this); } payload = stringUtil.transform(payload, this, transformer, this); return payload; }, _constructPayload : function(payloadMap, documentId) { var payload = FileEntryTmpl; var categoryXml = ""; var idXml = ""; var uuidXml = ""; var labelXml = ""; var titleXml = ""; var summaryXml = ""; var visibilityXml = ""; var itemXml = ""; var tagsXml = ""; var notificationXml = ""; var currentValue = null; var transformer = function(value, key) { if (currentValue) { value = xml.encodeXmlEntry(currentValue); } else if (key == "getCategory" && categoryXml != "") { value = categoryXml; } else if (key == "getId" && idXml != "") { value = idXml; } else if (key == "getUuid" && uuidXml != "") { value = uuidXml; } else if (key == "getLabel" && labelXml != "") { value = labelXml; } else if (key == "getTitle" && titleXml != "") { value = titleXml; } else if (key == "getSummary" && summaryXml != "") { value = summaryXml; } else if (key == "getVisibility" && visibilityXml != "") { value = visibilityXml; } else if (key == "getItem" && itemXml != "") { value = itemXml; } else if (key == "getTags" && tagsXml != "") { value = tagsXml; } else if (key == "getNotification" && notificationXml != "") { value = notificationXml; } return value; }; for ( var currentElement in payloadMap) { currentValue = payloadMap[currentElement]; if (currentElement.indexOf("category") != -1) { categoryXml = stringUtil.transform(FileCategoryTmpl, this, transformer, this); } else if (currentElement.indexOf("id") != -1) { idXml = stringUtil.transform(FileIdTmpl, this, transformer, this); } else if (currentElement.indexOf("uuid") != -1) { uuidXml = stringUtil.transform(FileUuidTmpl, this, transformer, this); } else if (currentElement.indexOf("label") != -1) { labelXml = stringUtil.transform(FileLabelTmpl, this, transformer, this); titleXml = stringUtil.transform(FileTitleTmpl, this, transformer, this); } else if (currentElement.indexOf("summary") != -1) { summaryXml = stringUtil.transform(FileSummaryTmpl, this, transformer, this); } else if (currentElement.indexOf("visibility") != -1) { visibilityXml = stringUtil.transform(FileVisibilityTmpl, this, transformer, this); } else if (currentElement.indexOf("itemId") != -1) { itemXml = stringUtil.transform(FileItemIdTmpl, this, transformer, this); } else if (currentElement.indexOf("tags") != -1) { var tags = currentValue; for ( var tag in tags) { tagsXml += stringUtil.transform(TagsTmpl, { "tag" : tags[tag] }); } } else if (currentElement.contains("notification")) { notificationXml = stringUtil.transform(NotificationTmpl, this, transformer, this); } } currentValue = null; payload = stringUtil.transform(payload, this, transformer, this); return payload; } }); return FileService; }); }, 'sbt/authenticator/SSO':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. * Definition of an authentication mechanism. */ define(["../declare", "../lang", "../util", "../i18n!../nls/messageSSO"],function(declare, lang, util, ssoMessages) { /** * Proxy SSO authentication. * * This class triggers the authentication for a service. */ return declare(null, { loginUi: "", messageSSO: "/sbt/authenticator/templates/MessageSSO.html", dialogMessageSSO: "authenticator/templates/MessageDialogSSO.html", url: "", constructor: function(args){ lang.mixin(this, args || {}); }, authenticate: function(options) { var self = this; require(['sbt/config'], function(config){ var mode = options.loginUi || config.Properties["loginUi"] || self.loginUi; var messagePage = options.messageSSO || config.Properties["messageSSO"] || self.messageSSO; var dialogMessagePage = options.dialogMessageSSO || config.Properties["dialogMessageSSO"] || self.dialogMessageSSO; if(mode=="popup") { self._authPopup(options, messagePage, self.url); } else if(mode=="dialog") { self._authDialog(options, dialogMessagePage); } else { self._authMainWindow(options, messagePage, self.url); } }); return true; }, _authPopup: function(options, messagePage, sbtUrl) { var urlParamsMap = { loginUi: 'popup' }; var urlParams = util.createQuery(urlParamsMap, "&"); var url = sbtUrl+messagePage + '?' + urlParams; var windowParamsMap = { width: window.screen.availWidth / 2, height: window.screen.availHeight / 2, left: window.screen.availWidth / 4, top: window.screen.availHeight / 4, menubar: 0, toolbar: 0, status: 0, location: 0, scrollbars: 1, resizable: 1 }; var windowParams = util.createQuery(windowParamsMap, ","); var loginWindow = window.open(url,'Authentication', windowParams); loginWindow.globalSSOStrings = ssoMessages; loginWindow.globalEndpointAlias = options.name; loginWindow.focus(); return true; }, _authDialog: function(options, dialogLoginPage) { require(["sbt/_bridge/ui/SSO_Dialog", "sbt/dom"], function(dialog, dom) { dialog.show(options, dialogLoginPage, ssoMessages); dom.setText('reloginMessage', ssoMessages.message); dom.setAttr(dom.byId('ssoLoginFormOK'), "value", ssoMessages.relogin_button_text); }); return true; }, _authMainWindow: function(options, loginPage, sbtUrl) { var urlParamsMap = { redirectURL: document.URL, loginUi: 'mainWindow', message_title: ssoMessages.message_title, message: ssoMessages.message, relogin_button_text: ssoMessages.relogin_button_text }; var urlParams = util.createQuery(urlParamsMap, "&"); var url = sbtUrl+loginPage + '?' + urlParams; var loginWindow = window.location.href = url; return true; } } ); }); }, 'sbt/nls/validate':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK - Default resource bundle for validate module. */ define({ root: ({ error_callback:"Error running error callback : {0}", error_console:"Error received. Error Code = {0}. Error Message = {1}", validate_nullObject:"{0}.{1} : Null argument provided for {2}. Expected type is {3}", validate_expectedType:"{0}.{1} : {2} argument type does not match expected type {3} for {4}" }) }); }, 'sbt/emailService':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Provides functionality to send emails. * * @module sbt.emailService */ define(['./declare', './lang', './config', './_bridge/Transport', './json'], function(declare, lang, config, Transport, sbtJson) { var transport = new Transport(); return { /** * Sends an email. * @method send * @static * @param {Object || Array} email The JSON object representing the email to send. * @return {sbt.Promise} A promise to fulfill the send. * * @example * var emails = * [ * { * "from" : "sdary@renovations.com", * "to" : ["fadams@renovations.com", "tamado@renovations.com"], * "cc" : ["pclemmons@renovations.com"], * "bcc" : [], * "subject" : "This is a test email", * "mimeParts" : * [ * { * "mimeType" : "text/plain", * "content" : "This is plain text", * "headers" : * { * "header1":"value1", * "header2":"value2" * } * }, * { * "mimeType" : "text/html", * "content" : "<b>This is html</b>" * }, * { * "mimeType" : "application/embed+json", * "content" : { * "gadget" : "http://renovations.com/gadget.xml", * "context" : { * "foo" : "bar" * } * } * } * ] * }, * { * "from" : "sdaryn@renovations.com", * "to" : ["fadams@renovations.com", "tamado@renovations.com"], * "subject": "This is a test email", * "mimeParts" : * [ * { * "mimeType" : "text/plain", * "content" : "This is plain text" * }, * { * "mimeType" : "text/html", * "content" : "<b>This is html</b>" * } * ] * } * ]; * var successCallback = function(response) { * //If you send multiple emails, for example emails is an array of email objects, * //than it is possible that some emails succeeded being sent while others may have * //failed. It is good practice to check for any emails that had errors being sent. * if(response.error && response.error.length != 0) { * //There was one of more errors with emails sent, handle them * } * * if(response.successful && response.successful.length > 0) { * //Some or all of your emails were successfully sent * } * }; * * var errorCallback = function(error) { * //This callback will only be called if there was an error in the request * //being made to the server. It will NOT be called if there are errors * //with any of the emails being sent. * if(error.message) { * //The request failed handle it. * } * }; * * email.send(emails).then(successCallback, errorCallback); */ send : function(emails) { var postUrl = config.Properties.serviceUrl + '/mailer'; var options = { method: "POST", data: sbtJson.stringify(emails), headers: {"Content-Type" : "application/json"}, handleAs: "json" }; return transport.request(postUrl, options); } }; }); }, 'sbt/main':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an AS IS BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * @module sbt.main */ define([ 'sbt/Cache', 'sbt/DebugTransport', 'sbt/Endpoint', 'sbt/ErrorTransport', 'sbt/Gadget', 'sbt/GadgetTransport', 'sbt/IWidget', 'sbt/Jsonpath', 'sbt/MockTransport', 'sbt/Portlet', 'sbt/Promise', 'sbt/Proxy', 'sbt/_config', 'sbt/compat', 'sbt/config', 'sbt/declare', 'sbt/defer', 'sbt/dom', 'sbt/emailService', 'sbt/i18n', 'sbt/itemFactory', 'sbt/json', 'sbt/lang', 'sbt/log', 'sbt/pathUtil', 'sbt/ready', 'sbt/stringUtil', 'sbt/text', 'sbt/url', 'sbt/util', 'sbt/validate', 'sbt/xml', 'sbt/xpath', 'sbt/xsl', 'sbt/WPSProxy', 'sbt/authenticator/Basic', 'sbt/authenticator/GadgetOAuth', 'sbt/authenticator/OAuth', 'sbt/authenticator/SSO', 'sbt/base/AtomEntity', 'sbt/base/BaseConstants', 'sbt/base/BaseEntity', 'sbt/base/BaseService', 'sbt/base/DataHandler', 'sbt/base/JsonDataHandler', 'sbt/base/VCardDataHandler', 'sbt/base/XmlDataHandler', 'sbt/base/core', 'sbt/connections/ActivityConstants', 'sbt/connections/ActivityService', 'sbt/connections/ActivityStreamConstants', 'sbt/connections/ActivityStreamService', 'sbt/connections/BlogConstants', 'sbt/connections/BlogService', 'sbt/connections/BookmarkConstants', 'sbt/connections/BookmarkService', 'sbt/connections/CommunityConstants', 'sbt/connections/CommunityService', 'sbt/connections/ConnectionsConstants', 'sbt/connections/ConnectionsService', 'sbt/connections/FileConstants', 'sbt/connections/FileService', 'sbt/connections/FollowConstants', 'sbt/connections/FollowService', 'sbt/connections/ForumConstants', 'sbt/connections/ForumService', 'sbt/connections/ProfileAdminService', 'sbt/connections/ProfileConstants', 'sbt/connections/ProfileService', 'sbt/connections/SearchConstants', 'sbt/connections/SearchService', 'sbt/connections/Tag', 'sbt/connections/WikiConstants', 'sbt/connections/WikiService', 'sbt/data/AtomReadStore', 'sbt/nls/Endpoint', 'sbt/nls/ErrorTransport', 'sbt/nls/loginForm', 'sbt/nls/messageSSO', 'sbt/nls/util', 'sbt/nls/validate', 'sbt/smartcloud/CommunityConstants', 'sbt/smartcloud/ProfileConstants', 'sbt/smartcloud/ProfileService', 'sbt/smartcloud/SmartcloudConstants', 'sbt/smartcloud/Subscriber', 'sbt/store/AtomStore', 'sbt/store/parameter', 'sbt/authenticator/nls/SSO', 'sbt/authenticator/templates/ConnectionsLogin.html', 'sbt/authenticator/templates/ConnectionsLoginDialog.html', 'sbt/authenticator/templates/Message.html', 'sbt/authenticator/templates/MessageDialogSSO.html', 'sbt/authenticator/templates/MessageSSO.html', 'sbt/authenticator/templates/login.html', 'sbt/authenticator/templates/login', 'sbt/authenticator/templates/loginDialog.html', 'sbt/authenticator/templates/messageSSO', 'sbt/connections/nls/CommunityService', 'sbt/connections/nls/ConnectionsService', 'sbt/connections/nls/ProfileService' ],function() { return; }); }, 'sbt/Proxy':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. * Definition of a proxy re-writer. * * @module sbt.Proxy */ define(['./declare','./lang','./pathUtil'],function(declare,lang,pathUtil) { /** * Definition of the proxy module * * @class sbt.Proxy * */ var Proxy = declare(null, { proxyUrl : null, constructor: function(args){ lang.mixin(this, args); }, rewriteUrl: function(baseUrl,serviceUrl,proxyPath) { // When this proxy is being used, we don't add the base URL as it will be added on the server side // A different implementation might use the full URL var u = serviceUrl; if(this.proxyUrl) { if(u.indexOf("http://")==0) { u = "/http/"+u.substring(7); } else if(u.indexOf("https://")==0) { u = "/https/"+u.substring(8); } if(proxyPath) { u = pathUtil.concat(proxyPath,u); } return pathUtil.concat(this.proxyUrl,u); } return u; } }); return Proxy; }); }, 'sbt/validate':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK - JS Validation Utilities * @module sbt.validate */ define([ "./log", "./stringUtil", "sbt/i18n!sbt/nls/validate","./util" ], function(log, stringUtil, nls, util) { var errorCode = 400; return { /** * Validates Input to be not null and of expected Type * @param {String} [className] class which called this utility * @param {String} [methodName] method which called this utility * @param {String} [fieldName] Name of Field which is being validated * @param {Object} [object] object to be validated * @param {String} [expectedType] expected type of the object * @param {Object} [args] Arguments containing callbacks * @param {Function} [args.error] The error parameter is a callback function that is only invoked when an error occurs. This allows to write * logic when an error occurs. The parameter passed to the error function is a JavaScript Error object indicating what the failure was. From the * error object. one can access the javascript library error object, the status code and the error message. * @param {Function} [args.handle = null] This callback function is called regardless of whether the call to update the file completes or fails. * The parameter passed to this callback is the FileEntry object (or error object). From the error object. one can get access to the javascript * library error object, the status code and the error message. * @static * @method _validateInputTypeAndNotify */ _validateInputTypeAndNotify : function(className, methodName, fieldName, object, expectedType, args) { if (!object || (typeof object == "object" && object.declaredClass && object.declaredClass != expectedType) || (typeof object == "object" && !object.declaredClass && typeof object != expectedType) || (typeof object != "object" && typeof object != expectedType)) { var message; if (!object) { message = stringUtil.substitute(nls.validate_nullObject, [ className, methodName, fieldName, expectedType ]); } else { var actualType; if (typeof object == "object" && object.declaredClass) { actualType = object.declaredClass; } else { actualType = typeof object; } message = stringUtil.substitute(nls.validate_expectedType, [ className, methodName, actualType, expectedType, fieldName ]); } util.notifyError({ code : errorCode, message : message }, args); return false; } return true; }, /** * Validates Input to be not null and of expected Type * @param {String} [className] class which called this utility * @param {String} [methodName] method which called this utility * @param {Object} [fieldNames] List of Names of Fields which are being validated * @param {Object} [objects] List of objects to be validated * @param {Object} [expectedTypes] List of expected types of the objects * @param {Object} [args] Arguments containing callbacks * @param {Function} [args.error] The error parameter is a callback function that is only invoked when an error occurs. This allows to write * logic when an error occurs. The parameter passed to the error function is a JavaScript Error object indicating what the failure was. From the * error object. one can access the javascript library error object, the status code and the error message. * @param {Function} [args.handle = null] This callback function is called regardless of whether the call to update the file completes or fails. * The parameter passed to this callback is the FileEntry object (or error object). From the error object. one can get access to the javascript * library error object, the status code and the error message. * @static * @method _validateInputTypeAndNotify */ _validateInputTypesAndNotify : function(className, methodName, fieldNames, objects, expectedTypes, args) { for ( var counter in objects) { var object = objects[counter]; var expectedType = expectedTypes[counter]; var fieldName = fieldNames[counter]; if (!(this._validateInputTypeAndNotify(className, methodName, fieldName, object, expectedType, args))) { return false; } } return true; } }; }); }, 'sbt/data/AtomReadStore':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * @module sbt.data.AtomReadStore */ define(["../declare","../config", "../lang", "../base/core", "../xml", "../xpath", "../entities"], function(declare, config, lang, core, xml, xpath, entities) { /** * A data store for Atom XML based services or documents. This store is still under development * and doesn't support filtering or paging yet. * * @class AtomReadStore * @namespace sbt.data */ var AtomReadStore = declare(null, { // private _endpoint : null, _xmlData : null, // read only totalResults : 0, startIndex : 0, itemsPerPage : 5, items : null, // public url : "", sendQuery : true, unescapeHTML : false, urlPreventCache : false, atom : core.feedXPath, attributes : core.entryXPath, namespaces : core.namespaces, paramSchema: {}, /** * Constructor for the AtomRead store. * * @param args * An anonymous object to initialize properties. It expects the following values: * url: The url to a service or an XML document that represents the store * unescapeHTML: A boolean to specify whether or not to unescape HTML text * sendQuery: A boolean indicate to add a query string to the service URL * endpoint: the endpoint to be used */ constructor: function(args) { this._endpoint = config.findEndpoint(args.endpoint || "connections"); if (args) { this.url = args.url; this.attributes = args.attributes || this.attributes; this.atom = args.feedXPath || this.atom; this.namespaces = args.namespaces || this.namespaces; this.paramSchema = args.paramSchema || this.paramSchema; this.rewriteUrl = args.rewriteUrl; this.label = args.label || this.label; this.sendQuery = (args.sendQuery || args.sendquery || this.sendQuery); this.unescapeHTML = args.unescapeHTML; if ("urlPreventCache" in args) { this.urlPreventCache = args.urlPreventCache ? true : false; } } if(!this.url) { throw new Error("sbt.data.AtomReadStore: A service URL must be specified when creating the data store"); } }, /** * @method getEndpoint * @returns */ getEndpoint: function() { return this._endpoint; }, setUrl: function(url){ this.url = url; }, getUrl: function(){ return this.url; }, setAttributes: function(attributes){ this.attributes = attributes; }, /* * Returns defaultValue if and only if *item* does not have a value for *attribute*. */ getValue: function(item, attribute, defaultValue) { var xpathCountFunction = /^count\(.*\)$/; this._assertIsItem(item); this._assertIsAttribute(attribute); if (!item._attribs[attribute]) { var access = this.attributes[attribute]; if (lang.isFunction(access)) { item._attribs[attribute] = access(item, attribute); }else if (access.match(xpathCountFunction)){ item._attribs[attribute] = xpath.selectNumber(item.element, this.attributes[attribute], this.namespaces)+""; } else { var nodes = xpath.selectNodes(item.element, this.attributes[attribute], this.namespaces); if (nodes && nodes.length == 1) { item._attribs[attribute] = nodes[0].text || nodes[0].textContent; } else if (nodes) { item._attribs[attribute] = []; for (var j=0; j<nodes.length; j++) { item._attribs[attribute].push(nodes[j].text || nodes[j].textContent); } } else { item._attribs[attribute] = null; } } } if (!item._attribs[attribute]) { return defaultValue; } if(typeof item._attribs[attribute] == "object"){ for(var i=0;i<item._attribs[attribute].length; i++){ item._attribs[attribute][i] = entities.encode(item._attribs[attribute][i]); } } else{ item._attribs[attribute] = entities.encode(item._attribs[attribute]); } return item._attribs[attribute]; }, /* * This getValues() method works just like the getValue() method, but getValues() * always returns an array rather than a single attribute value. */ getValues: function(item, attribute) { this._assertIsItem(item); this._assertIsAttribute(attribute); if (!item._attribs[attribute]) { var nodes = xpath.selectNodes(item.element, this.attributes[attribute], this.namespaces); var values = []; for (var i=0; i<nodes.length; i++) { values[i] = nodes[i].text || nodes[i].textContent; } item._attribs[attribute] = values; } return item._attribs[attribute]; }, /* * Returns an array with all the attributes that this item has. */ getAttributes: function(item) { var result = []; for (var name in this.attributes) { if (this.attributes.hasOwnProperty(name)) { result.push(name); } } return result; }, /* * Returns true if the given *item* has a value for the given attribute*. */ hasAttribute: function(item, attribute) { return (this.attributes[attribute] != undefined); }, /* * Returns true if the given *value* is one of the values that getValues() would return. */ containsValue: function(item, attribute, value) { throw new Error("sbt.data.AtomReadStore: Not implemented yet!"); }, /* * Returns true if *something* is an item and came from the store instance. */ isItem: function(something) { if (something && something.element && something.store && something.store === this) { return true; } return false; }, /* * Return true if *something* is loaded. */ isItemLoaded: function(something) { return this.isItem(something); }, /* * Given an item, this method loads the item so that a subsequent call * to store.isItemLoaded(item) will return true. */ loadItem: function(keywordArgs) { throw new Error("sbt.data.AtomReadStore: Not implemented yet!"); }, /* * Given a query and set of defined options, such as a start and count of items to return, * this method executes the query and makes the results available as data items. */ fetch: function(args) { var self = this; var scope = args.scope || self; var serviceUrl = this._getServiceUrl(this._getQuery(args)); if (!serviceUrl) { if (args.onError) { args.onError.call(new Error("sbt.data.AtomReadStore: No service URL specified.")); } return; } this._endpoint.xhrGet({ serviceUrl : serviceUrl, handleAs : "text", preventCache: true, load : function(response) { try { // parse the data self.response = response; self._xmlData = xml.parse(response); self.totalResults = parseInt(xpath.selectText(self._xmlData, self.atom.totalResults, self.namespaces)); self.startIndex = parseInt(xpath.selectText(self._xmlData, self.atom.startIndex, self.namespaces)); self.itemsPerPage = parseInt(xpath.selectText(self._xmlData, self.atom.itemsPerPage, self.namespaces)); self.items = self._createItems(self._xmlData); // invoke callbacks if (args.onBegin) { args.onBegin.call(scope, self.totalResults, args); } if (args.onItem) { for(var i=0; i<self._entries; i++){ args.onItem.call(scope, self.entries[i], args); } } if (args.onComplete) { args.onComplete.call(scope, args.onItem ? null : self.items, args); } } catch (e) { if (args.onError) { args.onError.call(e); } } }, error : function(error) { if (args.onError) { args.onError.call(error); } } }); }, /* * The getFeatures() method returns an simple keyword values object * that specifies what interface features the datastore implements. */ getFeatures: function() { return { 'dojo.data.api.Read': true }; }, /* * The close() method is intended for instructing the store to 'close' out * any information associated with a particular request. */ close: function(request) { throw new Error("sbt.data.AtomReadStore: Not implemented yet!"); }, /* * Method to inspect the item and return a user-readable 'label' for the item * that provides a general/adequate description of what the item is. */ getLabel: function(item) { return this.getValue(item, this.label); }, /* * Method to inspect the item and return an array of what attributes of the item were used * to generate its label, if any. */ getLabelAttributes: function(item) { return [ this.label ]; }, // Internals _getQuery: function(args) { var query = args.query || {}; query.pageSize = args.count || query.pageSize; var page = Math.floor(args.start / args.count) + 1; // needs to be a whole number query.pageNumber = page; if(args.sort && args.sort[0]) { var sort = args.sort[0]; query.sortBy = sort.attribute; if(sort.descending === true) { query.sortOrder = "desc"; } else if(sort.descending === false) { query.sortOrder = "asc"; } } return query; }, _getServiceUrl: function(query) { if (!this.sendQuery) { return this.url; } if (!query) { return this.url; } if (lang.isString(query)) { return this.url + query; } var queryString = ""; var paramSchema = this.paramSchema; for(var key in query) { if(key in paramSchema) { var val = paramSchema[key].format(query[key]); if(val) { queryString += val + "&"; } } else { queryString += (key + "=" + query[key] + "&"); } } if (!queryString) { return this.url; } var serviceUrl = this.url; if (serviceUrl.indexOf("?") < 0){ serviceUrl += "?"; } else { serviceUrl += "&"; } return serviceUrl + queryString; }, _createItems: function(document) { var nodes = xpath.selectNodes(document, this.atom.entries, this.namespaces); var items = []; for (var i=0; i<nodes.length; i++) { items.push(this._createItem(nodes[i])); } return items; }, _createItem: function(element) { var attribs = this.getAttributes(); var xpathCountFunction = /^count\(.*\)$/; // TODO add item.index and item.attribs var item = { element : element, getValue : function(attrib) { var result = []; if(typeof this[attrib] == "object"){ for(var i=0;i<this[attrib].length; i++){ result[i] = entities.encode(this[attrib][i]); } } else{ result = entities.encode(this[attrib]); } return result; } }; for (var i=0; i<attribs.length; i++) { var attrib = attribs[i]; var access = this.attributes[attrib]; if (lang.isFunction(access)) { item[attrib] = access(this, item); } else if (access.match(xpathCountFunction)){ item[attrib] = xpath.selectNumber(element, access, this.namespaces)+""; } else { var nodes = xpath.selectNodes(element, access, this.namespaces); if (nodes && nodes.length == 1) { item[attrib] = entities.encode(nodes[0].text) || entities.encode(nodes[0].textContent); } else if (nodes) { item[attrib] = []; for (var j=0; j<nodes.length; j++) { item[attrib].push(entities.encode(nodes[j].text) || entities.encode(nodes[j].textContent)); } } else { item[attrib] = null; } } } return item; }, _assertIsItem: function(item) { if (!this.isItem(item)) { throw new Error("sbt.data.AtomReadStore: Invalid item argument."); } }, _assertIsAttribute: function(attribute) { if (!this.attributes[attribute]) { throw new Error("sbt.data.AtomReadStore: Invalid attribute argument."); } } }); return AtomReadStore; }); }, 'sbt/Promise':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. * * @module sbt.Promise */ define(["./declare","./log"], function(declare,log) { /** * Promise class * * @class Promise * @namespace sbt */ var Promise = declare(null, { // private _isRejected : false, _isFulfilled : false, _isCanceled : false, _deferreds : null, response : null, error : null, /* * Constructor for the promise. */ constructor: function(response) { if (response) { if (response instanceof Error) { this.rejected(response); } else { this.fulfilled(response); } } else { this._deferreds = []; } }, /* * Add new callbacks to the promise. */ then: function(fulfilledHandler, errorHandler) { var promise = new Promise(); if (this._isFulfilled) { this._fulfilled(fulfilledHandler, errorHandler, promise, this.data); } else if (this._isRejected) { this._rejected(errorHandler, promise, this.error); } else { this._deferreds.push([ fulfilledHandler, errorHandler, promise ]); } return promise; }, /* * Inform the deferred it may cancel its asynchronous operation. */ cancel: function(reason, strict) { this._isCanceled = true; }, /* * Checks whether the promise has been resolved. */ isResolved: function() { return this._isRejected || this._isFulfilled; }, /* * Checks whether the promise has been rejected. */ isRejected: function() { return this._isRejected; }, /* * Checks whether the promise has been resolved or rejected. */ isFulfilled: function() { return this._isFulfilled; }, /* * Checks whether the promise has been canceled. */ isCanceled: function() { return this._isCanceled; }, /* * Called if the promise has been fulfilled */ fulfilled : function(data) { if (this._isCanceled) { return; } this._isFulfilled = true; this.data = data; if (this._deferreds) { while (this._deferreds.length > 0) { var deferred = this._deferreds.shift(); var fulfilledHandler = deferred[0]; var errorHandler = deferred[1]; var promise = deferred[2]; this._fulfilled(fulfilledHandler, errorHandler, promise, data); } } }, /* * Call if the promise has been rejected */ rejected : function(error) { if (this._canceled) { return; } this._isRejected = true; this.error = error; if (this._deferreds) { while (this._deferreds.length > 0) { var deferred = this._deferreds.shift(); var errorHandler = deferred[1]; var promise = deferred[2]; this._rejected(errorHandler, promise, error); } } }, _fulfilled : function(fulfilledHandler, errorHandler, promise, data) { if (fulfilledHandler) { try { var retval = fulfilledHandler(data); if (retval instanceof Promise) { retval.then( function(data) { promise.fulfilled(data); }, function(error) { promise.rejected(error); } ); } else { promise.fulfilled(retval); } } catch (error) { promise.rejected(error); } } else { promise.fulfilled(data); } }, _rejected : function(errorHandler, promise, error) { if (errorHandler) { try { var retval = errorHandler(error); if (!retval) { // stop propogating errors promise.rejected(retval); } } catch (error1) { promise.rejected(error1); } } else { promise.rejected(error); } } }); return Promise; }); }, 'sbt/_bridge/json':function(){ /** * Dojo AMD JSON implementation. */ define(['dojo/json'],function(json) { return json; }); }, 'sbt/ready':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * @module sbt.ready */ define(['./_bridge/ready'],function(ready) { return ready; }); }, 'sbt/connections/SearchConstants':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. * Definition of constants for SearchService. */ define([ "../lang", "./ConnectionsConstants" ], function(lang,conn) { return lang.mixin(conn, { /** * Namespaces to be used when reading the Search ATOM feed */ SearchNamespaces : { a : "http://www.w3.org/2005/Atom", ibmsc : "http://www.ibm.com/search/content/2010", opensearch : "http://a9.com/-/spec/opensearch/1.1/", relevance : "http://a9.com/-/opensearch/extensions/relevance/1.0/", snx : "http://www.ibm.com/xmlns/prod/sn", spelling : "http://a9.com/-/opensearch/extensions/spelling/1.0/" }, /** * XPath expressions used when parsing a Connections Search ATOM feed */ SearchFeedXPath : conn.ConnectionsFeedXPath, /** * XPath expressions used when parsing a Connections Search facets feed * that only contains a single facet */ SingleFacetXPath : { // used by getEntitiesDataArray entries : "/a:feed/ibmsc:facets/ibmsc:facet[@id='{facet.id}']/ibmsc:facetValue" // used by getSummary //totalResults : "", //startIndex : "", //itemsPerPage : "" }, /** * XPath expressions used when parsing a Connections Search facet */ FacetValueXPath : { // used by getEntityData entry : "/ibmsc:facetValue", // used by getEntityId uid : "@id", // used by getters id : "@id", label : "@label", weight : "@weight" }, /** * XPath expressions to be used when reading a scope */ ScopeXPath : lang.mixin({}, conn.AtomEntryXPath, { link : "link" }), /** * XPath expressions to be used when reading a search result */ SearchXPath : lang.mixin({}, conn.AtomEntryXPath, { rank : "snx:rank", relevance : "relevance:score", type : "a:category[@scheme='http://www.ibm.com/xmlns/prod/sn/type']/@term", application : "a:category[@scheme='http://www.ibm.com/xmlns/prod/sn/component']/@term", applicationCount : "count(a:category[@scheme='http://www.ibm.com/xmlns/prod/sn/component']/@term)", primaryComponent : "a:category[ibmsc:field[@id='primaryComponent']]/@term", tags : "a:category[not(@scheme)]/@term", commentCount : "snx:rank[@scheme='http://www.ibm.com/xmlns/prod/sn/comment']", resultLink : "a:link[not(@rel)]/@href", bookmarkLink : "ibmsc:field[@id='dogearURL']", eventStartDate : "ibmsc:field[@id='eventStartDate']", authorJobTitle : "a:content/xhtml:div/xhtml:span/xhtml:div[@class='title']", authorJobLocation : "a:content/xhtml:div/xhtml:span/xhtml:div[@class='location']", authorCount : "count(a:contributor)", contributorCount : "count(a:author)", tagCount : "count(a:category[not(@scheme)])", highlightField : "ibmsc:field[@id='highlight']", fileExtension : "ibmsc:field[@id='fileExtension']", memberCount : "snx:membercount", communityUuid : "snx:communityUuid", containerType : "ibmsc:field[@id='container_type']", communityParentLink : "a:link[@rel='http://www.ibm.com/xmlns/prod/sn/container' and @type='text/html']/@href", parentageMetaID : "ibmsc:field[contains(@id, 'ID')]/@id", parentageMetaURL : "ibmsc:field[contains(@id, 'URL')]", parentageMetaURLID : "ibmsc:field[contains(@id, 'URL')]/@id", objectRefDisplayName : "ibmsc:field[@id='FIELD_OBJECT_REF_DISPLAY_NAME']", objectRefUrl : "ibmsc:field[@id='FIELD_OBJECT_REF_URL']", accessControl : "a:category[@scheme='http://www.ibm.com/xmlns/prod/sn/accesscontrolled']/@term", commentsSummary : "ibmsc:field[@id='commentsSummary']" }), /** * Returns the set of supported values that can be passed to the "scope" parameter of the Search API. * Scopes relating to Connections applications that have not been installed will not be returned. */ AtomScopes : "/${search}/atom/scopes", /** * API call for searching IBM Connections to find content that, for example, contains a specific text * string in its title or content, or is tagged with a specific tag. */ AtomSearch : "/${search}/atom/search", /** * API call for searching IBM Connections to find content that, for example, contains a specific text * string in its title or content, or is tagged with a specific tag. */ AtomMySearch : "/${search}/atom/mysearch", /** * These API's are all deprecated */ publicSearch : "/${search}/atom/search/results", mySearch : "/${search}/atom/mysearch/results", peopleSearch : "/${search}/atom/search/facets/people", myPeopleSearch : "/${search}/atom/mysearch/facets/people", tagsSearch : "/${search}/atom/search/facets/tags", myTagsSearch : "/${search}/atom/mysearch/facets/tags", dateSearch : "/${search}/atom/search/facets/date", myDateSearch : "/${search}/atom/mysearch/facets/date", sourceSearch : "/${search}/atom/search/facets/source", mySourceSearch : "/${search}/atom/mysearch/facets/source" }); }); }, 'sbt/smartcloud/CommunityConstants':function(){ /* * ©©© Copyright IBM Corp. 2012,2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. Definition of constants for CommunityService. * * @module sbt.connections.CommunityConstants */ define([ "../lang", "../smartcloud/SmartcloudConstants" ], function(lang,conn) { return lang.mixin({ /** * Namespaces to be used when reading the Communities ATOM entry or feed */ CommunityNamespaces : { a : "http://www.w3.org/2005/Atom", app : "http://www.w3.org/2007/app", snx : "http://www.ibm.com/xmlns/prod/sn", opensearch: "http://a9.com/-/spec/opensearch/1.1/" }, /** * XPath expressions used when parsing a Connections Communities ATOM feed * * @property CommunityFeedXPath * @type Object * @for sbt.connections.CommunityService */ CommunityFeedXPath : conn.SmartcloudFeedXPath, /** * XPath expressions to be used when reading a Community Entry * * @property CommunityXPath * @type Object * @for sbt.connections.CommunityService */ CommunityXPath : lang.mixin({}, conn.AtomEntryXPath, { communityUuid : "a:id", communityTheme : "snx:communityTheme", logoUrl : "a:link[@rel='http://www.ibm.com/xmlns/prod/sn/logo']/@href", tags : "a:category[not(@scheme)]/@term", memberCount : "snx:membercount", communityType : "snx:communityType", isExternal : "snx:isExternal" }), /** * XPath expressions to be used when reading a Community Member Entry * * @property MemberXPath * @type Object * @for sbt.connections.CommunityService */ MemberXPath : lang.mixin({}, conn.AtomEntryXPath, { id : "a:contributor/snx:userid", uid : "a:contributor/snx:userid", role : "snx:role" }), /** * A feed of members. * * Retrieve the members feed to view a list of the members who belong to a given community. * * Supports: asc, email, page, ps, role, since, sortField, userid * * @property AtomCommunityMembers * @type String * @for sbt.connections.CommunityService */ AtomCommunityMembers : "${communities}/service/atom/community/members" }, conn); }); }, 'sbt/_bridge/i18n':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. */ define(['dojo/i18n', 'dojo/date/locale'],function(i18n, dateLocale) { var load = function(id, require, callback){ i18n.load(id, require, callback); }; return { load : load, getLocalizedTime: function(date) { return dateLocale.format(date, { selector:"time",formatLength:"short" }); }, getLocalizedDate: function(date) { return dateLocale.format(date, { selector:"date",formatLength:"medium" }); } }; }); }, 'sbt/nls/util':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK - Default resource bundle for validate module. */ define({ root: ({ error_callback:"Error running error callback : {0}", error_console:"Error received. Error Code = {0}. Error Message = {1}" }) }); }, 'sbt/declare':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK - declare() function. * * @module sbt.declare */ define(['./_bridge/declare'],function(declare) { return declare; }); }, 'sbt/connections/ActivityStreamService':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * JavaScript API for IBM Connections Activity Stream Service. * * @module sbt.connections.ActivityStreamService */ define([ "../declare", "../lang", "../stringUtil", "../config", "../Promise", "./ActivityStreamConstants", "./ConnectionsService","../base/BaseEntity", "../base/DataHandler", 'sbt/json'], function(declare,lang,stringUtil,config,Promise,consts,ConnectionsService, BaseEntity,DataHandler, json) { /** * JsonDataHandler class * * @class JsonDataHandler * @namespace sbt.base */ var ActivityStreamsDataHandler = declare(DataHandler, { constructor : function(args) { lang.mixin(this, args); this.data = args.data; }, getSummary : function() { if (!this._summary && this.data.totalResults) { this._summary = { totalResults : this.data.totalResults, startIndex : this.data.startIndex, itemsPerPage : this.data.itemsPerPage }; } return this._summary; }, getEntitiesDataArray : function() { return this.data.list; } }); /** * ActivityStreamEntry class. * * @class ActivityStreamEntry * @namespace sbt.connections */ var ActivityStreamEntry = declare(BaseEntity, { data: null, /** * Get published date of activity stream entry * * @method getPublishedDate */ getPublishedDate: function(){ return this.dataHandler.data.published; }, /** * Get plain title of the activity stream entry. this represents the action that was done by actor * * @method getPlainTitle */ getPlainTitle: function(){ return this.dataHandler.data.connections.plainTitle; }, /** * Get actor name of the activity stream entry * * @method getActorDisplayName */ getActorDisplayName: function(){ return this.dataHandler.data.actor.displayName; }, /** * Get full actor object of the activity stream entry. Object holds all properties of actor. Here is an example of an actor object: { connections:{ state:"active" }, objectType:"person", id:"urn:lsid:lconn.ibm.com:profiles.person:0EE5A7FA-3434-9A59-4825-7A7000278DAA", displayName:"Frank Adams" } * * @method getActor */ getActor: function(){ return this.dataHandler.data.actor; }, /** * Get verb of activity stream entry, verb represents the type of action that was done * * @method getVerb */ getVerb: function(){ return this.dataHandler.data.verb; }, /** * Get id of activity stream entry * * @method getId */ getId: function(){ return this.dataHandler.data.id; } }); /** * Callbacks used when reading a feed that contains ActivityStream entries. */ var getActivityStreamServiceCallbacks = { createEntities : function(service,data,response) { return new ActivityStreamsDataHandler({ data : data }); }, createEntity : function(service,data,response) { var entryHandler = new ActivityStreamsDataHandler({ data : data }); return new ActivityStreamEntry({ service : service, dataHandler : entryHandler }); } }; /** * ActivityStreamService class. * * @class ActivityStreamService * @namespace sbt.connections */ var ActivityStreamService = declare(ConnectionsService, { contextRootMap: { connections: "connections" }, serviceName : "connections", /** * Constructor for ActivityStreamService * * @constructor * @param args */ constructor : function(args) { if (!this.endpoint) { this.endpoint = config.findEndpoint(this.getDefaultEndpointName()); } }, /** * Callbacks used when reading a feed that contains Activity Stream entries. */ getActivityStreamCallbacks: function() { return getActivityStreamServiceCallbacks; }, /** * Get activity stream for given user, group and application type * * @method getStream * @param {String} [userType] user type for which activity stream is to be obtained. * If null is passed for userType, then '@public' will be used as * default * @param {String} [groupType] group type for which activity stream is to be obtained * If null is passed for userType, then '@all' will be used as * default * @param {String} [applicationType] application type for which activity stream is to be obtained * If null is passed for userType, then '@all' will be used as * default * @param {Object} [args] Object representing various query parameters * that can be passed. The parameters must be exactly as they are * supported by IBM Connections. */ getStream : function(userType, groupType, applicationType, args) { var _userType = userType || consts.ASUser.PUBLIC; //Default is public updates var _groupType = groupType || consts.ASGroup.ALL; // Default is all groups var _applicationType = applicationType || consts.ASApplication.STATUS; // Default is all Applications // var url = consts.ActivityStreamUrls.activityStreamBaseUrl+this.endpoint.authType+consts.ActivityStreamUrls.activityStreamRestUrl+_userType+"/"+_groupType+"/"+_applicationType; var url = this.constructUrl(consts.ActivityStreamUrls.activityStreamBaseUrl+"{authType}"+consts.ActivityStreamUrls.activityStreamRestUrl+"{userType}/{groupType}/{appType}", {}, { authType : this.endpoint.authType, userType : _userType, groupType : _groupType, appType : _applicationType }); var options = { method : "GET", handleAs : "json", query : args || {} }; return this.getEntities(url, options, this.getActivityStreamCallbacks()); }, /** * Get all updates. * * @method getAllUpdates * @param {Object} [args] Object representing various query parameters * that can be passed. The parameters must be exactly as they are * supported by IBM Connections. */ getAllUpdates : function(args) { return this.getStream(consts.ASUser.PUBLIC, consts.ASGroup.ALL, consts.ASApplication.ALL, args); }, /** * Get my status updates. * * @method getMyStatusUpdates * @param {Object} [args] Object representing various query parameters * that can be passed. The parameters must be exactly as they are * supported by IBM Connections. */ getMyStatusUpdates : function(args) { return this.getStream(consts.ASUser.ME, consts.ASGroup.ALL, consts.ASApplication.STATUS, args); }, /** * Get status updates from my network. * * @method getStatusUpdatesFromMyNetwork * @param {Object} [args] Object representing various query parameters * that can be passed. The parameters must be exactly as they are * supported by IBM Connections. */ getStatusUpdatesFromMyNetwork : function(args) { return this.getStream(consts.ASUser.ME, consts.ASGroup.FRIENDS, consts.ASApplication.STATUS, args); }, /** * Get Updates from My Network * * @method getUpdatesFromMyNetwork * @param {Object} [args] Object representing various query parameters * that can be passed. The parameters must be exactly as they are * supported by IBM Connections. */ getUpdatesFromMyNetwork : function(args) { return this.getStream(consts.ASUser.ME, consts.ASGroup.FRIENDS, consts.ASApplication.ALL, args); }, /** * Get Updates from People I Follow * * @method getUpdatesFromPeopleIFollow * @param {Object} [args] Object representing various query parameters * that can be passed. The parameters must be exactly as they are * supported by IBM Connections. */ getUpdatesFromPeopleIFollow : function(args) { return this.getStream(consts.ASUser.ME, consts.ASGroup.FOLLOWING, consts.ASApplication.STATUS, args); }, /** * Get Updates from Communities I Follow * * @method getUpdatesFromCommunitiesIFollow * @param {Object} [args] Object representing various query parameters * that can be passed. The parameters must be exactly as they are * supported by IBM Connections. */ getUpdatesFromCommunitiesIFollow : function(args) { return this.getStream(consts.ASUser.ME, consts.ASGroup.ALL, consts.ASApplication.COMMUNITIES, args); }, /** * Get Updates from a Community * * @method getUpdatesFromCommunity * @param {String} communityID Community id Community id for which activity Stream * is to be obtained * @param {Object} [args] Object representing various query parameters * that can be passed. The parameters must be exactly as they are * supported by IBM Connections. */ getUpdatesFromCommunity : function(communityID, args) { var promise = this._validateCommunityUuid(communityID); if (promise) { return promise; } return this.getStream(consts.ASUser.COMMUNITY+communityID, consts.ASGroup.ALL, consts.ASApplication.ALL, args); }, /** * Get Updates from a User * * @method getUpdatesFromUser * @param {String} userId User id for which activity Stream * is to be obtained * @param {Object} [args] Object representing various query parameters * that can be passed. The parameters must be exactly as they are * supported by IBM Connections. */ getUpdatesFromUser : function(userId, args) { var promise = this._validateUserId(userId); if (promise) { return promise; } return this.getStream(userId, consts.ASGroup.INVOLVED, consts.ASApplication.ALL, args); }, /** * Get Notifications for Me * * @method getNotificationsForMe * @param {Object} [args] Object representing various query parameters * that can be passed. The parameters must be exactly as they are * supported by IBM Connections. */ getNotificationsForMe : function(args) { return this.getStream(consts.ASUser.ME, consts.ASGroup.RESPONSES, consts.ASApplication.ALL, args); }, /** * Get Notifications from Me * * @method getNotificationsFromMe * @param {Object} [args] Object representing various query parameters * that can be passed. The parameters must be exactly as they are * supported by IBM Connections. */ getNotificationsFromMe : function(args) { return this.getStream(consts.ASUser.ME, consts.ASGroup.NOTESFROMME, consts.ASApplication.ALL, args); }, /** * Get Responses to My Content * * @method getResponsesToMyContent * @param {Object} [args] Object representing various query parameters * that can be passed. The parameters must be exactly as they are * supported by IBM Connections. */ getResponsesToMyContent : function(args) { return this.getStream(consts.ASUser.ME, consts.ASGroup.RESPONSES, consts.ASApplication.ALL, args); }, /** * Get Actions pending on me * * @method getMyActionableItems * @param {Object} [args] Object representing various query parameters * that can be passed. The parameters must be exactly as they are * supported by IBM Connections. */ getMyActionableItems : function(args) { return this.getStream(consts.ASUser.ME, consts.ASGroup.ACTIONS, consts.ASApplication.ALL, args); }, /** * Get Actions pending on me for an applications * * @method getMyActionableItemsForApplication * @param {String} application name for which pending action items * are to be obtained * @param {Object} [args] Object representing various query parameters * that can be passed. The parameters must be exactly as they are * supported by IBM Connections. */ getMyActionableItemsForApplication : function(application, args) { var promise = this._validateApplicationName(application); if (promise) { return promise; } return this.getStream(consts.ASUser.ME, consts.ASGroup.ACTIONS, application, args); }, /** * Get Updates Saved by me * * @method getMySavedItems * @param {Object} [args] Object representing various query parameters * that can be passed. The parameters must be exactly as they are * supported by IBM Connections. */ getMySavedItems : function(args) { return this.getStream(consts.ASUser.ME, consts.ASGroup.SAVED, consts.ASApplication.ALL, args); }, /** * Get Updates Saved by me * * @method getMySavedItemsForApplication * @param {String} application name for which saved items * are to be obtained * @param {Object} [args] Object representing various query parameters * that can be passed. The parameters must be exactly as they are * supported by IBM Connections. */ getMySavedItemsForApplication : function(application, args) { var promise = this._validateApplicationName(application); if (promise) { return promise; } return this.getStream(consts.ASUser.ME, consts.ASGroup.SAVED, application, args); }, /** * Get searched view by query * * @method searchByQuery * @param {String} query string for which activity stream search is to be done. */ searchByQuery : function(searchString) { var promise = this._validateSearchQuery(searchString); if (promise) { return promise; } var args = { query : searchString }; return this.getStream(null, null, null, args); }, /** * Get searched view by filters * * @method searchByFilters * @param {String} query Filters can be passed to this method to get as activity stream * filtered by them. here is a sample string of two filters: * "[{'type':'tag','values':['"+tags+"']},{'type':'tag','values':['test','mobile']}]" * @param {String} filters Filters can be passed to this method to get as activity stream * filtered by them. here is a sample string of two filters: * "[{'type':'tag','values':['"+tags+"']},{'type':'tag','values':['test','mobile']}]" */ searchByFilters : function(query, filters) { var promise = this._validateSearchQuery(query); if (promise) { return promise; } var promise = this._validateSearchFilters(filters); if (promise) { return promise; } var args = {}; args.query = query; args.filters = filters; return this.getStream(null, null, null, args); }, /** * Get searched view by tags * * @method searchByTags * @param {String} tags string containing tags separated by commas for which activity * stream search is to be done. */ searchByTags : function(tags) { var promise = this._validateSearchTags(tags); if (promise) { return promise; } var args = {}; args.filters = "[{'type':'tag','values':['"+tags+"']}]"; return this.getStream(null, null, null, args); }, /** * Get searched view by pattern * * @method searchByPattern * @param {String} pattern string containing tags separated by commas for which activity * stream search is to be done. */ searchByPattern : function(pattern) { var promise = this._validateSearchTags(pattern); if (promise) { return promise; } var args = {}; args.custom = pattern; return this.getStream(null, null, null, args); }, /** * post an Activity Stream entry * * @method postEntry * @param {Object} postData a json object representing data to be posted * @param {String} [userType] user type for which activity stream is to be posted * If null is passed for userType, then '@me' will be used as * default * @param {String} [groupType] group type for which activity stream is to be posted * If null is passed for userType, then '@all' will be used as * default * @param {String} [applicationType] for which activity stream is to be posted * If null is passed for userType, then '@all' will be used as * default * @param {Object} [args] Object representing various query parameters * that can be passed. The parameters must be exactly as they are * supported by IBM Connections. */ postEntry : function(postData, userType, groupType, applicationType, args) { var _userType = userType || consts.ASUser.ME; //Default is public updates var _groupType = groupType || consts.ASGroup.ALL; // Default is all groups var _applicationType = applicationType || consts.ASApplication.ALL; // Default is all Applications var url = consts.ActivityStreamUrls.activityStreamBaseUrl+this.endpoint.authType+consts.ActivityStreamUrls.activityStreamRestUrl+_userType+"/"+_groupType+"/"+_applicationType; var headers = {"Content-Type" : "application/json"}; var options = { method : "POST", query : args || {}, handleAs : "json", headers : headers, data : json.stringify(postData) }; var callbacks = {}; callbacks.createEntity = function(service,data,response) { return data; }; return this.updateEntity(url, options, callbacks, args); }, /** * post an Activity Stream microblog entry * * @method postMicroblogEntry * @param {Object/String} postData a json object representing data to be posted * @param {String} [userType] user type for which activity stream is to be posted * If null is passed for userType, then '@public' will be used as * default * @param {String} [groupType] group type for which activity stream is to be posted * If null is passed for userType, then '@all' will be used as * default * @param {String} [applicationType] for which activity stream is to be posted * If null is passed for userType, then '@all' will be used as * default * @param {Object} [args] Object representing various parameters * that can be passed to post an activity stream. * The parameters must be exactly as they are * supported by IBM Connections. */ postMicroblogEntry : function(postData, userType, groupType, applicationType, args) { if (typeof postData == "string") { postData = {"content":postData}; } else if (typeof postData == "object") { postData = postData; } else { return this.createBadRequestPromise("Invalid argument with postMicroblogEntry, expected String or Object"); } var _userType = userType || consts.ASUser.ME; //Default is public updates var _groupType = groupType || consts.ASGroup.ALL; // Default is all groups var _applicationType = applicationType || ""; // Default is all Applications var url = consts.ActivityStreamUrls.activityStreamBaseUrl+this.endpoint.authType+consts.ActivityStreamUrls.activityStreamUBlogRestUrl+_userType+"/"+_groupType+"/"+_applicationType; var headers = {"Content-Type" : "application/json"}; var options = { method : "POST", query : args || {}, handleAs : "json", headers : headers, data : json.stringify(postData) }; var callbacks = {}; callbacks.createEntity = function(service,data,response) { return data; }; return this.updateEntity(url, options, callbacks, args); }, /* * Validate a community UUID, and return a Promise if invalid. */ _validateCommunityUuid : function(communityUuid) { if (!communityUuid || communityUuid.length == 0) { return this.createBadRequestPromise("Invalid argument, expected communityUuid."); } }, /* * Validate a search query, and return a Promise if invalid. */ _validateSearchQuery : function(searchQuery) { if (!searchQuery || searchQuery.length == 0) { return this.createBadRequestPromise("Invalid argument, expected communityUuid."); } }, /* * Validate application name, and return a Promise if invalid. */ _validateApplicationName : function(application) { if (!application || application.length == 0) { return this.createBadRequestPromise("Invalid argument, expected application name."); } }, /* * Validate search tags, and return a Promise if invalid. */ _validateSearchTags : function(searchTags) { if (!searchTags || searchTags.length == 0) { return this.createBadRequestPromise("Invalid argument, expected communityUuid."); } }, /* * Validate search filters, and return a Promise if invalid. */ _validateSearchFilters : function(searchFilters) { if (!searchFilters || searchFilters.length == 0) { return this.createBadRequestPromise("Invalid argument, expected communityUuid."); } }, /* * Validate a user ID, and return a Promise if invalid. */ _validateUserId : function(userId) { if (!userId || userId.length == 0) { return this.createBadRequestPromise("Invalid argument, expected userId."); } } }); return ActivityStreamService; }); }, 'sbt/base/DataHandler':function(){ /* * © Copyright IBM Corp. 2012,2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. Helpers for the base capabilities of data * handlers. * * @module sbt.base.DataHandler */ define([ "../declare", "../lang" ], function(declare,lang) { /** * DataHandler class * * @class DataHandler * @namespace sbt.base */ var DataHandler = declare(null, { /** * Data type for this DataHandler */ dataType : null, /** * Data for this DataHandler */ data : null, /** * @constructor * @param {Object} * args Arguments for this data handler. */ constructor : function(args) { lang.mixin(this, args); }, /** * Called to set the handler data. * * @param data */ setData : function(data) { this.data = data; }, /** * Called to get the handler data. * * @param data */ getData : function() { return this.data; }, /** * @method getAsString * @param data * @returns */ getAsString : function(property) { return null; }, /** * @method getAsNumber * @returns */ getAsNumber : function(property) { return null; }, /** * @method getAsDate * @returns */ getAsDate : function(property) { return null; }, /** * @method getAsBoolean * @returns */ getAsBoolean : function(property) { return null; }, /** * @method getAsArray * @returns */ getAsArray : function(property) { return null; }, /** * @method getEntityId * @returns */ getEntityId : function(data) { return null; }, /** * @param parent * @returns */ getEntityData : function(parent) { return data; }, /** * @method getSummary * @returns */ getSummary : function() { return null; }, /** * @method getEntitiesDataArray * @returns {Array} */ getEntitiesDataArray : function() { return []; }, /** * @method toJso * @returns {Object} */ toJson : function() { } }); return DataHandler; }); }, 'sbt/dom':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Definition of some DOM utilities. * * @module sbt.dom */ define(['./_bridge/dom'],function(dom) { // The actual implementation is library dependent // NOTE: dom.byId returns either a DOM element or false (null/undefined) return dom; }); }, 'sbt/authenticator/templates/messageSSO':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ function cancelOnClick() { var argsMap = getArgsMap();// get map of query string arguments var redirectURL = decodeURIComponent(argsMap.redirectURL); var loginUi = decodeURIComponent(argsMap.loginUi); if (loginUi == "popup") { opener.location.reload(); window.close(); } else { window.location.href = redirectURL; } } function onLoginPageLoad() { var argsMap = getArgsMap();// get map of query string arguments if(argsMap.loginUi == "popup"){ var ssoStrings = window.globalSSOStrings; document.getElementById('reloginMessage').appendChild(document.createTextNode(decodeURIComponent(ssoStrings.message))); document.getElementById('ssoLoginFormOK').value = decodeURIComponent(ssoStrings.relogin_button_text); }else{ document.getElementById('reloginMessage').appendChild(document.createTextNode(decodeURIComponent(argsMap.message))); document.getElementById('ssoLoginFormOK').value = decodeURIComponent(argsMap.relogin_button_text); } } function getArgsMap() { try { var qString = location.search.substring(1);// getting query string args var qStringParams = qString.split("&");// getting array of all query // string arg key value pairs var argsMap = {}; var i; for (i = 0; i < qStringParams.length; i++) { var argArray = qStringParams[i].split("="); argsMap[argArray[0]] = argArray[1]; } return argsMap; } catch (err) { console.log("Error making agrs map in messageSSO.js " + err); } } }, 'sbt/connections/ConnectionsService':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Connections common APIs allow application programs to discover information about IBM© Connections as a whole. * * @module sbt.connections.ConnectionsService */ define([ "../declare", "../config", "../Promise", "./ConnectionsConstants", "../base/BaseService", "../base/AtomEntity", "../base/XmlDataHandler", "../xpath" ], function(declare,config,Promise,consts,BaseService,AtomEntity,XmlDataHandler,xpath) { var CategoryConnectionsBookmark = "<category term=\"bookmark\" scheme=\"http://www.ibm.com/xmlns/prod/sn/type\"></category>"; var CategoryMember = "<category term=\"person\" scheme=\"http://www.ibm.com/xmlns/prod/sn/type\"></category>"; var CategoryServiceConfig = "<category term=\"service-config\" scheme=\"http://www.ibm.com/xmlns/prod/sn/type\"></category>" var ServiceConfigsDataHandler = declare(XmlDataHandler, { /** * @method getSummary * @returns */ getSummary : function() { var languageTermsArray = this._selectArray("language"); var languageLabelsArray = this._selectArray("languageLabels"); var displayLanguagesMap = []; for(var i=0;i<languageTermsArray.length;i++){ displayLanguagesMap.push({label: languageLabelsArray[i], term: languageTermsArray[i]}); } if (!this._summary) { this._summary = { isEmailExposed : (xpath.selectText(this.data, this._getXPath("emailConfig"), this.namespaces)=="email-exposed")?"true":"false", displayLanguages : displayLanguagesMap }; } return this._summary; } }); /** * ServiceConfig class represents an entry for a service config of a Connections server * * @class ServiceConfig * @namespace sbt.connections */ var ServiceConfig = declare(AtomEntity, { xpath : consts.ServiceConfigXPath, namespaces : consts.Namespaces, categoryScheme : CategoryServiceConfig, /** * Construct a ServiceConfig entity. * * @constructor * @param args */ constructor : function(args) { }, /** * Return the value of IBM Connections service config alternate SSL URL from service config ATOM * entry document. * * @method getAlternateSSLUrl * @return {String} Alternate SSL URL */ getAlternateSSLUrl : function() { return this.getAsString("alternateSSLUrl"); } }); /** * Member class represents an entry for a member of a Connections Activity, Community or Forum * * @class Member * @namespace sbt.connections */ var Member = declare(AtomEntity, { xpath : consts.MemberXPath, namespaces : consts.Namespaces, categoryScheme : CategoryMember, /** * Construct a Member entity. * * @constructor * @param args */ constructor : function(args) { }, /** * Return the value of IBM Connections bookmark URL from bookmark ATOM * entry document. * * @method getUrl * @return {String} Bookmark URL of the bookmark */ getRole : function() { return this.getAsString("role"); } }); /** * ReportEntry class represents the elements in a report created to flag inappropriate content. * * @class ReportEntry * @namespace sbt.connections */ var ReportEntry = declare(AtomEntity, { xpath : consts.ReportEntryXPath, namespaces : consts.Namespaces, /** * Construct a ReportEntry entity. * * @constructor * @param args */ constructor : function(args) { }, /** * Returns the type of issue reported * The default values are: * 001 * Legal issue * 002 * Human resource issue * * @method getCategoryIssue * @return {String} Issue type */ getCategoryIssue : function() { return this.getAsString("categoryIssue"); }, /** * Return the related link url entry that you want to flag * * @method getReportedItemLink * @return {String} Reported item link url */ getReportedItemLink : function() { return this.getAsString("reportItemLink"); }, /** * Return the related link url of the ATOM entry document .Required when flagging blog posts or blog comnments * * @method getRelatedLink * @return {String} Related link url */ getRelatedLink : function() { return this.getAsString("relatedLink"); }, /** * Return the id of the concerned entry * * @method getReferredEntryId * @return {String} Reported item id */ getReferredEntryId : function() { return this.getAsString("inRefTo"); } }); /** * ReportEntry class represents the elements in a report created to flag inappropriate content. * * @class ReportEntry * @namespace sbt.connections */ var ModerationActionEntry = declare(AtomEntity, { xpath : consts.ModerationActionEntryXPath, namespaces : consts.Namespaces, /** * Construct a ModerationActionEntry entity. * * @constructor * @param args */ constructor : function(args) { }, /** * Returns the type of moderation action to be taken * The options for premoderation are: * approve * reject * The options for post-moderation are: * dismiss * quarantine * restore * For Blogs, the option return is also supported for post-moderation of posts, but not comments. * * @method getModerationAction * @return {String} Issue type */ getModerationAction : function() { return this.getAsString("moderationAction"); }, /** * Return the related link url of the entry on which you want to take action using a link element. * This element is used in the Blogs API. * * @method getRelatedLink * @return {String} Related link url */ getRelatedLink : function() { return this.getAsString("relatedLink"); }, /** * Return the resource-id of the concerned entry * * @method getReferredEntryId * @return {String} Moderated item id */ getReferredEntryId : function() { return this.getAsString("inRefTo"); } }); /* * Callbacks used when reading a connections service configs feed. */ var ConnectionsServiceConfigsCallbacks = { createEntities : function(service,data,response) { return new ServiceConfigsDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.ConnectionsServiceDocsFeedXPath }); }, createEntity : function(service,data,response) { return new ServiceConfig({ service : service, data : data, response : response }); } }; /** * ConnectionService class. * * @class ConnectionService * @namespace sbt.connections */ var ConnectionsService = declare(BaseService, { /** * Constructor for ConnectionsService * * @constructor * @param args */ constructor : function(args) { if (!this.endpoint) { this.endpoint = config.findEndpoint(this.getDefaultEndpointName()); } }, /** * Return the default endpoint name if client did not specify one. * @returns {String} */ getDefaultEndpointName : function() { return "connections"; }, /** * Retrieve configuration information for the server. * * @method getServiceConfigs * */ getServiceConfigEntries : function(args) { var options = { method : "GET", handleAs : "text", query : args || {} }; url = this.constructUrl(consts.ServiceConfigs, null, { service : this.serviceName }); return this.getEntities(url, options, ConnectionsServiceConfigsCallbacks); } }); return ConnectionsService; }); }, 'sbt/store/parameter':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * */ define(["../stringUtil", "../config"], function(stringUtil, config) { var Formatter = { defaultFormat: function(param, val) { return param.key + "=" + val; }, sortField: function(vals) { return function(param, val) { var v = vals[val] || ""; return param.key + "=" + v; }; }, ascSortOrderBoolean: function(param, val) { var v = (val === "asc") ? true : false; return param.key + "=" + v; }, sortOrder: function(param,val){ return param.key + "=" + val; }, oneBasedInteger: function(param, val) { var v = Math.floor(val); if(v < 1) { v = 1; } return param.key + "=" + v; }, zeroBaseInteger: function(param, val) { var v = Math.floor(val); if(v < 0) { v = 0; } return param.key + "=" + v; } }; var Parameter = function(args) { var self = this; this.key = args.key; var formatFunc = args.format || Formatter.defaultFormat; this.format = function(val) { return formatFunc(self, val); }; }; return { defaultFormat: function (key){ return new Parameter({key: key, format: Formatter.defaultFormat}); }, sortField: function(key, sortVals){ return new Parameter({key: key, format: Formatter.sortField(sortVals)}); }, sortOrder: function(key){ return new Parameter({key: key, format: Formatter.sortOrder}); }, booleanSortOrder: function (key){ return new Parameter({key: key, format: Formatter.ascSortOrderBoolean}); }, /** * * @param key * @returns */ zeroBasedInteger : function(key) { return new Parameter({ key: key, format: Formatter.zeroBasedInteger }); }, /** * * @param key * @returns */ oneBasedInteger : function(key) { return new Parameter({ key: key, format: Formatter.oneBasedInteger }); } }; }); }, 'sbt/url':function(){ define(['./declare'], function(declare){ // regexp /^(?:(scheme)(:))?(\/\/)(?:(userna)(:)(passwo)(@))?(domain )(?:(:)(port ))?(path )?(?:(\?)(query ))?(?:(#)(fr))?$/ var URL_RE = /^(?:([A-z]+)(:))?(\/\/)(?:([^?#]*)(:)([^?#]*)(@))?([\w.\-]+)(?:(:)(\d{0,5}))?([\w.\/\-]+)?(?:(\?)([^?#]*))?(?:(#)(.*))?$/; var URL_RE_GROUPS = { 'URL': 0, 'SCHEME': 1, 'SCHEME_COLON': 2, 'SCHEME_SLASHES': 3, 'USER': 4, 'PASSWORD_COLON':5, 'PASSWORD': 6, 'USER_AT': 7, 'HOSTNAME': 8, 'PORT_COLON':9, 'PORT': 10, 'PATH': 11, 'QUERY_QUESTION':12, 'QUERY': 13, 'FRAGMENT_HASH': 14, 'FRAGMENT': 15 }; /** A class for representing urls. @class url @constructor **/ var url = declare(null, { /* Holds the parts of the url after URL_RE parses the url. @property _resultStore @type Array **/ _resultStore: [], /* * Ensures that, when setting a value, the required delimiter is before it, and when setting a value null, the relevant delimiter is not before it. * * e.g. setQuery(query). If there was no ? in the url then the url will still not have one when you set the query. It needsto be set in this case. If there was one and you set it null, it needs to be removed. */ _ensureDelimiter: function(urlPart, delimGroupNum, delim){ if(!urlPart && this._resultStore[delimGroupNum]){// if we are setting port empty, ensure there is no : before the port. this._resultStore[delimGroupNum] = undefined; }else if(urlPart && !this._resultStore[delimGroupNum]){// if we are setting port not empty, ensure there is a : before the port. this._resultStore[delimGroupNum] = delim; } }, /* @method constructor **/ constructor: function(url){ this.setUrl(url); }, /** @method getUrl @return {String} Returns the url in its current state. **/ getUrl: function(){ return this._resultStore.slice(1).join(""); }, /** @method setUrl @param url {String} **/ setUrl: function(url){ this._resultStore = URL_RE.exec(url); }, /** @method getScheme @return {String} Returns the scheme in its current state. **/ getScheme: function(){ return this._resultStore[URL_RE_GROUPS.SCHEME]; }, /** @method setScheme @param scheme {String} @param keepSlashes {Boolean} If true, keep the // even if the scheme is set empty. e.g. //ibm.com is a valid url **/ setScheme: function(scheme, keepSlashes){ this._ensureDelimiter(scheme, URL_RE_GROUPS.SCHEME_COLON, ':'); if(!keepSlashes || scheme){ // If they want to keep slashes and the scheme provided is empty, do not do the ensure part. this._ensureDelimiter(scheme, URL_RE_GROUPS.SCHEME_SLASHES, '//'); }else{ // they want to keep slashes and the scheme provided is empty this._resultStore[URL_RE_GROUPS.SCHEME_SLASHES] = '//'; } this._resultStore[URL_RE_GROUPS.SCHEME] = scheme; }, /** @method getUser @return {String} Returns the username in its current state. **/ getUser: function(){ return this._resultStore[URL_RE_GROUPS.USER]; }, /** @method setUser @param user {String} **/ setUser: function(user){ this._ensureDelimiter(user, URL_RE_GROUPS.USER_AT, '@'); this._resultStore[URL_RE_GROUPS.USER] = user; }, /** @method getPassword @return {String} Returns the password (domain) in its current state. **/ getPassword: function(){ return this._resultStore[URL_RE_GROUPS.PASSWORD]; }, /** @method setPassword @param password {String} **/ setPassword: function(password){ this._ensureDelimiter(password, URL_RE_GROUPS.PASSWORD_COLON, ':'); this._resultStore[URL_RE_GROUPS.PASSWORD] = password; }, /** @method getHostName @return {String} Returns the hostname (domain) in its current state. **/ getHostName: function(){ return this._resultStore[URL_RE_GROUPS.HOSTNAME]; }, /** @method setHostName @param hostName {String} **/ setHostName: function(hostName){ this._resultStore[URL_RE_GROUPS.HOSTNAME] = hostName; }, /** @method getPort @return {String} Returns the port in its current state. **/ getPort: function(){ return this._resultStore[URL_RE_GROUPS.PORT]; }, /** @method setPort @param port {Number} **/ setPort: function(port){ this._ensureDelimiter(port, URL_RE_GROUPS.PORT_COLON, ':'); this._resultStore[URL_RE_GROUPS.PORT] = port; }, /** @method getPath @return {String} Returns the path in its current state. **/ getPath: function(){ return this._resultStore[URL_RE_GROUPS.PATH]; }, /** @method setPath @param path {String} **/ setPath: function(path){ this._resultStore[URL_RE_GROUPS.PATH] = path; }, /** @method getQuery @return {String} Returns the query in its current state. **/ getQuery: function(){ return this._resultStore[URL_RE_GROUPS.QUERY]; }, /** @method setQuery @param query {String} **/ setQuery: function(query){ this._ensureDelimiter(query, URL_RE_GROUPS.QUERY_QUESTION, '?'); this._resultStore[URL_RE_GROUPS.QUERY] = query; }, /** @method getFragment @return {String} Returns the fragment in its current state. **/ getFragment: function(){ return this._resultStore[URL_RE_GROUPS.FRAGMENT]; }, /** @method setFragment @param fragment {String} **/ setFragment: function(fragment){ this._ensureDelimiter(fragment, URL_RE_GROUPS.FRAGMENT_HASH, '#'); this._resultStore[URL_RE_GROUPS.FRAGMENT] = fragment; }, /** @method getBaseUrl @return {String} Utility method, returns the url up until before the query. **/ getBaseUrl: function(){ return this._resultStore.slice(1, URL_RE_GROUPS.QUERY).join(""); } }); return url; }); }, 'sbt/ErrorTransport':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Implementation of a transport that emits an error the first time it is invoked. * @module sbt.ErrorTransport */ define(['./declare','./lang','./Promise','./stringUtil','./log','sbt/i18n!sbt/nls/ErrorTransport'], function(declare,lang,Promise,stringUtil,log,nls) { return declare(null, { _called: false, _endpointName: null, _message: null, constructor: function(endpointName, message) { this._endpointName = endpointName; if (message) { this._message = message; } else { this._message = stringUtil.substitute(nls.endpoint_not_available, [endpointName]); } }, request : function(url,options) { if (!this._called) { alert(this._message); this._called = true; } var promise = new Promise(); var error = new Error(this._message); error.status = 400; promise.rejected(error); return promise; }, xhr: function(method, args, hasBody) { if (!this._called) { log.error(this._message); this._called = true; } var _handle = args.handle; var _error = args.error; if (lang.isFunction(_error) || lang.isFunction(_handle)) { var error = new Error(this._message); error.status = 400; if(lang.isFunction(_error)){ _error(error); } if(lang.isFunction(_handle)){ _handle(error); } } } }); }); }, 'sbt/_bridge/ready':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK - ready() function. */ define(['dojo/ready'],function(ready) { return function(fct) { ready(fct); }; }); }, 'sbt/base/core':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. * Helpers for the core capabilities */ define(['../config'],function(sbt) { /** * Global Namespaces Object. */ return { // Namespaces used when parsing Atom feeds namespaces : { o : "http://ns.opensocial.org/2008/opensocial", app : "http://www.w3.org/2007/app", thr : "http://purl.org/syndication/thread/1.0", fh : "http://purl.org/syndication/history/1.0", snx : "http://www.ibm.com/xmlns/prod/sn", opensearch : "http://a9.com/-/spec/opensearch/1.1/", a : "http://www.w3.org/2005/Atom", h : "http://www.w3.org/1999/xhtml", td: "urn:ibm.com/td", relevance: "http://a9.com/-/opensearch/extensions/relevance/1.0/", ibmsc: "http://www.ibm.com/search/content/2010", xhtml: "http://www.w3.org/1999/xhtml" }, feedXPath : { "entry" : "/a:feed/a:entry", "entries" : "/a:feed/a:entry", "totalResults" : "/a:feed/opensearch:totalResults", "startIndex" : "/a:feed/opensearch:startIndex", "itemsPerPage" : "/a:feed/opensearch:itemsPerPage" }, entryXPath : { "title" : "a:title", "summaryText" : "a:summary[@type='text']", "selfUrl" : "a:link[@rel='self']/@href", "terms" : "a:category/@term", "contentHtml" : "a:content[@type='html']", "published" : "a:published", "updated" : "a:updated", "authorId" : "a:author/snx:userid", "contributorId" : "a:contributor/snx:userid" } }; }); }, 'sbt/connections/ActivityStreamConstants':function(){ /* * © Copyright IBM Corp. 2012,2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. Definition of constants for ActivityStreamService. */ define([ "../lang", "./ConnectionsConstants" ], function(lang,conn) { return lang.mixin({}, conn, { ASUser: { ME : "@me", PUBLIC : "@public", COMMUNITY : "urn:lsid:lconn.ibm.com:communities.community:",//Suffix Community with it id wherever this constant is used. UBLOG : "ublog" }, ASGroup: { ALL : "@all", FOLLOWING : "@following", FRIENDS : "@friends", SELF : "@self", INVOLVED : "@involved", NOTESFORME : "@notesforme", NOTESFROMME : "@notesfromme", RESPONSES : "@responses", ACTIONS : "@actions", SAVED : "@saved" }, ASApplication: { ALL : "@all", COMMUNITIES : "@communities", TAGS : "@tags", PEOPLE : "@people", STATUS : "@status", NOTESFORME : "@notesforme", NOTESFROMME : "@notesfromme", RESPONSES : "@responses", COMMENTS : "comments" }, Verb: { ACCEPT : "accept", ACCESS : "access", ACKNOWLEDGE : "acknowledge", ADD : "add", AGREE : "agree", APPEND : "append", APPROVE : "approve", ARCHIVE : "archive", ASSIGN : "assign", AT : "at", ATTACH : "attach", ATTEND : "attend", AUTHOR : "author", AUTHORIZE : "authorize", BORROW : "borrow", BUILD : "build", CANCEL : "cancel", CLOSE : "close", COMMENT : "comment", COMPLETE : "complete", CONFIRM : "confirm", CONSUME : "consume", CHECKIN : "checkin", CREATE : "create", DELETE : "delete", DELIVER : "deliver", DENY : "deny", DISAGREE : "disagree", DISLIKE : "dislike", EXPERIENCE : "experience", FAVORITE : "favorite", FIND : "find", FLAG_AS_INAPPROPRIATE : "flag-as-inappropriate", FOLLOW : "follow", GIVE : "give", HOST : "host", IGNORE : "ignore", INSERT : "insert", INSTALL : "install", INTERACT : "interact", INVITE : "invite", JOIN : "join", LEAVE : "leave", LIKE : "like", LISTEN : "listen", LOSE : "lose", MAKE_FRIEND : "make-friend", OPEN : "open", POST : "post", PLAY : "play", PRESENT : "present", PURCHASE : "purchase", QUALIFY : "qualify", READ : "read", RECEIVE : "receive", REJECT : "reject", REMOVE : "remove", REMOVE_FRIEND : "remove-friend", REPLACE : "replace", REQUEST : "request", REQUEST_FRIEND : "request-friend", RESOLVE : "resolve", RETURN : "return", RETRACT : "retract", RSVP_MAYBE : "rsvp-maybe", RSVP_NO : "rsvp-no", RSVP_YES : "rsvp-yes", SATISFY : "satisfy", SAVE : "save", SCHEDULE : "schedule", SEARCH : "search", SELL : "sell", SEND : "send", SHARE : "share", SPONSOR : "sponsor", START : "start", STOP_FOLLOWING : "stop-following", SUBMIT : "submit", TAG : "tag", TERMINATE : "terminate", TIE : "tie", UNFAVORITE : "unfavorite", UNLIKE : "unlike", UNSAVE : "unsave", UNSATISFY : "unsatisfy", UNSHARE : "unshare", UPDATE : "update", USE : "use", WATCH : "watch", WIN : "win" }, ActivityStreamUrls: { activityStreamBaseUrl : "/${connections}/opensocial/", activityStreamRestUrl : "/rest/activitystreams/", activityStreamUBlogRestUrl : "/rest/ublog/" }, errorMessages:{ args_object : "argument passed to get stream should be an Object", required_communityid : "Community ID is required" } }); }); }, 'sbt/_bridge/lang':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK - Some language utilities. */ define(['dojo/_base/lang', 'dojo/has', 'dojo/_base/sniff'],function(lang, has) { return { mixin: function(dest,sources) { return lang.mixin.apply(this, arguments); }, isArray: function(o) { return lang.isArray(o); }, isString: function(o) { return lang.isString(o); }, isFunction: function(o) { return typeof o == 'function'; }, isObject: function(o) { return typeof o == 'object'; }, clone: function(o) { return lang.clone(o); }, concatPath: function() { var a = arguments; if(a.length==1 && this.isArray(a[0])) { a = a[0]; } var s = ""; for(var i=0; i<a.length; i++) { var o = a[i].toString(); if(s) { s = s + "/"; } s = s + (o.charAt(0)=='/'?o.substring(1):o); } return s; }, trim: function(str) { return lang.trim(str); }, getObject: function(name, create, context) { return lang.getObject(name, create, context); }, hitch: function(scope, method) { return lang.hitch(scope, method); }, isIE: function(){ return has("ie"); } }; }); }, 'sbt/connections/nls/ProfileService':function(){ /* * © Copyright IBM Corp. 2012,2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK - Default resource bundle for ProfileService */ define({ root: ({ invalid_argument : "Invalid Argument" }) }); }, 'sbt/connections/ForumService':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * The Forums application of IBM© Connections enables a team to discuss issues that are pertinent to their work. * The Forums API allows application programs to create new forums, and to read and modify existing forums. * * @module sbt.connections.ForumService */ define([ "../declare", "../config", "../lang", "../stringUtil", "../Promise", "./ForumConstants", "./ConnectionsService", "../base/AtomEntity", "../base/XmlDataHandler" ], function(declare,config,lang,stringUtil,Promise,consts,ConnectionsService,AtomEntity,XmlDataHandler) { var CategoryForum = "<category scheme=\"http://www.ibm.com/xmlns/prod/sn/type\" term=\"forum-forum\"></category>"; var CategoryTopic = "<category scheme=\"http://www.ibm.com/xmlns/prod/sn/type\" term=\"forum-topic\"></category>"; var CategoryReply = "<category scheme=\"http://www.ibm.com/xmlns/prod/sn/type\" term=\"forum-reply\"></category>"; var CategoryRecommendation = "<category scheme=\"http://www.ibm.com/xmlns/prod/sn/type\" term=\"recommendation\"></category>"; var CommunityTmpl = "<snx:communityUuid xmlns:snx=\"http://www.ibm.com/xmlns/prod/sn\">${getCommunityUuid}</snx:communityUuid>"; var TopicTmpl = "<thr:in-reply-to xmlns:thr=\"http://purl.org/syndication/thread/1.0\" ref=\"urn:lsid:ibm.com:forum:${getForumUuid}\" type=\"application/atom+xml\" href=\"\"></thr:in-reply-to>"; var ReplyTmpl = "<thr:in-reply-to xmlns:thr=\"http://purl.org/syndication/thread/1.0\" ref=\"urn:lsid:ibm.com:forum:${getTopicUuid}\" type=\"application/atom+xml\" href=\"\"></thr:in-reply-to>"; var FlagTmpl = "<category scheme=\"http://www.ibm.com/xmlns/prod/sn/flags\" term=\"${flag}\"></category>"; /** * Forum class represents an entry from a Forums feed returned by the * Connections REST API. * * @class Forum * @namespace sbt.connections */ var Forum = declare(AtomEntity, { xpath : consts.ForumXPath, contentType : "html", categoryScheme : CategoryForum, /** * Construct a Forum entity. * * @constructor * @param args */ constructor : function(args) { }, /** * Return extra entry data to be included in post data for this entity. * * @returns {String} */ createEntryData : function() { if (!this.getCommunityUuid()) { return ""; } var transformer = function(value,key) { return value; }; var postData = stringUtil.transform(CommunityTmpl, this, transformer, this); return stringUtil.trim(postData); }, /** * Return the value of id from Forum ATOM * entry document. * * @method getForumUuid * @return {String} ID of the Forum */ getForumUuid : function() { var uid = this.getAsString("forumUuid"); return extractForumUuid(uid); }, /** * Sets id of IBM Connections forum. * * @method setForumUuid * @param {String} forumUuid Id of the forum */ setForumUuid : function(forumUuid) { return this.setAsString("forumUuid", forumUuid); }, /** * Return the value of communityUuid from Forum ATOM * entry document. * * @method getCommunityUuid * @return {String} Uuid of the Community */ getCommunityUuid : function() { return this.getAsString("communityUuid"); }, /** * Sets communityUuid of IBM Connections forum. * * @method setCommunityUuid * @param {String} communityUuid Community Uuid of the forum */ setCommunityUuid : function(communityUuid) { return this.setAsString("communityUuid", communityUuid); }, /** * Return the moderation of the IBM Connections forum from * forum ATOM entry document. * * @method getModeration * @return {String} Moderation of the forum */ getModeration : function() { return this.getAsDate("moderation"); }, /** * Return the thread count of the IBM Connections forum from * forum ATOM entry document. * * @method getThreadCount * @return {Number} Thread count of the forum */ getThreadCount : function() { return this.getAsNumber("threadCount"); }, /** * Return the url of the IBM Connections forum from * forum ATOM entry document. * * @method getForumUrl * @return {String} Url of the forum */ getForumUrl : function() { return this.getAlternateUrl(); }, /** * Get a list for forum topics that includes the topics in the specified forum. * * @method getTopics * @param {Object} args */ getTopics : function(args) { return this.service.getTopics(this.getForumUuid(), args); }, /** * Return an array containing the tags for this forum. * * @method getTags * @return {Array} */ getTags : function() { return this.getAsArray("tags"); }, /** * Return an array containing the tags for this forum. * * @method setTags * @param {Array} */ setTags : function(tags) { return this.setAsArray("tags", tags); }, /** * Loads the forum object with the atom entry associated with the * forum. By default, a network call is made to load the atom entry * document in the forum object. * * @method load * @param {Object} [args] Argument object */ load : function(args) { // detect a bad request by validating required arguments var forumUuid = this.getForumUuid(); var promise = this.service._validateForumUuid(forumUuid); if (promise) { return promise; } var self = this; var callbacks = { createEntity : function(service,data,response) { self.setData(data); return self; } }; var requestArgs = lang.mixin({ forumUuid : forumUuid }, args || {}); var options = { handleAs : "text", query : requestArgs }; return this.service.getEntity(consts.AtomForum, options, forumUuid, callbacks); }, /** * Remove this forum * * @method remove * @param {Object} [args] Argument object */ remove : function(args) { return this.service.deleteForum(this.getForumUuid(), args); }, /** * Update this forum * * @method update * @param {Object} [args] Argument object */ update : function(args) { return this.service.updateForum(this, args); }, /** * Save this forum * * @method save * @param {Object} [args] Argument object */ save : function(args) { if (this.getForumUuid()) { return this.service.updateForum(this, args); } else { return this.service.createForum(this, args); } } }); /** * ForumTopic class represents an entry for a forums topic feed returned by the * Connections REST API. * * @class ForumTopic * @namespace sbt.connections */ var ForumTopic = declare(AtomEntity, { xpath : consts.ForumTopicXPath, contentType : "html", categoryScheme : CategoryTopic, /** * Construct a ForumTopic entity. * * @constructor * @param args */ constructor : function(args) { }, /** * Return extra entry data to be included in post data for this entity. * * @returns {String} */ createEntryData : function() { var entryData = ""; if (this.isPinned()) { entryData += stringUtil.transform(FlagTmpl, this, function(v,k) { return consts.FlagPinned; }, this); } if (this.isLocked()) { entryData += stringUtil.transform(FlagTmpl, this, function(v,k) { return consts.FlagLocked; }, this); } if (this.isQuestion()) { entryData += stringUtil.transform(FlagTmpl, this, function(v,k) { return consts.FlagQuestion; }, this); } return stringUtil.trim(entryData); }, /** * Return the value of id from Forum Topic ATOM * entry document. * * @method getTopicUuid * @return {String} ID of the Forum Topic */ getTopicUuid : function() { var uid = this.getAsString("topicUuid"); return extractForumUuid(uid); }, /** * Sets id of IBM Connections Forum Topic. * * @method setTopicUuid * @param {String} topicUuid Id of the forum topic */ setTopicUuid : function(topicUuid) { return this.setAsString("topicUuid", topicUuid); }, getTopicTitle: function(){ return this.getAsString("topicTitle"); }, setTopicTitle: function(title){ return this.setAsString("topicTitle", title); }, /** * Return the value of IBM Connections forum ID from forum ATOM * entry document. * * @method getForumUuid * @return {String} Forum ID of the forum */ getForumUuid : function() { var uid = this.getAsString("forumUuid"); return extractForumUuid(uid); }, /** * Sets id of IBM Connections forum. * * @method setForumUuid * @param {String} forumUuid Id of the forum */ setForumUuid : function(forumUuid) { return this.setAsString("forumUuid", forumUuid); }, /** * Return the value of communityUuid from Forum ATOM * entry document. * * @method getCommunityUuid * @return {String} Uuid of the Community */ getCommunityUuid : function() { return this.getAsString("communityUuid"); }, /** * Sets communityUuid of IBM Connections forum. * * @method setCommunityUuid * @param {String} communityUuid Community Uuid of the forum * @return {ForumTopic} */ setCommunityUuid : function(communityUuid) { return this.setAsString("communityUuid", communityUuid); }, /** * Return the url of the IBM Connections forum from * forum ATOM entry document. * * @method getTopicUrl * @return {String} Url of the forum */ getTopicUrl : function() { return this.getAsString("alternateUrl"); }, /** * Return the permissions of the IBM Connections forum topic from * forum ATOM entry document. * * @method getPermisisons * @return {String} Permissions of the forum topic */ getPermisisons : function() { return this.getAsString("permissions"); }, /** * True if you want the topic to be added to the top of the forum thread. * * @method isPinned * @return {Boolean} */ isPinned : function() { var terms = this.getAsArray("categoryTerm"); var pinned = consts.FlagPinned; if(lang.isArray(terms)){ for(var i=0;i<terms.length;i++){ if(terms[i].indexOf(pinned) != -1){ return true; } } }else if(lang.isString(terms)){ if(terms.indexOf(pinned) != -1){ return true; } }else{ return false; } }, /** * Set to true if you want the topic to be added to the top of the forum thread. * * @method setPinned * @param pinned * @return {ForumTopic} */ setPinned : function(pinned) { var terms = this.getAsArray("categoryTerm"); if(pinned){ if(terms){ terms.push(consts.setPinned); }else{ this.setAsArray("categoryTerm",consts.setPinned ); } }else{ if(terms){ var pinned = consts.FlagPinned; for(var i=0;i<terms.length;i++){ if(terms[i].indexOf(pinned) !=-1){ terms.splice(i,1); } } this.setAsArray("categoryTerm",terms); } } }, /** * If true, indicates that the topic is locked. * * @method isLocked * @return {Boolean} */ isLocked : function() { var terms = this.getAsArray("categoryTerm"); var locked = consts.FlagLocked; if(lang.isArray(terms)){ for(var i=0;i<terms.length;i++){ if(terms[i].indexOf(locked) !=-1){ return true; } } }else if(lang.isString(terms)){ if(terms.indexOf(locked) !=-1){ return true; } }else{ return false; } }, /** * Set to true, indicates that the topic is locked. * * @method isLocked * @param located * @return {ForumTopic} */ setLocked : function(locked) { var terms = this.getAsArray("categoryTerm"); if(locked){ if(terms){ terms.push(consts.setLocked); }else{ this.setAsArray("categoryTerm",consts.setLocked); } }else{ if(terms){ var locked = consts.FlagLocked; for(var i=0;i<terms.length;i++){ if(terms[i].indexOf(locked) !=-1){ terms.splice(i,1); } } this.setAsArray("categoryTerm",terms); } } }, /** * If true, indicates that the topic is a question. * * @method isQuestion * @return {Boolean} */ isQuestion : function() { var terms = this.getAsArray("categoryTerm"); var question = consts.FlagQuestion; if(lang.isArray(terms)){ for(var i=0;i<terms.length;i++){ if(terms[i].indexOf(question) != -1){ return true; } } }else if(lang.isString(terms)){ if(terms.indexOf(question) != -1){ return true; } }else{ return false; } }, /** * Set to true, indicates that the topic is a question. * * @method setQuestion * @param question * @return {Boolean} */ setQuestion : function(question) { var terms = this.getAsArray("categoryTerm"); if(question){ if(terms){ terms.push(consts.markAsQuestion); }else{ this.setAsArray("categoryTerm",consts.markAsQuestion); } }else{ var questionFlag = consts.FlagQuestion; if(terms){ for(var i=0;i<terms.length;i++){ if(terms[i].indexOf(questionFlag) !=-1){ terms.splice(i,1); } } this.setAsArray("categoryTerm",terms); } } }, /** * If true, indicates that the topic is a question that has been answered. * * @method isAnswered * @return {Boolean} */ isAnswered : function() { return this.getAsBoolean("answered"); }, /** * If true, this forum topic has not been recommended by the current user. * * @method isNotRecommendedByCurrentUser * @returns {Boolean} */ isNotRecommendedByCurrentUser : function() { return this.getAsBoolean("notRecommendedByCurrentUser"); }, /** * Return an array containing the tags for this forum topic. * * @method getTags * @return {Array} */ getTags : function() { return this.getAsArray("tags"); }, /** * Return an array containing the tags for this forum topic. * * @method setTags * @param {Array} */ setTags : function(tags) { return this.setAsArray("tags", tags); }, /** * Return the recommendations url of the forum topic. * * @method getRecommendationsUrl * @return {String} Recommendations url */ getRecommendationsUrl : function() { return this.getAsString("recommendationsUrl"); }, /** * Get a list for forum recommendations that includes the recommendations for this forum topic. * * @method getRecommendations */ getRecommendations : function(args) { return this.service.getForumRecommendations(this.getTopicUuid(), args); }, /** * Get a list for forum replies that includes the replies for this forum topic. * * @method getReplies */ getReplies : function(args) { return this.service.getForumTopicReplies(this.getTopicUuid(), args); }, /** * To like this topic in a stand-alone forum, create forum recommendation to the forum topic resources. * * @method deleteRecommendation * @param args */ createRecommendation : function(args) { return this.service.createForumRecommendation(this.getTopicUuid(), args); }, /** * Delete a recommendation of this topic in the forum. * Only the user who have already recommended the post can delete it's own recommendation. * * @method deleteRecommendation * @param args */ deleteRecommendation : function(args) { return this.service.deleteForumRecommendation(this.getTopicUuid(), args); }, /** * Loads the forum topic object with the atom entry associated with the * forum topic. By default, a network call is made to load the atom entry * document in the forum topic object. * * @method load * @param {Object} [args] Argument object */ load : function(args) { // detect a bad request by validating required arguments var topicUuid = this.getTopicUuid(); var promise = this.service._validateTopicUuid(topicUuid); if (promise) { return promise; } var self = this; var callbacks = { createEntity : function(service,data,response) { self.setData(data); return self; } }; var requestArgs = lang.mixin({ topicUuid : topicUuid }, args || {}); var options = { handleAs : "text", query : requestArgs }; return this.service.getEntity(consts.AtomTopic, options, topicUuid, callbacks); }, /** * Remove this forum topic * * @method remove * @param {Object} [args] Argument object */ remove : function(args) { return this.service.deleteForumTopic(this.getTopicUuid(), args); }, /** * Update this forum topic * * @method update * @param {Object} [args] Argument object */ update : function(args) { return this.service.updateForumTopic(this, args); }, /** * Save this forum topic * * @method save * @param {Object} [args] Argument object */ save : function(args) { if (this.getTopicUuid()) { return this.service.updateForumTopic(this, args); } else { return this.service.createForumTopic(this, args); } } }); /** * ForumReply class represents an entry for a forums reply feed returned by the * Connections REST API. * * @class ForumReply * @namespace sbt.connections */ var ForumReply = declare(AtomEntity, { xpath : consts.ForumReplyXPath, contentType : "html", categoryScheme : CategoryReply, /** * Construct a ForumReply entity. * * @constructor * @param args */ constructor : function(args) { }, /** * Return extra entry data to be included in post data for this entity. * * @returns {String} */ createEntryData : function() { if (!this.getTopicUuid()) { return ""; } var entryData = ""; if (this.isAnswer()) { entryData += stringUtil.transform(FlagTmpl, this, function(v,k) { return consts.FlagAnswer; }, this); } entryData += stringUtil.transform(ReplyTmpl, this, function(v,k) { return v; }, this); return stringUtil.trim(entryData); }, /** * Return the value of id from Forum Reply ATOM * entry document. * * @method getReplyUuid * @return {String} ID of the Forum Reply */ getReplyUuid : function() { var uid = this.getAsString("replyUuid"); return extractForumUuid(uid); }, /** * Sets id of IBM Connections Forum Reply. * * @method setReplyUuid * @param {String} replyUuid Id of the forum reply */ setReplyUuid : function(replyUuid) { return this.setAsString("replyUuid", replyUuid); }, /** * Return the value of IBM Connections topic ID from forum ATOM * entry document. * * @method getTopicUuid * @return {String} ID of the forum reply */ getTopicUuid : function() { var uid = this.getAsString("topicUuid"); return extractForumUuid(uid); }, /** * Sets id of IBM Connections forum reply. * * @method setTopicUuid * @param {String} topicUuid Id of the forum topic */ setTopicUuid : function(topicUuid) { return this.setAsString("topicUuid", topicUuid); }, /** * Return the value of id of the post that this is a repy to. * * @method getReplyToPostUuid * @returns {String} postUuid Id of the forum post */ getReplyToPostUuid : function() { var uid = this.getAsString("replyTo"); return extractForumUuid(uid); }, /** * Sets the value of id of the post that this is a repy to. * * @method setReplyToPostUuid * @param {String} postUuid Id of the forum post */ setReplyToPostUuid : function(postUuid) { return this.setAsString("replyTo", postUuid); }, /** * Return the url of the IBM Connections Forum Reply reply from * forum ATOM entry document. * * @method getReplyUrl * @return {String} Url of the forum */ getReplyUrl : function() { return this.getAlternateUrl(); }, /** * Return the permissions of the IBM Connections Forum Reply from * forum ATOM entry document. * * @method getPermisisons * @return {String} Permissions of the Forum Reply */ getPermisisons : function() { return this.getAsString("permissions"); }, /** * If true, indicates that the reply is an accepted answer. * * @method isAnswered * @return {Boolean} */ isAnswer : function() { return this.getAsBoolean("answer"); }, /** * Set to true, indicates that the reply is an accepted answer. * * @method setAnswer * @param answer * @return {Boolean} */ setAnswer : function(answer) { return this.setAsBoolean("answer", answer); }, /** * If true, this forum reply has not been recommended by the current user. * * @method isNotRecommendedByCurrentUser * @returns {Boolean} */ isNotRecommendedByCurrentUser : function() { return this.getAsBoolean("notRecommendedByCurrentUser"); }, /** * Return the recommendations url of the forum reply. * * @method getRecommendationsUrl * @return {String} Recommendations url */ getRecommendationsUrl : function() { return this.getAsString("recommendationsUrl"); }, /** * Get a list for forum recommendations that includes the recommendations for this forum reply. * * @method getRecommendations */ getRecommendations : function(args) { return this.service.getForumRecommendations(this.getReplyUuid(), args); }, /** * Get a list for forum replies that includes the replies for this forum reply. * * @method getReplies */ getReplies : function(args) { return this.service.getForumReplyReplies(this.getReplyUuid(), args); }, /** * To like this reply in a stand-alone forum, create forum recommendation to the forum reply resources. * * @method deleteRecommendation * @param args */ createRecommendation : function(args) { return this.service.createForumRecommendation(this.getReplyUuid(), args); }, /** * Delete a recommendation of this reply in the forum. * Only the user who have already recommended the post can delete it's own recommendation. * * @method deleteRecommendation * @param args */ deleteRecommendation : function(args) { return this.service.deleteForumRecommendation(this.getReplyUuid(), args); }, /** * Loads the forum reply object with the atom entry associated with the * forum reply. By default, a network call is made to load the atom entry * document in the forum reply object. * * @method load * @param {Object} [args] Argument object */ load : function(args) { // detect a bad request by validating required arguments var replyUuid = this.getReplyUuid(); var promise = this.service._validateReplyUuid(replyUuid); if (promise) { return promise; } var self = this; var callbacks = { createEntity : function(service,data,response) { self.setData(data); return self; } }; var requestArgs = lang.mixin({ replyUuid : replyUuid }, args || {}); var options = { handleAs : "text", query : requestArgs }; return this.service.getEntity(consts.AtomReply, options, replyUuid, callbacks); }, /** * Remove this forum reply * * @method remove * @param {Object} [args] Argument object */ remove : function(args) { return this.service.deleteForumReply(this.getReplyUuid(), args); }, /** * Update this forum reply * * @method update * @param {Object} [args] Argument object */ update : function(args) { return this.service.updateForumReply(this, args); }, /** * Save this forum reply * * @method save * @param {Object} [args] Argument object */ save : function(args) { if (this.getReplyUuid()) { return this.service.updateForumReply(this, args); } else { return this.service.createForumReply(this, args); } } }); /** * ForumMember class represents an entry for a forums member feed returned by the * Connections REST API. * * @class ForumMember * @namespace sbt.connections */ var ForumMember = declare(AtomEntity, { categoryScheme : null, /** * Construct a Forum Tag entity. * * @constructor * @param args */ constructor : function(args) { } }); /** * ForumRecommendation class represents an entry for a forums recommendation feed returned by the * Connections REST API. * * @class ForumTag * @namespace sbt.connections */ var ForumRecommendation = declare(AtomEntity, { xpath : consts.ForumRecommendationXPath, contentType : "text", categoryScheme : CategoryRecommendation, /** * Construct a Forum Tag entity. * * @constructor * @param args */ constructor : function(args) { }, /** * Return the value of title from ATOM entry document. * * @method getTitle * @return {String} ATOM entry title */ getTitle : function() { return this.getAsString("title") || "liked"; }, /** * Return the value of IBM Connections recommendation ID from recommendation ATOM * entry document. * * @method getRecommendationUuid * @return {String} ID of the recommendation topic */ getRecommendationUuid : function() { var uid = this.getAsString("id"); return extractForumUuid(uid); }, /** * Return the value of IBM Connections post ID from recommendation ATOM * entry document. * * @method getPostUuid * @return {String} ID of the forum post */ getPostUuid : function() { var postUuid = this.getAsString("postUuid"); return this.service.getUrlParameter(postUuid, "postUuid") || postUuid; }, /** * Set the value of IBM Connections post ID from recommendation ATOM * entry document. * * @method setPostUuid * @return {String} ID of the forum post */ setPostUuid : function(postUuid) { return this.setAsString("postUuid", postUuid); } }); /** * ForumTag class represents an entry for a forums tag feed returned by the * Connections REST API. * * @class ForumTag * @namespace sbt.connections */ var ForumTag = declare(AtomEntity, { categoryScheme : null, /** * Construct a Forum Tag entity. * * @constructor * @param args */ constructor : function(args) { } }); /* * Method used to extract the forum uuid for an id string. */ var extractForumUuid = function(uid) { if (uid && uid.indexOf("urn:lsid:ibm.com:forum:") == 0) { return uid.substring("urn:lsid:ibm.com:forum:".length); } else { return uid; } }; /* * Callbacks used when reading a feed that contains forum entries. */ var ForumFeedCallbacks = { createEntities : function(service,data,response) { return new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.ForumsFeedXPath }); }, createEntity : function(service,data,response) { return new Forum({ service : service, data : data }); } }; /* * Callbacks used when reading a feed that contains forum topic entries. */ var ForumTopicFeedCallbacks = { createEntities : function(service,data,response) { return new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.ForumsFeedXPath }); }, createEntity : function(service,data,response) { return new ForumTopic({ service : service, data : data }); } }; /* * Callbacks used when reading a feed that contains forum topic reply entries. */ var ForumReplyFeedCallbacks = { createEntities : function(service,data,response) { return new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.ForumsFeedXPath }); }, createEntity : function(service,data,response) { return new ForumReply({ service : service, data : data }); } }; /* * Callbacks used when reading a feed that contains forum recommendation entries. */ var ForumRecommendationFeedCallbacks = { createEntities : function(service,data,response) { return new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.ForumsFeedXPath }); }, createEntity : function(service,data,response) { return new ForumRecommendation({ service : service, data : data }); } }; /** * ForumsService class. * * @class ForumsService * @namespace sbt.connections */ var ForumService = declare(ConnectionsService, { contextRootMap: { forums: "forums" }, serviceName : "forums", /** * Constructor for ForumsService * * @constructor * @param args */ constructor : function(args) { if (!this.endpoint) { this.endpoint = config.findEndpoint(this.getDefaultEndpointName()); } }, /** * Create a Forum object with the specified data. * * @method newForum * @param {Object} args Object containing the fields for the * new Forum */ newForum : function(args) { return this._toForum(args); }, /** * Create a ForumTopic object with the specified data. * * @method newForumTopic * @param {Object} args Object containing the fields for the * new ForumTopic */ newForumTopic : function(args) { return this._toForumTopic(args); }, /** * Create a ForumReply object with the specified data. * * @method newForumReply * @param {Object} args Object containing the fields for the * new ForumReply */ newForumReply : function(args) { return this._toForumReply(args); }, /** * Get a feed that includes forums created by the authenticated user or associated with communities to which the user belongs. * * @method getMyForums * @param args */ getMyForums: function(args) { var options = { method : "GET", handleAs : "text", query : args || {} }; return this.getEntities(consts.AtomForumsMy, options, ForumFeedCallbacks); }, /** * Get a feed that includes the topics that the authenticated user created in stand-alone forums and in forums associated * with communities to which the user belongs. * * @method getMyTopics * @param requestArgs */ getMyTopics: function(requestArgs) { var options = { method : "GET", handleAs : "text", query : requestArgs || {} }; return this.getEntities(consts.AtomTopicsMy, options, ForumTopicFeedCallbacks); }, /** * Get a feed that includes all stand-alone and forum forums created in the enterprise. * * @method getAllForums * @param requestArgs */ getAllForums: function(requestArgs) { var options = { method : "GET", handleAs : "text", query : requestArgs || {} }; return this.getEntities(consts.AtomForums, options, ForumFeedCallbacks); }, /** * Get a feed that includes all stand-alone and forum forums created in the enterprise. * * @method getPublicForums * @param args */ getPublicForums: function(args) { var options = { method : "GET", handleAs : "text", query : args || {} }; return this.getEntities(consts.AtomForumsPublic, options, ForumFeedCallbacks); }, /** * Get a list for forum topics that includes the topics in the specified forum. * * @method getForumTopics * @param forumUuid * @param args * @returns */ getForumTopics: function(forumUuid, args) { var promise = this._validateForumUuid(forumUuid); if (promise) { return promise; } var requestArgs = lang.mixin({ forumUuid : forumUuid }, args || {}); var options = { method : "GET", handleAs : "text", query : requestArgs }; return this.getEntities(consts.AtomTopics, options, ForumTopicFeedCallbacks); }, /** * Get a list for forum topics that includes the topics in the specified community. * * @method getCommunityForumTopics * @param forumUuid * @param args * @returns */ getCommunityForumTopics: function(communityUuid, args) { var promise = this._validateCommunityUuid(communityUuid); if (promise) { return promise; } var requestArgs = lang.mixin({ communityUuid : communityUuid }, args || {}); var options = { method : "GET", handleAs : "text", query : requestArgs }; return this.getEntities(consts.AtomTopics, options, ForumTopicFeedCallbacks); }, /** * Get a list for forum recommendations that includes the recommendations in the specified post. * * @method getForumRecommendations * @param postUuid * @param args * @returns */ getForumRecommendations: function(postUuid, args) { var promise = this._validatePostUuid(postUuid); if (promise) { return promise; } var requestArgs = lang.mixin({ postUuid : postUuid }, args || {}); var options = { method : "GET", handleAs : "text", query : requestArgs }; return this.getEntities(consts.AtomRecommendationEntries, options, ForumRecommendationFeedCallbacks); }, /** * Get a list for forum replies that includes the replies in the specified topic. * * @method getForumTopicReplies * @param topicUuid * @param args * @returns */ getForumTopicReplies: function(topicUuid, args) { var promise = this._validateTopicUuid(topicUuid); if (promise) { return promise; } var requestArgs = lang.mixin({ topicUuid : topicUuid }, args || {}); var options = { method : "GET", handleAs : "text", query : requestArgs }; return this.getEntities(consts.AtomReplies, options, ForumReplyFeedCallbacks); }, /** * Get a list for forum replies that includes the replies in the specified reply. * * @method getForumReplyReplies * @param replyUuid * @param args * @returns */ getForumReplyReplies: function(replyUuid, args) { var promise = this._validateReplyUuid(replyUuid); if (promise) { return promise; } var requestArgs = lang.mixin({ replyUuid : replyUuid }, args || {}); var options = { method : "GET", handleAs : "text", query : requestArgs }; return this.getEntities(consts.AtomReplies, options, ForumReplyFeedCallbacks); }, /** * Get a list for forum replies that includes the replies in the specified post. * The post uuid must be specified in the args as either: * { topicUuid : "<topicUuid>" } or { replyUuid : "<replyUuid>" } * * @method getForumReplies * @param topicUuid * @param args * @returns */ getForumReplies: function(args) { var options = { method : "GET", handleAs : "text", query : args }; return this.getEntities(consts.AtomReplies, options, ForumReplyFeedCallbacks); }, /** * Retrieve a list of all forum entries, add communityUuid to the requestArgs object to get the forums related to a specific community. * * @method getForums * @param {Object} requestArgs Object containing the query arguments to be * sent (defined in IBM Connections Communities REST API) */ getForums : function(requestArgs) { var options = { method : "GET", handleAs : "text", query : requestArgs || {} }; return this.getEntities(consts.AtomForums, options, ForumFeedCallbacks); }, /** * Retrieve a forum entry, use the edit link for the forum entry * which can be found in the my communities feed. * * @method getForum * @param {String } forumUuid * @param {Object} args Object containing the query arguments to be * sent (defined in IBM Connections Communities REST API) */ getForum : function(forumUuid, args) { var forum = new Forum({ service : this, _fields : { forumUuid : forumUuid } }); return forum.load(args); }, /** * Create a forum by sending an Atom entry document containing the * new forum to the My Forums resource. * * @method createForum * @param {Object} forum Forum object which denotes the forum to be created. * @param {Object} [args] Argument object */ createForum : function(forumOrJson,args) { var forum = this._toForum(forumOrJson); var promise = this._validateForum(forum, false, args); if (promise) { return promise; } var callbacks = {}; callbacks.createEntity = function(service,data,response) { forum.setData(data); var forumUuid = this.getLocationParameter(response, "forumUuid"); forum.setForumUuid(forumUuid); return forum; }; var options = { method : "POST", query : args || {}, headers : consts.AtomXmlHeaders, data : forum.createPostData() }; return this.updateEntity(consts.AtomForumsMy, options, callbacks, args); }, /** * Update a forum by sending a replacement forum entry document in Atom format * to the existing forum's edit web address. * All existing forum entry information will be replaced with the new data. To avoid * deleting all existing data, retrieve any data you want to retain first, and send it back * with this request. For example, if you want to add a new tag to a forum entry, retrieve * the existing tags, and send them all back with the new tag in the update request. * * @method updateForum * @param {Object} forum Forum object * @param {Object} [args] Argument object */ updateForum : function(forumOrJson,args) { var forum = this._toForum(forumOrJson); var promise = this._validateForum(forum, true, args); if (promise) { return promise; } var callbacks = {}; callbacks.createEntity = function(service,data,response) { // preserve the forumUuid var forumUuid = forum.getForumUuid(); forum.setData(data); forum.setForumUuid(forumUuid); return forum; }; var requestArgs = lang.mixin({ forumUuid : forum.getForumUuid() }, args || {}); var options = { method : "PUT", query : requestArgs, headers : consts.AtomXmlHeaders, data : forum.createPostData() }; return this.updateEntity(consts.AtomForum, options, callbacks, args); }, /** * Delete a forum, use the HTTP DELETE method. * Only the owner of a forum can delete it. Deleted communities cannot be restored * * @method deleteForum * @param {String/Object} forum id of the forum or the forum object (of the forum to be deleted) * @param {Object} [args] Argument object */ deleteForum : function(forumUuid,args) { var promise = this._validateForumUuid(forumUuid); if (promise) { return promise; } var requestArgs = lang.mixin({ forumUuid : forumUuid }, args || {}); var options = { method : "DELETE", query : requestArgs, handleAs : "text" }; return this.deleteEntity(consts.AtomForum, options, forumUuid); }, /** * Retrieve a forum topic entry, use the edit link for the forum topic entry * which can be found in the My Forums feed. * * @method getForumTopic * @param {String } topicUuid * @param {Object} args Object containing the query arguments to be * sent (defined in IBM Connections Communities REST API) */ getForumTopic : function(topicUuid, args) { var forumTopic = new ForumTopic({ service : this, _fields : { topicUuid : topicUuid } }); return forumTopic.load(args); }, /** * Create a forum topc by sending an Atom entry document containing the * new forum to the forum replies resource. * * @method createForumTopic * @param {Object} forumTopic Forum topic object which denotes the forum topic to be created. * @param {Object} [args] Argument object */ createForumTopic : function(topicOrJson,args) { var forumTopic = this._toForumTopic(topicOrJson); var promise = this._validateForumTopic(forumTopic, false, args); if (promise) { return promise; } var callbacks = {}; callbacks.createEntity = function(service,data,response) { var topicUuid = this.getLocationParameter(response, "topicUuid"); forumTopic.setTopicUuid(topicUuid); forumTopic.setData(data); return forumTopic; }; var requestArgs = lang.mixin({ forumUuid : forumTopic.getForumUuid() }, args || {}); var options = { method : "POST", query : requestArgs, headers : consts.AtomXmlHeaders, data : forumTopic.createPostData() }; return this.updateEntity(consts.AtomTopics, options, callbacks, args); }, /** * Update a forum topic by sending a replacement forum entry document in Atom format * to the existing forum topic's edit web address. * All existing forum entry information will be replaced with the new data. To avoid * deleting all existing data, retrieve any data you want to retain first, and send it back * with this request. For example, if you want to add a new tag to a forum entry, retrieve * the existing tags, and send them all back with the new tag in the update request. * * @method updateForumTopic * @param {Object} topicOrJson Forum topic object * @param {Object} [args] Argument object */ updateForumTopic : function(topicOrJson,args) { var forumTopic = this._toForumTopic(topicOrJson); var promise = this._validateForumTopic(forumTopic, true, args); if (promise) { return promise; } var callbacks = {}; callbacks.createEntity = function(service,data,response) { // preserve the topicUuid var topicUuid = forumTopic.getTopicUuid(); forumTopic.setData(data); forumTopic.setTopicUuid(topicUuid); return forumTopic; }; var requestArgs = lang.mixin({ topicUuid : forumTopic.getTopicUuid() }, args || {}); var options = { method : "PUT", query : requestArgs, headers : consts.AtomXmlHeaders, data : forumTopic.createPostData() }; return this.updateEntity(consts.AtomTopic, options, callbacks, args); }, /** * Delete a forum topic, use the HTTP DELETE method. * Only the owner of a forum topic can delete it. Deleted forum topics cannot be restored * * @method deleteForumTopic * @param {String/Object} id of the forum topic to be deleted * @param {Object} [args] Argument object */ deleteForumTopic : function(topicUuid,args) { var promise = this._validateTopicUuid(topicUuid); if (promise) { return promise; } var requestArgs = lang.mixin({ topicUuid : topicUuid }, args || {}); var options = { method : "DELETE", query : requestArgs, handleAs : "text" }; return this.deleteEntity(consts.AtomTopic, options, topicUuid); }, /** * Retrieve a forum reply entry, use the edit link for the forum reply entry * which can be found in the my communities feed. * * @method getForumReply * @param {String } replyUuid * @param {Object} args Object containing the query arguments to be * sent (defined in IBM Connections Communities REST API) */ getForumReply : function(replyUuid, args) { var forumReply = new ForumReply({ service : this, _fields : { replyUuid : replyUuid } }); return forumReply.load(args); }, /** * Create a forum reply by sending an Atom entry document containing the * new forum reply to the My Communities resource. * * @method createForumReply * @param {Object} reply ForumReply object which denotes the forum to be created. * @param {Object} [args] Argument object */ createForumReply : function(replyOrJson,args) { var forumReply = this._toForumReply(replyOrJson); var promise = this._validateForumReply(forumReply, false, args); if (promise) { return promise; } var callbacks = {}; callbacks.createEntity = function(service,data,response) { var replyUuid = this.getLocationParameter(response, "replyUuid"); forumReply.setReplyUuid(replyUuid); forumReply.setData(data); return forumReply; }; var options = { method : "POST", query : args || { topicUuid : forumReply.getTopicUuid() }, headers : consts.AtomXmlHeaders, data : forumReply.createPostData() }; return this.updateEntity(consts.AtomReplies, options, callbacks, args); }, /** * Update a forum by sending a replacement forum entry document in Atom format * to the existing forum's edit web address. * All existing forum entry information will be replaced with the new data. To avoid * deleting all existing data, retrieve any data you want to retain first, and send it back * with this request. For example, if you want to add a new tag to a forum entry, retrieve * the existing tags, and send them all back with the new tag in the update request. * * @method updateForumReply * @param {Object} replyOrJson Forum reply object * @param {Object} [args] Argument object */ updateForumReply : function(replyOrJson,args) { var forumReply = this._toForumReply(replyOrJson); var promise = this._validateForumReply(forumReply, true, args); if (promise) { return promise; } var callbacks = {}; callbacks.createEntity = function(service,data,response) { // preserve the replyUuid var replyUuid = forumReply.getReplyUuid(); forumReply.setData(data); forumReply.setReplyUuid(replyUuid); return forumReply; }; var requestArgs = lang.mixin({ replyUuid : forumReply.getReplyUuid() }, args || {}); var options = { method : "PUT", query : requestArgs, headers : consts.AtomXmlHeaders, data : forumReply.createPostData() }; return this.updateEntity(consts.AtomReply, options, callbacks, args); }, /** * Delete a forum reply, use the HTTP DELETE method. * Only the owner of a forum reply can delete it. Deleted forum replies cannot be restored * * @method deleteForumReply * @param {String/Object} Id of the forum reply to be deleted * @param {Object} [args] Argument object */ deleteForumReply : function(replyUuid,args) { var promise = this._validateReplyUuid(replyUuid); if (promise) { return promise; } var requestArgs = lang.mixin({ replyUuid : replyUuid }, args || {}); var options = { method : "DELETE", query : requestArgs, handleAs : "text" }; return this.deleteEntity(consts.AtomReply, options, replyUuid); }, /** * Retrieve complete information about recommendations to a post(topic/reply) in a stand-alone forum. * * @method getForumRecommendation * @param postUuid * @param args */ getForumRecommendation : function(postUuid, args) { var forumRecommendation = new ForumRecommendation({ service : this, _fields : { postUuid : postUuid } }); return forumRecommendation.load(args); }, /** * To like a post(topic/reply) in a stand-alone forum, create forum recommendation to the forum topic/reply resources. * * @method createForumRecommendation * @param recommendationOrJson * @param args */ createForumRecommendation : function(recommendationOrJson, args) { var forumRecommendation = this._toForumRecommendation(recommendationOrJson); var promise = this._validateForumRecommendation(forumRecommendation, false, args); if (promise) { return promise; } var callbacks = {}; callbacks.createEntity = function(service,data,response) { forumRecommendation.setData(data); return forumRecommendation; }; var options = { method : "POST", query : args || { postUuid : forumRecommendation.getPostUuid() }, headers : consts.AtomXmlHeaders, data : forumRecommendation.createPostData() }; return this.updateEntity(consts.AtomRecommendationEntries, options, callbacks, args); }, /** * Delete a recommendation of a post(topic or reply) in a forum. * Only the user who have already recommended the post can delete it's own recommendation. * * @method deleteForumRecommendation * @param postUuid * @param args */ deleteForumRecommendation : function(postUuid, args) { var promise = this._validatePostUuid(postUuid); if (promise) { return promise; } var requestArgs = lang.mixin({ postUuid : postUuid }, args || {}); var options = { method : "DELETE", query : requestArgs, handleAs : "text" }; return this.deleteEntity(consts.AtomRecommendationEntries, options, postUuid); }, // // Internals // /* * Validate a forum and return a Promise if invalid. */ _validateForum : function(forum,checkUuid) { if (!forum || !forum.getTitle()) { return this.createBadRequestPromise("Invalid argument, forum with title must be specified."); } if (checkUuid && !forum.getForumUuid()) { return this.createBadRequestPromise("Invalid argument, forum with UUID must be specified."); } }, /* * Validate a forum topic and return a Promise if invalid. */ _validateForumTopic : function(forumTopic,checkUuid) { if (!forumTopic || !forumTopic.getTitle()) { return this.createBadRequestPromise("Invalid argument, forum topic with title must be specified."); } if (checkUuid && !forumTopic.getTopicUuid()) { return this.createBadRequestPromise("Invalid argument, forum topic with UUID must be specified."); } }, /* * Validate a forum reply and return a Promise if invalid. */ _validateForumReply : function(forumReply,checkUuid) { if (!forumReply || !forumReply.getTitle()) { return this.createBadRequestPromise("Invalid argument, forum reply with title must be specified."); } if (checkUuid && !forumReply.getReplyUuid()) { return this.createBadRequestPromise("Invalid argument, forum reply with UUID must be specified."); } }, /* * Validate a forum recommendation and return a Promise if invalid. */ _validateForumRecommendation : function(forumRecommendation,checkUuid) { if (!forumRecommendation || !forumRecommendation.getPostUuid()) { return this.createBadRequestPromise("Invalid argument, forum recommendation with postUuid must be specified."); } if (checkUuid && !forumRecommendation.getRecommendationUuid()) { return this.createBadRequestPromise("Invalid argument, forum recommendation with UUID must be specified."); } }, /* * Validate a forum UUID, and return a Promise if invalid. */ _validateForumUuid : function(forumUuid) { if (!forumUuid || forumUuid.length == 0) { return this.createBadRequestPromise("Invalid argument, expected forumUuid."); } }, /* * Validate a community UUID, and return a Promise if invalid. */ _validateCommunityUuid : function(communityUuid) { if (!communityUuid || communityUuid.length == 0) { return this.createBadRequestPromise("Invalid argument, expected communityUuid."); } }, /* * Validate a post UUID, and return a Promise if invalid. */ _validatePostUuid : function(postUuid) { if (!postUuid || postUuid.length == 0) { return this.createBadRequestPromise("Invalid argument, expected postUuid."); } }, /* * Validate a topic UUID, and return a Promise if invalid. */ _validateTopicUuid : function(topicUuid) { if (!topicUuid || topicUuid.length == 0) { return this.createBadRequestPromise("Invalid argument, expected topicUuid."); } }, /* * Validate a reply UUID, and return a Promise if invalid. */ _validateReplyUuid : function(replyUuid) { if (!replyUuid || replyUuid.length == 0) { return this.createBadRequestPromise("Invalid argument, expected replyUuid."); } }, /* * Return a Forum instance from Forum or JSON or String. Throws * an error if the argument was neither. */ _toForum : function(forumOrJsonOrString) { if (forumOrJsonOrString instanceof Forum) { return forumOrJsonOrString; } else { if (lang.isString(forumOrJsonOrString)) { forumOrJsonOrString = { forumUuid : forumOrJsonOrString }; } return new Forum({ service : this, _fields : lang.mixin({}, forumOrJsonOrString) }); } }, /* * Return a ForumTopic instance from Forum or JSON or String. Throws * an error if the argument was neither. */ _toForumTopic : function(topicOrJsonOrString) { if (topicOrJsonOrString instanceof ForumTopic) { return topicOrJsonOrString; } else { if (lang.isString(topicOrJsonOrString)) { topicOrJsonOrString = { forumTopicUuid : topicOrJsonOrString }; } return new ForumTopic({ service : this, _fields : lang.mixin({}, topicOrJsonOrString) }); } }, /* * Return a Forum instance from ForumReply or JSON or String. Throws * an error if the argument was neither. */ _toForumReply : function(replyOrJsonOrString) { if (replyOrJsonOrString instanceof ForumReply) { return replyOrJsonOrString; } else { if (lang.isString(replyOrJsonOrString)) { replyOrJsonOrString = { forumReplyUuid : replyOrJsonOrString }; } return new ForumReply({ service : this, _fields : lang.mixin({}, replyOrJsonOrString) }); } }, /* * Return a ForumRecommendation instance from ForumRecommendation, ForumTopic, * ForumReply or JSON or String. Throws an error if the argument was neither. */ _toForumRecommendation : function(entityOrJsonOrString) { if (entityOrJsonOrString instanceof ForumRecommendation) { return entityOrJsonOrString; } else { if (lang.isString(entityOrJsonOrString)) { entityOrJsonOrString = { postUuid : entityOrJsonOrString }; } if (entityOrJsonOrString instanceof ForumTopic) { entityOrJsonOrString = { postUuid : entityOrJsonOrString.getTopicUuid() }; } if (entityOrJsonOrString instanceof ForumReply) { entityOrJsonOrString = { postUuid : entityOrJsonOrString.getReplyUuid() }; } return new ForumRecommendation({ service : this, _fields : lang.mixin({}, entityOrJsonOrString) }); } } }); return ForumService; }); }, 'sbt/connections/nls/CommunityService':function(){ /* * © Copyright IBM Corp. 2012,2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK - Default resource bundle for CommunityService */ define({ root: ({ invalid_argument : "Invalid Argument" }) }); }, 'sbt/nls/messageSSO':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK - Default resource bundle for validate module. */ define({ root: ({ message_title: "ReAuthenticate", message:"Authentication expired, Please login again.", relogin_button_text: "Re-Login" }) }); }, 'sbt/connections/BlogConstants':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. Definition of constants for BlogService. * * @module sbt.connections.BlogConstants */ define([ "../lang", "./ConnectionsConstants" ], function(lang,conn) { return lang.mixin({}, conn, { /** * XPath expressions used when parsing a Connections Blogs ATOM feed * * @property BlogFeedXPath * @type Object * @for sbt.connections.BlogService */ BlogFeedXPath : conn.ConnectionsFeedXPath, RecommendersFeedXpath : { entries : "/a:feed/a:entry", totalResults : "/a:feed/os:totalResults" }, /** * Namespaces to be used when reading the Blogs ATOM entry or feed */ BlogNamespaces : { a : "http://www.w3.org/2005/Atom", app : "http://www.w3.org/2007/app", snx : "http://www.ibm.com/xmlns/prod/sn" }, /** * XPath expressions to be used when reading a Blog * * @property BlogXPath * @type Object * @for sbt.connections.BlogService */ BlogXPath : lang.mixin({}, conn.AtomEntryXPath, { blogUuid : "a:id", handle : "snx:handle", timezone : "snx:timezone", rank : "snx:rank[@scheme='http://www.ibm.com/xmlns/prod/sn/recommendations']", categoryupdates : "a:category[@term='updates']", categoryfaq : "a:category[@term='faq']", categorywith : "a:category[@term='with']", categoryshared : "a:category[@term='shared']", communityUuid : "snx:communityUuid", containerUrl : "a:link[@rel='http://www.ibm.com/xmlns/prod/sn/container']/@href", containerType : "snx:containertype", categoryFlags : "a:link[@scheme='http://www.ibm.com/xmlns/prod/sn/flags']/@term", summary : "a:summary[@type='html']" }), /** * XPath expressions to be used when reading a Blog Post * * @property BlogPostXPath * @type Object * @for sbt.connections.BlogService */ BlogPostXPath : lang.mixin({}, conn.AtomEntryXPath, { postUuid : "a:id", replies : "a:link[@rel='replies']/@href", recommendationsUrl : "a:link[@rel='http://www.ibm.com/xmlns/prod/sn/recommendations']/@href", rankRecommendations : "snx:rank[@scheme='http://www.ibm.com/xmlns/prod/sn/recommendations']", rankComment : "snx:rank[@scheme='http://www.ibm.com/xmlns/prod/sn/comment']", rankHit : "snx:rank[@scheme='http://www.ibm.com/xmlns/prod/sn/hit']", repliesUrl : "a:link[@rel='replies']/@href", sourceId : "a:source/a:id", sourceTitle : "a:source/a:title ", sourceLink : "a:source/a:link[@rel='self']/@href", sourceLinkAlternate : "a:source/a:link[@rel='alternate']/@href", sourceUpdated : "a:source/a:updated", sourceCategory : "a:source/a:link[@scheme='http://www.ibm.com/xmlns/prod/sn/type']/@term", blogHandle : "blogHandle", summary : "a:summary[@type='html']" }), /** * XPath expressions to be used when reading a Blog Post Comment * * @property CommentXPath * @type Object * @for sbt.connections.BlogService */ CommentXPath : lang.mixin({}, conn.AtomEntryXPath, { commentUuid : "a:id", commentUrl : "a:link[@rel='self']/@href", recommendationsUrl : "a:link[@rel='http://www.ibm.com/xmlns/prod/sn/recommendations']/@href", trackbacktitle : "snx:trackbacktitle", replyTo : "thr:in-reply-to/@ref", replyToSource : "thr:in-reply-to/@source", rankRecommendations : "snx:rank[@scheme='http://www.ibm.com/xmlns/prod/sn/recommendations']", sourceId : "a:source/a:id", sourceTitle : "a:source/a:title ", sourceLink : "a:source/a:link[@rel='self']/@href", sourceLinkAlternate : "a:source/a:link[@rel='alternate']/@href", blogHandle : "blogHandle", blogPostUuid : "blogPostUuid" }), /** * XPath expressions to be used when reading a Blog Post Recommenders feed * * @property RecommendersXPath * @type Object * @for sbt.connections.BlogService */ RecommendersXPath : lang.mixin({}, conn.AtomEntryXPath, { recommenderUuid : "a:id", category : "a:category[@scheme='http://www.ibm.com/xmlns/prod/sn/type']/@term" }), /** * page Page number. Specifies the page to be returned. The default value is 1, which returns the first page. * ps Page size. Specify the number of entries to return per page. * search Well-formed full text search query. Performs a text search on community titles and descriptions. * since Includes in the resulting feed all communities updated after a specified date. Specify the date using a date-time value that conforms to RFC3339. Use an upper case "T" to separate the date and time, and an uppercase "Z" in the absence of a numeric time zone offset. For example: 2009-01-04T20:32:31.171Z. * sortBy Specifies what value to use as the basis for organizing the entries returned in the feed. The options are: * modified © Sorts the results by last modified date. * commented - Sorts the entries by the number of comments or replies an item has received. * popularity - Sorts the entries by how popular the item is. * recommended - Sorts the entries by the number of times the item was recommended. * title - Sorts the entries alphabetically by title. The title used is the text that is displayed in the <title> element of each entry in the feed. * sortOrder Specifies the order in which to sort the results. The options are: * asc - Sorts the results in ascending order. * desc - Sorts the results in descending order. * communityUuid Returns community blog and community ideation blog in the specified community. * ps Page size. Specify the number of entries to return per page. * blogType Returns only specific Blogs type: * blog - regular blogs and community blogs * communityblog - community blogs only * communityideationblog - community ideation blogs only * tags Returns blog entries with the specified tags. Separate multiple tags with a plus sign (+). */ /** * A feed of all blogs. * * Get the Blogs feed to see a list of all blogs * * Supports: page, ps, sortBy, sortOrder, search, since, communityUuid, blogType, sortField, tag * * @property AtomBlogsAll * @type String * @for sbt.connections.BlogService */ AtomBlogsAll : "/${blogs}/{blogHomepageHandle}/feed/blogs/atom", /** * A feed of my blogs. * * Get the Blogs feed to see a list of Blogs created by logged in user * * Supports: page, ps, sortBy, sortOrder, search, since, communityUuid, blogType, sortField, tag * * @property AtomBlogsMy * @type String * @for sbt.connections.BlogService */ AtomBlogsMy : "/${blogs}/{blogHomepageHandle}/api/blogs", /** * A blog instance. * * @property AtomBlogInstance * @type String * @for sbt.connections.BlogService */ AtomBlogInstance : "/${blogs}/{blogHomepageHandle}/api/blogs/{blogUuid}", /** * A blog post entry. * * @property AtomBlogPostInstance * @type String * @for sbt.connections.BlogService */ AtomBlogPostInstance : "/${blogs}/{blogHomepageHandle}/api/entries/{postUuid}", /** * A feed of all blogs posts. * * Get the Blogs posts feed to see a list of posts from all Blogs * * Supports: page, ps, sortBy, sortOrder, search, since * * @property AtomEntriesAll * @type String * @for sbt.connections.BlogService */ AtomEntriesAll : "/${blogs}/{blogHomepageHandle}/feed/entries/atom", /** * A feed of a blog's posts. * * Get the Blog posts feed to see a list of posts from a Blog * * Supports: page, ps, sortBy, sortOrder, search, since * * @property AtomBlogEntries * @type String * @for sbt.connections.BlogService */ AtomBlogEntries : "/${blogs}/{blogHandle}/feed/entries/atom", /** * A feed of a blog's comments. * * Get the Blog Comments feed to see a list of comments from a blog post * * Supports: page, ps, sortBy, sortOrder, search, since * * @property AtomBlogComments * @type String * @for sbt.connections.BlogService */ AtomBlogComments : "/${blogs}/{blogHandle}/feed/comments/atom", /** * A feed of a blog's comments. * * Get the Blog Comments feed to see a list of comments from all blog post * * Supports: page, ps, sortBy, sortOrder, search, since * * @property AtomBlogCommentsAll * @type String * @for sbt.connections.BlogService */ AtomBlogCommentsAll : "/${blogs}/{blogHomepageHandle}/feed/comments/atom", /** * A feed of featured blogs. * * Get the featured blogs feed to find the blogs that have had the most activity across * all of the blogs hosted by the Blogs application in the past two weeks. * * Supports: page, ps, sortBy, sortOrder, search, since * * @property AtomBlogsFeatured * @type String * @for sbt.connections.BlogService */ AtomBlogsFeatured : "/${blogs}/{blogHomepageHandle}/feed/featuredblogs/atom", /** * A feed of featured blogs posts. * * Get the featured posts feed to find the blog posts that have had the most activity across * all of the blogs hosted by the Blogs application within the past two weeks * * Supports: page, ps, sortBy, sortOrder, search, since * * @property AtomBlogsPostsFeatured * @type String * @for sbt.connections.BlogService */ AtomBlogsPostsFeatured : "/${blogs}/{blogHomepageHandle}/feed/featured/atom", /** * A feed of featured blogs posts. * * Get a feed that includes all of the recommended blog posts * in all of the blogs hosted by the Blogs application. * * Supports: page, ps, sortBy, sortOrder, search, since * * @property AtomBlogsPostsRecommended * @type String * @for sbt.connections.BlogService */ AtomBlogsPostsRecommended : "/${blogs}/{blogHomepageHandle}/feed/recommended/atom", /** * A feed of blogs tags. * * Get a feed that includes all of the tags * in all of the blogs hosted by the Blogs application. * * @property AtomBlogsTags * @type String * @for sbt.connections.BlogService */ AtomBlogsTags : "/${blogs}/{blogHomepageHandle}/feed/tags/atom", /** * A feed of blog tags. * * Get a feed that includes all of the tags * in a perticular Blog. * * @property AtomBlogTags * @type String * @for sbt.connections.BlogService */ AtomBlogTags : "/${blogs}/{blogHandle}/feed/tags/atom", /** * Create a Blog. * * @property AtomBlogCreate * @type String * @for sbt.connections.BlogService */ AtomBlogCreate : "/${blogs}/{blogHomepageHandle}/api/blogs", /** * Edit or remove a Blog. * * @property AtomBlogEditDelete * @type String * @for sbt.connections.BlogService */ AtomBlogEditDelete : "/${blogs}/{blogHomepageHandle}/api/blogs/{blogUuid}", /** * Create, Edit or remove a Blog Post. * * @property AtomBlogPostCreate * @type String * @for sbt.connections.BlogService */ AtomBlogPostCreate : "/${blogs}/{blogHandle}/api/entries", /** * Edit or remove a Blog Post. * * @property AtomBlogPostEditDelete * @type String * @for sbt.connections.BlogService */ AtomBlogPostEditDelete : "/${blogs}/{blogHandle}/api/entries/{postUuid}", /** * Create, Edit or remove a Blog Comment. * * @property AtomBlogCommentCreate * @type String * @for sbt.connections.BlogService */ AtomBlogCommentCreate : "/${blogs}/{blogHandle}/api/entrycomments/{postUuid}", /** * Edit or remove a Blog Comment. * * @property AtomBlogCommentEditRemove * @type String * @for sbt.connections.BlogService */ AtomBlogCommentEditRemove : "/${blogs}/{blogHandle}/api/comments/{commentUuid}", /** * Recommend or Unrecommend a Blog Post. * * @property AtomRecommendBlogPost * @type String * @for sbt.connections.BlogService */ AtomRecommendBlogPost : "/${blogs}/{blogHandle}/api/recommend/entries/{postUuid}", /** * Get list of voted Ideas by user. * * @property AtomVotedIdeas * @type String * @for sbt.connections.IdeationBlogService */ AtomVotedIdeas : "/${blogs}/{blogHomepageHandle}/feed/myvotes/atom", /** * Get list of comments to the specified blog entry. * * @property AtomBlogEntryComments * @type String * @for sbt.connections.BlogService */ AtomBlogEntryComments : "/${blogs}/{blogHandle}/feed/entrycomments/{entryAnchor}/atom" }); }); }, 'sbt/connections/ConnectionsConstants':function(){ /* * © Copyright IBM Corp. 2012,2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. Definition of constants for IBM Connections. * * @module sbt.connections.ConnectionsConstants */ define([ "../lang", "../base/BaseConstants" ], function(lang, base) { return lang.mixin(base, { /** * Error code used for a bad request */ BadRequest : 400, /** * XPath expressions used when parsing a Connections ATOM feed */ ConnectionsFeedXPath : { // used by getEntitiesDataArray entries : "/a:feed/a:entry", // used by getSummary totalResults : "/a:feed/opensearch:totalResults", startIndex : "/a:feed/opensearch:startIndex", itemsPerPage : "/a:feed/opensearch:itemsPerPage" }, /** * XPath expressions used when parsing a Connections service document ATOM feeds */ ConnectionsServiceDocsFeedXPath : { // used by getEntitiesDataArray entries : "/a:feed/a:entry", // used by getSummary emailConfig : "/a:feed/a:category[@scheme='http://www.ibm.com/xmlns/prod/sn/configuration']/@term", language : "/a:feed/a:category[@scheme='http://www.ibm.com/xmlns/prod/sn/language']/@term", languageLabels : "/a:feed/a:category[@scheme='http://www.ibm.com/xmlns/prod/sn/language']/@label" }, /** * AuthType variable values for endpoint * * @property AuthTypes * @type Object */ AuthTypes : { OAuth : "oauth", Basic : "basic" }, /** * XPath expressions to be used when reading a Connections entity * * @property TagsXPath * @type Object */ TagsXPath : { entries : "app:categories/a:category", term : "@term", frequency : "@snx:frequency", uid : "@term" }, /** * XPath expressions to be used when reading a Blog * * @property BlogXPath * @type Object */ ServiceConfigXPath : lang.mixin({}, base.AtomEntryXPath, { alternateSSLUrl : "a:link[@rel='http://www.ibm.com/xmlns/prod/sn/alternate-ssl']/@href" }), /** * XPath expressions to be used when reading a Member Entry * * @property MemberXPath * @type Object */ MemberXPath : lang.mixin({}, base.AtomEntryXPath, { role : "snx:role" }), /** * XPath expressions to be used when reading a Report Entry * * @property MemberXPath * @type Object */ ReportEntryXPath : lang.mixin({}, base.AtomEntryXPath, { categoryIssue : "a:category[@scheme='http://www.ibm.com/xmlns/prod/sn/issue']/@term", reportItemLink : "a:link[@rel='http://www.ibm.com/xmlns/prod/sn/report-item']/@href", relatedLink : "a:link[@rel='related']/@href", inRefTo : "snx:in-ref-to[@rel='http://www.ibm.com/xmlns/prod/sn/report-item']/@ref" }), /** * XPath expressions to be used when reading a Moderation Action Entry * * @property MemberXPath * @type Object */ ModerationActionEntryXPath : lang.mixin({}, base.AtomEntryXPath, { moderationAction : "snx:moderation/action", relatedLink : "a:link[@rel='related']/@href", inRefTo : "snx:in-ref-to[@rel='http://www.ibm.com/xmlns/prod/sn/report-item']/@ref" }), /** * Get service configs */ ServiceConfigs : "/{service}/serviceconfigs" }); }); }, 'sbt/authenticator/Basic':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. * Definition of an authentication mechanism. */ define(["../declare", "../lang", "../util", "../i18n!../nls/loginForm"],function(declare, lang, util, loginForm) { /** * Proxy basic authentication. * * This class triggers the authentication for a service. */ return declare(null, { loginUi: "", loginPage: "/sbt/authenticator/templates/login.html", dialogLoginPage:"authenticator/templates/loginDialog.html", url: "", actionUrl: "", /** * Constructor, necessary so that this.url is not empty. * It may also mixin loginUi, loginPage or dialogLoginPage if they are present in sbt.properties. */ constructor: function(args){ lang.mixin(this, args || {}); }, /** * Method that authenticate the current user . * * This is a working version. But this is work in progress with following todos * * todos: * Internationalization */ authenticate: function(options) { var self = this; require(['sbt/config'], function(config){ var mode = options.loginUi || config.Properties["loginUi"] || self.loginUi; var loginPage = options.loginPage || config.Properties["loginPage"] || self.loginPage; var dialogLoginPage = options.dialogLoginPage || config.Properties["dialogLoginPage"] || self.dialogLoginPage; if(mode=="popup") { self._authPopup(options, loginPage, config, self.url); } else if(mode=="dialog") { self._authDialog(options, dialogLoginPage, config); } else { self._authMainWindow(options, loginPage, self.url); } }); return true; }, _authDialog: function(options, dialogLoginPage, sbtConfig) { var self = this; require(["sbt/_bridge/ui/BasicAuth_Dialog", "sbt/dom"], function(dialog, dom) { if(options.cancel){ sbtConfig.cancel = options.cancel; } options.actionUrl = self._computeActionURL(options); dialog.show(options, dialogLoginPage); dom.setText('wrongCredsMessage', loginForm.wrong_creds_message); dom.setText('basicLoginFormUsername', loginForm.username); dom.setText('basicLoginFormPassword', loginForm.password); dom.setAttr(dom.byId('basicLoginFormOK'), "value", loginForm.login_ok); dom.setAttr(dom.byId('basicLoginFormCancel'), "value", loginForm.login_cancel); }); return true; }, _authPopup: function(options, loginPage, sbtConfig, sbtUrl) { var actionURL = this._computeActionURL(options); var urlParamsMap = { actionURL: actionURL, redirectURL: 'empty', loginUi: 'popup', showWrongCredsMessage: 'false' }; var urlParams = util.createQuery(urlParamsMap, "&"); var url = sbtUrl+loginPage + '?' + urlParams; var windowParamsMap = { width: window.screen.availWidth / 2, height: window.screen.availHeight / 2, left: window.screen.availWidth / 4, top: window.screen.availHeight / 4, menubar: 0, toolbar: 0, status: 0, location: 0, scrollbars: 1, resizable: 1 }; var windowParams = util.createQuery(windowParamsMap, ","); var loginWindow = window.open(url,'Authentication', windowParams); if(options.callback){ sbtConfig.callback = options.callback; loginWindow.callback = options.callback; } if(options.cancel){ sbtConfig.cancel = options.cancel; loginWindow.cancel = options.cancel; } globalLoginFormStrings = loginForm; globalEndpointAlias = options.name; loginWindow.focus(); return true; }, _authMainWindow: function(options, loginPage, sbtUrl) { var actionURL = this._computeActionURL(options); var urlParamsMap = { actionURL: actionURL, redirectURL: document.URL, loginUi: 'mainWindow', showWrongCredsMessage: 'false', username: loginForm.username, password: loginForm.password, login_ok: loginForm.login_ok, login_cancel: loginForm.login_cancel, wrong_creds_message: loginForm.wrong_creds_message }; var urlParams = util.createQuery(urlParamsMap, "&"); var url = sbtUrl+loginPage + '?' + urlParams; window.location.href = url; return true; }, _computeActionURL: function(options) { if (!this.actionUrl) { var proxy = options.proxy.proxyUrl; return proxy.substring(0,proxy.lastIndexOf("/"))+"/basicAuth/"+options.proxyPath+"/JSApp"; } return this.actionUrl; } } ); }); }, 'sbt/connections/BookmarkConstants':function(){ /* * © Copyright IBM Corp. 2012,2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. Definition of constants for BookmarkService. * * @module sbt.connections.BookmarkConstants */ define([ "../lang", "./ConnectionsConstants" ], function(lang,conn) { return lang.mixin({}, conn, { BookmarkFeedXPath : conn.ConnectionsFeedXPath, /** * XPath expressions * * @property BookmarkXPath * @type Object * @for sbt.connections.CommunityService */ BookmarkXPath : lang.mixin({}, conn.AtomEntryXPath, { BookmarkUuid: "a:id", privateFlag: "a:category[@term='private' and @scheme='http://www.ibm.com/xmlns/prod/sn/flags']", categoryType: "a:category[@scheme='http://www.ibm.com/xmlns/prod/sn/type']/@term", link: "a:link[not(@rel)]/@href", linkSame: "a:link[@rel='http://www.ibm.com/xmlns/prod/sn/same']/@href", url: "a:link[1]/@href", authorId:"a:author/snx:userid", authorName: "a:author/a:name", authorEmail: "a:author/a:email", authorUri: "a:author/a:uri", tags : "a:category[not(@scheme)]/@term", clickcount: "snx:clickcount" }), /** * Namespaces to be used when reading the Bookmarks ATOM entry or feed */ BookmarkNamespaces : { a : "http://www.w3.org/2005/Atom", snx : "http://www.ibm.com/xmlns/prod/sn" }, /** * A feed of all bookmarks. * * @property AtomBookmarkssAll * @type String * @for sbt.connections.BoomarkService */ AtomBookmarksAll : "/${dogear}/atom", /** * A feed of popular bookmarks. * * @property AtomBookmarkssAll * @type String * @for sbt.connections.BoomarkService */ AtomBookmarksPopular : "/${dogear}/atom/popular", /** * A feed of bookmarks that others notified me about. * * @property AtomBookmarkssAll * @type String * @for sbt.connections.BoomarkService */ AtomBookmarksMyNotifications : "/${dogear}/atom/mynotifications", /** * A feed of bookmarks about which I notified others. * * @property AtomBookmarkssAll * @type String * @for sbt.connections.BoomarkService */ AtomBookmarksINotifiedMySentNotifications : "/${dogear}/atom/mysentnotifications", /** * A feed of all bookmark tags. * * @property AtomBookmarksTags * @type String * @for sbt.connections.BoomarkService */ AtomBookmarksTags : "/${dogear}/tags", /** * create delete or update a bookmark. * * @property AtomBookmarkCreateUpdateDelete * @type String * @for sbt.connections.BoomarkService */ AtomBookmarkCreateUpdateDelete : "/${dogear}/api/app" }); }); }, 'sbt/log':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK - Logging Utilities * @module sbt.log */ define(['./stringUtil'], function(stringUtil) { var loggingEnabled = function isLoggingEnabled(){ return sbt.Properties["js.logging.enabled"] ? sbt.Properties["js.logging.enabled"].toLowerCase() == "true" : true; }; var Level = { DEBUG : 1, INFO : 2, WARN : 3, ERROR : 4 }; var loggingLevel = function getLoggingLevel(){ return Level[sbt.Properties["js.logging.level"] ? sbt.Properties["js.logging.level"] : "DEBUG"]; }; return { /** * Sets the logging level. * @param {String} [l ]logging level. Possible values are DEBUG, INFO, WARN, ERROR * @static * @method setLevel */ setLevel : function(l) { loggingLevel = Level[l]; }, /** * Enables/disables logging. * @param {Boolean} [enabled] logging enabled true or false * @static * @method setEnabled */ setEnabled : function(enabled) { loggingEnabled = enabled; }, /** * log a debug statement. * @static * @method debug */ debug : function() { if (!loggingEnabled) { return; } if (loggingLevel > 1) { return; } if (console && arguments.length > 0) { var args = Array.prototype.slice.call(arguments); var text = args[0]; args = args.slice(1); var formattedText = stringUtil.substitute(text, args); if (console.debug) { console.debug(formattedText); } else { console.log("DEBUG : " + formattedText); } } }, /** * log an info statement. * @static * @method info */ info : function() { if (!loggingEnabled) { return; } if (loggingLevel > 2) { return; } if (console && arguments.length > 0) { var args = Array.prototype.slice.call(arguments); var text = args[0]; args = args.slice(1); var formattedText = stringUtil.substitute(text, args); if (console.info) { console.info(formattedText); } else { console.log("INFO : " + formattedText); } } }, /** * log a warning statement. * @static * @method warn */ warn : function() { if (!loggingEnabled) { return; } if (loggingLevel > 3) { return; } if (console && arguments.length > 0) { var args = Array.prototype.slice.call(arguments); var text = args[0]; args = args.slice(1); var formattedText = stringUtil.substitute(text, args); if (console.warn) { console.warn(formattedText); } else { console.log("WARN : " + formattedText); } } }, /** * log an error statement. * @static * @method error */ error : function() { if (!loggingEnabled) { return; } if (console && arguments.length > 0) { var args = Array.prototype.slice.call(arguments); var text = args[0]; args = args.slice(1); var formattedText = stringUtil.substitute(text, args); if (console.error) { console.error(formattedText); } else { console.log("ERROR : " + formattedText); } } }, /** * log an exception * @static * @method error */ exception : function() { if (!loggingEnabled) { return; } if (console && arguments.length > 0) { var args = Array.prototype.slice.call(arguments); var text = args[0]; args = args.slice(1); var formattedText = stringUtil.substitute(text, args); if (console.error) { console.error("EXCEPTION : " + formattedText); } else { console.log("EXCEPTION : " + formattedText); } } } }; }); }, 'sbt/connections/SearchService':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Use the Search API to perform searches across the installed Connections applications. * * Returns a list of results with the specified text in the title, description, or content. Encode the strings. By default, spaces are treated as an AND operator. The following operators are supported: * * AND or &&: Searches for items that contain both words. For example: query=red%20AND%20test returns items that contain both the word red and the word test. AND is the default operator. * NOT or !: Excludes the word that follows the operator from the search. For example: query=test%20NOT%20red returns items that contain the word test, but not the word red. * OR: Searches for items that contain either of the words. For example: query=test%20OR%20red * To search for a phrase, enclose the phrase in quotation marks (" "). * +: The plus sign indicates that the word must be present in the result. For example: query=+test%20red returns only items that contain the word test and many that also contain red, but none that contain only the word red. * ?: Use a question mark to match individual characters. For example: query=te%3Ft returns items that contain the words test, text, tent, and others that begin with te. * -: The dash prohibits the return of a given word. This operator is similar to NOT. For example: query=test%20-red returns items that contains the word test, but not the word red. * * Note: Wildcard searches are permitted, but wildcard only searches (*) are not. * For more details about supported operators, see Advanced search options in the Using section of the product documentation. * * @module sbt.connections.SearchService */ define([ "../declare", "../config", "../lang", "../stringUtil", "../Promise", "../json", "./SearchConstants", "./ConnectionsService", "../base/BaseEntity", "../base/AtomEntity", "../base/XmlDataHandler" ], function(declare,config,lang,stringUtil,Promise,json,consts,ConnectionsService,BaseEntity,AtomEntity,XmlDataHandler) { /** * Scope class represents an entry for a scopes feed returned by the * Connections REST API. * * @class Scope * @namespace sbt.connections */ var Scope = declare(AtomEntity, { /** * Construct a Scope entity. * * @constructor * @param args */ constructor : function(args) { }, /** * Return the scope search link. * * @method getLink * @return {String} Scope link */ getLink : function() { return this.getAsString("link"); } }); /** * Result class represents an entry for a search feed returned by the * Connections REST API. * * @class Result * @namespace sbt.connections */ var Result = declare(AtomEntity, { /** * Construct a Scope entity. * * @constructor * @param args */ constructor : function(args) { }, /** * Return the primary component for a particular search * result with respect to the search query. * * @method getPrimaryComponent * @return {String} Primary component */ getPrimaryComponent : function() { return this.getAsString("primaryComponent"); }, /** * Indicates a relative assessment of relevance for a particular search * result with respect to the search query. * * @method getRelevance * @return {String} Relative assessment of relevance */ getRelevance : function() { return this.getAsNumber("relevance"); } }); /** * FacetValue class represents an entry for a search facet returned by the * Connections REST API. * * @class FacetValue * @namespace sbt.connections */ var FacetValue = declare(BaseEntity, { /** * Construct an FacetValue. * * @constructor * @param args */ constructor : function(args) { // create XML data handler this.dataHandler = new XmlDataHandler({ service : args.service, data : args.data, namespaces : lang.mixin(consts.Namespaces, args.namespaces || {}), xpath : lang.mixin(consts.FacetValueXPath, args.xpath || this.xpath || {}) }); this.id = this.getAsString("uid"); }, /** * Return the value of id from facet entry. * * @method getId * @return {String} ID of the facet entry */ getId : function() { var id = this.getAsString("id"); var parts = id.split("/"); return (parts.length == 1) ? parts[0] : parts[1]; }, /** * Return the value of label from facet entry. * * @method getLabel * @return {String} Facet entry label */ getLabel : function() { return this.getAsString("label"); }, /** * Return the value of weigth from facet entry. * * @method getWeight * @return {Number} Facet entry weight */ getWeight : function() { return this.getAsNumber("weight"); } }); /* * Callbacks used when reading a feed that contains scope entries. */ var ScopeFeedCallbacks = { createEntities : function(service,data,response) { return new XmlDataHandler({ namespaces : consts.Namespaces, xpath : consts.SearchFeedXPath, service : service, data : data }); }, createEntity : function(service,data,response) { return new Scope({ namespaces : consts.Namespaces, service : service, data : data }); } }; /* * Callbacks used when reading a feed that contains search entries. */ var ResultFeedCallbacks = { createEntities : function(service,data,response) { return new XmlDataHandler({ namespaces : consts.Namespaces, xpath : consts.SearchFeedXPath, service : service, data : data }); }, createEntity : function(service,data,response) { return new Result({ namespaces : consts.Namespaces, xpath : consts.SearchXPath, service : service, data : data }); } }; /* * Callbacks used when reading a feed that contains search facets. */ var FacetsCallbacks = { createEntities : function(service,data,response) { var xpathExprs = lang.mixin({}, consts.SingleFacetXPath); // facet param looks like this "{"id": "Person"}" var facet = json.parse(response.options.query.facet); xpathExprs.entries = xpathExprs.entries.replace("{facet.id}", facet.id); return new XmlDataHandler({ namespaces : consts.Namespaces, xpath : xpathExprs, service : service, data : data }); }, createEntity : function(service,data,response) { return new FacetValue({ namespaces : consts.Namespaces, xpath : consts.FacetValueXPath, service : service, data : data }); } }; /** * SearchService class. * * @class SearchService * @namespace sbt.connections */ var SearchService = declare(ConnectionsService, { contextRootMap: { search: "search" }, serviceName : "search", /** * Constructor for SearchService * * @constructor * @param args */ constructor : function(args) { if (!this.endpoint) { this.endpoint = config.findEndpoint(this.getDefaultEndpointName()); } }, /** * Returns the set of supported values that can be passed to the "scope" parameter of the Search API. * Scopes relating to Connections applications that have not been installed will not be returned. * * @method getScopes * @param requestArgs */ getScopes: function(requestArgs) { var options = { method : "GET", handleAs : "text", query : requestArgs || {} }; return this.getEntities(consts.AtomScopes, options, ScopeFeedCallbacks); }, /** * Search Lotus Connection for public information. * * @method getResults * @param query Text to search for * @param requestArgs */ getResults: function(queryArg, requestArgs) { requestArgs = this._stringifyRequestArgs(requestArgs); var options = { method : "GET", handleAs : "text", query : lang.mixin({ query : queryArg } , requestArgs || {}) }; return this.getEntities(consts.AtomSearch, options, ResultFeedCallbacks); }, /** * Search Lotus Connections for both public information and * private information that you have access to. You must provide * authentication information in the request to retrieve this * resource. * * @method getMyResults * @param query Text to search for * @param requestArgs */ getMyResults: function(queryArg, requestArgs) { requestArgs = this._stringifyRequestArgs(requestArgs); var options = { method : "GET", handleAs : "text", query : lang.mixin({ query : queryArg } , requestArgs || {}) }; return this.getEntities(consts.AtomMySearch, options, ResultFeedCallbacks); }, /** * Search Lotus Connection for public information. * * @method getResultsWithConstraint * @param query Text to search for * @param constraint Constraint(s) to be used while searching * @param requestArgs */ getResultsWithConstraint: function(queryArg, constraint, requestArgs) { requestArgs = this._stringifyRequestArgs(requestArgs); var query = { query : queryArg, constraint : json.stringify(constraint) }; var options = { method : "GET", handleAs : "text", query : lang.mixin(query, requestArgs || {}) }; return this.getEntities(consts.AtomSearch, options, ResultFeedCallbacks); }, /** * Search Lotus Connections for both public information and * private information that you have access to. You must provide * authentication information in the request to retrieve this * resource. * * @method getMyResultsWithConstraint * @param query Text to search for * @param constraint Constraint(s) to be used while searching * @param requestArgs */ getMyResultsWithConstraint: function(queryArg, constraint, requestArgs) { requestArgs = this._stringifyRequestArgs(requestArgs); var query = { query : queryArg, constraint : json.stringify(constraint) }; var options = { method : "GET", handleAs : "text", query : lang.mixin(query, requestArgs || {}) }; return this.getEntities(consts.AtomMySearch, options, ResultFeedCallbacks); }, /** * Search IBM Connections for public information, tagged * with the specified tags. * * @method getTagged * @param tags tags to search for * @param requestArgs */ getResultsByTag: function(tags, requestArgs) { var options = { method : "GET", handleAs : "text", query : lang.mixin({ constraint : this._createTagConstraint(tags) } , requestArgs || {}) }; return this.getEntities(consts.AtomSearch, options, ResultFeedCallbacks); }, /** * Search IBM Connections for both public information and private * information that you have access to, tagged * with the specified tags. * * @method getMyResultsByTag * @param tags Tags to search for * @param requestArgs */ getMyResultsByTag: function(tags, requestArgs) { var options = { method : "GET", handleAs : "text", query : lang.mixin({ constraint : this._createTagConstraint(tags) } , requestArgs || {}) }; return this.getEntities(consts.AtomMySearch, options, ResultFeedCallbacks); }, /** * Search IBM Connections Profiles for people using the specified * query string and return public information. * * @method getPeople * @param query Text to search for * @param requestArgs */ getPeople: function(queryArg, requestArgs) { var options = { method : "GET", handleAs : "text", query : lang.mixin({ query : queryArg, pageSize : "0", facet : "{\"id\": \"Person\"}" } , requestArgs || {}) }; return this.getEntities(consts.AtomSearch, options, FacetsCallbacks); }, /** * Search IBM Connections Profiles for people using the specified * query string and return public information. * * @method getMyPeople * @param query Text to search for * @param requestArgs */ getMyPeople: function(queryArg, requestArgs) { var options = { method : "GET", handleAs : "text", query : lang.mixin({ query : queryArg, pageSize : "0", facet : "{\"id\": \"Person\"}" } , requestArgs || {}) }; return this.getEntities(consts.AtomMySearch, options, FacetsCallbacks); }, // // Internals // /* * */ _stringifyRequestArgs: function(requestArgs) { if (!requestArgs) { return null; } var _requestArgs = {}; for(var name in requestArgs){ var value = requestArgs[name]; if (lang.isObject(value)) { _requestArgs[name] = json.stringify(value); } else { _requestArgs[name] = value; } } return _requestArgs; }, /* * Create a contraint JSON string for the specified tags */ _createTagConstraint: function(tags) { var jsonObj = { "type" : "category", "values" : new Array() }; if (lang.isArray(tags)) { for (var i=0;i<tags.length;i++) { jsonObj.values[i] = "Tag/" + tags[i]; } } else { jsonObj.values[0] = "Tag/" + tags; } return json.stringify(jsonObj); } }); return SearchService; }); }, 'sbt/util':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * @module sbt.util */ define(['./lang','sbt/i18n!sbt/nls/util','./log','./stringUtil','./pathUtil'],function(lang, nls, log, stringUtil, pathUtil) { var errorCode = 400; function _notifyError(error, args){ if (args && (args.error || args.handle)) { if (args.error) { try { args.error(error); } catch (error1) { log.error(nls.notifyError_catchError, error1); } } if (args.handle) { try { args.handle(error); } catch (error2) { log.error(nls.notifyError_catchError, error2); } } } else { log.error(nls.notifyError_console, error.code, error.message); } } return { notifyError: _notifyError, isEmptyObject: function(obj){ var isEmpty = true; for( var key in obj ){ if(obj.hasOwnProperty(key)){ isEmpty = false; break; } } return isEmpty; }, checkObjectClass: function(object, className, message, args){ if(object.declaredClass != className){ if(args){ _notifyError({code:errorCode,message:message},args); }else{ log(message); } return false; }else{ return true; } }, checkNullValue: function(object, message, args){ if(!object){ if(args){ _notifyError({code:errorCode,message:message},args); }else{ log(message); } return false; }else{ return true; } }, minVersion: function(required, used) { var reqParts = required.split('.'); var usedParts = used.split('.'); for (var i = 0; i < reqParts.length; ++i) { if (usedParts.length == i) { return false; } if (reqParts[i] == usedParts[i]) { continue; } else if (reqParts[i] > usedParts[i]) { return false; } else { return true; } } if (reqParts.length != usedParts.length) { return true; } return true; }, getAllResponseHeaders: function(xhr) { var headers = {}; try { var headersStr = xhr.getAllResponseHeaders(); if (headersStr) { var headersStrs = headersStr.split('\n'); for (var i=0; i<headersStrs.length; i++) { var index = headersStrs[i].indexOf(':'); var key = lang.trim(headersStrs[i].substring(0, index)); var value = lang.trim(headersStrs[i].substring(index+1)); if (key.length > 0) { headers[key] = value; } } } } catch(ex) { console.log(ex); } return headers; }, /** * Takes an object mapping query names to values, and formats them into a query string separated by the delimiter. * e.g. * createQuery({height: 100, width: 200}, ",") * * returns "height=100,width=200" * * @method createQuery * * @param {Object} queryMap An object mapping query names to values, e.g. {height:100,width:200...} * @param {String} delimiter The string to delimit the queries */ createQuery: function(queryMap, delimiter){ if(!queryMap){ return null; } var delim = delimiter; if(!delim){ delim = ","; } var pairs = []; for(var name in queryMap){ var value = queryMap[name]; pairs.push(encodeURIComponent(name) + "=" + encodeURIComponent(value)); } return pairs.join(delim); }, /** * Takes a query string and returns an equivalent object mapping. * e.g. * splitQuery("height=100,width=200", ",") * * returns {height: 100, width: 200} * * @method splitQuery * * @param {String} query A query string, e.g. "height=100,width=200" * @param {String} delimiter The string which delimits the queries */ splitQuery: function(query, delimiter){ var i; var result = {}; var part; var parts; var length; query = query.replace("?", ""); parts = query.split(delimiter); length = parts.length; for (i = 0; i < length; i++) { if(!parts[i]){ continue; } part = parts[i].split('='); result[part[0]] = part[1]; } return result; }, /** * Returns the JavaScript Library and version used * @returns {String} JavaScript Library with version */ getJavaScriptLibrary : function(){ var jsLib = "Unknown"; if(window.dojo) { if(dojo.version) { jsLib = "Dojo "+dojo.version; } } else if(define && define.amd && define.amd.vendor && define.amd.vendor === "dojotoolkit.org") { require(["dojo/_base/kernel"], function(kernel){ jsLib = "Dojo AMD "+kernel.version; }); } else if(window.jQuery) { jsLib = "JQuery "+jQuery.fn.jquery; } return jsLib; }, /** * Return san absolute version of the specified url * @param {String} URL to convert * @returns {String} Absolute version of the url */ makeAbsoluteUrl : function(url) { if (stringUtil.startsWith(url, "http")) { return url; } var loc = window.location; var baseUrl = loc.protocol+'//'+loc.hostname+(loc.port ? ':'+loc.port: ''); return pathUtil.concat(baseUrl, url); } }; }); }, 'sbt/nls/loginForm':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK - Default resource bundle for validate module. */ define({ root: ({ username:"User name :", password:"Password :", authentication_dialog_title: "Authentication", login_ok: "Log in", login_cancel: "Cancel", wrong_creds_message:"Wrong Credentials" }) }); }, 'sbt/connections/BookmarkService':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * The Bookmarks API can be used to save, organize, and share Internet and intranet bookmarks. The Bookmarks API allows * application programs to read and write to the collections of bookmarks stored in the Bookmarks application.. * * @module sbt.connections.BookmarkService */ define([ "../declare", "../config", "../lang", "../stringUtil", "../Promise", "./BookmarkConstants", "./ConnectionsService", "../base/AtomEntity", "../base/XmlDataHandler", "./Tag"], function(declare,config,lang,stringUtil,Promise,consts,ConnectionsService,AtomEntity,XmlDataHandler, Tag) { var BookmarkTmpl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><entry xmlns=\"http://www.w3.org/2005/Atom\"><title type=\"text\">${getTitle}</title><category scheme=\"http://www.ibm.com/xmlns/prod/sn/type\" term=\"bookmark\"/><link href='${getUrl}'/>${isPrivate}<content type=\"html\">${getContent}</content>${getTags}</entry>"; var CategoryPrivateFlag = "<category scheme=\"http://www.ibm.com/xmlns/prod/sn/flags\" term=\"private\" />" CategoryTmpl = "<category term=\"${tag}\"></category>"; var CategoryBookmark = "<category term=\"bookmark\" scheme=\"http://www.ibm.com/xmlns/prod/sn/type\"></category>"; /** * Bookmark class represents an entry for a Bookmarks feed returned by the * Connections REST API. * * @class Bookmark * @namespace sbt.connections */ var Bookmark = declare(AtomEntity, { xpath : consts.BookmarkXPath, namespaces : consts.BookmarkNamespaces, categoryScheme : CategoryBookmark, /** * Construct a Bookmark entity. * * @constructor * @param args */ constructor : function(args) { }, /** * Return the value of IBM Connections bookmark ID from bookmark ATOM * entry document. * * @method getBookmarkUuid * @return {String} ID of the bookmark */ getBookmarkUuid : function() { return this.getAsString("BookmarkUuid"); }, /** * Sets id of IBM Connections bookmark. * * @method setBookmarkUuid * @param {String} bookmarkUuid of the bookmark */ setBookmarkUuid : function(BookmarkUuid) { return this.setAsString("BookmarkUuid", BookmarkUuid); }, /** * Return the value of private flag * * @method isPrivate * @return {String} accessibility flag of the bookmark */ isPrivate : function() { return this.getAsBoolean("privateFlag"); }, /** * Sets the value of private flag * * @method setPrivate * @param {String} accessibility flag of the bookmark */ setPrivate : function(privateFlag) { return this.setAsBoolean("privateFlag", privateFlag); }, /** * Return the value of IBM Connections bookmark URL from bookmark ATOM * entry document. * * @method getUrl * @return {String} Bookmark URL of the bookmark */ getUrl : function() { return this.getAsString("link"); }, /** * Sets title of IBM Connections bookmark. * * @method setUrl * @param {String} title Title of the bookmark */ setUrl : function(link) { return this.setAsString("link", link); }, /** * Return the click count of the IBM Connections bookmark. * * @method getClickCount * @return {String} click count of the bookmark */ getClickCount : function() { return this.getAsString("clickcount"); }, /** * Return the category type of the IBM Connections bookmark. * * @method getCategoryType * @return {String} content of the bookmark */ getCategoryType : function() { return this.getAsString("categoryType"); }, /** * Return the edit link for IBM Connections bookmark. * * @method getEditLink * @return {String} edit link of the bookmark */ getEditLink : function() { return this.getAsString("linkEdit"); }, /** * Return the same link for IBM Connections bookmark. * * @method getSameLink * @return {String} same link of the bookmark */ getSameLink : function() { return this.getAsString("linkSame"); }, /** * Gets an author of IBM Connections Bookmark. * * @method getAuthor * @return {Member} Author of the bookmark */ getAuthor : function() { return this.getAsObject([ "authorId", "authorName", "authorEmail", "authorUri" ]); }, /** * Return tags of IBM Connections bookmark * document. * * @method getTags * @return {Object} Array of tags of the bookmark */ getTags : function() { return this.getAsArray("tags"); }, /** * Set new tags to be associated with this IBM Connections bookmark. * * @method setTags * @param {Object} Array of tags to be added to the bookmark */ setTags : function(tags) { return this.setAsArray("tags", tags); }, /** * Loads the bookmark object with the atom entry associated with the * bookmark. By default, a network call is made to load the atom entry * document in the bookmark object. * * @method load * @param {Object} [args] Argument object */ load : function(args) { // detect a bad request by validating required arguments var bookmarkUrl = this.getUrl(); var promise = this.service._validateBookmarkUrl(bookmarkUrl); if (promise) { return promise; } var self = this; var callbacks = { createEntity : function(service,data,response) { self.setDataHandler(new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.BookmarkXPath })); return self; } }; var requestArgs = lang.mixin({ url : bookmarkUrl }, args || {}); var options = { handleAs : "text", query : requestArgs }; return this.service.getEntity(consts.AtomBookmarkCreateUpdateDelete, options, bookmarkUrl, callbacks); }, /** * Remove this bookmark * * @method remove * @param {Object} [args] Argument object */ remove : function(args) { return this.service.deleteBookmark(this.getUrl(), args); }, /** * Update this bookmark * * @method update * @param {Object} [args] Argument object */ update : function(args) { return this.service.updateBookmark(this, args); }, /** * Save this bookmark * * @method save * @param {Object} [args] Argument object */ save : function(args) { if (this.getBookmarkUuid()) { return this.service.updateBookmark(this, args); } else { return this.service.createBookmark(this, args); } } }); /* * Callbacks used when reading a feed that contains bookmark entries. */ var ConnectionsBookmarkFeedCallbacks = { createEntities : function(service,data,response) { return new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.BookmarkFeedXPath }); }, createEntity : function(service,data,response) { return new Bookmark({ service : service, data : data }); } }; /* * Callbacks used when reading a feed that contains bookmark entries. */ var ConnectionsTagsFeedCallbacks = { createEntities : function(service,data,response) { return new XmlDataHandler({ data : data, namespaces : consts.Namespaces, xpath : consts.TagsXPath }); }, createEntity : function(service,data,response) { var entryHandler = new XmlDataHandler({ data : data, namespaces : consts.Namespaces, xpath : consts.TagsXPath }); return new Tag({ service : service, id : entryHandler.getEntityId(), dataHandler : entryHandler }); } }; /** * BookmarkService class. * * @class BookmarkService * @namespace sbt.connections */ var BookmarkService = declare(ConnectionsService, { contextRootMap: { dogear : "dogear" }, serviceName : "dogear", /** * Constructor for BookmarkService * * @constructor * @param args */ constructor : function(args) { if (!this.endpoint) { this.endpoint = config.findEndpoint(this.getDefaultEndpointName()); } }, /** * Get the All Bookmarks feed to see a list of all bookmarks to which the * authenticated user has access. * * @method getAllBookmarks * * @param {Object} [args] Object representing various parameters * that can be passed to get a feed of all bookmarks. The * parameters must be exactly as they are supported by IBM * Connections like ps, sortBy etc. */ getAllBookmarks : function(args) { var options = { method : "GET", handleAs : "text", query : args || {} }; return this.getEntities(consts.AtomBookmarksAll, options, this.getBookmarkFeedCallbacks()); }, /** * Get the popular Bookmarks feed. * * @method getPopularBookmarks * * @param {Object} [args] Object representing various parameters * that can be passed to get a feed of all bookmarks. The * parameters must be exactly as they are supported by IBM * Connections like ps, sortBy etc. */ getPopularBookmarks : function(args) { var options = { method : "GET", handleAs : "text", query : args || {} }; return this.getEntities(consts.AtomBookmarksPopular, options, this.getBookmarkFeedCallbacks()); }, /** * A feed of bookmarks that others notified me about. * * @method getBookmarksMyNotifications * * @param {Object} [args] Object representing various parameters * that can be passed to get a feed of all bookmarks. The * parameters must be exactly as they are supported by IBM * Connections like ps, sortBy etc. */ getBookmarksMyNotifications : function(args) { var options = { method : "GET", handleAs : "text", query : args || {} }; return this.getEntities(consts.AtomBookmarksMyNotifications, options, this.getBookmarkFeedCallbacks()); }, /** * A feed of bookmarks about which I notified others.. * * @method getBookmarksMySentNotifications * * @param {Object} [args] Object representing various parameters * that can be passed to get a feed of all bookmarks. The * parameters must be exactly as they are supported by IBM * Connections like ps, sortBy etc. */ getBookmarksMySentNotifications : function(args) { var options = { method : "GET", handleAs : "text", query : args || {} }; return this.getEntities(consts.AtomBookmarksINotifiedMySentNotifications, options, this.getBookmarkFeedCallbacks()); }, /** * Retrieve a bookmark instance. * * @method getBookmark * @param {String } bookmarkUrl * @param {Object} args Object containing the query arguments to be * sent (defined in IBM Connections Bookmarks REST API) */ getBookmark : function(bookmarkUrl, args) { var bookmark = new Bookmark({ service : this, _fields : { link : bookmarkUrl } }); return bookmark.load(args); }, /** * Create a bookmark by sending an Atom entry document containing the * new bookmark. * * @method createBookmark * @param {String} url Url to post to when creating the bookmark. * @param {String/Object} bookmarkOrJson Bookmark object which denotes the bookmark to be created. * @param {Object} [args] Argument object */ createBookmark : function(bookmarkOrJson, args) { var bookmark = this._toBookmark(bookmarkOrJson); var promise = this._validateBookmark(bookmark, false, args); if (promise) { return promise; } var callbacks = {}; callbacks.createEntity = function(service,data,response) { if (data) { var dataHandler = new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.BookmarkXPath }); bookmark.setDataHandler(dataHandler); bookmark.setData(data); } else { bookmark.setData(data); var referenceId = this.getLocationParameter(response, "referenceId"); bookmark.setBookmarkUuid(referenceId); } return bookmark; }; var url = consts.AtomBookmarkCreateUpdateDelete; if (args && args.url) { url = args.url; delete args.url; } var options = { method : "POST", query : args || {}, headers : consts.AtomXmlHeaders, data : this._constructBookmarkPostData(bookmark) }; return this.updateEntity(url, options, callbacks, args); }, /** * Update a bookmark by sending a replacement bookmark entry document * to the existing bookmark's edit web address. * All existing bookmark entry information will be replaced with the new data. To avoid * deleting all existing data, retrieve any data you want to retain first, and send it back * with this request. For example, if you want to add a new tag to a bookmark entry, retrieve * the existing tags, and send them all back with the new tag in the update request. * * @method updateBookmark * @param {String/Object} bookmarkOrJson Bookmark object * @param {Object} [args] Argument object */ updateBookmark : function(bookmarkOrJson,args) { var bookmark = this._toBookmark(bookmarkOrJson); var promise = this._validateBookmark(bookmark, true, args); if (promise) { return promise; } var callbacks = {}; callbacks.createEntity = function(service,data,response) { var bookmarkUuid = bookmark.getBookmarkUuid(); if (data) { var dataHandler = new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.BookmarkXPath }); bookmark.setDataHandler(dataHandler); } bookmark.setBookmarkUuid(bookmarkUuid); return bookmark; }; var requestArgs = lang.mixin({ url : bookmark.getUrl() }, args || {}); var options = { method : "PUT", query : requestArgs, headers : consts.AtomXmlHeaders, data : this._constructBookmarkPostData(bookmark) }; return this.updateEntity(consts.AtomBookmarkCreateUpdateDelete, options, callbacks, args); }, /** * Delete a bookmark, use the HTTP DELETE method. * * @method deleteBookmark * @param {String} bookmarkUuid bookmark id of the bookmark or the bookmark object (of the bookmark to be deleted) * @param {Object} [args] Argument object */ deleteBookmark : function(bookmarkUrl,args) { var promise = this._validateBookmarkUrl(bookmarkUrl); if (promise) { return promise; } var requestArgs = lang.mixin({ url : bookmarkUrl }, args || {}); var options = { method : "DELETE", query : requestArgs, handleAs : "text" }; return this.deleteEntity(consts.AtomBookmarkCreateUpdateDelete, options, bookmarkUrl); }, /** * Get the tags feed to see a list of the tags for all bookmarks. * * @method getBookmarksTags * @param {Object} [args] Object representing various parameters. * The parameters must be exactly as they are supported by IBM * Connections. */ getBookmarksTags : function(args) { var options = { method : "GET", handleAs : "text", query : args || {} }; return this.getEntities(consts.AtomBookmarksTags, options, this.getTagsFeedCallbacks(), args); }, /** * Create a Bookmark object with the specified data. * * @method newBookmark * @param {Object} args Object containing the fields for the * new bookmark */ newBookmark : function(args) { return this._toBookmark(args); }, /* * Callbacks used when reading a feed that contains Bookmark entries. */ getBookmarkFeedCallbacks: function() { return ConnectionsBookmarkFeedCallbacks; }, /* * Callbacks used when reading a feed that contains Bookmark entries. */ getTagsFeedCallbacks: function() { return ConnectionsTagsFeedCallbacks; }, /* * Return a Bookmark instance from Bookmark or JSON or String. Throws * an error if the argument was neither. */ _toBookmark : function(bookmarkOrJsonOrString) { if (bookmarkOrJsonOrString instanceof Bookmark) { return bookmarkOrJsonOrString; } else { if (lang.isString(bookmarkOrJsonOrString)) { bookmarkOrJsonOrString = { bookmarkUuid : bookmarkOrJsonOrString }; } return new Bookmark({ service : this, _fields : lang.mixin({}, bookmarkOrJsonOrString) }); } }, /* * Validate a bookmark UUID, and return a Promise if invalid. */ _validateBookmarkUuid : function(bookmarkUuid) { if (!bookmarkUuid || bookmarkUuid.length == 0) { return this.createBadRequestPromise("Invalid argument, expected bookmarkUuid."); } }, /* * Validate a bookmark UUID, and return a Promise if invalid. */ _validateBookmarkUrl : function(bookmarkUrl) { if (!bookmarkUrl || bookmarkUrl.length == 0) { return this.createBadRequestPromise("Invalid argument, expected bookmarkUrl."); } }, /* * Validate a bookmark, and return a Promise if invalid. */ _validateBookmark : function(bookmark,checkUuid) { if (!bookmark || !bookmark.getTitle()) { return this.createBadRequestPromise("Invalid argument, bookmark with title must be specified."); } if (checkUuid && !bookmark.getBookmarkUuid()) { return this.createBadRequestPromise("Invalid argument, bookmark with UUID must be specified."); } }, /* * Construct a post data for a Bookmark */ _constructBookmarkPostData : function(bookmark) { var transformer = function(value,key) { if (key == "getTags") { var tags = value; value = ""; for (var tag in tags) { value += stringUtil.transform(CategoryTmpl, { "tag" : tags[tag] }); } } else if (key == "getTitle" && !value) { value = bookmark.getTitle(); } else if (key == "getUrl" && !value) { value = bookmark.getUrl(); } else if (key == "getContent" && !value) { value = bookmark.getContent(); } else if (key == "isPrivate" && !value) { if(bookmark.isPrivate()){ value = CategoryPrivateFlag; }else{ value = ""; } } return value; }; var postData = stringUtil.transform(BookmarkTmpl, bookmark, transformer, bookmark); return stringUtil.trim(postData); } }); return BookmarkService; }); }, 'sbt/connections/CommunityConstants':function(){ /* * © Copyright IBM Corp. 2012,2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. Definition of constants for CommunityService. * * @module sbt.connections.CommunityConstants */ define([ "../lang", "./ConnectionsConstants" ], function(lang,conn) { return lang.mixin({}, conn, { /** * Public community * * @property Public * @type String * @for sbt.connections.Community */ Public : "public", /** * Moderated community * * @property Moderated * @type String * @for sbt.connections.Community */ Moderated : "publicInviteOnly", /** * Restricted community * * @property Restricted * @type String * @for sbt.connections.Community */ Restricted : "private", /** * Community owner * * @property Owner * @type String * @for sbt.connections.Member */ Owner : "owner", /** * Community member * * @property Member * @type String * @for sbt.connections.Member */ Member : "member", /** * Namespaces to be used when reading the Communities ATOM entry or feed */ CommunityNamespaces : { a : "http://www.w3.org/2005/Atom", app : "http://www.w3.org/2007/app", snx : "http://www.ibm.com/xmlns/prod/sn" }, /** * XPath expressions used when parsing a Connections Communities ATOM feed * * @property CommunityFeedXPath * @type Object * @for sbt.connections.CommunityService */ CommunityFeedXPath : conn.ConnectionsFeedXPath, /** * XPath expressions to be used when reading a Community Entry * * @property CommunityXPath * @type Object * @for sbt.connections.CommunityService */ CommunityXPath : lang.mixin({}, conn.AtomEntryXPath, { communityUuid : "a:id", communityTheme : "snx:communityTheme", logoUrl : "a:link[@rel='http://www.ibm.com/xmlns/prod/sn/logo']/@href", tags : "a:category[not(@scheme)]/@term", memberCount : "snx:membercount", communityType : "snx:communityType", communityUrl : "a:link[@rel='alternate']/@href", isExternal : "snx:isExternal", parentCommunityUrl: "a:link[@rel='http://www.ibm.com/xmlns/prod/sn/parentcommunity']/@href" }), /** * XPath expressions to be used when reading a Community Member Entry * * @property MemberXPath * @type Object * @for sbt.connections.CommunityService */ MemberXPath : lang.mixin({}, conn.AtomEntryXPath, { id : "a:contributor/snx:userid", uid : "a:contributor/snx:userid", role : "snx:role" }), /** * XPath expressions to be used when reading a Community Invite Entry * * @property InviteXPath * @type Object * @for sbt.connections.CommunityService */ InviteXPath : lang.mixin({}, conn.AtomEntryXPath, { inviteUuid : "a:id", communityUuid : "snx:communityUuid", communityUrl : "a:link[@rel='http://www.ibm.com/xmlns/prod/sn/community']/@href" }), /** * XPath expressions to be used when reading a Community Event Entry * * @property EventXPath * @type Object * @for sbt.connections.CommunityService */ EventXPath : lang.mixin({}, conn.AtomEntryXPath, { eventUuid : "snx:eventUuid", eventInstUuid : "snx:eventInstUuid", location : "snx:location", allDay : "snx:allday", selfLink : "a:link[@rel='self']/@href", sourceId : "a:source/a:id", sourceTitle : "a:source/a:title", sourceLink : "a:source/a:link[@rel='self']/@href", attendLink : "a:link[@rel='http://www.ibm.com/xmlns/prod/sn/calendar/event/attend']/@href", followLink : "a:link[@rel='http://www.ibm.com/xmlns/prod/sn/calendar/event/follow']/@href", followed : "snx:followed", attended : "snx:attended", attendeesAtomUrl : "a:link[@rel='http://www.ibm.com/xmlns/prod/sn/calendar/event/attendees']/@href", containerLink : "a:link[@rel='http://www.ibm.com/xmlns/prod/sn/container']/@href", instStartDate : "snx:startDate", instEndDate : "snx:endDate", repeats : "snx:repeats", parentEventId : "snx:parentEvent", parentEventLink : "a:link[@rel='http://www.ibm.com/xmlns/prod/sn/calendar/event/parentevent']/@href", communityLink : "a:link[@rel='http://www.ibm.com/xmlns/prod/sn/container']/@href", communityUuid : "snx:communityUuid", eventAtomInstances : "a:link[@rel='http://www.ibm.com/xmlns/prod/sn/calendar/event/instances']/@href", eventAtomAttendees : "a:link[@rel='http://www.ibm.com/xmlns/prod/sn/calendar/event/attend']/@href", eventAtomFollowers : "a:link[@rel='http://www.ibm.com/xmlns/prod/sn/calendar/event/follow']/@href", frequency : "snx:recurrence/@frequency", interval : "snx:recurrence/@interval", until : "snx:recurrence/snx:until", byDay : "snx:recurrence/snx:byDay", startDate : "snx:recurrence/snx:startDate", endDate : "snx:recurrence/snx:endDate" }), /** * A feed of all public communities. * * Get the All Communities feed to see a list of all public communities to which the authenticated user has access or pass in parameters to search for communities that match a specific criteria. * * Supports: asc, email, ps, search, since, sortField, tag, userid * * @property AtomCommunitiesAll * @type String * @for sbt.connections.CommunityService */ AtomCommunitiesAll : "/${communities}/service/atom/communities/all", /** * A feed of communities of which the authenticated user is a member. * * Get the My Communities feed to see a list of the communities to which the authenticated user is a member or pass in parameters to search for a subset of those communities that match a specific criteria. * * Supports: asc, email, ps, search, since, sortField, tag, userid * * @property AtomCommunitiesMy * @type String * @for sbt.connections.CommunityService */ AtomCommunitiesMy : "/${communities}/service/atom/communities/my", /** * A feed of invitations. * * Get a list of the outstanding community invitations of the currently authenticated user or provide parameters to search for a subset of those invitations. * * Supports: asc, ps, search, since, sortField * * @property AtomCommunityInvitesMy * @type String * @for sbt.connections.CommunityService */ AtomCommunityInvitesMy : "/${communities}/service/atom/community/invites/my", /** * URL to delete/create Community Invites * * @property AtomCommunityInvites * @type String * @for sbt.connections.CommunityService */ AtomCommunityInvites : "${communities}/service/atom/community/invites", /** * A feed of subcommunities. * * Get a list of subcommunities associated with a community. * * Supports: asc, page, ps, since, sortBy, sortOrder, sortField * * @property AtomCommunitySubCommunities * @type String * @for sbt.connections.CommunityService */ AtomCommunitySubCommunities : "${communities}/service/atom/community/subcommunities", /** * A feed of members. * * Retrieve the members feed to view a list of the members who belong to a given community. * * Supports: asc, email, page, ps, role, since, sortField, userid * * @property AtomCommunityMembers * @type String * @for sbt.connections.CommunityService */ AtomCommunityMembers : "${communities}/service/atom/community/members", /** * A community entry. * * @property AtomCommunityInstance * @type String * @for sbt.connections.CommunityService */ AtomCommunityInstance : "${communities}/service/atom/community/instance", /** * Get a feed that includes the topics in a specific community forum. * * @property AtomCommunityForumTopics * @type String * @for sbt.connections.CommunityService */ AtomCommunityForumTopics : "/${communities}/service/atom/community/forum/topics", /** * Get a feed of a Community's bookmarks. Requires a url parameter of the form communityUuid=xxx * @property AtomCommunityBookmarks * @type String * @for sbt.connections.CommunityService */ AtomCommunityBookmarks : "/${communities}/service/atom/community/bookmarks", /** * Get a feed of a Community's Events or EventInsts. * @property AtomCommunityEvents * @type String * @for sbt.connections.CommunityService */ AtomCommunityEvents : "/${communities}/calendar/atom/calendar/event", /** * Get a feed of a Community's Event Attendess. * @property AtomCommunityEventAttend * @type String * @for sbt.connections.CommunityService */ AtomCommunityEventAttend : "/${communities}/calendar/atom/calendar/event/attendees", /** * Get a feed of a Community's Event Comments. * @property AtomCommunityEventComments * @type String * @for sbt.connections.CommunityService */ AtomCommunityEventComments : "/${communities}/calendar/atom/calendar/event/comment", /** * Get a feed of a Community's Invites. * @property AtomCommunityInvites * @type String * @for sbt.connections.CommunityService */ AtomCommunityInvites : "/${communities}/service/atom/community/invites", /** * Get a feed of a Community's Bookmarks. * @property AtomCommunityInvites * @type String * @for sbt.connections.CommunityService */ AtomCommunityBookmarks : "/${communities}/service/atom/community/bookmarks", /** * File Proxy URL for update community logo * @property AtomUpdateCommunityLogo * @type String * @for sbt.connections.CommunityService */ AtomUpdateCommunityLogo : "/${files}/{endpointName}/connections/UpdateCommunityLogo/{fileName}", /** * File Proxy URL for uploading a community file * @property AtomUploadCommunityFile * @type String * @for sbt.connections.CommunityService */ AtomUploadCommunityFile : "/${files}/{endpointName}/connections/UploadCommunityFile/{communityUuid}" }); }); }, 'sbt/connections/ActivityConstants':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. Definition of constants for ActivityService. */ define([ "../lang", "./ConnectionsConstants" ], function(lang, conn) { return lang.mixin({}, conn, { /** * Namespaces to be used when reading the Activities ATOM entry or feed */ ActivityNamespaces : { a : conn.Namespaces.a, app : conn.Namespaces.app, thr : conn.Namespaces.thr, snx : conn.Namespaces.snx }, /** * Map to store all possible types of activity node entry types */ ActivityNodeTypes : { Activity : "activity", Chat : "chat", Email : "email", Entry : "entry", EntryTemplate : "entrytemplate", Reply : "reply", Section : "section", ToDo : "todo" }, /** * XPath expressions used when parsing a Connections Activities ATOM feed */ ActivitiesFeedXPath : conn.ConnectionsFeedXPath, /** * XPath expressions for Person Fields */ PersonFieldXPath : { name : "a:name", userId : "snx:userid", email : "a:email" }, /** * XPath expressions for File Fields */ FileFieldXPath : { url : "a:link[@rel='enclosure']/@href", type : "a:link[@rel='enclosure']/@type", size : "a:link[@rel='enclosure']/@size", length : "a:link/@length" }, /** * XPath expressions for Link Fields */ LinkFieldXPath : { url : "a:link/@href", title : "a:link/@title" }, /** * XPath expressions for Text Fields */ TextFieldXPath : { summary : "a:summary" }, /** * XPath expressions to be used when reading an activity Node entry * */ ActivityNodeXPath : lang.mixin({}, conn.AtomEntryXPath, { activityUuid : "snx:activity", categoryFlagCompleted : "a:category[@term='completed']/@label", categoryFlagTemplate : "a:category[@term='template']/@label", categoryFlagDelete : "a:category[@term='deleted']/@label", authorLdapid : "a:author/snx:ldapid", contributorLdapid : "a:contributor/snx:ldapid", type : "a:category[@scheme='http://www.ibm.com/xmlns/prod/sn/type']/@term", priority : "a:category[@scheme='http://www.ibm.com/xmlns/prod/sn/priority']/@label", coummunityUuid : "snx:communityUuid", communityUrl : "a:link[@rel='http://www.ibm.com/xmlns/prod/sn/container']/@href", dueDate : "snx:duedate", membersUrl : "a:link[@rel='http://www.ibm.com/xmlns/prod/sn/member-list']/@href", historyUrl : "a:link[@rel='http://www.ibm.com/xmlns/prod/sn/history']/@href", templatesUrl : "a:link[@rel='http://www.ibm.com/xmlns/prod/sn/templates']/@href", position : "snx:position", depth : "snx:depth", permissions : "snx:permissions", iconUrl : "snx:icon", tags : "a:category[not(@scheme)]/@term", inReplyToId : "thr:in-reply-to/@ref", inReplyToUrl : "thr:in-reply-to/@href", inReplyToActivity : "thr:in-reply-to/snx:activity", assignedToName : "snx:assignedto/@name", assignedToUserId : "snx:assignedto/@userid", assignedToEmail : "snx:assignedto", textFields : "snx:field[@type='text']", linkFields : "snx:field[@type='link']", personFields : "snx:field[@type='person']", dateFields : "snx:field[@type='date']", fileFields : "snx:field[@type='file']" }), /** * XPath expressions to be used when reading an Tag Node entry */ TagXPath : { term : "@term", frequency : "@snx:frequency", entries : "app:categories/a:category", uid : "@term", bin : "@snx:bin" }, /** * XPath expressions to be used when reading a Community Member Entry * * @property MemberXPath * @type Object * @for sbt.connections.ActivityService */ MemberXPath : lang.mixin({}, conn.AtomEntryXPath, { entry : "a:feed/a:entry", id : "a:id", uid : "a:id", role : "snx:role", permissions : "snx:permissions", category : "a:category[@scheme='http://www.ibm.com/xmlns/prod/sn/type']/@term" }), /** * Search for content in all of the activities, both completed and active, that matches a specific criteria. */ AtomActivitiesEverything : "/${activities}/service/atom2/everything", /** * Get a feed of all active activities that match a specific criteria. */ AtomActivitiesMy : "${activities}/service/atom2/activities", /** * Get a feed of all active activities in trash */ AtomActivitiesTrash : "${activities}/service/atom2/trash", /** * Search for a set of completed activities that match a specific criteria. */ AtomActivitiesCompleted : "${activities}/service/atom2/completed", /** * Get Activity node feed */ AtomActivityNode : "${activities}/service/atom2/activitynode", /** * Get feed of all Activity Nodes in an Activity */ AtomActivityNodes : "${activities}/service/atom2/descendants", // ?nodeUuid=" /** * Get Activity Node feed from Trash */ AtomActivityNodeTrash : "${activities}/service/atom2/trashednode", /** * Create a new Activity */ AtomCreateActivityNode : "${activities}/service/atom2/activity", /** * Get a Feeds of all ToDo Entries in an activity */ AtomActivitiesToDos : "${activities}/service/atom2/todos", /** * Get a feed of Activity Members */ AtomActivitiesMembers : "${activities}/service/atom2/acl", /** * Get a member for an activity */ AtomActivitiesMember : "${activities}/service/atom2/acl?activityUuid={activityUuid}&amp;memberid={memberId}", /** * Get all tags for an activity */ AtomActivitiesTags : "${activities}/service/atom2/tags" }); }); }, 'sbt/text':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. * @module sbt.text */ define(['./_bridge/text'],function(text) { return text; }); }, 'sbt/xsl':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * Social Business Toolkit SDK - XSL utilities. * Borrowed from the Connections source code, for now */ /** * @module sbt.xsl */ define(['./Cache','./xml','./lang'],function(cache,sbtml,lang) { return { /** * Transform an XML document using an XSL stylesheet. * The XML document can be either a string or an actual DOM document. In case of a * string, if it starts with "http", then the string is read from the URL. Then, it * is parsed to a DOM document. * The XSL must be a string */ xsltTransform: function(xml,xsl) { if(!xml) return null; // Resolve the XML if it is a URL if(lang.isString(xml)) { xml = sbtml.parse(sbt.cache.get(xml)); } // Resolve the XSL if it is a URL if(!xsl) return lang.clone(xml); xsl = sbt.cache.get(xsl); // Run the transformation if(window.ActiveXObject) { return xml.transformNode(xsl); } else if(document.implementation && document.implementation.createDocument) { var xslt = new XSLTProcessor(); xslt.importStyleSheet(xsl); return xslt.transformToFragment(xml,document); } // No XSLT engine is available, just return the document as is return lang.clone(xml); } }; }); }, 'sbt/xpath':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK - XPath utilities. * * @module sbt.xpath */ define(['./declare'],function(declare) { /* * @class sbt.xpath.XPathExpr */ var XPathExpr = declare(null, { ie: false, constructor: function(xpath, nsArray){ this.xpath = xpath; this.nsArray = nsArray || {}; if (!document.evaluate) { this.ie = true; this.nsString = ""; if (this.nsArray) { for(var ns in this.nsArray) { this.nsString += ' xmlns:' + ns + '="' + this.nsArray[ns] + '"'; } } } }, selectSingleNode : function(xmlDomCtx) { var doc = xmlDomCtx.ownerDocument || xmlDomCtx; if (this.ie) { try { doc.setProperty("SelectionLanguage", "XPath"); doc.setProperty("SelectionNamespaces", this.nsString); if (xmlDomCtx === doc) xmlDomCtx = doc.documentElement; return xmlDomCtx.selectSingleNode(this.xpath); } catch (ex) { throw "XPath is not supported"; } } else { var _this = this; if (xmlDomCtx.documentElement) xmlDomCtx = xmlDomCtx.documentElement; var result = doc.evaluate(this.xpath, xmlDomCtx, function(prefix) { return _this.nsArray[prefix]; }, XPathResult.FIRST_ORDERED_NODE_TYPE, null); return result.singleNodeValue; } }, selectNumber : function(xmlDomCtx){ var doc = xmlDomCtx.ownerDocument || xmlDomCtx; if (this.ie) { return this.selectText(xmlDomCtx); } else { var _this = this; var result = doc.evaluate(this.xpath, xmlDomCtx, function(prefix) { return _this.nsArray[prefix]; }, XPathResult.NUMBER_TYPE, null); return result.numberValue; } }, selectNodes : function(xmlDomCtx) { var doc = xmlDomCtx.ownerDocument || xmlDomCtx; if (this.ie) { try { doc.setProperty("SelectionLanguage", "XPath"); doc.setProperty("SelectionNamespaces", this.nsString); if (xmlDomCtx === doc) xmlDomCtx = doc.documentElement; return xmlDomCtx.selectNodes(this.xpath); } catch (ex) { throw "XPath is not supported"; } } else { var _this = this; var result = doc.evaluate(this.xpath, xmlDomCtx, function(prefix) { return _this.nsArray[prefix]; }, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); var r = []; for(var i = 0; i < result.snapshotLength; i++) { r.push(result.snapshotItem(i)); } return r; } }, selectText : function(node) { var result = this.selectSingleNode(node); return result ? (result.text || result.textContent) : null; } }); return { /** * Selects nodes from XML data object * * @method selectNodes * @param {Object} * node xml data to be parsed * @param {String} * xpath xpath expression * @param {Array} * nsArray Array of namespaces for the xml. * @return {Array} Array of nodes * @static */ selectNodes : function(node, xpath, nsArray) { var expr = new XPathExpr(xpath, nsArray); return expr.selectNodes(node); }, /** * Selects single node from XML data object * * @method selectSingleNode * @param {Object} * node xml data to be parsed * @param {String} * xpath xpath expression * @param {Array} * nsArray Array of namespaces for the xml. * @return {Object} selected node object * @static */ selectSingleNode : function(node, xpath, nsArray) { var expr = new XPathExpr(xpath, nsArray); return expr.selectSingleNode(node); }, /** * Selects text from a single node from XML data object * * @method selectText * @param {Object} * node xml data to be parsed * @param {String} * xpath xpath expression * @param {Array} * nsArray Array of namespaces for the xml. * @return {String} inner text of the node object * @static */ selectText : function(node, xpath, nsArray) { var expr = new XPathExpr(xpath, nsArray); return expr.selectText(node); }, /** * * @param node * @param xpath * @param nsArray * @returns */ selectNumber : function(node, xpath, nsArray){ var expr = new XPathExpr(xpath, nsArray); return expr.selectNumber(node); } }; }); }, 'sbt/WPSProxy':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK to be used with WebSphere Portal server * Definition of a proxy re-writer. * * @module sbt.Proxy */ define(['./declare','./lang','./pathUtil'],function(declare,lang,pathUtil) { /** * Definition of the proxy module * * @class sbt.Proxy * */ var Proxy = declare(null, { proxyUrl : null, constructor: function(args){ lang.mixin(this, args); }, rewriteUrl: function(baseUrl,serviceUrl,proxyPath) { var u = serviceUrl; if(this.proxyUrl) { if(u.indexOf("http://")==0) { u = "/http/"+u.substring(7); } else if(u.indexOf("https://")==0) { u = "/https/"+u.substring(8); } if(baseUrl.indexOf("http://")==0) { baseUrl = "/http/"+baseUrl.substring(7); } else if(baseUrl.indexOf("https://")==0) { baseUrl = "/https/"+baseUrl.substring(8); } var networkUrl = pathUtil.concat(this.proxyUrl, baseUrl); networkUrl = pathUtil.concat(networkUrl, serviceUrl); return networkUrl; } return u; } }); return Proxy; }); }, 'sbt/config':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Definition of config module. * This module needs a _config module to be defined at runtime. * * @module sbt.config */ define(['./defer!./_config'],function(cfg){ return cfg; }); }, 'sbt/base/BaseConstants':function(){ /* * © Copyright IBM Corp. 2014 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. Definition of constants for BaseService. */ define([ "../config" ], function(sbt) { return { /** * Error codes used by the SBT based service implementations. */ sbtErrorCodes : { badRequest : 400 }, /** * Namespaces to be used when reading the Connections ATOM entry or feed */ Namespaces : { o : "http://ns.opensocial.org/2008/opensocial", app : "http://www.w3.org/2007/app", thr : "http://purl.org/syndication/thread/1.0", fh : "http://purl.org/syndication/history/1.0", snx : "http://www.ibm.com/xmlns/prod/sn", opensearch : "http://a9.com/-/spec/opensearch/1.1/", a : "http://www.w3.org/2005/Atom", h : "http://www.w3.org/1999/xhtml", td : "urn:ibm.com/td", relevance : "http://a9.com/-/opensearch/extensions/relevance/1.0/", ibmsc : "http://www.ibm.com/search/content/2010", xhtml : "http://www.w3.org/1999/xhtml", spelling : "http://a9.com/-/opensearch/extensions/spelling/1.0/", ca : "http://www.ibm.com/xmlns/prod/composite-applications/v1.0 namespace" }, /** * XPath expressions used when parsing an ATOM feed */ AtomFeedXPath : { // used by getEntitiesDataArray entries : "/a:feed/a:entry", // used by getSummary totalResults : "/a:feed/opensearch:totalResults", startIndex : "/a:feed/opensearch:startIndex", itemsPerPage : "/a:feed/opensearch:itemsPerPage" }, /** * XPath expressions to be used when reading an entry */ AtomEntryXPath : { // used by getEntityData entry : "/a:entry", // used by getEntityId uid : "a:id", // used by getters id : "a:id", title : "a:title", updated : "a:updated", published : "a:published", authorName : "a:author/a:name", authorEmail : "a:author/a:email", authorUserid : "a:author/snx:userid", authorUserState : "a:author/snx:userState", contributorName : "a:contributor/a:name", contributorEmail : "a:contributor/a:email", contributorUserid : "a:contributor/snx:userid", contributorUserState : "a:contributor/snx:userState", content : "a:content[@type='html']", summary : "a:summary[@type='text']", categoryTerm : "a:category/@term", editUrl : "a:link[@rel='edit']/@href", selfUrl : "a:link[@rel='self']/@href", alternateUrl : "a:link[@rel='alternate']/@href", tags : "./a:category[not(@scheme)]/@term" }, /** * */ AtomXmlHeaders : { "Content-Type" : "application/atom+xml" } }; }); }, 'sbt/xml':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK - XML utilities. */ define(['./lang'], function(lang) { var xml_to_encoded = { '&': '&amp;', '"': '&quot;', '<': '&lt;', '>': '&gt;' }; var encoded_to_xml = { '&amp;': '&', '&quot;': '"', '&lt;': '<', '&gt;': '>' }; return { /** * XML Parser. * This function parses an XML string and returns a DOM. */ parse: function(xml) { var xmlDoc=null; try { if(!document.evaluate){ xmlDoc=new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async="false"; xmlDoc.loadXML(xml); }else{ if(window.DOMParser){ parser=new DOMParser(); xmlDoc=parser.parseFromString(xml,"text/xml"); } } }catch(ex){ console.log(ex.message); } return xmlDoc; }, asString: function(xmlDoc) { if (xmlDoc==null) { return ""; } else if(window.ActiveXObject){ return xmlDoc.xml; } else { return (new XMLSerializer()).serializeToString(xmlDoc); } }, getText : function (xmlElement){ if(!document.evaluate){ return xmlElement.text; }else{ return xmlElement.textContent; } }, encodeXmlEntry: function(string) { if (lang.isArray(string)) { string = string.join(); } if (!lang.isString(string)) { string = string.toString(); } return string.replace(/([\&"<>])/g, function(str, item) { return xml_to_encoded[item]; }); }, decodeXmlEntry: function (string) { return string.replace(/(&quot;|&lt;|&gt;|&amp;)/g,function(str, item) { return encoded_to_xml[item]; }); } }; }); }, 'sbt/entities':function(){ // The entities class from dojox/html/entities. define(["./lang"], function(lang) { // Entity characters for HTML, represented as an array of // character code, entity name (minus & and ; wrapping. // The function wrapper is to fix global leaking with the build tools. var dhe = {}; var _applyEncodingMap = function(str, map){ // summary: // Private internal function for performing encoding of entity characters. // tags: // private // Check to see if we have genned and cached a regexp for this map yet // If we have, use it, if not, gen it, cache, then use. var mapper, regexp; if(map._encCache && map._encCache.regexp && map._encCache.mapper && map.length == map._encCache.length){ mapper = map._encCache.mapper; regexp = map._encCache.regexp; }else{ mapper = {}; regexp = ["["]; var i; for(i = 0; i < map.length; i++){ mapper[map[i][0]] = "&" + map[i][1] + ";"; regexp.push(map[i][0]); } regexp.push("]"); regexp = new RegExp(regexp.join(""), "g"); map._encCache = { mapper: mapper, regexp: regexp, length: map.length }; } str = str.replace(regexp, function(c){ return mapper[c]; }); return str; }; var _applyDecodingMap = function(str, map){ // summary: // Private internal function for performing decoding of entity characters. // tags: // private var mapper, regexp; if(map._decCache && map._decCache.regexp && map._decCache.mapper && map.length == map._decCache.length){ mapper = map._decCache.mapper; regexp = map._decCache.regexp; }else{ mapper = {}; regexp = ["("]; var i; for(i = 0; i < map.length; i++){ var e = "&" + map[i][1] + ";"; if(i){regexp.push("|");} mapper[e] = map[i][0]; regexp.push(e); } regexp.push(")"); regexp = new RegExp(regexp.join(""), "g"); map._decCache = { mapper: mapper, regexp: regexp, length: map.length }; } str = str.replace(regexp, function(c){ return mapper[c]; }); return str; }; dhe.html = [ ["\u0026","amp"], ["\u0022","quot"],["\u003C","lt"], ["\u003E","gt"], ["\u00A0","nbsp"] ]; // Entity characters for Latin characters and similar, represented as an array of // character code, entity name (minus & and ; wrapping. dhe.latin = [ ["\u00A1","iexcl"],["\u00A2","cent"],["\u00A3","pound"],["\u20AC","euro"], ["\u00A4","curren"],["\u00A5","yen"],["\u00A6","brvbar"],["\u00A7","sect"], ["\u00A8","uml"],["\u00A9","copy"],["\u00AA","ordf"],["\u00AB","laquo"], ["\u00AC","not"],["\u00AD","shy"],["\u00AE","reg"],["\u00AF","macr"], ["\u00B0","deg"],["\u00B1","plusmn"],["\u00B2","sup2"],["\u00B3","sup3"], ["\u00B4","acute"],["\u00B5","micro"],["\u00B6","para"],["\u00B7","middot"], ["\u00B8","cedil"],["\u00B9","sup1"],["\u00BA","ordm"],["\u00BB","raquo"], ["\u00BC","frac14"],["\u00BD","frac12"],["\u00BE","frac34"],["\u00BF","iquest"], ["\u00C0","Agrave"],["\u00C1","Aacute"],["\u00C2","Acirc"],["\u00C3","Atilde"], ["\u00C4","Auml"],["\u00C5","Aring"],["\u00C6","AElig"],["\u00C7","Ccedil"], ["\u00C8","Egrave"],["\u00C9","Eacute"],["\u00CA","Ecirc"],["\u00CB","Euml"], ["\u00CC","Igrave"],["\u00CD","Iacute"],["\u00CE","Icirc"],["\u00CF","Iuml"], ["\u00D0","ETH"],["\u00D1","Ntilde"],["\u00D2","Ograve"],["\u00D3","Oacute"], ["\u00D4","Ocirc"],["\u00D5","Otilde"],["\u00D6","Ouml"],["\u00D7","times"], ["\u00D8","Oslash"],["\u00D9","Ugrave"],["\u00DA","Uacute"],["\u00DB","Ucirc"], ["\u00DC","Uuml"],["\u00DD","Yacute"],["\u00DE","THORN"],["\u00DF","szlig"], ["\u00E0","agrave"],["\u00E1","aacute"],["\u00E2","acirc"],["\u00E3","atilde"], ["\u00E4","auml"],["\u00E5","aring"],["\u00E6","aelig"],["\u00E7","ccedil"], ["\u00E8","egrave"],["\u00E9","eacute"],["\u00EA","ecirc"],["\u00EB","euml"], ["\u00EC","igrave"],["\u00ED","iacute"],["\u00EE","icirc"],["\u00EF","iuml"], ["\u00F0","eth"],["\u00F1","ntilde"],["\u00F2","ograve"],["\u00F3","oacute"], ["\u00F4","ocirc"],["\u00F5","otilde"],["\u00F6","ouml"],["\u00F7","divide"], ["\u00F8","oslash"],["\u00F9","ugrave"],["\u00FA","uacute"],["\u00FB","ucirc"], ["\u00FC","uuml"],["\u00FD","yacute"],["\u00FE","thorn"],["\u00FF","yuml"], ["\u0192","fnof"],["\u0391","Alpha"],["\u0392","Beta"],["\u0393","Gamma"], ["\u0394","Delta"],["\u0395","Epsilon"],["\u0396","Zeta"],["\u0397","Eta"], ["\u0398","Theta"], ["\u0399","Iota"],["\u039A","Kappa"],["\u039B","Lambda"], ["\u039C","Mu"],["\u039D","Nu"],["\u039E","Xi"],["\u039F","Omicron"], ["\u03A0","Pi"],["\u03A1","Rho"],["\u03A3","Sigma"],["\u03A4","Tau"], ["\u03A5","Upsilon"],["\u03A6","Phi"],["\u03A7","Chi"],["\u03A8","Psi"], ["\u03A9","Omega"],["\u03B1","alpha"],["\u03B2","beta"],["\u03B3","gamma"], ["\u03B4","delta"],["\u03B5","epsilon"],["\u03B6","zeta"],["\u03B7","eta"], ["\u03B8","theta"],["\u03B9","iota"],["\u03BA","kappa"],["\u03BB","lambda"], ["\u03BC","mu"],["\u03BD","nu"],["\u03BE","xi"],["\u03BF","omicron"], ["\u03C0","pi"],["\u03C1","rho"],["\u03C2","sigmaf"],["\u03C3","sigma"], ["\u03C4","tau"],["\u03C5","upsilon"],["\u03C6","phi"],["\u03C7","chi"], ["\u03C8","psi"],["\u03C9","omega"],["\u03D1","thetasym"],["\u03D2","upsih"], ["\u03D6","piv"],["\u2022","bull"],["\u2026","hellip"],["\u2032","prime"], ["\u2033","Prime"],["\u203E","oline"],["\u2044","frasl"],["\u2118","weierp"], ["\u2111","image"],["\u211C","real"],["\u2122","trade"],["\u2135","alefsym"], ["\u2190","larr"],["\u2191","uarr"],["\u2192","rarr"],["\u2193","darr"], ["\u2194","harr"],["\u21B5","crarr"],["\u21D0","lArr"],["\u21D1","uArr"], ["\u21D2","rArr"],["\u21D3","dArr"],["\u21D4","hArr"],["\u2200","forall"], ["\u2202","part"],["\u2203","exist"],["\u2205","empty"],["\u2207","nabla"], ["\u2208","isin"],["\u2209","notin"],["\u220B","ni"],["\u220F","prod"], ["\u2211","sum"],["\u2212","minus"],["\u2217","lowast"],["\u221A","radic"], ["\u221D","prop"],["\u221E","infin"],["\u2220","ang"],["\u2227","and"], ["\u2228","or"],["\u2229","cap"],["\u222A","cup"],["\u222B","int"], ["\u2234","there4"],["\u223C","sim"],["\u2245","cong"],["\u2248","asymp"], ["\u2260","ne"],["\u2261","equiv"],["\u2264","le"],["\u2265","ge"], ["\u2282","sub"],["\u2283","sup"],["\u2284","nsub"],["\u2286","sube"], ["\u2287","supe"],["\u2295","oplus"],["\u2297","otimes"],["\u22A5","perp"], ["\u22C5","sdot"],["\u2308","lceil"],["\u2309","rceil"],["\u230A","lfloor"], ["\u230B","rfloor"],["\u2329","lang"],["\u232A","rang"],["\u25CA","loz"], ["\u2660","spades"],["\u2663","clubs"],["\u2665","hearts"],["\u2666","diams"], ["\u0152","Elig"],["\u0153","oelig"],["\u0160","Scaron"],["\u0161","scaron"], ["\u0178","Yuml"],["\u02C6","circ"],["\u02DC","tilde"],["\u2002","ensp"], ["\u2003","emsp"],["\u2009","thinsp"],["\u200C","zwnj"],["\u200D","zwj"], ["\u200E","lrm"],["\u200F","rlm"],["\u2013","ndash"],["\u2014","mdash"], ["\u2018","lsquo"],["\u2019","rsquo"],["\u201A","sbquo"],["\u201C","ldquo"], ["\u201D","rdquo"],["\u201E","bdquo"],["\u2020","dagger"],["\u2021","Dagger"], ["\u2030","permil"],["\u2039","lsaquo"],["\u203A","rsaquo"] ]; dhe.encode = function(str/*string*/, m /*array?*/){ // summary: // Function to obtain an entity encoding for a specified character // str: // The string to process for possible entity encoding. // m: // An optional list of character to entity name mappings (array of // arrays). If not provided, it uses the and Latin entities as the // set to map and escape. // tags: // public if(str){ if(!m){ // Apply the basic mappings. HTML should always come first when decoding // as well. str = _applyEncodingMap(str, dhe.html); str = _applyEncodingMap(str, dhe.latin); }else{ str = _applyEncodingMap(str, m); } } return str; }; dhe.decode = function(str/*string*/, m /*array?*/){ // summary: // Function to obtain an entity encoding for a specified character // str: // The string to process for possible entity encoding to decode. // m: // An optional list of character to entity name mappings (array of // arrays). If not provided, it uses the HTML and Latin entities as the // set to map and decode. // tags: // public if(str){ if(!m){ // Apply the basic mappings. HTML should always come first when decoding // as well. str = _applyDecodingMap(str, dhe.html); str = _applyDecodingMap(str, dhe.latin); }else{ str = _applyDecodingMap(str, m); } } return str; }; return dhe; }); }, 'sbt/smartcloud/ProfileService':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. * @author Vimal Dhupar * * Javascript APIs for IBM SmartCloud Profiles Service. * @module sbt.smartcloud.ProfileService **/ define(["../declare","../lang", "../config","../stringUtil","../Cache","./Subscriber","../Jsonpath","../base/BaseService", "../base/JsonDataHandler", "./ProfileConstants", "../base/BaseEntity","../Promise"], function(declare, lang, config, StringUtil, Cache, Subscriber, JsonPath, BaseService, JsonDataHandler, Consts, BaseEntity, Promise) { /** * Profile class representing the Smartcloud User Profile. * * @class Profile * @namespace sbt.smartcloud */ var Profile = declare(BaseEntity, { /** * Profile Class Constructor * * @constructor * @param args */ constructor : function(args) { }, /** * Loads the profile object with the profile entry document associated * with the profile. By default, a network call is made to load the * profile entry document in the profile object. * * @method load * @param {Object} [args] Argument object * */ load: function(args) { var profileId = this.getId(); var promise = this.service._validateProfileId(profileId); if (promise) { return promise; } var self = this; var callbacks = { createEntity : function(service,data,response) { return new JsonDataHandler({ data : data, jsonpath : Consts.ProfileJsonPath }); } }; var requestArgs = {}; requestArgs.userid = profileId; lang.mixin(requestArgs, args || {format:"json"}); var options = { handleAs : "json", query : requestArgs }; return this.service.getEntity(consts.GetProfile, options, profileId, callbacks, args); }, /** * Returns the id of the User * @method getId * @return {String} id of the User **/ getId: function () { return this.getAsString("id"); }, /** * Returns the id of the User * @method getUserid * @return {String} id of the User **/ getUserid: function () { return this.getAsString("id"); }, /** * Returns the object id of the User * @method getObjectId * @return {String} id of the User */ getObjectId: function () { return this.getAsString("objectId"); }, /** * Get display name of the User * @method getDisplayName * @return {String} display name of the User */ getDisplayName: function () { return this.getAsString("displayName"); }, /** * Get display name of the User * @method getName * @return {String} display name of the User */ getName: function () { return this.getAsString("displayName"); }, /** * Get email of the User * @method getEmail * @return {String} email of the User */ getEmail: function () { return this.getAsString("emailAddress"); }, /** * Get thumbnail URL of the User * @method getThumbnailUrl * @return {String} thumbnail URL of the User */ getThumbnailUrl: function () { var image = this.getAsString("thumbnailUrl"); if(image) image = this.service.endpoint.baseUrl+"/contacts/img/photos/"+ image; // TODO : work in making this generic return image; }, /** * Get address of the profile * @method getAddress * @return {String} Address object of the profile */ getAddress: function () { var address = this.getAsArray("address"); address = this.dataHandler.extractFirstElement(address); return address; }, /** * Get department of the profile * @method getDepartment * @return {String} department of the profile */ getDepartment: function () { return this.getAsString("department"); }, /** * Get job title of the profile * @method getJobTitle * @return {String} job title of the profile */ getJobTitle: function () { return this.getAsString("jobTitle"); }, /** * Get profile URL of the profile * @method getProfileUrl * @return {String} profile URL of the profile */ getProfileUrl: function () { return this.getAsString("profileUrl"); }, /** * Get telephone number of the profile * @method getTelehoneNumber * @return {String} Telephone number object of the profile */ getTelephoneNumber: function () { return this.getAsString("telephone"); }, /** * Get Country of the profile * @method getCountry * @return {String} country of the profile */ getCountry: function () { return this.getAsString("country"); }, /** * Get Organization Id of the profile * @method getOrgId * @return {String} Organization Id of the profile */ getOrgId: function () { return this.getAsString("orgId"); }, /** * Get Organization of the profile * @method getOrg * @return {String} Organization of the profile */ getOrg: function () { return this.getAsString("org"); }, /** * Get "About Me"/description of the profile * @method getAbout * @return {String} description of the profile */ getAbout: function () { return this.getAsString("about"); } }); /** * Callbacks used when reading an entry that contains a Profile. */ var ProfileCallbacks = { createEntity : function(service,data,response) { var entryHandler = new JsonDataHandler({ data : data, jsonpath : Consts.ProfileJsonPath }); return new Profile({ service : service, id : entryHandler.getEntityId(), dataHandler : entryHandler }); } }; /** * Callbacks used when reading a feed that contains multiple Profiles. */ var ProfileFeedCallbacks = { createEntities : function(service,data,response) { return new JsonDataHandler({ data : data, jsonpath : Consts.ProfileJsonPath }); }, createEntity : function(service,data,response) { var entryHandler = new JsonDataHandler({ data : data, jsonpath : Consts.ProfileJsonPath }); return new Profile({ service : service, id : entryHandler.getEntityId(), dataHandler : entryHandler }); } }; /** * Profile service class associated with a profile service of IBM SmartCloud. * * @class ProfileService * @namespace sbt.smartcloud */ var ProfileService = declare(BaseService, { _profiles: null, /** * * @constructor * @param args */ constructor : function(args) { if (!this.endpoint) { this.endpoint = config.findEndpoint(this.getDefaultEndpointName()); } if(!this._cache){ if(config.Properties.ProfileCacheSize || Consts.DefaultCacheSize){ this._cache = new Cache(config.Properties.ProfileCacheSize || Consts.DefaultCacheSize); } } }, /** * Return the default endpoint name if client did not specify one. * @returns {String} */ getDefaultEndpointName: function() { return "smartcloud"; }, /** * Get the profile of a user. * * @method getProfile * @param {String} userId Userid of the profile * @param {Object} args Argument object */ getProfile : function(userId, args) { var idObject = this._toIdObject(userId); var promise = this._validateIdObject(idObject); if (promise) { return promise; } var requestArgs = lang.mixin(idObject, args || {format:"json"}); var options = { method : "GET", handleAs : "json", query : args || { format: "json" } }; var entityId = encodeURIComponent(idObject.userid); var url = this.constructUrl(Consts.GetProfileByGUID, {}, {idToBeReplaced : entityId}); return this.getEntity(url, options, entityId, this.getProfileCallbacks()); }, /** * Get the profile of a user. * * @method getProfileByGUID * @param {String} userId Userid of the profile * @param {Object} args Argument object * @deprecated Use getProfile instead. */ getProfileByGUID : function(userId, args) { return this.getProfile(userId, args); }, /** * Get the profile of a logged in user. * * @method getMyProfile * @param {Object} args Argument object */ getMyProfile : function(args) { var self = this; var url = Consts.GetUserIdentity; var promise = new Promise(); this.endpoint.request(url, { handleAs : "json" }).then(function(response) { var idObject = self._toIdObject(response.subscriberid); var promise1 = self._validateIdObject(idObject); if (promise1) { return promise1; } var requestArgs = lang.mixin(idObject, args || {format:"json"}); var options = { method : "GET", handleAs : "json", query : requestArgs }; var entityId = encodeURIComponent(idObject.userid); var url = self.constructUrl(Consts.GetProfileByGUID, {}, {idToBeReplaced : entityId}); (self.getEntity(url, options, entityId, self.getProfileCallbacks())).then(function(response) { promise.fulfilled(response); }, function(error) { promise.rejected(error); }); }, function(error) { promise.rejected(error); } ); return promise; }, /** * Get the contact details of a user. * * @method getContact * @param {String} userId Userid of the profile * @param {Object} args Argument object */ getContact : function(userId, args) { var idObject = this._toIdObject(userId); var promise = this._validateIdObject(idObject); if (promise) { return promise; } var requestArgs = lang.mixin(idObject, args || {format:"json"}); var options = { method : "GET", handleAs : "json", query : requestArgs }; var entityId = idObject.userid; var url = this.constructUrl(Consts.GetContactByGUID, {}, {idToBeReplaced : entityId}); return this.getEntity(url, options, entityId, this.getProfileCallbacks()); }, /** * Get the contact details of a user. * * @method getContactByGUID * @param {String} userId Userid of the profile * @param {Object} args Argument object * @deprecated Use getContact instead. */ getContactByGUID : function(userId, args) { return this.getContact(userId, args); }, /** * Get logged in user's Connections * * @method getMyConnections * @param {Object} args Argument object */ getMyConnections : function(args) { var options = { method : "GET", handleAs : "json", query : args || {format:"json"} }; return this.getEntities(Consts.GetMyConnections, options, this.getProfileFeedCallbacks()); }, /** * Get logged in user's Contacts * * @method getMyContacts * @param {Object} args Argument object */ getMyContacts : function(args) { var options = { method : "GET", handleAs : "json", query : args || {format:"json"} }; return this.getEntities(Consts.GetMyContacts, options, this.getProfileFeedCallbacks()); }, /** * Get logged in user's Contacts considering the startIndex and count as provided by the user * * @method getMyContactsByIndex * @param startIndex * @param count * @param {Object} args Argument object */ getMyContactsByIndex : function(startIndex, count, args) { var requestArgs = { "startIndex" : startIndex, "count" : count }; var options = { method : "GET", handleAs : "json", query : lang.mixin(requestArgs , args || {format:"json"}) }; return this.getEntities(Consts.GetMyContacts, options, this.getProfileFeedCallbacks()); }, /** * Return callbacks for a profile entry **/ getProfileCallbacks : function() { return ProfileCallbacks; }, /** * Return callbacks for a profile feed **/ getProfileFeedCallbacks : function() { return ProfileFeedCallbacks; }, _toIdObject : function(profileOrId) { var idObject = {}; if (lang.isString(profileOrId)) { idObject.userid = profileOrId; } else if (profileOrId instanceof Profile) { idObject.userid = profileOrId.getUserid(); } return idObject; }, _validateIdObject : function(idObject) { if (!idObject.userid) { return this.createBadRequestPromise("Invalid argument, userid must be specified."); } }, _validateProfileId : function(profileId) { if (!profileId || profileId.length == 0) { return this.createBadRequestPromise("Invalid argument, expected userid"); } } }); return ProfileService; }); }, 'sbt/connections/ProfileAdminService':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * JavaScript API for IBM Connections Profile Service. * * @module sbt.connections.ProfileService */ define([ "../declare", "../lang", "../config", "../stringUtil", "./ProfileConstants", "../base/BaseService", "../base/XmlDataHandler", "./ProfileService" ], function( declare,lang,config,stringUtil,consts,BaseService,XmlDataHandler, ProfileService) { /** * ProfileAdminService class. * * @class ProfileAdminService * @namespace sbt.connections */ var ProfileAdminService = declare(ProfileService , { /** * Create a new profile * * @method createProfile * @param {Object} profileOrJson Profile object or json representing the profile to be created. * @param {Object} [args] Object representing various query parameters * that can be passed. The parameters must be exactly as they are * supported by IBM Connections. */ createProfile : function(profileOrJson,args) { var profile = this._toProfile(profileOrJson); var promise = this._validateProfile(profile); if (promise) { return promise; } var requestArgs = {}; profile.getUserid() ? requestArgs.userid = profile.getUserid() : requestArgs.email = profile.getEmail(); lang.mixin(requestArgs, args || {}); var callbacks = {}; callbacks.createEntity = function(service,data,response) { return profile; }; var options = { method : "POST", query : requestArgs, headers : consts.AtomXmlHeaders, data : profile.createPostData() }; return this.updateEntity(consts.AdminAtomProfileDo, options, callbacks, args); }, /** * Delete an existing profile * * @method deleteProfile * @param {Object} profileId userid or email of the profile * @param {Object}[args] Object representing various query parameters * that can be passed. The parameters must be exactly as they are * supported by IBM Connections. */ deleteProfile : function(profileId,args) { var promise = this._validateProfileId(profileId); if (promise) { return promise; } var requestArgs = {}; this.isEmail(profileId) ? requestArgs.email = profileId : requestArgs.userid = profileId; lang.mixin(requestArgs, args || {}); var options = { method : "DELETE", query : requestArgs, handleAs : "text" }; return this.deleteEntity(consts.AdminAtomProfileEntryDo, options, profileId, args); } }); return ProfileAdminService; }); }, 'sbt/authenticator/GadgetOAuth':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. * Definition of the authentication mechanism for OAuth 1.0. */ define([ "../declare", "../lang" ], function(declare,lang) { /** * OpenSocial OAuth authentication. * * This class triggers the authentication for a service. */ return declare(null, { constructor : function(args) { lang.mixin(this, args || {}); }, /** * Method that authenticates the current user */ authenticate : function(options) { var onOpen = function() { }; var onClose = function() { }; var response = options.error.response; var popup = new gadgets.oauth.Popup(response.oauthApprovalUrl, null, onOpen, onClose); popup.createOpenerOnClick(); } }); }); }, 'sbt/authenticator/OAuth':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK. * Definition of the authentication mechanism for OAuth 1.0. */ define(['../declare','../lang', '../util'], function(declare, lang, util) { /** * OAuth 1.0 authentication. * * This class triggers the authentication for a service. */ return declare(null, { url: "", loginUi: "", // mainWindow, dialog or popup constructor: function(args){ lang.mixin(this, args || {}); }, /** * Method that authenticates the current user */ authenticate: function(options) { var self = this; require(["sbt/config"], function(config) { var mode = options.loginUi || config.Properties["loginUi"] || this.loginUi; var width = config.Properties["login.oauth.width"] || 800; var height = config.Properties["login.oauth.height"] || 450; if(mode=="popup") { return self._authPopup(options, self.url, width, height); } else if(mode=="dialog") { return self._authDialog(options, self.url, width, height); } else { return self._authMainWindow(options, self.url); } }); }, _authMainWindow: function(options, sbtUrl) { var url = sbtUrl + "?oaredirect="+encodeURIComponent(window.location.href); newwindow=window.location.href = url; return true; }, _authPopup: function(options, sbtUrl, width, height) { require(["sbt/config"], function(config){ config.callback = options.callback; var url = sbtUrl + "?loginUi=popup"; var windowQueryMap = { height: height, width: width }; var windowQuery = util.createQuery(windowQueryMap, ","); newwindow = window.open(url,'Authentication',windowQuery); return true; }); }, _authDialog: function(options, sbtUrl, width, height) { require(["sbt/_bridge/ui/OAuthDialog"], function(dialog) { dialog.show(sbtUrl, width, height); }); return true; } }); }); }, 'sbt/store/AtomStore':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * @module sbt.store.AtomStore */ define(["../declare","../config","../lang", "../base/core", "../xml", "../xpath", "../itemFactory", "../Promise", "dojo/_base/Deferred", "dojo/promise/Promise", "dojo/store/util/QueryResults", "../entities"], function(declare, config, lang, core, xml, xpath, itemFactory, SbtPromise, Deferred, Promise, QueryResults, entities) { /** * @class sbt.store.AtomStore */ var AtomStorePromise = declare(Promise, { // private _store : null, _isRejected : false, _isFulfilled : false, _isCancelled : false, _callbacks : [], _errbacks : [], _endpoint : null, _xmlData : null, // read only totalResults : null, startIndex : 0, itemsPerPage : 5, items : null, // public url : "", sendQuery : true, unescapeHTML : false, atom : core.feedXPath, attributes : core.entryXPath, namespaces : core.namespaces, paramSchema: {}, total: null, /** * Constructor for the AtomStore promise. * @param args requires * endpoint: the endpoint to be used */ constructor: function(args, query, options) { this._endpoint = config.findEndpoint(args.endpoint || "connections"); this._options = options; this._callbacks = []; this._errbacks = []; this.total = new SbtPromise(); if (args) { this.url = args.url; this.attributes = args.attributes || this.attributes; this.atom = args.feedXPath || this.atom; this.namespaces = args.namespaces || this.namespaces; this.sendQuery = args.hasOwnProperty("sendQuery") ? args.sendQuery : this.sendQuery; this.unescapeHTML = args.unescapeHTML || this.unescapeHTML; this.paramSchema = args.paramSchema || this.paramSchema; } // add paging information to the query if (this.paramSchema.pageNumber) { var page = Math.floor(options.start / options.count) + 1; query.pageNumber = query.pageNumber || page; } if (this.paramSchema.startIndex) { query.startIndex = query.startIndex || options.start; } if (this.paramSchema.pageSize) { query.pageSize = query.pageSize || options.count; } // add the sorting information to the query if (options.sort && options.sort[0]) { if (options.sort[0].attribute) { query.sortBy = options.sort[0].attribute; } if(options.sort[0].descending === true) { query.sortOrder = "desc"; } else if(options.sort[0].descending === false) { query.sortOrder = "asc"; } } var fetchArgs = { query : query }; this._doFetch(fetchArgs); }, /* * Add new callbacks to the promise. */ then: function(callback, errback, progback) { if (this._isFulfilled) { callback(this.items); return; } if (callback) { this._callbacks.push(callback); } if (errback) { this._errbacks.push(errback); } }, /* * Inform the deferred it may cancel its asynchronous operation. */ cancel: function(reason, strict) { this._isCancelled = true; }, /* * Checks whether the promise has been resolved. */ isResolved: function() { return this._isRejected || this._isFulfilled; }, /* * Checks whether the promise has been rejected. */ isRejected: function() { return this._isRejected; }, /* * Checks whether the promise has been resolved or rejected. */ isFulfilled: function() { return this._isFulfilled; }, /* * Checks whether the promise has been canceled. */ isCanceled: function() { return this._isCancelled; }, // Internals /* * Given a query and set of defined options, such as a start and count of items to return, * this method executes the query and makes the results available as data items. */ _doFetch: function(args) { var self = this; var scope = args.scope || self; var serviceUrl = this._getServiceUrl(args.query); if (!serviceUrl) { if (args.onError) { args.onError.call(new Error("sbt.store.AtomStore: No service URL specified.")); } return; } this._endpoint.xhrGet({ serviceUrl : serviceUrl, handleAs : "text", preventCache: true, load : function(response) { try { // parse the data self.response = response; self._xmlData = xml.parse(response); self.totalResults = parseInt(xpath.selectText(self._xmlData, self.atom.totalResults, self.namespaces)); self.startIndex = parseInt(xpath.selectText(self._xmlData, self.atom.startIndex, self.namespaces)); self.itemsPerPage = parseInt(xpath.selectText(self._xmlData, self.atom.itemsPerPage, self.namespaces)); self.items = self._createItems(self._xmlData); if (self._options.onComplete) { self._options.onComplete.call(self._options.scope || self, self.items, self._options); } // invoke callbacks self.total.fulfilled(self.totalResults); self._fulfilled(self.items); } catch (error) { self.total._rejected(error); self._rejected(error); } }, error : function(error) { self.total._rejected(error); self._rejected(error); } }); }, /* * Create the service url and include query params */ _getServiceUrl: function(query) { if (!this.sendQuery) { return this.url; } if (!query) { return this.url; } if (lang.isString(query)) { return this.url + (~this.url.indexOf('?') ? '&' : '?') + query; } var pairs = []; var paramSchema = this.paramSchema; for(var key in query) { if (key in paramSchema) { var val = paramSchema[key].format(query[key]); if (val) { pairs.push(val); } } else { pairs.push(encodeURIComponent(key) + "=" + encodeURIComponent(query[key])); } } if (pairs.length == 0) { return this.url; } return this.url + (~this.url.indexOf('?') ? '&' : '?') + pairs.join("&"); }, /* * Create a query string from an object */ _createQuery: function(queryMap) { if (!queryMap) { return null; } var pairs = []; for(var name in queryMap){ var value = queryMap[name]; pairs.push(encodeURIComponent(name) + "=" + encodeURIComponent(value)); } return pairs.join("&"); }, _createItems: function(document) { var nodes = xpath.selectNodes(document, this.atom.entries, this.namespaces); var items = []; for (var i=0; i<nodes.length; i++) { items.push(this._createItem(nodes[i])); } return items; }, _createItem: function(element) { var attribs = this._getAttributes(); var xpathCountFunction = /^count\(.*\)$/; // TODO add item.index and item.attribs var item = { element : element, getValue : function(attrib) { var result = []; if(typeof this[attrib] == "object"){ for(var i=0;i<this[attrib].length; i++){ result[i] = entities.encode(this[attrib][i]); } } else{ result = entities.encode(this[attrib]); } return result; } }; for (var i=0; i<attribs.length; i++) { var attrib = attribs[i]; var access = this.attributes[attrib]; if (lang.isFunction(access)) { item[attrib] = access(this, item); } else if (access.match(xpathCountFunction)){ item[attrib] = xpath.selectNumber(element, access, this.namespaces)+""; } else { var nodes = xpath.selectNodes(element, access, this.namespaces); if (nodes && nodes.length == 1) { item[attrib] = entities.encode(nodes[0].text) || entities.encode(nodes[0].textContent); } else if (nodes) { item[attrib] = []; for (var j=0; j<nodes.length; j++) { item[attrib].push(entities.encode(nodes[j].text) || entities.encode(nodes[j].textContent)); } } else { item[attrib] = null; } } } return item; }, _getAttributes: function() { var result = []; for (var name in this.attributes) { if (this.attributes.hasOwnProperty(name)) { result.push(name); } } return result; }, _fulfilled : function(totalCount) { if (this._isCancelled) { return; } this._isFulfilled = true; while (this._callbacks.length > 0) { var callback = this._callbacks.shift(); callback(totalCount); } }, _rejected : function(error) { if (this._isCancelled) { return; } this._isRejected = true; while (this._errbacks.length > 0) { var errback = this._errbacks.shift(); errback(error); } } }); /** * @module sbt.store.AtomStore */ var AtomStore = declare(null, { // Indicates the property to use as the identity property. The values of this // property should be unique. idProperty: "id", _args : null, /** * Constructor for the Atom store. * * @param args * An anonymous object to initialize properties. It expects the following values: * url: The url to a service or an XML document that represents the store * unescapeHTML: A boolean to specify whether or not to unescape HTML text * sendQuery: A boolean indicate to add a query string to the service URL */ constructor: function(args) { this._args = args; //if(!args.url) { // throw new Error("sbt.store.AtomStore: A service URL must be specified when creating the data store"); //} }, /** * @method getEndpoint * @returns */ getEndpoint: function() { return config.findEndpoint(this._args.endpoint || "connections"); }, /** * Retrieves an object by its identity * @method get * @param id */ get: function(id) { throw new Error("sbt.store.AtomStore: Not implemented yet!"); }, /** * Returns an object's identity * @method getIdentity * @param object */ getIdentity: function(object) { return object.id; }, setUrl: function(url){ this._args.url = url; }, getUrl: function(){ return this._args.url; }, setAttributes: function(attributes){ this._args.attributes = attributes; }, /** * Queries the store for objects. This does not alter the store, but returns a set of data from the store. * @method query * @param query * @param options */ query: function(query, options) { var results = new AtomStorePromise(this._args, query, options); return QueryResults(results); } }); return AtomStore; }); }, 'sbt/connections/nls/ConnectionsService':function(){ /* * © Copyright IBM Corp. 2012,2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK - Default resource bundle for ConnectionsService */ define({ root: ({ invalid_argument : "Invalid Argument" }) }); }, 'sbt/itemFactory':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * I18n utilities */ define(["./lang", "./xpath", "./base/core"], function(lang, xpath, core) { var XPathCountFunction = /^count\(.*\)$/; /** * @module sbt.itemFactory */ return { createItems: function(document, attributes, thisObject, decoder) { var nodes = xpath.selectNodes(document, core.feedXPath.entry, core.namespaces); var items = []; if (nodes.length == 0) { nodes = xpath.selectNodes(document, "a:entry", core.namespaces); } for (var i=0; i<nodes.length; i++) { items.push(this.createItem(nodes[i], attributes, thisObject, decoder)); } return items; }, createItem: function(element, attributes, thisObject, decoder) { // TODO add item.index and item.attribs var item = { element : element, getValue : function(attrib) { return this[attrib]; } }; var attribs = this.getAttribs(attributes); for (var i=0; i<attribs.length; i++) { var attrib = attribs[i]; var access = attributes[attrib]; if (lang.isFunction(access)) { item[attrib] = access(thisObject, item); } else if (access.match(XPathCountFunction)){ item[attrib] = xpath.selectNumber(element, access, core.namespaces); } else { var nodes = xpath.selectNodes(element, access, core.namespaces); if (nodes && nodes.length == 1) { item[attrib] = nodes[0].text || nodes[0].textContent; } else if (nodes) { item[attrib] = []; for (var j=0; j<nodes.length; j++) { item[attrib].push(nodes[j].text || nodes[j].textContent); } } else { item[attrib] = null; } } item[attrib] = (decoder) ? decoder.decode(item[attrib]) : item[attrib]; } return item; }, getAttribs: function(attributes) { var attribs = []; for (var name in attributes) { if (attributes.hasOwnProperty(name)) { attribs.push(name); } } return attribs; } }; }); }, 'sbt/compat':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK - Compatibility with older browsers * * @module sbt.compat */ define([],function() { if (!Array.prototype.indexOf){ Array.prototype.indexOf = function(item, start) { var index = start || 0; var max = this.length; for (; index < max; index++) { if (this[index] === item) { return index; } } return -1; }; } return { }; }); }, 'sbt/authenticator/nls/SSO':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK - Default resource bundle for validate module. */ define({ root: ({ message_title: "ReAuthenticate", message:"Authentication expired, Please login again." }) }); }, 'sbt/_bridge/dom':function(){ /* * © Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Social Business Toolkit SDK - Some DOM utilities. */ define(['dojo/dom','dojo/_base/window', 'dojo/dom-construct', 'dojo/dom-class'],function(dom,win,domConstruct,domClass) { return { byId: function(id) { return dom.byId(id); }, createTextNode: function(text) { //return dojo.doc.createTextNode(text); //change also made to define, added 'dojo/_base/window' return win.doc.createTextNode(text); }, create: function(element, props, refNode) { return domConstruct.create(element, props, refNode); }, destroy: function(node) { return domConstruct.destroy(node); }, toDom: function(template, parent) { return domConstruct.toDom(template, parent); }, removeAll: function(node) { node = this.byId(node); if(node) { while(node.firstChild) node.removeChild(node.firstChild); } return node; }, setText: function(node,text) { node = this.byId(node); if(node) { this.removeAll(node); node.appendChild(this.createTextNode(text)); } return node; }, setAttr: function(node,attr,text) { node = this.byId(node); if(node) { if(text) { node.setAttribute(attr,text); } else { node.removeAttribute(attr); } } return node; }, addClass: function(node, className) { return domClass.add(node, className); }, removeClass: function(node, className) { return domClass.remove(node, className); } }; }); }, 'sbt/connections/FollowService':function(){ /* * © Copyright IBM Corp. 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /** *The following resources are enabled for these applications: *Activities *You can follow any public activity. To follow a private activity, you must be a member of the activity. *Blogs *You can follow any stand-alone blog; you cannot follow community blogs. *Communities *You do not have to be a member to follow public or moderated communities. You must be a member to follow private communities. *Files *You can follow any public file or file folders. You can only follow private files and file folders that have been shared with you. *Forums *You can follow any public forum or forum topic. You can only follow private forums if you are a member or owner of the forum. *News repository *You can follow any tag. *Profiles *You can follow any profile. *Wikis *You can follow any public wiki or wiki page. You must be a reader, editor, or owner of a private wiki before you can follow it or one of its pages. * * @module sbt.connections.FollowService */ define( [ "../declare", "../config", "../lang", "../stringUtil", "../Promise", "./FollowConstants", "./ConnectionsService", "../base/AtomEntity", "../base/XmlDataHandler" ], function(declare, config, lang, stringUtil, Promise, consts, ConnectionsService, AtomEntity, XmlDataHandler) { var SourceTmpl = "<category term=\"${getSource}\" scheme=\"http://www.ibm.com/xmlns/prod/sn/source\"></category>"; var ResourceTypeTmpl = "<category term=\"${getResourceType}\" scheme=\"http://www.ibm.com/xmlns/prod/sn/resource-type\"></category>"; var ResourceIdTmpl = "<category term=\"${getResourceId}\" scheme=\"http://www.ibm.com/xmlns/prod/sn/resource-id\"></category>"; /** * FollowedResource class represents an entry for a resource followed by logged in user. * * @class FollowedResource * @namespace sbt.connections */ var FollowedResource = declare(AtomEntity, { xpath : consts.FollowedResourceXPath, /** * Construct a FollowedResource entity. * * @constructor * @param args */ constructor : function(args) { }, /** * Return extra entry data to be included in post data for this entity. * * @returns {String} */ createEntryData : function() { var postData = ""; var transformer = function(value,key) { return value; }; postData += stringUtil.transform(SourceTmpl, this, transformer, this); postData += stringUtil.transform(ResourceTypeTmpl, this, transformer, this); if (this.getResourceId()) { postData += stringUtil.transform(ResourceIdTmpl, this, transformer, this); } return stringUtil.trim(postData); }, /** * Return the value of IBM Connections followed resource ID from * resource ATOM entry document. * * @method getFollowedResourceUuid * @return {String} Resource ID */ getFollowedResourceUuid : function() { var followedResourceUuid = this.getAsString("followedResourceUuid"); return extractFollowedResourceUuid(followedResourceUuid); }, /** * Sets id of IBM Connections followed resource. * * @method setFollowedResourceUuid * @param {String} followedResourceUuid Id of the followed resource */ setFollowedResourceUuid : function(followedResourceUuid) { return this.setAsString("followedResourceUuid", followedResourceUuid); }, /** * Return the value of IBM Connections followed resource's service name * * @method getSource * @return {String} Followed resource's service name */ getSource : function() { return this.getAsString("source"); }, /** * Sets IBM Connections followed resource's service name. * * @method setSource * @param {String} * Source service name of the followed resource */ setSource : function(source) { return this.setAsString("source", source); }, /** * Return the value of IBM Connections followed resource's resourceType * * @method getResourceType * @return {String} Followed resource's resource type */ getResourceType : function() { return this.getAsString("resourceType"); }, /** * Sets IBM Connections followed resource's resource type. * * @method setResourceType * @param {String} * resourceType of the followed resource */ setResourceType : function(resourceType) { return this.setAsString("resourceType", resourceType); }, /** * Return the value of IBM Connections followed resource's resourceId * * @method getResourceId * @return {String} Followed resource's resource Id */ getResourceId : function() { return this.getAsString("resourceId"); }, /** * Sets IBM Connections followed resource's resourceId. * * @method setResourceType * @param {String} * resource id of the followed resource */ setResourceId : function(resourceId) { return this.setAsString("resourceId", resourceId); }, /** * Return the value of IBM Connections followed resource's type * * @method getType * @return {String} Followed resource's resource type */ getType : function() { return this.getAsString("categoryType"); }, /** * Sets IBM Connections followed resource's resource type. * * @method setCategoryResourceType * @param {String} * type of the followed resource */ setCategoryType : function(categoryType) { return this.setAsString("categoryType", categoryType); }, /** * Start following * * @method startFollowing * @param {Object} [args] Argument object */ startFollowing : function(args) { return this.service.startFollowing(this, args); }, /** * Stop following * * @method stopFollowing * @param {Object} [args] Argument object */ stopFollowing : function(args) { return this.service.stopFollowing(this, args); } }); /* * Callbacks used when reading a feed that contains followed resource entries. */ var FollowResourceFeedCallbacks = { createEntities : function(service,data,response) { return new XmlDataHandler({ service : service, data : data, namespaces : consts.Namespaces, xpath : consts.FollowedResourceFeedXPath }); }, createEntity : function(service,data,response) { return new FollowedResource({ service : service, data : data }); } }; /* * Method used to extract the community uuid for an id url. */ var extractFollowedResourceUuid = function(followedResourceUuid) { var followedResourceUuidPrefix = "urn:lsid:ibm.com:follow:resource-"; if(followedResourceUuid && followedResourceUuid.indexOf(followedResourceUuidPrefix) != -1){ followedResourceUuid = followedResourceUuid.substring(followedResourceUuidPrefix.length, followedResourceUuid.length); } return followedResourceUuid; }; /** * FollowService class. * * @class FollowService * @namespace sbt.connections */ var FollowService = declare( ConnectionsService, { contextRootMap : { activities : "activities", blogs : "blogs", communities : "communities", files : "files", forums : "forums", news : "news", profiles : "profiles", wikis : "wikis" }, serviceName : "connections", /** * Constructor for FollowService * * @constructor * @param args */ constructor : function(args) { if (!this.endpoint) { this.endpoint = config.findEndpoint(this .getDefaultEndpointName()); } }, /** * Get the followed resources feed * * @method getFollowedResources * @param {String} source String specifying the resource. * @param {String} resourceType String representing the resource type. * @param {Object} [args] Addtional request arguments supported by Connections REST API. */ getFollowedResources : function(source, resourceType, args) { var requestArgs = lang.mixin({ source : source, type : resourceType }, args || {}); var options = { method : "GET", handleAs : "text", query : requestArgs }; var url = null; url = this.constructUrl(consts.AtomFollowAPI, null, { service : this._getServiceName(source) }); return this.getEntities(url, options, this._getFollowedResourceFeedCallbacks()); }, /** * Get the followed resource * * @method getFollowedResource * @param {String/Object} followedResource * @param {Object} [args] Object representing various parameters if any */ getFollowedResource : function(followedResourceOrJson, args) { var followedResource = this._toFollowedResource(followedResourceOrJson); var promise = this._validateFollowedResource(followedResource, false, args); if (promise) { return promise; } var requestArgs = lang.mixin({ source : followedResource.getSource(), type : followedResource.getResourceType(), resource : followedResource.getResourceId() }, args || {}); var options = { method : "GET", handleAs : "text", query : requestArgs }; var callbacks = { createEntity : function(service,data,response) { followedResource.xpath = consts.OneFollowedResourceXPath; followedResource.setData(data); return followedResource; } }; var url = null; url = this.constructUrl(consts.AtomFollowAPI, null, { service : this._getServiceName(followedResource.getSource()) }); return this.getEntity(url, options, followedResource.getResourceId(), callbacks); }, /** * Start Following a resource * * @method startFollowing * @param {String/Object} followedResource * @param {Object} [args] Object representing various parameters if any */ startFollowing : function(followedResourceOrJson, args) { var followedResource = this._toFollowedResource(followedResourceOrJson); var promise = this._validateFollowedResource(followedResource, false, args); if (promise) { return promise; } var options = { method : "POST", headers : consts.AtomXmlHeaders, data : followedResource.createPostData() }; var callbacks = {}; callbacks.createEntity = function(service,data,response) { followedResource.setData(data); return followedResource; }; var url = null; url = this.constructUrl(consts.AtomFollowAPI, null, { service : this._getServiceName(followedResource.getSource()) }); return this.updateEntity(url, options, callbacks); }, /** * Stop Following a resource * * @method stopFollowing * @param {String/Object} followedResource * @param {Object} [args] Object representing various parameters if any */ stopFollowing : function(followedResourceOrJson, args) { var followedResource = this._toFollowedResource(followedResourceOrJson); var promise = this._validateFollowedResource(followedResource, true); if (promise) { return promise; } var requestArgs = lang.mixin({ source : followedResource.getSource(), type : followedResource.getResourceType(), resource : followedResource.getResourceId() }, args || {}); var options = { method : "DELETE", headers : consts.AtomXmlHeaders, query : requestArgs }; var url = this.constructUrl(consts.AtomStopFollowAPI, null, { service : this._getServiceName(followedResource.getSource()), resourceId : followedResource.getFollowedResourceUuid() }); return this.deleteEntity(url, options, followedResource.getResourceId()); }, /** * Create a FollowedResource object with the specified data. * * @method newFollowedResource * @param {Object} args Object containing the fields for the * new blog */ newFollowedResource : function(args) { return this._toFollowedResource(args); }, /* * Callbacks used when reading a feed that contains * followed resource entries. */ _getFollowedResourceFeedCallbacks : function() { return FollowResourceFeedCallbacks; }, /* * Validate a blog, and return a Promise if invalid. */ _validateFollowedResource : function(followedResource, checkUuid) { if (!followedResource || !followedResource.getSource()) { return this.createBadRequestPromise("Invalid argument, resource with source must be specified."); } if (!followedResource.getResourceType()) { return this.createBadRequestPromise("Invalid argument, resource with resource yype must be specified."); } if (!followedResource.getResourceId()) { return this.createBadRequestPromise("Invalid argument, resource with resource id must be specified."); } if (checkUuid && !followedResource.getFollowedResourceUuid()) { return this.createBadRequestPromise("Invalid argument, resource with UUID must be specified."); } }, /* * Validate a followedResource UUID, and return a Promise if invalid. */ _validateFollowedResourceUuid : function(followedResourceUuid) { if (!followedResourceUuid || followedResourceUuid.length == 0) { return this.createBadRequestPromise("Invalid argument, expected followedResourceUuid."); } }, /* * Return a Followed Resource instance from FollowedResource or JSON or String. Throws * an error if the argument was neither. */ _toFollowedResource : function(followedResourceOrJsonOrString) { if (followedResourceOrJsonOrString instanceof FollowedResource) { return followedResourceOrJsonOrString; } else { if (lang.isString(followedResourceOrJsonOrString)) { followedResourceOrJsonOrString = { followedResourceUuid : followedResourceOrJsonOrString }; } return new FollowedResource({ service : this, _fields : lang.mixin({}, followedResourceOrJsonOrString) }); } }, /* * Return a Followed Resource instance from FollowedResource or JSON or String. Throws * an error if the argument was neither. */ _getServiceName : function(source) { var contextRoot = this.contextRootMap; for (var key in contextRoot) { if(source == key){ return contextRoot[key]; } } return ""; } }); return FollowService; }); }}}); define([], 1);
/* YUI 3.16.0 (build 76f0e08) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('node-style', function (Y, NAME) { (function(Y) { /** * Extended Node interface for managing node styles. * @module node * @submodule node-style */ Y.mix(Y.Node.prototype, { /** * Sets a style property of the node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyle * @param {String} attr The style attribute to set. * @param {String|Number} val The value. * @chainable */ setStyle: function(attr, val) { Y.DOM.setStyle(this._node, attr, val); return this; }, /** * Sets multiple style properties on the node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyles * @param {Object} hash An object literal of property:value pairs. * @chainable */ setStyles: function(hash) { Y.DOM.setStyles(this._node, hash); return this; }, /** * Returns the style's current value. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getStyle * @for Node * @param {String} attr The style attribute to retrieve. * @return {String} The current value of the style property for the element. */ getStyle: function(attr) { return Y.DOM.getStyle(this._node, attr); }, /** * Returns the computed value for the given style property. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getComputedStyle * @param {String} attr The style attribute to retrieve. * @return {String} The computed value of the style property for the element. */ getComputedStyle: function(attr) { return Y.DOM.getComputedStyle(this._node, attr); } }); /** * Returns an array of values for each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getStyle * @for NodeList * @see Node.getStyle * @param {String} attr The style attribute to retrieve. * @return {Array} The current values of the style property for the element. */ /** * Returns an array of the computed value for each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getComputedStyle * @see Node.getComputedStyle * @param {String} attr The style attribute to retrieve. * @return {Array} The computed values for each node. */ /** * Sets a style property on each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyle * @see Node.setStyle * @param {String} attr The style attribute to set. * @param {String|Number} val The value. * @chainable */ /** * Sets multiple style properties on each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyles * @see Node.setStyles * @param {Object} hash An object literal of property:value pairs. * @chainable */ // These are broken out to handle undefined return (avoid false positive for // chainable) Y.NodeList.importMethod(Y.Node.prototype, ['getStyle', 'getComputedStyle', 'setStyle', 'setStyles']); })(Y); /** * @module node * @submodule node-base */ var Y_Node = Y.Node; Y.mix(Y_Node.prototype, { /** * Makes the node visible. * If the "transition" module is loaded, show optionally * animates the showing of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method show * @for Node * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ show: function(callback) { callback = arguments[arguments.length - 1]; this.toggleView(true, callback); return this; }, /** * The implementation for showing nodes. * Default is to remove the hidden attribute and reset the CSS style.display property. * @method _show * @protected * @chainable */ _show: function() { this.removeAttribute('hidden'); // For back-compat we need to leave this in for browsers that // do not visually hide a node via the hidden attribute // and for users that check visibility based on style display. this.setStyle('display', ''); }, /** Returns whether the node is hidden by YUI or not. The hidden status is determined by the 'hidden' attribute and the value of the 'display' CSS property. @method _isHidden @return {Boolean} `true` if the node is hidden. @private **/ _isHidden: function() { return this.hasAttribute('hidden') || Y.DOM.getComputedStyle(this._node, 'display') === 'none'; }, /** * Displays or hides the node. * If the "transition" module is loaded, toggleView optionally * animates the toggling of the node using given named effect. * @method toggleView * @for Node * @param {Boolean} [on] An optional boolean value to force the node to be shown or hidden * @param {Function} [callback] An optional function to run after the transition completes. * @chainable */ toggleView: function(on, callback) { this._toggleView.apply(this, arguments); return this; }, _toggleView: function(on, callback) { callback = arguments[arguments.length - 1]; // base on current state if not forcing if (typeof on != 'boolean') { on = (this._isHidden()) ? 1 : 0; } if (on) { this._show(); } else { this._hide(); } if (typeof callback == 'function') { callback.call(this); } return this; }, /** * Hides the node. * If the "transition" module is loaded, hide optionally * animates the hiding of the node using either the default * transition effect ('fadeOut'), or the given named effect. * @method hide * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ hide: function(callback) { callback = arguments[arguments.length - 1]; this.toggleView(false, callback); return this; }, /** * The implementation for hiding nodes. * Default is to set the hidden attribute to true and set the CSS style.display to 'none'. * @method _hide * @protected * @chainable */ _hide: function() { this.setAttribute('hidden', 'hidden'); // For back-compat we need to leave this in for browsers that // do not visually hide a node via the hidden attribute // and for users that check visibility based on style display. this.setStyle('display', 'none'); } }); Y.NodeList.importMethod(Y.Node.prototype, [ /** * Makes each node visible. * If the "transition" module is loaded, show optionally * animates the showing of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method show * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @for NodeList * @chainable */ 'show', /** * Hides each node. * If the "transition" module is loaded, hide optionally * animates the hiding of the node using either the default * transition effect ('fadeOut'), or the given named effect. * @method hide * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ 'hide', /** * Displays or hides each node. * If the "transition" module is loaded, toggleView optionally * animates the toggling of the nodes using given named effect. * @method toggleView * @param {Boolean} [on] An optional boolean value to force the nodes to be shown or hidden * @param {Function} [callback] An optional function to run after the transition completes. * @chainable */ 'toggleView' ]); }, '3.16.0', {"requires": ["dom-style", "node-base"]});
/* YUI 3.17.1 (build 0eb5a52) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('editor-para', function (Y, NAME) { /** * Plugin for Editor to paragraph auto wrapping and correction. * @class Plugin.EditorPara * @extends Plugin.EditorParaBase * @constructor * @module editor * @submodule editor-para */ var EditorPara = function() { EditorPara.superclass.constructor.apply(this, arguments); }, HOST = 'host', NODE_CHANGE = 'nodeChange', PARENT_NODE = 'parentNode', FIRST_P = '> p', P = 'p', BR = '<br>', FC = 'firstChild', LI = 'li'; Y.extend(EditorPara, Y.Plugin.EditorParaBase, { /** * Resolves the ROOT editor element. * @method _getRoot * @private */ _getRoot: function() { return this.get(HOST).getInstance().EditorSelection.ROOT; }, /** * nodeChange handler to handle fixing an empty document. * @private * @method _onNodeChange */ _onNodeChange: function(e) { var host = this.get(HOST), inst = host.getInstance(), html, txt, par , d, sel, btag = inst.EditorSelection.DEFAULT_BLOCK_TAG, inHTML, txt2, childs, aNode, node2, top, n, sib, para2, prev, ps, br, item, p, imgs, t, LAST_CHILD = ':last-child', para, b, dir, lc, lc2, found = false, root = this._getRoot(), start; switch (e.changedType) { case 'enter-up': para = ((this._lastPara) ? this._lastPara : e.changedNode); b = para.one('br.yui-cursor'); if (this._lastPara) { delete this._lastPara; } if (b) { if (b.previous() || b.next()) { if (b.ancestor(P)) { b.remove(); } } } if (!para.test(btag)) { para2 = para.ancestor(btag); if (para2) { para = para2; para2 = null; } } if (para.test(btag)) { prev = para.previous(); if (prev) { lc = prev.one(LAST_CHILD); while (!found) { if (lc) { lc2 = lc.one(LAST_CHILD); if (lc2) { lc = lc2; } else { found = true; } } else { found = true; } } if (lc) { host.copyStyles(lc, para); } } } break; case 'enter': if (Y.UA.webkit) { //Webkit doesn't support shift+enter as a BR, this fixes that. if (e.changedEvent.shiftKey) { host.execCommand('insertbr'); e.changedEvent.preventDefault(); } } if (e.changedNode.test('li') && !Y.UA.ie) { html = inst.EditorSelection.getText(e.changedNode); if (html === '') { par = e.changedNode.ancestor('ol,ul'); dir = par.getAttribute('dir'); if (dir !== '') { dir = ' dir = "' + dir + '"'; } par = e.changedNode.ancestor(inst.EditorSelection.BLOCKS); d = inst.Node.create('<p' + dir + '>' + inst.EditorSelection.CURSOR + '</p>'); par.insert(d, 'after'); e.changedNode.remove(); e.changedEvent.halt(); sel = new inst.EditorSelection(); sel.selectNode(d, true, false); } } //TODO Move this to a GECKO MODULE - Can't for the moment, requires no change to metadata (YMAIL) if (Y.UA.gecko && host.get('defaultblock') !== 'p') { par = e.changedNode; if (!par.test(LI) && !par.ancestor(LI)) { if (!par.test(btag)) { par = par.ancestor(btag); } d = inst.Node.create('<' + btag + '></' + btag + '>'); par.insert(d, 'after'); sel = new inst.EditorSelection(); if (sel.anchorOffset) { inHTML = sel.anchorNode.get('textContent'); txt = inst.one(inst.config.doc.createTextNode(inHTML.substr(0, sel.anchorOffset))); txt2 = inst.one(inst.config.doc.createTextNode(inHTML.substr(sel.anchorOffset))); aNode = sel.anchorNode; aNode.setContent(''); //I node2 = aNode.cloneNode(); //I node2.append(txt2); //text top = false; sib = aNode; //I while (!top) { sib = sib.get(PARENT_NODE); //B if (sib && !sib.test(btag)) { n = sib.cloneNode(); n.set('innerHTML', ''); n.append(node2); //Get children.. childs = sib.get('childNodes'); start = false; /*jshint loopfunc: true */ childs.each(function(c) { if (start) { n.append(c); } if (c === aNode) { start = true; } }); aNode = sib; //Top sibling node2 = n; } else { top = true; } } txt2 = node2; sel.anchorNode.append(txt); if (txt2) { d.append(txt2); } } if (d.get(FC)) { d = d.get(FC); } d.prepend(inst.EditorSelection.CURSOR); sel.focusCursor(true, true); html = inst.EditorSelection.getText(d); if (html !== '') { inst.EditorSelection.cleanCursor(); } e.changedEvent.preventDefault(); } } break; case 'keyup': if (Y.UA.gecko) { if (root && root.getHTML().length < 20) { if (!root.one(FIRST_P)) { this._fixFirstPara(); } } } break; case 'backspace-up': case 'backspace-down': case 'delete-up': if (!Y.UA.ie) { ps = root.all(FIRST_P); item = root; if (ps.item(0)) { item = ps.item(0); } br = item.one('br'); if (br) { br.removeAttribute('id'); br.removeAttribute('class'); } txt = inst.EditorSelection.getText(item); txt = txt.replace(/ /g, '').replace(/\n/g, ''); imgs = item.all('img'); if (txt.length === 0 && !imgs.size()) { //God this is horrible.. if (!item.test(P)) { this._fixFirstPara(); } p = null; if (e.changedNode && e.changedNode.test(P)) { p = e.changedNode; } if (!p && host._lastPara && host._lastPara.inDoc()) { p = host._lastPara; } if (p && !p.test(P)) { p = p.ancestor(P); } if (p) { if (!p.previous() && p.get(PARENT_NODE) && p.get(PARENT_NODE).compareTo(root)) { e.changedEvent.frameEvent.halt(); e.preventDefault(); } } } if (Y.UA.webkit) { if (e.changedNode) { //All backspace calls in Webkit need a preventDefault to //stop history navigation #2531299 e.preventDefault(); item = e.changedNode; if (item.test('li') && (!item.previous() && !item.next())) { html = item.get('innerHTML').replace(BR, ''); if (html === '') { if (item.get(PARENT_NODE)) { item.get(PARENT_NODE).replace(inst.Node.create(BR)); e.changedEvent.frameEvent.halt(); inst.EditorSelection.filterBlocks(); } } } } } } if (Y.UA.gecko) { /* * This forced FF to redraw the content on backspace. * On some occasions FF will leave a cursor residue after content has been deleted. * Dropping in the empty textnode and then removing it causes FF to redraw and * remove the "ghost cursors" */ // d = e.changedNode; // t = inst.config.doc.createTextNode(' '); // d.appendChild(t); // d.removeChild(t); this._fixGeckoOnBackspace(inst); } break; } if (Y.UA.gecko) { if (e.changedNode && !e.changedNode.test(btag)) { p = e.changedNode.ancestor(btag); if (p) { this._lastPara = p; } } } }, //If we just backspaced into a P on FF, we have to put the cursor //before the BR that FF (usually) had injected when we used <ENTER> to //leave the P. _fixGeckoOnBackspace: function (inst) { var sel = new inst.EditorSelection(), node, childNodes; //not a cursor, not in a paragraph, or anchored at paragraph start. if (!sel.isCollapsed || sel.anchorNode.get('nodeName') !== 'P' || sel.anchorOffset === 0) { return; } //cursor not on the injected final BR childNodes = sel.anchorNode.get('childNodes'); node = sel.anchorNode.get('lastChild'); if (sel.anchorOffset !== childNodes.size() || node.get('nodeName') !== 'BR') { return; } //empty P (only contains BR) if (sel.anchorOffset === 1) { sel.selectNode(sel.anchorNode, true); return; } //We only expect injected BR behavior when last Node is text node = node.get('previousSibling'); if (node.get('nodeType') !== Node.TEXT_NODE) { return; } offset = node.get('length'); // the cursor's position is strictly // at the offset when this bug occurs if (sel.getEditorOffset() === offset) { sel.selectNode(node, true, offset); } }, initializer: function() { var host = this.get(HOST); if (host.editorBR) { Y.error('Can not plug EditorPara and EditorBR at the same time.'); return; } host.on(NODE_CHANGE, Y.bind(this._onNodeChange, this)); } }, { /** * editorPara * @static * @property NAME */ NAME: 'editorPara', /** * editorPara * @static * @property NS */ NS: 'editorPara', ATTRS: { host: { value: false } } }); Y.namespace('Plugin'); Y.Plugin.EditorPara = EditorPara; }, '3.17.1', {"requires": ["editor-para-base"]});
'use strict'; const http = require('http') const createHandler = require('github-webhook-handler') const handler = createHandler({ path: '/webhook', secret: 'myhashsecret' }) const port = process.env.PORT || 7777 const r = require('rethinkdb'); let connection = null; r.connect({ db: 'popcubex' }, function(err, conn) { console.log(`[${new Date()}] Started database`); connection = conn; }); http.createServer((req, res) => { handler(req, res, (err) => { res.statusCode = 404 res.end('no such location') }) }).listen(port); console.log(`[${new Date()}] Started Webhook server`); handler.on('error', (err) => { console.error('Error:', err.message) }); handler.on('pull_request', (event) => { let pr = event.payload switch (pr.action) { case 'opened': writePR(pr); break; case 'closed': deletePR(pr) break; default: // do nothing break; } console.log(`pull request ${event.payload.repository.name} - #${pr.number} was ${event.payload.action}`); }); function writePR(pr){ return new Promise((resolve, reject) => { r.table('pull_requests').filter({number: pr.number}).run(connection, (err, cursor) => { if( err ) return reject(err); cursor.toArray().then( data => { if( data.length > 0 ){ r.table('pull_requests').update(data[0].id, pr).run(connection, (err, value) => { if( err ) reject(err); else resolve(value); }); }else { r.table('pull_requests').insert(pr).run(connection, (err, value) => { if( err ) reject(err); else resolve(value); }); } }); }); }); } function deletePR(pr){ return new Promise((resolve, reject) => { r.table('pull_requests').filter({number: pr.number}).delete().run(connection, (err, value) => { if( err ) reject(err); else resolve(value); }); }); } function afterInsert(err, value){ if( err ) throw err; else console.log(`[${new Date()}] New written value: ${value}`); } function afterDelete(err, value){ if( err ) throw err; else console.log(`[${new Date()}] Delete pull request value: ${value}`); }
'use strict'; var shell = require('shelljs'); var fs = require('fs'); var _ = require('lodash'); function Fetcher(exclusions) { this._exclusions = exclusions; } Fetcher.prototype.get = function(onSuccess) { var self = this; if (fs.existsSync('./bower.json')) { var child = shell.exec('bower list --json', { async: true, silent: true }); var shellData = ''; child.stdout.on('data', function(data) { shellData += data; }); child.stdout.on('end', function() { var jsonOutdated = JSON.parse(shellData); var parsedOutdated = {}; _.forEach(jsonOutdated.dependencies, function(dependency, packageName) { if (dependency.update !== undefined && !_.includes(self._exclusions, packageName)) { parsedOutdated[packageName] = { current: dependency.pkgMeta.version, latest: dependency.update.latest }; } }); onSuccess(parsedOutdated); }); } else { onSuccess(null); } }; module.exports = Fetcher;
var template = require('../templates/poll.hbs'), modal = require('./modal.js'), $ = require('jquery'), Promise = require('bluebird'), _ = require('underscore'); var PollView = { init: function(cfg) { // configuration parameters this.config = cfg; this.initEvents(); }, initEvents: function() { var self = this; $(document).ready(function() { // Fetch state for this client/ip and show a poll (if any unseen) self.getState().then(function(results) { self.showPoll(); }); }); }, getState: function() { // Fetch our initial state from backend service return $.getJSON(this.config.url + '/track'); }, showPoll: function() { var self = this; $.getJSON(this.config.url + '/show') .then(function(response) { if (response.success) { var html = template(response.data), pollModal = modal({ contents: html }); self.$modal = pollModal.show(); // Submit vote self.$modal.find('#vote-btn').click(function(ev) { var vote = parseInt(self.$modal.find('input:checked').val(), 10); console.log("vote:", vote); $.ajax({ method: 'POST', dataType: "json", url: self.config.url + '/votes/' + vote }) .then(function(result) { if (result.success) { console.log('>', result.message); } }) .fail(function(response) { console.log("> error: ", response.responseJSON.message || response.responseText); }) .always(function() { pollModal.hide(); }); }); } }); } }; module.exports = PollView;
'use strict' import Fact from './fact' import { UndefinedFactError } from './errors' import debug from './debug' import { JSONPath } from 'jsonpath-plus' import isObjectLike from 'lodash.isobjectlike' function defaultPathResolver (value, path) { return JSONPath({ path, json: value, wrap: false }) } /** * Fact results lookup * Triggers fact computations and saves the results * A new almanac is used for every engine run() */ export default class Almanac { constructor (factMap, runtimeFacts = {}, options = {}) { this.factMap = new Map(factMap) this.factResultsCache = new Map() // { cacheKey: Promise<factValu> } this.allowUndefinedFacts = Boolean(options.allowUndefinedFacts) this.pathResolver = options.pathResolver || defaultPathResolver this.events = { success: [], failure: [] } this.ruleResults = [] for (const factId in runtimeFacts) { let fact if (runtimeFacts[factId] instanceof Fact) { fact = runtimeFacts[factId] } else { fact = new Fact(factId, runtimeFacts[factId]) } this._addConstantFact(fact) debug(`almanac::constructor initialized runtime fact:${fact.id} with ${fact.value}<${typeof fact.value}>`) } } /** * Adds a success event * @param {Object} event */ addEvent (event, outcome) { if (!outcome) throw new Error('outcome required: "success" | "failure"]') this.events[outcome].push(event) } /** * retrieve successful events */ getEvents (outcome = '') { if (outcome) return this.events[outcome] return this.events.success.concat(this.events.failure) } /** * Adds a rule result * @param {Object} event */ addResult (ruleResult) { this.ruleResults.push(ruleResult) } /** * retrieve successful events */ getResults () { return this.ruleResults } /** * Retrieve fact by id, raising an exception if it DNE * @param {String} factId * @return {Fact} */ _getFact (factId) { return this.factMap.get(factId) } /** * Registers fact with the almanac * @param {[type]} fact [description] */ _addConstantFact (fact) { this.factMap.set(fact.id, fact) this._setFactValue(fact, {}, fact.value) } /** * Sets the computed value of a fact * @param {Fact} fact * @param {Object} params - values for differentiating this fact value from others, used for cache key * @param {Mixed} value - computed value */ _setFactValue (fact, params, value) { const cacheKey = fact.getCacheKey(params) const factValue = Promise.resolve(value) if (cacheKey) { this.factResultsCache.set(cacheKey, factValue) } return factValue } /** * Adds a constant fact during runtime. Can be used mid-run() to add additional information * @param {String} fact - fact identifier * @param {Mixed} value - constant value of the fact */ addRuntimeFact (factId, value) { debug(`almanac::addRuntimeFact id:${factId}`) const fact = new Fact(factId, value) return this._addConstantFact(fact) } /** * Returns the value of a fact, based on the given parameters. Utilizes the 'almanac' maintained * by the engine, which cache's fact computations based on parameters provided * @param {string} factId - fact identifier * @param {Object} params - parameters to feed into the fact. By default, these will also be used to compute the cache key * @param {String} path - object * @return {Promise} a promise which will resolve with the fact computation. */ factValue (factId, params = {}, path = '') { let factValuePromise const fact = this._getFact(factId) if (fact === undefined) { if (this.allowUndefinedFacts) { return Promise.resolve(undefined) } else { return Promise.reject(new UndefinedFactError(`Undefined fact: ${factId}`)) } } if (fact.isConstant()) { factValuePromise = Promise.resolve(fact.calculate(params, this)) } else { const cacheKey = fact.getCacheKey(params) const cacheVal = cacheKey && this.factResultsCache.get(cacheKey) if (cacheVal) { factValuePromise = Promise.resolve(cacheVal) debug(`almanac::factValue cache hit for fact:${factId}`) } else { debug(`almanac::factValue cache miss for fact:${factId}; calculating`) factValuePromise = this._setFactValue(fact, params, fact.calculate(params, this)) } } if (path) { debug(`condition::evaluate extracting object property ${path}`) return factValuePromise .then(factValue => { if (isObjectLike(factValue)) { const pathValue = this.pathResolver(factValue, path) debug(`condition::evaluate extracting object property ${path}, received: ${JSON.stringify(pathValue)}`) return pathValue } else { debug(`condition::evaluate could not compute object path(${path}) of non-object: ${factValue} <${typeof factValue}>; continuing with ${factValue}`) return factValue } }) } return factValuePromise } }
// Generated by CoffeeScript 1.9.3 (function() { var assert, curry, deepEqual, describe, ref, ref1; ref = require("./core"), curry = ref.curry, deepEqual = ref.deepEqual; ref1 = require("./helpers"), describe = ref1.describe, assert = ref1.assert; describe("Type functions", function(context) { var GeneratorFunction, instanceOf, isArray, isBoolean, isDate, isDefined, isFinite, isFloat, isFunction, isGenerator, isInteger, isNaN, isNumber, isObject, isRegexp, isString, isType, type; type = function(x) { return typeof x; }; context.test("type"); isType = curry(function(t, x) { return type(x) === t; }); context.test("isType"); instanceOf = curry(function(t, x) { return x instanceof t; }); context.test("instanceOf"); isNumber = isType(Number); context.test("isNumber", function() { assert(isNumber(7)); assert(!isNumber("7")); return assert(!isNumber(false)); }); isNaN = function(n) { return Number.isNaN(n); }; isFinite = function(n) { return Number.isFinite(n); }; isInteger = function(n) { return Number.isInteger(n); }; context.test("isInteger", function() { assert(isInteger(5)); assert(!isInteger(3.5)); assert(!isInteger("5")); return assert(!isInteger(NaN)); }); isFloat = function(n) { return n === +n && n !== (n | 0); }; context.test("isFloat", function() { assert(isFloat(3.5)); assert(!isFloat(5)); assert(!isFloat("3.5")); return assert(!isFloat(NaN)); }); isBoolean = isType(Boolean); context.test("isBoolean", function() { assert(isBoolean(true)); return assert(!isBoolean(7)); }); isDate = isType(Date); context.test("isDate", function() { assert(isDate(new Date)); return assert(!isDate(7)); }); isRegexp = isType(RegExp); context.test("isRegexp", function() { assert(isRegexp(/\s/)); return assert(!isRegexp(7)); }); isString = isType(String); context.test("isString", function() { assert(isString("x")); return assert(!isString(7)); }); isFunction = isType(Function); context.test("isFunction", function() { assert(isFunction(function() {})); return assert(!isFunction(7)); }); GeneratorFunction = (function*() { return (yield null); }).constructor; isGenerator = isType(GeneratorFunction); context.test("isGenerator", function() { var f; f = function*() { return (yield true); }; return assert(isGenerator(f)); }); isObject = isType(Object); context.test("isObject", function() { assert(isObject({})); return assert(!isObject(7)); }); isArray = isType(Array); context.test("isArray", function() { assert(isArray([])); return assert(!isArray(7)); }); isDefined = function(x) { return x != null; }; context.test("isDefined", function() { assert(isDefined({})); return assert(!isDefined(void 0)); }); return module.exports = { deepEqual: deepEqual, type: type, isType: isType, instanceOf: instanceOf, isBoolean: isBoolean, isNumber: isNumber, isNaN: isNaN, isFinite: isFinite, isInteger: isInteger, isFloat: isFloat, isString: isString, isFunction: isFunction, isGenerator: isGenerator, isObject: isObject, isArray: isArray, isDefined: isDefined }; }); }).call(this);
var URI = require('urijs'); var runner = require('../runner'); require('../keychain'); var _ = require('lodash'); runner(function(param, directory){ suite(`account login page - ${directory}`, function() { var login_url, providers = []; suiteSetup(function *(){ login_url = yield browser .url(param.init_url) .waitForVisible(param.btn_signin, 30e3) .click(param.btn_signin) .waitForVisible(param.btn_submit, 30e3) .getUrl(); return assert.ok(login_url); }); suiteTeardown(function *(){ if (param.teardown_visible){ var href = yield browser .url(param.init_url) .waitForVisible(param.teardown_visible) .moveToObject(param.teardown_visible) .click(param.teardown_click) .waitForVisible(param.btn_signin) .getAttribute(param.btn_signin, 'href'); return assert.ok(href); } else { this.skip(); } }); setup(function *() { return assert.notInclude(yield browser .url(login_url) .waitForEnabled(param.btn_submit, 30e3) .getAttribute(param.btn_submit, 'class'), 'disabled', 'check form submit button is available'); }); test('check the links to register and reset page', function *() { var continue_uri = URI(login_url).search(true).continue_uri; providers_str = URI(continue_uri).search(true).providers; if (providers_str) { providers = providers_str.split(','); } var selector = 'a#link-to-register, a#link-to-reset'; var $els = yield browser.getAttribute(selector, 'href'); assert.sameMembers($els.map(function (href) { var link = URI(href); assert.equal(link.search(true).continue_uri, continue_uri, '"continue_uri" should inherit from current page'); return link.relativeTo(login_url).search('').toString(); }), param.login.relative_to_links, 'check links are correct'); }); test('page title', function *() { return assert.equal( yield browser .getTitle(), 'EFID Sign in' ); }); test('page language', function *() { return assert.equal(yield browser.getAttribute('html', 'lang'), 'en'); }); test('email login failed', function *() { return assert.equal(yield browser .fill_login_cred_invalid() .submitForm('form') .waitForText('#error_box') .getText('#error_box'), 'Invalid login details'); }); test('email login succeed', function *() { return assert.equal(yield browser .fill_login_cred_valid() .submitForm('form') .waitForVisible(param.login_success) .getText(param.login_success), param.login_text); }); test('facebook login succeed', function *() { // facebook login can't be autotest because of its' robot // login check this.skip(); if(_.includes(providers, 'facebook')) { return assert.equal(yield browser .waitForVisible(param['facebook'].button) .click(param['facebook'].button) .waitForVisible(param['facebook'].input) .fill_facebook_login_valid() .submitForm('form') .waitForVisible(param.login_success) .getText(param.login_success), param.login_text); } else { this.skip(); } }); test('linkedin login succeed', function *() { if(_.includes(providers,'linkedin')) { return assert.equal(yield browser .waitForVisible(param['linkedin'].button) .click(param['linkedin'].button) .waitForVisible(param['linkedin'].input) .fill_linkedin_login_valid() .submitForm('form') .waitForVisible(param.login_success) .getText(param.login_success), param.login_text); } else { this.skip(); } }); test('google login succeed', function *() { if(_.includes(providers,'google')) { return assert.equal(yield browser .waitForVisible(param['google'].button) .click(param['google'].button) .waitForVisible(param['google'].input) .fill_google_login_valid() .submitForm('form') .waitForVisible(param.login_success) .getText(param.login_success), param.login_text); } else { this.skip(); } }); }); });
// ==UserScript== // @id iitc-plugin-done-links@jonatkins // @name IITC plugin: done links // @category 圖層 // @version 0.0.1.@@DATETIMEVERSION@@ // @namespace https://github.com/jonatkins/ingress-intel-total-conversion // @updateURL @@UPDATEURL@@ // @downloadURL @@DOWNLOADURL@@ // @description [@@BUILDNAME@@-@@BUILDDATE@@] A companion to the Cross Links plugin. Highlights any links that match existing draw-tools line/polygon edges // @include https://*.ingress.com/intel* // @include http://*.ingress.com/intel* // @match https://*.ingress.com/intel* // @match http://*.ingress.com/intel* // @include https://*.ingress.com/mission/* // @include http://*.ingress.com/mission/* // @match https://*.ingress.com/mission/* // @match http://*.ingress.com/mission/* // @grant none // ==/UserScript== @@PLUGINSTART@@ // PLUGIN START //////////////////////////////////////////////////////// window.plugin.doneLinks = function() {}; window.plugin.doneLinks.sameLink = function(a0, a1, b0, b1) { if (a0.equals(b0) && a1.equals(b1)) return true; if (a0.equals(b1) && a1.equals(b0)) return true; return false; } window.plugin.doneLinks.testPolyLine = function (polyline, link,closed) { var a = link.getLatLngs(); var b = polyline.getLatLngs(); for (var i=0;i<b.length-1;++i) { if (window.plugin.doneLinks.sameLink(a[0],a[1],b[i],b[i+1])) return true; } if (closed) { if (window.plugin.doneLinks.sameLink(a[0],a[1],b[b.length-1],b[0])) return true; } return false; } window.plugin.doneLinks.onLinkAdded = function (data) { if (window.plugin.doneLinks.disabled) return; plugin.doneLinks.testLink(data.link); } window.plugin.doneLinks.checkAllLinks = function() { if (window.plugin.doneLinks.disabled) return; console.debug("Done-Links: checking all links"); plugin.doneLinks.linkLayer.clearLayers(); plugin.doneLinks.linkLayerGuids = {}; $.each(window.links, function(guid, link) { plugin.doneLinks.testLink(link); }); } window.plugin.doneLinks.testLink = function (link) { if (plugin.doneLinks.linkLayerGuids[link.options.guid]) return; for (var i in plugin.drawTools.drawnItems._layers) { // leaflet don't support breaking out of the loop var layer = plugin.drawTools.drawnItems._layers[i]; if (layer instanceof L.GeodesicPolygon) { if (plugin.doneLinks.testPolyLine(layer, link,true)) { plugin.doneLinks.showLink(link); break; } } else if (layer instanceof L.GeodesicPolyline) { if (plugin.doneLinks.testPolyLine(layer, link)) { plugin.doneLinks.showLink(link); break; } } }; } window.plugin.doneLinks.showLink = function(link) { var poly = L.geodesicPolyline(link.getLatLngs(), { color: COLORS[link.options.team], opacity: 0.8, weight: 6, clickable: false, dashArray: [6,12], guid: link.options.guid }); poly.addTo(plugin.doneLinks.linkLayer); plugin.doneLinks.linkLayerGuids[link.options.guid]=poly; } window.plugin.doneLinks.onMapDataRefreshEnd = function () { if (window.plugin.doneLinks.disabled) return; window.plugin.doneLinks.linkLayer.bringToFront(); window.plugin.doneLinks.testForDeletedLinks(); } window.plugin.doneLinks.testAllLinksAgainstLayer = function (layer) { if (window.plugin.doneLinks.disabled) return; $.each(window.links, function(guid, link) { if (!plugin.doneLinks.linkLayerGuids[link.options.guid]) { if (layer instanceof L.GeodesicPolygon) { if (plugin.doneLinks.testPolyLine(layer, link,true)) { plugin.doneLinks.showLink(link); } } else if (layer instanceof L.GeodesicPolyline) { if (plugin.doneLinks.testPolyLine(layer, link)) { plugin.doneLinks.showLink(link); } } } }); } window.plugin.doneLinks.testForDeletedLinks = function () { window.plugin.doneLinks.linkLayer.eachLayer( function(layer) { var guid = layer.options.guid; if (!window.links[guid]) { console.log("link removed"); plugin.doneLinks.linkLayer.removeLayer(layer); delete plugin.doneLinks.linkLayerGuids[guid]; } }); } window.plugin.doneLinks.createLayer = function() { window.plugin.doneLinks.linkLayer = new L.FeatureGroup(); window.plugin.doneLinks.linkLayerGuids={}; window.addLayerGroup('Done Links', window.plugin.doneLinks.linkLayer, true); map.on('layeradd', function(obj) { if(obj.layer === window.plugin.doneLinks.linkLayer) { delete window.plugin.doneLinks.disabled; window.plugin.doneLinks.checkAllLinks(); } }); map.on('layerremove', function(obj) { if(obj.layer === window.plugin.doneLinks.linkLayer) { window.plugin.doneLinks.disabled = true; window.plugin.doneLinks.linkLayer.clearLayers(); plugin.doneLinks.linkLayerGuids = {}; } }); // ensure 'disabled' flag is initialised if (!map.hasLayer(window.plugin.doneLinks.linkLayer)) { window.plugin.doneLinks.disabled = true; } } var setup = function() { if (window.plugin.drawTools === undefined) { alert("'Done-Links' requires 'draw-tools'"); return; } // this plugin also needs to create the draw-tools hook, in case it is initialised before draw-tools window.pluginCreateHook('pluginDrawTools'); window.plugin.doneLinks.createLayer(); // events window.addHook('pluginDrawTools',function(e) { if (e.event == 'layerCreated') { // we can just test the new layer in this case window.plugin.doneLinks.testAllLinksAgainstLayer(e.layer); } else { // all other event types - assume anything could have been modified and re-check all links window.plugin.doneLinks.checkAllLinks(); } }); window.addHook('linkAdded', window.plugin.doneLinks.onLinkAdded); window.addHook('mapDataRefreshEnd', window.plugin.doneLinks.onMapDataRefreshEnd); } // PLUGIN END ////////////////////////////////////////////////////////// @@PLUGINEND@@
import mod1570 from './mod1570'; var value=mod1570+1; export default value;
import { event as d3_event, select as d3_select } from 'd3-selection'; import { geoVecLength } from '../geo'; import { prefs } from '../core/preferences'; import { modeBrowse } from '../modes/browse'; import { modeSelect } from '../modes/select'; import { modeSelectData } from '../modes/select_data'; import { modeSelectNote } from '../modes/select_note'; import { modeSelectError } from '../modes/select_error'; import { osmEntity, osmNote, QAItem } from '../osm'; import { utilArrayIdentical } from '../util/array'; import { utilFastMouse } from '../util/util'; export function behaviorSelect(context) { // legacy option to show menu on every click var isShowAlways = +prefs('edit-menu-show-always') === 1; var tolerance = 4; var _lastMouse = null; var _showMenu = false; var _p1 = null; // use pointer events on supported platforms; fallback to mouse events var _pointerPrefix = 'PointerEvent' in window ? 'pointer' : 'mouse'; function point() { return utilFastMouse(context.container().node())(d3_event); } function keydown() { var e = d3_event; if (e && e.shiftKey) { context.surface() .classed('behavior-multiselect', true); } if (e && e.keyCode === 93) { // context menu e.preventDefault(); e.stopPropagation(); } } function keyup() { var e = d3_event; if (!e || !e.shiftKey) { context.surface() .classed('behavior-multiselect', false); } if (e && e.keyCode === 93) { // context menu e.preventDefault(); e.stopPropagation(); contextmenu(); } } function pointerdown() { if (!_p1) { _p1 = point(); } d3_select(window) .on(_pointerPrefix + 'up.select', pointerup, true); _showMenu = isShowAlways; } function pointermove() { if (d3_event) { _lastMouse = d3_event; } } function pointerup() { click(); } function contextmenu() { var e = d3_event; e.preventDefault(); e.stopPropagation(); if (!+e.clientX && !+e.clientY) { if (_lastMouse) { e.sourceEvent = _lastMouse; } else { return; } } if (!_p1) { _p1 = point(); } _showMenu = true; click(); } function click() { d3_select(window) .on(_pointerPrefix + 'up.select', null, true); if (!_p1) return; var p2 = point(); var dist = geoVecLength(_p1, p2); _p1 = null; if (dist > tolerance) return; var datum = d3_event.target.__data__ || (_lastMouse && _lastMouse.target.__data__); var isMultiselect = d3_event.shiftKey || context.surface().select('.lasso').node(); processClick(datum, isMultiselect); } function processClick(datum, isMultiselect) { var mode = context.mode(); var entity = datum && datum.properties && datum.properties.entity; if (entity) datum = entity; if (datum && datum.type === 'midpoint') { datum = datum.parents[0]; } var newMode; if (datum instanceof osmEntity) { // clicked an entity.. var selectedIDs = context.selectedIDs(); context.selectedNoteID(null); context.selectedErrorID(null); if (!isMultiselect) { if (selectedIDs.length > 1 && (_showMenu && !isShowAlways)) { // multiple things already selected, just show the menu... mode.reselect().showMenu(); } else { if (mode.id !== 'select' || !utilArrayIdentical(mode.selectedIDs(), [datum.id])) { newMode = modeSelect(context, [datum.id]); // select a single thing if it's not already selected context.enter(newMode); if (_showMenu) newMode.showMenu(); } else { mode.reselect(); if (_showMenu) mode.showMenu(); } } } else { if (selectedIDs.indexOf(datum.id) !== -1) { // clicked entity is already in the selectedIDs list.. if (_showMenu && !isShowAlways) { // don't deselect clicked entity, just show the menu. mode.reselect().showMenu(); } else { // deselect clicked entity, then reenter select mode or return to browse mode.. selectedIDs = selectedIDs.filter(function(id) { return id !== datum.id; }); context.enter(selectedIDs.length ? modeSelect(context, selectedIDs) : modeBrowse(context)); } } else { // clicked entity is not in the selected list, add it.. selectedIDs = selectedIDs.concat([datum.id]); newMode = modeSelect(context, selectedIDs); context.enter(newMode); if (_showMenu) newMode.showMenu(); } } } else if (datum && datum.__featurehash__ && !isMultiselect) { // clicked Data.. context .selectedNoteID(null) .enter(modeSelectData(context, datum)); } else if (datum instanceof osmNote && !isMultiselect) { // clicked a Note.. context .selectedNoteID(datum.id) .enter(modeSelectNote(context, datum.id)); } else if (datum instanceof QAItem & !isMultiselect) { // clicked an external QA issue context .selectedErrorID(datum.id) .enter(modeSelectError(context, datum.id, datum.service)); } else { // clicked nothing.. context.selectedNoteID(null); context.selectedErrorID(null); if (!isMultiselect && mode.id !== 'browse') { context.enter(modeBrowse(context)); } } // reset for next time.. _showMenu = false; } function behavior(selection) { _lastMouse = null; _showMenu = false; _p1 = null; d3_select(window) .on('keydown.select', keydown) .on('keyup.select', keyup) .on('contextmenu.select-window', function() { // Edge and IE really like to show the contextmenu on the // menubar when user presses a keyboard menu button // even after we've already preventdefaulted the key event. var e = d3_event; if (+e.clientX === 0 && +e.clientY === 0) { d3_event.preventDefault(); d3_event.stopPropagation(); } }); selection .on(_pointerPrefix + 'down.select', pointerdown) .on(_pointerPrefix + 'move.select', pointermove) .on('contextmenu.select', contextmenu); if (d3_event && d3_event.shiftKey) { context.surface() .classed('behavior-multiselect', true); } } behavior.off = function(selection) { d3_select(window) .on('keydown.select', null) .on('keyup.select', null) .on('contextmenu.select-window', null) .on(_pointerPrefix + 'up.select', null, true); selection .on(_pointerPrefix + 'down.select', null) .on(_pointerPrefix + 'move.select', null) .on('contextmenu.select', null); context.surface() .classed('behavior-multiselect', false); }; return behavior; }
'use strict'; var BaseClient = require('./BaseClient'); var util = require('util'); // # Client([options]) // Generic HTTP client with helper methods to make requests. Extends // [`BaseClient`](./BaseClient.js.html). function Client(options) { BaseClient.call(this, options); } util.inherits(Client, BaseClient); module.exports = Client; // ## Client#request(method, [options]) // Make a request. Set `method` to be any HTTP method, as understood by the // configured transport. Returns a [`Response`](./Response.js.html) promise. // For documentation on `options` see the [`Request`](./Request.js.html) class. Client.prototype.request = function(method, options) { return this._issueRequest(method, options); }; // ## Client#head([options]) // Make a `HEAD` request. Returns a `Response` promise. Client.prototype.head = function(options) { return this._issueRequest('HEAD', options); }; // ## Client#get([options]) // Make a `GET` request. Returns a `Response` promise. Client.prototype.get = function(options) { return this._issueRequest('GET', options); }; // ## Client#delete([options]) // Make a `DELETE` request. Returns a `Response` promise. Client.prototype.delete = function(options) { return this._issueRequest('DELETE', options); }; // ## Client#put([options]) // Make a `PUT` request. Returns a `Response` promise. Client.prototype.put = function(options) { return this._issueRequest('PUT', options); }; // ## Client#post([options]) // Make a `POST` request. Returns a `Response` promise. Client.prototype.post = function(options) { return this._issueRequest('POST', options); }; // ## Client#patch([options]) // Make a `PATCH` request. Returns a `Response` promise. Client.prototype.patch = function(options) { return this._issueRequest('PATCH', options); };
// constants.js // Constants used in Redux actions module.exports = { SET_CONNECTION_STATUS: 'SET_CONNECTION_STATUS', SET_GRAPHVIEW_DIMENSIONS: 'SET_GRAPHVIEW_DIMENSIONS', SET_BCI_ACTION: 'SET_BCI_ACTION', SET_OFFLINE_MODE: 'SET_OFFLINE_MODE', SET_MENU: 'SET_MENU', SET_MUSE_INFO: 'SET_MUSE_INFO', SET_AVAILABLE_MUSES: 'SET_AVAILABLE_MUSES', SET_NOTCH_FREQUENCY: 'SET_NOTCH_FREQUENCY', SET_NOISE: 'SET_NOISE', UPDATE_CLASSIFIER_DATA: 'UPDATE_CLASSIFIER_DATA', SET_NATIVE_EMITTER: 'SET_NATIVE_EMITTER', START_BCI_RUNNING: 'START_BCI_RUNNING', STOP_BCI_RUNNING: 'STOP_BCI_RUNNING', SET_BATTERY_VALUE: 'SET_BATTERY_VALUE' }
SystemJS.config({ paths: { "@ignavia/earl/": "src/" }, devConfig: { "map": { "babel-plugin-transform-export-extensions": "npm:babel-plugin-transform-export-extensions@6.8.0", "plugin-babel": "npm:systemjs-plugin-babel@0.0.8" }, "packages": { "npm:babel-plugin-transform-export-extensions@6.8.0": { "map": { "babel-plugin-syntax-export-extensions": "npm:babel-plugin-syntax-export-extensions@6.8.0", "babel-runtime": "npm:babel-runtime@6.9.2" } }, "npm:babel-runtime@6.9.2": { "map": { "core-js": "npm:core-js@2.4.0", "regenerator-runtime": "npm:regenerator-runtime@0.9.5" } }, "npm:babel-plugin-syntax-export-extensions@6.8.0": { "map": { "babel-runtime": "npm:babel-runtime@6.9.2" } } } }, transpiler: "plugin-babel", packages: { "@ignavia/earl": { "main": "index.js", "format": "esm", "meta": { "*js": { "babelOptions": { "plugins": [ "babel-plugin-transform-export-extensions" ] } } } } } }); SystemJS.config({ packageConfigPaths: [ "npm:@*/*.json", "npm:*.json", "github:*/*.json" ], map: { "@ignavia/ella": "npm:@ignavia/ella@1.2.0", "@ignavia/util": "npm:@ignavia/util@2.0.0", "assert": "github:jspm/nodelibs-assert@0.2.0-alpha", "buffer": "github:jspm/nodelibs-buffer@0.2.0-alpha", "core-js": "npm:core-js@1.2.6", "events": "github:jspm/nodelibs-events@0.2.0-alpha", "fs": "github:jspm/nodelibs-fs@0.2.0-alpha", "lodash": "npm:lodash@4.13.1", "net": "github:jspm/nodelibs-net@0.2.0-alpha", "os": "github:jspm/nodelibs-os@0.2.0-alpha", "path": "github:jspm/nodelibs-path@0.2.0-alpha", "process": "github:jspm/nodelibs-process@0.2.0-alpha", "stream": "github:jspm/nodelibs-stream@0.2.0-alpha", "tty": "github:jspm/nodelibs-tty@0.2.0-alpha", "util": "github:jspm/nodelibs-util@0.2.0-alpha", "vm": "github:jspm/nodelibs-vm@0.2.0-alpha" }, packages: { "github:jspm/nodelibs-buffer@0.2.0-alpha": { "map": { "buffer-browserify": "npm:buffer@4.7.0" } }, "github:jspm/nodelibs-os@0.2.0-alpha": { "map": { "os-browserify": "npm:os-browserify@0.2.1" } }, "github:jspm/nodelibs-stream@0.2.0-alpha": { "map": { "stream-browserify": "npm:stream-browserify@2.0.1" } }, "npm:stream-browserify@2.0.1": { "map": { "inherits": "npm:inherits@2.0.1", "readable-stream": "npm:readable-stream@2.1.4" } }, "npm:readable-stream@2.1.4": { "map": { "inherits": "npm:inherits@2.0.1", "buffer-shims": "npm:buffer-shims@1.0.0", "core-util-is": "npm:core-util-is@1.0.2", "process-nextick-args": "npm:process-nextick-args@1.0.7", "string_decoder": "npm:string_decoder@0.10.31", "util-deprecate": "npm:util-deprecate@1.0.2", "isarray": "npm:isarray@1.0.0" } }, "npm:buffer@4.7.0": { "map": { "ieee754": "npm:ieee754@1.1.6", "base64-js": "npm:base64-js@1.1.2", "isarray": "npm:isarray@1.0.0" } }, "npm:@ignavia/util@2.0.0": { "map": { "lodash": "npm:lodash@4.13.1" } } } });
var React = require('react'); var Iframe = require('../index'); var g = React.render( <Iframe url ='http://cnn.com' width={"100%"} height={"100%"}/> , document.body );
"use strict"; const debug = require("debug")("bot-express:messenger"); const fs = require("fs"); const clone = require("rfdc/default") /** * Messenger abstraction. *Context free * @class */ class Messenger { /** * @constructor * @param {Object} options * @param {String} messenger_type - line | facebook | google */ constructor(options, messenger_type){ this.type = messenger_type; this.Messenger_classes = {}; this.plugin = {}; // Load messenger libraries located under messenger directory. let messenger_scripts = fs.readdirSync(__dirname + "/messenger"); for (let messenger_script of messenger_scripts){ let messenger_type = messenger_script.replace(".js", ""); // Even if there is messenger implementation, we won't load it if corresponding messenger option is not configured. if (!options[messenger_type]){ continue; } debug("Loading " + messenger_script + "..."); this.Messenger_classes[messenger_type] = require("./messenger/" + messenger_script); this.plugin[messenger_type] = new this.Messenger_classes[messenger_type](options[messenger_type]); if (messenger_type === this.type){ this.service = this.plugin[messenger_type]; } } } validate_signature(req){ return this.service.validate_signature(req); } async refresh_token(){ await this.service.refresh_token(); } extract_events(body){ return this.Messenger_classes[this.type].extract_events(body); } extract_beacon_event_type(event){ return this.Messenger_classes[this.type].extract_beacon_event_type(event); } extract_param_value(event){ return this.Messenger_classes[this.type].extract_param_value(event); } extract_postback_payload(event){ return this.Messenger_classes[this.type].extract_postback_payload(event); } check_supported_event_type(event, flow){ return this.Messenger_classes[this.type].check_supported_event_type(event, flow); } /** * Extract message of the event. * @param {EventObject} event - Event to extract message. * @returns {MessageObject} - Extracted message. */ extract_message(event){ return this.Messenger_classes[this.type].extract_message(event); } /** * Extract message text of the event. * @param {EventObject} event - Event to extract message text. * @returns {String} - Extracted message text. */ extract_message_text(event){ return this.Messenger_classes[this.type].extract_message_text(event); } /** * Extract sender's user id. * @param {EventObject} event - Event to extract message text. * @returns {String} */ extract_sender_id(event){ return this.Messenger_classes[this.type].extract_sender_id(event); } /** * Extract session id. * @param {EventObject} event - Event to extract message text. * @returns {String} */ extract_session_id(event){ return this.Messenger_classes[this.type].extract_session_id(event); } /** * Extract channel id. * @param {Object} event - Event to extract channel id. * @returns {String} */ extract_channel_id(event){ return this.service.extract_channel_id(event); } /** * Extract reciever's user/room/group id. * @param {EventObject} event - Event to extract message text. * @returns {String} */ extract_to_id(event){ if (event.type == "bot-express:push"){ return event.to[`${event.to.type}Id`]; } return this.Messenger_classes[this.type].extract_to_id(event); } /** * Identify the event type. * @param {EventObject} event - Event to identify event type. * @returns {String} - Event type. In case of LINE, it can be "message", "follow", "unfollow", "join", "leave", "postback", "beacon". In case of Facebook, it can be "echo", "message", "delivery", "read", "postback", "optin", "referral", "account_linking". */ identify_event_type(event){ if (event.type && event.type.match(/^bot-express:/)){ return event.type; } return this.Messenger_classes[this.type].identify_event_type(event); } /** * Identify the message type. * @param {MessageObject} message - Message object to identify message type. * @returns {String} In case of LINE, it can be "text", "image", "audio", "video", "file", "location", "sticker", "imagemap", "buttons_template, "confirm_template" or "carousel_template". * In case of Facebook, it can be "text", "image", "audio", "video", "file", "button_template", "generic_template", "list_template", "open_graph_template", "receipt_template", "airline_boardingpass_template", "airline_checkin_template", "airline_itinerary_template", "airline_update_template". */ identify_message_type(message){ return this.Messenger_classes[this.type].identify_message_type(message); } get_secret(){ return this.service.get_secret() } /** * Pass event through specified webhook. * @method * @async * @param {String} webhook - URL to pass through event. * @param {String} secret - Secret key to create signature. * @param {Object} event - Event object to pass through. */ async pass_through(webhook, secret, event){ return this.service.pass_through(webhook, secret, event) } /** * Reply messages to sender to collect parameter * @param {Object} event - Event object. * @param {Array.<MessageObject>} messages - The array of message objects. * @returns {Array.<Promise>} */ async reply_to_collect(event, messages){ return this.service.reply_to_collect(event, messages); } /** * Reply messages to sender. * @param {Object} event - Event object. * @param {Array.<MessageObject>} messages - The array of message objects. * @returns {Promise.<Object>} */ async reply(event, messages){ return this.service.reply(event, messages); } /** * Send(Push) message to specified user. * @param {Object} event - Event object. * @param {String} recipient_id - Recipient user id. * @param {Array.<MessageObject>} messages - The array of message objects. * @returns {Array.<Promise>} */ async send(event, recipient_id, messages){ return this.service.send(event, recipient_id, messages); } /** * Push messages to multiple users. * @param {Array.<String>} recipient_ids - The array of recipent user id. * @param {Array.<MessageObject>} messages - The array of message objects. * @returns {Array.<Promise>} */ async multicast(event, recipient_ids, messages){ return this.service.multicast(event, recipient_ids, messages); } /** * Push messages to all users. * @param {Array.<MessageObject>} messages - The array of message objects. * @returns {Array.<Promise>} */ async broadcast(event, messages){ return this.service.broadcast(event, messages); } /** * Compile message format to the specified format. * @param {MessageObject} message - Message object to compile. * @param {String} format - Target format to compile. It can be "line" or "facebook". * @returns {Promise.<MessageObject>} - Compiled message object. */ async compile_message(message, format = this.type){ let source_format = this._identify_message_format(message); debug(`Identified message format is ${source_format}.`); let compiled_message; if (format != source_format){ debug(`Compiling message from ${source_format} to ${format}...`); // Identify message type. let message_type = this.Messenger_classes[source_format].identify_message_type(message); debug(`message type is ${message_type}`); // Compile message compiled_message = this.Messenger_classes[format].compile_message(source_format, message_type, message); debug(`Compiled message is following.`); debug(compiled_message); } else { compiled_message = clone(message) debug(`Compiled message is following.`); debug(compiled_message); } return compiled_message; } /** * Identify the message format. * @private * @param {MessageObject} message - Message object to identify message format. * @returns {String} - Message format. */ _identify_message_format(message){ let message_format; if (!!message.type){ message_format = "line"; } else { let message_keys = Object.keys(message).sort(); if (!!message.quick_replies || !!message.attachment || !!message.text){ // Provider is facebook. Type is quick reply. message_format = "facebook"; } else if (typeof message === "string"){ message_format = "google"; } } if (!message_format){ // We could not identify the format of this message object. throw new Error(`We can not identify the format of this message object.`); } return message_format; } } module.exports = Messenger;
export const genericCardData = [ { title: 'Brand Manual', description: 'Visual Brand Identity Manual.' }, { title: 'Logos and Posters', description: 'Official Franciscan University Logos and Poster Resources.' }, { title: 'Letterhead', description: 'Franciscan University approved letterhead and letter writing guidelines.' }, { title: 'Suggest a Story', description: 'Help us share your news.' }, { title: 'Service Request Form', description: 'Let us know what you need, and we will get started on it as soon as we can.' }, { title: 'Powerpoint', description: 'Official Franciscan University Powerpoint template.' } ]
import Rx from 'rx' import view from './page2-view' const Page2 = (sources) => { const props$ = sources.Props; const $view = view(props$); return { DOM: Rx.Observable.just($view), Props: props$, } }; export default Page2
// Generated by CoffeeScript 1.6.2 'use strict'; var App, CONFIG_TEMPLATE, CoffeeScript, DEFAULT_FILENAME, Inotify, MiniLog, RE_ENV, VERSION, app, args, deploy, fs, inotify, log, logBackend, minimatch, path; CONFIG_TEMPLATE = "'.':\n\t'*': 'echo %% was just modified!'\n"; DEFAULT_FILENAME = '.hawkeye'; RE_ENV = /\$(\S+)/; VERSION = '0.2.4'; args = require('commander'); CoffeeScript = require('../node_modules/coffee-script'); deploy = require('child_process').exec; fs = require('fs'); Inotify = require('inotify').Inotify; inotify = new Inotify(); minimatch = require('minimatch'); path = require('path'); MiniLog = require('minilog'); log = MiniLog('hawkeye'); logBackend = MiniLog.backends.nodeConsole; MiniLog.pipe(logBackend).format(logBackend.formatNpm); App = (function() { App.coffee = function(data) { return eval(CoffeeScript.compile(data, { bare: true })); }; App.createConfig = function(file) { if (file == null) { file = DEFAULT_FILENAME; } return fs.writeFile(file, CONFIG_TEMPLATE, function(error) { if (error) { log.error(error); } else { log.info("created config file '" + file + "'"); } return process.exit(error ? 1 : 0); }); }; App.handle = function(text, dir, file) { var env, key, rules, _i, _len, _ref; env = text.match(RE_ENV); text = !env ? text : text.replace(new RegExp("\\" + env[0], 'g'), process.env[env[1]]); rules = { b: path.basename(file, path.extname(file)), c: dir, d: new Date().toISOString(), e: path.extname(file), f: path.basename(file), h: process.env.PWD, '': path.join(dir, file) }; _ref = Object.keys(rules); for (_i = 0, _len = _ref.length; _i < _len; _i++) { key = _ref[_i]; text = text.replace(new RegExp("%%" + key, 'g'), rules[key]); } return text; }; function App(config, verbose) { var _this = this; if (verbose == null) { verbose = false; } this.addItem = function(dir, globs) { var callback, env, error; callback = function(event) { var file, glob, warhead, _i, _len, _ref, _results; file = event.name || 'n/a'; _ref = Object.keys(globs); _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { glob = _ref[_i]; if (minimatch(file, glob)) { log.debug("file " + file + " matched pattern '" + glob + "'"); warhead = App.handle(globs[glob], dir, file); if (verbose) { log.info("launching '" + warhead + "'"); } _results.push(deploy(warhead, function(error, stdout, stderr) { if (error) { return log.error(stderr); } else if (stdout) { return log.debug(stdout); } })); } else { _results.push(void 0); } } return _results; }; try { return process.chdir(path.dirname(config)); } catch (_error) { error = _error; log.error(error); return process.exit(1); } finally { env = dir.match(RE_ENV); dir = path.resolve(!env ? dir : dir.replace(new RegExp("\\" + env[0], 'g'), process.env[env[1]])); if (verbose) { log.info("tracking target '" + dir + "'"); } inotify.addWatch({ path: dir, watch_for: Inotify.IN_CLOSE_WRITE, callback: callback }); } }; fs.readFile(config, 'utf-8', function(error, data) { var item, items, _i, _len, _ref, _results; if (error) { log.error("error opening file '" + (path.resolve(config)) + "'. Check your syntax."); process.exit(1); } if (verbose) { log.info("version " + VERSION + " deployed"); } if (verbose) { log.info("opened watch file '" + (path.resolve(config)) + "'"); } items = App.coffee(data); _ref = Object.keys(items); _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { item = _ref[_i]; _results.push(_this.addItem(item, items[item])); } return _results; }); } return App; })(); args.version(VERSION).option('-c, --config [path]', "use this config file [" + DEFAULT_FILENAME + "]", DEFAULT_FILENAME).option('-C, --create [path]', "create a new config file here [" + DEFAULT_FILENAME + "]", DEFAULT_FILENAME).option('-v, --verbose', "output events to stdout").parse(process.argv); if (args.config === DEFAULT_FILENAME && args.create !== args.config) { App.createConfig(args.create); } else { app = new App(args.config, args.verbose); }
exports.utils = { toIncludesList: function(includes) { const list = [] if (!includes) return list if (!Array.isArray(includes)) includes = [includes] includes.forEach(function(item) { if (typeof item === 'string') { list.push({ relation: item, children: [], args: [], scope: null, conditions: null, through: false }) return } if (Array.isArray(item)) { list.push.apply(list, exports.utils.toIncludesList(item)) return } if (typeof item === 'object') { Object.keys(item).forEach(function(key) { var args = [] var scope var conditions if (item[key].$args) { args = item[key].$args if (!Array.isArray(args)) args = [args] delete item[key].$args } if (item[key].$scope) { scope = item[key].$scope delete item[key].$scope } if (item[key].$conditions) { conditions = item[key].$conditions delete item[key].$conditions } list.push({ relation: key, children: item[key], args: args, scope: scope, conditions: conditions, through: false }) }) } }) return list }, toConditionList: function(conditions, attributes) { const self = this const list = [] if (!conditions) return list if (!Array.isArray(conditions)) conditions = [conditions] // raw condition if (typeof conditions[0] === 'string') { var query = conditions[0] var args = conditions.slice(1) if (typeof args[0] === 'object' && !Array.isArray(args[0])) { // if we got e.g. ["login = :login", {login:"phil"}] var values = args[0] args = [] query = query.replace(/:(\w+)/g, function(res, field) { args.push(values[field]) return '?' // use a questionmark as a placeholder... }) } list.push({ type: 'raw', query: query, args: args }) return list } conditions.forEach(function(item) { // nested arrays. ignore them and resolve the inner items if (Array.isArray(item)) { list.push.apply(list, self.toConditionList(item, attributes)) return } if (item === undefined || item === null) return // conditions via object. e.g. `{title_like: 'foo'}` // here we need the attributes to check if it's a relation or an attribute with or without operator if (typeof item === 'object') { Object.keys(item).forEach(function(key) { const value = item[key] var foundAttribute = false // sort arrtibutes by string length. largest first! // to avoid conflicts with similar names and conditions. // e.g. ['text', 'text_long'] and condition {text_long_like: 'foo'} attributes = attributes.sort(function(a, b) { if (a.length < b.length) return 1 if (a.length > b.length) return -1 return 0 }) attributes.forEach(function(existingAttribute) { if (foundAttribute) return // e.g. {title: 'openrecord'} => direct condition if (key === existingAttribute) { list.push({ type: 'hash', attribute: existingAttribute, operator: null, // use default value: value }) foundAttribute = true return } // e.g. {title_like: 'open'} => condition with operator if (key.indexOf(existingAttribute + '_') === 0) { list.push({ type: 'hash', attribute: existingAttribute, operator: key.replace(existingAttribute + '_', ''), value: value }) foundAttribute = true } }) // if we did not find an attribute // it's maybee a conditions for a relation. `where()` will check that for us and throw an error if not! if (!foundAttribute) { list.push({ type: 'relation', relation: key, value: value }) } }) } }) return list }, assignInternals: function(targetChain, sourceChain, options) { options = options || {} const target = targetChain._internal_attributes const source = sourceChain._internal_attributes const exclude = options.exclude || [] Object.keys(source).forEach(function(key) { if (exclude.indexOf(key) !== -1) return if ( options.overwrite || !target[key] || (Array.isArray(target[key]) && target[key].length === 0) ) { target[key] = source[key] } }) } }
import prefix0 from '../prefix0' it('should be prefixed 0 if length < 2', () => { expect(prefix0(1)).toBe('01') expect(prefix0('2')).toBe('02') }) it('donnot prefix', () => { expect(prefix0(87)).toBe('87') expect(prefix0(8.7)).toBe('8.7') expect(prefix0(.7)).toBe('0.7') })
import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; // Import Style import styles from './App.css'; // Import Components import Helmet from 'react-helmet'; import DevTools from './components/DevTools'; import Header from './components/Header/Header'; import Footer from './components/Footer/Footer'; // Import Actions import { toggleAddPost } from './AppActions'; import { switchLanguage } from '../../modules/Intl/IntlActions'; export class App extends Component { constructor(props) { super(props); this.state = { isMounted: false }; } componentDidMount() { this.setState({isMounted: true}); // eslint-disable-line } toggleAddPostSection = () => { this.props.dispatch(toggleAddPost()); }; render() { return ( <div> {/*{this.state.isMounted && !window.devToolsExtension && process.env.NODE_ENV === 'development' && <DevTools />}*/} <div> <Helmet title="MERN Starter - Blog App" titleTemplate="%s - Blog App" meta={[ { charset: 'utf-8' }, { 'http-equiv': 'X-UA-Compatible', content: 'IE=edge', }, { name: 'viewport', content: 'width=device-width, initial-scale=1', }, ]} link={[ { rel: 'stylesheet', href: 'https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css' }, ]} script={[ { src: 'https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js' }, { src: 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js' }, {/*{ src: 'https://cdnjs.cloudflare.com/ajax/libs/react-bootstrap/0.30.2/react-bootstrap.min.js' },*/} ]} /> <Header switchLanguage={lang => this.props.dispatch(switchLanguage(lang))} intl={this.props.intl} toggleAddPost={this.toggleAddPostSection} /> <div className="container"> {this.props.children} </div> <Footer /> </div> </div> ); } } App.propTypes = { children: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; // Retrieve data from store as props function mapStateToProps(store) { return { intl: store.intl, }; } export default connect(mapStateToProps)(App);
/** * jsPsych plugin for showing animations and recording keyboard responses * Josh de Leeuw * * documentation: docs.jspsych.org */ import { jsPsych } from "jspsych-react"; var plugin = (function() { var plugin = {}; jsPsych.pluginAPI.registerPreload("animation", "stimuli", "image"); plugin.info = { name: "animation", description: "", parameters: { stimuli: { type: jsPsych.plugins.parameterType.STRING, pretty_name: "Stimuli", default: undefined, array: true, description: "The images to be displayed." }, frame_time: { type: jsPsych.plugins.parameterType.INT, pretty_name: "Frame time", default: 250, description: "Duration to display each image." }, frame_isi: { type: jsPsych.plugins.parameterType.INT, pretty_name: "Frame gap", default: 0, description: "Length of gap to be shown between each image." }, sequence_reps: { type: jsPsych.plugins.parameterType.INT, pretty_name: "Sequence repetitions", default: 1, description: "Number of times to show entire sequence." }, choices: { type: jsPsych.plugins.parameterType.KEYCODE, pretty_name: "Choices", default: jsPsych.ALL_KEYS, array: true, description: "Keys subject uses to respond to stimuli." }, prompt: { type: jsPsych.plugins.parameterType.STRING, pretty_name: "Prompt", default: null, description: "Any content here will be displayed below stimulus." } } }; plugin.trial = function(display_element, trial) { var interval_time = trial.frame_time + trial.frame_isi; var animate_frame = -1; var reps = 0; var startTime = new Date().getTime(); var animation_sequence = []; var responses = []; var current_stim = ""; var animate_interval = setInterval(function() { var showImage = true; display_element.innerHTML = ""; // clear everything animate_frame++; if (animate_frame == trial.stimuli.length) { animate_frame = 0; reps++; if (reps >= trial.sequence_reps) { endTrial(); clearInterval(animate_interval); showImage = false; } } if (showImage) { show_next_frame(); } }, interval_time); function show_next_frame() { // show image display_element.innerHTML = '<img src="' + trial.stimuli[animate_frame] + '" id="jspsych-animation-image"></img>'; current_stim = trial.stimuli[animate_frame]; // record when image was shown animation_sequence.push({ stimulus: trial.stimuli[animate_frame], time: new Date().getTime() - startTime }); if (trial.prompt !== null) { display_element.innerHTML += trial.prompt; } if (trial.frame_isi > 0) { jsPsych.pluginAPI.setTimeout(function() { display_element.querySelector( "#jspsych-animation-image" ).style.visibility = "hidden"; current_stim = "blank"; // record when blank image was shown animation_sequence.push({ stimulus: "blank", time: new Date().getTime() - startTime }); }, trial.frame_time); } } var after_response = function(info) { responses.push({ key_press: info.key, rt: info.rt, stimulus: current_stim }); // after a valid response, the stimulus will have the CSS class 'responded' // which can be used to provide visual feedback that a response was recorded display_element.querySelector("#jspsych-animation-image").className += " responded"; }; // hold the jspsych response listener object in memory // so that we can turn off the response collection when // the trial ends var response_listener = jsPsych.pluginAPI.getKeyboardResponse({ callback_function: after_response, valid_responses: trial.choices, rt_method: "date", persist: true, allow_held_key: false }); function endTrial() { jsPsych.pluginAPI.cancelKeyboardResponse(response_listener); var trial_data = { animation_sequence: JSON.stringify(animation_sequence), responses: JSON.stringify(responses) }; jsPsych.finishTrial(trial_data); } }; return plugin; })(); export default plugin;
(function() { 'use strict'; // Create the 'chat' controller angular.module('chat').controller('ChatController', ['$scope', '$window', 'Authentication', 'Socket', function($scope, $window, Authentication, Socket) { var vm = this; vm.messages = []; vm.messageText = ''; vm.sendMessage = sendMessage; // Make sure the Socket is connected if (!Socket.socket) { Socket.connect(); } // Add an event listener to the 'chatMessage' event Socket.on('chatMessage', function(message) { vm.messages.unshift(message); }); // Create a controller method for sending messages function sendMessage() { // Create a new message object var message = { text: vm.messageText }; // Emit a 'chatMessage' message event Socket.emit('chatMessage', message); // Clear the message text vm.messageText = ''; } // Remove the event listener when the controller instance is destroyed $scope.$on('$destroy', function() { Socket.removeListener('chatMessage'); }); angular.element($window).bind('resize', function() { vm.onResize(); }); vm.onResize = function() { angular.element('.direct-chat-messages').css('min-height', angular.element('.main-sidebar').height() - 251); }; vm.onResize(); } ]); })();
const express = require('express'); const server = express(); const port = 8080; server.use(express.static(__dirname + '/public')); server.get('/rerecounter', (req, res) => { res.sendFile('/public/html/index.html', {root: __dirname}); }); server.listen(port, () => { console.log('Server listening on', port); });
/**************************************************************************** The MIT License (MIT) Copyright (c) 2013 Apigee Corporation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ 'use strict'; var debug = require('debug')('oauth'); var _ = require('underscore'); var Url = require('url'); function OAuthConnect(oauth, options) { if (!(this instanceof OAuthConnect)) { return new OAuthConnect(oauth, options); } this.oauth = oauth; this.options = options || {}; } module.exports = OAuthConnect; OAuthConnect.prototype.handleAuthorize = function() { var self = this; return function(req, resp) { debug('Express authorize'); if (!req.query) { req.query = Url.parse(req.url).query; } self.oauth.authorize(req.query, req, function(err, result) { if (err) { if (debug.enabled) { debug('Authorization error: ' + err); } makeError(err, resp); } else { resp.statusCode = 302; debug('Setting location header to %s', result); resp.setHeader('Location', result); resp.end(); } }); }; }; OAuthConnect.prototype.handleAccessToken = function() { var self = this; return function(req, resp) { debug('Express accessToken'); getRequestBody(req, function(body) { req.body = body; self.oauth.generateToken(body, { authorizeHeader: req.headers.authorization, request: req }, function(err, result) { if (err) { if (debug.enabled) { debug('Access token error: ' + err); } makeError(err, resp); } else { resp.setHeader('Cache-Control', 'no-store'); resp.setHeader('Pragma', 'no-cache'); sendJson(resp, result); } }); }); }; }; OAuthConnect.prototype.authenticate = function(scopes) { var self = this; return function(req, resp, next) { debug('Express authenticate'); self.oauth.verifyToken( req.headers.authorization, scopes, function(err, result) { if (err) { if (debug.enabled) { debug('Authentication error: ' + err); } makeError(err, resp); } else { req.token = result; next(); } } ); }; }; OAuthConnect.prototype.refreshToken = function() { var self = this; return function(req, resp) { debug('Express refreshToken'); getRequestBody(req, function(body) { req.body = body; self.oauth.refreshToken(body, { authorizeHeader: req.headers.authorization, request: req }, function(err, result) { if (err) { if (debug.enabled) { debug('Refresh token error: ' + err); } makeError(err, resp); } else { resp.setHeader('Cache-Control', 'no-store'); resp.setHeader('Pragma', 'no-cache'); sendJson(resp, result); } }); }); }; }; OAuthConnect.prototype.invalidateToken = function() { var self = this; return function(req, resp) { debug('Express invalidateToken'); getRequestBody(req, function(body) { req.body = body; self.oauth.invalidateToken(body, { authorizeHeader: req.headers.authorization, request: req }, function(err, result) { if (err) { if (debug.enabled) { debug('Refresh token error: ' + err); } makeError(err, resp); } else { sendJson(resp, result); } }); }); }; }; function getRequestBody(req, cb) { if (req.complete) { return cb(req.body); } var body = ''; req.setEncoding('utf8'); req.on('readable', function() { var chunk; do { chunk = req.read(); if (chunk) { body += chunk; } } while (chunk); }); req.on('end', function() { cb(body); }); } function makeError(err, resp) { var rb = { error_description: err.message }; if (err.state) { rb.state = err.state; } if (err.code) { rb.error = err.code; } else { rb.error = 'server_error'; } if (err.headers) { _.each(_.keys(err.headers), function(name) { resp.setHeader(name, err.headers[name]); }); } sendJson(resp, err.statusCode, rb); } function sendJson(resp, code, body) { if (!body) { body = code; code = undefined; } if (code) { resp.statusCode = code; } resp.setHeader('Content-Type', 'application/json'); resp.end(JSON.stringify(body)); }
/*globals describe, it */ var should = require('should'), JGL = require('../../'); describe('JGL.segmentKeys()', function () { it('should expand ranges', function () { var result = JGL.segmentKeys({from: 0, to: 5}); result.should.eql([0, 1, 2, 3, 4, 5]); }); it('should leave integers and strings alone', function () { JGL.segmentKeys('foo').should.eql(['foo']); JGL.segmentKeys(1).should.eql([1]); }); it('should expand nested segments', function () { JGL.segmentKeys([1, 'foo', {from: 0, to: 4}]). should.eql([1, 'foo', 0, 2, 3, 4]); }); });
import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import withFB from 'common/withFB'; import Header from '../../../components/Layout/Header'; import { login, getLoginStatus, getMe } from '../../../actions/auth'; const mapStateToProps = state => ({ auth: state.auth, }); const mapDispatchToProps = dispatch => bindActionCreators({ login, getLoginStatus, getMe }, dispatch); export default connect(mapStateToProps, mapDispatchToProps)(withFB(Header));
module.exports = { rules: { strict: [2, 'never'] } };
import App from './App'; document.addEventListener('DOMContentLoaded', () => { let canvas = document.getElementById('screen'); let context = canvas.getContext('2d'); let width = document.body.clientWidth; let height = document.body.clientHeight; let swarmSize = 300; let runner = new App(canvas, context, width, height, swarmSize); let pump = () => { runner.step(); window.requestAnimationFrame(pump); }; window.requestAnimationFrame(pump); window.addEventListener('resize', () => { runner.setSize(document.body.clientWidth, document.body.clientHeight); }); });
var React = require('react-native'); var { StyleSheet, Text, View, ListView, TouchableHighlight, Image, ActivityIndicatorIOS } = React; var styles = require('./styles'); var redditApi = require('../../api/reddit'); var moment = require('moment'); var he = require('he'); var ParseHTML = require('../../ParseHTML'); var disclosure90= require('./images/disclosure90.png'); var disclosure = require('./images/disclosure.png'); var CommentsView = React.createClass({ comments: [], getInitialState: function () { return { loaded: false } }, componentDidMount: function() { this.fetchData(); }, fetchData: function() { redditApi.fetchComments(this.props.post) .then(comments => { comments.sort((a,b) => b.score - a.score); this.comments = comments; this.setState({ loaded: true }); }) .done(); }, renderComments: function () { return <CommentsList comments={this.comments}></CommentsList>; }, renderLoader: function () { return ( <View style={styles.activityIndicatorContainer}> <ActivityIndicatorIOS style={styles.activityIndicator} size="large" color="#48BBEC" /> </View> ) }, render: function() { return ( <View style={[styles.container, styles.viewContainer]}> {this.state.loaded ? this.renderComments() : this.renderLoader()} </View> ) }, }); var CommentsList = React.createClass({ getInitialState: function() { var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); return { dataSource: ds.cloneWithRows(this.props.comments), }; }, componentWillUpdate: function (nextProps) { this.state.dataSource = this.getDataSource(nextProps.comments); }, getDataSource: function(comments): ListView.DataSource { return this.state.dataSource.cloneWithRows(comments); }, render: function() { return ( <ListView style={styles.container} dataSource={this.state.dataSource} renderRow={this.renderComment} /> ); }, renderComment: function(comment) { return ( <Comment comment={comment}/> ) } }); var Comment = React.createClass({ getInitialState: function () { return { repliesShown: true } }, render: function() { return ( <View style={styles.comment}> <View style={styles.rowContainer}> <Text style={styles.author}>{this.props.comment.author + ' '}</Text> <Text style={styles.pointsAndTime}>{this.props.comment.score || 0} points {moment(this.props.comment.created_utc*1000).fromNow()}</Text> </View> <View style={styles.postDetailsContainer}> <Text style={styles.commentBody}>{this.props.comment.body && he.unescape(this.props.comment.body)}</Text> {this.props.comment.replies && this._renderRepliesSection()} </View> </View> ); }, _renderRepliesSection: function () { var repliesSection = this.props.comment.replies.length ? (<View> <View style={styles.rowContainer}> <Text onPress={this._toggleReplies} style={styles.repliesBtnText}> replies ({this.props.comment.replies.length}) </Text> <Image style={[styles.disclosure, styles.muted]} source={this.state.repliesShown ? disclosure90 : disclosure} /> </View> {this.state.repliesShown && this._renderReplies()} </View>) : <View/>; return repliesSection; }, _toggleReplies: function () { this.setState({ repliesShown: !this.state.repliesShown }) }, _renderReplies: function () { return ( <View style={styles.repliesContainer}> <CommentsList comments={this.props.comment.replies}></CommentsList> </View> ) } }); module.exports = CommentsView;
import DS from 'ember-data'; import AjaxRequestMixin from 'ember-ajax/mixins/ajax-request'; import Service, { inject as service } from '@ember/service'; import { assert } from '@ember/debug'; import { get } from '@ember/object'; import { createQueryParams } from '../utils/url-helpers'; const { Model } = DS; const JSONContentType = 'application/json; charset=UTF-8'; /** * Service for making custom requests to a backend API. * * This service uses both ember-ajax and ember-data for constructing the URL. * The service will alter the path passed to ember-ajax by first transforming the path * into a ember-data path. It creates the ember-data path by a given model instance or name * and using the corresponding adapter (or the application adapter if no model instance * or name is given). * * @module ember-api-requests * @class ApiService * @extends Service */ export default Service.extend(AjaxRequestMixin, { store: service(), /** * Build an URL based on given path and options. * * The URL will by default be created by using ember data adapters. * When a model instance or name is defined, the corresponding adapter will be used, * otherwise the application adapter will be used. * * Any custom set host on this service will also be applied to the URL. * * Options: * - model {DS.Model|String} used for creating a prefix for the URL * - params {Object} used for adding query parameters to the URL * - requestType {String} used for creating the URL using an ember data adapter, * defaults to 'findRecord' for instance and 'findAll' for non instance * * @method buildURL * @param {String} path The path * @param {Object} options Options for building the URL (optional) * @return {String} The full URL */ buildURL(path, options = {}) { let adapterURL = this._buildAdapterURL(path, options); return this._buildURL(adapterURL, options); }, /** * @method _buildAdapterURL * @private * @param {String} url * @param {Object} options * @return {String} */ _buildAdapterURL(url, options = {}) { let modelName, id, snapshot, requestType = options.requestType, model = options.model; if (model instanceof Model) { id = get(model, 'id'); assert('ember-api-requests expects a model instance to have an `id` set.', id !== null); modelName = model.constructor.modelName || model.constructor.typeKey || model._internalModel.modelName; snapshot = model._createSnapshot(); requestType = requestType || 'findRecord'; } else if (typeof model === 'string') { modelName = model; requestType = requestType || 'findAll'; } let adapter = get(this, 'store').adapterFor(modelName || 'application'); let result = adapter.buildURL(modelName, id, snapshot, requestType); result += url.charAt(0) === '/' ? url : `/${url}`; result += createQueryParams(adapter, options.params, options.traditional); return result; }, /** * @method options * @private * @param {String} url * @param {Object} options * @return {Object} */ options(url, options = {}) { // Skip the process if url is already set if (options.url) { return options; } let isGetType = options.type === 'GET'; if (isGetType && options.data) { assert("ember-api-requests does not allow the `data` property for `GET` requests, instead use the `params` property."); } url = this._buildAdapterURL(url, options); if (!isGetType && typeof options.jsonData === 'object') { options.data = JSON.stringify(options.jsonData); options.contentType = JSONContentType; options.processData = false; } ['jsonData','params','model','requestType'].forEach(i => delete options[i]); let hasDataType = !!options.dataType; let result = this._super(url, options); // Only set dataType when defined as option, this differs from ember-ajax if (!hasDataType) { delete result.dataType; } return result; } });
/* eslint-disable no-console */ "use strict"; const { ServiceBroker } = require("moleculer"); const ApiService = require("../../index"); // Create broker const broker = new ServiceBroker({ logger: console, logLevel: "warn" }); broker.createService({ name: "test", actions: { hello() { return "Hello"; } } }); // Load API Gateway broker.createService(ApiService); // Start server broker.start() .then(() => console.log("Test URL: http://localhost:3000/test/hello")); /** * Result on i7 4770K 32GB RAM Windows 10 x64 * * Throughtput: 14 427 req/sec */
import express from 'express'; import morgan from 'morgan'; import jwt from 'jwt-simple'; import bodyParser from 'body-parser'; import passport from 'passport'; import { Strategy } from 'passport-local'; import mongoose from 'mongoose'; mongoose.connect('mongodb://user:pass@ds037005.mongolab.com:37005/toomastahvesdb'); import User from './models/User.js'; const app = express(); app.use(passport.initialize()); passport.serializeUser((user, done) => { done(null, user.id); }); app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization'); next(); }); const loginStrategy = new Strategy({ usernameField: 'email' }, (email, enteredPassword, done) => { User.findOne({ email }, (err, user) => { if(err) { return done(err); } if(!user) { return done(null, false, { message: 'User not found' }); } user.comparePasswords(enteredPassword, user.password, (err2, isMatch) => { if(err2) { return done(err2); } if(!isMatch) { return done(null, false, { message: 'Wrong password' }); } return done(null, user); }); }); }); passport.use('local-login', loginStrategy); const registerStrategy = new Strategy({ usernameField: 'email' }, (email, password, done) => { console.log('registerStrategy'); User.findOne({ email }, (err, user) => { if(err) { return done(err); } if(user) { return done(null, false, { message: 'Email already exists' }); } const newUser = new User({ email, password }); newUser.save(() => { done(null, newUser); }); }); }); passport.use('local-register', registerStrategy); app.use(morgan('combined')); app.use(bodyParser.json()); app.use(express.static('public')); app.listen(1337, (err) => { if(err) console.log('Error', err); console.log('Server started'); }); import webpack from 'webpack'; import config from '../webpack.config'; const compiler = webpack(config); app.use(require('webpack-dev-middleware')(compiler, { publicPath: config.output.publicPath, hot: true, contentBase: './public', historyApiFallback: true })); app.use(require('webpack-hot-middleware')(compiler)); const createSendToken = (user, res) => { const payload = { sub: user.id }; const token = jwt.encode(payload, 'secret'); res.status(200).send({ user: user.toJSON(user), token }); }; app.post('/register', passport.authenticate('local-register'), (req, res) => { console.log('Register request coming in'); createSendToken(req.user, res); }); app.post('/login', passport.authenticate('local-login'), (req, res) => { console.log('Login request coming in'); createSendToken(req.user, res); }); app.get('/ponies', (req, res) => { if(!req.headers.authorization) { return res.status(401).send({ message: 'No Auth header' }); } const token = req.headers.authorization.split(' ')[1]; const payload = jwt.decode(token, 'secret'); if(!payload.sub) { res.status(401).send({ message: 'Bad Auth token' }); } res.json(['rainbow', 'dash']); }); app.get('/colors', (req, res) => { res.json(['blue', 'pink']); });
'use strict'; let interval; let count; let t; module.exports = function (nodecg) { const gameTime = nodecg.Replicant('gameTime'); function countdown() { if (gameTime.value === 0) { console.log('time is up'); clearTimeout(t); } else { gameTime.value--; t = setTimeout(countdown, 1000); } } function stopTime() { clearTimeout(t); } nodecg.listenFor('startTime', countdown); nodecg.listenFor('stopTime', stopTime); };
'use strict'; /* * Author: Pavel Bely * Mail: poul-white@yandex.ru * * Root Controller with Directive */ import app from '../../modules/app'; import markup from './root.html'; import {add} from '../../redux/actions'; class RootController { constructor($ngRedux, $scope, saveResource) { $ngRedux.connect( this.mapStateToThis, this.mapDispatchToThis($scope, saveResource) )(this); } mapStateToThis(state) { return { notification: state.notification, columns: Object.keys(state.columns) }; } mapDispatchToThis($scope, saveResource) { return dispatch => ({ addHandler: () => dispatch(add('TODO','Name:\nDate:\nTime:\n')), saveHandler: () => saveResource() }); } } app.directive('appRoot', function() { return { restrict: 'A', controller: ['$ngRedux', '$scope', 'saveService', RootController], controllerAs: 'root', template: markup, scope: {} }; });
'use strict'; /** * Retrun a random int, used by `utils.uid()` * * @param {Number} min * @param {Number} max * @return {Number} * @api private */ function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } /** * Return a unique identifier with the given `len`. * * utils.uid(10); * // => "FDaS435D2z" * * @param {Number} len * @return {String} * @api private */ exports.uid = function(len) { var buf = [], chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', charlen = chars.length; for (var i = 0; i < len; ++i) { buf.push(chars[getRandomInt(0, charlen - 1)]); } return buf.join(''); };
var React = require('react'); require('./css/addItem.css'); var AddItem = React.createClass({ render: function() { return ( <form id="add-todo" onSubmit={this.handleSubmit}> <input type="text" required ref="newItem" /> <input type="submit" value="Hit me" /> </form> ); }, // Render. // Custom functions. handleSubmit: function(e) { e.preventDefault(); this.props.onAdd(this.refs.newItem.value); } }); module.exports = AddItem;
describe('display', function(){ var image; beforeEach(function(done){ var img = new Image(); img.src = "img/logo.png"; img.onload = function(){ image = new arc.display.Image(img); done(); }; }); describe('DisplayObject', function(){ it('should return initial property', function(){ var display = new arc.display.DisplayObject(image); expect(display.getWidth()).to.eql(347); expect(display.getHeight()).to.eql(287); expect(display.getAlpha()).to.eql(1); expect(display.getRotation()).to.eql(0); expect(display.getVisible()).to.eql(true); }); it('should return its scale properly', function(){ var display = new arc.display.DisplayObject(image); var width = image.getWidth(); var height = image.getHeight(); display.setWidth(500); expect(display.getWidth()).to.eql(500); expect(display.getScaleX()).to.eql(500 / width); display.setWidth(1000); expect(display.getWidth()).to.eql(1000); expect(display.getScaleX()).to.eql(1000 / width); display.setHeight(500); expect(display.getHeight()).to.eql(500); expect(display.getScaleY()).to.eql(500 / height); display.setHeight(1000); expect(display.getHeight()).to.eql(1000); expect(display.getScaleY()).to.eql(1000 / height); }); it('should return its size properly', function(){ var display = new arc.display.DisplayObject(image); var width = image.getWidth(); var height = image.getHeight(); display.setRotation(90); display.setScaleX(2); expect(display.getWidth()).to.eql(width * 2); display.setScaleY(2); expect(display.getHeight()).to.eql(height * 2); }); }); });
/** * Created by mpbil on 4/10/2017. */ import React, {Component} from 'react'; import * as actions from '../actions/logonFormActions'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; class LoginForm extends Component{ constructor(props){ super(props); this.passwordChanged=this.passwordChanged.bind(this); this.usernameChanged=this.usernameChanged.bind(this); this.loginClicked=this.loginClicked.bind(this); this.passwordKeyPress = this.passwordKeyPress.bind(this); } usernameChanged(e){ this.props.updateUsername(e.target.value); } passwordChanged(e){ this.props.updatePassword(e.target.value); } loginClicked(){ this.props.login(this.props.loginForm.username,this.props.loginForm.password) } passwordKeyPress(e){ if(e.key==="Enter"){ this.loginClicked(); } } render(){ return ( <div className="column is-4 is-offset-4"> <label className="label">Username</label> <div className="control"> <input disabled={true} className="input" type="text" id={'username'} value={this.props.loginForm.username} onInput={this.usernameChanged} /> </div> <label className="label">Password</label> <div className="control"> <input className="input" type="password" value={this.props.loginForm.password} onInput={this.passwordChanged} onKeyPress={this.passwordKeyPress} /> </div> <div className="control"> <button className="button is-primary" onClick={this.loginClicked}>Login</button> </div> </div> ) } } export const LoginPage=(props)=>{ return ( <LoginForm updateUsername={props.actions.updateUsername} updatePassword={props.actions.updatePassword} login={props.actions.login} loginForm={props.loginForm} /> ) }; function mapStateToProps(state) { return { loginForm:state.loginForm } } function mapDispatchToProps(dispatch) { return { actions:bindActionCreators(actions,dispatch) } } export default connect( mapStateToProps, mapDispatchToProps )(LoginPage);
var unauthorizedTest = require("../../../unauthorized-test-factory"); unauthorizedTest({ uri: "/finishing-printing/monitoring-specification-machine" });
/* Highlight a node and forced it visible if it is hidden. */ sigma.publicPrototype.selectNodes = function (nodes) { var sigInst = this; var node=null; sigInst.iterNodes(function (n) { // Iterate node to find the node clicked if (n.id == nodes[0]) { node = n; } }); if (node && node.hidden) { node.attr.temp.forceVisible = true; sigInst.updateTypeNodeFilter(); } sigInst.changeColors(nodes); // We change the graph color according to the selected node }; /* If a node was focused, re-higlight it, else higlight all nodes. */ sigma.publicPrototype.deselectNodes = function () { var sigInst = this; sigInst.searchNodeValue(""); // If a search was in course, remove it if (sigInst.focusedNode) { sigInst.changeColors([sigInst.focusedNode]); } else { sigInst.changeColors(null); // We give the default colors } };
import {parseAndGetExpression} from '../../../utils'; import {expect} from 'chai'; describe('ClassExpression', () => { it('should return correct type', () => { expect(parseAndGetExpression('class {}').type).to.equal('ClassExpression'); }); it('should accept superClass', () => { var statement = parseAndGetExpression('class X extends Y {}'); expect(statement.id.type).to.equal('Identifier'); expect(statement.id.name).to.equal('X'); expect(statement.superClass.type).to.equal('Identifier'); expect(statement.superClass.name).to.equal('Y'); expect(statement.body.type).to.equal('ClassBody'); expect(statement.body.body.length).to.equal(0); }); it('should not require id with superClass', () => { var statement = parseAndGetExpression('class extends Y {}'); expect(statement.superClass.type).to.equal('Identifier'); expect(statement.superClass.name).to.equal('Y'); expect(statement.body.type).to.equal('ClassBody'); expect(statement.body.body.length).to.equal(0); }); it('should accept expession for superClass', () => { var statement = parseAndGetExpression('class X extends z.Y {}'); expect(statement.id.type).to.equal('Identifier'); expect(statement.id.name).to.equal('X'); expect(statement.superClass.type).to.equal('MemberExpression'); expect(statement.superClass.object.type).to.equal('Identifier'); expect(statement.superClass.object.name).to.equal('z'); expect(statement.superClass.property.type).to.equal('Identifier'); expect(statement.superClass.property.name).to.equal('Y'); expect(statement.body.type).to.equal('ClassBody'); expect(statement.body.body.length).to.equal(0); }); it('should not require id with members', () => { var statement = parseAndGetExpression('class { method() {} }'); expect(statement.id).to.equal(null); expect(statement.superClass).to.equal(null); expect(statement.body.type).to.equal('ClassBody'); expect(statement.body.body.length).to.equal(1); expect(statement.body.body[0].type).to.equal('ClassMethod'); expect(statement.body.body[0].key.name).to.equal('method'); }); it('should accept members', () => { var statement = parseAndGetExpression('class X { method() {} }'); expect(statement.id.type).to.equal('Identifier'); expect(statement.id.name).to.equal('X'); expect(statement.superClass).to.equal(null); expect(statement.body.type).to.equal('ClassBody'); expect(statement.body.body.length).to.equal(1); expect(statement.body.body[0].type).to.equal('ClassMethod'); expect(statement.body.body[0].key.name).to.equal('method'); }); });
import React from 'react' import { StyleSheet, css } from 'aphrodite' class ModalMenu extends React.Component { constructor(props) { super(props) this.state = { itemText: this.props.item.itemText, comments: this.props.item.itemComments } } handleClose(e){ this.props.close(e) } handleTextChange(e) { this.setState({ itemText: e.target.value }) } handleCommentsChange(e) { this.setState({ comments: e.target.value }) } handleSave(e) { const {itemText, comments} = this.state this.props.onSave(e, itemText, comments) } handleKeyDown(e){ if(e.key === 'Escape'){ this.props.close(e) } } render(){ const styles = StyleSheet.create({ modal: { position: 'absolute', left: '200px', top: '0px', border: '1px solid grey', backgroundColor: 'white', width: '400px', height: '350px', zIndex: 1, }, closeButton: { position: 'absolute', top: '10px', right: '10px', fontSize: '20px', padding: '5px' }, closer: { position: 'fixed', left: 0, top: 0, width: '100%', height: '100%', zIndex: -1 }, content: { display: 'flex', flexDirection: 'column', margin: '20px', marginTop: '0px' }, h1: { marginTop: '30px', fontWeight: 'bold', marginBottom: '10px' }, button: { marginTop: '30px', width: '50px', height: '30px' } }) const {item} = this.props return ( <div className={css(styles.modal)}> <div className={css(styles.closer)} onClick={this.handleClose.bind(this)}></div> <div className={css(styles.closeButton)} onClick={this.handleClose.bind(this)}>x</div> <div className={css(styles.content)}> <div className={css(styles.h1)}>Title: </div> <textarea autoFocus rows='5' value={this.state.itemText} onChange={this.handleTextChange.bind(this)} onKeyDown={this.handleKeyDown.bind(this)}/> <div className={css(styles.h1)}>Comments: </div> <textarea rows='5' value={this.state.comments} onChange={this.handleCommentsChange.bind(this)} onKeyDown={this.handleKeyDown.bind(this)}/> <button className={css(styles.button)} onClick={this.handleSave.bind(this)}>Save</button> </div> </div> ) } } export default ModalMenu
export const generatePortId = (items = []) => { const id = '' + Math.random().toString(36).slice(2) if (!items.filter(item => item.id === id)[0]) { return id } return generatePortId(items) } export const getFilename = url => { return url ? url.substring(url.lastIndexOf('/') + 1) : null }
var _ = require('lodash'); var Joi = require('joi'); import CONST from '../constants'; var common = { team: Joi.number().integer().min(0), userUuid: Joi.string().regex(/^[A-Za-z0-9_-]+$/).min(1, 'utf8').max(128, 'utf8'), primaryKeyId: Joi.number().integer().min(0) }; const schemas = { common: common, action: { user: common.userUuid.required(), type: Joi.string().uppercase().required(), imageData: Joi.string().when('type', { is: 'IMAGE', then: Joi.required() }), imageText: Joi.string().max(50, 'utf8').optional(), imageTextPosition: Joi.number().min(0).max(1).optional(), text: Joi.string().when('type', { is: Joi.valid('TEXT', 'COMMENT'), then: Joi.required() }), eventId: common.primaryKeyId.when('type', { is: 'CHECK_IN_EVENT', then: Joi.required()}), city: common.primaryKeyId, feedItemId: common.primaryKeyId.when('type', { is: 'COMMENT', then: Joi.required() }), location: Joi.object({ latitude: Joi.number(), longitude: Joi.number() }).when('type', {is: 'CHECK_IN_EVENT', then: Joi.required()}), }, user: { uuid: common.userUuid.required(), name: Joi.string().min(1, 'utf8').max(50, 'utf8').required(), team: common.team.required(), profilePicture: Joi.string(), }, userQueryParams: { userId: common.primaryKeyId.required(), }, feedParams: { city: common.primaryKeyId, beforeId: Joi.number().integer().min(0).optional(), limit: Joi.number().integer().min(1).max(100).optional(), since: Joi.date().iso(), offset: Joi.number().integer().min(0), type: Joi.string() .valid(['TEXT', 'IMAGE']) .optional(), sort: Joi.string() .valid(CONST.FEED_SORT_TYPES_ARRAY) .default(CONST.FEED_SORT_TYPES.NEW) .optional(), }, imageParams: { imageId: Joi.string().required() }, vote: { value: Joi.number().integer().valid(-1, 0, 1), feedItemId: Joi.number().integer().required(), }, upsertMoodParams: { rating: Joi.number().precision(4).min(0).max(10).required(), description: Joi.string().min(1, 'utf8').max(128, 'utf8').optional().allow([null]).default(null), location: Joi.object({ latitude: Joi.number(), longitude: Joi.number() }), }, getMoodParams: { user: common.primaryKeyId, team: common.primaryKeyId, city: common.primaryKeyId, }, radioParams: { city: common.primaryKeyId, id: common.primaryKeyId, }, eventsParams: { city: common.primaryKeyId, id: common.primaryKeyId, showPast: Joi.boolean().default(false), }, citiesParams: { city: common.primaryKeyId, }, teamsParams: { city: common.primaryKeyId, }, }; const conversions = {}; function assert(obj, schemaName) { var joiObj = _getSchema(schemaName); // All this hassle to get joi to format nice error messages var content = {}; content[schemaName] = obj; var expected = {}; expected[schemaName] = joiObj; var result = Joi.validate(content, expected); if (result.error) { if (!result.error.isJoi) { throw result.error; } _throwJoiError(result.error); } // Return for convenience return result.value[schemaName]; } // Converts string `value` to a correct js object. // `schemaName` refers to key in `conversion` object. It defines all // conversion functions. function convert(obj, schemaName) { return _.reduce(obj, (memo, val, key) => { var func = _getConversion(schemaName) if (_.isFunction(func)) { memo[key] = func(val); } else { memo[key] = val; } return memo; }, {}); } function _getConversion(name) { var conversion = _.get(conversions, name); if (!conversion) { throw new Error('Conversion with name ' + name + ' was not found'); } return conversion; } function _getSchema(name) { var joiObj = _.get(schemas, name); if (!joiObj) { throw new Error('Schema with name ' + name + ' was not found'); } return joiObj; } function _throwJoiError(err) { // See https://github.com/hapijs/joi/blob/v7.2.3/API.md#errors var msg = _.get(err, 'details.0.message') || 'Validation error'; var newErr = new Error(msg); newErr.status = 400; throw newErr; } export { assert, convert, common, schemas };
// Copyright 2009 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Tests loads of local properties from eval. function test(source) { var x = 27; eval(source); } test("assertEquals(27, x);"); test("(function() { assertEquals(27, x) })();"); test("(function() { var y = 42; eval('1'); assertEquals(42, y); })();"); test("(function() { var y = 42; eval('var y = 2; var z = 2;'); assertEquals(2, y); })();");
describe("QueueRunner", function() { it("runs all the functions it's passed", function() { var calls = [], queueableFn1 = { fn: jasmine.createSpy('fn1') }, queueableFn2 = { fn: jasmine.createSpy('fn2') }, queueRunner = new jasmineUnderTest.QueueRunner({ queueableFns: [queueableFn1, queueableFn2] }); queueableFn1.fn.and.callFake(function() { calls.push('fn1'); }); queueableFn2.fn.and.callFake(function() { calls.push('fn2'); }); queueRunner.execute(); expect(calls).toEqual(['fn1', 'fn2']); }); it("calls each function with a consistent 'this'-- an empty object", function() { var queueableFn1 = { fn: jasmine.createSpy('fn1') }, queueableFn2 = { fn: jasmine.createSpy('fn2') }, queueableFn3 = { fn: function(done) { asyncContext = this; done(); } }, queueRunner = new jasmineUnderTest.QueueRunner({ queueableFns: [queueableFn1, queueableFn2, queueableFn3] }), asyncContext; queueRunner.execute(); var context = queueableFn1.fn.calls.first().object; expect(context).toEqual({}); expect(queueableFn2.fn.calls.first().object).toBe(context); expect(asyncContext).toBe(context); }); describe("with an asynchronous function", function() { beforeEach(function() { jasmine.clock().install(); }); afterEach(function() { jasmine.clock().uninstall(); }); it("supports asynchronous functions, only advancing to next function after a done() callback", function() { //TODO: it would be nice if spy arity could match the fake, so we could do something like: //createSpy('asyncfn').and.callFake(function(done) {}); var onComplete = jasmine.createSpy('onComplete'), beforeCallback = jasmine.createSpy('beforeCallback'), fnCallback = jasmine.createSpy('fnCallback'), afterCallback = jasmine.createSpy('afterCallback'), queueableFn1 = { fn: function(done) { beforeCallback(); setTimeout(done, 100); } }, queueableFn2 = { fn: function(done) { fnCallback(); setTimeout(done, 100); } }, queueableFn3 = { fn: function(done) { afterCallback(); setTimeout(done, 100); } }, queueRunner = new jasmineUnderTest.QueueRunner({ queueableFns: [queueableFn1, queueableFn2, queueableFn3], onComplete: onComplete }); queueRunner.execute(); expect(beforeCallback).toHaveBeenCalled(); expect(fnCallback).not.toHaveBeenCalled(); expect(afterCallback).not.toHaveBeenCalled(); expect(onComplete).not.toHaveBeenCalled(); jasmine.clock().tick(100); expect(fnCallback).toHaveBeenCalled(); expect(afterCallback).not.toHaveBeenCalled(); expect(onComplete).not.toHaveBeenCalled(); jasmine.clock().tick(100); expect(afterCallback).toHaveBeenCalled(); expect(onComplete).not.toHaveBeenCalled(); jasmine.clock().tick(100); expect(onComplete).toHaveBeenCalled(); }); it("explicitly fails an async function with a provided fail function and moves to the next function", function() { var queueableFn1 = { fn: function(done) { setTimeout(function() { done.fail('foo'); }, 100); } }, queueableFn2 = { fn: jasmine.createSpy('fn2') }, failFn = jasmine.createSpy('fail'), queueRunner = new jasmineUnderTest.QueueRunner({ queueableFns: [queueableFn1, queueableFn2], fail: failFn }); queueRunner.execute(); expect(failFn).not.toHaveBeenCalled(); expect(queueableFn2.fn).not.toHaveBeenCalled(); jasmine.clock().tick(100); expect(failFn).toHaveBeenCalledWith('foo'); expect(queueableFn2.fn).toHaveBeenCalled(); }); it("sets a timeout if requested for asynchronous functions so they don't go on forever", function() { var timeout = 3, beforeFn = { fn: function(done) { }, type: 'before', timeout: function() { return timeout; } }, queueableFn = { fn: jasmine.createSpy('fn'), type: 'queueable' }, onComplete = jasmine.createSpy('onComplete'), onException = jasmine.createSpy('onException'), queueRunner = new jasmineUnderTest.QueueRunner({ queueableFns: [beforeFn, queueableFn], onComplete: onComplete, onException: onException }); queueRunner.execute(); expect(queueableFn.fn).not.toHaveBeenCalled(); jasmine.clock().tick(timeout); expect(onException).toHaveBeenCalledWith(jasmine.any(Error)); expect(queueableFn.fn).toHaveBeenCalled(); expect(onComplete).toHaveBeenCalled(); }); it("by default does not set a timeout for asynchronous functions", function() { var beforeFn = { fn: function(done) { } }, queueableFn = { fn: jasmine.createSpy('fn') }, onComplete = jasmine.createSpy('onComplete'), onException = jasmine.createSpy('onException'), queueRunner = new jasmineUnderTest.QueueRunner({ queueableFns: [beforeFn, queueableFn], onComplete: onComplete, onException: onException, }); queueRunner.execute(); expect(queueableFn.fn).not.toHaveBeenCalled(); jasmine.clock().tick(jasmineUnderTest.DEFAULT_TIMEOUT_INTERVAL); expect(onException).not.toHaveBeenCalled(); expect(queueableFn.fn).not.toHaveBeenCalled(); expect(onComplete).not.toHaveBeenCalled(); }); it("clears the timeout when an async function throws an exception, to prevent additional exception reporting", function() { var queueableFn = { fn: function(done) { throw new Error("error!"); } }, onComplete = jasmine.createSpy('onComplete'), onException = jasmine.createSpy('onException'), queueRunner = new jasmineUnderTest.QueueRunner({ queueableFns: [queueableFn], onComplete: onComplete, onException: onException }); queueRunner.execute(); expect(onComplete).toHaveBeenCalled(); expect(onException).toHaveBeenCalled(); jasmine.clock().tick(jasmineUnderTest.DEFAULT_TIMEOUT_INTERVAL); expect(onException.calls.count()).toEqual(1); }); it("clears the timeout when the done callback is called", function() { var queueableFn = { fn: function(done) { done(); } }, onComplete = jasmine.createSpy('onComplete'), onException = jasmine.createSpy('onException'), queueRunner = new jasmineUnderTest.QueueRunner({ queueableFns: [queueableFn], onComplete: onComplete, onException: onException }); queueRunner.execute(); expect(onComplete).toHaveBeenCalled(); jasmine.clock().tick(jasmineUnderTest.DEFAULT_TIMEOUT_INTERVAL); expect(onException).not.toHaveBeenCalled(); }); it("only moves to the next spec the first time you call done", function() { var queueableFn = { fn: function(done) {done(); done();} }, nextQueueableFn = { fn: jasmine.createSpy('nextFn') }; queueRunner = new jasmineUnderTest.QueueRunner({ queueableFns: [queueableFn, nextQueueableFn] }); queueRunner.execute(); expect(nextQueueableFn.fn.calls.count()).toEqual(1); }); it("does not move to the next spec if done is called after an exception has ended the spec", function() { var queueableFn = { fn: function(done) { setTimeout(done, 1); throw new Error('error!'); } }, nextQueueableFn = { fn: jasmine.createSpy('nextFn') }; queueRunner = new jasmineUnderTest.QueueRunner({ queueableFns: [queueableFn, nextQueueableFn] }); queueRunner.execute(); jasmine.clock().tick(1); expect(nextQueueableFn.fn.calls.count()).toEqual(1); }); }); it("calls exception handlers when an exception is thrown in a fn", function() { var queueableFn = { type: 'queueable', fn: function() { throw new Error('fake error'); } }, onExceptionCallback = jasmine.createSpy('on exception callback'), queueRunner = new jasmineUnderTest.QueueRunner({ queueableFns: [queueableFn], onException: onExceptionCallback }); queueRunner.execute(); expect(onExceptionCallback).toHaveBeenCalledWith(jasmine.any(Error)); }); it("rethrows an exception if told to", function() { var queueableFn = { fn: function() { throw new Error('fake error'); } }, queueRunner = new jasmineUnderTest.QueueRunner({ queueableFns: [queueableFn], catchException: function(e) { return false; } }); expect(function() { queueRunner.execute(); }).toThrowError('fake error'); }); it("continues running the functions even after an exception is thrown in an async spec", function() { var queueableFn = { fn: function(done) { throw new Error("error"); } }, nextQueueableFn = { fn: jasmine.createSpy("nextFunction") }, queueRunner = new jasmineUnderTest.QueueRunner({ queueableFns: [queueableFn, nextQueueableFn] }); queueRunner.execute(); expect(nextQueueableFn.fn).toHaveBeenCalled(); }); it("calls a provided complete callback when done", function() { var queueableFn = { fn: jasmine.createSpy('fn') }, completeCallback = jasmine.createSpy('completeCallback'), queueRunner = new jasmineUnderTest.QueueRunner({ queueableFns: [queueableFn], onComplete: completeCallback }); queueRunner.execute(); expect(completeCallback).toHaveBeenCalled(); }); it("calls a provided stack clearing function when done", function() { var asyncFn = { fn: function(done) { done() } }, afterFn = { fn: jasmine.createSpy('afterFn') }, completeCallback = jasmine.createSpy('completeCallback'), clearStack = jasmine.createSpy('clearStack'), queueRunner = new jasmineUnderTest.QueueRunner({ queueableFns: [asyncFn, afterFn], clearStack: clearStack, onComplete: completeCallback }); clearStack.and.callFake(function(fn) { fn(); }); queueRunner.execute(); expect(afterFn.fn).toHaveBeenCalled(); expect(clearStack).toHaveBeenCalledWith(completeCallback); }); });
const model = { filenameBase: 'stop_times', schema: [ { name: 'id', type: 'integer', primary: true, }, { name: 'trip_id', type: 'varchar(255)', required: true, index: true, }, { name: 'arrival_time', type: 'varchar(255)', }, { name: 'arrival_timestamp', type: 'integer', index: true, }, { name: 'departure_time', type: 'varchar(255)', }, { name: 'departure_timestamp', type: 'integer', index: true, }, { name: 'stop_id', type: 'varchar(255)', required: true, }, { name: 'stop_sequence', type: 'integer', required: true, min: 0, index: true, }, { name: 'stop_headsign', type: 'varchar(255)', nocase: true, }, { name: 'pickup_type', type: 'integer', min: 0, max: 3, }, { name: 'drop_off_type', type: 'integer', min: 0, max: 3, }, { name: 'continuous_pickup', type: 'integer', min: 0, max: 3, }, { name: 'continuous_drop_off', type: 'integer', min: 0, max: 3, }, { name: 'shape_dist_traveled', type: 'real', min: 0, }, { name: 'timepoint', type: 'integer', min: 0, max: 1, }, ], }; export default model;
"use strict"; // Gulp dev. var gulp = require('gulp'); var bump = require('gulp-bump'); var inject = require('gulp-inject'); var inlineNg2Template = require('gulp-inline-ng2-template'); var plumber = require('gulp-plumber'); var shell = require('gulp-shell'); var sourcemaps = require('gulp-sourcemaps'); var template = require('gulp-template'); var tsc = require('gulp-typescript'); var watch = require('gulp-watch'); // Gulp prod. // var concat = require('gulp-concat'); // var filter = require('gulp-filter'); // var minifyCSS = require('gulp-minify-css'); // var minifyHTML = require('gulp-minify-html'); // var uglify = require('gulp-uglify'); var Builder = require('systemjs-builder'); var del = require('del'); var fs = require('fs'); var path = require('path'); var join = path.join; var karma = require('karma').server; var runSequence = require('run-sequence'); var semver = require('semver'); var series = require('stream-series'); var express = require('express'); var serveStatic = require('serve-static'); var openResource = require('open'); var ghPages = require('gulp-gh-pages'); var tinylr = require('tiny-lr')(); var connectLivereload = require('connect-livereload'); // -------------- // Configuration. var PORT = 5555; var LIVE_RELOAD_PORT = 4002; var APP_BASE = '/'; var APP_SRC = 'app'; var APP_DEST = 'dist'; var ANGULAR_BUNDLES = './node_modules/angular2/bundles/'; var PATH = { dest: { all: APP_DEST, dev: { all: APP_DEST + '/dev', lib: APP_DEST + '/dev/lib' }, prod: { all: APP_DEST + '/prod', lib: APP_DEST + '/prod/lib' } }, src: { all: APP_SRC, lib: [ // Order is quite important here for the HTML tag injection. './node_modules/angular2/node_modules/traceur/bin/traceur-runtime.js', './node_modules/es6-module-loader/dist/es6-module-loader-sans-promises.js', './node_modules/es6-module-loader/dist/es6-module-loader-sans-promises.js.map', './node_modules/reflect-metadata/Reflect.js', './node_modules/reflect-metadata/Reflect.js.map', './node_modules/systemjs/dist/system.src.js', APP_SRC + '/system.config.js', ANGULAR_BUNDLES + '/angular2.dev.js', ANGULAR_BUNDLES + '/router.dev.js', ANGULAR_BUNDLES + '/http.dev.js' ] } }; var HTMLMinifierOpts = { conditionals: true }; var tsProject = tsc.createProject('tsconfig.json', { typescript: require('typescript') }); var semverReleases = ['major', 'premajor', 'minor', 'preminor', 'patch', 'prepatch', 'prerelease']; // -------------- // Clean. gulp.task('clean', function (done) { del(PATH.dest.all, done); }); gulp.task('clean.dev', function (done) { del(PATH.dest.dev.all, done); }); gulp.task('clean.app.dev', function (done) { del([join(PATH.dest.dev.all, '**/*'), '!' + PATH.dest.dev.lib, '!' + join(PATH.dest.dev.lib, '*')], done); }); gulp.task('clean.test', function(done) { del('test', done); }); gulp.task('clean.tsd_typings', function(done) { del('tsd_typings', done); }); // -------------- // Build dev. gulp.task('build.lib.dev', function () { return gulp.src(PATH.src.lib) .pipe(gulp.dest(PATH.dest.dev.lib)); }); gulp.task('build.js.dev', function () { var result = gulp.src([join(PATH.src.all, '**/*ts'), '!' + join(PATH.src.all, '**/*_spec.ts')]) .pipe(plumber()) .pipe(sourcemaps.init()) .pipe(inlineNg2Template({ base: 'app' })) .pipe(tsc(tsProject)); return result.js .pipe(sourcemaps.write()) .pipe(template(templateLocals())) .pipe(gulp.dest(PATH.dest.dev.all)); }); gulp.task('build.assets.dev', ['build.js.dev'], function () { return gulp.src([join(PATH.src.all, '**/*.html'), join(PATH.src.all, '**/*.css')]) .pipe(gulp.dest(PATH.dest.dev.all)); }); gulp.task('build.index.dev', function () { var target = gulp.src(injectableDevAssetsRef(), { read: false }); return gulp.src(join(PATH.src.all, 'index.html')) .pipe(inject(target, { transform: transformPath('dev') })) .pipe(template(templateLocals())) .pipe(gulp.dest(PATH.dest.dev.all)); }); gulp.task('build.app.dev', function (done) { runSequence('clean.app.dev', 'build.assets.dev', 'build.index.dev', done); }); gulp.task('build.dev', function (done) { runSequence('clean.dev', 'build.lib.dev', 'build.app.dev', done); }); // -------------- // Build prod. // To be implemented (https://github.com/mgechev/angular2-seed/issues/58) // -------------- // Post install gulp.task('install.typings', ['clean.tsd_typings'], shell.task([ './node_modules/.bin/tsd reinstall --overwrite', './node_modules/.bin/tsd link', './node_modules/.bin/tsd rebundle' ])); gulp.task('postinstall', function (done) { runSequence('install.typings', done); }); // -------------- // Version. registerBumpTasks(); gulp.task('bump.reset', function () { return gulp.src('package.json') .pipe(bump({version: '0.0.0'})) .pipe(gulp.dest('./')); }); // -------------- // Test. gulp.task('build.test', function() { var result = gulp.src(['./app/**/*.ts', '!./app/init.ts']) .pipe(plumber()) .pipe(inlineNg2Template({ base: 'app' })) .pipe(tsc(tsProject)); return result.js .pipe(gulp.dest('./test')); }); gulp.task('karma.start', ['build.test'], function(done) { karma.start({ configFile: join(__dirname, 'karma.conf.js'), singleRun: true }, done); }); gulp.task('test-dev', ['build.test'], function() { watch('./app/**', function() { gulp.start('build.test'); }); }); gulp.task('test', ['karma.start'], function() { watch('./app/**', function() { gulp.start('karma.start'); }); }); // -------------- // Serve dev. gulp.task('serve.dev', ['build.dev', 'livereload'], function () { watch(join(PATH.src.all, '**'), function (e) { runSequence('build.app.dev', function () { notifyLiveReload(e); }); }); serveSPA('dev'); }); // -------------- // Serve prod. gulp.task('serve.prod', ['build.prod', 'livereload'], function () { watch(join(PATH.src.all, '**'), function (e) { runSequence('build.app.prod', function () { notifyLiveReload(e); }); }); serveSPA('prod'); }); // -------------- // Livereload. gulp.task('livereload', function () { tinylr.listen(LIVE_RELOAD_PORT); }); // -------------- // Deploy gulp.task('deploy', function() { return gulp.src('./dist/dev/**/*') .pipe(ghPages()); }); // -------------- // Utils. function notifyLiveReload(e) { var fileName = e.path; tinylr.changed({ body: { files: [fileName] } }); } function transformPath(env) { var v = '?v=' + getVersion(); return function (filepath) { var filename = filepath.replace('/' + PATH.dest[env].all, '') + v; arguments[0] = join(APP_BASE, filename); return inject.transform.apply(inject.transform, arguments); }; } function injectableDevAssetsRef() { var src = PATH.src.lib.map(function (path) { return join(PATH.dest.dev.lib, path.split('/').pop()); }); return src; } function getVersion() { var pkg = JSON.parse(fs.readFileSync('package.json')); return pkg.version; } function templateLocals() { return { VERSION: getVersion(), APP_BASE: APP_BASE }; } function registerBumpTasks() { semverReleases.forEach(function (release) { var semverTaskName = 'semver.' + release; var bumpTaskName = 'bump.' + release; gulp.task(semverTaskName, function () { var version = semver.inc(getVersion(), release); return gulp.src('package.json') .pipe(bump({version: version})) .pipe(gulp.dest('./')); }); gulp.task(bumpTaskName, function (done) { runSequence(semverTaskName, 'build.app.prod', done); }); }); } function serveSPA(env) { var app; app = express().use(APP_BASE, connectLivereload({ port: LIVE_RELOAD_PORT }), serveStatic(join(__dirname, PATH.dest[env].all))); app.all(APP_BASE + '*', function (req, res) { res.sendFile(join(__dirname, PATH.dest[env].all, 'index.html')); }); app.listen(PORT, function () { openResource('http://localhost:' + PORT + APP_BASE); }); }
import React from 'react'; import snakeCase from 'lodash/snakeCase'; import './CheckboxList.css'; export default ({ id, title, list = {}, onChange = () => {} }) => ( <article styleName="checkboxList"> <fieldset> <legend>{title}</legend> {Object.keys(list).map((value, i) => ( <div key={`${id}.${i}`}> <input type="checkbox" name={id} id={snakeCase(value)} defaultValue={value} checked={list[value]} onChange={onChange} /> <label htmlFor={snakeCase(value)}>{value}</label> </div> ))} </fieldset> </article> );
var shared = function(config) { config.set({ basePath: '../', frameworks: ['mocha'], reporters: ['progress'], browsers: ['Chrome'], autoWatch: true, // these are default values anyway singleRun: false, colors: true, }); }; shared.files = [ 'test/mocha.conf.js', //3rd Party Code 'components/angularjs/index.js', 'components/lodash/dist/lodash.js', 'components/backbone/backbone.js', //App-specific Code 'app/angular-backbone-bindings.js', 'app/app.js', //Test-Specific Code 'node_modules/chai/chai.js', 'test/lib/chai-should.js', 'test/lib/chai-expect.js' ]; module.exports = shared;
require("/specs/spec_helper"); Screw.Unit(function() { describe("A failing spec", function() { it("fails", function() { expect(true).to(equal, false); }) }); });
var gulp = require('gulp'); var less = require('gulp-less'); var header = require('gulp-header'); var cleanCSS = require('gulp-clean-css'); var rename = require("gulp-rename"); var uglify = require('gulp-uglify'); var concat = require('gulp-concat'); const image = require('gulp-image'); var ngAnnotate = require('gulp-ng-annotate'); var pkg = require('./package.json'); // Set the banner content var banner = ['/*!\n', ' * Oboy Web Application - <%= pkg.title %> v<%= pkg.version %> (<%= pkg.homepage %>)\n', ' * Copyright 2017-' + (new Date()).getFullYear(), ' <%= pkg.author %>\n', ' * Licensed under <%= pkg.license.type %> (<%= pkg.license.url %>)\n', ' */\n', '' ].join(''); // Compile LESS files from /less into /css gulp.task('less', function() { return gulp.src('assets/less/styles.less') .pipe(less()) .pipe(header(banner, { pkg: pkg })) .pipe(gulp.dest('assets/css')) }); // Minify compiled CSS gulp.task('minify-css', ['less'], function() { return gulp.src('assets/css/styles.css') .pipe(cleanCSS({ compatibility: 'ie8' })) .pipe(rename({ suffix: '.min' })) .pipe(gulp.dest('assets/css')) }); gulp.task('minify-vendor-css', ['copy'], function() { return gulp.src('assets/vendor/angular-ui-bootstrap/*.css') .pipe(cleanCSS({ compatibility: 'ie8' })) .pipe(rename({ suffix: '.min' })) .pipe(gulp.dest('assets/vendor/angular-ui-bootstrap/')) }); // Concat Angular Files gulp.task('concat', function() { return gulp.src(['app/*module.js','app/*.js','app/*/*module.js','app/*/*.js']) .pipe(concat('oboy-app.js')) .pipe(gulp.dest('assets/vendor/oboy-app')); }); // Minify Concat Angular JS gulp.task('minify-js', ['concat'], function() { return gulp.src(['assets/vendor/oboy-app/oboy-app.js']) .pipe(ngAnnotate()) .pipe(uglify()) .pipe(header(banner, { pkg: pkg })) .pipe(rename({ suffix: '.min' })) .pipe(gulp.dest('assets/vendor/oboy-app')) }); // Minify Additional JS gulp.task('minify-ext-js', function() { return gulp.src(['assets/js/*.js']) .pipe(ngAnnotate()) .pipe(uglify()) .pipe(header(banner, { pkg: pkg })) .pipe(rename({ suffix: '.min' })) .pipe(gulp.dest('assets/vendor/oboy-app')) }); gulp.task('optimize-images', function () { gulp.src('assets/img/*') .pipe(image()) .pipe(gulp.dest('dist/img')); gulp.src('assets/img/icons/*') .pipe(image()) .pipe(gulp.dest('dist/img/icons')); }); // gulp.task('minify-vendor-js',['copy'], function() { // return gulp.src(['assets/vendor/angular-ui-bootstrap/*.js']) // .pipe(ngAnnotate()) // .pipe(uglify()) // .pipe(header(banner, { pkg: pkg })) // .pipe(rename({ suffix: '.min' })) // .pipe(gulp.dest('assets/vendor/angular-ui-bootstrap')) // }); // Copy vendor libraries from /node_modules into /vendor gulp.task('copy', function() { gulp.src(['node_modules/bootstrap/dist/**/*', '!**/npm.js', '!**/bootstrap-theme.*', '!**/*.map']) .pipe(gulp.dest('assets/vendor/bootstrap')) gulp.src(['node_modules/jquery/dist/jquery.js', 'node_modules/jquery/dist/jquery.min.js']) .pipe(gulp.dest('assets/vendor/jquery')) gulp.src(['node_modules/angular/angular.min.js','node_modules/angular-route/angular-route.min.js' ]) .pipe(gulp.dest('assets/vendor/angular')) gulp.src(['node_modules/angular-ui-bootstrap/dist/*']) .pipe(gulp.dest('assets/vendor/angular-ui-bootstrap')) // gulp.src(['node_modules/angular-ui-bootstrap/dist/ui-bootstrap-csp.css']) // .pipe(gulp.dest('assets/css/angular-ui-bootstrap')) gulp.src(['node_modules/angular-local-storage/dist/*', '!**/*.map']) .pipe(gulp.dest('assets/vendor/angular-local-storage')) gulp.src(['node_modules/angular-animate/*', '!**/*.map']) .pipe(gulp.dest('assets/vendor/angular-animate')) gulp.src(['node_modules/angular-sanitize/*', '!**/*.map']) .pipe(gulp.dest('assets/vendor/angular-sanitize')) gulp.src(['node_modules/ngmap/build/scripts/*', '!**/*.map']) .pipe(gulp.dest('assets/vendor/ngmap')) gulp.src([ 'node_modules/font-awesome/**', '!node_modules/font-awesome/**/*.map', '!node_modules/font-awesome/.npmignore', '!node_modules/font-awesome/*.txt', '!node_modules/font-awesome/*.md', '!node_modules/font-awesome/*.json' ]) .pipe(gulp.dest('assets/vendor/font-awesome')) }) // Run everything gulp.task('default', ['less', 'minify-css', 'concat', 'minify-js','minify-ext-js','copy']); // Run everything and optimize images gulp.task('setup', ['less', 'minify-css', 'concat', 'minify-js','minify-ext-js','copy','optimize-images']); // Dev task with browserSync gulp.task('dev', ['less', 'minify-css', 'concat', 'minify-js','minify-ext-js'], function() { gulp.watch('app/*.js', ['concat','minify-js']); gulp.watch('app/*/*.js', ['concat','minify-js']); gulp.watch('app/*/*/*.js', ['concat','minify-js']); gulp.watch('assets/less/*.less', ['less']); gulp.watch('assets/css/*.css', ['minify-css']); gulp.watch('assets/js/*.js', ['minify-ext-js']); gulp.watch('assets/img/', ['optimize-images']); });
import {partitionObject, partitionArray} from './partition' import {_isArray} from './_internals/_isArray' export function partitionIndexed(predicate, iterable) { if (arguments.length === 1) { return listHolder => partitionIndexed(predicate, listHolder) } if (!_isArray(iterable)) return partitionObject(predicate, iterable) return partitionArray(predicate, iterable, true) }
/** * Copyright 2012-2019, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; module.exports = { moduleType: 'locale', name: 'nl', dictionary: {}, format: { days: [ 'zondag', 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag' ], shortDays: ['zon', 'maa', 'din', 'woe', 'don', 'vri', 'zat'], months: [ 'januari', 'februari', 'maart', 'april', 'mei', 'juni', 'juli', 'augustus', 'september', 'oktober', 'november', 'december' ], shortMonths: [ 'jan', 'feb', 'maa', 'apr', 'mei', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec' ], date: '%d-%m-%Y' } };
import clazz from './class'; import test from './test'; import { toClassName, writeFile } from './utils'; let chalk = require('chalk'); let fs = require('fs'); export default function(namespace, name) { console.log(`${chalk.red('[BETA]')} ctrl(${name})`); clazz(namespace, `${name}-ctrl`, [], 'constructor() { }'); };
const _ = require('lodash'); const crypto = require('crypto'); const base32 = require('thirty-two'); const mail = require('../../email'); const models = require('../../models'); const User = models.User; const InviteCode = models.InviteCode; module.exports = { add: add, del: del, }; function updateInvite(invite, collaboration, done) { const found = _.find(invite.collaborations, function (c) { return c.project === collaboration.project; }); // There is already an outstanding invite to this user, just push these additional perms onto the collaborations // list and send another email. We only push if they have not already been added to the invite. if (!found) { invite.updateMany({ $push: { collaborations: collaboration } }, function (err) { if (err) return done(err); // Invite updated, should probably send another email to recipient. return done(null, false, false); }); } else { return done(null, false, true); } } function sendInvite(inviter, email, collaboration, done) { const random = crypto.randomBytes(5).toString('hex'); const invite_code = base32.encode(random); const invite = new InviteCode({ code: invite_code, emailed_to: email, created_timestamp: new Date(), collaborations: [collaboration], }); invite.save(function (err) { if (err) return done(err); // Invite created, send email to recipient. mail.sendInviteCollaboratorNewUser(inviter, email, invite_code, collaboration.project); return done(null, false, false); }); } // done(err, userExisted, inviteExisted) function add(project, email, accessLevel, inviter, done) { User.findOne({ email: email }, function (err, user) { if (err) { return done(err); } if (user) { const p = _.find(user.projects, function (p) { return p.name === project.toLowerCase(); }); if (p) { return done('user already a collaborator', true); } User.updateOne({ email: email }, { $push: { projects: { name: project.toLowerCase(), display_name: project, access_level: accessLevel, }, }, }, function (err) { if (err) return done(err, true); done(null, true); }); } else { const collaboration = { project: project, invited_by: inviter._id, access_level: accessLevel, }; InviteCode.findOne({ emailed_to: email, consumed_timestamp: null }, function (err, invite) { if (err) return done(err); if (invite) { return updateInvite(invite, collaboration, done); } sendInvite(inviter, email, collaboration, done); }); } }); } function del(project, email, done) { User.updateOne({ email: email, 'projects.name': project.toLowerCase() }, { $pull: { projects: { name: project.toLowerCase() } } }, done); } //# sourceMappingURL=api.js.map
import Page from '../components/Page' import Script from 'next/script' import * as snippet from '@segment/snippet' // This write key is associated with https://segment.com/nextjs-example/sources/nextjs. const DEFAULT_WRITE_KEY = 'NPsk1GimHq09s7egCUlv7D0tqtUAU5wa' function renderSnippet() { const opts = { apiKey: process.env.NEXT_PUBLIC_ANALYTICS_WRITE_KEY || DEFAULT_WRITE_KEY, // note: the page option only covers SSR tracking. // Page.js is used to track other events using `window.analytics.page()` page: true, } if (process.env.NODE_ENV === 'development') { return snippet.max(opts) } return snippet.min(opts) } function MyApp({ Component, pageProps }) { return ( <Page> {/* Inject the Segment snippet into the <head> of the document */} <Script dangerouslySetInnerHTML={{ __html: renderSnippet() }} /> <Component {...pageProps} /> </Page> ) } export default MyApp
import Regl from 'regl' import mat4 from 'gl-mat4' import vec4 from 'gl-vec4' import goatRock from '../assets/points.xyz' const regl = Regl() const drawPointCloud = ({ positions, color }) => { return regl({ vert: ` precision highp float; attribute vec3 position; uniform mat4 view, projection; void main() { gl_PointSize = 1.0; gl_Position = projection * view * vec4(position, 1.0); } `, frag: ` precision mediump float; uniform vec4 color; void main() { gl_FragColor = color; } `, attributes: { position: positions }, uniforms: { color, view: mat4.lookAt([], [0, 120, 70], [0, 0, 0], [0, 0.3, 0.7]), projection: ({viewportWidth, viewportHeight}) => mat4.perspective([], Math.PI / 4, viewportWidth / viewportHeight, 0.01, 1000) }, count: positions.length, primitive: 'points' }) } const parseXyz = (xyzStr) => xyzStr.split('\n').filter((line) => line !== '') .map((line) => line.split(',').map(Number.parseFloat).map(x => x)) const randColor = () => Math.random() * 0.2 + 0.4 const goatRockPoints = parseXyz(goatRock) const xs = goatRockPoints.map((coord) => coord[0]) const ys = goatRockPoints.map((coord) => coord[1]) const zs = goatRockPoints.map((coord) => coord[2]) const minX = xs.reduce((min, x) => Math.min(min, x), Infinity) const maxX = xs.reduce((max, x) => Math.max(max, x), -Infinity) const minY = ys.reduce((min, y) => Math.min(min, y), Infinity) const maxY = ys.reduce((max, y) => Math.max(max, y), - Infinity) const minZ = zs.reduce((min, z) => Math.min(min, z), Infinity) const maxZ = zs.reduce((max, z) => Math.max(max, z), -Infinity) const center = [(minX + maxX) / 2, (minY + maxY) / 2, (minZ + maxZ) / 2] const centered = goatRockPoints.map(([x, y, z]) => { const cx = x - center[0] const cy = y - center[1] const cz = z - center[2] return [cx, cy, cz] }) console.log(centered) const pointCloud = { positions: centered, color: [1, 0.98, 0.88, 1] } regl.frame(() => { regl.clear({ color: [0.22, 0.11, 0.47, 1] }) drawPointCloud(pointCloud)() })