From 3ebcc9cbc41732da981aa7a2ce7047faa502ae88 Mon Sep 17 00:00:00 2001 From: cdujeu Date: Mon, 4 May 2015 10:03:56 +0200 Subject: [PATCH] IE8 Support: - TODO: For the moment, disable the protolegacy stuff (drop IE7 support)? - TODO: Add es5 shim & es5 sham. To be detected based on user agent? - Strict usage of window.console, not just console. --- .../gui.ajax/class.AJXP_ClientDriver.php | 3 +- .../gui.ajax/res/js/ajaxplorer_boot_list.txt | 3 + .../js/ajaxplorer_boot_protolegacy_list.txt | 5 +- .../gui.ajax/res/js/ajaxplorer_list.txt | 1 - .../src/plugins/gui.ajax/res/js/core/Pydio.js | 835 +++++----- .../gui.ajax/res/js/core/http/PydioApi.js | 752 +++++---- .../res/js/core/http/ResourcesManager.js | 756 ++++----- .../gui.ajax/res/js/core/lang/Logger.js | 29 +- .../gui.ajax/res/js/core/lang/Observable.js | 93 +- .../gui.ajax/res/js/core/model/Action.js | 1229 +++++++-------- .../gui.ajax/res/js/core/model/AjxpNode.js | 817 +++++----- .../js/core/model/BackgroundTasksManager.js | 268 ++-- .../gui.ajax/res/js/core/model/Controller.js | 934 ++++++----- .../res/js/core/model/EmptyNodeProvider.js | 39 +- .../res/js/core/model/PydioDataModel.js | 1379 ++++++++--------- .../gui.ajax/res/js/core/model/Registry.js | 536 ++++--- .../res/js/core/model/RemoteNodeProvider.js | 453 +++--- .../gui.ajax/res/js/core/model/Repository.js | 340 ++-- .../gui.ajax/res/js/core/model/User.js | 486 +++--- .../gui.ajax/res/js/core/util/HasherUtils.js | 708 ++++----- .../gui.ajax/res/js/core/util/LangUtils.js | 75 +- .../gui.ajax/res/js/core/util/PathUtils.js | 152 +- .../gui.ajax/res/js/core/util/XMLUtils.js | 312 ++-- .../src/plugins/gui.ajax/res/js/es6/Pydio.es6 | 2 + .../gui.ajax/res/js/es6/lang/Logger.es6 | 6 +- .../gui.ajax/res/js/es6/model/Controller.es6 | 4 +- .../gui.ajax/res/js/es6/model/User.es6 | 4 +- .../js/ui/prototype/class.AjxpBootstrap.js | 8 +- .../res/js/ui/prototype/class.FilesList.js | 2 +- .../res/js/ui/prototype/class.InfoPanel.js | 2 +- .../res/js/ui/prototype/class.PydioUI.js | 4 +- .../res/js/vendor/es6/browser-polyfill.js | 7 +- .../res/js/vendor/es6/es5-sham.min.js | 7 + .../res/js/vendor/es6/es5-shim.min.js | 7 + .../res/js/vendor/prototype/prototype.js | 2 +- .../gui.ajax/res/js/vendor/webfx/xtree.js | 2 +- 36 files changed, 4923 insertions(+), 5339 deletions(-) create mode 100644 core/src/plugins/gui.ajax/res/js/vendor/es6/es5-sham.min.js create mode 100644 core/src/plugins/gui.ajax/res/js/vendor/es6/es5-shim.min.js diff --git a/core/src/plugins/gui.ajax/class.AJXP_ClientDriver.php b/core/src/plugins/gui.ajax/class.AJXP_ClientDriver.php index 7158ec1809..353ee9a93b 100644 --- a/core/src/plugins/gui.ajax/class.AJXP_ClientDriver.php +++ b/core/src/plugins/gui.ajax/class.AJXP_ClientDriver.php @@ -232,7 +232,8 @@ public function switchAction($action, $httpVars, $fileVars) $content = file_get_contents(AJXP_INSTALL_PATH."/plugins/gui.ajax/res/html/gui.html"); } if (preg_match('/MSIE 7/',$_SERVER['HTTP_USER_AGENT']) || preg_match('/MSIE 8/',$_SERVER['HTTP_USER_AGENT'])) { - $content = str_replace("ajaxplorer_boot.js", "ajaxplorer_boot_protolegacy.js", $content); + // TODO: OFFICIALLY DROP IE7 SUPPORT? + //$content = str_replace("ajaxplorer_boot.js", "ajaxplorer_boot_protolegacy.js", $content); } $content = str_replace("AJXP_ADDITIONAL_JS_FRAMEWORKS", $ADDITIONAL_FRAMEWORKS, $content); $content = AJXP_XMLWriter::replaceAjxpXmlKeywords($content, false); diff --git a/core/src/plugins/gui.ajax/res/js/ajaxplorer_boot_list.txt b/core/src/plugins/gui.ajax/res/js/ajaxplorer_boot_list.txt index 863f051abd..55cee8b925 100644 --- a/core/src/plugins/gui.ajax/res/js/ajaxplorer_boot_list.txt +++ b/core/src/plugins/gui.ajax/res/js/ajaxplorer_boot_list.txt @@ -1,3 +1,6 @@ +js/vendor/es6/es5-shim.min.js +js/vendor/es6/es5-sham.min.js +js/vendor/es6/browser-polyfill.js js/vendor/prototype/prototype.js js/vendor/prototype/prototype.livepipe.js js/vendor/prototype/prototype.oo.js diff --git a/core/src/plugins/gui.ajax/res/js/ajaxplorer_boot_protolegacy_list.txt b/core/src/plugins/gui.ajax/res/js/ajaxplorer_boot_protolegacy_list.txt index 0cfcc43a7d..bba14f1eab 100644 --- a/core/src/plugins/gui.ajax/res/js/ajaxplorer_boot_protolegacy_list.txt +++ b/core/src/plugins/gui.ajax/res/js/ajaxplorer_boot_protolegacy_list.txt @@ -1,3 +1,6 @@ +js/vendor/es6/es5-shim.min.js +js/vendor/es6/es5-sham.min.js +js/vendor/es6/browser-polyfill.js js/vendor/prototype/prototype-1.6.js js/vendor/prototype/prototype.livepipe.js js/vendor/prototype/prototype.oo.js @@ -6,4 +9,4 @@ js/vendor/prototype/jsProgressBarHandler.js js/ui/prototype/http/class.Connexion.js js/core/util/HasherUtils.js js/ui/prototype/util/ajxp_utils.js -js/ui/prototype/class.AjxpBootstrap.js +js/ui/prototype/class.AjxpBootstrap.js \ No newline at end of file diff --git a/core/src/plugins/gui.ajax/res/js/ajaxplorer_list.txt b/core/src/plugins/gui.ajax/res/js/ajaxplorer_list.txt index eb7393ecbc..4f2ce08727 100644 --- a/core/src/plugins/gui.ajax/res/js/ajaxplorer_list.txt +++ b/core/src/plugins/gui.ajax/res/js/ajaxplorer_list.txt @@ -1,4 +1,3 @@ -js/vendor/es6/browser-polyfill.js js/core/lang/Observable.js js/core/lang/Logger.js js/core/util/LangUtils.js diff --git a/core/src/plugins/gui.ajax/res/js/core/Pydio.js b/core/src/plugins/gui.ajax/res/js/core/Pydio.js index 1001b0db75..8e76f0aea7 100644 --- a/core/src/plugins/gui.ajax/res/js/core/Pydio.js +++ b/core/src/plugins/gui.ajax/res/js/core/Pydio.js @@ -2,10 +2,6 @@ var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; -var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - -var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; - var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; var Pydio = (function (_Observable) { @@ -18,7 +14,7 @@ var Pydio = (function (_Observable) { function Pydio(parameters) { _classCallCheck(this, Pydio); - _get(Object.getPrototypeOf(Pydio.prototype), 'constructor', this).call(this); + _Observable.call(this); this.Parameters = parameters; this._initLoadRep = parameters.get('initLoadRep') || null; this.usersEnabled = parameters.get('usersEnabled') || null; @@ -42,473 +38,452 @@ var Pydio = (function (_Observable) { _inherits(Pydio, _Observable); - _createClass(Pydio, [{ - key: 'fire', - value: function fire(eventName, data) { - this.notify(eventName, data); - // Backward compatibility - if (document.fire) { - document.fire('ajaxplorer:' + eventName, data); - } + Pydio.prototype.fire = function fire(eventName, data) { + this.notify(eventName, data); + // Backward compatibility + if (document.fire) { + document.fire('ajaxplorer:' + eventName, data); } - }, { - key: 'init', - - /** - * Real initialisation sequence. Will Trigger the whole GUI building. - * Event ajaxplorer:loaded is fired at the end. - */ - value: function init() { - if (!this.Parameters.has('SECURE_TOKEN')) { - PydioApi.getClient().getBootConf((function () { - this.init(); - }).bind(this)); - return; - } + }; - if (window.PydioUI) { - this.UI = new PydioUI(this); - } else { - // FAKE CLASSE - this.UI = { - guiLoaded: true, - modal: { - setLoadingStepCounts: function setLoadingStepCounts() {}, - refreshDialogAppearance: function refreshDialogAppearance() {}, - displayMessage: function displayMessage() {}, - initForms: function initForms() {}, - updateLoadingProgress: function updateLoadingProgress(progress) { - Logger.log(progress); - }, - prepareHeader: function prepareHeader() {}, - showModalDialog: function showModalDialog() {} + /** + * Real initialisation sequence. Will Trigger the whole GUI building. + * Event ajaxplorer:loaded is fired at the end. + */ + + Pydio.prototype.init = function init() { + if (!this.Parameters.has('SECURE_TOKEN')) { + PydioApi.getClient().getBootConf((function () { + this.init(); + }).bind(this)); + return; + } + + if (window.PydioUI) { + this.UI = new PydioUI(this); + } else { + // FAKE CLASSE + this.UI = { + guiLoaded: true, + modal: { + setLoadingStepCounts: function setLoadingStepCounts() {}, + refreshDialogAppearance: function refreshDialogAppearance() {}, + displayMessage: function displayMessage() {}, + initForms: function initForms() {}, + updateLoadingProgress: function updateLoadingProgress(progress) { + Logger.log(progress); }, - refreshTemplateParts: function refreshTemplateParts() {}, - initTemplates: function initTemplates() {}, - initObjects: function initObjects() {}, - updateI18nTags: function updateI18nTags() {}, - insertForm: function insertForm(formId, formCode) {}, - removeForm: function removeForm(formId) {} - }; - } + prepareHeader: function prepareHeader() {}, + showModalDialog: function showModalDialog() {} + }, + refreshTemplateParts: function refreshTemplateParts() {}, + initTemplates: function initTemplates() {}, + initObjects: function initObjects() {}, + updateI18nTags: function updateI18nTags() {}, + insertForm: function insertForm(formId, formCode) {}, + removeForm: function removeForm(formId) {} + }; + } - this.observe('registry_loaded', (function () { - this.Controller.loadActionsFromRegistry(this.getXmlRegistry()); + this.observe('registry_loaded', (function () { + // TODO: CAN WE REMOVE THIS? IT IS TRIGGERED TWO TIMES (in PydioUI). + this.Controller.loadActionsFromRegistry(this.getXmlRegistry()); + // END + this.Registry.refreshExtensionsRegistry(); + this.Registry.logXmlUser(false); + if (this.user) { + var repId = this.user.getActiveRepository(); + var repList = this.user.getRepositoriesList(); + var repositoryObject = repList.get(repId); + if (repositoryObject) repositoryObject.loadResources(); + } + if (this.UI.guiLoaded) { + this.UI.refreshTemplateParts(); this.Registry.refreshExtensionsRegistry(); - this.Registry.logXmlUser(false); - if (this.user) { - var repId = this.user.getActiveRepository(); - var repList = this.user.getRepositoriesList(); - var repositoryObject = repList.get(repId); - if (repositoryObject) repositoryObject.loadResources(); - } - if (this.UI.guiLoaded) { + } else { + this.observe('gui_loaded', (function () { this.UI.refreshTemplateParts(); this.Registry.refreshExtensionsRegistry(); - } else { - this.observe('gui_loaded', (function () { - this.UI.refreshTemplateParts(); - this.Registry.refreshExtensionsRegistry(); - }).bind(this)); - } - this.loadActiveRepository(); - if (this.Parameters.has('USER_GUI_ACTION')) { - var a = this.Parameters.get('USER_GUI_ACTION'); - this.Parameters['delete']('USER_GUI_ACTION'); - var aBar = this.Controller; - window.setTimeout(function () { - aBar.fireAction(a); - }, 2000); - } - }).bind(this)); + }).bind(this)); + } + this.loadActiveRepository(); + if (this.Parameters.has('USER_GUI_ACTION')) { + var a = this.Parameters.get('USER_GUI_ACTION'); + this.Parameters['delete']('USER_GUI_ACTION'); + var aBar = this.Controller; + window.setTimeout(function () { + aBar.fireAction(a); + }, 2000); + } + }).bind(this)); - if (this.UI.modal) this.UI.modal.setLoadingStepCounts(5); + if (this.UI.modal) this.UI.modal.setLoadingStepCounts(5); - var starterFunc = (function () { + var starterFunc = (function () { - this.UI.initTemplates(); - if (this.UI.modal) this.UI.modal.initForms(); - this.UI.initObjects(); + this.UI.initTemplates(); + if (this.UI.modal) this.UI.modal.initForms(); + this.UI.initObjects(); - this.tryLogUserFromCookie(); - this.fire('registry_loaded', this.Registry.getXML()); + this.tryLogUserFromCookie(); + this.fire('registry_loaded', this.Registry.getXML()); - window.setTimeout((function () { - this.fire('loaded'); - }).bind(this), 200); + window.setTimeout((function () { + this.fire('loaded'); + }).bind(this), 200); - this.Router = new Router(this); - }).bind(this); + this.Router = new Router(this); + }).bind(this); - if (this.Parameters.get('PRELOADED_REGISTRY')) { - this.Registry.loadFromString(this.Parameters.get('PRELOADED_REGISTRY')); - this.Parameters['delete']('PRELOADED_REGISTRY'); - if (this.UI.modal) this.UI.modal.updateLoadingProgress('XML Registry loaded'); - starterFunc(); - } else { - this.loadXmlRegistry(false, null, starterFunc); - } - this.observe('server_message', (function (xml) { - if (XMLUtils.XPathSelectSingleNode(xml, 'tree/require_registry_reload')) { - this.repositoryId = null; - this.loadXmlRegistry(false); - } - }).bind(this)); + if (this.Parameters.get('PRELOADED_REGISTRY')) { + this.Registry.loadFromString(this.Parameters.get('PRELOADED_REGISTRY')); + this.Parameters['delete']('PRELOADED_REGISTRY'); + if (this.UI.modal) this.UI.modal.updateLoadingProgress('XML Registry loaded'); + starterFunc(); + } else { + this.loadXmlRegistry(false, null, starterFunc); } - }, { - key: 'loadXmlRegistry', - - /** - * Loads the XML Registry, an image of the application in its current state - * sent by the server. - * @param sync Boolean Whether to send synchronously or not. - * @param xPath String An XPath to load only a subpart of the registry - */ - value: function loadXmlRegistry(sync) { - var xPath = arguments[1] === undefined ? null : arguments[1]; - var completeFunc = arguments[2] === undefined ? null : arguments[2]; - - this.Registry.load(sync, xPath, completeFunc); - } - }, { - key: 'getXmlRegistry', - - /** - * Get the XML Registry - * @returns Document - */ - value: function getXmlRegistry() { - return this.Registry.getXML(); - } - }, { - key: 'tryLogUserFromCookie', - - /** - * Try reading the cookie and sending it to the server - */ - value: function tryLogUserFromCookie() {} - }, { - key: 'loadActiveRepository', - - /** - * Find the current repository (from the current user) and load it. - */ - value: function loadActiveRepository() { - var repositoryObject = new Repository(null); - if (this.user != null) { - var repId = this.user.getActiveRepository(); - var repList = this.user.getRepositoriesList(); - repositoryObject = repList.get(repId); - if (!repositoryObject) { - if (this.user.lock) { - this.Controller.loadActionsFromRegistry(this.getXmlRegistry()); - window.setTimeout((function () { - this.Controller.fireAction(this.user.lock); - }).bind(this), 50); - return; - } - alert('No active repository found for user!'); - } - if (this.user.getPreference('pending_folder') && this.user.getPreference('pending_folder') != '-1') { - this._initLoadRep = this.user.getPreference('pending_folder'); - this.user.setPreference('pending_folder', '-1'); - this.user.savePreference('pending_folder'); - } else if (this.user.getPreference('ls_history', true)) { - var data = this.user.getPreference('ls_history', true); - this._initLoadRep = data[repId]; + this.observe('server_message', (function (xml) { + if (XMLUtils.XPathSelectSingleNode(xml, 'tree/require_registry_reload')) { + this.repositoryId = null; + this.loadXmlRegistry(false); + } + }).bind(this)); + }; + + /** + * Loads the XML Registry, an image of the application in its current state + * sent by the server. + * @param sync Boolean Whether to send synchronously or not. + * @param xPath String An XPath to load only a subpart of the registry + */ + + Pydio.prototype.loadXmlRegistry = function loadXmlRegistry(sync) { + var xPath = arguments[1] === undefined ? null : arguments[1]; + var completeFunc = arguments[2] === undefined ? null : arguments[2]; + + this.Registry.load(sync, xPath, completeFunc); + }; + + /** + * Get the XML Registry + * @returns Document + */ + + Pydio.prototype.getXmlRegistry = function getXmlRegistry() { + return this.Registry.getXML(); + }; + + /** + * Try reading the cookie and sending it to the server + */ + + Pydio.prototype.tryLogUserFromCookie = function tryLogUserFromCookie() {}; + + /** + * Find the current repository (from the current user) and load it. + */ + + Pydio.prototype.loadActiveRepository = function loadActiveRepository() { + var repositoryObject = new Repository(null); + if (this.user != null) { + var repId = this.user.getActiveRepository(); + var repList = this.user.getRepositoriesList(); + repositoryObject = repList.get(repId); + if (!repositoryObject) { + if (this.user.lock) { + this.Controller.loadActionsFromRegistry(this.getXmlRegistry()); + window.setTimeout((function () { + this.Controller.fireAction(this.user.lock); + }).bind(this), 50); + return; } + alert('No active repository found for user!'); } - this.loadRepository(repositoryObject); - if (repList && repId) { - this.fire('repository_list_refreshed', { list: repList, active: repId }); - } else { - this.fire('repository_list_refreshed', { list: false, active: false }); + if (this.user.getPreference('pending_folder') && this.user.getPreference('pending_folder') != '-1') { + this._initLoadRep = this.user.getPreference('pending_folder'); + this.user.setPreference('pending_folder', '-1'); + this.user.savePreference('pending_folder'); + } else if (this.user.getPreference('ls_history', true)) { + var data = this.user.getPreference('ls_history', true); + this._initLoadRep = data[repId]; } } - }, { - key: 'reloadRepositoriesList', - - /** - * Refresh the repositories list for the current user - */ - value: function reloadRepositoriesList() { - if (!this.user) { - return; - }this.observeOnce('registry_part_loaded', (function (data) { - if (data != 'user/repositories') return; - this.Registry.logXmlUser(true); - document.fire('ajaxplorer:repository_list_refreshed', { - list: this.user.getRepositoriesList(), - active: this.user.getActiveRepository() }); - }).bind(this)); - this.loadXmlRegistry(false, 'user/repositories'); + this.loadRepository(repositoryObject); + if (repList && repId) { + this.fire('repository_list_refreshed', { list: repList, active: repId }); + } else { + this.fire('repository_list_refreshed', { list: false, active: false }); } - }, { - key: 'loadRepository', + }; + + /** + * Refresh the repositories list for the current user + */ - /** - * Load a Repository instance - * @param repository Repository - */ - value: function loadRepository(repository) { + Pydio.prototype.reloadRepositoriesList = function reloadRepositoriesList() { + if (!this.user) { + return; + }this.observeOnce('registry_part_loaded', (function (data) { + if (data != 'user/repositories') return; + this.Registry.logXmlUser(true); + document.fire('ajaxplorer:repository_list_refreshed', { + list: this.user.getRepositoriesList(), + active: this.user.getActiveRepository() }); + }).bind(this)); + this.loadXmlRegistry(false, 'user/repositories'); + }; - if (this.repositoryId != null && this.repositoryId == repository.getId()) { - Logger.debug('Repository already loaded, do nothing'); - } - this._contextHolder.setSelectedNodes([]); - if (repository == null) { - return; - }repository.loadResources(); - var repositoryId = repository.getId(); - var newIcon = repository.getIcon(); + /** + * Load a Repository instance + * @param repository Repository + */ - this.skipLsHistory = true; + Pydio.prototype.loadRepository = function loadRepository(repository) { - var providerDef = repository.getNodeProviderDef(); - var rootNode; - if (providerDef != null) { - var provider = eval('new ' + providerDef.name + '()'); - if (providerDef.options) { - provider.initProvider(providerDef.options); - } - this._contextHolder.setAjxpNodeProvider(provider); - rootNode = new AjxpNode('/', false, repository.getLabel(), newIcon, provider); - } else { - rootNode = new AjxpNode('/', false, repository.getLabel(), newIcon); - // Default - this._contextHolder.setAjxpNodeProvider(new RemoteNodeProvider()); + if (this.repositoryId != null && this.repositoryId == repository.getId()) { + Logger.debug('Repository already loaded, do nothing'); + } + this._contextHolder.setSelectedNodes([]); + if (repository == null) { + return; + }repository.loadResources(); + var repositoryId = repository.getId(); + var newIcon = repository.getIcon(); + + this.skipLsHistory = true; + + var providerDef = repository.getNodeProviderDef(); + var rootNode; + if (providerDef != null) { + var provider = eval('new ' + providerDef.name + '()'); + if (providerDef.options) { + provider.initProvider(providerDef.options); } - this._contextHolder.setRootNode(rootNode); - rootNode.observeOnce('first_load', (function () { - this._contextHolder.notify('context_changed', rootNode); - }).bind(this)); - this.repositoryId = repositoryId; - - if (this._initLoadRep) { - if (this._initLoadRep != '' && this._initLoadRep != '/') { - var copy = this._initLoadRep.valueOf(); - this._initLoadRep = null; - rootNode.observeOnce('first_load', (function () { - setTimeout((function () { - this.goTo(copy); - this.skipLsHistory = false; - }).bind(this), 1000); - }).bind(this)); - } else { - this.skipLsHistory = false; - } + this._contextHolder.setAjxpNodeProvider(provider); + rootNode = new AjxpNode('/', false, repository.getLabel(), newIcon, provider); + } else { + rootNode = new AjxpNode('/', false, repository.getLabel(), newIcon); + // Default + this._contextHolder.setAjxpNodeProvider(new RemoteNodeProvider()); + } + this._contextHolder.setRootNode(rootNode); + rootNode.observeOnce('first_load', (function () { + this._contextHolder.notify('context_changed', rootNode); + }).bind(this)); + this.repositoryId = repositoryId; + + if (this._initLoadRep) { + if (this._initLoadRep != '' && this._initLoadRep != '/') { + var copy = this._initLoadRep.valueOf(); + this._initLoadRep = null; + rootNode.observeOnce('first_load', (function () { + setTimeout((function () { + this.goTo(copy); + this.skipLsHistory = false; + }).bind(this), 1000); + }).bind(this)); } else { this.skipLsHistory = false; } - - rootNode.load(); + } else { + this.skipLsHistory = false; } - }, { - key: 'goTo', - - /** - * Require a context change to the given path - * @param nodeOrPath AjxpNode|String A node or a path - */ - value: function goTo(nodeOrPath) { - var path; - if (typeof nodeOrPath == 'string') { - path = nodeOrPath; - } else { - path = nodeOrPath.getPath(); - if (nodeOrPath.getMetadata().has('repository_id') && nodeOrPath.getMetadata().get('repository_id') != this.repositoryId && nodeOrPath.getAjxpMime() != 'repository' && nodeOrPath.getAjxpMime() != 'repository_editable') { - if (this.user) { - this.user.setPreference('pending_folder', nodeOrPath.getPath()); - } - this.triggerRepositoryChange(nodeOrPath.getMetadata().get('repository_id')); - return; - } - } - var current = this._contextHolder.getContextNode(); - if (current && current.getPath() == path) { - return; - } - var gotoNode; - if (path == '' || path == '/') { - gotoNode = new AjxpNode('/'); - this._contextHolder.requireContextChange(gotoNode); - return; - } - this._contextHolder.loadPathInfoAsync(path, (function (foundNode) { - if (foundNode.isLeaf() && foundNode.getAjxpMime() != 'ajxp_browsable_archive') { - this._contextHolder.setPendingSelection(PathUtils.getBasename(path)); - gotoNode = new AjxpNode(PathUtils.getDirname(path)); - } else { - gotoNode = foundNode; - } - this._contextHolder.requireContextChange(gotoNode); - }).bind(this)); - } - }, { - key: 'triggerRepositoryChange', - - /** - * Change the repository of the current user and reload list and current. - * @param repositoryId String Id of the new repository - */ - value: function triggerRepositoryChange(repositoryId) { - this.fire('trigger_repository_switch'); - var onComplete = (function (transport) { - if (transport.responseXML) { - this.Controller.parseXmlMessage(transport.responseXML); + rootNode.load(); + }; + + /** + * Require a context change to the given path + * @param nodeOrPath AjxpNode|String A node or a path + */ + + Pydio.prototype.goTo = function goTo(nodeOrPath) { + var path; + if (typeof nodeOrPath == 'string') { + path = nodeOrPath; + } else { + path = nodeOrPath.getPath(); + if (nodeOrPath.getMetadata().has('repository_id') && nodeOrPath.getMetadata().get('repository_id') != this.repositoryId && nodeOrPath.getAjxpMime() != 'repository' && nodeOrPath.getAjxpMime() != 'repository_editable') { + if (this.user) { + this.user.setPreference('pending_folder', nodeOrPath.getPath()); } - this.repositoryId = null; - this.loadXmlRegistry(); - }).bind(this); - var root = this._contextHolder.getRootNode(); - if (root) { - this.skipLsHistory = true; - root.clear(); + this.triggerRepositoryChange(nodeOrPath.getMetadata().get('repository_id')); + return; } - this.ApiClient.switchRepository(repositoryId, onComplete); - } - }, { - key: 'getPluginConfigs', - value: function getPluginConfigs(pluginQuery) { - return this.Registry.getPluginConfigs(pluginQuery); } - }, { - key: 'loadI18NMessages', - - /** - * Reload all messages from server and trigger updateI18nTags - * @param newLanguage String - */ - value: function loadI18NMessages(newLanguage) { - var onComplete = (function (transport) { - if (transport.responseJSON) { - this.MessageHash = transport.responseJSON; - for (var key in this.MessageHash) { - if (this.MessageHash.hasOwnProperty(key)) { - this.MessageHash[key] = this.MessageHash[key].replace('\\n', '\n'); - } - } - this.UI.updateI18nTags(); - this.Controller.refreshGuiActionsI18n(); - this.loadXmlRegistry(); - this.fireContextRefresh(); - this.currentLanguage = newLanguage; - } - }).bind(this); - this.ApiClient.switchLanguage(newLanguage, onComplete); - } - }, { - key: 'getController', - - /** - * Get the main controller - * @returns ActionManager - */ - value: function getController() { - return this.Controller; + var current = this._contextHolder.getContextNode(); + if (current && current.getPath() == path) { + return; } - }, { - key: 'displayMessage', - - /** - * Display an information or error message to the user - * @param messageType String ERROR or SUCCESS - * @param message String the message - */ - value: function displayMessage(messageType, message) { - var urls = LangUtils.parseUrl(message); - if (urls.length && this.user && this.user.repositories) { - urls.forEach((function (match) { - var repo = this.user.repositories.get(match.host); - if (!repo) return; - message = message.replace(match.url, repo.label + ':' + match.path + match.file); - }).bind(this)); - } - if (messageType == 'ERROR') Logger.error(message);else Logger.log(message); - if (this.UI.modal) this.UI.modal.displayMessage(messageType, message); + var gotoNode; + if (path == '' || path == '/') { + gotoNode = new AjxpNode('/'); + this._contextHolder.requireContextChange(gotoNode); + return; } - }, { - key: 'updateContextData', - - /************************************************* - * - * PROXY METHODS FOR DATAMODEL - * - ************************************************/ - - /** - * Accessor for updating the datamodel context - * @param ajxpContextNode AjxpNode - * @param ajxpSelectedNodes AjxpNode[] - * @param selectionSource String - */ - value: function updateContextData(ajxpContextNode, ajxpSelectedNodes, selectionSource) { - if (ajxpContextNode) { - this._contextHolder.requireContextChange(ajxpContextNode); + this._contextHolder.loadPathInfoAsync(path, (function (foundNode) { + if (foundNode.isLeaf() && foundNode.getAjxpMime() != 'ajxp_browsable_archive') { + this._contextHolder.setPendingSelection(PathUtils.getBasename(path)); + gotoNode = new AjxpNode(PathUtils.getDirname(path)); + } else { + gotoNode = foundNode; } - if (ajxpSelectedNodes) { - this._contextHolder.setSelectedNodes(ajxpSelectedNodes, selectionSource); + this._contextHolder.requireContextChange(gotoNode); + }).bind(this)); + }; + + /** + * Change the repository of the current user and reload list and current. + * @param repositoryId String Id of the new repository + */ + + Pydio.prototype.triggerRepositoryChange = function triggerRepositoryChange(repositoryId) { + this.fire('trigger_repository_switch'); + var onComplete = (function (transport) { + if (transport.responseXML) { + this.Controller.parseXmlMessage(transport.responseXML); } + this.repositoryId = null; + this.loadXmlRegistry(); + }).bind(this); + var root = this._contextHolder.getRootNode(); + if (root) { + this.skipLsHistory = true; + root.clear(); } - }, { - key: 'getContextHolder', - - /** - * @returns AjxpDataModel - */ - value: function getContextHolder() { - return this._contextHolder; - } - }, { - key: 'getContextNode', - - /** - * @returns AjxpNode - */ - value: function getContextNode() { - return this._contextHolder.getContextNode() || new AjxpNode(''); - } - }, { - key: 'getUserSelection', - - /** - * @returns AjxpDataModel - */ - value: function getUserSelection() { - return this._contextHolder; - } - }, { - key: 'fireContextRefresh', - - /** - * Accessor for datamodel.requireContextChange() - */ - value: function fireContextRefresh() { - this.getContextHolder().requireContextChange(this.getContextNode(), true); + this.ApiClient.switchRepository(repositoryId, onComplete); + }; + + Pydio.prototype.getPluginConfigs = function getPluginConfigs(pluginQuery) { + return this.Registry.getPluginConfigs(pluginQuery); + }; + + /** + * Reload all messages from server and trigger updateI18nTags + * @param newLanguage String + */ + + Pydio.prototype.loadI18NMessages = function loadI18NMessages(newLanguage) { + var onComplete = (function (transport) { + if (transport.responseJSON) { + this.MessageHash = transport.responseJSON; + for (var key in this.MessageHash) { + if (this.MessageHash.hasOwnProperty(key)) { + this.MessageHash[key] = this.MessageHash[key].replace('\\n', '\n'); + } + } + this.UI.updateI18nTags(); + this.Controller.refreshGuiActionsI18n(); + + this.loadXmlRegistry(); + this.fireContextRefresh(); + this.currentLanguage = newLanguage; + } + }).bind(this); + this.ApiClient.switchLanguage(newLanguage, onComplete); + }; + + /** + * Get the main controller + * @returns ActionManager + */ + + Pydio.prototype.getController = function getController() { + return this.Controller; + }; + + /** + * Display an information or error message to the user + * @param messageType String ERROR or SUCCESS + * @param message String the message + */ + + Pydio.prototype.displayMessage = function displayMessage(messageType, message) { + var urls = LangUtils.parseUrl(message); + if (urls.length && this.user && this.user.repositories) { + urls.forEach((function (match) { + var repo = this.user.repositories.get(match.host); + if (!repo) return; + message = message.replace(match.url, repo.label + ':' + match.path + match.file); + }).bind(this)); } - }, { - key: 'fireNodeRefresh', - - /** - * Accessor for datamodel.requireContextChange() - */ - value: function fireNodeRefresh(nodePathOrNode, completeCallback) { - this.getContextHolder().requireNodeReload(nodePathOrNode, completeCallback); + if (messageType == 'ERROR') Logger.error(message);else Logger.log(message); + if (this.UI.modal) this.UI.modal.displayMessage(messageType, message); + }; + + /************************************************* + * + * PROXY METHODS FOR DATAMODEL + * + ************************************************/ + + /** + * Accessor for updating the datamodel context + * @param ajxpContextNode AjxpNode + * @param ajxpSelectedNodes AjxpNode[] + * @param selectionSource String + */ + + Pydio.prototype.updateContextData = function updateContextData(ajxpContextNode, ajxpSelectedNodes, selectionSource) { + if (ajxpContextNode) { + this._contextHolder.requireContextChange(ajxpContextNode); } - }, { - key: 'fireContextUp', - - /** - * Accessor for datamodel.requireContextChange() - */ - value: function fireContextUp() { - if (this.getContextNode().isRoot()) { - return; - }this.updateContextData(this.getContextNode().getParent()); + if (ajxpSelectedNodes) { + this._contextHolder.setSelectedNodes(ajxpSelectedNodes, selectionSource); } - }]); + }; + + /** + * @returns AjxpDataModel + */ + + Pydio.prototype.getContextHolder = function getContextHolder() { + return this._contextHolder; + }; + + /** + * @returns AjxpNode + */ + + Pydio.prototype.getContextNode = function getContextNode() { + return this._contextHolder.getContextNode() || new AjxpNode(''); + }; + + /** + * @returns AjxpDataModel + */ + + Pydio.prototype.getUserSelection = function getUserSelection() { + return this._contextHolder; + }; + + /** + * Accessor for datamodel.requireContextChange() + */ + + Pydio.prototype.fireContextRefresh = function fireContextRefresh() { + this.getContextHolder().requireContextChange(this.getContextNode(), true); + }; + + /** + * Accessor for datamodel.requireContextChange() + */ + + Pydio.prototype.fireNodeRefresh = function fireNodeRefresh(nodePathOrNode, completeCallback) { + this.getContextHolder().requireNodeReload(nodePathOrNode, completeCallback); + }; + + /** + * Accessor for datamodel.requireContextChange() + */ + + Pydio.prototype.fireContextUp = function fireContextUp() { + if (this.getContextNode().isRoot()) { + return; + }this.updateContextData(this.getContextNode().getParent()); + }; return Pydio; })(Observable); diff --git a/core/src/plugins/gui.ajax/res/js/core/http/PydioApi.js b/core/src/plugins/gui.ajax/res/js/core/http/PydioApi.js index bde37d8ee6..3bf84b94e3 100644 --- a/core/src/plugins/gui.ajax/res/js/core/http/PydioApi.js +++ b/core/src/plugins/gui.ajax/res/js/core/http/PydioApi.js @@ -2,8 +2,6 @@ var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; -var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - var PydioApi = (function () { function PydioApi() { _classCallCheck(this, PydioApi); @@ -11,416 +9,398 @@ var PydioApi = (function () { this._secureToken = ''; } - _createClass(PydioApi, [{ - key: 'setPydioObject', - value: function setPydioObject(pydioObject) { - this._pydioObject = pydioObject; - this._baseUrl = pydioObject.Parameters.get('serverAccessPath'); - this._secureToken = pydioObject.Parameters.get('SECURE_TOKEN'); - } - }, { - key: 'setSecureToken', - value: function setSecureToken(token) { - this._secureToken = token; - } - }, { - key: 'request', - value: function request(parameters) { - var onComplete = arguments[1] === undefined ? null : arguments[1]; - var onError = arguments[2] === undefined ? null : arguments[2]; - var settings = arguments[3] === undefined ? {} : arguments[3]; - - parameters.secure_token = this._secureToken; - if (window.Connexion) { - var c = new Connexion(); - c.setParameters($H(parameters)); - if (settings.method) { - c.setMethod(settings.method); - } - c.onComplete = onComplete; - if (settings.async === false) { - c.sendSync(); - } else { - c.sendAsync(); - } - } else if (window.jQuery) { - jQuery.ajax(this._baseUrl, { - method: settings.method || 'post', - data: parameters, - async: settings && settings.async !== undefined ? settings.async : true, - complete: onComplete, - error: onError - }); + PydioApi.prototype.setPydioObject = function setPydioObject(pydioObject) { + this._pydioObject = pydioObject; + this._baseUrl = pydioObject.Parameters.get('serverAccessPath'); + this._secureToken = pydioObject.Parameters.get('SECURE_TOKEN'); + }; + + PydioApi.prototype.setSecureToken = function setSecureToken(token) { + this._secureToken = token; + }; + + PydioApi.prototype.request = function request(parameters) { + var onComplete = arguments[1] === undefined ? null : arguments[1]; + var onError = arguments[2] === undefined ? null : arguments[2]; + var settings = arguments[3] === undefined ? {} : arguments[3]; + + parameters.secure_token = this._secureToken; + if (window.Connexion) { + var c = new Connexion(); + c.setParameters($H(parameters)); + if (settings.method) { + c.setMethod(settings.method); } - } - }, { - key: 'switchRepository', - value: function switchRepository(repositoryId, completeCallback) { - var params = { - get_action: 'switch_repository', - repository_id: repositoryId - }; - this.request(params, completeCallback); - } - }, { - key: 'switchLanguage', - value: function switchLanguage(lang, completeCallback) { - var params = { - get_action: 'get_i18n_messages', - lang: lang, - format: 'json' - }; - this.request(params, completeCallback); - } - }, { - key: 'loadXmlRegistry', - value: function loadXmlRegistry(completeCallback) { - var xPath = arguments[1] === undefined ? null : arguments[1]; - - var params = { get_action: 'get_xml_registry' }; - if (xPath) params[xPath] = xPath; - this.request(params, completeCallback); - } - }, { - key: 'getBootConf', - value: function getBootConf(completeCallback) { - var params = { get_action: 'get_boot_conf' }; - var cB = (function (transport) { - if (transport.responseJSON && transport.responseJSON.SECURE_TOKEN) { - this._pydioObject.Parameters.set('SECURE_TOKEN', transport.responseJSON.SECURE_TOKEN); - this.setSecureToken(transport.responseJSON.SECURE_TOKEN); - } - if (completeCallback) { - completeCallback(transport); - } - }).bind(this); - this.request(params, cB); - } - }, { - key: 'userSavePreference', - value: function userSavePreference(prefName, prefValue) { - var conn = new Connexion(); - conn.setMethod('post'); - conn.discrete = true; - conn.addParameter('get_action', 'save_user_pref'); - conn.addParameter('pref_name_' + 0, prefName); - conn.addParameter('pref_value_' + 0, prefValue); - conn.sendAsync(); - } - }, { - key: 'userSavePreferences', - value: function userSavePreferences(preferences, completeCallback) { - var conn = new Connexion(); - conn.addParameter('get_action', 'save_user_pref'); - var i = 0; - preferences.forEach(function (value, key) { - conn.addParameter('pref_name_' + i, key); - conn.addParameter('pref_value_' + i, value); - i++; + c.onComplete = onComplete; + if (settings.async === false) { + c.sendSync(); + } else { + c.sendAsync(); + } + } else if (window.jQuery) { + jQuery.ajax(this._baseUrl, { + method: settings.method || 'post', + data: parameters, + async: settings && settings.async !== undefined ? settings.async : true, + complete: onComplete, + error: onError }); - conn.onComplete = completeCallback; - conn.sendAsync(); } - }, { - key: 'userSavePassword', - value: function userSavePassword(oldPass, newPass, seed, completeCallback) { - var conn = new Connexion(); - conn.addParameter('get_action', 'save_user_pref'); - conn.addParameter('pref_name_' + i, 'password'); - conn.addParameter('pref_value_' + i, newPass); - conn.addParameter('crt', oldPass); - conn.addParameter('pass_seed', seed); - conn.onComplete = completeCallback; - conn.sendAsync(); + }; + + PydioApi.getClient = function getClient() { + if (PydioApi._PydioClient) { + return PydioApi._PydioClient; + }var client = new PydioApi(); + PydioApi._PydioClient = client; + return client; + }; + + /** + * Load a javascript library + * @param fileName String + * @param onLoadedCode Function Callback + * @param aSync Boolean load library asynchroneously + * @todo : We should use Require or equivalent instead. + */ + + PydioApi.loadLibrary = function loadLibrary(fileName, onLoadedCode, aSync) { + if (window.pydio && pydio.Parameters.get('ajxpVersion') && fileName.indexOf('?') == -1) { + fileName += '?v=' + pydio.Parameters.get('ajxpVersion'); } - }, { - key: 'applyCheckHook', - value: function applyCheckHook(node, hookName, hookArg, completeCallback) { - var params = { - get_action: 'apply_check_hook', - file: node.getPath(), - hook_name: hookName, - hook_arg: hookArg - }; - this.request(params, completeCallback, null, { async: false }); + PydioApi._libUrl = false; + if (window.pydio && pydio.Parameters.get('SERVER_PREFIX_URI')) { + PydioApi._libUrl = pydio.Parameters.get('SERVER_PREFIX_URI'); } - }, { - key: 'parseXmlMessage', - - /** - * Standard parser for server XML answers - * @param xmlResponse DOMDocument - */ - value: function parseXmlMessage(xmlResponse) { - if (xmlResponse == null || xmlResponse.documentElement == null) { - return null; - }var childs = xmlResponse.documentElement.childNodes; - - var reloadNodes = []; - var error = false; - this.LAST_ERROR_ID = null; - - for (var i = 0; i < childs.length; i++) { - if (childs[i].tagName == 'message') { - var messageTxt = 'No message'; - if (childs[i].firstChild) messageTxt = childs[i].firstChild.nodeValue; - if (childs[i].getAttribute('type') == 'ERROR') { - Logger.error(messageTxt); - error = true; - } else { - Logger.log(messageTxt); - } - } else if (childs[i].tagName == 'prompt') { - - var message = XMLUtils.XPathSelectSingleNode(childs[i], 'message').firstChild.nodeValue; - var jsonData = XMLUtils.XPathSelectSingleNode(childs[i], 'data').firstChild.nodeValue; - var json = JSON.parse(jsonData); - // TODO: DELEGATE TO UI - /* - var dialogContent = new Element('div').update(json["DIALOG"]); - modal.showSimpleModal(modal.messageBox?modal.messageBox:document.body, dialogContent, function(){ - // ok callback; - if(json["OK"]["GET_FIELDS"]){ - var params = $H(); - $A(json["OK"]["GET_FIELDS"]).each(function(fName){ - params.set(fName, dialogContent.down('input[name="'+fName+'"]').getValue()); - }); - var conn = new Connexion(); - conn.setParameters(params); - if(json["OK"]["EVAL"]){ - conn.onComplete = function(){ - eval(json["OK"]["EVAL"]); - }; + var path = PydioApi._libUrl ? PydioApi._libUrl + '/' + fileName : fileName; + + /*if(window.jQuery && window.jQuery.ajax){ + jQuery.ajax(path, + { + method:'get', + async: (aSync?true:false), + complete:function(transport){ + if(transport.responseText) + { + try + { + var script = transport.responseText; + if (window.execScript){ + window.execScript( script ); + } + else{ + // TO TEST, THIS SEEM TO WORK ON SAFARI + window.my_code = script; + var script_tag = document.createElement('script'); + script_tag.type = 'text/javascript'; + script_tag.innerHTML = 'eval(window.my_code)'; + document.getElementsByTagName('head')[0].appendChild(script_tag); + } + if(onLoadedCode != null) onLoadedCode(); } - conn.sendAsync(); - }else{ - if(json["OK"]["EVAL"]){ - eval(json["OK"]["EVAL"]); + catch(e) + { + alert('error loading '+fileName+':'+ e.message); } } - return true; - }, function(){ - // cancel callback - if(json["CANCEL"]["EVAL"]){ - eval(json["CANCEL"]["EVAL"]); + pydio.fire("server_answer"); + } + }); + }else */if (window.Connexion) { + + var conn = new Connexion(); + conn._libUrl = false; + if (pydio.Parameters.get('SERVER_PREFIX_URI')) { + conn._libUrl = pydio.Parameters.get('SERVER_PREFIX_URI'); + } + conn.loadLibrary(fileName, onLoadedCode, aSync); + } + }; + + PydioApi.prototype.switchRepository = function switchRepository(repositoryId, completeCallback) { + var params = { + get_action: 'switch_repository', + repository_id: repositoryId + }; + this.request(params, completeCallback); + }; + + PydioApi.prototype.switchLanguage = function switchLanguage(lang, completeCallback) { + var params = { + get_action: 'get_i18n_messages', + lang: lang, + format: 'json' + }; + this.request(params, completeCallback); + }; + + PydioApi.prototype.loadXmlRegistry = function loadXmlRegistry(completeCallback) { + var xPath = arguments[1] === undefined ? null : arguments[1]; + + var params = { get_action: 'get_xml_registry' }; + if (xPath) params[xPath] = xPath; + this.request(params, completeCallback); + }; + + PydioApi.prototype.getBootConf = function getBootConf(completeCallback) { + var params = { get_action: 'get_boot_conf' }; + var cB = (function (transport) { + if (transport.responseJSON && transport.responseJSON.SECURE_TOKEN) { + this._pydioObject.Parameters.set('SECURE_TOKEN', transport.responseJSON.SECURE_TOKEN); + this.setSecureToken(transport.responseJSON.SECURE_TOKEN); + } + if (completeCallback) { + completeCallback(transport); + } + }).bind(this); + this.request(params, cB); + }; + + PydioApi.prototype.userSavePreference = function userSavePreference(prefName, prefValue) { + var conn = new Connexion(); + conn.setMethod('post'); + conn.discrete = true; + conn.addParameter('get_action', 'save_user_pref'); + conn.addParameter('pref_name_' + 0, prefName); + conn.addParameter('pref_value_' + 0, prefValue); + conn.sendAsync(); + }; + + PydioApi.prototype.userSavePreferences = function userSavePreferences(preferences, completeCallback) { + var conn = new Connexion(); + conn.addParameter('get_action', 'save_user_pref'); + var i = 0; + preferences.forEach(function (value, key) { + conn.addParameter('pref_name_' + i, key); + conn.addParameter('pref_value_' + i, value); + i++; + }); + conn.onComplete = completeCallback; + conn.sendAsync(); + }; + + PydioApi.prototype.userSavePassword = function userSavePassword(oldPass, newPass, seed, completeCallback) { + var conn = new Connexion(); + conn.addParameter('get_action', 'save_user_pref'); + conn.addParameter('pref_name_' + i, 'password'); + conn.addParameter('pref_value_' + i, newPass); + conn.addParameter('crt', oldPass); + conn.addParameter('pass_seed', seed); + conn.onComplete = completeCallback; + conn.sendAsync(); + }; + + PydioApi.prototype.applyCheckHook = function applyCheckHook(node, hookName, hookArg, completeCallback) { + var params = { + get_action: 'apply_check_hook', + file: node.getPath(), + hook_name: hookName, + hook_arg: hookArg + }; + this.request(params, completeCallback, null, { async: false }); + }; + + /** + * Standard parser for server XML answers + * @param xmlResponse DOMDocument + */ + + PydioApi.prototype.parseXmlMessage = function parseXmlMessage(xmlResponse) { + if (xmlResponse == null || xmlResponse.documentElement == null) { + return null; + }var childs = xmlResponse.documentElement.childNodes; + + var reloadNodes = []; + var error = false; + this.LAST_ERROR_ID = null; + + for (var i = 0; i < childs.length; i++) { + if (childs[i].tagName == 'message') { + var messageTxt = 'No message'; + if (childs[i].firstChild) messageTxt = childs[i].firstChild.nodeValue; + if (childs[i].getAttribute('type') == 'ERROR') { + Logger.error(messageTxt); + error = true; + } else { + Logger.log(messageTxt); + } + } else if (childs[i].tagName == 'prompt') { + + var message = XMLUtils.XPathSelectSingleNode(childs[i], 'message').firstChild.nodeValue; + var jsonData = XMLUtils.XPathSelectSingleNode(childs[i], 'data').firstChild.nodeValue; + var json = JSON.parse(jsonData); + // TODO: DELEGATE TO UI + /* + var dialogContent = new Element('div').update(json["DIALOG"]); + modal.showSimpleModal(modal.messageBox?modal.messageBox:document.body, dialogContent, function(){ + // ok callback; + if(json["OK"]["GET_FIELDS"]){ + var params = $H(); + $A(json["OK"]["GET_FIELDS"]).each(function(fName){ + params.set(fName, dialogContent.down('input[name="'+fName+'"]').getValue()); + }); + var conn = new Connexion(); + conn.setParameters(params); + if(json["OK"]["EVAL"]){ + conn.onComplete = function(){ + eval(json["OK"]["EVAL"]); + }; } - return true; - }); - */ - throw new Error(); - } else if (childs[i].tagName == 'reload_instruction') { - var obName = childs[i].getAttribute('object'); - if (obName == 'data') { - var node = childs[i].getAttribute('node'); - if (node) { - reloadNodes.push(node); - } else { - var file = childs[i].getAttribute('file'); - if (file) { - this._pydioObject.getContextHolder().setPendingSelection(file); - } - reloadNodes.push(this._pydioObject.getContextNode()); + conn.sendAsync(); + }else{ + if(json["OK"]["EVAL"]){ + eval(json["OK"]["EVAL"]); } - } else if (obName == 'repository_list') { - this._pydioObject.reloadRepositoriesList(); } - } else if (childs[i].nodeName == 'nodes_diff') { - var dm = this._pydioObject.getContextHolder(); - if (dm.getAjxpNodeProvider().parseAjxpNodesDiffs) { - dm.getAjxpNodeProvider().parseAjxpNodesDiffs(childs[i], dm, !window.currentLightBox); + return true; + }, function(){ + // cancel callback + if(json["CANCEL"]["EVAL"]){ + eval(json["CANCEL"]["EVAL"]); } - } else if (childs[i].tagName == 'logging_result') { - if (childs[i].getAttribute('secure_token')) { - var serverAccessPath = this._pydioObject.Parameters.get('ajxpServerAccess'); - var regex = new RegExp('.*?[&\\?]' + 'minisite_session' + '=(.*?)&.*'); - - var val = serverAccessPath.replace(regex, '$1'); - var minisite_session = val == serverAccessPath ? false : val; - - var secure_token = childs[i].getAttribute('secure_token'); - - var parts = serverAccessPath.split('?secure_token'); - serverAccessPath = parts[0] + '?secure_token=' + secure_token; - if (minisite_session) serverAccessPath += '&minisite_session=' + minisite_session; - - this.setSecureToken(secure_token); - this._pydioObject.Parameters.set('SECURE_TOKEN', secure_token); - // BACKWARD COMPAT - window.ajxpServerAccessPath = serverAccessPath; - this._pydioObject.Parameters.set('ajxpServerAccess', serverAccessPath); - if (window.ajxpBootstrap && ajxpBootstrap.parameters) { - ajxpBootstrap.parameters.set('ajxpServerAccess', serverAccessPath); - ajxpBootstrap.parameters.set('SECURE_TOKEN', secure_token); - } - if (window.Connexion) Connexion.SECURE_TOKEN = secure_token; - } - var result = childs[i].getAttribute('value'); - var errorId = false; - if (result == '1') { - try {} catch (e) { - Logger.error('Error after login, could prevent registry loading!', e); + return true; + }); + */ + throw new Error(); + } else if (childs[i].tagName == 'reload_instruction') { + var obName = childs[i].getAttribute('object'); + if (obName == 'data') { + var node = childs[i].getAttribute('node'); + if (node) { + reloadNodes.push(node); + } else { + var file = childs[i].getAttribute('file'); + if (file) { + this._pydioObject.getContextHolder().setPendingSelection(file); } - this._pydioObject.loadXmlRegistry(); - } else if (result == '0' || result == '-1') { - errorId = 285; - } else if (result == '2') { - this._pydioObject.loadXmlRegistry(); - } else if (result == '-2') { - errorId = 285; - } else if (result == '-3') { - errorId = 366; - } else if (result == '-4') { - errorId = 386; + reloadNodes.push(this._pydioObject.getContextNode()); } - if (errorId) { - error = true; - this.LAST_ERROR_ID = errorId; - Logger.error(this._pydioObject.MessageHash[errorId]); + } else if (obName == 'repository_list') { + this._pydioObject.reloadRepositoriesList(); + } + } else if (childs[i].nodeName == 'nodes_diff') { + var dm = this._pydioObject.getContextHolder(); + if (dm.getAjxpNodeProvider().parseAjxpNodesDiffs) { + dm.getAjxpNodeProvider().parseAjxpNodesDiffs(childs[i], dm, !window.currentLightBox); + } + } else if (childs[i].tagName == 'logging_result') { + if (childs[i].getAttribute('secure_token')) { + var serverAccessPath = this._pydioObject.Parameters.get('ajxpServerAccess'); + var regex = new RegExp('.*?[&\\?]' + 'minisite_session' + '=(.*?)&.*'); + + var val = serverAccessPath.replace(regex, '$1'); + var minisite_session = val == serverAccessPath ? false : val; + + var secure_token = childs[i].getAttribute('secure_token'); + + var parts = serverAccessPath.split('?secure_token'); + serverAccessPath = parts[0] + '?secure_token=' + secure_token; + if (minisite_session) serverAccessPath += '&minisite_session=' + minisite_session; + + this.setSecureToken(secure_token); + this._pydioObject.Parameters.set('SECURE_TOKEN', secure_token); + // BACKWARD COMPAT + window.ajxpServerAccessPath = serverAccessPath; + this._pydioObject.Parameters.set('ajxpServerAccess', serverAccessPath); + if (window.ajxpBootstrap && ajxpBootstrap.parameters) { + ajxpBootstrap.parameters.set('ajxpServerAccess', serverAccessPath); + ajxpBootstrap.parameters.set('SECURE_TOKEN', secure_token); } - } else if (childs[i].tagName == 'trigger_bg_action') { - var name = childs[i].getAttribute('name'); - var messageId = childs[i].getAttribute('messageId'); - var parameters = {}; - for (var j = 0; j < childs[i].childNodes.length; j++) { - var paramChild = childs[i].childNodes[j]; - if (paramChild.tagName == 'param') { - parameters[paramChild.getAttribute('name')] = paramChild.getAttribute('value'); - } + if (window.Connexion) Connexion.SECURE_TOKEN = secure_token; + } + var result = childs[i].getAttribute('value'); + var errorId = false; + if (result == '1') { + try {} catch (e) { + Logger.error('Error after login, could prevent registry loading!', e); } - var bgManager = this._pydioObject.getController().getBackgroundTasksManager(); - if (bgManager) { - bgManager.queueAction(name, parameters, messageId); - bgManager.next(); + this._pydioObject.loadXmlRegistry(); + } else if (result == '0' || result == '-1') { + errorId = 285; + } else if (result == '2') { + this._pydioObject.loadXmlRegistry(); + } else if (result == '-2') { + errorId = 285; + } else if (result == '-3') { + errorId = 366; + } else if (result == '-4') { + errorId = 386; + } + if (errorId) { + error = true; + this.LAST_ERROR_ID = errorId; + Logger.error(this._pydioObject.MessageHash[errorId]); + } + } else if (childs[i].tagName == 'trigger_bg_action') { + var name = childs[i].getAttribute('name'); + var messageId = childs[i].getAttribute('messageId'); + var parameters = {}; + for (var j = 0; j < childs[i].childNodes.length; j++) { + var paramChild = childs[i].childNodes[j]; + if (paramChild.tagName == 'param') { + parameters[paramChild.getAttribute('name')] = paramChild.getAttribute('value'); } } + var bgManager = this._pydioObject.getController().getBackgroundTasksManager(); + if (bgManager) { + bgManager.queueAction(name, parameters, messageId); + bgManager.next(); + } } - if (reloadNodes.length) { - this._pydioObject.getContextHolder().multipleNodesReload(reloadNodes); - } - return !error; } - }, { - key: 'submitForm', - - /** - * Submits a form using Connexion class. - * @param formName String The id of the form - * @param post Boolean Whether to POST or GET - * @param completeCallback Function Callback to be called on complete - */ - value: function submitForm(formName, post, completeCallback) { - var params = {}; - // TODO: UI IMPLEMENTATION - $(formName).getElements().each(function (fElement) { - var fValue = fElement.getValue(); - if (fElement.name == 'get_action' && fValue.substr(0, 4) == 'http') { - fValue = getBaseName(fValue); - } - if (fElement.type == 'radio' && !fElement.checked) return; - if (params[fElement.name] && fElement.name.endsWith('[]')) { - var existing = params[fElement.name]; - if (typeof existing == 'string') existing = [existing]; - existing.push(fValue); - params[fElement.name] = existing; - } else { - params[fElement.name] = fValue; - } - }); - if (this._pydioObject.getContextNode()) { - params.dir = this._pydioObject.getContextNode().getPath(); + if (reloadNodes.length) { + this._pydioObject.getContextHolder().multipleNodesReload(reloadNodes); + } + return !error; + }; + + /** + * Submits a form using Connexion class. + * @param formName String The id of the form + * @param post Boolean Whether to POST or GET + * @param completeCallback Function Callback to be called on complete + */ + + PydioApi.prototype.submitForm = function submitForm(formName, post, completeCallback) { + var params = {}; + // TODO: UI IMPLEMENTATION + $(formName).getElements().each(function (fElement) { + var fValue = fElement.getValue(); + if (fElement.name == 'get_action' && fValue.substr(0, 4) == 'http') { + fValue = getBaseName(fValue); } - var onComplete; - if (completeCallback) { - onComplete = completeCallback; + if (fElement.type == 'radio' && !fElement.checked) return; + if (params[fElement.name] && fElement.name.endsWith('[]')) { + var existing = params[fElement.name]; + if (typeof existing == 'string') existing = [existing]; + existing.push(fValue); + params[fElement.name] = existing; } else { - onComplete = (function (transport) { - this.parseXmlMessage(transport.responseXML); - }).bind(this); + params[fElement.name] = fValue; } - this.request(params, onComplete, null, { method: post ? 'post' : 'get' }); - } - }, { - key: 'triggerDownload', - - /** - * Trigger a simple download - * @param url String - */ - value: function triggerDownload(url) { - document.location.href = url; + }); + if (this._pydioObject.getContextNode()) { + params.dir = this._pydioObject.getContextNode().getPath(); } - }], [{ - key: 'getClient', - value: function getClient() { - if (PydioApi._PydioClient) { - return PydioApi._PydioClient; - }var client = new PydioApi(); - PydioApi._PydioClient = client; - return client; + var onComplete; + if (completeCallback) { + onComplete = completeCallback; + } else { + onComplete = (function (transport) { + this.parseXmlMessage(transport.responseXML); + }).bind(this); } - }, { - key: 'loadLibrary', - - /** - * Load a javascript library - * @param fileName String - * @param onLoadedCode Function Callback - * @param aSync Boolean load library asynchroneously - * @todo : We should use Require or equivalent instead. - */ - value: function loadLibrary(fileName, onLoadedCode, aSync) { - if (window.pydio && pydio.Parameters.get('ajxpVersion') && fileName.indexOf('?') == -1) { - fileName += '?v=' + pydio.Parameters.get('ajxpVersion'); - } - PydioApi._libUrl = false; - if (window.pydio && pydio.Parameters.get('SERVER_PREFIX_URI')) { - PydioApi._libUrl = pydio.Parameters.get('SERVER_PREFIX_URI'); - } - var path = PydioApi._libUrl ? PydioApi._libUrl + '/' + fileName : fileName; - - /*if(window.jQuery && window.jQuery.ajax){ - jQuery.ajax(path, - { - method:'get', - async: (aSync?true:false), - complete:function(transport){ - if(transport.responseText) - { - try - { - var script = transport.responseText; - if (window.execScript){ - window.execScript( script ); - } - else{ - // TO TEST, THIS SEEM TO WORK ON SAFARI - window.my_code = script; - var script_tag = document.createElement('script'); - script_tag.type = 'text/javascript'; - script_tag.innerHTML = 'eval(window.my_code)'; - document.getElementsByTagName('head')[0].appendChild(script_tag); - } - if(onLoadedCode != null) onLoadedCode(); - } - catch(e) - { - alert('error loading '+fileName+':'+ e.message); - } - } - pydio.fire("server_answer"); - } - }); - }else */if (window.Connexion) { + this.request(params, onComplete, null, { method: post ? 'post' : 'get' }); + }; - var conn = new Connexion(); - conn._libUrl = false; - if (pydio.Parameters.get('SERVER_PREFIX_URI')) { - conn._libUrl = pydio.Parameters.get('SERVER_PREFIX_URI'); - } - conn.loadLibrary(fileName, onLoadedCode, aSync); - } - } - }]); + /** + * Trigger a simple download + * @param url String + */ + + PydioApi.prototype.triggerDownload = function triggerDownload(url) { + document.location.href = url; + }; return PydioApi; })(); diff --git a/core/src/plugins/gui.ajax/res/js/core/http/ResourcesManager.js b/core/src/plugins/gui.ajax/res/js/core/http/ResourcesManager.js index b0ccf6b675..5051140d78 100644 --- a/core/src/plugins/gui.ajax/res/js/core/http/ResourcesManager.js +++ b/core/src/plugins/gui.ajax/res/js/core/http/ResourcesManager.js @@ -2,8 +2,6 @@ var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; -var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - /* * Copyright 2007-2013 Charles du Jeu - Abstrium SAS * This file is part of Pydio. @@ -41,465 +39,395 @@ var ResourcesManager = (function () { this.loaded = false; } - _createClass(ResourcesManager, [{ - key: 'addJSResource', + /** + * Adds a Javascript resource + * @param fileName String + * @param className String + */ - /** - * Adds a Javascript resource - * @param fileName String - * @param className String - */ - value: function addJSResource(fileName, className) { - var autoload = arguments[2] === undefined ? false : arguments[2]; + ResourcesManager.prototype.addJSResource = function addJSResource(fileName, className) { + var autoload = arguments[2] === undefined ? false : arguments[2]; - if (!this.resources.js) { - this.resources.js = []; - } - this.resources.js.push({ - fileName: fileName, - className: className, - autoload: false - }); + if (!this.resources.js) { + this.resources.js = []; } - }, { - key: 'addCSSResource', - - /** - * Adds a CSS resource - * @param fileName String - */ - value: function addCSSResource(fileName) { - if (!this.resources.css) { - this.resources.css = []; - } - this.resources.css.push(fileName); + this.resources.js.push({ + fileName: fileName, + className: className, + autoload: false + }); + }; + + /** + * Adds a CSS resource + * @param fileName String + */ + + ResourcesManager.prototype.addCSSResource = function addCSSResource(fileName) { + if (!this.resources.css) { + this.resources.css = []; } - }, { - key: 'addGuiForm', - - /** - * Adds a FORM from html snipper - * @param formId String - * @param htmlSnippet String - */ - value: function addGuiForm(formId, htmlSnippet) { - if (!this.resources.forms) { - this.resources.forms = new Map(); - } - this.resources.forms.set(formId, htmlSnippet); + this.resources.css.push(fileName); + }; + + /** + * Adds a FORM from html snipper + * @param formId String + * @param htmlSnippet String + */ + + ResourcesManager.prototype.addGuiForm = function addGuiForm(formId, htmlSnippet) { + if (!this.resources.forms) { + this.resources.forms = new Map(); } - }, { - key: 'addDependency', - - /** - * Add a dependency to another plugin - * @param data Object - */ - value: function addDependency(data) { - if (!this.resources.dependencies) { - this.resources.dependencies = []; - } - this.resources.dependencies.push(data); + this.resources.forms.set(formId, htmlSnippet); + }; + + /** + * Add a dependency to another plugin + * @param data Object + */ + + ResourcesManager.prototype.addDependency = function addDependency(data) { + if (!this.resources.dependencies) { + this.resources.dependencies = []; } - }, { - key: 'hasDependencies', - - /** - * Check if some dependencies must be loaded before - * @returns Boolean - */ - value: function hasDependencies() { - return this.resources.dependencies || false; + this.resources.dependencies.push(data); + }; + + /** + * Check if some dependencies must be loaded before + * @returns Boolean + */ + + ResourcesManager.prototype.hasDependencies = function hasDependencies() { + return this.resources.dependencies || false; + }; + + /** + * Load resources + * @param resourcesRegistry $H Ajaxplorer ressources registry + */ + + ResourcesManager.prototype.load = function load(resourcesRegistry) { + var jsAutoloadOnly = arguments[1] === undefined ? false : arguments[1]; + + if (this.loaded) { + return; + }if (this.hasDependencies()) { + this.resources.dependencies.forEach((function (el) { + if (resourcesRegistry[el]) { + resourcesRegistry[el].load(resourcesRegistry); + } + }).bind(this)); } - }, { - key: 'load', - - /** - * Load resources - * @param resourcesRegistry $H Ajaxplorer ressources registry - */ - value: function load(resourcesRegistry) { - var jsAutoloadOnly = arguments[1] === undefined ? false : arguments[1]; - - if (this.loaded) { - return; - }if (this.hasDependencies()) { - this.resources.dependencies.forEach((function (el) { - if (resourcesRegistry[el]) { - resourcesRegistry[el].load(resourcesRegistry); - } - }).bind(this)); - } - if (this.resources.forms) { - this.resources.forms.forEach((function (value, key) { - this.loadGuiForm(key, value); - }).bind(this)); - } - if (this.resources.js) { - this.resources.js.forEach((function (value) { - if (jsAutoloadOnly && !value.autoload) return; - this.loadJSResource(value.fileName, value.className); - }).bind(this)); - } - if (this.resources.css) { - this.resources.css.forEach((function (value) { - this.loadCSSResource(value); - }).bind(this)); - } - this.loaded = true; + if (this.resources.forms) { + this.resources.forms.forEach((function (value, key) { + this.loadGuiForm(key, value); + }).bind(this)); } - }, { - key: 'loadJSResource', - - /** - * Load a javascript file - * @param fileName String - * @param className String - * @param callback Function - * @param aSync Boolean - */ - value: function loadJSResource(fileName, className, callback, aSync) { - - if (!window[className]) { - if (typeof className != 'function' || typeof className.prototype != 'object') { - PydioApi.loadLibrary(fileName, callback, aSync); - } - } else if (callback) { - callback(); - } + if (this.resources.js) { + this.resources.js.forEach((function (value) { + if (jsAutoloadOnly && !value.autoload) return; + this.loadJSResource(value.fileName, value.className); + }).bind(this)); } - }, { - key: 'loadWebComponents', - value: function loadWebComponents(fileNames, callback) { - if (!Polymer) { - throw Error('Cannot find Polymer library!'); - } - Polymer['import'](fileNames, callback); + if (this.resources.css) { + this.resources.css.forEach((function (value) { + this.loadCSSResource(value); + }).bind(this)); } - }, { - key: 'loadCSSResource', - - /** - * Load a CSS file - * @param fileName String - */ - value: function loadCSSResource(fileName) { - - var head = document.getElementsByTagName('head')[0]; - if (head && head.down) { - if (pydio.Parameters.get('SERVER_PREFIX_URI')) { - fileName = pydio.Parameters.get('SERVER_PREFIX_URI') + fileName; - } - fileName = fileName + '?v=' + pydio.Parameters.get('ajxpVersion'); - // WARNING PROTOTYPE STUFF - var select = head.down('[href="' + fileName + '"]'); - if (!select) { - var cssNode = new Element('link', { - type: 'text/css', - rel: 'stylesheet', - href: fileName, - media: 'screen' - }); - head.insert(cssNode); - } + this.loaded = true; + }; + + /** + * Load a javascript file + * @param fileName String + * @param className String + * @param callback Function + * @param aSync Boolean + */ + + ResourcesManager.prototype.loadJSResource = function loadJSResource(fileName, className, callback, aSync) { + + if (!window[className]) { + if (typeof className != 'function' || typeof className.prototype != 'object') { + PydioApi.loadLibrary(fileName, callback, aSync); } + } else if (callback) { + callback(); } - }, { - key: 'loadGuiForm', - - /** - * Insert the HTML snipper and evaluate scripts - * @param formId String - * @param htmlSnippet String - */ - value: function loadGuiForm(formId, htmlSnippet) { - if (!$(this.mainFormContainerId).select('[id="' + formId + '"]').length) { - // TODO - PROTOTYPE STUFF - htmlSnippet.evalScripts(); - $(this.mainFormContainerId).insert(htmlSnippet.stripScripts()); - } + }; + + ResourcesManager.prototype.loadWebComponents = function loadWebComponents(fileNames, callback) { + if (!Polymer) { + throw Error('Cannot find Polymer library!'); } - }, { - key: 'loadFromXmlNode', - - /** - * Load the resources from XML - * @param node XMLNode - */ - value: function loadFromXmlNode(node) { - var clForm = {}; - var k; - if (node.nodeName == 'resources') { - for (k = 0; k < node.childNodes.length; k++) { - if (node.childNodes[k].nodeName == 'js') { - this.addJSResource(node.childNodes[k].getAttribute('file'), node.childNodes[k].getAttribute('className'), node.childNodes[k].getAttribute('autoload') === true); - } else if (node.childNodes[k].nodeName == 'css') { - this.addCSSResource(node.childNodes[k].getAttribute('file')); - } else if (node.childNodes[k].nodeName == 'img_library') { - ResourcesManager.addImageLibrary(node.childNodes[k].getAttribute('alias'), node.childNodes[k].getAttribute('path')); - } - } - } else if (node.nodeName == 'dependencies') { - for (k = 0; k < node.childNodes.length; k++) { - if (node.childNodes[k].nodeName == 'pluginResources') { - this.addDependency(node.childNodes[k].getAttribute('pluginName')); - } - } - } else if (node.nodeName == 'clientForm') { - if (!node.getAttribute('theme') || node.getAttribute('theme') == pydio.Parameters.get('theme')) { - clForm = { formId: node.getAttribute('id'), formCode: node.firstChild.nodeValue }; - } + Polymer['import'](fileNames, callback); + }; + + /** + * Load a CSS file + * @param fileName String + */ + + ResourcesManager.prototype.loadCSSResource = function loadCSSResource(fileName) { + + var head = document.getElementsByTagName('head')[0]; + if (head && head.down) { + if (pydio.Parameters.get('SERVER_PREFIX_URI')) { + fileName = pydio.Parameters.get('SERVER_PREFIX_URI') + fileName; } - if (clForm.formId) { - this.addGuiForm(clForm.formId, clForm.formCode); + fileName = fileName + '?v=' + pydio.Parameters.get('ajxpVersion'); + // WARNING PROTOTYPE STUFF + var select = head.down('[href="' + fileName + '"]'); + if (!select) { + var cssNode = new Element('link', { + type: 'text/css', + rel: 'stylesheet', + href: fileName, + media: 'screen' + }); + head.insert(cssNode); } } - }], [{ - key: 'addImageLibrary', - - /** - * - * @param aliasName - * @param aliasPath - * @todo MOVE OUTSIDE? - */ - value: function addImageLibrary(aliasName, aliasPath) { - if (!window.AjxpImageLibraries) window.AjxpImageLibraries = {}; - window.AjxpImageLibraries[aliasName] = aliasPath; + }; + + /** + * Insert the HTML snipper and evaluate scripts + * @param formId String + * @param htmlSnippet String + */ + + ResourcesManager.prototype.loadGuiForm = function loadGuiForm(formId, htmlSnippet) { + if (!$(this.mainFormContainerId).select('[id="' + formId + '"]').length) { + // TODO - PROTOTYPE STUFF + htmlSnippet.evalScripts(); + $(this.mainFormContainerId).insert(htmlSnippet.stripScripts()); } - }, { - key: 'loadAutoLoadResources', - - /** - * Check if resources are tagged autoload and load them - * @param registry DOMDocument XML Registry - */ - value: function loadAutoLoadResources(registry) { - var manager = new ResourcesManager(); - var jsNodes = XMLUtils.XPathSelectNodes(registry, 'plugins/*/client_settings/resources/js'); - var node; - ResourcesManager.__modules = new Map(); - ResourcesManager.__dependencies = new Map(); - ResourcesManager.__components = new Map(); - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = jsNodes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - node = _step.value; - - ResourcesManager.__modules.set(node.getAttribute('className'), node.getAttribute('file')); - if (node.getAttribute('autoload') === 'true') { - manager.loadJSResource(node.getAttribute('file'), node.getAttribute('className'), null, false); - } - if (node.getAttribute('depends')) { - ResourcesManager.__dependencies.set(node.getAttribute('className'), node.getAttribute('depends').split(',')); - } + }; + + /** + * Load the resources from XML + * @param node XMLNode + */ + + ResourcesManager.prototype.loadFromXmlNode = function loadFromXmlNode(node) { + var clForm = {}; + var k; + if (node.nodeName == 'resources') { + for (k = 0; k < node.childNodes.length; k++) { + if (node.childNodes[k].nodeName == 'js') { + this.addJSResource(node.childNodes[k].getAttribute('file'), node.childNodes[k].getAttribute('className'), node.childNodes[k].getAttribute('autoload') === true); + } else if (node.childNodes[k].nodeName == 'css') { + this.addCSSResource(node.childNodes[k].getAttribute('file')); + } else if (node.childNodes[k].nodeName == 'img_library') { + ResourcesManager.addImageLibrary(node.childNodes[k].getAttribute('alias'), node.childNodes[k].getAttribute('path')); } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator['return']) { - _iterator['return'](); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } + } + } else if (node.nodeName == 'dependencies') { + for (k = 0; k < node.childNodes.length; k++) { + if (node.childNodes[k].nodeName == 'pluginResources') { + this.addDependency(node.childNodes[k].getAttribute('pluginName')); } } + } else if (node.nodeName == 'clientForm') { + if (!node.getAttribute('theme') || node.getAttribute('theme') == pydio.Parameters.get('theme')) { + clForm = { formId: node.getAttribute('id'), formCode: node.firstChild.nodeValue }; + } + } + if (clForm.formId) { + this.addGuiForm(clForm.formId, clForm.formCode); + } + }; - var compNodes = XMLUtils.XPathSelectNodes(registry, 'plugins/*/client_settings/resources/component'); - var _iteratorNormalCompletion2 = true; - var _didIteratorError2 = false; - var _iteratorError2 = undefined; + /** + * + * @param aliasName + * @param aliasPath + * @todo MOVE OUTSIDE? + */ - try { - for (var _iterator2 = compNodes[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { - node = _step2.value; + ResourcesManager.addImageLibrary = function addImageLibrary(aliasName, aliasPath) { + if (!window.AjxpImageLibraries) window.AjxpImageLibraries = {}; + window.AjxpImageLibraries[aliasName] = aliasPath; + }; - ResourcesManager.__components.set(node.getAttribute('componentName'), node.getAttribute('file')); - if (node.getAttribute('autoload') === 'true') { - manager.loadWebComponents([node.getAttribute('file')]); - } - } - } catch (err) { - _didIteratorError2 = true; - _iteratorError2 = err; - } finally { - try { - if (!_iteratorNormalCompletion2 && _iterator2['return']) { - _iterator2['return'](); - } - } finally { - if (_didIteratorError2) { - throw _iteratorError2; - } - } + /** + * Check if resources are tagged autoload and load them + * @param registry DOMDocument XML Registry + */ + + ResourcesManager.loadAutoLoadResources = function loadAutoLoadResources(registry) { + var manager = new ResourcesManager(); + var jsNodes = XMLUtils.XPathSelectNodes(registry, 'plugins/*/client_settings/resources/js'); + var node; + ResourcesManager.__modules = new Map(); + ResourcesManager.__dependencies = new Map(); + ResourcesManager.__components = new Map(); + for (var _iterator = jsNodes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { + if (_isArray) { + if (_i >= _iterator.length) break; + node = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + node = _i.value; } - var imgNodes = XMLUtils.XPathSelectNodes(registry, 'plugins/*/client_settings/resources/img_library'); - var _iteratorNormalCompletion3 = true; - var _didIteratorError3 = false; - var _iteratorError3 = undefined; + ResourcesManager.__modules.set(node.getAttribute('className'), node.getAttribute('file')); + if (node.getAttribute('autoload') === 'true') { + manager.loadJSResource(node.getAttribute('file'), node.getAttribute('className'), null, false); + } + if (node.getAttribute('depends')) { + ResourcesManager.__dependencies.set(node.getAttribute('className'), node.getAttribute('depends').split(',')); + } + } + var compNodes = XMLUtils.XPathSelectNodes(registry, 'plugins/*/client_settings/resources/component'); + for (var _iterator2 = compNodes, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) { + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + node = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + node = _i2.value; + } - try { - for (var _iterator3 = imgNodes[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { - node = _step3.value; + ResourcesManager.__components.set(node.getAttribute('componentName'), node.getAttribute('file')); + if (node.getAttribute('autoload') === 'true') { + manager.loadWebComponents([node.getAttribute('file')]); + } + } + var imgNodes = XMLUtils.XPathSelectNodes(registry, 'plugins/*/client_settings/resources/img_library'); + for (var _iterator3 = imgNodes, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) { + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + node = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + node = _i3.value; + } - ResourcesManager.addImageLibrary(node.getAttribute('alias'), node.getAttribute('path')); - } - } catch (err) { - _didIteratorError3 = true; - _iteratorError3 = err; - } finally { - try { - if (!_iteratorNormalCompletion3 && _iterator3['return']) { - _iterator3['return'](); - } - } finally { - if (_didIteratorError3) { - throw _iteratorError3; - } - } + ResourcesManager.addImageLibrary(node.getAttribute('alias'), node.getAttribute('path')); + } + var cssNodes = XMLUtils.XPathSelectNodes(registry, 'plugins/*/client_settings/resources/css[@autoload="true"]'); + for (var _iterator4 = cssNodes, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) { + if (_isArray4) { + if (_i4 >= _iterator4.length) break; + node = _iterator4[_i4++]; + } else { + _i4 = _iterator4.next(); + if (_i4.done) break; + node = _i4.value; } - var cssNodes = XMLUtils.XPathSelectNodes(registry, 'plugins/*/client_settings/resources/css[@autoload="true"]'); - var _iteratorNormalCompletion4 = true; - var _didIteratorError4 = false; - var _iteratorError4 = undefined; + manager.loadCSSResource(node.getAttribute('file')); + } + }; - try { - for (var _iterator4 = cssNodes[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { - node = _step4.value; + /** + * + * @param className String + * @param dependencies Set + */ - manager.loadCSSResource(node.getAttribute('file')); + ResourcesManager.findDependencies = function findDependencies(className, dependencies) { + if (ResourcesManager.__dependencies.has(className)) { + var deps = ResourcesManager.__dependencies.get(className); + deps.forEach(function (dep) { + if (!dependencies.has(dep) && ResourcesManager.__modules.has(dep)) { + dependencies.add(dep); + ResourcesManager.findDependencies(dep, dependencies); } - } catch (err) { - _didIteratorError4 = true; - _iteratorError4 = err; - } finally { - try { - if (!_iteratorNormalCompletion4 && _iterator4['return']) { - _iterator4['return'](); - } - } finally { - if (_didIteratorError4) { - throw _iteratorError4; - } - } - } + }); } - }, { - key: 'findDependencies', - - /** - * - * @param className String - * @param dependencies Set - */ - value: function findDependencies(className, dependencies) { - if (ResourcesManager.__dependencies.has(className)) { - var deps = ResourcesManager.__dependencies.get(className); - deps.forEach(function (dep) { - if (!dependencies.has(dep) && ResourcesManager.__modules.has(dep)) { - dependencies.add(dep); - ResourcesManager.findDependencies(dep, dependencies); - } - }); - } + }; + + ResourcesManager.loadClassesAndApply = function loadClassesAndApply(classNames, callbackFunc) { + if (!ResourcesManager.__modules) { + ResourcesManager.loadAutoLoadResources(pydio.Registry.getXML()); } - }, { - key: 'loadClassesAndApply', - value: function loadClassesAndApply(classNames, callbackFunc) { - if (!ResourcesManager.__modules) { - ResourcesManager.loadAutoLoadResources(pydio.Registry.getXML()); - } - var modules = new Map(); - classNames.forEach(function (c) { - if (!window[c] && ResourcesManager.__modules.has(c)) { - var deps = new Set(); - ResourcesManager.findDependencies(c, deps); - if (deps.size) { - deps.forEach(function (d) { - modules.set(d, { - className: d, - fileName: ResourcesManager.__modules.get(d), - require: ResourcesManager.__modules.get(d).replace('.js', '') - }); + var modules = new Map(); + classNames.forEach(function (c) { + if (!window[c] && ResourcesManager.__modules.has(c)) { + var deps = new Set(); + ResourcesManager.findDependencies(c, deps); + if (deps.size) { + deps.forEach(function (d) { + modules.set(d, { + className: d, + fileName: ResourcesManager.__modules.get(d), + require: ResourcesManager.__modules.get(d).replace('.js', '') }); - } - modules.set(c, { - className: c, - fileName: ResourcesManager.__modules.get(c), - require: ResourcesManager.__modules.get(c).replace('.js', '') }); } - }); - if (!modules.size) { - callbackFunc(); - return; + modules.set(c, { + className: c, + fileName: ResourcesManager.__modules.get(c), + require: ResourcesManager.__modules.get(c).replace('.js', '') + }); } + }); + if (!modules.size) { + callbackFunc(); + return; + } - if (modules.size == 1) { - ResourcesManager.detectModuleToLoadAndApply(modules.keys().next().value, callbackFunc); - return; - } + if (modules.size == 1) { + ResourcesManager.detectModuleToLoadAndApply(modules.keys().next().value, callbackFunc); + return; + } + if (window.requirejs) { + // Let require handle multiple async + var requires = []; + modules.forEach(function (e) { + requires.push(e.require); + }); + requirejs(requires, callbackFunc); + } else { + // Load sync and apply the callback manually + var loader = new ResourcesManager(); + modules.forEach(function (element) { + loader.loadJSResource(element.fileName, element.className, null, false); + }); + callbackFunc(); + } + }; + + ResourcesManager.detectModuleToLoadAndApply = function detectModuleToLoadAndApply(callbackString, callbackFunc) { + if (!ResourcesManager.__modules) { + ResourcesManager.loadAutoLoadResources(pydio.Registry.getXML()); + } + var className = callbackString.split('.', 1).shift(); + if (!window[className] && ResourcesManager.__modules.has(className)) { if (window.requirejs) { - // Let require handle multiple async - var requires = []; - modules.forEach(function (e) { - requires.push(e.require); - }); - requirejs(requires, callbackFunc); + requirejs([ResourcesManager.__modules.get(className).replace('.js', '')], callbackFunc); } else { - // Load sync and apply the callback manually var loader = new ResourcesManager(); - modules.forEach(function (element) { - loader.loadJSResource(element.fileName, element.className, null, false); - }); - callbackFunc(); + loader.loadJSResource(ResourcesManager.__modules.get(className), className, callbackFunc, true); } + } else { + callbackFunc(); } - }, { - key: 'detectModuleToLoadAndApply', - value: function detectModuleToLoadAndApply(callbackString, callbackFunc) { - if (!ResourcesManager.__modules) { - ResourcesManager.loadAutoLoadResources(pydio.Registry.getXML()); - } - var className = callbackString.split('.', 1).shift(); - if (!window[className] && ResourcesManager.__modules.has(className)) { - if (window.requirejs) { - requirejs([ResourcesManager.__modules.get(className).replace('.js', '')], callbackFunc); - } else { - var loader = new ResourcesManager(); - loader.loadJSResource(ResourcesManager.__modules.get(className), className, callbackFunc, true); - } - } else { - callbackFunc(); - } + }; + + ResourcesManager.loadWebComponentsAndApply = function loadWebComponentsAndApply(componentsList, callbackFunc) { + if (!ResourcesManager.__modules) { + ResourcesManager.loadAutoLoadResources(pydio.Registry.getXML()); } - }, { - key: 'loadWebComponentsAndApply', - value: function loadWebComponentsAndApply(componentsList, callbackFunc) { - if (!ResourcesManager.__modules) { - ResourcesManager.loadAutoLoadResources(pydio.Registry.getXML()); - } - var files = []; - componentsList.forEach(function (v) { - if (ResourcesManager.__components.has(v)) { - files.push(ResourcesManager.__components.get(v)); - } - }); - if (files.length) { - var manager = new ResourcesManager(); - manager.loadWebComponents(files, callbackFunc); + var files = []; + componentsList.forEach(function (v) { + if (ResourcesManager.__components.has(v)) { + files.push(ResourcesManager.__components.get(v)); } + }); + if (files.length) { + var manager = new ResourcesManager(); + manager.loadWebComponents(files, callbackFunc); } - }]); + }; return ResourcesManager; })(); \ No newline at end of file diff --git a/core/src/plugins/gui.ajax/res/js/core/lang/Logger.js b/core/src/plugins/gui.ajax/res/js/core/lang/Logger.js index 6626178f81..b97e438360 100644 --- a/core/src/plugins/gui.ajax/res/js/core/lang/Logger.js +++ b/core/src/plugins/gui.ajax/res/js/core/lang/Logger.js @@ -2,29 +2,22 @@ var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; -var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - var Logger = (function () { function Logger() { _classCallCheck(this, Logger); } - _createClass(Logger, null, [{ - key: "log", - value: function log(message) { - if (console) console.log(message); - } - }, { - key: "error", - value: function error(message) { - if (console) console.error(message); - } - }, { - key: "debug", - value: function debug(message) { - if (console) console.debug(message); - } - }]); + Logger.log = function log(message) { + if (window.console) console.log(message); + }; + + Logger.error = function error(message) { + if (window.console) console.error(message); + }; + + Logger.debug = function debug(message) { + if (window.console) console.debug(message); + }; return Logger; })(); \ No newline at end of file diff --git a/core/src/plugins/gui.ajax/res/js/core/lang/Observable.js b/core/src/plugins/gui.ajax/res/js/core/lang/Observable.js index 8d17b3cec1..ce0c87018d 100644 --- a/core/src/plugins/gui.ajax/res/js/core/lang/Observable.js +++ b/core/src/plugins/gui.ajax/res/js/core/lang/Observable.js @@ -2,67 +2,58 @@ var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; -var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - var Observable = (function () { function Observable() { _classCallCheck(this, Observable); } - _createClass(Observable, [{ - key: '_objectEventSetup', - value: function _objectEventSetup(event_name) { - this._observers = this._observers || {}; - this._observers[event_name] = this._observers[event_name] || []; - } - }, { - key: 'observe', - value: function observe(event_name, observer) { - if (typeof event_name == 'string' && typeof observer != 'undefined') { - this._objectEventSetup(event_name); - if (this._observers[event_name].indexOf(observer) == -1) this._observers[event_name].push(observer); - } else { - for (var e in event_name) { - if (event_name.hasOwnProperty(e)) { - this.observe(e, event_name[e]); - } - } - } - } - }, { - key: 'stopObserving', - value: function stopObserving(event_name, observer) { + Observable.prototype._objectEventSetup = function _objectEventSetup(event_name) { + this._observers = this._observers || {}; + this._observers[event_name] = this._observers[event_name] || []; + }; + + Observable.prototype.observe = function observe(event_name, observer) { + if (typeof event_name == 'string' && typeof observer != 'undefined') { this._objectEventSetup(event_name); - if (event_name && observer) this._observers[event_name] = this._observers[event_name].filter(function (o) { - return o != observer; - });else if (event_name) { - this._observers[event_name] = []; - } else { - this._observers = {}; + if (this._observers[event_name].indexOf(observer) == -1) this._observers[event_name].push(observer); + } else { + for (var e in event_name) { + if (event_name.hasOwnProperty(e)) { + this.observe(e, event_name[e]); + } } } - }, { - key: 'observeOnce', - value: function observeOnce(event_name, outer_observer) { - var inner_observer = (function () { - outer_observer.apply(this, arguments); - this.stopObserving(event_name, inner_observer); - }).bind(this); - this._objectEventSetup(event_name); - this._observers[event_name].push(inner_observer); + }; + + Observable.prototype.stopObserving = function stopObserving(event_name, observer) { + this._objectEventSetup(event_name); + if (event_name && observer) this._observers[event_name] = this._observers[event_name].filter(function (o) { + return o != observer; + });else if (event_name) { + this._observers[event_name] = []; + } else { + this._observers = {}; } - }, { - key: 'notify', - value: function notify(event_name) { - this._objectEventSetup(event_name); - var collected_return_values = []; - var args = Array.from(arguments).slice(1); - for (var i = 0; i < this._observers[event_name].length; ++i) { - collected_return_values.push(this._observers[event_name][i].apply(this._observers[event_name][i], args) || null); - } - return collected_return_values; + }; + + Observable.prototype.observeOnce = function observeOnce(event_name, outer_observer) { + var inner_observer = (function () { + outer_observer.apply(this, arguments); + this.stopObserving(event_name, inner_observer); + }).bind(this); + this._objectEventSetup(event_name); + this._observers[event_name].push(inner_observer); + }; + + Observable.prototype.notify = function notify(event_name) { + this._objectEventSetup(event_name); + var collected_return_values = []; + var args = Array.from(arguments).slice(1); + for (var i = 0; i < this._observers[event_name].length; ++i) { + collected_return_values.push(this._observers[event_name][i].apply(this._observers[event_name][i], args) || null); } - }]); + return collected_return_values; + }; return Observable; })(); \ No newline at end of file diff --git a/core/src/plugins/gui.ajax/res/js/core/model/Action.js b/core/src/plugins/gui.ajax/res/js/core/model/Action.js index 924c5ea913..fa205de339 100644 --- a/core/src/plugins/gui.ajax/res/js/core/model/Action.js +++ b/core/src/plugins/gui.ajax/res/js/core/model/Action.js @@ -2,10 +2,6 @@ var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; -var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - -var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; - var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; /* @@ -41,7 +37,7 @@ var Action = (function (_Observable) { function Action() { _classCallCheck(this, Action); - _get(Object.getPrototypeOf(Action.prototype), 'constructor', this).call(this); + _Observable.call(this); this.__DEFAULT_ICON_PATH = '/images/actions/ICON_SIZE'; this.options = LangUtils.objectMerge({ name: '', @@ -121,689 +117,664 @@ var Action = (function (_Observable) { _inherits(Action, _Observable); - _createClass(Action, [{ - key: '_evalScripts', - value: function _evalScripts(data, localScopeMetadata) { - var metadata = localScopeMetadata; - return eval(data); - } - }, { - key: 'setManager', - - /** - * Sets the manager for this action - * @param manager ActionsManager - */ - value: function setManager(manager) { - this.manager = manager; - if (this.options.subMenu) { - if (this.subMenuItems.staticItems) { - this.buildSubmenuStaticItems(); - } - if (this.subMenuItems.dynamicItems || this.subMenuItems.dynamicBuilderCode) { - this.prepareSubmenuDynamicBuilder(); - } + Action.prototype._evalScripts = function _evalScripts(data, localScopeMetadata) { + var metadata = localScopeMetadata; + return eval(data); + }; + + /** + * Sets the manager for this action + * @param manager ActionsManager + */ + + Action.prototype.setManager = function setManager(manager) { + this.manager = manager; + if (this.options.subMenu) { + if (this.subMenuItems.staticItems) { + this.buildSubmenuStaticItems(); } - if (this.options.listeners.init) { - try { - window.listenerContext = this; - if (typeof this.options.listeners.init == 'string') { - this._evalScripts(this.options.listeners.init); - } else { - this.options.listeners.init(); - } - } catch (e) { - Logger.error('Error while evaluating init script for action ' + this.options.name); - } + if (this.subMenuItems.dynamicItems || this.subMenuItems.dynamicBuilderCode) { + this.prepareSubmenuDynamicBuilder(); } } - }, { - key: 'apply', - - /** - * Execute the action code - */ - value: function apply() { - if (this.deny) { - return; - }this.manager.publishActionEvent('beforeApply-' + this.options.name); - if (this.options.prepareModal) { - var modal = this.manager.uiGetModal(); - if (modal) { - modal.prepareHeader(this.options.title, this.options.src, this.options.icon_class); + if (this.options.listeners.init) { + try { + window.listenerContext = this; + if (typeof this.options.listeners.init == 'string') { + this._evalScripts(this.options.listeners.init); + } else { + this.options.listeners.init(); } + } catch (e) { + Logger.error('Error while evaluating init script for action ' + this.options.name); } - window.actionArguments = []; - window.actionManager = this.manager; - if (arguments[0]) window.actionArguments = arguments[0]; - if (this.options.callbackCode) { - try { - this._evalScripts(this.options.callbackCode); - } catch (e) { - Logger.error(e); - } - } else if (this.options.callbackDialogNode) { - var node = this.options.callbackDialogNode; - var dialogFormId = node.getAttribute('dialogOpenForm'); - var okButtonOnly = node.getAttribute('dialogOkButtonOnly') === 'true'; - var skipButtons = node.getAttribute('dialogSkipButtons') === 'true'; - - var onOpenFunc = null;var onCompleteFunc = null;var onCancelFunc = null; - var onOpenNode = XMLUtils.XPathSelectSingleNode(node, 'dialogOnOpen'); - if (onOpenNode && onOpenNode.firstChild) onOpenFunc = new Function('oForm', onOpenNode.firstChild.nodeValue); - var onCompleteNode = XMLUtils.XPathSelectSingleNode(node, 'dialogOnComplete'); - if (onCompleteNode && onCompleteNode.firstChild) { - var completeCode = onCompleteNode.firstChild.nodeValue; - if (onCompleteNode.getAttribute('hideDialog') === 'true') { - completeCode += 'hideLightBox(true);'; - } - onCompleteFunc = new Function('oForm', completeCode); - } - var onCancelNode = XMLUtils.XPathSelectSingleNode(node, 'dialogOnCancel'); - if (onCancelNode && onCancelNode.firstChild) onCancelFunc = new Function('oForm', onCancelNode.firstChild.nodeValue); + } + }; - this.options.callback = (function () { - var modal = this.manager.uiGetModal(); - if (modal) { - modal.showDialogForm('Dialog', dialogFormId, onOpenFunc, onCompleteFunc, onCancelFunc, okButtonOnly, skipButtons); - } - }).bind(this); - this.options.callback(); - this.options.callbackDialogNode = null; - } else if (this.options.callback) { - this.options.callback(); - } - if (this.options.subMenu && arguments[0] && arguments[0][0]) { - this.notify('submenu_active', arguments[0][0]); + /** + * Execute the action code + */ + + Action.prototype.apply = function apply() { + if (this.deny) { + return; + }this.manager.publishActionEvent('beforeApply-' + this.options.name); + if (this.options.prepareModal) { + var modal = this.manager.uiGetModal(); + if (modal) { + modal.prepareHeader(this.options.title, this.options.src, this.options.icon_class); } - window.actionArguments = null; - window.actionManager = null; - this.manager.publishActionEvent('afterApply-' + this.options.name); - } - }, { - key: 'fireContextChange', - - /** - * Updates the action status on context change - * @returns void - */ - value: function fireContextChange() { - if (arguments.length < 3) { - return; - }var usersEnabled = arguments[0]; - var crtUser = arguments[1]; - - var crtIsRecycle = false; - var crtInZip = false; - var crtIsRoot = false; - var crtAjxpMime = ''; - var crtIsReadOnly = false; - - var crtNode = arguments[2]; - if (crtNode) { - crtIsRecycle = crtNode.getAjxpMime() == 'ajxp_recycle'; - crtInZip = crtNode.hasAjxpMimeInBranch('ajxp_browsable_archive'); - crtIsRoot = crtNode.isRoot(); - crtAjxpMime = crtNode.getAjxpMime(); - crtIsReadOnly = crtNode.hasMetadataInBranch('ajxp_readonly', 'true'); + } + window.actionArguments = []; + window.actionManager = this.manager; + if (arguments[0]) window.actionArguments = arguments[0]; + if (this.options.callbackCode) { + try { + this._evalScripts(this.options.callbackCode); + } catch (e) { + Logger.error(e); + } + } else if (this.options.callbackDialogNode) { + var node = this.options.callbackDialogNode; + var dialogFormId = node.getAttribute('dialogOpenForm'); + var okButtonOnly = node.getAttribute('dialogOkButtonOnly') === 'true'; + var skipButtons = node.getAttribute('dialogSkipButtons') === 'true'; + + var onOpenFunc = null;var onCompleteFunc = null;var onCancelFunc = null; + var onOpenNode = XMLUtils.XPathSelectSingleNode(node, 'dialogOnOpen'); + if (onOpenNode && onOpenNode.firstChild) onOpenFunc = new Function('oForm', onOpenNode.firstChild.nodeValue); + var onCompleteNode = XMLUtils.XPathSelectSingleNode(node, 'dialogOnComplete'); + if (onCompleteNode && onCompleteNode.firstChild) { + var completeCode = onCompleteNode.firstChild.nodeValue; + if (onCompleteNode.getAttribute('hideDialog') === 'true') { + completeCode += 'hideLightBox(true);'; + } + onCompleteFunc = new Function('oForm', completeCode); } + var onCancelNode = XMLUtils.XPathSelectSingleNode(node, 'dialogOnCancel'); + if (onCancelNode && onCancelNode.firstChild) onCancelFunc = new Function('oForm', onCancelNode.firstChild.nodeValue); - if (this.options.listeners.contextChange) { - window.listenerContext = this; - try { - this._evalScripts(this.options.listeners.contextChange); - } catch (e) { - Logger.error('Error while evaluating script for contextChange event - action ' + this.options.name); + this.options.callback = (function () { + var modal = this.manager.uiGetModal(); + if (modal) { + modal.showDialogForm('Dialog', dialogFormId, onOpenFunc, onCompleteFunc, onCancelFunc, okButtonOnly, skipButtons); } + }).bind(this); + this.options.callback(); + this.options.callbackDialogNode = null; + } else if (this.options.callback) { + this.options.callback(); + } + if (this.options.subMenu && arguments[0] && arguments[0][0]) { + this.notify('submenu_active', arguments[0][0]); + } + window.actionArguments = null; + window.actionManager = null; + this.manager.publishActionEvent('afterApply-' + this.options.name); + }; + + /** + * Updates the action status on context change + * @returns void + */ + + Action.prototype.fireContextChange = function fireContextChange() { + if (arguments.length < 3) { + return; + }var usersEnabled = arguments[0]; + var crtUser = arguments[1]; + + var crtIsRecycle = false; + var crtInZip = false; + var crtIsRoot = false; + var crtAjxpMime = ''; + var crtIsReadOnly = false; + + var crtNode = arguments[2]; + if (crtNode) { + crtIsRecycle = crtNode.getAjxpMime() == 'ajxp_recycle'; + crtInZip = crtNode.hasAjxpMimeInBranch('ajxp_browsable_archive'); + crtIsRoot = crtNode.isRoot(); + crtAjxpMime = crtNode.getAjxpMime(); + crtIsReadOnly = crtNode.hasMetadataInBranch('ajxp_readonly', 'true'); + } + + if (this.options.listeners.contextChange) { + window.listenerContext = this; + try { + this._evalScripts(this.options.listeners.contextChange); + } catch (e) { + Logger.error('Error while evaluating script for contextChange event - action ' + this.options.name); } - var rightsContext = this.rightsContext; - if (!rightsContext.noUser && !usersEnabled) { - return this.hideForContext(); - } - if (rightsContext.userLogged == 'only' && crtUser == null || rightsContext.guestLogged && rightsContext.guestLogged == 'hidden' && crtUser != null && crtUser.id == 'guest') { - return this.hideForContext(); - } - if (rightsContext.userLogged == 'hidden' && crtUser != null && !(crtUser.id == 'guest' && rightsContext.guestLogged && rightsContext.guestLogged == 'show')) { - return this.hideForContext(); - } - if (rightsContext.adminOnly && (crtUser == null || !crtUser.isAdmin)) { - return this.hideForContext(); - } - if (rightsContext.read && crtUser != null && !crtUser.canRead()) { - return this.hideForContext(); - } - if (rightsContext.write && crtUser != null && !crtUser.canWrite()) { + } + var rightsContext = this.rightsContext; + if (!rightsContext.noUser && !usersEnabled) { + return this.hideForContext(); + } + if (rightsContext.userLogged == 'only' && crtUser == null || rightsContext.guestLogged && rightsContext.guestLogged == 'hidden' && crtUser != null && crtUser.id == 'guest') { + return this.hideForContext(); + } + if (rightsContext.userLogged == 'hidden' && crtUser != null && !(crtUser.id == 'guest' && rightsContext.guestLogged && rightsContext.guestLogged == 'show')) { + return this.hideForContext(); + } + if (rightsContext.adminOnly && (crtUser == null || !crtUser.isAdmin)) { + return this.hideForContext(); + } + if (rightsContext.read && crtUser != null && !crtUser.canRead()) { + return this.hideForContext(); + } + if (rightsContext.write && crtUser != null && !crtUser.canWrite()) { + return this.hideForContext(); + } + if (rightsContext.write && crtIsReadOnly) { + return this.hideForContext(); + } + if (this.context.allowedMimes.length) { + if (this.context.allowedMimes.indexOf('*') == -1 && this.context.allowedMimes.indexOf(crtAjxpMime) == -1) { return this.hideForContext(); } - if (rightsContext.write && crtIsReadOnly) { + if (this.context.allowedMimes.indexOf('^' + crtAjxpMime) != -1) { return this.hideForContext(); } - if (this.context.allowedMimes.length) { - if (this.context.allowedMimes.indexOf('*') == -1 && this.context.allowedMimes.indexOf(crtAjxpMime) == -1) { - return this.hideForContext(); - } - if (this.context.allowedMimes.indexOf('^' + crtAjxpMime) != -1) { - return this.hideForContext(); - } - } - if (this.context.recycle) { - if (this.context.recycle == 'only' && !crtIsRecycle) { - return this.hideForContext(); - } - if (this.context.recycle == 'hidden' && crtIsRecycle) { - return this.hideForContext(); - } - } - if (!this.context.inZip && crtInZip) { + } + if (this.context.recycle) { + if (this.context.recycle == 'only' && !crtIsRecycle) { return this.hideForContext(); } - if (!this.context.root && crtIsRoot) { + if (this.context.recycle == 'hidden' && crtIsRecycle) { return this.hideForContext(); } - this.showForContext(); } - }, { - key: 'fireSelectionChange', + if (!this.context.inZip && crtInZip) { + return this.hideForContext(); + } + if (!this.context.root && crtIsRoot) { + return this.hideForContext(); + } + this.showForContext(); + }; - /** - * Upates the action status on selection change - */ - value: function fireSelectionChange() { - if (this.options.listeners.selectionChange) { - window.listenerContext = this; - try { - this._evalScripts(this.options.listeners.selectionChange); - } catch (e) { - Logger.error('Error while evaluating script for selectionChange event - action ' + this.options.name); - } - } - if (this.options.activeCondition) { - try { - var result = this.options.activeCondition(); - if (result === false) this.disable();else if (result === true) this.enable(); - } catch (e) { - Logger.error('Error while evaluating activeCondition() script for action ' + this.options.name); - } - } - if (this.contextHidden || !this.context.selection) { - return; + /** + * Upates the action status on selection change + */ + + Action.prototype.fireSelectionChange = function fireSelectionChange() { + if (this.options.listeners.selectionChange) { + window.listenerContext = this; + try { + this._evalScripts(this.options.listeners.selectionChange); + } catch (e) { + Logger.error('Error while evaluating script for selectionChange event - action ' + this.options.name); } - var userSelection = arguments[0]; - var hasRoot = false; - if (userSelection != null) { - hasRoot = userSelection.selectionHasRootNode(); - var bUnique = userSelection.isUnique(); - var bFile = userSelection.hasFile(); - var bDir = userSelection.hasDir(); - var bRecycle = userSelection.isRecycle(); + } + if (this.options.activeCondition) { + try { + var result = this.options.activeCondition(); + if (result === false) this.disable();else if (result === true) this.enable(); + } catch (e) { + Logger.error('Error while evaluating activeCondition() script for action ' + this.options.name); } - var selectionContext = this.selectionContext; - if (selectionContext.allowedMimes.length) { + } + if (this.contextHidden || !this.context.selection) { + return; + } + var userSelection = arguments[0]; + var hasRoot = false; + if (userSelection != null) { + hasRoot = userSelection.selectionHasRootNode(); + var bUnique = userSelection.isUnique(); + var bFile = userSelection.hasFile(); + var bDir = userSelection.hasDir(); + var bRecycle = userSelection.isRecycle(); + } + var selectionContext = this.selectionContext; + if (selectionContext.allowedMimes.length) { + if (selectionContext.behaviour == 'hidden') this.hide();else this.disable(); + } + if (selectionContext.evalMetadata && userSelection && userSelection.isUnique()) { + var result = this._evalScripts(selectionContext.evalMetadata, userSelection.getUniqueNode().getMetadata()); + if (!result) { if (selectionContext.behaviour == 'hidden') this.hide();else this.disable(); + return; } - if (selectionContext.evalMetadata && userSelection && userSelection.isUnique()) { - var result = this._evalScripts(selectionContext.evalMetadata, userSelection.getUniqueNode().getMetadata()); - if (!result) { - if (selectionContext.behaviour == 'hidden') this.hide();else this.disable(); - return; - } - } - if (!selectionContext.enableRoot && hasRoot) { - return this.disable(); - } - if (selectionContext.unique && !bUnique) { - return this.disable(); - } - if (selectionContext.multipleOnly && bUnique) { - return this.disable(); - } - if ((selectionContext.file || selectionContext.dir) && !bFile && !bDir) { - return this.disable(); - } - if (selectionContext.dir && !selectionContext.file && bFile || !selectionContext.dir && selectionContext.file && bDir) { - return this.disable(); - } - if (!selectionContext.recycle && bRecycle) { - return this.disable(); - } - if (this.rightsContext.write && userSelection.hasReadOnly()) { + } + if (!selectionContext.enableRoot && hasRoot) { + return this.disable(); + } + if (selectionContext.unique && !bUnique) { + return this.disable(); + } + if (selectionContext.multipleOnly && bUnique) { + return this.disable(); + } + if ((selectionContext.file || selectionContext.dir) && !bFile && !bDir) { + return this.disable(); + } + if (selectionContext.dir && !selectionContext.file && bFile || !selectionContext.dir && selectionContext.file && bDir) { + return this.disable(); + } + if (!selectionContext.recycle && bRecycle) { + return this.disable(); + } + if (this.rightsContext.write && userSelection.hasReadOnly()) { + return this.disable(); + } + if (selectionContext.allowedMimes.length && userSelection && selectionContext.allowedMimes.indexOf('*') == -1 && !userSelection.hasMime(selectionContext.allowedMimes)) { + if (selectionContext.behaviour == 'hidden') { + return this.hide(); + } else { return this.disable(); } - if (selectionContext.allowedMimes.length && userSelection && selectionContext.allowedMimes.indexOf('*') == -1 && !userSelection.hasMime(selectionContext.allowedMimes)) { + } + if (selectionContext.allowedMimes.length && userSelection && selectionContext.allowedMimes.indexOf('^') !== -1) { + var forbiddenValueFound = false; + selectionContext.allowedMimes.forEach(function (m) { + if (m.indexOf('^') == -1) return; + if (userSelection.hasMime([m.replace('^', '')])) { + forbiddenValueFound = true; + //throw $break; + } + }); + if (forbiddenValueFound) { if (selectionContext.behaviour == 'hidden') { return this.hide(); } else { return this.disable(); } } - if (selectionContext.allowedMimes.length && userSelection && selectionContext.allowedMimes.indexOf('^') !== -1) { - var forbiddenValueFound = false; - selectionContext.allowedMimes.forEach(function (m) { - if (m.indexOf('^') == -1) return; - if (userSelection.hasMime([m.replace('^', '')])) { - forbiddenValueFound = true; - //throw $break; - } - }); - if (forbiddenValueFound) { - if (selectionContext.behaviour == 'hidden') { - return this.hide(); - } else { - return this.disable(); - } + } + this.show(); + this.enable(); + }; + + /** + * Parses an XML fragment to configure this action + * @param xmlNode Node XML Fragment describing the action + */ + + Action.prototype.createFromXML = function createFromXML(xmlNode) { + + this.options.name = xmlNode.getAttribute('name'); + for (var i = 0; i < xmlNode.childNodes.length; i++) { + var node = xmlNode.childNodes[i]; + var defaultAttributes = { + dir: 'dirDefault', + file: 'fileDefault', + dragndrop: 'dragndropDefault', + ctrldragndrop: 'ctrlDragndropDefault', + expire: 'expireDefault' + }; + for (var key in defaultAttributes) { + if (!defaultAttributes.hasOwnProperty(key)) continue; + var value = defaultAttributes[key]; + if (xmlNode.getAttribute(value) && xmlNode.getAttribute(value) == 'true') { + if (!this.defaults) this.defaults = {}; + this.defaults[key] = true; } } - this.show(); - this.enable(); - } - }, { - key: 'createFromXML', - - /** - * Parses an XML fragment to configure this action - * @param xmlNode Node XML Fragment describing the action - */ - value: function createFromXML(xmlNode) { - - this.options.name = xmlNode.getAttribute('name'); - for (var i = 0; i < xmlNode.childNodes.length; i++) { - var node = xmlNode.childNodes[i]; - var defaultAttributes = { - dir: 'dirDefault', - file: 'fileDefault', - dragndrop: 'dragndropDefault', - ctrldragndrop: 'ctrlDragndropDefault', - expire: 'expireDefault' - }; - for (var key in defaultAttributes) { - if (!defaultAttributes.hasOwnProperty(key)) continue; - var value = defaultAttributes[key]; - if (xmlNode.getAttribute(value) && xmlNode.getAttribute(value) == 'true') { - if (!this.defaults) this.defaults = {}; - this.defaults[key] = true; - } - } - var j; - if (node.nodeName == 'processing') { - var clientFormData = {}; - for (j = 0; j < node.childNodes.length; j++) { - var processNode = node.childNodes[j]; - if (processNode.nodeName == 'clientForm') { - // TODO: Filtering by theme - if (!processNode.getAttribute('theme') || pydio.Parameters.get('theme') == processNode.getAttribute('theme')) { - clientFormData.formId = processNode.getAttribute('id'); - clientFormData.formCode = processNode.firstChild.nodeValue; - } - } else if (processNode.nodeName == 'clientCallback') { - if (processNode.getAttribute('prepareModal') && processNode.getAttribute('prepareModal') == 'true') { - this.options.prepareModal = true; - } - if (processNode.getAttribute('dialogOpenForm')) { - this.options.callbackDialogNode = processNode; - } else if (processNode.firstChild) { - this.options.callbackCode = processNode.firstChild.nodeValue.trim(); - } - } else if (processNode.nodeName == 'clientListener' && processNode.firstChild) { - this.options.listeners[processNode.getAttribute('name')] = processNode.firstChild.nodeValue.trim(); - } else if (processNode.nodeName == 'activeCondition' && processNode.firstChild) { - this.options.activeCondition = new Function(processNode.firstChild.nodeValue.trim()); + var j; + if (node.nodeName == 'processing') { + var clientFormData = {}; + for (j = 0; j < node.childNodes.length; j++) { + var processNode = node.childNodes[j]; + if (processNode.nodeName == 'clientForm') { + // TODO: Filtering by theme + if (!processNode.getAttribute('theme') || pydio.Parameters.get('theme') == processNode.getAttribute('theme')) { + clientFormData.formId = processNode.getAttribute('id'); + clientFormData.formCode = processNode.firstChild.nodeValue; } - } - if (clientFormData.formId) { - this.options.formId = clientFormData.formId; - this.options.formCode = clientFormData.formCode; - if (this.options.formCode && this.options.formId) { - this.manager.uiInsertForm(this.options.formId, this.options.formCode); + } else if (processNode.nodeName == 'clientCallback') { + if (processNode.getAttribute('prepareModal') && processNode.getAttribute('prepareModal') == 'true') { + this.options.prepareModal = true; } - } - } else if (node.nodeName == 'gui') { - this.options.text_id = node.getAttribute('text'); - this.options.title_id = node.getAttribute('title'); - this.options.text = this.manager.getMessage(node.getAttribute('text')) || 'not_found'; - this.options.title = this.manager.getMessage(node.getAttribute('title')) || 'not_found'; - this.options.src = node.getAttribute('src'); - this.options.icon_class = node.getAttribute('iconClass'); - if (node.getAttribute('hasAccessKey') && node.getAttribute('hasAccessKey') == 'true') { - this.options.accessKey = node.getAttribute('accessKey'); - this.options.hasAccessKey = true; - } - if (node.getAttribute('specialAccessKey')) { - this.options.specialAccessKey = node.getAttribute('specialAccessKey'); - } - for (j = 0; j < node.childNodes.length; j++) { - if (node.childNodes[j].nodeName == 'context') { - this.attributesToObject(this.context, node.childNodes[j]); - if (this.context.ajxpWidgets) { - this.context.ajxpWidgets = this.context.ajxpWidgets.split(','); - } else { - this.context.ajxpWidgets = []; - } - // Backward compatibility - if (this.context.infoPanel) this.context.ajxpWidgets.push('InfoPanel'); - if (this.context.actionBar) this.context.ajxpWidgets.push('ActionsToolbar'); - } else if (node.childNodes[j].nodeName == 'selectionContext') { - this.attributesToObject(this.selectionContext, node.childNodes[j]); + if (processNode.getAttribute('dialogOpenForm')) { + this.options.callbackDialogNode = processNode; + } else if (processNode.firstChild) { + this.options.callbackCode = processNode.firstChild.nodeValue.trim(); } + } else if (processNode.nodeName == 'clientListener' && processNode.firstChild) { + this.options.listeners[processNode.getAttribute('name')] = processNode.firstChild.nodeValue.trim(); + } else if (processNode.nodeName == 'activeCondition' && processNode.firstChild) { + this.options.activeCondition = new Function(processNode.firstChild.nodeValue.trim()); } - } else if (node.nodeName == 'rightsContext') { - this.attributesToObject(this.rightsContext, node); - } else if (node.nodeName == 'subMenu') { - this.options.subMenu = true; - if (node.getAttribute('updateImageOnSelect') && node.getAttribute('updateImageOnSelect') == 'true') { - this.options.subMenuUpdateImage = true; + } + if (clientFormData.formId) { + this.options.formId = clientFormData.formId; + this.options.formCode = clientFormData.formCode; + if (this.options.formCode && this.options.formId) { + this.manager.uiInsertForm(this.options.formId, this.options.formCode); } - if (node.getAttribute('updateTitleOnSelect') && node.getAttribute('updateTitleOnSelect') == 'true') { - this.options.subMenuUpdateTitle = true; + } + } else if (node.nodeName == 'gui') { + this.options.text_id = node.getAttribute('text'); + this.options.title_id = node.getAttribute('title'); + this.options.text = this.manager.getMessage(node.getAttribute('text')) || 'not_found'; + this.options.title = this.manager.getMessage(node.getAttribute('title')) || 'not_found'; + this.options.src = node.getAttribute('src'); + this.options.icon_class = node.getAttribute('iconClass'); + if (node.getAttribute('hasAccessKey') && node.getAttribute('hasAccessKey') == 'true') { + this.options.accessKey = node.getAttribute('accessKey'); + this.options.hasAccessKey = true; + } + if (node.getAttribute('specialAccessKey')) { + this.options.specialAccessKey = node.getAttribute('specialAccessKey'); + } + for (j = 0; j < node.childNodes.length; j++) { + if (node.childNodes[j].nodeName == 'context') { + this.attributesToObject(this.context, node.childNodes[j]); + if (this.context.ajxpWidgets) { + this.context.ajxpWidgets = this.context.ajxpWidgets.split(','); + } else { + this.context.ajxpWidgets = []; + } + // Backward compatibility + if (this.context.infoPanel) this.context.ajxpWidgets.push('InfoPanel'); + if (this.context.actionBar) this.context.ajxpWidgets.push('ActionsToolbar'); + } else if (node.childNodes[j].nodeName == 'selectionContext') { + this.attributesToObject(this.selectionContext, node.childNodes[j]); } - for (j = 0; j < node.childNodes.length; j++) { - if (node.childNodes[j].nodeName == 'staticItems' || node.childNodes[j].nodeName == 'dynamicItems') { - this.subMenuItems[node.childNodes[j].nodeName] = []; - for (var k = 0; k < node.childNodes[j].childNodes.length; k++) { - if (node.childNodes[j].childNodes[k].nodeName.startsWith('item')) { - var item = {}; - for (var z = 0; z < node.childNodes[j].childNodes[k].attributes.length; z++) { - var attribute = node.childNodes[j].childNodes[k].attributes[z]; - item[attribute.nodeName] = attribute.value; - } - this.subMenuItems[node.childNodes[j].nodeName].push(item); + } + } else if (node.nodeName == 'rightsContext') { + this.attributesToObject(this.rightsContext, node); + } else if (node.nodeName == 'subMenu') { + this.options.subMenu = true; + if (node.getAttribute('updateImageOnSelect') && node.getAttribute('updateImageOnSelect') == 'true') { + this.options.subMenuUpdateImage = true; + } + if (node.getAttribute('updateTitleOnSelect') && node.getAttribute('updateTitleOnSelect') == 'true') { + this.options.subMenuUpdateTitle = true; + } + for (j = 0; j < node.childNodes.length; j++) { + if (node.childNodes[j].nodeName == 'staticItems' || node.childNodes[j].nodeName == 'dynamicItems') { + this.subMenuItems[node.childNodes[j].nodeName] = []; + for (var k = 0; k < node.childNodes[j].childNodes.length; k++) { + if (node.childNodes[j].childNodes[k].nodeName.startsWith('item')) { + var item = {}; + for (var z = 0; z < node.childNodes[j].childNodes[k].attributes.length; z++) { + var attribute = node.childNodes[j].childNodes[k].attributes[z]; + item[attribute.nodeName] = attribute.value; } + this.subMenuItems[node.childNodes[j].nodeName].push(item); } - } else if (node.childNodes[j].nodeName == 'dynamicBuilder') { - this.subMenuItems.dynamicBuilderCode = node.childNodes[j].firstChild.nodeValue; } + } else if (node.childNodes[j].nodeName == 'dynamicBuilder') { + this.subMenuItems.dynamicBuilderCode = node.childNodes[j].firstChild.nodeValue; } } } - if (!this.options.hasAccessKey) { - return; - }if (this.options.accessKey == '' || !this.manager.getMessage(this.options.accessKey) || this.options.text.indexOf(this.manager.getMessage(this.options.accessKey)) == -1) { - this.options.accessKey = this.options.text.charAt(0); - } else { - this.options.accessKey = this.manager.getMessage(this.options.accessKey); - } } - }, { - key: 'buildSubmenuStaticItems', + if (!this.options.hasAccessKey) { + return; + }if (this.options.accessKey == '' || !this.manager.getMessage(this.options.accessKey) || this.options.text.indexOf(this.manager.getMessage(this.options.accessKey)) == -1) { + this.options.accessKey = this.options.text.charAt(0); + } else { + this.options.accessKey = this.manager.getMessage(this.options.accessKey); + } + }; - /** - * Creates the submenu items - */ - value: function buildSubmenuStaticItems() { - var menuItems = []; - if (this.subMenuItems.staticItems) { - this.subMenuItems.staticItems.forEach(function (item) { - var itemText = this.manager.getMessage(item.text); - if (item.hasAccessKey && (item.hasAccessKey == 'true' || item.hasAccessKey === true) && this.manager.getMessage(item.accessKey)) { - itemText = this.getKeyedText(this.manager.getMessage(item.text), true, this.manager.getMessage(item.accessKey)); - if (!this.subMenuItems.accessKeys) this.subMenuItems.accessKeys = []; - this.manager.registerKey(this.manager.getMessage(item.accessKey), this.options.name, item.command); - } - menuItems.push({ - name: itemText, - alt: this.manager.getMessage(item.title), - image_unresolved: item.src, - icon_class: item.icon_class, - isDefault: item.isDefault ? true : false, - callback: (function () { - this.apply([item]); - }).bind(this) - }); - }, this); - } - this.subMenuItems.staticOptions = menuItems; - } - }, { - key: 'prepareSubmenuDynamicBuilder', - - /** - * Caches some data for dynamically built menus - */ - value: function prepareSubmenuDynamicBuilder() { - this.subMenuItems.dynamicBuilder = (function (protoMenu) { - var menuItems; - setTimeout((function () { - if (this.subMenuItems.dynamicBuilderCode) { - window.builderContext = this; - window.builderProtoMenu = protoMenu; - this._evalScripts(this.subMenuItems.dynamicBuilderCode); - menuItems = this.builderMenuItems || []; - } else { - menuItems = []; - this.subMenuItems.dynamicItems.forEach(function (item) { - if (item.separator) { - menuItems.push(item); - return; + /** + * Creates the submenu items + */ + + Action.prototype.buildSubmenuStaticItems = function buildSubmenuStaticItems() { + var menuItems = []; + if (this.subMenuItems.staticItems) { + this.subMenuItems.staticItems.forEach(function (item) { + var itemText = this.manager.getMessage(item.text); + if (item.hasAccessKey && (item.hasAccessKey == 'true' || item.hasAccessKey === true) && this.manager.getMessage(item.accessKey)) { + itemText = this.getKeyedText(this.manager.getMessage(item.text), true, this.manager.getMessage(item.accessKey)); + if (!this.subMenuItems.accessKeys) this.subMenuItems.accessKeys = []; + this.manager.registerKey(this.manager.getMessage(item.accessKey), this.options.name, item.command); + } + menuItems.push({ + name: itemText, + alt: this.manager.getMessage(item.title), + image_unresolved: item.src, + icon_class: item.icon_class, + isDefault: item.isDefault ? true : false, + callback: (function () { + this.apply([item]); + }).bind(this) + }); + }, this); + } + this.subMenuItems.staticOptions = menuItems; + }; + + /** + * Caches some data for dynamically built menus + */ + + Action.prototype.prepareSubmenuDynamicBuilder = function prepareSubmenuDynamicBuilder() { + this.subMenuItems.dynamicBuilder = (function (protoMenu) { + var menuItems; + setTimeout((function () { + if (this.subMenuItems.dynamicBuilderCode) { + window.builderContext = this; + window.builderProtoMenu = protoMenu; + this._evalScripts(this.subMenuItems.dynamicBuilderCode); + menuItems = this.builderMenuItems || []; + } else { + menuItems = []; + this.subMenuItems.dynamicItems.forEach(function (item) { + if (item.separator) { + menuItems.push(item); + return; + } + var action = this.manager.actions.get(item.actionId); + if (action.deny) return; + var itemData = { + name: action.getKeyedText(), + alt: action.options.title, + icon_class: action.options.icon_class, + image_unresolved: action.options.src, + callback: (function () { + this.apply(); + }).bind(action) + }; + if (action.options.subMenu) { + itemData.subMenu = []; + if (action.subMenuItems.staticOptions) { + itemData.subMenu = action.subMenuItems.staticOptions; } - var action = this.manager.actions.get(item.actionId); - if (action.deny) return; - var itemData = { - name: action.getKeyedText(), - alt: action.options.title, - icon_class: action.options.icon_class, - image_unresolved: action.options.src, - callback: (function () { - this.apply(); - }).bind(action) - }; - if (action.options.subMenu) { - itemData.subMenu = []; - if (action.subMenuItems.staticOptions) { - itemData.subMenu = action.subMenuItems.staticOptions; - } - if (action.subMenuItems.dynamicBuilder) { - itemData.subMenuBeforeShow = action.subMenuItems.dynamicBuilder; - } + if (action.subMenuItems.dynamicBuilder) { + itemData.subMenuBeforeShow = action.subMenuItems.dynamicBuilder; } - menuItems.push(itemData); - }, this); - } - protoMenu.options.menuItems = menuItems; - protoMenu.refreshList(); - }).bind(this), 0); - }).bind(this); + } + menuItems.push(itemData); + }, this); + } + protoMenu.options.menuItems = menuItems; + protoMenu.refreshList(); + }).bind(this), 0); + }).bind(this); + }; + + /** + * Refresh icon image source + * @param newSrc String The image source. Can reference an image library + * @param iconClass String Optional class to replace image + */ + + Action.prototype.setIconSrc = function setIconSrc(newSrc, iconClass) { + this.options.src = newSrc; + var previousIconClass = this.options.icon_class; + this.notify('update_icon', { new_src: newSrc, new_class: iconClass, previous_class: previousIconClass }); + if (iconClass) { + this.options.icon_class = iconClass; } - }, { - key: 'setIconSrc', - - /** - * Refresh icon image source - * @param newSrc String The image source. Can reference an image library - * @param iconClass String Optional class to replace image - */ - value: function setIconSrc(newSrc, iconClass) { - this.options.src = newSrc; - var previousIconClass = this.options.icon_class; - this.notify('update_icon', { new_src: newSrc, new_class: iconClass, previous_class: previousIconClass }); - if (iconClass) { - this.options.icon_class = iconClass; - } + }; + + /** + * Refresh the action label + * @param newLabel String the new label + * @param newTitle String the new tooltip + */ + + Action.prototype.setLabel = function setLabel(newLabel, newTitle) { + this.options.text = this.manager.getMessage(newLabel); + this.notify('update_label', this.getKeyedText()); + if (newTitle) { + this.options.title = this.manager.getMessage(newTitle); + this.notify('update_title', this.options.title); } - }, { - key: 'setLabel', - - /** - * Refresh the action label - * @param newLabel String the new label - * @param newTitle String the new tooltip - */ - value: function setLabel(newLabel, newTitle) { - this.options.text = this.manager.getMessage(newLabel); - this.notify('update_label', this.getKeyedText()); - if (newTitle) { - this.options.title = this.manager.getMessage(newTitle); - this.notify('update_title', this.options.title); - } + }; + + Action.prototype.refreshInstances = function refreshInstances() {}; + + /** + * Grab its label from the i18n + */ + + Action.prototype.refreshFromI18NHash = function refreshFromI18NHash() { + this.setLabel(this.options.text_id, this.options.title_id); + }; + + /** + * Return data necessary to build InfoPanel + * @returns Object + */ + + Action.prototype.toInfoPanel = function toInfoPanel() { + return this.options; + }; + + /** + * Return necessary data to build contextual menu + * @returns Object + */ + + Action.prototype.toContextMenu = function toContextMenu() { + return this.options; + }; + + /** + * Changes show/hide state + */ + + Action.prototype.hideForContext = function hideForContext() { + this.hide(); + this.contextHidden = true; + }; + + /** + * Changes show/hide state + */ + + Action.prototype.showForContext = function showForContext() { + this.contextHidden = false; + this.show(); + if (this.selectionContext) { + this.fireSelectionChange(); } - }, { - key: 'refreshInstances', - value: function refreshInstances() {} - }, { - key: 'refreshFromI18NHash', - - /** - * Grab its label from the i18n - */ - value: function refreshFromI18NHash() { - this.setLabel(this.options.text_id, this.options.title_id); - } - }, { - key: 'toInfoPanel', - - /** - * Return data necessary to build InfoPanel - * @returns Object - */ - value: function toInfoPanel() { - return this.options; - } - }, { - key: 'toContextMenu', - - /** - * Return necessary data to build contextual menu - * @returns Object - */ - value: function toContextMenu() { - return this.options; - } - }, { - key: 'hideForContext', - - /** - * Changes show/hide state - */ - value: function hideForContext() { - this.hide(); - this.contextHidden = true; - } - }, { - key: 'showForContext', - - /** - * Changes show/hide state - */ - value: function showForContext() { - this.contextHidden = false; - this.show(); - if (this.selectionContext) { - this.fireSelectionChange(); - } + }; + + /** + * Changes show/hide state + * Notifies "hide" Event + */ + + Action.prototype.hide = function hide() { + this.deny = true; + this.notify('hide'); + }; + + /** + * Changes show/hide state + * Notifies "show" Event + */ + + Action.prototype.show = function show() { + this.deny = false; + this.notify('show'); + }; + + /** + * Changes enable/disable state + * Notifies "disable" Event + */ + + Action.prototype.disable = function disable() { + this.deny = true; + this.notify('disable'); + }; + + /** + * Changes enable/disable state + * Notifies "enable" Event + */ + + Action.prototype.enable = function enable() { + this.deny = false; + this.notify('enable'); + }; + + /** + * To be called when removing + */ + + Action.prototype.remove = function remove() { + this.notify('remove'); + if (this.options.formId) { + this.manager.uiRemoveForm(this.options.formId); } - }, { - key: 'hide', - - /** - * Changes show/hide state - * Notifies "hide" Event - */ - value: function hide() { - this.deny = true; - this.notify('hide'); - } - }, { - key: 'show', - - /** - * Changes show/hide state - * Notifies "show" Event - */ - value: function show() { - this.deny = false; - this.notify('show'); - } - }, { - key: 'disable', - - /** - * Changes enable/disable state - * Notifies "disable" Event - */ - value: function disable() { - this.deny = true; - this.notify('disable'); - } - }, { - key: 'enable', - - /** - * Changes enable/disable state - * Notifies "enable" Event - */ - value: function enable() { - this.deny = false; - this.notify('enable'); - } - }, { - key: 'remove', - - /** - * To be called when removing - */ - value: function remove() { - this.notify('remove'); - if (this.options.formId) { - this.manager.uiRemoveForm(this.options.formId); - } + }; + + /** + * Create a text label with access-key underlined. + * @param displayString String the label + * @param hasAccessKey Boolean whether there is an accessKey or not + * @param accessKey String The key to underline + * @returns String + */ + + Action.prototype.getKeyedText = function getKeyedText(displayString, hasAccessKey, accessKey) { + if (!displayString) { + displayString = this.options.text; } - }, { - key: 'getKeyedText', - - /** - * Create a text label with access-key underlined. - * @param displayString String the label - * @param hasAccessKey Boolean whether there is an accessKey or not - * @param accessKey String The key to underline - * @returns String - */ - value: function getKeyedText(displayString, hasAccessKey, accessKey) { - if (!displayString) { - displayString = this.options.text; - } - if (!hasAccessKey) { - hasAccessKey = this.options.hasAccessKey; - } - if (!accessKey) { - accessKey = this.options.accessKey; - } - if (!hasAccessKey) { - return displayString; - }var keyPos = displayString.toLowerCase().indexOf(accessKey.toLowerCase()); - if (keyPos == -1) { - return displayString + ' (' + accessKey + ')'; - } - if (displayString.charAt(keyPos) != accessKey) { - // case differ - accessKey = displayString.charAt(keyPos); - } - var returnString = displayString.substring(0, displayString.indexOf(accessKey)); - returnString += '' + accessKey + ''; - returnString += displayString.substring(displayString.indexOf(accessKey) + 1, displayString.length); - return returnString; - } - }, { - key: 'attributesToObject', - - /** - * Utilitary function to transform XML Node attributes into Object mapping keys. - * @param object Object The target object - * @param node Node The source node - */ - value: function attributesToObject(object, node) { - for (var key in object) { - if (!object.hasOwnProperty(key) || !node.getAttribute(key)) continue; - var value = node.getAttribute(key); - if (value == 'true') value = true;else if (value == 'false') value = false; - if (key == 'allowedMimes') { - if (value && value.split(',').length) { - value = value.split(','); - } else { - value = []; - } + if (!hasAccessKey) { + hasAccessKey = this.options.hasAccessKey; + } + if (!accessKey) { + accessKey = this.options.accessKey; + } + if (!hasAccessKey) { + return displayString; + }var keyPos = displayString.toLowerCase().indexOf(accessKey.toLowerCase()); + if (keyPos == -1) { + return displayString + ' (' + accessKey + ')'; + } + if (displayString.charAt(keyPos) != accessKey) { + // case differ + accessKey = displayString.charAt(keyPos); + } + var returnString = displayString.substring(0, displayString.indexOf(accessKey)); + returnString += '' + accessKey + ''; + returnString += displayString.substring(displayString.indexOf(accessKey) + 1, displayString.length); + return returnString; + }; + + /** + * Utilitary function to transform XML Node attributes into Object mapping keys. + * @param object Object The target object + * @param node Node The source node + */ + + Action.prototype.attributesToObject = function attributesToObject(object, node) { + for (var key in object) { + if (!object.hasOwnProperty(key) || !node.getAttribute(key)) continue; + var value = node.getAttribute(key); + if (value == 'true') value = true;else if (value == 'false') value = false; + if (key == 'allowedMimes') { + if (value && value.split(',').length) { + value = value.split(','); + } else { + value = []; } - object[key] = value; } + object[key] = value; } - }]); + }; return Action; })(Observable); diff --git a/core/src/plugins/gui.ajax/res/js/core/model/AjxpNode.js b/core/src/plugins/gui.ajax/res/js/core/model/AjxpNode.js index 18e72ea9ef..90b7d2ef1b 100644 --- a/core/src/plugins/gui.ajax/res/js/core/model/AjxpNode.js +++ b/core/src/plugins/gui.ajax/res/js/core/model/AjxpNode.js @@ -2,10 +2,6 @@ var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; -var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - -var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; - var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; var AjxpNode = (function (_Observable) { @@ -27,7 +23,7 @@ var AjxpNode = (function (_Observable) { _classCallCheck(this, AjxpNode); - _get(Object.getPrototypeOf(AjxpNode.prototype), 'constructor', this).call(this); + _Observable.call(this); this._path = path; if (this._path && this._path.length && this._path.length > 1) { if (this._path[this._path.length - 1] == '/') { @@ -49,452 +45,421 @@ var AjxpNode = (function (_Observable) { _inherits(AjxpNode, _Observable); - _createClass(AjxpNode, [{ - key: 'isLoaded', + /** + * The node is loaded or not + * @returns Boolean + */ - /** - * The node is loaded or not - * @returns Boolean - */ - value: function isLoaded() { - return this._isLoaded; - } - }, { - key: 'setLoaded', - - /** - * Changes loaded status - * @param bool Boolean - */ - value: function setLoaded(bool) { - this._isLoaded = bool; - } - }, { - key: 'load', - - /** - * Loads the node using its own provider or the one passed - * @param iAjxpNodeProvider IAjxpNodeProvider Optionnal - */ - value: function load(iAjxpNodeProvider) { - if (this._isLoading) { - return; - }if (!iAjxpNodeProvider) { - if (this._iNodeProvider) { - iAjxpNodeProvider = this._iNodeProvider; - } else { - iAjxpNodeProvider = new RemoteNodeProvider(); - } - } - this._isLoading = true; - this.notify('loading'); - if (this._isLoaded) { - this._isLoading = false; - this.notify('loaded'); - return; + AjxpNode.prototype.isLoaded = function isLoaded() { + return this._isLoaded; + }; + + /** + * Changes loaded status + * @param bool Boolean + */ + + AjxpNode.prototype.setLoaded = function setLoaded(bool) { + this._isLoaded = bool; + }; + + /** + * Loads the node using its own provider or the one passed + * @param iAjxpNodeProvider IAjxpNodeProvider Optionnal + */ + + AjxpNode.prototype.load = function load(iAjxpNodeProvider) { + if (this._isLoading) { + return; + }if (!iAjxpNodeProvider) { + if (this._iNodeProvider) { + iAjxpNodeProvider = this._iNodeProvider; + } else { + iAjxpNodeProvider = new RemoteNodeProvider(); } - iAjxpNodeProvider.loadNode(this, (function (node) { - this._isLoaded = true; - this._isLoading = false; - this.notify('loaded'); - this.notify('first_load'); - }).bind(this)); - } - }, { - key: 'reload', - - /** - * Remove children and reload node - * @param iAjxpNodeProvider IAjxpNodeProvider Optionnal - */ - value: function reload(iAjxpNodeProvider) { - this._children.forEach(function (child, key) { - child.notify('node_removed'); - child._parentNode = null; - this._children['delete'](key); - this.notify('child_removed', child); - }, this); - this._isLoaded = false; - this.load(iAjxpNodeProvider); - } - }, { - key: 'clear', - - /** - * Unload child and notify "force_clear" - */ - value: function clear() { - this._children.forEach(function (child, key) { - child.notify('node_removed'); - child._parentNode = null; - this._children['delete'](key); - this.notify('child_removed', child); - }, this); - this._isLoaded = false; - this.notify('force_clear'); } - }, { - key: 'setRoot', - - /** - * Sets this AjxpNode as being the root parent - */ - value: function setRoot() { - this._isRoot = true; + this._isLoading = true; + this.notify('loading'); + if (this._isLoaded) { + this._isLoading = false; + this.notify('loaded'); + return; } - }, { - key: 'setChildren', - - /** - * Set the node children as a bunch - * @param ajxpNodes AjxpNodes[] - */ - value: function setChildren(ajxpNodes) { - this._children = new Map(); - ajxpNodes.forEach((function (value) { - this._children.set(value.getPath(), value); - value.setParent(this); - }).bind(this)); + iAjxpNodeProvider.loadNode(this, (function (node) { + this._isLoaded = true; + this._isLoading = false; + this.notify('loaded'); + this.notify('first_load'); + }).bind(this)); + }; + + /** + * Remove children and reload node + * @param iAjxpNodeProvider IAjxpNodeProvider Optionnal + */ + + AjxpNode.prototype.reload = function reload(iAjxpNodeProvider) { + this._children.forEach(function (child, key) { + child.notify('node_removed'); + child._parentNode = null; + this._children['delete'](key); + this.notify('child_removed', child); + }, this); + this._isLoaded = false; + this.load(iAjxpNodeProvider); + }; + + /** + * Unload child and notify "force_clear" + */ + + AjxpNode.prototype.clear = function clear() { + this._children.forEach(function (child, key) { + child.notify('node_removed'); + child._parentNode = null; + this._children['delete'](key); + this.notify('child_removed', child); + }, this); + this._isLoaded = false; + this.notify('force_clear'); + }; + + /** + * Sets this AjxpNode as being the root parent + */ + + AjxpNode.prototype.setRoot = function setRoot() { + this._isRoot = true; + }; + + /** + * Set the node children as a bunch + * @param ajxpNodes AjxpNodes[] + */ + + AjxpNode.prototype.setChildren = function setChildren(ajxpNodes) { + this._children = new Map(); + ajxpNodes.forEach((function (value) { + this._children.set(value.getPath(), value); + value.setParent(this); + }).bind(this)); + }; + + /** + * Get all children as a bunch + * @returns AjxpNode[] + */ + + AjxpNode.prototype.getChildren = function getChildren() { + return this._children; + }; + + AjxpNode.prototype.getFirstChildIfExists = function getFirstChildIfExists() { + if (this._children.size) { + return this._children.values().next().value; } - }, { - key: 'getChildren', - - /** - * Get all children as a bunch - * @returns AjxpNode[] - */ - value: function getChildren() { - return this._children; + return null; + }; + + /** + * Adds a child to children + * @param ajxpNode AjxpNode The child + */ + + AjxpNode.prototype.addChild = function addChild(ajxpNode) { + ajxpNode.setParent(this); + if (this._iNodeProvider) ajxpNode._iNodeProvider = this._iNodeProvider; + var existingNode = this.findChildByPath(ajxpNode.getPath()); + if (existingNode && !(existingNode instanceof String)) { + existingNode.replaceBy(ajxpNode, 'override'); + } else { + this._children.set(ajxpNode.getPath(), ajxpNode); + this.notify('child_added', ajxpNode.getPath()); } - }, { - key: 'getFirstChildIfExists', - value: function getFirstChildIfExists() { - if (this._children.size) { - return this._children.values().next().value; + }; + + /** + * Removes the child from the children + * @param ajxpNode AjxpNode + */ + + AjxpNode.prototype.removeChild = function removeChild(ajxpNode) { + var removePath = ajxpNode.getPath(); + ajxpNode.notify('node_removed'); + ajxpNode._parentNode = null; + this._children['delete'](ajxpNode.getPath()); + this.notify('child_removed', removePath); + }; + + /** + * Replaces the current node by a new one. Copy all properties deeply + * @param ajxpNode AjxpNode + * @param metaMerge + */ + + AjxpNode.prototype.replaceBy = function replaceBy(ajxpNode, metaMerge) { + this._isLeaf = ajxpNode._isLeaf; + if (ajxpNode.getPath() && this._path != ajxpNode.getPath()) { + var originalPath = this._path; + if (this.getParent()) { + var parentChildrenIndex = this.getParent()._children; + parentChildrenIndex.set(ajxpNode.getPath(), this); + parentChildrenIndex['delete'](originalPath); } - return null; + this._path = ajxpNode.getPath(); + var pathChanged = true; } - }, { - key: 'addChild', - - /** - * Adds a child to children - * @param ajxpNode AjxpNode The child - */ - value: function addChild(ajxpNode) { - ajxpNode.setParent(this); - if (this._iNodeProvider) ajxpNode._iNodeProvider = this._iNodeProvider; - var existingNode = this.findChildByPath(ajxpNode.getPath()); - if (existingNode && !(existingNode instanceof String)) { - existingNode.replaceBy(ajxpNode, 'override'); - } else { - this._children.set(ajxpNode.getPath(), ajxpNode); - this.notify('child_added', ajxpNode.getPath()); - } + if (ajxpNode._label) { + this._label = ajxpNode._label; } - }, { - key: 'removeChild', - - /** - * Removes the child from the children - * @param ajxpNode AjxpNode - */ - value: function removeChild(ajxpNode) { - var removePath = ajxpNode.getPath(); - ajxpNode.notify('node_removed'); - ajxpNode._parentNode = null; - this._children['delete'](ajxpNode.getPath()); - this.notify('child_removed', removePath); + if (ajxpNode._icon) { + this._icon = ajxpNode._icon; } - }, { - key: 'replaceBy', - - /** - * Replaces the current node by a new one. Copy all properties deeply - * @param ajxpNode AjxpNode - * @param metaMerge - */ - value: function replaceBy(ajxpNode, metaMerge) { - this._isLeaf = ajxpNode._isLeaf; - if (ajxpNode.getPath() && this._path != ajxpNode.getPath()) { - var originalPath = this._path; - if (this.getParent()) { - var parentChildrenIndex = this.getParent()._children; - parentChildrenIndex.set(ajxpNode.getPath(), this); - parentChildrenIndex['delete'](originalPath); - } - this._path = ajxpNode.getPath(); - var pathChanged = true; - } - if (ajxpNode._label) { - this._label = ajxpNode._label; - } - if (ajxpNode._icon) { - this._icon = ajxpNode._icon; - } - if (ajxpNode._iNodeProvider) { - this._iNodeProvider = ajxpNode._iNodeProvider; - } - //this._isRoot = ajxpNode._isRoot; - this._isLoaded = ajxpNode._isLoaded; - this.fake = ajxpNode.fake; - var meta = ajxpNode.getMetadata(); - if (metaMerge == 'override') this._metadata = new Map(); - meta.forEach((function (value, key) { - if (metaMerge == 'override') { - this._metadata.set(key, value); - } else { - if (this._metadata.has(key) && value === '') { - return; - } - this._metadata.set(key, value); + if (ajxpNode._iNodeProvider) { + this._iNodeProvider = ajxpNode._iNodeProvider; + } + //this._isRoot = ajxpNode._isRoot; + this._isLoaded = ajxpNode._isLoaded; + this.fake = ajxpNode.fake; + var meta = ajxpNode.getMetadata(); + if (metaMerge == 'override') this._metadata = new Map(); + meta.forEach((function (value, key) { + if (metaMerge == 'override') { + this._metadata.set(key, value); + } else { + if (this._metadata.has(key) && value === '') { + return; } - }).bind(this)); - if (pathChanged && !this._isLeaf && this.getChildren().size) { - window.setTimeout((function () { - this.reload(this._iNodeProvider); - }).bind(this), 100); - return; + this._metadata.set(key, value); } - ajxpNode.getChildren().forEach((function (child) { - this.addChild(child); - }).bind(this)); - this.notify('node_replaced', this); - } - }, { - key: 'findChildByPath', - - /** - * Finds a child node by its path - * @param path String - * @returns AjxpNode - */ - value: function findChildByPath(path) { - return this._children.get(path); - } - }, { - key: 'setMetadata', - - /** - * Sets the metadata as a bunch - * @param data Map A Map - */ - value: function setMetadata(data) { - this._metadata = data; - } - }, { - key: 'getMetadata', - - /** - * Gets the metadat - * @returns Map - */ - value: function getMetadata() { - return this._metadata; - } - }, { - key: 'isLeaf', - - /** - * Is this node a leaf - * @returns Boolean - */ - value: function isLeaf() { - return this._isLeaf; + }).bind(this)); + if (pathChanged && !this._isLeaf && this.getChildren().size) { + window.setTimeout((function () { + this.reload(this._iNodeProvider); + }).bind(this), 100); + return; } - }, { - key: 'getPath', - - /** - * @returns String - */ - value: function getPath() { - return this._path; - } - }, { - key: 'getLabel', - - /** - * @returns String - */ - value: function getLabel() { - return this._label; - } - }, { - key: 'getIcon', - - /** - * @returns String - */ - value: function getIcon() { - return this._icon; - } - }, { - key: 'isRecycle', - - /** - * @returns Boolean - */ - value: function isRecycle() { - return this.getAjxpMime() == 'ajxp_recycle'; + ajxpNode.getChildren().forEach((function (child) { + this.addChild(child); + }).bind(this)); + this.notify('node_replaced', this); + }; + + /** + * Finds a child node by its path + * @param path String + * @returns AjxpNode + */ + + AjxpNode.prototype.findChildByPath = function findChildByPath(path) { + return this._children.get(path); + }; + + /** + * Sets the metadata as a bunch + * @param data Map A Map + */ + + AjxpNode.prototype.setMetadata = function setMetadata(data) { + this._metadata = data; + }; + + /** + * Gets the metadat + * @returns Map + */ + + AjxpNode.prototype.getMetadata = function getMetadata() { + return this._metadata; + }; + + /** + * Is this node a leaf + * @returns Boolean + */ + + AjxpNode.prototype.isLeaf = function isLeaf() { + return this._isLeaf; + }; + + /** + * @returns String + */ + + AjxpNode.prototype.getPath = function getPath() { + return this._path; + }; + + /** + * @returns String + */ + + AjxpNode.prototype.getLabel = function getLabel() { + return this._label; + }; + + /** + * @returns String + */ + + AjxpNode.prototype.getIcon = function getIcon() { + return this._icon; + }; + + /** + * @returns Boolean + */ + + AjxpNode.prototype.isRecycle = function isRecycle() { + return this.getAjxpMime() == 'ajxp_recycle'; + }; + + /** + * Search the mime type in the parent branch + * @param ajxpMime String + * @returns Boolean + */ + + AjxpNode.prototype.hasAjxpMimeInBranch = function hasAjxpMimeInBranch(ajxpMime) { + if (this.getAjxpMime() == ajxpMime.toLowerCase()) { + return true; + }var parent, + crt = this; + while (parent = crt._parentNode) { + if (parent.getAjxpMime() == ajxpMime.toLowerCase()) { + return true; + } + crt = parent; } - }, { - key: 'hasAjxpMimeInBranch', - - /** - * Search the mime type in the parent branch - * @param ajxpMime String - * @returns Boolean - */ - value: function hasAjxpMimeInBranch(ajxpMime) { - if (this.getAjxpMime() == ajxpMime.toLowerCase()) { + return false; + }; + + /** + * Search the mime type in the parent branch + * @returns Boolean + * @param metadataKey + * @param metadataValue + */ + + AjxpNode.prototype.hasMetadataInBranch = function hasMetadataInBranch(metadataKey, metadataValue) { + if (this.getMetadata().has(metadataKey)) { + if (metadataValue) { + return this.getMetadata().get(metadataKey) == metadataValue; + } else { return true; - }var parent, - crt = this; - while (parent = crt._parentNode) { - if (parent.getAjxpMime() == ajxpMime.toLowerCase()) { - return true; - } - crt = parent; } - return false; } - }, { - key: 'hasMetadataInBranch', - - /** - * Search the mime type in the parent branch - * @returns Boolean - * @param metadataKey - * @param metadataValue - */ - value: function hasMetadataInBranch(metadataKey, metadataValue) { - if (this.getMetadata().has(metadataKey)) { + var parent, + crt = this; + while (parent = crt._parentNode) { + if (parent.getMetadata().has(metadataKey)) { if (metadataValue) { - return this.getMetadata().get(metadataKey) == metadataValue; + return parent.getMetadata().get(metadataKey) == metadataValue; } else { return true; } } - var parent, - crt = this; - while (parent = crt._parentNode) { - if (parent.getMetadata().has(metadataKey)) { - if (metadataValue) { - return parent.getMetadata().get(metadataKey) == metadataValue; - } else { - return true; - } - } - crt = parent; - } - return false; - } - }, { - key: 'setParent', - - /** - * Sets a reference to the parent node - * @param parentNode AjxpNode - */ - value: function setParent(parentNode) { - this._parentNode = parentNode; + crt = parent; } - }, { - key: 'getParent', - - /** - * Gets the parent Node - * @returns AjxpNode - */ - value: function getParent() { - return this._parentNode; - } - }, { - key: 'findInArbo', - - /** - * Finds this node by path if it already exists in arborescence - * @param rootNode AjxpNode - * @param fakeNodes AjxpNode[] - * @returns AjxpNode|undefined - */ - value: function findInArbo(rootNode, fakeNodes) { - if (!this.getPath()) { - return; - }var pathParts = this.getPath().split('/'); - var crtPath = ''; - var crtNode, - crtParentNode = rootNode; - for (var i = 0; i < pathParts.length; i++) { - if (pathParts[i] == '') continue; - crtPath = crtPath + '/' + pathParts[i]; - var node = crtParentNode.findChildByPath(crtPath); - if (node && !(node instanceof String)) { - crtNode = node; - } else { - if (fakeNodes === undefined) { - return undefined; - }crtNode = new AjxpNode(crtPath, false, PathUtils.getBasename(crtPath)); - crtNode.fake = true; - crtNode.getMetadata().set('text', PathUtils.getBasename(crtPath)); - fakeNodes.push(crtNode); - crtParentNode.addChild(crtNode); - } - crtParentNode = crtNode; + return false; + }; + + /** + * Sets a reference to the parent node + * @param parentNode AjxpNode + */ + + AjxpNode.prototype.setParent = function setParent(parentNode) { + this._parentNode = parentNode; + }; + + /** + * Gets the parent Node + * @returns AjxpNode + */ + + AjxpNode.prototype.getParent = function getParent() { + return this._parentNode; + }; + + /** + * Finds this node by path if it already exists in arborescence + * @param rootNode AjxpNode + * @param fakeNodes AjxpNode[] + * @returns AjxpNode|undefined + */ + + AjxpNode.prototype.findInArbo = function findInArbo(rootNode, fakeNodes) { + if (!this.getPath()) { + return; + }var pathParts = this.getPath().split('/'); + var crtPath = ''; + var crtNode, + crtParentNode = rootNode; + for (var i = 0; i < pathParts.length; i++) { + if (pathParts[i] == '') continue; + crtPath = crtPath + '/' + pathParts[i]; + var node = crtParentNode.findChildByPath(crtPath); + if (node && !(node instanceof String)) { + crtNode = node; + } else { + if (fakeNodes === undefined) { + return undefined; + }crtNode = new AjxpNode(crtPath, false, PathUtils.getBasename(crtPath)); + crtNode.fake = true; + crtNode.getMetadata().set('text', PathUtils.getBasename(crtPath)); + fakeNodes.push(crtNode); + crtParentNode.addChild(crtNode); } - return crtNode; - } - }, { - key: 'isRoot', - - /** - * @returns Boolean - */ - value: function isRoot() { - return this._isRoot; + crtParentNode = crtNode; } - }, { - key: 'isParentOf', - - /** - * Check if it's the parent of the given node - * @param node AjxpNode - * @returns Boolean - */ - value: function isParentOf(node) { - var childPath = node.getPath(); - var parentPath = this.getPath(); - return childPath.substring(0, parentPath.length) == parentPath; - } - }, { - key: 'isChildOf', - - /** - * Check if it's a child of the given node - * @param node AjxpNode - * @returns Boolean - */ - value: function isChildOf(node) { - var childPath = this.getPath(); - var parentPath = node.getPath(); - return childPath.substring(0, parentPath.length) == parentPath; - } - }, { - key: 'getAjxpMime', - - /** - * Gets the current's node mime type, either by ajxp_mime or by extension. - * @returns String - */ - value: function getAjxpMime() { - if (this._metadata && this._metadata.has('ajxp_mime')) { - return this._metadata.get('ajxp_mime').toLowerCase(); - }if (this._metadata && this.isLeaf()) { - return PathUtils.getAjxpMimeType(this._metadata).toLowerCase(); - }return ''; - } - }]); + return crtNode; + }; + + /** + * @returns Boolean + */ + + AjxpNode.prototype.isRoot = function isRoot() { + return this._isRoot; + }; + + /** + * Check if it's the parent of the given node + * @param node AjxpNode + * @returns Boolean + */ + + AjxpNode.prototype.isParentOf = function isParentOf(node) { + var childPath = node.getPath(); + var parentPath = this.getPath(); + return childPath.substring(0, parentPath.length) == parentPath; + }; + + /** + * Check if it's a child of the given node + * @param node AjxpNode + * @returns Boolean + */ + + AjxpNode.prototype.isChildOf = function isChildOf(node) { + var childPath = this.getPath(); + var parentPath = node.getPath(); + return childPath.substring(0, parentPath.length) == parentPath; + }; + + /** + * Gets the current's node mime type, either by ajxp_mime or by extension. + * @returns String + */ + + AjxpNode.prototype.getAjxpMime = function getAjxpMime() { + if (this._metadata && this._metadata.has('ajxp_mime')) { + return this._metadata.get('ajxp_mime').toLowerCase(); + }if (this._metadata && this.isLeaf()) { + return PathUtils.getAjxpMimeType(this._metadata).toLowerCase(); + }return ''; + }; return AjxpNode; })(Observable); \ No newline at end of file diff --git a/core/src/plugins/gui.ajax/res/js/core/model/BackgroundTasksManager.js b/core/src/plugins/gui.ajax/res/js/core/model/BackgroundTasksManager.js index b09d54fef8..71b66ca509 100644 --- a/core/src/plugins/gui.ajax/res/js/core/model/BackgroundTasksManager.js +++ b/core/src/plugins/gui.ajax/res/js/core/model/BackgroundTasksManager.js @@ -2,10 +2,6 @@ var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; -var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - -var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; - var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; /* @@ -42,7 +38,7 @@ var BackgroundTasksManager = (function (_Observable) { function BackgroundTasksManager(actionManager) { _classCallCheck(this, BackgroundTasksManager); - _get(Object.getPrototypeOf(BackgroundTasksManager.prototype), 'constructor', this).call(this); + _Observable.call(this); this.queue = []; this.actionManager = actionManager; this.working = false; @@ -50,152 +46,144 @@ var BackgroundTasksManager = (function (_Observable) { _inherits(BackgroundTasksManager, _Observable); - _createClass(BackgroundTasksManager, [{ - key: 'queueAction', - - /** - * Add an action to the queue - * @param actionName String Name of the action - * @param parameters Object Parameters of the action, NOT HASH - * @param messageId String An i18n id of the message to be displayed during the action - */ - value: function queueAction(actionName, parameters, messageId) { - var actionDef = {}; - actionDef.name = actionName; - actionDef.messageId = messageId; - actionDef.parameters = parameters; - this.queue.push(actionDef); + /** + * Add an action to the queue + * @param actionName String Name of the action + * @param parameters Object Parameters of the action, NOT HASH + * @param messageId String An i18n id of the message to be displayed during the action + */ + + BackgroundTasksManager.prototype.queueAction = function queueAction(actionName, parameters, messageId) { + var actionDef = {}; + actionDef.name = actionName; + actionDef.messageId = messageId; + actionDef.parameters = parameters; + this.queue.push(actionDef); + }; + + /** + * Processes the next action in the queue + */ + + BackgroundTasksManager.prototype.next = function next() { + if (!this.queue.length) { + this.finished(); + return; } - }, { - key: 'next', - - /** - * Processes the next action in the queue - */ - value: function next() { - if (!this.queue.length) { - this.finished(); - return; + if (this.working) { + return; + }var actionDef = this.queue[0]; + if (actionDef.name == 'javascript_instruction' && actionDef.parameters.callback) { + var cb = actionDef.parameters.callback; + this.notify('update_message', actionDef.messageId); + this.queue.shift(); + cb(); + this.working = false; + this.next(); + } else { + var client = PydioApi.getClient(); + var params = { get_action: actionDef.name }; + for (var k in actionDef.parameters) { + if (actionDef.parameters.hasOwnProperty(k)) params[k] = actionDef.parameters[k]; } - if (this.working) { - return; - }var actionDef = this.queue[0]; - if (actionDef.name == 'javascript_instruction' && actionDef.parameters.callback) { - var cb = actionDef.parameters.callback; - this.notify('update_message', actionDef.messageId); - this.queue.shift(); - cb(); - this.working = false; - this.next(); - } else { - var client = PydioApi.getClient(); - var params = { get_action: actionDef.name }; - for (var k in actionDef.parameters) { - if (actionDef.parameters.hasOwnProperty(k)) params[k] = actionDef.parameters[k]; - } - client.request(params, (function (transport) { - var xmlResponse = transport.responseXML; - if (xmlResponse == null || xmlResponse.documentElement == null) { - this.working = false; - this.next(); - return; - } - this.parseAnswer(transport.responseXML); + client.request(params, (function (transport) { + var xmlResponse = transport.responseXML; + if (xmlResponse == null || xmlResponse.documentElement == null) { this.working = false; - }).bind(this), null, { method: 'POST' }); - this.notify('update_message', actionDef.messageId); - this.queue.shift(); - this.working = true; - } + this.next(); + return; + } + this.parseAnswer(transport.responseXML); + this.working = false; + }).bind(this), null, { method: 'POST' }); + this.notify('update_message', actionDef.messageId); + this.queue.shift(); + this.working = true; } - }, { - key: 'parseAnswer', - - /** - * Parses the response. Should probably use the actionBar parser instead. - * @param xmlResponse XMLDocument - */ - value: function parseAnswer(xmlResponse) { - var childs = xmlResponse.documentElement.childNodes; - var delay = 0; - for (var i = 0; i < childs.length; i++) { - if (childs[i].tagName == 'message') { - var type = childs[i].getAttribute('type'); - if (type != 'SUCCESS') { - this.interruptOnError(childs[i].firstChild.nodeValue); - } - } else if (childs[i].nodeName == 'trigger_bg_action') { - var name = childs[i].getAttribute('name'); - var messageId = childs[i].getAttribute('messageId'); - delay = parseInt(childs[i].getAttribute('delay')); - var parameters = {}; - for (var j = 0; j < childs[i].childNodes.length; j++) { - var paramChild = childs[i].childNodes[j]; - if (paramChild.tagName == 'param') { - parameters[paramChild.getAttribute('name')] = paramChild.getAttribute('value'); - } else if (paramChild.tagName == 'clientCallback') { - var callbackCode = paramChild.firstChild.nodeValue; - var callback = new Function(callbackCode); - } + }; + + /** + * Parses the response. Should probably use the actionBar parser instead. + * @param xmlResponse XMLDocument + */ + + BackgroundTasksManager.prototype.parseAnswer = function parseAnswer(xmlResponse) { + var childs = xmlResponse.documentElement.childNodes; + var delay = 0; + for (var i = 0; i < childs.length; i++) { + if (childs[i].tagName == 'message') { + var type = childs[i].getAttribute('type'); + if (type != 'SUCCESS') { + this.interruptOnError(childs[i].firstChild.nodeValue); + } + } else if (childs[i].nodeName == 'trigger_bg_action') { + var name = childs[i].getAttribute('name'); + var messageId = childs[i].getAttribute('messageId'); + delay = parseInt(childs[i].getAttribute('delay')); + var parameters = {}; + for (var j = 0; j < childs[i].childNodes.length; j++) { + var paramChild = childs[i].childNodes[j]; + if (paramChild.tagName == 'param') { + parameters[paramChild.getAttribute('name')] = paramChild.getAttribute('value'); + } else if (paramChild.tagName == 'clientCallback') { + var callbackCode = paramChild.firstChild.nodeValue; + var callback = new Function(callbackCode); } - if (name == 'reload_node') { - if (delay) { - window.setTimeout((function () { - this.actionManager.getDataModel().requireContextChange(this.actionManager.getDataModel().getContextNode(), true); - this.next(); - }).bind(this), delay * 1000); - return; - } - this.actionManager.getDataModel().requireContextChange(this.actionManager.getDataModel().getContextNode(), true); - } else if (name == 'info_message') { - this.notify('update_message', messageId); - } else if (name == 'javascript_instruction' && callback) { - parameters.callback = callback; - this.queueAction('javascript_instruction', parameters, messageId); - } else { - this.queueAction(name, parameters, messageId); + } + if (name == 'reload_node') { + if (delay) { + window.setTimeout((function () { + this.actionManager.getDataModel().requireContextChange(this.actionManager.getDataModel().getContextNode(), true); + this.next(); + }).bind(this), delay * 1000); + return; } + this.actionManager.getDataModel().requireContextChange(this.actionManager.getDataModel().getContextNode(), true); + } else if (name == 'info_message') { + this.notify('update_message', messageId); + } else if (name == 'javascript_instruction' && callback) { + parameters.callback = callback; + this.queueAction('javascript_instruction', parameters, messageId); + } else { + this.queueAction(name, parameters, messageId); } } - this.working = false; - if (delay) { - window.setTimeout(this.next.bind(this), delay * 1000); - } else { - this.next(); - } } - }, { - key: 'interruptOnError', - - /** - * Interrupt the task on error - * @param errorMessage String - */ - value: function interruptOnError(errorMessage) { - if (this.queue.length) this.queue = []; - this.notify('update_message_error', errorMessage); - this.working = false; + this.working = false; + if (delay) { + window.setTimeout(this.next.bind(this), delay * 1000); + } else { + this.next(); } - }, { - key: 'finished', + }; - /** - * All tasks are processed - */ - value: function finished() { - this.working = false; - this.notify('tasks_finished'); - } - }, { - key: 'addStub', - - /** - * Create a stub action with not parameter. - */ - value: function addStub() { - this.queueAction('local_to_remote', {}, 'Stubing a 10s bg action'); - } - }]); + /** + * Interrupt the task on error + * @param errorMessage String + */ + + BackgroundTasksManager.prototype.interruptOnError = function interruptOnError(errorMessage) { + if (this.queue.length) this.queue = []; + this.notify('update_message_error', errorMessage); + this.working = false; + }; + + /** + * All tasks are processed + */ + + BackgroundTasksManager.prototype.finished = function finished() { + this.working = false; + this.notify('tasks_finished'); + }; + + /** + * Create a stub action with not parameter. + */ + + BackgroundTasksManager.prototype.addStub = function addStub() { + this.queueAction('local_to_remote', {}, 'Stubing a 10s bg action'); + }; return BackgroundTasksManager; })(Observable); \ No newline at end of file diff --git a/core/src/plugins/gui.ajax/res/js/core/model/Controller.js b/core/src/plugins/gui.ajax/res/js/core/model/Controller.js index 09f259de7a..6dc24ba793 100644 --- a/core/src/plugins/gui.ajax/res/js/core/model/Controller.js +++ b/core/src/plugins/gui.ajax/res/js/core/model/Controller.js @@ -2,10 +2,6 @@ var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; -var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - -var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; - var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; /* @@ -45,7 +41,7 @@ var Controller = (function (_Observable) { _classCallCheck(this, Controller); - _get(Object.getPrototypeOf(Controller.prototype), "constructor", this).call(this); + _Observable.call(this); this._pydioObject = pydioObject; this._registeredKeys = new Map(); this.usersEnabled = pydioObject.Parameters.get("usersEnabled"); @@ -97,531 +93,489 @@ var Controller = (function (_Observable) { _inherits(Controller, _Observable); - _createClass(Controller, [{ - key: "publishActionEvent", - value: function publishActionEvent(eventName, data) { - this._pydioObject.fire(eventName, data); - } - }, { - key: "_connectDataModel", - value: function _connectDataModel() { - if (this.localDataModel) { - this._dataModel.observe("context_changed", this.contextChangedObs); - this._dataModel.observe("selection_changed", this.selectionChangedObs); - this.loadActionsFromRegistry(); - this._pydioObject.observe("registry_loaded", (function (registry) { - this.loadActionsFromRegistry(registry); - }).bind(this)); - } else { - this._pydioObject.observe("context_changed", this.contextChangedObs); - this._pydioObject.observe("selection_changed", this.selectionChangedObs); - this._dataModel = this._pydioObject.getContextHolder(); - } - } - }, { - key: "updateGuiActions", - value: function updateGuiActions(actions) { - actions.forEach((function (v, k) { - this._guiActions.set(k, v); + Controller.prototype.publishActionEvent = function publishActionEvent(eventName, data) { + this._pydioObject.fire(eventName, data); + }; + + Controller.prototype._connectDataModel = function _connectDataModel() { + if (this.localDataModel) { + this._dataModel.observe("context_changed", this.contextChangedObs); + this._dataModel.observe("selection_changed", this.selectionChangedObs); + this.loadActionsFromRegistry(); + this._pydioObject.observe("registry_loaded", (function (registry) { + this.loadActionsFromRegistry(registry); }).bind(this)); + } else { + this._pydioObject.observe("context_changed", this.contextChangedObs); + this._pydioObject.observe("selection_changed", this.selectionChangedObs); + this._dataModel = this._pydioObject.getContextHolder(); } - }, { - key: "deleteFromGuiActions", - value: function deleteFromGuiActions(actionName) { - this._guiActions["delete"](actionName); - } - }, { - key: "refreshGuiActionsI18n", - value: function refreshGuiActionsI18n() { - this._guiActions.forEach(function (value, key) { - value.refreshFromI18NHash(); - }); - } - }, { - key: "getBackgroundTasksManager", - value: function getBackgroundTasksManager() { - if (!Controller._bgManager) { - Controller._bgManager = new BackgroundTasksManager(); - } - return Controller._bgManager; - } - }, { - key: "getDataModel", - value: function getDataModel() { - return this._dataModel; - } - }, { - key: "destroy", - value: function destroy() { - if (this.localDataModel && this._dataModel) { - this._dataModel.stopObserving("context_changed", this.contextChangedObs); - this._dataModel.stopObserving("selection_changed", this.selectionChangedObs); - } - } - }, { - key: "getMessage", - value: function getMessage(messageId) { - try { - return this._pydioObject.MessageHash[messageId]; - } catch (e) { - return messageId; - } + }; + + Controller.prototype.updateGuiActions = function updateGuiActions(actions) { + actions.forEach((function (v, k) { + this._guiActions.set(k, v); + }).bind(this)); + }; + + Controller.prototype.deleteFromGuiActions = function deleteFromGuiActions(actionName) { + this._guiActions["delete"](actionName); + }; + + Controller.prototype.refreshGuiActionsI18n = function refreshGuiActionsI18n() { + this._guiActions.forEach(function (value, key) { + value.refreshFromI18NHash(); + }); + }; + + Controller.prototype.getBackgroundTasksManager = function getBackgroundTasksManager() { + if (!Controller._bgManager) { + Controller._bgManager = new BackgroundTasksManager(); } - }, { - key: "uiInsertForm", - value: function uiInsertForm(formId, formCode) { - if (this._pydioObject.UI) { - this._pydioObject.UI.insertForm(formId, formCode); - } + return Controller._bgManager; + }; + + Controller.prototype.getDataModel = function getDataModel() { + return this._dataModel; + }; + + Controller.prototype.destroy = function destroy() { + if (this.localDataModel && this._dataModel) { + this._dataModel.stopObserving("context_changed", this.contextChangedObs); + this._dataModel.stopObserving("selection_changed", this.selectionChangedObs); } - }, { - key: "uiRemoveForm", - value: function uiRemoveForm(formId) { - if (this._pydioObject.UI) { - this._pydioObject.UI.removeForm(formId); - } + }; + + Controller.prototype.getMessage = function getMessage(messageId) { + try { + return this._pydioObject.MessageHash[messageId]; + } catch (e) { + return messageId; } - }, { - key: "uiGetModal", - value: function uiGetModal() { - if (this._pydioObject && this._pydioObject.UI) { - return this._pydioObject.UI.modal; - } - return null; + }; + + Controller.prototype.uiInsertForm = function uiInsertForm(formId, formCode) { + if (this._pydioObject.UI) { + this._pydioObject.UI.insertForm(formId, formCode); } - }, { - key: "parseXmlMessage", - - /** - * COMPATIBILITY METHD - * @param xmlDoc - * @returns {*} - */ - value: function parseXmlMessage(xmlDoc) { - if (console) console.warn("Controller.parseXmlMessage() is deprecated, use PydioApi instead", new Error()); - return PydioApi.getClient().parseXmlMessage(xmlDoc); + }; + + Controller.prototype.uiRemoveForm = function uiRemoveForm(formId) { + if (this._pydioObject.UI) { + this._pydioObject.UI.removeForm(formId); } - }, { - key: "submitForm", - - /** - * Submits a form using Connexion class. - * @param formName String The id of the form - * @param post Boolean Whether to POST or GET - * @param completeCallback Function Callback to be called on complete - */ - value: function submitForm(formName, post, completeCallback) { - if (console) console.warn("Controller.submitForm() is deprecated, use PydioApi instead", new Error()); - return PydioApi.getClient().submitForm(formName, post, completeCallback); + }; + + Controller.prototype.uiGetModal = function uiGetModal() { + if (this._pydioObject && this._pydioObject.UI) { + return this._pydioObject.UI.modal; } - }, { - key: "setUser", - - /** - * Stores the currently logged user object - * @param oUser User User instance - */ - value: function setUser(oUser) { - this.oUser = oUser; - if (oUser != null && oUser.id != "guest" && oUser.getPreference("lang") != null && oUser.getPreference("lang") != "" && oUser.getPreference("lang") != this._pydioObject.currentLanguage && !oUser.lock) { - this._pydioObject.loadI18NMessages(oUser.getPreference("lang")); - } + return null; + }; + + /** + * COMPATIBILITY METHD + * @param xmlDoc + * @returns {*} + */ + + Controller.prototype.parseXmlMessage = function parseXmlMessage(xmlDoc) { + Logger.log("Controller.parseXmlMessage() is deprecated, use PydioApi instead"); + return PydioApi.getClient().parseXmlMessage(xmlDoc); + }; + + /** + * Submits a form using Connexion class. + * @param formName String The id of the form + * @param post Boolean Whether to POST or GET + * @param completeCallback Function Callback to be called on complete + */ + + Controller.prototype.submitForm = function submitForm(formName, post, completeCallback) { + Logger.log("Controller.submitForm() is deprecated, use PydioApi instead"); + return PydioApi.getClient().submitForm(formName, post, completeCallback); + }; + + /** + * Stores the currently logged user object + * @param oUser User User instance + */ + + Controller.prototype.setUser = function setUser(oUser) { + this.oUser = oUser; + if (oUser != null && oUser.id != "guest" && oUser.getPreference("lang") != null && oUser.getPreference("lang") != "" && oUser.getPreference("lang") != this._pydioObject.currentLanguage && !oUser.lock) { + this._pydioObject.loadI18NMessages(oUser.getPreference("lang")); } - }, { - key: "getContextActions", - - /** - * Filter the actions given the srcElement passed as arguments. - * TODO: SIGNATURE CHANGED, FROM srcElement to actionsSelectorAtt - * @param srcElement String An identifier among selectionContext, genericContext, a webfx object id - * @param ignoreGroups Array a list of groups to ignore - * @returns Array - */ - value: function getContextActions(actionsSelectorAtt, ignoreGroups) { - var contextActions = []; - var defaultGroup; - var contextActionsGroup = new Map(); - this.actions.forEach((function (action) { - if (!action.context.contextMenu) return; - if (actionsSelectorAtt == "selectionContext" && !action.context.selection) return; - if (actionsSelectorAtt == "directoryContext" && !action.context.dir) return; - if (actionsSelectorAtt == "genericContext" && action.context.selection) return; - if (action.contextHidden || action.deny) return; - action.context.actionBarGroup.split(",").forEach(function (barGroup) { - if (!contextActionsGroup.has(barGroup)) { - contextActionsGroup.set(barGroup, []); - } - }); - var isDefault = false; - if (actionsSelectorAtt == "selectionContext") { - // set default in bold - var userSelection = this._dataModel; - if (!userSelection.isEmpty()) { - var defaultAction = "file"; - if (userSelection.isUnique() && (userSelection.hasDir() || userSelection.hasMime(["ajxp_browsable_archive"]))) { - defaultAction = "dir"; - } - if (this.defaultActions.get(defaultAction) && action.options.name == this.defaultActions.get(defaultAction)) { - isDefault = true; - } - } - } - action.context.actionBarGroup.split(",").forEach(function (barGroup) { - var menuItem = { - name: action.getKeyedText(), - alt: action.options.title, - action_id: action.options.name, - image_unresolved: action.options.src, - isDefault: isDefault, - callback: (function (e) { - this.apply(); - }).bind(action) - }; - if (action.options.icon_class) { - menuItem.icon_class = action.options.icon_class; - } - if (action.options.subMenu) { - menuItem.subMenu = []; - if (action.subMenuItems.staticOptions) { - menuItem.subMenu = action.subMenuItems.staticOptions; - } - if (action.subMenuItems.dynamicBuilder) { - menuItem.subMenuBeforeShow = action.subMenuItems.dynamicBuilder; - } - } - contextActionsGroup.get(barGroup).push(menuItem); - if (isDefault) { - defaultGroup = barGroup; - } - }); - }).bind(this)); - var first = true, - keys = []; - if (defaultGroup && contextActionsGroup.has(defaultGroup)) { - keys.push(defaultGroup); - } - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; + }; - try { - for (var _iterator = contextActionsGroup.keys()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var k = _step.value; + /** + * Filter the actions given the srcElement passed as arguments. + * TODO: SIGNATURE CHANGED, FROM srcElement to actionsSelectorAtt + * @param srcElement String An identifier among selectionContext, genericContext, a webfx object id + * @param ignoreGroups Array a list of groups to ignore + * @returns Array + */ - if (k == defaultGroup) continue; - keys.push(k); + Controller.prototype.getContextActions = function getContextActions(actionsSelectorAtt, ignoreGroups) { + var contextActions = []; + var defaultGroup; + var contextActionsGroup = new Map(); + this.actions.forEach((function (action) { + if (!action.context.contextMenu) return; + if (actionsSelectorAtt == "selectionContext" && !action.context.selection) return; + if (actionsSelectorAtt == "directoryContext" && !action.context.dir) return; + if (actionsSelectorAtt == "genericContext" && action.context.selection) return; + if (action.contextHidden || action.deny) return; + action.context.actionBarGroup.split(",").forEach(function (barGroup) { + if (!contextActionsGroup.has(barGroup)) { + contextActionsGroup.set(barGroup, []); } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator["return"]) { - _iterator["return"](); + }); + var isDefault = false; + if (actionsSelectorAtt == "selectionContext") { + // set default in bold + var userSelection = this._dataModel; + if (!userSelection.isEmpty()) { + var defaultAction = "file"; + if (userSelection.isUnique() && (userSelection.hasDir() || userSelection.hasMime(["ajxp_browsable_archive"]))) { + defaultAction = "dir"; } - } finally { - if (_didIteratorError) { - throw _iteratorError; + if (this.defaultActions.get(defaultAction) && action.options.name == this.defaultActions.get(defaultAction)) { + isDefault = true; } } } - - keys.sort(); - keys.each(function (key) { - var value = contextActionsGroup.get(key); - if (!first) { - contextActions.push({ separator: true }); + action.context.actionBarGroup.split(",").forEach(function (barGroup) { + var menuItem = { + name: action.getKeyedText(), + alt: action.options.title, + action_id: action.options.name, + image_unresolved: action.options.src, + isDefault: isDefault, + callback: (function (e) { + this.apply(); + }).bind(action) + }; + if (action.options.icon_class) { + menuItem.icon_class = action.options.icon_class; } - if (ignoreGroups && ignoreGroups.indexOf(key) != -1) { - return; + if (action.options.subMenu) { + menuItem.subMenu = []; + if (action.subMenuItems.staticOptions) { + menuItem.subMenu = action.subMenuItems.staticOptions; + } + if (action.subMenuItems.dynamicBuilder) { + menuItem.subMenuBeforeShow = action.subMenuItems.dynamicBuilder; + } } - first = false; - value.forEach(function (mItem) { - contextActions.push(mItem); - }); - }); - return contextActions; - } - }, { - key: "getActionsForAjxpWidget", - - /** - * Generic method to get actions for a given component part. - * @param ajxpClassName String - * @param widgetId String - * @returns [] - */ - value: function getActionsForAjxpWidget(ajxpClassName, widgetId) { - var actions = []; - this.actions.forEach(function (action) { - if (action.context.ajxpWidgets && (action.context.ajxpWidgets.indexOf(ajxpClassName + "::" + widgetId) != -1 || action.context.ajxpWidgets.indexOf(ajxpClassName) != -1) && !action.deny) actions.push(action); - }); - return actions; - } - }, { - key: "fireDefaultAction", - - /** - * Finds a default action and fires it. - * @param defaultName String ("file", "dir", "dragndrop", "ctrldragndrop") - */ - value: function fireDefaultAction(defaultName) { - var actionName = this.defaultActions.get(defaultName); - if (actionName) { - arguments[0] = actionName; - if (actionName == "ls") { - var action = this.actions.get(actionName); - if (action) action.enable(); // Force enable on default action + contextActionsGroup.get(barGroup).push(menuItem); + if (isDefault) { + defaultGroup = barGroup; } - this.fireAction.apply(this, arguments); + }); + }).bind(this)); + var first = true, + keys = []; + if (defaultGroup && contextActionsGroup.has(defaultGroup)) { + keys.push(defaultGroup); + } + for (var _iterator = contextActionsGroup.keys(), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { + var _ref; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; } + + var k = _ref; + + if (k == defaultGroup) continue; + keys.push(k); } - }, { - key: "fireAction", - - /** - * Fire an action based on its name - * @param actionName String The name of the action - */ - value: function fireAction(actionName) { - var action = this.actions.get(actionName); - if (action != null) { - var args = Array.from(arguments).slice(1); - action.apply(args); + keys.sort(); + keys.each(function (key) { + var value = contextActionsGroup.get(key); + if (!first) { + contextActions.push({ separator: true }); } - } - }, { - key: "registerKey", - - /** - * Registers an accesskey for a given action. - * @param key String The access key - * @param actionName String The name of the action - * @param optionnalCommand String An optionnal argument - * that will be passed to the action when fired. - */ - value: function registerKey(key, actionName, optionnalCommand) { - if (optionnalCommand) { - actionName = actionName + "::" + optionnalCommand; + if (ignoreGroups && ignoreGroups.indexOf(key) != -1) { + return; + } + first = false; + value.forEach(function (mItem) { + contextActions.push(mItem); + }); + }); + return contextActions; + }; + + /** + * Generic method to get actions for a given component part. + * @param ajxpClassName String + * @param widgetId String + * @returns [] + */ + + Controller.prototype.getActionsForAjxpWidget = function getActionsForAjxpWidget(ajxpClassName, widgetId) { + var actions = []; + this.actions.forEach(function (action) { + if (action.context.ajxpWidgets && (action.context.ajxpWidgets.indexOf(ajxpClassName + "::" + widgetId) != -1 || action.context.ajxpWidgets.indexOf(ajxpClassName) != -1) && !action.deny) actions.push(action); + }); + return actions; + }; + + /** + * Finds a default action and fires it. + * @param defaultName String ("file", "dir", "dragndrop", "ctrldragndrop") + */ + + Controller.prototype.fireDefaultAction = function fireDefaultAction(defaultName) { + var actionName = this.defaultActions.get(defaultName); + if (actionName) { + arguments[0] = actionName; + if (actionName == "ls") { + var action = this.actions.get(actionName); + if (action) action.enable(); // Force enable on default action } - this._registeredKeys.set(key.toLowerCase(), actionName); + this.fireAction.apply(this, arguments); + } + }; + + /** + * Fire an action based on its name + * @param actionName String The name of the action + */ + + Controller.prototype.fireAction = function fireAction(actionName) { + var action = this.actions.get(actionName); + if (action != null) { + var args = Array.from(arguments).slice(1); + action.apply(args); } - }, { - key: "clearRegisteredKeys", - - /** - * Remove all registered keys. - */ - value: function clearRegisteredKeys() { - this._registeredKeys = new Map(); + }; + + /** + * Registers an accesskey for a given action. + * @param key String The access key + * @param actionName String The name of the action + * @param optionnalCommand String An optionnal argument + * that will be passed to the action when fired. + */ + + Controller.prototype.registerKey = function registerKey(key, actionName, optionnalCommand) { + if (optionnalCommand) { + actionName = actionName + "::" + optionnalCommand; } - }, { - key: "fireActionByKey", - - /** - * Triggers an action by its access key. - * @param event Event The key event (will be stopped) - * @param keyName String A key name - */ - value: function fireActionByKey(event, keyName) { - if (this._registeredKeys.get(keyName)) { - if (this._registeredKeys.get(keyName).indexOf("::") !== -1) { - var parts = this._registeredKeys.get(keyName).split("::"); - this.fireAction(parts[0], parts[1]); - } else { - this.fireAction(this._registeredKeys.get(keyName)); - } - try { - event.preventDefault(); - event.stopPropagation(); - } catch (e) { - Logger.error("Error trying to stop event propagation"); - } + this._registeredKeys.set(key.toLowerCase(), actionName); + }; + + /** + * Remove all registered keys. + */ + + Controller.prototype.clearRegisteredKeys = function clearRegisteredKeys() { + this._registeredKeys = new Map(); + }; + + /** + * Triggers an action by its access key. + * @param event Event The key event (will be stopped) + * @param keyName String A key name + */ + + Controller.prototype.fireActionByKey = function fireActionByKey(event, keyName) { + if (this._registeredKeys.get(keyName)) { + if (this._registeredKeys.get(keyName).indexOf("::") !== -1) { + var parts = this._registeredKeys.get(keyName).split("::"); + this.fireAction(parts[0], parts[1]); + } else { + this.fireAction(this._registeredKeys.get(keyName)); } - } - }, { - key: "applyDragMove", - - /** - * Complex function called when drag'n'dropping. Basic checks of who is child of who. - * @param fileName String The dragged element - * @param destDir String The drop target node path - * @param destNodeName String The drop target node name - * @param copy Boolean Copy or Move - */ - value: function applyDragMove(fileName, destDir, destNodeName, copy) { - if (!copy && (!this.defaultActions.has("dragndrop") || this.getDefaultAction("dragndrop").deny) || copy && (!this.defaultActions.has("ctrldragndrop") || this.getDefaultAction("ctrldragndrop").deny)) { - return; + try { + event.preventDefault(); + event.stopPropagation(); + } catch (e) { + Logger.error("Error trying to stop event propagation"); } - var fileNames; - if (fileName == null) fileNames = this._dataModel.getFileNames();else fileNames = [fileName]; - // Check that dest is not the direct parent of source, ie current rep! - if (destDir == this._dataModel.getContextNode().getPath()) { - this._pydioObject.displayMessage("ERROR", MessageHash[203]); + } + }; + + /** + * Complex function called when drag'n'dropping. Basic checks of who is child of who. + * @param fileName String The dragged element + * @param destDir String The drop target node path + * @param destNodeName String The drop target node name + * @param copy Boolean Copy or Move + */ + + Controller.prototype.applyDragMove = function applyDragMove(fileName, destDir, destNodeName, copy) { + if (!copy && (!this.defaultActions.has("dragndrop") || this.getDefaultAction("dragndrop").deny) || copy && (!this.defaultActions.has("ctrldragndrop") || this.getDefaultAction("ctrldragndrop").deny)) { + return; + } + var fileNames; + if (fileName == null) fileNames = this._dataModel.getFileNames();else fileNames = [fileName]; + // Check that dest is not the direct parent of source, ie current rep! + if (destDir == this._dataModel.getContextNode().getPath()) { + this._pydioObject.displayMessage("ERROR", MessageHash[203]); + return; + } + // Check that dest is not child of source it self + for (var i = 0; i < fileNames.length; i++) { + if (destDir.lastIndexOf(fileNames[i], 0) === 0) { + this._pydioObject.displayMessage("ERROR", MessageHash[202]); return; } - // Check that dest is not child of source it self - for (var i = 0; i < fileNames.length; i++) { - if (destDir.lastIndexOf(fileNames[i], 0) === 0) { - this._pydioObject.displayMessage("ERROR", MessageHash[202]); - return; - } - } - var params = {}; - params.get_action = this.defaultActions.get(copy ? "ctrldragndrop" : "dragndrop"); - params["nodes[]"] = fileNames; - params.dest = destDir; - params.dir = this._dataModel.getContextNode().getPath(); - PydioApi.getClient().request(params, (function (transport) { - this.parseXmlMessage(transport.responseXML); - }).bind(PydioApi.getClient())); } - }, { - key: "getDefaultAction", - - /** - * Get the action defined as default for a given default string - * @param defaultName String - * @returns Action - */ - value: function getDefaultAction(defaultName) { - if (this.defaultActions.has(defaultName)) { - return this.actions.get(this.defaultActions.get(defaultName)); - } - return null; + var params = {}; + params.get_action = this.defaultActions.get(copy ? "ctrldragndrop" : "dragndrop"); + params["nodes[]"] = fileNames; + params.dest = destDir; + params.dir = this._dataModel.getContextNode().getPath(); + PydioApi.getClient().request(params, (function (transport) { + this.parseXmlMessage(transport.responseXML); + }).bind(PydioApi.getClient())); + }; + + /** + * Get the action defined as default for a given default string + * @param defaultName String + * @returns Action + */ + + Controller.prototype.getDefaultAction = function getDefaultAction(defaultName) { + if (this.defaultActions.has(defaultName)) { + return this.actions.get(this.defaultActions.get(defaultName)); } - }, { - key: "fireSelectionChange", - - /** - * Spreads a selection change to all actions and to registered components - * by triggering ajaxplorer:actions_refreshed event. - */ - value: function fireSelectionChange() { - var userSelection = null; - userSelection = this._dataModel; - if (userSelection.isEmpty()) userSelection = null; - this.actions.forEach(function (action) { - action.fireSelectionChange(userSelection); - }); - if (this.localDataModel) { - this.notify("actions_refreshed"); - } else { - this._pydioObject.fire("actions_refreshed"); - } + return null; + }; + + /** + * Spreads a selection change to all actions and to registered components + * by triggering ajaxplorer:actions_refreshed event. + */ + + Controller.prototype.fireSelectionChange = function fireSelectionChange() { + var userSelection = null; + userSelection = this._dataModel; + if (userSelection.isEmpty()) userSelection = null; + this.actions.forEach(function (action) { + action.fireSelectionChange(userSelection); + }); + if (this.localDataModel) { + this.notify("actions_refreshed"); + } else { + this._pydioObject.fire("actions_refreshed"); } - }, { - key: "fireContextChange", - - /** - * Spreads a context change to all actions and to registered components - * by triggering ajaxplorer:actions_refreshed event. - */ - value: function fireContextChange() { - var crtNode = this._dataModel.getContextNode(); - this.actions.forEach((function (action) { - action.fireContextChange(this.usersEnabled, this.oUser, crtNode); - }).bind(this)); - if (this.localDataModel) { - this.notify("actions_refreshed"); - } else { - this._pydioObject.fire("actions_refreshed"); - } + }; + + /** + * Spreads a context change to all actions and to registered components + * by triggering ajaxplorer:actions_refreshed event. + */ + + Controller.prototype.fireContextChange = function fireContextChange() { + var crtNode = this._dataModel.getContextNode(); + this.actions.forEach((function (action) { + action.fireContextChange(this.usersEnabled, this.oUser, crtNode); + }).bind(this)); + if (this.localDataModel) { + this.notify("actions_refreshed"); + } else { + this._pydioObject.fire("actions_refreshed"); } - }, { - key: "removeActions", - - /** - * Remove all actions - */ - value: function removeActions() { - this.actions.forEach(function (action) { - action.remove(); - }); - this.actions = new Map(); - this.clearRegisteredKeys(); + }; + + /** + * Remove all actions + */ + + Controller.prototype.removeActions = function removeActions() { + this.actions.forEach(function (action) { + action.remove(); + }); + this.actions = new Map(); + this.clearRegisteredKeys(); + }; + + /** + * Create actions from XML Registry + * @param registry DOMDocument + */ + + Controller.prototype.loadActionsFromRegistry = function loadActionsFromRegistry() { + var registry = arguments[0] === undefined ? null : arguments[0]; + + if (!registry) { + registry = pydio.getXmlRegistry(); } - }, { - key: "loadActionsFromRegistry", - - /** - * Create actions from XML Registry - * @param registry DOMDocument - */ - value: function loadActionsFromRegistry() { - var registry = arguments[0] === undefined ? null : arguments[0]; - - if (!registry) { - registry = pydio.getXmlRegistry(); - } - this.removeActions(); - this.parseActions(registry); - this._guiActions.forEach((function (act) { - this.registerAction(act); - }).bind(this)); - if (this.localDataModel) { - this.notify("actions_loaded"); - } else { - this._pydioObject.fire("actions_loaded", this.actions); - } - this.fireContextChange(); - this.fireSelectionChange(); + this.removeActions(); + this.parseActions(registry); + this._guiActions.forEach((function (act) { + this.registerAction(act); + }).bind(this)); + if (this.localDataModel) { + this.notify("actions_loaded"); + } else { + this._pydioObject.fire("actions_loaded", this.actions); } - }, { - key: "registerAction", - - /** - * Registers an action to this manager (default, accesskey). - * @param action Action - */ - value: function registerAction(action) { - var actionName = action.options.name; - this.actions.set(actionName, action); - if (action.defaults) { - for (var key in action.defaults) { - if (action.defaults.hasOwnProperty(key)) { - this.defaultActions.set(key, actionName); - } + this.fireContextChange(); + this.fireSelectionChange(); + }; + + /** + * Registers an action to this manager (default, accesskey). + * @param action Action + */ + + Controller.prototype.registerAction = function registerAction(action) { + var actionName = action.options.name; + this.actions.set(actionName, action); + if (action.defaults) { + for (var key in action.defaults) { + if (action.defaults.hasOwnProperty(key)) { + this.defaultActions.set(key, actionName); } } - if (action.options.hasAccessKey) { - this.registerKey(action.options.accessKey, actionName); - } - if (action.options.specialAccessKey) { - this.registerKey("key_" + action.options.specialAccessKey, actionName); - } - action.setManager(this); } - }, { - key: "parseActions", - - /** - * Parse an XML action node and registers the action - * @param documentElement DOMNode The node to parse - */ - value: function parseActions(documentElement) { - var actions = XMLUtils.XPathSelectNodes(documentElement, "actions/action"); - for (var i = 0; i < actions.length; i++) { - if (actions[i].nodeName != "action") continue; - if (actions[i].getAttribute("enabled") == "false") continue; - var newAction = new Action(); - newAction.setManager(this); - newAction.createFromXML(actions[i]); - this.registerAction(newAction); - } + if (action.options.hasAccessKey) { + this.registerKey(action.options.accessKey, actionName); + } + if (action.options.specialAccessKey) { + this.registerKey("key_" + action.options.specialAccessKey, actionName); } - }, { - key: "getActionByName", - - /** - * Find an action by its name - * @param actionName String - * @returns Action - */ - value: function getActionByName(actionName) { - return this.actions.get(actionName); + action.setManager(this); + }; + + /** + * Parse an XML action node and registers the action + * @param documentElement DOMNode The node to parse + */ + + Controller.prototype.parseActions = function parseActions(documentElement) { + var actions = XMLUtils.XPathSelectNodes(documentElement, "actions/action"); + for (var i = 0; i < actions.length; i++) { + if (actions[i].nodeName != "action") continue; + if (actions[i].getAttribute("enabled") == "false") continue; + var newAction = new Action(); + newAction.setManager(this); + newAction.createFromXML(actions[i]); + this.registerAction(newAction); } - }]); + }; + + /** + * Find an action by its name + * @param actionName String + * @returns Action + */ + + Controller.prototype.getActionByName = function getActionByName(actionName) { + return this.actions.get(actionName); + }; return Controller; })(Observable); \ No newline at end of file diff --git a/core/src/plugins/gui.ajax/res/js/core/model/EmptyNodeProvider.js b/core/src/plugins/gui.ajax/res/js/core/model/EmptyNodeProvider.js index 38d9208cc3..42205f1cbd 100644 --- a/core/src/plugins/gui.ajax/res/js/core/model/EmptyNodeProvider.js +++ b/core/src/plugins/gui.ajax/res/js/core/model/EmptyNodeProvider.js @@ -2,40 +2,31 @@ var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; -var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - -var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; - var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; var EmptyNodeProvider = (function (_Observable) { function EmptyNodeProvider() { _classCallCheck(this, EmptyNodeProvider); - _get(Object.getPrototypeOf(EmptyNodeProvider.prototype), "constructor", this).call(this); + _Observable.call(this); } _inherits(EmptyNodeProvider, _Observable); - _createClass(EmptyNodeProvider, [{ - key: "initProvider", - value: function initProvider(properties) { - this.properties = properties; - } - }, { - key: "loadNode", - - /** - * - * @param node AjxpNode - * @param nodeCallback Function - * @param childCallback Function - */ - value: function loadNode(node, nodeCallback, childCallback) {} - }, { - key: "loadLeafNodeSyncfunction", - value: function loadLeafNodeSyncfunction(node, callback) {} - }]); + EmptyNodeProvider.prototype.initProvider = function initProvider(properties) { + this.properties = properties; + }; + + /** + * + * @param node AjxpNode + * @param nodeCallback Function + * @param childCallback Function + */ + + EmptyNodeProvider.prototype.loadNode = function loadNode(node, nodeCallback, childCallback) {}; + + EmptyNodeProvider.prototype.loadLeafNodeSyncfunction = function loadLeafNodeSyncfunction(node, callback) {}; return EmptyNodeProvider; })(Observable); \ No newline at end of file diff --git a/core/src/plugins/gui.ajax/res/js/core/model/PydioDataModel.js b/core/src/plugins/gui.ajax/res/js/core/model/PydioDataModel.js index 77be460c83..4d70a427f0 100644 --- a/core/src/plugins/gui.ajax/res/js/core/model/PydioDataModel.js +++ b/core/src/plugins/gui.ajax/res/js/core/model/PydioDataModel.js @@ -2,10 +2,6 @@ var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; -var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - -var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; - var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; /* @@ -44,7 +40,7 @@ var PydioDataModel = (function (_Observable) { _classCallCheck(this, PydioDataModel); - _get(Object.getPrototypeOf(PydioDataModel.prototype), "constructor", this).call(this); + _Observable.call(this); this._currentRep = "/"; this._selectedNodes = []; this._bEmpty = true; @@ -63,773 +59,726 @@ var PydioDataModel = (function (_Observable) { _inherits(PydioDataModel, _Observable); - _createClass(PydioDataModel, [{ - key: "setAjxpNodeProvider", + /** + * Sets the data source that will feed the nodes with children. + * @param iAjxpNodeProvider IAjxpNodeProvider + */ - /** - * Sets the data source that will feed the nodes with children. - * @param iAjxpNodeProvider IAjxpNodeProvider - */ - value: function setAjxpNodeProvider(iAjxpNodeProvider) { - this._iAjxpNodeProvider = iAjxpNodeProvider; - } - }, { - key: "getAjxpNodeProvider", - - /** - * Return the current data source provider - * @return IAjxpNodeProvider - */ - value: function getAjxpNodeProvider() { - return this._iAjxpNodeProvider; - } - }, { - key: "requireContextChange", - - /** - * Changes the current context node. - * @param ajxpNode AjxpNode Target node, either an existing one or a fake one containing the target part. - * @param forceReload Boolean If set to true, the node will be reloaded even if already loaded. - */ - value: function requireContextChange(ajxpNode, forceReload) { - if (ajxpNode == null) { + PydioDataModel.prototype.setAjxpNodeProvider = function setAjxpNodeProvider(iAjxpNodeProvider) { + this._iAjxpNodeProvider = iAjxpNodeProvider; + }; + + /** + * Return the current data source provider + * @return IAjxpNodeProvider + */ + + PydioDataModel.prototype.getAjxpNodeProvider = function getAjxpNodeProvider() { + return this._iAjxpNodeProvider; + }; + + /** + * Changes the current context node. + * @param ajxpNode AjxpNode Target node, either an existing one or a fake one containing the target part. + * @param forceReload Boolean If set to true, the node will be reloaded even if already loaded. + */ + + PydioDataModel.prototype.requireContextChange = function requireContextChange(ajxpNode, forceReload) { + if (ajxpNode == null) { + return; + }var path = ajxpNode.getPath(); + if ((path == "" || path == "/") && ajxpNode != this._rootNode) { + ajxpNode = this._rootNode; + } + if (ajxpNode.getMetadata().has("paginationData") && ajxpNode.getMetadata().get("paginationData").has("new_page") && ajxpNode.getMetadata().get("paginationData").get("new_page") != ajxpNode.getMetadata().get("paginationData").get("current")) { + var paginationPage = ajxpNode.getMetadata().get("paginationData").get("new_page"); + forceReload = true; + } + if (ajxpNode != this._rootNode && (!ajxpNode.getParent() || ajxpNode.fake)) { + // Find in arbo or build fake arbo + var fakeNodes = []; + ajxpNode = ajxpNode.findInArbo(this._rootNode, fakeNodes); + if (fakeNodes.length) { + var firstFake = fakeNodes.shift(); + firstFake.observeOnce("first_load", (function (e) { + this.requireContextChange(ajxpNode); + }).bind(this)); + firstFake.observeOnce("error", (function (message) { + Logger.error(message); + firstFake.notify("node_removed"); + var parent = firstFake.getParent(); + parent.removeChild(firstFake); + //delete(firstFake); + this.requireContextChange(parent); + }).bind(this)); + this.publish("context_loading"); + firstFake.load(this._iAjxpNodeProvider); return; - }var path = ajxpNode.getPath(); - if ((path == "" || path == "/") && ajxpNode != this._rootNode) { - ajxpNode = this._rootNode; - } - if (ajxpNode.getMetadata().has("paginationData") && ajxpNode.getMetadata().get("paginationData").has("new_page") && ajxpNode.getMetadata().get("paginationData").get("new_page") != ajxpNode.getMetadata().get("paginationData").get("current")) { - var paginationPage = ajxpNode.getMetadata().get("paginationData").get("new_page"); - forceReload = true; - } - if (ajxpNode != this._rootNode && (!ajxpNode.getParent() || ajxpNode.fake)) { - // Find in arbo or build fake arbo - var fakeNodes = []; - ajxpNode = ajxpNode.findInArbo(this._rootNode, fakeNodes); - if (fakeNodes.length) { - var firstFake = fakeNodes.shift(); - firstFake.observeOnce("first_load", (function (e) { - this.requireContextChange(ajxpNode); - }).bind(this)); - firstFake.observeOnce("error", (function (message) { - Logger.error(message); - firstFake.notify("node_removed"); - var parent = firstFake.getParent(); - parent.removeChild(firstFake); - //delete(firstFake); - this.requireContextChange(parent); - }).bind(this)); - this.publish("context_loading"); - firstFake.load(this._iAjxpNodeProvider); - return; - } } - ajxpNode.observeOnce("loaded", (function () { - this.setContextNode(ajxpNode, true); - this.publish("context_loaded"); - if (this.getPendingSelection()) { - var selPath = ajxpNode.getPath() + (ajxpNode.getPath() == "/" ? "" : "/") + this.getPendingSelection(); - var selNode = ajxpNode.findChildByPath(selPath); - if (selNode) { - this.setSelectedNodes([selNode], this); - } else { - if (ajxpNode.getMetadata().get("paginationData") && arguments.length < 3) { - var newPage; - var currentPage = ajxpNode.getMetadata().get("paginationData").get("current"); - this.loadPathInfoSync(selPath, function (foundNode) { - newPage = foundNode.getMetadata().get("page_position"); - }); - if (newPage && newPage != currentPage) { - ajxpNode.getMetadata().get("paginationData").set("new_page", newPage); - this.requireContextChange(ajxpNode, true, true); - return; - } + } + ajxpNode.observeOnce("loaded", (function () { + this.setContextNode(ajxpNode, true); + this.publish("context_loaded"); + if (this.getPendingSelection()) { + var selPath = ajxpNode.getPath() + (ajxpNode.getPath() == "/" ? "" : "/") + this.getPendingSelection(); + var selNode = ajxpNode.findChildByPath(selPath); + if (selNode) { + this.setSelectedNodes([selNode], this); + } else { + if (ajxpNode.getMetadata().get("paginationData") && arguments.length < 3) { + var newPage; + var currentPage = ajxpNode.getMetadata().get("paginationData").get("current"); + this.loadPathInfoSync(selPath, function (foundNode) { + newPage = foundNode.getMetadata().get("page_position"); + }); + if (newPage && newPage != currentPage) { + ajxpNode.getMetadata().get("paginationData").set("new_page", newPage); + this.requireContextChange(ajxpNode, true, true); + return; } } - this.clearPendingSelection(); - } - }).bind(this)); - ajxpNode.observeOnce("error", (function (message) { - Logger.error(message); - this.publish("context_loaded"); - }).bind(this)); - this.publish("context_loading"); - try { - if (forceReload) { - if (paginationPage) { - ajxpNode.getMetadata().get("paginationData").set("current", paginationPage); - } - ajxpNode.reload(this._iAjxpNodeProvider); - } else { - ajxpNode.load(this._iAjxpNodeProvider); } - } catch (e) { - this.publish("context_loaded"); - } - } - }, { - key: "requireNodeReload", - value: function requireNodeReload(nodeOrPath, completeCallback) { - if (nodeOrPath instanceof String) { - nodeOrPath = new AjxpNode(nodeOrPath); + this.clearPendingSelection(); } - var onComplete = null; - if (this._selectedNodes.length) { - var found = false; - this._selectedNodes.each(function (node) { - if (node.getPath() == nodeOrPath.getPath()) found = node; - }); - if (found) { - // MAKE SURE SELECTION IS OK AFTER RELOAD - this._selectedNodes = this._selectedNodes.without(found); - this.publish("selection_changed", this); - onComplete = (function (newNode) { - this._selectedNodes.push(newNode); - this._selectionSource = {}; - this.publish("selection_changed", this); - if (completeCallback) completeCallback(newNode); - }).bind(this); + }).bind(this)); + ajxpNode.observeOnce("error", (function (message) { + Logger.error(message); + this.publish("context_loaded"); + }).bind(this)); + this.publish("context_loading"); + try { + if (forceReload) { + if (paginationPage) { + ajxpNode.getMetadata().get("paginationData").set("current", paginationPage); } + ajxpNode.reload(this._iAjxpNodeProvider); + } else { + ajxpNode.load(this._iAjxpNodeProvider); } - this._iAjxpNodeProvider.refreshNodeAndReplace(nodeOrPath, onComplete); + } catch (e) { + this.publish("context_loaded"); } - }, { - key: "loadPathInfoSync", - value: function loadPathInfoSync(path, callback) { - this._iAjxpNodeProvider.loadLeafNodeSync(new AjxpNode(path), callback, false); + }; + + PydioDataModel.prototype.requireNodeReload = function requireNodeReload(nodeOrPath, completeCallback) { + if (nodeOrPath instanceof String) { + nodeOrPath = new AjxpNode(nodeOrPath); } - }, { - key: "loadPathInfoAsync", - value: function loadPathInfoAsync(path, callback) { - this._iAjxpNodeProvider.loadLeafNodeSync(new AjxpNode(path), callback, true); + var onComplete = null; + if (this._selectedNodes.length) { + var found = false; + this._selectedNodes.each(function (node) { + if (node.getPath() == nodeOrPath.getPath()) found = node; + }); + if (found) { + // MAKE SURE SELECTION IS OK AFTER RELOAD + this._selectedNodes = this._selectedNodes.without(found); + this.publish("selection_changed", this); + onComplete = (function (newNode) { + this._selectedNodes.push(newNode); + this._selectionSource = {}; + this.publish("selection_changed", this); + if (completeCallback) completeCallback(newNode); + }).bind(this); + } } - }, { - key: "setRootNode", - - /** - * Sets the root of the data store - * @param ajxpRootNode AjxpNode The parent node - */ - value: function setRootNode(ajxpRootNode) { - this._rootNode = ajxpRootNode; - this._rootNode.setRoot(); - this._rootNode.observe("child_added", function (c) {}); - this.publish("root_node_changed", this._rootNode); - this.setContextNode(this._rootNode); + this._iAjxpNodeProvider.refreshNodeAndReplace(nodeOrPath, onComplete); + }; + + PydioDataModel.prototype.loadPathInfoSync = function loadPathInfoSync(path, callback) { + this._iAjxpNodeProvider.loadLeafNodeSync(new AjxpNode(path), callback, false); + }; + + PydioDataModel.prototype.loadPathInfoAsync = function loadPathInfoAsync(path, callback) { + this._iAjxpNodeProvider.loadLeafNodeSync(new AjxpNode(path), callback, true); + }; + + /** + * Sets the root of the data store + * @param ajxpRootNode AjxpNode The parent node + */ + + PydioDataModel.prototype.setRootNode = function setRootNode(ajxpRootNode) { + this._rootNode = ajxpRootNode; + this._rootNode.setRoot(); + this._rootNode.observe("child_added", function (c) {}); + this.publish("root_node_changed", this._rootNode); + this.setContextNode(this._rootNode); + }; + + /** + * Gets the current root node + * @returns AjxpNode + */ + + PydioDataModel.prototype.getRootNode = function getRootNode() { + return this._rootNode; + }; + + /** + * Sets the current context node + * @param ajxpDataNode AjxpNode + * @param forceEvent Boolean If set to true, event will be triggered even if the current node is already the same. + */ + + PydioDataModel.prototype.setContextNode = function setContextNode(ajxpDataNode, forceEvent) { + if (this._contextNode && this._contextNode == ajxpDataNode && this._currentRep == ajxpDataNode.getPath() && !forceEvent) { + return; // No changes } - }, { - key: "getRootNode", - - /** - * Gets the current root node - * @returns AjxpNode - */ - value: function getRootNode() { - return this._rootNode; + if (!ajxpDataNode) { + return; + }if (this._contextNodeReplacedObserver && this._contextNode) { + this._contextNode.stopObserving("node_replaced", this._contextNodeReplacedObserver); } - }, { - key: "setContextNode", - - /** - * Sets the current context node - * @param ajxpDataNode AjxpNode - * @param forceEvent Boolean If set to true, event will be triggered even if the current node is already the same. - */ - value: function setContextNode(ajxpDataNode, forceEvent) { - if (this._contextNode && this._contextNode == ajxpDataNode && this._currentRep == ajxpDataNode.getPath() && !forceEvent) { - return; // No changes + this._contextNode = ajxpDataNode; + this._currentRep = ajxpDataNode.getPath(); + this.publish("context_changed", ajxpDataNode); + if (!this._contextNodeReplacedObserver) this._contextNodeReplacedObserver = this.contextNodeReplaced.bind(this); + ajxpDataNode.observe("node_replaced", this._contextNodeReplacedObserver); + }; + + PydioDataModel.prototype.contextNodeReplaced = function contextNodeReplaced(newNode) { + this.setContextNode(newNode); + }; + + /** + * + */ + + PydioDataModel.prototype.publish = function publish(eventName, optionalData) { + var args = []; + if (this._globalEvents) { + if (window.pydio) { + args.push(eventName); + if (optionalData) args.push(optionalData); + pydio.fire.apply(pydio, args); + } else if (document.fire) { + args.push("ajaxplorer:" + eventName); + if (optionalData) args.push(optionalData); + document.fire.apply(document, args); } - if (!ajxpDataNode) { - return; - }if (this._contextNodeReplacedObserver && this._contextNode) { - this._contextNode.stopObserving("node_replaced", this._contextNodeReplacedObserver); + if (optionalData) { + args = [eventName, { memo: optionalData }]; + } else { + args = [eventName]; } - this._contextNode = ajxpDataNode; - this._currentRep = ajxpDataNode.getPath(); - this.publish("context_changed", ajxpDataNode); - if (!this._contextNodeReplacedObserver) this._contextNodeReplacedObserver = this.contextNodeReplaced.bind(this); - ajxpDataNode.observe("node_replaced", this._contextNodeReplacedObserver); - } - }, { - key: "contextNodeReplaced", - value: function contextNodeReplaced(newNode) { - this.setContextNode(newNode); - } - }, { - key: "publish", - - /** - * - */ - value: function publish(eventName, optionalData) { - var args = []; - if (this._globalEvents) { - if (window.pydio) { - args.push(eventName); - if (optionalData) args.push(optionalData); - pydio.fire.apply(pydio, args); - } else if (document.fire) { - args.push("ajaxplorer:" + eventName); - if (optionalData) args.push(optionalData); - document.fire.apply(document, args); - } - if (optionalData) { - args = [eventName, { memo: optionalData }]; - } else { - args = [eventName]; - } - this.notify.apply(this, args); + this.notify.apply(this, args); + } else { + if (optionalData) { + args = [eventName, { memo: optionalData }]; } else { - if (optionalData) { - args = [eventName, { memo: optionalData }]; - } else { - args = [eventName]; - } - this.notify.apply(this, args); + args = [eventName]; } + this.notify.apply(this, args); } - }, { - key: "getContextNode", - - /** - * Get the current context node - * @returns AjxpNode - */ - value: function getContextNode() { - return this._contextNode; - } - }, { - key: "multipleNodesReload", - - /** - * After a copy or move operation, many nodes may have to be reloaded - * This function tries to reload them in the right order and if necessary. - * @param nodes AjxpNodes[] An array of nodes - */ - value: function multipleNodesReload(nodes) { - for (var i = 0; i < nodes.length; i++) { - var nodePathOrNode = nodes[i]; - var node; - if (nodePathOrNode instanceof String) { - node = new AjxpNode(nodePathOrNode); - if (node.getPath() == this._rootNode.getPath()) node = this._rootNode;else node = node.findInArbo(this._rootNode, []); - } else { - node = nodePathOrNode; - } - nodes[i] = node; + }; + + /** + * Get the current context node + * @returns AjxpNode + */ + + PydioDataModel.prototype.getContextNode = function getContextNode() { + return this._contextNode; + }; + + /** + * After a copy or move operation, many nodes may have to be reloaded + * This function tries to reload them in the right order and if necessary. + * @param nodes AjxpNodes[] An array of nodes + */ + + PydioDataModel.prototype.multipleNodesReload = function multipleNodesReload(nodes) { + for (var i = 0; i < nodes.length; i++) { + var nodePathOrNode = nodes[i]; + var node; + if (nodePathOrNode instanceof String) { + node = new AjxpNode(nodePathOrNode); + if (node.getPath() == this._rootNode.getPath()) node = this._rootNode;else node = node.findInArbo(this._rootNode, []); + } else { + node = nodePathOrNode; } - var children = []; - nodes.sort(function (a, b) { - if (a.isParentOf(b)) { - children.push(b); - return -1; - } - if (a.isChildOf(b)) { - children.push(a); - return +1; - } - return 0; - }); - children.each(function (c) { - nodes = nodes.without(c); - }); - nodes.each(this.queueNodeReload.bind(this)); - this.nextNodeReloader(); + nodes[i] = node; } - }, { - key: "queueNodeReload", - - /** - * Add a node to the queue of nodes to reload. - * @param node AjxpNode - */ - value: function queueNodeReload(node) { - if (!this.queue) this.queue = []; - if (node) { - this.queue.push(node); + var children = []; + nodes.sort(function (a, b) { + if (a.isParentOf(b)) { + children.push(b); + return -1; } - } - }, { - key: "nextNodeReloader", - - /** - * Queue processor for the nodes to reload - */ - value: function nextNodeReloader() { - if (!this.queue.length) { - window.setTimeout((function () { - this.publish("context_changed", this._contextNode); - }).bind(this), 200); - return; + if (a.isChildOf(b)) { + children.push(a); + return +1; } - var next = this.queue.shift(); - var observer = this.nextNodeReloader.bind(this); - next.observeOnce("loaded", observer); - next.observeOnce("error", observer); - if (next == this._contextNode || next.isParentOf(this._contextNode)) { - this.requireContextChange(next, true); - } else { - next.reload(this._iAjxpNodeProvider); + return 0; + }); + children.each(function (c) { + nodes = nodes.without(c); + }); + nodes.each(this.queueNodeReload.bind(this)); + this.nextNodeReloader(); + }; + + /** + * Add a node to the queue of nodes to reload. + * @param node AjxpNode + */ + + PydioDataModel.prototype.queueNodeReload = function queueNodeReload(node) { + if (!this.queue) this.queue = []; + if (node) { + this.queue.push(node); + } + }; + + /** + * Queue processor for the nodes to reload + */ + + PydioDataModel.prototype.nextNodeReloader = function nextNodeReloader() { + if (!this.queue.length) { + window.setTimeout((function () { + this.publish("context_changed", this._contextNode); + }).bind(this), 200); + return; + } + var next = this.queue.shift(); + var observer = this.nextNodeReloader.bind(this); + next.observeOnce("loaded", observer); + next.observeOnce("error", observer); + if (next == this._contextNode || next.isParentOf(this._contextNode)) { + this.requireContextChange(next, true); + } else { + next.reload(this._iAjxpNodeProvider); + } + }; + + /** + * Insert a node somewhere in the datamodel + * @param node AjxpNode + * @param setSelectedAfterAdd bool + */ + + PydioDataModel.prototype.addNode = function addNode(node) { + var setSelectedAfterAdd = arguments[1] === undefined ? false : arguments[1]; + + var parentFake = new AjxpNode(PathUtils.getDirname(node.getPath())); + var parent = parentFake.findInArbo(this.getRootNode(), undefined); + if (!parent && PathUtils.getDirname(node.getPath()) == "") parent = this.getRootNode(); + if (parent) { + parent.addChild(node); + if (setSelectedAfterAdd && this.getContextNode() == parent) { + this.setSelectedNodes([node], {}); } } - }, { - key: "addNode", - - /** - * Insert a node somewhere in the datamodel - * @param node AjxpNode - * @param setSelectedAfterAdd bool - */ - value: function addNode(node) { - var setSelectedAfterAdd = arguments[1] === undefined ? false : arguments[1]; - - var parentFake = new AjxpNode(PathUtils.getDirname(node.getPath())); + }; + + /** + * Remove a node by path somewhere + * @param path string + */ + + PydioDataModel.prototype.removeNodeByPath = function removeNodeByPath(path) { + var fake = new AjxpNode(path); + var n = fake.findInArbo(this.getRootNode(), undefined); + if (n) { + n.getParent().removeChild(n); + return true; + } + return false; + }; + + /** + * Update a node somewhere in the datamodel + * @param node AjxpNode + * @param setSelectedAfterUpdate bool + */ + + PydioDataModel.prototype.updateNode = function updateNode(node) { + var setSelectedAfterUpdate = arguments[1] === undefined ? false : arguments[1]; + + var original = node.getMetadata().get("original_path"); + var fake, n; + if (original && original != node.getPath() && PathUtils.getDirname(original) != PathUtils.getDirname(node.getPath())) { + // Node was really moved to another folder + fake = new AjxpNode(original); + n = fake.findInArbo(this.getRootNode(), undefined); + if (n) { + n.getParent().removeChild(n); + } + var parentFake = new AjxpNode(getRepName(node.getPath())); var parent = parentFake.findInArbo(this.getRootNode(), undefined); - if (!parent && PathUtils.getDirname(node.getPath()) == "") parent = this.getRootNode(); + if (!parent && getRepName(node.getPath()) == "") parent = this.getRootNode(); if (parent) { + node.getMetadata().set("original_path", undefined); parent.addChild(node); - if (setSelectedAfterAdd && this.getContextNode() == parent) { - this.setSelectedNodes([node], {}); - } } - } - }, { - key: "removeNodeByPath", - - /** - * Remove a node by path somewhere - * @param path string - */ - value: function removeNodeByPath(path) { - var fake = new AjxpNode(path); - var n = fake.findInArbo(this.getRootNode(), undefined); + } else { + fake = new AjxpNode(original); + n = fake.findInArbo(this.getRootNode(), undefined); if (n) { - n.getParent().removeChild(n); - return true; - } - return false; - } - }, { - key: "updateNode", - - /** - * Update a node somewhere in the datamodel - * @param node AjxpNode - * @param setSelectedAfterUpdate bool - */ - value: function updateNode(node) { - var setSelectedAfterUpdate = arguments[1] === undefined ? false : arguments[1]; - - var original = node.getMetadata().get("original_path"); - var fake, n; - if (original && original != node.getPath() && PathUtils.getDirname(original) != PathUtils.getDirname(node.getPath())) { - // Node was really moved to another folder - fake = new AjxpNode(original); - n = fake.findInArbo(this.getRootNode(), undefined); - if (n) { - n.getParent().removeChild(n); - } - var parentFake = new AjxpNode(getRepName(node.getPath())); - var parent = parentFake.findInArbo(this.getRootNode(), undefined); - if (!parent && getRepName(node.getPath()) == "") parent = this.getRootNode(); - if (parent) { - node.getMetadata().set("original_path", undefined); - parent.addChild(node); - } - } else { - fake = new AjxpNode(original); - n = fake.findInArbo(this.getRootNode(), undefined); - if (n) { - node._isLoaded = n._isLoaded; - n.replaceBy(node, "override"); - if (setSelectedAfterUpdate && this.getContextNode() == n.getParent()) { - this.setSelectedNodes([n], {}); - } + node._isLoaded = n._isLoaded; + n.replaceBy(node, "override"); + if (setSelectedAfterUpdate && this.getContextNode() == n.getParent()) { + this.setSelectedNodes([n], {}); } } } - }, { - key: "setPendingSelection", - - /** - * Sets an array of nodes to be selected after the context is (re)loaded - * @param selection AjxpNode[] - */ - value: function setPendingSelection(selection) { - this._pendingSelection = selection; - } - }, { - key: "getPendingSelection", - - /** - * Gets the array of nodes to be selected after the context is (re)loaded - * @returns AjxpNode[] - */ - value: function getPendingSelection() { - return this._pendingSelection; - } - }, { - key: "clearPendingSelection", - - /** - * Clears the nodes to be selected - */ - value: function clearPendingSelection() { - this._pendingSelection = null; - } - }, { - key: "setSelectedNodes", - - /** - * Set an array of nodes as the current selection - * @param ajxpDataNodes AjxpNode[] The nodes to select - * @param source String The source of this selection action - */ - value: function setSelectedNodes(ajxpDataNodes, source) { - if (!source) { - this._selectionSource = {}; - } else { - this._selectionSource = source; - } - this._selectedNodes = ajxpDataNodes; - this._bEmpty = ajxpDataNodes && ajxpDataNodes.length ? false : true; - this._bFile = this._bDir = this._isRecycle = false; - if (!this._bEmpty) { - this._bUnique = ajxpDataNodes.length == 1; - for (var i = 0; i < ajxpDataNodes.length; i++) { - var selectedNode = ajxpDataNodes[i]; - if (selectedNode.isLeaf()) this._bFile = true;else this._bDir = true; - if (selectedNode.isRecycle()) this._isRecycle = true; - } + }; + + /** + * Sets an array of nodes to be selected after the context is (re)loaded + * @param selection AjxpNode[] + */ + + PydioDataModel.prototype.setPendingSelection = function setPendingSelection(selection) { + this._pendingSelection = selection; + }; + + /** + * Gets the array of nodes to be selected after the context is (re)loaded + * @returns AjxpNode[] + */ + + PydioDataModel.prototype.getPendingSelection = function getPendingSelection() { + return this._pendingSelection; + }; + + /** + * Clears the nodes to be selected + */ + + PydioDataModel.prototype.clearPendingSelection = function clearPendingSelection() { + this._pendingSelection = null; + }; + + /** + * Set an array of nodes as the current selection + * @param ajxpDataNodes AjxpNode[] The nodes to select + * @param source String The source of this selection action + */ + + PydioDataModel.prototype.setSelectedNodes = function setSelectedNodes(ajxpDataNodes, source) { + if (!source) { + this._selectionSource = {}; + } else { + this._selectionSource = source; + } + this._selectedNodes = ajxpDataNodes; + this._bEmpty = ajxpDataNodes && ajxpDataNodes.length ? false : true; + this._bFile = this._bDir = this._isRecycle = false; + if (!this._bEmpty) { + this._bUnique = ajxpDataNodes.length == 1; + for (var i = 0; i < ajxpDataNodes.length; i++) { + var selectedNode = ajxpDataNodes[i]; + if (selectedNode.isLeaf()) this._bFile = true;else this._bDir = true; + if (selectedNode.isRecycle()) this._isRecycle = true; } - this.publish("selection_changed", this); } - }, { - key: "getSelectedNodes", - - /** - * Gets the currently selected nodes - * @returns AjxpNode[] - */ - value: function getSelectedNodes() { - return this._selectedNodes; + this.publish("selection_changed", this); + }; + + /** + * Gets the currently selected nodes + * @returns AjxpNode[] + */ + + PydioDataModel.prototype.getSelectedNodes = function getSelectedNodes() { + return this._selectedNodes; + }; + + /** + * Gets the source of the last selection action + * @returns String + */ + + PydioDataModel.prototype.getSelectionSource = function getSelectionSource() { + return this._selectionSource; + }; + + /** + * Manually sets the source of the selection + * @param object + */ + + PydioDataModel.prototype.setSelectionSource = function setSelectionSource(object) { + this._selectionSource = object; + }; + + /** + * DEPRECATED + */ + + PydioDataModel.prototype.getSelectedItems = function getSelectedItems() { + throw new Error("Deprecated : use getSelectedNodes() instead"); + }; + + /** + * Select all the children of the current context node + */ + + PydioDataModel.prototype.selectAll = function selectAll() { + this.setSelectedNodes(this._contextNode.getChildren(), "dataModel"); + }; + + /** + * Whether the selection is empty + * @returns Boolean + */ + + PydioDataModel.prototype.isEmpty = function isEmpty() { + return this._selectedNodes ? this._selectedNodes.length == 0 : true; + }; + + PydioDataModel.prototype.hasReadOnly = function hasReadOnly() { + var test = false; + try { + this._selectedNodes.forEach(function (node) { + if (node.hasMetadataInBranch("ajxp_readonly", "true")) { + test = true; + throw $break; + } + }); + } catch (e) {} + return test; + }; + + PydioDataModel.prototype.selectionHasRootNode = function selectionHasRootNode() { + var found = false; + try { + this._selectedNodes.forEach(function (el) { + if (el.isRoot()) { + found = true; + throw new Error(); + } + }); + } catch (e) {} + }; + + /** + * Whether the selection is unique + * @returns Boolean + */ + + PydioDataModel.prototype.isUnique = function isUnique() { + return this._bUnique; + }; + + /** + * Whether the selection has a file selected. + * Should be hasLeaf + * @returns Boolean + */ + + PydioDataModel.prototype.hasFile = function hasFile() { + return this._bFile; + }; + + /** + * Whether the selection has a dir selected + * @returns Boolean + */ + + PydioDataModel.prototype.hasDir = function hasDir() { + return this._bDir; + }; + + /** + * Whether the current context is the recycle bin + * @returns Boolean + */ + + PydioDataModel.prototype.isRecycle = function isRecycle() { + return this._isRecycle; + }; + + /** + * Whether the selection has more than one node selected + * @returns Boolean + */ + + PydioDataModel.prototype.isMultiple = function isMultiple() { + return this._selectedNodes && this._selectedNodes.length > 1; + }; + + /** + * Whether the selection has a file with one of the mimes + * @param mimeTypes Array Array of mime types + * @returns Boolean + */ + + PydioDataModel.prototype.hasMime = function hasMime(mimeTypes) { + if (mimeTypes.length == 1 && mimeTypes[0] == "*") { + return true; + }var has = false; + mimeTypes.each((function (mime) { + if (has) return; + has = this._selectedNodes.any(function (node) { + return getAjxpMimeType(node) == mime; + }); + }).bind(this)); + return has; + }; + + /** + * Get all selected filenames as an array. + * @param separator String Is a separator, will return a string joined + * @returns Array|String|bool + */ + + PydioDataModel.prototype.getFileNames = function getFileNames(separator) { + if (!this._selectedNodes.length) { + alert("Please select a file!"); + return false; } - }, { - key: "getSelectionSource", - - /** - * Gets the source of the last selection action - * @returns String - */ - value: function getSelectionSource() { - return this._selectionSource; + var tmp = new Array(this._selectedNodes.length); + for (var i = 0; i < this._selectedNodes.length; i++) { + tmp[i] = this._selectedNodes[i].getPath(); } - }, { - key: "setSelectionSource", - - /** - * Manually sets the source of the selection - * @param object - */ - value: function setSelectionSource(object) { - this._selectionSource = object; + if (separator) { + return tmp.join(separator); + } else { + return tmp; } - }, { - key: "getSelectedItems", - - /** - * DEPRECATED - */ - value: function getSelectedItems() { - throw new Error("Deprecated : use getSelectedNodes() instead"); + }; + + /** + * Get all the filenames of the current context node children + * @param separator String If passed, will join the array as a string + * @return Array|String|bool + */ + + PydioDataModel.prototype.getContextFileNames = function getContextFileNames(separator) { + var allItems = this._contextNode.getChildren(); + if (!allItems.length) { + return false; } - }, { - key: "selectAll", - - /** - * Select all the children of the current context node - */ - value: function selectAll() { - this.setSelectedNodes(this._contextNode.getChildren(), "dataModel"); + var names = []; + for (var i = 0; i < allItems.length; i++) { + names.push(getBaseName(allItems[i].getPath())); } - }, { - key: "isEmpty", - - /** - * Whether the selection is empty - * @returns Boolean - */ - value: function isEmpty() { - return this._selectedNodes ? this._selectedNodes.length == 0 : true; + if (separator) { + return names.join(separator); + } else { + return names; } - }, { - key: "hasReadOnly", - value: function hasReadOnly() { - var test = false; - try { - this._selectedNodes.forEach(function (node) { - if (node.hasMetadataInBranch("ajxp_readonly", "true")) { - test = true; - throw $break; - } - }); - } catch (e) {} - return test; + }; + + /** + * Whether the context node has a child with this basename + * @param newFileName String The name to check + * @returns Boolean + * @param local + * @param contextNode + */ + + PydioDataModel.prototype.fileNameExists = function fileNameExists(newFileName, local, contextNode) { + if (!contextNode) { + contextNode = this._contextNode; } - }, { - key: "selectionHasRootNode", - value: function selectionHasRootNode() { + if (local) { + var test = (contextNode.getPath() == "/" ? "" : contextNode.getPath()) + "/" + newFileName; var found = false; try { - this._selectedNodes.forEach(function (el) { - if (el.isRoot()) { + contextNode.getChildren().forEach(function (c) { + if (c.getPath() == test) { found = true; throw new Error(); } }); } catch (e) {} - } - }, { - key: "isUnique", - - /** - * Whether the selection is unique - * @returns Boolean - */ - value: function isUnique() { - return this._bUnique; - } - }, { - key: "hasFile", - - /** - * Whether the selection has a file selected. - * Should be hasLeaf - * @returns Boolean - */ - value: function hasFile() { - return this._bFile; - } - }, { - key: "hasDir", - - /** - * Whether the selection has a dir selected - * @returns Boolean - */ - value: function hasDir() { - return this._bDir; - } - }, { - key: "isRecycle", - - /** - * Whether the current context is the recycle bin - * @returns Boolean - */ - value: function isRecycle() { - return this._isRecycle; - } - }, { - key: "isMultiple", - - /** - * Whether the selection has more than one node selected - * @returns Boolean - */ - value: function isMultiple() { - return this._selectedNodes && this._selectedNodes.length > 1; - } - }, { - key: "hasMime", - - /** - * Whether the selection has a file with one of the mimes - * @param mimeTypes Array Array of mime types - * @returns Boolean - */ - value: function hasMime(mimeTypes) { - if (mimeTypes.length == 1 && mimeTypes[0] == "*") { - return true; - }var has = false; - mimeTypes.each((function (mime) { - if (has) return; - has = this._selectedNodes.any(function (node) { - return getAjxpMimeType(node) == mime; - }); - }).bind(this)); - return has; - } - }, { - key: "getFileNames", - - /** - * Get all selected filenames as an array. - * @param separator String Is a separator, will return a string joined - * @returns Array|String|bool - */ - value: function getFileNames(separator) { - if (!this._selectedNodes.length) { - alert("Please select a file!"); - return false; - } - var tmp = new Array(this._selectedNodes.length); - for (var i = 0; i < this._selectedNodes.length; i++) { - tmp[i] = this._selectedNodes[i].getPath(); - } - if (separator) { - return tmp.join(separator); - } else { - return tmp; - } - } - }, { - key: "getContextFileNames", - - /** - * Get all the filenames of the current context node children - * @param separator String If passed, will join the array as a string - * @return Array|String|bool - */ - value: function getContextFileNames(separator) { - var allItems = this._contextNode.getChildren(); - if (!allItems.length) { - return false; - } - var names = []; - for (var i = 0; i < allItems.length; i++) { - names.push(getBaseName(allItems[i].getPath())); - } - if (separator) { - return names.join(separator); - } else { - return names; - } - } - }, { - key: "fileNameExists", - - /** - * Whether the context node has a child with this basename - * @param newFileName String The name to check - * @returns Boolean - * @param local - * @param contextNode - */ - value: function fileNameExists(newFileName, local, contextNode) { - if (!contextNode) { - contextNode = this._contextNode; - } - if (local) { - var test = (contextNode.getPath() == "/" ? "" : contextNode.getPath()) + "/" + newFileName; - var found = false; - try { - contextNode.getChildren().forEach(function (c) { - if (c.getPath() == test) { - found = true; - throw new Error(); - } - }); - } catch (e) {} - return found; - } else { - var nodeExists = false; - this.loadPathInfoSync(contextNode.getPath() + "/" + newFileName, function (foundNode) { - nodeExists = true; - }); - return nodeExists; - } - } - }, { - key: "applyCheckHook", - value: function applyCheckHook(node) { - "use strict"; - var client = PydioApi.getClient(); - var result; - client.applyCheckHook(node, "before_create", node.getMetadata().get("filesize") || -1, function (transport) { - result = pydio.getController().parseXmlMessage(transport.responseXML); + return found; + } else { + var nodeExists = false; + this.loadPathInfoSync(contextNode.getPath() + "/" + newFileName, function (foundNode) { + nodeExists = true; }); - if (result === false) { - throw new Error("Check failed"); - } + return nodeExists; } - }, { - key: "getUniqueFileName", - - /** - * Gets the first name of the current selection - * @returns String - */ - value: function getUniqueFileName() { - if (this.getFileNames().length) { - return this.getFileNames()[0]; - }return null; + }; + + PydioDataModel.prototype.applyCheckHook = function applyCheckHook(node) { + "use strict"; + var client = PydioApi.getClient(); + var result; + client.applyCheckHook(node, "before_create", node.getMetadata().get("filesize") || -1, function (transport) { + result = pydio.getController().parseXmlMessage(transport.responseXML); + }); + if (result === false) { + throw new Error("Check failed"); } - }, { - key: "getUniqueNode", - - /** - * Gets the first node of the selection, or Null - * @returns AjxpNode - */ - value: function getUniqueNode() { - if (this._selectedNodes.length) { - return this._selectedNodes[0]; - } - return null; + }; + + /** + * Gets the first name of the current selection + * @returns String + */ + + PydioDataModel.prototype.getUniqueFileName = function getUniqueFileName() { + if (this.getFileNames().length) { + return this.getFileNames()[0]; + }return null; + }; + + /** + * Gets the first node of the selection, or Null + * @returns AjxpNode + */ + + PydioDataModel.prototype.getUniqueNode = function getUniqueNode() { + if (this._selectedNodes.length) { + return this._selectedNodes[0]; } - }, { - key: "getNode", - - /** - * Gets a node from the current selection - * @param i Integer the node index - * @returns AjxpNode - */ - value: function getNode(i) { - return this._selectedNodes[i]; + return null; + }; + + /** + * Gets a node from the current selection + * @param i Integer the node index + * @returns AjxpNode + */ + + PydioDataModel.prototype.getNode = function getNode(i) { + return this._selectedNodes[i]; + }; + + /** + * Will add the current selection nodes as serializable data to the element passed : + * either as hidden input elements if it's a form, or as query parameters if it's an url + * @param oFormElement HTMLForm The form + * @param sUrl String An url to complete + * @returns String + */ + + PydioDataModel.prototype.updateFormOrUrl = function updateFormOrUrl(oFormElement, sUrl) { + // CLEAR FROM PREVIOUS ACTIONS! + if (oFormElement) { + $(oFormElement).select("input[type=\"hidden\"]").each(function (element) { + if (element.name == "nodes[]" || element.name == "file") element.remove(); + }); } - }, { - key: "updateFormOrUrl", - - /** - * Will add the current selection nodes as serializable data to the element passed : - * either as hidden input elements if it's a form, or as query parameters if it's an url - * @param oFormElement HTMLForm The form - * @param sUrl String An url to complete - * @returns String - */ - value: function updateFormOrUrl(oFormElement, sUrl) { - // CLEAR FROM PREVIOUS ACTIONS! - if (oFormElement) { - $(oFormElement).select("input[type=\"hidden\"]").each(function (element) { - if (element.name == "nodes[]" || element.name == "file") element.remove(); - }); - } - // UPDATE THE 'DIR' FIELDS - if (oFormElement && oFormElement.rep) oFormElement.rep.value = this._currentRep; - sUrl += "&dir=" + encodeURIComponent(this._currentRep); - - // UPDATE THE 'file' FIELDS - if (this.isEmpty()) { - return sUrl; - }var fileNames = this.getFileNames(); - for (var i = 0; i < fileNames.length; i++) { - sUrl += "&" + "nodes[]=" + encodeURIComponent(fileNames[i]); - if (oFormElement) this._addHiddenField(oFormElement, "nodes[]", fileNames[i]); - } - if (fileNames.length == 1) { - sUrl += "&" + "file=" + encodeURIComponent(fileNames[0]); - if (oFormElement) this._addHiddenField(oFormElement, "file", fileNames[0]); - } + // UPDATE THE 'DIR' FIELDS + if (oFormElement && oFormElement.rep) oFormElement.rep.value = this._currentRep; + sUrl += "&dir=" + encodeURIComponent(this._currentRep); + + // UPDATE THE 'file' FIELDS + if (this.isEmpty()) { return sUrl; + }var fileNames = this.getFileNames(); + for (var i = 0; i < fileNames.length; i++) { + sUrl += "&" + "nodes[]=" + encodeURIComponent(fileNames[i]); + if (oFormElement) this._addHiddenField(oFormElement, "nodes[]", fileNames[i]); } - }, { - key: "_addHiddenField", - value: function _addHiddenField(oFormElement, sFieldName, sFieldValue) { - oFormElement.insert(new Element("input", { type: "hidden", name: sFieldName, value: sFieldValue })); + if (fileNames.length == 1) { + sUrl += "&" + "file=" + encodeURIComponent(fileNames[0]); + if (oFormElement) this._addHiddenField(oFormElement, "file", fileNames[0]); } - }]); + return sUrl; + }; + + PydioDataModel.prototype._addHiddenField = function _addHiddenField(oFormElement, sFieldName, sFieldValue) { + oFormElement.insert(new Element("input", { type: "hidden", name: sFieldName, value: sFieldValue })); + }; return PydioDataModel; })(Observable); diff --git a/core/src/plugins/gui.ajax/res/js/core/model/Registry.js b/core/src/plugins/gui.ajax/res/js/core/model/Registry.js index 4e1c344958..7c8ab658e3 100644 --- a/core/src/plugins/gui.ajax/res/js/core/model/Registry.js +++ b/core/src/plugins/gui.ajax/res/js/core/model/Registry.js @@ -2,8 +2,6 @@ var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; -var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - /* * Copyright 2007-2013 Charles du Jeu - Abstrium SAS * This file is part of Pydio. @@ -34,311 +32,295 @@ var Registry = (function () { this._pydioObject = pydioObject; } - _createClass(Registry, [{ - key: "loadFromString", - value: function loadFromString(s) { - this._registry = XMLUtils.parseXml(s).documentElement; - } - }, { - key: "load", - value: function load(sync, xPath, completeFunc) { - var onComplete = (function (transport) { - if (transport.responseXML == null || transport.responseXML.documentElement == null) return; - if (transport.responseXML.documentElement.nodeName == "ajxp_registry") { - this._registry = transport.responseXML.documentElement; - //modal.updateLoadingProgress('XML Registry loaded'); - if (!sync && !completeFunc) { - this._pydioObject.fire("registry_loaded", this._registry); - } - } else if (transport.responseXML.documentElement.nodeName == "ajxp_registry_part") { - this.refreshXmlRegistryPart(transport.responseXML.documentElement); - } - if (completeFunc) completeFunc(this._registry); - }).bind(this); - var params = { get_action: "get_xml_registry" }; - if (xPath) { - params.xPath = xPath; - } - PydioApi.getClient().request(params, onComplete, null, { async: !sync }); - } - }, { - key: "refreshXmlRegistryPart", + Registry.prototype.loadFromString = function loadFromString(s) { + this._registry = XMLUtils.parseXml(s).documentElement; + }; - /** - * Inserts a document fragment retrieved from server inside the full tree. - * The node must contains the xPath attribute to locate it inside the registry. - * Event ajaxplorer:registry_part_loaded is triggerd once this is done. - * @param documentElement DOMNode - */ - value: function refreshXmlRegistryPart(documentElement) { - var xPath = documentElement.getAttribute("xPath"); - var existingNode = XMLUtils.XPathSelectSingleNode(this._registry, xPath); - var parentNode; - if (existingNode && existingNode.parentNode) { - parentNode = existingNode.parentNode; - parentNode.removeChild(existingNode); - if (documentElement.firstChild) { - parentNode.appendChild(documentElement.firstChild.cloneNode(true)); - } - } else if (xPath.indexOf("/") > -1) { - // try selecting parentNode - var parentPath = xPath.substring(0, xPath.lastIndexOf("/")); - parentNode = XMLUtils.XPathSelectSingleNode(this._registry, parentPath); - if (parentNode && documentElement.firstChild) { - parentNode.appendChild(documentElement.firstChild.cloneNode(true)); + Registry.prototype.load = function load(sync, xPath, completeFunc) { + var onComplete = (function (transport) { + if (transport.responseXML == null || transport.responseXML.documentElement == null) return; + if (transport.responseXML.documentElement.nodeName == "ajxp_registry") { + this._registry = transport.responseXML.documentElement; + //modal.updateLoadingProgress('XML Registry loaded'); + if (!sync && !completeFunc) { + this._pydioObject.fire("registry_loaded", this._registry); } - } else { - if (documentElement.firstChild) this._registry.appendChild(documentElement.firstChild.cloneNode(true)); + } else if (transport.responseXML.documentElement.nodeName == "ajxp_registry_part") { + this.refreshXmlRegistryPart(transport.responseXML.documentElement); } - this._pydioObject.fire("registry_part_loaded", xPath); + if (completeFunc) completeFunc(this._registry); + }).bind(this); + var params = { get_action: "get_xml_registry" }; + if (xPath) { + params.xPath = xPath; } - }, { - key: "logXmlUser", + PydioApi.getClient().request(params, onComplete, null, { async: !sync }); + }; - /** - * Translate the XML answer to a new User object - * @param skipEvent Boolean Whether to skip the sending of ajaxplorer:user_logged event. - */ - value: function logXmlUser(skipEvent) { - this._pydioObject.user = null; - var userNode; - if (this._registry) { - userNode = XMLUtils.XPathSelectSingleNode(this._registry, "user"); - } - if (userNode) { - var userId = userNode.getAttribute("id"); - var children = userNode.childNodes; - if (userId) { - this._pydioObject.user = new User(userId, children); - } + /** + * Inserts a document fragment retrieved from server inside the full tree. + * The node must contains the xPath attribute to locate it inside the registry. + * Event ajaxplorer:registry_part_loaded is triggerd once this is done. + * @param documentElement DOMNode + */ + + Registry.prototype.refreshXmlRegistryPart = function refreshXmlRegistryPart(documentElement) { + var xPath = documentElement.getAttribute("xPath"); + var existingNode = XMLUtils.XPathSelectSingleNode(this._registry, xPath); + var parentNode; + if (existingNode && existingNode.parentNode) { + parentNode = existingNode.parentNode; + parentNode.removeChild(existingNode); + if (documentElement.firstChild) { + parentNode.appendChild(documentElement.firstChild.cloneNode(true)); } - if (!skipEvent) { - this._pydioObject.fire("user_logged", this._pydioObject.user); + } else if (xPath.indexOf("/") > -1) { + // try selecting parentNode + var parentPath = xPath.substring(0, xPath.lastIndexOf("/")); + parentNode = XMLUtils.XPathSelectSingleNode(this._registry, parentPath); + if (parentNode && documentElement.firstChild) { + parentNode.appendChild(documentElement.firstChild.cloneNode(true)); } + } else { + if (documentElement.firstChild) this._registry.appendChild(documentElement.firstChild.cloneNode(true)); } - }, { - key: "getXML", - value: function getXML() { - return this._registry; - } - }, { - key: "initExtension", + this._pydioObject.fire("registry_part_loaded", xPath); + }; - /** - * Find Extension initialisation nodes (activeCondition, onInit, etc), parses - * the XML and execute JS. - * @param xmlNode DOMNode The extension node - * @param extensionDefinition Object Information already collected about this extension - * @returns Boolean - */ - value: function initExtension(xmlNode, extensionDefinition) { - var activeCondition = XMLUtils.XPathSelectSingleNode(xmlNode, "processing/activeCondition"); - if (activeCondition && activeCondition.firstChild) { - try { - var func = new Function(activeCondition.firstChild.nodeValue.trim()); - if (func() === false) return false; - } catch (e) {} - } - if (xmlNode.nodeName == "editor") { - var properties = { - openable: xmlNode.getAttribute("openable") == "true", - modalOnly: xmlNode.getAttribute("modalOnly") == "true", - previewProvider: xmlNode.getAttribute("previewProvider") == "true", - order: xmlNode.getAttribute("order") ? parseInt(xmlNode.getAttribute("order")) : 0, - formId: xmlNode.getAttribute("formId") || null, - text: this._pydioObject.MessageHash[xmlNode.getAttribute("text")], - title: this._pydioObject.MessageHash[xmlNode.getAttribute("title")], - icon: xmlNode.getAttribute("icon"), - icon_class: xmlNode.getAttribute("iconClass"), - editorClass: xmlNode.getAttribute("className"), - mimes: xmlNode.getAttribute("mimes").split(","), - write: xmlNode.getAttribute("write") && xmlNode.getAttribute("write") == "true" ? true : false - }; - for (var k in properties) { - if (properties.hasOwnProperty(k)) { - extensionDefinition[k] = properties[k]; - } - } - } else if (xmlNode.nodeName == "uploader") { - var th = this._pydioObject.Parameters.get("theme"); - var clientForm = XMLUtils.XPathSelectSingleNode(xmlNode, "processing/clientForm[@theme=\"" + th + "\"]"); - if (!clientForm) { - clientForm = XMLUtils.XPathSelectSingleNode(xmlNode, "processing/clientForm"); - } - if (clientForm && clientForm.firstChild && clientForm.getAttribute("id")) { - extensionDefinition.formId = clientForm.getAttribute("id"); - this._pydioObject.UI.insertForm(clientForm.getAttribute("id"), clientForm.firstChild.nodeValue); - } - if (xmlNode.getAttribute("order")) { - extensionDefinition.order = parseInt(xmlNode.getAttribute("order")); - } else { - extensionDefinition.order = 0; - } - var extensionOnInit = XMLUtils.XPathSelectSingleNode(xmlNode, "processing/extensionOnInit"); - if (extensionOnInit && extensionOnInit.firstChild) { - try { - // @TODO: THIS WILL LIKELY TRIGGER PROTOTYPE CODE - eval(extensionOnInit.firstChild.nodeValue); - } catch (e) { - Logger.error("Ignoring Error in extensionOnInit code:"); - Logger.error(extensionOnInit.firstChild.nodeValue); - } - } - var dialogOnOpen = XMLUtils.XPathSelectSingleNode(xmlNode, "processing/dialogOnOpen"); - if (dialogOnOpen && dialogOnOpen.firstChild) { - extensionDefinition.dialogOnOpen = dialogOnOpen.firstChild.nodeValue; - } - var dialogOnComplete = XMLUtils.XPathSelectSingleNode(xmlNode, "processing/dialogOnComplete"); - if (dialogOnComplete && dialogOnComplete.firstChild) { - extensionDefinition.dialogOnComplete = dialogOnComplete.firstChild.nodeValue; - } + /** + * Translate the XML answer to a new User object + * @param skipEvent Boolean Whether to skip the sending of ajaxplorer:user_logged event. + */ + + Registry.prototype.logXmlUser = function logXmlUser(skipEvent) { + this._pydioObject.user = null; + var userNode; + if (this._registry) { + userNode = XMLUtils.XPathSelectSingleNode(this._registry, "user"); + } + if (userNode) { + var userId = userNode.getAttribute("id"); + var children = userNode.childNodes; + if (userId) { + this._pydioObject.user = new User(userId, children); } - return true; } - }, { - key: "refreshExtensionsRegistry", + if (!skipEvent) { + this._pydioObject.fire("user_logged", this._pydioObject.user); + } + }; + + Registry.prototype.getXML = function getXML() { + return this._registry; + }; + + /** + * Find Extension initialisation nodes (activeCondition, onInit, etc), parses + * the XML and execute JS. + * @param xmlNode DOMNode The extension node + * @param extensionDefinition Object Information already collected about this extension + * @returns Boolean + */ - /** - * Refresh the currently active extensions - * Extensions are editors and uploaders for the moment. - */ - value: function refreshExtensionsRegistry() { - this._extensionsRegistry = { editor: [], uploader: [] }; - var extensions = XMLUtils.XPathSelectNodes(this._registry, "plugins/editor|plugins/uploader"); - for (var i = 0; i < extensions.length; i++) { - var extensionDefinition = { - id: extensions[i].getAttribute("id"), - xmlNode: extensions[i], - resourcesManager: new ResourcesManager() - }; - this._resourcesRegistry[extensionDefinition.id] = extensionDefinition.resourcesManager; - var resourceNodes = XMLUtils.XPathSelectNodes(extensions[i], "client_settings/resources|dependencies|clientForm"); - for (var j = 0; j < resourceNodes.length; j++) { - var child = resourceNodes[j]; - extensionDefinition.resourcesManager.loadFromXmlNode(child); + Registry.prototype.initExtension = function initExtension(xmlNode, extensionDefinition) { + var activeCondition = XMLUtils.XPathSelectSingleNode(xmlNode, "processing/activeCondition"); + if (activeCondition && activeCondition.firstChild) { + try { + var func = new Function(activeCondition.firstChild.nodeValue.trim()); + if (func() === false) return false; + } catch (e) {} + } + if (xmlNode.nodeName == "editor") { + var properties = { + openable: xmlNode.getAttribute("openable") == "true", + modalOnly: xmlNode.getAttribute("modalOnly") == "true", + previewProvider: xmlNode.getAttribute("previewProvider") == "true", + order: xmlNode.getAttribute("order") ? parseInt(xmlNode.getAttribute("order")) : 0, + formId: xmlNode.getAttribute("formId") || null, + text: this._pydioObject.MessageHash[xmlNode.getAttribute("text")], + title: this._pydioObject.MessageHash[xmlNode.getAttribute("title")], + icon: xmlNode.getAttribute("icon"), + icon_class: xmlNode.getAttribute("iconClass"), + editorClass: xmlNode.getAttribute("className"), + mimes: xmlNode.getAttribute("mimes").split(","), + write: xmlNode.getAttribute("write") && xmlNode.getAttribute("write") == "true" ? true : false + }; + for (var k in properties) { + if (properties.hasOwnProperty(k)) { + extensionDefinition[k] = properties[k]; } - if (this.initExtension(extensions[i], extensionDefinition)) { - this._extensionsRegistry[extensions[i].nodeName].push(extensionDefinition); + } + } else if (xmlNode.nodeName == "uploader") { + var th = this._pydioObject.Parameters.get("theme"); + var clientForm = XMLUtils.XPathSelectSingleNode(xmlNode, "processing/clientForm[@theme=\"" + th + "\"]"); + if (!clientForm) { + clientForm = XMLUtils.XPathSelectSingleNode(xmlNode, "processing/clientForm"); + } + if (clientForm && clientForm.firstChild && clientForm.getAttribute("id")) { + extensionDefinition.formId = clientForm.getAttribute("id"); + this._pydioObject.UI.insertForm(clientForm.getAttribute("id"), clientForm.firstChild.nodeValue); + } + if (xmlNode.getAttribute("order")) { + extensionDefinition.order = parseInt(xmlNode.getAttribute("order")); + } else { + extensionDefinition.order = 0; + } + var extensionOnInit = XMLUtils.XPathSelectSingleNode(xmlNode, "processing/extensionOnInit"); + if (extensionOnInit && extensionOnInit.firstChild) { + try { + // @TODO: THIS WILL LIKELY TRIGGER PROTOTYPE CODE + eval(extensionOnInit.firstChild.nodeValue); + } catch (e) { + Logger.error("Ignoring Error in extensionOnInit code:"); + Logger.error(extensionOnInit.firstChild.nodeValue); } } - ResourcesManager.loadAutoLoadResources(this._registry); - } - }, { - key: "getActiveExtensionByType", - - /** - * Find the currently active extensions by type - * @param extensionType String "editor" or "uploader" - * @returns {array} - */ - value: function getActiveExtensionByType(extensionType) { - return this._extensionsRegistry[extensionType]; + var dialogOnOpen = XMLUtils.XPathSelectSingleNode(xmlNode, "processing/dialogOnOpen"); + if (dialogOnOpen && dialogOnOpen.firstChild) { + extensionDefinition.dialogOnOpen = dialogOnOpen.firstChild.nodeValue; + } + var dialogOnComplete = XMLUtils.XPathSelectSingleNode(xmlNode, "processing/dialogOnComplete"); + if (dialogOnComplete && dialogOnComplete.firstChild) { + extensionDefinition.dialogOnComplete = dialogOnComplete.firstChild.nodeValue; + } } - }, { - key: "findEditorById", + return true; + }; - /** - * Find a given editor by its id - * @param editorId String - * @returns AbstractEditor - */ - value: function findEditorById(editorId) { - return this._extensionsRegistry.editor.find(function (el) { - return el.id == editorId; - }); - } - }, { - key: "findEditorsForMime", + /** + * Refresh the currently active extensions + * Extensions are editors and uploaders for the moment. + */ - /** - * Find Editors that can handle a given mime type - * @param mime String - * @returns AbstractEditor[] - * @param restrictToPreviewProviders - */ - value: function findEditorsForMime(mime, restrictToPreviewProviders) { - var editors = []; - var checkWrite = false; - if (this.user != null && !this.user.canWrite()) { - checkWrite = true; + Registry.prototype.refreshExtensionsRegistry = function refreshExtensionsRegistry() { + this._extensionsRegistry = { editor: [], uploader: [] }; + var extensions = XMLUtils.XPathSelectNodes(this._registry, "plugins/editor|plugins/uploader"); + for (var i = 0; i < extensions.length; i++) { + var extensionDefinition = { + id: extensions[i].getAttribute("id"), + xmlNode: extensions[i], + resourcesManager: new ResourcesManager() + }; + this._resourcesRegistry[extensionDefinition.id] = extensionDefinition.resourcesManager; + var resourceNodes = XMLUtils.XPathSelectNodes(extensions[i], "client_settings/resources|dependencies|clientForm"); + for (var j = 0; j < resourceNodes.length; j++) { + var child = resourceNodes[j]; + extensionDefinition.resourcesManager.loadFromXmlNode(child); } - this._extensionsRegistry.editor.forEach(function (el) { - if (el.mimes.indexOf(mime) !== -1 || el.mimes.indexOf("*") !== -1) { - if (restrictToPreviewProviders && !el.previewProvider) return; - if (!checkWrite || !el.write) editors.push(el); - } - }); - if (editors.length && editors.length > 1) { - editors = editors.sort(function (a, b) { - return (a.order || 0) - (b.order || 0); - }); + if (this.initExtension(extensions[i], extensionDefinition)) { + this._extensionsRegistry[extensions[i].nodeName].push(extensionDefinition); } - return editors; } - }, { - key: "loadEditorResources", + ResourcesManager.loadAutoLoadResources(this._registry); + }; - /** - * Trigger the load method of the resourcesManager. - * @param resourcesManager ResourcesManager - */ - value: function loadEditorResources(resourcesManager) { - resourcesManager.load(this._resourcesRegistry); - } - }, { - key: "getPluginConfigs", + /** + * Find the currently active extensions by type + * @param extensionType String "editor" or "uploader" + * @returns {array} + */ - /** - * - * @param pluginQuery - * @returns {Map} - */ - value: function getPluginConfigs(pluginQuery) { - var xpath = "plugins/*[@id=\"core." + pluginQuery + "\"]/plugin_configs/property | plugins/*[@id=\"" + pluginQuery + "\"]/plugin_configs/property"; - if (pluginQuery.indexOf(".") == -1) { - xpath = "plugins/" + pluginQuery + "/plugin_configs/property |" + xpath; + Registry.prototype.getActiveExtensionByType = function getActiveExtensionByType(extensionType) { + return this._extensionsRegistry[extensionType]; + }; + + /** + * Find a given editor by its id + * @param editorId String + * @returns AbstractEditor + */ + + Registry.prototype.findEditorById = function findEditorById(editorId) { + return this._extensionsRegistry.editor.find(function (el) { + return el.id == editorId; + }); + }; + + /** + * Find Editors that can handle a given mime type + * @param mime String + * @returns AbstractEditor[] + * @param restrictToPreviewProviders + */ + + Registry.prototype.findEditorsForMime = function findEditorsForMime(mime, restrictToPreviewProviders) { + var editors = []; + var checkWrite = false; + if (this.user != null && !this.user.canWrite()) { + checkWrite = true; + } + this._extensionsRegistry.editor.forEach(function (el) { + if (el.mimes.indexOf(mime) !== -1 || el.mimes.indexOf("*") !== -1) { + if (restrictToPreviewProviders && !el.previewProvider) return; + if (!checkWrite || !el.write) editors.push(el); } - var properties = XMLUtils.XPathSelectNodes(this._registry, xpath); - var configs = new Map(); - properties.forEach(function (propNode) { - configs.set(propNode.getAttribute("name"), JSON.parse(propNode.firstChild.nodeValue)); + }); + if (editors.length && editors.length > 1) { + editors = editors.sort(function (a, b) { + return (a.order || 0) - (b.order || 0); }); - return configs; } - }, { - key: "getDefaultImageFromParameters", + return editors; + }; + + /** + * Trigger the load method of the resourcesManager. + * @param resourcesManager ResourcesManager + */ + + Registry.prototype.loadEditorResources = function loadEditorResources(resourcesManager) { + resourcesManager.load(this._resourcesRegistry); + }; - /** - * - * @param pluginId - * @param paramName - * @returns {string} - */ - value: function getDefaultImageFromParameters(pluginId, paramName) { - var node = XMLUtils.XPathSelectSingleNode(this._registry, "plugins/*[@id='" + pluginId + "']/server_settings/global_param[@name='" + paramName + "']"); - if (!node) { - return ""; - }return node.getAttribute("defaultImage") || ""; + /** + * + * @param pluginQuery + * @returns {Map} + */ + + Registry.prototype.getPluginConfigs = function getPluginConfigs(pluginQuery) { + var xpath = "plugins/*[@id=\"core." + pluginQuery + "\"]/plugin_configs/property | plugins/*[@id=\"" + pluginQuery + "\"]/plugin_configs/property"; + if (pluginQuery.indexOf(".") == -1) { + xpath = "plugins/" + pluginQuery + "/plugin_configs/property |" + xpath; } - }, { - key: "hasPluginOfType", + var properties = XMLUtils.XPathSelectNodes(this._registry, xpath); + var configs = new Map(); + properties.forEach(function (propNode) { + configs.set(propNode.getAttribute("name"), JSON.parse(propNode.firstChild.nodeValue)); + }); + return configs; + }; - /** - * - * @param type - * @param name - * @returns {bool} - */ - value: function hasPluginOfType(type, name) { - var node; - if (name == null) { - node = XMLUtils.XPathSelectSingleNode(this._registry, "plugins/ajxp_plugin[contains(@id, \"" + type + ".\")] | plugins/" + type + "[@id]"); - } else { - node = XMLUtils.XPathSelectSingleNode(this._registry, "plugins/ajxp_plugin[@id=\"" + type + "." + name + "\"] | plugins/" + type + "[@id=\"" + type + "." + name + "\"]"); - } - return node != undefined; + /** + * + * @param pluginId + * @param paramName + * @returns {string} + */ + + Registry.prototype.getDefaultImageFromParameters = function getDefaultImageFromParameters(pluginId, paramName) { + var node = XMLUtils.XPathSelectSingleNode(this._registry, "plugins/*[@id='" + pluginId + "']/server_settings/global_param[@name='" + paramName + "']"); + if (!node) { + return ""; + }return node.getAttribute("defaultImage") || ""; + }; + + /** + * + * @param type + * @param name + * @returns {bool} + */ + + Registry.prototype.hasPluginOfType = function hasPluginOfType(type, name) { + var node; + if (name == null) { + node = XMLUtils.XPathSelectSingleNode(this._registry, "plugins/ajxp_plugin[contains(@id, \"" + type + ".\")] | plugins/" + type + "[@id]"); + } else { + node = XMLUtils.XPathSelectSingleNode(this._registry, "plugins/ajxp_plugin[@id=\"" + type + "." + name + "\"] | plugins/" + type + "[@id=\"" + type + "." + name + "\"]"); } - }]); + return node != undefined; + }; return Registry; })(); \ No newline at end of file diff --git a/core/src/plugins/gui.ajax/res/js/core/model/RemoteNodeProvider.js b/core/src/plugins/gui.ajax/res/js/core/model/RemoteNodeProvider.js index e44fa79c92..5b9c7d8ebb 100644 --- a/core/src/plugins/gui.ajax/res/js/core/model/RemoteNodeProvider.js +++ b/core/src/plugins/gui.ajax/res/js/core/model/RemoteNodeProvider.js @@ -2,8 +2,6 @@ var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; -var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - /* * Copyright 2007-2013 Charles du Jeu - Abstrium SAS * This file is part of Pydio. @@ -41,267 +39,258 @@ var RemoteNodeProvider = (function () { this.discrete = false; } - _createClass(RemoteNodeProvider, [{ - key: 'initProvider', + /** + * Initialize properties + * @param properties Object + */ - /** - * Initialize properties - * @param properties Object - */ - value: function initProvider(properties) { - this.properties = new Map(); - for (var p in properties) { - if (properties.hasOwnProperty(p)) this.properties.set(p, properties[p]); - } - if (this.properties && this.properties.has('connexion_discrete')) { - this.discrete = true; - this.properties['delete']('connexion_discrete'); - } + RemoteNodeProvider.prototype.initProvider = function initProvider(properties) { + this.properties = new Map(); + for (var p in properties) { + if (properties.hasOwnProperty(p)) this.properties.set(p, properties[p]); } - }, { - key: 'loadNode', - - /** - * Load a node - * @param node AjxpNode - * @param nodeCallback Function On node loaded - * @param childCallback Function On child added - * @param recursive - * @param depth - */ - value: function loadNode(node) { - var nodeCallback = arguments[1] === undefined ? null : arguments[1]; - var childCallback = arguments[2] === undefined ? null : arguments[2]; - var recursive = arguments[3] === undefined ? false : arguments[3]; - var depth = arguments[4] === undefined ? -1 : arguments[4]; - - var params = { - get_action: 'ls', - options: 'al' - }; - if (recursive) { - params.recursive = true; - params.depth = depth; - } - //if(this.discrete) conn.discrete = true; - var path = node.getPath(); - // Double encode # character - var paginationHash; - if (node.getMetadata().has('paginationData')) { - paginationHash = '%23' + node.getMetadata().get('paginationData').get('current'); - path += paginationHash; - params.remote_order = 'true'; - if (node.getMetadata().get('remote_order')) { - node.getMetadata().get('remote_order').forEach(function (value, key) { - params[key] = value; - }); - } - } - params.dir = path; - if (this.properties) { - this.properties.forEach(function (value, key) { - params[key] = value + (key == 'dir' && paginationHash ? paginationHash : ''); - }); - } - var complete = (function (transport) { - this.parseNodes(node, transport, nodeCallback, childCallback); - }).bind(this); - PydioApi.getClient().request(params, complete); + if (this.properties && this.properties.has('connexion_discrete')) { + this.discrete = true; + this.properties['delete']('connexion_discrete'); } - }, { - key: 'loadLeafNodeSync', + }; + + /** + * Load a node + * @param node AjxpNode + * @param nodeCallback Function On node loaded + * @param childCallback Function On child added + * @param recursive + * @param depth + */ - /** - * Load a node - * @param node AjxpNode - * @param nodeCallback Function On node loaded - * @param aSync bool - */ - value: function loadLeafNodeSync(node, nodeCallback) { - var aSync = arguments[2] === undefined ? false : arguments[2]; + RemoteNodeProvider.prototype.loadNode = function loadNode(node) { + var nodeCallback = arguments[1] === undefined ? null : arguments[1]; + var childCallback = arguments[2] === undefined ? null : arguments[2]; + var recursive = arguments[3] === undefined ? false : arguments[3]; + var depth = arguments[4] === undefined ? -1 : arguments[4]; - var params = { - get_action: 'ls', - options: 'al', - dir: PathUtils.getDirname(node.getPath()), - file: PathUtils.getBasename(node.getPath()) - }; - if (this.properties) { - this.properties.forEach(function (value, key) { + var params = { + get_action: 'ls', + options: 'al' + }; + if (recursive) { + params.recursive = true; + params.depth = depth; + } + //if(this.discrete) conn.discrete = true; + var path = node.getPath(); + // Double encode # character + var paginationHash; + if (node.getMetadata().has('paginationData')) { + paginationHash = '%23' + node.getMetadata().get('paginationData').get('current'); + path += paginationHash; + params.remote_order = 'true'; + if (node.getMetadata().get('remote_order')) { + node.getMetadata().get('remote_order').forEach(function (value, key) { params[key] = value; }); } - var complete = (function (transport) { - try { - if (node.isRoot()) { - this.parseNodes(node, transport, nodeCallback, null, true); - } else { - this.parseNodes(node, transport, null, nodeCallback, true); - } - } catch (e) { - Logger.error('Loading error :' + e.message); - } - }).bind(this); - PydioApi.getClient().request(params, complete, null, { async: aSync }); } - }, { - key: 'refreshNodeAndReplace', - value: function refreshNodeAndReplace(node, onComplete) { + params.dir = path; + if (this.properties) { + this.properties.forEach(function (value, key) { + params[key] = value + (key == 'dir' && paginationHash ? paginationHash : ''); + }); + } + var complete = (function (transport) { + this.parseNodes(node, transport, nodeCallback, childCallback); + }).bind(this); + PydioApi.getClient().request(params, complete); + }; - var params = { - get_action: 'ls', - options: 'al', - dir: PathUtils.getDirname(node.getPath()), - file: PathUtils.getBasename(node.getPath()) - }; - if (this.properties) { - this.properties.forEach(function (value, key) { - params[key] = value; - }); - } + /** + * Load a node + * @param node AjxpNode + * @param nodeCallback Function On node loaded + * @param aSync bool + */ - var nodeCallback = function nodeCallback(newNode) { - node.replaceBy(newNode, 'override'); - if (onComplete) onComplete(node); - }; - PydioApi.getClient().request(params, (function (transport) { - try { - if (node.isRoot()) { - this.parseNodes(node, transport, nodeCallback, null, true); - } else { - this.parseNodes(node, transport, null, nodeCallback, true); - } - } catch (e) { - Logger.error(e); - } - }).bind(this)); - } - }, { - key: 'parseNodes', + RemoteNodeProvider.prototype.loadLeafNodeSync = function loadLeafNodeSync(node, nodeCallback) { + var aSync = arguments[2] === undefined ? false : arguments[2]; - /** - * Parse the answer and create AjxpNodes - * @param origNode AjxpNode - * @param transport Ajax.Response - * @param nodeCallback Function - * @param childCallback Function - * @param childrenOnly - */ - value: function parseNodes(origNode, transport, nodeCallback, childCallback, childrenOnly) { - if (!transport.responseXML || !transport.responseXML.documentElement) { - if (!transport.responseText) { - throw new Error('Empty response!'); + var params = { + get_action: 'ls', + options: 'al', + dir: PathUtils.getDirname(node.getPath()), + file: PathUtils.getBasename(node.getPath()) + }; + if (this.properties) { + this.properties.forEach(function (value, key) { + params[key] = value; + }); + } + var complete = (function (transport) { + try { + if (node.isRoot()) { + this.parseNodes(node, transport, nodeCallback, null, true); + } else { + this.parseNodes(node, transport, null, nodeCallback, true); } - Logger.debug(transport.responseText); - if (nodeCallback) nodeCallback(origNode); - origNode.setLoaded(false); - throw new Error('Invalid XML Document (see console)'); - } - var rootNode = transport.responseXML.documentElement; - if (!childrenOnly) { - var contextNode = this.parseAjxpNode(rootNode); - origNode.replaceBy(contextNode, 'merge'); + } catch (e) { + Logger.error('Loading error :' + e.message); } + }).bind(this); + PydioApi.getClient().request(params, complete, null, { async: aSync }); + }; - // CHECK FOR MESSAGE OR ERRORS - var errorNode = XMLUtils.XPathSelectSingleNode(rootNode, 'error|message'); - if (errorNode) { - var type; - if (errorNode.nodeName == 'message') type = errorNode.getAttribute('type'); - if (type == 'ERROR') { - origNode.notify('error', errorNode.firstChild.nodeValue + '(Source:' + origNode.getPath() + ')'); + RemoteNodeProvider.prototype.refreshNodeAndReplace = function refreshNodeAndReplace(node, onComplete) { + + var params = { + get_action: 'ls', + options: 'al', + dir: PathUtils.getDirname(node.getPath()), + file: PathUtils.getBasename(node.getPath()) + }; + if (this.properties) { + this.properties.forEach(function (value, key) { + params[key] = value; + }); + } + + var nodeCallback = function nodeCallback(newNode) { + node.replaceBy(newNode, 'override'); + if (onComplete) onComplete(node); + }; + PydioApi.getClient().request(params, (function (transport) { + try { + if (node.isRoot()) { + this.parseNodes(node, transport, nodeCallback, null, true); + } else { + this.parseNodes(node, transport, null, nodeCallback, true); } + } catch (e) { + Logger.error(e); } + }).bind(this)); + }; - // CHECK FOR PAGINATION DATA - var paginationNode = XMLUtils.XPathSelectSingleNode(rootNode, 'pagination'); - if (paginationNode) { - var paginationData = new Map(); - Array.from(paginationNode.attributes).forEach((function (att) { - paginationData.set(att.nodeName, att.value); - }).bind(this)); - origNode.getMetadata().set('paginationData', paginationData); - } else if (origNode.getMetadata().get('paginationData')) { - origNode.getMetadata()['delete']('paginationData'); + /** + * Parse the answer and create AjxpNodes + * @param origNode AjxpNode + * @param transport Ajax.Response + * @param nodeCallback Function + * @param childCallback Function + * @param childrenOnly + */ + + RemoteNodeProvider.prototype.parseNodes = function parseNodes(origNode, transport, nodeCallback, childCallback, childrenOnly) { + if (!transport.responseXML || !transport.responseXML.documentElement) { + if (!transport.responseText) { + throw new Error('Empty response!'); } + Logger.debug(transport.responseText); + if (nodeCallback) nodeCallback(origNode); + origNode.setLoaded(false); + throw new Error('Invalid XML Document (see console)'); + } + var rootNode = transport.responseXML.documentElement; + if (!childrenOnly) { + var contextNode = this.parseAjxpNode(rootNode); + origNode.replaceBy(contextNode, 'merge'); + } - // CHECK FOR COMPONENT CONFIGS CONTEXTUAL DATA - var configs = XMLUtils.XPathSelectSingleNode(rootNode, 'client_configs'); - if (configs) { - origNode.getMetadata().set('client_configs', configs); + // CHECK FOR MESSAGE OR ERRORS + var errorNode = XMLUtils.XPathSelectSingleNode(rootNode, 'error|message'); + if (errorNode) { + var type; + if (errorNode.nodeName == 'message') type = errorNode.getAttribute('type'); + if (type == 'ERROR') { + origNode.notify('error', errorNode.firstChild.nodeValue + '(Source:' + origNode.getPath() + ')'); } + } - // NOW PARSE CHILDREN - var children = XMLUtils.XPathSelectNodes(rootNode, 'tree'); - children.forEach((function (childNode) { - var child = this.parseAjxpNode(childNode); - if (!childrenOnly) origNode.addChild(child); - var cLoaded; - if (XMLUtils.XPathSelectNodes(childNode, 'tree').length) { - XMLUtils.XPathSelectNodes(childNode, 'tree').forEach((function (c) { - var newChild = this.parseAjxpNode(c); - if (newChild) { - child.addChild(newChild); - } - }).bind(this)); - cLoaded = true; - } - if (childCallback) { - childCallback(child); - } - if (cLoaded) child.setLoaded(true); + // CHECK FOR PAGINATION DATA + var paginationNode = XMLUtils.XPathSelectSingleNode(rootNode, 'pagination'); + if (paginationNode) { + var paginationData = new Map(); + Array.from(paginationNode.attributes).forEach((function (att) { + paginationData.set(att.nodeName, att.value); }).bind(this)); + origNode.getMetadata().set('paginationData', paginationData); + } else if (origNode.getMetadata().get('paginationData')) { + origNode.getMetadata()['delete']('paginationData'); + } - if (nodeCallback) { - nodeCallback(origNode); - } + // CHECK FOR COMPONENT CONFIGS CONTEXTUAL DATA + var configs = XMLUtils.XPathSelectSingleNode(rootNode, 'client_configs'); + if (configs) { + origNode.getMetadata().set('client_configs', configs); } - }, { - key: 'parseAjxpNodesDiffs', - value: function parseAjxpNodesDiffs(xmlElement, targetDataModel) { - var setContextChildrenSelected = arguments[2] === undefined ? false : arguments[2]; - var removes = XMLUtils.XPathSelectNodes(xmlElement, 'remove/tree'); - var adds = XMLUtils.XPathSelectNodes(xmlElement, 'add/tree'); - var updates = XMLUtils.XPathSelectNodes(xmlElement, 'update/tree'); - // TODO: MOVE TO DATAMODEL - if (removes && removes.length) { - removes.forEach(function (r) { - var p = r.getAttribute('filename'); - targetDataModel.removeNodeByPath(p); - }); - } - if (adds && adds.length && targetDataModel.getAjxpNodeProvider().parseAjxpNode) { - adds.forEach(function (tree) { - var newNode = targetDataModel.getAjxpNodeProvider().parseAjxpNode(tree); - targetDataModel.addNode(newNode, setContextChildrenSelected); - }); + // NOW PARSE CHILDREN + var children = XMLUtils.XPathSelectNodes(rootNode, 'tree'); + children.forEach((function (childNode) { + var child = this.parseAjxpNode(childNode); + if (!childrenOnly) origNode.addChild(child); + var cLoaded; + if (XMLUtils.XPathSelectNodes(childNode, 'tree').length) { + XMLUtils.XPathSelectNodes(childNode, 'tree').forEach((function (c) { + var newChild = this.parseAjxpNode(c); + if (newChild) { + child.addChild(newChild); + } + }).bind(this)); + cLoaded = true; } - if (updates && updates.length && targetDataModel.getAjxpNodeProvider().parseAjxpNode) { - updates.forEach(function (tree) { - var newNode = targetDataModel.getAjxpNodeProvider().parseAjxpNode(tree); - targetDataModel.updateNode(newNode, setContextChildrenSelected); - }); + if (childCallback) { + childCallback(child); } + if (cLoaded) child.setLoaded(true); + }).bind(this)); + + if (nodeCallback) { + nodeCallback(origNode); } - }, { - key: 'parseAjxpNode', + }; - /** - * Parses XML Node and create AjxpNode - * @param xmlNode XMLNode - * @returns AjxpNode - */ - value: function parseAjxpNode(xmlNode) { - var node = new AjxpNode(xmlNode.getAttribute('filename'), xmlNode.getAttribute('is_file') == '1' || xmlNode.getAttribute('is_file') == 'true', xmlNode.getAttribute('text'), xmlNode.getAttribute('icon')); - var metadata = new Map(); - for (var i = 0; i < xmlNode.attributes.length; i++) { - metadata.set(xmlNode.attributes[i].nodeName, xmlNode.attributes[i].value); - } - node.setMetadata(metadata); - return node; + RemoteNodeProvider.prototype.parseAjxpNodesDiffs = function parseAjxpNodesDiffs(xmlElement, targetDataModel) { + var setContextChildrenSelected = arguments[2] === undefined ? false : arguments[2]; + + var removes = XMLUtils.XPathSelectNodes(xmlElement, 'remove/tree'); + var adds = XMLUtils.XPathSelectNodes(xmlElement, 'add/tree'); + var updates = XMLUtils.XPathSelectNodes(xmlElement, 'update/tree'); + // TODO: MOVE TO DATAMODEL + if (removes && removes.length) { + removes.forEach(function (r) { + var p = r.getAttribute('filename'); + targetDataModel.removeNodeByPath(p); + }); + } + if (adds && adds.length && targetDataModel.getAjxpNodeProvider().parseAjxpNode) { + adds.forEach(function (tree) { + var newNode = targetDataModel.getAjxpNodeProvider().parseAjxpNode(tree); + targetDataModel.addNode(newNode, setContextChildrenSelected); + }); + } + if (updates && updates.length && targetDataModel.getAjxpNodeProvider().parseAjxpNode) { + updates.forEach(function (tree) { + var newNode = targetDataModel.getAjxpNodeProvider().parseAjxpNode(tree); + targetDataModel.updateNode(newNode, setContextChildrenSelected); + }); + } + }; + + /** + * Parses XML Node and create AjxpNode + * @param xmlNode XMLNode + * @returns AjxpNode + */ + + RemoteNodeProvider.prototype.parseAjxpNode = function parseAjxpNode(xmlNode) { + var node = new AjxpNode(xmlNode.getAttribute('filename'), xmlNode.getAttribute('is_file') == '1' || xmlNode.getAttribute('is_file') == 'true', xmlNode.getAttribute('text'), xmlNode.getAttribute('icon')); + var metadata = new Map(); + for (var i = 0; i < xmlNode.attributes.length; i++) { + metadata.set(xmlNode.attributes[i].nodeName, xmlNode.attributes[i].value); } - }]); + node.setMetadata(metadata); + return node; + }; return RemoteNodeProvider; })(); \ No newline at end of file diff --git a/core/src/plugins/gui.ajax/res/js/core/model/Repository.js b/core/src/plugins/gui.ajax/res/js/core/model/Repository.js index da6ee3f5fd..c5ca8e9389 100644 --- a/core/src/plugins/gui.ajax/res/js/core/model/Repository.js +++ b/core/src/plugins/gui.ajax/res/js/core/model/Repository.js @@ -2,8 +2,6 @@ var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; -var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - /* * Copyright 2007-2013 Charles du Jeu - Abstrium SAS * This file is part of Pydio. @@ -55,190 +53,172 @@ var Repository = (function () { if (xmlDef) this.loadFromXml(xmlDef); } - _createClass(Repository, [{ - key: 'getId', + /** + * @returns String + */ - /** - * @returns String - */ - value: function getId() { - return this.id; - } - }, { - key: 'getLabel', - - /** - * @returns String - */ - value: function getLabel() { - return this.label; - } - }, { - key: 'setLabel', - - /** - * @param label String - */ - value: function setLabel(label) { - this.label = label; - } - }, { - key: 'getHtmlBadge', - value: function getHtmlBadge() { - if (!this.label) { - return ''; - }if (!this.badge) { - var letters = this.label.split(' ').map(function (word) { - return word.substr(0, 1); - }).join(''); - this.badge = '' + letters + ''; - } - return this.badge; - } - }, { - key: 'getDescription', - - /** - * @return String - */ - value: function getDescription() { - return this.description; - } - }, { - key: 'getIcon', - - /** - * @returns String - */ - value: function getIcon() { - return this.icon; - } - }, { - key: 'setIcon', - - /** - * @param icon String - */ - value: function setIcon(icon) { - this.icon = icon; - } - }, { - key: 'getOwner', - - /** - * @return String - */ - value: function getOwner() { - return this.owner; - } - }, { - key: 'getAccessType', - - /** - * @returns String - */ - value: function getAccessType() { - return this.accessType; - } - }, { - key: 'setAccessType', - - /** - * @param access String - */ - value: function setAccessType(access) { - this.accessType = access; - } - }, { - key: 'loadResources', - - /** - * Triggers ResourcesManager.load - */ - value: function loadResources() { - this.resourcesManager.load(null, true); - } - }, { - key: 'getNodeProviderDef', - - /** - * @returns Object - */ - value: function getNodeProviderDef() { - return this.nodeProviderDef; - } - }, { - key: 'setSlug', - - /** - * @param slug String - */ - value: function setSlug(slug) { - this.slug = slug; - } - }, { - key: 'getSlug', - - /** - * @returns String - */ - value: function getSlug() { - return this.slug; - } - }, { - key: 'getOverlay', - value: function getOverlay() { - return this.getOwner() ? resolveImageSource('shared.png', '/images/overlays/ICON_SIZE', 8) : ''; + Repository.prototype.getId = function getId() { + return this.id; + }; + + /** + * @returns String + */ + + Repository.prototype.getLabel = function getLabel() { + return this.label; + }; + + /** + * @param label String + */ + + Repository.prototype.setLabel = function setLabel(label) { + this.label = label; + }; + + Repository.prototype.getHtmlBadge = function getHtmlBadge() { + if (!this.label) { + return ''; + }if (!this.badge) { + var letters = this.label.split(' ').map(function (word) { + return word.substr(0, 1); + }).join(''); + this.badge = '' + letters + ''; } - }, { - key: 'loadFromXml', - - /** - * Parses XML Node - * @param repoNode XMLNode - */ - value: function loadFromXml(repoNode) { - if (repoNode.getAttribute('allowCrossRepositoryCopy') && repoNode.getAttribute('allowCrossRepositoryCopy') == 'true') { - this.allowCrossRepositoryCopy = true; - } - if (repoNode.getAttribute('user_editable_repository') && repoNode.getAttribute('user_editable_repository') == 'true') { - this.userEditable = true; - } - if (repoNode.getAttribute('access_type')) { - this.setAccessType(repoNode.getAttribute('access_type')); - } - if (repoNode.getAttribute('repositorySlug')) { - this.setSlug(repoNode.getAttribute('repositorySlug')); - } - if (repoNode.getAttribute('owner')) { - this.owner = repoNode.getAttribute('owner'); - } - for (var i = 0; i < repoNode.childNodes.length; i++) { - var childNode = repoNode.childNodes[i]; - if (childNode.nodeName == 'label') { - this.setLabel(childNode.firstChild.nodeValue); - } else if (childNode.nodeName == 'description') { - this.description = childNode.firstChild.nodeValue; - } else if (childNode.nodeName == 'client_settings') { - if (childNode.getAttribute('icon_tpl_id')) { - this.setIcon(window.ajxpServerAccessPath + '&get_action=get_user_template_logo&template_id=' + childNode.getAttribute('icon_tpl_id') + '&icon_format=small'); - } else { - this.setIcon(childNode.getAttribute('icon')); - } - for (var j = 0; j < childNode.childNodes.length; j++) { - var subCh = childNode.childNodes[j]; - if (subCh.nodeName == 'resources') { - this.resourcesManager.loadFromXmlNode(subCh); - } else if (subCh.nodeName == 'node_provider') { - var nodeProviderName = subCh.getAttribute('ajxpClass'); - var nodeProviderOptions = JSON.parse(subCh.getAttribute('ajxpOptions')); - this.nodeProviderDef = { name: nodeProviderName, options: nodeProviderOptions }; - } + return this.badge; + }; + + /** + * @return String + */ + + Repository.prototype.getDescription = function getDescription() { + return this.description; + }; + + /** + * @returns String + */ + + Repository.prototype.getIcon = function getIcon() { + return this.icon; + }; + + /** + * @param icon String + */ + + Repository.prototype.setIcon = function setIcon(icon) { + this.icon = icon; + }; + + /** + * @return String + */ + + Repository.prototype.getOwner = function getOwner() { + return this.owner; + }; + + /** + * @returns String + */ + + Repository.prototype.getAccessType = function getAccessType() { + return this.accessType; + }; + + /** + * @param access String + */ + + Repository.prototype.setAccessType = function setAccessType(access) { + this.accessType = access; + }; + + /** + * Triggers ResourcesManager.load + */ + + Repository.prototype.loadResources = function loadResources() { + this.resourcesManager.load(null, true); + }; + + /** + * @returns Object + */ + + Repository.prototype.getNodeProviderDef = function getNodeProviderDef() { + return this.nodeProviderDef; + }; + + /** + * @param slug String + */ + + Repository.prototype.setSlug = function setSlug(slug) { + this.slug = slug; + }; + + /** + * @returns String + */ + + Repository.prototype.getSlug = function getSlug() { + return this.slug; + }; + + Repository.prototype.getOverlay = function getOverlay() { + return this.getOwner() ? resolveImageSource('shared.png', '/images/overlays/ICON_SIZE', 8) : ''; + }; + + /** + * Parses XML Node + * @param repoNode XMLNode + */ + + Repository.prototype.loadFromXml = function loadFromXml(repoNode) { + if (repoNode.getAttribute('allowCrossRepositoryCopy') && repoNode.getAttribute('allowCrossRepositoryCopy') == 'true') { + this.allowCrossRepositoryCopy = true; + } + if (repoNode.getAttribute('user_editable_repository') && repoNode.getAttribute('user_editable_repository') == 'true') { + this.userEditable = true; + } + if (repoNode.getAttribute('access_type')) { + this.setAccessType(repoNode.getAttribute('access_type')); + } + if (repoNode.getAttribute('repositorySlug')) { + this.setSlug(repoNode.getAttribute('repositorySlug')); + } + if (repoNode.getAttribute('owner')) { + this.owner = repoNode.getAttribute('owner'); + } + for (var i = 0; i < repoNode.childNodes.length; i++) { + var childNode = repoNode.childNodes[i]; + if (childNode.nodeName == 'label') { + this.setLabel(childNode.firstChild.nodeValue); + } else if (childNode.nodeName == 'description') { + this.description = childNode.firstChild.nodeValue; + } else if (childNode.nodeName == 'client_settings') { + if (childNode.getAttribute('icon_tpl_id')) { + this.setIcon(window.ajxpServerAccessPath + '&get_action=get_user_template_logo&template_id=' + childNode.getAttribute('icon_tpl_id') + '&icon_format=small'); + } else { + this.setIcon(childNode.getAttribute('icon')); + } + for (var j = 0; j < childNode.childNodes.length; j++) { + var subCh = childNode.childNodes[j]; + if (subCh.nodeName == 'resources') { + this.resourcesManager.loadFromXmlNode(subCh); + } else if (subCh.nodeName == 'node_provider') { + var nodeProviderName = subCh.getAttribute('ajxpClass'); + var nodeProviderOptions = JSON.parse(subCh.getAttribute('ajxpOptions')); + this.nodeProviderDef = { name: nodeProviderName, options: nodeProviderOptions }; } } } } - }]); + }; return Repository; })(); \ No newline at end of file diff --git a/core/src/plugins/gui.ajax/res/js/core/model/User.js b/core/src/plugins/gui.ajax/res/js/core/model/User.js index 104a7b793b..060a760bf0 100644 --- a/core/src/plugins/gui.ajax/res/js/core/model/User.js +++ b/core/src/plugins/gui.ajax/res/js/core/model/User.js @@ -2,8 +2,6 @@ var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; -var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - /* * Copyright 2007-2013 Charles du Jeu - Abstrium SAS * This file is part of Pydio. @@ -98,293 +96,275 @@ var User = (function () { if (xmlDef) this.loadFromXml(xmlDef); } - _createClass(User, [{ - key: "setActiveRepository", + /** + * Set current repository + * @param id String + * @param read Boolean + * @param write Boolean + */ - /** - * Set current repository - * @param id String - * @param read Boolean - * @param write Boolean - */ - value: function setActiveRepository(id, read, write) { - this.activeRepository = id; - this.read = read == "1"; - this.write = write == "1"; - if (this.repositories.has(id)) { - this.crossRepositoryCopy = this.repositories.get(id).allowCrossRepositoryCopy; - } - if (this.crossRepositories.has(id)) { - this.crossRepositories["delete"](id); - } + User.prototype.setActiveRepository = function setActiveRepository(id, read, write) { + this.activeRepository = id; + this.read = read == "1"; + this.write = write == "1"; + if (this.repositories.has(id)) { + this.crossRepositoryCopy = this.repositories.get(id).allowCrossRepositoryCopy; } - }, { - key: "getActiveRepository", - - /** - * Gets the current active repository - * @returns String - */ - value: function getActiveRepository() { - return this.activeRepository; + if (this.crossRepositories.has(id)) { + this.crossRepositories["delete"](id); } - }, { - key: "canRead", + }; - /** - * Whether current repo is allowed to be read - * @returns Boolean - */ - value: function canRead() { - return this.read; - } - }, { - key: "canWrite", + /** + * Gets the current active repository + * @returns String + */ - /** - * Whether current repo is allowed to be written - * @returns Boolean - */ - value: function canWrite() { - return this.write; - } - }, { - key: "canCrossRepositoryCopy", + User.prototype.getActiveRepository = function getActiveRepository() { + return this.activeRepository; + }; - /** - * Whether current repo is allowed to be cross-copied - * @returns Boolean - */ - value: function canCrossRepositoryCopy() { - return this.crossRepositoryCopy; - } - }, { - key: "getPreference", + /** + * Whether current repo is allowed to be read + * @returns Boolean + */ - /** - * Get a user preference by its name - * @returns Mixed - */ - value: function getPreference(prefName, fromJSON) { - if (fromJSON) { - var test = this._parsedJSONCache.get(prefName); - if (test !== undefined) { - return test; - } + User.prototype.canRead = function canRead() { + return this.read; + }; + + /** + * Whether current repo is allowed to be written + * @returns Boolean + */ + + User.prototype.canWrite = function canWrite() { + return this.write; + }; + + /** + * Whether current repo is allowed to be cross-copied + * @returns Boolean + */ + + User.prototype.canCrossRepositoryCopy = function canCrossRepositoryCopy() { + return this.crossRepositoryCopy; + }; + + /** + * Get a user preference by its name + * @returns Mixed + */ + + User.prototype.getPreference = function getPreference(prefName, fromJSON) { + if (fromJSON) { + var test = this._parsedJSONCache.get(prefName); + if (test !== undefined) { + return test; } - var value = this.preferences.get(prefName); - if (fromJSON && value) { - try { - if (typeof value == "object") return value; - var parsed = JSON.parse(value); - this._parsedJSONCache.set(prefName, parsed); - return parsed; - } catch (e) { - if (console) { - console.log("Error parsing JSON in preferences (" + prefName + "). You should contact system admin and clear user preferences."); - } else { - alert("Error parsing JSON in preferences. You should contact system admin and clear user preferences."); - } + } + var value = this.preferences.get(prefName); + if (fromJSON && value) { + try { + if (typeof value == "object") return value; + var parsed = JSON.parse(value); + this._parsedJSONCache.set(prefName, parsed); + return parsed; + } catch (e) { + if (window.console) { + Logger.log("Error parsing JSON in preferences (" + prefName + "). You should contact system admin and clear user preferences."); + } else { + alert("Error parsing JSON in preferences. You should contact system admin and clear user preferences."); } } - return value; } - }, { - key: "getRepositoriesList", + return value; + }; - /** - * Get all repositories - * @returns Map - */ - value: function getRepositoriesList() { - return this.repositories; - } - }, { - key: "setPreference", + /** + * Get all repositories + * @returns Map + */ - /** - * Set a preference value - * @param prefName String - * @param prefValue Mixed - * @param toJSON Boolean Whether to convert the value to JSON representation - */ - value: function setPreference(prefName, prefValue) { - var toJSON = arguments[2] === undefined ? false : arguments[2]; - - if (toJSON) { - this._parsedJSONCache["delete"](prefName); - try { - prefValue = JSON.stringify(prefValue); - } catch (e) { - if (console) { - var isCyclic = function (obj) { - var seenObjects = []; - - function detect(obj) { - if (obj && typeof obj === "object") { - if (seenObjects.indexOf(obj) !== -1) { + User.prototype.getRepositoriesList = function getRepositoriesList() { + return this.repositories; + }; + + /** + * Set a preference value + * @param prefName String + * @param prefValue Mixed + * @param toJSON Boolean Whether to convert the value to JSON representation + */ + + User.prototype.setPreference = function setPreference(prefName, prefValue) { + var toJSON = arguments[2] === undefined ? false : arguments[2]; + + if (toJSON) { + this._parsedJSONCache["delete"](prefName); + try { + prefValue = JSON.stringify(prefValue); + } catch (e) { + if (console) { + var isCyclic = function (obj) { + var seenObjects = []; + + function detect(obj) { + if (obj && typeof obj === "object") { + if (seenObjects.indexOf(obj) !== -1) { + return true; + } + seenObjects.push(obj); + for (var key in obj) { + if (obj.hasOwnProperty(key) && detect(obj[key])) { + console.log(obj, "cycle at " + key); return true; } - seenObjects.push(obj); - for (var key in obj) { - if (obj.hasOwnProperty(key) && detect(obj[key])) { - console.log(obj, "cycle at " + key); - return true; - } - } } - return false; } - return detect(obj); - }; + return false; + } + return detect(obj); + }; - console.log("Caught toJSON error " + e.message, prefValue, isCyclic(prefValue)); - } - return; + console.log("Caught toJSON error " + e.message, prefValue, isCyclic(prefValue)); } + return; } - this.preferences.set(prefName, prefValue); } - }, { - key: "setRepositoriesList", + this.preferences.set(prefName, prefValue); + }; - /** - * Set the repositories as a bunch - * @param repoHash Map - */ - value: function setRepositoriesList(repoHash) { - this.repositories = repoHash; - // filter repositories once for all - this.crossRepositories = new Map(); - this.repositories.forEach((function (value, key) { - if (value.allowCrossRepositoryCopy) { - this.crossRepositories.set(key, value); - } - }).bind(this)); - } - }, { - key: "hasCrossRepositories", + /** + * Set the repositories as a bunch + * @param repoHash Map + */ - /** - * Whether there are any repositories allowing crossCopy - * @returns Boolean - */ - value: function hasCrossRepositories() { - return this.crossRepositories.size; - } - }, { - key: "getCrossRepositories", + User.prototype.setRepositoriesList = function setRepositoriesList(repoHash) { + this.repositories = repoHash; + // filter repositories once for all + this.crossRepositories = new Map(); + this.repositories.forEach((function (value, key) { + if (value.allowCrossRepositoryCopy) { + this.crossRepositories.set(key, value); + } + }).bind(this)); + }; - /** - * Get repositories allowing cross copy - * @returns {Map} - */ - value: function getCrossRepositories() { - return this.crossRepositories; - } - }, { - key: "getRepositoryIcon", + /** + * Whether there are any repositories allowing crossCopy + * @returns Boolean + */ - /** - * Get the current repository Icon - * @param repoId String - * @returns String - */ - value: function getRepositoryIcon(repoId) { - return this.repoIcon.get(repoId); - } - }, { - key: "getRepoSearchEngine", + User.prototype.hasCrossRepositories = function hasCrossRepositories() { + return this.crossRepositories.size; + }; - /** - * Get the repository search engine - * @param repoId String - * @returns String - */ - value: function getRepoSearchEngine(repoId) { - return this.repoSearchEngines.get(repoId); - } - }, { - key: "savePreference", + /** + * Get repositories allowing cross copy + * @returns {Map} + */ - /** - * Send the preference to the server for saving - * @param prefName String - */ - value: function savePreference(prefName) { - if (!this.preferences.has(prefName)) { - return; - }var prefValue = this.preferences.get(prefName); - window.setTimeout(function () { - PydioApi.getClient().userSavePreference(prefName, prefValue); - }, 250); - } - }, { - key: "savePreferences", + User.prototype.getCrossRepositories = function getCrossRepositories() { + return this.crossRepositories; + }; - /** - * Send all preferences to the server. If oldPass, newPass and seed are set, also save pass. - * @param oldPass String - * @param newPass String - * @param seed String - * @param onCompleteFunc Function - */ - value: function savePreferences(oldPass, newPass, seed, onCompleteFunc) { - if (oldPass && newPass) { - PydioApi.getClient().userSavePassword(oldPass, newPass, seed, onCompleteFunc); - } else { - PydioApi.getClient().userSavePreferences(this.preferences, onCompleteFunc); - } + /** + * Get the current repository Icon + * @param repoId String + * @returns String + */ + + User.prototype.getRepositoryIcon = function getRepositoryIcon(repoId) { + return this.repoIcon.get(repoId); + }; + + /** + * Get the repository search engine + * @param repoId String + * @returns String + */ + + User.prototype.getRepoSearchEngine = function getRepoSearchEngine(repoId) { + return this.repoSearchEngines.get(repoId); + }; + + /** + * Send the preference to the server for saving + * @param prefName String + */ + + User.prototype.savePreference = function savePreference(prefName) { + if (!this.preferences.has(prefName)) { + return; + }var prefValue = this.preferences.get(prefName); + window.setTimeout(function () { + PydioApi.getClient().userSavePreference(prefName, prefValue); + }, 250); + }; + + /** + * Send all preferences to the server. If oldPass, newPass and seed are set, also save pass. + * @param oldPass String + * @param newPass String + * @param seed String + * @param onCompleteFunc Function + */ + + User.prototype.savePreferences = function savePreferences(oldPass, newPass, seed, onCompleteFunc) { + if (oldPass && newPass) { + PydioApi.getClient().userSavePassword(oldPass, newPass, seed, onCompleteFunc); + } else { + PydioApi.getClient().userSavePreferences(this.preferences, onCompleteFunc); } - }, { - key: "loadFromXml", + }; - /** - * Parse the registry fragment to load this user - * @param userNodes DOMNode - */ - value: function loadFromXml(userNodes) { - - var repositories = new Map(); - var i, j; - for (i = 0; i < userNodes.length; i++) { - if (userNodes[i].nodeName == "active_repo") { - var activeNode = userNodes[i]; - } else if (userNodes[i].nodeName == "repositories") { - for (j = 0; j < userNodes[i].childNodes.length; j++) { - var repoChild = userNodes[i].childNodes[j]; - if (repoChild.nodeName == "repo") { - var repository = new Repository(repoChild.getAttribute("id"), repoChild); - repositories.set(repoChild.getAttribute("id"), repository); - } + /** + * Parse the registry fragment to load this user + * @param userNodes DOMNode + */ + + User.prototype.loadFromXml = function loadFromXml(userNodes) { + + var repositories = new Map(); + var i, j; + for (i = 0; i < userNodes.length; i++) { + if (userNodes[i].nodeName == "active_repo") { + var activeNode = userNodes[i]; + } else if (userNodes[i].nodeName == "repositories") { + for (j = 0; j < userNodes[i].childNodes.length; j++) { + var repoChild = userNodes[i].childNodes[j]; + if (repoChild.nodeName == "repo") { + var repository = new Repository(repoChild.getAttribute("id"), repoChild); + repositories.set(repoChild.getAttribute("id"), repository); } - this.setRepositoriesList(repositories); - } else if (userNodes[i].nodeName == "preferences") { - for (j = 0; j < userNodes[i].childNodes.length; j++) { - var prefChild = userNodes[i].childNodes[j]; - if (prefChild.nodeName == "pref") { - var value = prefChild.getAttribute("value"); - if (!value && prefChild.firstChild) { - // Retrieve value from CDATA - value = prefChild.firstChild.nodeValue; - } - this.setPreference(prefChild.getAttribute("name"), value); + } + this.setRepositoriesList(repositories); + } else if (userNodes[i].nodeName == "preferences") { + for (j = 0; j < userNodes[i].childNodes.length; j++) { + var prefChild = userNodes[i].childNodes[j]; + if (prefChild.nodeName == "pref") { + var value = prefChild.getAttribute("value"); + if (!value && prefChild.firstChild) { + // Retrieve value from CDATA + value = prefChild.firstChild.nodeValue; } - } - } else if (userNodes[i].nodeName == "special_rights") { - var attr = userNodes[i].getAttribute("is_admin"); - if (attr && attr == "1") this.isAdmin = true; - if (userNodes[i].getAttribute("lock")) { - this.lock = userNodes[i].getAttribute("lock"); + this.setPreference(prefChild.getAttribute("name"), value); } } + } else if (userNodes[i].nodeName == "special_rights") { + var attr = userNodes[i].getAttribute("is_admin"); + if (attr && attr == "1") this.isAdmin = true; + if (userNodes[i].getAttribute("lock")) { + this.lock = userNodes[i].getAttribute("lock"); + } } - // Make sure it happens at the end - if (activeNode) { - this.setActiveRepository(activeNode.getAttribute("id"), activeNode.getAttribute("read"), activeNode.getAttribute("write")); - } } - }]); + // Make sure it happens at the end + if (activeNode) { + this.setActiveRepository(activeNode.getAttribute("id"), activeNode.getAttribute("read"), activeNode.getAttribute("write")); + } + }; return User; })(); \ No newline at end of file diff --git a/core/src/plugins/gui.ajax/res/js/core/util/HasherUtils.js b/core/src/plugins/gui.ajax/res/js/core/util/HasherUtils.js index 9c0ba492b1..09e9feedfb 100644 --- a/core/src/plugins/gui.ajax/res/js/core/util/HasherUtils.js +++ b/core/src/plugins/gui.ajax/res/js/core/util/HasherUtils.js @@ -2,8 +2,6 @@ var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; -var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - var HasherUtils = (function () { /* @@ -19,392 +17,368 @@ var HasherUtils = (function () { _classCallCheck(this, HasherUtils); } - _createClass(HasherUtils, null, [{ - key: 'hex_md5', + /* + * These are the functions you'll usually want to call + * They take string arguments and return either hex or base-64 encoded strings + */ - /* - * These are the functions you'll usually want to call - * They take string arguments and return either hex or base-64 encoded strings - */ - value: function hex_md5(s) { - return HasherUtils.binl2hex(HasherUtils.core_md5(HasherUtils.str2binl(s), s.length * HasherUtils.chrsz)); - } - }, { - key: 'b64_md5', - value: function b64_md5(s) { - return HasherUtils.binl2b64(HasherUtils.core_md5(HasherUtils.str2binl(s), s.length * HasherUtils.chrsz)); - } - }, { - key: 'str_md5', - value: function str_md5(s) { - return HasherUtils.binl2str(HasherUtils.core_md5(HasherUtils.str2binl(s), s.length * HasherUtils.chrsz)); + HasherUtils.hex_md5 = function hex_md5(s) { + return HasherUtils.binl2hex(HasherUtils.core_md5(HasherUtils.str2binl(s), s.length * HasherUtils.chrsz)); + }; + + HasherUtils.b64_md5 = function b64_md5(s) { + return HasherUtils.binl2b64(HasherUtils.core_md5(HasherUtils.str2binl(s), s.length * HasherUtils.chrsz)); + }; + + HasherUtils.str_md5 = function str_md5(s) { + return HasherUtils.binl2str(HasherUtils.core_md5(HasherUtils.str2binl(s), s.length * HasherUtils.chrsz)); + }; + + HasherUtils.hex_hmac_md5 = function hex_hmac_md5(key, data) { + return HasherUtils.binl2hex(HasherUtils.core_hmac_md5(key, data)); + }; + + HasherUtils.b64_hmac_md5 = function b64_hmac_md5(key, data) { + return HasherUtils.binl2b64(HasherUtils.core_hmac_md5(key, data)); + }; + + HasherUtils.str_hmac_md5 = function str_hmac_md5(key, data) { + return HasherUtils.binl2str(HasherUtils.core_hmac_md5(key, data)); + }; + + HasherUtils.base64_encode = function base64_encode(data) { + // http://kevin.vanzonneveld.net + // + original by: Tyler Akins (http://rumkin.com) + // + improved by: Bayron Guevara + // + improved by: Thunder.m + // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) + // + bugfixed by: Pellentesque Malesuada + // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) + // - depends on: utf8_encode + // * example 1: base64_encode('Kevin van Zonneveld'); + // * returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA==' + + // mozilla has this native + // - but breaks in 2.0.0.12! + //if (typeof window['atob'] == 'function') { + // return atob(data); + //} + + var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + var o1, + o2, + o3, + h1, + h2, + h3, + h4, + bits, + i = 0, + ac = 0, + enc, + tmp_arr = []; + + if (!data) { + return data; } - }, { - key: 'hex_hmac_md5', - value: function hex_hmac_md5(key, data) { - return HasherUtils.binl2hex(HasherUtils.core_hmac_md5(key, data)); - } - }, { - key: 'b64_hmac_md5', - value: function b64_hmac_md5(key, data) { - return HasherUtils.binl2b64(HasherUtils.core_hmac_md5(key, data)); - } - }, { - key: 'str_hmac_md5', - value: function str_hmac_md5(key, data) { - return HasherUtils.binl2str(HasherUtils.core_hmac_md5(key, data)); - } - }, { - key: 'base64_encode', - value: function base64_encode(data) { - // http://kevin.vanzonneveld.net - // + original by: Tyler Akins (http://rumkin.com) - // + improved by: Bayron Guevara - // + improved by: Thunder.m - // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) - // + bugfixed by: Pellentesque Malesuada - // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) - // - depends on: utf8_encode - // * example 1: base64_encode('Kevin van Zonneveld'); - // * returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA==' - - // mozilla has this native - // - but breaks in 2.0.0.12! - //if (typeof window['atob'] == 'function') { - // return atob(data); - //} - - var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; - var o1, - o2, - o3, - h1, - h2, - h3, - h4, - bits, - i = 0, - ac = 0, - enc, - tmp_arr = []; - - if (!data) { - return data; - } - data = HasherUtils.utf8_encode(data + ''); + data = HasherUtils.utf8_encode(data + ''); - do { - // pack three octets into four hexets - o1 = data.charCodeAt(i++); - o2 = data.charCodeAt(i++); - o3 = data.charCodeAt(i++); + do { + // pack three octets into four hexets + o1 = data.charCodeAt(i++); + o2 = data.charCodeAt(i++); + o3 = data.charCodeAt(i++); - bits = o1 << 16 | o2 << 8 | o3; + bits = o1 << 16 | o2 << 8 | o3; - h1 = bits >> 18 & 63; - h2 = bits >> 12 & 63; - h3 = bits >> 6 & 63; - h4 = bits & 63; + h1 = bits >> 18 & 63; + h2 = bits >> 12 & 63; + h3 = bits >> 6 & 63; + h4 = bits & 63; - // use hexets to index into b64, and append result to encoded string - tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4); - } while (i < data.length); + // use hexets to index into b64, and append result to encoded string + tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4); + } while (i < data.length); - enc = tmp_arr.join(''); + enc = tmp_arr.join(''); - switch (data.length % 3) { - case 1: - enc = enc.slice(0, -2) + '=='; - break; - case 2: - enc = enc.slice(0, -1) + '='; - break; - } - - return enc; + switch (data.length % 3) { + case 1: + enc = enc.slice(0, -2) + '=='; + break; + case 2: + enc = enc.slice(0, -1) + '='; + break; } - }, { - key: 'utf8_encode', - value: function utf8_encode(string) { - // http://kevin.vanzonneveld.net - // + original by: Webtoolkit.info (http://www.webtoolkit.info/) - // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) - // + improved by: sowberry - // + tweaked by: Jack - // + bugfixed by: Onno Marsman - // + improved by: Yves Sucaet - // + bugfixed by: Onno Marsman - // * example 1: utf8_encode('Kevin van Zonneveld'); - // * returns 1: 'Kevin van Zonneveld' - - string = (string + '').replace(/\r\n/g, '\n').replace(/\r/g, '\n'); - - var utftext = ''; - var start, end; - var stringl; - - start = end = 0; - stringl = string.length; - for (var n = 0; n < stringl; n++) { - var c1 = string.charCodeAt(n); - var enc = null; - - if (c1 < 128) { - end++; - } else if (c1 > 127 && c1 < 2048) { - enc = String.fromCharCode(c1 >> 6 | 192) + String.fromCharCode(c1 & 63 | 128); - } else { - enc = String.fromCharCode(c1 >> 12 | 224) + String.fromCharCode(c1 >> 6 & 63 | 128) + String.fromCharCode(c1 & 63 | 128); - } - if (enc != null) { - if (end > start) { - utftext += string.substring(start, end); - } - utftext += enc; - start = end = n + 1; - } - } - if (end > start) { - utftext += string.substring(start, string.length); + return enc; + }; + + HasherUtils.utf8_encode = function utf8_encode(string) { + // http://kevin.vanzonneveld.net + // + original by: Webtoolkit.info (http://www.webtoolkit.info/) + // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) + // + improved by: sowberry + // + tweaked by: Jack + // + bugfixed by: Onno Marsman + // + improved by: Yves Sucaet + // + bugfixed by: Onno Marsman + // * example 1: utf8_encode('Kevin van Zonneveld'); + // * returns 1: 'Kevin van Zonneveld' + + string = (string + '').replace(/\r\n/g, '\n').replace(/\r/g, '\n'); + + var utftext = ''; + var start, end; + var stringl; + + start = end = 0; + stringl = string.length; + for (var n = 0; n < stringl; n++) { + var c1 = string.charCodeAt(n); + var enc = null; + + if (c1 < 128) { + end++; + } else if (c1 > 127 && c1 < 2048) { + enc = String.fromCharCode(c1 >> 6 | 192) + String.fromCharCode(c1 & 63 | 128); + } else { + enc = String.fromCharCode(c1 >> 12 | 224) + String.fromCharCode(c1 >> 6 & 63 | 128) + String.fromCharCode(c1 & 63 | 128); } - - return utftext; - } - }, { - key: 'md5_vm_test', - - /* - * Perform a simple self-test to see if the VM is working - */ - value: function md5_vm_test() { - return HasherUtils.hex_md5('abc') == '900150983cd24fb0d6963f7d28e17f72'; - } - }, { - key: 'core_md5', - - /* - * Calculate the MD5 of an array of little-endian words, and a bit length - */ - value: function core_md5(x, len) { - /* append padding */ - x[len >> 5] |= 128 << len % 32; - x[(len + 64 >>> 9 << 4) + 14] = len; - - var a = 1732584193; - var b = -271733879; - var c = -1732584194; - var d = 271733878; - - for (var i = 0; i < x.length; i += 16) { - var olda = a; - var oldb = b; - var oldc = c; - var oldd = d; - - a = HasherUtils.md5_ff(a, b, c, d, x[i + 0], 7, -680876936); - d = HasherUtils.md5_ff(d, a, b, c, x[i + 1], 12, -389564586); - c = HasherUtils.md5_ff(c, d, a, b, x[i + 2], 17, 606105819); - b = HasherUtils.md5_ff(b, c, d, a, x[i + 3], 22, -1044525330); - a = HasherUtils.md5_ff(a, b, c, d, x[i + 4], 7, -176418897); - d = HasherUtils.md5_ff(d, a, b, c, x[i + 5], 12, 1200080426); - c = HasherUtils.md5_ff(c, d, a, b, x[i + 6], 17, -1473231341); - b = HasherUtils.md5_ff(b, c, d, a, x[i + 7], 22, -45705983); - a = HasherUtils.md5_ff(a, b, c, d, x[i + 8], 7, 1770035416); - d = HasherUtils.md5_ff(d, a, b, c, x[i + 9], 12, -1958414417); - c = HasherUtils.md5_ff(c, d, a, b, x[i + 10], 17, -42063); - b = HasherUtils.md5_ff(b, c, d, a, x[i + 11], 22, -1990404162); - a = HasherUtils.md5_ff(a, b, c, d, x[i + 12], 7, 1804603682); - d = HasherUtils.md5_ff(d, a, b, c, x[i + 13], 12, -40341101); - c = HasherUtils.md5_ff(c, d, a, b, x[i + 14], 17, -1502002290); - b = HasherUtils.md5_ff(b, c, d, a, x[i + 15], 22, 1236535329); - - a = HasherUtils.md5_gg(a, b, c, d, x[i + 1], 5, -165796510); - d = HasherUtils.md5_gg(d, a, b, c, x[i + 6], 9, -1069501632); - c = HasherUtils.md5_gg(c, d, a, b, x[i + 11], 14, 643717713); - b = HasherUtils.md5_gg(b, c, d, a, x[i + 0], 20, -373897302); - a = HasherUtils.md5_gg(a, b, c, d, x[i + 5], 5, -701558691); - d = HasherUtils.md5_gg(d, a, b, c, x[i + 10], 9, 38016083); - c = HasherUtils.md5_gg(c, d, a, b, x[i + 15], 14, -660478335); - b = HasherUtils.md5_gg(b, c, d, a, x[i + 4], 20, -405537848); - a = HasherUtils.md5_gg(a, b, c, d, x[i + 9], 5, 568446438); - d = HasherUtils.md5_gg(d, a, b, c, x[i + 14], 9, -1019803690); - c = HasherUtils.md5_gg(c, d, a, b, x[i + 3], 14, -187363961); - b = HasherUtils.md5_gg(b, c, d, a, x[i + 8], 20, 1163531501); - a = HasherUtils.md5_gg(a, b, c, d, x[i + 13], 5, -1444681467); - d = HasherUtils.md5_gg(d, a, b, c, x[i + 2], 9, -51403784); - c = HasherUtils.md5_gg(c, d, a, b, x[i + 7], 14, 1735328473); - b = HasherUtils.md5_gg(b, c, d, a, x[i + 12], 20, -1926607734); - - a = HasherUtils.md5_hh(a, b, c, d, x[i + 5], 4, -378558); - d = HasherUtils.md5_hh(d, a, b, c, x[i + 8], 11, -2022574463); - c = HasherUtils.md5_hh(c, d, a, b, x[i + 11], 16, 1839030562); - b = HasherUtils.md5_hh(b, c, d, a, x[i + 14], 23, -35309556); - a = HasherUtils.md5_hh(a, b, c, d, x[i + 1], 4, -1530992060); - d = HasherUtils.md5_hh(d, a, b, c, x[i + 4], 11, 1272893353); - c = HasherUtils.md5_hh(c, d, a, b, x[i + 7], 16, -155497632); - b = HasherUtils.md5_hh(b, c, d, a, x[i + 10], 23, -1094730640); - a = HasherUtils.md5_hh(a, b, c, d, x[i + 13], 4, 681279174); - d = HasherUtils.md5_hh(d, a, b, c, x[i + 0], 11, -358537222); - c = HasherUtils.md5_hh(c, d, a, b, x[i + 3], 16, -722521979); - b = HasherUtils.md5_hh(b, c, d, a, x[i + 6], 23, 76029189); - a = HasherUtils.md5_hh(a, b, c, d, x[i + 9], 4, -640364487); - d = HasherUtils.md5_hh(d, a, b, c, x[i + 12], 11, -421815835); - c = HasherUtils.md5_hh(c, d, a, b, x[i + 15], 16, 530742520); - b = HasherUtils.md5_hh(b, c, d, a, x[i + 2], 23, -995338651); - - a = HasherUtils.md5_ii(a, b, c, d, x[i + 0], 6, -198630844); - d = HasherUtils.md5_ii(d, a, b, c, x[i + 7], 10, 1126891415); - c = HasherUtils.md5_ii(c, d, a, b, x[i + 14], 15, -1416354905); - b = HasherUtils.md5_ii(b, c, d, a, x[i + 5], 21, -57434055); - a = HasherUtils.md5_ii(a, b, c, d, x[i + 12], 6, 1700485571); - d = HasherUtils.md5_ii(d, a, b, c, x[i + 3], 10, -1894986606); - c = HasherUtils.md5_ii(c, d, a, b, x[i + 10], 15, -1051523); - b = HasherUtils.md5_ii(b, c, d, a, x[i + 1], 21, -2054922799); - a = HasherUtils.md5_ii(a, b, c, d, x[i + 8], 6, 1873313359); - d = HasherUtils.md5_ii(d, a, b, c, x[i + 15], 10, -30611744); - c = HasherUtils.md5_ii(c, d, a, b, x[i + 6], 15, -1560198380); - b = HasherUtils.md5_ii(b, c, d, a, x[i + 13], 21, 1309151649); - a = HasherUtils.md5_ii(a, b, c, d, x[i + 4], 6, -145523070); - d = HasherUtils.md5_ii(d, a, b, c, x[i + 11], 10, -1120210379); - c = HasherUtils.md5_ii(c, d, a, b, x[i + 2], 15, 718787259); - b = HasherUtils.md5_ii(b, c, d, a, x[i + 9], 21, -343485551); - - a = HasherUtils.safe_add(a, olda); - b = HasherUtils.safe_add(b, oldb); - c = HasherUtils.safe_add(c, oldc); - d = HasherUtils.safe_add(d, oldd); + if (enc != null) { + if (end > start) { + utftext += string.substring(start, end); + } + utftext += enc; + start = end = n + 1; } - return [a, b, c, d]; - } - }, { - key: 'md5_cmn', - - /* - * These functions implement the four basic operations the algorithm uses. - */ - value: function md5_cmn(q, a, b, x, s, t) { - return HasherUtils.safe_add(HasherUtils.bit_rol(HasherUtils.safe_add(HasherUtils.safe_add(a, q), HasherUtils.safe_add(x, t)), s), b); } - }, { - key: 'md5_ff', - value: function md5_ff(a, b, c, d, x, s, t) { - return HasherUtils.md5_cmn(b & c | ~b & d, a, b, x, s, t); - } - }, { - key: 'md5_gg', - value: function md5_gg(a, b, c, d, x, s, t) { - return HasherUtils.md5_cmn(b & d | c & ~d, a, b, x, s, t); - } - }, { - key: 'md5_hh', - value: function md5_hh(a, b, c, d, x, s, t) { - return HasherUtils.md5_cmn(b ^ c ^ d, a, b, x, s, t); - } - }, { - key: 'md5_ii', - value: function md5_ii(a, b, c, d, x, s, t) { - return HasherUtils.md5_cmn(c ^ (b | ~d), a, b, x, s, t); - } - }, { - key: 'core_hmac_md5', - - /* - * Calculate the HMAC-MD5, of a key and some data - */ - value: function core_hmac_md5(key, data) { - var bkey = HasherUtils.str2binl(key); - if (bkey.length > 16) bkey = HasherUtils.core_md5(bkey, key.length * HasherUtils.chrsz); - - var ipad = new Array(16), - opad = new Array(16); - for (var i = 0; i < 16; i++) { - ipad[i] = bkey[i] ^ 909522486; - opad[i] = bkey[i] ^ 1549556828; - } - var hash = HasherUtils.core_md5(ipad.concat(HasherUtils.str2binl(data)), 512 + data.length * HasherUtils.chrsz); - return HasherUtils.core_md5(opad.concat(hash), 512 + 128); + if (end > start) { + utftext += string.substring(start, string.length); } - }, { - key: 'safe_add', - - /* - * Add integers, wrapping at 2^32. This uses 16-bit operations internally - * to work around bugs in some JS interpreters. - */ - value: function safe_add(x, y) { - var lsw = (x & 65535) + (y & 65535); - var msw = (x >> 16) + (y >> 16) + (lsw >> 16); - return msw << 16 | lsw & 65535; - } - }, { - key: 'bit_rol', - - /* - * Bitwise rotate a 32-bit number to the left. - */ - value: function bit_rol(num, cnt) { - return num << cnt | num >>> 32 - cnt; - } - }, { - key: 'str2binl', - - /* - * Convert a string to an array of little-endian words - * If HasherUtils.chrsz is ASCII, characters >255 have their hi-byte silently ignored. - */ - value: function str2binl(str) { - var bin = []; - var mask = (1 << HasherUtils.chrsz) - 1; - for (var i = 0; i < str.length * HasherUtils.chrsz; i += HasherUtils.chrsz) bin[i >> 5] |= (str.charCodeAt(i / HasherUtils.chrsz) & mask) << i % 32; - return bin; + + return utftext; + }; + + /* + * Perform a simple self-test to see if the VM is working + */ + + HasherUtils.md5_vm_test = function md5_vm_test() { + return HasherUtils.hex_md5('abc') == '900150983cd24fb0d6963f7d28e17f72'; + }; + + /* + * Calculate the MD5 of an array of little-endian words, and a bit length + */ + + HasherUtils.core_md5 = function core_md5(x, len) { + /* append padding */ + x[len >> 5] |= 128 << len % 32; + x[(len + 64 >>> 9 << 4) + 14] = len; + + var a = 1732584193; + var b = -271733879; + var c = -1732584194; + var d = 271733878; + + for (var i = 0; i < x.length; i += 16) { + var olda = a; + var oldb = b; + var oldc = c; + var oldd = d; + + a = HasherUtils.md5_ff(a, b, c, d, x[i + 0], 7, -680876936); + d = HasherUtils.md5_ff(d, a, b, c, x[i + 1], 12, -389564586); + c = HasherUtils.md5_ff(c, d, a, b, x[i + 2], 17, 606105819); + b = HasherUtils.md5_ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = HasherUtils.md5_ff(a, b, c, d, x[i + 4], 7, -176418897); + d = HasherUtils.md5_ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = HasherUtils.md5_ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = HasherUtils.md5_ff(b, c, d, a, x[i + 7], 22, -45705983); + a = HasherUtils.md5_ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = HasherUtils.md5_ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = HasherUtils.md5_ff(c, d, a, b, x[i + 10], 17, -42063); + b = HasherUtils.md5_ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = HasherUtils.md5_ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = HasherUtils.md5_ff(d, a, b, c, x[i + 13], 12, -40341101); + c = HasherUtils.md5_ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = HasherUtils.md5_ff(b, c, d, a, x[i + 15], 22, 1236535329); + + a = HasherUtils.md5_gg(a, b, c, d, x[i + 1], 5, -165796510); + d = HasherUtils.md5_gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = HasherUtils.md5_gg(c, d, a, b, x[i + 11], 14, 643717713); + b = HasherUtils.md5_gg(b, c, d, a, x[i + 0], 20, -373897302); + a = HasherUtils.md5_gg(a, b, c, d, x[i + 5], 5, -701558691); + d = HasherUtils.md5_gg(d, a, b, c, x[i + 10], 9, 38016083); + c = HasherUtils.md5_gg(c, d, a, b, x[i + 15], 14, -660478335); + b = HasherUtils.md5_gg(b, c, d, a, x[i + 4], 20, -405537848); + a = HasherUtils.md5_gg(a, b, c, d, x[i + 9], 5, 568446438); + d = HasherUtils.md5_gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = HasherUtils.md5_gg(c, d, a, b, x[i + 3], 14, -187363961); + b = HasherUtils.md5_gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = HasherUtils.md5_gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = HasherUtils.md5_gg(d, a, b, c, x[i + 2], 9, -51403784); + c = HasherUtils.md5_gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = HasherUtils.md5_gg(b, c, d, a, x[i + 12], 20, -1926607734); + + a = HasherUtils.md5_hh(a, b, c, d, x[i + 5], 4, -378558); + d = HasherUtils.md5_hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = HasherUtils.md5_hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = HasherUtils.md5_hh(b, c, d, a, x[i + 14], 23, -35309556); + a = HasherUtils.md5_hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = HasherUtils.md5_hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = HasherUtils.md5_hh(c, d, a, b, x[i + 7], 16, -155497632); + b = HasherUtils.md5_hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = HasherUtils.md5_hh(a, b, c, d, x[i + 13], 4, 681279174); + d = HasherUtils.md5_hh(d, a, b, c, x[i + 0], 11, -358537222); + c = HasherUtils.md5_hh(c, d, a, b, x[i + 3], 16, -722521979); + b = HasherUtils.md5_hh(b, c, d, a, x[i + 6], 23, 76029189); + a = HasherUtils.md5_hh(a, b, c, d, x[i + 9], 4, -640364487); + d = HasherUtils.md5_hh(d, a, b, c, x[i + 12], 11, -421815835); + c = HasherUtils.md5_hh(c, d, a, b, x[i + 15], 16, 530742520); + b = HasherUtils.md5_hh(b, c, d, a, x[i + 2], 23, -995338651); + + a = HasherUtils.md5_ii(a, b, c, d, x[i + 0], 6, -198630844); + d = HasherUtils.md5_ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = HasherUtils.md5_ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = HasherUtils.md5_ii(b, c, d, a, x[i + 5], 21, -57434055); + a = HasherUtils.md5_ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = HasherUtils.md5_ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = HasherUtils.md5_ii(c, d, a, b, x[i + 10], 15, -1051523); + b = HasherUtils.md5_ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = HasherUtils.md5_ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = HasherUtils.md5_ii(d, a, b, c, x[i + 15], 10, -30611744); + c = HasherUtils.md5_ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = HasherUtils.md5_ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = HasherUtils.md5_ii(a, b, c, d, x[i + 4], 6, -145523070); + d = HasherUtils.md5_ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = HasherUtils.md5_ii(c, d, a, b, x[i + 2], 15, 718787259); + b = HasherUtils.md5_ii(b, c, d, a, x[i + 9], 21, -343485551); + + a = HasherUtils.safe_add(a, olda); + b = HasherUtils.safe_add(b, oldb); + c = HasherUtils.safe_add(c, oldc); + d = HasherUtils.safe_add(d, oldd); } - }, { - key: 'binl2str', - - /* - * Convert an array of little-endian words to a string - */ - value: function binl2str(bin) { - var str = ''; - var mask = (1 << HasherUtils.chrsz) - 1; - for (var i = 0; i < bin.length * 32; i += HasherUtils.chrsz) str += String.fromCharCode(bin[i >> 5] >>> i % 32 & mask); - return str; + return [a, b, c, d]; + }; + + /* + * These functions implement the four basic operations the algorithm uses. + */ + + HasherUtils.md5_cmn = function md5_cmn(q, a, b, x, s, t) { + return HasherUtils.safe_add(HasherUtils.bit_rol(HasherUtils.safe_add(HasherUtils.safe_add(a, q), HasherUtils.safe_add(x, t)), s), b); + }; + + HasherUtils.md5_ff = function md5_ff(a, b, c, d, x, s, t) { + return HasherUtils.md5_cmn(b & c | ~b & d, a, b, x, s, t); + }; + + HasherUtils.md5_gg = function md5_gg(a, b, c, d, x, s, t) { + return HasherUtils.md5_cmn(b & d | c & ~d, a, b, x, s, t); + }; + + HasherUtils.md5_hh = function md5_hh(a, b, c, d, x, s, t) { + return HasherUtils.md5_cmn(b ^ c ^ d, a, b, x, s, t); + }; + + HasherUtils.md5_ii = function md5_ii(a, b, c, d, x, s, t) { + return HasherUtils.md5_cmn(c ^ (b | ~d), a, b, x, s, t); + }; + + /* + * Calculate the HMAC-MD5, of a key and some data + */ + + HasherUtils.core_hmac_md5 = function core_hmac_md5(key, data) { + var bkey = HasherUtils.str2binl(key); + if (bkey.length > 16) bkey = HasherUtils.core_md5(bkey, key.length * HasherUtils.chrsz); + + var ipad = new Array(16), + opad = new Array(16); + for (var i = 0; i < 16; i++) { + ipad[i] = bkey[i] ^ 909522486; + opad[i] = bkey[i] ^ 1549556828; } - }, { - key: 'binl2hex', - - /* - * Convert an array of little-endian words to a hex string. - */ - value: function binl2hex(binarray) { - var hex_tab = HasherUtils.hexcase ? '0123456789ABCDEF' : '0123456789abcdef'; - var str = ''; - for (var i = 0; i < binarray.length * 4; i++) { - str += hex_tab.charAt(binarray[i >> 2] >> i % 4 * 8 + 4 & 15) + hex_tab.charAt(binarray[i >> 2] >> i % 4 * 8 & 15); - } - return str; + + var hash = HasherUtils.core_md5(ipad.concat(HasherUtils.str2binl(data)), 512 + data.length * HasherUtils.chrsz); + return HasherUtils.core_md5(opad.concat(hash), 512 + 128); + }; + + /* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ + + HasherUtils.safe_add = function safe_add(x, y) { + var lsw = (x & 65535) + (y & 65535); + var msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return msw << 16 | lsw & 65535; + }; + + /* + * Bitwise rotate a 32-bit number to the left. + */ + + HasherUtils.bit_rol = function bit_rol(num, cnt) { + return num << cnt | num >>> 32 - cnt; + }; + + /* + * Convert a string to an array of little-endian words + * If HasherUtils.chrsz is ASCII, characters >255 have their hi-byte silently ignored. + */ + + HasherUtils.str2binl = function str2binl(str) { + var bin = []; + var mask = (1 << HasherUtils.chrsz) - 1; + for (var i = 0; i < str.length * HasherUtils.chrsz; i += HasherUtils.chrsz) bin[i >> 5] |= (str.charCodeAt(i / HasherUtils.chrsz) & mask) << i % 32; + return bin; + }; + + /* + * Convert an array of little-endian words to a string + */ + + HasherUtils.binl2str = function binl2str(bin) { + var str = ''; + var mask = (1 << HasherUtils.chrsz) - 1; + for (var i = 0; i < bin.length * 32; i += HasherUtils.chrsz) str += String.fromCharCode(bin[i >> 5] >>> i % 32 & mask); + return str; + }; + + /* + * Convert an array of little-endian words to a hex string. + */ + + HasherUtils.binl2hex = function binl2hex(binarray) { + var hex_tab = HasherUtils.hexcase ? '0123456789ABCDEF' : '0123456789abcdef'; + var str = ''; + for (var i = 0; i < binarray.length * 4; i++) { + str += hex_tab.charAt(binarray[i >> 2] >> i % 4 * 8 + 4 & 15) + hex_tab.charAt(binarray[i >> 2] >> i % 4 * 8 & 15); } - }, { - key: 'binl2b64', - - /* - * Convert an array of little-endian words to a base-64 string - */ - value: function binl2b64(binarray) { - var tab = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - var str = ''; - for (var i = 0; i < binarray.length * 4; i += 3) { - var triplet = (binarray[i >> 2] >> 8 * (i % 4) & 255) << 16 | (binarray[i + 1 >> 2] >> 8 * ((i + 1) % 4) & 255) << 8 | binarray[i + 2 >> 2] >> 8 * ((i + 2) % 4) & 255; - for (var j = 0; j < 4; j++) { - if (i * 8 + j * 6 > binarray.length * 32) str += HasherUtils.b64pad;else str += tab.charAt(triplet >> 6 * (3 - j) & 63); - } + return str; + }; + + /* + * Convert an array of little-endian words to a base-64 string + */ + + HasherUtils.binl2b64 = function binl2b64(binarray) { + var tab = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + var str = ''; + for (var i = 0; i < binarray.length * 4; i += 3) { + var triplet = (binarray[i >> 2] >> 8 * (i % 4) & 255) << 16 | (binarray[i + 1 >> 2] >> 8 * ((i + 1) % 4) & 255) << 8 | binarray[i + 2 >> 2] >> 8 * ((i + 2) % 4) & 255; + for (var j = 0; j < 4; j++) { + if (i * 8 + j * 6 > binarray.length * 32) str += HasherUtils.b64pad;else str += tab.charAt(triplet >> 6 * (3 - j) & 63); } - return str; } - }]); + return str; + }; return HasherUtils; })(); diff --git a/core/src/plugins/gui.ajax/res/js/core/util/LangUtils.js b/core/src/plugins/gui.ajax/res/js/core/util/LangUtils.js index afd18b9028..a9e2dbc3ba 100644 --- a/core/src/plugins/gui.ajax/res/js/core/util/LangUtils.js +++ b/core/src/plugins/gui.ajax/res/js/core/util/LangUtils.js @@ -2,57 +2,50 @@ var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; -var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - var LangUtils = (function () { function LangUtils() { _classCallCheck(this, LangUtils); } - _createClass(LangUtils, null, [{ - key: 'objectMerge', - value: function objectMerge(obj1, obj2) { - for (var k in obj2) { - if (obj2.hasOwnProperty(k)) { - obj1[k] = obj2[k]; - } + LangUtils.objectMerge = function objectMerge(obj1, obj2) { + for (var k in obj2) { + if (obj2.hasOwnProperty(k)) { + obj1[k] = obj2[k]; } - return obj1; } - }, { - key: 'parseUrl', - value: function parseUrl(data) { - var matches = $A(); - //var e=/((http|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+\.[^#?\s]+)(#[\w\-]+)?/; - var detect = /(((ajxp\.)(\w+)):\/)?\/?([^:\/\s]+)((\/\w+)*\/)(.*)(#[\w\-]+)?/g; - var results = data.match(detect); - if (results && results.length) { - var e = /^((ajxp\.(\w+)):\/)?\/?([^:\/\s]+)((\/\w+)*\/)(.*)(#[\w\-]+)?$/; - for (var i = 0; i < results.length; i++) { - if (results[i].match(e)) { - matches.push({ url: RegExp['$&'], - protocol: RegExp.$2, - host: RegExp.$4, - path: RegExp.$5, - file: RegExp.$7, - hash: RegExp.$8 }); - } + return obj1; + }; + + LangUtils.parseUrl = function parseUrl(data) { + var matches = $A(); + //var e=/((http|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+\.[^#?\s]+)(#[\w\-]+)?/; + var detect = /(((ajxp\.)(\w+)):\/)?\/?([^:\/\s]+)((\/\w+)*\/)(.*)(#[\w\-]+)?/g; + var results = data.match(detect); + if (results && results.length) { + var e = /^((ajxp\.(\w+)):\/)?\/?([^:\/\s]+)((\/\w+)*\/)(.*)(#[\w\-]+)?$/; + for (var i = 0; i < results.length; i++) { + if (results[i].match(e)) { + matches.push({ url: RegExp['$&'], + protocol: RegExp.$2, + host: RegExp.$4, + path: RegExp.$5, + file: RegExp.$7, + hash: RegExp.$8 }); } } - return matches; } - }, { - key: 'computeStringSlug', - value: function computeStringSlug(value) { - for (var i = 0, len = LangUtils.slugTable.length; i < len; i++) value = value.replace(LangUtils.slugTable[i].re, LangUtils.slugTable[i].ch); - - // 1) met en bas de casse - // 2) remplace les espace par des tirets - // 3) enleve tout les caratères non alphanumeriques - // 4) enlève les doubles tirets - return value.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '').replace(/\-{2,}/g, '-'); - } - }]); + return matches; + }; + + LangUtils.computeStringSlug = function computeStringSlug(value) { + for (var i = 0, len = LangUtils.slugTable.length; i < len; i++) value = value.replace(LangUtils.slugTable[i].re, LangUtils.slugTable[i].ch); + + // 1) met en bas de casse + // 2) remplace les espace par des tirets + // 3) enleve tout les caratères non alphanumeriques + // 4) enlève les doubles tirets + return value.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '').replace(/\-{2,}/g, '-'); + }; return LangUtils; })(); diff --git a/core/src/plugins/gui.ajax/res/js/core/util/PathUtils.js b/core/src/plugins/gui.ajax/res/js/core/util/PathUtils.js index 983b106c5f..4e7a6deb08 100644 --- a/core/src/plugins/gui.ajax/res/js/core/util/PathUtils.js +++ b/core/src/plugins/gui.ajax/res/js/core/util/PathUtils.js @@ -2,97 +2,87 @@ var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; -var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - var PathUtils = (function () { function PathUtils() { _classCallCheck(this, PathUtils); } - _createClass(PathUtils, null, [{ - key: "getBasename", - value: function getBasename(fileName) { - if (fileName == null) { - return null; - }var separator = "/"; - if (fileName.indexOf("\\") != -1) separator = "\\"; - return fileName.substr(fileName.lastIndexOf(separator) + 1, fileName.length); - } - }, { - key: "getDirname", - value: function getDirname(fileName) { - return fileName.substr(0, fileName.lastIndexOf("/")); - } - }, { - key: "getAjxpMimeType", - value: function getAjxpMimeType(item) { - if (!item) { - return ""; - }if (item instanceof Map) { - return item.get("ajxp_mime") || PathUtils.getFileExtension(item.get("filename")); - } else if (item.getMetadata) { - return item.getMetadata().get("ajxp_mime") || PathUtils.getFileExtension(item.getPath()); - } else { - return item.getAttribute("ajxp_mime") || PathUtils.getFileExtension(item.getAttribute("filename")); - } - } - }, { - key: "getFileExtension", - value: function getFileExtension(fileName) { - if (!fileName || fileName == "") { - return ""; - }var split = PathUtils.getBasename(fileName).split("."); - if (split.length > 1) { - return split[split.length - 1].toLowerCase(); - }return ""; + PathUtils.getBasename = function getBasename(fileName) { + if (fileName == null) { + return null; + }var separator = "/"; + if (fileName.indexOf("\\") != -1) separator = "\\"; + return fileName.substr(fileName.lastIndexOf(separator) + 1, fileName.length); + }; + + PathUtils.getDirname = function getDirname(fileName) { + return fileName.substr(0, fileName.lastIndexOf("/")); + }; + + PathUtils.getAjxpMimeType = function getAjxpMimeType(item) { + if (!item) { + return ""; + }if (item instanceof Map) { + return item.get("ajxp_mime") || PathUtils.getFileExtension(item.get("filename")); + } else if (item.getMetadata) { + return item.getMetadata().get("ajxp_mime") || PathUtils.getFileExtension(item.getPath()); + } else { + return item.getAttribute("ajxp_mime") || PathUtils.getFileExtension(item.getAttribute("filename")); } - }, { - key: "roundFileSize", - value: function roundFileSize(filesize) { - var size_unit = arguments[1] === undefined ? "o" : arguments[1]; + }; + + PathUtils.getFileExtension = function getFileExtension(fileName) { + if (!fileName || fileName == "") { + return ""; + }var split = PathUtils.getBasename(fileName).split("."); + if (split.length > 1) { + return split[split.length - 1].toLowerCase(); + }return ""; + }; - if (filesize >= 1073741824) { - filesize = Math.round(filesize / 1073741824 * 100) / 100 + " G" + size_unit; - } else if (filesize >= 1048576) { - filesize = Math.round(filesize / 1048576 * 100) / 100 + " M" + size_unit; - } else if (filesize >= 1024) { - filesize = Math.round(filesize / 1024 * 100) / 100 + " K" + size_unit; - } else { - filesize = filesize + " " + size_unit; - } - return filesize; + PathUtils.roundFileSize = function roundFileSize(filesize) { + var size_unit = arguments[1] === undefined ? "o" : arguments[1]; + + if (filesize >= 1073741824) { + filesize = Math.round(filesize / 1073741824 * 100) / 100 + " G" + size_unit; + } else if (filesize >= 1048576) { + filesize = Math.round(filesize / 1048576 * 100) / 100 + " M" + size_unit; + } else if (filesize >= 1024) { + filesize = Math.round(filesize / 1024 * 100) / 100 + " K" + size_unit; + } else { + filesize = filesize + " " + size_unit; } - }, { - key: "formatModifDate", + return filesize; + }; + + /** + * + * @param dateObject Date + * @param format String + * @returns {*} + */ - /** - * - * @param dateObject Date - * @param format String - * @returns {*} - */ - value: function formatModifDate(dateObject, format) { - if (!format && window && window.pydio && pydio.MessageHash) { - format = pydio.MessageHash.date_format; - } - if (!format) { - return "no format"; - }format = format.replace("d", dateObject.getDate() < 10 ? "0" + dateObject.getDate() : dateObject.getDate()); - format = format.replace("D", dateObject.getDay()); - format = format.replace("Y", dateObject.getFullYear()); - format = format.replace("y", dateObject.getYear()); - var month = dateObject.getMonth() + 1; - format = format.replace("m", month < 10 ? "0" + month : month); - format = format.replace("H", (dateObject.getHours() < 10 ? "0" : "") + dateObject.getHours()); - // Support 12 hour format compatibility - format = format.replace("h", dateObject.getHours() % 12 || 12); - format = format.replace("p", dateObject.getHours() < 12 ? "am" : "pm"); - format = format.replace("P", dateObject.getHours() < 12 ? "AM" : "PM"); - format = format.replace("i", (dateObject.getMinutes() < 10 ? "0" : "") + dateObject.getMinutes()); - format = format.replace("s", (dateObject.getSeconds() < 10 ? "0" : "") + dateObject.getSeconds()); - return format; + PathUtils.formatModifDate = function formatModifDate(dateObject, format) { + if (!format && window && window.pydio && pydio.MessageHash) { + format = pydio.MessageHash.date_format; } - }]); + if (!format) { + return "no format"; + }format = format.replace("d", dateObject.getDate() < 10 ? "0" + dateObject.getDate() : dateObject.getDate()); + format = format.replace("D", dateObject.getDay()); + format = format.replace("Y", dateObject.getFullYear()); + format = format.replace("y", dateObject.getYear()); + var month = dateObject.getMonth() + 1; + format = format.replace("m", month < 10 ? "0" + month : month); + format = format.replace("H", (dateObject.getHours() < 10 ? "0" : "") + dateObject.getHours()); + // Support 12 hour format compatibility + format = format.replace("h", dateObject.getHours() % 12 || 12); + format = format.replace("p", dateObject.getHours() < 12 ? "am" : "pm"); + format = format.replace("P", dateObject.getHours() < 12 ? "AM" : "PM"); + format = format.replace("i", (dateObject.getMinutes() < 10 ? "0" : "") + dateObject.getMinutes()); + format = format.replace("s", (dateObject.getSeconds() < 10 ? "0" : "") + dateObject.getSeconds()); + return format; + }; return PathUtils; })(); \ No newline at end of file diff --git a/core/src/plugins/gui.ajax/res/js/core/util/XMLUtils.js b/core/src/plugins/gui.ajax/res/js/core/util/XMLUtils.js index 5b1aa7f268..dde2b71492 100644 --- a/core/src/plugins/gui.ajax/res/js/core/util/XMLUtils.js +++ b/core/src/plugins/gui.ajax/res/js/core/util/XMLUtils.js @@ -2,195 +2,185 @@ var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; -var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - var XMLUtils = (function () { function XMLUtils() { _classCallCheck(this, XMLUtils); } - _createClass(XMLUtils, null, [{ - key: "loadXPathReplacer", - value: function loadXPathReplacer() { - if (document.createExpression) { - return; - }PydioApi.loadLibrary("plugins/gui.ajax/res/js/vendor/xpath-polyfill/javascript-xpath-cmp.js", null, false); - } - }, { - key: "XPathSelectSingleNode", - - /** - * Selects the first XmlNode that matches the XPath expression. - * - * @param element {Element | Document} root element for the search - * @param query {String} XPath query - * @return {Element} first matching element - * @signature function(element, query) - */ - value: function XPathSelectSingleNode(element, query) { + XMLUtils.loadXPathReplacer = function loadXPathReplacer() { + if (document.createExpression) { + return; + }PydioApi.loadLibrary("plugins/gui.ajax/res/js/vendor/xpath-polyfill/javascript-xpath-cmp.js", null, false); + }; + + /** + * Selects the first XmlNode that matches the XPath expression. + * + * @param element {Element | Document} root element for the search + * @param query {String} XPath query + * @return {Element} first matching element + * @signature function(element, query) + */ + + XMLUtils.XPathSelectSingleNode = function XPathSelectSingleNode(element, query) { + try { + var res = element.selectSingleNode(query); + if (res) return res; + } catch (e) {} + + if (!XMLUtils.__xpe) { try { - var res = element.selectSingleNode(query); - if (res) return res; + XMLUtils.__xpe = new XPathEvaluator(); } catch (e) {} + } - if (!XMLUtils.__xpe) { - try { - XMLUtils.__xpe = new XPathEvaluator(); - } catch (e) {} - } - - if (!XMLUtils.__xpe) { - if (!document.createExpression) XMLUtils.loadXPathReplacer(); - query = document.createExpression(query, null); - var result = query.evaluate(element, 7, null); - return result.snapshotLength ? result.snapshotItem(0) : null; - } + if (!XMLUtils.__xpe) { + if (!document.createExpression) XMLUtils.loadXPathReplacer(); + query = document.createExpression(query, null); + var result = query.evaluate(element, 7, null); + return result.snapshotLength ? result.snapshotItem(0) : null; + } - var xpe = XMLUtils.__xpe; + var xpe = XMLUtils.__xpe; - try { - return xpe.evaluate(query, element, xpe.createNSResolver(element), XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; - } catch (err) { - throw new Error("selectSingleNode: query: " + query + ", element: " + element + ", error: " + err); - } + try { + return xpe.evaluate(query, element, xpe.createNSResolver(element), XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; + } catch (err) { + throw new Error("selectSingleNode: query: " + query + ", element: " + element + ", error: " + err); } - }, { - key: "XPathSelectNodes", - - /** - * Selects a list of nodes matching the XPath expression. - * - * @param element {Element | Document} root element for the search - * @param query {String} XPath query - * @return {Element[]} List of matching elements - * @signature function(element, query) - */ - value: function XPathSelectNodes(element, query) { + }; + + /** + * Selects a list of nodes matching the XPath expression. + * + * @param element {Element | Document} root element for the search + * @param query {String} XPath query + * @return {Element[]} List of matching elements + * @signature function(element, query) + */ + + XMLUtils.XPathSelectNodes = function XPathSelectNodes(element, query) { + try { try { - try { - if (element.ownerDocument) { - element.ownerDocument.setProperty("SelectionLanguage", "XPath"); - } else { - element.setProperty("SelectionLanguage", "XPath"); - } - } catch (e) {} - var res = Array.from(element.selectNodes(query)); - if (res) return res; + if (element.ownerDocument) { + element.ownerDocument.setProperty("SelectionLanguage", "XPath"); + } else { + element.setProperty("SelectionLanguage", "XPath"); + } } catch (e) {} + var res = Array.from(element.selectNodes(query)); + if (res) return res; + } catch (e) {} - var xpe = XMLUtils.__xpe; - - if (!xpe) { - try { - XMLUtils.__xpe = xpe = new XPathEvaluator(); - } catch (e) {} - } - var result, - nodes = [], - i; - if (!XMLUtils.__xpe) { - if (!document.createExpression) XMLUtils.loadXPathReplacer(); - query = document.createExpression(query, null); - result = query.evaluate(element, 7, null); - nodes = []; - for (i = 0; i < result.snapshotLength; i++) { - if (Element.extend) { - nodes[i] = Element.extend(result.snapshotItem(i)); - } else { - nodes[i] = result.snapshotItem(i); - } - } - return nodes; - } + var xpe = XMLUtils.__xpe; + if (!xpe) { try { - result = xpe.evaluate(query, element, xpe.createNSResolver(element), XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); - } catch (err) { - throw new Error("selectNodes: query: " + query + ", element: " + element + ", error: " + err); - } - + XMLUtils.__xpe = xpe = new XPathEvaluator(); + } catch (e) {} + } + var result, + nodes = [], + i; + if (!XMLUtils.__xpe) { + if (!document.createExpression) XMLUtils.loadXPathReplacer(); + query = document.createExpression(query, null); + result = query.evaluate(element, 7, null); + nodes = []; for (i = 0; i < result.snapshotLength; i++) { - nodes[i] = result.snapshotItem(i); + if (Element.extend) { + nodes[i] = Element.extend(result.snapshotItem(i)); + } else { + nodes[i] = result.snapshotItem(i); + } } - return nodes; } - }, { - key: "XPathGetSingleNodeText", - - /** - * Selects the first XmlNode that matches the XPath expression and returns the text content of the element - * - * @param element {Element|Document} root element for the search - * @param query {String} XPath query - * @return {String} the joined text content of the found element or null if not appropriate. - * @signature function(element, query) - */ - value: function XPathGetSingleNodeText(element, query) { - var node = XPathSelectSingleNode(element, query); - return XMLUtils.getDomNodeText(node); + + try { + result = xpe.evaluate(query, element, xpe.createNSResolver(element), XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); + } catch (err) { + throw new Error("selectNodes: query: " + query + ", element: " + element + ", error: " + err); } - }, { - key: "getDomNodeText", - value: function getDomNodeText(node) { - var includeCData = arguments[1] === undefined ? false : arguments[1]; - if (!node || !node.nodeType) { - return null; - } + for (i = 0; i < result.snapshotLength; i++) { + nodes[i] = result.snapshotItem(i); + } - switch (node.nodeType) { - case 1: - // NODE_ELEMENT - var i, - a = [], - nodes = node.childNodes, - length = nodes.length; - for (i = 0; i < length; i++) { - a[i] = XMLUtils.getDomNodeText(nodes[i], includeCData); - } - - return a.join(""); - - case 2: - // NODE_ATTRIBUTE - return node.value; - break; - - case 3: - // NODE_TEXT - return node.nodeValue; - break; + return nodes; + }; + + /** + * Selects the first XmlNode that matches the XPath expression and returns the text content of the element + * + * @param element {Element|Document} root element for the search + * @param query {String} XPath query + * @return {String} the joined text content of the found element or null if not appropriate. + * @signature function(element, query) + */ + + XMLUtils.XPathGetSingleNodeText = function XPathGetSingleNodeText(element, query) { + var node = XPathSelectSingleNode(element, query); + return XMLUtils.getDomNodeText(node); + }; - case 4: - // CDATA - if (includeCData) { - return node.nodeValue; - }} + XMLUtils.getDomNodeText = function getDomNodeText(node) { + var includeCData = arguments[1] === undefined ? false : arguments[1]; + if (!node || !node.nodeType) { return null; } - }, { - key: "parseXml", - - /** - * @param xmlStr - * @returns {*} - */ - value: function parseXml(xmlStr) { - - if (typeof window.ActiveXObject != "undefined" && new window.ActiveXObject("MSXML2.DOMDocument.6.0")) { - var xmlDoc = new window.ActiveXObject("MSXML2.DOMDocument.6.0"); - xmlDoc.validateOnParse = false; - xmlDoc.async = false; - xmlDoc.loadXML(xmlStr); - xmlDoc.setProperty("SelectionLanguage", "XPath"); - return xmlDoc; - } else if (typeof window.DOMParser != "undefined") { - return new window.DOMParser().parseFromString(xmlStr, "text/xml"); - } + + switch (node.nodeType) { + case 1: + // NODE_ELEMENT + var i, + a = [], + nodes = node.childNodes, + length = nodes.length; + for (i = 0; i < length; i++) { + a[i] = XMLUtils.getDomNodeText(nodes[i], includeCData); + } + + return a.join(""); + + case 2: + // NODE_ATTRIBUTE + return node.value; + break; + + case 3: + // NODE_TEXT + return node.nodeValue; + break; + + case 4: + // CDATA + if (includeCData) { + return node.nodeValue; + }} + + return null; + }; + + /** + * @param xmlStr + * @returns {*} + */ + + XMLUtils.parseXml = function parseXml(xmlStr) { + + if (typeof window.ActiveXObject != "undefined" && new window.ActiveXObject("MSXML2.DOMDocument.6.0")) { + var xmlDoc = new window.ActiveXObject("MSXML2.DOMDocument.6.0"); + xmlDoc.validateOnParse = false; + xmlDoc.async = false; + xmlDoc.loadXML(xmlStr); + xmlDoc.setProperty("SelectionLanguage", "XPath"); + return xmlDoc; + } else if (typeof window.DOMParser != "undefined") { + return new window.DOMParser().parseFromString(xmlStr, "text/xml"); } - }]); + }; return XMLUtils; })(); \ No newline at end of file diff --git a/core/src/plugins/gui.ajax/res/js/es6/Pydio.es6 b/core/src/plugins/gui.ajax/res/js/es6/Pydio.es6 index 060d754aee..217ea29aee 100644 --- a/core/src/plugins/gui.ajax/res/js/es6/Pydio.es6 +++ b/core/src/plugins/gui.ajax/res/js/es6/Pydio.es6 @@ -75,7 +75,9 @@ class Pydio extends Observable{ } this.observe("registry_loaded", function(){ + // TODO: CAN WE REMOVE THIS? IT IS TRIGGERED TWO TIMES (in PydioUI). this.Controller.loadActionsFromRegistry(this.getXmlRegistry()); + // END this.Registry.refreshExtensionsRegistry(); this.Registry.logXmlUser(false); if(this.user){ diff --git a/core/src/plugins/gui.ajax/res/js/es6/lang/Logger.es6 b/core/src/plugins/gui.ajax/res/js/es6/lang/Logger.es6 index a8b3afd9c4..60ee972234 100644 --- a/core/src/plugins/gui.ajax/res/js/es6/lang/Logger.es6 +++ b/core/src/plugins/gui.ajax/res/js/es6/lang/Logger.es6 @@ -1,15 +1,15 @@ class Logger{ static log(message){ - if(console) console.log(message); + if(window.console) console.log(message); } static error(message){ - if(console) console.error(message); + if(window.console) console.error(message); } static debug(message){ - if(console) console.debug(message); + if(window.console) console.debug(message); } } \ No newline at end of file diff --git a/core/src/plugins/gui.ajax/res/js/es6/model/Controller.es6 b/core/src/plugins/gui.ajax/res/js/es6/model/Controller.es6 index 4b2f3d3823..2c9dd5c350 100644 --- a/core/src/plugins/gui.ajax/res/js/es6/model/Controller.es6 +++ b/core/src/plugins/gui.ajax/res/js/es6/model/Controller.es6 @@ -167,7 +167,7 @@ class Controller extends Observable{ * @returns {*} */ parseXmlMessage(xmlDoc){ - if(console) console.warn("Controller.parseXmlMessage() is deprecated, use PydioApi instead", new Error()); + Logger.log("Controller.parseXmlMessage() is deprecated, use PydioApi instead"); return PydioApi.getClient().parseXmlMessage(xmlDoc); } @@ -178,7 +178,7 @@ class Controller extends Observable{ * @param completeCallback Function Callback to be called on complete */ submitForm(formName, post, completeCallback){ - if(console) console.warn("Controller.submitForm() is deprecated, use PydioApi instead", new Error()); + Logger.log("Controller.submitForm() is deprecated, use PydioApi instead"); return PydioApi.getClient().submitForm(formName, post, completeCallback); } diff --git a/core/src/plugins/gui.ajax/res/js/es6/model/User.es6 b/core/src/plugins/gui.ajax/res/js/es6/model/User.es6 index e533e25cc6..abd0c1de63 100644 --- a/core/src/plugins/gui.ajax/res/js/es6/model/User.es6 +++ b/core/src/plugins/gui.ajax/res/js/es6/model/User.es6 @@ -154,8 +154,8 @@ class User{ this._parsedJSONCache.set(prefName, parsed); return parsed; }catch(e){ - if(console){ - console.log("Error parsing JSON in preferences ("+prefName+"). You should contact system admin and clear user preferences."); + if(window.console){ + Logger.log("Error parsing JSON in preferences ("+prefName+"). You should contact system admin and clear user preferences."); }else{ alert("Error parsing JSON in preferences. You should contact system admin and clear user preferences."); } diff --git a/core/src/plugins/gui.ajax/res/js/ui/prototype/class.AjxpBootstrap.js b/core/src/plugins/gui.ajax/res/js/ui/prototype/class.AjxpBootstrap.js index 84a4529cae..ea09d8616b 100644 --- a/core/src/plugins/gui.ajax/res/js/ui/prototype/class.AjxpBootstrap.js +++ b/core/src/plugins/gui.ajax/res/js/ui/prototype/class.AjxpBootstrap.js @@ -56,7 +56,7 @@ Class.create("AjxpBootstrap", { startedFromOpener = true; } }catch(e){ - if(console && console.log) console.log(e); + if(window.console && console.log) console.log(e); } if(!startedFromOpener){ this.loadBootConfig(); @@ -77,10 +77,10 @@ Class.create("AjxpBootstrap", { }.bind(this)); document.observe("ajaxplorer:actions_loaded", function(){ if(!this.parameters.get("SELECTOR_DATA") && pydio.getController().actions.get("ext_select")){ - if(pydio.getController().actions.delete){ - pydio.getController().actions.delete("ext_select"); - }else{ + if(pydio.getController().actions._object){ pydio.getController().actions.unset("ext_select"); + }else{ + pydio.getController().actions.delete("ext_select"); } pydio.getController().fireContextChange(); pydio.getController().fireSelectionChange(); diff --git a/core/src/plugins/gui.ajax/res/js/ui/prototype/class.FilesList.js b/core/src/plugins/gui.ajax/res/js/ui/prototype/class.FilesList.js index 3d778f15a2..bdce997471 100644 --- a/core/src/plugins/gui.ajax/res/js/ui/prototype/class.FilesList.js +++ b/core/src/plugins/gui.ajax/res/js/ui/prototype/class.FilesList.js @@ -1350,7 +1350,7 @@ Class.create("FilesList", SelectableElements, { new Effect.RowFade(item, {afterFinish:function(){ try{ item.remove(); - }catch(e){if(console) console.log(e);} + }catch(e){if(window.console) console.log(e);} delete item; this.initRowsBuffered(); }.bind(this), duration:0.2}); diff --git a/core/src/plugins/gui.ajax/res/js/ui/prototype/class.InfoPanel.js b/core/src/plugins/gui.ajax/res/js/ui/prototype/class.InfoPanel.js index d78dd48e19..c67e01d874 100644 --- a/core/src/plugins/gui.ajax/res/js/ui/prototype/class.InfoPanel.js +++ b/core/src/plugins/gui.ajax/res/js/ui/prototype/class.InfoPanel.js @@ -498,7 +498,7 @@ Class.create("InfoPanel", AjxpPane, { try{ var modifierFunc = eval(tModifier); }catch(e){ - if(console) console.error('InfoPanel: trying to eval function ' + tModifier + ' failed!', e); + if(window.console) console.error('InfoPanel: trying to eval function ' + tModifier + ' failed!', e); } if(modifierFunc) modifierFunc(cContainer, fileNode); }); diff --git a/core/src/plugins/gui.ajax/res/js/ui/prototype/class.PydioUI.js b/core/src/plugins/gui.ajax/res/js/ui/prototype/class.PydioUI.js index 2fb7417778..bb132a7426 100644 --- a/core/src/plugins/gui.ajax/res/js/ui/prototype/class.PydioUI.js +++ b/core/src/plugins/gui.ajax/res/js/ui/prototype/class.PydioUI.js @@ -147,7 +147,7 @@ Class.create("PydioUI", { if(pydioObject.getXmlRegistry()){ pydioObject.Controller.loadActionsFromRegistry(pydioObject.getXmlRegistry()); } - document.observe("ajaxplorer:registry_loaded", function(event){ + pydioObject.observe("registry_loaded", function(event){ if(Prototype.Browser.IE) ResourcesManager.loadAutoLoadResources(event.memo); pydioObject.Controller.loadActionsFromRegistry(event.memo); }.bind(this) ); @@ -432,7 +432,7 @@ Class.create("PydioUI", { try{ this.setGuiComponentConfig(nodes[i]); }catch(e){ - console.error("Error while setting ComponentConfig", e); + if(window.console) console.error("Error while setting ComponentConfig", e); } } var element = $(window.ajxpBootstrap.parameters.get("MAIN_ELEMENT")); diff --git a/core/src/plugins/gui.ajax/res/js/vendor/es6/browser-polyfill.js b/core/src/plugins/gui.ajax/res/js/vendor/es6/browser-polyfill.js index 1c0ff8ed2b..19a52864da 100644 --- a/core/src/plugins/gui.ajax/res/js/vendor/es6/browser-polyfill.js +++ b/core/src/plugins/gui.ajax/res/js/vendor/es6/browser-polyfill.js @@ -1,5 +1,4 @@ -(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;oindex){value=O[index++];if(value!=value)return true}else for(;length>index;index++)if(IS_INCLUDES||index in O){if(O[index]===el)return IS_INCLUDES||index}return!IS_INCLUDES&&-1}}},{"./$":16}],3:[function(require,module,exports){"use strict";var $=require("./$"),ctx=require("./$.ctx");module.exports=function(TYPE){var IS_MAP=TYPE==1,IS_FILTER=TYPE==2,IS_SOME=TYPE==3,IS_EVERY=TYPE==4,IS_FIND_INDEX=TYPE==6,NO_HOLES=TYPE==5||IS_FIND_INDEX;return function(callbackfn){var O=Object($.assertDefined(this)),self=$.ES5Object(O),f=ctx(callbackfn,arguments[1],3),length=$.toLength(self.length),index=0,result=IS_MAP?Array(length):IS_FILTER?[]:undefined,val,res;for(;length>index;index++)if(NO_HOLES||index in self){val=self[index];res=f(val,index,O);if(TYPE){if(IS_MAP)result[index]=res;else if(res)switch(TYPE){case 3:return true;case 5:return val;case 6:return index;case 2:result.push(val)}else if(IS_EVERY)return false}}return IS_FIND_INDEX?-1:IS_SOME||IS_EVERY?IS_EVERY:result}}},{"./$":16,"./$.ctx":10}],4:[function(require,module,exports){var $=require("./$");function assert(condition,msg1,msg2){if(!condition)throw TypeError(msg2?msg1+msg2:msg1)}assert.def=$.assertDefined;assert.fn=function(it){if(!$.isFunction(it))throw TypeError(it+" is not a function!");return it};assert.obj=function(it){if(!$.isObject(it))throw TypeError(it+" is not an object!");return it};assert.inst=function(it,Constructor,name){if(!(it instanceof Constructor))throw TypeError(name+": use the 'new' operator!");return it};module.exports=assert},{"./$":16}],5:[function(require,module,exports){var $=require("./$");module.exports=Object.assign||function assign(target,source){var T=Object($.assertDefined(target)),l=arguments.length,i=1;while(l>i){var S=$.ES5Object(arguments[i++]),keys=$.getKeys(S),length=keys.length,j=0,key;while(length>j)T[key=keys[j++]]=S[key]}return T}},{"./$":16}],6:[function(require,module,exports){var $=require("./$"),TAG=require("./$.wks")("toStringTag"),toString={}.toString;function cof(it){return toString.call(it).slice(8,-1)}cof.classof=function(it){var O,T;return it==undefined?it===undefined?"Undefined":"Null":typeof(T=(O=Object(it))[TAG])=="string"?T:cof(O)};cof.set=function(it,tag,stat){if(it&&!$.has(it=stat?it:it.prototype,TAG))$.hide(it,TAG,tag)};module.exports=cof},{"./$":16,"./$.wks":27}],7:[function(require,module,exports){"use strict";var $=require("./$"),ctx=require("./$.ctx"),safe=require("./$.uid").safe,assert=require("./$.assert"),$iter=require("./$.iter"),has=$.has,set=$.set,isObject=$.isObject,hide=$.hide,step=$iter.step,isFrozen=Object.isFrozen||$.core.Object.isFrozen,ID=safe("id"),O1=safe("O1"),LAST=safe("last"),FIRST=safe("first"),ITER=safe("iter"),SIZE=$.DESC?safe("size"):"size",id=0;function fastKey(it,create){if(!isObject(it))return(typeof it=="string"?"S":"P")+it;if(isFrozen(it))return"F";if(!has(it,ID)){if(!create)return"E";hide(it,ID,++id)}return"O"+it[ID]}function getEntry(that,key){var index=fastKey(key),entry;if(index!="F")return that[O1][index];for(entry=that[FIRST];entry;entry=entry.n){if(entry.k==key)return entry}}module.exports={getConstructor:function(NAME,IS_MAP,ADDER){function C(iterable){var that=assert.inst(this,C,NAME);set(that,O1,$.create(null));set(that,SIZE,0);set(that,LAST,undefined);set(that,FIRST,undefined);if(iterable!=undefined)$iter.forOf(iterable,IS_MAP,that[ADDER],that)}$.mix(C.prototype,{clear:function clear(){for(var that=this,data=that[O1],entry=that[FIRST];entry;entry=entry.n){entry.r=true;if(entry.p)entry.p=entry.p.n=undefined;delete data[entry.i]}that[FIRST]=that[LAST]=undefined;that[SIZE]=0},"delete":function(key){var that=this,entry=getEntry(that,key);if(entry){var next=entry.n,prev=entry.p;delete that[O1][entry.i];entry.r=true;if(prev)prev.n=next;if(next)next.p=prev;if(that[FIRST]==entry)that[FIRST]=next;if(that[LAST]==entry)that[LAST]=prev;that[SIZE]--}return!!entry},forEach:function forEach(callbackfn){var f=ctx(callbackfn,arguments[1],3),entry;while(entry=entry?entry.n:this[FIRST]){f(entry.v,entry.k,this);while(entry&&entry.r)entry=entry.p}},has:function has(key){return!!getEntry(this,key)}});if($.DESC)$.setDesc(C.prototype,"size",{get:function(){return assert.def(this[SIZE])}});return C},def:function(that,key,value){var entry=getEntry(that,key),prev,index;if(entry){entry.v=value}else{that[LAST]=entry={i:index=fastKey(key,true),k:key,v:value,p:prev=that[LAST],n:undefined,r:false};if(!that[FIRST])that[FIRST]=entry;if(prev)prev.n=entry;that[SIZE]++;if(index!="F")that[O1][index]=entry}return that},getEntry:getEntry,getIterConstructor:function(){return function(iterated,kind){set(this,ITER,{o:iterated,k:kind})}},next:function(){var iter=this[ITER],kind=iter.k,entry=iter.l;while(entry&&entry.r)entry=entry.p;if(!iter.o||!(iter.l=entry=entry?entry.n:iter.o[FIRST])){iter.o=undefined;return step(1)}if(kind=="key")return step(0,entry.k);if(kind=="value")return step(0,entry.v);return step(0,[entry.k,entry.v])}}},{"./$":16,"./$.assert":4,"./$.ctx":10,"./$.iter":15,"./$.uid":25}],8:[function(require,module,exports){"use strict";var $=require("./$"),safe=require("./$.uid").safe,assert=require("./$.assert"),forOf=require("./$.iter").forOf,_has=$.has,isObject=$.isObject,hide=$.hide,isFrozen=Object.isFrozen||$.core.Object.isFrozen,id=0,ID=safe("id"),WEAK=safe("weak"),LEAK=safe("leak"),method=require("./$.array-methods"),find=method(5),findIndex=method(6);function findFrozen(store,key){return find.call(store.array,function(it){return it[0]===key})}function leakStore(that){return that[LEAK]||hide(that,LEAK,{array:[],get:function(key){var entry=findFrozen(this,key);if(entry)return entry[1]},has:function(key){return!!findFrozen(this,key)},set:function(key,value){var entry=findFrozen(this,key);if(entry)entry[1]=value;else this.array.push([key,value])},"delete":function(key){var index=findIndex.call(this.array,function(it){return it[0]===key});if(~index)this.array.splice(index,1);return!!~index}})[LEAK]}module.exports={getConstructor:function(NAME,IS_MAP,ADDER){function C(iterable){$.set(assert.inst(this,C,NAME),ID,id++);if(iterable!=undefined)forOf(iterable,IS_MAP,this[ADDER],this)}$.mix(C.prototype,{"delete":function(key){if(!isObject(key))return false;if(isFrozen(key))return leakStore(this)["delete"](key);return _has(key,WEAK)&&_has(key[WEAK],this[ID])&&delete key[WEAK][this[ID]]},has:function has(key){if(!isObject(key))return false;if(isFrozen(key))return leakStore(this).has(key);return _has(key,WEAK)&&_has(key[WEAK],this[ID])}});return C},def:function(that,key,value){if(isFrozen(assert.obj(key))){leakStore(that).set(key,value)}else{_has(key,WEAK)||hide(key,WEAK,{});key[WEAK][that[ID]]=value}return that},leakStore:leakStore,WEAK:WEAK,ID:ID}},{"./$":16,"./$.array-methods":3,"./$.assert":4,"./$.iter":15,"./$.uid":25}],9:[function(require,module,exports){"use strict";var $=require("./$"),$def=require("./$.def"),$iter=require("./$.iter"),assertInstance=require("./$.assert").inst;module.exports=function(NAME,methods,common,IS_MAP,isWeak){var Base=$.g[NAME],C=Base,ADDER=IS_MAP?"set":"add",proto=C&&C.prototype,O={};function fixMethod(KEY,CHAIN){var method=proto[KEY];if($.FW)proto[KEY]=function(a,b){var result=method.call(this,a===0?0:a,b);return CHAIN?this:result}}if(!$.isFunction(C)||!(isWeak||!$iter.BUGGY&&proto.forEach&&proto.entries)){C=common.getConstructor(NAME,IS_MAP,ADDER);$.mix(C.prototype,methods)}else{var inst=new C,chain=inst[ADDER](isWeak?{}:-0,1),buggyZero;if(!require("./$.iter-detect")(function(iter){new C(iter)})){C=function(iterable){assertInstance(this,C,NAME);var that=new Base;if(iterable!=undefined)$iter.forOf(iterable,IS_MAP,that[ADDER],that);return that};C.prototype=proto;if($.FW)proto.constructor=C}isWeak||inst.forEach(function(val,key){buggyZero=1/key===-Infinity});if(buggyZero){fixMethod("delete");fixMethod("has");IS_MAP&&fixMethod("get")}if(buggyZero||chain!==inst)fixMethod(ADDER,true)}require("./$.cof").set(C,NAME);require("./$.species")(C);O[NAME]=C;$def($def.G+$def.W+$def.F*(C!=Base),O);if(!isWeak)$iter.std(C,NAME,common.getIterConstructor(),common.next,IS_MAP?"key+value":"value",!IS_MAP,true);return C}},{"./$":16,"./$.assert":4,"./$.cof":6,"./$.def":11,"./$.iter":15,"./$.iter-detect":14,"./$.species":22}],10:[function(require,module,exports){var assertFunction=require("./$.assert").fn;module.exports=function(fn,that,length){assertFunction(fn);if(~length&&that===undefined)return fn;switch(length){case 1:return function(a){return fn.call(that,a)};case 2:return function(a,b){return fn.call(that,a,b)};case 3:return function(a,b,c){return fn.call(that,a,b,c)}}return function(){return fn.apply(that,arguments)}}},{"./$.assert":4}],11:[function(require,module,exports){var $=require("./$"),global=$.g,core=$.core,isFunction=$.isFunction;function ctx(fn,that){return function(){return fn.apply(that,arguments)}}global.core=core;$def.F=1;$def.G=2;$def.S=4;$def.P=8;$def.B=16;$def.W=32;function $def(type,name,source){var key,own,out,exp,isGlobal=type&$def.G,target=isGlobal?global:type&$def.S?global[name]:(global[name]||{}).prototype,exports=isGlobal?core:core[name]||(core[name]={});if(isGlobal)source=name;for(key in source){own=!(type&$def.F)&&target&&key in target;out=(own?target:source)[key];if(type&$def.B&&own)exp=ctx(out,global);else exp=type&$def.P&&isFunction(out)?ctx(Function.call,out):out;if(target&&!own){if(isGlobal)target[key]=out;else delete target[key]&&$.hide(target,key,out)}if(exports[key]!=out)$.hide(exports,key,exp)}}module.exports=$def},{"./$":16}],12:[function(require,module,exports){module.exports=function($){$.FW=true;$.path=$.g;return $}},{}],13:[function(require,module,exports){module.exports=function(fn,args,that){var un=that===undefined;switch(args.length){case 0:return un?fn():fn.call(that);case 1:return un?fn(args[0]):fn.call(that,args[0]);case 2:return un?fn(args[0],args[1]):fn.call(that,args[0],args[1]);case 3:return un?fn(args[0],args[1],args[2]):fn.call(that,args[0],args[1],args[2]);case 4:return un?fn(args[0],args[1],args[2],args[3]):fn.call(that,args[0],args[1],args[2],args[3]);case 5:return un?fn(args[0],args[1],args[2],args[3],args[4]):fn.call(that,args[0],args[1],args[2],args[3],args[4])}return fn.apply(that,args)}},{}],14:[function(require,module,exports){var SYMBOL_ITERATOR=require("./$.wks")("iterator"),SAFE_CLOSING=false;try{var riter=[7][SYMBOL_ITERATOR]();riter["return"]=function(){SAFE_CLOSING=true};Array.from(riter,function(){throw 2})}catch(e){}module.exports=function(exec){if(!SAFE_CLOSING)return false;var safe=false;try{var arr=[7],iter=arr[SYMBOL_ITERATOR]();iter.next=function(){safe=true};arr[SYMBOL_ITERATOR]=function(){return iter};exec(arr)}catch(e){}return safe}},{"./$.wks":27}],15:[function(require,module,exports){"use strict";var $=require("./$"),ctx=require("./$.ctx"),cof=require("./$.cof"),$def=require("./$.def"),assertObject=require("./$.assert").obj,SYMBOL_ITERATOR=require("./$.wks")("iterator"),FF_ITERATOR="@@iterator",Iterators={},IteratorPrototype={};var BUGGY="keys"in[]&&!("next"in[].keys());setIterator(IteratorPrototype,$.that);function setIterator(O,value){$.hide(O,SYMBOL_ITERATOR,value);if(FF_ITERATOR in[])$.hide(O,FF_ITERATOR,value)}function defineIterator(Constructor,NAME,value,DEFAULT){var proto=Constructor.prototype,iter=proto[SYMBOL_ITERATOR]||proto[FF_ITERATOR]||DEFAULT&&proto[DEFAULT]||value;if($.FW)setIterator(proto,iter);if(iter!==value){var iterProto=$.getProto(iter.call(new Constructor));cof.set(iterProto,NAME+" Iterator",true);if($.FW)$.has(proto,FF_ITERATOR)&&setIterator(iterProto,$.that)}Iterators[NAME]=iter;Iterators[NAME+" Iterator"]=$.that;return iter}function getIterator(it){var Symbol=$.g.Symbol,ext=it[Symbol&&Symbol.iterator||FF_ITERATOR],getIter=ext||it[SYMBOL_ITERATOR]||Iterators[cof.classof(it)];return assertObject(getIter.call(it))}function closeIterator(iterator){var ret=iterator["return"];if(ret!==undefined)assertObject(ret.call(iterator))}function stepCall(iterator,fn,value,entries){try{return entries?fn(assertObject(value)[0],value[1]):fn(value)}catch(e){closeIterator(iterator);throw e}}var $iter=module.exports={BUGGY:BUGGY,Iterators:Iterators,prototype:IteratorPrototype,step:function(done,value){return{value:value,done:!!done}},stepCall:stepCall,close:closeIterator,is:function(it){var O=Object(it),Symbol=$.g.Symbol,SYM=Symbol&&Symbol.iterator||FF_ITERATOR;return SYM in O||SYMBOL_ITERATOR in O||$.has(Iterators,cof.classof(O))},get:getIterator,set:setIterator,create:function(Constructor,NAME,next,proto){Constructor.prototype=$.create(proto||$iter.prototype,{next:$.desc(1,next)});cof.set(Constructor,NAME+" Iterator")},define:defineIterator,std:function(Base,NAME,Constructor,next,DEFAULT,IS_SET,FORCE){function createIter(kind){return function(){return new Constructor(this,kind)}}$iter.create(Constructor,NAME,next);var entries=createIter("key+value"),values=createIter("value"),proto=Base.prototype,methods,key;if(DEFAULT=="value")values=defineIterator(Base,NAME,values,"values");else entries=defineIterator(Base,NAME,entries,"entries");if(DEFAULT){methods={entries:entries,keys:IS_SET?values:createIter("key"),values:values};$def($def.P+$def.F*BUGGY,NAME,methods);if(FORCE)for(key in methods){if(!(key in proto))$.hide(proto,key,methods[key])}}},forOf:function(iterable,entries,fn,that){var iterator=getIterator(iterable),f=ctx(fn,that,entries?2:1),step;while(!(step=iterator.next()).done){if(stepCall(iterator,f,step.value,entries)===false){return closeIterator(iterator)}}}}},{"./$":16,"./$.assert":4,"./$.cof":6,"./$.ctx":10,"./$.def":11,"./$.wks":27}],16:[function(require,module,exports){"use strict";var global=typeof self!="undefined"?self:Function("return this")(),core={},defineProperty=Object.defineProperty,hasOwnProperty={}.hasOwnProperty,ceil=Math.ceil,floor=Math.floor,max=Math.max,min=Math.min;var DESC=!!function(){try{return defineProperty({},"a",{get:function(){return 2}}).a==2}catch(e){}}();var hide=createDefiner(1);function toInteger(it){return isNaN(it=+it)?0:(it>0?floor:ceil)(it)}function desc(bitmap,value){return{enumerable:!(bitmap&1),configurable:!(bitmap&2),writable:!(bitmap&4),value:value}}function simpleSet(object,key,value){object[key]=value;return object}function createDefiner(bitmap){return DESC?function(object,key,value){return $.setDesc(object,key,desc(bitmap,value))}:simpleSet}function isObject(it){return it!==null&&(typeof it=="object"||typeof it=="function")}function isFunction(it){return typeof it=="function"}function assertDefined(it){if(it==undefined)throw TypeError("Can't call method on "+it);return it}var $=module.exports=require("./$.fw")({g:global,core:core,html:global.document&&document.documentElement,isObject:isObject,isFunction:isFunction,it:function(it){return it},that:function(){return this},toInteger:toInteger,toLength:function(it){return it>0?min(toInteger(it),9007199254740991):0},toIndex:function(index,length){index=toInteger(index);return index<0?max(index+length,0):min(index,length)},has:function(it,key){return hasOwnProperty.call(it,key)},create:Object.create,getProto:Object.getPrototypeOf,DESC:DESC,desc:desc,getDesc:Object.getOwnPropertyDescriptor,setDesc:defineProperty,getKeys:Object.keys,getNames:Object.getOwnPropertyNames,getSymbols:Object.getOwnPropertySymbols,assertDefined:assertDefined,ES5Object:Object,toObject:function(it){return $.ES5Object(assertDefined(it))},hide:hide,def:createDefiner(0),set:global.Symbol?simpleSet:hide,mix:function(target,src){for(var key in src)hide(target,key,src[key]);return target},each:[].forEach});if(typeof __e!="undefined")__e=core;if(typeof __g!="undefined")__g=global},{"./$.fw":12}],17:[function(require,module,exports){var $=require("./$");module.exports=function(object,el){var O=$.toObject(object),keys=$.getKeys(O),length=keys.length,index=0,key;while(length>index)if(O[key=keys[index++]]===el)return key}},{"./$":16}],18:[function(require,module,exports){var $=require("./$"),assertObject=require("./$.assert").obj;module.exports=function ownKeys(it){assertObject(it);return $.getSymbols?$.getNames(it).concat($.getSymbols(it)):$.getNames(it)}},{"./$":16,"./$.assert":4}],19:[function(require,module,exports){"use strict";var $=require("./$"),invoke=require("./$.invoke"),assertFunction=require("./$.assert").fn;module.exports=function(){var fn=assertFunction(this),length=arguments.length,pargs=Array(length),i=0,_=$.path._,holder=false;while(length>i)if((pargs[i]=arguments[i++])===_)holder=true;return function(){var that=this,_length=arguments.length,j=0,k=0,args;if(!holder&&!_length)return invoke(fn,pargs,that);args=pargs.slice();if(holder)for(;length>j;j++)if(args[j]===_)args[j]=arguments[k++];while(_length>k)args.push(arguments[k++]);return invoke(fn,args,that)}}},{"./$":16,"./$.assert":4,"./$.invoke":13}],20:[function(require,module,exports){"use strict";module.exports=function(regExp,replace,isStatic){var replacer=replace===Object(replace)?function(part){return replace[part]}:replace;return function(it){return String(isStatic?it:this).replace(regExp,replacer)}}},{}],21:[function(require,module,exports){var $=require("./$"),assert=require("./$.assert");function check(O,proto){assert.obj(O);assert(proto===null||$.isObject(proto),proto,": can't set as prototype!")}module.exports={set:Object.setPrototypeOf||("__proto__"in{}?function(buggy,set){try{set=require("./$.ctx")(Function.call,$.getDesc(Object.prototype,"__proto__").set,2);set({},[])}catch(e){buggy=true}return function setPrototypeOf(O,proto){check(O,proto);if(buggy)O.__proto__=proto;else set(O,proto);return O}}():undefined),check:check}},{"./$":16,"./$.assert":4,"./$.ctx":10}],22:[function(require,module,exports){var $=require("./$");module.exports=function(C){if($.DESC&&$.FW)$.setDesc(C,require("./$.wks")("species"),{configurable:true,get:$.that})}},{"./$":16,"./$.wks":27}],23:[function(require,module,exports){"use strict";var $=require("./$");module.exports=function(TO_STRING){return function(pos){var s=String($.assertDefined(this)),i=$.toInteger(pos),l=s.length,a,b;if(i<0||i>=l)return TO_STRING?"":undefined;a=s.charCodeAt(i);return a<55296||a>56319||i+1===l||(b=s.charCodeAt(i+1))<56320||b>57343?TO_STRING?s.charAt(i):a:TO_STRING?s.slice(i,i+2):(a-55296<<10)+(b-56320)+65536}}},{"./$":16}],24:[function(require,module,exports){"use strict";var $=require("./$"),ctx=require("./$.ctx"),cof=require("./$.cof"),invoke=require("./$.invoke"),global=$.g,isFunction=$.isFunction,html=$.html,document=global.document,process=global.process,setTask=global.setImmediate,clearTask=global.clearImmediate,postMessage=global.postMessage,addEventListener=global.addEventListener,MessageChannel=global.MessageChannel,counter=0,queue={},ONREADYSTATECHANGE="onreadystatechange",defer,channel,port;function run(){var id=+this;if($.has(queue,id)){var fn=queue[id];delete queue[id];fn()}}function listner(event){run.call(event.data)}if(!isFunction(setTask)||!isFunction(clearTask)){setTask=function(fn){var args=[],i=1;while(arguments.length>i)args.push(arguments[i++]);queue[++counter]=function(){invoke(isFunction(fn)?fn:Function(fn),args)};defer(counter);return counter};clearTask=function(id){delete queue[id]};if(cof(process)=="process"){defer=function(id){process.nextTick(ctx(run,id,1))}}else if(addEventListener&&isFunction(postMessage)&&!global.importScripts){defer=function(id){postMessage(id,"*")};addEventListener("message",listner,false)}else if(isFunction(MessageChannel)){channel=new MessageChannel;port=channel.port2;channel.port1.onmessage=listner;defer=ctx(port.postMessage,port,1)}else if(document&&ONREADYSTATECHANGE in document.createElement("script")){defer=function(id){html.appendChild(document.createElement("script"))[ONREADYSTATECHANGE]=function(){html.removeChild(this);run.call(id)}}}else{defer=function(id){setTimeout(ctx(run,id,1),0)}}}module.exports={set:setTask,clear:clearTask}},{"./$":16,"./$.cof":6,"./$.ctx":10,"./$.invoke":13}],25:[function(require,module,exports){var sid=0;function uid(key){return"Symbol("+key+")_"+(++sid+Math.random()).toString(36)}uid.safe=require("./$").g.Symbol||uid;module.exports=uid},{"./$":16}],26:[function(require,module,exports){var $=require("./$"),UNSCOPABLES=require("./$.wks")("unscopables");if($.FW&&!(UNSCOPABLES in[]))$.hide(Array.prototype,UNSCOPABLES,{});module.exports=function(key){if($.FW)[][UNSCOPABLES][key]=true}},{"./$":16,"./$.wks":27}],27:[function(require,module,exports){var global=require("./$").g,store={};module.exports=function(name){return store[name]||(store[name]=global.Symbol&&global.Symbol[name]||require("./$.uid").safe("Symbol."+name))}},{"./$":16,"./$.uid":25}],28:[function(require,module,exports){var $=require("./$"),cof=require("./$.cof"),$def=require("./$.def"),invoke=require("./$.invoke"),arrayMethod=require("./$.array-methods"),IE_PROTO=require("./$.uid").safe("__proto__"),assert=require("./$.assert"),assertObject=assert.obj,ObjectProto=Object.prototype,A=[],slice=A.slice,indexOf=A.indexOf,classof=cof.classof,defineProperties=Object.defineProperties,has=$.has,defineProperty=$.setDesc,getOwnDescriptor=$.getDesc,isFunction=$.isFunction,toObject=$.toObject,toLength=$.toLength,IE8_DOM_DEFINE=false;if(!$.DESC){try{IE8_DOM_DEFINE=defineProperty(document.createElement("div"),"x",{get:function(){return 8}}).x==8}catch(e){}$.setDesc=function(O,P,Attributes){if(IE8_DOM_DEFINE)try{return defineProperty(O,P,Attributes)}catch(e){}if("get"in Attributes||"set"in Attributes)throw TypeError("Accessors not supported!");if("value"in Attributes)assertObject(O)[P]=Attributes.value;return O};$.getDesc=function(O,P){if(IE8_DOM_DEFINE)try{return getOwnDescriptor(O,P)}catch(e){}if(has(O,P))return $.desc(!ObjectProto.propertyIsEnumerable.call(O,P),O[P])};defineProperties=function(O,Properties){assertObject(O);var keys=$.getKeys(Properties),length=keys.length,i=0,P;while(length>i)$.setDesc(O,P=keys[i++],Properties[P]);return O}}$def($def.S+$def.F*!$.DESC,"Object",{getOwnPropertyDescriptor:$.getDesc,defineProperty:$.setDesc,defineProperties:defineProperties});var keys1=("constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,"+"toLocaleString,toString,valueOf").split(","),keys2=keys1.concat("length","prototype"),keysLen1=keys1.length;var createDict=function(){var iframe=document.createElement("iframe"),i=keysLen1,gt=">",iframeDocument;iframe.style.display="none";$.html.appendChild(iframe);iframe.src="javascript:";iframeDocument=iframe.contentWindow.document;iframeDocument.open();iframeDocument.write("