diff --git a/UI/WebServerResources/js/Contacts.js b/UI/WebServerResources/js/Contacts.js index 917f074fe..f6207b0dc 100644 --- a/UI/WebServerResources/js/Contacts.js +++ b/UI/WebServerResources/js/Contacts.js @@ -1,2 +1,2 @@ -!function(){"use strict";function a(a,h){a.state("app",{url:"/addressbooks",abstract:!0,views:{addressbooks:{templateUrl:"UIxContactFoldersView",controller:"AddressBooksController",controllerAs:"app"}},resolve:{stateAddressbooks:b}}).state("app.addressbook",{url:"/:addressbookId",views:{addressbook:{templateUrl:"addressbook",controller:"AddressBookController",controllerAs:"addressbook"}},resolve:{stateAddressbook:c}}).state("app.addressbook.new",{url:"/{contactType:(?:card|list)}/new",views:{card:{templateUrl:"UIxContactEditorTemplate",controller:"CardController",controllerAs:"editor"}},resolve:{stateCard:d}}).state("app.addressbook.card",{url:"/:cardId",abstract:!0,views:{card:{template:""}},resolve:{stateCard:e},onEnter:f,onExit:g}).state("app.addressbook.card.view",{url:"/view",views:{"card@app.addressbook":{templateUrl:"UIxContactViewTemplate",controller:"CardController",controllerAs:"editor"}}}).state("app.addressbook.card.editor",{url:"/edit",views:{"card@app.addressbook":{templateUrl:"UIxContactEditorTemplate",controller:"CardController",controllerAs:"editor"}}}),h.otherwise("/addressbooks/personal")}function b(a){return a.$findAll(window.contactFolders)}function c(a,b,c,d){var e=_.find(d.$findAll(),function(a){return a.id==c.addressbookId});return e?(delete e.selectedCard,e.$reload(),e):a.reject("Addressbook "+c.addressbookId+" not found")}function d(a,b,c){var d="v"+a.contactType,e=new c({pid:a.addressbookId,c_component:d});return b.selectedCard=!0,e}function e(a,b,c){var d;if(d=_.find(c.$cards,function(a){return a.id==b.cardId}))return d.$reload();a.go("app.addressbook")}function f(a,b){b.selectedCard=a.cardId}function g(a){delete c.selectedCard}function h(a,b,c){a.$on("$stateChangeError",function(a,d,e,f,g,h){b.error(h),c.go("app.addressbook",{addressbookId:"personal"})}),a.$on("$routeChangeError",function(a,c,d,e){b.error(a,c,d,e)})}angular.module("SOGo.ContactsUI",["ngCookies","ui.router","angularFileUpload","ck","SOGo.Common","SOGo.PreferencesUI","SOGo.MailerUI"]).config(a).run(h),a.$inject=["$stateProvider","$urlRouterProvider"],b.$inject=["AddressBook"],c.$inject=["$q","$state","$stateParams","AddressBook"],d.$inject=["$stateParams","stateAddressbook","Card"],e.$inject=["$state","$stateParams","stateAddressbook"],f.$inject=["$stateParams","stateAddressbook"],g.$inject=["stateAddressbook"],h.$inject=["$rootScope","$log","$state"]}(),function(){"use strict";function a(a,b,c,d,e,f,g,h,i,j,k,m,n,o,p,q){function r(a){a.push(o.createHotkey({key:l("hotkey_search"),description:l("Search"),callback:H})),a.push(o.createHotkey({key:l("key_create_card"),description:l("Create a new address book card"),callback:angular.bind(M,u,"card")})),a.push(o.createHotkey({key:l("key_create_list"),description:l("Create a new list"),callback:angular.bind(M,u,"list")})),a.push(o.createHotkey({key:"space",description:l("Toggle item"),callback:t})),a.push(o.createHotkey({key:"shift+space",description:l("Toggle range of items"),callback:t})),a.push(o.createHotkey({key:"up",description:l("View next item"),callback:w})),a.push(o.createHotkey({key:"down",description:l("View previous item"),callback:x})),a.push(o.createHotkey({key:"shift+up",description:l("Add next item to selection"),callback:y})),a.push(o.createHotkey({key:"shift+down",description:l("Add previous item to selection"),callback:z})),a.push(o.createHotkey({key:"backspace",description:l("Delete selected card or address book"),callback:A})),_.forEach(a,function(a){o.registerHotkey(a)})}function s(a){d.go("app.addressbook.card.view",{cardId:a.id})}function t(a,b){var c,d,e,f=M.selectedFolder;if(b||(b=f.$selectedCard()),b.selected=!b.selected,M.mode.multiple+=b.selected?1:-1,a.shiftKey&&f.$selectedCount()>1){for(c=f.idsMap[b.id],d=c-2;d>=0&&!f.$cards[d].selected;)d--;if(d<0)for(d=c+2;d=0&&d0&&M.selectedFolder.$topIndex--):(b=M.selectedFolder.$cards.length()-1,M.selectedFolder.$topIndex=M.selectedFolder.getLength()),b>-1&&s(M.selectedFolder.$cards[b]),a.preventDefault(),b}function x(a){var b=M.selectedFolder.$selectedCardIndex();return angular.isDefined(b)?(b++,M.selectedFolder.$topIndex=0&&t(a,M.selectedFolder.$cards[b]))}function z(a){var b;M.selectedFolder.hasSelectedCard()&&(b=x(a),b>=0&&t(a,M.selectedFolder.$cards[b]))}function A(a){var b=M.selectedFolder.$selectedCards();_.size(b)>0&&m.confirm(l("Warning"),l("Are you sure you want to delete the selected contacts?"),{ok:l("Delete")}).then(function(){M.selectedFolder.$deleteCards(b).then(function(){M.mode.multiple=0,M.selectedFolder.selectedCard||d.go("app.addressbook")})}),a.preventDefault()}function B(a,b){var c,e,f,h,i,j,k;c=M.selectedFolder,i=!1,e=c.$selectedCards(),f=_.filter(e,function(a){return a.$isCard()}),f.length!=e.length&&g.show(g.simple().content(l("Lists can't be moved or copied.")).position("top right").hideDelay(2e3)),f.length&&("copy"==a?(j=c.$copyCards(f,b),k=l("%{0} card(s) copied",f.length)):(j=c.$moveCards(f,b),k=l("%{0} card(s) moved",f.length),h=_.map(f,"id"),i=c.selectedCard&&h.indexOf(c.selectedCard)>=0),j.then(function(){i&&d.go("app.addressbook"),g.show(g.simple().content(k).position("top right").hideDelay(2e3))}))}function C(a){B("copy",a)}function D(a){B("move",a)}function E(){_.forEach(M.selectedFolder.$cards,function(a){a.selected=!0}),M.mode.multiple=M.selectedFolder.$cards.length}function F(a){M.selectedFolder.$filter("",{sort:a})}function G(a){return j.$query.sort==a}function H(){M.mode.search=!0,k("search")}function I(){M.mode.search=!1,M.selectedFolder.$filter("")}function J(a,b,c){h.$findAll().then(function(d){var e=_.find(d,function(a){if(0===a.id)return a});e.$getMailboxes().then(function(d){e.$newMessage().then(function(d){d.editable[c]=b,f.show({parent:angular.element(document.body),targetEvent:a,clickOutsideToClose:!1,escapeToClose:!1,templateUrl:"../Mail/UIxMailEditor",controller:"MessageEditorController",controllerAs:"editor",locals:{stateAccount:e,stateMessage:d}})})})})}function K(a,b,c){var d=[c+" <"+b+">"];M.newMessage(a,d,"to"),a.stopPropagation(),a.preventDefault()}function L(a,c){var d=_.filter(M.selectedFolder.$cards,function(a){return a.selected}),e=[],f=[];_.forEach(d,function(a){a.$isList({expandable:!0})?angular.isDefined(a.refs)&&a.refs.length?_.forEach(a.refs,function(a){a.email.length&&f.push(a.$shortFormat())}):e.push(a.$reload().then(function(a){_.forEach(a.refs,function(a){a.email.length&&f.push(a.$shortFormat())})})):a.c_mail.length&&f.push(a.$shortFormat())}),b.all(e).then(function(){f=_.uniq(f),f.length&&M.newMessage(a,f,c)})}var M=this,N=[];j.selectedFolder=q,M.service=j,M.selectedFolder=q,M.selectCard=s,M.toggleCardSelection=t,M.newComponent=u,M.unselectCards=v,M.confirmDeleteSelectedCards=A,M.copySelectedCards=C,M.moveSelectedCards=D,M.selectAll=E,M.sort=F,M.sortedBy=G,M.searchMode=H,M.cancelSearch=I,M.newMessage=J,M.newMessageWithSelectedCards=L,M.newMessageWithRecipient=K,M.mode={search:!1,multiple:0},r(N),a.$on("$destroy",function(){_.forEach(N,function(a){o.deregisterHotkey(a)})})}a.$inject=["$scope","$q","$window","$state","$timeout","$mdDialog","$mdToast","Account","Card","AddressBook","sgFocus","Dialog","sgSettings","sgHotkeys","stateAddressbooks","stateAddressbook"],angular.module("SOGo.ContactsUI").controller("AddressBookController",a)}(),function(){"use strict";function a(a,b,c,d,e,f,g,h,i,j,k,m,n,o,p,q,r,s,t,u,v){function w(a){a.push(o.createHotkey({key:"backspace",description:l("Delete selected card or address book"),callback:function(){r.selectedFolder&&!r.selectedFolder.hasSelectedCard()&&C()}})),_.forEach(a,function(a){o.registerHotkey(a)})}function x(a,c){b.params.addressbookId!=c.id&&K.editMode!=c.id?(K.editMode=!1,r.$query.value="",j(n["gt-md"])||k("left").close(),b.go("app.addressbook",{addressbookId:c.id})):(a.preventDefault(),a.stopPropagation())}function y(){s.prompt(l("New Addressbook..."),l("Name of the Address Book")).then(function(a){var b=new r({name:a,isEditable:!0,isRemote:!1,owner:UserLogin});r.$add(b)})}function z(a){a.isRemote||(K.editMode=a.id,K.originalAddressbook=angular.extend({},a.$omit()),p("addressBookName_"+a.id))}function A(a){a.name=K.originalAddressbook.name,K.editMode=!1}function B(a){var b=a.name;b&&b.length>0&&b!=K.originalAddressbook.name&&a.$rename(b).then(function(a){K.editMode=!1},function(a,b){s.alert(l("Warning"),a)})}function C(){K.service.selectedFolder.isSubscription?K.service.selectedFolder.$delete().then(function(){K.service.selectedFolder=null,b.go("app.addressbook",{addressbookId:"personal"})},function(a,b){s.alert(l('An error occured while deleting the addressbook "%{0}".',K.service.selectedFolder.name),l(a.error))}):s.confirm(l("Warning"),l('Are you sure you want to delete the addressbook "%{0}"?',K.service.selectedFolder.name),{ok:l("Delete")}).then(function(){return K.service.selectedFolder.$delete()}).then(function(){return K.service.selectedFolder=null,b.go("app.addressbook",{addressbookId:"personal"}),!0}).catch(function(a){if(a){var b=a.data.message||a.statusText;s.alert(l('An error occured while deleting the addressbook "%{0}".',K.service.selectedFolder.name),b)}})}function D(a,b){function c(a,b,c){function d(a){var b=0===a.type.indexOf("text")||/\.(ldif|vcf|vcard)$/.test(a.name);return b||i.show({template:["",'
',' error_outline'," "+l("Select a vCard or LDIF file.")+"","
","
"].join(""),position:"top right",hideDelay:3e3}),b}var e=this;e.uploader=new m({url:ApplicationBaseURL+[c.id,"import"].join("/"),autoUpload:!0,queueLimit:1,filters:[{name:d,fn:d}],onSuccessItem:function(a,c,d,e){var f;b.hide(),0===c.imported?f=l("No card was imported."):(f=l("A total of %{0} cards were imported in the addressbook.",c.imported),r.selectedFolder.$reload()),i.show(i.simple().content(f).position("top right").hideDelay(3e3))},onErrorItem:function(a,b,c,d){i.show({template:["",'
',' error_outline'," "+l("An error occured while importing contacts.")+"","
","
"].join(""),position:"top right",hideDelay:3e3})}}),e.close=function(){b.hide()}}h.show({parent:angular.element(document.body),targetEvent:a,clickOutsideToClose:!0,escapeToClose:!0,templateUrl:"UIxContactsImportDialog",controller:c,controllerAs:"$CardsImportDialogController",locals:{folder:b}}),c.$inject=["scope","$mdDialog","folder"]}function E(b){function c(a,b){function c(){a.hide()}this.addressbook=b,this.close=c}var d;d=b.urls?a.when():r.$reloadAll(),d.then(function(){h.show({parent:angular.element(document.body),clickOutsideToClose:!0,escapeToClose:!0,templateUrl:b.id+"/links",controller:c,controllerAs:"links",locals:{addressbook:b}})}),c.$inject=["$mdDialog","addressbook"]}function F(a){function b(a,b,c){function d(){f.addressbook.$save().then(function(){c.init(f.addressbook.$omit()),b.hide()})}function e(){b.cancel()}var f=this;f.addressbook=new r(c.$omit()),f.saveProperties=d,f.close=e}h.show({templateUrl:a.id+"/properties",controller:b,controllerAs:"properties",clickOutsideToClose:!0,escapeToClose:!0,locals:{srcAddressBook:a}}).catch(function(){}),b.$inject=["$scope","$mdDialog","srcAddressBook"]}function G(a){a.$acl.$users().then(function(){h.show({templateUrl:a.id+"/UIxAclEditor",controller:"AclController",controllerAs:"acl",clickOutsideToClose:!0,escapeToClose:!0,locals:{usersWithACL:a.$acl.users,User:u,folder:a}})})}function H(a){console.debug("subscribeToFolder "+a.owner+a.name),r.$subscribe(a.owner,a.name).then(function(a){i.show(i.simple().content(l("Successfully subscribed to address book")).position("top right").hideDelay(3e3))})}function I(a,b){return b.id!=a.id&&(b.isOwned||b.acls.objectCreator)}function J(a,c,d){var e,f,g,h,j,k,m;e=c.id,j=!1,f=a.$selectedCards(),0===f.length&&(f=[a.$selectedCard()]),g=_.filter(f,function(a){return a.$isCard()}),g.length!=f.length&&i.show(i.simple().content(l("Lists can't be moved or copied.")).position("top right").hideDelay(2e3)),g.length&&("copy"==d?(k=a.$copyCards(g,e),m=l("%{0} card(s) copied",g.length)):(k=a.$moveCards(g,e),m=l("%{0} card(s) moved",g.length),h=_.map(g,"id"),j=a.selectedCard&&h.indexOf(a.selectedCard)>=0),k.then(function(){j&&b.go("app.addressbook"),i.show(i.simple().content(m).position("top right").hideDelay(2e3))}))}var K=this,L=[];K.activeUser=t.activeUser,K.service=r,K.select=x,K.newAddressbook=y,K.edit=z,K.revertEditing=A,K.save=B,K.confirmDelete=C,K.importCards=D,K.showLinks=E,K.showProperties=F,K.share=G,K.subscribeToFolder=H,K.isDroppableFolder=I,K.dragSelectedCards=J,w(L),c.$on("$destroy",function(){_.forEach(L,function(a){o.deregisterHotkey(a)})})}a.$inject=["$q","$state","$scope","$rootScope","$stateParams","$timeout","$window","$mdDialog","$mdToast","$mdMedia","$mdSidenav","FileUploader","sgConstant","sgHotkeys","sgFocus","Card","AddressBook","Dialog","sgSettings","User","stateAddressbooks"],angular.module("SOGo.ContactsUI").controller("AddressBooksController",a)}(),function(){"use strict";function a(a,b,c,d,e,f,g,h,i,j,k,m,n){function o(a){a.push(i.createHotkey({key:"backspace",description:l("Delete"),callback:function(a){0===E.currentFolder.$selectedCount()&&C(),a.preventDefault()}})),_.forEach(a,function(a){i.registerHotkey(a)})}function p(a){return angular.isString(a)?{value:a}:a}function q(){j("orgUnit_"+E.card.$addOrgUnit(""))}function r(){E.card.birthday=new Date}function s(){E.card.$addScreenName("")}function t(){j("email_"+E.card.$addEmail(""))}function u(){j("phone_"+E.card.$addPhone(""))}function v(){j("url_"+E.card.$addUrl("",""))}function w(){j("address_"+E.card.$addAddress("","","","","","","",""))}function x(a,b){return a.length"+a.$fullname()+""),{ok:l("Delete")}).then(function(){f.selectedFolder.$deleteCards([a]).then(function(){z()},function(b,c){h.alert(l("Warning"),l('An error occured while deleting the card "%{0}".',a.$fullname()))})})}function D(a){E.showRawSource||E.rawSource?E.showRawSource=!E.showRawSource:g.$$resource.post(E.currentFolder.id+"/"+E.card.id,"raw").then(function(a){E.rawSource=a,E.showRawSource=!0})}var E=this,F=[];E.card=n,E.currentFolder=f.selectedFolder,E.allEmailTypes=g.$EMAIL_TYPES,E.allTelTypes=g.$TEL_TYPES,E.allUrlTypes=g.$URL_TYPES,E.allAddressTypes=g.$ADDRESS_TYPES,E.categories={},E.userFilterResults=[],E.transformCategory=p,E.addOrgUnit=q,E.addBirthday=r,E.addScreenName=s,E.addEmail=t,E.addPhone=u,E.addUrl=v,E.addAddress=w,E.userFilter=x,E.save=y,E.close=z,E.reset=A,E.cancel=B,E.confirmDelete=C,E.toggleRawSource=D,E.showRawSource=!1,o(F),a.$on("$destroy",function(){_.forEach(F,function(a){i.deregisterHotkey(a)})})}a.$inject=["$scope","$timeout","$window","$mdDialog","sgSettings","AddressBook","Card","Dialog","sgHotkeys","sgFocus","$state","$stateParams","stateCard"],angular.module("SOGo.ContactsUI").controller("CardController",a)}(),function(){"use strict";function a(){return{restrict:"A",scope:{data:"=sgAddress"},controller:["$scope",function(a){a.addressLines=function(a){var b=[],c=[];return a.street&&b.push(a.street),a.street2&&b.push(a.street2),a.locality&&c.push(a.locality),a.region&&c.push(a.region),c.length>0&&b.push(c.join(", ")),a.country&&b.push(a.country),a.postalcode&&b.push(a.postalcode),b.join("
")}}],template:'
'}}angular.module("SOGo.Common").directive("sgAddress",a)}(); +!function(){"use strict";function a(a,h){a.state("app",{url:"/addressbooks",abstract:!0,views:{addressbooks:{templateUrl:"UIxContactFoldersView",controller:"AddressBooksController",controllerAs:"app"}},resolve:{stateAddressbooks:b}}).state("app.addressbook",{url:"/:addressbookId",views:{addressbook:{templateUrl:"addressbook",controller:"AddressBookController",controllerAs:"addressbook"}},resolve:{stateAddressbook:c}}).state("app.addressbook.new",{url:"/{contactType:(?:card|list)}/new",views:{card:{templateUrl:"UIxContactEditorTemplate",controller:"CardController",controllerAs:"editor"}},resolve:{stateCard:d}}).state("app.addressbook.card",{url:"/:cardId",abstract:!0,views:{card:{template:""}},resolve:{stateCard:e},onEnter:f,onExit:g}).state("app.addressbook.card.view",{url:"/view",views:{"card@app.addressbook":{templateUrl:"UIxContactViewTemplate",controller:"CardController",controllerAs:"editor"}}}).state("app.addressbook.card.editor",{url:"/edit",views:{"card@app.addressbook":{templateUrl:"UIxContactEditorTemplate",controller:"CardController",controllerAs:"editor"}}}),h.otherwise("/addressbooks/personal")}function b(a){return a.$findAll(window.contactFolders)}function c(a,b,c,d){var e=_.find(d.$findAll(),function(a){return a.id==c.addressbookId});return e?(delete e.selectedCard,e.$reload(),e):a.reject("Addressbook "+c.addressbookId+" not found")}function d(a,b,c){var d="v"+a.contactType,e=new c({pid:a.addressbookId,c_component:d});return b.selectedCard=!0,e}function e(a,b,c){var d;if(d=_.find(c.$cards,function(a){return a.id==b.cardId}))return d.$reload();a.go("app.addressbook")}function f(a,b){b.selectedCard=a.cardId}function g(a){delete c.selectedCard}function h(a,b,c){a.$on("$stateChangeError",function(a,d,e,f,g,h){b.error(h),c.go("app.addressbook",{addressbookId:"personal"})}),a.$on("$routeChangeError",function(a,c,d,e){b.error(a,c,d,e)})}angular.module("SOGo.ContactsUI",["ngCookies","ui.router","angularFileUpload","ck","SOGo.Common","SOGo.PreferencesUI","SOGo.MailerUI"]).config(a).run(h),a.$inject=["$stateProvider","$urlRouterProvider"],b.$inject=["AddressBook"],c.$inject=["$q","$state","$stateParams","AddressBook"],d.$inject=["$stateParams","stateAddressbook","Card"],e.$inject=["$state","$stateParams","stateAddressbook"],f.$inject=["$stateParams","stateAddressbook"],g.$inject=["stateAddressbook"],h.$inject=["$rootScope","$log","$state"]}(),function(){"use strict";function a(a,b,c,d,e,f,g,h,i,j,k,m,n,o,p,q){function r(a){a.push(o.createHotkey({key:l("hotkey_search"),description:l("Search"),callback:H})),a.push(o.createHotkey({key:l("key_create_card"),description:l("Create a new address book card"),callback:angular.bind(M,u,"card")})),a.push(o.createHotkey({key:l("key_create_list"),description:l("Create a new list"),callback:angular.bind(M,u,"list")})),a.push(o.createHotkey({key:"space",description:l("Toggle item"),callback:t})),a.push(o.createHotkey({key:"shift+space",description:l("Toggle range of items"),callback:t})),a.push(o.createHotkey({key:"up",description:l("View next item"),callback:w})),a.push(o.createHotkey({key:"down",description:l("View previous item"),callback:x})),a.push(o.createHotkey({key:"shift+up",description:l("Add next item to selection"),callback:y})),a.push(o.createHotkey({key:"shift+down",description:l("Add previous item to selection"),callback:z})),a.push(o.createHotkey({key:"backspace",description:l("Delete selected card or address book"),callback:A})),_.forEach(a,function(a){o.registerHotkey(a)})}function s(a){d.go("app.addressbook.card.view",{cardId:a.id})}function t(a,b){var c,d,e,f=M.selectedFolder;if(b||(b=f.$selectedCard()),b.selected=!b.selected,M.mode.multiple+=b.selected?1:-1,a.shiftKey&&f.$selectedCount()>1){for(c=f.idsMap[b.id],d=c-2;d>=0&&!f.$cards[d].selected;)d--;if(d<0)for(d=c+2;d=0&&d0&&M.selectedFolder.$topIndex--):(b=M.selectedFolder.$cards.length()-1,M.selectedFolder.$topIndex=M.selectedFolder.getLength()),b>-1&&s(M.selectedFolder.$cards[b]),a.preventDefault(),b}function x(a){var b=M.selectedFolder.$selectedCardIndex();return angular.isDefined(b)?(b++,M.selectedFolder.$topIndex=0&&t(a,M.selectedFolder.$cards[b]))}function z(a){var b;M.selectedFolder.hasSelectedCard()&&(b=x(a),b>=0&&t(a,M.selectedFolder.$cards[b]))}function A(a){var b=M.selectedFolder.$selectedCards();_.size(b)>0&&m.confirm(l("Warning"),l("Are you sure you want to delete the selected contacts?"),{ok:l("Delete")}).then(function(){M.selectedFolder.$deleteCards(b).then(function(){M.mode.multiple=0,M.selectedFolder.selectedCard||d.go("app.addressbook")})}),a.preventDefault()}function B(a,b){var c,e,f,h,i,j,k;c=M.selectedFolder,i=!1,e=c.$selectedCards(),f=_.filter(e,function(a){return a.$isCard()}),f.length!=e.length&&g.show(g.simple().content(l("Lists can't be moved or copied.")).position("top right").hideDelay(2e3)),f.length&&("copy"==a?(j=c.$copyCards(f,b),k=l("%{0} card(s) copied",f.length)):(j=c.$moveCards(f,b),k=l("%{0} card(s) moved",f.length),h=_.map(f,"id"),i=c.selectedCard&&h.indexOf(c.selectedCard)>=0),j.then(function(){i&&d.go("app.addressbook"),g.show(g.simple().content(k).position("top right").hideDelay(2e3))}))}function C(a){B("copy",a)}function D(a){B("move",a)}function E(){_.forEach(M.selectedFolder.$cards,function(a){a.selected=!0}),M.mode.multiple=M.selectedFolder.$cards.length}function F(a){M.selectedFolder.$filter("",{sort:a})}function G(a){return j.$query.sort==a}function H(){M.mode.search=!0,k("search")}function I(){M.mode.search=!1,M.selectedFolder.$filter("")}function J(a,b,c){h.$findAll().then(function(d){var e=_.find(d,function(a){if(0===a.id)return a});e.$getMailboxes().then(function(d){e.$newMessage().then(function(d){d.editable[c]=b,f.show({parent:angular.element(document.body),targetEvent:a,clickOutsideToClose:!1,escapeToClose:!1,templateUrl:"../Mail/UIxMailEditor",controller:"MessageEditorController",controllerAs:"editor",locals:{stateAccount:e,stateMessage:d}})})})})}function K(a,b,c){var d=[c+" <"+b+">"];M.newMessage(a,d,"to"),a.stopPropagation(),a.preventDefault()}function L(a,c){var d=_.filter(M.selectedFolder.$cards,function(a){return a.selected}),e=[],f=[];_.forEach(d,function(a){a.$isList({expandable:!0})?angular.isDefined(a.refs)&&a.refs.length?_.forEach(a.refs,function(a){a.email.length&&f.push(a.$shortFormat())}):e.push(a.$reload().then(function(a){_.forEach(a.refs,function(a){a.email.length&&f.push(a.$shortFormat())})})):a.c_mail.length&&f.push(a.$shortFormat())}),b.all(e).then(function(){f=_.uniq(f),f.length&&M.newMessage(a,f,c)})}var M=this,N=[];j.selectedFolder=q,M.service=j,M.selectedFolder=q,M.selectCard=s,M.toggleCardSelection=t,M.newComponent=u,M.unselectCards=v,M.confirmDeleteSelectedCards=A,M.copySelectedCards=C,M.moveSelectedCards=D,M.selectAll=E,M.sort=F,M.sortedBy=G,M.searchMode=H,M.cancelSearch=I,M.newMessage=J,M.newMessageWithSelectedCards=L,M.newMessageWithRecipient=K,M.mode={search:!1,multiple:0},r(N),a.$on("$destroy",function(){_.forEach(N,function(a){o.deregisterHotkey(a)})})}a.$inject=["$scope","$q","$window","$state","$timeout","$mdDialog","$mdToast","Account","Card","AddressBook","sgFocus","Dialog","sgSettings","sgHotkeys","stateAddressbooks","stateAddressbook"],angular.module("SOGo.ContactsUI").controller("AddressBookController",a)}(),function(){"use strict";function a(a,b,c,d,e,f,g,h,i,j,k,m,n,o,p,q,r,s,t,u,v){function w(a){a.push(o.createHotkey({key:"backspace",description:l("Delete selected card or address book"),callback:function(){r.selectedFolder&&!r.selectedFolder.hasSelectedCard()&&C()}})),_.forEach(a,function(a){o.registerHotkey(a)})}function x(a,c){b.params.addressbookId!=c.id&&K.editMode!=c.id?(K.editMode=!1,r.$query.value="",j(n["gt-md"])||k("left").close(),b.go("app.addressbook",{addressbookId:c.id})):(a.preventDefault(),a.stopPropagation())}function y(){s.prompt(l("New Addressbook..."),l("Name of the Address Book")).then(function(a){var b=new r({name:a,isEditable:!0,isRemote:!1,owner:UserLogin});r.$add(b)})}function z(a){a.isRemote||(K.editMode=a.id,K.originalAddressbook=angular.extend({},a.$omit()),p("addressBookName_"+a.id))}function A(a){a.name=K.originalAddressbook.name,K.editMode=!1}function B(a){var b=a.name;b&&b.length>0&&b!=K.originalAddressbook.name&&a.$rename(b).then(function(a){K.editMode=!1},function(a,b){s.alert(l("Warning"),a)})}function C(){K.service.selectedFolder.isSubscription?K.service.selectedFolder.$delete().then(function(){K.service.selectedFolder=null,b.go("app.addressbook",{addressbookId:"personal"})},function(a,b){s.alert(l('An error occured while deleting the addressbook "%{0}".',K.service.selectedFolder.name),l(a.error))}):s.confirm(l("Warning"),l('Are you sure you want to delete the addressbook "%{0}"?',K.service.selectedFolder.name),{ok:l("Delete")}).then(function(){return K.service.selectedFolder.$delete()}).then(function(){return K.service.selectedFolder=null,b.go("app.addressbook",{addressbookId:"personal"}),!0}).catch(function(a){if(a){var b=a.data.message||a.statusText;s.alert(l('An error occured while deleting the addressbook "%{0}".',K.service.selectedFolder.name),b)}})}function D(a,b){function c(a,b,c){function d(a){var b=0===a.type.indexOf("text")||/\.(ldif|vcf|vcard)$/.test(a.name);return b||i.show({template:["",'
',' error_outline'," "+l("Select a vCard or LDIF file.")+"","
","
"].join(""),position:"top right",hideDelay:3e3}),b}var e=this;e.uploader=new m({url:ApplicationBaseURL+[c.id,"import"].join("/"),autoUpload:!0,queueLimit:1,filters:[{name:d,fn:d}],onSuccessItem:function(a,c,d,e){var f;b.hide(),0===c.imported?f=l("No card was imported."):(f=l("A total of %{0} cards were imported in the addressbook.",c.imported),r.selectedFolder.$reload()),i.show(i.simple().content(f).position("top right").hideDelay(3e3))},onErrorItem:function(a,b,c,d){i.show({template:["",'
',' error_outline'," "+l("An error occured while importing contacts.")+"","
","
"].join(""),position:"top right",hideDelay:3e3})}}),e.close=function(){b.hide()}}h.show({parent:angular.element(document.body),targetEvent:a,clickOutsideToClose:!0,escapeToClose:!0,templateUrl:"UIxContactsImportDialog",controller:c,controllerAs:"$CardsImportDialogController",locals:{folder:b}}),c.$inject=["scope","$mdDialog","folder"]}function E(b){function c(a,b){function c(){a.hide()}this.addressbook=b,this.close=c}var d;d=b.urls?a.when():r.$reloadAll(),d.then(function(){h.show({parent:angular.element(document.body),clickOutsideToClose:!0,escapeToClose:!0,templateUrl:b.id+"/links",controller:c,controllerAs:"links",locals:{addressbook:b}})}),c.$inject=["$mdDialog","addressbook"]}function F(a){function b(a,b,c){function d(){f.addressbook.$save().then(function(){c.init(f.addressbook.$omit()),b.hide()})}function e(){b.cancel()}var f=this;f.addressbook=new r(c.$omit()),f.saveProperties=d,f.close=e}h.show({templateUrl:a.id+"/properties",controller:b,controllerAs:"properties",clickOutsideToClose:!0,escapeToClose:!0,locals:{srcAddressBook:a}}).catch(function(){}),b.$inject=["$scope","$mdDialog","srcAddressBook"]}function G(a){a.$acl.$users().then(function(){h.show({templateUrl:a.id+"/UIxAclEditor",controller:"AclController",controllerAs:"acl",clickOutsideToClose:!0,escapeToClose:!0,locals:{usersWithACL:a.$acl.users,User:u,folder:a}})})}function H(a){console.debug("subscribeToFolder "+a.owner+a.name),r.$subscribe(a.owner,a.name).then(function(a){i.show(i.simple().content(l("Successfully subscribed to address book")).position("top right").hideDelay(3e3))})}function I(a,b){return b.id!=a.id&&(b.isOwned||b.acls.objectCreator)}function J(a,c,d){var e,f,g,h,j,k,m;e=c.id,j=!1,f=a.$selectedCards(),0===f.length&&(f=[a.$selectedCard()]),g=_.filter(f,function(a){return a.$isCard()}),g.length!=f.length&&i.show(i.simple().content(l("Lists can't be moved or copied.")).position("top right").hideDelay(2e3)),g.length&&("copy"==d?(k=a.$copyCards(g,e),m=l("%{0} card(s) copied",g.length)):(k=a.$moveCards(g,e),m=l("%{0} card(s) moved",g.length),h=_.map(g,"id"),j=a.selectedCard&&h.indexOf(a.selectedCard)>=0),k.then(function(){j&&b.go("app.addressbook"),i.show(i.simple().content(m).position("top right").hideDelay(2e3))}))}var K=this,L=[];K.activeUser=t.activeUser,K.service=r,K.select=x,K.newAddressbook=y,K.edit=z,K.revertEditing=A,K.save=B,K.confirmDelete=C,K.importCards=D,K.showLinks=E,K.showProperties=F,K.share=G,K.subscribeToFolder=H,K.isDroppableFolder=I,K.dragSelectedCards=J,w(L),c.$on("$destroy",function(){_.forEach(L,function(a){o.deregisterHotkey(a)})})}a.$inject=["$q","$state","$scope","$rootScope","$stateParams","$timeout","$window","$mdDialog","$mdToast","$mdMedia","$mdSidenav","FileUploader","sgConstant","sgHotkeys","sgFocus","Card","AddressBook","Dialog","sgSettings","User","stateAddressbooks"],angular.module("SOGo.ContactsUI").controller("AddressBooksController",a)}(),function(){"use strict";function a(a,b,c,d,e,f,g,h,i,j,k,m,n){function o(a){a.push(i.createHotkey({key:"backspace",description:l("Delete"),callback:function(a){0===E.currentFolder.$selectedCount()&&C(),a.preventDefault()}})),_.forEach(a,function(a){i.registerHotkey(a)})}function p(a){return angular.isString(a)?{value:a}:a}function q(){j("org_"+E.card.$addOrg({value:""}))}function r(){E.card.birthday=new Date}function s(){E.card.$addScreenName("")}function t(){j("email_"+E.card.$addEmail(""))}function u(){j("phone_"+E.card.$addPhone(""))}function v(){j("url_"+E.card.$addUrl("",""))}function w(){j("address_"+E.card.$addAddress("","","","","","","",""))}function x(a,b){return a.length"+a.$fullname()+""),{ok:l("Delete")}).then(function(){f.selectedFolder.$deleteCards([a]).then(function(){z()},function(b,c){h.alert(l("Warning"),l('An error occured while deleting the card "%{0}".',a.$fullname()))})})}function D(a){E.showRawSource||E.rawSource?E.showRawSource=!E.showRawSource:g.$$resource.post(E.currentFolder.id+"/"+E.card.id,"raw").then(function(a){E.rawSource=a,E.showRawSource=!0})}var E=this,F=[];E.card=n,E.currentFolder=f.selectedFolder,E.allEmailTypes=g.$EMAIL_TYPES,E.allTelTypes=g.$TEL_TYPES,E.allUrlTypes=g.$URL_TYPES,E.allAddressTypes=g.$ADDRESS_TYPES,E.categories={},E.userFilterResults=[],E.transformCategory=p,E.addOrg=q,E.addBirthday=r,E.addScreenName=s,E.addEmail=t,E.addPhone=u,E.addUrl=v,E.addAddress=w,E.userFilter=x,E.save=y,E.close=z,E.reset=A,E.cancel=B,E.confirmDelete=C,E.toggleRawSource=D,E.showRawSource=!1,o(F),a.$on("$destroy",function(){_.forEach(F,function(a){i.deregisterHotkey(a)})})}a.$inject=["$scope","$timeout","$window","$mdDialog","sgSettings","AddressBook","Card","Dialog","sgHotkeys","sgFocus","$state","$stateParams","stateCard"],angular.module("SOGo.ContactsUI").controller("CardController",a)}(),function(){"use strict";function a(){return{restrict:"A",scope:{data:"=sgAddress"},controller:["$scope",function(a){a.addressLines=function(a){var b=[],c=[];return a.street&&b.push(a.street),a.street2&&b.push(a.street2),a.locality&&c.push(a.locality),a.region&&c.push(a.region),c.length>0&&b.push(c.join(", ")),a.country&&b.push(a.country),a.postalcode&&b.push(a.postalcode),b.join("
")}}],template:'
'}}angular.module("SOGo.Common").directive("sgAddress",a)}(); //# sourceMappingURL=Contacts.js.map \ No newline at end of file diff --git a/UI/WebServerResources/js/Contacts.js.map b/UI/WebServerResources/js/Contacts.js.map index c382e62da..c896f1109 100644 --- a/UI/WebServerResources/js/Contacts.js.map +++ b/UI/WebServerResources/js/Contacts.js.map @@ -1 +1 @@ -{"version":3,"sources":["Contacts/Contacts.app.js","Contacts/AddressBookController.js","Contacts/AddressBooksController.js","Contacts/CardController.js","Contacts/sgAddress.directive.js"],"names":["configure","$stateProvider","$urlRouterProvider","state","url","abstract","views","addressbooks","templateUrl","controller","controllerAs","resolve","stateAddressbooks","addressbook","stateAddressbook","card","stateCard","stateNewCard","template","onEnter","onEnterCard","onExit","onExitCard","card@app.addressbook","otherwise","AddressBook","$findAll","window","contactFolders","$q","$state","$stateParams","_","find","id","addressbookId","selectedCard","$reload","reject","Card","tag","contactType","pid","c_component","$cards","cardObject","cardId","go","stateMailbox","runBlock","$rootScope","$log","$on","event","toState","toParams","fromState","fromParams","error","current","previous","rejection","angular","module","config","run","$inject","AddressBookController","$scope","$window","$timeout","$mdDialog","$mdToast","Account","focus","Dialog","Settings","sgHotkeys","_registerHotkeys","keys","push","createHotkey","key","l","description","callback","searchMode","bind","vm","newComponent","toggleCardSelection","_nextCard","_previousCard","_addNextCardToSelection","_addPreviousCardToSelection","confirmDeleteSelectedCards","forEach","registerHotkey","selectCard","$event","selectedIndex","nextSelectedIndex","i","folder","selectedFolder","$selectedCard","selected","mode","multiple","shiftKey","$selectedCount","idsMap","getLength","Math","min","max","preventDefault","stopPropagation","type","unselectCards","index","$selectedCardIndex","isDefined","$topIndex","length","hasSelectedCard","selectedCards","$selectedCards","size","confirm","ok","then","$deleteCards","_selectedCardsOperation","operation","dstId","srcFolder","allCards","cards","ids","clearCardView","promise","success","filter","$isCard","show","simple","content","position","hideDelay","$copyCards","$moveCards","map","indexOf","copySelectedCards","moveSelectedCards","selectAll","sort","field","$filter","sortedBy","$query","search","cancelSearch","newMessage","recipients","recipientsField","accounts","account","o","$getMailboxes","mailboxes","$newMessage","message","editable","parent","element","document","body","targetEvent","clickOutsideToClose","escapeToClose","locals","stateAccount","stateMessage","newMessageWithRecipient","recipient","fn","newMessageWithSelectedCards","promises","$isList","expandable","refs","ref","email","$shortFormat","c_mail","all","uniq","this","hotkeys","service","deregisterHotkey","AddressBooksController","$mdMedia","$mdSidenav","FileUploader","sgConstant","User","confirmDelete","select","params","editMode","value","close","newAddressbook","prompt","name","isEditable","isRemote","owner","UserLogin","$add","edit","originalAddressbook","extend","$omit","revertEditing","save","$rename","data","status","alert","isSubscription","$delete","catch","response","statusText","importCards","CardsImportDialogController","scope","filterByExtension","item","isTextFile","test","join","uploader","ApplicationBaseURL","autoUpload","queueLimit","filters","onSuccessItem","headers","msg","hide","imported","onErrorItem","showLinks","LinksDialogController","urls","when","$reloadAll","showProperties","PropertiesDialogController","srcAddressBook","saveProperties","$save","init","cancel","share","$acl","$users","usersWithACL","users","subscribeToFolder","addressbookData","console","debug","$subscribe","isDroppableFolder","dstFolder","isOwned","acls","objectCreator","dragSelectedCards","activeUser","CardController","sgSettings","currentFolder","transformCategory","input","isString","addOrgUnit","$addOrgUnit","addBirthday","birthday","Date","addScreenName","$addScreenName","addEmail","$addEmail","addPhone","$addPhone","addUrl","$addUrl","addAddress","$addAddress","userFilter","excludedCards","minimumSearchLength","dry","excludeLists","form","$valid","copy","reset","$reset","$setPristine","isNew","$fullname","toggleRawSource","showRawSource","rawSource","$$resource","post","allEmailTypes","$EMAIL_TYPES","allTelTypes","$TEL_TYPES","allUrlTypes","$URL_TYPES","allAddressTypes","$ADDRESS_TYPES","categories","userFilterResults","sgAddress","restrict","addressLines","lines","locality_region","street","street2","locality","region","country","postalcode","directive"],"mappings":"CAGA,WACE,YAUA,SAASA,GAAUC,EAAgBC,GACjCD,EACGE,MAAM,OACLC,IAAK,gBACLC,UAAU,EACVC,OACEC,cACEC,YAAa,wBACbC,WAAY,yBACZC,aAAc,QAGlBC,SACEC,kBAAmBA,KAGtBT,MAAM,mBACLC,IAAK,kBACLE,OACEO,aACEL,YAAa,cACbC,WAAY,wBACZC,aAAc,gBAGlBC,SACEG,iBAAkBA,KAGrBX,MAAM,uBACLC,IAAK,mCACLE,OACES,MACEP,YAAa,2BACbC,WAAY,iBACZC,aAAc,WAGlBC,SACEK,UAAWC,KAGdd,MAAM,wBACLC,IAAK,WACLC,UAAU,EACVC,OACES,MACEG,SAAU,eAGdP,SACEK,UAAWA,GAEbG,QAASC,E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EAAGyN,WAAaA,EAChBzN,EAAG2N,WAAaA,EAChB3N,EAAG4I,KAAOA,EACV5I,EAAG8H,MAAQA,EACX9H,EAAGmO,MAAQA,EACXnO,EAAGoL,OAASA,EACZpL,EAAGyH,cAAgBA,EACnBzH,EAAGwO,gBAAkBA,EACrBxO,EAAGyO,eAAgB,EAGnBnP,EAAiB0H,GAEjBpI,EAAOhB,IAAI,WAAY,WAErBpB,EAAEgE,QAAQwG,EAAS,SAAStH,GAC1BL,EAAU6H,iBAAiBxH,OApCjC4M,EAAe5N,SAAW,SAAU,WAAY,UAAW,YAAa,aAAc,cAAe,OAAQ,SAAU,YAAa,UAAW,SAAU,eAAgB,aAyKzKJ,QACGC,OAAO,mBACPtD,WAAW,iBAAkBqR,MClLlC,WACE,YAQA,SAASiD,KACP,OACEC,SAAU,IACVhG,OAASV,KAAM,cACf7N,YAAa,SAAU,SAAS2D,GAC9BA,EAAO6Q,aAAe,SAAS3G,GAC7B,GAAI4G,MACAC,IAQJ,OAPI7G,GAAK8G,QAAQF,EAAMlQ,KAAKsJ,EAAK8G,QAC7B9G,EAAK+G,SAASH,EAAMlQ,KAAKsJ,EAAK+G,SAC9B/G,EAAKgH,UAAUH,EAAgBnQ,KAAKsJ,EAAKgH,UACzChH,EAAKiH,QAAQJ,EAAgBnQ,KAAKsJ,EAAKiH,QACvCJ,EAAgBvN,OAAS,GAAGsN,EAAMlQ,KAAKmQ,EAAgB9F,KAAK,OAC5Df,EAAKkH,SAASN,EAAMlQ,KAAKsJ,EAAKkH,SAC9BlH,EAAKmH,YAAYP,EAAMlQ,KAAKsJ,EAAKmH,YAC9BP,EAAM7F,KAAK,WAGtBnO,SAAU,yDAId4C,QACGC,OAAO,eACP2R,UAAU,YAAaX","file":"Contacts.js","sourcesContent":["/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n/* JavaScript for SOGoContacts */\n\n(function() {\n 'use strict';\n\n angular.module('SOGo.ContactsUI', ['ngCookies', 'ui.router', 'angularFileUpload', 'ck', 'SOGo.Common', 'SOGo.PreferencesUI', 'SOGo.MailerUI'])\n .config(configure)\n .run(runBlock);\n\n /**\n * @ngInject\n */\n configure.$inject = ['$stateProvider', '$urlRouterProvider'];\n function configure($stateProvider, $urlRouterProvider) {\n $stateProvider\n .state('app', {\n url: '/addressbooks',\n abstract: true,\n views: {\n addressbooks: {\n templateUrl: 'UIxContactFoldersView', // UI/Templates/Contacts/UIxContactFoldersView.wox\n controller: 'AddressBooksController',\n controllerAs: 'app'\n }\n },\n resolve: {\n stateAddressbooks: stateAddressbooks\n }\n })\n .state('app.addressbook', {\n url: '/:addressbookId',\n views: {\n addressbook: {\n templateUrl: 'addressbook',\n controller: 'AddressBookController',\n controllerAs: 'addressbook'\n }\n },\n resolve: {\n stateAddressbook: stateAddressbook\n }\n })\n .state('app.addressbook.new', {\n url: '/{contactType:(?:card|list)}/new',\n views: {\n card: {\n templateUrl: 'UIxContactEditorTemplate', // UI/Templates/Contacts/UIxContactEditorTemplate.wox\n controller: 'CardController',\n controllerAs: 'editor'\n }\n },\n resolve: {\n stateCard: stateNewCard\n }\n })\n .state('app.addressbook.card', {\n url: '/:cardId',\n abstract: true,\n views: {\n card: {\n template: ''\n }\n },\n resolve: {\n stateCard: stateCard\n },\n onEnter: onEnterCard,\n onExit: onExitCard\n })\n .state('app.addressbook.card.view', {\n url: '/view',\n views: {\n 'card@app.addressbook': {\n templateUrl: 'UIxContactViewTemplate', // UI/Templates/Contacts/UIxContactViewTemplate.wox\n controller: 'CardController',\n controllerAs: 'editor'\n }\n }\n })\n .state('app.addressbook.card.editor', {\n url: '/edit',\n views: {\n 'card@app.addressbook': {\n templateUrl: 'UIxContactEditorTemplate', // UI/Templates/Contacts/UIxContactEditorTemplate.wox\n controller: 'CardController',\n controllerAs: 'editor'\n }\n }\n });\n\n // if none of the above states are matched, use this as the fallback\n $urlRouterProvider.otherwise('/addressbooks/personal');\n }\n\n /**\n * @ngInject\n */\n stateAddressbooks.$inject = ['AddressBook'];\n function stateAddressbooks(AddressBook) {\n return AddressBook.$findAll(window.contactFolders);\n }\n\n /**\n * @ngInject\n */\n stateAddressbook.$inject = ['$q', '$state', '$stateParams', 'AddressBook'];\n function stateAddressbook($q, $state, $stateParams, AddressBook) {\n var addressbook = _.find(AddressBook.$findAll(), function(addressbook) {\n return addressbook.id == $stateParams.addressbookId;\n });\n if (addressbook) {\n delete addressbook.selectedCard;\n addressbook.$reload();\n return addressbook;\n }\n return $q.reject('Addressbook ' + $stateParams.addressbookId + ' not found');\n }\n\n /**\n * @ngInject\n */\n stateNewCard.$inject = ['$stateParams', 'stateAddressbook', 'Card'];\n function stateNewCard($stateParams, stateAddressbook, Card) {\n var tag = 'v' + $stateParams.contactType,\n card = new Card({ pid: $stateParams.addressbookId, c_component: tag });\n stateAddressbook.selectedCard = true;\n return card;\n }\n\n /**\n * @ngInject\n */\n stateCard.$inject = ['$state', '$stateParams', 'stateAddressbook'];\n function stateCard($state, $stateParams, stateAddressbook) {\n var card;\n\n card = _.find(stateAddressbook.$cards, function(cardObject) {\n return (cardObject.id == $stateParams.cardId);\n });\n\n if (card) {\n return card.$reload();\n }\n else {\n // Card not found\n $state.go('app.addressbook');\n }\n }\n\n /**\n * @ngInject\n */\n onEnterCard.$inject = ['$stateParams', 'stateAddressbook'];\n function onEnterCard($stateParams, stateAddressbook) {\n stateAddressbook.selectedCard = $stateParams.cardId;\n }\n\n /**\n * @ngInject\n */\n onExitCard.$inject = ['stateAddressbook'];\n function onExitCard(stateMailbox) {\n delete stateAddressbook.selectedCard;\n }\n\n /**\n * @ngInject\n */\n runBlock.$inject = ['$rootScope', '$log', '$state'];\n function runBlock($rootScope, $log, $state) {\n $rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error) {\n $log.error(error);\n $state.go('app.addressbook', { addressbookId: 'personal' });\n });\n $rootScope.$on('$routeChangeError', function(event, current, previous, rejection) {\n $log.error(event, current, previous, rejection);\n });\n }\n\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n AddressBookController.$inject = ['$scope', '$q', '$window', '$state', '$timeout', '$mdDialog', '$mdToast', 'Account', 'Card', 'AddressBook', 'sgFocus', 'Dialog', 'sgSettings', 'sgHotkeys', 'stateAddressbooks', 'stateAddressbook'];\n function AddressBookController($scope, $q, $window, $state, $timeout, $mdDialog, $mdToast, Account, Card, AddressBook, focus, Dialog, Settings, sgHotkeys, stateAddressbooks, stateAddressbook) {\n var vm = this, hotkeys = [];\n\n AddressBook.selectedFolder = stateAddressbook;\n\n vm.service = AddressBook;\n vm.selectedFolder = stateAddressbook;\n vm.selectCard = selectCard;\n vm.toggleCardSelection = toggleCardSelection;\n vm.newComponent = newComponent;\n vm.unselectCards = unselectCards;\n vm.confirmDeleteSelectedCards = confirmDeleteSelectedCards;\n vm.copySelectedCards = copySelectedCards;\n vm.moveSelectedCards = moveSelectedCards;\n vm.selectAll = selectAll;\n vm.sort = sort;\n vm.sortedBy = sortedBy;\n vm.searchMode = searchMode;\n vm.cancelSearch = cancelSearch;\n vm.newMessage = newMessage;\n vm.newMessageWithSelectedCards = newMessageWithSelectedCards;\n vm.newMessageWithRecipient = newMessageWithRecipient;\n vm.mode = { search: false, multiple: 0 };\n\n\n _registerHotkeys(hotkeys);\n\n $scope.$on('$destroy', function() {\n // Deregister hotkeys\n _.forEach(hotkeys, function(key) {\n sgHotkeys.deregisterHotkey(key);\n });\n });\n\n\n function _registerHotkeys(keys) {\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_search'),\n description: l('Search'),\n callback: searchMode\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('key_create_card'),\n description: l('Create a new address book card'),\n callback: angular.bind(vm, newComponent, 'card')\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('key_create_list'),\n description: l('Create a new list'),\n callback: angular.bind(vm, newComponent, 'list')\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'space',\n description: l('Toggle item'),\n callback: toggleCardSelection\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'shift+space',\n description: l('Toggle range of items'),\n callback: toggleCardSelection\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'up',\n description: l('View next item'),\n callback: _nextCard\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'down',\n description: l('View previous item'),\n callback: _previousCard\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'shift+up',\n description: l('Add next item to selection'),\n callback: _addNextCardToSelection\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'shift+down',\n description: l('Add previous item to selection'),\n callback: _addPreviousCardToSelection\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'backspace',\n description: l('Delete selected card or address book'),\n callback: confirmDeleteSelectedCards\n }));\n\n // Register the hotkeys\n _.forEach(keys, function(key) {\n sgHotkeys.registerHotkey(key);\n });\n }\n\n function selectCard(card) {\n $state.go('app.addressbook.card.view', {cardId: card.id});\n }\n\n function toggleCardSelection($event, card) {\n var folder = vm.selectedFolder,\n selectedIndex, nextSelectedIndex, i;\n\n if (!card)\n card = folder.$selectedCard();\n card.selected = !card.selected;\n vm.mode.multiple += card.selected? 1 : -1;\n\n // Select closest range of cards when shift key is pressed\n if ($event.shiftKey && folder.$selectedCount() > 1) {\n selectedIndex = folder.idsMap[card.id];\n // Search for next selected card above\n nextSelectedIndex = selectedIndex - 2;\n while (nextSelectedIndex >= 0 &&\n !folder.$cards[nextSelectedIndex].selected)\n nextSelectedIndex--;\n if (nextSelectedIndex < 0) {\n // Search for next selected card bellow\n nextSelectedIndex = selectedIndex + 2;\n while (nextSelectedIndex < folder.getLength() &&\n !folder.$cards[nextSelectedIndex].selected)\n nextSelectedIndex++;\n }\n if (nextSelectedIndex >= 0 && nextSelectedIndex < folder.getLength()) {\n for (i = Math.min(selectedIndex, nextSelectedIndex);\n i <= Math.max(selectedIndex, nextSelectedIndex);\n i++)\n folder.$cards[i].selected = true;\n }\n }\n\n $event.preventDefault();\n $event.stopPropagation();\n }\n\n function newComponent(type) {\n $state.go('app.addressbook.new', { contactType: type });\n }\n\n function unselectCards() {\n _.forEach(vm.selectedFolder.$cards, function(card) {\n card.selected = false;\n });\n vm.mode.multiple = 0;\n }\n\n /**\n * User has pressed up arrow key\n */\n function _nextCard($event) {\n var index = vm.selectedFolder.$selectedCardIndex();\n\n if (angular.isDefined(index)) {\n index--;\n if (vm.selectedFolder.$topIndex > 0)\n vm.selectedFolder.$topIndex--;\n }\n else {\n // No card is selected, show oldest card\n index = vm.selectedFolder.$cards.length() - 1;\n vm.selectedFolder.$topIndex = vm.selectedFolder.getLength();\n }\n\n if (index > -1)\n selectCard(vm.selectedFolder.$cards[index]);\n\n $event.preventDefault();\n\n return index;\n }\n\n /**\n * User has pressed the down arrow key\n */\n function _previousCard($event) {\n var index = vm.selectedFolder.$selectedCardIndex();\n\n if (angular.isDefined(index)) {\n index++;\n if (vm.selectedFolder.$topIndex < vm.selectedFolder.$cards.length)\n vm.selectedFolder.$topIndex++;\n }\n else\n // No card is selected, show newest\n index = 0;\n\n if (index < vm.selectedFolder.$cards.length)\n selectCard(vm.selectedFolder.$cards[index]);\n else\n index = -1;\n\n $event.preventDefault();\n\n return index;\n }\n\n function _addNextCardToSelection($event) {\n var index;\n\n if (vm.selectedFolder.hasSelectedCard()) {\n index = _nextCard($event);\n if (index >= 0)\n toggleCardSelection($event, vm.selectedFolder.$cards[index]);\n }\n }\n\n function _addPreviousCardToSelection($event) {\n var index;\n\n if (vm.selectedFolder.hasSelectedCard()) {\n index = _previousCard($event);\n if (index >= 0)\n toggleCardSelection($event, vm.selectedFolder.$cards[index]);\n }\n }\n\n function confirmDeleteSelectedCards($event) {\n var selectedCards = vm.selectedFolder.$selectedCards();\n\n if (_.size(selectedCards) > 0)\n Dialog.confirm(l('Warning'),\n l('Are you sure you want to delete the selected contacts?'),\n { ok: l('Delete') })\n .then(function() {\n // User confirmed the deletion\n vm.selectedFolder.$deleteCards(selectedCards).then(function() {\n vm.mode.multiple = 0;\n if (!vm.selectedFolder.selectedCard)\n $state.go('app.addressbook');\n });\n });\n\n $event.preventDefault();\n }\n\n /**\n * @see AddressBooksController.dragSelectedCards\n */\n function _selectedCardsOperation(operation, dstId) {\n var srcFolder, allCards, cards, ids, clearCardView, promise, success;\n\n srcFolder = vm.selectedFolder;\n clearCardView = false;\n allCards = srcFolder.$selectedCards();\n cards = _.filter(allCards, function(card) {\n return card.$isCard();\n });\n\n if (cards.length != allCards.length)\n $mdToast.show(\n $mdToast.simple()\n .content(l(\"Lists can't be moved or copied.\"))\n .position('top right')\n .hideDelay(2000));\n\n if (cards.length) {\n if (operation == 'copy') {\n promise = srcFolder.$copyCards(cards, dstId);\n success = l('%{0} card(s) copied', cards.length);\n }\n else {\n promise = srcFolder.$moveCards(cards, dstId);\n success = l('%{0} card(s) moved', cards.length);\n // Check if currently displayed card will be moved\n ids = _.map(cards, 'id');\n clearCardView = (srcFolder.selectedCard && ids.indexOf(srcFolder.selectedCard) >= 0);\n }\n\n // Show success toast when action succeeds\n promise.then(function() {\n if (clearCardView)\n $state.go('app.addressbook');\n $mdToast.show(\n $mdToast.simple()\n .content(success)\n .position('top right')\n .hideDelay(2000));\n });\n }\n }\n\n function copySelectedCards(folder) {\n _selectedCardsOperation('copy', folder);\n }\n\n function moveSelectedCards(folder) {\n _selectedCardsOperation('move', folder);\n }\n\n function selectAll() {\n _.forEach(vm.selectedFolder.$cards, function(card) {\n card.selected = true;\n });\n vm.mode.multiple = vm.selectedFolder.$cards.length;\n }\n\n function sort(field) {\n vm.selectedFolder.$filter('', { sort: field });\n }\n\n function sortedBy(field) {\n return AddressBook.$query.sort == field;\n }\n\n function searchMode() {\n vm.mode.search = true;\n focus('search');\n }\n\n function cancelSearch() {\n vm.mode.search = false;\n vm.selectedFolder.$filter('');\n }\n\n function newMessage($event, recipients, recipientsField) {\n Account.$findAll().then(function(accounts) {\n var account = _.find(accounts, function(o) {\n if (o.id === 0)\n return o;\n });\n\n // We must initialize the Account with its mailbox\n // list before proceeding with message's creation\n account.$getMailboxes().then(function(mailboxes) {\n account.$newMessage().then(function(message) {\n message.editable[recipientsField] = recipients;\n $mdDialog.show({\n parent: angular.element(document.body),\n targetEvent: $event,\n clickOutsideToClose: false,\n escapeToClose: false,\n templateUrl: '../Mail/UIxMailEditor',\n controller: 'MessageEditorController',\n controllerAs: 'editor',\n locals: {\n stateAccount: account,\n stateMessage: message\n }\n });\n });\n });\n });\n }\n\n function newMessageWithRecipient($event, recipient, fn) {\n var recipients = [fn + ' <' + recipient + '>'];\n vm.newMessage($event, recipients, 'to');\n $event.stopPropagation();\n $event.preventDefault();\n }\n\n function newMessageWithSelectedCards($event, recipientsField) {\n var selectedCards = _.filter(vm.selectedFolder.$cards, function(card) { return card.selected; });\n var promises = [], recipients = [];\n\n _.forEach(selectedCards, function(card) {\n if (card.$isList({expandable: true})) {\n // If the list's members were already fetch, use them\n if (angular.isDefined(card.refs) && card.refs.length) {\n _.forEach(card.refs, function(ref) {\n if (ref.email.length)\n recipients.push(ref.$shortFormat());\n });\n }\n else {\n promises.push(card.$reload().then(function(card) {\n _.forEach(card.refs, function(ref) {\n if (ref.email.length)\n recipients.push(ref.$shortFormat());\n });\n }));\n }\n }\n else if (card.c_mail.length) {\n recipients.push(card.$shortFormat());\n }\n });\n\n $q.all(promises).then(function() {\n recipients = _.uniq(recipients);\n if (recipients.length)\n vm.newMessage($event, recipients, recipientsField);\n });\n }\n }\n\n angular\n .module('SOGo.ContactsUI')\n .controller('AddressBookController', AddressBookController);\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n AddressBooksController.$inject = ['$q', '$state', '$scope', '$rootScope', '$stateParams', '$timeout', '$window', '$mdDialog', '$mdToast', '$mdMedia', '$mdSidenav', 'FileUploader', 'sgConstant', 'sgHotkeys', 'sgFocus', 'Card', 'AddressBook', 'Dialog', 'sgSettings', 'User', 'stateAddressbooks'];\n function AddressBooksController($q, $state, $scope, $rootScope, $stateParams, $timeout, $window, $mdDialog, $mdToast, $mdMedia, $mdSidenav, FileUploader, sgConstant, sgHotkeys, focus, Card, AddressBook, Dialog, Settings, User, stateAddressbooks) {\n var vm = this, hotkeys = [];\n\n vm.activeUser = Settings.activeUser;\n vm.service = AddressBook;\n vm.select = select;\n vm.newAddressbook = newAddressbook;\n vm.edit = edit;\n vm.revertEditing = revertEditing;\n vm.save = save;\n vm.confirmDelete = confirmDelete;\n vm.importCards = importCards;\n vm.showLinks = showLinks;\n vm.showProperties = showProperties;\n vm.share = share;\n vm.subscribeToFolder = subscribeToFolder;\n vm.isDroppableFolder = isDroppableFolder;\n vm.dragSelectedCards = dragSelectedCards;\n\n\n _registerHotkeys(hotkeys);\n\n $scope.$on('$destroy', function() {\n // Deregister hotkeys\n _.forEach(hotkeys, function(key) {\n sgHotkeys.deregisterHotkey(key);\n });\n });\n\n\n function _registerHotkeys(keys) {\n keys.push(sgHotkeys.createHotkey({\n key: 'backspace',\n description: l('Delete selected card or address book'),\n callback: function() {\n if (AddressBook.selectedFolder && !AddressBook.selectedFolder.hasSelectedCard())\n confirmDelete();\n }\n }));\n\n // Register the hotkeys\n _.forEach(keys, function(key) {\n sgHotkeys.registerHotkey(key);\n });\n }\n\n function select($event, folder) {\n if ($state.params.addressbookId != folder.id &&\n vm.editMode != folder.id) {\n vm.editMode = false;\n AddressBook.$query.value = '';\n // Close sidenav on small devices\n if (!$mdMedia(sgConstant['gt-md']))\n $mdSidenav('left').close();\n $state.go('app.addressbook', {addressbookId: folder.id});\n }\n else {\n $event.preventDefault();\n $event.stopPropagation();\n }\n }\n\n function newAddressbook() {\n Dialog.prompt(l('New Addressbook...'),\n l('Name of the Address Book'))\n .then(function(name) {\n var addressbook = new AddressBook(\n {\n name: name,\n isEditable: true,\n isRemote: false,\n owner: UserLogin\n }\n );\n AddressBook.$add(addressbook);\n });\n }\n\n function edit(folder) {\n if (!folder.isRemote) {\n vm.editMode = folder.id;\n vm.originalAddressbook = angular.extend({}, folder.$omit());\n focus('addressBookName_' + folder.id);\n }\n }\n\n function revertEditing(folder) {\n folder.name = vm.originalAddressbook.name;\n vm.editMode = false;\n }\n\n function save(folder) {\n var name = folder.name;\n if (name && name.length > 0 && name != vm.originalAddressbook.name) {\n folder.$rename(name)\n .then(function(data) {\n vm.editMode = false;\n }, function(data, status) {\n Dialog.alert(l('Warning'), data);\n });\n }\n }\n\n function confirmDelete() {\n if (vm.service.selectedFolder.isSubscription) {\n // Unsubscribe without confirmation\n vm.service.selectedFolder.$delete()\n .then(function() {\n vm.service.selectedFolder = null;\n $state.go('app.addressbook', { addressbookId: 'personal' });\n }, function(data, status) {\n Dialog.alert(l('An error occured while deleting the addressbook \"%{0}\".',\n vm.service.selectedFolder.name),\n l(data.error));\n });\n }\n else {\n Dialog.confirm(l('Warning'), l('Are you sure you want to delete the addressbook \"%{0}\"?',\n vm.service.selectedFolder.name),\n { ok: l('Delete') })\n .then(function() {\n return vm.service.selectedFolder.$delete();\n })\n .then(function() {\n vm.service.selectedFolder = null;\n $state.go('app.addressbook', { addressbookId: 'personal' });\n return true;\n })\n .catch(function(response) {\n if (response) {\n var message = response.data.message || response.statusText;\n Dialog.alert(l('An error occured while deleting the addressbook \"%{0}\".',\n vm.service.selectedFolder.name),\n message);\n }\n });\n }\n }\n\n function importCards($event, folder) {\n $mdDialog.show({\n parent: angular.element(document.body),\n targetEvent: $event,\n clickOutsideToClose: true,\n escapeToClose: true,\n templateUrl: 'UIxContactsImportDialog',\n controller: CardsImportDialogController,\n controllerAs: '$CardsImportDialogController',\n locals: {\n folder: folder\n }\n });\n\n /**\n * @ngInject\n */\n CardsImportDialogController.$inject = ['scope', '$mdDialog', 'folder'];\n function CardsImportDialogController(scope, $mdDialog, folder) {\n var vm = this;\n\n vm.uploader = new FileUploader({\n url: ApplicationBaseURL + [folder.id, 'import'].join('/'),\n autoUpload: true,\n queueLimit: 1,\n filters: [{ name: filterByExtension, fn: filterByExtension }],\n onSuccessItem: function(item, response, status, headers) {\n var msg;\n\n $mdDialog.hide();\n\n if (response.imported === 0)\n msg = l('No card was imported.');\n else {\n msg = l('A total of %{0} cards were imported in the addressbook.', response.imported);\n AddressBook.selectedFolder.$reload();\n }\n\n $mdToast.show(\n $mdToast.simple()\n .content(msg)\n .position('top right')\n .hideDelay(3000));\n },\n onErrorItem: function(item, response, status, headers) {\n $mdToast.show({\n template: [\n '',\n '
',\n ' error_outline',\n ' ' + l('An error occured while importing contacts.') + '',\n '
',\n '
'\n ].join(''),\n position: 'top right',\n hideDelay: 3000\n });\n }\n });\n\n vm.close = function() {\n $mdDialog.hide();\n };\n\n function filterByExtension(item) {\n var isTextFile = item.type.indexOf('text') === 0 ||\n /\\.(ldif|vcf|vcard)$/.test(item.name);\n\n if (!isTextFile)\n $mdToast.show({\n template: [\n '',\n '
',\n ' error_outline',\n ' ' + l('Select a vCard or LDIF file.') + '',\n '
',\n '
'\n ].join(''),\n position: 'top right',\n hideDelay: 3000\n });\n\n return isTextFile;\n }\n }\n }\n\n function showLinks(addressbook) {\n var promise;\n if (addressbook.urls)\n promise = $q.when();\n else\n // Refresh list of addressbooks to fetch links associated to addressbook\n promise = AddressBook.$reloadAll();\n promise.then(function() {\n $mdDialog.show({\n parent: angular.element(document.body),\n clickOutsideToClose: true,\n escapeToClose: true,\n templateUrl: addressbook.id + '/links',\n controller: LinksDialogController,\n controllerAs: 'links',\n locals: {\n addressbook: addressbook\n }\n });\n });\n\n /**\n * @ngInject\n */\n LinksDialogController.$inject = ['$mdDialog', 'addressbook'];\n function LinksDialogController($mdDialog, addressbook) {\n var vm = this;\n this.addressbook = addressbook;\n this.close = close;\n\n function close() {\n $mdDialog.hide();\n }\n }\n }\n\n function showProperties(addressbook) {\n $mdDialog.show({\n templateUrl: addressbook.id + '/properties',\n controller: PropertiesDialogController,\n controllerAs: 'properties',\n clickOutsideToClose: true,\n escapeToClose: true,\n locals: {\n srcAddressBook: addressbook\n }\n }).catch(function() {\n // Do nothing\n });\n\n /**\n * @ngInject\n */\n PropertiesDialogController.$inject = ['$scope', '$mdDialog', 'srcAddressBook'];\n function PropertiesDialogController($scope, $mdDialog, srcAddressBook) {\n var vm = this;\n\n vm.addressbook = new AddressBook(srcAddressBook.$omit());\n vm.saveProperties = saveProperties;\n vm.close = close;\n\n function saveProperties() {\n vm.addressbook.$save().then(function() {\n // Refresh list instance\n srcAddressBook.init(vm.addressbook.$omit());\n $mdDialog.hide();\n });\n }\n\n function close() {\n $mdDialog.cancel();\n }\n }\n }\n\n function share(addressbook) {\n // Fetch list of ACL users\n addressbook.$acl.$users().then(function() {\n // Show ACL editor\n $mdDialog.show({\n templateUrl: addressbook.id + '/UIxAclEditor', // UI/Templates/UIxAclEditor.wox\n controller: 'AclController', // from the ng module SOGo.Common\n controllerAs: 'acl',\n clickOutsideToClose: true,\n escapeToClose: true,\n locals: {\n usersWithACL: addressbook.$acl.users,\n User: User,\n folder: addressbook\n }\n });\n });\n }\n\n /**\n * subscribeToFolder - Callback of sgSubscribe directive\n */\n function subscribeToFolder(addressbookData) {\n console.debug('subscribeToFolder ' + addressbookData.owner + addressbookData.name);\n AddressBook.$subscribe(addressbookData.owner, addressbookData.name).then(function(data) {\n $mdToast.show(\n $mdToast.simple()\n .content(l('Successfully subscribed to address book'))\n .position('top right')\n .hideDelay(3000));\n });\n }\n\n function isDroppableFolder(srcFolder, dstFolder) {\n return (dstFolder.id != srcFolder.id) && (dstFolder.isOwned || dstFolder.acls.objectCreator);\n }\n\n /**\n * @see AddressBookController._selectedCardsOperation\n */\n function dragSelectedCards(srcFolder, dstFolder, mode) {\n var dstId, allCards, cards, ids, clearCardView, promise, success;\n\n dstId = dstFolder.id;\n clearCardView = false;\n allCards = srcFolder.$selectedCards();\n if (allCards.length === 0)\n allCards = [srcFolder.$selectedCard()];\n cards = _.filter(allCards, function(card) {\n return card.$isCard();\n });\n\n if (cards.length != allCards.length)\n $mdToast.show(\n $mdToast.simple()\n .content(l(\"Lists can't be moved or copied.\"))\n .position('top right')\n .hideDelay(2000));\n\n if (cards.length) {\n if (mode == 'copy') {\n promise = srcFolder.$copyCards(cards, dstId);\n success = l('%{0} card(s) copied', cards.length);\n }\n else {\n promise = srcFolder.$moveCards(cards, dstId);\n success = l('%{0} card(s) moved', cards.length);\n // Check if currently displayed card will be moved\n ids = _.map(cards, 'id');\n clearCardView = (srcFolder.selectedCard && ids.indexOf(srcFolder.selectedCard) >= 0);\n }\n\n // Show success toast when action succeeds\n promise.then(function() {\n if (clearCardView)\n $state.go('app.addressbook');\n $mdToast.show(\n $mdToast.simple()\n .content(success)\n .position('top right')\n .hideDelay(2000));\n });\n }\n }\n\n }\n\n angular\n .module('SOGo.ContactsUI')\n .controller('AddressBooksController', AddressBooksController);\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * Controller to view and edit a card\n * @ngInject\n */\n CardController.$inject = ['$scope', '$timeout', '$window', '$mdDialog', 'sgSettings', 'AddressBook', 'Card', 'Dialog', 'sgHotkeys', 'sgFocus', '$state', '$stateParams', 'stateCard'];\n function CardController($scope, $timeout, $window, $mdDialog, sgSettings, AddressBook, Card, Dialog, sgHotkeys, focus, $state, $stateParams, stateCard) {\n var vm = this, hotkeys = [];\n\n vm.card = stateCard;\n\n vm.currentFolder = AddressBook.selectedFolder;\n vm.allEmailTypes = Card.$EMAIL_TYPES;\n vm.allTelTypes = Card.$TEL_TYPES;\n vm.allUrlTypes = Card.$URL_TYPES;\n vm.allAddressTypes = Card.$ADDRESS_TYPES;\n vm.categories = {};\n vm.userFilterResults = [];\n vm.transformCategory = transformCategory;\n vm.addOrgUnit = addOrgUnit;\n vm.addBirthday = addBirthday;\n vm.addScreenName = addScreenName;\n vm.addEmail = addEmail;\n vm.addPhone = addPhone;\n vm.addUrl = addUrl;\n vm.addAddress = addAddress;\n vm.userFilter = userFilter;\n vm.save = save;\n vm.close = close;\n vm.reset = reset;\n vm.cancel = cancel;\n vm.confirmDelete = confirmDelete;\n vm.toggleRawSource = toggleRawSource;\n vm.showRawSource = false;\n\n\n _registerHotkeys(hotkeys);\n\n $scope.$on('$destroy', function() {\n // Deregister hotkeys\n _.forEach(hotkeys, function(key) {\n sgHotkeys.deregisterHotkey(key);\n });\n });\n\n\n function _registerHotkeys(keys) {\n keys.push(sgHotkeys.createHotkey({\n key: 'backspace',\n description: l('Delete'),\n callback: function($event) {\n if (vm.currentFolder.$selectedCount() === 0)\n confirmDelete();\n $event.preventDefault();\n }\n }));\n\n // Register the hotkeys\n _.forEach(keys, function(key) {\n sgHotkeys.registerHotkey(key);\n });\n }\n\n function transformCategory(input) {\n if (angular.isString(input))\n return { value: input };\n else\n return input;\n }\n function addOrgUnit() {\n var i = vm.card.$addOrgUnit('');\n focus('orgUnit_' + i);\n }\n function addBirthday() {\n vm.card.birthday = new Date();\n }\n function addScreenName() {\n vm.card.$addScreenName('');\n }\n function addEmail() {\n var i = vm.card.$addEmail('');\n focus('email_' + i);\n }\n function addPhone() {\n var i = vm.card.$addPhone('');\n focus('phone_' + i);\n }\n function addUrl() {\n var i = vm.card.$addUrl('', '');\n focus('url_' + i);\n }\n function addAddress() {\n var i = vm.card.$addAddress('', '', '', '', '', '', '', '');\n focus('address_' + i);\n }\n function userFilter($query, excludedCards) {\n if ($query.length < sgSettings.minimumSearchLength())\n return [];\n\n return AddressBook.selectedFolder.$filter($query, {dry: true, excludeLists: true}, excludedCards).then(function(cards) {\n return cards;\n });\n }\n function save(form) {\n if (form.$valid) {\n vm.card.$save()\n .then(function(data) {\n var i = _.indexOf(_.map(AddressBook.selectedFolder.$cards, 'id'), vm.card.id);\n if (i < 0) {\n // New card; reload contacts list and show addressbook in which the card has been created\n AddressBook.selectedFolder.$reload();\n }\n else {\n // Update contacts list with new version of the Card object\n AddressBook.selectedFolder.$cards[i] = angular.copy(vm.card);\n }\n $state.go('app.addressbook.card.view', { cardId: vm.card.id });\n });\n }\n }\n function close() {\n $state.go('app.addressbook').then(function() {\n vm.card = null;\n delete AddressBook.selectedFolder.selectedCard;\n });\n }\n function reset(form) {\n vm.card.$reset();\n form.$setPristine();\n }\n function cancel() {\n vm.card.$reset();\n if (vm.card.isNew) {\n // Cancelling the creation of a card\n vm.card = null;\n delete AddressBook.selectedFolder.selectedCard;\n $state.go('app.addressbook', { addressbookId: AddressBook.selectedFolder.id });\n }\n else {\n // Cancelling the edition of an existing card\n $state.go('app.addressbook.card.view', { cardId: vm.card.id });\n }\n }\n function confirmDelete() {\n var card = stateCard;\n\n Dialog.confirm(l('Warning'),\n l('Are you sure you want to delete the card of %{0}?', '' + card.$fullname() + ''),\n { ok: l('Delete') })\n .then(function() {\n // User confirmed the deletion\n AddressBook.selectedFolder.$deleteCards([card])\n .then(function() {\n close();\n }, function(data, status) {\n Dialog.alert(l('Warning'), l('An error occured while deleting the card \"%{0}\".',\n card.$fullname()));\n });\n });\n }\n\n function toggleRawSource($event) {\n if (!vm.showRawSource && !vm.rawSource) {\n Card.$$resource.post(vm.currentFolder.id + '/' + vm.card.id, \"raw\").then(function(data) {\n vm.rawSource = data;\n vm.showRawSource = true;\n });\n }\n else {\n vm.showRawSource = !vm.showRawSource;\n }\n }\n }\n\n angular\n .module('SOGo.ContactsUI')\n .controller('CardController', CardController);\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @name sgAddress\n * @memberof ContactsUI\n * @desc Directive to format a postal address.\n * @ngInject\n */\n function sgAddress() {\n return {\n restrict: 'A',\n scope: { data: '=sgAddress' },\n controller: ['$scope', function($scope) {\n $scope.addressLines = function(data) {\n var lines = [],\n locality_region = [];\n if (data.street) lines.push(data.street);\n if (data.street2) lines.push(data.street2);\n if (data.locality) locality_region.push(data.locality);\n if (data.region) locality_region.push(data.region);\n if (locality_region.length > 0) lines.push(locality_region.join(', '));\n if (data.country) lines.push(data.country);\n if (data.postalcode) lines.push(data.postalcode);\n return lines.join('
');\n };\n }],\n template: '
'\n };\n }\n \n angular\n .module('SOGo.Common')\n .directive('sgAddress', sgAddress);\n})();\n"]} \ No newline at end of file +{"version":3,"sources":["Contacts/Contacts.app.js","Contacts/AddressBookController.js","Contacts/AddressBooksController.js","Contacts/CardController.js","Contacts/sgAddress.directive.js"],"names":["configure","$stateProvider","$urlRouterProvider","state","url","abstract","views","addressbooks","templateUrl","controller","controllerAs","resolve","stateAddressbooks","addressbook","stateAddressbook","card","stateCard","stateNewCard","template","onEnter","onEnterCard","onExit","onExitCard","card@app.addressbook","otherwise","AddressBook","$findAll","window","contactFolders","$q","$state","$stateParams","_","find","id","addressbookId","selectedCard","$reload","reject","Card","tag","contactType","pid","c_component","$cards","cardObject","cardId","go","stateMailbox","runBlock","$rootScope","$log","$on","event","toState","toParams","fromState","fromParams","error","current","previous","rejection","angular","module","config","run","$inject","AddressBookController","$scope","$window","$timeout","$mdDialog","$mdToast","Account","focus","Dialog","Settings","sgHotkeys","_registerHotkeys","keys","push","createHotkey","key","l","description","callback","searchMode","bind","vm","newComponent","toggleCardSelection","_nextCard","_previousCard","_addNextCardToSelection","_addPreviousCardToSelection","confirmDeleteSelectedCards","forEach","registerHotkey","selectCard","$event","selectedIndex","nextSelectedIndex","i","folder","selectedFolder","$selectedCard","selected","mode","multiple","shiftKey","$selectedCount","idsMap","getLength","Math","min","max","preventDefault","stopPropagation","type","unselectCards","index","$selectedCardIndex","isDefined","$topIndex","length","hasSelectedCard","selectedCards","$selectedCards","size","confirm","ok","then","$deleteCards","_selectedCardsOperation","operation","dstId","srcFolder","allCards","cards","ids","clearCardView","promise","success","filter","$isCard","show","simple","content","position","hideDelay","$copyCards","$moveCards","map","indexOf","copySelectedCards","moveSelectedCards","selectAll","sort","field","$filter","sortedBy","$query","search","cancelSearch","newMessage","recipients","recipientsField","accounts","account","o","$getMailboxes","mailboxes","$newMessage","message","editable","parent","element","document","body","targetEvent","clickOutsideToClose","escapeToClose","locals","stateAccount","stateMessage","newMessageWithRecipient","recipient","fn","newMessageWithSelectedCards","promises","$isList","expandable","refs","ref","email","$shortFormat","c_mail","all","uniq","this","hotkeys","service","deregisterHotkey","AddressBooksController","$mdMedia","$mdSidenav","FileUploader","sgConstant","User","confirmDelete","select","params","editMode","value","close","newAddressbook","prompt","name","isEditable","isRemote","owner","UserLogin","$add","edit","originalAddressbook","extend","$omit","revertEditing","save","$rename","data","status","alert","isSubscription","$delete","catch","response","statusText","importCards","CardsImportDialogController","scope","filterByExtension","item","isTextFile","test","join","uploader","ApplicationBaseURL","autoUpload","queueLimit","filters","onSuccessItem","headers","msg","hide","imported","onErrorItem","showLinks","LinksDialogController","urls","when","$reloadAll","showProperties","PropertiesDialogController","srcAddressBook","saveProperties","$save","init","cancel","share","$acl","$users","usersWithACL","users","subscribeToFolder","addressbookData","console","debug","$subscribe","isDroppableFolder","dstFolder","isOwned","acls","objectCreator","dragSelectedCards","activeUser","CardController","sgSettings","currentFolder","transformCategory","input","isString","addOrg","$addOrg","addBirthday","birthday","Date","addScreenName","$addScreenName","addEmail","$addEmail","addPhone","$addPhone","addUrl","$addUrl","addAddress","$addAddress","userFilter","excludedCards","minimumSearchLength","dry","excludeLists","form","$valid","copy","reset","$reset","$setPristine","isNew","$fullname","toggleRawSource","showRawSource","rawSource","$$resource","post","allEmailTypes","$EMAIL_TYPES","allTelTypes","$TEL_TYPES","allUrlTypes","$URL_TYPES","allAddressTypes","$ADDRESS_TYPES","categories","userFilterResults","sgAddress","restrict","addressLines","lines","locality_region","street","street2","locality","region","country","postalcode","directive"],"mappings":"CAGA,WACE,YAUA,SAASA,GAAUC,EAAgBC,GACjCD,EACGE,MAAM,OACLC,IAAK,gBACLC,UAAU,EACVC,OACEC,cACEC,YAAa,wBACbC,WAAY,yBACZC,aAAc,QAGlBC,SACEC,kBAAmBA,KAGtBT,MAAM,mBACLC,IAAK,kBACLE,OACEO,aACEL,YAAa,cACbC,WAAY,wBACZC,aAAc,gBAGlBC,SACEG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KAAK,WAGtBnO,SAAU,yDAId4C,QACGC,OAAO,eACP2R,UAAU,YAAaX","file":"Contacts.js","sourcesContent":["/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n/* JavaScript for SOGoContacts */\n\n(function() {\n 'use strict';\n\n angular.module('SOGo.ContactsUI', ['ngCookies', 'ui.router', 'angularFileUpload', 'ck', 'SOGo.Common', 'SOGo.PreferencesUI', 'SOGo.MailerUI'])\n .config(configure)\n .run(runBlock);\n\n /**\n * @ngInject\n */\n configure.$inject = ['$stateProvider', '$urlRouterProvider'];\n function configure($stateProvider, $urlRouterProvider) {\n $stateProvider\n .state('app', {\n url: '/addressbooks',\n abstract: true,\n views: {\n addressbooks: {\n templateUrl: 'UIxContactFoldersView', // UI/Templates/Contacts/UIxContactFoldersView.wox\n controller: 'AddressBooksController',\n controllerAs: 'app'\n }\n },\n resolve: {\n stateAddressbooks: stateAddressbooks\n }\n })\n .state('app.addressbook', {\n url: '/:addressbookId',\n views: {\n addressbook: {\n templateUrl: 'addressbook',\n controller: 'AddressBookController',\n controllerAs: 'addressbook'\n }\n },\n resolve: {\n stateAddressbook: stateAddressbook\n }\n })\n .state('app.addressbook.new', {\n url: '/{contactType:(?:card|list)}/new',\n views: {\n card: {\n templateUrl: 'UIxContactEditorTemplate', // UI/Templates/Contacts/UIxContactEditorTemplate.wox\n controller: 'CardController',\n controllerAs: 'editor'\n }\n },\n resolve: {\n stateCard: stateNewCard\n }\n })\n .state('app.addressbook.card', {\n url: '/:cardId',\n abstract: true,\n views: {\n card: {\n template: ''\n }\n },\n resolve: {\n stateCard: stateCard\n },\n onEnter: onEnterCard,\n onExit: onExitCard\n })\n .state('app.addressbook.card.view', {\n url: '/view',\n views: {\n 'card@app.addressbook': {\n templateUrl: 'UIxContactViewTemplate', // UI/Templates/Contacts/UIxContactViewTemplate.wox\n controller: 'CardController',\n controllerAs: 'editor'\n }\n }\n })\n .state('app.addressbook.card.editor', {\n url: '/edit',\n views: {\n 'card@app.addressbook': {\n templateUrl: 'UIxContactEditorTemplate', // UI/Templates/Contacts/UIxContactEditorTemplate.wox\n controller: 'CardController',\n controllerAs: 'editor'\n }\n }\n });\n\n // if none of the above states are matched, use this as the fallback\n $urlRouterProvider.otherwise('/addressbooks/personal');\n }\n\n /**\n * @ngInject\n */\n stateAddressbooks.$inject = ['AddressBook'];\n function stateAddressbooks(AddressBook) {\n return AddressBook.$findAll(window.contactFolders);\n }\n\n /**\n * @ngInject\n */\n stateAddressbook.$inject = ['$q', '$state', '$stateParams', 'AddressBook'];\n function stateAddressbook($q, $state, $stateParams, AddressBook) {\n var addressbook = _.find(AddressBook.$findAll(), function(addressbook) {\n return addressbook.id == $stateParams.addressbookId;\n });\n if (addressbook) {\n delete addressbook.selectedCard;\n addressbook.$reload();\n return addressbook;\n }\n return $q.reject('Addressbook ' + $stateParams.addressbookId + ' not found');\n }\n\n /**\n * @ngInject\n */\n stateNewCard.$inject = ['$stateParams', 'stateAddressbook', 'Card'];\n function stateNewCard($stateParams, stateAddressbook, Card) {\n var tag = 'v' + $stateParams.contactType,\n card = new Card({ pid: $stateParams.addressbookId, c_component: tag });\n stateAddressbook.selectedCard = true;\n return card;\n }\n\n /**\n * @ngInject\n */\n stateCard.$inject = ['$state', '$stateParams', 'stateAddressbook'];\n function stateCard($state, $stateParams, stateAddressbook) {\n var card;\n\n card = _.find(stateAddressbook.$cards, function(cardObject) {\n return (cardObject.id == $stateParams.cardId);\n });\n\n if (card) {\n return card.$reload();\n }\n else {\n // Card not found\n $state.go('app.addressbook');\n }\n }\n\n /**\n * @ngInject\n */\n onEnterCard.$inject = ['$stateParams', 'stateAddressbook'];\n function onEnterCard($stateParams, stateAddressbook) {\n stateAddressbook.selectedCard = $stateParams.cardId;\n }\n\n /**\n * @ngInject\n */\n onExitCard.$inject = ['stateAddressbook'];\n function onExitCard(stateMailbox) {\n delete stateAddressbook.selectedCard;\n }\n\n /**\n * @ngInject\n */\n runBlock.$inject = ['$rootScope', '$log', '$state'];\n function runBlock($rootScope, $log, $state) {\n $rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error) {\n $log.error(error);\n $state.go('app.addressbook', { addressbookId: 'personal' });\n });\n $rootScope.$on('$routeChangeError', function(event, current, previous, rejection) {\n $log.error(event, current, previous, rejection);\n });\n }\n\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n AddressBookController.$inject = ['$scope', '$q', '$window', '$state', '$timeout', '$mdDialog', '$mdToast', 'Account', 'Card', 'AddressBook', 'sgFocus', 'Dialog', 'sgSettings', 'sgHotkeys', 'stateAddressbooks', 'stateAddressbook'];\n function AddressBookController($scope, $q, $window, $state, $timeout, $mdDialog, $mdToast, Account, Card, AddressBook, focus, Dialog, Settings, sgHotkeys, stateAddressbooks, stateAddressbook) {\n var vm = this, hotkeys = [];\n\n AddressBook.selectedFolder = stateAddressbook;\n\n vm.service = AddressBook;\n vm.selectedFolder = stateAddressbook;\n vm.selectCard = selectCard;\n vm.toggleCardSelection = toggleCardSelection;\n vm.newComponent = newComponent;\n vm.unselectCards = unselectCards;\n vm.confirmDeleteSelectedCards = confirmDeleteSelectedCards;\n vm.copySelectedCards = copySelectedCards;\n vm.moveSelectedCards = moveSelectedCards;\n vm.selectAll = selectAll;\n vm.sort = sort;\n vm.sortedBy = sortedBy;\n vm.searchMode = searchMode;\n vm.cancelSearch = cancelSearch;\n vm.newMessage = newMessage;\n vm.newMessageWithSelectedCards = newMessageWithSelectedCards;\n vm.newMessageWithRecipient = newMessageWithRecipient;\n vm.mode = { search: false, multiple: 0 };\n\n\n _registerHotkeys(hotkeys);\n\n $scope.$on('$destroy', function() {\n // Deregister hotkeys\n _.forEach(hotkeys, function(key) {\n sgHotkeys.deregisterHotkey(key);\n });\n });\n\n\n function _registerHotkeys(keys) {\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_search'),\n description: l('Search'),\n callback: searchMode\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('key_create_card'),\n description: l('Create a new address book card'),\n callback: angular.bind(vm, newComponent, 'card')\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('key_create_list'),\n description: l('Create a new list'),\n callback: angular.bind(vm, newComponent, 'list')\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'space',\n description: l('Toggle item'),\n callback: toggleCardSelection\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'shift+space',\n description: l('Toggle range of items'),\n callback: toggleCardSelection\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'up',\n description: l('View next item'),\n callback: _nextCard\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'down',\n description: l('View previous item'),\n callback: _previousCard\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'shift+up',\n description: l('Add next item to selection'),\n callback: _addNextCardToSelection\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'shift+down',\n description: l('Add previous item to selection'),\n callback: _addPreviousCardToSelection\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'backspace',\n description: l('Delete selected card or address book'),\n callback: confirmDeleteSelectedCards\n }));\n\n // Register the hotkeys\n _.forEach(keys, function(key) {\n sgHotkeys.registerHotkey(key);\n });\n }\n\n function selectCard(card) {\n $state.go('app.addressbook.card.view', {cardId: card.id});\n }\n\n function toggleCardSelection($event, card) {\n var folder = vm.selectedFolder,\n selectedIndex, nextSelectedIndex, i;\n\n if (!card)\n card = folder.$selectedCard();\n card.selected = !card.selected;\n vm.mode.multiple += card.selected? 1 : -1;\n\n // Select closest range of cards when shift key is pressed\n if ($event.shiftKey && folder.$selectedCount() > 1) {\n selectedIndex = folder.idsMap[card.id];\n // Search for next selected card above\n nextSelectedIndex = selectedIndex - 2;\n while (nextSelectedIndex >= 0 &&\n !folder.$cards[nextSelectedIndex].selected)\n nextSelectedIndex--;\n if (nextSelectedIndex < 0) {\n // Search for next selected card bellow\n nextSelectedIndex = selectedIndex + 2;\n while (nextSelectedIndex < folder.getLength() &&\n !folder.$cards[nextSelectedIndex].selected)\n nextSelectedIndex++;\n }\n if (nextSelectedIndex >= 0 && nextSelectedIndex < folder.getLength()) {\n for (i = Math.min(selectedIndex, nextSelectedIndex);\n i <= Math.max(selectedIndex, nextSelectedIndex);\n i++)\n folder.$cards[i].selected = true;\n }\n }\n\n $event.preventDefault();\n $event.stopPropagation();\n }\n\n function newComponent(type) {\n $state.go('app.addressbook.new', { contactType: type });\n }\n\n function unselectCards() {\n _.forEach(vm.selectedFolder.$cards, function(card) {\n card.selected = false;\n });\n vm.mode.multiple = 0;\n }\n\n /**\n * User has pressed up arrow key\n */\n function _nextCard($event) {\n var index = vm.selectedFolder.$selectedCardIndex();\n\n if (angular.isDefined(index)) {\n index--;\n if (vm.selectedFolder.$topIndex > 0)\n vm.selectedFolder.$topIndex--;\n }\n else {\n // No card is selected, show oldest card\n index = vm.selectedFolder.$cards.length() - 1;\n vm.selectedFolder.$topIndex = vm.selectedFolder.getLength();\n }\n\n if (index > -1)\n selectCard(vm.selectedFolder.$cards[index]);\n\n $event.preventDefault();\n\n return index;\n }\n\n /**\n * User has pressed the down arrow key\n */\n function _previousCard($event) {\n var index = vm.selectedFolder.$selectedCardIndex();\n\n if (angular.isDefined(index)) {\n index++;\n if (vm.selectedFolder.$topIndex < vm.selectedFolder.$cards.length)\n vm.selectedFolder.$topIndex++;\n }\n else\n // No card is selected, show newest\n index = 0;\n\n if (index < vm.selectedFolder.$cards.length)\n selectCard(vm.selectedFolder.$cards[index]);\n else\n index = -1;\n\n $event.preventDefault();\n\n return index;\n }\n\n function _addNextCardToSelection($event) {\n var index;\n\n if (vm.selectedFolder.hasSelectedCard()) {\n index = _nextCard($event);\n if (index >= 0)\n toggleCardSelection($event, vm.selectedFolder.$cards[index]);\n }\n }\n\n function _addPreviousCardToSelection($event) {\n var index;\n\n if (vm.selectedFolder.hasSelectedCard()) {\n index = _previousCard($event);\n if (index >= 0)\n toggleCardSelection($event, vm.selectedFolder.$cards[index]);\n }\n }\n\n function confirmDeleteSelectedCards($event) {\n var selectedCards = vm.selectedFolder.$selectedCards();\n\n if (_.size(selectedCards) > 0)\n Dialog.confirm(l('Warning'),\n l('Are you sure you want to delete the selected contacts?'),\n { ok: l('Delete') })\n .then(function() {\n // User confirmed the deletion\n vm.selectedFolder.$deleteCards(selectedCards).then(function() {\n vm.mode.multiple = 0;\n if (!vm.selectedFolder.selectedCard)\n $state.go('app.addressbook');\n });\n });\n\n $event.preventDefault();\n }\n\n /**\n * @see AddressBooksController.dragSelectedCards\n */\n function _selectedCardsOperation(operation, dstId) {\n var srcFolder, allCards, cards, ids, clearCardView, promise, success;\n\n srcFolder = vm.selectedFolder;\n clearCardView = false;\n allCards = srcFolder.$selectedCards();\n cards = _.filter(allCards, function(card) {\n return card.$isCard();\n });\n\n if (cards.length != allCards.length)\n $mdToast.show(\n $mdToast.simple()\n .content(l(\"Lists can't be moved or copied.\"))\n .position('top right')\n .hideDelay(2000));\n\n if (cards.length) {\n if (operation == 'copy') {\n promise = srcFolder.$copyCards(cards, dstId);\n success = l('%{0} card(s) copied', cards.length);\n }\n else {\n promise = srcFolder.$moveCards(cards, dstId);\n success = l('%{0} card(s) moved', cards.length);\n // Check if currently displayed card will be moved\n ids = _.map(cards, 'id');\n clearCardView = (srcFolder.selectedCard && ids.indexOf(srcFolder.selectedCard) >= 0);\n }\n\n // Show success toast when action succeeds\n promise.then(function() {\n if (clearCardView)\n $state.go('app.addressbook');\n $mdToast.show(\n $mdToast.simple()\n .content(success)\n .position('top right')\n .hideDelay(2000));\n });\n }\n }\n\n function copySelectedCards(folder) {\n _selectedCardsOperation('copy', folder);\n }\n\n function moveSelectedCards(folder) {\n _selectedCardsOperation('move', folder);\n }\n\n function selectAll() {\n _.forEach(vm.selectedFolder.$cards, function(card) {\n card.selected = true;\n });\n vm.mode.multiple = vm.selectedFolder.$cards.length;\n }\n\n function sort(field) {\n vm.selectedFolder.$filter('', { sort: field });\n }\n\n function sortedBy(field) {\n return AddressBook.$query.sort == field;\n }\n\n function searchMode() {\n vm.mode.search = true;\n focus('search');\n }\n\n function cancelSearch() {\n vm.mode.search = false;\n vm.selectedFolder.$filter('');\n }\n\n function newMessage($event, recipients, recipientsField) {\n Account.$findAll().then(function(accounts) {\n var account = _.find(accounts, function(o) {\n if (o.id === 0)\n return o;\n });\n\n // We must initialize the Account with its mailbox\n // list before proceeding with message's creation\n account.$getMailboxes().then(function(mailboxes) {\n account.$newMessage().then(function(message) {\n message.editable[recipientsField] = recipients;\n $mdDialog.show({\n parent: angular.element(document.body),\n targetEvent: $event,\n clickOutsideToClose: false,\n escapeToClose: false,\n templateUrl: '../Mail/UIxMailEditor',\n controller: 'MessageEditorController',\n controllerAs: 'editor',\n locals: {\n stateAccount: account,\n stateMessage: message\n }\n });\n });\n });\n });\n }\n\n function newMessageWithRecipient($event, recipient, fn) {\n var recipients = [fn + ' <' + recipient + '>'];\n vm.newMessage($event, recipients, 'to');\n $event.stopPropagation();\n $event.preventDefault();\n }\n\n function newMessageWithSelectedCards($event, recipientsField) {\n var selectedCards = _.filter(vm.selectedFolder.$cards, function(card) { return card.selected; });\n var promises = [], recipients = [];\n\n _.forEach(selectedCards, function(card) {\n if (card.$isList({expandable: true})) {\n // If the list's members were already fetch, use them\n if (angular.isDefined(card.refs) && card.refs.length) {\n _.forEach(card.refs, function(ref) {\n if (ref.email.length)\n recipients.push(ref.$shortFormat());\n });\n }\n else {\n promises.push(card.$reload().then(function(card) {\n _.forEach(card.refs, function(ref) {\n if (ref.email.length)\n recipients.push(ref.$shortFormat());\n });\n }));\n }\n }\n else if (card.c_mail.length) {\n recipients.push(card.$shortFormat());\n }\n });\n\n $q.all(promises).then(function() {\n recipients = _.uniq(recipients);\n if (recipients.length)\n vm.newMessage($event, recipients, recipientsField);\n });\n }\n }\n\n angular\n .module('SOGo.ContactsUI')\n .controller('AddressBookController', AddressBookController);\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n AddressBooksController.$inject = ['$q', '$state', '$scope', '$rootScope', '$stateParams', '$timeout', '$window', '$mdDialog', '$mdToast', '$mdMedia', '$mdSidenav', 'FileUploader', 'sgConstant', 'sgHotkeys', 'sgFocus', 'Card', 'AddressBook', 'Dialog', 'sgSettings', 'User', 'stateAddressbooks'];\n function AddressBooksController($q, $state, $scope, $rootScope, $stateParams, $timeout, $window, $mdDialog, $mdToast, $mdMedia, $mdSidenav, FileUploader, sgConstant, sgHotkeys, focus, Card, AddressBook, Dialog, Settings, User, stateAddressbooks) {\n var vm = this, hotkeys = [];\n\n vm.activeUser = Settings.activeUser;\n vm.service = AddressBook;\n vm.select = select;\n vm.newAddressbook = newAddressbook;\n vm.edit = edit;\n vm.revertEditing = revertEditing;\n vm.save = save;\n vm.confirmDelete = confirmDelete;\n vm.importCards = importCards;\n vm.showLinks = showLinks;\n vm.showProperties = showProperties;\n vm.share = share;\n vm.subscribeToFolder = subscribeToFolder;\n vm.isDroppableFolder = isDroppableFolder;\n vm.dragSelectedCards = dragSelectedCards;\n\n\n _registerHotkeys(hotkeys);\n\n $scope.$on('$destroy', function() {\n // Deregister hotkeys\n _.forEach(hotkeys, function(key) {\n sgHotkeys.deregisterHotkey(key);\n });\n });\n\n\n function _registerHotkeys(keys) {\n keys.push(sgHotkeys.createHotkey({\n key: 'backspace',\n description: l('Delete selected card or address book'),\n callback: function() {\n if (AddressBook.selectedFolder && !AddressBook.selectedFolder.hasSelectedCard())\n confirmDelete();\n }\n }));\n\n // Register the hotkeys\n _.forEach(keys, function(key) {\n sgHotkeys.registerHotkey(key);\n });\n }\n\n function select($event, folder) {\n if ($state.params.addressbookId != folder.id &&\n vm.editMode != folder.id) {\n vm.editMode = false;\n AddressBook.$query.value = '';\n // Close sidenav on small devices\n if (!$mdMedia(sgConstant['gt-md']))\n $mdSidenav('left').close();\n $state.go('app.addressbook', {addressbookId: folder.id});\n }\n else {\n $event.preventDefault();\n $event.stopPropagation();\n }\n }\n\n function newAddressbook() {\n Dialog.prompt(l('New Addressbook...'),\n l('Name of the Address Book'))\n .then(function(name) {\n var addressbook = new AddressBook(\n {\n name: name,\n isEditable: true,\n isRemote: false,\n owner: UserLogin\n }\n );\n AddressBook.$add(addressbook);\n });\n }\n\n function edit(folder) {\n if (!folder.isRemote) {\n vm.editMode = folder.id;\n vm.originalAddressbook = angular.extend({}, folder.$omit());\n focus('addressBookName_' + folder.id);\n }\n }\n\n function revertEditing(folder) {\n folder.name = vm.originalAddressbook.name;\n vm.editMode = false;\n }\n\n function save(folder) {\n var name = folder.name;\n if (name && name.length > 0 && name != vm.originalAddressbook.name) {\n folder.$rename(name)\n .then(function(data) {\n vm.editMode = false;\n }, function(data, status) {\n Dialog.alert(l('Warning'), data);\n });\n }\n }\n\n function confirmDelete() {\n if (vm.service.selectedFolder.isSubscription) {\n // Unsubscribe without confirmation\n vm.service.selectedFolder.$delete()\n .then(function() {\n vm.service.selectedFolder = null;\n $state.go('app.addressbook', { addressbookId: 'personal' });\n }, function(data, status) {\n Dialog.alert(l('An error occured while deleting the addressbook \"%{0}\".',\n vm.service.selectedFolder.name),\n l(data.error));\n });\n }\n else {\n Dialog.confirm(l('Warning'), l('Are you sure you want to delete the addressbook \"%{0}\"?',\n vm.service.selectedFolder.name),\n { ok: l('Delete') })\n .then(function() {\n return vm.service.selectedFolder.$delete();\n })\n .then(function() {\n vm.service.selectedFolder = null;\n $state.go('app.addressbook', { addressbookId: 'personal' });\n return true;\n })\n .catch(function(response) {\n if (response) {\n var message = response.data.message || response.statusText;\n Dialog.alert(l('An error occured while deleting the addressbook \"%{0}\".',\n vm.service.selectedFolder.name),\n message);\n }\n });\n }\n }\n\n function importCards($event, folder) {\n $mdDialog.show({\n parent: angular.element(document.body),\n targetEvent: $event,\n clickOutsideToClose: true,\n escapeToClose: true,\n templateUrl: 'UIxContactsImportDialog',\n controller: CardsImportDialogController,\n controllerAs: '$CardsImportDialogController',\n locals: {\n folder: folder\n }\n });\n\n /**\n * @ngInject\n */\n CardsImportDialogController.$inject = ['scope', '$mdDialog', 'folder'];\n function CardsImportDialogController(scope, $mdDialog, folder) {\n var vm = this;\n\n vm.uploader = new FileUploader({\n url: ApplicationBaseURL + [folder.id, 'import'].join('/'),\n autoUpload: true,\n queueLimit: 1,\n filters: [{ name: filterByExtension, fn: filterByExtension }],\n onSuccessItem: function(item, response, status, headers) {\n var msg;\n\n $mdDialog.hide();\n\n if (response.imported === 0)\n msg = l('No card was imported.');\n else {\n msg = l('A total of %{0} cards were imported in the addressbook.', response.imported);\n AddressBook.selectedFolder.$reload();\n }\n\n $mdToast.show(\n $mdToast.simple()\n .content(msg)\n .position('top right')\n .hideDelay(3000));\n },\n onErrorItem: function(item, response, status, headers) {\n $mdToast.show({\n template: [\n '',\n '
',\n ' error_outline',\n ' ' + l('An error occured while importing contacts.') + '',\n '
',\n '
'\n ].join(''),\n position: 'top right',\n hideDelay: 3000\n });\n }\n });\n\n vm.close = function() {\n $mdDialog.hide();\n };\n\n function filterByExtension(item) {\n var isTextFile = item.type.indexOf('text') === 0 ||\n /\\.(ldif|vcf|vcard)$/.test(item.name);\n\n if (!isTextFile)\n $mdToast.show({\n template: [\n '',\n '
',\n ' error_outline',\n ' ' + l('Select a vCard or LDIF file.') + '',\n '
',\n '
'\n ].join(''),\n position: 'top right',\n hideDelay: 3000\n });\n\n return isTextFile;\n }\n }\n }\n\n function showLinks(addressbook) {\n var promise;\n if (addressbook.urls)\n promise = $q.when();\n else\n // Refresh list of addressbooks to fetch links associated to addressbook\n promise = AddressBook.$reloadAll();\n promise.then(function() {\n $mdDialog.show({\n parent: angular.element(document.body),\n clickOutsideToClose: true,\n escapeToClose: true,\n templateUrl: addressbook.id + '/links',\n controller: LinksDialogController,\n controllerAs: 'links',\n locals: {\n addressbook: addressbook\n }\n });\n });\n\n /**\n * @ngInject\n */\n LinksDialogController.$inject = ['$mdDialog', 'addressbook'];\n function LinksDialogController($mdDialog, addressbook) {\n var vm = this;\n this.addressbook = addressbook;\n this.close = close;\n\n function close() {\n $mdDialog.hide();\n }\n }\n }\n\n function showProperties(addressbook) {\n $mdDialog.show({\n templateUrl: addressbook.id + '/properties',\n controller: PropertiesDialogController,\n controllerAs: 'properties',\n clickOutsideToClose: true,\n escapeToClose: true,\n locals: {\n srcAddressBook: addressbook\n }\n }).catch(function() {\n // Do nothing\n });\n\n /**\n * @ngInject\n */\n PropertiesDialogController.$inject = ['$scope', '$mdDialog', 'srcAddressBook'];\n function PropertiesDialogController($scope, $mdDialog, srcAddressBook) {\n var vm = this;\n\n vm.addressbook = new AddressBook(srcAddressBook.$omit());\n vm.saveProperties = saveProperties;\n vm.close = close;\n\n function saveProperties() {\n vm.addressbook.$save().then(function() {\n // Refresh list instance\n srcAddressBook.init(vm.addressbook.$omit());\n $mdDialog.hide();\n });\n }\n\n function close() {\n $mdDialog.cancel();\n }\n }\n }\n\n function share(addressbook) {\n // Fetch list of ACL users\n addressbook.$acl.$users().then(function() {\n // Show ACL editor\n $mdDialog.show({\n templateUrl: addressbook.id + '/UIxAclEditor', // UI/Templates/UIxAclEditor.wox\n controller: 'AclController', // from the ng module SOGo.Common\n controllerAs: 'acl',\n clickOutsideToClose: true,\n escapeToClose: true,\n locals: {\n usersWithACL: addressbook.$acl.users,\n User: User,\n folder: addressbook\n }\n });\n });\n }\n\n /**\n * subscribeToFolder - Callback of sgSubscribe directive\n */\n function subscribeToFolder(addressbookData) {\n console.debug('subscribeToFolder ' + addressbookData.owner + addressbookData.name);\n AddressBook.$subscribe(addressbookData.owner, addressbookData.name).then(function(data) {\n $mdToast.show(\n $mdToast.simple()\n .content(l('Successfully subscribed to address book'))\n .position('top right')\n .hideDelay(3000));\n });\n }\n\n function isDroppableFolder(srcFolder, dstFolder) {\n return (dstFolder.id != srcFolder.id) && (dstFolder.isOwned || dstFolder.acls.objectCreator);\n }\n\n /**\n * @see AddressBookController._selectedCardsOperation\n */\n function dragSelectedCards(srcFolder, dstFolder, mode) {\n var dstId, allCards, cards, ids, clearCardView, promise, success;\n\n dstId = dstFolder.id;\n clearCardView = false;\n allCards = srcFolder.$selectedCards();\n if (allCards.length === 0)\n allCards = [srcFolder.$selectedCard()];\n cards = _.filter(allCards, function(card) {\n return card.$isCard();\n });\n\n if (cards.length != allCards.length)\n $mdToast.show(\n $mdToast.simple()\n .content(l(\"Lists can't be moved or copied.\"))\n .position('top right')\n .hideDelay(2000));\n\n if (cards.length) {\n if (mode == 'copy') {\n promise = srcFolder.$copyCards(cards, dstId);\n success = l('%{0} card(s) copied', cards.length);\n }\n else {\n promise = srcFolder.$moveCards(cards, dstId);\n success = l('%{0} card(s) moved', cards.length);\n // Check if currently displayed card will be moved\n ids = _.map(cards, 'id');\n clearCardView = (srcFolder.selectedCard && ids.indexOf(srcFolder.selectedCard) >= 0);\n }\n\n // Show success toast when action succeeds\n promise.then(function() {\n if (clearCardView)\n $state.go('app.addressbook');\n $mdToast.show(\n $mdToast.simple()\n .content(success)\n .position('top right')\n .hideDelay(2000));\n });\n }\n }\n\n }\n\n angular\n .module('SOGo.ContactsUI')\n .controller('AddressBooksController', AddressBooksController);\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * Controller to view and edit a card\n * @ngInject\n */\n CardController.$inject = ['$scope', '$timeout', '$window', '$mdDialog', 'sgSettings', 'AddressBook', 'Card', 'Dialog', 'sgHotkeys', 'sgFocus', '$state', '$stateParams', 'stateCard'];\n function CardController($scope, $timeout, $window, $mdDialog, sgSettings, AddressBook, Card, Dialog, sgHotkeys, focus, $state, $stateParams, stateCard) {\n var vm = this, hotkeys = [];\n\n vm.card = stateCard;\n\n vm.currentFolder = AddressBook.selectedFolder;\n vm.allEmailTypes = Card.$EMAIL_TYPES;\n vm.allTelTypes = Card.$TEL_TYPES;\n vm.allUrlTypes = Card.$URL_TYPES;\n vm.allAddressTypes = Card.$ADDRESS_TYPES;\n vm.categories = {};\n vm.userFilterResults = [];\n vm.transformCategory = transformCategory;\n vm.addOrg = addOrg;\n vm.addBirthday = addBirthday;\n vm.addScreenName = addScreenName;\n vm.addEmail = addEmail;\n vm.addPhone = addPhone;\n vm.addUrl = addUrl;\n vm.addAddress = addAddress;\n vm.userFilter = userFilter;\n vm.save = save;\n vm.close = close;\n vm.reset = reset;\n vm.cancel = cancel;\n vm.confirmDelete = confirmDelete;\n vm.toggleRawSource = toggleRawSource;\n vm.showRawSource = false;\n\n\n _registerHotkeys(hotkeys);\n\n $scope.$on('$destroy', function() {\n // Deregister hotkeys\n _.forEach(hotkeys, function(key) {\n sgHotkeys.deregisterHotkey(key);\n });\n });\n\n\n function _registerHotkeys(keys) {\n keys.push(sgHotkeys.createHotkey({\n key: 'backspace',\n description: l('Delete'),\n callback: function($event) {\n if (vm.currentFolder.$selectedCount() === 0)\n confirmDelete();\n $event.preventDefault();\n }\n }));\n\n // Register the hotkeys\n _.forEach(keys, function(key) {\n sgHotkeys.registerHotkey(key);\n });\n }\n\n function transformCategory(input) {\n if (angular.isString(input))\n return { value: input };\n else\n return input;\n }\n function addOrg() {\n var i = vm.card.$addOrg({ value: '' });\n focus('org_' + i);\n }\n function addBirthday() {\n vm.card.birthday = new Date();\n }\n function addScreenName() {\n vm.card.$addScreenName('');\n }\n function addEmail() {\n var i = vm.card.$addEmail('');\n focus('email_' + i);\n }\n function addPhone() {\n var i = vm.card.$addPhone('');\n focus('phone_' + i);\n }\n function addUrl() {\n var i = vm.card.$addUrl('', '');\n focus('url_' + i);\n }\n function addAddress() {\n var i = vm.card.$addAddress('', '', '', '', '', '', '', '');\n focus('address_' + i);\n }\n function userFilter($query, excludedCards) {\n if ($query.length < sgSettings.minimumSearchLength())\n return [];\n\n return AddressBook.selectedFolder.$filter($query, {dry: true, excludeLists: true}, excludedCards).then(function(cards) {\n return cards;\n });\n }\n function save(form) {\n if (form.$valid) {\n vm.card.$save()\n .then(function(data) {\n var i = _.indexOf(_.map(AddressBook.selectedFolder.$cards, 'id'), vm.card.id);\n if (i < 0) {\n // New card; reload contacts list and show addressbook in which the card has been created\n AddressBook.selectedFolder.$reload();\n }\n else {\n // Update contacts list with new version of the Card object\n AddressBook.selectedFolder.$cards[i] = angular.copy(vm.card);\n }\n $state.go('app.addressbook.card.view', { cardId: vm.card.id });\n });\n }\n }\n function close() {\n $state.go('app.addressbook').then(function() {\n vm.card = null;\n delete AddressBook.selectedFolder.selectedCard;\n });\n }\n function reset(form) {\n vm.card.$reset();\n form.$setPristine();\n }\n function cancel() {\n vm.card.$reset();\n if (vm.card.isNew) {\n // Cancelling the creation of a card\n vm.card = null;\n delete AddressBook.selectedFolder.selectedCard;\n $state.go('app.addressbook', { addressbookId: AddressBook.selectedFolder.id });\n }\n else {\n // Cancelling the edition of an existing card\n $state.go('app.addressbook.card.view', { cardId: vm.card.id });\n }\n }\n function confirmDelete() {\n var card = stateCard;\n\n Dialog.confirm(l('Warning'),\n l('Are you sure you want to delete the card of %{0}?', '' + card.$fullname() + ''),\n { ok: l('Delete') })\n .then(function() {\n // User confirmed the deletion\n AddressBook.selectedFolder.$deleteCards([card])\n .then(function() {\n close();\n }, function(data, status) {\n Dialog.alert(l('Warning'), l('An error occured while deleting the card \"%{0}\".',\n card.$fullname()));\n });\n });\n }\n\n function toggleRawSource($event) {\n if (!vm.showRawSource && !vm.rawSource) {\n Card.$$resource.post(vm.currentFolder.id + '/' + vm.card.id, \"raw\").then(function(data) {\n vm.rawSource = data;\n vm.showRawSource = true;\n });\n }\n else {\n vm.showRawSource = !vm.showRawSource;\n }\n }\n }\n\n angular\n .module('SOGo.ContactsUI')\n .controller('CardController', CardController);\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @name sgAddress\n * @memberof ContactsUI\n * @desc Directive to format a postal address.\n * @ngInject\n */\n function sgAddress() {\n return {\n restrict: 'A',\n scope: { data: '=sgAddress' },\n controller: ['$scope', function($scope) {\n $scope.addressLines = function(data) {\n var lines = [],\n locality_region = [];\n if (data.street) lines.push(data.street);\n if (data.street2) lines.push(data.street2);\n if (data.locality) locality_region.push(data.locality);\n if (data.region) locality_region.push(data.region);\n if (locality_region.length > 0) lines.push(locality_region.join(', '));\n if (data.country) lines.push(data.country);\n if (data.postalcode) lines.push(data.postalcode);\n return lines.join('
');\n };\n }],\n template: '
'\n };\n }\n \n angular\n .module('SOGo.Common')\n .directive('sgAddress', sgAddress);\n})();\n"]} \ No newline at end of file diff --git a/UI/WebServerResources/js/Contacts.services.js b/UI/WebServerResources/js/Contacts.services.js index 8ea015e3e..6db09aae9 100644 --- a/UI/WebServerResources/js/Contacts.services.js +++ b/UI/WebServerResources/js/Contacts.services.js @@ -1,2 +1,2 @@ -!function(){"use strict";function a(b){if("function"!=typeof b.then)if(this.init(b),this.name&&!this.id){var c=a.$$resource.create("createFolder",this.name);this.$unwrap(c),this.acls={objectEditor:1,objectCreator:1,objectEraser:1}}else this.id&&(this.$acl=new a.$$Acl("Contacts/"+this.id));else this.$unwrap(b)}a.$factory=["$q","$timeout","$log","sgSettings","sgAddressBook_PRELOAD","Resource","Card","Acl","Preferences",function(b,c,d,e,f,g,h,i,j){return angular.extend(a,{$q:b,$timeout:c,$log:d,PRELOAD:f,$$resource:new g(e.activeUser("folderURL")+"Contacts",e.activeUser()),$Card:h,$$Acl:i,$Preferences:j,$query:{search:"name_or_address",value:"",sort:"c_cn",asc:1},activeUser:e.activeUser(),selectedFolder:null,$refreshTimeout:null}),j.ready().then(function(){j.settings.Contact.SortingState&&(a.$query.sort=j.settings.Contact.SortingState[0],a.$query.asc=parseInt(j.settings.Contact.SortingState[1]))}),a}];try{angular.module("SOGo.ContactsUI")}catch(a){angular.module("SOGo.ContactsUI",["SOGo.Common","SOGo.PreferencesUI"])}angular.module("SOGo.ContactsUI").constant("sgAddressBook_PRELOAD",{LOOKAHEAD:50,SIZE:100}).factory("AddressBook",a.$factory),a.$filterAll=function(b,c,d){var e={search:b};return b?(angular.isUndefined(a.$cards)&&(a.$cards=[]),angular.extend(e,c),a.$$resource.fetch(null,"allContactSearch",e).then(function(c){var e,f,g,h=function(a){return this.id==a.id};for(e=d?_.filter(c.contacts,function(a){return _.isUndefined(_.find(d,_.bind(h,a)))}):c.contacts,g=a.$cards.length-1;g>=0;g--)f=a.$cards[g],_.isUndefined(_.find(e,_.bind(h,f)))&&a.$cards.splice(g,1);return _.forEach(e,function(c,d){if(_.isUndefined(_.find(a.$cards,_.bind(h,c)))){var e=new a.$Card(_.mapKeys(c,function(a,b){return b.toLowerCase()}),b);a.$cards.splice(d,0,e)}}),a.$log.debug(a.$cards),a.$cards})):(a.$cards=[],a.$q.when(a.$cards))},a.$add=function(a){var b,c,d;b=a.isSubscription?this.$subscriptions:this.$addressbooks,c=_.find(b,function(b){return"personal"==a.id||"personal"!=b.id&&1===b.name.localeCompare(a.name)}),d=c?_.indexOf(_.map(b,"id"),c.id):1,b.splice(d,0,a)},a.$findAll=function(b){var c=this;return b&&(this.$addressbooks=[],this.$subscriptions=[],this.$remotes=[],angular.forEach(b,function(b,d){var e=new a(b);e.isRemote?c.$remotes.push(e):e.isSubscription?c.$subscriptions.push(e):c.$addressbooks.push(e)})),_.union(this.$addressbooks,this.$subscriptions,this.$remotes)},a.$subscribe=function(b,c){var d=this;return a.$$resource.userResource(b).fetch(c,"subscribe").then(function(b){var c=new a(b);return _.isUndefined(_.find(d.$subscriptions,function(a){return a.id==b.id}))&&a.$add(c),c})},a.$reloadAll=function(){var b=this;return a.$$resource.fetch("addressbooksList").then(function(c){_.forEach(c.addressbooks,function(c){var d,e;d=c.isRemote?b.$remotes:c.owner!=a.activeUser.login?b.$subscriptions:b.$addressbooks,e=_.find(d,function(a){return a.id==c.id}),e&&e.init(c)})})},a.prototype.init=function(b,c){var d=this;this.$$cards||(this.$$cards=[]),this.idsMap={},this.$cards=[],angular.forEach(b,function(a,b){"headers"!=b&&"cards"!=b&&(d[b]=a)}),this.isOwned=a.activeUser.isSuperUser||this.owner==a.activeUser.login,this.isSubscription=!this.isRemote&&this.owner!=a.activeUser.login},a.prototype.$id=function(){return this.id?a.$q.when(this.id):this.$futureAddressBookData.then(function(a){return a.id})},a.prototype.getLength=function(){return this.$cards.length},a.prototype.getItemAtIndex=function(a){var b;return!this.$isLoading&&a>=0&&a0&&(f=a.$$resource.post(this.id,"headers",{ids:e}),this.$unwrapHeaders(f))}return j},a.prototype.hasSelectedCard=function(){return angular.isDefined(this.selectedCard)},a.prototype.isSelectedCard=function(a){return this.hasSelectedCard()&&this.selectedCard==a},a.prototype.$selectedCard=function(){var a=this;return _.find(this.$cards,function(b){return b.id==a.selectedCard})},a.prototype.$selectedCardIndex=function(){return _.indexOf(_.map(this.$cards,"id"),this.selectedCard)},a.prototype.$selectedCards=function(){return _.filter(this.$cards,function(a){return a.selected})},a.prototype.$selectedCount=function(){var a;return a=0,this.$cards&&(a=_.filter(this.$cards,function(a){return a.selected}).length),a},a.prototype.$startRefreshTimeout=function(){var b=this;a.$refreshTimeout&&a.$timeout.cancel(a.$refreshTimeout),a.$Preferences.ready().then(function(){var c=a.$Preferences.defaults.SOGoRefreshViewCheck;if(c&&"manually"!=c){var d=angular.bind(b,a.prototype.$reload);a.$refreshTimeout=a.$timeout(d,1e3*c.timeInterval())}})},a.prototype.$reload=function(){return this.$startRefreshTimeout(),this.$filter()},a.prototype.$filter=function(b,c,d){var e,f=this,g=c&&c.dry;return g?e=angular.copy(a.$query):(this.$isLoading=!0,e=a.$query,this.isRemote||(e.partial=1)),a.$Preferences.ready().then(function(){return c&&(angular.extend(e,c),g&&!b)?(f.$$cards=[],a.$q.when(f.$$cards)):(angular.isDefined(b)&&(e.value=b),f.$id().then(function(c){var h=a.$$resource.fetch(c,"view",e);return g?h.then(function(e){var g,h,i,j,k,l=f.$$cards,m=function(a){return this==a.id};for(e.headers&&(j=_.invokeMap(e.headers[0],"toLowerCase"),k=j.indexOf("id"),e.headers.splice(0,1)),g=d?_.filter(e.ids,function(a){return _.isUndefined(_.find(d,_.bind(m,a)))}):e.ids,i=l.length-1;i>=0;i--)h=l[i],_.isUndefined(_.find(g,_.bind(m,h.id)))&&l.splice(i,1);return _.forEach(g,function(d,e){if(_.isUndefined(_.find(l,_.bind(m,d)))){var f={pid:c,id:d},g=new a.$Card(f,b);l.splice(e,0,g)}}),_.forEach(g,function(a,b){var c,d;l[b].id!=a&&(c=_.findIndex(l,_.bind(m,a)),d=l.splice(c,1),l.splice(b,0,d[0]))}),_.forEach(e.headers,function(a){var c,d=_.findIndex(l,_.bind(m,a[k]));d>-1&&(c=_.zipObject(j,a),l[d].init(c,b))}),l}):f.$unwrap(h)}))})},a.prototype.$rename=function(b){var c,d;return d=this.isSubscription?a.$subscriptions:a.$addressbooks,c=_.indexOf(_.map(d,"id"),this.id),this.name=b,d.splice(c,1),a.$add(this),this.$save()},a.prototype.$delete=function(){var b,c,d=this,e=a.$q.defer();return this.isSubscription?(c=a.$$resource.fetch(this.id,"unsubscribe"),b=a.$subscriptions):(c=a.$$resource.remove(this.id),b=a.$addressbooks),c.then(function(){var a=_.indexOf(_.map(b,"id"),d.id);b.splice(a,1),e.resolve()},e.reject),e.promise},a.prototype.$_deleteCards=function(a){var b=this;_.forEachRight(this.$cards,function(c,d){var e=_.findIndex(a,function(a){return c.id==a});e>-1?(a.splice(e,1),delete b.idsMap[c.id],b.isSelectedCard(c.id)&&delete b.selectedCard,b.$cards.splice(d,1)):b.idsMap[c.id]-=a.length})},a.prototype.$deleteCards=function(b){var c=this,d=_.map(b,"id");return a.$$resource.post(this.id,"batchDelete",{uids:d}).then(function(){c.$_deleteCards(d)})},a.prototype.$copyCards=function(b,c){var d=_.map(b,"id");return a.$$resource.post(this.id,"copy",{uids:d,folder:c})},a.prototype.$moveCards=function(b,c){var d,e=this;return d=_.map(b,"id"),a.$$resource.post(this.id,"move",{uids:d,folder:c}).then(function(){return e.$_deleteCards(d)})},a.prototype.$save=function(){return a.$$resource.save(this.id,this.$omit()).then(function(a){return a})},a.prototype.exportCards=function(b){var c,d,e=null;return c={type:"application/octet-stream",filename:this.name+".ldif"},b&&(d=_.filter(this.$cards,function(a){return a.selected}),e={uids:_.map(d,"id")}),a.$$resource.download(this.id,"export",e,c)},a.prototype.$unwrap=function(b){var c=this;this.$isLoading=!0,this.$futureAddressBookData=b.then(function(b){return a.$timeout(function(){var d;return(!b.ids||c.$topIndex>b.ids.length-1)&&(c.$topIndex=0),angular.forEach(a.$findAll(),function(a,d){a.id==b.id&&angular.extend(c,a)}),c.init(b),c.ids&&(a.$log.debug("unwrapping "+c.ids.length+" cards"),_.reduce(c.ids,function(b,d,e){var f={pid:c.id,id:d};return c.idsMap[f.id]=e,b.push(new a.$Card(f)),b},c.$cards)),b.headers&&(d=_.invokeMap(b.headers[0],"toLowerCase"),b.headers.splice(0,1),c.ids?_.forEach(b.headers,function(a){var b=_.zipObject(d,a),e=c.idsMap[b.id];c.$cards[e].init(b)}):(c.$cards=[],angular.forEach(b.headers,function(b){var e=_.zipObject(d,b);angular.extend(e,{pid:c.id}),c.$cards.push(new a.$Card(e))}))),c.$acl=new a.$$Acl("Contacts/"+c.id),c.$startRefreshTimeout(),c.$isLoading=!1,a.$log.debug("addressbook "+c.id+" ready"),c})},function(b){c.isError=!0,angular.isObject(b)&&a.$timeout(function(){angular.extend(c,b)})})},a.prototype.$unwrapHeaders=function(b){var c=this;b.then(function(b){a.$timeout(function(){var a,d;b.length>0&&(a=_.invokeMap(b[0],"toLowerCase"),b.splice(0,1),_.forEach(b,function(b){b=_.zipObject(a,b),d=c.idsMap[b.id],angular.isDefined(d)&&c.$cards[d].init(b)}))})})},a.prototype.$omit=function(){var a={};return angular.forEach(this,function(b,c){"constructor"!=c&&"acls"!=c&&"ids"!=c&&"idsMap"!=c&&"urls"!=c&&"$"!=c[0]&&(a[c]=b)}),a}}(),function(){"use strict";function a(b,c){if("function"!=typeof b.then){if(this.init(b,c),this.pid&&!this.id){var d=a.$$resource.newguid(this.pid);this.$unwrap(d),this.isNew=!0}}else this.$unwrap(b)}a.$TEL_TYPES=["work","home","cell","fax","pager"],a.$EMAIL_TYPES=["work","home","pref"],a.$URL_TYPES=["work","home","pref"],a.$ADDRESS_TYPES=["work","home"],a.$factory=["$timeout","sgSettings","sgCard_STATUS","Resource","Preferences",function(b,c,d,e,f){return angular.extend(a,{STATUS:d,$$resource:new e(c.activeUser("folderURL")+"Contacts",c.activeUser()),$timeout:b,$Preferences:f}),f.ready().then(function(){f.defaults.SOGoContactsCategories&&(a.$categories=f.defaults.SOGoContactsCategories),f.defaults.SOGoAlternateAvatar&&(a.$alternateAvatar=f.defaults.SOGoAlternateAvatar)}),a}];try{angular.module("SOGo.ContactsUI")}catch(a){angular.module("SOGo.ContactsUI",["SOGo.Common","SOGo.PreferencesUI"])}angular.module("SOGo.ContactsUI").constant("sgCard_STATUS",{NOT_LOADED:0,DELAYED_LOADING:1,LOADING:2,LOADED:3,DELAYED_MS:300}).factory("Card",a.$factory),a.$find=function(b,c){var d=this.$$resource.fetch([b,c].join("/"),"view");return c?new a(d):a.$unwrapCollection(d)},a.filterCategories=function(b){var c=new RegExp(b,"i");return _.map(_.filter(a.$categories,function(a){return a.search(c)!=-1}),function(a){return{value:a}})},a.$unwrapCollection=function(b){var c={};return c.$futureCardData=b,b.then(function(b){a.$timeout(function(){angular.forEach(b,function(b,d){c[b.id]=new a(b)})})}),c},a.prototype.init=function(b,c){var d=this;this.refs=[],this.categories=[],this.c_screenname=null,angular.extend(this,b),this.$$fullname||(this.$$fullname=this.$fullname()),this.$$email||(this.$$email=this.$preferredEmail(c)),this.$$image||(this.$$image=this.image),this.$$image||a.$Preferences.avatar(this.$$email,32,{no_404:!0}).then(function(a){d.$$image=a}),this.hasphoto&&(this.photoURL=a.$$resource.path(this.pid,this.id,"photo")),this.isgroup&&(this.c_component="vlist"),this.$avatarIcon=this.$isList()?"group":"person",b.notes&&b.notes.length?this.notes=_.map(b.notes,function(a){return{value:a}}):this.notes&&this.notes.length||(this.notes=[{value:""}]),angular.forEach(["addresses","phones","urls"],function(a){angular.forEach(d[a],function(a){a.type&&(a.type=a.type.toLowerCase())})}),angular.forEach(this.refs,function(b,c){b.email&&(b.emails=[{value:b.email}]),b.id=b.reference,d.refs[c]=new a(b)}),this.birthday&&a.$Preferences.ready().then(function(){var b=a.$Preferences.$mdDateLocaleProvider;d.birthday=d.birthday.parseDate(b,"%Y-%m-%d"),d.$birthday=b.formatDate(d.birthday)}),this.$loaded=angular.isDefined(this.c_name)?a.STATUS.LOADED:a.STATUS.NOT_LOADED,this.empty=" "},a.prototype.$id=function(){return this.$futureCardData.then(function(a){return a.id})},a.prototype.$isLoading=function(){return this.$loaded==a.STATUS.LOADING},a.prototype.$reload=function(){var b;return this.$futureCardData?this:(b=a.$$resource.fetch([this.pid,this.id].join("/"),"view"),this.$unwrap(b))},a.prototype.$save=function(){var b=this,c="saveAsContact";return"vlist"==this.c_component&&(c="saveAsList",_.forEach(this.refs,function(a){a.reference=a.id})),a.$$resource.save([this.pid,this.id||"_new_"].join("/"),this.$omit(),{action:c}).then(function(c){return b.birthday&&(b.$birthday=a.$Preferences.$mdDateLocaleProvider.formatDate(b.birthday)),b.$shadowData=b.$omit(!0),c})},a.prototype.$delete=function(b,c){if(!b)return a.$$resource.remove([this.pid,this.id].join("/"));c>-1&&this[b].length>c?this[b].splice(c,1):delete this[b]},a.prototype.export=function(){var b,c;return b={uids:[this.id]},c={type:"application/octet-stream",filename:this.$$fullname+".ldif"},a.$$resource.download(this.pid,"export",b,c)},a.prototype.$fullname=function(a){var b,c,d=this.c_cn||"",e=a&&a.html;return 0===d.length&&(c=[],this.c_givenname&&this.c_givenname.length>0&&c.push(this.c_givenname),this.nickname&&this.nickname.length>0&&c.push((e?"":"")+this.nickname+(e?"":"")),this.c_sn&&this.c_sn.length>0&&c.push(this.c_sn),c.length>0?d=c.join(" "):this.c_org&&this.c_org.length>0?d=this.c_org:this.emails&&this.emails.length>0&&(b=_.find(this.emails,function(a){return""!==a.value}),b&&(d=b.value))),d},a.prototype.$description=function(){var a=[];return this.title&&a.push(this.title),this.role&&a.push(this.role),this.orgUnits&&this.orgUnits.length>0&&_.forEach(this.orgUnits,function(b){""!==b.value&&a.push(b.value)}),this.c_org&&a.push(this.c_org),this.description&&a.push(this.description),a.join(", ")},a.prototype.$preferredEmail=function(a){var b,c;return a&&(c=new RegExp(a,"i"),b=_.find(this.emails,function(a){return c.test(a.value)})),b?b=b.value:(b=_.find(this.emails,function(a){return"pref"==a.type}),b=b?b.value:this.emails&&this.emails.length?this.emails[0].value:this.c_mail&&this.c_mail.length?this.c_mail[0]:""),b},a.prototype.$shortFormat=function(a){var b=[this.$$fullname],c=this.$preferredEmail(a);return c&&c!=this.$$fullname&&b.push(" <"+c+">"),b.join(" ")},a.prototype.$isCard=function(){return"vcard"==this.c_component},a.prototype.$isList=function(a){var b=!a||!a.expandable||a.expandable&&!this.isgroup;return"vlist"==this.c_component&&b},a.prototype.$addOrgUnit=function(a){if(angular.isUndefined(this.orgUnits))this.orgUnits=[{value:a}];else{for(var b=0;b1?(b=this.$omit(),_.forEach(this.emails,function(d){var e=new a(angular.extend({},b,{emails:[d]}));c.push(e)}),c):[this]},a.prototype.$reset=function(){var a=this;angular.forEach(this,function(b,c){"constructor"!=c&&"$"!=c[0]&&delete a[c]}),this.init(this.$shadowData),this.$shadowData=this.$omit(!0)},a.prototype.$unwrap=function(b){var c=this;return this.$loaded=a.STATUS.DELAYED_LOADING,a.$timeout(function(){c.$loaded!=a.STATUS.LOADED&&(c.$loaded=a.STATUS.LOADING)},a.STATUS.DELAYED_MS),this.$futureCardData=b.then(function(b){return c.init(b),c.$loaded=a.STATUS.LOADED,c.$shadowData=c.$omit(!0),c}),this.$futureCardData},a.prototype.$omit=function(b){var c={};return angular.forEach(this,function(a,d){"refs"==d?c.refs=_.map(a,function(a){return a.$omit(b)}):"constructor"!=d&&"$"!=d[0]&&(c[d]=b?angular.copy(a):a)}),b||(c.birthday?c.birthday=c.birthday.format(a.$Preferences.$mdDateLocaleProvider,"%Y-%m-%d"):c.birthday=""),this.notes&&(c.notes=_.map(this.notes,"value")),c},a.prototype.toString=function(){var a=this.id+" "+this.$$fullname;return this.$$email&&(a+=" <"+this.$$email+">"),"["+a+"]"}}(); +!function(){"use strict";function a(b){if("function"!=typeof b.then)if(this.init(b),this.name&&!this.id){var c=a.$$resource.create("createFolder",this.name);this.$unwrap(c),this.acls={objectEditor:1,objectCreator:1,objectEraser:1}}else this.id&&(this.$acl=new a.$$Acl("Contacts/"+this.id));else this.$unwrap(b)}a.$factory=["$q","$timeout","$log","sgSettings","sgAddressBook_PRELOAD","Resource","Card","Acl","Preferences",function(b,c,d,e,f,g,h,i,j){return angular.extend(a,{$q:b,$timeout:c,$log:d,PRELOAD:f,$$resource:new g(e.activeUser("folderURL")+"Contacts",e.activeUser()),$Card:h,$$Acl:i,$Preferences:j,$query:{search:"name_or_address",value:"",sort:"c_cn",asc:1},activeUser:e.activeUser(),selectedFolder:null,$refreshTimeout:null}),j.ready().then(function(){j.settings.Contact.SortingState&&(a.$query.sort=j.settings.Contact.SortingState[0],a.$query.asc=parseInt(j.settings.Contact.SortingState[1]))}),a}];try{angular.module("SOGo.ContactsUI")}catch(a){angular.module("SOGo.ContactsUI",["SOGo.Common","SOGo.PreferencesUI"])}angular.module("SOGo.ContactsUI").constant("sgAddressBook_PRELOAD",{LOOKAHEAD:50,SIZE:100}).factory("AddressBook",a.$factory),a.$filterAll=function(b,c,d){var e={search:b};return b?(angular.isUndefined(a.$cards)&&(a.$cards=[]),angular.extend(e,c),a.$$resource.fetch(null,"allContactSearch",e).then(function(c){var e,f,g,h=function(a){return this.id==a.id};for(e=d?_.filter(c.contacts,function(a){return _.isUndefined(_.find(d,_.bind(h,a)))}):c.contacts,g=a.$cards.length-1;g>=0;g--)f=a.$cards[g],_.isUndefined(_.find(e,_.bind(h,f)))&&a.$cards.splice(g,1);return _.forEach(e,function(c,d){if(_.isUndefined(_.find(a.$cards,_.bind(h,c)))){var e=new a.$Card(_.mapKeys(c,function(a,b){return b.toLowerCase()}),b);a.$cards.splice(d,0,e)}}),a.$log.debug(a.$cards),a.$cards})):(a.$cards=[],a.$q.when(a.$cards))},a.$add=function(a){var b,c,d;b=a.isSubscription?this.$subscriptions:this.$addressbooks,c=_.find(b,function(b){return"personal"==a.id||"personal"!=b.id&&1===b.name.localeCompare(a.name)}),d=c?_.indexOf(_.map(b,"id"),c.id):1,b.splice(d,0,a)},a.$findAll=function(b){var c=this;return b&&(this.$addressbooks=[],this.$subscriptions=[],this.$remotes=[],angular.forEach(b,function(b,d){var e=new a(b);e.isRemote?c.$remotes.push(e):e.isSubscription?c.$subscriptions.push(e):c.$addressbooks.push(e)})),_.union(this.$addressbooks,this.$subscriptions,this.$remotes)},a.$subscribe=function(b,c){var d=this;return a.$$resource.userResource(b).fetch(c,"subscribe").then(function(b){var c=new a(b);return _.isUndefined(_.find(d.$subscriptions,function(a){return a.id==b.id}))&&a.$add(c),c})},a.$reloadAll=function(){var b=this;return a.$$resource.fetch("addressbooksList").then(function(c){_.forEach(c.addressbooks,function(c){var d,e;d=c.isRemote?b.$remotes:c.owner!=a.activeUser.login?b.$subscriptions:b.$addressbooks,e=_.find(d,function(a){return a.id==c.id}),e&&e.init(c)})})},a.prototype.init=function(b,c){var d=this;this.$$cards||(this.$$cards=[]),this.idsMap={},this.$cards=[],angular.forEach(b,function(a,b){"headers"!=b&&"cards"!=b&&(d[b]=a)}),this.isOwned=a.activeUser.isSuperUser||this.owner==a.activeUser.login,this.isSubscription=!this.isRemote&&this.owner!=a.activeUser.login},a.prototype.$id=function(){return this.id?a.$q.when(this.id):this.$futureAddressBookData.then(function(a){return a.id})},a.prototype.getLength=function(){return this.$cards.length},a.prototype.getItemAtIndex=function(a){var b;return!this.$isLoading&&a>=0&&a0&&(f=a.$$resource.post(this.id,"headers",{ids:e}),this.$unwrapHeaders(f))}return j},a.prototype.hasSelectedCard=function(){return angular.isDefined(this.selectedCard)},a.prototype.isSelectedCard=function(a){return this.hasSelectedCard()&&this.selectedCard==a},a.prototype.$selectedCard=function(){var a=this;return _.find(this.$cards,function(b){return b.id==a.selectedCard})},a.prototype.$selectedCardIndex=function(){return _.indexOf(_.map(this.$cards,"id"),this.selectedCard)},a.prototype.$selectedCards=function(){return _.filter(this.$cards,function(a){return a.selected})},a.prototype.$selectedCount=function(){var a;return a=0,this.$cards&&(a=_.filter(this.$cards,function(a){return a.selected}).length),a},a.prototype.$startRefreshTimeout=function(){var b=this;a.$refreshTimeout&&a.$timeout.cancel(a.$refreshTimeout),a.$Preferences.ready().then(function(){var c=a.$Preferences.defaults.SOGoRefreshViewCheck;if(c&&"manually"!=c){var d=angular.bind(b,a.prototype.$reload);a.$refreshTimeout=a.$timeout(d,1e3*c.timeInterval())}})},a.prototype.$reload=function(){return this.$startRefreshTimeout(),this.$filter()},a.prototype.$filter=function(b,c,d){var e,f=this,g=c&&c.dry;return g?e=angular.copy(a.$query):(this.$isLoading=!0,e=a.$query,this.isRemote||(e.partial=1)),a.$Preferences.ready().then(function(){return c&&(angular.extend(e,c),g&&!b)?(f.$$cards=[],a.$q.when(f.$$cards)):(angular.isDefined(b)&&(e.value=b),f.$id().then(function(c){var h=a.$$resource.fetch(c,"view",e);return g?h.then(function(e){var g,h,i,j,k,l=f.$$cards,m=function(a){return this==a.id};for(e.headers&&(j=_.invokeMap(e.headers[0],"toLowerCase"),k=j.indexOf("id"),e.headers.splice(0,1)),g=d?_.filter(e.ids,function(a){return _.isUndefined(_.find(d,_.bind(m,a)))}):e.ids,i=l.length-1;i>=0;i--)h=l[i],_.isUndefined(_.find(g,_.bind(m,h.id)))&&l.splice(i,1);return _.forEach(g,function(d,e){if(_.isUndefined(_.find(l,_.bind(m,d)))){var f={pid:c,id:d},g=new a.$Card(f,b);l.splice(e,0,g)}}),_.forEach(g,function(a,b){var c,d;l[b].id!=a&&(c=_.findIndex(l,_.bind(m,a)),d=l.splice(c,1),l.splice(b,0,d[0]))}),_.forEach(e.headers,function(a){var c,d=_.findIndex(l,_.bind(m,a[k]));d>-1&&(c=_.zipObject(j,a),l[d].init(c,b))}),l}):f.$unwrap(h)}))})},a.prototype.$rename=function(b){var c,d;return d=this.isSubscription?a.$subscriptions:a.$addressbooks,c=_.indexOf(_.map(d,"id"),this.id),this.name=b,d.splice(c,1),a.$add(this),this.$save()},a.prototype.$delete=function(){var b,c,d=this,e=a.$q.defer();return this.isSubscription?(c=a.$$resource.fetch(this.id,"unsubscribe"),b=a.$subscriptions):(c=a.$$resource.remove(this.id),b=a.$addressbooks),c.then(function(){var a=_.indexOf(_.map(b,"id"),d.id);b.splice(a,1),e.resolve()},e.reject),e.promise},a.prototype.$_deleteCards=function(a){var b=this;_.forEachRight(this.$cards,function(c,d){var e=_.findIndex(a,function(a){return c.id==a});e>-1?(a.splice(e,1),delete b.idsMap[c.id],b.isSelectedCard(c.id)&&delete b.selectedCard,b.$cards.splice(d,1)):b.idsMap[c.id]-=a.length})},a.prototype.$deleteCards=function(b){var c=this,d=_.map(b,"id");return a.$$resource.post(this.id,"batchDelete",{uids:d}).then(function(){c.$_deleteCards(d)})},a.prototype.$copyCards=function(b,c){var d=_.map(b,"id");return a.$$resource.post(this.id,"copy",{uids:d,folder:c})},a.prototype.$moveCards=function(b,c){var d,e=this;return d=_.map(b,"id"),a.$$resource.post(this.id,"move",{uids:d,folder:c}).then(function(){return e.$_deleteCards(d)})},a.prototype.$save=function(){return a.$$resource.save(this.id,this.$omit()).then(function(a){return a})},a.prototype.exportCards=function(b){var c,d,e=null;return c={type:"application/octet-stream",filename:this.name+".ldif"},b&&(d=_.filter(this.$cards,function(a){return a.selected}),e={uids:_.map(d,"id")}),a.$$resource.download(this.id,"export",e,c)},a.prototype.$unwrap=function(b){var c=this;this.$isLoading=!0,this.$futureAddressBookData=b.then(function(b){return a.$timeout(function(){var d;return(!b.ids||c.$topIndex>b.ids.length-1)&&(c.$topIndex=0),angular.forEach(a.$findAll(),function(a,d){a.id==b.id&&angular.extend(c,a)}),c.init(b),c.ids&&(a.$log.debug("unwrapping "+c.ids.length+" cards"),_.reduce(c.ids,function(b,d,e){var f={pid:c.id,id:d};return c.idsMap[f.id]=e,b.push(new a.$Card(f)),b},c.$cards)),b.headers&&(d=_.invokeMap(b.headers[0],"toLowerCase"),b.headers.splice(0,1),c.ids?_.forEach(b.headers,function(a){var b=_.zipObject(d,a),e=c.idsMap[b.id];c.$cards[e].init(b)}):(c.$cards=[],angular.forEach(b.headers,function(b){var e=_.zipObject(d,b);angular.extend(e,{pid:c.id}),c.$cards.push(new a.$Card(e))}))),c.$acl=new a.$$Acl("Contacts/"+c.id),c.$startRefreshTimeout(),c.$isLoading=!1,a.$log.debug("addressbook "+c.id+" ready"),c})},function(b){c.isError=!0,angular.isObject(b)&&a.$timeout(function(){angular.extend(c,b)})})},a.prototype.$unwrapHeaders=function(b){var c=this;b.then(function(b){a.$timeout(function(){var a,d;b.length>0&&(a=_.invokeMap(b[0],"toLowerCase"),b.splice(0,1),_.forEach(b,function(b){b=_.zipObject(a,b),d=c.idsMap[b.id],angular.isDefined(d)&&c.$cards[d].init(b)}))})})},a.prototype.$omit=function(){var a={};return angular.forEach(this,function(b,c){"constructor"!=c&&"acls"!=c&&"ids"!=c&&"idsMap"!=c&&"urls"!=c&&"$"!=c[0]&&(a[c]=b)}),a}}(),function(){"use strict";function a(b,c){if("function"!=typeof b.then){if(this.init(b,c),this.pid&&!this.id){var d=a.$$resource.newguid(this.pid);this.$unwrap(d),this.isNew=!0}}else this.$unwrap(b)}a.$TEL_TYPES=["work","home","cell","fax","pager"],a.$EMAIL_TYPES=["work","home","pref"],a.$URL_TYPES=["work","home","pref"],a.$ADDRESS_TYPES=["work","home"],a.$factory=["$timeout","sgSettings","sgCard_STATUS","Resource","Preferences",function(b,c,d,e,f){return angular.extend(a,{STATUS:d,$$resource:new e(c.activeUser("folderURL")+"Contacts",c.activeUser()),$timeout:b,$Preferences:f}),f.ready().then(function(){f.defaults.SOGoContactsCategories&&(a.$categories=f.defaults.SOGoContactsCategories),f.defaults.SOGoAlternateAvatar&&(a.$alternateAvatar=f.defaults.SOGoAlternateAvatar)}),a}];try{angular.module("SOGo.ContactsUI")}catch(a){angular.module("SOGo.ContactsUI",["SOGo.Common","SOGo.PreferencesUI"])}angular.module("SOGo.ContactsUI").constant("sgCard_STATUS",{NOT_LOADED:0,DELAYED_LOADING:1,LOADING:2,LOADED:3,DELAYED_MS:300}).factory("Card",a.$factory),a.$find=function(b,c){var d=this.$$resource.fetch([b,c].join("/"),"view");return c?new a(d):a.$unwrapCollection(d)},a.filterCategories=function(b){var c=new RegExp(b,"i");return _.map(_.filter(a.$categories,function(a){return a.search(c)!=-1}),function(a){return{value:a}})},a.$unwrapCollection=function(b){var c={};return c.$futureCardData=b,b.then(function(b){a.$timeout(function(){angular.forEach(b,function(b,d){c[b.id]=new a(b)})})}),c},a.prototype.init=function(b,c){var d=this;this.refs=[],this.categories=[],this.c_screenname=null,angular.extend(this,b),this.$$fullname||(this.$$fullname=this.$fullname()),this.$$email||(this.$$email=this.$preferredEmail(c)),this.$$image||(this.$$image=this.image),this.$$image||a.$Preferences.avatar(this.$$email,32,{no_404:!0}).then(function(a){d.$$image=a}),this.hasphoto&&(this.photoURL=a.$$resource.path(this.pid,this.id,"photo")),this.isgroup&&(this.c_component="vlist"),this.$avatarIcon=this.$isList()?"group":"person",b.orgs&&b.orgs.length&&(this.orgs=_.map(b.orgs,function(a){return{value:a}})),b.notes&&b.notes.length?this.notes=_.map(b.notes,function(a){return{value:a}}):this.notes&&this.notes.length||(this.notes=[{value:""}]),angular.forEach(["addresses","phones","urls"],function(a){angular.forEach(d[a],function(a){a.type&&(a.type=a.type.toLowerCase())})}),angular.forEach(this.refs,function(b,c){b.email&&(b.emails=[{value:b.email}]),b.id=b.reference,d.refs[c]=new a(b)}),this.birthday&&a.$Preferences.ready().then(function(){var b=a.$Preferences.$mdDateLocaleProvider;d.birthday=d.birthday.parseDate(b,"%Y-%m-%d"),d.$birthday=b.formatDate(d.birthday)}),this.$loaded=angular.isDefined(this.c_name)?a.STATUS.LOADED:a.STATUS.NOT_LOADED,this.empty=" "},a.prototype.$id=function(){return this.$futureCardData.then(function(a){return a.id})},a.prototype.$isLoading=function(){return this.$loaded==a.STATUS.LOADING},a.prototype.$reload=function(){var b;return this.$futureCardData?this:(b=a.$$resource.fetch([this.pid,this.id].join("/"),"view"),this.$unwrap(b))},a.prototype.$save=function(){var b=this,c="saveAsContact";return"vlist"==this.c_component&&(c="saveAsList",_.forEach(this.refs,function(a){a.reference=a.id})),a.$$resource.save([this.pid,this.id||"_new_"].join("/"),this.$omit(),{action:c}).then(function(c){return b.birthday&&(b.$birthday=a.$Preferences.$mdDateLocaleProvider.formatDate(b.birthday)),b.$shadowData=b.$omit(!0),c})},a.prototype.$delete=function(b,c){if(!b)return a.$$resource.remove([this.pid,this.id].join("/"));c>-1&&this[b].length>c?this[b].splice(c,1):delete this[b]},a.prototype.export=function(){var b,c;return b={uids:[this.id]},c={type:"application/octet-stream",filename:this.$$fullname+".ldif"},a.$$resource.download(this.pid,"export",b,c)},a.prototype.$fullname=function(a){var b,c,d=this.c_cn||"",e=a&&a.html;return 0===d.length&&(c=[],this.c_givenname&&this.c_givenname.length>0&&c.push(this.c_givenname),this.nickname&&this.nickname.length>0&&c.push((e?"":"")+this.nickname+(e?"":"")),this.c_sn&&this.c_sn.length>0&&c.push(this.c_sn),c.length>0?d=c.join(" "):this.org&&this.org.length>0?d=this.org:this.emails&&this.emails.length>0&&(b=_.find(this.emails,function(a){return""!==a.value}),b&&(d=b.value))),d},a.prototype.$description=function(){var a=[];return this.title&&a.push(this.title),this.role&&a.push(this.role),this.org&&a.push(this.org),this.orgs&&(a=_.concat(a,_.map(this.orgs,"value"))),this.description&&a.push(this.description),a.join(", ")},a.prototype.$preferredEmail=function(a){var b,c;return a&&(c=new RegExp(a,"i"),b=_.find(this.emails,function(a){return c.test(a.value)})),b?b=b.value:(b=_.find(this.emails,function(a){return"pref"==a.type}),b=b?b.value:this.emails&&this.emails.length?this.emails[0].value:this.c_mail&&this.c_mail.length?this.c_mail[0]:""),b},a.prototype.$shortFormat=function(a){var b=[this.$$fullname],c=this.$preferredEmail(a);return c&&c!=this.$$fullname&&b.push(" <"+c+">"),b.join(" ")},a.prototype.$isCard=function(){return"vcard"==this.c_component},a.prototype.$isList=function(a){var b=!a||!a.expandable||a.expandable&&!this.isgroup;return"vlist"==this.c_component&&b},a.prototype.$addOrg=function(a){return angular.isUndefined(this.orgs)?this.orgs=[a]:a==this.org||_.includes(this.orgs,a)||this.orgs.push(a),this.orgs.length-1},a.prototype.$addEmail=function(a){return angular.isUndefined(this.emails)?this.emails=[{type:a,value:""}]:_.isUndefined(_.find(this.emails,function(a){return""===a.value}))&&this.emails.push({type:a,value:""}),this.emails.length-1},a.prototype.$addScreenName=function(a){this.c_screenname=a},a.prototype.$addPhone=function(a){return angular.isUndefined(this.phones)?this.phones=[{type:a,value:""}]:_.isUndefined(_.find(this.phones,function(a){return""===a.value}))&&this.phones.push({type:a,value:""}),this.phones.length-1},a.prototype.$addUrl=function(a,b){return angular.isUndefined(this.urls)?this.urls=[{type:a,value:b}]:_.isUndefined(_.find(this.urls,function(a){return a.value==b}))&&this.urls.push({type:a,value:b}),this.urls.length-1},a.prototype.$addAddress=function(a,b,c,d,e,f,g,h){return angular.isUndefined(this.addresses)?this.addresses=[{type:a,postoffice:b,street:c,street2:d,locality:e,region:f,country:g,postalcode:h}]:_.find(this.addresses,function(a){return a.street==c&&a.street2==d&&a.locality==e&&a.country==g&&a.postalcode==h})||this.addresses.push({type:a,postoffice:b,street:c,street2:d,locality:e,region:f,country:g,postalcode:h}),this.addresses.length-1},a.prototype.$addMember=function(b){var c,d=new a({email:b,emails:[{value:b}]});if(angular.isUndefined(this.refs))this.refs=[d];else if(0===b.length)this.refs.push(d);else{for(c=0;c1?(b=this.$omit(),_.forEach(this.emails,function(d){var e=new a(angular.extend({},b,{emails:[d]}));c.push(e)}),c):[this]},a.prototype.$reset=function(){var a=this;angular.forEach(this,function(b,c){"constructor"!=c&&"$"!=c[0]&&delete a[c]}),this.init(this.$shadowData),this.$shadowData=this.$omit(!0)},a.prototype.$unwrap=function(b){var c=this;return this.$loaded=a.STATUS.DELAYED_LOADING,a.$timeout(function(){c.$loaded!=a.STATUS.LOADED&&(c.$loaded=a.STATUS.LOADING)},a.STATUS.DELAYED_MS),this.$futureCardData=b.then(function(b){return c.init(b),c.$loaded=a.STATUS.LOADED,c.$shadowData=c.$omit(!0),c}),this.$futureCardData},a.prototype.$omit=function(b){var c={};return angular.forEach(this,function(a,d){"refs"==d?c.refs=_.map(a,function(a){return a.$omit(b)}):"constructor"!=d&&"$"!=d[0]&&(c[d]=b?angular.copy(a):a)}),b||(c.birthday?c.birthday=c.birthday.format(a.$Preferences.$mdDateLocaleProvider,"%Y-%m-%d"):c.birthday=""),this.orgs&&(c.orgs=_.map(this.orgs,"value")),this.notes&&(c.notes=_.map(this.notes,"value")),c},a.prototype.toString=function(){var a=this.id+" "+this.$$fullname;return this.$$email&&(a+=" <"+this.$$email+">"),"["+a+"]"}}(); //# sourceMappingURL=Contacts.services.js.map \ No newline at end of file diff --git a/UI/WebServerResources/js/Contacts.services.js.map b/UI/WebServerResources/js/Contacts.services.js.map index 89d6b3395..bb5331b43 100644 --- a/UI/WebServerResources/js/Contacts.services.js.map +++ b/UI/WebServerResources/js/Contacts.services.js.map @@ -1 +1 @@ -{"version":3,"sources":["Contacts/AddressBook.service.js","Contacts/Card.service.js"],"names":["AddressBook","futureAddressBookData","then","this","init","name","id","newAddressBookData","$$resource","create","$unwrap","acls","objectEditor","objectCreator","objectEraser","$acl","$$Acl","$factory","$q","$timeout","$log","Settings","AddressBook_PRELOAD","Resource","Card","Acl","Preferences","angular","extend","PRELOAD","activeUser","$Card","$Preferences","$query","search","value","sort","asc","selectedFolder","$refreshTimeout","ready","settings","Contact","SortingState","parseInt","module","e","constant","LOOKAHEAD","SIZE","factory","$filterAll","options","excludedCards","params","isUndefined","$cards","fetch","response","results","card","index","compareIds","data","_","filter","contacts","find","bind","length","splice","forEach","mapKeys","key","toLowerCase","debug","when","$add","addressbook","list","sibling","i","isSubscription","$subscriptions","$addressbooks","o","localeCompare","indexOf","map","$findAll","_this","$remotes","isRemote","push","union","$subscribe","uid","path","userResource","addressbookData","$reloadAll","addressbooks","group","owner","login","prototype","$$cards","idsMap","isOwned","isSuperUser","$id","$futureAddressBookData","getLength","getItemAtIndex","$isLoading","$lastVisibleIndex","Math","max","$loadCard","endIndex","ids","futureHeadersData","cardId","startIndex","loaded","isDefined","$loaded","STATUS","NOT_LOADED","min","LOADED","LOADING","join","post","$unwrapHeaders","hasSelectedCard","selectedCard","isSelectedCard","$selectedCard","$selectedCardIndex","$selectedCards","selected","$selectedCount","count","$startRefreshTimeout","cancel","refreshViewCheck","defaults","SOGoRefreshViewCheck","f","$reload","timeInterval","$filter","query","dry","copy","partial","addressbookId","futureData","fields","idFieldIndex","cards","headers","invokeMap","pid","oldIndex","removedCards","findIndex","zipObject","$rename","$save","$delete","promise","d","defer","remove","resolve","reject","$_deleteCards","forEachRight","selectedIndex","$deleteCards","uids","$copyCards","folder","$moveCards","save","$omit","exportCards","selectedOnly","selectedCards","type","filename","download","$topIndex","reduce","isError","isObject","j","cardHeaders","futureCardData","newCardData","newguid","isNew","$TEL_TYPES","$EMAIL_TYPES","$URL_TYPES","$ADDRESS_TYPES","Card_STATUS","SOGoContactsCategories","$categories","SOGoAlternateAvatar","$alternateAvatar","DELAYED_LOADING","DELAYED_MS","$find","$unwrapCollection","filterCategories","re","RegExp","category","collection","$futureCardData","refs","categories","c_screenname","$$fullname","$fullname","$$email","$preferredEmail","$$image","image","avatar","no_404","url","hasphoto","photoURL","isgroup","c_component","$avatarIcon","$isList","notes","note","email","emails","reference","birthday","dlp","$mdDateLocaleProvider","parseDate","$birthday","formatDate","c_name","empty","action","ref","$shadowData","attribute","export","names","fn","c_cn","html","c_givenname","nickname","c_sn","c_org","$description","description","title","role","orgUnits","unit","test","c_mail","$shortFormat","fullname","$isCard","condition","expandable","$addOrgUnit","orgUnit","$addEmail","$addScreenName","screenName","$addPhone","phones","$addUrl","urls","$addAddress","postoffice","street","street2","locality","region","country","postalcode","addresses","$addMember","explode","$reset","deep","format","toString","desc"],"mappings":"CAEA,WACE,YAOA,SAASA,GAAYC,GAEnB,GAA0C,kBAA/BA,GAAsBC,KAE/B,GADAC,KAAKC,KAAKH,GACNE,KAAKE,OAASF,KAAKG,GAAI,CAEzB,GAAIC,GAAqBP,EAAYQ,WAAWC,OAAO,eAAgBN,KAAKE,KAC5EF,MAAKO,QAAQH,GACbJ,KAAKQ,MAAQC,aAAgB,EAAGC,cAAiB,EAAGC,aAAgB,OAE7DX,MAAKG,KACZH,KAAKY,KAAO,GAAIf,GAAYgB,MAAM,YAAcb,KAAKG,SAKvDH,MAAKO,QAAQT,GASjBD,EAAYiB,UAAY,KAAM,WAAY,OAAQ,aAAc,wBAAyB,WAAY,OAAQ,MAAO,cAAe,SAASC,EAAIC,EAAUC,EAAMC,EAAUC,EAAqBC,EAAUC,EAAMC,EAAKC,GAsBlN,MArBAC,SAAQC,OAAO5B,GACbkB,GAAIA,EACJC,SAAUA,EACVC,KAAMA,EACNS,QAASP,EACTd,WAAY,GAAIe,GAASF,EAASS,WAAW,aAAe,WAAYT,EAASS,cACjFC,MAAOP,EACPR,MAAOS,EACPO,aAAcN,EACdO,QAASC,OAAQ,kBAAmBC,MAAO,GAAIC,KAAM,OAAQC,IAAK,GAClEP,WAAYT,EAASS,aACrBQ,eAAgB,KAChBC,gBAAiB,OAGnBb,EAAYc,QAAQtC,KAAK,WACnBwB,EAAYe,SAASC,QAAQC,eAC/B3C,EAAYiC,OAAOG,KAAOV,EAAYe,SAASC,QAAQC,aAAa,GACpE3C,EAAYiC,OAAOI,IAAMO,SAASlB,EAAYe,SAASC,QAAQC,aAAa,OAGzE3C,GAOT,KACE2B,QAAQkB,OAAO,mBAEjB,MAAMC,GACJnB,QAAQkB,OAAO,mBAAoB,cAAe,uBAEpDlB,QAAQ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EAAKuG,OAAOI,UAC7B3G,EAAKuG,OAAOuF,YAGfnN,KAAK2N,gBAAkBtB,EAAetM,KAAK,SAAS6D,GAOlD,MANA2B,GAAMtF,KAAK2D,GAEX2B,EAAMoC,QAAUtG,EAAKuG,OAAOG,OAE5BxC,EAAMsK,YAActK,EAAMiG,OAAM,GAEzBjG,IAGFvF,KAAK2N,iBAUdtM,EAAKiF,UAAUkF,MAAQ,SAASkH,GAC9B,GAAIjP,KA2BJ,OA1BAjC,SAAQ4C,QAAQpE,KAAM,SAASgC,EAAOsC,GACzB,QAAPA,EACFb,EAAKmK,KAAO/J,EAAEwB,IAAIrD,EAAO,SAASkD,GAChC,MAAOA,GAAEsG,MAAMkH,KAGH,eAAPpO,GAAkC,KAAVA,EAAI,KAEjCb,EAAKa,GADHoO,EACUlR,QAAQgI,KAAKxH,GAEbA,KAKb0Q,IACCjP,EAAK0L,SACP1L,EAAK0L,SAAW1L,EAAK0L,SAASwD,OAAOtR,EAAKQ,aAAawN,sBAAuB,YAE9E5L,EAAK0L,SAAW,IAIhBnP,KAAK8O,QACPrL,EAAKqL,MAAQjL,EAAEwB,IAAIrF,KAAK8O,MAAO,UAE1BrL,GAGTpC,EAAKiF,UAAUsM,SAAW,WACxB,GAAIC,GAAO7S,KAAKG,GAAK,IAAMH,KAAK+N,UAKhC,OAHI/N,MAAKiO,UACP4E,GAAQ,KAAO7S,KAAKiO,QAAU,KAEzB,IAAM4E,EAAO","file":"Contacts.services.js","sourcesContent":["/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @name AddressBook\n * @constructor\n * @param {object} futureAddressBookData - either an object literal or a promise\n */\n function AddressBook(futureAddressBookData) {\n // Data is immediately available\n if (typeof futureAddressBookData.then !== 'function') {\n this.init(futureAddressBookData);\n if (this.name && !this.id) {\n // Create a new addressbook on the server\n var newAddressBookData = AddressBook.$$resource.create('createFolder', this.name);\n this.$unwrap(newAddressBookData);\n this.acls = {'objectEditor': 1, 'objectCreator': 1, 'objectEraser': 1};\n }\n else if (this.id) {\n this.$acl = new AddressBook.$$Acl('Contacts/' + this.id);\n }\n }\n else {\n // The promise will be unwrapped first\n this.$unwrap(futureAddressBookData);\n }\n }\n\n /**\n * @memberof AddressBook\n * @desc The factory we'll use to register with Angular\n * @returns the AddressBook constructor\n */\n AddressBook.$factory = ['$q', '$timeout', '$log', 'sgSettings', 'sgAddressBook_PRELOAD', 'Resource', 'Card', 'Acl', 'Preferences', function($q, $timeout, $log, Settings, AddressBook_PRELOAD, Resource, Card, Acl, Preferences) {\n angular.extend(AddressBook, {\n $q: $q,\n $timeout: $timeout,\n $log: $log,\n PRELOAD: AddressBook_PRELOAD,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Contacts', Settings.activeUser()),\n $Card: Card,\n $$Acl: Acl,\n $Preferences: Preferences,\n $query: {search: 'name_or_address', value: '', sort: 'c_cn', asc: 1},\n activeUser: Settings.activeUser(),\n selectedFolder: null,\n $refreshTimeout: null\n });\n // Initialize sort parameters from user's settings\n Preferences.ready().then(function() {\n if (Preferences.settings.Contact.SortingState) {\n AddressBook.$query.sort = Preferences.settings.Contact.SortingState[0];\n AddressBook.$query.asc = parseInt(Preferences.settings.Contact.SortingState[1]);\n }\n });\n return AddressBook; // return constructor\n }];\n\n /**\n * @module SOGo.ContactsUI\n * @desc Factory registration of AddressBook in Angular module.\n */\n try {\n angular.module('SOGo.ContactsUI');\n }\n catch(e) {\n angular.module('SOGo.ContactsUI', ['SOGo.Common', 'SOGo.PreferencesUI']);\n }\n angular.module('SOGo.ContactsUI')\n .constant('sgAddressBook_PRELOAD', {\n LOOKAHEAD: 50,\n SIZE: 100\n })\n .factory('AddressBook', AddressBook.$factory);\n\n /**\n * @memberof AddressBook\n * @desc Search for cards among all addressbooks matching some criterias.\n * @param {string} search - the search string to match\n * @param {object} [options] - additional options to the query (excludeGroups and excludeLists)\n * @param {object[]} excludedCards - a list of Card objects that must be excluded from the results\n * @returns a collection of Cards instances\n */\n AddressBook.$filterAll = function(search, options, excludedCards) {\n var params = { search: search };\n\n if (!search) {\n // No query specified\n AddressBook.$cards = [];\n return AddressBook.$q.when(AddressBook.$cards);\n }\n if (angular.isUndefined(AddressBook.$cards)) {\n // First session query\n AddressBook.$cards = [];\n }\n\n angular.extend(params, options);\n\n return AddressBook.$$resource.fetch(null, 'allContactSearch', params).then(function(response) {\n var results, card, index,\n compareIds = function(data) {\n return this.id == data.id;\n };\n if (excludedCards) {\n // Remove excluded cards from results\n results = _.filter(response.contacts, function(data) {\n return _.isUndefined(_.find(excludedCards, _.bind(compareIds, data)));\n });\n }\n else {\n results = response.contacts;\n }\n // Remove cards that no longer match the search query\n for (index = AddressBook.$cards.length - 1; index >= 0; index--) {\n card = AddressBook.$cards[index];\n if (_.isUndefined(_.find(results, _.bind(compareIds, card)))) {\n AddressBook.$cards.splice(index, 1);\n }\n }\n // Add new cards matching the search query\n _.forEach(results, function(data, index) {\n if (_.isUndefined(_.find(AddressBook.$cards, _.bind(compareIds, data)))) {\n var card = new AddressBook.$Card(_.mapKeys(data, function(value, key) {\n return key.toLowerCase();\n }), search);\n AddressBook.$cards.splice(index, 0, card);\n }\n });\n AddressBook.$log.debug(AddressBook.$cards);\n return AddressBook.$cards;\n });\n };\n\n /**\n * @memberof AddressBook\n * @desc Add a new addressbook to the static list of addressbooks\n * @param {AddressBook} addressbook - an Addressbook object instance\n */\n AddressBook.$add = function(addressbook) {\n // Insert new addressbook at proper index\n var list, sibling, i;\n\n list = addressbook.isSubscription? this.$subscriptions : this.$addressbooks;\n sibling = _.find(list, function(o) {\n return (addressbook.id == 'personal' ||\n (o.id != 'personal' &&\n o.name.localeCompare(addressbook.name) === 1));\n });\n i = sibling ? _.indexOf(_.map(list, 'id'), sibling.id) : 1;\n list.splice(i, 0, addressbook);\n };\n\n /**\n * @memberof AddressBook\n * @desc Set or get the list of addressbooks. Will instantiate a new AddressBook object for each item.\n * @param {array} [data] - the metadata of the addressbooks\n * @returns the list of addressbooks\n */\n AddressBook.$findAll = function(data) {\n var _this = this;\n if (data) {\n this.$addressbooks = [];\n this.$subscriptions = [];\n this.$remotes = [];\n // Instanciate AddressBook objects\n angular.forEach(data, function(o, i) {\n var addressbook = new AddressBook(o);\n if (addressbook.isRemote)\n _this.$remotes.push(addressbook);\n else if (addressbook.isSubscription)\n _this.$subscriptions.push(addressbook);\n else\n _this.$addressbooks.push(addressbook);\n });\n }\n return _.union(this.$addressbooks, this.$subscriptions, this.$remotes);\n };\n\n /**\n * @memberOf AddressBook\n * @desc Subscribe to another user's addressbook and add it to the list of addressbooks.\n * @param {string} uid - user id\n * @param {string} path - path of folder for specified user\n * @returns a promise of the HTTP query result\n */\n AddressBook.$subscribe = function(uid, path) {\n var _this = this;\n return AddressBook.$$resource.userResource(uid).fetch(path, 'subscribe').then(function(addressbookData) {\n var addressbook = new AddressBook(addressbookData);\n if (_.isUndefined(_.find(_this.$subscriptions, function(o) {\n return o.id == addressbookData.id;\n }))) {\n // Not already subscribed\n AddressBook.$add(addressbook);\n }\n return addressbook;\n });\n };\n\n /**\n * @memberof AddressBook\n * @desc Reload the list of known addressbooks.\n */\n AddressBook.$reloadAll = function() {\n var _this = this;\n\n return AddressBook.$$resource.fetch('addressbooksList').then(function(data) {\n _.forEach(data.addressbooks, function(addressbookData) {\n var group, addressbook;\n\n if (addressbookData.isRemote)\n group = _this.$remotes;\n else if (addressbookData.owner != AddressBook.activeUser.login)\n group = _this.$subscriptions;\n else\n group = _this.$addressbooks;\n\n addressbook = _.find(group, function(o) { return o.id == addressbookData.id; });\n if (addressbook)\n addressbook.init(addressbookData);\n });\n });\n };\n\n /**\n * @function init\n * @memberof AddressBook.prototype\n * @desc Extend instance with new data and compute additional attributes.\n * @param {object} data - attributes of addressbook\n */\n AddressBook.prototype.init = function(data, options) {\n var _this = this;\n if (!this.$$cards) {\n // Array of cards for \"dry\" searches (see $filter)\n this.$$cards = [];\n }\n this.idsMap = {};\n this.$cards = [];\n // Extend instance with all attributes of data except headers\n angular.forEach(data, function(value, key) {\n if (key != 'headers' && key != 'cards') {\n _this[key] = value;\n }\n });\n // Add 'isOwned' and 'isSubscription' attributes based on active user (TODO: add it server-side?)\n this.isOwned = AddressBook.activeUser.isSuperUser || this.owner == AddressBook.activeUser.login;\n this.isSubscription = !this.isRemote && this.owner != AddressBook.activeUser.login;\n };\n\n /**\n * @function $id\n * @memberof AddressBook.prototype\n * @desc Resolve the addressbook id.\n * @returns a promise of the addressbook id\n */\n AddressBook.prototype.$id = function() {\n if (this.id) {\n // Object already unwrapped\n return AddressBook.$q.when(this.id);\n }\n else {\n // Wait until object is unwrapped\n return this.$futureAddressBookData.then(function(addressbook) {\n return addressbook.id;\n });\n }\n };\n\n /**\n * @function getLength\n * @memberof AddressBook.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the number of cards in the addressbook\n */\n AddressBook.prototype.getLength = function() {\n return this.$cards.length;\n };\n\n /**\n * @function getItemAtIndex\n * @memberof AddressBook.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the card at the specified index\n */\n AddressBook.prototype.getItemAtIndex = function(index) {\n var card;\n\n if (!this.$isLoading && index >= 0 && index < this.$cards.length) {\n card = this.$cards[index];\n this.$lastVisibleIndex = Math.max(0, index - 3); // Magic number is NUM_EXTRA from virtual-repeater.js\n\n if (this.$loadCard(card))\n return card;\n }\n return null;\n };\n\n /**\n * @function $loadCard\n * @memberof AddressBook.prototype\n * @desc Check if the card is loaded and in any case, fetch more cards headers from the server.\n * @returns true if the card metadata are already fetched\n */\n AddressBook.prototype.$loadCard = function(card) {\n var cardId = card.id,\n startIndex = this.idsMap[cardId],\n endIndex,\n index,\n max = this.$cards.length,\n loaded = false,\n ids,\n futureHeadersData;\n\n if (angular.isUndefined(this.ids) && card.id) {\n loaded = true;\n }\n else if (angular.isDefined(startIndex) && startIndex < this.$cards.length) {\n // Index is valid\n if (card.$loaded != AddressBook.$Card.STATUS.NOT_LOADED) {\n // Card headers are loaded or data is coming\n loaded = true;\n }\n\n // Preload more headers if possible\n endIndex = Math.min(startIndex + AddressBook.PRELOAD.LOOKAHEAD, max - 1);\n if (this.$cards[endIndex].$loaded != AddressBook.$Card.STATUS.NOT_LOADED) {\n index = Math.max(startIndex - AddressBook.PRELOAD.LOOKAHEAD, 0);\n if (this.$cards[index].$loaded != AddressBook.$Card.STATUS.LOADED) {\n // Previous cards not loaded; preload more headers further up\n endIndex = startIndex;\n startIndex = Math.max(startIndex - AddressBook.PRELOAD.SIZE, 0);\n }\n }\n else\n // Next cards not load; preload more headers further down\n endIndex = Math.min(startIndex + AddressBook.PRELOAD.SIZE, max - 1);\n\n if (this.$cards[startIndex].$loaded == AddressBook.$Card.STATUS.NOT_LOADED ||\n this.$cards[endIndex].$loaded == AddressBook.$Card.STATUS.NOT_LOADED) {\n\n for (ids = []; startIndex < endIndex && startIndex < max; startIndex++) {\n if (this.$cards[startIndex].$loaded != AddressBook.$Card.STATUS.NOT_LOADED) {\n // Card at this index is already loaded; increase the end index\n endIndex++;\n }\n else {\n // Card at this index will be loaded\n ids.push(this.$cards[startIndex].id);\n this.$cards[startIndex].$loaded = AddressBook.$Card.STATUS.LOADING;\n }\n }\n\n AddressBook.$log.debug('Loading Ids ' + ids.join(' ') + ' (' + ids.length + ' cards)');\n if (ids.length > 0) {\n futureHeadersData = AddressBook.$$resource.post(this.id, 'headers', {ids: ids});\n this.$unwrapHeaders(futureHeadersData);\n }\n }\n }\n return loaded;\n };\n\n /**\n * @function hasSelectedMessage\n * @memberof AddressBook.prototype\n * @desc Check if a card is selected.\n * @returns true if the a card is selected\n */\n AddressBook.prototype.hasSelectedCard = function() {\n return angular.isDefined(this.selectedCard);\n };\n\n /**\n * @function isSelectedCard\n * @memberof AddressBook.prototype\n * @desc Check if the specified card is selected.\n * @param {string} CardId\n * @returns true if the specified card is selected\n */\n AddressBook.prototype.isSelectedCard = function(cardId) {\n return this.hasSelectedCard() && this.selectedCard == cardId;\n };\n\n /**\n * @function $selectedCard\n * @memberof AddressBook.prototype\n * @desc Return the currently visible card.\n * @returns a Card instance or undefined if no card is displayed\n */\n AddressBook.prototype.$selectedCard = function() {\n var _this = this;\n\n return _.find(this.$cards, function(card) { return card.id == _this.selectedCard; });\n };\n\n /**\n * @function $selectedCardIndex\n * @memberof AddressBook.prototype\n * @desc Return the index of the currently visible card.\n * @returns a number or undefined if no card is selected\n */\n AddressBook.prototype.$selectedCardIndex = function() {\n return _.indexOf(_.map(this.$cards, 'id'), this.selectedCard);\n };\n\n /**\n * @function $selectedCards\n * @memberof AddressBook.prototype\n * @desc Return the cards selected by the user.\n * @returns Card instances\n */\n AddressBook.prototype.$selectedCards = function() {\n return _.filter(this.$cards, function(card) { return card.selected; });\n };\n\n /**\n * @function $selectedCount\n * @memberof AddressBook.prototype\n * @desc Return the number of cards selected by the user.\n * @returns the number of selected cards\n */\n AddressBook.prototype.$selectedCount = function() {\n var count;\n\n count = 0;\n if (this.$cards) {\n count = (_.filter(this.$cards, function(card) { return card.selected; })).length;\n }\n return count;\n };\n\n /**\n * @function $startRefreshTimeout\n * @memberof AddressBook.prototype\n * @desc Starts the refresh timeout for the current selected address book\n */\n AddressBook.prototype.$startRefreshTimeout = function() {\n var _this = this;\n\n if (AddressBook.$refreshTimeout)\n AddressBook.$timeout.cancel(AddressBook.$refreshTimeout);\n\n AddressBook.$Preferences.ready().then(function() {\n // Restart the refresh timer, if needed\n var refreshViewCheck = AddressBook.$Preferences.defaults.SOGoRefreshViewCheck;\n if (refreshViewCheck && refreshViewCheck != 'manually') {\n var f = angular.bind(_this, AddressBook.prototype.$reload);\n AddressBook.$refreshTimeout = AddressBook.$timeout(f, refreshViewCheck.timeInterval()*1000);\n }\n });\n };\n\n /**\n * @function $reload\n * @memberof AddressBook.prototype\n * @desc Reload list of cards\n * @returns a promise of the Cards instances\n */\n AddressBook.prototype.$reload = function() {\n var _this = this;\n\n this.$startRefreshTimeout();\n return this.$filter();\n };\n\n /**\n * @function $filter\n * @memberof AddressBook.prototype\n * @desc Search for cards matching some criterias\n * @param {string} search - the search string to match\n * @param {object} [options] - additional options to the query (dry, excludeList)\n * @returns a collection of Cards instances\n */\n AddressBook.prototype.$filter = function(search, options, excludedCards) {\n var _this = this, query,\n dry = options && options.dry;\n\n if (dry) {\n // Don't keep a copy of the query in dry mode\n query = angular.copy(AddressBook.$query);\n }\n else {\n this.$isLoading = true;\n query = AddressBook.$query;\n if (!this.isRemote) query.partial = 1;\n }\n\n return AddressBook.$Preferences.ready().then(function() {\n if (options) {\n angular.extend(query, options);\n if (dry) {\n if (!search) {\n // No query specified\n _this.$$cards = [];\n return AddressBook.$q.when(_this.$$cards);\n }\n }\n }\n\n if (angular.isDefined(search))\n query.value = search;\n\n return _this.$id().then(function(addressbookId) {\n var futureData = AddressBook.$$resource.fetch(addressbookId, 'view', query);\n\n if (dry) {\n return futureData.then(function(response) {\n var results, headers, card, index, fields, idFieldIndex,\n cards = _this.$$cards,\n compareIds = function(card) {\n return this == card.id;\n };\n\n if (response.headers) {\n // First entry of 'headers' are keys\n fields = _.invokeMap(response.headers[0], 'toLowerCase');\n idFieldIndex = fields.indexOf('id');\n response.headers.splice(0, 1);\n }\n\n if (excludedCards)\n // Remove excluded cards from results\n results = _.filter(response.ids, function(id) {\n return _.isUndefined(_.find(excludedCards, _.bind(compareIds, id)));\n });\n else\n results = response.ids;\n\n // Remove cards that no longer match the search query\n for (index = cards.length - 1; index >= 0; index--) {\n card = cards[index];\n if (_.isUndefined(_.find(results, _.bind(compareIds, card.id)))) {\n cards.splice(index, 1);\n }\n }\n\n // Add new cards matching the search query\n _.forEach(results, function(cardId, index) {\n if (_.isUndefined(_.find(cards, _.bind(compareIds, cardId)))) {\n var data = { pid: addressbookId, id: cardId };\n var card = new AddressBook.$Card(data, search);\n cards.splice(index, 0, card);\n }\n });\n\n // Respect the order of the results\n _.forEach(results, function(cardId, index) {\n var oldIndex, removedCards;\n if (cards[index].id != cardId) {\n oldIndex = _.findIndex(cards, _.bind(compareIds, cardId));\n removedCards = cards.splice(oldIndex, 1);\n cards.splice(index, 0, removedCards[0]);\n }\n });\n\n // Extend Card objects with received headers\n _.forEach(response.headers, function(data) {\n var card, index = _.findIndex(cards, _.bind(compareIds, data[idFieldIndex]));\n if (index > -1) {\n card = _.zipObject(fields, data);\n cards[index].init(card, search);\n }\n });\n\n return cards;\n });\n }\n else {\n // Unwrap promise and instantiate or extend Cards objets\n return _this.$unwrap(futureData);\n }\n });\n });\n };\n\n /**\n * @function $rename\n * @memberof AddressBook.prototype\n * @desc Rename the addressbook and keep the list sorted\n * @param {string} name - the new name\n * @returns a promise of the HTTP operation\n */\n AddressBook.prototype.$rename = function(name) {\n var i, list;\n\n list = this.isSubscription? AddressBook.$subscriptions : AddressBook.$addressbooks;\n i = _.indexOf(_.map(list, 'id'), this.id);\n this.name = name;\n list.splice(i, 1);\n AddressBook.$add(this);\n\n return this.$save();\n };\n\n /**\n * @function $delete\n * @memberof AddressBook.prototype\n * @desc Delete the addressbook from the server and the static list of addressbooks.\n * @returns a promise of the HTTP operation\n */\n AddressBook.prototype.$delete = function() {\n var _this = this,\n d = AddressBook.$q.defer(),\n list,\n promise;\n\n if (this.isSubscription) {\n promise = AddressBook.$$resource.fetch(this.id, 'unsubscribe');\n list = AddressBook.$subscriptions;\n }\n else {\n promise = AddressBook.$$resource.remove(this.id);\n list = AddressBook.$addressbooks;\n }\n\n promise.then(function() {\n var i = _.indexOf(_.map(list, 'id'), _this.id);\n list.splice(i, 1);\n d.resolve();\n }, d.reject);\n return d.promise;\n };\n\n /**\n * @function $_deleteCards\n * @memberof AddressBook.prototype\n * @desc Delete multiple cards from AddressBook object.\n * @param {string[]} ids - the cards ids\n */\n AddressBook.prototype.$_deleteCards = function(ids) {\n var _this = this;\n\n // Remove cards from $cards and idsMap\n _.forEachRight(this.$cards, function(card, index) {\n var selectedIndex = _.findIndex(ids, function(id) {\n return card.id == id;\n });\n if (selectedIndex > -1) {\n ids.splice(selectedIndex, 1);\n delete _this.idsMap[card.id];\n if (_this.isSelectedCard(card.id))\n delete _this.selectedCard;\n _this.$cards.splice(index, 1);\n }\n else {\n _this.idsMap[card.id] -= ids.length;\n }\n });\n };\n\n /**\n * @function $deleteCards\n * @memberof AddressBook.prototype\n * @desc Delete multiple cards from addressbook.\n * @return a promise of the HTTP operation\n */\n AddressBook.prototype.$deleteCards = function(cards) {\n var _this = this,\n ids = _.map(cards, 'id');\n\n return AddressBook.$$resource.post(this.id, 'batchDelete', {uids: ids}).then(function() {\n _this.$_deleteCards(ids);\n });\n };\n\n /**\n * @function $copyCards\n * @memberof AddressBook.prototype\n * @desc Copy multiple cards from addressbook to an other one.\n * @return a promise of the HTTP operation\n */\n AddressBook.prototype.$copyCards = function(cards, folder) {\n var uids = _.map(cards, 'id');\n return AddressBook.$$resource.post(this.id, 'copy', {uids: uids, folder: folder});\n };\n\n /**\n * @function $moveCards\n * @memberof AddressBook.prototype\n * @desc Move multiple cards from the current addressbook to a target one\n * @param {object[]} cards - instances of Card object\n * @param {string} folder - the destination folder id\n * @return a promise of the HTTP operation\n */\n AddressBook.prototype.$moveCards = function(cards, folder) {\n var _this = this, uids;\n\n uids = _.map(cards, 'id');\n return AddressBook.$$resource.post(this.id, 'move', {uids: uids, folder: folder})\n .then(function() {\n return _this.$_deleteCards(uids);\n });\n };\n\n /**\n * @function $save\n * @memberof AddressBook.prototype\n * @desc Save the addressbook to the server. This currently can only affect the name of the addressbook.\n * @returns a promise of the HTTP operation\n */\n AddressBook.prototype.$save = function() {\n return AddressBook.$$resource.save(this.id, this.$omit()).then(function(data) {\n return data;\n });\n };\n\n /**\n * @function $exportCards\n * @memberof AddressBook.prototype\n * @desc Export the selected/all cards\n * @returns a promise of the HTTP operation\n */\n AddressBook.prototype.exportCards = function(selectedOnly) {\n var data = null, options, selectedCards;\n\n options = {\n type: 'application/octet-stream',\n filename: this.name + '.ldif'\n };\n\n if (selectedOnly) {\n selectedCards = _.filter(this.$cards, function(card) { return card.selected; });\n data = { uids: _.map(selectedCards, 'id') };\n }\n\n return AddressBook.$$resource.download(this.id, 'export', data, options);\n };\n\n /**\n * @function $unwrap\n * @memberof AddressBook.prototype\n * @desc Unwrap a promise and instanciate new Card objects using received data.\n * @param {promise} futureAddressBookData - a promise of the AddressBook's data\n */\n AddressBook.prototype.$unwrap = function(futureAddressBookData) {\n var _this = this;\n\n this.$isLoading = true;\n\n // Expose and resolve the promise\n this.$futureAddressBookData = futureAddressBookData.then(function(response) {\n return AddressBook.$timeout(function() {\n var headers;\n\n if (!response.ids || _this.$topIndex > response.ids.length - 1)\n _this.$topIndex = 0;\n\n // Extend AddressBook instance from data of addressbooks list.\n // Will inherit attributes such as isEditable and isRemote.\n angular.forEach(AddressBook.$findAll(), function(o, i) {\n if (o.id == response.id) {\n angular.extend(_this, o);\n }\n });\n\n // Extend AddressBook instance with received data\n _this.init(response);\n\n if (_this.ids) {\n AddressBook.$log.debug('unwrapping ' + _this.ids.length + ' cards');\n\n // Instanciate Card objects\n _.reduce(_this.ids, function(cards, card, i) {\n var data = { pid: _this.id, id: card };\n\n // Build map of ID <=> index\n _this.idsMap[data.id] = i;\n\n cards.push(new AddressBook.$Card(data));\n\n return cards;\n }, _this.$cards);\n }\n\n if (response.headers) {\n // First entry of 'headers' are keys\n headers = _.invokeMap(response.headers[0], 'toLowerCase');\n response.headers.splice(0, 1);\n\n if (_this.ids) {\n // Extend Card objects with received headers\n _.forEach(response.headers, function(data) {\n var o = _.zipObject(headers, data),\n i = _this.idsMap[o.id];\n _this.$cards[i].init(o);\n });\n }\n else {\n // Instanciate Card objects\n _this.$cards = [];\n angular.forEach(response.headers, function(data) {\n var o = _.zipObject(headers, data);\n angular.extend(o, { pid: _this.id });\n _this.$cards.push(new AddressBook.$Card(o));\n });\n }\n }\n\n // Instanciate Acl object\n _this.$acl = new AddressBook.$$Acl('Contacts/' + _this.id);\n\n _this.$startRefreshTimeout();\n\n _this.$isLoading = false;\n\n AddressBook.$log.debug('addressbook ' + _this.id + ' ready');\n\n return _this;\n });\n }, function(data) {\n _this.isError = true;\n if (angular.isObject(data)) {\n AddressBook.$timeout(function() {\n angular.extend(_this, data);\n });\n }\n });\n };\n\n /**\n * @function $unwrapHeaders\n * @memberof AddressBook.prototype\n * @desc Unwrap a promise and extend matching Card objects with received data.\n * @param {promise} futureHeadersData - a promise of the metadata of some cards\n */\n AddressBook.prototype.$unwrapHeaders = function(futureHeadersData) {\n var _this = this;\n\n futureHeadersData.then(function(data) {\n AddressBook.$timeout(function() {\n var headers, j;\n if (data.length > 0) {\n // First entry of 'headers' are keys\n headers = _.invokeMap(data[0], 'toLowerCase');\n data.splice(0, 1);\n _.forEach(data, function(cardHeaders) {\n cardHeaders = _.zipObject(headers, cardHeaders);\n j = _this.idsMap[cardHeaders.id];\n if (angular.isDefined(j)) {\n _this.$cards[j].init(cardHeaders);\n }\n });\n }\n });\n });\n };\n\n /**\n * @function $omit\n * @memberof AddressBook.prototype\n * @desc Return a sanitized object used to send to the server.\n * @return an object literal copy of the Addressbook instance\n */\n AddressBook.prototype.$omit = function() {\n var addressbook = {};\n angular.forEach(this, function(value, key) {\n if (key != 'constructor' &&\n key != 'acls' &&\n key != 'ids' &&\n key != 'idsMap' &&\n key != 'urls' &&\n key[0] != '$') {\n addressbook[key] = value;\n }\n });\n return addressbook;\n };\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @name Card\n * @constructor\n * @param {object} futureCardData\n * @param {string} [partial]\n */\n function Card(futureCardData, partial) {\n\n // Data is immediately available\n if (typeof futureCardData.then !== 'function') {\n this.init(futureCardData, partial);\n if (this.pid && !this.id) {\n // Prepare for the creation of a new card;\n // Get UID from the server.\n var newCardData = Card.$$resource.newguid(this.pid);\n this.$unwrap(newCardData);\n this.isNew = true;\n }\n }\n else {\n // The promise will be unwrapped first\n this.$unwrap(futureCardData);\n }\n }\n\n Card.$TEL_TYPES = ['work', 'home', 'cell', 'fax', 'pager'];\n Card.$EMAIL_TYPES = ['work', 'home', 'pref'];\n Card.$URL_TYPES = ['work', 'home', 'pref'];\n Card.$ADDRESS_TYPES = ['work', 'home'];\n\n /**\n * @memberof Card\n * @desc The factory we'll use to register with Angular.\n * @returns the Card constructor\n */\n Card.$factory = ['$timeout', 'sgSettings', 'sgCard_STATUS', 'Resource', 'Preferences', function($timeout, Settings, Card_STATUS, Resource, Preferences) {\n angular.extend(Card, {\n STATUS: Card_STATUS,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Contacts', Settings.activeUser()),\n $timeout: $timeout,\n $Preferences: Preferences\n });\n // Initialize categories from user's defaults\n Preferences.ready().then(function() {\n if (Preferences.defaults.SOGoContactsCategories) {\n Card.$categories = Preferences.defaults.SOGoContactsCategories;\n }\n if (Preferences.defaults.SOGoAlternateAvatar)\n Card.$alternateAvatar = Preferences.defaults.SOGoAlternateAvatar;\n });\n\n return Card; // return constructor\n }];\n\n /**\n * @module SOGo.ContactsUI\n * @desc Factory registration of Card in Angular module.\n */\n try {\n angular.module('SOGo.ContactsUI');\n }\n catch(e) {\n angular.module('SOGo.ContactsUI', ['SOGo.Common', 'SOGo.PreferencesUI']);\n }\n angular.module('SOGo.ContactsUI')\n .constant('sgCard_STATUS', {\n NOT_LOADED: 0,\n DELAYED_LOADING: 1,\n LOADING: 2,\n LOADED: 3,\n DELAYED_MS: 300\n })\n .factory('Card', Card.$factory);\n\n /**\n * @memberof Card\n * @desc Fetch a card from a specific addressbook.\n * @param {string} addressbookId - the addressbook ID\n * @param {string} cardId - the card ID\n * @see {@link AddressBook.$getCard}\n */\n Card.$find = function(addressbookId, cardId) {\n var futureCardData = this.$$resource.fetch([addressbookId, cardId].join('/'), 'view');\n\n if (cardId) return new Card(futureCardData); // a single card\n\n return Card.$unwrapCollection(futureCardData); // a collection of cards\n };\n\n /**\n * @function filterCategories\n * @memberof Card.prototype\n * @desc Search for categories matching some criterias\n * @param {string} search - the search string to match\n * @returns a collection of strings\n */\n Card.filterCategories = function(query) {\n var re = new RegExp(query, 'i');\n return _.map(_.filter(Card.$categories, function(category) {\n return category.search(re) != -1;\n }), function(category) {\n return { value: category };\n });\n };\n\n /**\n * @memberof Card\n * @desc Unwrap to a collection of Card instances.\n * @param {object} futureCardData\n */\n Card.$unwrapCollection = function(futureCardData) {\n var collection = {};\n\n collection.$futureCardData = futureCardData;\n\n futureCardData.then(function(cards) {\n Card.$timeout(function() {\n angular.forEach(cards, function(data, index) {\n collection[data.id] = new Card(data);\n });\n });\n });\n\n return collection;\n };\n\n /**\n * @function init\n * @memberof Card.prototype\n * @desc Extend instance with required attributes and new data.\n * @param {object} data - attributes of card\n */\n Card.prototype.init = function(data, partial) {\n var _this = this;\n\n this.refs = [];\n this.categories = [];\n this.c_screenname = null;\n angular.extend(this, data);\n if (!this.$$fullname)\n this.$$fullname = this.$fullname();\n if (!this.$$email)\n this.$$email = this.$preferredEmail(partial);\n if (!this.$$image)\n this.$$image = this.image;\n if (!this.$$image)\n Card.$Preferences.avatar(this.$$email, 32, {no_404: true}).then(function(url) {\n _this.$$image = url;\n });\n if (this.hasphoto)\n this.photoURL = Card.$$resource.path(this.pid, this.id, 'photo');\n if (this.isgroup)\n this.c_component = 'vlist';\n this.$avatarIcon = this.$isList()? 'group' : 'person';\n if (data.notes && data.notes.length)\n this.notes = _.map(data.notes, function(note) { return { 'value': note }; });\n else if (!this.notes || !this.notes.length)\n this.notes = [ { value: '' } ];\n // Lowercase the type of specific fields\n angular.forEach(['addresses', 'phones', 'urls'], function(key) {\n angular.forEach(_this[key], function(o) {\n if (o.type) o.type = o.type.toLowerCase();\n });\n });\n // Instanciate Card objects for list members\n angular.forEach(this.refs, function(o, i) {\n if (o.email) o.emails = [{value: o.email}];\n o.id = o.reference;\n _this.refs[i] = new Card(o);\n });\n // Instanciate date object of birthday\n if (this.birthday) {\n Card.$Preferences.ready().then(function() {\n var dlp = Card.$Preferences.$mdDateLocaleProvider;\n _this.birthday = _this.birthday.parseDate(dlp, '%Y-%m-%d');\n _this.$birthday = dlp.formatDate(_this.birthday);\n });\n }\n\n this.$loaded = angular.isDefined(this.c_name)? Card.STATUS.LOADED : Card.STATUS.NOT_LOADED;\n\n // An empty attribute to trick md-autocomplete when adding attendees from the appointment editor\n this.empty = ' ';\n };\n\n /**\n * @function $id\n * @memberof Card.prototype\n * @desc Return the card ID.\n * @returns the card ID\n */\n Card.prototype.$id = function() {\n return this.$futureCardData.then(function(data) {\n return data.id;\n });\n };\n\n /**\n * @function $isLoading\n * @memberof Card.prototype\n * @returns true if the Card definition is still being retrieved from server after a specific delay\n * @see sgCard_STATUS\n */\n Card.prototype.$isLoading = function() {\n return this.$loaded == Card.STATUS.LOADING;\n };\n\n /**\n * @function $reload\n * @memberof Message.prototype\n * @desc Fetch the viewable message body along with other metadata such as the list of attachments.\n * @returns a promise of the HTTP operation\n */\n Card.prototype.$reload = function() {\n var futureCardData;\n\n if (this.$futureCardData)\n return this;\n\n futureCardData = Card.$$resource.fetch([this.pid, this.id].join('/'), 'view');\n\n return this.$unwrap(futureCardData);\n };\n\n /**\n * @function $save\n * @memberof Card.prototype\n * @desc Save the card to the server.\n */\n Card.prototype.$save = function() {\n var _this = this,\n action = 'saveAsContact';\n\n if (this.c_component == 'vlist') {\n action = 'saveAsList';\n _.forEach(this.refs, function(ref) {\n ref.reference = ref.id;\n });\n }\n\n return Card.$$resource.save([this.pid, this.id || '_new_'].join('/'),\n this.$omit(),\n { action: action })\n .then(function(data) {\n // Format birthdate\n if (_this.birthday)\n _this.$birthday = Card.$Preferences.$mdDateLocaleProvider.formatDate(_this.birthday);\n // Make a copy of the data for an eventual reset\n _this.$shadowData = _this.$omit(true);\n return data;\n });\n };\n\n Card.prototype.$delete = function(attribute, index) {\n if (attribute) {\n if (index > -1 && this[attribute].length > index) {\n this[attribute].splice(index, 1);\n }\n else\n delete this[attribute];\n }\n else {\n // No arguments -- delete card\n return Card.$$resource.remove([this.pid, this.id].join('/'));\n }\n };\n\n /**\n * @function export\n * @memberof Card.prototype\n * @desc Download the current card\n * @returns a promise of the HTTP operation\n */\n Card.prototype.export = function() {\n var data, options;\n\n data = { uids: [ this.id ] };\n options = {\n type: 'application/octet-stream',\n filename: this.$$fullname + '.ldif'\n };\n\n return Card.$$resource.download(this.pid, 'export', data, options);\n };\n\n Card.prototype.$fullname = function(options) {\n var fn = this.c_cn || '', html = options && options.html, email, names;\n if (fn.length === 0) {\n names = [];\n if (this.c_givenname && this.c_givenname.length > 0)\n names.push(this.c_givenname);\n if (this.nickname && this.nickname.length > 0)\n names.push((html?'':'') + this.nickname + (html?'':''));\n if (this.c_sn && this.c_sn.length > 0)\n names.push(this.c_sn);\n if (names.length > 0)\n fn = names.join(' ');\n else if (this.c_org && this.c_org.length > 0) {\n fn = this.c_org;\n }\n else if (this.emails && this.emails.length > 0) {\n email = _.find(this.emails, function(i) { return i.value !== ''; });\n if (email)\n fn = email.value;\n }\n }\n\n return fn;\n };\n\n Card.prototype.$description = function() {\n var description = [];\n if (this.title) description.push(this.title);\n if (this.role) description.push(this.role);\n if (this.orgUnits && this.orgUnits.length > 0)\n _.forEach(this.orgUnits, function(unit) {\n if (unit.value !== '')\n description.push(unit.value);\n });\n if (this.c_org) description.push(this.c_org);\n if (this.description) description.push(this.description);\n\n return description.join(', ');\n };\n\n /**\n * @function $preferredEmail\n * @memberof Card.prototype\n * @desc Get the preferred email address.\n * @param {string} [partial] - a partial string that the email must match\n * @returns the first email address of type \"pref\" or the first address if none found\n */\n Card.prototype.$preferredEmail = function(partial) {\n var email, re;\n if (partial) {\n re = new RegExp(partial, 'i');\n email = _.find(this.emails, function(o) {\n return re.test(o.value);\n });\n }\n if (email) {\n email = email.value;\n }\n else {\n email = _.find(this.emails, function(o) {\n return o.type == 'pref';\n });\n if (email) {\n email = email.value;\n }\n else if (this.emails && this.emails.length) {\n email = this.emails[0].value;\n }\n else if (this.c_mail && this.c_mail.length) {\n email = this.c_mail[0];\n }\n else {\n email = '';\n }\n }\n\n return email;\n };\n\n /**\n * @function $shortFormat\n * @memberof Card.prototype\n * @param {string} [partial] - a partial string that the email must match\n * @returns the fullname along with a matching email address in parentheses\n */\n Card.prototype.$shortFormat = function(partial) {\n var fullname = [this.$$fullname],\n email = this.$preferredEmail(partial);\n if (email && email != this.$$fullname)\n fullname.push(' <' + email + '>');\n return fullname.join(' ');\n };\n\n Card.prototype.$isCard = function() {\n return this.c_component == 'vcard';\n };\n\n Card.prototype.$isList = function(options) {\n // isGroup attribute means it's a group of a LDAP source (not expandable on the client-side)\n var condition = (!options || !options.expandable || options.expandable && !this.isgroup);\n return this.c_component == 'vlist' && condition;\n };\n\n Card.prototype.$addOrgUnit = function(orgUnit) {\n if (angular.isUndefined(this.orgUnits)) {\n this.orgUnits = [{value: orgUnit}];\n }\n else {\n for (var i = 0; i < this.orgUnits.length; i++) {\n if (this.orgUnits[i].value == orgUnit) {\n break;\n }\n }\n if (i == this.orgUnits.length)\n this.orgUnits.push({value: orgUnit});\n }\n return this.orgUnits.length - 1;\n };\n\n // Card.prototype.$addCategory = function(category) {\n // if (category) {\n // if (angular.isUndefined(this.categories)) {\n // this.categories = [{value: category}];\n // }\n // else {\n // for (var i = 0; i < this.categories.length; i++) {\n // if (this.categories[i].value == category) {\n // break;\n // }\n // }\n // if (i == this.categories.length)\n // this.categories.push({value: category});\n // }\n // }\n // };\n\n Card.prototype.$addEmail = function(type) {\n if (angular.isUndefined(this.emails)) {\n this.emails = [{type: type, value: ''}];\n }\n else if (_.isUndefined(_.find(this.emails, function(i) { return i.value === ''; }))) {\n this.emails.push({type: type, value: ''});\n }\n return this.emails.length - 1;\n };\n\n Card.prototype.$addScreenName = function(screenName) {\n this.c_screenname = screenName;\n };\n\n Card.prototype.$addPhone = function(type) {\n if (angular.isUndefined(this.phones)) {\n this.phones = [{type: type, value: ''}];\n }\n else if (_.isUndefined(_.find(this.phones, function(i) { return i.value === ''; }))) {\n this.phones.push({type: type, value: ''});\n }\n return this.phones.length - 1;\n };\n\n Card.prototype.$addUrl = function(type, url) {\n if (angular.isUndefined(this.urls)) {\n this.urls = [{type: type, value: url}];\n }\n else if (_.isUndefined(_.find(this.urls, function(i) { return i.value == url; }))) {\n this.urls.push({type: type, value: url});\n }\n return this.urls.length - 1;\n };\n\n Card.prototype.$addAddress = function(type, postoffice, street, street2, locality, region, country, postalcode) {\n if (angular.isUndefined(this.addresses)) {\n this.addresses = [{type: type, postoffice: postoffice, street: street, street2: street2, locality: locality, region: region, country: country, postalcode: postalcode}];\n }\n else if (!_.find(this.addresses, function(i) {\n return i.street == street &&\n i.street2 == street2 &&\n i.locality == locality &&\n i.country == country &&\n i.postalcode == postalcode;\n })) {\n this.addresses.push({type: type, postoffice: postoffice, street: street, street2: street2, locality: locality, region: region, country: country, postalcode: postalcode});\n }\n return this.addresses.length - 1;\n };\n\n Card.prototype.$addMember = function(email) {\n var card = new Card({email: email, emails: [{value: email}]}),\n i;\n if (angular.isUndefined(this.refs)) {\n this.refs = [card];\n }\n else if (email.length === 0) {\n this.refs.push(card);\n }\n else {\n for (i = 0; i < this.refs.length; i++) {\n if (this.refs[i].email == email) {\n break;\n }\n }\n if (i == this.refs.length)\n this.refs.push(card);\n }\n return this.refs.length - 1;\n };\n\n /**\n * @function explode\n * @memberof Card.prototype\n * @desc Create a new Card associated to each email address of this card.\n * @return an array of Card instances\n */\n Card.prototype.explode = function() {\n var _this = this, cards = [], data;\n\n if (this.emails.length > 1) {\n data = this.$omit();\n _.forEach(this.emails, function(email) {\n var card = new Card(angular.extend({}, data, {emails: [email]}));\n cards.push(card);\n });\n return cards;\n }\n else\n return [this];\n };\n\n /**\n * @function $reset\n * @memberof Card.prototype\n * @desc Reset the original state the card's data.\n */\n Card.prototype.$reset = function() {\n var _this = this;\n angular.forEach(this, function(value, key) {\n if (key != 'constructor' && key[0] != '$') {\n delete _this[key];\n }\n });\n this.init(this.$shadowData);\n this.$shadowData = this.$omit(true);\n };\n\n /**\n * @function $updateMember\n * @memberof Card.prototype\n * @desc Update an existing list member from a Card instance.\n * A list member has the following attribtues:\n * - email\n * - reference\n * - fn\n * @param {number} index\n * @param {string} email\n * @param {Card} card\n */\n // Card.prototype.$updateMember = function(index, email, card) {\n // var ref = {\n // email: email,\n // emails: [{value: email}],\n // reference: card.c_name,\n // c_cn: card.$fullname()\n // };\n // this.refs[index] = new Card(ref);\n // };\n\n /**\n * @function $unwrap\n * @memberof Card.prototype\n * @desc Unwrap a promise and make a copy of the resolved data.\n * @param {object} futureCardData - a promise of the Card's data\n */\n Card.prototype.$unwrap = function(futureCardData) {\n var _this = this;\n\n // Card is not loaded yet\n this.$loaded = Card.STATUS.DELAYED_LOADING;\n Card.$timeout(function() {\n if (_this.$loaded != Card.STATUS.LOADED)\n _this.$loaded = Card.STATUS.LOADING;\n }, Card.STATUS.DELAYED_MS);\n\n // Expose the promise\n this.$futureCardData = futureCardData.then(function(data) {\n _this.init(data);\n // Mark card as loaded\n _this.$loaded = Card.STATUS.LOADED;\n // Make a copy of the data for an eventual reset\n _this.$shadowData = _this.$omit(true);\n\n return _this;\n });\n\n return this.$futureCardData;\n };\n\n /**\n * @function $omit\n * @memberof Card.prototype\n * @desc Return a sanitized object used to send to the server.\n * @param {boolean} [deep] - make a deep copy if true\n * @return an object literal copy of the Card instance\n */\n Card.prototype.$omit = function(deep) {\n var card = {};\n angular.forEach(this, function(value, key) {\n if (key == 'refs') {\n card.refs = _.map(value, function(o) {\n return o.$omit(deep);\n });\n }\n else if (key != 'constructor' && key[0] != '$') {\n if (deep)\n card[key] = angular.copy(value);\n else\n card[key] = value;\n }\n });\n\n // We convert back our birthday object\n if (!deep) {\n if (card.birthday)\n card.birthday = card.birthday.format(Card.$Preferences.$mdDateLocaleProvider, '%Y-%m-%d');\n else\n card.birthday = '';\n }\n\n // We flatten the notes to an array of strings\n if (this.notes)\n card.notes = _.map(this.notes, 'value');\n\n return card;\n };\n\n Card.prototype.toString = function() {\n var desc = this.id + ' ' + this.$$fullname;\n\n if (this.$$email)\n desc += ' <' + this.$$email + '>';\n\n return '[' + desc + ']';\n };\n})();\n"]} \ No newline at end of file +{"version":3,"sources":["Contacts/AddressBook.service.js","Contacts/Card.service.js"],"names":["AddressBook","futureAddressBookData","then","this","init","name","id","newAddressBookData","$$resource","create","$unwrap","acls","objectEditor","objectCreator","objectEraser","$acl","$$Acl","$factory","$q","$timeout","$log","Settings","AddressBook_PRELOAD","Resource","Card","Acl","Preferences","angular","extend","PRELOAD","activeUser","$Card","$Preferences","$query","search","value","sort","asc","selectedFolder","$refreshTimeout","ready","settings","Contact","SortingState","parseInt","module","e","constant","LOOKAHEAD","SIZE","factory","$filterAll","options","excludedCards","params","isUndefined","$cards","fetch","response","results","card","index","compareIds","data","_","filter","contacts","find","bind","length","splice","forEach","mapKeys","key","toLowerCase","debug","when","$add","addressbook","list","sibling","i","isSubscription","$subscriptions","$addressbooks","o","localeCompare","indexOf","map","$findAll","_this","$remotes","isRemote","push","union","$subscribe","uid","path","userResource","addressbookData","$reloadAll","addressbooks","group","owner","login","prototype","$$cards","idsMap","isOwned","isSuperUser","$id","$futureAddressBookData","getLength","getItemAtIndex","$isLoading","$lastVisibleIndex","Math","max","$loadCard","endIndex","ids","futureHeadersData","cardId","startIndex","loaded","isDefined","$loaded","STATUS","NOT_LOADED","min","LOADED","LOADING","join","post","$unwrapHeaders","hasSelectedCard","selectedCard","isSelectedCard","$selectedCard","$selectedCardIndex","$selectedCards","selected","$selectedCount","count","$startRefreshTimeout","cancel","refreshViewCheck","defaults","SOGoRefreshViewCheck","f","$reload","timeInterval","$filter","query","dry","copy","partial","addressbookId","futureData","fields","idFieldIndex","cards","headers","invokeMap","pid","oldIndex","removedCards","findIndex","zipObject","$rename","$save","$delete","promise","d","defer","remove","resolve","reject","$_deleteCards","forEachRight","selectedIndex","$deleteCards","uids","$copyCards","folder","$moveCards","save","$omit","exportCards","selectedOnly","selectedCards","type","filename","download","$topIndex","reduce","isError","isObject","j","cardHeaders","futureCardData","newCardData","newguid","isNew","$TEL_TYPES","$EMAIL_TYPES","$URL_TYPES","$ADDRESS_TYPES","Card_STATUS","SOGoContactsCategories","$categories","SOGoAlternateAvatar","$alternateAvatar","DELAYED_LOADING","DELAYED_MS","$find","$unwrapCollection","filterCategories","re","RegExp","category","collection","$futureCardData","refs","categories","c_screenname","$$fullname","$fullname","$$email","$preferredEmail","$$image","image","avatar","no_404","url","hasphoto","photoURL","isgroup","c_component","$avatarIcon","$isList","orgs","org","notes","note","email","emails","reference","birthday","dlp","$mdDateLocaleProvider","parseDate","$birthday","formatDate","c_name","empty","action","ref","$shadowData","attribute","export","names","fn","c_cn","html","c_givenname","nickname","c_sn","$description","description","title","role","concat","test","c_mail","$shortFormat","fullname","$isCard","condition","expandable","$addOrg","includes","$addEmail","$addScreenName","screenName","$addPhone","phones","$addUrl","urls","$addAddress","postoffice","street","street2","locality","region","country","postalcode","addresses","$addMember","explode","$reset","deep","format","toString","desc"],"mappings":"CAEA,WACE,YAOA,SAASA,GAAYC,GAEnB,GAA0C,kBAA/BA,GAAsBC,KAE/B,GADAC,KAAKC,KAAKH,GACNE,KAAKE,OAASF,KAAKG,GAAI,CAEzB,GAAIC,GAAqBP,EAAYQ,WAAWC,OAAO,eAAgBN,KAAKE,KAC5EF,MAAKO,QAAQH,GACbJ,KAAKQ,MAAQC,aAAgB,EAAGC,cAAiB,EAAGC,aAAgB,OAE7DX,MAAKG,KACZH,KAAKY,KAAO,GAAIf,GAAYgB,MAAM,YAAcb,KAAKG,SAKvDH,MAAKO,QAAQT,GASjBD,EAAYiB,UAAY,KAAM,WAAY,OAAQ,aAAc,wBAAyB,WAAY,OAAQ,MAAO,cAAe,SAASC,EAAIC,EAAUC,EAAMC,EAAUC,EAAqBC,EAAUC,EAAMC,EAAKC,GAsBlN,MArBAC,SAAQC,OAAO5B,GACbkB,GAAIA,EACJC,SAAUA,EACVC,KAAMA,EACNS,QAASP,EACTd,WAAY,GAAIe,GAASF,EAASS,WAAW,aAAe,WAAYT,EAASS,cACjFC,MAAOP,EACPR,MAAOS,EACPO,aAAcN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AK+N,UAKhC,OAHI/N,MAAKiO,UACP4E,GAAQ,KAAO7S,KAAKiO,QAAU,KAEzB,IAAM4E,EAAO","file":"Contacts.services.js","sourcesContent":["/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @name AddressBook\n * @constructor\n * @param {object} futureAddressBookData - either an object literal or a promise\n */\n function AddressBook(futureAddressBookData) {\n // Data is immediately available\n if (typeof futureAddressBookData.then !== 'function') {\n this.init(futureAddressBookData);\n if (this.name && !this.id) {\n // Create a new addressbook on the server\n var newAddressBookData = AddressBook.$$resource.create('createFolder', this.name);\n this.$unwrap(newAddressBookData);\n this.acls = {'objectEditor': 1, 'objectCreator': 1, 'objectEraser': 1};\n }\n else if (this.id) {\n this.$acl = new AddressBook.$$Acl('Contacts/' + this.id);\n }\n }\n else {\n // The promise will be unwrapped first\n this.$unwrap(futureAddressBookData);\n }\n }\n\n /**\n * @memberof AddressBook\n * @desc The factory we'll use to register with Angular\n * @returns the AddressBook constructor\n */\n AddressBook.$factory = ['$q', '$timeout', '$log', 'sgSettings', 'sgAddressBook_PRELOAD', 'Resource', 'Card', 'Acl', 'Preferences', function($q, $timeout, $log, Settings, AddressBook_PRELOAD, Resource, Card, Acl, Preferences) {\n angular.extend(AddressBook, {\n $q: $q,\n $timeout: $timeout,\n $log: $log,\n PRELOAD: AddressBook_PRELOAD,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Contacts', Settings.activeUser()),\n $Card: Card,\n $$Acl: Acl,\n $Preferences: Preferences,\n $query: {search: 'name_or_address', value: '', sort: 'c_cn', asc: 1},\n activeUser: Settings.activeUser(),\n selectedFolder: null,\n $refreshTimeout: null\n });\n // Initialize sort parameters from user's settings\n Preferences.ready().then(function() {\n if (Preferences.settings.Contact.SortingState) {\n AddressBook.$query.sort = Preferences.settings.Contact.SortingState[0];\n AddressBook.$query.asc = parseInt(Preferences.settings.Contact.SortingState[1]);\n }\n });\n return AddressBook; // return constructor\n }];\n\n /**\n * @module SOGo.ContactsUI\n * @desc Factory registration of AddressBook in Angular module.\n */\n try {\n angular.module('SOGo.ContactsUI');\n }\n catch(e) {\n angular.module('SOGo.ContactsUI', ['SOGo.Common', 'SOGo.PreferencesUI']);\n }\n angular.module('SOGo.ContactsUI')\n .constant('sgAddressBook_PRELOAD', {\n LOOKAHEAD: 50,\n SIZE: 100\n })\n .factory('AddressBook', AddressBook.$factory);\n\n /**\n * @memberof AddressBook\n * @desc Search for cards among all addressbooks matching some criterias.\n * @param {string} search - the search string to match\n * @param {object} [options] - additional options to the query (excludeGroups and excludeLists)\n * @param {object[]} excludedCards - a list of Card objects that must be excluded from the results\n * @returns a collection of Cards instances\n */\n AddressBook.$filterAll = function(search, options, excludedCards) {\n var params = { search: search };\n\n if (!search) {\n // No query specified\n AddressBook.$cards = [];\n return AddressBook.$q.when(AddressBook.$cards);\n }\n if (angular.isUndefined(AddressBook.$cards)) {\n // First session query\n AddressBook.$cards = [];\n }\n\n angular.extend(params, options);\n\n return AddressBook.$$resource.fetch(null, 'allContactSearch', params).then(function(response) {\n var results, card, index,\n compareIds = function(data) {\n return this.id == data.id;\n };\n if (excludedCards) {\n // Remove excluded cards from results\n results = _.filter(response.contacts, function(data) {\n return _.isUndefined(_.find(excludedCards, _.bind(compareIds, data)));\n });\n }\n else {\n results = response.contacts;\n }\n // Remove cards that no longer match the search query\n for (index = AddressBook.$cards.length - 1; index >= 0; index--) {\n card = AddressBook.$cards[index];\n if (_.isUndefined(_.find(results, _.bind(compareIds, card)))) {\n AddressBook.$cards.splice(index, 1);\n }\n }\n // Add new cards matching the search query\n _.forEach(results, function(data, index) {\n if (_.isUndefined(_.find(AddressBook.$cards, _.bind(compareIds, data)))) {\n var card = new AddressBook.$Card(_.mapKeys(data, function(value, key) {\n return key.toLowerCase();\n }), search);\n AddressBook.$cards.splice(index, 0, card);\n }\n });\n AddressBook.$log.debug(AddressBook.$cards);\n return AddressBook.$cards;\n });\n };\n\n /**\n * @memberof AddressBook\n * @desc Add a new addressbook to the static list of addressbooks\n * @param {AddressBook} addressbook - an Addressbook object instance\n */\n AddressBook.$add = function(addressbook) {\n // Insert new addressbook at proper index\n var list, sibling, i;\n\n list = addressbook.isSubscription? this.$subscriptions : this.$addressbooks;\n sibling = _.find(list, function(o) {\n return (addressbook.id == 'personal' ||\n (o.id != 'personal' &&\n o.name.localeCompare(addressbook.name) === 1));\n });\n i = sibling ? _.indexOf(_.map(list, 'id'), sibling.id) : 1;\n list.splice(i, 0, addressbook);\n };\n\n /**\n * @memberof AddressBook\n * @desc Set or get the list of addressbooks. Will instantiate a new AddressBook object for each item.\n * @param {array} [data] - the metadata of the addressbooks\n * @returns the list of addressbooks\n */\n AddressBook.$findAll = function(data) {\n var _this = this;\n if (data) {\n this.$addressbooks = [];\n this.$subscriptions = [];\n this.$remotes = [];\n // Instanciate AddressBook objects\n angular.forEach(data, function(o, i) {\n var addressbook = new AddressBook(o);\n if (addressbook.isRemote)\n _this.$remotes.push(addressbook);\n else if (addressbook.isSubscription)\n _this.$subscriptions.push(addressbook);\n else\n _this.$addressbooks.push(addressbook);\n });\n }\n return _.union(this.$addressbooks, this.$subscriptions, this.$remotes);\n };\n\n /**\n * @memberOf AddressBook\n * @desc Subscribe to another user's addressbook and add it to the list of addressbooks.\n * @param {string} uid - user id\n * @param {string} path - path of folder for specified user\n * @returns a promise of the HTTP query result\n */\n AddressBook.$subscribe = function(uid, path) {\n var _this = this;\n return AddressBook.$$resource.userResource(uid).fetch(path, 'subscribe').then(function(addressbookData) {\n var addressbook = new AddressBook(addressbookData);\n if (_.isUndefined(_.find(_this.$subscriptions, function(o) {\n return o.id == addressbookData.id;\n }))) {\n // Not already subscribed\n AddressBook.$add(addressbook);\n }\n return addressbook;\n });\n };\n\n /**\n * @memberof AddressBook\n * @desc Reload the list of known addressbooks.\n */\n AddressBook.$reloadAll = function() {\n var _this = this;\n\n return AddressBook.$$resource.fetch('addressbooksList').then(function(data) {\n _.forEach(data.addressbooks, function(addressbookData) {\n var group, addressbook;\n\n if (addressbookData.isRemote)\n group = _this.$remotes;\n else if (addressbookData.owner != AddressBook.activeUser.login)\n group = _this.$subscriptions;\n else\n group = _this.$addressbooks;\n\n addressbook = _.find(group, function(o) { return o.id == addressbookData.id; });\n if (addressbook)\n addressbook.init(addressbookData);\n });\n });\n };\n\n /**\n * @function init\n * @memberof AddressBook.prototype\n * @desc Extend instance with new data and compute additional attributes.\n * @param {object} data - attributes of addressbook\n */\n AddressBook.prototype.init = function(data, options) {\n var _this = this;\n if (!this.$$cards) {\n // Array of cards for \"dry\" searches (see $filter)\n this.$$cards = [];\n }\n this.idsMap = {};\n this.$cards = [];\n // Extend instance with all attributes of data except headers\n angular.forEach(data, function(value, key) {\n if (key != 'headers' && key != 'cards') {\n _this[key] = value;\n }\n });\n // Add 'isOwned' and 'isSubscription' attributes based on active user (TODO: add it server-side?)\n this.isOwned = AddressBook.activeUser.isSuperUser || this.owner == AddressBook.activeUser.login;\n this.isSubscription = !this.isRemote && this.owner != AddressBook.activeUser.login;\n };\n\n /**\n * @function $id\n * @memberof AddressBook.prototype\n * @desc Resolve the addressbook id.\n * @returns a promise of the addressbook id\n */\n AddressBook.prototype.$id = function() {\n if (this.id) {\n // Object already unwrapped\n return AddressBook.$q.when(this.id);\n }\n else {\n // Wait until object is unwrapped\n return this.$futureAddressBookData.then(function(addressbook) {\n return addressbook.id;\n });\n }\n };\n\n /**\n * @function getLength\n * @memberof AddressBook.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the number of cards in the addressbook\n */\n AddressBook.prototype.getLength = function() {\n return this.$cards.length;\n };\n\n /**\n * @function getItemAtIndex\n * @memberof AddressBook.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the card at the specified index\n */\n AddressBook.prototype.getItemAtIndex = function(index) {\n var card;\n\n if (!this.$isLoading && index >= 0 && index < this.$cards.length) {\n card = this.$cards[index];\n this.$lastVisibleIndex = Math.max(0, index - 3); // Magic number is NUM_EXTRA from virtual-repeater.js\n\n if (this.$loadCard(card))\n return card;\n }\n return null;\n };\n\n /**\n * @function $loadCard\n * @memberof AddressBook.prototype\n * @desc Check if the card is loaded and in any case, fetch more cards headers from the server.\n * @returns true if the card metadata are already fetched\n */\n AddressBook.prototype.$loadCard = function(card) {\n var cardId = card.id,\n startIndex = this.idsMap[cardId],\n endIndex,\n index,\n max = this.$cards.length,\n loaded = false,\n ids,\n futureHeadersData;\n\n if (angular.isUndefined(this.ids) && card.id) {\n loaded = true;\n }\n else if (angular.isDefined(startIndex) && startIndex < this.$cards.length) {\n // Index is valid\n if (card.$loaded != AddressBook.$Card.STATUS.NOT_LOADED) {\n // Card headers are loaded or data is coming\n loaded = true;\n }\n\n // Preload more headers if possible\n endIndex = Math.min(startIndex + AddressBook.PRELOAD.LOOKAHEAD, max - 1);\n if (this.$cards[endIndex].$loaded != AddressBook.$Card.STATUS.NOT_LOADED) {\n index = Math.max(startIndex - AddressBook.PRELOAD.LOOKAHEAD, 0);\n if (this.$cards[index].$loaded != AddressBook.$Card.STATUS.LOADED) {\n // Previous cards not loaded; preload more headers further up\n endIndex = startIndex;\n startIndex = Math.max(startIndex - AddressBook.PRELOAD.SIZE, 0);\n }\n }\n else\n // Next cards not load; preload more headers further down\n endIndex = Math.min(startIndex + AddressBook.PRELOAD.SIZE, max - 1);\n\n if (this.$cards[startIndex].$loaded == AddressBook.$Card.STATUS.NOT_LOADED ||\n this.$cards[endIndex].$loaded == AddressBook.$Card.STATUS.NOT_LOADED) {\n\n for (ids = []; startIndex < endIndex && startIndex < max; startIndex++) {\n if (this.$cards[startIndex].$loaded != AddressBook.$Card.STATUS.NOT_LOADED) {\n // Card at this index is already loaded; increase the end index\n endIndex++;\n }\n else {\n // Card at this index will be loaded\n ids.push(this.$cards[startIndex].id);\n this.$cards[startIndex].$loaded = AddressBook.$Card.STATUS.LOADING;\n }\n }\n\n AddressBook.$log.debug('Loading Ids ' + ids.join(' ') + ' (' + ids.length + ' cards)');\n if (ids.length > 0) {\n futureHeadersData = AddressBook.$$resource.post(this.id, 'headers', {ids: ids});\n this.$unwrapHeaders(futureHeadersData);\n }\n }\n }\n return loaded;\n };\n\n /**\n * @function hasSelectedMessage\n * @memberof AddressBook.prototype\n * @desc Check if a card is selected.\n * @returns true if the a card is selected\n */\n AddressBook.prototype.hasSelectedCard = function() {\n return angular.isDefined(this.selectedCard);\n };\n\n /**\n * @function isSelectedCard\n * @memberof AddressBook.prototype\n * @desc Check if the specified card is selected.\n * @param {string} CardId\n * @returns true if the specified card is selected\n */\n AddressBook.prototype.isSelectedCard = function(cardId) {\n return this.hasSelectedCard() && this.selectedCard == cardId;\n };\n\n /**\n * @function $selectedCard\n * @memberof AddressBook.prototype\n * @desc Return the currently visible card.\n * @returns a Card instance or undefined if no card is displayed\n */\n AddressBook.prototype.$selectedCard = function() {\n var _this = this;\n\n return _.find(this.$cards, function(card) { return card.id == _this.selectedCard; });\n };\n\n /**\n * @function $selectedCardIndex\n * @memberof AddressBook.prototype\n * @desc Return the index of the currently visible card.\n * @returns a number or undefined if no card is selected\n */\n AddressBook.prototype.$selectedCardIndex = function() {\n return _.indexOf(_.map(this.$cards, 'id'), this.selectedCard);\n };\n\n /**\n * @function $selectedCards\n * @memberof AddressBook.prototype\n * @desc Return the cards selected by the user.\n * @returns Card instances\n */\n AddressBook.prototype.$selectedCards = function() {\n return _.filter(this.$cards, function(card) { return card.selected; });\n };\n\n /**\n * @function $selectedCount\n * @memberof AddressBook.prototype\n * @desc Return the number of cards selected by the user.\n * @returns the number of selected cards\n */\n AddressBook.prototype.$selectedCount = function() {\n var count;\n\n count = 0;\n if (this.$cards) {\n count = (_.filter(this.$cards, function(card) { return card.selected; })).length;\n }\n return count;\n };\n\n /**\n * @function $startRefreshTimeout\n * @memberof AddressBook.prototype\n * @desc Starts the refresh timeout for the current selected address book\n */\n AddressBook.prototype.$startRefreshTimeout = function() {\n var _this = this;\n\n if (AddressBook.$refreshTimeout)\n AddressBook.$timeout.cancel(AddressBook.$refreshTimeout);\n\n AddressBook.$Preferences.ready().then(function() {\n // Restart the refresh timer, if needed\n var refreshViewCheck = AddressBook.$Preferences.defaults.SOGoRefreshViewCheck;\n if (refreshViewCheck && refreshViewCheck != 'manually') {\n var f = angular.bind(_this, AddressBook.prototype.$reload);\n AddressBook.$refreshTimeout = AddressBook.$timeout(f, refreshViewCheck.timeInterval()*1000);\n }\n });\n };\n\n /**\n * @function $reload\n * @memberof AddressBook.prototype\n * @desc Reload list of cards\n * @returns a promise of the Cards instances\n */\n AddressBook.prototype.$reload = function() {\n var _this = this;\n\n this.$startRefreshTimeout();\n return this.$filter();\n };\n\n /**\n * @function $filter\n * @memberof AddressBook.prototype\n * @desc Search for cards matching some criterias\n * @param {string} search - the search string to match\n * @param {object} [options] - additional options to the query (dry, excludeList)\n * @returns a collection of Cards instances\n */\n AddressBook.prototype.$filter = function(search, options, excludedCards) {\n var _this = this, query,\n dry = options && options.dry;\n\n if (dry) {\n // Don't keep a copy of the query in dry mode\n query = angular.copy(AddressBook.$query);\n }\n else {\n this.$isLoading = true;\n query = AddressBook.$query;\n if (!this.isRemote) query.partial = 1;\n }\n\n return AddressBook.$Preferences.ready().then(function() {\n if (options) {\n angular.extend(query, options);\n if (dry) {\n if (!search) {\n // No query specified\n _this.$$cards = [];\n return AddressBook.$q.when(_this.$$cards);\n }\n }\n }\n\n if (angular.isDefined(search))\n query.value = search;\n\n return _this.$id().then(function(addressbookId) {\n var futureData = AddressBook.$$resource.fetch(addressbookId, 'view', query);\n\n if (dry) {\n return futureData.then(function(response) {\n var results, headers, card, index, fields, idFieldIndex,\n cards = _this.$$cards,\n compareIds = function(card) {\n return this == card.id;\n };\n\n if (response.headers) {\n // First entry of 'headers' are keys\n fields = _.invokeMap(response.headers[0], 'toLowerCase');\n idFieldIndex = fields.indexOf('id');\n response.headers.splice(0, 1);\n }\n\n if (excludedCards)\n // Remove excluded cards from results\n results = _.filter(response.ids, function(id) {\n return _.isUndefined(_.find(excludedCards, _.bind(compareIds, id)));\n });\n else\n results = response.ids;\n\n // Remove cards that no longer match the search query\n for (index = cards.length - 1; index >= 0; index--) {\n card = cards[index];\n if (_.isUndefined(_.find(results, _.bind(compareIds, card.id)))) {\n cards.splice(index, 1);\n }\n }\n\n // Add new cards matching the search query\n _.forEach(results, function(cardId, index) {\n if (_.isUndefined(_.find(cards, _.bind(compareIds, cardId)))) {\n var data = { pid: addressbookId, id: cardId };\n var card = new AddressBook.$Card(data, search);\n cards.splice(index, 0, card);\n }\n });\n\n // Respect the order of the results\n _.forEach(results, function(cardId, index) {\n var oldIndex, removedCards;\n if (cards[index].id != cardId) {\n oldIndex = _.findIndex(cards, _.bind(compareIds, cardId));\n removedCards = cards.splice(oldIndex, 1);\n cards.splice(index, 0, removedCards[0]);\n }\n });\n\n // Extend Card objects with received headers\n _.forEach(response.headers, function(data) {\n var card, index = _.findIndex(cards, _.bind(compareIds, data[idFieldIndex]));\n if (index > -1) {\n card = _.zipObject(fields, data);\n cards[index].init(card, search);\n }\n });\n\n return cards;\n });\n }\n else {\n // Unwrap promise and instantiate or extend Cards objets\n return _this.$unwrap(futureData);\n }\n });\n });\n };\n\n /**\n * @function $rename\n * @memberof AddressBook.prototype\n * @desc Rename the addressbook and keep the list sorted\n * @param {string} name - the new name\n * @returns a promise of the HTTP operation\n */\n AddressBook.prototype.$rename = function(name) {\n var i, list;\n\n list = this.isSubscription? AddressBook.$subscriptions : AddressBook.$addressbooks;\n i = _.indexOf(_.map(list, 'id'), this.id);\n this.name = name;\n list.splice(i, 1);\n AddressBook.$add(this);\n\n return this.$save();\n };\n\n /**\n * @function $delete\n * @memberof AddressBook.prototype\n * @desc Delete the addressbook from the server and the static list of addressbooks.\n * @returns a promise of the HTTP operation\n */\n AddressBook.prototype.$delete = function() {\n var _this = this,\n d = AddressBook.$q.defer(),\n list,\n promise;\n\n if (this.isSubscription) {\n promise = AddressBook.$$resource.fetch(this.id, 'unsubscribe');\n list = AddressBook.$subscriptions;\n }\n else {\n promise = AddressBook.$$resource.remove(this.id);\n list = AddressBook.$addressbooks;\n }\n\n promise.then(function() {\n var i = _.indexOf(_.map(list, 'id'), _this.id);\n list.splice(i, 1);\n d.resolve();\n }, d.reject);\n return d.promise;\n };\n\n /**\n * @function $_deleteCards\n * @memberof AddressBook.prototype\n * @desc Delete multiple cards from AddressBook object.\n * @param {string[]} ids - the cards ids\n */\n AddressBook.prototype.$_deleteCards = function(ids) {\n var _this = this;\n\n // Remove cards from $cards and idsMap\n _.forEachRight(this.$cards, function(card, index) {\n var selectedIndex = _.findIndex(ids, function(id) {\n return card.id == id;\n });\n if (selectedIndex > -1) {\n ids.splice(selectedIndex, 1);\n delete _this.idsMap[card.id];\n if (_this.isSelectedCard(card.id))\n delete _this.selectedCard;\n _this.$cards.splice(index, 1);\n }\n else {\n _this.idsMap[card.id] -= ids.length;\n }\n });\n };\n\n /**\n * @function $deleteCards\n * @memberof AddressBook.prototype\n * @desc Delete multiple cards from addressbook.\n * @return a promise of the HTTP operation\n */\n AddressBook.prototype.$deleteCards = function(cards) {\n var _this = this,\n ids = _.map(cards, 'id');\n\n return AddressBook.$$resource.post(this.id, 'batchDelete', {uids: ids}).then(function() {\n _this.$_deleteCards(ids);\n });\n };\n\n /**\n * @function $copyCards\n * @memberof AddressBook.prototype\n * @desc Copy multiple cards from addressbook to an other one.\n * @return a promise of the HTTP operation\n */\n AddressBook.prototype.$copyCards = function(cards, folder) {\n var uids = _.map(cards, 'id');\n return AddressBook.$$resource.post(this.id, 'copy', {uids: uids, folder: folder});\n };\n\n /**\n * @function $moveCards\n * @memberof AddressBook.prototype\n * @desc Move multiple cards from the current addressbook to a target one\n * @param {object[]} cards - instances of Card object\n * @param {string} folder - the destination folder id\n * @return a promise of the HTTP operation\n */\n AddressBook.prototype.$moveCards = function(cards, folder) {\n var _this = this, uids;\n\n uids = _.map(cards, 'id');\n return AddressBook.$$resource.post(this.id, 'move', {uids: uids, folder: folder})\n .then(function() {\n return _this.$_deleteCards(uids);\n });\n };\n\n /**\n * @function $save\n * @memberof AddressBook.prototype\n * @desc Save the addressbook to the server. This currently can only affect the name of the addressbook.\n * @returns a promise of the HTTP operation\n */\n AddressBook.prototype.$save = function() {\n return AddressBook.$$resource.save(this.id, this.$omit()).then(function(data) {\n return data;\n });\n };\n\n /**\n * @function $exportCards\n * @memberof AddressBook.prototype\n * @desc Export the selected/all cards\n * @returns a promise of the HTTP operation\n */\n AddressBook.prototype.exportCards = function(selectedOnly) {\n var data = null, options, selectedCards;\n\n options = {\n type: 'application/octet-stream',\n filename: this.name + '.ldif'\n };\n\n if (selectedOnly) {\n selectedCards = _.filter(this.$cards, function(card) { return card.selected; });\n data = { uids: _.map(selectedCards, 'id') };\n }\n\n return AddressBook.$$resource.download(this.id, 'export', data, options);\n };\n\n /**\n * @function $unwrap\n * @memberof AddressBook.prototype\n * @desc Unwrap a promise and instanciate new Card objects using received data.\n * @param {promise} futureAddressBookData - a promise of the AddressBook's data\n */\n AddressBook.prototype.$unwrap = function(futureAddressBookData) {\n var _this = this;\n\n this.$isLoading = true;\n\n // Expose and resolve the promise\n this.$futureAddressBookData = futureAddressBookData.then(function(response) {\n return AddressBook.$timeout(function() {\n var headers;\n\n if (!response.ids || _this.$topIndex > response.ids.length - 1)\n _this.$topIndex = 0;\n\n // Extend AddressBook instance from data of addressbooks list.\n // Will inherit attributes such as isEditable and isRemote.\n angular.forEach(AddressBook.$findAll(), function(o, i) {\n if (o.id == response.id) {\n angular.extend(_this, o);\n }\n });\n\n // Extend AddressBook instance with received data\n _this.init(response);\n\n if (_this.ids) {\n AddressBook.$log.debug('unwrapping ' + _this.ids.length + ' cards');\n\n // Instanciate Card objects\n _.reduce(_this.ids, function(cards, card, i) {\n var data = { pid: _this.id, id: card };\n\n // Build map of ID <=> index\n _this.idsMap[data.id] = i;\n\n cards.push(new AddressBook.$Card(data));\n\n return cards;\n }, _this.$cards);\n }\n\n if (response.headers) {\n // First entry of 'headers' are keys\n headers = _.invokeMap(response.headers[0], 'toLowerCase');\n response.headers.splice(0, 1);\n\n if (_this.ids) {\n // Extend Card objects with received headers\n _.forEach(response.headers, function(data) {\n var o = _.zipObject(headers, data),\n i = _this.idsMap[o.id];\n _this.$cards[i].init(o);\n });\n }\n else {\n // Instanciate Card objects\n _this.$cards = [];\n angular.forEach(response.headers, function(data) {\n var o = _.zipObject(headers, data);\n angular.extend(o, { pid: _this.id });\n _this.$cards.push(new AddressBook.$Card(o));\n });\n }\n }\n\n // Instanciate Acl object\n _this.$acl = new AddressBook.$$Acl('Contacts/' + _this.id);\n\n _this.$startRefreshTimeout();\n\n _this.$isLoading = false;\n\n AddressBook.$log.debug('addressbook ' + _this.id + ' ready');\n\n return _this;\n });\n }, function(data) {\n _this.isError = true;\n if (angular.isObject(data)) {\n AddressBook.$timeout(function() {\n angular.extend(_this, data);\n });\n }\n });\n };\n\n /**\n * @function $unwrapHeaders\n * @memberof AddressBook.prototype\n * @desc Unwrap a promise and extend matching Card objects with received data.\n * @param {promise} futureHeadersData - a promise of the metadata of some cards\n */\n AddressBook.prototype.$unwrapHeaders = function(futureHeadersData) {\n var _this = this;\n\n futureHeadersData.then(function(data) {\n AddressBook.$timeout(function() {\n var headers, j;\n if (data.length > 0) {\n // First entry of 'headers' are keys\n headers = _.invokeMap(data[0], 'toLowerCase');\n data.splice(0, 1);\n _.forEach(data, function(cardHeaders) {\n cardHeaders = _.zipObject(headers, cardHeaders);\n j = _this.idsMap[cardHeaders.id];\n if (angular.isDefined(j)) {\n _this.$cards[j].init(cardHeaders);\n }\n });\n }\n });\n });\n };\n\n /**\n * @function $omit\n * @memberof AddressBook.prototype\n * @desc Return a sanitized object used to send to the server.\n * @return an object literal copy of the Addressbook instance\n */\n AddressBook.prototype.$omit = function() {\n var addressbook = {};\n angular.forEach(this, function(value, key) {\n if (key != 'constructor' &&\n key != 'acls' &&\n key != 'ids' &&\n key != 'idsMap' &&\n key != 'urls' &&\n key[0] != '$') {\n addressbook[key] = value;\n }\n });\n return addressbook;\n };\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @name Card\n * @constructor\n * @param {object} futureCardData\n * @param {string} [partial]\n */\n function Card(futureCardData, partial) {\n\n // Data is immediately available\n if (typeof futureCardData.then !== 'function') {\n this.init(futureCardData, partial);\n if (this.pid && !this.id) {\n // Prepare for the creation of a new card;\n // Get UID from the server.\n var newCardData = Card.$$resource.newguid(this.pid);\n this.$unwrap(newCardData);\n this.isNew = true;\n }\n }\n else {\n // The promise will be unwrapped first\n this.$unwrap(futureCardData);\n }\n }\n\n Card.$TEL_TYPES = ['work', 'home', 'cell', 'fax', 'pager'];\n Card.$EMAIL_TYPES = ['work', 'home', 'pref'];\n Card.$URL_TYPES = ['work', 'home', 'pref'];\n Card.$ADDRESS_TYPES = ['work', 'home'];\n\n /**\n * @memberof Card\n * @desc The factory we'll use to register with Angular.\n * @returns the Card constructor\n */\n Card.$factory = ['$timeout', 'sgSettings', 'sgCard_STATUS', 'Resource', 'Preferences', function($timeout, Settings, Card_STATUS, Resource, Preferences) {\n angular.extend(Card, {\n STATUS: Card_STATUS,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Contacts', Settings.activeUser()),\n $timeout: $timeout,\n $Preferences: Preferences\n });\n // Initialize categories from user's defaults\n Preferences.ready().then(function() {\n if (Preferences.defaults.SOGoContactsCategories) {\n Card.$categories = Preferences.defaults.SOGoContactsCategories;\n }\n if (Preferences.defaults.SOGoAlternateAvatar)\n Card.$alternateAvatar = Preferences.defaults.SOGoAlternateAvatar;\n });\n\n return Card; // return constructor\n }];\n\n /**\n * @module SOGo.ContactsUI\n * @desc Factory registration of Card in Angular module.\n */\n try {\n angular.module('SOGo.ContactsUI');\n }\n catch(e) {\n angular.module('SOGo.ContactsUI', ['SOGo.Common', 'SOGo.PreferencesUI']);\n }\n angular.module('SOGo.ContactsUI')\n .constant('sgCard_STATUS', {\n NOT_LOADED: 0,\n DELAYED_LOADING: 1,\n LOADING: 2,\n LOADED: 3,\n DELAYED_MS: 300\n })\n .factory('Card', Card.$factory);\n\n /**\n * @memberof Card\n * @desc Fetch a card from a specific addressbook.\n * @param {string} addressbookId - the addressbook ID\n * @param {string} cardId - the card ID\n * @see {@link AddressBook.$getCard}\n */\n Card.$find = function(addressbookId, cardId) {\n var futureCardData = this.$$resource.fetch([addressbookId, cardId].join('/'), 'view');\n\n if (cardId) return new Card(futureCardData); // a single card\n\n return Card.$unwrapCollection(futureCardData); // a collection of cards\n };\n\n /**\n * @function filterCategories\n * @memberof Card.prototype\n * @desc Search for categories matching some criterias\n * @param {string} search - the search string to match\n * @returns a collection of strings\n */\n Card.filterCategories = function(query) {\n var re = new RegExp(query, 'i');\n return _.map(_.filter(Card.$categories, function(category) {\n return category.search(re) != -1;\n }), function(category) {\n return { value: category };\n });\n };\n\n /**\n * @memberof Card\n * @desc Unwrap to a collection of Card instances.\n * @param {object} futureCardData\n */\n Card.$unwrapCollection = function(futureCardData) {\n var collection = {};\n\n collection.$futureCardData = futureCardData;\n\n futureCardData.then(function(cards) {\n Card.$timeout(function() {\n angular.forEach(cards, function(data, index) {\n collection[data.id] = new Card(data);\n });\n });\n });\n\n return collection;\n };\n\n /**\n * @function init\n * @memberof Card.prototype\n * @desc Extend instance with required attributes and new data.\n * @param {object} data - attributes of card\n */\n Card.prototype.init = function(data, partial) {\n var _this = this;\n\n this.refs = [];\n this.categories = [];\n this.c_screenname = null;\n angular.extend(this, data);\n if (!this.$$fullname)\n this.$$fullname = this.$fullname();\n if (!this.$$email)\n this.$$email = this.$preferredEmail(partial);\n if (!this.$$image)\n this.$$image = this.image;\n if (!this.$$image)\n Card.$Preferences.avatar(this.$$email, 32, {no_404: true}).then(function(url) {\n _this.$$image = url;\n });\n if (this.hasphoto)\n this.photoURL = Card.$$resource.path(this.pid, this.id, 'photo');\n if (this.isgroup)\n this.c_component = 'vlist';\n this.$avatarIcon = this.$isList()? 'group' : 'person';\n if (data.orgs && data.orgs.length)\n this.orgs = _.map(data.orgs, function(org) { return { 'value': org }; });\n if (data.notes && data.notes.length)\n this.notes = _.map(data.notes, function(note) { return { 'value': note }; });\n else if (!this.notes || !this.notes.length)\n this.notes = [ { value: '' } ];\n // Lowercase the type of specific fields\n angular.forEach(['addresses', 'phones', 'urls'], function(key) {\n angular.forEach(_this[key], function(o) {\n if (o.type) o.type = o.type.toLowerCase();\n });\n });\n // Instanciate Card objects for list members\n angular.forEach(this.refs, function(o, i) {\n if (o.email) o.emails = [{value: o.email}];\n o.id = o.reference;\n _this.refs[i] = new Card(o);\n });\n // Instanciate date object of birthday\n if (this.birthday) {\n Card.$Preferences.ready().then(function() {\n var dlp = Card.$Preferences.$mdDateLocaleProvider;\n _this.birthday = _this.birthday.parseDate(dlp, '%Y-%m-%d');\n _this.$birthday = dlp.formatDate(_this.birthday);\n });\n }\n\n this.$loaded = angular.isDefined(this.c_name)? Card.STATUS.LOADED : Card.STATUS.NOT_LOADED;\n\n // An empty attribute to trick md-autocomplete when adding attendees from the appointment editor\n this.empty = ' ';\n };\n\n /**\n * @function $id\n * @memberof Card.prototype\n * @desc Return the card ID.\n * @returns the card ID\n */\n Card.prototype.$id = function() {\n return this.$futureCardData.then(function(data) {\n return data.id;\n });\n };\n\n /**\n * @function $isLoading\n * @memberof Card.prototype\n * @returns true if the Card definition is still being retrieved from server after a specific delay\n * @see sgCard_STATUS\n */\n Card.prototype.$isLoading = function() {\n return this.$loaded == Card.STATUS.LOADING;\n };\n\n /**\n * @function $reload\n * @memberof Message.prototype\n * @desc Fetch the viewable message body along with other metadata such as the list of attachments.\n * @returns a promise of the HTTP operation\n */\n Card.prototype.$reload = function() {\n var futureCardData;\n\n if (this.$futureCardData)\n return this;\n\n futureCardData = Card.$$resource.fetch([this.pid, this.id].join('/'), 'view');\n\n return this.$unwrap(futureCardData);\n };\n\n /**\n * @function $save\n * @memberof Card.prototype\n * @desc Save the card to the server.\n */\n Card.prototype.$save = function() {\n var _this = this,\n action = 'saveAsContact';\n\n if (this.c_component == 'vlist') {\n action = 'saveAsList';\n _.forEach(this.refs, function(ref) {\n ref.reference = ref.id;\n });\n }\n\n return Card.$$resource.save([this.pid, this.id || '_new_'].join('/'),\n this.$omit(),\n { action: action })\n .then(function(data) {\n // Format birthdate\n if (_this.birthday)\n _this.$birthday = Card.$Preferences.$mdDateLocaleProvider.formatDate(_this.birthday);\n // Make a copy of the data for an eventual reset\n _this.$shadowData = _this.$omit(true);\n return data;\n });\n };\n\n Card.prototype.$delete = function(attribute, index) {\n if (attribute) {\n if (index > -1 && this[attribute].length > index) {\n this[attribute].splice(index, 1);\n }\n else\n delete this[attribute];\n }\n else {\n // No arguments -- delete card\n return Card.$$resource.remove([this.pid, this.id].join('/'));\n }\n };\n\n /**\n * @function export\n * @memberof Card.prototype\n * @desc Download the current card\n * @returns a promise of the HTTP operation\n */\n Card.prototype.export = function() {\n var data, options;\n\n data = { uids: [ this.id ] };\n options = {\n type: 'application/octet-stream',\n filename: this.$$fullname + '.ldif'\n };\n\n return Card.$$resource.download(this.pid, 'export', data, options);\n };\n\n Card.prototype.$fullname = function(options) {\n var fn = this.c_cn || '', html = options && options.html, email, names;\n if (fn.length === 0) {\n names = [];\n if (this.c_givenname && this.c_givenname.length > 0)\n names.push(this.c_givenname);\n if (this.nickname && this.nickname.length > 0)\n names.push((html?'':'') + this.nickname + (html?'':''));\n if (this.c_sn && this.c_sn.length > 0)\n names.push(this.c_sn);\n if (names.length > 0)\n fn = names.join(' ');\n else if (this.org && this.org.length > 0) {\n fn = this.org;\n }\n else if (this.emails && this.emails.length > 0) {\n email = _.find(this.emails, function(i) { return i.value !== ''; });\n if (email)\n fn = email.value;\n }\n }\n\n return fn;\n };\n\n Card.prototype.$description = function() {\n var description = [];\n if (this.title) description.push(this.title);\n if (this.role) description.push(this.role);\n if (this.org) description.push(this.org);\n if (this.orgs) description = _.concat(description, _.map(this.orgs, 'value'));\n if (this.description) description.push(this.description);\n\n return description.join(', ');\n };\n\n /**\n * @function $preferredEmail\n * @memberof Card.prototype\n * @desc Get the preferred email address.\n * @param {string} [partial] - a partial string that the email must match\n * @returns the first email address of type \"pref\" or the first address if none found\n */\n Card.prototype.$preferredEmail = function(partial) {\n var email, re;\n if (partial) {\n re = new RegExp(partial, 'i');\n email = _.find(this.emails, function(o) {\n return re.test(o.value);\n });\n }\n if (email) {\n email = email.value;\n }\n else {\n email = _.find(this.emails, function(o) {\n return o.type == 'pref';\n });\n if (email) {\n email = email.value;\n }\n else if (this.emails && this.emails.length) {\n email = this.emails[0].value;\n }\n else if (this.c_mail && this.c_mail.length) {\n email = this.c_mail[0];\n }\n else {\n email = '';\n }\n }\n\n return email;\n };\n\n /**\n * @function $shortFormat\n * @memberof Card.prototype\n * @param {string} [partial] - a partial string that the email must match\n * @returns the fullname along with a matching email address in parentheses\n */\n Card.prototype.$shortFormat = function(partial) {\n var fullname = [this.$$fullname],\n email = this.$preferredEmail(partial);\n if (email && email != this.$$fullname)\n fullname.push(' <' + email + '>');\n return fullname.join(' ');\n };\n\n Card.prototype.$isCard = function() {\n return this.c_component == 'vcard';\n };\n\n Card.prototype.$isList = function(options) {\n // isGroup attribute means it's a group of a LDAP source (not expandable on the client-side)\n var condition = (!options || !options.expandable || options.expandable && !this.isgroup);\n return this.c_component == 'vlist' && condition;\n };\n\n Card.prototype.$addOrg = function(org) {\n if (angular.isUndefined(this.orgs)) {\n this.orgs = [org];\n }\n else if (org != this.org && !_.includes(this.orgs, org)) {\n this.orgs.push(org);\n }\n return this.orgs.length - 1;\n };\n\n // Card.prototype.$addCategory = function(category) {\n // if (category) {\n // if (angular.isUndefined(this.categories)) {\n // this.categories = [{value: category}];\n // }\n // else {\n // for (var i = 0; i < this.categories.length; i++) {\n // if (this.categories[i].value == category) {\n // break;\n // }\n // }\n // if (i == this.categories.length)\n // this.categories.push({value: category});\n // }\n // }\n // };\n\n Card.prototype.$addEmail = function(type) {\n if (angular.isUndefined(this.emails)) {\n this.emails = [{type: type, value: ''}];\n }\n else if (_.isUndefined(_.find(this.emails, function(i) { return i.value === ''; }))) {\n this.emails.push({type: type, value: ''});\n }\n return this.emails.length - 1;\n };\n\n Card.prototype.$addScreenName = function(screenName) {\n this.c_screenname = screenName;\n };\n\n Card.prototype.$addPhone = function(type) {\n if (angular.isUndefined(this.phones)) {\n this.phones = [{type: type, value: ''}];\n }\n else if (_.isUndefined(_.find(this.phones, function(i) { return i.value === ''; }))) {\n this.phones.push({type: type, value: ''});\n }\n return this.phones.length - 1;\n };\n\n Card.prototype.$addUrl = function(type, url) {\n if (angular.isUndefined(this.urls)) {\n this.urls = [{type: type, value: url}];\n }\n else if (_.isUndefined(_.find(this.urls, function(i) { return i.value == url; }))) {\n this.urls.push({type: type, value: url});\n }\n return this.urls.length - 1;\n };\n\n Card.prototype.$addAddress = function(type, postoffice, street, street2, locality, region, country, postalcode) {\n if (angular.isUndefined(this.addresses)) {\n this.addresses = [{type: type, postoffice: postoffice, street: street, street2: street2, locality: locality, region: region, country: country, postalcode: postalcode}];\n }\n else if (!_.find(this.addresses, function(i) {\n return i.street == street &&\n i.street2 == street2 &&\n i.locality == locality &&\n i.country == country &&\n i.postalcode == postalcode;\n })) {\n this.addresses.push({type: type, postoffice: postoffice, street: street, street2: street2, locality: locality, region: region, country: country, postalcode: postalcode});\n }\n return this.addresses.length - 1;\n };\n\n Card.prototype.$addMember = function(email) {\n var card = new Card({email: email, emails: [{value: email}]}),\n i;\n if (angular.isUndefined(this.refs)) {\n this.refs = [card];\n }\n else if (email.length === 0) {\n this.refs.push(card);\n }\n else {\n for (i = 0; i < this.refs.length; i++) {\n if (this.refs[i].email == email) {\n break;\n }\n }\n if (i == this.refs.length)\n this.refs.push(card);\n }\n return this.refs.length - 1;\n };\n\n /**\n * @function explode\n * @memberof Card.prototype\n * @desc Create a new Card associated to each email address of this card.\n * @return an array of Card instances\n */\n Card.prototype.explode = function() {\n var _this = this, cards = [], data;\n\n if (this.emails.length > 1) {\n data = this.$omit();\n _.forEach(this.emails, function(email) {\n var card = new Card(angular.extend({}, data, {emails: [email]}));\n cards.push(card);\n });\n return cards;\n }\n else\n return [this];\n };\n\n /**\n * @function $reset\n * @memberof Card.prototype\n * @desc Reset the original state the card's data.\n */\n Card.prototype.$reset = function() {\n var _this = this;\n angular.forEach(this, function(value, key) {\n if (key != 'constructor' && key[0] != '$') {\n delete _this[key];\n }\n });\n this.init(this.$shadowData);\n this.$shadowData = this.$omit(true);\n };\n\n /**\n * @function $updateMember\n * @memberof Card.prototype\n * @desc Update an existing list member from a Card instance.\n * A list member has the following attribtues:\n * - email\n * - reference\n * - fn\n * @param {number} index\n * @param {string} email\n * @param {Card} card\n */\n // Card.prototype.$updateMember = function(index, email, card) {\n // var ref = {\n // email: email,\n // emails: [{value: email}],\n // reference: card.c_name,\n // c_cn: card.$fullname()\n // };\n // this.refs[index] = new Card(ref);\n // };\n\n /**\n * @function $unwrap\n * @memberof Card.prototype\n * @desc Unwrap a promise and make a copy of the resolved data.\n * @param {object} futureCardData - a promise of the Card's data\n */\n Card.prototype.$unwrap = function(futureCardData) {\n var _this = this;\n\n // Card is not loaded yet\n this.$loaded = Card.STATUS.DELAYED_LOADING;\n Card.$timeout(function() {\n if (_this.$loaded != Card.STATUS.LOADED)\n _this.$loaded = Card.STATUS.LOADING;\n }, Card.STATUS.DELAYED_MS);\n\n // Expose the promise\n this.$futureCardData = futureCardData.then(function(data) {\n _this.init(data);\n // Mark card as loaded\n _this.$loaded = Card.STATUS.LOADED;\n // Make a copy of the data for an eventual reset\n _this.$shadowData = _this.$omit(true);\n\n return _this;\n });\n\n return this.$futureCardData;\n };\n\n /**\n * @function $omit\n * @memberof Card.prototype\n * @desc Return a sanitized object used to send to the server.\n * @param {boolean} [deep] - make a deep copy if true\n * @return an object literal copy of the Card instance\n */\n Card.prototype.$omit = function(deep) {\n var card = {};\n angular.forEach(this, function(value, key) {\n if (key == 'refs') {\n card.refs = _.map(value, function(o) {\n return o.$omit(deep);\n });\n }\n else if (key != 'constructor' && key[0] != '$') {\n if (deep)\n card[key] = angular.copy(value);\n else\n card[key] = value;\n }\n });\n\n // We convert back our birthday object\n if (!deep) {\n if (card.birthday)\n card.birthday = card.birthday.format(Card.$Preferences.$mdDateLocaleProvider, '%Y-%m-%d');\n else\n card.birthday = '';\n }\n\n // We flatten the organizations to an array of strings\n if (this.orgs)\n card.orgs = _.map(this.orgs, 'value');\n\n // We flatten the notes to an array of strings\n if (this.notes)\n card.notes = _.map(this.notes, 'value');\n\n return card;\n };\n\n Card.prototype.toString = function() {\n var desc = this.id + ' ' + this.$$fullname;\n\n if (this.$$email)\n desc += ' <' + this.$$email + '>';\n\n return '[' + desc + ']';\n };\n})();\n"]} \ No newline at end of file diff --git a/UI/WebServerResources/js/Mailer.services.js b/UI/WebServerResources/js/Mailer.services.js index f07c14408..58b8aac8e 100644 --- a/UI/WebServerResources/js/Mailer.services.js +++ b/UI/WebServerResources/js/Mailer.services.js @@ -1,3 +1,3 @@ -!function(){"use strict";function a(b){"function"!=typeof b.then&&(angular.extend(this,b),_.forEach(this.identities,function(a){a.fullName?a.full=a.fullName+" <"+a.email+">":a.full="<"+a.email+">"}),a.$log.debug("Account: "+JSON.stringify(b,void 0,2)))}a.$factory=["$q","$timeout","$log","sgSettings","Resource","Preferences","Mailbox","Message",function(b,c,d,e,f,g,h,i){return angular.extend(a,{$q:b,$timeout:c,$log:d,$$resource:new f(e.activeUser("folderURL")+"Mail",e.activeUser()),$Preferences:g,$Mailbox:h,$Message:i}),a}];try{angular.module("SOGo.MailerUI")}catch(a){angular.module("SOGo.MailerUI",["SOGo.Common"])}angular.module("SOGo.MailerUI").factory("Account",a.$factory),a.$findAll=function(b){return b?a.$unwrapCollection(b):a.$$resource.fetch("","mailAccounts").then(function(b){return a.$unwrapCollection(b)})},a.$unwrapCollection=function(b){var c=[];return angular.forEach(b,function(b,d){b.id=d,c[d]=new a(b)}),a.$accounts=c,c},a.prototype.getLength=function(){return this.$flattenMailboxes().length},a.prototype.getItemAtIndex=function(a){var b;return b=this.$flattenMailboxes(),a>=0&&a=0,a.children&&a.children.length>0&&d(a.children)})};a.$Preferences.settings.Mail.ExpandedFolders&&(b=angular.isString(a.$Preferences.settings.Mail.ExpandedFolders)?angular.fromJson(a.$Preferences.settings.Mail.ExpandedFolders):a.$Preferences.settings.Mail.ExpandedFolders,c.$expanded=b.indexOf("/"+c.id)>=0,b.length>0&&d(c.$mailboxes)),a.$accounts&&(c.$expanded|=1==a.$accounts.length),c.$flattenMailboxes({reload:!0})}),c.$mailboxes}):a.$q.when(this.$mailboxes)},a.prototype.$flattenMailboxes=function(b){var c=this,d=[],e=[],f=function(a){_.forEach(a,function(a){d.push(a),(b&&b.all||a.$expanded)&&a.children&&a.children.length>0&&f(a.children)})};return!this.$$flattenMailboxes||b&&(b.reload||b.all)?(f(this.$mailboxes),b&&b.all||(c.$$flattenMailboxes=d,b&&b.saveState&&(_.forEach(a.$accounts,function(a){a.$expanded&&e.push("/"+a.id),_.reduce(a.$$flattenMailboxes,function(a,b){return b.$expanded&&a.push("/"+b.id),a},e)}),a.$$resource.post(null,"saveFoldersState",e)))):d=this.$$flattenMailboxes,d},a.prototype.$getMailboxByType=function(a){var b=function(c){var d=_.find(c,function(b){return b.type==a});return d||angular.forEach(c,function(a){!d&&a.children&&a.children.length>0&&(d=b(a.children))}),d};return b(this.$mailboxes)},a.prototype.$getMailboxByPath=function(a){var b=function(c){var d=_.find(c,function(b){return b.path==a});return d||angular.forEach(c,function(a){!d&&a.children&&a.children.length>0&&(d=b(a.children))}),d};return b(this.$mailboxes)},a.prototype.$newMailbox=function(b,c){var d=this;return a.$$resource.post(b.toString(),"createFolder",{name:c}).then(function(){d.$getMailboxes({reload:!0})})},a.prototype.updateQuota=function(a){var b,c,d;b=Math.round(1e4*a.usedSpace/a.maxQuota)/100,c=l("quotasFormat"),d=c.formatted(b,Math.round(a.maxQuota/10.24)/100),this.$quota={percent:b,description:d}},a.prototype.$newMessage=function(){var b=this;return a.$$resource.fetch(this.id.toString(),"compose").then(function(c){return a.$log.debug("New message (compose): "+JSON.stringify(c,void 0,2)),new a.$Message(c.accountId,b.$getMailboxByPath(c.mailboxPath),c)}).then(function(b){return a.$$resource.fetch(b.$absolutePath({asDraft:!0}),"edit").then(function(c){return a.$log.debug("New message (edit): "+JSON.stringify(c,void 0,2)),angular.extend(b.editable,c),b.isNew=!0,b})})},a.prototype.$addDelegate=function(b){var c=this,d=a.$q.defer(),e={uid:b.uid};return!b.uid||_.indexOf(_.map(this.delegates,"uid"),b.uid)>-1?d.resolve():a.$$resource.fetch(this.id.toString(),"addDelegate",e).then(function(){c.delegates.push(b),d.resolve(c.users)},function(a,b){d.reject(l("An error occured please try again."))}),d.promise},a.prototype.$removeDelegate=function(b){var c=this,d={uid:b};return a.$$resource.fetch(this.id.toString(),"removeDelegate",d).then(function(){var a=_.indexOf(_.map(c.delegates,"uid"),b);a>=0&&c.delegates.splice(a,1)})}}(),function(){"use strict";function a(b,c){if(this.$account=b,"function"!=typeof c.then){if(this.init(c),this.name&&!this.path){var d=a.$$resource.create("createFolder",this.name);this.$unwrap(d)}}else this.$unwrap(c)}a.$factory=["$q","$timeout","$log","sgSettings","Resource","Message","Acl","Preferences","sgMailbox_PRELOAD",function(b,c,d,e,f,g,h,i,j){return angular.extend(a,{$q:b,$timeout:c,$log:d,$$resource:new f(e.activeUser("folderURL")+"Mail",e.activeUser()),$Message:g,$$Acl:h,$Preferences:i,$query:{sort:"arrival",asc:0},selectedFolder:null,$refreshTimeout:null,$virtualMode:!1,PRELOAD:j}),i.ready().then(function(){i.settings.Mail.SortingState&&(a.$query.sort=i.settings.Mail.SortingState[0],a.$query.asc=parseInt(i.settings.Mail.SortingState[1]))}),a}];try{angular.module("SOGo.MailerUI")}catch(a){angular.module("SOGo.MailerUI",["SOGo.Common"])}angular.module("SOGo.MailerUI").constant("sgMailbox_PRELOAD",{LOOKAHEAD:50,SIZE:100}).factory("Mailbox",a.$factory),a.$find=function(b,c){var d;return d=c&&c.all?this.$$resource.fetch(b.id.toString(),"viewAll"):this.$$resource.fetch(b.id.toString(),"view"),a.$unwrapCollection(b,d)},a.$unwrapCollection=function(b,c){var d=[],e=function(c,d){for(var f=0;f=0&&a=0},a.prototype.isNoSelect=function(){return this.flags.indexOf("noselect")>=0},a.prototype.$rename=function(){var b,c,d,e,f=this;return this.name==this.$shadowData.name?a.$q.when():(b=function(a,c){var d=null;return _.find(c,function(a){return a.path==f.path})?d=a:angular.forEach(c,function(a){!d&&a.children&&a.children.length>0&&(d=b(a,a.children))}),d},c=b(null,this.$account.$mailboxes),d=null===c?this.$account.$mailboxes:c.children,e=_.indexOf(_.map(d,"id"),this.id),this.$save().then(function(b){var c,g=f.path;f.init(b),d.splice(e,1),c=_.find(d,function(b){return a.$log.debug(b.name+" ? "+f.name),"folder"==b.type&&b.name.localeCompare(f.name)>0}),e=c?_.indexOf(_.map(d,"id"),c.id):d.length,d.splice(e,0,f);var h=new RegExp("^"+g),i=function(a){_.forEach(a.children,function(a){a.path=a.path.replace(h,f.path),a.id=a.$id(),i(a)})};i(f)}))},a.prototype.$compact=function(){var b=this;return a.$$resource.post(this.id,"expunge").then(function(a){a.quotas&&b.$account.updateQuota(a.quotas)})},a.prototype.$setFolderAs=function(b){return a.$$resource.post(this.id,"setAs"+b+"Folder")},a.prototype.$emptyTrash=function(){var b=this;return a.$$resource.post(this.id,"emptyTrash").then(function(a){b.$messages=[],b.uidsMap={},b.unseenCount=0,angular.isDefined(b.children)&&b.children.length&&b.$account.$getMailboxes({reload:!0}),a.quotas&&b.$account.updateQuota(a.quotas)})},a.prototype.$markAsRead=function(){return a.$$resource.post(this.id,"markRead")},a.prototype.$flagMessages=function(b,c,d){var e={msgUIDs:_.map(b,"uid"),flags:c,operation:d};return a.$$resource.post(this.id,"addOrRemoveLabel",e).then(function(){return b})},a.prototype.saveSelectedMessages=function(){var b,c;return b=_.filter(this.$messages,function(a){return a.selected}),c=_.map(b,"uid"),{uids:c},{filename:l("Saved Messages.zip")},a.$$resource.download(this.id,"saveMessages",{uids:c})},a.prototype.exportFolder=function(){var b;return b={filename:this.name+".zip"},a.$$resource.download(this.id,"exportFolder",null,b)},a.prototype.$delete=function(b){var c=this;return a.$$resource.post(this.id,"delete",b).then(function(){return c.$account.$getMailboxes({reload:!0}),!0})},a.prototype.$_deleteMessages=function(a,b){var c,d=this,e=this.$messages.length;return c=_.filter(b,function(a,b){return!a.isread}),this.unseenCount-=c.length,_.forEachRight(this.$messages,function(b,c){var f=_.findIndex(a,function(a){return b.uid==a});f>-1?(a.splice(f,1),delete d.uidsMap[b.uid],b.uid==d.selectedMessage&&delete d.selectedMessage,d.$messages.splice(c,1),cb.uids.length-1)&&(c.$topIndex=0),c.init(b),c.uids&&(a.$log.debug("unwrapping "+c.uids.length+" messages"),f=_.invokeMap(c.headers[0],"toLowerCase"),c.headers.splice(0,1),c.threaded&&(e=c.uids[0],c.uids.splice(0,1)),_.reduce(c.uids,function(b,d,f){var g;return g=c.threaded?_.zipObject(e,d):{uid:d.toString()},c.uidsMap[g.uid]=f,b.push(new a.$Message(c.$account.id,c,g,!0)),b},c.$messages),_.forEach(c.headers,function(a){var b=_.zipObject(f,a),d=c.uidsMap[b.uid.toString()];_.extend(c.$messages[d],b)})),a.$log.debug("mailbox "+c.id+" ready"),c.$isLoading=!1,d.resolve(c.$messages)})},function(a){angular.extend(c,a),c.isError=!0,d.reject()}),d.promise},a.prototype.$unwrapHeaders=function(b){var c=this;b.then(function(b){a.$timeout(function(){var a,d;b.length>0&&(a=_.invokeMap(b[0],"toLowerCase"),b.splice(0,1),_.forEach(b,function(b){b=_.zipObject(a,b),d=c.uidsMap[b.uid.toString()],angular.isDefined(d)&&_.extend(c.$messages[d],b)}))})})},a.prototype.$updateSubscribe=function(){var b=this.subscribed?"subscribe":"unsubscribe";a.$$resource.post(this.id,b)}}(),function(){"use strict";function a(a,b,c,d){this.accountId=a,this.$mailbox=b,this.$hasUnsafeContent=!1,this.$loadUnsafeContent=!1,this.editable={to:[],cc:[],bcc:[]},this.selected=!1,"function"!=typeof c.then?(!angular.isUndefined(d)&&d||(angular.extend(this,c),this.$formatFullAddresses()),this.uid=parseInt(c.uid)):this.$unwrap(c)}a.$factory=["$q","$timeout","$log","sgSettings","sgMessage_STATUS","Resource","Preferences",function(b,c,d,e,f,g,h){return angular.extend(a,{STATUS:f,$q:b,$timeout:c,$log:d,$$resource:new g(e.activeUser("folderURL")+"Mail",e.activeUser()),$avatar:angular.bind(h,h.avatar)}),h.ready().then(function(){h.defaults.SOGoMailLabelsColors&&(a.$tags=h.defaults.SOGoMailLabelsColors),h.defaults.SOGoMailDisplayRemoteInlineImages&&"always"==h.defaults.SOGoMailDisplayRemoteInlineImages&&(a.$displayRemoteInlineImages=!0)}),a}];try{angular.module("SOGo.MailerUI")}catch(a){angular.module("SOGo.MailerUI",["SOGo.Common"])}angular.module("SOGo.MailerUI").constant("sgMessage_STATUS",{NOT_LOADED:0,DELAYED_LOADING:1,LOADING:2,LOADED:3,DELAYED_MS:300}).factory("Message",a.$factory),a.filterTags=function(b,c){var d=new RegExp(b,"i"),e=[];return _.forEach(_.keys(a.$tags),function(b){var f=a.$tags[b];f[0].search(d)!=-1&&(_.includes(c,b)||e.push({name:b,description:f[0],color:f[1]}))}),e},a.prototype.$absolutePath=function(a){function b(){var a;return a=_.map(c.$mailbox.path.split("/"),function(a){return"folder"+a.asCSSIdentifier()}),a.splice(0,0,c.accountId),a.join("/")}var c=this,d=this.id;return(angular.isUndefined(this.id)||a&&a.nocache)&&(this.id=b()+"/"+this.uid,d=this.id),a&&a.asDraft&&this.draftId&&(d=b()+"/"+this.draftId),d},a.prototype.$setUID=function(a){var b,c=this.uid||-1,d=this;c!=parseInt(a)&&(this.uid=parseInt(a),this.$absolutePath({nocache:!0}),c>-1?(c=c.toString(),angular.isDefined(this.$mailbox.uidsMap[c])&&(b=this.$mailbox.uidsMap[c],this.$mailbox.uidsMap[a]=b,delete this.$mailbox.uidsMap[c],_.forEach(["from","to","subject"],function(a){d.$mailbox.$messages[b][a]=d[a]}))):this.$mailbox.constructor.selectedFolder&&"draft"==this.$mailbox.constructor.selectedFolder.type&&this.$mailbox.constructor.selectedFolder.$filter())},a.prototype.$formatFullAddresses=function(){var b=this,c=_.map(b.$mailbox.$account.identities,"email");_.forEach(["from","to","cc","bcc","reply-to"],function(d){_.forEach(b[d],function(b){b.name&&b.name!=b.email?(b.full=b.name+" <"+b.email+">",b.name.length<10?b.shortname=b.name:b.name.split(" ").length&&(b.shortname=_.first(_.last(b.name.split(/, */)).split(/ +/)).replace("'",""))):b.email&&(b.full="<"+b.email+">",b.shortname=b.email.split("@")[0]),b.image=a.$avatar(b.email,32),_.indexOf(c,b.email)>=0&&(b.shortname=l("me"))})})},a.prototype.$shortRecipients=function(a){var b=this,c=[],d=0,e=0;return _.forEach(["to","cc","bcc"],function(f){e+=b[f]?b[f].length:0,_.forEach(b[f],function(b,e){da&&c.push(l("and %{0} more...",e-a)),c.join(", ")},a.prototype.$shortAddress=function(a){var b="";return this[a]&&this[a].length>0&&(b=this[a][0].name||this[a][0].email||""),b},a.prototype.allowReplyAll=function(){var a=0;return a=_.reduce(["to","cc"],_.bind(function(a,b){return this[b]?a+this[b].length:a},this),a),!this.isDraft&&a>1},a.prototype.loadUnsafeContent=function(){this.$loadUnsafeContent=!0},a.prototype.$content=function(){var b=this,c=[],d=function(e){if(e.msgclass="msg-attachment-other","UIxMailPartAlternativeViewer"==e.type)d(_.find(e.content,function(a){return e.preferredPart==a.contentType}));else if(angular.isArray(e.content)){if("UIxMailPartSignedViewer"==e.type&&1===e["supports-smime"]){var f="

"+e.error.replace(/\n/,'

');f=f.replace(/\n/g,'

')+"

",b.$smime={validSignature:e.valid,message:f}}_.forEach(e.content,function(a){d(a)})}else angular.isUndefined(e.safeContent)&&(e.safeContent=e.content,b.$hasUnsafeContent|=e.safeContent.indexOf(" unsafe-")>-1),"UIxMailPartHTMLViewer"==e.type?(e.html=!0,b.$loadUnsafeContent||a.$displayRemoteInlineImages?(angular.isUndefined(e.unsafeContent)&&(e.unsafeContent=document.createElement("div"),e.unsafeContent.innerHTML=e.safeContent,angular.forEach(["src","data","classid","background","style"],function(a){var b,c,d,f=e.unsafeContent.querySelectorAll("[unsafe-"+a+"]");for(d=0;d=0)for(b=0,c=0;c0){var d=_.map(b,"uid");f.push(b);var h=a.$$resource.post(c,"addOrRemoveLabel",_.assign(e,{msgUIDs:d}));g.push(h)}}),a.$q.all(g).then(function(){return _.flatten(f)})},a.prototype.$deleteMessages=function(b){var c=[];return _.forEach(b,function(a,b){if(a.length>0){var d=a[0].$mailbox,e=d.$deleteMessages(a);c.push(e)}}),a.$q.all(c)},a.prototype.$markOrUnMarkMessagesAsJunk=function(b){var c=[];return _.forEach(b,function(a,b){if(a.length>0){var d=a[0].$mailbox,e=d.$markOrUnMarkMessagesAsJunk(a);c.push(e)}}),a.$q.all(c)},a.prototype.$copyMessages=function(b,c){var d=[];return _.forEach(b,function(a,b){if(a.length>0){var e=a[0].$mailbox,f=e.$copyMessages(a,c);d.push(f)}}),a.$q.all(d)},a.prototype.$moveMessages=function(b,c){var d=[];return _.forEach(b,function(a,b){if(a.length>0){var e=a[0].$mailbox,f=e.$moveMessages(a,c);d.push(f)}}),a.$q.all(d)}}(),function(){"use strict";function a(a,b,c,d,e,f,g,h,i,j,k,m,n,o,p,q,r){function s(a){a.push(k.createHotkey({key:l("hotkey_search"),description:l("Search"),callback:w})),a.push(k.createHotkey({key:l("hotkey_compose"),description:l("Write a new message"),callback:function(a){null===R.messageDialog&&y(a)}})),a.push(k.createHotkey({key:l("hotkey_junk"),description:l("Mark the selected messages as junk"),callback:J})),a.push(k.createHotkey({key:"space",description:l("Toggle item"),callback:F})),a.push(k.createHotkey({key:"shift+space",description:l("Toggle range of items"),callback:F})),a.push(k.createHotkey({key:"up",description:l("View next item"),callback:A,preventInClass:["sg-mail-part"]})),a.push(k.createHotkey({key:"down",description:l("View previous item"),callback:B,preventInClass:["sg-mail-part"]})),a.push(k.createHotkey({key:"shift+up",description:l("Add next item to selection"),callback:C,preventInClass:["sg-mail-part"]})),a.push(k.createHotkey({key:"shift+down",description:l("Add previous item to selection"),callback:D,preventInClass:["sg-mail-part"]})),a.push(k.createHotkey({key:"backspace",description:l("Delete selected message or folder"),callback:I})),_.forEach(a,function(a){k.registerHotkey(a)})}function t(a){return R.selectedFolder.$compact()}function u(a){R.selectedFolder.$filter({sort:a})}function v(a){return r.$query.sort==a}function w(){R.mode.search=!0,o("search")}function x(){R.mode.search=!1,R.selectedFolder.$filter().then(function(){R.selectedFolder.selectedMessage&&c(function(){R.selectedFolder.$topIndex=R.selectedFolder.uidsMap[R.selectedFolder.selectedMessage]})})}function y(a,b){var c;null===R.messageDialog&&(b?z():(c=R.account.$newMessage(),R.messageDialog=f.show({parent:angular.element(document.body),targetEvent:a,clickOutsideToClose:!1,escapeToClose:!1,templateUrl:"UIxMailEditor",controller:"MessageEditorController",controllerAs:"editor",locals:{stateAccount:R.account,stateMessage:c}}).finally(function(){R.messageDialog=null})))}function z(){var b=[n.baseURL(),"UIxMailPopupView#!/Mail",R.account.id,m(m(R.selectedFolder.path)),"new"].join("/"),c=R.selectedFolder.$id()+"/"+Math.random(0,1e3);console.debug(b),a.open(b,c,["width=680","height=520","resizable=1","scrollbars=1","toolbar=0","location=0","directories=0","status=0","menubar=0","copyhistory=0"].join(","))}function A(a){var b=R.selectedFolder.$selectedMessageIndex();return angular.isDefined(b)?(b--,R.selectedFolder.$topIndex>0&&R.selectedFolder.$topIndex--):(b=R.selectedFolder.getLength()-1,R.selectedFolder.$topIndex=R.selectedFolder.getLength()),b>-1&&E(R.selectedFolder.$messages[b]),a.preventDefault(),b}function B(a){var b=R.selectedFolder.$selectedMessageIndex();return angular.isDefined(b)?(b++,R.selectedFolder.$topIndex=0&&F(a,R.selectedFolder.$messages[b]))}function D(a){var b;R.selectedFolder.hasSelectedMessage()&&(b=B(a),b>=0&&F(a,R.selectedFolder.$messages[b]))}function E(a){r.$virtualMode?e.go("mail.account.virtualMailbox.message",{mailboxId:m(a.$mailbox.path),messageId:a.uid}):e.go("mail.account.mailbox.message",{messageId:a.uid})}function F(a,b){var c,d,e,f=R.selectedFolder;if(b||(b=f.$selectedMessage()),b.selected=!b.selected,R.mode.multiple+=b.selected?1:-1,a.shiftKey&&f.$selectedCount()>1){for(c=f.uidsMap[b.uid],d=c-2;d>=0&&!f.$messages[d].selected;)d--;if(d<0)for(d=c+2;d=0&&d0&&(g-=1,d=R.selectedFolder.$messages[g]),b0&&(R.messageDialog=p.confirm(l("Confirmation"),l("Are you sure you want to delete the selected messages?"),{ok:l("Delete")}).then(function(){var a=R.selectedFolder.hasSelectedMessage();R.selectedFolder.$deleteMessages(b).then(function(b){r.$virtualMode?a&&e.go("mail.account.virtualMailbox"):H(a,b)},function(c){R.messageDialog=p.confirm(l("Warning"),l("The messages could not be moved to the trash folder. Would you like to delete them immediately?"),{ok:l("Delete")}).then(function(){R.selectedFolder.$deleteMessages(b,{withoutTrash:!0}).then(function(b){r.$virtualMode?a&&e.go("mail.account.virtualMailbox"):H(a,b)})})})}).finally(function(){R.messageDialog=null})),a.preventDefault()}function J(){var a=R.selectedFolder.hasSelectedMessage(),b=R.selectedFolder.$selectedMessages();0===_.size(b)&&a&&(b=[R.selectedFolder.$selectedMessage()]),_.size(b)>0&&R.selectedFolder.$markOrUnMarkMessagesAsJunk(b).then(function(){var c="/"+R.account.id+"/folderINBOX";"junk"!=R.selectedFolder.type&&(c="/"+R.account.$getMailboxByType("junk").id),R.selectedFolder.$moveMessages(b,c).then(function(b){r.$virtualMode?a&&e.go("mail.account.virtualMailbox"):H(a,b)})})}function K(a){var b=R.selectedFolder.$selectedMessages();_.size(b)>0&&R.selectedFolder.$copyMessages(b,"/"+a).then(function(){g.show(g.simple().content(l("%{0} message(s) copied",R.selectedFolder.$selectedCount())).position("top right").hideDelay(2e3))})}function L(a){var b=R.selectedFolder.hasSelectedMessage(),c=R.selectedFolder.$selectedMessages(),d=R.selectedFolder.$selectedCount();_.size(c)>0&&R.selectedFolder.$moveMessages(c,"/"+a).then(function(a){g.show(g.simple().content(l("%{0} message(s) moved",d)).position("top right").hideDelay(2e3)),r.$virtualMode?b&&e.go("mail.account.virtualMailbox"):H(b,a)})}function M(){var a=0;_.forEach(G(),function(b){for(var c=0,d=b.$messages.length;c0&&R.selectedFolder.$flagMessages(a,"\\Flagged","add").then(function(a){_.forEach(a,function(a){a.isflagged=!0})})}function P(){var a=R.selectedFolder.$selectedMessages();_.size(a)>0&&R.selectedFolder.$flagMessages(a,"seen","remove").then(function(a){_.forEach(a,function(a){a.isread&&a.$mailbox.unseenCount++,a.isread=!1})})}function Q(){var a=R.selectedFolder.$selectedMessages();_.size(a)>0&&R.selectedFolder.$flagMessages(a,"seen","add").then(function(a){_.forEach(a,function(a){a.isread||a.$mailbox.unseenCount--,a.isread=!0})})}var R=this,S=angular.element(a.document).find("title").attr("sg-default")||"SOGo",T=[];a.$mailboxController=R,R.service=r,R.accounts=h,R.account=i,R.selectedFolder=j,R.selectMessage=E,R.messageDialog=null,R.toggleMessageSelection=F,R.sort=u,R.sortedBy=v,R.searchMode=w,R.cancelSearch=x,R.newMessage=y,R.mode={search:!1,multiple:0},R.confirmDeleteSelectedMessages=I,R.markOrUnMarkMessagesAsJunk=J,R.copySelectedMessages=K,R.moveSelectedMessages=L,R.markSelectedMessagesAsFlagged=O,R.markSelectedMessagesAsUnread=P,R.markSelectedMessagesAsRead=Q,R.selectAll=M,R.unselectMessages=N,j.selectFolder(),s(T),angular.element(a).on("beforeunload",t),b.$on("$destroy",function(){angular.element(a).off("beforeunload",t),_.forEach(T,function(a){k.deregisterHotkey(a)})}),b.$watch(function(){return R.selectedFolder.unseenCount},function(b){var c=S+" - ";b&&(c+="("+b+") "),c+=R.selectedFolder.$displayName,a.document.title=c})}function b(a){return a[0].controller.prototype.resetScroll=function(){"messagesList"==this.$element.parent().attr("id")?this.updateSize():this.scrollTo(0)},a}a.$inject=["$window","$scope","$timeout","$q","$state","$mdDialog","$mdToast","stateAccounts","stateAccount","stateMailbox","sgHotkeys","encodeUriFilter","sgSettings","sgFocus","Dialog","Account","Mailbox"],angular.module("material.components.virtualRepeat").decorator("mdVirtualRepeatContainerDirective",b),b.$inject=["$delegate"],angular.module("SOGo.MailerUI").controller("MailboxController",a)}(),function(){"use strict";function a(a,b,c,d,e,f,g,h,i,j,k,m,n,o,p,q,r,s,t,u){function v(a){a.push(o.createHotkey({key:"backspace",description:l("Delete selected message or folder"),callback:function(){q.selectedFolder&&!q.selectedFolder.hasSelectedMessage()&&L(q.selectedFolder)}})),_.forEach(a,function(a){o.registerHotkey(a)})}function w(a){U.showingAdvancedSearch=!0,U.search.mailbox=a,g(i["gt-md"])||h("left").close()}function x(){U.showingAdvancedSearch=!1,U.service.$virtualMode=!1,S=U.accounts[0],T=U.searchPreviousMailbox,b.go("mail.account.mailbox",{accountId:S.id,mailboxId:k(T.path)})}function y(){if(q.selectedFolder.$isLoading)U.virtualMailbox.stopSearch();else{var a,c=[],d=function(a){_.forEach(a,function(a){c.push(a),a.children&&a.children.length>0&&d(a.children)})};U.virtualMailbox=new r(U.accounts[0]),q.$virtualMode||(U.searchPreviousMailbox=q.selectedFolder),q.selectedFolder=U.virtualMailbox,q.$virtualMode=!0,angular.isDefined(U.search.mailbox)?(a=U.accounts[0].$getMailboxByPath(U.search.mailbox),c.push(a),U.search.subfolders&&a.children.length&&d(a.children)):c=U.accounts[0].$flattenMailboxes(),U.virtualMailbox.setMailboxes(c),U.virtualMailbox.startSearch(U.search.match,U.search.params),b.go("mail.account.virtualMailbox",{accountId:U.accounts[0].id})}}function z(a){return U.currentSearchParam=a,j("advancedSearch"),!1}function A(a){if(a.length&&U.currentSearchParam.length){var b=0,c=U.currentSearchParam;return a.startsWith("!")&&(b=1,a=a.substring(1).trim()),U.currentSearchParam="",{searchBy:c,searchInput:a,negative:b}}}function B(a){a.$expanded=!a.$expanded,a.$flattenMailboxes({reload:!0,saveState:!0}),c(function(){angular.element(d).triggerHandler("resize")},150)}function C(a){function b(a,b,c){function d(){b.cancel()}var e=this;e.loading=!0,e.filter={name:""},e.account=new p({id:c.id,name:c.name}),e.close=d,e.account.$getMailboxes({reload:!0,all:!0}).then(function(){e.loading=!1})}e.show({templateUrl:a.id+"/subscribe",controller:b,controllerAs:"subscriptions",clickOutsideToClose:!0,escapeToClose:!0,locals:{srcAccount:a}}).finally(function(){a.$getMailboxes({reload:!0})}),b.$inject=["$scope","$mdDialog","srcAccount"]}function D(a){m.prompt(l("New Folder..."),l("Enter the new name of your folder")).then(function(b){a.$newMailbox(a.id,b).then(function(){},function(a,c){m.alert(l('An error occured while creating the mailbox "%{0}".',b),l(a.error))})})}function E(a){function b(a,b,c,d){function e(a){return c.$filter(a,d.delegates)}function f(){b.hide()}function g(a){d.$removeDelegate(a.uid).catch(function(a,b){m.alert(l("Warning"),l("An error occured please try again."))})}function h(a){a&&d.$addDelegate(a).then(function(){i.userToAdd="",i.searchText=""},function(a){m.alert(l("Warning"),a)})}var i=this;i.users=d.delegates,i.account=d,i.userToAdd="",i.searchText="",i.userFilter=e,i.closeModal=f,i.removeUser=g,i.addUser=h}e.show({templateUrl:a.id+"/delegation",controller:b,controllerAs:"delegate",clickOutsideToClose:!0,escapeToClose:!0,locals:{User:s,account:a}}),b.$inject=["$scope","$mdDialog","User","account"]}function F(a){U.editMode=a.path,j("mailboxName_"+a.path)}function G(a){a.$reset(),U.editMode=!1}function H(a,c,d){U.editMode!=d.path&&(U.editMode=!1,U.showingAdvancedSearch=!1,U.service.$virtualMode=!1,g(i["gt-md"])||h("left").close(),b.go("mail.account.mailbox",{accountId:c.id,mailboxId:k(d.path)}),a.stopPropagation(),a.preventDefault())}function I(a){a.$rename().then(function(a){U.editMode=!1})}function J(a){a.$compact().then(function(){f.show(f.simple().content(l("Folder compacted")).position("top right").hideDelay(3e3))})}function K(a){a.$emptyTrash().then(function(){f.show(f.simple().content(l("Trash emptied")).position("top right").hideDelay(3e3))})}function L(a){m.confirm(l("Warning"),l("Do you really want to move this folder into the trash ?"),{ok:l("Delete")}).then(function(){a.$delete().then(function(){b.go("mail.account.inbox")},function(c){m.confirm(l("Warning"),l("The mailbox could not be moved to the trash folder. Would you like to delete it immediately?"),{ok:l("Delete")}).then(function(){a.$delete({withoutTrash:!0}).then(function(){b.go("mail.account.inbox")},function(b){m.alert(l('An error occured while deleting the mailbox "%{0}".',a.name),l(b.error))})})})})}function M(a){a.$markAsRead()}function N(a){a.$acl.$users().then(function(){e.show({templateUrl:a.id+"/UIxAclEditor",controller:"AclController",controllerAs:"acl",clickOutsideToClose:!0,escapeToClose:!0,locals:{usersWithACL:a.$acl.users,User:s,folder:a}})})}function O(a,b){a.$setFolderAs(b).then(function(){a.$account.$getMailboxes({reload:!0})})}function P(){var a=d.unseenCountFolders;_.forEach(U.accounts,function(b){_.includes(a,b.id+"/folderINBOX")||a.push(b.id+"/folderINBOX"),_.forEach(b.$$flattenMailboxes,function(b){angular.isDefined(b.unseenCount)&&!_.includes(a,b.id)&&a.push(b.id)})}),p.$$resource.post("","unseenCount",{mailboxes:a}).then(function(a){_.forEach(U.accounts,function(b){_.forEach(b.$$flattenMailboxes,function(b){a[b.id]&&(b.unseenCount=a[b.id])})})}),t.ready().then(function(){var a=t.defaults.SOGoRefreshViewCheck;a&&"manually"!=a&&c(U.refreshUnseenCount,1e3*a.timeInterval())})}function Q(a,b){return b.id!=a.id&&!b.isNoSelect()}function R(a,c,d){var e,g,h,i,j,k;e="/"+c.id,g=a.$selectedMessages(),0===g.length&&(g=[a.$selectedMessage()]),h=_.map(g,"uid"),i=a.selectedMessage&&h.indexOf(a.selectedMessage)>=0,"copy"==d?(j=a.$copyMessages(g,e),k=l("%{0} message(s) copied",g.length)):(j=a.$moveMessages(g,e),k=l("%{0} message(s) moved",g.length)),j.then(function(){i&&b.go("mail.account.mailbox"),f.show(f.simple().content(k).position("top right").hideDelay(2e3))})}var S,T,U=this,V=[];U.service=q,U.accounts=u,U.toggleAccountState=B,U.subscribe=C,U.newFolder=D,U.delegate=E,U.editFolder=F,U.revertEditing=G,U.selectFolder=H,U.saveFolder=I,U.compactFolder=J,U.emptyTrashFolder=K,U.confirmDelete=L,U.markFolderRead=M,U.share=N,U.setFolderAs=O,U.refreshUnseenCount=P,U.isDroppableFolder=Q,U.dragSelectedMessages=R,U.showingAdvancedSearch=!1,U.currentSearchParam="",U.addSearchParam=z,U.newSearchParam=A,U.showAdvancedSearch=w,U.hideAdvancedSearch=x,U.toggleAdvancedSearch=y,U.search={options:{"":"",subject:l("Enter Subject"),from:l("Enter From"),to:l("Enter To"),cc:l("Enter Cc"),body:l("Enter Body")},mailbox:"INBOX",subfolders:1,match:"AND",params:[]},t.ready().then(function(){U.showSubscribedOnly=t.defaults.SOGoMailShowSubscribedFoldersOnly}),U.refreshUnseenCount(),v(V),a.$on("$destroy",function(){_.forEach(V,function(a){o.deregisterHotkey(a)})})}a.$inject=["$scope","$state","$timeout","$window","$mdDialog","$mdToast","$mdMedia","$mdSidenav","sgConstant","sgFocus","encodeUriFilter","Dialog","sgSettings","sgHotkeys","Account","Mailbox","VirtualMailbox","User","Preferences","stateAccounts"],angular.module("SOGo.MailerUI").controller("MailboxesController",a)}(),function(){"use strict";function a(a,b,c,d,e,f,g,h,i,j,k,m,n,o,p,q,r,s,t,u){function v(){return b.mailbox?(arguments.length>0&&(b.mailbox.messageDialog=arguments[0]),b.mailbox.messageDialog):null}function w(a){return function(){if(null===v())return a.apply(Q,arguments)}}function x(a){a.push(k.createHotkey({key:l("hotkey_reply"),description:l("Reply to the message"),callback:w(E)})),a.push(k.createHotkey({key:l("hotkey_replyall"),description:l("Reply to sender and all recipients"),callback:w(F)})),a.push(k.createHotkey({key:l("hotkey_forward"),description:l("Forward selected message"),callback:w(G)})),a.push(k.createHotkey({key:l("hotkey_flag"),description:l("Flagged"),callback:w(angular.bind(j,j.toggleFlag))})),a.push(k.createHotkey({key:"backspace",callback:w(function(a){0===Q.mailbox.$selectedCount()&&B(),a.preventDefault()})})),_.forEach(a,function(a){k.registerHotkey(a)})}function y(){var b,c,d={};return a.opener&&a.opener.$mailboxController&&a.opener.$mailboxController.selectedFolder.$id()==i.$id()&&(c=a.opener.$mailboxController,d.mailboxCtrl=c,a.opener.$messageController&&a.opener.$messageController.message.uid==j.uid&&(b=a.opener.$messageController,d.messageCtrl=b)),d}function z(a){Q.$showDetailedRecipients=!Q.$showDetailedRecipients,a.stopPropagation(),a.preventDefault()}function A(a){var b,c,d,e;"A"==a.target.tagName&&"href"in a.target.attributes&&(b=a.target.attributes.href.value,c=/^mailto:([^\?]+)/.exec(b),c&&(d=_.map(decodeURIComponent(c[1]).split(","),function(a){return"<"+a+">"}),e={to:d},_.forEach(["subject","body"],function(a){var d=new RegExp(a+"=([^&]+)");a="body"==a?"text":a,c=d.exec(b),c&&(e[a]=[decodeURIComponent(c[1])])}),_.forEach(["cc","bcc"],function(a){c=new RegExp(a+"=([^&]+)").exec(b),c&&(e[a]=[decodeURIComponent(c[1])])}),K(a,e)))}function B(){var a,b,e,g,h,k=y();k.messageCtrl?(a=k.mailboxCtrl.selectedFolder,b=k.messageCtrl.message,e=k.messageCtrl.$state):(a=i,b=j,e=c),a.$deleteMessages([b]).then(function(c){var i=c;if(b=null,angular.isDefined(e)){c>0&&(i-=1,g=a.$messages[i]),ca.$lastVisibleIndex&&(a.$topIndex=i-(a.$lastVisibleIndex-a.$topIndex))):e.go("mail.account.mailbox").then(function(){b=null,delete a.selectedMessage})}catch(a){}}J()})}function C(a,b){null===v()&&v(e.show({parent:angular.element(document.body),targetEvent:a,clickOutsideToClose:!1,escapeToClose:!1,templateUrl:"UIxMailEditor",controller:"MessageEditorController",controllerAs:"editor",locals:{stateAccount:Q.account,stateMessage:b}}).finally(function(){v(null),J()}))}function D(){c.go("mail.account.mailbox").then(function(){Q.message=null,delete i.selectedMessage})}function E(a){C(a,Q.message.$reply())}function F(a){C(a,Q.message.$replyAll())}function G(a){C(a,Q.message.$forward())}function H(a){Q.message.$editableContent().then(function(){C(a,Q.message)})}function I(){var b=[n.baseURL(),"UIxMailPopupView#!/Mail",Q.message.accountId,m(m(Q.message.$mailbox.path)),Q.message.uid].join("/"),c=Q.message.$absolutePath();R=a.open(b,c,["width=680","height=520","resizable=1","scrollbars=1","toolbar=0","location=0","directories=0","status=0","menubar=0","copyhistory=0"].join(","))}function J(){a.opener&&a.close()}function K(a,b){Q.account.$newMessage().then(function(c){angular.extend(c.editable,b),C(a,c)}),a.stopPropagation(),a.preventDefault()}function L(a){Q.showRawSource||Q.message.$rawSource?Q.showRawSource=!Q.showRawSource:u.$$resource.post(Q.message.id,"viewsource").then(function(a){Q.message.$rawSource=a,Q.showRawSource=!0})}function M(b){a.print()}function N(a){return P(a,"appointment")}function O(a){return P(a,"task")}function P(a,b){Q.message.$plainContent().then(function(c){var d={pid:q.$defaultCalendar(),type:b,summary:c.subject,comment:c.content},f=new r(d),g=[n.activeUser("folderURL"),"Calendar","UIx"+b.capitalize()+"EditorTemplate"].join("/");return e.show({parent:angular.element(document.body),targetEvent:a,clickOutsideToClose:!0,escapeToClose:!0,templateUrl:g,controller:"ComponentEditorController",controllerAs:"editor",locals:{stateComponent:f}})})}var Q=this,R=null,S=[];a.$messageController=Q,Q.$state=c,Q.accounts=g,Q.account=h,Q.mailbox=i,Q.message=j,Q.service=u,Q.tags={searchText:"",selected:""},Q.showFlags=j.flags&&j.flags.length>0,Q.$showDetailedRecipients=!1,Q.toggleDetailedRecipients=z,Q.filterMailtoLinks=A,Q.deleteMessage=B,Q.close=D,Q.reply=E,Q.replyAll=F,Q.forward=G,Q.edit=H,Q.openPopup=I,Q.closePopup=J,Q.newMessage=K,Q.toggleRawSource=L,Q.showRawSource=!1,Q.print=M,Q.convertToEvent=N,Q.convertToTask=O,x(S),a.opener?(b.$watchCollection(function(){return Q.message.flags},function(a,b){var c;(a||b)&&(c=y(),c.messageCtrl&&c.messageCtrl.service.$timeout(function(){c.messageCtrl.showFlags=!0,c.messageCtrl.message.flags=a}))}),b.$watch(function(){return Q.message.isflagged},function(a,b){var c=y();c.mailboxCtrl&&c.mailboxCtrl.service.$timeout(function(){_.find(c.mailboxCtrl.selectedFolder.$messages,{uid:Q.message.uid}).isflagged=a})})):b.$watchCollection(function(){return Q.message.flags},function(a,b){var c,d,e;(a||b)&&(c=a||[],d=b||[],_.forEach(c,function(a,b){angular.isObject(a)&&(c[b]=a.name)}),c.length>d.length?(e=_.difference(c,d),_.forEach(e,function(a){Q.message.addTag(a)})):c.length":a.full="<"+a.email+">"}),a.$log.debug("Account: "+JSON.stringify(b,void 0,2)))}a.$factory=["$q","$timeout","$log","sgSettings","Resource","Preferences","Mailbox","Message",function(b,c,d,e,f,g,h,i){return angular.extend(a,{$q:b,$timeout:c,$log:d,$$resource:new f(e.activeUser("folderURL")+"Mail",e.activeUser()),$Preferences:g,$Mailbox:h,$Message:i}),a}];try{angular.module("SOGo.MailerUI")}catch(a){angular.module("SOGo.MailerUI",["SOGo.Common"])}angular.module("SOGo.MailerUI").factory("Account",a.$factory),a.$findAll=function(b){return b?a.$unwrapCollection(b):a.$$resource.fetch("","mailAccounts").then(function(b){return a.$unwrapCollection(b)})},a.$unwrapCollection=function(b){var c=[];return angular.forEach(b,function(b,d){b.id=d,c[d]=new a(b)}),a.$accounts=c,c},a.prototype.getLength=function(){return this.$flattenMailboxes().length},a.prototype.getItemAtIndex=function(a){var b;return b=this.$flattenMailboxes(),a>=0&&a=0,a.children&&a.children.length>0&&d(a.children)})};a.$Preferences.settings.Mail.ExpandedFolders&&(b=angular.isString(a.$Preferences.settings.Mail.ExpandedFolders)?angular.fromJson(a.$Preferences.settings.Mail.ExpandedFolders):a.$Preferences.settings.Mail.ExpandedFolders,c.$expanded=b.indexOf("/"+c.id)>=0,b.length>0&&d(c.$mailboxes)),a.$accounts&&(c.$expanded|=1==a.$accounts.length),c.$flattenMailboxes({reload:!0})}),c.$mailboxes}):a.$q.when(this.$mailboxes)},a.prototype.$flattenMailboxes=function(b){var c=this,d=[],e=[],f=function(a){_.forEach(a,function(a){d.push(a),(b&&b.all||a.$expanded)&&a.children&&a.children.length>0&&f(a.children)})};return!this.$$flattenMailboxes||b&&(b.reload||b.all)?(f(this.$mailboxes),b&&b.all||(c.$$flattenMailboxes=d,b&&b.saveState&&(_.forEach(a.$accounts,function(a){a.$expanded&&e.push("/"+a.id),_.reduce(a.$$flattenMailboxes,function(a,b){return b.$expanded&&a.push("/"+b.id),a},e)}),a.$$resource.post(null,"saveFoldersState",e)))):d=this.$$flattenMailboxes,d},a.prototype.$getMailboxByType=function(a){var b=function(c){var d=_.find(c,function(b){return b.type==a});return d||angular.forEach(c,function(a){!d&&a.children&&a.children.length>0&&(d=b(a.children))}),d};return b(this.$mailboxes)},a.prototype.$getMailboxByPath=function(a){var b=function(c){var d=_.find(c,function(b){return b.path==a});return d||angular.forEach(c,function(a){!d&&a.children&&a.children.length>0&&(d=b(a.children))}),d};return b(this.$mailboxes)},a.prototype.$newMailbox=function(b,c){var d=this;return a.$$resource.post(b.toString(),"createFolder",{name:c}).then(function(){d.$getMailboxes({reload:!0})})},a.prototype.updateQuota=function(a){var b,c,d;b=Math.round(1e4*a.usedSpace/a.maxQuota)/100,c=l("quotasFormat"),d=c.formatted(b,Math.round(a.maxQuota/10.24)/100),this.$quota={percent:b,description:d}},a.prototype.$newMessage=function(){var b=this;return a.$$resource.fetch(this.id.toString(),"compose").then(function(c){return a.$log.debug("New message (compose): "+JSON.stringify(c,void 0,2)),new a.$Message(c.accountId,b.$getMailboxByPath(c.mailboxPath),c)}).then(function(b){return a.$$resource.fetch(b.$absolutePath({asDraft:!0}),"edit").then(function(c){return a.$log.debug("New message (edit): "+JSON.stringify(c,void 0,2)),angular.extend(b.editable,c),b.isNew=!0,b})})},a.prototype.$addDelegate=function(b){var c=this,d=a.$q.defer(),e={uid:b.uid};return!b.uid||_.indexOf(_.map(this.delegates,"uid"),b.uid)>-1?d.resolve():a.$$resource.fetch(this.id.toString(),"addDelegate",e).then(function(){c.delegates.push(b),d.resolve(c.users)},function(a,b){d.reject(l("An error occured please try again."))}),d.promise},a.prototype.$removeDelegate=function(b){var c=this,d={uid:b};return a.$$resource.fetch(this.id.toString(),"removeDelegate",d).then(function(){var a=_.indexOf(_.map(c.delegates,"uid"),b);a>=0&&c.delegates.splice(a,1)})}}(),function(){"use strict";function a(b,c){if(this.$account=b,"function"!=typeof c.then){if(this.init(c),this.name&&!this.path){var d=a.$$resource.create("createFolder",this.name);this.$unwrap(d)}}else this.$unwrap(c)}a.$factory=["$q","$timeout","$log","sgSettings","Resource","Message","Acl","Preferences","sgMailbox_PRELOAD",function(b,c,d,e,f,g,h,i,j){return angular.extend(a,{$q:b,$timeout:c,$log:d,$$resource:new f(e.activeUser("folderURL")+"Mail",e.activeUser()),$Message:g,$$Acl:h,$Preferences:i,$query:{sort:"arrival",asc:0},selectedFolder:null,$refreshTimeout:null,$virtualMode:!1,PRELOAD:j}),i.ready().then(function(){i.settings.Mail.SortingState&&(a.$query.sort=i.settings.Mail.SortingState[0],a.$query.asc=parseInt(i.settings.Mail.SortingState[1]))}),a}];try{angular.module("SOGo.MailerUI")}catch(a){angular.module("SOGo.MailerUI",["SOGo.Common"])}angular.module("SOGo.MailerUI").constant("sgMailbox_PRELOAD",{LOOKAHEAD:50,SIZE:100}).factory("Mailbox",a.$factory),a.$find=function(b,c){var d;return d=c&&c.all?this.$$resource.fetch(b.id.toString(),"viewAll"):this.$$resource.fetch(b.id.toString(),"view"),a.$unwrapCollection(b,d)},a.$unwrapCollection=function(b,c){var d=[],e=function(c,d){for(var f=0;f=0&&a=0},a.prototype.isNoSelect=function(){return this.flags.indexOf("noselect")>=0},a.prototype.$rename=function(){var b,c,d,e,f=this;return this.name==this.$shadowData.name?a.$q.when():(b=function(a,c){var d=null;return _.find(c,function(a){return a.path==f.path})?d=a:angular.forEach(c,function(a){!d&&a.children&&a.children.length>0&&(d=b(a,a.children))}),d},c=b(null,this.$account.$mailboxes),d=null===c?this.$account.$mailboxes:c.children,e=_.indexOf(_.map(d,"id"),this.id),this.$save().then(function(b){var c,g=f.path;f.init(b),d.splice(e,1),c=_.find(d,function(b){return a.$log.debug(b.name+" ? "+f.name),"folder"==b.type&&b.name.localeCompare(f.name)>0}),e=c?_.indexOf(_.map(d,"id"),c.id):d.length,d.splice(e,0,f);var h=new RegExp("^"+g),i=function(a){_.forEach(a.children,function(a){a.path=a.path.replace(h,f.path),a.id=a.$id(),i(a)})};i(f)}))},a.prototype.$compact=function(){var b=this;return a.$$resource.post(this.id,"expunge").then(function(a){a.quotas&&b.$account.updateQuota(a.quotas)})},a.prototype.$setFolderAs=function(b){return a.$$resource.post(this.id,"setAs"+b+"Folder")},a.prototype.$emptyTrash=function(){var b=this;return a.$$resource.post(this.id,"emptyTrash").then(function(a){b.$messages=[],b.uidsMap={},b.unseenCount=0,angular.isDefined(b.children)&&b.children.length&&b.$account.$getMailboxes({reload:!0}),a.quotas&&b.$account.updateQuota(a.quotas)})},a.prototype.$markAsRead=function(){return a.$$resource.post(this.id,"markRead")},a.prototype.$flagMessages=function(b,c,d){var e={msgUIDs:_.map(b,"uid"),flags:c,operation:d};return a.$$resource.post(this.id,"addOrRemoveLabel",e).then(function(){return b})},a.prototype.saveSelectedMessages=function(){var b,c;return b=_.filter(this.$messages,function(a){return a.selected}),c=_.map(b,"uid"),{uids:c},{filename:l("Saved Messages.zip")},a.$$resource.download(this.id,"saveMessages",{uids:c})},a.prototype.exportFolder=function(){var b;return b={filename:this.name+".zip"},a.$$resource.download(this.id,"exportFolder",null,b)},a.prototype.$delete=function(b){var c=this;return a.$$resource.post(this.id,"delete",b).then(function(){return c.$account.$getMailboxes({reload:!0}),!0})},a.prototype.$_deleteMessages=function(a,b){var c,d=this,e=this.$messages.length;return c=_.filter(b,function(a,b){return!a.isread}),this.unseenCount-=c.length,_.forEachRight(this.$messages,function(b,c){var f=_.findIndex(a,function(a){return b.uid==a});f>-1?(a.splice(f,1),delete d.uidsMap[b.uid],b.uid==d.selectedMessage&&delete d.selectedMessage,d.$messages.splice(c,1),cb.uids.length-1)&&(c.$topIndex=0),c.init(b),c.uids&&(a.$log.debug("unwrapping "+c.uids.length+" messages"),f=_.invokeMap(c.headers[0],"toLowerCase"),c.headers.splice(0,1),c.threaded&&(e=c.uids[0],c.uids.splice(0,1)),_.reduce(c.uids,function(b,d,f){var g;return g=c.threaded?_.zipObject(e,d):{uid:d.toString()},c.uidsMap[g.uid]=f,b.push(new a.$Message(c.$account.id,c,g,!0)),b},c.$messages),_.forEach(c.headers,function(a){var b=_.zipObject(f,a),d=c.uidsMap[b.uid.toString()];_.extend(c.$messages[d],b)})),a.$log.debug("mailbox "+c.id+" ready"),c.$isLoading=!1,d.resolve(c.$messages)})},function(a){angular.extend(c,a),c.isError=!0,d.reject()}),d.promise},a.prototype.$unwrapHeaders=function(b){var c=this;b.then(function(b){a.$timeout(function(){var a,d;b.length>0&&(a=_.invokeMap(b[0],"toLowerCase"),b.splice(0,1),_.forEach(b,function(b){b=_.zipObject(a,b),d=c.uidsMap[b.uid.toString()],angular.isDefined(d)&&_.extend(c.$messages[d],b)}))})})},a.prototype.$updateSubscribe=function(){var b=this.subscribed?"subscribe":"unsubscribe";a.$$resource.post(this.id,b)}}(),function(){"use strict";function a(a,b,c,d){this.accountId=a,this.$mailbox=b,this.$hasUnsafeContent=!1,this.$loadUnsafeContent=!1,this.editable={to:[],cc:[],bcc:[]},this.selected=!1,"function"!=typeof c.then?(!angular.isUndefined(d)&&d||(angular.extend(this,c),this.$formatFullAddresses()),this.uid=parseInt(c.uid)):this.$unwrap(c)}a.$factory=["$q","$timeout","$log","sgSettings","sgMessage_STATUS","Resource","Preferences",function(b,c,d,e,f,g,h){return angular.extend(a,{STATUS:f,$q:b,$timeout:c,$log:d,$$resource:new g(e.activeUser("folderURL")+"Mail",e.activeUser()),$avatar:angular.bind(h,h.avatar)}),h.ready().then(function(){h.defaults.SOGoMailLabelsColors&&(a.$tags=h.defaults.SOGoMailLabelsColors),h.defaults.SOGoMailDisplayRemoteInlineImages&&"always"==h.defaults.SOGoMailDisplayRemoteInlineImages&&(a.$displayRemoteInlineImages=!0)}),a}];try{angular.module("SOGo.MailerUI")}catch(a){angular.module("SOGo.MailerUI",["SOGo.Common"])}angular.module("SOGo.MailerUI").constant("sgMessage_STATUS",{NOT_LOADED:0,DELAYED_LOADING:1,LOADING:2,LOADED:3,DELAYED_MS:300}).factory("Message",a.$factory),a.filterTags=function(b,c){var d=new RegExp(b,"i"),e=[];return _.forEach(_.keys(a.$tags),function(b){var f=a.$tags[b];f[0].search(d)!=-1&&(_.includes(c,b)||e.push({name:b,description:f[0],color:f[1]}))}),e},a.prototype.$absolutePath=function(a){function b(){var a;return a=_.map(c.$mailbox.path.split("/"),function(a){return"folder"+a.asCSSIdentifier()}),a.splice(0,0,c.accountId),a.join("/")}var c=this,d=this.id;return(angular.isUndefined(this.id)||a&&a.nocache)&&(this.id=b()+"/"+this.uid,d=this.id),a&&a.asDraft&&this.draftId&&(d=b()+"/"+this.draftId),d},a.prototype.$setUID=function(a){var b,c=this.uid||-1,d=this;c!=parseInt(a)&&(this.uid=parseInt(a),this.$absolutePath({nocache:!0}),c>-1?(c=c.toString(),angular.isDefined(this.$mailbox.uidsMap[c])&&(b=this.$mailbox.uidsMap[c],this.$mailbox.uidsMap[a]=b,delete this.$mailbox.uidsMap[c],_.forEach(["from","to","subject"],function(a){d.$mailbox.$messages[b][a]=d[a]}))):this.$mailbox.constructor.selectedFolder&&"draft"==this.$mailbox.constructor.selectedFolder.type&&this.$mailbox.constructor.selectedFolder.$filter())},a.prototype.$formatFullAddresses=function(){var b=this,c=_.map(b.$mailbox.$account.identities,"email");_.forEach(["from","to","cc","bcc","reply-to"],function(d){_.forEach(b[d],function(b){b.name&&b.name!=b.email?(b.full=b.name+" <"+b.email+">",b.name.length<10?b.shortname=b.name:b.name.split(" ").length&&(b.shortname=_.first(_.last(b.name.split(/, */)).split(/ +/)).replace("'",""))):b.email&&(b.full="<"+b.email+">",b.shortname=b.email.split("@")[0]),b.image=a.$avatar(b.email,32),_.indexOf(c,b.email)>=0&&(b.shortname=l("me"))})})},a.prototype.$shortRecipients=function(a){var b=this,c=[],d=0,e=0;return _.forEach(["to","cc","bcc"],function(f){e+=b[f]?b[f].length:0,_.forEach(b[f],function(b,e){da&&c.push(l("and %{0} more...",e-a)),c.join(", ")},a.prototype.$shortAddress=function(a){var b="";return this[a]&&this[a].length>0&&(b=this[a][0].name||this[a][0].email||""),b},a.prototype.allowReplyAll=function(){var a=0;return a=_.reduce(["to","cc"],_.bind(function(a,b){return this[b]?a+this[b].length:a},this),a),!this.isDraft&&a>1},a.prototype.loadUnsafeContent=function(){this.$loadUnsafeContent=!0},a.prototype.$content=function(){var b=this,c=[],d=function(e){if(e.msgclass="msg-attachment-other","UIxMailPartAlternativeViewer"==e.type)d(_.find(e.content,function(a){return e.preferredPart==a.contentType}));else if(angular.isArray(e.content)){if("UIxMailPartSignedViewer"==e.type&&1===e["supports-smime"]){var f="

"+e.error.replace(/\n/,'

');f=f.replace(/\n/g,'

')+"

",b.$smime={validSignature:e.valid,message:f}}_.forEach(e.content,function(a){d(a)})}else angular.isUndefined(e.safeContent)&&(e.safeContent=e.content,b.$hasUnsafeContent|=e.safeContent.indexOf(" unsafe-")>-1),"UIxMailPartHTMLViewer"==e.type?(e.html=!0,b.$loadUnsafeContent||a.$displayRemoteInlineImages?(angular.isUndefined(e.unsafeContent)&&(e.unsafeContent=document.createElement("div"),e.unsafeContent.innerHTML=e.safeContent,angular.forEach(["src","data","classid","background","style"],function(a){var b,c,d,f=e.unsafeContent.querySelectorAll("[unsafe-"+a+"]");for(d=0;d=0)for(b=0,c=0;c0){var d=_.map(b,"uid");f.push(b);var h=a.$$resource.post(c,"addOrRemoveLabel",_.assign(e,{msgUIDs:d}));g.push(h)}}),a.$q.all(g).then(function(){return _.flatten(f)})},a.prototype.$deleteMessages=function(b){var c=[];return _.forEach(b,function(a,b){if(a.length>0){var d=a[0].$mailbox,e=d.$deleteMessages(a);c.push(e)}}),a.$q.all(c)},a.prototype.$markOrUnMarkMessagesAsJunk=function(b){var c=[];return _.forEach(b,function(a,b){if(a.length>0){var d=a[0].$mailbox,e=d.$markOrUnMarkMessagesAsJunk(a);c.push(e)}}),a.$q.all(c)},a.prototype.$copyMessages=function(b,c){var d=[];return _.forEach(b,function(a,b){if(a.length>0){var e=a[0].$mailbox,f=e.$copyMessages(a,c);d.push(f)}}),a.$q.all(d)},a.prototype.$moveMessages=function(b,c){var d=[];return _.forEach(b,function(a,b){if(a.length>0){var e=a[0].$mailbox,f=e.$moveMessages(a,c);d.push(f)}}),a.$q.all(d)}}(),function(){"use strict";function a(a,b,c,d,e,f,g,h,i,j,k,m,n,o,p,q,r){function s(a){a.push(k.createHotkey({key:l("hotkey_search"),description:l("Search"),callback:w})),a.push(k.createHotkey({key:l("hotkey_compose"),description:l("Write a new message"),callback:function(a){null===R.messageDialog&&y(a)}})),a.push(k.createHotkey({key:l("hotkey_junk"),description:l("Mark the selected messages as junk"),callback:J})),a.push(k.createHotkey({key:"space",description:l("Toggle item"),callback:F})),a.push(k.createHotkey({key:"shift+space",description:l("Toggle range of items"),callback:F})),a.push(k.createHotkey({key:"up",description:l("View next item"),callback:A,preventInClass:["sg-mail-part"]})),a.push(k.createHotkey({key:"down",description:l("View previous item"),callback:B,preventInClass:["sg-mail-part"]})),a.push(k.createHotkey({key:"shift+up",description:l("Add next item to selection"),callback:C,preventInClass:["sg-mail-part"]})),a.push(k.createHotkey({key:"shift+down",description:l("Add previous item to selection"),callback:D,preventInClass:["sg-mail-part"]})),a.push(k.createHotkey({key:"backspace",description:l("Delete selected message or folder"),callback:I})),_.forEach(a,function(a){k.registerHotkey(a)})}function t(a){return R.selectedFolder.$compact()}function u(a){R.selectedFolder.$filter({sort:a})}function v(a){return r.$query.sort==a}function w(){R.mode.search=!0,o("search")}function x(){R.mode.search=!1,R.selectedFolder.$filter().then(function(){R.selectedFolder.selectedMessage&&c(function(){R.selectedFolder.$topIndex=R.selectedFolder.uidsMap[R.selectedFolder.selectedMessage]})})}function y(a,b){var c;null===R.messageDialog&&(b?z():(c=R.account.$newMessage(),R.messageDialog=f.show({parent:angular.element(document.body),targetEvent:a,clickOutsideToClose:!1,escapeToClose:!1,templateUrl:"UIxMailEditor",controller:"MessageEditorController",controllerAs:"editor",locals:{stateAccount:R.account,stateMessage:c}}).finally(function(){R.messageDialog=null})))}function z(){var b=[n.baseURL(),"UIxMailPopupView#!/Mail",R.account.id,m(m(R.selectedFolder.path)),"new"].join("/"),c=R.selectedFolder.$id()+"/"+Math.random(0,1e3);console.debug(b),a.open(b,c,["width=680","height=520","resizable=1","scrollbars=1","toolbar=0","location=0","directories=0","status=0","menubar=0","copyhistory=0"].join(","))}function A(a){var b=R.selectedFolder.$selectedMessageIndex();return angular.isDefined(b)?(b--,R.selectedFolder.$topIndex>0&&R.selectedFolder.$topIndex--):(b=R.selectedFolder.getLength()-1,R.selectedFolder.$topIndex=R.selectedFolder.getLength()),b>-1&&E(R.selectedFolder.$messages[b]),a.preventDefault(),b}function B(a){var b=R.selectedFolder.$selectedMessageIndex();return angular.isDefined(b)?(b++,R.selectedFolder.$topIndex=0&&F(a,R.selectedFolder.$messages[b]))}function D(a){var b;R.selectedFolder.hasSelectedMessage()&&(b=B(a),b>=0&&F(a,R.selectedFolder.$messages[b]))}function E(a){r.$virtualMode?e.go("mail.account.virtualMailbox.message",{mailboxId:m(a.$mailbox.path),messageId:a.uid}):e.go("mail.account.mailbox.message",{messageId:a.uid})}function F(a,b){var c,d,e,f=R.selectedFolder;if(b||(b=f.$selectedMessage()),b.selected=!b.selected,R.mode.multiple+=b.selected?1:-1,a.shiftKey&&f.$selectedCount()>1){for(c=f.uidsMap[b.uid],d=c-2;d>=0&&!f.$messages[d].selected;)d--;if(d<0)for(d=c+2;d=0&&d0&&(g-=1,d=R.selectedFolder.$messages[g]),b0&&(R.messageDialog=p.confirm(l("Confirmation"),l("Are you sure you want to delete the selected messages?"),{ok:l("Delete")}).then(function(){var a=R.selectedFolder.hasSelectedMessage();R.selectedFolder.$deleteMessages(b).then(function(b){r.$virtualMode?a&&e.go("mail.account.virtualMailbox"):H(a,b)},function(c){R.messageDialog=p.confirm(l("Warning"),l("The messages could not be moved to the trash folder. Would you like to delete them immediately?"),{ok:l("Delete")}).then(function(){R.selectedFolder.$deleteMessages(b,{withoutTrash:!0}).then(function(b){r.$virtualMode?a&&e.go("mail.account.virtualMailbox"):H(a,b)})})})}).finally(function(){R.messageDialog=null})),a.preventDefault()}function J(){var a=R.selectedFolder.hasSelectedMessage(),b=R.selectedFolder.$selectedMessages();0===_.size(b)&&a&&(b=[R.selectedFolder.$selectedMessage()]),_.size(b)>0&&R.selectedFolder.$markOrUnMarkMessagesAsJunk(b).then(function(){var c="/"+R.account.id+"/folderINBOX";"junk"!=R.selectedFolder.type&&(c="/"+R.account.$getMailboxByType("junk").id),R.selectedFolder.$moveMessages(b,c).then(function(b){r.$virtualMode?a&&e.go("mail.account.virtualMailbox"):H(a,b)})})}function K(a){var b=R.selectedFolder.$selectedMessages();_.size(b)>0&&R.selectedFolder.$copyMessages(b,"/"+a).then(function(){g.show(g.simple().content(l("%{0} message(s) copied",R.selectedFolder.$selectedCount())).position("top right").hideDelay(2e3))})}function L(a){var b=R.selectedFolder.hasSelectedMessage(),c=R.selectedFolder.$selectedMessages(),d=R.selectedFolder.$selectedCount();_.size(c)>0&&R.selectedFolder.$moveMessages(c,"/"+a).then(function(a){g.show(g.simple().content(l("%{0} message(s) moved",d)).position("top right").hideDelay(2e3)),r.$virtualMode?b&&e.go("mail.account.virtualMailbox"):H(b,a)})}function M(){var a=0;_.forEach(G(),function(b){for(var c=0,d=b.$messages.length;c0&&R.selectedFolder.$flagMessages(a,"\\Flagged","add").then(function(a){_.forEach(a,function(a){a.isflagged=!0})})}function P(){var a=R.selectedFolder.$selectedMessages();_.size(a)>0&&R.selectedFolder.$flagMessages(a,"seen","remove").then(function(a){_.forEach(a,function(a){a.isread&&a.$mailbox.unseenCount++,a.isread=!1})})}function Q(){var a=R.selectedFolder.$selectedMessages();_.size(a)>0&&R.selectedFolder.$flagMessages(a,"seen","add").then(function(a){_.forEach(a,function(a){a.isread||a.$mailbox.unseenCount--,a.isread=!0})})}var R=this,S=angular.element(a.document).find("title").attr("sg-default")||"SOGo",T=[];a.$mailboxController=R,R.service=r,R.accounts=h,R.account=i,R.selectedFolder=j,R.selectMessage=E,R.messageDialog=null,R.toggleMessageSelection=F,R.sort=u,R.sortedBy=v,R.searchMode=w,R.cancelSearch=x,R.newMessage=y,R.mode={search:!1,multiple:0},R.confirmDeleteSelectedMessages=I,R.markOrUnMarkMessagesAsJunk=J,R.copySelectedMessages=K,R.moveSelectedMessages=L,R.markSelectedMessagesAsFlagged=O,R.markSelectedMessagesAsUnread=P,R.markSelectedMessagesAsRead=Q,R.selectAll=M,R.unselectMessages=N,j.selectFolder(),s(T),angular.element(a).on("beforeunload",t),b.$on("$destroy",function(){angular.element(a).off("beforeunload",t),_.forEach(T,function(a){k.deregisterHotkey(a)})}),b.$watch(function(){return R.selectedFolder.unseenCount},function(b){var c=S+" - ";b&&(c+="("+b+") "),c+=R.selectedFolder.$displayName,a.document.title=c})}function b(a){return a[0].controller.prototype.resetScroll=function(){"messagesList"==this.$element.parent().attr("id")?this.updateSize():this.scrollTo(0)},a}a.$inject=["$window","$scope","$timeout","$q","$state","$mdDialog","$mdToast","stateAccounts","stateAccount","stateMailbox","sgHotkeys","encodeUriFilter","sgSettings","sgFocus","Dialog","Account","Mailbox"],angular.module("material.components.virtualRepeat").decorator("mdVirtualRepeatContainerDirective",b),b.$inject=["$delegate"],angular.module("SOGo.MailerUI").controller("MailboxController",a)}(),function(){"use strict";function a(a,b,c,d,e,f,g,h,i,j,k,m,n,o,p,q,r,s,t,u){function v(a){a.push(o.createHotkey({key:"backspace",description:l("Delete selected message or folder"),callback:function(){q.selectedFolder&&!q.selectedFolder.hasSelectedMessage()&&L(q.selectedFolder)}})),_.forEach(a,function(a){o.registerHotkey(a)})}function w(a){U.showingAdvancedSearch=!0,U.search.mailbox=a,g(i["gt-md"])||h("left").close()}function x(){U.showingAdvancedSearch=!1,U.service.$virtualMode=!1,S=U.accounts[0],T=U.searchPreviousMailbox,b.go("mail.account.mailbox",{accountId:S.id,mailboxId:k(T.path)})}function y(){if(q.selectedFolder.$isLoading)U.virtualMailbox.stopSearch();else{var a,c=[],d=function(a){_.forEach(a,function(a){c.push(a),a.children&&a.children.length>0&&d(a.children)})};U.virtualMailbox=new r(U.accounts[0]),q.$virtualMode||(U.searchPreviousMailbox=q.selectedFolder),q.selectedFolder=U.virtualMailbox,q.$virtualMode=!0,angular.isDefined(U.search.mailbox)?(a=U.accounts[0].$getMailboxByPath(U.search.mailbox),c.push(a),U.search.subfolders&&a.children.length&&d(a.children)):c=U.accounts[0].$flattenMailboxes(),U.virtualMailbox.setMailboxes(c),U.virtualMailbox.startSearch(U.search.match,U.search.params),b.go("mail.account.virtualMailbox",{accountId:U.accounts[0].id})}}function z(a){return U.currentSearchParam=a,j("advancedSearch"),!1}function A(a){if(a.length&&U.currentSearchParam.length){var b=0,c=U.currentSearchParam;return a.startsWith("!")&&(b=1,a=a.substring(1).trim()),U.currentSearchParam="",{searchBy:c,searchInput:a,negative:b}}}function B(a){a.$expanded=!a.$expanded,a.$flattenMailboxes({reload:!0,saveState:!0}),c(function(){angular.element(d).triggerHandler("resize")},150)}function C(a){function b(a,b,c){function d(){b.cancel()}var e=this;e.loading=!0,e.filter={name:""},e.account=new p({id:c.id,name:c.name}),e.close=d,e.account.$getMailboxes({reload:!0,all:!0}).then(function(){e.loading=!1})}e.show({templateUrl:a.id+"/subscribe",controller:b,controllerAs:"subscriptions",clickOutsideToClose:!0,escapeToClose:!0,locals:{srcAccount:a}}).finally(function(){a.$getMailboxes({reload:!0})}),b.$inject=["$scope","$mdDialog","srcAccount"]}function D(a){m.prompt(l("New Folder..."),l("Enter the new name of your folder")).then(function(b){a.$newMailbox(a.id,b).then(function(){},function(a,c){m.alert(l('An error occured while creating the mailbox "%{0}".',b),l(a.error))})})}function E(a){function b(a,b,c,d){function e(a){return c.$filter(a,d.delegates)}function f(){b.hide()}function g(a){d.$removeDelegate(a.uid).catch(function(a,b){m.alert(l("Warning"),l("An error occured please try again."))})}function h(a){a&&d.$addDelegate(a).then(function(){i.userToAdd="",i.searchText=""},function(a){m.alert(l("Warning"),a)})}var i=this;i.users=d.delegates,i.account=d,i.userToAdd="",i.searchText="",i.userFilter=e,i.closeModal=f,i.removeUser=g,i.addUser=h}e.show({templateUrl:a.id+"/delegation",controller:b,controllerAs:"delegate",clickOutsideToClose:!0,escapeToClose:!0,locals:{User:s,account:a}}),b.$inject=["$scope","$mdDialog","User","account"]}function F(a){U.editMode=a.path,j("mailboxName_"+a.path)}function G(a){a.$reset(),U.editMode=!1}function H(a,c,d){U.editMode!=d.path&&(U.editMode=!1,U.showingAdvancedSearch=!1,U.service.$virtualMode=!1,g(i["gt-md"])||h("left").close(),b.go("mail.account.mailbox",{accountId:c.id,mailboxId:k(d.path)}),a.stopPropagation(),a.preventDefault())}function I(a){a.$rename().then(function(a){U.editMode=!1})}function J(a){a.$compact().then(function(){f.show(f.simple().content(l("Folder compacted")).position("top right").hideDelay(3e3))})}function K(a){a.$emptyTrash().then(function(){f.show(f.simple().content(l("Trash emptied")).position("top right").hideDelay(3e3))})}function L(a){m.confirm(l("Warning"),l("Do you really want to move this folder into the trash ?"),{ok:l("Delete")}).then(function(){a.$delete().then(function(){b.go("mail.account.inbox")},function(c){m.confirm(l("Warning"),l("The mailbox could not be moved to the trash folder. Would you like to delete it immediately?"),{ok:l("Delete")}).then(function(){a.$delete({withoutTrash:!0}).then(function(){b.go("mail.account.inbox")},function(b){m.alert(l('An error occured while deleting the mailbox "%{0}".',a.name),l(b.error))})})})})}function M(a){a.$markAsRead()}function N(a){a.$acl.$users().then(function(){e.show({templateUrl:a.id+"/UIxAclEditor",controller:"AclController",controllerAs:"acl",clickOutsideToClose:!0,escapeToClose:!0,locals:{usersWithACL:a.$acl.users,User:s,folder:a}})})}function O(a,b){a.$setFolderAs(b).then(function(){a.$account.$getMailboxes({reload:!0})})}function P(){var a=d.unseenCountFolders;_.forEach(U.accounts,function(b){_.includes(a,b.id+"/folderINBOX")||a.push(b.id+"/folderINBOX"),_.forEach(b.$$flattenMailboxes,function(b){angular.isDefined(b.unseenCount)&&!_.includes(a,b.id)&&a.push(b.id)})}),p.$$resource.post("","unseenCount",{mailboxes:a}).then(function(a){_.forEach(U.accounts,function(b){_.forEach(b.$$flattenMailboxes,function(b){a[b.id]&&(b.unseenCount=a[b.id])})})}),t.ready().then(function(){var a=t.defaults.SOGoRefreshViewCheck;a&&"manually"!=a&&c(U.refreshUnseenCount,1e3*a.timeInterval())})}function Q(a,b){return b.id!=a.id&&!b.isNoSelect()}function R(a,c,d){var e,g,h,i,j,k;e="/"+c.id,g=a.$selectedMessages(),0===g.length&&(g=[a.$selectedMessage()]),h=_.map(g,"uid"),i=a.selectedMessage&&h.indexOf(a.selectedMessage)>=0,"copy"==d?(j=a.$copyMessages(g,e),k=l("%{0} message(s) copied",g.length)):(j=a.$moveMessages(g,e),k=l("%{0} message(s) moved",g.length)),j.then(function(){i&&b.go("mail.account.mailbox"),f.show(f.simple().content(k).position("top right").hideDelay(2e3))})}var S,T,U=this,V=[];U.service=q,U.accounts=u,U.toggleAccountState=B,U.subscribe=C,U.newFolder=D,U.delegate=E,U.editFolder=F,U.revertEditing=G,U.selectFolder=H,U.saveFolder=I,U.compactFolder=J,U.emptyTrashFolder=K,U.confirmDelete=L,U.markFolderRead=M,U.share=N,U.setFolderAs=O,U.refreshUnseenCount=P,U.isDroppableFolder=Q,U.dragSelectedMessages=R,U.showingAdvancedSearch=!1,U.currentSearchParam="",U.addSearchParam=z,U.newSearchParam=A,U.showAdvancedSearch=w,U.hideAdvancedSearch=x,U.toggleAdvancedSearch=y,U.search={options:{"":"",subject:l("Enter Subject"),from:l("Enter From"),to:l("Enter To"),cc:l("Enter Cc"),body:l("Enter Body")},mailbox:"INBOX",subfolders:1,match:"AND",params:[]},t.ready().then(function(){U.showSubscribedOnly=t.defaults.SOGoMailShowSubscribedFoldersOnly}),U.refreshUnseenCount(),v(V),a.$on("$destroy",function(){_.forEach(V,function(a){o.deregisterHotkey(a)})})}a.$inject=["$scope","$state","$timeout","$window","$mdDialog","$mdToast","$mdMedia","$mdSidenav","sgConstant","sgFocus","encodeUriFilter","Dialog","sgSettings","sgHotkeys","Account","Mailbox","VirtualMailbox","User","Preferences","stateAccounts"],angular.module("SOGo.MailerUI").controller("MailboxesController",a)}(),function(){"use strict";function a(a,b,c,d,e,f,g,h,i,j,k,m,n,o,p,q,r,s,t,u){function v(){return b.mailbox?(arguments.length>0&&(b.mailbox.messageDialog=arguments[0]),b.mailbox.messageDialog):null}function w(a){return function(){if(null===v())return a.apply(Q,arguments)}}function x(a){a.push(k.createHotkey({key:l("hotkey_reply"),description:l("Reply to the message"),callback:w(E)})),a.push(k.createHotkey({key:l("hotkey_replyall"),description:l("Reply to sender and all recipients"),callback:w(F)})),a.push(k.createHotkey({key:l("hotkey_forward"),description:l("Forward selected message"),callback:w(G)})),a.push(k.createHotkey({key:l("hotkey_flag"),description:l("Flagged"),callback:w(angular.bind(j,j.toggleFlag))})),a.push(k.createHotkey({key:"backspace",callback:w(function(a){0===Q.mailbox.$selectedCount()&&B(),a.preventDefault()})})),_.forEach(a,function(a){k.registerHotkey(a)})}function y(){var b,c,d={};return a.opener&&a.opener.$mailboxController&&a.opener.$mailboxController.selectedFolder.$id()==i.$id()&&(c=a.opener.$mailboxController,d.mailboxCtrl=c,a.opener.$messageController&&a.opener.$messageController.message.uid==j.uid&&(b=a.opener.$messageController,d.messageCtrl=b)),d}function z(a){Q.$showDetailedRecipients=!Q.$showDetailedRecipients,a.stopPropagation(),a.preventDefault()}function A(a){var b,c,d,e;"A"==a.target.tagName&&"href"in a.target.attributes&&(b=a.target.attributes.href.value,c=/^mailto:([^\?]+)/.exec(b),c&&(d=_.map(decodeURIComponent(c[1]).split(","),function(a){return"<"+a+">"}),e={to:d},_.forEach(["subject","body"],function(a){var d=new RegExp(a+"=([^&]+)");a="body"==a?"text":a,c=d.exec(b),c&&(e[a]=[decodeURIComponent(c[1])])}),_.forEach(["cc","bcc"],function(a){c=new RegExp(a+"=([^&]+)").exec(b),c&&(e[a]=[decodeURIComponent(c[1])])}),K(a,e)))}function B(){var a,b,e,g,h,k=y();k.messageCtrl?(a=k.mailboxCtrl.selectedFolder,b=k.messageCtrl.message,e=k.messageCtrl.$state):(a=i,b=j,e=c),a.$deleteMessages([b]).then(function(c){var i=c;if(b=null,angular.isDefined(e)){c>0&&(i-=1,g=a.$messages[i]),ca.$lastVisibleIndex&&(a.$topIndex=i-(a.$lastVisibleIndex-a.$topIndex))):e.go("mail.account.mailbox").then(function(){b=null,delete a.selectedMessage})}catch(a){}}J()})}function C(a,b){null===v()&&v(e.show({parent:angular.element(document.body),targetEvent:a,clickOutsideToClose:!1,escapeToClose:!1,templateUrl:"UIxMailEditor",controller:"MessageEditorController",controllerAs:"editor",locals:{stateAccount:Q.account,stateMessage:b}}).finally(function(){v(null),J()}))}function D(){c.go("mail.account.mailbox").then(function(){Q.message=null,delete i.selectedMessage})}function E(a){C(a,Q.message.$reply())}function F(a){C(a,Q.message.$replyAll())}function G(a){C(a,Q.message.$forward())}function H(a){Q.message.$editableContent().then(function(){C(a,Q.message)})}function I(){var b=[n.baseURL(),"UIxMailPopupView#!/Mail",Q.message.accountId,m(m(Q.message.$mailbox.path)),Q.message.uid].join("/"),c=Q.message.$absolutePath();R=a.open(b,c,["width=680","height=520","resizable=1","scrollbars=1","toolbar=0","location=0","directories=0","status=0","menubar=0","copyhistory=0"].join(","))}function J(){a.opener&&a.close()}function K(a,b){Q.account.$newMessage().then(function(c){angular.extend(c.editable,b),C(a,c)}),a.stopPropagation(),a.preventDefault()}function L(a){Q.showRawSource||Q.message.$rawSource?Q.showRawSource=!Q.showRawSource:u.$$resource.post(Q.message.id,"viewsource").then(function(a){Q.message.$rawSource=a,Q.showRawSource=!0})}function M(b){a.print()}function N(a){return P(a,"appointment")}function O(a){return P(a,"task")}function P(a,b){Q.message.$plainContent().then(function(c){var d={pid:q.$defaultCalendar(),type:b,summary:c.subject,comment:c.content},f=new r(d),g=[n.activeUser("folderURL"),"Calendar","UIx"+b.capitalize()+"EditorTemplate"].join("/");return e.show({parent:angular.element(document.body),targetEvent:a,clickOutsideToClose:!0,escapeToClose:!0,templateUrl:g,controller:"ComponentEditorController",controllerAs:"editor",locals:{stateComponent:f}})})}var Q=this,R=null,S=[];a.$messageController=Q,Q.$state=c,Q.accounts=g,Q.account=h,Q.mailbox=i,Q.message=j,Q.service=u,Q.tags={searchText:"",selected:""},Q.showFlags=j.flags&&j.flags.length>0,Q.$showDetailedRecipients=!1,Q.toggleDetailedRecipients=z,Q.filterMailtoLinks=A,Q.deleteMessage=B,Q.close=D,Q.reply=E,Q.replyAll=F,Q.forward=G,Q.edit=H,Q.openPopup=I,Q.closePopup=J,Q.newMessage=K,Q.toggleRawSource=L,Q.showRawSource=!1,Q.print=M,Q.convertToEvent=N,Q.convertToTask=O,x(S),a.opener?(b.$watchCollection(function(){return Q.message.flags},function(a,b){var c;(a||b)&&(c=y(),c.messageCtrl&&c.messageCtrl.service.$timeout(function(){c.messageCtrl.showFlags=!0,c.messageCtrl.message.flags=a}))}),b.$watch(function(){return Q.message.isflagged},function(a,b){var c=y();c.mailboxCtrl&&c.mailboxCtrl.service.$timeout(function(){_.find(c.mailboxCtrl.selectedFolder.$messages,{uid:Q.message.uid}).isflagged=a})})):b.$watchCollection(function(){return Q.message.flags},function(a,b){var c,d,e;(a||b)&&(c=a||[],d=b||[],_.forEach(c,function(a,b){angular.isObject(a)&&(c[b]=a.name)}),c.length>d.length?(e=_.difference(c,d),_.forEach(e,function(a){Q.message.addTag(a)})):c.length';\n else\n identity.full = '<' + identity.email + '>';\n });\n Account.$log.debug('Account: ' + JSON.stringify(futureAccountData, undefined, 2));\n }\n else {\n // The promise will be unwrapped first\n //this.$unwrap(futureAccountData);\n }\n }\n\n /**\n * @memberof Account\n * @desc The factory we'll use to register with Angular\n * @returns the Account constructor\n */\n Account.$factory = ['$q', '$timeout', '$log', 'sgSettings', 'Resource', 'Preferences', 'Mailbox', 'Message', function($q, $timeout, $log, Settings, Resource, Preferences, Mailbox, Message) {\n angular.extend(Account, {\n $q: $q,\n $timeout: $timeout,\n $log: $log,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Mail', Settings.activeUser()),\n $Preferences: Preferences,\n $Mailbox: Mailbox,\n $Message: Message\n });\n\n return Account; // return constructor\n }];\n\n /**\n * @module SOGo.MailerUI\n * @desc Factory registration of Account in Angular module.\n */\n try {\n angular.module('SOGo.MailerUI');\n }\n catch(e) {\n angular.module('SOGo.MailerUI', ['SOGo.Common']);\n }\n angular.module('SOGo.MailerUI')\n .factory('Account', Account.$factory);\n\n /**\n * @memberof Account\n * @desc Set the list of accounts and instanciate a new Account object for each item.\n * @param {array} [data] - the metadata of the accounts\n * @returns the list of accounts\n */\n Account.$findAll = function(data) {\n if (!data) {\n return Account.$$resource.fetch('', 'mailAccounts').then(function(o) {\n return Account.$unwrapCollection(o);\n });\n }\n return Account.$unwrapCollection(data);\n };\n\n /**\n * @memberof Account\n * @desc Unwrap to a collection of Account instances.\n * @param {object} data - the accounts information\n * @returns a collection of Account objects\n */\n Account.$unwrapCollection = function(data) {\n var collection = [];\n\n angular.forEach(data, function(o, i) {\n o.id = i;\n collection[i] = new Account(o);\n });\n Account.$accounts = collection;\n\n return collection;\n };\n\n /**\n * @function getLength\n * @memberof Account.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the number of mailboxes in the account\n */\n Account.prototype.getLength = function() {\n return this.$flattenMailboxes().length;\n };\n\n /**\n * @function getItemAtIndex\n * @memberof Account.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the mailbox at the specified index\n */\n Account.prototype.getItemAtIndex = function(index) {\n var expandedMailboxes;\n\n expandedMailboxes = this.$flattenMailboxes();\n if (index >= 0 && index < expandedMailboxes.length)\n return expandedMailboxes[index];\n\n return null;\n };\n\n /**\n * @function $getMailboxes\n * @memberof Account.prototype\n * @desc Fetch the list of mailboxes for the current account.\n * @param {object} [options] - force a reload by setting 'reload' to true\n * @returns a promise of the HTTP operation\n */\n Account.prototype.$getMailboxes = function(options) {\n var _this = this;\n\n if (this.$mailboxes && !(options && options.reload)) {\n return Account.$q.when(this.$mailboxes);\n }\n else {\n return Account.$Mailbox.$find(this, options).then(function(data) {\n _this.$mailboxes = data;\n _this.$expanded = false;\n\n // Set expanded folders from user's settings\n Account.$Preferences.ready().then(function() {\n var expandedFolders,\n _visit = function(mailboxes) {\n _.forEach(mailboxes, function(o) {\n o.$expanded = (expandedFolders.indexOf('/' + o.id) >= 0);\n if (o.children && o.children.length > 0) {\n _visit(o.children);\n }\n });\n };\n if (Account.$Preferences.settings.Mail.ExpandedFolders) {\n if (angular.isString(Account.$Preferences.settings.Mail.ExpandedFolders))\n // Backward compatibility support\n expandedFolders = angular.fromJson(Account.$Preferences.settings.Mail.ExpandedFolders);\n else\n expandedFolders = Account.$Preferences.settings.Mail.ExpandedFolders;\n _this.$expanded = (expandedFolders.indexOf('/' + _this.id) >= 0);\n if (expandedFolders.length > 0) {\n _visit(_this.$mailboxes);\n }\n }\n if (Account.$accounts)\n _this.$expanded |= (Account.$accounts.length == 1); // Always expand single account\n _this.$flattenMailboxes({reload: true});\n });\n\n return _this.$mailboxes;\n });\n }\n };\n\n /**\n * @function $flattenMailboxes\n * @memberof Account.prototype\n * @desc Get a flatten array of the mailboxes.\n * @param {object} [options] - the following boolean attributes are available:\n * - reload: rebuild the flatten array of mailboxes from the original tree representation (this.$mailboxes)\n * - all: return all mailboxes, ignoring their expanstion state\n * - saveState: save expansion state of mailboxes to the server\n * @returns an array of Mailbox instances\n */\n Account.prototype.$flattenMailboxes = function(options) {\n var _this = this,\n allMailboxes = [],\n expandedMailboxes = [],\n _visit = function(mailboxes) {\n _.forEach(mailboxes, function(o) {\n allMailboxes.push(o);\n if ((options && options.all || o.$expanded) && o.children && o.children.length > 0) {\n _visit(o.children);\n }\n });\n };\n\n if (this.$$flattenMailboxes && !(options && (options.reload || options.all))) {\n allMailboxes = this.$$flattenMailboxes;\n }\n else {\n _visit(this.$mailboxes);\n if (!options || !options.all) {\n _this.$$flattenMailboxes = allMailboxes;\n if (options && options.saveState) {\n // Save expansion state of mailboxes to the server\n _.forEach(Account.$accounts, function(account) {\n if (account.$expanded) {\n expandedMailboxes.push('/' + account.id);\n }\n _.reduce(account.$$flattenMailboxes, function(expandedFolders, mailbox) {\n if (mailbox.$expanded) {\n expandedFolders.push('/' + mailbox.id);\n }\n return expandedFolders;\n }, expandedMailboxes);\n });\n Account.$$resource.post(null, 'saveFoldersState', expandedMailboxes);\n }\n }\n }\n\n return allMailboxes;\n };\n\n Account.prototype.$getMailboxByType = function(type) {\n var mailbox,\n // Recursive find function\n _find = function(mailboxes) {\n var mailbox = _.find(mailboxes, function(o) {\n return o.type == type;\n });\n if (!mailbox) {\n angular.forEach(mailboxes, function(o) {\n if (!mailbox && o.children && o.children.length > 0) {\n mailbox = _find(o.children);\n }\n });\n }\n return mailbox;\n };\n mailbox = _find(this.$mailboxes);\n\n return mailbox;\n };\n\n /**\n * @function $getMailboxByPath\n * @memberof Account.prototype\n * @desc Recursively find a mailbox using its path\n * @returns a promise of the HTTP operation\n */\n Account.prototype.$getMailboxByPath = function(path) {\n var mailbox = null,\n // Recursive find function\n _find = function(mailboxes) {\n var mailbox = _.find(mailboxes, function(o) {\n return o.path == path;\n });\n if (!mailbox) {\n angular.forEach(mailboxes, function(o) {\n if (!mailbox && o.children && o.children.length > 0) {\n mailbox = _find(o.children);\n }\n });\n }\n return mailbox;\n };\n mailbox = _find(this.$mailboxes);\n\n return mailbox;\n };\n\n /**\n * @function $newMailbox\n * @memberof Account.prototype\n * @desc Create a new mailbox on the server and refresh the list of mailboxes.\n * @returns a promise of the HTTP operations\n */\n Account.prototype.$newMailbox = function(path, name) {\n var _this = this;\n\n return Account.$$resource.post(path.toString(), 'createFolder', {name: name}).then(function() {\n _this.$getMailboxes({reload: true});\n });\n };\n\n /**\n * @function updateQuota\n * @memberof Account.prototype\n * @param {Object} data - the inbox quota information returned by the server\n * @desc Update the quota definition associated to the account\n */\n Account.prototype.updateQuota = function(data) {\n var percent, format, description;\n\n percent = (Math.round(data.usedSpace * 10000 / data.maxQuota) / 100);\n format = l(\"quotasFormat\");\n description = format.formatted(percent, Math.round(data.maxQuota/10.24)/100);\n\n this.$quota = { percent: percent, description: description };\n };\n\n /**\n * @function $newMessage\n * @memberof Account.prototype\n * @desc Prepare a new Message object associated to the appropriate mailbox.\n * @returns a promise of the HTTP operations\n */\n Account.prototype.$newMessage = function() {\n var _this = this;\n\n // Query account for draft folder and draft UID\n return Account.$$resource.fetch(this.id.toString(), 'compose').then(function(data) {\n Account.$log.debug('New message (compose): ' + JSON.stringify(data, undefined, 2));\n var message = new Account.$Message(data.accountId, _this.$getMailboxByPath(data.mailboxPath), data);\n return message;\n }).then(function(message) {\n // Fetch draft initial data\n return Account.$$resource.fetch(message.$absolutePath({asDraft: true}), 'edit').then(function(data) {\n Account.$log.debug('New message (edit): ' + JSON.stringify(data, undefined, 2));\n angular.extend(message.editable, data);\n message.isNew = true;\n return message;\n });\n });\n };\n\n /**\n * @function $addDelegate\n * @memberof Account.prototype\n * @param {Object} user - a User object with minimal set of attributes (uid, isGroup, cn, c_email)\n * @desc Remove a user from the account's delegates\n * @see {@link User.$filter}\n */\n Account.prototype.$addDelegate = function(user) {\n var _this = this,\n deferred = Account.$q.defer(),\n param = {uid: user.uid};\n if (!user.uid || _.indexOf(_.map(this.delegates, 'uid'), user.uid) > -1) {\n // No UID specified or user already in delegates\n deferred.resolve();\n }\n else {\n Account.$$resource.fetch(this.id.toString(), 'addDelegate', param).then(function() {\n _this.delegates.push(user);\n deferred.resolve(_this.users);\n }, function(data, status) {\n deferred.reject(l('An error occured please try again.'));\n });\n }\n return deferred.promise;\n };\n\n /**\n * @function $removeDelegate\n * @memberof Account.prototype\n * @param {Object} user - a User object with minimal set of attributes (uid, isGroup, cn, c_email)\n * @desc Remove a user from the account's delegates\n * @return a promise of the server call to remove the user from the account's delegates\n */\n Account.prototype.$removeDelegate = function(uid) {\n var _this = this,\n param = {uid: uid};\n return Account.$$resource.fetch(this.id.toString(), 'removeDelegate', param).then(function() {\n var i = _.indexOf(_.map(_this.delegates, 'uid'), uid);\n if (i >= 0) {\n _this.delegates.splice(i, 1);\n }\n });\n };\n \n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @name Mailbox\n * @constructor\n * @param {object} futureMailboxData - either an object literal or a promise\n */\n function Mailbox(account, futureMailboxData) {\n this.$account = account;\n // Data is immediately available\n if (typeof futureMailboxData.then !== 'function') {\n this.init(futureMailboxData);\n if (this.name && !this.path) {\n // Create a new mailbox on the server\n var newMailboxData = Mailbox.$$resource.create('createFolder', this.name);\n this.$unwrap(newMailboxData);\n }\n }\n else {\n // The promise will be unwrapped first\n // NOTE: this condition never happen for the moment\n this.$unwrap(futureMailboxData);\n }\n }\n\n /**\n * @memberof Mailbox\n * @desc The factory we'll use to register with Angular\n * @returns the Mailbox constructor\n */\n Mailbox.$factory = ['$q', '$timeout', '$log', 'sgSettings', 'Resource', 'Message', 'Acl', 'Preferences', 'sgMailbox_PRELOAD', function($q, $timeout, $log, Settings, Resource, Message, Acl, Preferences, PRELOAD) {\n angular.extend(Mailbox, {\n $q: $q,\n $timeout: $timeout,\n $log: $log,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Mail', Settings.activeUser()),\n $Message: Message,\n $$Acl: Acl,\n $Preferences: Preferences,\n $query: { sort: 'arrival', asc: 0 }, // The default sort must match [UIxMailListActions defaultSortKey]\n selectedFolder: null,\n $refreshTimeout: null,\n $virtualMode: false,\n PRELOAD: PRELOAD\n });\n // Initialize sort parameters from user's settings\n Preferences.ready().then(function() {\n if (Preferences.settings.Mail.SortingState) {\n Mailbox.$query.sort = Preferences.settings.Mail.SortingState[0];\n Mailbox.$query.asc = parseInt(Preferences.settings.Mail.SortingState[1]);\n }\n });\n\n return Mailbox; // return constructor\n }];\n\n /**\n * @module SOGo.MailerUI\n * @desc Factory registration of Mailbox in Angular module.\n */\n try {\n angular.module('SOGo.MailerUI');\n }\n catch(e) {\n angular.module('SOGo.MailerUI', ['SOGo.Common']);\n }\n angular.module('SOGo.MailerUI')\n .constant('sgMailbox_PRELOAD', {\n LOOKAHEAD: 50,\n SIZE: 100\n })\n .factory('Mailbox', Mailbox.$factory);\n\n /**\n * @memberof Mailbox\n * @desc Fetch list of mailboxes of a specific account\n * @param {string} accountId - the account\n * @return a promise of the HTTP operation\n * @see {@link Account.$getMailboxes}\n */\n Mailbox.$find = function(account, options) {\n var path, futureMailboxData;\n\n if (options && options.all)\n futureMailboxData = this.$$resource.fetch(account.id.toString(), 'viewAll');\n else\n futureMailboxData = this.$$resource.fetch(account.id.toString(), 'view');\n\n return Mailbox.$unwrapCollection(account, futureMailboxData); // a collection of mailboxes\n };\n\n /**\n * @memberof Mailbox\n * @desc Unwrap to a collection of Mailbox instances.\n * @param {string} account - the account\n * @param {promise} futureMailboxData - a promise of the mailboxes metadata\n * @returns a promise of a collection of Mailbox objects\n */\n Mailbox.$unwrapCollection = function(account, futureMailboxData) {\n var collection = [],\n // Local recursive function\n createMailboxes = function(level, mailbox) {\n for (var i = 0; i < mailbox.children.length; i++) {\n mailbox.children[i].level = level;\n mailbox.children[i] = new Mailbox(account, mailbox.children[i]);\n createMailboxes(level+1, mailbox.children[i]);\n }\n };\n //collection.$futureMailboxData = futureMailboxData;\n\n return futureMailboxData.then(function(data) {\n return Mailbox.$timeout(function() {\n // Each entry is spun up as a Mailbox instance\n angular.forEach(data.mailboxes, function(data, index) {\n data.level = 0;\n var mailbox = new Mailbox(account, data);\n createMailboxes(1, mailbox); // recursively create all sub-mailboxes\n collection.push(mailbox);\n });\n // Update inbox quota\n if (data.quotas)\n account.updateQuota(data.quotas);\n return collection;\n });\n });\n };\n\n /**\n * @memberof Mailbox\n * @desc Build the path of the mailbox (or account only).\n * @param {string} accountId - the account ID\n * @param {string} [mailboxPath] - the mailbox path\n * @returns a string representing the path relative to the mail module\n */\n Mailbox.$absolutePath = function(accountId, mailboxPath) {\n var path = [];\n\n if (mailboxPath) {\n path = _.map(mailboxPath.split('/'), function(component) {\n return 'folder' + component.asCSSIdentifier();\n });\n }\n\n path.splice(0, 0, accountId); // insert account ID\n\n return path.join('/');\n };\n\n /**\n * @function init\n * @memberof Mailbox.prototype\n * @desc Extend instance with new data and compute additional attributes.\n * @param {object} data - attributes of mailbox\n */\n Mailbox.prototype.init = function(data) {\n var _this = this;\n if (data.headers) {\n this.$isLoading = true;\n this.$messages = [];\n this.uidsMap = {};\n }\n angular.extend(this, data);\n if (this.path) {\n this.id = this.$id();\n this.$acl = new Mailbox.$$Acl('Mail/' + this.id);\n }\n this.$displayName = this.name;\n if (this.type) {\n this.$isEditable = this.isEditable();\n this.$isSpecial = true;\n if (this.type == 'inbox') {\n this.$displayName = l('InboxFolderName');\n this.$icon = 'inbox';\n }\n else if (this.type == 'draft') {\n this.$displayName = l('DraftsFolderName');\n this.$icon = 'drafts';\n }\n else if (this.type == 'sent') {\n this.$displayName = l('SentFolderName');\n this.$icon = 'send';\n }\n else if (this.type == 'trash') {\n this.$displayName = l('TrashFolderName');\n this.$icon = 'delete';\n }\n else if (this.type == 'junk') {\n this.$displayName = l('JunkFolderName');\n this.$icon = 'thumb_down';\n }\n else if (this.type == 'additional') {\n this.$icon = 'folder_shared';\n }\n else {\n this.$isSpecial = false;\n this.$icon = 'folder_open';\n }\n }\n this.$isNoInferiors = this.isNoInferiors();\n if (angular.isUndefined(this.$shadowData)) {\n // Make a copy of the data for an eventual reset\n this.$shadowData = this.$omit();\n }\n };\n\n /**\n * @function selectFolder\n * @memberof Mailbox.prototype\n * @desc Mark the folder as selected in the constructor unless virtual mode is active\n */\n Mailbox.prototype.selectFolder = function() {\n if (!Mailbox.$virtualMode)\n Mailbox.selectedFolder = this;\n };\n\n /**\n * @function getLength\n * @memberof Mailbox.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the number of messages in the mailbox\n */\n Mailbox.prototype.getLength = function() {\n return this.$messages.length;\n };\n\n /**\n * @function getItemAtIndex\n * @memberof Mailbox.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the message at the specified index\n */\n Mailbox.prototype.getItemAtIndex = function(index) {\n var message;\n\n if (index >= 0 && index < this.$messages.length) {\n message = this.$messages[index];\n this.$lastVisibleIndex = Math.max(0, index - 3); // Magic number is NUM_EXTRA from virtual-repeater.js\n\n if (this.$loadMessage(message.uid))\n return message;\n }\n return null;\n };\n\n /**\n * @function $id\n * @memberof Mailbox.prototype\n * @desc Build the unique ID to identified the mailbox.\n * @returns a string representing the path relative to the mail module\n */\n Mailbox.prototype.$id = function() {\n return Mailbox.$absolutePath(this.$account.id, this.path);\n };\n\n /**\n * @function $selectedMessages\n * @memberof Mailbox.prototype\n * @desc Return the messages selected by the user.\n * @returns Message instances\n */\n Mailbox.prototype.$selectedMessages = function() {\n return _.filter(this.$messages, function(message) { return message.selected; });\n };\n\n /**\n * @function $selectedCount\n * @memberof Mailbox.prototype\n * @desc Return the number of messages selected by the user.\n * @returns the number of selected messages\n */\n Mailbox.prototype.$selectedCount = function() {\n return this.$selectedMessages().length;\n };\n\n /**\n * @function isSelectedMessage\n * @memberof Mailbox.prototype\n * @desc Check if the specified message is displayed in the detailed view.\n * @param {string} messageId\n * @returns true if the specified message is displayed\n */\n Mailbox.prototype.isSelectedMessage = function(messageId) {\n return this.selectedMessage == messageId;\n };\n\n /**\n * @function $selectedMessage\n * @memberof Mailbox.prototype\n * @desc Return the currently visible message.\n * @returns a Message instance or undefined if no message is displayed\n */\n Mailbox.prototype.$selectedMessage = function() {\n var _this = this;\n\n return _.find(this.$messages, function(message) { return message.uid == _this.selectedMessage; });\n };\n\n /**\n * @function $selectedMessageIndex\n * @memberof Mailbox.prototype\n * @desc Return the index of the currently visible message.\n * @returns a number or undefined if no message is selected\n */\n Mailbox.prototype.$selectedMessageIndex = function() {\n return this.uidsMap[this.selectedMessage];\n };\n\n /**\n * @function hasSelectedMessage\n * @memberof Mailbox.prototype\n * @desc Check if a message is selected.\n * @returns true if the a message is selected\n */\n Mailbox.prototype.hasSelectedMessage = function() {\n return angular.isDefined(this.selectedMessage);\n };\n\n /**\n * @function $filter\n * @memberof Mailbox.prototype\n * @desc Fetch the messages metadata of the mailbox\n * @param {object} [sort] - sort preferences. Defaults to descendent by date.\n * @param {string} sort.match - either AND or OR\n * @param {string} sort.sort - either arrival, subject, from, to, date, or size\n * @param {boolean} sort.asc - sort is ascendant if true\n * @param {object[]} [filters] - list of filters for the query\n * @param {string} filters.searchBy - either subject, from, to, cc, or body\n * @param {string} filters.searchInput - the search string to match\n * @param {boolean} filters.negative - negate the condition\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$filter = function(sortingAttributes, filters) {\n var _this = this, options = {};\n\n if (!angular.isDefined(this.unseenCount))\n this.unseenCount = 0;\n\n Mailbox.$timeout(function() {\n _this.$isLoading = true;\n });\n\n return Mailbox.$Preferences.ready().then(function() {\n\n if (Mailbox.$refreshTimeout)\n Mailbox.$timeout.cancel(Mailbox.$refreshTimeout);\n\n if (sortingAttributes)\n // Sorting preferences are common to all mailboxes\n angular.extend(Mailbox.$query, sortingAttributes);\n\n angular.extend(options, { sortingAttributes: Mailbox.$query });\n if (angular.isDefined(filters)) {\n options.filters = _.reject(filters, function(filter) {\n return !filter.searchInput || filter.searchInput.length === 0;\n });\n // Decompose filters that match two fields\n _.forEach(options.filters, function(filter) {\n var secondFilter,\n match = filter.searchBy.match(/(\\w+)_or_(\\w+)/);\n if (match) {\n options.sortingAttributes.match = 'OR';\n filter.searchBy = match[1];\n secondFilter = angular.copy(filter);\n secondFilter.searchBy = match[2];\n options.filters.push(secondFilter);\n }\n });\n }\n\n // Restart the refresh timer, if needed\n if (!Mailbox.$virtualMode) {\n var refreshViewCheck = Mailbox.$Preferences.defaults.SOGoRefreshViewCheck;\n if (refreshViewCheck && refreshViewCheck != 'manually') {\n var f = angular.bind(_this, Mailbox.prototype.$filter, null, filters);\n Mailbox.$refreshTimeout = Mailbox.$timeout(f, refreshViewCheck.timeInterval()*1000);\n }\n }\n\n var futureMailboxData = Mailbox.$$resource.post(_this.id, 'view', options);\n return _this.$unwrap(futureMailboxData);\n });\n };\n\n /**\n * @function $loadMessage\n * @memberof Mailbox.prototype\n * @desc Check if the message is loaded and in any case, fetch more messages headers from the server.\n * @returns true if the message metadata are already fetched\n */\n Mailbox.prototype.$loadMessage = function(messageId) {\n var startIndex = this.uidsMap[messageId],\n endIndex,\n index,\n max = this.$messages.length,\n loaded = false,\n uids,\n futureHeadersData;\n if (angular.isDefined(this.uidsMap[messageId]) && startIndex < this.$messages.length) {\n // Index is valid\n if (angular.isDefined(this.$messages[startIndex].subject)) {// || this.$messages[startIndex].loading) {\n // Message headers are loaded or data is coming\n loaded = true;\n }\n\n // Preload more headers if possible\n endIndex = Math.min(startIndex + Mailbox.PRELOAD.LOOKAHEAD, max - 1);\n if (angular.isDefined(this.$messages[endIndex].subject) ||\n angular.isDefined(this.$messages[endIndex].loading)) {\n index = Math.max(startIndex - Mailbox.PRELOAD.LOOKAHEAD, 0);\n if (!angular.isDefined(this.$messages[index].subject) &&\n !angular.isDefined(this.$messages[index].loading)) {\n // Previous messages not loaded; preload more headers further up\n endIndex = startIndex;\n startIndex = Math.max(startIndex - Mailbox.PRELOAD.SIZE, 0);\n }\n }\n else\n // Next messages not load; preload more headers further down\n endIndex = Math.min(startIndex + Mailbox.PRELOAD.SIZE, max - 1);\n\n if (!angular.isDefined(this.$messages[startIndex].subject) &&\n !angular.isDefined(this.$messages[startIndex].loading) ||\n !angular.isDefined(this.$messages[endIndex].subject) &&\n !angular.isDefined(this.$messages[endIndex].loading)) {\n\n for (uids = []; startIndex < endIndex && startIndex < max; startIndex++) {\n if (angular.isDefined(this.$messages[startIndex].subject) || this.$messages[startIndex].loading) {\n // Message at this index is already loaded; increase the end index\n endIndex++;\n }\n else {\n // Message at this index will be loaded\n uids.push(this.$messages[startIndex].uid);\n this.$messages[startIndex].loading = true;\n }\n }\n\n Mailbox.$log.debug('Loading UIDs ' + uids.join(' '));\n futureHeadersData = Mailbox.$$resource.post(this.id, 'headers', {uids: uids});\n this.$unwrapHeaders(futureHeadersData);\n }\n }\n return loaded;\n };\n\n /**\n * @function isEditable\n * @memberof Mailbox.prototype\n * @desc Checks if the mailbox is editable based on its type.\n * @returns true if the mailbox is not a special folder.\n */\n Mailbox.prototype.isEditable = function() {\n return this.type == 'folder';\n };\n\n /**\n * @function isNoInferiors\n * @memberof Mailbox.prototype\n * @desc Checks if the mailbox can contain submailboxes\n * @returns true if the mailbox can not contain submailboxes\n */\n Mailbox.prototype.isNoInferiors = function() {\n return this.flags.indexOf('noinferiors') >= 0;\n };\n\n /**\n * @function isNoSelect\n * @memberof Mailbox.prototype\n * @desc Checks if the mailbox can be selected\n * @returns true if the mailbox can not be selected\n */\n Mailbox.prototype.isNoSelect = function() {\n return this.flags.indexOf('noselect') >= 0;\n };\n\n /**\n * @function $rename\n * @memberof AddressBook.prototype\n * @desc Rename the addressbook and keep the list sorted\n * @param {string} name - the new name\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$rename = function() {\n var _this = this,\n findParent,\n parent,\n children,\n i;\n\n if (this.name == this.$shadowData.name) {\n // Name hasn't changed\n return Mailbox.$q.when();\n }\n\n // Local recursive function\n findParent = function(parent, children) {\n var parentMailbox = null,\n mailbox = _.find(children, function(o) {\n return o.path == _this.path;\n });\n if (mailbox) {\n parentMailbox = parent;\n }\n else {\n angular.forEach(children, function(o) {\n if (!parentMailbox && o.children && o.children.length > 0) {\n parentMailbox = findParent(o, o.children);\n }\n });\n }\n return parentMailbox;\n };\n\n // Find mailbox parent\n parent = findParent(null, this.$account.$mailboxes);\n if (parent === null)\n children = this.$account.$mailboxes;\n else\n children = parent.children;\n\n // Find index of mailbox among siblings\n i = _.indexOf(_.map(children, 'id'), this.id);\n\n return this.$save().then(function(data) {\n var sibling, oldPath = _this.path;\n _this.init(data); // update the path and id\n\n // Move mailbox among its siblings according to its new name\n children.splice(i, 1);\n sibling = _.find(children, function(o) {\n Mailbox.$log.debug(o.name + ' ? ' + _this.name);\n return (o.type == 'folder' && o.name.localeCompare(_this.name) > 0);\n });\n if (sibling) {\n i = _.indexOf(_.map(children, 'id'), sibling.id);\n }\n else {\n i = children.length;\n }\n children.splice(i, 0, _this);\n\n // Update the path and id of children\n var pathRE = new RegExp('^' + oldPath);\n var _updateChildren = function(mailbox) {\n _.forEach(mailbox.children, function(child) {\n child.path = child.path.replace(pathRE, _this.path);\n child.id = child.$id();\n _updateChildren(child);\n });\n };\n _updateChildren(_this);\n });\n };\n\n /**\n * @function $compact\n * @memberof Mailbox.prototype\n * @desc Compact the mailbox\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$compact = function() {\n var _this = this;\n return Mailbox.$$resource.post(this.id, 'expunge')\n .then(function(data) {\n // Update inbox quota\n if (data.quotas)\n _this.$account.updateQuota(data.quotas);\n });\n };\n\n /**\n * @function $setFolderAs\n * @memberof Mailbox.prototype\n * @desc Set a folder as Drafts/Sent/Trash\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$setFolderAs = function(type) {\n return Mailbox.$$resource.post(this.id, 'setAs' + type + 'Folder');\n };\n\n /**\n * @function $emptyTrash\n * @memberof Mailbox.prototype\n * @desc Empty the Trash folder.\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$emptyTrash = function() {\n var _this = this;\n\n return Mailbox.$$resource.post(this.id, 'emptyTrash').then(function(data) {\n // Remove all messages from the mailbox\n _this.$messages = [];\n _this.uidsMap = {};\n _this.unseenCount = 0;\n\n // If we had any submailboxes, lets do a refresh of the mailboxes list\n if (angular.isDefined(_this.children) && _this.children.length)\n _this.$account.$getMailboxes({reload: true});\n\n // Update inbox quota\n if (data.quotas)\n _this.$account.updateQuota(data.quotas);\n });\n };\n\n /**\n * @function $markAsRead\n * @memberof Mailbox.prototype\n * @desc Mark all messages from folder as read\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$markAsRead = function() {\n return Mailbox.$$resource.post(this.id, 'markRead');\n };\n\n /**\n * @function $flagMessages\n * @memberof Mailbox.prototype\n * @desc Add or remove a flag on a message set\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$flagMessages = function(messages, flags, operation) {\n var data = {msgUIDs: _.map(messages, 'uid'),\n flags: flags,\n operation: operation};\n\n return Mailbox.$$resource.post(this.id, 'addOrRemoveLabel', data).then(function() {\n return messages;\n });\n };\n\n /**\n * @function saveSelectedMessages\n * @memberof Mailbox.prototype\n * @desc Download the selected messages\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.saveSelectedMessages = function() {\n var data, options, selectedMessages, selectedUIDs;\n\n selectedMessages = _.filter(this.$messages, function(message) { return message.selected; });\n selectedUIDs = _.map(selectedMessages, 'uid');\n data = { uids: selectedUIDs };\n options = { filename: l('Saved Messages.zip') };\n\n return Mailbox.$$resource.download(this.id, 'saveMessages', {uids: selectedUIDs});\n };\n\n /**\n * @function exportFolder\n * @memberof Mailbox.prototype\n * @desc Export this mailbox\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.exportFolder = function() {\n var options;\n\n options = { filename: this.name + '.zip' };\n\n return Mailbox.$$resource.download(this.id, 'exportFolder', null, options);\n };\n\n /**\n * @function $delete\n * @memberof Mailbox.prototype\n * @desc Delete the mailbox from the server\n * @param {object} [options] - additional options (use {withoutTrash: true} to delete immediately)\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$delete = function(options) {\n var _this = this;\n\n return Mailbox.$$resource.post(this.id, 'delete', options)\n .then(function() {\n _this.$account.$getMailboxes({reload: true});\n return true;\n });\n };\n\n /**\n * @function $_deleteMessages\n * @memberof Mailbox.prototype\n * @desc Delete multiple messages from Mailbox object.\n * @param {string[]} uids - the messages uids\n * @param {object[]} messages - the Message instances\n * @return the index of the first deleted message\n */\n Mailbox.prototype.$_deleteMessages = function(uids, messages) {\n var _this = this, selectedUIDs, _$messages, unseen, firstIndex = this.$messages.length;\n\n // Decrement the unseen count\n unseen = _.filter(messages, function(message, i) { return !message.isread; });\n this.unseenCount -= unseen.length;\n\n // Remove messages from $messages and uidsMap\n _.forEachRight(this.$messages, function(message, index) {\n var selectedIndex = _.findIndex(uids, function(uid) {\n return message.uid == uid;\n });\n if (selectedIndex > -1) {\n uids.splice(selectedIndex, 1);\n delete _this.uidsMap[message.uid];\n if (message.uid == _this.selectedMessage)\n delete _this.selectedMessage;\n _this.$messages.splice(index, 1);\n if (index < firstIndex)\n firstIndex = index;\n }\n else {\n _this.uidsMap[message.uid] -= uids.length;\n }\n });\n\n // Return the index of the first deleted message\n return firstIndex;\n };\n\n /**\n * @function $deleteMessages\n * @memberof Mailbox.prototype\n * @desc Delete multiple messages from mailbox.\n * @param {object} [options] - additional options (use {withoutTrash: true} to delete immediately)\n * @return a promise of the HTTP operation\n */\n Mailbox.prototype.$deleteMessages = function(messages, options) {\n var _this = this, uids, data;\n\n uids = _.map(messages, 'uid');\n data = { uids: uids };\n if (options) angular.extend(data, options);\n\n return Mailbox.$$resource.post(this.id, 'batchDelete', data)\n .then(function(data) {\n // Update inbox quota\n if (data.quotas)\n _this.$account.updateQuota(data.quotas);\n\n return _this.$_deleteMessages(uids, messages);\n });\n };\n\n /**\n * @function $markOrUnMarkMessagesAsJunk\n * @memberof Mailbox.prototype\n * @desc Mark messages as junk/not junk\n * @return a promise of the HTTP operation\n */\n Mailbox.prototype.$markOrUnMarkMessagesAsJunk = function(messages) {\n var _this = this,\n uids = _.map(messages, 'uid'),\n method = (this.type == 'junk' ? 'markMessagesAsNotJunk' : 'markMessagesAsJunk');\n\n return Mailbox.$$resource.post(this.id, method, {uids: uids});\n };\n\n /**\n * @function $copyMessages\n * @memberof Mailbox.prototype\n * @desc Copy multiple messages from the current mailbox to a target one\n * @return a promise of the HTTP operation\n */\n Mailbox.prototype.$copyMessages = function(messages, folder) {\n var _this = this,\n uids = _.map(messages, 'uid');\n\n return Mailbox.$$resource.post(this.id, 'copyMessages', {uids: uids, folder: folder})\n .then(function(data) {\n // Update inbox quota\n if (data.quotas)\n _this.$account.updateQuota(data.quotas);\n });\n };\n\n /**\n * @function $moveMessages\n * @memberof Mailbox.prototype\n * @desc Move multiple messages from the current mailbox to a target one\n * @return a promise of the HTTP operation\n */\n Mailbox.prototype.$moveMessages = function(messages, folder) {\n var _this = this, uids;\n\n uids = _.map(messages, 'uid');\n return Mailbox.$$resource.post(this.id, 'moveMessages', {uids: uids, folder: folder})\n .then(function() {\n return _this.$_deleteMessages(uids, messages);\n });\n };\n\n /**\n * @function $reset\n * @memberof Mailbox.prototype\n * @desc Reset the original state the mailbox's data.\n */\n Mailbox.prototype.$reset = function() {\n var _this = this;\n angular.forEach(this.$shadowData, function(value, key) {\n delete _this[key];\n });\n angular.extend(this, this.$shadowData);\n this.$shadowData = this.$omit();\n };\n\n /**\n * @function $save\n * @memberof Mailbox.prototype\n * @desc Save the mailbox to the server. This currently can only affect the name of the mailbox.\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$save = function() {\n var _this = this;\n\n return Mailbox.$$resource.save(this.id, this.$omit()).then(function(data) {\n // Make a copy of the data for an eventual reset\n _this.$shadowData = _this.$omit();\n Mailbox.$log.debug(JSON.stringify(data, undefined, 2));\n return data;\n }, function(response) {\n Mailbox.$log.error(JSON.stringify(response.data, undefined, 2));\n // Restore previous version\n _this.$reset();\n return response.data;\n });\n };\n\n /**\n * @function $newMailbox\n * @memberof Mailbox.prototype\n * @desc Create a new mailbox on the server and refresh the list of mailboxes.\n * @returns a promise of the HTTP operations\n */\n Mailbox.prototype.$newMailbox = function(path, name) {\n return this.$account.$newMailbox(path, name);\n };\n\n /**\n * @function $omit\n * @memberof Mailbox.prototype\n * @desc Return a sanitized object used to send to the server.\n * @return an object literal copy of the Mailbox instance\n */\n Mailbox.prototype.$omit = function() {\n var mailbox = {};\n angular.forEach(this, function(value, key) {\n if (key != 'constructor' &&\n key != 'children' &&\n key != 'headers' &&\n key != 'uids' &&\n key != 'uidsMap' &&\n key[0] != '$') {\n mailbox[key] = value;\n }\n });\n return mailbox;\n };\n\n /**\n * @function $unwrap\n * @memberof Mailbox.prototype\n * @desc Unwrap a promise and instanciate new Message objects using received data.\n * @param {promise} futureMailboxData - a promise of the Mailbox's metadata\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$unwrap = function(futureMailboxData) {\n var _this = this,\n deferred = Mailbox.$q.defer();\n\n this.$futureMailboxData = futureMailboxData;\n this.$futureMailboxData.then(function(data) {\n Mailbox.$timeout(function() {\n var uids, headers;\n\n if (!data.uids || _this.$topIndex > data.uids.length - 1)\n _this.$topIndex = 0;\n\n _this.init(data);\n\n if (_this.uids) {\n Mailbox.$log.debug('unwrapping ' + _this.uids.length + ' messages');\n\n // First entry of 'headers' are keys\n headers = _.invokeMap(_this.headers[0], 'toLowerCase');\n _this.headers.splice(0, 1);\n\n // First entry of 'uids' are keys when threaded view is enabled\n if (_this.threaded) {\n uids = _this.uids[0];\n _this.uids.splice(0, 1);\n }\n\n // Instanciate Message objects\n _.reduce(_this.uids, function(msgs, msg, i) {\n var data;\n if (_this.threaded)\n data = _.zipObject(uids, msg);\n else\n data = {uid: msg.toString()};\n\n // Build map of UID <=> index\n _this.uidsMap[data.uid] = i;\n\n msgs.push(new Mailbox.$Message(_this.$account.id, _this, data, true));\n\n return msgs;\n }, _this.$messages);\n\n // Extend Message objects with received headers\n _.forEach(_this.headers, function(data) {\n var msg = _.zipObject(headers, data),\n i = _this.uidsMap[msg.uid.toString()];\n _.extend(_this.$messages[i], msg);\n });\n }\n Mailbox.$log.debug('mailbox ' + _this.id + ' ready');\n _this.$isLoading = false;\n deferred.resolve(_this.$messages);\n });\n }, function(data) {\n angular.extend(_this, data);\n _this.isError = true;\n deferred.reject();\n });\n\n return deferred.promise;\n };\n\n /**\n * @function $unwrapHeaders\n * @memberof Mailbox.prototype\n * @desc Unwrap a promise and extend matching Message objects using received data.\n * @param {promise} futureHeadersData - a promise of some messages metadata\n */\n Mailbox.prototype.$unwrapHeaders = function(futureHeadersData) {\n var _this = this;\n\n futureHeadersData.then(function(data) {\n Mailbox.$timeout(function() {\n var headers, j;\n if (data.length > 0) {\n // First entry of 'headers' are keys\n headers = _.invokeMap(data[0], 'toLowerCase');\n data.splice(0, 1);\n _.forEach(data, function(messageHeaders) {\n messageHeaders = _.zipObject(headers, messageHeaders);\n j = _this.uidsMap[messageHeaders.uid.toString()];\n if (angular.isDefined(j)) {\n _.extend(_this.$messages[j], messageHeaders);\n }\n });\n }\n });\n });\n };\n\n /**\n * @function $updateSubscribe\n * @memberof Mailbox.prototype\n * @desc Update mailbox subscription state with server.\n */\n Mailbox.prototype.$updateSubscribe = function() {\n var action = this.subscribed? 'subscribe' : 'unsubscribe';\n\n Mailbox.$$resource.post(this.id, action);\n };\n\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @name Message\n * @constructor\n * @param {string} accountId - the account ID\n * @param {string} mailboxPath - an array of the mailbox path components\n * @param {object} futureAddressBookData - either an object literal or a promise\n * @param {bool} lazy - do \"lazy loading\" so we are very quick at initializing message instances\n */\n function Message(accountId, mailbox, futureMessageData, lazy) {\n this.accountId = accountId;\n this.$mailbox = mailbox;\n this.$hasUnsafeContent = false;\n this.$loadUnsafeContent = false;\n this.editable = {to: [], cc: [], bcc: []};\n this.selected = false;\n\n // Data is immediately available\n if (typeof futureMessageData.then !== 'function') {\n //console.debug(JSON.stringify(futureMessageData, undefined, 2));\n if (angular.isUndefined(lazy) || !lazy) {\n angular.extend(this, futureMessageData);\n this.$formatFullAddresses();\n }\n this.uid = parseInt(futureMessageData.uid);\n }\n else {\n // The promise will be unwrapped first\n this.$unwrap(futureMessageData);\n }\n }\n\n /**\n * @memberof Message\n * @desc The factory we'll use to register with Angular\n * @returns the Message constructor\n */\n Message.$factory = ['$q', '$timeout', '$log', 'sgSettings', 'sgMessage_STATUS', 'Resource', 'Preferences', function($q, $timeout, $log, Settings, Message_STATUS, Resource, Preferences) {\n angular.extend(Message, {\n STATUS: Message_STATUS,\n $q: $q,\n $timeout: $timeout,\n $log: $log,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Mail', Settings.activeUser()),\n $avatar: angular.bind(Preferences, Preferences.avatar)\n });\n // Initialize tags form user's defaults\n Preferences.ready().then(function() {\n if (Preferences.defaults.SOGoMailLabelsColors) {\n Message.$tags = Preferences.defaults.SOGoMailLabelsColors;\n }\n if (Preferences.defaults.SOGoMailDisplayRemoteInlineImages &&\n Preferences.defaults.SOGoMailDisplayRemoteInlineImages == 'always') {\n Message.$displayRemoteInlineImages = true;\n }\n });\n\n return Message; // return constructor\n }];\n\n /**\n * @module SOGo.MailerUI\n * @desc Factory registration of Message in Angular module.\n */\n try {\n angular.module('SOGo.MailerUI');\n }\n catch(e) {\n angular.module('SOGo.MailerUI', ['SOGo.Common']);\n }\n angular.module('SOGo.MailerUI')\n .constant('sgMessage_STATUS', {\n NOT_LOADED: 0,\n DELAYED_LOADING: 1,\n LOADING: 2,\n LOADED: 3,\n DELAYED_MS: 300\n })\n .factory('Message', Message.$factory);\n\n /**\n * @function filterTags\n * @memberof Message.prototype\n * @desc Search for tags (ie., mail labels) matching some criterias\n * @param {string} search - the search string to match\n * @returns a collection of strings\n */\n Message.filterTags = function(query, excludedTags) {\n var re = new RegExp(query, 'i'),\n results = [];\n\n _.forEach(_.keys(Message.$tags), function(tag) {\n var pair = Message.$tags[tag];\n if (pair[0].search(re) != -1) {\n if (!_.includes(excludedTags, tag))\n results.push({ name: tag, description: pair[0], color: pair[1] });\n }\n });\n\n return results;\n };\n\n /**\n * @function $absolutePath\n * @memberof Message.prototype\n * @desc Build the path of the message\n * @returns a string representing the path relative to the mail module\n */\n Message.prototype.$absolutePath = function(options) {\n var _this = this, id = this.id;\n\n function buildPath() {\n var path;\n path = _.map(_this.$mailbox.path.split('/'), function(component) {\n return 'folder' + component.asCSSIdentifier();\n });\n path.splice(0, 0, _this.accountId); // insert account ID\n return path.join('/');\n }\n\n if (angular.isUndefined(this.id) || options && options.nocache) {\n this.id = buildPath() + '/' + this.uid; // add message UID\n id = this.id;\n }\n if (options && options.asDraft && this.draftId) {\n id = buildPath() + '/' + this.draftId; // add draft ID\n }\n\n return id;\n };\n\n /**\n * @function $setUID\n * @memberof Message.prototype\n * @desc Change the UID of the message. This happens when saving a draft.\n * @param {number} uid - the new message UID\n */\n Message.prototype.$setUID = function(uid) {\n var oldUID = (this.uid || -1), _this = this, index;\n\n if (oldUID != parseInt(uid)) {\n this.uid = parseInt(uid);\n this.$absolutePath({nocache: true});\n if (oldUID > -1) {\n oldUID = oldUID.toString();\n if (angular.isDefined(this.$mailbox.uidsMap[oldUID])) {\n index = this.$mailbox.uidsMap[oldUID];\n this.$mailbox.uidsMap[uid] = index;\n delete this.$mailbox.uidsMap[oldUID];\n\n // Update messages list of mailbox\n _.forEach(['from', 'to', 'subject'], function(attr) {\n _this.$mailbox.$messages[index][attr] = _this[attr];\n });\n }\n }\n else {\n // Refresh selected folder if it's the drafts mailbox\n if (this.$mailbox.constructor.selectedFolder &&\n this.$mailbox.constructor.selectedFolder.type == 'draft') {\n this.$mailbox.constructor.selectedFolder.$filter();\n }\n }\n }\n };\n\n /**\n * @function $formatFullAddresses\n * @memberof Message.prototype\n * @desc Format all sender and recipients addresses with a complete description (name ).\n * This function also generates the avatar URL for each email address and a short name\n */\n Message.prototype.$formatFullAddresses = function() {\n var _this = this;\n var identities = _.map(_this.$mailbox.$account.identities, 'email');\n\n // Build long representation of email addresses\n _.forEach(['from', 'to', 'cc', 'bcc', 'reply-to'], function(type) {\n _.forEach(_this[type], function(data) {\n if (data.name && data.name != data.email) {\n data.full = data.name + ' <' + data.email + '>';\n\n if (data.name.length < 10)\n // Name is already short\n data.shortname = data.name;\n else if (data.name.split(' ').length)\n // If we have \"Alice Foo\" or \"Foo, Alice\" as name, we grab \"Alice\"\n data.shortname = _.first(_.last(data.name.split(/, */)).split(/ +/)).replace('\\'','');\n }\n else if (data.email) {\n data.full = '<' + data.email + '>';\n data.shortname = data.email.split('@')[0];\n }\n\n data.image = Message.$avatar(data.email, 32);\n\n // If the current user is the recepient, overwrite\n // the short name with 'me'\n if (_.indexOf(identities, data.email) >= 0)\n data.shortname = l('me');\n });\n });\n };\n\n /**\n * @function $shortRecipients\n * @memberof Message.prototype\n * @desc Format all recipients into a very compact string\n * @returns a compacted string of all recipients\n */\n Message.prototype.$shortRecipients = function(max) {\n var _this = this, result = [], count = 0, total = 0;\n\n // Build short representation of email addresses\n _.forEach(['to', 'cc', 'bcc'], function(type) {\n total += _this[type]? _this[type].length : 0;\n _.forEach(_this[type], function(data, i) {\n if (count < max)\n result.push(data.shortname);\n count++;\n });\n });\n\n if (total > max)\n result.push(l('and %{0} more...', (total - max)));\n\n return result.join(', ');\n };\n\n /**\n * @function $shortAddress\n * @memberof Message.prototype\n * @desc Format the first address of a specific type with a short description.\n * @returns a string of the name or the email of the envelope address type\n */\n Message.prototype.$shortAddress = function(type) {\n var address = '';\n if (this[type] && this[type].length > 0) {\n address = this[type][0].name || this[type][0].email || '';\n }\n\n return address;\n };\n\n /**\n * @function allowReplyAll\n * @memberof Message.prototype\n * @desc Check if 'Reply to All' is an appropriate action on the message.\n * @returns true if the message is not a draft and has more than one recipient\n */\n Message.prototype.allowReplyAll = function() {\n var recipientsCount = 0;\n recipientsCount = _.reduce(['to', 'cc'], _.bind(function(count, type) {\n if (this[type])\n return count + this[type].length;\n else\n return count;\n }, this), recipientsCount);\n\n return !this.isDraft && recipientsCount > 1;\n };\n\n /**\n * @function loadUnsafeContent\n * @memberof Message.prototype\n * @desc Mark the message to load unsafe resources when calling $content().\n */\n Message.prototype.loadUnsafeContent = function() {\n this.$loadUnsafeContent = true;\n };\n\n /**\n * @function $content\n * @memberof Message.prototype\n * @desc Get the message body as accepted by SCE (Angular Strict Contextual Escaping).\n * @returns the HTML representation of the body\n */\n Message.prototype.$content = function() {\n var _this = this,\n parts = [],\n _visit = function(part) {\n part.msgclass = 'msg-attachment-other';\n if (part.type == 'UIxMailPartAlternativeViewer') {\n _visit(_.find(part.content, function(alternatePart) {\n return part.preferredPart == alternatePart.contentType;\n }));\n }\n // Can be used for UIxMailPartMixedViewer, UIxMailPartMessageViewer, and UIxMailPartSignedViewer\n else if (angular.isArray(part.content)) {\n if (part.type == 'UIxMailPartSignedViewer' && part['supports-smime'] === 1) {\n // First line in a h1, others each in a p\n var formattedMessage = \"

\" + part.error.replace(/\\n/, \"

\");\n formattedMessage = formattedMessage.replace(/\\n/g, \"

\") + \"

\";\n _this.$smime = {\n validSignature: part.valid,\n message: formattedMessage\n };\n }\n _.forEach(part.content, function(mixedPart) {\n _visit(mixedPart);\n });\n }\n else {\n if (angular.isUndefined(part.safeContent)) {\n // Keep a copy of the original content\n part.safeContent = part.content;\n _this.$hasUnsafeContent |= (part.safeContent.indexOf(' unsafe-') > -1);\n }\n if (part.type == 'UIxMailPartHTMLViewer') {\n part.html = true;\n if (_this.$loadUnsafeContent || Message.$displayRemoteInlineImages) {\n if (angular.isUndefined(part.unsafeContent)) {\n part.unsafeContent = document.createElement('div');\n part.unsafeContent.innerHTML = part.safeContent;\n angular.forEach(['src', 'data', 'classid', 'background', 'style'], function(suffix) {\n var elements = part.unsafeContent.querySelectorAll('[unsafe-' + suffix + ']'),\n element,\n value,\n i;\n for (i = 0; i < elements.length; i++) {\n element = angular.element(elements[i]);\n value = element.attr('unsafe-' + suffix);\n element.attr(suffix, value);\n element.removeAttr('unsafe-' + suffix);\n }\n });\n _this.$hasUnsafeContent = false;\n }\n part.content = part.unsafeContent.innerHTML;\n }\n else {\n part.content = part.safeContent;\n }\n parts.push(part);\n }\n else if (part.type == 'UIxMailPartICalViewer' ||\n part.type == 'UIxMailPartImageViewer' ||\n part.type == 'UIxMailPartLinkViewer') {\n\n if (part.type == 'UIxMailPartImageViewer')\n part.msgclass = 'msg-attachment-image';\n else if (part.type == 'UIxMailPartLinkViewer')\n part.msgclass = 'msg-attachment-link';\n\n // Trusted content that can be compiled (Angularly-speaking)\n part.compile = true;\n parts.push(part);\n }\n else {\n part.html = true;\n part.content = part.safeContent;\n parts.push(part);\n }\n }\n };\n\n if (this.parts)\n _visit(this.parts);\n\n return parts;\n };\n\n /**\n * @function $editableContent\n * @memberof Message.prototype\n * @desc First, fetch the draft ID that corresponds to the temporary draft object on the SOGo server.\n * Secondly, fetch the editable message body along with other metadata such as the recipients.\n * @returns the HTML representation of the body\n */\n Message.prototype.$editableContent = function() {\n var _this = this;\n\n return Message.$$resource.fetch(this.$absolutePath(), 'edit').then(function(data) {\n angular.extend(_this, data);\n return Message.$$resource.fetch(_this.$absolutePath({asDraft: true}), 'edit').then(function(data) {\n // Try to match a known account identity from the specified \"from\" address\n var identity = _.find(_this.$mailbox.$account.identities, function(identity) {\n return data.from.toLowerCase().indexOf(identity.email) !== -1;\n });\n if (identity)\n data.from = identity.full;\n Message.$log.debug('editable = ' + JSON.stringify(data, undefined, 2));\n angular.extend(_this.editable, data);\n return data.text;\n });\n });\n };\n\n /**\n * @function $plainContent\n * @memberof Message.prototype\n * @returns the a plain text representation of the subject and body\n */\n Message.prototype.$plainContent = function() {\n return Message.$$resource.fetch(this.$absolutePath(), 'viewplain');\n };\n\n /**\n * @function addTag\n * @memberof Message.prototype\n * @desc Add a mail tag on the current message.\n * @param {string} tag - the tag name\n * @returns a promise of the HTTP operation\n */\n Message.prototype.addTag = function(tag) {\n return this.$addOrRemoveTag('add', tag);\n };\n\n /**\n * @function removeTag\n * @memberof Message.prototype\n * @desc Remove a mail tag from the current message.\n * @param {string} tag - the tag name\n * @returns a promise of the HTTP operation\n */\n Message.prototype.removeTag = function(tag) {\n return this.$addOrRemoveTag('remove', tag);\n };\n\n /**\n * @function $addOrRemoveTag\n * @memberof Message.prototype\n * @desc Add or remove a mail tag on the current message.\n * @param {string} operation - the operation name to perform\n * @param {string} tag - the tag name\n * @returns a promise of the HTTP operation\n */\n Message.prototype.$addOrRemoveTag = function(operation, tag) {\n var data = {\n operation: operation,\n msgUIDs: [this.uid],\n flags: tag\n };\n\n if (tag)\n return Message.$$resource.post(this.$mailbox.$id(), 'addOrRemoveLabel', data);\n };\n\n /**\n * @function $imipAction\n * @memberof Message.prototype\n * @desc Perform IMIP actions on the current message.\n * @param {string} path - the path of the IMIP calendar part\n * @param {string} action - the the IMIP action to perform\n * @param {object} data - the delegation info\n */\n Message.prototype.$imipAction = function(path, action, data) {\n var _this = this;\n Message.$$resource.post([this.$absolutePath(), path].join('/'), action, data).then(function(data) {\n Message.$timeout(function() {\n _this.$reload();\n });\n });\n };\n\n /**\n * @function $sendMDN\n * @memberof Message.prototype\n * @desc Send MDN response for current email message\n */\n Message.prototype.$sendMDN = function() {\n this.shouldAskReceipt = 0;\n return Message.$$resource.post(this.$absolutePath(), 'sendMDN');\n };\n\n /**\n * @function $deleteAttachment\n * @memberof Message.prototype\n * @desc Delete an attachment from a message being composed\n * @param {string} filename - the filename of the attachment to delete\n */\n Message.prototype.$deleteAttachment = function(filename) {\n var action = 'deleteAttachment?filename=' + filename;\n var _this = this;\n Message.$$resource.post(this.$absolutePath({asDraft: true}), action).then(function(data) {\n Message.$timeout(function() {\n _this.editable.attachmentAttrs = _.filter(_this.editable.attachmentAttrs, function(attachment) {\n return attachment.filename != filename;\n });\n });\n });\n };\n\n /**\n * @function $markAsFlaggedOrUnflagged\n * @memberof Message.prototype\n * @desc Add or remove a the \\\\Flagged flag on the current message.\n * @returns a promise of the HTTP operation\n */\n Message.prototype.toggleFlag = function() {\n var _this = this,\n action = 'markMessageFlagged';\n\n if (this.isflagged)\n action = 'markMessageUnflagged';\n\n return Message.$$resource.post(this.$absolutePath(), action).then(function(data) {\n Message.$timeout(function() {\n _this.isflagged = !_this.isflagged;\n });\n });\n };\n\n /**\n * @function $isLoading\n * @memberof Message.prototype\n * @returns true if the Message content is still being retrieved from server after a specific delay\n * @see sgMessage_STATUS\n */\n Message.prototype.$isLoading = function() {\n return this.$loaded == Message.STATUS.LOADING;\n };\n\n /**\n * @function $reload\n * @memberof Message.prototype\n * @desc Fetch the viewable message body along with other metadata such as the list of attachments.\n * @param {object} [options] - set {useCache: true} to use already fetched data\n * @returns a promise of the HTTP operation\n */\n Message.prototype.$reload = function(options) {\n var _this = this, futureMessageData;\n\n if (options && options.useCache && this.$futureMessageData) {\n if (!this.isread) {\n Message.$$resource.fetch(this.$absolutePath(), 'markMessageRead').then(function() {\n Message.$timeout(function() {\n _this.isread = true;\n _this.$mailbox.unseenCount--;\n });\n });\n }\n return this;\n }\n\n futureMessageData = Message.$$resource.fetch(this.$absolutePath(options), 'view');\n\n return this.$unwrap(futureMessageData);\n };\n\n /**\n * @function $reply\n * @memberof Message.prototype\n * @desc Prepare a new Message object as a reply to the sender.\n * @returns a promise of the HTTP operations\n */\n Message.prototype.$reply = function() {\n return this.$newDraft('reply');\n };\n\n /**\n * @function $replyAll\n * @memberof Message.prototype\n * @desc Prepare a new Message object as a reply to the sender and all recipients.\n * @returns a promise of the HTTP operations\n */\n Message.prototype.$replyAll = function() {\n return this.$newDraft('replyall');\n };\n\n /**\n * @function $forward\n * @memberof Message.prototype\n * @desc Prepare a new Message object as a forward.\n * @returns a promise of the HTTP operations\n */\n Message.prototype.$forward = function() {\n return this.$newDraft('forward');\n };\n\n /**\n * @function $newDraft\n * @memberof Message.prototype\n * @desc Prepare a new Message object as a reply or a forward of the current message and associated\n * to the draft mailbox.\n * @see {@link Account.$newMessage}\n * @see {@link Message.$editableContent}\n * @see {@link Message.$reply}\n * @see {@link Message.$replyAll}\n * @see {@link Message.$forwad}\n * @param {string} action - the HTTP action to perform on the message\n * @returns a promise of the HTTP operations\n */\n Message.prototype.$newDraft = function(action) {\n var _this = this;\n\n // Query server for draft folder and draft UID\n return Message.$$resource.fetch(this.$absolutePath(), action).then(function(data) {\n var mailbox, message;\n Message.$log.debug('New ' + action + ': ' + JSON.stringify(data, undefined, 2));\n mailbox = _this.$mailbox.$account.$getMailboxByPath(data.mailboxPath);\n message = new Message(data.accountId, mailbox, data);\n // Fetch draft initial data\n return Message.$$resource.fetch(message.$absolutePath({asDraft: true}), 'edit').then(function(data) {\n Message.$log.debug('New ' + action + ': ' + JSON.stringify(data, undefined, 2) + ' original UID: ' + _this.uid);\n angular.extend(message.editable, data);\n\n // We keep a reference to our original message in order to update the flags\n message.origin = {message: _this, action: action};\n return message;\n });\n });\n };\n\n /**\n * @function $save\n * @memberof Message.prototype\n * @desc Save the message to the server.\n * @returns a promise of the HTTP operation\n */\n Message.prototype.$save = function() {\n var _this = this,\n data = this.editable;\n\n Message.$log.debug('save = ' + JSON.stringify(data, undefined, 2));\n\n return Message.$$resource.save(this.$absolutePath({asDraft: true}), data).then(function(response) {\n Message.$log.debug('save = ' + JSON.stringify(response, undefined, 2));\n _this.$setUID(response.uid);\n _this.$reload(); // fetch a new viewable version of the message\n _this.isNew = false;\n });\n };\n\n /**\n * @function $send\n * @memberof Message.prototype\n * @desc Send the message.\n * @returns a promise of the HTTP operation\n */\n Message.prototype.$send = function() {\n var _this = this,\n data = angular.copy(this.editable);\n\n Message.$log.debug('send = ' + JSON.stringify(data, undefined, 2));\n\n return Message.$$resource.post(this.$absolutePath({asDraft: true}), 'send', data).then(function(response) {\n if (response.status == 'success') {\n if (angular.isDefined(_this.origin)) {\n if (_this.origin.action.startsWith('reply'))\n _this.origin.message.isanswered = true;\n else if (_this.origin.action == 'forward')\n _this.origin.message.isforwarded = true;\n }\n return response;\n }\n else {\n return Message.$q.reject(response.data);\n }\n });\n };\n\n /**\n * @function $unwrap\n * @memberof Message.prototype\n * @desc Unwrap a promise.\n * @param {promise} futureMessageData - a promise of some of the Message's data\n */\n Message.prototype.$unwrap = function(futureMessageData) {\n var _this = this;\n\n // Message is not loaded yet\n this.$loaded = Message.STATUS.DELAYED_LOADING;\n Message.$timeout(function() {\n if (_this.$loaded != Message.STATUS.LOADED)\n _this.$loaded = Message.STATUS.LOADING;\n }, Message.STATUS.DELAYED_MS);\n\n // Resolve and expose the promise\n this.$futureMessageData = futureMessageData.then(function(data) {\n // Calling $timeout will force Angular to refresh the view\n if (_this.isread === 0) {\n _this.isread = true;\n _this.$mailbox.unseenCount--;\n }\n return Message.$timeout(function() {\n angular.extend(_this, data);\n _this.$formatFullAddresses();\n _this.$loadUnsafeContent = false;\n _this.$loaded = Message.STATUS.LOADED;\n return _this;\n });\n });\n\n return this.$futureMessageData;\n };\n\n /**\n * @function $omit\n * @memberof Message.prototype\n * @desc Return a sanitized object used to send to the server.\n * @return an object literal copy of the Message instance\n */\n Message.prototype.$omit = function(options) {\n var message = {},\n privateAttributes = options && options.privateAttributes;\n angular.forEach(this, function(value, key) {\n if (key != 'constructor' && key[0] != '$' || privateAttributes) {\n message[key] = value;\n }\n });\n\n return message;\n };\n\n /**\n * @function download\n * @memberof Message.prototype\n * @desc Download the current message\n * @returns a promise of the HTTP operation\n */\n Message.prototype.download = function() {\n var data, options;\n\n data = { uids: [this.uid] };\n options = { filename: this.subject + '.zip' };\n\n return Message.$$resource.download(this.$mailbox.id, 'saveMessages', data, options);\n };\n\n /**\n * @function downloadAttachments\n * @memberof Message.prototype\n * @desc Download an archive of all attachments\n * @returns a promise of the HTTP operation\n */\n Message.prototype.downloadAttachments = function() {\n var options;\n\n options = { filename: l('attachments') + \"-\" + this.uid + \".zip\" };\n\n return Message.$$resource.download(this.$absolutePath(), 'archiveAttachments', null, options);\n };\n\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @name VirtualMailbox\n * @constructor\n * @param {object} account - the mail account associated with the virtual search\n */\n function VirtualMailbox(account) {\n this.$account = account;\n }\n\n /**\n * @memberof VirtualMailbox\n * @desc The factory we'll use to register with Angular\n * @returns the VirtualMailbox constructor\n */\n VirtualMailbox.$factory = ['$q', '$timeout', '$log', 'sgSettings', 'Resource', 'Message', 'Mailbox', 'sgMailbox_PRELOAD', function($q, $timeout, $log, Settings, Resource, Mailbox, Message, PRELOAD) {\n angular.extend(VirtualMailbox, {\n $q: $q,\n $timeout: $timeout,\n $log: $log,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Mail', Settings.activeUser()),\n $Message: Message,\n selectedFolder: null,\n PRELOAD: PRELOAD\n });\n\n return VirtualMailbox; // return constructor\n }];\n\n /**\n * @module SOGo.MailerUI\n * @desc Factory registration of VirtualMailbox in Angular module.\n */\n try {\n angular.module('SOGo.MailerUI');\n }\n catch(e) {\n angular.module('SOGo.MailerUI', ['SOGo.Common']);\n }\n angular.module('SOGo.MailerUI')\n .constant('sgMailbox_PRELOAD', {\n LOOKAHEAD: 50,\n SIZE: 100\n })\n .factory('VirtualMailbox', VirtualMailbox.$factory);\n\n /**\n * @memberof VirtualMailbox\n * @desc Build the path of the virtual mailbox (or account only).\n * @param {string} accountId - the account ID\n * @returns a string representing the path relative to the mail module\n */\n VirtualMailbox.$absolutePath = function(accountId) {\n return [accountId, \"virtual\"].join('/');\n };\n\n /**\n * @function init\n * @memberof VirtualMailbox.prototype\n * @desc Extend instance with new data and compute additional attributes.\n * @param {object} data - attributes of mailbox\n */\n VirtualMailbox.prototype.init = function(data) {\n this.$isLoading = false;\n this.$mailboxes = [];\n this.uidsMap = {};\n angular.extend(this, data);\n this.id = this.$id();\n };\n\n VirtualMailbox.prototype.setMailboxes = function(data) {\n this.$mailboxes = data;\n\n _.forEach(this.$mailboxes, function(mailbox) {\n mailbox.$messages = [];\n mailbox.uidsMap = {};\n });\n };\n\n VirtualMailbox.prototype.startSearch = function(match, params) {\n var _this = this,\n search = VirtualMailbox.$q.when();\n\n this.$isLoading = true;\n\n _.forEach(this.$mailboxes, function(mailbox) {\n search = search.then(function() {\n if (_this.$isLoading) {\n VirtualMailbox.$log.debug(\"searching mailbox \" + mailbox.path);\n return mailbox.$filter( {sort: \"date\", asc: false, match: match}, params);\n }\n });\n });\n\n search.finally(function() {\n _this.$isLoading = false;\n });\n };\n\n VirtualMailbox.prototype.stopSearch = function() {\n VirtualMailbox.$log.debug(\"stopping search...\");\n this.$isLoading = false;\n };\n\n /**\n * @function selectFolder\n * @memberof VirtualMailbox.prototype\n * @desc A no-op for virtual mailbox\n */\n VirtualMailbox.prototype.selectFolder = function() {\n return;\n };\n\n /**\n * @function resetSelectedMessage\n * @memberof VirtualMailbox.prototype\n * @desc Delete 'selectedMessage' attribute of all submailboxes.\n */\n VirtualMailbox.prototype.resetSelectedMessage = function() {\n _.forEach(this.$mailboxes, function(mailbox) {\n delete mailbox.selectedMessage;\n });\n };\n\n /**\n * @function hasSelectedMessage\n * @memberof VirtualMailbox.prototype\n * @desc Check if a message is selected among the resulting mailboxes\n * @returns true if one message is selected\n */\n VirtualMailbox.prototype.hasSelectedMessage = function() {\n return angular.isDefined(_.find(this.$mailboxes, function(mailbox) {\n return angular.isDefined(mailbox.selectedMessage);\n }));\n };\n\n /**\n * @function isSelectedMessage\n * @memberof VirtualMailbox.prototype\n * @desc Check if the message of the specified mailbox is selected.\n * @param {string} messageId\n * @param {string} mailboxPath\n * @returns true if the specified message is selected\n */\n VirtualMailbox.prototype.isSelectedMessage = function(messageId, mailboxPath) {\n return angular.isDefined(_.find(this.$mailboxes, function(mailbox) {\n return mailbox.path == mailboxPath && mailbox.selectedMessage == messageId;\n }));\n };\n\n /**\n * @function getLength\n * @memberof VirtualMailbox.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the number of items in the mailbox\n */\n VirtualMailbox.prototype.getLength = function() {\n var len = 0;\n\n if (!angular.isDefined(this.$mailboxes))\n return len;\n\n _.forEach(this.$mailboxes, function(mailbox) {\n len += mailbox.$messages.length;\n });\n\n return len;\n };\n\n /**\n * @function getItemAtIndex\n * @memberof VirtualMailbox.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the message as the specified index\n */\n VirtualMailbox.prototype.getItemAtIndex = function(index) {\n var i, j, k, mailbox, message;\n\n if (angular.isDefined(this.$mailboxes) && index >= 0) {\n i = 0;\n for (j = 0; j < this.$mailboxes.length; j++) {\n mailbox = this.$mailboxes[j];\n for (k = 0; k < mailbox.$messages.length; i++, k++) {\n message = mailbox.$messages[k];\n if (i == index) {\n if (mailbox.$loadMessage(message.uid))\n return message;\n }\n }\n }\n }\n\n return null;\n };\n\n /**\n * @function $id\n * @memberof VirtualMailbox.prototype\n * @desc Build the unique ID to identified the mailbox.\n * @returns a string representing the path relative to the mail module\n */\n VirtualMailbox.prototype.$id = function() {\n return VirtualMailbox.$absolutePath(this.$account.id);\n };\n\n /**\n * @function $selectedMessages\n * @memberof VirtualMailbox.prototype\n * @desc Return an associative array of the selected messages for each mailbox. Keys are the mailboxes ids.\n * @returns an associative array\n */\n VirtualMailbox.prototype.$selectedMessages = function() {\n var messagesMap = {};\n return _.transform(this.$mailboxes, function(messagesMap, mailbox) {\n messagesMap[mailbox.id] = mailbox.$selectedMessages();\n }, {});\n };\n\n /**\n * @function $selectedCount\n * @memberof VirtualMailbox.prototype\n * @desc Return the number of messages selected by the user.\n * @returns the number of selected messages\n */\n VirtualMailbox.prototype.$selectedCount = function() {\n return _.sum(_.invokeMap(this.$mailboxes, '$selectedCount'));\n };\n\n /**\n * @function $flagMessages\n * @memberof VirtualMailbox.prototype\n * @desc Add or remove a flag on a message set\n * @param {object} messagesMap\n * @param {array} flags\n * @param {string} operation\n * @returns a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$flagMessages = function(messagesMap, flags, operation) {\n var data = {\n flags: flags,\n operation: operation\n };\n var allMessages = [];\n var promises = [];\n\n _.forEach(messagesMap, function(messages, id) {\n if (messages.length > 0) {\n var uids = _.map(messages, 'uid');\n allMessages.push(messages);\n var promise = VirtualMailbox.$$resource.post(id, 'addOrRemoveLabel', _.assign(data, {msgUIDs: uids}));\n promises.push(promise);\n }\n });\n\n return VirtualMailbox.$q.all(promises).then(function() {\n return _.flatten(allMessages);\n });\n };\n\n /**\n * @function $deleteMessages\n * @memberof VirtualMailbox.prototype\n * @desc Delete multiple messages from mailbox.\n * @param {object} messagesMap\n * @return a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$deleteMessages = function(messagesMap) {\n var promises = [];\n\n _.forEach(messagesMap, function(messages, id) {\n if (messages.length > 0) {\n var mailbox = messages[0].$mailbox;\n var promise = mailbox.$deleteMessages(messages);\n promises.push(promise);\n }\n });\n\n return VirtualMailbox.$q.all(promises);\n };\n\n /**\n * @function $markOrUnMarkMessagesAsJunk\n * @memberof VirtualMailbox.prototype\n * @desc Mark messages as junk/not junk\n * @param {object} messagesMap\n * @return a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$markOrUnMarkMessagesAsJunk = function(messagesMap) {\n var promises = [];\n\n _.forEach(messagesMap, function(messages, id) {\n if (messages.length > 0) {\n var mailbox = messages[0].$mailbox;\n var promise = mailbox.$markOrUnMarkMessagesAsJunk(messages);\n promises.push(promise);\n }\n });\n\n return VirtualMailbox.$q.all(promises);\n };\n\n /**\n * @function $copyMessages\n * @memberof VirtualMailbox.prototype\n * @desc Copy multiple messages from the current mailbox to a target one\n * @param {object} messagesMap\n * @param {string} folder\n * @return a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$copyMessages = function(messagesMap, folder) {\n var promises = [];\n\n _.forEach(messagesMap, function(messages, id) {\n if (messages.length > 0) {\n var mailbox = messages[0].$mailbox;\n var promise = mailbox.$copyMessages(messages, folder);\n promises.push(promise);\n }\n });\n\n return VirtualMailbox.$q.all(promises);\n };\n\n /**\n * @function $moveMessages\n * @memberof VirtualMailbox.prototype\n * @desc Move multiple messages from the current mailbox to a target one\n * @param {object} messagesMap\n * @param {string} folder\n * @return a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$moveMessages = function(messagesMap, folder) {\n var promises = [];\n\n _.forEach(messagesMap, function(messages, id) {\n if (messages.length > 0) {\n var mailbox = messages[0].$mailbox;\n var promise = mailbox.$moveMessages(messages, folder);\n promises.push(promise);\n }\n });\n\n return VirtualMailbox.$q.all(promises);\n };\n\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n MailboxController.$inject = ['$window', '$scope', '$timeout', '$q', '$state', '$mdDialog', '$mdToast', 'stateAccounts', 'stateAccount', 'stateMailbox', 'sgHotkeys', 'encodeUriFilter', 'sgSettings', 'sgFocus', 'Dialog', 'Account', 'Mailbox'];\n function MailboxController($window, $scope, $timeout, $q, $state, $mdDialog, $mdToast, stateAccounts, stateAccount, stateMailbox, sgHotkeys, encodeUriFilter, sgSettings, focus, Dialog, Account, Mailbox) {\n var vm = this,\n defaultWindowTitle = angular.element($window.document).find('title').attr('sg-default') || \"SOGo\",\n hotkeys = [];\n\n // Expose controller for eventual popup windows\n $window.$mailboxController = vm;\n\n vm.service = Mailbox;\n vm.accounts = stateAccounts;\n vm.account = stateAccount;\n vm.selectedFolder = stateMailbox;\n vm.selectMessage = selectMessage;\n vm.messageDialog = null; // also access from Message controller\n vm.toggleMessageSelection = toggleMessageSelection;\n vm.sort = sort;\n vm.sortedBy = sortedBy;\n vm.searchMode = searchMode;\n vm.cancelSearch = cancelSearch;\n vm.newMessage = newMessage;\n vm.mode = { search: false, multiple: 0 };\n vm.confirmDeleteSelectedMessages = confirmDeleteSelectedMessages;\n vm.markOrUnMarkMessagesAsJunk = markOrUnMarkMessagesAsJunk;\n vm.copySelectedMessages = copySelectedMessages;\n vm.moveSelectedMessages = moveSelectedMessages;\n vm.markSelectedMessagesAsFlagged = markSelectedMessagesAsFlagged;\n vm.markSelectedMessagesAsUnread = markSelectedMessagesAsUnread;\n vm.markSelectedMessagesAsRead = markSelectedMessagesAsRead;\n vm.selectAll = selectAll;\n vm.unselectMessages = unselectMessages;\n\n\n stateMailbox.selectFolder();\n\n _registerHotkeys(hotkeys);\n\n // Expunge mailbox when leaving the Mail module\n angular.element($window).on('beforeunload', _compactBeforeUnload);\n $scope.$on('$destroy', function() {\n angular.element($window).off('beforeunload', _compactBeforeUnload);\n // Deregister hotkeys\n _.forEach(hotkeys, function(key) {\n sgHotkeys.deregisterHotkey(key);\n });\n });\n\n // Update window's title with unseen messages count of selected mailbox\n $scope.$watch(function() { return vm.selectedFolder.unseenCount; }, function(unseenCount) {\n var title = defaultWindowTitle + ' - ';\n if (unseenCount)\n title += '(' + unseenCount + ') ';\n title += vm.selectedFolder.$displayName;\n $window.document.title = title;\n });\n\n\n function _registerHotkeys(keys) {\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_search'),\n description: l('Search'),\n callback: searchMode\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_compose'),\n description: l('Write a new message'),\n callback: function($event) {\n if (vm.messageDialog === null)\n newMessage($event);\n }\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_junk'),\n description: l('Mark the selected messages as junk'),\n callback: markOrUnMarkMessagesAsJunk\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'space',\n description: l('Toggle item'),\n callback: toggleMessageSelection\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'shift+space',\n description: l('Toggle range of items'),\n callback: toggleMessageSelection\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'up',\n description: l('View next item'),\n callback: _nextMessage,\n preventInClass: ['sg-mail-part']\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'down',\n description: l('View previous item'),\n callback: _previousMessage,\n preventInClass: ['sg-mail-part']\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'shift+up',\n description: l('Add next item to selection'),\n callback: _addNextMessageToSelection,\n preventInClass: ['sg-mail-part']\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'shift+down',\n description: l('Add previous item to selection'),\n callback: _addPreviousMessageToSelection,\n preventInClass: ['sg-mail-part']\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'backspace',\n description: l('Delete selected message or folder'),\n callback: confirmDeleteSelectedMessages\n }));\n\n // Register the hotkeys\n _.forEach(keys, function(key) {\n sgHotkeys.registerHotkey(key);\n });\n }\n\n function _compactBeforeUnload(event) {\n return vm.selectedFolder.$compact();\n }\n\n function sort(field) {\n vm.selectedFolder.$filter({ sort: field });\n }\n\n function sortedBy(field) {\n return Mailbox.$query.sort == field;\n }\n\n function searchMode() {\n vm.mode.search = true;\n focus('search');\n }\n\n function cancelSearch() {\n vm.mode.search = false;\n vm.selectedFolder.$filter().then(function() {\n if (vm.selectedFolder.selectedMessage) {\n $timeout(function() {\n vm.selectedFolder.$topIndex = vm.selectedFolder.uidsMap[vm.selectedFolder.selectedMessage];\n });\n }\n });\n }\n\n function newMessage($event, inPopup) {\n var message;\n\n if (vm.messageDialog === null) {\n if (inPopup)\n _newMessageInPopup();\n else {\n message = vm.account.$newMessage();\n vm.messageDialog = $mdDialog\n .show({\n parent: angular.element(document.body),\n targetEvent: $event,\n clickOutsideToClose: false,\n escapeToClose: false,\n templateUrl: 'UIxMailEditor',\n controller: 'MessageEditorController',\n controllerAs: 'editor',\n locals: {\n stateAccount: vm.account,\n stateMessage: message\n }\n })\n .finally(function() {\n vm.messageDialog = null;\n });\n }\n }\n }\n\n function _newMessageInPopup() {\n var url = [sgSettings.baseURL(),\n 'UIxMailPopupView#!/Mail',\n vm.account.id,\n // The double-encoding is necessary\n encodeUriFilter(encodeUriFilter(vm.selectedFolder.path)),\n 'new']\n .join('/'),\n wId = vm.selectedFolder.$id() + '/' + Math.random(0, 1000);\n console.debug(url);\n $window.open(url, wId,\n [\"width=680\",\n \"height=520\",\n \"resizable=1\",\n \"scrollbars=1\",\n \"toolbar=0\",\n \"location=0\",\n \"directories=0\",\n \"status=0\",\n \"menubar=0\",\n \"copyhistory=0\"]\n .join(','));\n }\n\n /**\n * User has pressed up arrow key\n */\n function _nextMessage($event) {\n var index = vm.selectedFolder.$selectedMessageIndex();\n\n if (angular.isDefined(index)) {\n index--;\n if (vm.selectedFolder.$topIndex > 0)\n vm.selectedFolder.$topIndex--;\n }\n else {\n // No message is selected, show oldest message\n index = vm.selectedFolder.getLength() - 1;\n vm.selectedFolder.$topIndex = vm.selectedFolder.getLength();\n }\n\n if (index > -1)\n selectMessage(vm.selectedFolder.$messages[index]);\n\n $event.preventDefault();\n\n return index;\n }\n\n /**\n * User has pressed the down arrow key\n */\n function _previousMessage($event) {\n var index = vm.selectedFolder.$selectedMessageIndex();\n\n if (angular.isDefined(index)) {\n index++;\n if (vm.selectedFolder.$topIndex < vm.selectedFolder.getLength())\n vm.selectedFolder.$topIndex++;\n }\n else\n // No message is selected, show newest\n index = 0;\n\n if (index < vm.selectedFolder.getLength())\n selectMessage(vm.selectedFolder.$messages[index]);\n else\n index = -1;\n\n $event.preventDefault();\n\n return index;\n }\n\n function _addNextMessageToSelection($event) {\n var index;\n\n if (vm.selectedFolder.hasSelectedMessage()) {\n index = _nextMessage($event);\n if (index >= 0)\n toggleMessageSelection($event, vm.selectedFolder.$messages[index]);\n }\n }\n\n function _addPreviousMessageToSelection($event) {\n var index;\n\n if (vm.selectedFolder.hasSelectedMessage()) {\n index = _previousMessage($event);\n if (index >= 0)\n toggleMessageSelection($event, vm.selectedFolder.$messages[index]);\n }\n }\n\n function selectMessage(message) {\n if (Mailbox.$virtualMode)\n $state.go('mail.account.virtualMailbox.message', {mailboxId: encodeUriFilter(message.$mailbox.path), messageId: message.uid});\n else\n $state.go('mail.account.mailbox.message', {messageId: message.uid});\n }\n\n function toggleMessageSelection($event, message) {\n var folder = vm.selectedFolder,\n selectedIndex, nextSelectedIndex, i;\n\n if (!message)\n message = folder.$selectedMessage();\n message.selected = !message.selected;\n vm.mode.multiple += message.selected? 1 : -1;\n\n // Select closest range of messages when shift key is pressed\n if ($event.shiftKey && folder.$selectedCount() > 1) {\n selectedIndex = folder.uidsMap[message.uid];\n // Search for next selected message above\n nextSelectedIndex = selectedIndex - 2;\n while (nextSelectedIndex >= 0 &&\n !folder.$messages[nextSelectedIndex].selected)\n nextSelectedIndex--;\n if (nextSelectedIndex < 0) {\n // Search for next selected message bellow\n nextSelectedIndex = selectedIndex + 2;\n while (nextSelectedIndex < folder.getLength() &&\n !folder.$messages[nextSelectedIndex].selected)\n nextSelectedIndex++;\n }\n if (nextSelectedIndex >= 0 && nextSelectedIndex < folder.getLength()) {\n for (i = Math.min(selectedIndex, nextSelectedIndex);\n i <= Math.max(selectedIndex, nextSelectedIndex);\n i++)\n folder.$messages[i].selected = true;\n }\n }\n\n $event.preventDefault();\n $event.stopPropagation();\n }\n\n /**\n * Batch operations\n */\n\n function _currentMailboxes() {\n if (Mailbox.$virtualMode)\n return vm.selectedFolder.$mailboxes;\n else\n return [vm.selectedFolder];\n }\n\n // Unselect current message and cleverly load the next message.\n // This function must not be called in virtual mode.\n function _unselectMessage(message, index) {\n var nextMessage, previousMessage, nextIndex = index;\n vm.mode.multiple = vm.selectedFolder.$selectedCount();\n if (message) {\n // Select either the next or previous message\n if (index > 0) {\n nextIndex -= 1;\n nextMessage = vm.selectedFolder.$messages[nextIndex];\n }\n if (index < vm.selectedFolder.$messages.length)\n previousMessage = vm.selectedFolder.$messages[index];\n if (nextMessage) {\n if (nextMessage.isread && previousMessage && !previousMessage.isread) {\n nextIndex = index;\n nextMessage = previousMessage;\n }\n }\n else if (previousMessage) {\n nextIndex = index;\n nextMessage = previousMessage;\n }\n if (nextMessage) {\n vm.selectedFolder.$topIndex = nextIndex;\n $state.go('mail.account.mailbox.message', { messageId: nextMessage.uid });\n }\n else {\n $state.go('mail.account.mailbox');\n }\n }\n else {\n $timeout(function() {\n console.warn('go to mailbox');\n $state.go('mail.account.mailbox');\n });\n }\n }\n\n function confirmDeleteSelectedMessages($event) {\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n\n if (vm.messageDialog === null && _.size(selectedMessages) > 0)\n vm.messageDialog = Dialog.confirm(l('Confirmation'),\n l('Are you sure you want to delete the selected messages?'),\n { ok: l('Delete') })\n .then(function() {\n var deleteSelectedMessage = vm.selectedFolder.hasSelectedMessage();\n vm.selectedFolder.$deleteMessages(selectedMessages).then(function(index) {\n if (Mailbox.$virtualMode) {\n // When performing an advanced search, we refresh the view if the selected message\n // was deleted, but only once all promises have completed.\n if (deleteSelectedMessage)\n $state.go('mail.account.virtualMailbox');\n }\n else {\n // In normal mode, we immediately unselect the selected message.\n _unselectMessage(deleteSelectedMessage, index);\n }\n }, function(response) {\n vm.messageDialog = Dialog.confirm(l('Warning'),\n l('The messages could not be moved to the trash folder. Would you like to delete them immediately?'),\n { ok: l('Delete') })\n .then(function() {\n vm.selectedFolder.$deleteMessages(selectedMessages, { withoutTrash: true }).then(function(index) {\n if (Mailbox.$virtualMode) {\n // When performing an advanced search, we refresh the view if the selected message\n // was deleted, but only once all promises have completed.\n if (deleteSelectedMessage)\n $state.go('mail.account.virtualMailbox');\n }\n else {\n // In normal mode, we immediately unselect the selected message.\n _unselectMessage(deleteSelectedMessage, index);\n }\n });\n });\n });\n })\n .finally(function() {\n vm.messageDialog = null;\n });\n\n $event.preventDefault();\n }\n\n function markOrUnMarkMessagesAsJunk() {\n var moveSelectedMessage = vm.selectedFolder.hasSelectedMessage();\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n if (_.size(selectedMessages) === 0 && moveSelectedMessage)\n selectedMessages = [vm.selectedFolder.$selectedMessage()];\n if (_.size(selectedMessages) > 0)\n vm.selectedFolder.$markOrUnMarkMessagesAsJunk(selectedMessages).then(function() {\n var dstFolder = '/' + vm.account.id + '/folderINBOX';\n if (vm.selectedFolder.type != 'junk') {\n dstFolder = '/' + vm.account.$getMailboxByType('junk').id;\n }\n vm.selectedFolder.$moveMessages(selectedMessages, dstFolder).then(function(index) {\n if (Mailbox.$virtualMode) {\n // When performing an advanced search, we refresh the view if the selected message\n // was deleted, but only once all promises have completed.\n if (moveSelectedMessage)\n $state.go('mail.account.virtualMailbox');\n }\n else {\n // In normal mode, we immediately unselect the selected message.\n _unselectMessage(moveSelectedMessage, index);\n }\n });\n });\n }\n\n function copySelectedMessages(dstFolder) {\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n if (_.size(selectedMessages) > 0)\n vm.selectedFolder.$copyMessages(selectedMessages, '/' + dstFolder).then(function() {\n $mdToast.show(\n $mdToast.simple()\n .content(l('%{0} message(s) copied', vm.selectedFolder.$selectedCount()))\n .position('top right')\n .hideDelay(2000));\n });\n }\n\n function moveSelectedMessages(dstFolder) {\n var moveSelectedMessage = vm.selectedFolder.hasSelectedMessage();\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n var count = vm.selectedFolder.$selectedCount();\n if (_.size(selectedMessages) > 0)\n vm.selectedFolder.$moveMessages(selectedMessages, '/' + dstFolder).then(function(index) {\n $mdToast.show(\n $mdToast.simple()\n .content(l('%{0} message(s) moved', count))\n .position('top right')\n .hideDelay(2000));\n if (Mailbox.$virtualMode) {\n // When performing an advanced search, we refresh the view if the selected message\n // was moved, but only once all promises have completed.\n if (moveSelectedMessage)\n $state.go('mail.account.virtualMailbox');\n }\n else {\n // In normal mode, we immediately unselect the selected message.\n _unselectMessage(moveSelectedMessage, index);\n }\n });\n }\n\n function selectAll() {\n var count = 0;\n _.forEach(_currentMailboxes(), function(folder) {\n var i = 0, length = folder.$messages.length;\n for (; i < length; i++)\n folder.$messages[i].selected = true;\n count += length;\n });\n vm.mode.multiple = count;\n }\n\n function unselectMessages() {\n _.forEach(_currentMailboxes(), function(folder) {\n _.forEach(folder.$messages, function(message) {\n message.selected = false;\n });\n });\n vm.mode.multiple = 0;\n }\n\n function markSelectedMessagesAsFlagged() {\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n if (_.size(selectedMessages) > 0)\n vm.selectedFolder.$flagMessages(selectedMessages, '\\\\Flagged', 'add').then(function(messages) {\n _.forEach(messages, function(message) {\n message.isflagged = true;\n });\n });\n }\n\n function markSelectedMessagesAsUnread() {\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n if (_.size(selectedMessages) > 0) {\n vm.selectedFolder.$flagMessages(selectedMessages, 'seen', 'remove').then(function(messages) {\n _.forEach(messages, function(message) {\n if (message.isread)\n message.$mailbox.unseenCount++;\n message.isread = false;\n });\n });\n }\n }\n\n function markSelectedMessagesAsRead() {\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n if (_.size(selectedMessages) > 0) {\n vm.selectedFolder.$flagMessages(selectedMessages, 'seen', 'add').then(function(messages) {\n _.forEach(messages, function(message) {\n if (!message.isread)\n message.$mailbox.unseenCount--;\n message.isread = true;\n });\n });\n }\n }\n\n }\n\n angular\n .module('material.components.virtualRepeat')\n .decorator('mdVirtualRepeatContainerDirective', mdVirtualRepeatContainerDirectiveDecorator);\n\n /**\n * @ngInject\n */\n mdVirtualRepeatContainerDirectiveDecorator.$inject = ['$delegate'];\n function mdVirtualRepeatContainerDirectiveDecorator($delegate) {\n $delegate[0].controller.prototype.resetScroll = function() {\n // Don't scroll to top if current virtual repeater is the messages list\n // but do update the container size\n if (this.$element.parent().attr('id') == 'messagesList')\n this.updateSize();\n else\n this.scrollTo(0);\n };\n return $delegate;\n }\n\n angular\n .module('SOGo.MailerUI')\n .controller('MailboxController', MailboxController);\n})();\n\n","/* -*- Mode: js; indent-tabs-mode: nil; js-indent-level: 2; -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n MailboxesController.$inject = ['$scope', '$state', '$timeout', '$window', '$mdDialog', '$mdToast', '$mdMedia', '$mdSidenav', 'sgConstant', 'sgFocus', 'encodeUriFilter', 'Dialog', 'sgSettings', 'sgHotkeys', 'Account', 'Mailbox', 'VirtualMailbox', 'User', 'Preferences', 'stateAccounts'];\n function MailboxesController($scope, $state, $timeout, $window, $mdDialog, $mdToast, $mdMedia, $mdSidenav, sgConstant, focus, encodeUriFilter, Dialog, Settings, sgHotkeys, Account, Mailbox, VirtualMailbox, User, Preferences, stateAccounts) {\n var vm = this,\n account,\n mailbox,\n hotkeys = [];\n\n vm.service = Mailbox;\n vm.accounts = stateAccounts;\n vm.toggleAccountState = toggleAccountState;\n vm.subscribe = subscribe;\n vm.newFolder = newFolder;\n vm.delegate = delegate;\n vm.editFolder = editFolder;\n vm.revertEditing = revertEditing;\n vm.selectFolder = selectFolder;\n vm.saveFolder = saveFolder;\n vm.compactFolder = compactFolder;\n vm.emptyTrashFolder = emptyTrashFolder;\n vm.confirmDelete = confirmDelete;\n vm.markFolderRead = markFolderRead;\n vm.share = share;\n vm.setFolderAs = setFolderAs;\n vm.refreshUnseenCount = refreshUnseenCount;\n vm.isDroppableFolder = isDroppableFolder;\n vm.dragSelectedMessages = dragSelectedMessages;\n\n // Advanced search options\n vm.showingAdvancedSearch = false;\n vm.currentSearchParam = '';\n vm.addSearchParam = addSearchParam;\n vm.newSearchParam = newSearchParam;\n vm.showAdvancedSearch = showAdvancedSearch;\n vm.hideAdvancedSearch = hideAdvancedSearch;\n vm.toggleAdvancedSearch = toggleAdvancedSearch;\n vm.search = {\n options: {'': '', // no placeholder when no criteria is active\n subject: l('Enter Subject'),\n from: l('Enter From'),\n to: l('Enter To'),\n cc: l('Enter Cc'),\n body: l('Enter Body')\n },\n mailbox: 'INBOX',\n subfolders: 1,\n match: 'AND',\n params: []\n };\n\n\n Preferences.ready().then(function() {\n vm.showSubscribedOnly = Preferences.defaults.SOGoMailShowSubscribedFoldersOnly;\n });\n\n vm.refreshUnseenCount();\n\n _registerHotkeys(hotkeys);\n\n $scope.$on('$destroy', function() {\n // Deregister hotkeys\n _.forEach(hotkeys, function(key) {\n sgHotkeys.deregisterHotkey(key);\n });\n });\n\n\n function _registerHotkeys(keys) {\n keys.push(sgHotkeys.createHotkey({\n key: 'backspace',\n description: l('Delete selected message or folder'),\n callback: function() {\n if (Mailbox.selectedFolder && !Mailbox.selectedFolder.hasSelectedMessage())\n confirmDelete(Mailbox.selectedFolder);\n }\n }));\n\n // Register the hotkeys\n _.forEach(keys, function(key) {\n sgHotkeys.registerHotkey(key);\n });\n }\n\n function showAdvancedSearch(path) {\n vm.showingAdvancedSearch = true;\n vm.search.mailbox = path;\n // Close sidenav on small devices\n if (!$mdMedia(sgConstant['gt-md']))\n $mdSidenav('left').close();\n }\n\n function hideAdvancedSearch() {\n vm.showingAdvancedSearch = false;\n vm.service.$virtualMode = false;\n\n account = vm.accounts[0];\n mailbox = vm.searchPreviousMailbox;\n $state.go('mail.account.mailbox', { accountId: account.id, mailboxId: encodeUriFilter(mailbox.path) });\n }\n\n function toggleAdvancedSearch() {\n if (Mailbox.selectedFolder.$isLoading) {\n // Stop search\n vm.virtualMailbox.stopSearch();\n }\n else {\n // Start search\n var root, mailboxes = [],\n _visit = function(folders) {\n _.forEach(folders, function(o) {\n mailboxes.push(o);\n if (o.children && o.children.length > 0) {\n _visit(o.children);\n }\n });\n };\n\n vm.virtualMailbox = new VirtualMailbox(vm.accounts[0]);\n\n // Don't set the previous selected mailbox if we're in virtual mode\n // That allows users to do multiple advanced search but return\n // correctly to the previously selected mailbox once done.\n if (!Mailbox.$virtualMode)\n vm.searchPreviousMailbox = Mailbox.selectedFolder;\n\n Mailbox.selectedFolder = vm.virtualMailbox;\n Mailbox.$virtualMode = true;\n\n if (angular.isDefined(vm.search.mailbox)) {\n root = vm.accounts[0].$getMailboxByPath(vm.search.mailbox);\n mailboxes.push(root);\n if (vm.search.subfolders && root.children.length)\n _visit(root.children);\n }\n else {\n mailboxes = vm.accounts[0].$flattenMailboxes();\n }\n\n vm.virtualMailbox.setMailboxes(mailboxes);\n vm.virtualMailbox.startSearch(vm.search.match, vm.search.params);\n $state.go('mail.account.virtualMailbox', { accountId: vm.accounts[0].id });\n }\n }\n\n function addSearchParam(v) {\n vm.currentSearchParam = v;\n focus('advancedSearch');\n return false;\n }\n\n function newSearchParam(pattern) {\n if (pattern.length && vm.currentSearchParam.length) {\n var n = 0, searchParam = vm.currentSearchParam;\n if (pattern.startsWith(\"!\")) {\n n = 1;\n pattern = pattern.substring(1).trim();\n }\n vm.currentSearchParam = '';\n return { searchBy: searchParam, searchInput: pattern, negative: n };\n }\n }\n\n function toggleAccountState(account) {\n account.$expanded = !account.$expanded;\n account.$flattenMailboxes({ reload: true, saveState: true });\n // Fire a window resize to recompute the virtual-repeater.\n // This is a fix until the following issue is officially resolved:\n // https://github.com/angular/material/issues/7309\n $timeout(function() {\n angular.element($window).triggerHandler('resize');\n }, 150);\n }\n\n function subscribe(account) {\n $mdDialog.show({\n templateUrl: account.id + '/subscribe',\n controller: SubscriptionsDialogController,\n controllerAs: 'subscriptions',\n clickOutsideToClose: true,\n escapeToClose: true,\n locals: {\n srcAccount: account\n }\n }).finally(function() {\n account.$getMailboxes({reload: true});\n });\n\n /**\n * @ngInject\n */\n SubscriptionsDialogController.$inject = ['$scope', '$mdDialog', 'srcAccount'];\n function SubscriptionsDialogController($scope, $mdDialog, srcAccount) {\n var vm = this;\n\n vm.loading = true;\n vm.filter = { name: '' };\n vm.account = new Account({\n id: srcAccount.id,\n name: srcAccount.name\n });\n vm.close = close;\n\n vm.account.$getMailboxes({ reload: true, all: true }).then(function() {\n vm.loading = false;\n });\n\n function close() {\n $mdDialog.cancel();\n }\n }\n }\n\n function newFolder(parentFolder) {\n Dialog.prompt(l('New Folder...'),\n l('Enter the new name of your folder'))\n .then(function(name) {\n parentFolder.$newMailbox(parentFolder.id, name)\n .then(function() {\n // success\n }, function(data, status) {\n Dialog.alert(l('An error occured while creating the mailbox \"%{0}\".', name),\n l(data.error));\n });\n });\n }\n\n function delegate(account) {\n $mdDialog.show({\n templateUrl: account.id + '/delegation', // UI/Templates/MailerUI/UIxMailUserDelegation.wox\n controller: MailboxDelegationController,\n controllerAs: 'delegate',\n clickOutsideToClose: true,\n escapeToClose: true,\n locals: {\n User: User,\n account: account\n }\n });\n\n /**\n * @ngInject\n */\n MailboxDelegationController.$inject = ['$scope', '$mdDialog', 'User', 'account'];\n function MailboxDelegationController($scope, $mdDialog, User, account) {\n var vm = this;\n\n vm.users = account.delegates;\n vm.account = account;\n vm.userToAdd = '';\n vm.searchText = '';\n vm.userFilter = userFilter;\n vm.closeModal = closeModal;\n vm.removeUser = removeUser;\n vm.addUser = addUser;\n\n function userFilter($query) {\n return User.$filter($query, account.delegates);\n }\n\n function closeModal() {\n $mdDialog.hide();\n }\n\n function removeUser(user) {\n account.$removeDelegate(user.uid).catch(function(data, status) {\n Dialog.alert(l('Warning'), l('An error occured please try again.'));\n });\n }\n\n function addUser(data) {\n if (data) {\n account.$addDelegate(data).then(function() {\n vm.userToAdd = '';\n vm.searchText = '';\n }, function(error) {\n Dialog.alert(l('Warning'), error);\n });\n }\n }\n }\n } // delegate\n\n function editFolder(folder) {\n vm.editMode = folder.path;\n focus('mailboxName_' + folder.path);\n }\n\n function revertEditing(folder) {\n folder.$reset();\n vm.editMode = false;\n }\n\n function selectFolder($event, account, folder) {\n if (vm.editMode == folder.path)\n return;\n vm.editMode = false;\n vm.showingAdvancedSearch = false;\n vm.service.$virtualMode = false;\n // Close sidenav on small devices\n if (!$mdMedia(sgConstant['gt-md']))\n $mdSidenav('left').close();\n $state.go('mail.account.mailbox', { accountId: account.id, mailboxId: encodeUriFilter(folder.path) });\n $event.stopPropagation();\n $event.preventDefault();\n }\n\n function saveFolder(folder) {\n folder.$rename()\n .then(function(data) {\n vm.editMode = false;\n });\n }\n\n function compactFolder(folder) {\n folder.$compact().then(function() {\n $mdToast.show(\n $mdToast.simple()\n .content(l('Folder compacted'))\n .position('top right')\n .hideDelay(3000));\n });\n }\n\n function emptyTrashFolder(folder) {\n folder.$emptyTrash().then(function() {\n $mdToast.show(\n $mdToast.simple()\n .content(l('Trash emptied'))\n .position('top right')\n .hideDelay(3000));\n });\n }\n\n function confirmDelete(folder) {\n Dialog.confirm(l('Warning'),\n l('Do you really want to move this folder into the trash ?'),\n { ok: l('Delete') })\n .then(function() {\n folder.$delete()\n .then(function() {\n $state.go('mail.account.inbox');\n }, function(response) {\n Dialog.confirm(l('Warning'),\n l('The mailbox could not be moved to the trash folder. Would you like to delete it immediately?'),\n { ok: l('Delete') })\n .then(function() {\n folder.$delete({ withoutTrash: true })\n .then(function() {\n $state.go('mail.account.inbox');\n }, function(response) {\n Dialog.alert(l('An error occured while deleting the mailbox \"%{0}\".', folder.name),\n l(response.error));\n });\n });\n });\n });\n }\n\n function markFolderRead(folder) {\n folder.$markAsRead();\n }\n\n function share(folder) {\n // Fetch list of ACL users\n folder.$acl.$users().then(function() {\n // Show ACL editor\n $mdDialog.show({\n templateUrl: folder.id + '/UIxAclEditor', // UI/Templates/UIxAclEditor.wox\n controller: 'AclController', // from the ng module SOGo.Common\n controllerAs: 'acl',\n clickOutsideToClose: true,\n escapeToClose: true,\n locals: {\n usersWithACL: folder.$acl.users,\n User: User,\n folder: folder\n }\n });\n });\n } // share\n\n function setFolderAs(folder, type) {\n folder.$setFolderAs(type).then(function() {\n folder.$account.$getMailboxes({reload: true});\n });\n }\n\n function refreshUnseenCount() {\n var unseenCountFolders = $window.unseenCountFolders;\n\n _.forEach(vm.accounts, function(account) {\n\n // Always include the INBOX\n if (!_.includes(unseenCountFolders, account.id + '/folderINBOX'))\n unseenCountFolders.push(account.id + '/folderINBOX');\n\n _.forEach(account.$$flattenMailboxes, function(mailbox) {\n if (angular.isDefined(mailbox.unseenCount) &&\n !_.includes(unseenCountFolders, mailbox.id))\n unseenCountFolders.push(mailbox.id);\n });\n });\n\n Account.$$resource.post('', 'unseenCount', {mailboxes: unseenCountFolders}).then(function(data) {\n _.forEach(vm.accounts, function(account) {\n _.forEach(account.$$flattenMailboxes, function(mailbox) {\n if (data[mailbox.id])\n mailbox.unseenCount = data[mailbox.id];\n });\n });\n });\n\n Preferences.ready().then(function() {\n var refreshViewCheck = Preferences.defaults.SOGoRefreshViewCheck;\n if (refreshViewCheck && refreshViewCheck != 'manually')\n $timeout(vm.refreshUnseenCount, refreshViewCheck.timeInterval()*1000);\n });\n }\n\n function isDroppableFolder(srcFolder, dstFolder) {\n return (dstFolder.id != srcFolder.id) && !dstFolder.isNoSelect();\n }\n\n function dragSelectedMessages(srcFolder, dstFolder, mode) {\n var dstId, messages, uids, clearMessageView, promise, success;\n\n dstId = '/' + dstFolder.id;\n messages = srcFolder.$selectedMessages();\n if (messages.length === 0)\n messages = [srcFolder.$selectedMessage()];\n uids = _.map(messages, 'uid');\n clearMessageView = (srcFolder.selectedMessage && uids.indexOf(srcFolder.selectedMessage) >= 0);\n\n if (mode == 'copy') {\n promise = srcFolder.$copyMessages(messages, dstId);\n success = l('%{0} message(s) copied', messages.length);\n }\n else {\n promise = srcFolder.$moveMessages(messages, dstId);\n success = l('%{0} message(s) moved', messages.length);\n }\n\n promise.then(function() {\n if (clearMessageView)\n $state.go('mail.account.mailbox');\n $mdToast.show(\n $mdToast.simple()\n .content(success)\n .position('top right')\n .hideDelay(2000));\n });\n }\n\n }\n\n angular\n .module('SOGo.MailerUI')\n .controller('MailboxesController', MailboxesController);\n})();\n\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n MessageController.$inject = ['$window', '$scope', '$state', '$mdMedia', '$mdDialog', 'sgConstant', 'stateAccounts', 'stateAccount', 'stateMailbox', 'stateMessage', 'sgHotkeys', 'encodeUriFilter', 'sgSettings', 'sgFocus', 'Dialog', 'Calendar', 'Component', 'Account', 'Mailbox', 'Message'];\n function MessageController($window, $scope, $state, $mdMedia, $mdDialog, sgConstant, stateAccounts, stateAccount, stateMailbox, stateMessage, sgHotkeys, encodeUriFilter, sgSettings, focus, Dialog, Calendar, Component, Account, Mailbox, Message) {\n var vm = this, popupWindow = null, hotkeys = [];\n\n // Expose controller\n $window.$messageController = vm;\n\n vm.$state = $state;\n vm.accounts = stateAccounts;\n vm.account = stateAccount;\n vm.mailbox = stateMailbox;\n vm.message = stateMessage;\n vm.service = Message;\n vm.tags = { searchText: '', selected: '' };\n vm.showFlags = stateMessage.flags && stateMessage.flags.length > 0;\n vm.$showDetailedRecipients = false;\n vm.toggleDetailedRecipients = toggleDetailedRecipients;\n vm.filterMailtoLinks = filterMailtoLinks;\n vm.deleteMessage = deleteMessage;\n vm.close = close;\n vm.reply = reply;\n vm.replyAll = replyAll;\n vm.forward = forward;\n vm.edit = edit;\n vm.openPopup = openPopup;\n vm.closePopup = closePopup;\n vm.newMessage = newMessage;\n vm.toggleRawSource = toggleRawSource;\n vm.showRawSource = false;\n vm.print = print;\n vm.convertToEvent = convertToEvent;\n vm.convertToTask = convertToTask;\n\n _registerHotkeys(hotkeys);\n\n // One-way refresh of the parent window when modifying the message from a popup window.\n if ($window.opener) {\n // Update the message flags. The message must be displayed in the parent window.\n $scope.$watchCollection(function() { return vm.message.flags; }, function(newTags, oldTags) {\n var ctrls;\n if (newTags || oldTags) {\n ctrls = $parentControllers();\n if (ctrls.messageCtrl) {\n ctrls.messageCtrl.service.$timeout(function() {\n ctrls.messageCtrl.showFlags = true;\n ctrls.messageCtrl.message.flags = newTags;\n });\n }\n }\n });\n // Update the \"isflagged\" (star icon) of the message. The mailbox must be displayed in the parent window.\n $scope.$watch(function() { return vm.message.isflagged; }, function(isflagged, wasflagged) {\n var ctrls = $parentControllers();\n if (ctrls.mailboxCtrl) {\n ctrls.mailboxCtrl.service.$timeout(function() {\n var message = _.find(ctrls.mailboxCtrl.selectedFolder.$messages, { uid: vm.message.uid });\n message.isflagged = isflagged;\n });\n }\n });\n }\n else {\n // Flatten new tags when coming from the predefined list of tags (Message.$tags) and\n // sync tags with server when adding or removing a tag.\n $scope.$watchCollection(function() { return vm.message.flags; }, function(_newTags, _oldTags) {\n var newTags, oldTags, tags;\n if (_newTags || _oldTags) {\n newTags = _newTags || [];\n oldTags = _oldTags || [];\n _.forEach(newTags, function(tag, i) {\n if (angular.isObject(tag))\n newTags[i] = tag.name;\n });\n if (newTags.length > oldTags.length) {\n tags = _.difference(newTags, oldTags);\n _.forEach(tags, function(tag) {\n vm.message.addTag(tag);\n });\n }\n else if (newTags.length < oldTags.length) {\n tags = _.difference(oldTags, newTags);\n _.forEach(tags, function(tag) {\n vm.message.removeTag(tag);\n });\n }\n }\n });\n }\n\n $scope.$on('$destroy', function() {\n // Deregister hotkeys\n _.forEach(hotkeys, function(key) {\n sgHotkeys.deregisterHotkey(key);\n });\n });\n\n\n /**\n * To keep track of the currently active dialog, we share a common variable with the parent controller.\n */\n function _messageDialog() {\n if ($scope.mailbox) {\n if (arguments.length > 0)\n $scope.mailbox.messageDialog = arguments[0];\n return $scope.mailbox.messageDialog;\n }\n return null;\n }\n\n function _unlessInDialog(callback) {\n return function() {\n // Check if a dialog is opened either from the current controller or the parent controller\n if (_messageDialog() === null)\n return callback.apply(vm, arguments);\n };\n }\n\n function _registerHotkeys(keys) {\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_reply'),\n description: l('Reply to the message'),\n callback: _unlessInDialog(reply)\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_replyall'),\n description: l('Reply to sender and all recipients'),\n callback: _unlessInDialog(replyAll)\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_forward'),\n description: l('Forward selected message'),\n callback: _unlessInDialog(forward)\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_flag'),\n description: l('Flagged'),\n callback: _unlessInDialog(angular.bind(stateMessage, stateMessage.toggleFlag))\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'backspace',\n callback: _unlessInDialog(function($event) {\n if (vm.mailbox.$selectedCount() === 0)\n deleteMessage();\n $event.preventDefault();\n })\n }));\n\n // Register the hotkeys\n _.forEach(keys, function(key) {\n sgHotkeys.registerHotkey(key);\n });\n }\n\n /**\n * If this is a popup window, retrieve the matching controllers (mailbox and message) of the parent window.\n */\n function $parentControllers() {\n var message, mailbox, ctrls = {};\n if ($window.opener) {\n // Deleting the message from a popup window\n if ($window.opener.$mailboxController &&\n $window.opener.$mailboxController.selectedFolder.$id() == stateMailbox.$id()) {\n // The message mailbox is opened in the parent window\n mailbox = $window.opener.$mailboxController;\n ctrls.mailboxCtrl = mailbox;\n if ($window.opener.$messageController &&\n $window.opener.$messageController.message.uid == stateMessage.uid) {\n // The message is opened in the parent window\n message = $window.opener.$messageController;\n ctrls.messageCtrl = message;\n }\n }\n }\n return ctrls;\n }\n\n function toggleDetailedRecipients($event) {\n vm.$showDetailedRecipients = !vm.$showDetailedRecipients;\n $event.stopPropagation();\n $event.preventDefault();\n }\n\n function filterMailtoLinks($event) {\n var href, match, to, cc, bcc, subject, body, data;\n if ($event.target.tagName == 'A' && 'href' in $event.target.attributes) {\n href = $event.target.attributes.href.value;\n match = /^mailto:([^\\?]+)/.exec(href);\n if (match) {\n // Recipients\n to = _.map(decodeURIComponent(match[1]).split(','), function(email) {\n return '<' + email + '>';\n });\n data = { to: to };\n // Subject & body\n _.forEach(['subject', 'body'], function(param) {\n var re = new RegExp(param + '=([^&]+)');\n param = (param == 'body')? 'text' : param;\n match = re.exec(href);\n if (match)\n data[param] = [decodeURIComponent(match[1])];\n });\n // Recipients\n _.forEach(['cc', 'bcc'], function(param) {\n var re = new RegExp(param + '=([^&]+)');\n match = re.exec(href);\n if (match)\n data[param] = [decodeURIComponent(match[1])];\n });\n newMessage($event, data); // will stop event propagation\n }\n }\n }\n\n function deleteMessage() {\n var mailbox, message, state, nextMessage, previousMessage,\n parentCtrls = $parentControllers();\n\n if (parentCtrls.messageCtrl) {\n mailbox = parentCtrls.mailboxCtrl.selectedFolder;\n message = parentCtrls.messageCtrl.message;\n state = parentCtrls.messageCtrl.$state;\n }\n else {\n mailbox = stateMailbox;\n message = stateMessage;\n state = $state;\n }\n\n mailbox.$deleteMessages([message]).then(function(index) {\n var nextIndex = index;\n // Remove message object from scope\n message = null;\n if (angular.isDefined(state)) {\n // Select either the next or previous message\n if (index > 0) {\n nextIndex -= 1;\n nextMessage = mailbox.$messages[nextIndex];\n }\n if (index < mailbox.$messages.length)\n previousMessage = mailbox.$messages[index];\n\n if (nextMessage) {\n if (nextMessage.isread && previousMessage && !previousMessage.isread) {\n nextIndex = index;\n nextMessage = previousMessage;\n }\n }\n else if (previousMessage) {\n nextIndex = index;\n nextMessage = previousMessage;\n }\n\n try {\n if (nextMessage && $mdMedia(sgConstant['gt-md'])) {\n state.go('mail.account.mailbox.message', { messageId: nextMessage.uid });\n if (nextIndex < mailbox.$topIndex)\n mailbox.$topIndex = nextIndex;\n else if (nextIndex > mailbox.$lastVisibleIndex)\n mailbox.$topIndex = nextIndex - (mailbox.$lastVisibleIndex - mailbox.$topIndex);\n }\n else {\n state.go('mail.account.mailbox').then(function() {\n message = null;\n delete mailbox.selectedMessage;\n });\n }\n }\n catch (error) {}\n }\n closePopup();\n });\n }\n\n function showMailEditor($event, message) {\n if (_messageDialog() === null) {\n _messageDialog(\n $mdDialog\n .show({\n parent: angular.element(document.body),\n targetEvent: $event,\n clickOutsideToClose: false,\n escapeToClose: false,\n templateUrl: 'UIxMailEditor',\n controller: 'MessageEditorController',\n controllerAs: 'editor',\n locals: {\n stateAccount: vm.account,\n stateMessage: message\n }\n })\n .finally(function() {\n _messageDialog(null);\n closePopup();\n })\n );\n }\n }\n\n function close() {\n $state.go('mail.account.mailbox').then(function() {\n vm.message = null;\n delete stateMailbox.selectedMessage;\n });\n }\n\n function reply($event) {\n var message = vm.message.$reply();\n showMailEditor($event, message);\n }\n\n function replyAll($event) {\n var message = vm.message.$replyAll();\n showMailEditor($event, message);\n }\n\n function forward($event) {\n var message = vm.message.$forward();\n showMailEditor($event, message);\n }\n\n function edit($event) {\n vm.message.$editableContent().then(function() {\n showMailEditor($event, vm.message);\n });\n }\n\n function openPopup() {\n var url = [sgSettings.baseURL(),\n 'UIxMailPopupView#!/Mail',\n vm.message.accountId,\n // The double-encoding is necessary\n encodeUriFilter(encodeUriFilter(vm.message.$mailbox.path)),\n vm.message.uid]\n .join('/'),\n wId = vm.message.$absolutePath();\n popupWindow = $window.open(url, wId,\n [\"width=680\",\n \"height=520\",\n \"resizable=1\",\n \"scrollbars=1\",\n \"toolbar=0\",\n \"location=0\",\n \"directories=0\",\n \"status=0\",\n \"menubar=0\",\n \"copyhistory=0\"]\n .join(','));\n }\n\n function closePopup() {\n if ($window.opener)\n $window.close();\n }\n\n function newMessage($event, editableContent) {\n vm.account.$newMessage().then(function(message) {\n angular.extend(message.editable, editableContent);\n showMailEditor($event, message);\n });\n $event.stopPropagation();\n $event.preventDefault();\n }\n\n function toggleRawSource($event) {\n if (!vm.showRawSource && !vm.message.$rawSource) {\n Message.$$resource.post(vm.message.id, \"viewsource\").then(function(data) {\n vm.message.$rawSource = data;\n vm.showRawSource = true;\n });\n }\n else {\n vm.showRawSource = !vm.showRawSource;\n }\n }\n\n function print($event) {\n $window.print();\n }\n\n function convertToEvent($event) {\n return convertToComponent($event, 'appointment');\n }\n\n function convertToTask($event) {\n return convertToComponent($event, 'task');\n }\n\n function convertToComponent($event, type) {\n vm.message.$plainContent().then(function(data) {\n var componentData = {\n pid: Calendar.$defaultCalendar(),\n type: type,\n summary: data.subject,\n comment: data.content\n };\n var component = new Component(componentData);\n // UI/Templates/SchedulerUI/UIxAppointmentEditorTemplate.wox or\n // UI/Templates/SchedulerUI/UIxTaskEditorTemplate.wox\n var templateUrl = [\n sgSettings.activeUser('folderURL'),\n 'Calendar',\n 'UIx' + type.capitalize() + 'EditorTemplate'\n ].join('/');\n return $mdDialog.show({\n parent: angular.element(document.body),\n targetEvent: $event,\n clickOutsideToClose: true,\n escapeToClose: true,\n templateUrl: templateUrl,\n controller: 'ComponentEditorController',\n controllerAs: 'editor',\n locals: {\n stateComponent: component\n }\n });\n });\n }\n }\n \n angular\n .module('SOGo.MailerUI') \n .controller('MessageController', MessageController); \n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n MessageEditorController.$inject = ['$scope', '$window', '$stateParams', '$mdConstant', '$mdDialog', '$mdToast', 'FileUploader', 'stateAccount', 'stateMessage', 'encodeUriFilter', '$timeout', 'Dialog', 'AddressBook', 'Card', 'Preferences'];\n function MessageEditorController($scope, $window, $stateParams, $mdConstant, $mdDialog, $mdToast, FileUploader, stateAccount, stateMessage, encodeUriFilter, $timeout, Dialog, AddressBook, Card, Preferences) {\n var vm = this, hotkeys = [];\n\n vm.addRecipient = addRecipient;\n vm.autocomplete = {to: {}, cc: {}, bcc: {}};\n vm.autosave = null;\n vm.autosaveDrafts = autosaveDrafts;\n vm.cancel = cancel;\n vm.contactFilter = contactFilter;\n vm.isFullscreen = false;\n vm.hideBcc = (stateMessage.editable.bcc.length === 0);\n vm.hideCc = (stateMessage.editable.cc.length === 0);\n vm.identities = _.map(stateAccount.identities, 'full');\n vm.message = stateMessage;\n vm.recipientSeparatorKeys = [\n $mdConstant.KEY_CODE.ENTER,\n $mdConstant.KEY_CODE.TAB,\n $mdConstant.KEY_CODE.COMMA,\n $mdConstant.KEY_CODE.SEMICOLON\n ];\n vm.removeAttachment = removeAttachment;\n vm.save = save;\n vm.send = send;\n vm.sendState = false;\n vm.toggleFullscreen = toggleFullscreen;\n vm.uploader = new FileUploader({\n url: stateMessage.$absolutePath({asDraft: true}) + '/save',\n autoUpload: true,\n alias: 'attachments',\n removeAfterUpload: false,\n // onProgressItem: function(item, progress) {\n // console.debug(item); console.debug(progress);\n // },\n onSuccessItem: function(item, response, status, headers) {\n stateMessage.$setUID(response.uid);\n stateMessage.$reload({asDraft: false});\n item.inlineUrl = response.lastAttachmentAttrs[0].url;\n //console.debug(item); console.debug('success = ' + JSON.stringify(response, undefined, 2));\n },\n onCancelItem: function(item, response, status, headers) {\n //console.debug(item); console.debug('cancel = ' + JSON.stringify(response, undefined, 2));\n // We remove the attachment\n stateMessage.$deleteAttachment(item.file.name);\n this.removeFromQueue(item);\n },\n onErrorItem: function(item, response, status, headers) {\n $mdToast.show(\n $mdToast.simple()\n .content(l('Error while uploading the file \\\"%{0}\\\":', item.file.name) +\n ' ' + (response.message? l(response.message) : ''))\n .position('top right')\n .action(l('OK'))\n .hideDelay(false));\n this.removeFromQueue(item);\n //console.debug(item); console.debug('error = ' + JSON.stringify(response, undefined, 2));\n }\n });\n\n // Destroy file uploader when the controller is being deactivated\n $scope.$on('$destroy', function() { vm.uploader.destroy(); });\n\n if ($stateParams.actionName == 'reply') {\n stateMessage.$reply().then(function(msgObject) {\n vm.message = msgObject;\n vm.hideCc = (!msgObject.editable.cc || msgObject.editable.cc.length === 0);\n vm.hideBcc = (!msgObject.editable.bcc || msgObject.editable.bcc.length === 0);\n });\n }\n else if ($stateParams.actionName == 'replyall') {\n stateMessage.$replyAll().then(function(msgObject) {\n vm.message = msgObject;\n vm.hideCc = (!msgObject.editable.cc || msgObject.editable.cc.length === 0);\n vm.hideBcc = (!msgObject.editable.bcc || msgObject.editable.bcc.length === 0);\n });\n }\n else if ($stateParams.actionName == 'forward') {\n stateMessage.$forward().then(function(msgObject) {\n vm.message = msgObject;\n addAttachments();\n });\n }\n else if (angular.isDefined(stateMessage)) {\n vm.message = stateMessage;\n addAttachments();\n }\n\n /**\n * If this is a popup window, retrieve the mailbox controller of the parent window.\n */\n function $parentControllers() {\n var originMessage, ctrls = {};\n\n try {\n if ($window.opener) {\n if ('$mailboxController' in $window.opener &&\n 'selectedFolder' in $window.opener.$mailboxController) {\n if ($window.opener.$mailboxController.selectedFolder.type == 'draft') {\n ctrls.draftMailboxCtrl = $window.opener.$mailboxController;\n if ('$messageController' in $window.opener &&\n $window.opener.$messageController.message.uid == stateMessage.uid) {\n // The draft is opened in the parent window\n ctrls.draftMessageCtrl = $window.opener.$messageController;\n }\n }\n else if (stateMessage.origin) {\n originMessage = stateMessage.origin.message;\n if ($window.opener.$mailboxController.selectedFolder.$id() == originMessage.$mailbox.$id()) {\n // The message mailbox is opened in the parent window\n ctrls.originMailboxCtrl = $window.opener.$mailboxController;\n }\n }\n }\n }\n }\n catch (e) {}\n\n return ctrls;\n }\n\n function addAttachments() {\n // Add existing attached files to uploader\n var i, data, fileItem, attrs = vm.message.editable.attachmentAttrs;\n if (attrs)\n for (i = 0; i < attrs.length; i++) {\n data = {\n name: attrs[i].filename,\n type: attrs[i].mimetype,\n size: parseInt(attrs[i].size)\n };\n fileItem = new FileUploader.FileItem(vm.uploader, data);\n fileItem.progress = 100;\n fileItem.isUploaded = true;\n fileItem.isSuccess = true;\n fileItem.inlineUrl = attrs[i].url;\n vm.uploader.queue.push(fileItem);\n }\n }\n\n function removeAttachment(item, id) {\n if (item.isUploading)\n vm.uploader.cancelItem(item);\n else {\n vm.message.$deleteAttachment(item.file.name);\n item.remove();\n }\n // Hack to allow adding the same file again\n // See https://github.com/nervgh/angular-file-upload/issues/671\n var element = $window.document.getElementById(id);\n if (element)\n angular.element(element).prop('value', null);\n }\n\n function cancel() {\n if (vm.autosave)\n $timeout.cancel(vm.autosave);\n\n if (vm.message.isNew && vm.message.attachmentAttrs)\n vm.message.$mailbox.$deleteMessages([vm.message]);\n\n $mdDialog.cancel();\n }\n\n function save() {\n var ctrls = $parentControllers();\n vm.message.$save().then(function(data) {\n vm.message.$rawSource = null;\n if (ctrls.draftMailboxCtrl) {\n // We're saving a draft from a popup window.\n // Reload draft mailbox\n ctrls.draftMailboxCtrl.selectedFolder.$filter().then(function() {\n if (ctrls.draftMessageCtrl) {\n // Reload selected message\n ctrls.draftMessageCtrl.$state.go('mail.account.mailbox.message', { messageId: vm.message.uid });\n }\n });\n }\n $mdToast.show(\n $mdToast.simple()\n .content(l('Your email has been saved'))\n .position('top right')\n .hideDelay(3000));\n });\n }\n\n function send() {\n var ctrls = $parentControllers();\n\n vm.sendState = 'sending';\n if (vm.autosave)\n $timeout.cancel(vm.autosave);\n\n vm.message.$send().then(function(data) {\n vm.sendState = 'sent';\n if (ctrls.draftMailboxCtrl) {\n // We're sending a draft from a popup window and the draft mailbox is opened.\n // Reload draft mailbox\n ctrls.draftMailboxCtrl.selectedFolder.$filter().then(function() {\n if (ctrls.draftMessageCtrl) {\n // Close draft\n ctrls.draftMessageCtrl.close();\n }\n });\n }\n if (ctrls.originMailboxCtrl) {\n // We're sending a draft from a popup window and the original mailbox is opened.\n // Reload mailbox\n ctrls.originMailboxCtrl.selectedFolder.$filter();\n }\n $mdToast.show(\n $mdToast.simple()\n .content(l('Your email has been sent'))\n .position('top right')\n .hideDelay(3000));\n\n // Let the user see the succesfull message before closing the dialog\n $timeout($mdDialog.hide, 1000);\n }, function(response) {\n vm.sendState = 'error';\n vm.errorMessage = response.data? response.data.message : response.statusText;\n });\n }\n\n function toggleFullscreen() {\n vm.isFullscreen = !vm.isFullscreen;\n }\n\n function contactFilter($query) {\n return AddressBook.$filterAll($query).then(function(cards) {\n // Divide the matching cards by email addresses so the user can select\n // the recipient address of her choice\n var explodedCards = [];\n _.forEach(_.invokeMap(cards, 'explode'), function(manyCards) {\n _.forEach(manyCards, function(card) {\n explodedCards.push(card);\n });\n });\n // Remove duplicates\n return _.uniqBy(explodedCards, function(card) {\n return card.$$fullname + ' ' + card.$$email;\n });\n });\n }\n\n function addRecipient(contact, field) {\n var recipients, recipient, list;\n\n if (angular.isString(contact))\n return contact;\n\n recipients = vm.message.editable[field];\n\n if (contact.$isList({expandable: true})) {\n // If the list's members were already fetch, use them\n if (angular.isDefined(contact.refs) && contact.refs.length) {\n _.forEach(contact.refs, function(ref) {\n if (ref.email.length)\n recipients.push(ref.$shortFormat());\n });\n }\n else {\n list = Card.$find(contact.container, contact.c_name);\n list.$id().then(function(listId) {\n _.forEach(list.refs, function(ref) {\n if (ref.email.length)\n recipients.push(ref.$shortFormat());\n });\n });\n }\n }\n else {\n recipient = contact.$shortFormat();\n }\n\n if (recipient)\n return recipient;\n else\n return null;\n }\n\n // Drafts autosaving\n function autosaveDrafts() {\n vm.message.$save();\n if (Preferences.defaults.SOGoMailAutoSave)\n vm.autosave = $timeout(vm.autosaveDrafts, Preferences.defaults.SOGoMailAutoSave*1000*60);\n }\n\n // Read user's defaults\n Preferences.ready().then(function() {\n if (Preferences.defaults.SOGoMailAutoSave)\n // Enable auto-save of draft\n vm.autosave = $timeout(vm.autosaveDrafts, Preferences.defaults.SOGoMailAutoSave*1000*60);\n // Set the locale of CKEditor\n vm.localeCode = Preferences.defaults.LocaleCode;\n });\n }\n\n SendMessageToastController.$inject = ['$scope', '$mdToast'];\n function SendMessageToastController($scope, $mdToast) {\n $scope.closeToast = function() {\n $mdToast.hide();\n };\n }\n\n angular\n .module('SOGo.MailerUI')\n .controller('SendMessageToastController', SendMessageToastController)\n .controller('MessageEditorController', MessageEditorController);\n\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n /* jshint validthis: true */\n 'use strict';\n\n /**\n * sgIMIP - A directive to handle IMIP actions on emails\n * @memberof SOGo.MailerUI\n * @example:\n\n */\n function sgImip() {\n return {\n restrict: 'A',\n link: link,\n controller: 'sgImipController'\n };\n\n function link(scope, iElement, attrs, ctrl) {\n ctrl.pathToAttachment = attrs.sgImipPath;\n }\n }\n\n /**\n * @ngInject\n */\n sgImipController.$inject = ['$scope', 'User'];\n function sgImipController($scope, User) {\n var vm = this;\n\n $scope.delegateInvitation = false;\n $scope.delegatedTo = '';\n $scope.searchText = '';\n\n $scope.userFilter = function($query) {\n return User.$filter($query);\n };\n\n $scope.iCalendarAction = function(action) {\n var data;\n\n if (action == 'delegate') {\n data = {\n receiveUpdates: false,\n delegatedTo: $scope.delegatedTo.c_email\n };\n }\n\n $scope.viewer.message.$imipAction(vm.pathToAttachment, action, data);\n };\n }\n\n angular\n .module('SOGo.MailerUI')\n .controller('sgImipController', sgImipController)\n .directive('sgImip', sgImip);\n})();\n\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /*\n * sgZoomableImage - Toggle the 'sg-zoom' class when clicking on the image inside the container.\n * @memberof SOGo.MailerUI\n * @restrict attribute\n * @ngInject\n * @example:\n\n
\n \n \n \n
\n */\n function sgZoomableImage() {\n return {\n restrict: 'A',\n link: link\n };\n\n function link(scope, iElement, attrs, ctrl) {\n var parentNode = iElement.parent(),\n toggleClass;\n\n toggleClass = function(event) {\n if (event.target.tagName == 'IMG')\n parentNode.toggleClass('sg-zoom');\n };\n\n iElement.on('click', toggleClass);\n }\n }\n\n angular\n .module('SOGo.MailerUI')\n .directive('sgZoomableImage', sgZoomableImage);\n})();\n"]} \ No newline at end of file +{"version":3,"sources":["Mailer/Account.service.js","Mailer/Mailbox.service.js","Mailer/Message.service.js","Mailer/VirtualMailbox.service.js","Mailer/MailboxController.js","Mailer/MailboxesController.js","Mailer/MessageController.js","Mailer/MessageEditorController.js","Mailer/sgIMIP.directive.js","Mailer/sgZoomableImage.directive.js"],"names":["Account","futureAccountData","then","angular","extend","this","_","forEach","identities","identity","fullName","full","email","$log","debug","JSON","stringify","undefined","$factory","$q","$timeout","Settings","Resource","Preferences","Mailbox","Message","$$resource","activeUser","$Preferences","$Mailbox","$Message","module","e","factory","$findAll","data","$unwrapCollection","fetch","o","collection","i","id","$accounts","prototype","getLength","$flattenMailboxes","length","getItemAtIndex","index","expandedMailboxes","$getMailboxes","options","_this","$mailboxes","reload","$find","$expanded","ready","expandedFolders","_visit","mailboxes","indexOf","children","settings","Mail","ExpandedFolders","isString","fromJson","when","allMailboxes","push","all","$$flattenMailboxes","saveState","account","reduce","mailbox","post","$getMailboxByType","type","_find","find","$getMailboxByPath","path","$newMailbox","name","toString","updateQuota","percent","format","description","Math","round","usedSpace","maxQuota","l","formatted","$quota","$newMessage","accountId","mailboxPath","message","$absolutePath","asDraft","editable","isNew","$addDelegate","user","deferred","defer","param","uid","map","delegates","resolve","users","status","reject","promise","$removeDelegate","splice","futureMailboxData","$account","init","newMailboxData","create","$unwrap","Acl","PRELOAD","$$Acl","$query","sort","asc","selectedFolder","$refreshTimeout","$virtualMode","SortingState","parseInt","constant","LOOKAHEAD","SIZE","createMailboxes","level","quotas","split","component","asCSSIdentifier","join","isUndefined","uidsMap","headers","$isLoading","$messages","$id","$acl","$displayName","$isEditable","isEditable","$isSpecial","$icon","$isNoInferiors","isNoInferiors","$shadowData","$omit","selectFolder","$lastVisibleIndex","max","$loadMessage","$selectedMessages","filter","selected","$selectedCount","isSelectedMessage","messageId","selectedMessage","$selectedMessage","$selectedMessageIndex","hasSelectedMessage","isDefined","$filter","sortingAttributes","filters","unseenCount","cancel","searchInput","secondFilter","match","searchBy","copy","refreshViewCheck","defaults","SOGoRefreshViewCheck","f","bind","timeInterval","endIndex","uids","futureHeadersData","startIndex","loaded","subject","min","loading","$unwrapHeaders","flags","isNoSelect","$rename","findParent","parent","parentMailbox","$save","sibling","oldPath","localeCompare","pathRE","RegExp","_updateChildren","child","replace","$compact","$setFolderAs","$emptyTrash","$markAsRead","$flagMessages","messages","operation","msgUIDs","saveSelectedMessages","selectedMessages","selectedUIDs","filename","download","exportFolder","$delete","$_deleteMessages","unseen","firstIndex","isread","forEachRight","selectedIndex","findIndex","$deleteMessages","$markOrUnMarkMessagesAsJunk","method","$copyMessages","folder","$moveMessages","$reset","value","key","save","response","error","$futureMailboxData","$topIndex","invokeMap","threaded","msgs","msg","zipObject","isError","j","messageHeaders","$updateSubscribe","action","subscribed","futureMessageData","lazy","$mailbox","$hasUnsafeContent","$loadUnsafeContent","to","cc","bcc","$formatFullAddresses","Message_STATUS","STATUS","$avatar","avatar","SOGoMailLabelsColors","$tags","SOGoMailDisplayRemoteInlineImages","$displayRemoteInlineImages","NOT_LOADED","DELAYED_LOADING","LOADING","LOADED","DELAYED_MS","filterTags","query","excludedTags","re","results","keys","tag","pair","search","includes","color","buildPath","nocache","draftId","$setUID","oldUID","attr","constructor","shortname","first","last","image","$shortRecipients","result","count","total","$shortAddress","address","allowReplyAll","recipientsCount","isDraft","loadUnsafeContent","$content","parts","part","msgclass","content","alternatePart","preferredPart","contentType","isArray","formattedMessage","$smime","validSignature","valid","mixedPart","safeContent","html","unsafeContent","document","createElement","innerHTML","suffix","element","elements","querySelectorAll","removeAttr","compile","$editableContent","from","toLowerCase","text","$plainContent","addTag","$addOrRemoveTag","removeTag","$imipAction","$reload","$sendMDN","shouldAskReceipt","$deleteAttachment","attachmentAttrs","attachment","toggleFlag","isflagged","$loaded","useCache","$futureMessageData","$reply","$newDraft","$replyAll","$forward","origin","$send","startsWith","isanswered","isforwarded","privateAttributes","downloadAttachments","VirtualMailbox","setMailboxes","startSearch","params","finally","stopSearch","resetSelectedMessage","len","k","transform","messagesMap","sum","allMessages","promises","assign","flatten","MailboxController","$window","$scope","$state","$mdDialog","$mdToast","stateAccounts","stateAccount","stateMailbox","sgHotkeys","encodeUriFilter","sgSettings","focus","Dialog","_registerHotkeys","createHotkey","callback","searchMode","$event","vm","messageDialog","newMessage","markOrUnMarkMessagesAsJunk","toggleMessageSelection","_nextMessage","preventInClass","_previousMessage","_addNextMessageToSelection","_addPreviousMessageToSelection","confirmDeleteSelectedMessages","registerHotkey","_compactBeforeUnload","event","field","sortedBy","mode","cancelSearch","inPopup","_newMessageInPopup","show","body","targetEvent","clickOutsideToClose","escapeToClose","templateUrl","controller","controllerAs","locals","stateMessage","url","baseURL","wId","random","console","open","selectMessage","preventDefault","go","mailboxId","nextSelectedIndex","multiple","shiftKey","stopPropagation","_currentMailboxes","_unselectMessage","nextMessage","previousMessage","nextIndex","warn","size","confirm","ok","deleteSelectedMessage","withoutTrash","moveSelectedMessage","dstFolder","copySelectedMessages","simple","position","hideDelay","moveSelectedMessages","selectAll","unselectMessages","markSelectedMessagesAsFlagged","markSelectedMessagesAsUnread","markSelectedMessagesAsRead","defaultWindowTitle","hotkeys","$mailboxController","service","accounts","on","$on","off","deregisterHotkey","$watch","title","mdVirtualRepeatContainerDirectiveDecorator","$delegate","resetScroll","$element","updateSize","scrollTo","$inject","decorator","MailboxesController","$mdMedia","$mdSidenav","sgConstant","User","confirmDelete","showAdvancedSearch","showingAdvancedSearch","close","hideAdvancedSearch","searchPreviousMailbox","toggleAdvancedSearch","virtualMailbox","root","folders","subfolders","addSearchParam","v","currentSearchParam","newSearchParam","pattern","n","searchParam","substring","trim","negative","toggleAccountState","triggerHandler","subscribe","SubscriptionsDialogController","srcAccount","newFolder","parentFolder","prompt","alert","delegate","MailboxDelegationController","userFilter","closeModal","hide","removeUser","catch","addUser","userToAdd","searchText","editFolder","editMode","revertEditing","saveFolder","compactFolder","emptyTrashFolder","markFolderRead","share","$users","usersWithACL","setFolderAs","refreshUnseenCount","unseenCountFolders","isDroppableFolder","srcFolder","dragSelectedMessages","dstId","clearMessageView","success","","showSubscribedOnly","SOGoMailShowSubscribedFoldersOnly","MessageController","Calendar","Component","_messageDialog","arguments","_unlessInDialog","apply","reply","replyAll","forward","deleteMessage","$parentControllers","ctrls","opener","mailboxCtrl","$messageController","messageCtrl","toggleDetailedRecipients","$showDetailedRecipients","filterMailtoLinks","href","target","tagName","attributes","exec","decodeURIComponent","state","parentCtrls","closePopup","showMailEditor","edit","openPopup","popupWindow","editableContent","toggleRawSource","showRawSource","$rawSource","print","convertToEvent","convertToComponent","convertToTask","componentData","pid","$defaultCalendar","summary","comment","capitalize","stateComponent","tags","showFlags","$watchCollection","newTags","oldTags","wasflagged","_newTags","_oldTags","isObject","difference","MessageEditorController","$stateParams","$mdConstant","FileUploader","AddressBook","Card","originMessage","draftMailboxCtrl","draftMessageCtrl","originMailboxCtrl","addAttachments","fileItem","attrs","mimetype","FileItem","uploader","progress","isUploaded","isSuccess","inlineUrl","queue","removeAttachment","item","isUploading","cancelItem","file","remove","getElementById","prop","autosave","send","sendState","errorMessage","statusText","toggleFullscreen","isFullscreen","contactFilter","$filterAll","cards","explodedCards","manyCards","card","uniqBy","$$fullname","$$email","addRecipient","contact","recipients","recipient","list","$isList","expandable","refs","ref","$shortFormat","container","c_name","listId","autosaveDrafts","SOGoMailAutoSave","autocomplete","hideBcc","hideCc","recipientSeparatorKeys","KEY_CODE","ENTER","TAB","COMMA","SEMICOLON","autoUpload","alias","removeAfterUpload","onSuccessItem","lastAttachmentAttrs","onCancelItem","removeFromQueue","onErrorItem","destroy","actionName","msgObject","localeCode","LocaleCode","SendMessageToastController","closeToast","sgImip","link","scope","iElement","ctrl","pathToAttachment","sgImipPath","restrict","sgImipController","delegateInvitation","delegatedTo","iCalendarAction","receiveUpdates","c_email","viewer","directive","sgZoomableImage","toggleClass","parentNode"],"mappings":"CAEA,WACE,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mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @name Account\n * @constructor\n * @param {object} futureAccountData\n */\n function Account(futureAccountData) {\n // Data is immediately available\n if (typeof futureAccountData.then !== 'function') {\n angular.extend(this, futureAccountData);\n _.forEach(this.identities, function(identity) {\n if (identity.fullName)\n identity.full = identity.fullName + ' <' + identity.email + '>';\n else\n identity.full = '<' + identity.email + '>';\n });\n Account.$log.debug('Account: ' + JSON.stringify(futureAccountData, undefined, 2));\n }\n else {\n // The promise will be unwrapped first\n //this.$unwrap(futureAccountData);\n }\n }\n\n /**\n * @memberof Account\n * @desc The factory we'll use to register with Angular\n * @returns the Account constructor\n */\n Account.$factory = ['$q', '$timeout', '$log', 'sgSettings', 'Resource', 'Preferences', 'Mailbox', 'Message', function($q, $timeout, $log, Settings, Resource, Preferences, Mailbox, Message) {\n angular.extend(Account, {\n $q: $q,\n $timeout: $timeout,\n $log: $log,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Mail', Settings.activeUser()),\n $Preferences: Preferences,\n $Mailbox: Mailbox,\n $Message: Message\n });\n\n return Account; // return constructor\n }];\n\n /**\n * @module SOGo.MailerUI\n * @desc Factory registration of Account in Angular module.\n */\n try {\n angular.module('SOGo.MailerUI');\n }\n catch(e) {\n angular.module('SOGo.MailerUI', ['SOGo.Common']);\n }\n angular.module('SOGo.MailerUI')\n .factory('Account', Account.$factory);\n\n /**\n * @memberof Account\n * @desc Set the list of accounts and instanciate a new Account object for each item.\n * @param {array} [data] - the metadata of the accounts\n * @returns the list of accounts\n */\n Account.$findAll = function(data) {\n if (!data) {\n return Account.$$resource.fetch('', 'mailAccounts').then(function(o) {\n return Account.$unwrapCollection(o);\n });\n }\n return Account.$unwrapCollection(data);\n };\n\n /**\n * @memberof Account\n * @desc Unwrap to a collection of Account instances.\n * @param {object} data - the accounts information\n * @returns a collection of Account objects\n */\n Account.$unwrapCollection = function(data) {\n var collection = [];\n\n angular.forEach(data, function(o, i) {\n o.id = i;\n collection[i] = new Account(o);\n });\n Account.$accounts = collection;\n\n return collection;\n };\n\n /**\n * @function getLength\n * @memberof Account.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the number of mailboxes in the account\n */\n Account.prototype.getLength = function() {\n return this.$flattenMailboxes().length;\n };\n\n /**\n * @function getItemAtIndex\n * @memberof Account.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the mailbox at the specified index\n */\n Account.prototype.getItemAtIndex = function(index) {\n var expandedMailboxes;\n\n expandedMailboxes = this.$flattenMailboxes();\n if (index >= 0 && index < expandedMailboxes.length)\n return expandedMailboxes[index];\n\n return null;\n };\n\n /**\n * @function $getMailboxes\n * @memberof Account.prototype\n * @desc Fetch the list of mailboxes for the current account.\n * @param {object} [options] - force a reload by setting 'reload' to true\n * @returns a promise of the HTTP operation\n */\n Account.prototype.$getMailboxes = function(options) {\n var _this = this;\n\n if (this.$mailboxes && !(options && options.reload)) {\n return Account.$q.when(this.$mailboxes);\n }\n else {\n return Account.$Mailbox.$find(this, options).then(function(data) {\n _this.$mailboxes = data;\n _this.$expanded = false;\n\n // Set expanded folders from user's settings\n Account.$Preferences.ready().then(function() {\n var expandedFolders,\n _visit = function(mailboxes) {\n _.forEach(mailboxes, function(o) {\n o.$expanded = (expandedFolders.indexOf('/' + o.id) >= 0);\n if (o.children && o.children.length > 0) {\n _visit(o.children);\n }\n });\n };\n if (Account.$Preferences.settings.Mail.ExpandedFolders) {\n if (angular.isString(Account.$Preferences.settings.Mail.ExpandedFolders))\n // Backward compatibility support\n expandedFolders = angular.fromJson(Account.$Preferences.settings.Mail.ExpandedFolders);\n else\n expandedFolders = Account.$Preferences.settings.Mail.ExpandedFolders;\n _this.$expanded = (expandedFolders.indexOf('/' + _this.id) >= 0);\n if (expandedFolders.length > 0) {\n _visit(_this.$mailboxes);\n }\n }\n if (Account.$accounts)\n _this.$expanded |= (Account.$accounts.length == 1); // Always expand single account\n _this.$flattenMailboxes({reload: true});\n });\n\n return _this.$mailboxes;\n });\n }\n };\n\n /**\n * @function $flattenMailboxes\n * @memberof Account.prototype\n * @desc Get a flatten array of the mailboxes.\n * @param {object} [options] - the following boolean attributes are available:\n * - reload: rebuild the flatten array of mailboxes from the original tree representation (this.$mailboxes)\n * - all: return all mailboxes, ignoring their expanstion state\n * - saveState: save expansion state of mailboxes to the server\n * @returns an array of Mailbox instances\n */\n Account.prototype.$flattenMailboxes = function(options) {\n var _this = this,\n allMailboxes = [],\n expandedMailboxes = [],\n _visit = function(mailboxes) {\n _.forEach(mailboxes, function(o) {\n allMailboxes.push(o);\n if ((options && options.all || o.$expanded) && o.children && o.children.length > 0) {\n _visit(o.children);\n }\n });\n };\n\n if (this.$$flattenMailboxes && !(options && (options.reload || options.all))) {\n allMailboxes = this.$$flattenMailboxes;\n }\n else {\n _visit(this.$mailboxes);\n if (!options || !options.all) {\n _this.$$flattenMailboxes = allMailboxes;\n if (options && options.saveState) {\n // Save expansion state of mailboxes to the server\n _.forEach(Account.$accounts, function(account) {\n if (account.$expanded) {\n expandedMailboxes.push('/' + account.id);\n }\n _.reduce(account.$$flattenMailboxes, function(expandedFolders, mailbox) {\n if (mailbox.$expanded) {\n expandedFolders.push('/' + mailbox.id);\n }\n return expandedFolders;\n }, expandedMailboxes);\n });\n Account.$$resource.post(null, 'saveFoldersState', expandedMailboxes);\n }\n }\n }\n\n return allMailboxes;\n };\n\n Account.prototype.$getMailboxByType = function(type) {\n var mailbox,\n // Recursive find function\n _find = function(mailboxes) {\n var mailbox = _.find(mailboxes, function(o) {\n return o.type == type;\n });\n if (!mailbox) {\n angular.forEach(mailboxes, function(o) {\n if (!mailbox && o.children && o.children.length > 0) {\n mailbox = _find(o.children);\n }\n });\n }\n return mailbox;\n };\n mailbox = _find(this.$mailboxes);\n\n return mailbox;\n };\n\n /**\n * @function $getMailboxByPath\n * @memberof Account.prototype\n * @desc Recursively find a mailbox using its path\n * @returns a promise of the HTTP operation\n */\n Account.prototype.$getMailboxByPath = function(path) {\n var mailbox = null,\n // Recursive find function\n _find = function(mailboxes) {\n var mailbox = _.find(mailboxes, function(o) {\n return o.path == path;\n });\n if (!mailbox) {\n angular.forEach(mailboxes, function(o) {\n if (!mailbox && o.children && o.children.length > 0) {\n mailbox = _find(o.children);\n }\n });\n }\n return mailbox;\n };\n mailbox = _find(this.$mailboxes);\n\n return mailbox;\n };\n\n /**\n * @function $newMailbox\n * @memberof Account.prototype\n * @desc Create a new mailbox on the server and refresh the list of mailboxes.\n * @returns a promise of the HTTP operations\n */\n Account.prototype.$newMailbox = function(path, name) {\n var _this = this;\n\n return Account.$$resource.post(path.toString(), 'createFolder', {name: name}).then(function() {\n _this.$getMailboxes({reload: true});\n });\n };\n\n /**\n * @function updateQuota\n * @memberof Account.prototype\n * @param {Object} data - the inbox quota information returned by the server\n * @desc Update the quota definition associated to the account\n */\n Account.prototype.updateQuota = function(data) {\n var percent, format, description;\n\n percent = (Math.round(data.usedSpace * 10000 / data.maxQuota) / 100);\n format = l(\"quotasFormat\");\n description = format.formatted(percent, Math.round(data.maxQuota/10.24)/100);\n\n this.$quota = { percent: percent, description: description };\n };\n\n /**\n * @function $newMessage\n * @memberof Account.prototype\n * @desc Prepare a new Message object associated to the appropriate mailbox.\n * @returns a promise of the HTTP operations\n */\n Account.prototype.$newMessage = function() {\n var _this = this;\n\n // Query account for draft folder and draft UID\n return Account.$$resource.fetch(this.id.toString(), 'compose').then(function(data) {\n Account.$log.debug('New message (compose): ' + JSON.stringify(data, undefined, 2));\n var message = new Account.$Message(data.accountId, _this.$getMailboxByPath(data.mailboxPath), data);\n return message;\n }).then(function(message) {\n // Fetch draft initial data\n return Account.$$resource.fetch(message.$absolutePath({asDraft: true}), 'edit').then(function(data) {\n Account.$log.debug('New message (edit): ' + JSON.stringify(data, undefined, 2));\n angular.extend(message.editable, data);\n message.isNew = true;\n return message;\n });\n });\n };\n\n /**\n * @function $addDelegate\n * @memberof Account.prototype\n * @param {Object} user - a User object with minimal set of attributes (uid, isGroup, cn, c_email)\n * @desc Remove a user from the account's delegates\n * @see {@link User.$filter}\n */\n Account.prototype.$addDelegate = function(user) {\n var _this = this,\n deferred = Account.$q.defer(),\n param = {uid: user.uid};\n if (!user.uid || _.indexOf(_.map(this.delegates, 'uid'), user.uid) > -1) {\n // No UID specified or user already in delegates\n deferred.resolve();\n }\n else {\n Account.$$resource.fetch(this.id.toString(), 'addDelegate', param).then(function() {\n _this.delegates.push(user);\n deferred.resolve(_this.users);\n }, function(data, status) {\n deferred.reject(l('An error occured please try again.'));\n });\n }\n return deferred.promise;\n };\n\n /**\n * @function $removeDelegate\n * @memberof Account.prototype\n * @param {Object} user - a User object with minimal set of attributes (uid, isGroup, cn, c_email)\n * @desc Remove a user from the account's delegates\n * @return a promise of the server call to remove the user from the account's delegates\n */\n Account.prototype.$removeDelegate = function(uid) {\n var _this = this,\n param = {uid: uid};\n return Account.$$resource.fetch(this.id.toString(), 'removeDelegate', param).then(function() {\n var i = _.indexOf(_.map(_this.delegates, 'uid'), uid);\n if (i >= 0) {\n _this.delegates.splice(i, 1);\n }\n });\n };\n \n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @name Mailbox\n * @constructor\n * @param {object} futureMailboxData - either an object literal or a promise\n */\n function Mailbox(account, futureMailboxData) {\n this.$account = account;\n // Data is immediately available\n if (typeof futureMailboxData.then !== 'function') {\n this.init(futureMailboxData);\n if (this.name && !this.path) {\n // Create a new mailbox on the server\n var newMailboxData = Mailbox.$$resource.create('createFolder', this.name);\n this.$unwrap(newMailboxData);\n }\n }\n else {\n // The promise will be unwrapped first\n // NOTE: this condition never happen for the moment\n this.$unwrap(futureMailboxData);\n }\n }\n\n /**\n * @memberof Mailbox\n * @desc The factory we'll use to register with Angular\n * @returns the Mailbox constructor\n */\n Mailbox.$factory = ['$q', '$timeout', '$log', 'sgSettings', 'Resource', 'Message', 'Acl', 'Preferences', 'sgMailbox_PRELOAD', function($q, $timeout, $log, Settings, Resource, Message, Acl, Preferences, PRELOAD) {\n angular.extend(Mailbox, {\n $q: $q,\n $timeout: $timeout,\n $log: $log,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Mail', Settings.activeUser()),\n $Message: Message,\n $$Acl: Acl,\n $Preferences: Preferences,\n $query: { sort: 'arrival', asc: 0 }, // The default sort must match [UIxMailListActions defaultSortKey]\n selectedFolder: null,\n $refreshTimeout: null,\n $virtualMode: false,\n PRELOAD: PRELOAD\n });\n // Initialize sort parameters from user's settings\n Preferences.ready().then(function() {\n if (Preferences.settings.Mail.SortingState) {\n Mailbox.$query.sort = Preferences.settings.Mail.SortingState[0];\n Mailbox.$query.asc = parseInt(Preferences.settings.Mail.SortingState[1]);\n }\n });\n\n return Mailbox; // return constructor\n }];\n\n /**\n * @module SOGo.MailerUI\n * @desc Factory registration of Mailbox in Angular module.\n */\n try {\n angular.module('SOGo.MailerUI');\n }\n catch(e) {\n angular.module('SOGo.MailerUI', ['SOGo.Common']);\n }\n angular.module('SOGo.MailerUI')\n .constant('sgMailbox_PRELOAD', {\n LOOKAHEAD: 50,\n SIZE: 100\n })\n .factory('Mailbox', Mailbox.$factory);\n\n /**\n * @memberof Mailbox\n * @desc Fetch list of mailboxes of a specific account\n * @param {string} accountId - the account\n * @return a promise of the HTTP operation\n * @see {@link Account.$getMailboxes}\n */\n Mailbox.$find = function(account, options) {\n var path, futureMailboxData;\n\n if (options && options.all)\n futureMailboxData = this.$$resource.fetch(account.id.toString(), 'viewAll');\n else\n futureMailboxData = this.$$resource.fetch(account.id.toString(), 'view');\n\n return Mailbox.$unwrapCollection(account, futureMailboxData); // a collection of mailboxes\n };\n\n /**\n * @memberof Mailbox\n * @desc Unwrap to a collection of Mailbox instances.\n * @param {string} account - the account\n * @param {promise} futureMailboxData - a promise of the mailboxes metadata\n * @returns a promise of a collection of Mailbox objects\n */\n Mailbox.$unwrapCollection = function(account, futureMailboxData) {\n var collection = [],\n // Local recursive function\n createMailboxes = function(level, mailbox) {\n for (var i = 0; i < mailbox.children.length; i++) {\n mailbox.children[i].level = level;\n mailbox.children[i] = new Mailbox(account, mailbox.children[i]);\n createMailboxes(level+1, mailbox.children[i]);\n }\n };\n //collection.$futureMailboxData = futureMailboxData;\n\n return futureMailboxData.then(function(data) {\n return Mailbox.$timeout(function() {\n // Each entry is spun up as a Mailbox instance\n angular.forEach(data.mailboxes, function(data, index) {\n data.level = 0;\n var mailbox = new Mailbox(account, data);\n createMailboxes(1, mailbox); // recursively create all sub-mailboxes\n collection.push(mailbox);\n });\n // Update inbox quota\n if (data.quotas)\n account.updateQuota(data.quotas);\n return collection;\n });\n });\n };\n\n /**\n * @memberof Mailbox\n * @desc Build the path of the mailbox (or account only).\n * @param {string} accountId - the account ID\n * @param {string} [mailboxPath] - the mailbox path\n * @returns a string representing the path relative to the mail module\n */\n Mailbox.$absolutePath = function(accountId, mailboxPath) {\n var path = [];\n\n if (mailboxPath) {\n path = _.map(mailboxPath.split('/'), function(component) {\n return 'folder' + component.asCSSIdentifier();\n });\n }\n\n path.splice(0, 0, accountId); // insert account ID\n\n return path.join('/');\n };\n\n /**\n * @function init\n * @memberof Mailbox.prototype\n * @desc Extend instance with new data and compute additional attributes.\n * @param {object} data - attributes of mailbox\n */\n Mailbox.prototype.init = function(data) {\n var _this = this;\n if (angular.isUndefined(this.uidsMap) || data.headers) {\n this.$isLoading = true;\n this.$messages = [];\n this.uidsMap = {};\n }\n angular.extend(this, data);\n if (this.path) {\n this.id = this.$id();\n this.$acl = new Mailbox.$$Acl('Mail/' + this.id);\n }\n this.$displayName = this.name;\n if (this.type) {\n this.$isEditable = this.isEditable();\n this.$isSpecial = true;\n if (this.type == 'inbox') {\n this.$displayName = l('InboxFolderName');\n this.$icon = 'inbox';\n }\n else if (this.type == 'draft') {\n this.$displayName = l('DraftsFolderName');\n this.$icon = 'drafts';\n }\n else if (this.type == 'sent') {\n this.$displayName = l('SentFolderName');\n this.$icon = 'send';\n }\n else if (this.type == 'trash') {\n this.$displayName = l('TrashFolderName');\n this.$icon = 'delete';\n }\n else if (this.type == 'junk') {\n this.$displayName = l('JunkFolderName');\n this.$icon = 'thumb_down';\n }\n else if (this.type == 'additional') {\n this.$icon = 'folder_shared';\n }\n else {\n this.$isSpecial = false;\n this.$icon = 'folder_open';\n }\n }\n this.$isNoInferiors = this.isNoInferiors();\n if (angular.isUndefined(this.$shadowData)) {\n // Make a copy of the data for an eventual reset\n this.$shadowData = this.$omit();\n }\n };\n\n /**\n * @function selectFolder\n * @memberof Mailbox.prototype\n * @desc Mark the folder as selected in the constructor unless virtual mode is active\n */\n Mailbox.prototype.selectFolder = function() {\n if (!Mailbox.$virtualMode)\n Mailbox.selectedFolder = this;\n };\n\n /**\n * @function getLength\n * @memberof Mailbox.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the number of messages in the mailbox\n */\n Mailbox.prototype.getLength = function() {\n return this.$messages.length;\n };\n\n /**\n * @function getItemAtIndex\n * @memberof Mailbox.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the message at the specified index\n */\n Mailbox.prototype.getItemAtIndex = function(index) {\n var message;\n\n if (index >= 0 && index < this.$messages.length) {\n message = this.$messages[index];\n this.$lastVisibleIndex = Math.max(0, index - 3); // Magic number is NUM_EXTRA from virtual-repeater.js\n\n if (this.$loadMessage(message.uid))\n return message;\n }\n return null;\n };\n\n /**\n * @function $id\n * @memberof Mailbox.prototype\n * @desc Build the unique ID to identified the mailbox.\n * @returns a string representing the path relative to the mail module\n */\n Mailbox.prototype.$id = function() {\n return Mailbox.$absolutePath(this.$account.id, this.path);\n };\n\n /**\n * @function $selectedMessages\n * @memberof Mailbox.prototype\n * @desc Return the messages selected by the user.\n * @returns Message instances\n */\n Mailbox.prototype.$selectedMessages = function() {\n return _.filter(this.$messages, function(message) { return message.selected; });\n };\n\n /**\n * @function $selectedCount\n * @memberof Mailbox.prototype\n * @desc Return the number of messages selected by the user.\n * @returns the number of selected messages\n */\n Mailbox.prototype.$selectedCount = function() {\n return this.$selectedMessages().length;\n };\n\n /**\n * @function isSelectedMessage\n * @memberof Mailbox.prototype\n * @desc Check if the specified message is displayed in the detailed view.\n * @param {string} messageId\n * @returns true if the specified message is displayed\n */\n Mailbox.prototype.isSelectedMessage = function(messageId) {\n return this.selectedMessage == messageId;\n };\n\n /**\n * @function $selectedMessage\n * @memberof Mailbox.prototype\n * @desc Return the currently visible message.\n * @returns a Message instance or undefined if no message is displayed\n */\n Mailbox.prototype.$selectedMessage = function() {\n var _this = this;\n\n return _.find(this.$messages, function(message) { return message.uid == _this.selectedMessage; });\n };\n\n /**\n * @function $selectedMessageIndex\n * @memberof Mailbox.prototype\n * @desc Return the index of the currently visible message.\n * @returns a number or undefined if no message is selected\n */\n Mailbox.prototype.$selectedMessageIndex = function() {\n return this.uidsMap[this.selectedMessage];\n };\n\n /**\n * @function hasSelectedMessage\n * @memberof Mailbox.prototype\n * @desc Check if a message is selected.\n * @returns true if the a message is selected\n */\n Mailbox.prototype.hasSelectedMessage = function() {\n return angular.isDefined(this.selectedMessage);\n };\n\n /**\n * @function $filter\n * @memberof Mailbox.prototype\n * @desc Fetch the messages metadata of the mailbox\n * @param {object} [sort] - sort preferences. Defaults to descendent by date.\n * @param {string} sort.match - either AND or OR\n * @param {string} sort.sort - either arrival, subject, from, to, date, or size\n * @param {boolean} sort.asc - sort is ascendant if true\n * @param {object[]} [filters] - list of filters for the query\n * @param {string} filters.searchBy - either subject, from, to, cc, or body\n * @param {string} filters.searchInput - the search string to match\n * @param {boolean} filters.negative - negate the condition\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$filter = function(sortingAttributes, filters) {\n var _this = this, options = {};\n\n if (!angular.isDefined(this.unseenCount))\n this.unseenCount = 0;\n\n Mailbox.$timeout(function() {\n _this.$isLoading = true;\n });\n\n return Mailbox.$Preferences.ready().then(function() {\n\n if (Mailbox.$refreshTimeout)\n Mailbox.$timeout.cancel(Mailbox.$refreshTimeout);\n\n if (sortingAttributes)\n // Sorting preferences are common to all mailboxes\n angular.extend(Mailbox.$query, sortingAttributes);\n\n angular.extend(options, { sortingAttributes: Mailbox.$query });\n if (angular.isDefined(filters)) {\n options.filters = _.reject(filters, function(filter) {\n return !filter.searchInput || filter.searchInput.length === 0;\n });\n // Decompose filters that match two fields\n _.forEach(options.filters, function(filter) {\n var secondFilter,\n match = filter.searchBy.match(/(\\w+)_or_(\\w+)/);\n if (match) {\n options.sortingAttributes.match = 'OR';\n filter.searchBy = match[1];\n secondFilter = angular.copy(filter);\n secondFilter.searchBy = match[2];\n options.filters.push(secondFilter);\n }\n });\n }\n\n // Restart the refresh timer, if needed\n if (!Mailbox.$virtualMode) {\n var refreshViewCheck = Mailbox.$Preferences.defaults.SOGoRefreshViewCheck;\n if (refreshViewCheck && refreshViewCheck != 'manually') {\n var f = angular.bind(_this, Mailbox.prototype.$filter, null, filters);\n Mailbox.$refreshTimeout = Mailbox.$timeout(f, refreshViewCheck.timeInterval()*1000);\n }\n }\n\n var futureMailboxData = Mailbox.$$resource.post(_this.id, 'view', options);\n return _this.$unwrap(futureMailboxData);\n });\n };\n\n /**\n * @function $loadMessage\n * @memberof Mailbox.prototype\n * @desc Check if the message is loaded and in any case, fetch more messages headers from the server.\n * @returns true if the message metadata are already fetched\n */\n Mailbox.prototype.$loadMessage = function(messageId) {\n var startIndex = this.uidsMap[messageId],\n endIndex,\n index,\n max = this.$messages.length,\n loaded = false,\n uids,\n futureHeadersData;\n if (angular.isDefined(this.uidsMap[messageId]) && startIndex < this.$messages.length) {\n // Index is valid\n if (angular.isDefined(this.$messages[startIndex].subject)) {// || this.$messages[startIndex].loading) {\n // Message headers are loaded or data is coming\n loaded = true;\n }\n\n // Preload more headers if possible\n endIndex = Math.min(startIndex + Mailbox.PRELOAD.LOOKAHEAD, max - 1);\n if (angular.isDefined(this.$messages[endIndex].subject) ||\n angular.isDefined(this.$messages[endIndex].loading)) {\n index = Math.max(startIndex - Mailbox.PRELOAD.LOOKAHEAD, 0);\n if (!angular.isDefined(this.$messages[index].subject) &&\n !angular.isDefined(this.$messages[index].loading)) {\n // Previous messages not loaded; preload more headers further up\n endIndex = startIndex;\n startIndex = Math.max(startIndex - Mailbox.PRELOAD.SIZE, 0);\n }\n }\n else\n // Next messages not load; preload more headers further down\n endIndex = Math.min(startIndex + Mailbox.PRELOAD.SIZE, max - 1);\n\n if (!angular.isDefined(this.$messages[startIndex].subject) &&\n !angular.isDefined(this.$messages[startIndex].loading) ||\n !angular.isDefined(this.$messages[endIndex].subject) &&\n !angular.isDefined(this.$messages[endIndex].loading)) {\n\n for (uids = []; startIndex < endIndex && startIndex < max; startIndex++) {\n if (angular.isDefined(this.$messages[startIndex].subject) || this.$messages[startIndex].loading) {\n // Message at this index is already loaded; increase the end index\n endIndex++;\n }\n else {\n // Message at this index will be loaded\n uids.push(this.$messages[startIndex].uid);\n this.$messages[startIndex].loading = true;\n }\n }\n\n Mailbox.$log.debug('Loading UIDs ' + uids.join(' '));\n futureHeadersData = Mailbox.$$resource.post(this.id, 'headers', {uids: uids});\n this.$unwrapHeaders(futureHeadersData);\n }\n }\n return loaded;\n };\n\n /**\n * @function isEditable\n * @memberof Mailbox.prototype\n * @desc Checks if the mailbox is editable based on its type.\n * @returns true if the mailbox is not a special folder.\n */\n Mailbox.prototype.isEditable = function() {\n return this.type == 'folder';\n };\n\n /**\n * @function isNoInferiors\n * @memberof Mailbox.prototype\n * @desc Checks if the mailbox can contain submailboxes\n * @returns true if the mailbox can not contain submailboxes\n */\n Mailbox.prototype.isNoInferiors = function() {\n return this.flags.indexOf('noinferiors') >= 0;\n };\n\n /**\n * @function isNoSelect\n * @memberof Mailbox.prototype\n * @desc Checks if the mailbox can be selected\n * @returns true if the mailbox can not be selected\n */\n Mailbox.prototype.isNoSelect = function() {\n return this.flags.indexOf('noselect') >= 0;\n };\n\n /**\n * @function $rename\n * @memberof AddressBook.prototype\n * @desc Rename the addressbook and keep the list sorted\n * @param {string} name - the new name\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$rename = function() {\n var _this = this,\n findParent,\n parent,\n children,\n i;\n\n if (this.name == this.$shadowData.name) {\n // Name hasn't changed\n return Mailbox.$q.when();\n }\n\n // Local recursive function\n findParent = function(parent, children) {\n var parentMailbox = null,\n mailbox = _.find(children, function(o) {\n return o.path == _this.path;\n });\n if (mailbox) {\n parentMailbox = parent;\n }\n else {\n angular.forEach(children, function(o) {\n if (!parentMailbox && o.children && o.children.length > 0) {\n parentMailbox = findParent(o, o.children);\n }\n });\n }\n return parentMailbox;\n };\n\n // Find mailbox parent\n parent = findParent(null, this.$account.$mailboxes);\n if (parent === null)\n children = this.$account.$mailboxes;\n else\n children = parent.children;\n\n // Find index of mailbox among siblings\n i = _.indexOf(_.map(children, 'id'), this.id);\n\n return this.$save().then(function(data) {\n var sibling, oldPath = _this.path;\n _this.init(data); // update the path and id\n\n // Move mailbox among its siblings according to its new name\n children.splice(i, 1);\n sibling = _.find(children, function(o) {\n Mailbox.$log.debug(o.name + ' ? ' + _this.name);\n return (o.type == 'folder' && o.name.localeCompare(_this.name) > 0);\n });\n if (sibling) {\n i = _.indexOf(_.map(children, 'id'), sibling.id);\n }\n else {\n i = children.length;\n }\n children.splice(i, 0, _this);\n\n // Update the path and id of children\n var pathRE = new RegExp('^' + oldPath);\n var _updateChildren = function(mailbox) {\n _.forEach(mailbox.children, function(child) {\n child.path = child.path.replace(pathRE, _this.path);\n child.id = child.$id();\n _updateChildren(child);\n });\n };\n _updateChildren(_this);\n });\n };\n\n /**\n * @function $compact\n * @memberof Mailbox.prototype\n * @desc Compact the mailbox\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$compact = function() {\n var _this = this;\n return Mailbox.$$resource.post(this.id, 'expunge')\n .then(function(data) {\n // Update inbox quota\n if (data.quotas)\n _this.$account.updateQuota(data.quotas);\n });\n };\n\n /**\n * @function $setFolderAs\n * @memberof Mailbox.prototype\n * @desc Set a folder as Drafts/Sent/Trash\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$setFolderAs = function(type) {\n return Mailbox.$$resource.post(this.id, 'setAs' + type + 'Folder');\n };\n\n /**\n * @function $emptyTrash\n * @memberof Mailbox.prototype\n * @desc Empty the Trash folder.\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$emptyTrash = function() {\n var _this = this;\n\n return Mailbox.$$resource.post(this.id, 'emptyTrash').then(function(data) {\n // Remove all messages from the mailbox\n _this.$messages = [];\n _this.uidsMap = {};\n _this.unseenCount = 0;\n\n // If we had any submailboxes, lets do a refresh of the mailboxes list\n if (angular.isDefined(_this.children) && _this.children.length)\n _this.$account.$getMailboxes({reload: true});\n\n // Update inbox quota\n if (data.quotas)\n _this.$account.updateQuota(data.quotas);\n });\n };\n\n /**\n * @function $markAsRead\n * @memberof Mailbox.prototype\n * @desc Mark all messages from folder as read\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$markAsRead = function() {\n return Mailbox.$$resource.post(this.id, 'markRead');\n };\n\n /**\n * @function $flagMessages\n * @memberof Mailbox.prototype\n * @desc Add or remove a flag on a message set\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$flagMessages = function(messages, flags, operation) {\n var data = {msgUIDs: _.map(messages, 'uid'),\n flags: flags,\n operation: operation};\n\n return Mailbox.$$resource.post(this.id, 'addOrRemoveLabel', data).then(function() {\n return messages;\n });\n };\n\n /**\n * @function saveSelectedMessages\n * @memberof Mailbox.prototype\n * @desc Download the selected messages\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.saveSelectedMessages = function() {\n var data, options, selectedMessages, selectedUIDs;\n\n selectedMessages = _.filter(this.$messages, function(message) { return message.selected; });\n selectedUIDs = _.map(selectedMessages, 'uid');\n data = { uids: selectedUIDs };\n options = { filename: l('Saved Messages.zip') };\n\n return Mailbox.$$resource.download(this.id, 'saveMessages', {uids: selectedUIDs});\n };\n\n /**\n * @function exportFolder\n * @memberof Mailbox.prototype\n * @desc Export this mailbox\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.exportFolder = function() {\n var options;\n\n options = { filename: this.name + '.zip' };\n\n return Mailbox.$$resource.download(this.id, 'exportFolder', null, options);\n };\n\n /**\n * @function $delete\n * @memberof Mailbox.prototype\n * @desc Delete the mailbox from the server\n * @param {object} [options] - additional options (use {withoutTrash: true} to delete immediately)\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$delete = function(options) {\n var _this = this;\n\n return Mailbox.$$resource.post(this.id, 'delete', options)\n .then(function() {\n _this.$account.$getMailboxes({reload: true});\n return true;\n });\n };\n\n /**\n * @function $_deleteMessages\n * @memberof Mailbox.prototype\n * @desc Delete multiple messages from Mailbox object.\n * @param {string[]} uids - the messages uids\n * @param {object[]} messages - the Message instances\n * @return the index of the first deleted message\n */\n Mailbox.prototype.$_deleteMessages = function(uids, messages) {\n var _this = this, selectedUIDs, _$messages, unseen, firstIndex = this.$messages.length;\n\n // Decrement the unseen count\n unseen = _.filter(messages, function(message, i) { return !message.isread; });\n this.unseenCount -= unseen.length;\n\n // Remove messages from $messages and uidsMap\n _.forEachRight(this.$messages, function(message, index) {\n var selectedIndex = _.findIndex(uids, function(uid) {\n return message.uid == uid;\n });\n if (selectedIndex > -1) {\n uids.splice(selectedIndex, 1);\n delete _this.uidsMap[message.uid];\n if (message.uid == _this.selectedMessage)\n delete _this.selectedMessage;\n _this.$messages.splice(index, 1);\n if (index < firstIndex)\n firstIndex = index;\n }\n else {\n _this.uidsMap[message.uid] -= uids.length;\n }\n });\n\n // Return the index of the first deleted message\n return firstIndex;\n };\n\n /**\n * @function $deleteMessages\n * @memberof Mailbox.prototype\n * @desc Delete multiple messages from mailbox.\n * @param {object} [options] - additional options (use {withoutTrash: true} to delete immediately)\n * @return a promise of the HTTP operation\n */\n Mailbox.prototype.$deleteMessages = function(messages, options) {\n var _this = this, uids, data;\n\n uids = _.map(messages, 'uid');\n data = { uids: uids };\n if (options) angular.extend(data, options);\n\n return Mailbox.$$resource.post(this.id, 'batchDelete', data)\n .then(function(data) {\n // Update inbox quota\n if (data.quotas)\n _this.$account.updateQuota(data.quotas);\n\n return _this.$_deleteMessages(uids, messages);\n });\n };\n\n /**\n * @function $markOrUnMarkMessagesAsJunk\n * @memberof Mailbox.prototype\n * @desc Mark messages as junk/not junk\n * @return a promise of the HTTP operation\n */\n Mailbox.prototype.$markOrUnMarkMessagesAsJunk = function(messages) {\n var _this = this,\n uids = _.map(messages, 'uid'),\n method = (this.type == 'junk' ? 'markMessagesAsNotJunk' : 'markMessagesAsJunk');\n\n return Mailbox.$$resource.post(this.id, method, {uids: uids});\n };\n\n /**\n * @function $copyMessages\n * @memberof Mailbox.prototype\n * @desc Copy multiple messages from the current mailbox to a target one\n * @return a promise of the HTTP operation\n */\n Mailbox.prototype.$copyMessages = function(messages, folder) {\n var _this = this,\n uids = _.map(messages, 'uid');\n\n return Mailbox.$$resource.post(this.id, 'copyMessages', {uids: uids, folder: folder})\n .then(function(data) {\n // Update inbox quota\n if (data.quotas)\n _this.$account.updateQuota(data.quotas);\n });\n };\n\n /**\n * @function $moveMessages\n * @memberof Mailbox.prototype\n * @desc Move multiple messages from the current mailbox to a target one\n * @return a promise of the HTTP operation\n */\n Mailbox.prototype.$moveMessages = function(messages, folder) {\n var _this = this, uids;\n\n uids = _.map(messages, 'uid');\n return Mailbox.$$resource.post(this.id, 'moveMessages', {uids: uids, folder: folder})\n .then(function() {\n return _this.$_deleteMessages(uids, messages);\n });\n };\n\n /**\n * @function $reset\n * @memberof Mailbox.prototype\n * @desc Reset the original state the mailbox's data.\n */\n Mailbox.prototype.$reset = function() {\n var _this = this;\n angular.forEach(this.$shadowData, function(value, key) {\n delete _this[key];\n });\n angular.extend(this, this.$shadowData);\n this.$shadowData = this.$omit();\n };\n\n /**\n * @function $save\n * @memberof Mailbox.prototype\n * @desc Save the mailbox to the server. This currently can only affect the name of the mailbox.\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$save = function() {\n var _this = this;\n\n return Mailbox.$$resource.save(this.id, this.$omit()).then(function(data) {\n // Make a copy of the data for an eventual reset\n _this.$shadowData = _this.$omit();\n Mailbox.$log.debug(JSON.stringify(data, undefined, 2));\n return data;\n }, function(response) {\n Mailbox.$log.error(JSON.stringify(response.data, undefined, 2));\n // Restore previous version\n _this.$reset();\n return response.data;\n });\n };\n\n /**\n * @function $newMailbox\n * @memberof Mailbox.prototype\n * @desc Create a new mailbox on the server and refresh the list of mailboxes.\n * @returns a promise of the HTTP operations\n */\n Mailbox.prototype.$newMailbox = function(path, name) {\n return this.$account.$newMailbox(path, name);\n };\n\n /**\n * @function $omit\n * @memberof Mailbox.prototype\n * @desc Return a sanitized object used to send to the server.\n * @return an object literal copy of the Mailbox instance\n */\n Mailbox.prototype.$omit = function() {\n var mailbox = {};\n angular.forEach(this, function(value, key) {\n if (key != 'constructor' &&\n key != 'children' &&\n key != 'headers' &&\n key != 'uids' &&\n key != 'uidsMap' &&\n key[0] != '$') {\n mailbox[key] = value;\n }\n });\n return mailbox;\n };\n\n /**\n * @function $unwrap\n * @memberof Mailbox.prototype\n * @desc Unwrap a promise and instanciate new Message objects using received data.\n * @param {promise} futureMailboxData - a promise of the Mailbox's metadata\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$unwrap = function(futureMailboxData) {\n var _this = this,\n deferred = Mailbox.$q.defer();\n\n this.$futureMailboxData = futureMailboxData;\n this.$futureMailboxData.then(function(data) {\n Mailbox.$timeout(function() {\n var uids, headers;\n\n if (!data.uids || _this.$topIndex > data.uids.length - 1)\n _this.$topIndex = 0;\n\n _this.init(data);\n\n if (_this.uids) {\n Mailbox.$log.debug('unwrapping ' + _this.uids.length + ' messages');\n\n // First entry of 'headers' are keys\n headers = _.invokeMap(_this.headers[0], 'toLowerCase');\n _this.headers.splice(0, 1);\n\n // First entry of 'uids' are keys when threaded view is enabled\n if (_this.threaded) {\n uids = _this.uids[0];\n _this.uids.splice(0, 1);\n }\n\n // Instanciate Message objects\n _.reduce(_this.uids, function(msgs, msg, i) {\n var data;\n if (_this.threaded)\n data = _.zipObject(uids, msg);\n else\n data = {uid: msg.toString()};\n\n // Build map of UID <=> index\n _this.uidsMap[data.uid] = i;\n\n msgs.push(new Mailbox.$Message(_this.$account.id, _this, data, true));\n\n return msgs;\n }, _this.$messages);\n\n // Extend Message objects with received headers\n _.forEach(_this.headers, function(data) {\n var msg = _.zipObject(headers, data),\n i = _this.uidsMap[msg.uid.toString()];\n _.extend(_this.$messages[i], msg);\n });\n }\n Mailbox.$log.debug('mailbox ' + _this.id + ' ready');\n _this.$isLoading = false;\n deferred.resolve(_this.$messages);\n });\n }, function(data) {\n angular.extend(_this, data);\n _this.isError = true;\n deferred.reject();\n });\n\n return deferred.promise;\n };\n\n /**\n * @function $unwrapHeaders\n * @memberof Mailbox.prototype\n * @desc Unwrap a promise and extend matching Message objects using received data.\n * @param {promise} futureHeadersData - a promise of some messages metadata\n */\n Mailbox.prototype.$unwrapHeaders = function(futureHeadersData) {\n var _this = this;\n\n futureHeadersData.then(function(data) {\n Mailbox.$timeout(function() {\n var headers, j;\n if (data.length > 0) {\n // First entry of 'headers' are keys\n headers = _.invokeMap(data[0], 'toLowerCase');\n data.splice(0, 1);\n _.forEach(data, function(messageHeaders) {\n messageHeaders = _.zipObject(headers, messageHeaders);\n j = _this.uidsMap[messageHeaders.uid.toString()];\n if (angular.isDefined(j)) {\n _.extend(_this.$messages[j], messageHeaders);\n }\n });\n }\n });\n });\n };\n\n /**\n * @function $updateSubscribe\n * @memberof Mailbox.prototype\n * @desc Update mailbox subscription state with server.\n */\n Mailbox.prototype.$updateSubscribe = function() {\n var action = this.subscribed? 'subscribe' : 'unsubscribe';\n\n Mailbox.$$resource.post(this.id, action);\n };\n\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @name Message\n * @constructor\n * @param {string} accountId - the account ID\n * @param {string} mailboxPath - an array of the mailbox path components\n * @param {object} futureAddressBookData - either an object literal or a promise\n * @param {bool} lazy - do \"lazy loading\" so we are very quick at initializing message instances\n */\n function Message(accountId, mailbox, futureMessageData, lazy) {\n this.accountId = accountId;\n this.$mailbox = mailbox;\n this.$hasUnsafeContent = false;\n this.$loadUnsafeContent = false;\n this.editable = {to: [], cc: [], bcc: []};\n this.selected = false;\n\n // Data is immediately available\n if (typeof futureMessageData.then !== 'function') {\n //console.debug(JSON.stringify(futureMessageData, undefined, 2));\n if (angular.isUndefined(lazy) || !lazy) {\n angular.extend(this, futureMessageData);\n this.$formatFullAddresses();\n }\n this.uid = parseInt(futureMessageData.uid);\n }\n else {\n // The promise will be unwrapped first\n this.$unwrap(futureMessageData);\n }\n }\n\n /**\n * @memberof Message\n * @desc The factory we'll use to register with Angular\n * @returns the Message constructor\n */\n Message.$factory = ['$q', '$timeout', '$log', 'sgSettings', 'sgMessage_STATUS', 'Resource', 'Preferences', function($q, $timeout, $log, Settings, Message_STATUS, Resource, Preferences) {\n angular.extend(Message, {\n STATUS: Message_STATUS,\n $q: $q,\n $timeout: $timeout,\n $log: $log,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Mail', Settings.activeUser()),\n $avatar: angular.bind(Preferences, Preferences.avatar)\n });\n // Initialize tags form user's defaults\n Preferences.ready().then(function() {\n if (Preferences.defaults.SOGoMailLabelsColors) {\n Message.$tags = Preferences.defaults.SOGoMailLabelsColors;\n }\n if (Preferences.defaults.SOGoMailDisplayRemoteInlineImages &&\n Preferences.defaults.SOGoMailDisplayRemoteInlineImages == 'always') {\n Message.$displayRemoteInlineImages = true;\n }\n });\n\n return Message; // return constructor\n }];\n\n /**\n * @module SOGo.MailerUI\n * @desc Factory registration of Message in Angular module.\n */\n try {\n angular.module('SOGo.MailerUI');\n }\n catch(e) {\n angular.module('SOGo.MailerUI', ['SOGo.Common']);\n }\n angular.module('SOGo.MailerUI')\n .constant('sgMessage_STATUS', {\n NOT_LOADED: 0,\n DELAYED_LOADING: 1,\n LOADING: 2,\n LOADED: 3,\n DELAYED_MS: 300\n })\n .factory('Message', Message.$factory);\n\n /**\n * @function filterTags\n * @memberof Message.prototype\n * @desc Search for tags (ie., mail labels) matching some criterias\n * @param {string} search - the search string to match\n * @returns a collection of strings\n */\n Message.filterTags = function(query, excludedTags) {\n var re = new RegExp(query, 'i'),\n results = [];\n\n _.forEach(_.keys(Message.$tags), function(tag) {\n var pair = Message.$tags[tag];\n if (pair[0].search(re) != -1) {\n if (!_.includes(excludedTags, tag))\n results.push({ name: tag, description: pair[0], color: pair[1] });\n }\n });\n\n return results;\n };\n\n /**\n * @function $absolutePath\n * @memberof Message.prototype\n * @desc Build the path of the message\n * @returns a string representing the path relative to the mail module\n */\n Message.prototype.$absolutePath = function(options) {\n var _this = this, id = this.id;\n\n function buildPath() {\n var path;\n path = _.map(_this.$mailbox.path.split('/'), function(component) {\n return 'folder' + component.asCSSIdentifier();\n });\n path.splice(0, 0, _this.accountId); // insert account ID\n return path.join('/');\n }\n\n if (angular.isUndefined(this.id) || options && options.nocache) {\n this.id = buildPath() + '/' + this.uid; // add message UID\n id = this.id;\n }\n if (options && options.asDraft && this.draftId) {\n id = buildPath() + '/' + this.draftId; // add draft ID\n }\n\n return id;\n };\n\n /**\n * @function $setUID\n * @memberof Message.prototype\n * @desc Change the UID of the message. This happens when saving a draft.\n * @param {number} uid - the new message UID\n */\n Message.prototype.$setUID = function(uid) {\n var oldUID = (this.uid || -1), _this = this, index;\n\n if (oldUID != parseInt(uid)) {\n this.uid = parseInt(uid);\n this.$absolutePath({nocache: true});\n if (oldUID > -1) {\n oldUID = oldUID.toString();\n if (angular.isDefined(this.$mailbox.uidsMap[oldUID])) {\n index = this.$mailbox.uidsMap[oldUID];\n this.$mailbox.uidsMap[uid] = index;\n delete this.$mailbox.uidsMap[oldUID];\n\n // Update messages list of mailbox\n _.forEach(['from', 'to', 'subject'], function(attr) {\n _this.$mailbox.$messages[index][attr] = _this[attr];\n });\n }\n }\n else {\n // Refresh selected folder if it's the drafts mailbox\n if (this.$mailbox.constructor.selectedFolder &&\n this.$mailbox.constructor.selectedFolder.type == 'draft') {\n this.$mailbox.constructor.selectedFolder.$filter();\n }\n }\n }\n };\n\n /**\n * @function $formatFullAddresses\n * @memberof Message.prototype\n * @desc Format all sender and recipients addresses with a complete description (name ).\n * This function also generates the avatar URL for each email address and a short name\n */\n Message.prototype.$formatFullAddresses = function() {\n var _this = this;\n var identities = _.map(_this.$mailbox.$account.identities, 'email');\n\n // Build long representation of email addresses\n _.forEach(['from', 'to', 'cc', 'bcc', 'reply-to'], function(type) {\n _.forEach(_this[type], function(data) {\n if (data.name && data.name != data.email) {\n data.full = data.name + ' <' + data.email + '>';\n\n if (data.name.length < 10)\n // Name is already short\n data.shortname = data.name;\n else if (data.name.split(' ').length)\n // If we have \"Alice Foo\" or \"Foo, Alice\" as name, we grab \"Alice\"\n data.shortname = _.first(_.last(data.name.split(/, */)).split(/ +/)).replace('\\'','');\n }\n else if (data.email) {\n data.full = '<' + data.email + '>';\n data.shortname = data.email.split('@')[0];\n }\n\n data.image = Message.$avatar(data.email, 32);\n\n // If the current user is the recepient, overwrite\n // the short name with 'me'\n if (_.indexOf(identities, data.email) >= 0)\n data.shortname = l('me');\n });\n });\n };\n\n /**\n * @function $shortRecipients\n * @memberof Message.prototype\n * @desc Format all recipients into a very compact string\n * @returns a compacted string of all recipients\n */\n Message.prototype.$shortRecipients = function(max) {\n var _this = this, result = [], count = 0, total = 0;\n\n // Build short representation of email addresses\n _.forEach(['to', 'cc', 'bcc'], function(type) {\n total += _this[type]? _this[type].length : 0;\n _.forEach(_this[type], function(data, i) {\n if (count < max)\n result.push(data.shortname);\n count++;\n });\n });\n\n if (total > max)\n result.push(l('and %{0} more...', (total - max)));\n\n return result.join(', ');\n };\n\n /**\n * @function $shortAddress\n * @memberof Message.prototype\n * @desc Format the first address of a specific type with a short description.\n * @returns a string of the name or the email of the envelope address type\n */\n Message.prototype.$shortAddress = function(type) {\n var address = '';\n if (this[type] && this[type].length > 0) {\n address = this[type][0].name || this[type][0].email || '';\n }\n\n return address;\n };\n\n /**\n * @function allowReplyAll\n * @memberof Message.prototype\n * @desc Check if 'Reply to All' is an appropriate action on the message.\n * @returns true if the message is not a draft and has more than one recipient\n */\n Message.prototype.allowReplyAll = function() {\n var recipientsCount = 0;\n recipientsCount = _.reduce(['to', 'cc'], _.bind(function(count, type) {\n if (this[type])\n return count + this[type].length;\n else\n return count;\n }, this), recipientsCount);\n\n return !this.isDraft && recipientsCount > 1;\n };\n\n /**\n * @function loadUnsafeContent\n * @memberof Message.prototype\n * @desc Mark the message to load unsafe resources when calling $content().\n */\n Message.prototype.loadUnsafeContent = function() {\n this.$loadUnsafeContent = true;\n };\n\n /**\n * @function $content\n * @memberof Message.prototype\n * @desc Get the message body as accepted by SCE (Angular Strict Contextual Escaping).\n * @returns the HTML representation of the body\n */\n Message.prototype.$content = function() {\n var _this = this,\n parts = [],\n _visit = function(part) {\n part.msgclass = 'msg-attachment-other';\n if (part.type == 'UIxMailPartAlternativeViewer') {\n _visit(_.find(part.content, function(alternatePart) {\n return part.preferredPart == alternatePart.contentType;\n }));\n }\n // Can be used for UIxMailPartMixedViewer, UIxMailPartMessageViewer, and UIxMailPartSignedViewer\n else if (angular.isArray(part.content)) {\n if (part.type == 'UIxMailPartSignedViewer' && part['supports-smime'] === 1) {\n // First line in a h1, others each in a p\n var formattedMessage = \"

\" + part.error.replace(/\\n/, \"

\");\n formattedMessage = formattedMessage.replace(/\\n/g, \"

\") + \"

\";\n _this.$smime = {\n validSignature: part.valid,\n message: formattedMessage\n };\n }\n _.forEach(part.content, function(mixedPart) {\n _visit(mixedPart);\n });\n }\n else {\n if (angular.isUndefined(part.safeContent)) {\n // Keep a copy of the original content\n part.safeContent = part.content;\n _this.$hasUnsafeContent |= (part.safeContent.indexOf(' unsafe-') > -1);\n }\n if (part.type == 'UIxMailPartHTMLViewer') {\n part.html = true;\n if (_this.$loadUnsafeContent || Message.$displayRemoteInlineImages) {\n if (angular.isUndefined(part.unsafeContent)) {\n part.unsafeContent = document.createElement('div');\n part.unsafeContent.innerHTML = part.safeContent;\n angular.forEach(['src', 'data', 'classid', 'background', 'style'], function(suffix) {\n var elements = part.unsafeContent.querySelectorAll('[unsafe-' + suffix + ']'),\n element,\n value,\n i;\n for (i = 0; i < elements.length; i++) {\n element = angular.element(elements[i]);\n value = element.attr('unsafe-' + suffix);\n element.attr(suffix, value);\n element.removeAttr('unsafe-' + suffix);\n }\n });\n _this.$hasUnsafeContent = false;\n }\n part.content = part.unsafeContent.innerHTML;\n }\n else {\n part.content = part.safeContent;\n }\n parts.push(part);\n }\n else if (part.type == 'UIxMailPartICalViewer' ||\n part.type == 'UIxMailPartImageViewer' ||\n part.type == 'UIxMailPartLinkViewer') {\n\n if (part.type == 'UIxMailPartImageViewer')\n part.msgclass = 'msg-attachment-image';\n else if (part.type == 'UIxMailPartLinkViewer')\n part.msgclass = 'msg-attachment-link';\n\n // Trusted content that can be compiled (Angularly-speaking)\n part.compile = true;\n parts.push(part);\n }\n else {\n part.html = true;\n part.content = part.safeContent;\n parts.push(part);\n }\n }\n };\n\n if (this.parts)\n _visit(this.parts);\n\n return parts;\n };\n\n /**\n * @function $editableContent\n * @memberof Message.prototype\n * @desc First, fetch the draft ID that corresponds to the temporary draft object on the SOGo server.\n * Secondly, fetch the editable message body along with other metadata such as the recipients.\n * @returns the HTML representation of the body\n */\n Message.prototype.$editableContent = function() {\n var _this = this;\n\n return Message.$$resource.fetch(this.$absolutePath(), 'edit').then(function(data) {\n angular.extend(_this, data);\n return Message.$$resource.fetch(_this.$absolutePath({asDraft: true}), 'edit').then(function(data) {\n // Try to match a known account identity from the specified \"from\" address\n var identity = _.find(_this.$mailbox.$account.identities, function(identity) {\n return data.from.toLowerCase().indexOf(identity.email) !== -1;\n });\n if (identity)\n data.from = identity.full;\n Message.$log.debug('editable = ' + JSON.stringify(data, undefined, 2));\n angular.extend(_this.editable, data);\n return data.text;\n });\n });\n };\n\n /**\n * @function $plainContent\n * @memberof Message.prototype\n * @returns the a plain text representation of the subject and body\n */\n Message.prototype.$plainContent = function() {\n return Message.$$resource.fetch(this.$absolutePath(), 'viewplain');\n };\n\n /**\n * @function addTag\n * @memberof Message.prototype\n * @desc Add a mail tag on the current message.\n * @param {string} tag - the tag name\n * @returns a promise of the HTTP operation\n */\n Message.prototype.addTag = function(tag) {\n return this.$addOrRemoveTag('add', tag);\n };\n\n /**\n * @function removeTag\n * @memberof Message.prototype\n * @desc Remove a mail tag from the current message.\n * @param {string} tag - the tag name\n * @returns a promise of the HTTP operation\n */\n Message.prototype.removeTag = function(tag) {\n return this.$addOrRemoveTag('remove', tag);\n };\n\n /**\n * @function $addOrRemoveTag\n * @memberof Message.prototype\n * @desc Add or remove a mail tag on the current message.\n * @param {string} operation - the operation name to perform\n * @param {string} tag - the tag name\n * @returns a promise of the HTTP operation\n */\n Message.prototype.$addOrRemoveTag = function(operation, tag) {\n var data = {\n operation: operation,\n msgUIDs: [this.uid],\n flags: tag\n };\n\n if (tag)\n return Message.$$resource.post(this.$mailbox.$id(), 'addOrRemoveLabel', data);\n };\n\n /**\n * @function $imipAction\n * @memberof Message.prototype\n * @desc Perform IMIP actions on the current message.\n * @param {string} path - the path of the IMIP calendar part\n * @param {string} action - the the IMIP action to perform\n * @param {object} data - the delegation info\n */\n Message.prototype.$imipAction = function(path, action, data) {\n var _this = this;\n Message.$$resource.post([this.$absolutePath(), path].join('/'), action, data).then(function(data) {\n Message.$timeout(function() {\n _this.$reload();\n });\n });\n };\n\n /**\n * @function $sendMDN\n * @memberof Message.prototype\n * @desc Send MDN response for current email message\n */\n Message.prototype.$sendMDN = function() {\n this.shouldAskReceipt = 0;\n return Message.$$resource.post(this.$absolutePath(), 'sendMDN');\n };\n\n /**\n * @function $deleteAttachment\n * @memberof Message.prototype\n * @desc Delete an attachment from a message being composed\n * @param {string} filename - the filename of the attachment to delete\n */\n Message.prototype.$deleteAttachment = function(filename) {\n var data = { 'filename': filename };\n var _this = this;\n Message.$$resource.fetch(this.$absolutePath({asDraft: true}), 'deleteAttachment', data).then(function(data) {\n Message.$timeout(function() {\n _this.editable.attachmentAttrs = _.filter(_this.editable.attachmentAttrs, function(attachment) {\n return attachment.filename != filename;\n });\n });\n });\n };\n\n /**\n * @function $markAsFlaggedOrUnflagged\n * @memberof Message.prototype\n * @desc Add or remove a the \\\\Flagged flag on the current message.\n * @returns a promise of the HTTP operation\n */\n Message.prototype.toggleFlag = function() {\n var _this = this,\n action = 'markMessageFlagged';\n\n if (this.isflagged)\n action = 'markMessageUnflagged';\n\n return Message.$$resource.post(this.$absolutePath(), action).then(function(data) {\n Message.$timeout(function() {\n _this.isflagged = !_this.isflagged;\n });\n });\n };\n\n /**\n * @function $isLoading\n * @memberof Message.prototype\n * @returns true if the Message content is still being retrieved from server after a specific delay\n * @see sgMessage_STATUS\n */\n Message.prototype.$isLoading = function() {\n return this.$loaded == Message.STATUS.LOADING;\n };\n\n /**\n * @function $reload\n * @memberof Message.prototype\n * @desc Fetch the viewable message body along with other metadata such as the list of attachments.\n * @param {object} [options] - set {useCache: true} to use already fetched data\n * @returns a promise of the HTTP operation\n */\n Message.prototype.$reload = function(options) {\n var _this = this, futureMessageData;\n\n if (options && options.useCache && this.$futureMessageData) {\n if (!this.isread) {\n Message.$$resource.fetch(this.$absolutePath(), 'markMessageRead').then(function() {\n Message.$timeout(function() {\n _this.isread = true;\n _this.$mailbox.unseenCount--;\n });\n });\n }\n return this;\n }\n\n futureMessageData = Message.$$resource.fetch(this.$absolutePath(options), 'view');\n\n return this.$unwrap(futureMessageData);\n };\n\n /**\n * @function $reply\n * @memberof Message.prototype\n * @desc Prepare a new Message object as a reply to the sender.\n * @returns a promise of the HTTP operations\n */\n Message.prototype.$reply = function() {\n return this.$newDraft('reply');\n };\n\n /**\n * @function $replyAll\n * @memberof Message.prototype\n * @desc Prepare a new Message object as a reply to the sender and all recipients.\n * @returns a promise of the HTTP operations\n */\n Message.prototype.$replyAll = function() {\n return this.$newDraft('replyall');\n };\n\n /**\n * @function $forward\n * @memberof Message.prototype\n * @desc Prepare a new Message object as a forward.\n * @returns a promise of the HTTP operations\n */\n Message.prototype.$forward = function() {\n return this.$newDraft('forward');\n };\n\n /**\n * @function $newDraft\n * @memberof Message.prototype\n * @desc Prepare a new Message object as a reply or a forward of the current message and associated\n * to the draft mailbox.\n * @see {@link Account.$newMessage}\n * @see {@link Message.$editableContent}\n * @see {@link Message.$reply}\n * @see {@link Message.$replyAll}\n * @see {@link Message.$forwad}\n * @param {string} action - the HTTP action to perform on the message\n * @returns a promise of the HTTP operations\n */\n Message.prototype.$newDraft = function(action) {\n var _this = this;\n\n // Query server for draft folder and draft UID\n return Message.$$resource.fetch(this.$absolutePath(), action).then(function(data) {\n var mailbox, message;\n Message.$log.debug('New ' + action + ': ' + JSON.stringify(data, undefined, 2));\n mailbox = _this.$mailbox.$account.$getMailboxByPath(data.mailboxPath);\n message = new Message(data.accountId, mailbox, data);\n // Fetch draft initial data\n return Message.$$resource.fetch(message.$absolutePath({asDraft: true}), 'edit').then(function(data) {\n Message.$log.debug('New ' + action + ': ' + JSON.stringify(data, undefined, 2) + ' original UID: ' + _this.uid);\n angular.extend(message.editable, data);\n\n // We keep a reference to our original message in order to update the flags\n message.origin = {message: _this, action: action};\n return message;\n });\n });\n };\n\n /**\n * @function $save\n * @memberof Message.prototype\n * @desc Save the message to the server.\n * @returns a promise of the HTTP operation\n */\n Message.prototype.$save = function() {\n var _this = this,\n data = this.editable;\n\n Message.$log.debug('save = ' + JSON.stringify(data, undefined, 2));\n\n return Message.$$resource.save(this.$absolutePath({asDraft: true}), data).then(function(response) {\n Message.$log.debug('save = ' + JSON.stringify(response, undefined, 2));\n _this.$setUID(response.uid);\n _this.$reload(); // fetch a new viewable version of the message\n _this.isNew = false;\n });\n };\n\n /**\n * @function $send\n * @memberof Message.prototype\n * @desc Send the message.\n * @returns a promise of the HTTP operation\n */\n Message.prototype.$send = function() {\n var _this = this,\n data = angular.copy(this.editable);\n\n Message.$log.debug('send = ' + JSON.stringify(data, undefined, 2));\n\n return Message.$$resource.post(this.$absolutePath({asDraft: true}), 'send', data).then(function(response) {\n if (response.status == 'success') {\n if (angular.isDefined(_this.origin)) {\n if (_this.origin.action.startsWith('reply'))\n _this.origin.message.isanswered = true;\n else if (_this.origin.action == 'forward')\n _this.origin.message.isforwarded = true;\n }\n return response;\n }\n else {\n return Message.$q.reject(response.data);\n }\n });\n };\n\n /**\n * @function $unwrap\n * @memberof Message.prototype\n * @desc Unwrap a promise.\n * @param {promise} futureMessageData - a promise of some of the Message's data\n */\n Message.prototype.$unwrap = function(futureMessageData) {\n var _this = this;\n\n // Message is not loaded yet\n this.$loaded = Message.STATUS.DELAYED_LOADING;\n Message.$timeout(function() {\n if (_this.$loaded != Message.STATUS.LOADED)\n _this.$loaded = Message.STATUS.LOADING;\n }, Message.STATUS.DELAYED_MS);\n\n // Resolve and expose the promise\n this.$futureMessageData = futureMessageData.then(function(data) {\n // Calling $timeout will force Angular to refresh the view\n if (_this.isread === 0) {\n _this.isread = true;\n _this.$mailbox.unseenCount--;\n }\n return Message.$timeout(function() {\n angular.extend(_this, data);\n _this.$formatFullAddresses();\n _this.$loadUnsafeContent = false;\n _this.$loaded = Message.STATUS.LOADED;\n return _this;\n });\n });\n\n return this.$futureMessageData;\n };\n\n /**\n * @function $omit\n * @memberof Message.prototype\n * @desc Return a sanitized object used to send to the server.\n * @return an object literal copy of the Message instance\n */\n Message.prototype.$omit = function(options) {\n var message = {},\n privateAttributes = options && options.privateAttributes;\n angular.forEach(this, function(value, key) {\n if (key != 'constructor' && key[0] != '$' || privateAttributes) {\n message[key] = value;\n }\n });\n\n return message;\n };\n\n /**\n * @function download\n * @memberof Message.prototype\n * @desc Download the current message\n * @returns a promise of the HTTP operation\n */\n Message.prototype.download = function() {\n var data, options;\n\n data = { uids: [this.uid] };\n options = { filename: this.subject + '.zip' };\n\n return Message.$$resource.download(this.$mailbox.id, 'saveMessages', data, options);\n };\n\n /**\n * @function downloadAttachments\n * @memberof Message.prototype\n * @desc Download an archive of all attachments\n * @returns a promise of the HTTP operation\n */\n Message.prototype.downloadAttachments = function() {\n var options;\n\n options = { filename: l('attachments') + \"-\" + this.uid + \".zip\" };\n\n return Message.$$resource.download(this.$absolutePath(), 'archiveAttachments', null, options);\n };\n\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @name VirtualMailbox\n * @constructor\n * @param {object} account - the mail account associated with the virtual search\n */\n function VirtualMailbox(account) {\n this.$account = account;\n }\n\n /**\n * @memberof VirtualMailbox\n * @desc The factory we'll use to register with Angular\n * @returns the VirtualMailbox constructor\n */\n VirtualMailbox.$factory = ['$q', '$timeout', '$log', 'sgSettings', 'Resource', 'Message', 'Mailbox', 'sgMailbox_PRELOAD', function($q, $timeout, $log, Settings, Resource, Mailbox, Message, PRELOAD) {\n angular.extend(VirtualMailbox, {\n $q: $q,\n $timeout: $timeout,\n $log: $log,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Mail', Settings.activeUser()),\n $Message: Message,\n selectedFolder: null,\n PRELOAD: PRELOAD\n });\n\n return VirtualMailbox; // return constructor\n }];\n\n /**\n * @module SOGo.MailerUI\n * @desc Factory registration of VirtualMailbox in Angular module.\n */\n try {\n angular.module('SOGo.MailerUI');\n }\n catch(e) {\n angular.module('SOGo.MailerUI', ['SOGo.Common']);\n }\n angular.module('SOGo.MailerUI')\n .constant('sgMailbox_PRELOAD', {\n LOOKAHEAD: 50,\n SIZE: 100\n })\n .factory('VirtualMailbox', VirtualMailbox.$factory);\n\n /**\n * @memberof VirtualMailbox\n * @desc Build the path of the virtual mailbox (or account only).\n * @param {string} accountId - the account ID\n * @returns a string representing the path relative to the mail module\n */\n VirtualMailbox.$absolutePath = function(accountId) {\n return [accountId, \"virtual\"].join('/');\n };\n\n /**\n * @function init\n * @memberof VirtualMailbox.prototype\n * @desc Extend instance with new data and compute additional attributes.\n * @param {object} data - attributes of mailbox\n */\n VirtualMailbox.prototype.init = function(data) {\n this.$isLoading = false;\n this.$mailboxes = [];\n this.uidsMap = {};\n angular.extend(this, data);\n this.id = this.$id();\n };\n\n VirtualMailbox.prototype.setMailboxes = function(data) {\n this.$mailboxes = data;\n\n _.forEach(this.$mailboxes, function(mailbox) {\n mailbox.$messages = [];\n mailbox.uidsMap = {};\n });\n };\n\n VirtualMailbox.prototype.startSearch = function(match, params) {\n var _this = this,\n search = VirtualMailbox.$q.when();\n\n this.$isLoading = true;\n\n _.forEach(this.$mailboxes, function(mailbox) {\n search = search.then(function() {\n if (_this.$isLoading) {\n VirtualMailbox.$log.debug(\"searching mailbox \" + mailbox.path);\n return mailbox.$filter( {sort: \"date\", asc: false, match: match}, params);\n }\n });\n });\n\n search.finally(function() {\n _this.$isLoading = false;\n });\n };\n\n VirtualMailbox.prototype.stopSearch = function() {\n VirtualMailbox.$log.debug(\"stopping search...\");\n this.$isLoading = false;\n };\n\n /**\n * @function selectFolder\n * @memberof VirtualMailbox.prototype\n * @desc A no-op for virtual mailbox\n */\n VirtualMailbox.prototype.selectFolder = function() {\n return;\n };\n\n /**\n * @function resetSelectedMessage\n * @memberof VirtualMailbox.prototype\n * @desc Delete 'selectedMessage' attribute of all submailboxes.\n */\n VirtualMailbox.prototype.resetSelectedMessage = function() {\n _.forEach(this.$mailboxes, function(mailbox) {\n delete mailbox.selectedMessage;\n });\n };\n\n /**\n * @function hasSelectedMessage\n * @memberof VirtualMailbox.prototype\n * @desc Check if a message is selected among the resulting mailboxes\n * @returns true if one message is selected\n */\n VirtualMailbox.prototype.hasSelectedMessage = function() {\n return angular.isDefined(_.find(this.$mailboxes, function(mailbox) {\n return angular.isDefined(mailbox.selectedMessage);\n }));\n };\n\n /**\n * @function isSelectedMessage\n * @memberof VirtualMailbox.prototype\n * @desc Check if the message of the specified mailbox is selected.\n * @param {string} messageId\n * @param {string} mailboxPath\n * @returns true if the specified message is selected\n */\n VirtualMailbox.prototype.isSelectedMessage = function(messageId, mailboxPath) {\n return angular.isDefined(_.find(this.$mailboxes, function(mailbox) {\n return mailbox.path == mailboxPath && mailbox.selectedMessage == messageId;\n }));\n };\n\n /**\n * @function getLength\n * @memberof VirtualMailbox.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the number of items in the mailbox\n */\n VirtualMailbox.prototype.getLength = function() {\n var len = 0;\n\n if (!angular.isDefined(this.$mailboxes))\n return len;\n\n _.forEach(this.$mailboxes, function(mailbox) {\n len += mailbox.$messages.length;\n });\n\n return len;\n };\n\n /**\n * @function getItemAtIndex\n * @memberof VirtualMailbox.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the message as the specified index\n */\n VirtualMailbox.prototype.getItemAtIndex = function(index) {\n var i, j, k, mailbox, message;\n\n if (angular.isDefined(this.$mailboxes) && index >= 0) {\n i = 0;\n for (j = 0; j < this.$mailboxes.length; j++) {\n mailbox = this.$mailboxes[j];\n for (k = 0; k < mailbox.$messages.length; i++, k++) {\n message = mailbox.$messages[k];\n if (i == index) {\n if (mailbox.$loadMessage(message.uid))\n return message;\n }\n }\n }\n }\n\n return null;\n };\n\n /**\n * @function $id\n * @memberof VirtualMailbox.prototype\n * @desc Build the unique ID to identified the mailbox.\n * @returns a string representing the path relative to the mail module\n */\n VirtualMailbox.prototype.$id = function() {\n return VirtualMailbox.$absolutePath(this.$account.id);\n };\n\n /**\n * @function $selectedMessages\n * @memberof VirtualMailbox.prototype\n * @desc Return an associative array of the selected messages for each mailbox. Keys are the mailboxes ids.\n * @returns an associative array\n */\n VirtualMailbox.prototype.$selectedMessages = function() {\n var messagesMap = {};\n return _.transform(this.$mailboxes, function(messagesMap, mailbox) {\n messagesMap[mailbox.id] = mailbox.$selectedMessages();\n }, {});\n };\n\n /**\n * @function $selectedCount\n * @memberof VirtualMailbox.prototype\n * @desc Return the number of messages selected by the user.\n * @returns the number of selected messages\n */\n VirtualMailbox.prototype.$selectedCount = function() {\n return _.sum(_.invokeMap(this.$mailboxes, '$selectedCount'));\n };\n\n /**\n * @function $flagMessages\n * @memberof VirtualMailbox.prototype\n * @desc Add or remove a flag on a message set\n * @param {object} messagesMap\n * @param {array} flags\n * @param {string} operation\n * @returns a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$flagMessages = function(messagesMap, flags, operation) {\n var data = {\n flags: flags,\n operation: operation\n };\n var allMessages = [];\n var promises = [];\n\n _.forEach(messagesMap, function(messages, id) {\n if (messages.length > 0) {\n var uids = _.map(messages, 'uid');\n allMessages.push(messages);\n var promise = VirtualMailbox.$$resource.post(id, 'addOrRemoveLabel', _.assign(data, {msgUIDs: uids}));\n promises.push(promise);\n }\n });\n\n return VirtualMailbox.$q.all(promises).then(function() {\n return _.flatten(allMessages);\n });\n };\n\n /**\n * @function $deleteMessages\n * @memberof VirtualMailbox.prototype\n * @desc Delete multiple messages from mailbox.\n * @param {object} messagesMap\n * @return a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$deleteMessages = function(messagesMap) {\n var promises = [];\n\n _.forEach(messagesMap, function(messages, id) {\n if (messages.length > 0) {\n var mailbox = messages[0].$mailbox;\n var promise = mailbox.$deleteMessages(messages);\n promises.push(promise);\n }\n });\n\n return VirtualMailbox.$q.all(promises);\n };\n\n /**\n * @function $markOrUnMarkMessagesAsJunk\n * @memberof VirtualMailbox.prototype\n * @desc Mark messages as junk/not junk\n * @param {object} messagesMap\n * @return a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$markOrUnMarkMessagesAsJunk = function(messagesMap) {\n var promises = [];\n\n _.forEach(messagesMap, function(messages, id) {\n if (messages.length > 0) {\n var mailbox = messages[0].$mailbox;\n var promise = mailbox.$markOrUnMarkMessagesAsJunk(messages);\n promises.push(promise);\n }\n });\n\n return VirtualMailbox.$q.all(promises);\n };\n\n /**\n * @function $copyMessages\n * @memberof VirtualMailbox.prototype\n * @desc Copy multiple messages from the current mailbox to a target one\n * @param {object} messagesMap\n * @param {string} folder\n * @return a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$copyMessages = function(messagesMap, folder) {\n var promises = [];\n\n _.forEach(messagesMap, function(messages, id) {\n if (messages.length > 0) {\n var mailbox = messages[0].$mailbox;\n var promise = mailbox.$copyMessages(messages, folder);\n promises.push(promise);\n }\n });\n\n return VirtualMailbox.$q.all(promises);\n };\n\n /**\n * @function $moveMessages\n * @memberof VirtualMailbox.prototype\n * @desc Move multiple messages from the current mailbox to a target one\n * @param {object} messagesMap\n * @param {string} folder\n * @return a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$moveMessages = function(messagesMap, folder) {\n var promises = [];\n\n _.forEach(messagesMap, function(messages, id) {\n if (messages.length > 0) {\n var mailbox = messages[0].$mailbox;\n var promise = mailbox.$moveMessages(messages, folder);\n promises.push(promise);\n }\n });\n\n return VirtualMailbox.$q.all(promises);\n };\n\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n MailboxController.$inject = ['$window', '$scope', '$timeout', '$q', '$state', '$mdDialog', '$mdToast', 'stateAccounts', 'stateAccount', 'stateMailbox', 'sgHotkeys', 'encodeUriFilter', 'sgSettings', 'sgFocus', 'Dialog', 'Account', 'Mailbox'];\n function MailboxController($window, $scope, $timeout, $q, $state, $mdDialog, $mdToast, stateAccounts, stateAccount, stateMailbox, sgHotkeys, encodeUriFilter, sgSettings, focus, Dialog, Account, Mailbox) {\n var vm = this,\n defaultWindowTitle = angular.element($window.document).find('title').attr('sg-default') || \"SOGo\",\n hotkeys = [];\n\n // Expose controller for eventual popup windows\n $window.$mailboxController = vm;\n\n vm.service = Mailbox;\n vm.accounts = stateAccounts;\n vm.account = stateAccount;\n vm.selectedFolder = stateMailbox;\n vm.selectMessage = selectMessage;\n vm.messageDialog = null; // also access from Message controller\n vm.toggleMessageSelection = toggleMessageSelection;\n vm.sort = sort;\n vm.sortedBy = sortedBy;\n vm.searchMode = searchMode;\n vm.cancelSearch = cancelSearch;\n vm.newMessage = newMessage;\n vm.mode = { search: false, multiple: 0 };\n vm.confirmDeleteSelectedMessages = confirmDeleteSelectedMessages;\n vm.markOrUnMarkMessagesAsJunk = markOrUnMarkMessagesAsJunk;\n vm.copySelectedMessages = copySelectedMessages;\n vm.moveSelectedMessages = moveSelectedMessages;\n vm.markSelectedMessagesAsFlagged = markSelectedMessagesAsFlagged;\n vm.markSelectedMessagesAsUnread = markSelectedMessagesAsUnread;\n vm.markSelectedMessagesAsRead = markSelectedMessagesAsRead;\n vm.selectAll = selectAll;\n vm.unselectMessages = unselectMessages;\n\n\n stateMailbox.selectFolder();\n\n _registerHotkeys(hotkeys);\n\n // Expunge mailbox when leaving the Mail module\n angular.element($window).on('beforeunload', _compactBeforeUnload);\n $scope.$on('$destroy', function() {\n angular.element($window).off('beforeunload', _compactBeforeUnload);\n // Deregister hotkeys\n _.forEach(hotkeys, function(key) {\n sgHotkeys.deregisterHotkey(key);\n });\n });\n\n // Update window's title with unseen messages count of selected mailbox\n $scope.$watch(function() { return vm.selectedFolder.unseenCount; }, function(unseenCount) {\n var title = defaultWindowTitle + ' - ';\n if (unseenCount)\n title += '(' + unseenCount + ') ';\n title += vm.selectedFolder.$displayName;\n $window.document.title = title;\n });\n\n\n function _registerHotkeys(keys) {\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_search'),\n description: l('Search'),\n callback: searchMode\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_compose'),\n description: l('Write a new message'),\n callback: function($event) {\n if (vm.messageDialog === null)\n newMessage($event);\n }\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_junk'),\n description: l('Mark the selected messages as junk'),\n callback: markOrUnMarkMessagesAsJunk\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'space',\n description: l('Toggle item'),\n callback: toggleMessageSelection\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'shift+space',\n description: l('Toggle range of items'),\n callback: toggleMessageSelection\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'up',\n description: l('View next item'),\n callback: _nextMessage,\n preventInClass: ['sg-mail-part']\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'down',\n description: l('View previous item'),\n callback: _previousMessage,\n preventInClass: ['sg-mail-part']\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'shift+up',\n description: l('Add next item to selection'),\n callback: _addNextMessageToSelection,\n preventInClass: ['sg-mail-part']\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'shift+down',\n description: l('Add previous item to selection'),\n callback: _addPreviousMessageToSelection,\n preventInClass: ['sg-mail-part']\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'backspace',\n description: l('Delete selected message or folder'),\n callback: confirmDeleteSelectedMessages\n }));\n\n // Register the hotkeys\n _.forEach(keys, function(key) {\n sgHotkeys.registerHotkey(key);\n });\n }\n\n function _compactBeforeUnload(event) {\n return vm.selectedFolder.$compact();\n }\n\n function sort(field) {\n vm.selectedFolder.$filter({ sort: field });\n }\n\n function sortedBy(field) {\n return Mailbox.$query.sort == field;\n }\n\n function searchMode() {\n vm.mode.search = true;\n focus('search');\n }\n\n function cancelSearch() {\n vm.mode.search = false;\n vm.selectedFolder.$filter().then(function() {\n if (vm.selectedFolder.selectedMessage) {\n $timeout(function() {\n vm.selectedFolder.$topIndex = vm.selectedFolder.uidsMap[vm.selectedFolder.selectedMessage];\n });\n }\n });\n }\n\n function newMessage($event, inPopup) {\n var message;\n\n if (vm.messageDialog === null) {\n if (inPopup)\n _newMessageInPopup();\n else {\n message = vm.account.$newMessage();\n vm.messageDialog = $mdDialog\n .show({\n parent: angular.element(document.body),\n targetEvent: $event,\n clickOutsideToClose: false,\n escapeToClose: false,\n templateUrl: 'UIxMailEditor',\n controller: 'MessageEditorController',\n controllerAs: 'editor',\n locals: {\n stateAccount: vm.account,\n stateMessage: message\n }\n })\n .finally(function() {\n vm.messageDialog = null;\n });\n }\n }\n }\n\n function _newMessageInPopup() {\n var url = [sgSettings.baseURL(),\n 'UIxMailPopupView#!/Mail',\n vm.account.id,\n // The double-encoding is necessary\n encodeUriFilter(encodeUriFilter(vm.selectedFolder.path)),\n 'new']\n .join('/'),\n wId = vm.selectedFolder.$id() + '/' + Math.random(0, 1000);\n console.debug(url);\n $window.open(url, wId,\n [\"width=680\",\n \"height=520\",\n \"resizable=1\",\n \"scrollbars=1\",\n \"toolbar=0\",\n \"location=0\",\n \"directories=0\",\n \"status=0\",\n \"menubar=0\",\n \"copyhistory=0\"]\n .join(','));\n }\n\n /**\n * User has pressed up arrow key\n */\n function _nextMessage($event) {\n var index = vm.selectedFolder.$selectedMessageIndex();\n\n if (angular.isDefined(index)) {\n index--;\n if (vm.selectedFolder.$topIndex > 0)\n vm.selectedFolder.$topIndex--;\n }\n else {\n // No message is selected, show oldest message\n index = vm.selectedFolder.getLength() - 1;\n vm.selectedFolder.$topIndex = vm.selectedFolder.getLength();\n }\n\n if (index > -1)\n selectMessage(vm.selectedFolder.$messages[index]);\n\n $event.preventDefault();\n\n return index;\n }\n\n /**\n * User has pressed the down arrow key\n */\n function _previousMessage($event) {\n var index = vm.selectedFolder.$selectedMessageIndex();\n\n if (angular.isDefined(index)) {\n index++;\n if (vm.selectedFolder.$topIndex < vm.selectedFolder.getLength())\n vm.selectedFolder.$topIndex++;\n }\n else\n // No message is selected, show newest\n index = 0;\n\n if (index < vm.selectedFolder.getLength())\n selectMessage(vm.selectedFolder.$messages[index]);\n else\n index = -1;\n\n $event.preventDefault();\n\n return index;\n }\n\n function _addNextMessageToSelection($event) {\n var index;\n\n if (vm.selectedFolder.hasSelectedMessage()) {\n index = _nextMessage($event);\n if (index >= 0)\n toggleMessageSelection($event, vm.selectedFolder.$messages[index]);\n }\n }\n\n function _addPreviousMessageToSelection($event) {\n var index;\n\n if (vm.selectedFolder.hasSelectedMessage()) {\n index = _previousMessage($event);\n if (index >= 0)\n toggleMessageSelection($event, vm.selectedFolder.$messages[index]);\n }\n }\n\n function selectMessage(message) {\n if (Mailbox.$virtualMode)\n $state.go('mail.account.virtualMailbox.message', {mailboxId: encodeUriFilter(message.$mailbox.path), messageId: message.uid});\n else\n $state.go('mail.account.mailbox.message', {messageId: message.uid});\n }\n\n function toggleMessageSelection($event, message) {\n var folder = vm.selectedFolder,\n selectedIndex, nextSelectedIndex, i;\n\n if (!message)\n message = folder.$selectedMessage();\n message.selected = !message.selected;\n vm.mode.multiple += message.selected? 1 : -1;\n\n // Select closest range of messages when shift key is pressed\n if ($event.shiftKey && folder.$selectedCount() > 1) {\n selectedIndex = folder.uidsMap[message.uid];\n // Search for next selected message above\n nextSelectedIndex = selectedIndex - 2;\n while (nextSelectedIndex >= 0 &&\n !folder.$messages[nextSelectedIndex].selected)\n nextSelectedIndex--;\n if (nextSelectedIndex < 0) {\n // Search for next selected message bellow\n nextSelectedIndex = selectedIndex + 2;\n while (nextSelectedIndex < folder.getLength() &&\n !folder.$messages[nextSelectedIndex].selected)\n nextSelectedIndex++;\n }\n if (nextSelectedIndex >= 0 && nextSelectedIndex < folder.getLength()) {\n for (i = Math.min(selectedIndex, nextSelectedIndex);\n i <= Math.max(selectedIndex, nextSelectedIndex);\n i++)\n folder.$messages[i].selected = true;\n }\n }\n\n $event.preventDefault();\n $event.stopPropagation();\n }\n\n /**\n * Batch operations\n */\n\n function _currentMailboxes() {\n if (Mailbox.$virtualMode)\n return vm.selectedFolder.$mailboxes;\n else\n return [vm.selectedFolder];\n }\n\n // Unselect current message and cleverly load the next message.\n // This function must not be called in virtual mode.\n function _unselectMessage(message, index) {\n var nextMessage, previousMessage, nextIndex = index;\n vm.mode.multiple = vm.selectedFolder.$selectedCount();\n if (message) {\n // Select either the next or previous message\n if (index > 0) {\n nextIndex -= 1;\n nextMessage = vm.selectedFolder.$messages[nextIndex];\n }\n if (index < vm.selectedFolder.$messages.length)\n previousMessage = vm.selectedFolder.$messages[index];\n if (nextMessage) {\n if (nextMessage.isread && previousMessage && !previousMessage.isread) {\n nextIndex = index;\n nextMessage = previousMessage;\n }\n }\n else if (previousMessage) {\n nextIndex = index;\n nextMessage = previousMessage;\n }\n if (nextMessage) {\n vm.selectedFolder.$topIndex = nextIndex;\n $state.go('mail.account.mailbox.message', { messageId: nextMessage.uid });\n }\n else {\n $state.go('mail.account.mailbox');\n }\n }\n else {\n $timeout(function() {\n console.warn('go to mailbox');\n $state.go('mail.account.mailbox');\n });\n }\n }\n\n function confirmDeleteSelectedMessages($event) {\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n\n if (vm.messageDialog === null && _.size(selectedMessages) > 0)\n vm.messageDialog = Dialog.confirm(l('Confirmation'),\n l('Are you sure you want to delete the selected messages?'),\n { ok: l('Delete') })\n .then(function() {\n var deleteSelectedMessage = vm.selectedFolder.hasSelectedMessage();\n vm.selectedFolder.$deleteMessages(selectedMessages).then(function(index) {\n if (Mailbox.$virtualMode) {\n // When performing an advanced search, we refresh the view if the selected message\n // was deleted, but only once all promises have completed.\n if (deleteSelectedMessage)\n $state.go('mail.account.virtualMailbox');\n }\n else {\n // In normal mode, we immediately unselect the selected message.\n _unselectMessage(deleteSelectedMessage, index);\n }\n }, function(response) {\n vm.messageDialog = Dialog.confirm(l('Warning'),\n l('The messages could not be moved to the trash folder. Would you like to delete them immediately?'),\n { ok: l('Delete') })\n .then(function() {\n vm.selectedFolder.$deleteMessages(selectedMessages, { withoutTrash: true }).then(function(index) {\n if (Mailbox.$virtualMode) {\n // When performing an advanced search, we refresh the view if the selected message\n // was deleted, but only once all promises have completed.\n if (deleteSelectedMessage)\n $state.go('mail.account.virtualMailbox');\n }\n else {\n // In normal mode, we immediately unselect the selected message.\n _unselectMessage(deleteSelectedMessage, index);\n }\n });\n });\n });\n })\n .finally(function() {\n vm.messageDialog = null;\n });\n\n $event.preventDefault();\n }\n\n function markOrUnMarkMessagesAsJunk() {\n var moveSelectedMessage = vm.selectedFolder.hasSelectedMessage();\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n if (_.size(selectedMessages) === 0 && moveSelectedMessage)\n selectedMessages = [vm.selectedFolder.$selectedMessage()];\n if (_.size(selectedMessages) > 0)\n vm.selectedFolder.$markOrUnMarkMessagesAsJunk(selectedMessages).then(function() {\n var dstFolder = '/' + vm.account.id + '/folderINBOX';\n if (vm.selectedFolder.type != 'junk') {\n dstFolder = '/' + vm.account.$getMailboxByType('junk').id;\n }\n vm.selectedFolder.$moveMessages(selectedMessages, dstFolder).then(function(index) {\n if (Mailbox.$virtualMode) {\n // When performing an advanced search, we refresh the view if the selected message\n // was deleted, but only once all promises have completed.\n if (moveSelectedMessage)\n $state.go('mail.account.virtualMailbox');\n }\n else {\n // In normal mode, we immediately unselect the selected message.\n _unselectMessage(moveSelectedMessage, index);\n }\n });\n });\n }\n\n function copySelectedMessages(dstFolder) {\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n if (_.size(selectedMessages) > 0)\n vm.selectedFolder.$copyMessages(selectedMessages, '/' + dstFolder).then(function() {\n $mdToast.show(\n $mdToast.simple()\n .content(l('%{0} message(s) copied', vm.selectedFolder.$selectedCount()))\n .position('top right')\n .hideDelay(2000));\n });\n }\n\n function moveSelectedMessages(dstFolder) {\n var moveSelectedMessage = vm.selectedFolder.hasSelectedMessage();\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n var count = vm.selectedFolder.$selectedCount();\n if (_.size(selectedMessages) > 0)\n vm.selectedFolder.$moveMessages(selectedMessages, '/' + dstFolder).then(function(index) {\n $mdToast.show(\n $mdToast.simple()\n .content(l('%{0} message(s) moved', count))\n .position('top right')\n .hideDelay(2000));\n if (Mailbox.$virtualMode) {\n // When performing an advanced search, we refresh the view if the selected message\n // was moved, but only once all promises have completed.\n if (moveSelectedMessage)\n $state.go('mail.account.virtualMailbox');\n }\n else {\n // In normal mode, we immediately unselect the selected message.\n _unselectMessage(moveSelectedMessage, index);\n }\n });\n }\n\n function selectAll() {\n var count = 0;\n _.forEach(_currentMailboxes(), function(folder) {\n var i = 0, length = folder.$messages.length;\n for (; i < length; i++)\n folder.$messages[i].selected = true;\n count += length;\n });\n vm.mode.multiple = count;\n }\n\n function unselectMessages() {\n _.forEach(_currentMailboxes(), function(folder) {\n _.forEach(folder.$messages, function(message) {\n message.selected = false;\n });\n });\n vm.mode.multiple = 0;\n }\n\n function markSelectedMessagesAsFlagged() {\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n if (_.size(selectedMessages) > 0)\n vm.selectedFolder.$flagMessages(selectedMessages, '\\\\Flagged', 'add').then(function(messages) {\n _.forEach(messages, function(message) {\n message.isflagged = true;\n });\n });\n }\n\n function markSelectedMessagesAsUnread() {\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n if (_.size(selectedMessages) > 0) {\n vm.selectedFolder.$flagMessages(selectedMessages, 'seen', 'remove').then(function(messages) {\n _.forEach(messages, function(message) {\n if (message.isread)\n message.$mailbox.unseenCount++;\n message.isread = false;\n });\n });\n }\n }\n\n function markSelectedMessagesAsRead() {\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n if (_.size(selectedMessages) > 0) {\n vm.selectedFolder.$flagMessages(selectedMessages, 'seen', 'add').then(function(messages) {\n _.forEach(messages, function(message) {\n if (!message.isread)\n message.$mailbox.unseenCount--;\n message.isread = true;\n });\n });\n }\n }\n\n }\n\n angular\n .module('material.components.virtualRepeat')\n .decorator('mdVirtualRepeatContainerDirective', mdVirtualRepeatContainerDirectiveDecorator);\n\n /**\n * @ngInject\n */\n mdVirtualRepeatContainerDirectiveDecorator.$inject = ['$delegate'];\n function mdVirtualRepeatContainerDirectiveDecorator($delegate) {\n $delegate[0].controller.prototype.resetScroll = function() {\n // Don't scroll to top if current virtual repeater is the messages list\n // but do update the container size\n if (this.$element.parent().attr('id') == 'messagesList')\n this.updateSize();\n else\n this.scrollTo(0);\n };\n return $delegate;\n }\n\n angular\n .module('SOGo.MailerUI')\n .controller('MailboxController', MailboxController);\n})();\n\n","/* -*- Mode: js; indent-tabs-mode: nil; js-indent-level: 2; -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n MailboxesController.$inject = ['$scope', '$state', '$timeout', '$window', '$mdDialog', '$mdToast', '$mdMedia', '$mdSidenav', 'sgConstant', 'sgFocus', 'encodeUriFilter', 'Dialog', 'sgSettings', 'sgHotkeys', 'Account', 'Mailbox', 'VirtualMailbox', 'User', 'Preferences', 'stateAccounts'];\n function MailboxesController($scope, $state, $timeout, $window, $mdDialog, $mdToast, $mdMedia, $mdSidenav, sgConstant, focus, encodeUriFilter, Dialog, Settings, sgHotkeys, Account, Mailbox, VirtualMailbox, User, Preferences, stateAccounts) {\n var vm = this,\n account,\n mailbox,\n hotkeys = [];\n\n vm.service = Mailbox;\n vm.accounts = stateAccounts;\n vm.toggleAccountState = toggleAccountState;\n vm.subscribe = subscribe;\n vm.newFolder = newFolder;\n vm.delegate = delegate;\n vm.editFolder = editFolder;\n vm.revertEditing = revertEditing;\n vm.selectFolder = selectFolder;\n vm.saveFolder = saveFolder;\n vm.compactFolder = compactFolder;\n vm.emptyTrashFolder = emptyTrashFolder;\n vm.confirmDelete = confirmDelete;\n vm.markFolderRead = markFolderRead;\n vm.share = share;\n vm.setFolderAs = setFolderAs;\n vm.refreshUnseenCount = refreshUnseenCount;\n vm.isDroppableFolder = isDroppableFolder;\n vm.dragSelectedMessages = dragSelectedMessages;\n\n // Advanced search options\n vm.showingAdvancedSearch = false;\n vm.currentSearchParam = '';\n vm.addSearchParam = addSearchParam;\n vm.newSearchParam = newSearchParam;\n vm.showAdvancedSearch = showAdvancedSearch;\n vm.hideAdvancedSearch = hideAdvancedSearch;\n vm.toggleAdvancedSearch = toggleAdvancedSearch;\n vm.search = {\n options: {'': '', // no placeholder when no criteria is active\n subject: l('Enter Subject'),\n from: l('Enter From'),\n to: l('Enter To'),\n cc: l('Enter Cc'),\n body: l('Enter Body')\n },\n mailbox: 'INBOX',\n subfolders: 1,\n match: 'AND',\n params: []\n };\n\n\n Preferences.ready().then(function() {\n vm.showSubscribedOnly = Preferences.defaults.SOGoMailShowSubscribedFoldersOnly;\n });\n\n vm.refreshUnseenCount();\n\n _registerHotkeys(hotkeys);\n\n $scope.$on('$destroy', function() {\n // Deregister hotkeys\n _.forEach(hotkeys, function(key) {\n sgHotkeys.deregisterHotkey(key);\n });\n });\n\n\n function _registerHotkeys(keys) {\n keys.push(sgHotkeys.createHotkey({\n key: 'backspace',\n description: l('Delete selected message or folder'),\n callback: function() {\n if (Mailbox.selectedFolder && !Mailbox.selectedFolder.hasSelectedMessage())\n confirmDelete(Mailbox.selectedFolder);\n }\n }));\n\n // Register the hotkeys\n _.forEach(keys, function(key) {\n sgHotkeys.registerHotkey(key);\n });\n }\n\n function showAdvancedSearch(path) {\n vm.showingAdvancedSearch = true;\n vm.search.mailbox = path;\n // Close sidenav on small devices\n if (!$mdMedia(sgConstant['gt-md']))\n $mdSidenav('left').close();\n }\n\n function hideAdvancedSearch() {\n vm.showingAdvancedSearch = false;\n vm.service.$virtualMode = false;\n\n account = vm.accounts[0];\n mailbox = vm.searchPreviousMailbox;\n $state.go('mail.account.mailbox', { accountId: account.id, mailboxId: encodeUriFilter(mailbox.path) });\n }\n\n function toggleAdvancedSearch() {\n if (Mailbox.selectedFolder.$isLoading) {\n // Stop search\n vm.virtualMailbox.stopSearch();\n }\n else {\n // Start search\n var root, mailboxes = [],\n _visit = function(folders) {\n _.forEach(folders, function(o) {\n mailboxes.push(o);\n if (o.children && o.children.length > 0) {\n _visit(o.children);\n }\n });\n };\n\n vm.virtualMailbox = new VirtualMailbox(vm.accounts[0]);\n\n // Don't set the previous selected mailbox if we're in virtual mode\n // That allows users to do multiple advanced search but return\n // correctly to the previously selected mailbox once done.\n if (!Mailbox.$virtualMode)\n vm.searchPreviousMailbox = Mailbox.selectedFolder;\n\n Mailbox.selectedFolder = vm.virtualMailbox;\n Mailbox.$virtualMode = true;\n\n if (angular.isDefined(vm.search.mailbox)) {\n root = vm.accounts[0].$getMailboxByPath(vm.search.mailbox);\n mailboxes.push(root);\n if (vm.search.subfolders && root.children.length)\n _visit(root.children);\n }\n else {\n mailboxes = vm.accounts[0].$flattenMailboxes();\n }\n\n vm.virtualMailbox.setMailboxes(mailboxes);\n vm.virtualMailbox.startSearch(vm.search.match, vm.search.params);\n $state.go('mail.account.virtualMailbox', { accountId: vm.accounts[0].id });\n }\n }\n\n function addSearchParam(v) {\n vm.currentSearchParam = v;\n focus('advancedSearch');\n return false;\n }\n\n function newSearchParam(pattern) {\n if (pattern.length && vm.currentSearchParam.length) {\n var n = 0, searchParam = vm.currentSearchParam;\n if (pattern.startsWith(\"!\")) {\n n = 1;\n pattern = pattern.substring(1).trim();\n }\n vm.currentSearchParam = '';\n return { searchBy: searchParam, searchInput: pattern, negative: n };\n }\n }\n\n function toggleAccountState(account) {\n account.$expanded = !account.$expanded;\n account.$flattenMailboxes({ reload: true, saveState: true });\n // Fire a window resize to recompute the virtual-repeater.\n // This is a fix until the following issue is officially resolved:\n // https://github.com/angular/material/issues/7309\n $timeout(function() {\n angular.element($window).triggerHandler('resize');\n }, 150);\n }\n\n function subscribe(account) {\n $mdDialog.show({\n templateUrl: account.id + '/subscribe',\n controller: SubscriptionsDialogController,\n controllerAs: 'subscriptions',\n clickOutsideToClose: true,\n escapeToClose: true,\n locals: {\n srcAccount: account\n }\n }).finally(function() {\n account.$getMailboxes({reload: true});\n });\n\n /**\n * @ngInject\n */\n SubscriptionsDialogController.$inject = ['$scope', '$mdDialog', 'srcAccount'];\n function SubscriptionsDialogController($scope, $mdDialog, srcAccount) {\n var vm = this;\n\n vm.loading = true;\n vm.filter = { name: '' };\n vm.account = new Account({\n id: srcAccount.id,\n name: srcAccount.name\n });\n vm.close = close;\n\n vm.account.$getMailboxes({ reload: true, all: true }).then(function() {\n vm.loading = false;\n });\n\n function close() {\n $mdDialog.cancel();\n }\n }\n }\n\n function newFolder(parentFolder) {\n Dialog.prompt(l('New Folder...'),\n l('Enter the new name of your folder'))\n .then(function(name) {\n parentFolder.$newMailbox(parentFolder.id, name)\n .then(function() {\n // success\n }, function(data, status) {\n Dialog.alert(l('An error occured while creating the mailbox \"%{0}\".', name),\n l(data.error));\n });\n });\n }\n\n function delegate(account) {\n $mdDialog.show({\n templateUrl: account.id + '/delegation', // UI/Templates/MailerUI/UIxMailUserDelegation.wox\n controller: MailboxDelegationController,\n controllerAs: 'delegate',\n clickOutsideToClose: true,\n escapeToClose: true,\n locals: {\n User: User,\n account: account\n }\n });\n\n /**\n * @ngInject\n */\n MailboxDelegationController.$inject = ['$scope', '$mdDialog', 'User', 'account'];\n function MailboxDelegationController($scope, $mdDialog, User, account) {\n var vm = this;\n\n vm.users = account.delegates;\n vm.account = account;\n vm.userToAdd = '';\n vm.searchText = '';\n vm.userFilter = userFilter;\n vm.closeModal = closeModal;\n vm.removeUser = removeUser;\n vm.addUser = addUser;\n\n function userFilter($query) {\n return User.$filter($query, account.delegates);\n }\n\n function closeModal() {\n $mdDialog.hide();\n }\n\n function removeUser(user) {\n account.$removeDelegate(user.uid).catch(function(data, status) {\n Dialog.alert(l('Warning'), l('An error occured please try again.'));\n });\n }\n\n function addUser(data) {\n if (data) {\n account.$addDelegate(data).then(function() {\n vm.userToAdd = '';\n vm.searchText = '';\n }, function(error) {\n Dialog.alert(l('Warning'), error);\n });\n }\n }\n }\n } // delegate\n\n function editFolder(folder) {\n vm.editMode = folder.path;\n focus('mailboxName_' + folder.path);\n }\n\n function revertEditing(folder) {\n folder.$reset();\n vm.editMode = false;\n }\n\n function selectFolder($event, account, folder) {\n if (vm.editMode == folder.path)\n return;\n vm.editMode = false;\n vm.showingAdvancedSearch = false;\n vm.service.$virtualMode = false;\n // Close sidenav on small devices\n if (!$mdMedia(sgConstant['gt-md']))\n $mdSidenav('left').close();\n $state.go('mail.account.mailbox', { accountId: account.id, mailboxId: encodeUriFilter(folder.path) });\n $event.stopPropagation();\n $event.preventDefault();\n }\n\n function saveFolder(folder) {\n folder.$rename()\n .then(function(data) {\n vm.editMode = false;\n });\n }\n\n function compactFolder(folder) {\n folder.$compact().then(function() {\n $mdToast.show(\n $mdToast.simple()\n .content(l('Folder compacted'))\n .position('top right')\n .hideDelay(3000));\n });\n }\n\n function emptyTrashFolder(folder) {\n folder.$emptyTrash().then(function() {\n $mdToast.show(\n $mdToast.simple()\n .content(l('Trash emptied'))\n .position('top right')\n .hideDelay(3000));\n });\n }\n\n function confirmDelete(folder) {\n Dialog.confirm(l('Warning'),\n l('Do you really want to move this folder into the trash ?'),\n { ok: l('Delete') })\n .then(function() {\n folder.$delete()\n .then(function() {\n $state.go('mail.account.inbox');\n }, function(response) {\n Dialog.confirm(l('Warning'),\n l('The mailbox could not be moved to the trash folder. Would you like to delete it immediately?'),\n { ok: l('Delete') })\n .then(function() {\n folder.$delete({ withoutTrash: true })\n .then(function() {\n $state.go('mail.account.inbox');\n }, function(response) {\n Dialog.alert(l('An error occured while deleting the mailbox \"%{0}\".', folder.name),\n l(response.error));\n });\n });\n });\n });\n }\n\n function markFolderRead(folder) {\n folder.$markAsRead();\n }\n\n function share(folder) {\n // Fetch list of ACL users\n folder.$acl.$users().then(function() {\n // Show ACL editor\n $mdDialog.show({\n templateUrl: folder.id + '/UIxAclEditor', // UI/Templates/UIxAclEditor.wox\n controller: 'AclController', // from the ng module SOGo.Common\n controllerAs: 'acl',\n clickOutsideToClose: true,\n escapeToClose: true,\n locals: {\n usersWithACL: folder.$acl.users,\n User: User,\n folder: folder\n }\n });\n });\n } // share\n\n function setFolderAs(folder, type) {\n folder.$setFolderAs(type).then(function() {\n folder.$account.$getMailboxes({reload: true});\n });\n }\n\n function refreshUnseenCount() {\n var unseenCountFolders = $window.unseenCountFolders;\n\n _.forEach(vm.accounts, function(account) {\n\n // Always include the INBOX\n if (!_.includes(unseenCountFolders, account.id + '/folderINBOX'))\n unseenCountFolders.push(account.id + '/folderINBOX');\n\n _.forEach(account.$$flattenMailboxes, function(mailbox) {\n if (angular.isDefined(mailbox.unseenCount) &&\n !_.includes(unseenCountFolders, mailbox.id))\n unseenCountFolders.push(mailbox.id);\n });\n });\n\n Account.$$resource.post('', 'unseenCount', {mailboxes: unseenCountFolders}).then(function(data) {\n _.forEach(vm.accounts, function(account) {\n _.forEach(account.$$flattenMailboxes, function(mailbox) {\n if (data[mailbox.id])\n mailbox.unseenCount = data[mailbox.id];\n });\n });\n });\n\n Preferences.ready().then(function() {\n var refreshViewCheck = Preferences.defaults.SOGoRefreshViewCheck;\n if (refreshViewCheck && refreshViewCheck != 'manually')\n $timeout(vm.refreshUnseenCount, refreshViewCheck.timeInterval()*1000);\n });\n }\n\n function isDroppableFolder(srcFolder, dstFolder) {\n return (dstFolder.id != srcFolder.id) && !dstFolder.isNoSelect();\n }\n\n function dragSelectedMessages(srcFolder, dstFolder, mode) {\n var dstId, messages, uids, clearMessageView, promise, success;\n\n dstId = '/' + dstFolder.id;\n messages = srcFolder.$selectedMessages();\n if (messages.length === 0)\n messages = [srcFolder.$selectedMessage()];\n uids = _.map(messages, 'uid');\n clearMessageView = (srcFolder.selectedMessage && uids.indexOf(srcFolder.selectedMessage) >= 0);\n\n if (mode == 'copy') {\n promise = srcFolder.$copyMessages(messages, dstId);\n success = l('%{0} message(s) copied', messages.length);\n }\n else {\n promise = srcFolder.$moveMessages(messages, dstId);\n success = l('%{0} message(s) moved', messages.length);\n }\n\n promise.then(function() {\n if (clearMessageView)\n $state.go('mail.account.mailbox');\n $mdToast.show(\n $mdToast.simple()\n .content(success)\n .position('top right')\n .hideDelay(2000));\n });\n }\n\n }\n\n angular\n .module('SOGo.MailerUI')\n .controller('MailboxesController', MailboxesController);\n})();\n\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n MessageController.$inject = ['$window', '$scope', '$state', '$mdMedia', '$mdDialog', 'sgConstant', 'stateAccounts', 'stateAccount', 'stateMailbox', 'stateMessage', 'sgHotkeys', 'encodeUriFilter', 'sgSettings', 'sgFocus', 'Dialog', 'Calendar', 'Component', 'Account', 'Mailbox', 'Message'];\n function MessageController($window, $scope, $state, $mdMedia, $mdDialog, sgConstant, stateAccounts, stateAccount, stateMailbox, stateMessage, sgHotkeys, encodeUriFilter, sgSettings, focus, Dialog, Calendar, Component, Account, Mailbox, Message) {\n var vm = this, popupWindow = null, hotkeys = [];\n\n // Expose controller\n $window.$messageController = vm;\n\n vm.$state = $state;\n vm.accounts = stateAccounts;\n vm.account = stateAccount;\n vm.mailbox = stateMailbox;\n vm.message = stateMessage;\n vm.service = Message;\n vm.tags = { searchText: '', selected: '' };\n vm.showFlags = stateMessage.flags && stateMessage.flags.length > 0;\n vm.$showDetailedRecipients = false;\n vm.toggleDetailedRecipients = toggleDetailedRecipients;\n vm.filterMailtoLinks = filterMailtoLinks;\n vm.deleteMessage = deleteMessage;\n vm.close = close;\n vm.reply = reply;\n vm.replyAll = replyAll;\n vm.forward = forward;\n vm.edit = edit;\n vm.openPopup = openPopup;\n vm.closePopup = closePopup;\n vm.newMessage = newMessage;\n vm.toggleRawSource = toggleRawSource;\n vm.showRawSource = false;\n vm.print = print;\n vm.convertToEvent = convertToEvent;\n vm.convertToTask = convertToTask;\n\n _registerHotkeys(hotkeys);\n\n // One-way refresh of the parent window when modifying the message from a popup window.\n if ($window.opener) {\n // Update the message flags. The message must be displayed in the parent window.\n $scope.$watchCollection(function() { return vm.message.flags; }, function(newTags, oldTags) {\n var ctrls;\n if (newTags || oldTags) {\n ctrls = $parentControllers();\n if (ctrls.messageCtrl) {\n ctrls.messageCtrl.service.$timeout(function() {\n ctrls.messageCtrl.showFlags = true;\n ctrls.messageCtrl.message.flags = newTags;\n });\n }\n }\n });\n // Update the \"isflagged\" (star icon) of the message. The mailbox must be displayed in the parent window.\n $scope.$watch(function() { return vm.message.isflagged; }, function(isflagged, wasflagged) {\n var ctrls = $parentControllers();\n if (ctrls.mailboxCtrl) {\n ctrls.mailboxCtrl.service.$timeout(function() {\n var message = _.find(ctrls.mailboxCtrl.selectedFolder.$messages, { uid: vm.message.uid });\n message.isflagged = isflagged;\n });\n }\n });\n }\n else {\n // Flatten new tags when coming from the predefined list of tags (Message.$tags) and\n // sync tags with server when adding or removing a tag.\n $scope.$watchCollection(function() { return vm.message.flags; }, function(_newTags, _oldTags) {\n var newTags, oldTags, tags;\n if (_newTags || _oldTags) {\n newTags = _newTags || [];\n oldTags = _oldTags || [];\n _.forEach(newTags, function(tag, i) {\n if (angular.isObject(tag))\n newTags[i] = tag.name;\n });\n if (newTags.length > oldTags.length) {\n tags = _.difference(newTags, oldTags);\n _.forEach(tags, function(tag) {\n vm.message.addTag(tag);\n });\n }\n else if (newTags.length < oldTags.length) {\n tags = _.difference(oldTags, newTags);\n _.forEach(tags, function(tag) {\n vm.message.removeTag(tag);\n });\n }\n }\n });\n }\n\n $scope.$on('$destroy', function() {\n // Deregister hotkeys\n _.forEach(hotkeys, function(key) {\n sgHotkeys.deregisterHotkey(key);\n });\n });\n\n\n /**\n * To keep track of the currently active dialog, we share a common variable with the parent controller.\n */\n function _messageDialog() {\n if ($scope.mailbox) {\n if (arguments.length > 0)\n $scope.mailbox.messageDialog = arguments[0];\n return $scope.mailbox.messageDialog;\n }\n return null;\n }\n\n function _unlessInDialog(callback) {\n return function() {\n // Check if a dialog is opened either from the current controller or the parent controller\n if (_messageDialog() === null)\n return callback.apply(vm, arguments);\n };\n }\n\n function _registerHotkeys(keys) {\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_reply'),\n description: l('Reply to the message'),\n callback: _unlessInDialog(reply)\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_replyall'),\n description: l('Reply to sender and all recipients'),\n callback: _unlessInDialog(replyAll)\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_forward'),\n description: l('Forward selected message'),\n callback: _unlessInDialog(forward)\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_flag'),\n description: l('Flagged'),\n callback: _unlessInDialog(angular.bind(stateMessage, stateMessage.toggleFlag))\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'backspace',\n callback: _unlessInDialog(function($event) {\n if (vm.mailbox.$selectedCount() === 0)\n deleteMessage();\n $event.preventDefault();\n })\n }));\n\n // Register the hotkeys\n _.forEach(keys, function(key) {\n sgHotkeys.registerHotkey(key);\n });\n }\n\n /**\n * If this is a popup window, retrieve the matching controllers (mailbox and message) of the parent window.\n */\n function $parentControllers() {\n var message, mailbox, ctrls = {};\n if ($window.opener) {\n // Deleting the message from a popup window\n if ($window.opener.$mailboxController &&\n $window.opener.$mailboxController.selectedFolder.$id() == stateMailbox.$id()) {\n // The message mailbox is opened in the parent window\n mailbox = $window.opener.$mailboxController;\n ctrls.mailboxCtrl = mailbox;\n if ($window.opener.$messageController &&\n $window.opener.$messageController.message.uid == stateMessage.uid) {\n // The message is opened in the parent window\n message = $window.opener.$messageController;\n ctrls.messageCtrl = message;\n }\n }\n }\n return ctrls;\n }\n\n function toggleDetailedRecipients($event) {\n vm.$showDetailedRecipients = !vm.$showDetailedRecipients;\n $event.stopPropagation();\n $event.preventDefault();\n }\n\n function filterMailtoLinks($event) {\n var href, match, to, cc, bcc, subject, body, data;\n if ($event.target.tagName == 'A' && 'href' in $event.target.attributes) {\n href = $event.target.attributes.href.value;\n match = /^mailto:([^\\?]+)/.exec(href);\n if (match) {\n // Recipients\n to = _.map(decodeURIComponent(match[1]).split(','), function(email) {\n return '<' + email + '>';\n });\n data = { to: to };\n // Subject & body\n _.forEach(['subject', 'body'], function(param) {\n var re = new RegExp(param + '=([^&]+)');\n param = (param == 'body')? 'text' : param;\n match = re.exec(href);\n if (match)\n data[param] = [decodeURIComponent(match[1])];\n });\n // Recipients\n _.forEach(['cc', 'bcc'], function(param) {\n var re = new RegExp(param + '=([^&]+)');\n match = re.exec(href);\n if (match)\n data[param] = [decodeURIComponent(match[1])];\n });\n newMessage($event, data); // will stop event propagation\n }\n }\n }\n\n function deleteMessage() {\n var mailbox, message, state, nextMessage, previousMessage,\n parentCtrls = $parentControllers();\n\n if (parentCtrls.messageCtrl) {\n mailbox = parentCtrls.mailboxCtrl.selectedFolder;\n message = parentCtrls.messageCtrl.message;\n state = parentCtrls.messageCtrl.$state;\n }\n else {\n mailbox = stateMailbox;\n message = stateMessage;\n state = $state;\n }\n\n mailbox.$deleteMessages([message]).then(function(index) {\n var nextIndex = index;\n // Remove message object from scope\n message = null;\n if (angular.isDefined(state)) {\n // Select either the next or previous message\n if (index > 0) {\n nextIndex -= 1;\n nextMessage = mailbox.$messages[nextIndex];\n }\n if (index < mailbox.$messages.length)\n previousMessage = mailbox.$messages[index];\n\n if (nextMessage) {\n if (nextMessage.isread && previousMessage && !previousMessage.isread) {\n nextIndex = index;\n nextMessage = previousMessage;\n }\n }\n else if (previousMessage) {\n nextIndex = index;\n nextMessage = previousMessage;\n }\n\n try {\n if (nextMessage && $mdMedia(sgConstant['gt-md'])) {\n state.go('mail.account.mailbox.message', { messageId: nextMessage.uid });\n if (nextIndex < mailbox.$topIndex)\n mailbox.$topIndex = nextIndex;\n else if (nextIndex > mailbox.$lastVisibleIndex)\n mailbox.$topIndex = nextIndex - (mailbox.$lastVisibleIndex - mailbox.$topIndex);\n }\n else {\n state.go('mail.account.mailbox').then(function() {\n message = null;\n delete mailbox.selectedMessage;\n });\n }\n }\n catch (error) {}\n }\n closePopup();\n });\n }\n\n function showMailEditor($event, message) {\n if (_messageDialog() === null) {\n _messageDialog(\n $mdDialog\n .show({\n parent: angular.element(document.body),\n targetEvent: $event,\n clickOutsideToClose: false,\n escapeToClose: false,\n templateUrl: 'UIxMailEditor',\n controller: 'MessageEditorController',\n controllerAs: 'editor',\n locals: {\n stateAccount: vm.account,\n stateMessage: message\n }\n })\n .finally(function() {\n _messageDialog(null);\n closePopup();\n })\n );\n }\n }\n\n function close() {\n $state.go('mail.account.mailbox').then(function() {\n vm.message = null;\n delete stateMailbox.selectedMessage;\n });\n }\n\n function reply($event) {\n var message = vm.message.$reply();\n showMailEditor($event, message);\n }\n\n function replyAll($event) {\n var message = vm.message.$replyAll();\n showMailEditor($event, message);\n }\n\n function forward($event) {\n var message = vm.message.$forward();\n showMailEditor($event, message);\n }\n\n function edit($event) {\n vm.message.$editableContent().then(function() {\n showMailEditor($event, vm.message);\n });\n }\n\n function openPopup() {\n var url = [sgSettings.baseURL(),\n 'UIxMailPopupView#!/Mail',\n vm.message.accountId,\n // The double-encoding is necessary\n encodeUriFilter(encodeUriFilter(vm.message.$mailbox.path)),\n vm.message.uid]\n .join('/'),\n wId = vm.message.$absolutePath();\n popupWindow = $window.open(url, wId,\n [\"width=680\",\n \"height=520\",\n \"resizable=1\",\n \"scrollbars=1\",\n \"toolbar=0\",\n \"location=0\",\n \"directories=0\",\n \"status=0\",\n \"menubar=0\",\n \"copyhistory=0\"]\n .join(','));\n }\n\n function closePopup() {\n if ($window.opener)\n $window.close();\n }\n\n function newMessage($event, editableContent) {\n vm.account.$newMessage().then(function(message) {\n angular.extend(message.editable, editableContent);\n showMailEditor($event, message);\n });\n $event.stopPropagation();\n $event.preventDefault();\n }\n\n function toggleRawSource($event) {\n if (!vm.showRawSource && !vm.message.$rawSource) {\n Message.$$resource.post(vm.message.id, \"viewsource\").then(function(data) {\n vm.message.$rawSource = data;\n vm.showRawSource = true;\n });\n }\n else {\n vm.showRawSource = !vm.showRawSource;\n }\n }\n\n function print($event) {\n $window.print();\n }\n\n function convertToEvent($event) {\n return convertToComponent($event, 'appointment');\n }\n\n function convertToTask($event) {\n return convertToComponent($event, 'task');\n }\n\n function convertToComponent($event, type) {\n vm.message.$plainContent().then(function(data) {\n var componentData = {\n pid: Calendar.$defaultCalendar(),\n type: type,\n summary: data.subject,\n comment: data.content\n };\n var component = new Component(componentData);\n // UI/Templates/SchedulerUI/UIxAppointmentEditorTemplate.wox or\n // UI/Templates/SchedulerUI/UIxTaskEditorTemplate.wox\n var templateUrl = [\n sgSettings.activeUser('folderURL'),\n 'Calendar',\n 'UIx' + type.capitalize() + 'EditorTemplate'\n ].join('/');\n return $mdDialog.show({\n parent: angular.element(document.body),\n targetEvent: $event,\n clickOutsideToClose: true,\n escapeToClose: true,\n templateUrl: templateUrl,\n controller: 'ComponentEditorController',\n controllerAs: 'editor',\n locals: {\n stateComponent: component\n }\n });\n });\n }\n }\n \n angular\n .module('SOGo.MailerUI') \n .controller('MessageController', MessageController); \n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n MessageEditorController.$inject = ['$scope', '$window', '$stateParams', '$mdConstant', '$mdDialog', '$mdToast', 'FileUploader', 'stateAccount', 'stateMessage', 'encodeUriFilter', '$timeout', 'Dialog', 'AddressBook', 'Card', 'Preferences'];\n function MessageEditorController($scope, $window, $stateParams, $mdConstant, $mdDialog, $mdToast, FileUploader, stateAccount, stateMessage, encodeUriFilter, $timeout, Dialog, AddressBook, Card, Preferences) {\n var vm = this, hotkeys = [];\n\n vm.addRecipient = addRecipient;\n vm.autocomplete = {to: {}, cc: {}, bcc: {}};\n vm.autosave = null;\n vm.autosaveDrafts = autosaveDrafts;\n vm.cancel = cancel;\n vm.contactFilter = contactFilter;\n vm.isFullscreen = false;\n vm.hideBcc = (stateMessage.editable.bcc.length === 0);\n vm.hideCc = (stateMessage.editable.cc.length === 0);\n vm.identities = _.map(stateAccount.identities, 'full');\n vm.message = stateMessage;\n vm.recipientSeparatorKeys = [\n $mdConstant.KEY_CODE.ENTER,\n $mdConstant.KEY_CODE.TAB,\n $mdConstant.KEY_CODE.COMMA,\n $mdConstant.KEY_CODE.SEMICOLON\n ];\n vm.removeAttachment = removeAttachment;\n vm.save = save;\n vm.send = send;\n vm.sendState = false;\n vm.toggleFullscreen = toggleFullscreen;\n vm.uploader = new FileUploader({\n url: stateMessage.$absolutePath({asDraft: true}) + '/save',\n autoUpload: true,\n alias: 'attachments',\n removeAfterUpload: false,\n // onProgressItem: function(item, progress) {\n // console.debug(item); console.debug(progress);\n // },\n onSuccessItem: function(item, response, status, headers) {\n stateMessage.$setUID(response.uid);\n stateMessage.$reload({asDraft: false});\n item.inlineUrl = response.lastAttachmentAttrs[0].url;\n //console.debug(item); console.debug('success = ' + JSON.stringify(response, undefined, 2));\n },\n onCancelItem: function(item, response, status, headers) {\n //console.debug(item); console.debug('cancel = ' + JSON.stringify(response, undefined, 2));\n // We remove the attachment\n stateMessage.$deleteAttachment(item.file.name);\n this.removeFromQueue(item);\n },\n onErrorItem: function(item, response, status, headers) {\n $mdToast.show(\n $mdToast.simple()\n .content(l('Error while uploading the file \\\"%{0}\\\":', item.file.name) +\n ' ' + (response.message? l(response.message) : ''))\n .position('top right')\n .action(l('OK'))\n .hideDelay(false));\n this.removeFromQueue(item);\n //console.debug(item); console.debug('error = ' + JSON.stringify(response, undefined, 2));\n }\n });\n\n // Destroy file uploader when the controller is being deactivated\n $scope.$on('$destroy', function() { vm.uploader.destroy(); });\n\n if ($stateParams.actionName == 'reply') {\n stateMessage.$reply().then(function(msgObject) {\n vm.message = msgObject;\n vm.hideCc = (!msgObject.editable.cc || msgObject.editable.cc.length === 0);\n vm.hideBcc = (!msgObject.editable.bcc || msgObject.editable.bcc.length === 0);\n });\n }\n else if ($stateParams.actionName == 'replyall') {\n stateMessage.$replyAll().then(function(msgObject) {\n vm.message = msgObject;\n vm.hideCc = (!msgObject.editable.cc || msgObject.editable.cc.length === 0);\n vm.hideBcc = (!msgObject.editable.bcc || msgObject.editable.bcc.length === 0);\n });\n }\n else if ($stateParams.actionName == 'forward') {\n stateMessage.$forward().then(function(msgObject) {\n vm.message = msgObject;\n addAttachments();\n });\n }\n else if (angular.isDefined(stateMessage)) {\n vm.message = stateMessage;\n addAttachments();\n }\n\n /**\n * If this is a popup window, retrieve the mailbox controller of the parent window.\n */\n function $parentControllers() {\n var originMessage, ctrls = {};\n\n try {\n if ($window.opener) {\n if ('$mailboxController' in $window.opener &&\n 'selectedFolder' in $window.opener.$mailboxController) {\n if ($window.opener.$mailboxController.selectedFolder.type == 'draft') {\n ctrls.draftMailboxCtrl = $window.opener.$mailboxController;\n if ('$messageController' in $window.opener &&\n $window.opener.$messageController.message.uid == stateMessage.uid) {\n // The draft is opened in the parent window\n ctrls.draftMessageCtrl = $window.opener.$messageController;\n }\n }\n else if (stateMessage.origin) {\n originMessage = stateMessage.origin.message;\n if ($window.opener.$mailboxController.selectedFolder.$id() == originMessage.$mailbox.$id()) {\n // The message mailbox is opened in the parent window\n ctrls.originMailboxCtrl = $window.opener.$mailboxController;\n }\n }\n }\n }\n }\n catch (e) {}\n\n return ctrls;\n }\n\n function addAttachments() {\n // Add existing attached files to uploader\n var i, data, fileItem, attrs = vm.message.editable.attachmentAttrs;\n if (attrs)\n for (i = 0; i < attrs.length; i++) {\n data = {\n name: attrs[i].filename,\n type: attrs[i].mimetype,\n size: parseInt(attrs[i].size)\n };\n fileItem = new FileUploader.FileItem(vm.uploader, data);\n fileItem.progress = 100;\n fileItem.isUploaded = true;\n fileItem.isSuccess = true;\n fileItem.inlineUrl = attrs[i].url;\n vm.uploader.queue.push(fileItem);\n }\n }\n\n function removeAttachment(item, id) {\n if (item.isUploading)\n vm.uploader.cancelItem(item);\n else {\n vm.message.$deleteAttachment(item.file.name);\n item.remove();\n }\n // Hack to allow adding the same file again\n // See https://github.com/nervgh/angular-file-upload/issues/671\n var element = $window.document.getElementById(id);\n if (element)\n angular.element(element).prop('value', null);\n }\n\n function cancel() {\n if (vm.autosave)\n $timeout.cancel(vm.autosave);\n\n if (vm.message.isNew && vm.message.attachmentAttrs)\n vm.message.$mailbox.$deleteMessages([vm.message]);\n\n $mdDialog.cancel();\n }\n\n function save() {\n var ctrls = $parentControllers();\n vm.message.$save().then(function(data) {\n vm.message.$rawSource = null;\n if (ctrls.draftMailboxCtrl) {\n // We're saving a draft from a popup window.\n // Reload draft mailbox\n ctrls.draftMailboxCtrl.selectedFolder.$filter().then(function() {\n if (ctrls.draftMessageCtrl) {\n // Reload selected message\n ctrls.draftMessageCtrl.$state.go('mail.account.mailbox.message', { messageId: vm.message.uid });\n }\n });\n }\n $mdToast.show(\n $mdToast.simple()\n .content(l('Your email has been saved'))\n .position('top right')\n .hideDelay(3000));\n });\n }\n\n function send() {\n var ctrls = $parentControllers();\n\n vm.sendState = 'sending';\n if (vm.autosave)\n $timeout.cancel(vm.autosave);\n\n vm.message.$send().then(function(data) {\n vm.sendState = 'sent';\n if (ctrls.draftMailboxCtrl) {\n // We're sending a draft from a popup window and the draft mailbox is opened.\n // Reload draft mailbox\n ctrls.draftMailboxCtrl.selectedFolder.$filter().then(function() {\n if (ctrls.draftMessageCtrl) {\n // Close draft\n ctrls.draftMessageCtrl.close();\n }\n });\n }\n if (ctrls.originMailboxCtrl) {\n // We're sending a draft from a popup window and the original mailbox is opened.\n // Reload mailbox\n ctrls.originMailboxCtrl.selectedFolder.$filter();\n }\n $mdToast.show(\n $mdToast.simple()\n .content(l('Your email has been sent'))\n .position('top right')\n .hideDelay(3000));\n\n // Let the user see the succesfull message before closing the dialog\n $timeout($mdDialog.hide, 1000);\n }, function(response) {\n vm.sendState = 'error';\n vm.errorMessage = response.data? response.data.message : response.statusText;\n });\n }\n\n function toggleFullscreen() {\n vm.isFullscreen = !vm.isFullscreen;\n }\n\n function contactFilter($query) {\n return AddressBook.$filterAll($query).then(function(cards) {\n // Divide the matching cards by email addresses so the user can select\n // the recipient address of her choice\n var explodedCards = [];\n _.forEach(_.invokeMap(cards, 'explode'), function(manyCards) {\n _.forEach(manyCards, function(card) {\n explodedCards.push(card);\n });\n });\n // Remove duplicates\n return _.uniqBy(explodedCards, function(card) {\n return card.$$fullname + ' ' + card.$$email;\n });\n });\n }\n\n function addRecipient(contact, field) {\n var recipients, recipient, list;\n\n if (angular.isString(contact))\n return contact;\n\n recipients = vm.message.editable[field];\n\n if (contact.$isList({expandable: true})) {\n // If the list's members were already fetch, use them\n if (angular.isDefined(contact.refs) && contact.refs.length) {\n _.forEach(contact.refs, function(ref) {\n if (ref.email.length)\n recipients.push(ref.$shortFormat());\n });\n }\n else {\n list = Card.$find(contact.container, contact.c_name);\n list.$id().then(function(listId) {\n _.forEach(list.refs, function(ref) {\n if (ref.email.length)\n recipients.push(ref.$shortFormat());\n });\n });\n }\n }\n else {\n recipient = contact.$shortFormat();\n }\n\n if (recipient)\n return recipient;\n else\n return null;\n }\n\n // Drafts autosaving\n function autosaveDrafts() {\n vm.message.$save();\n if (Preferences.defaults.SOGoMailAutoSave)\n vm.autosave = $timeout(vm.autosaveDrafts, Preferences.defaults.SOGoMailAutoSave*1000*60);\n }\n\n // Read user's defaults\n Preferences.ready().then(function() {\n if (Preferences.defaults.SOGoMailAutoSave)\n // Enable auto-save of draft\n vm.autosave = $timeout(vm.autosaveDrafts, Preferences.defaults.SOGoMailAutoSave*1000*60);\n // Set the locale of CKEditor\n vm.localeCode = Preferences.defaults.LocaleCode;\n });\n }\n\n SendMessageToastController.$inject = ['$scope', '$mdToast'];\n function SendMessageToastController($scope, $mdToast) {\n $scope.closeToast = function() {\n $mdToast.hide();\n };\n }\n\n angular\n .module('SOGo.MailerUI')\n .controller('SendMessageToastController', SendMessageToastController)\n .controller('MessageEditorController', MessageEditorController);\n\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n /* jshint validthis: true */\n 'use strict';\n\n /**\n * sgIMIP - A directive to handle IMIP actions on emails\n * @memberof SOGo.MailerUI\n * @example:\n\n */\n function sgImip() {\n return {\n restrict: 'A',\n link: link,\n controller: 'sgImipController'\n };\n\n function link(scope, iElement, attrs, ctrl) {\n ctrl.pathToAttachment = attrs.sgImipPath;\n }\n }\n\n /**\n * @ngInject\n */\n sgImipController.$inject = ['$scope', 'User'];\n function sgImipController($scope, User) {\n var vm = this;\n\n $scope.delegateInvitation = false;\n $scope.delegatedTo = '';\n $scope.searchText = '';\n\n $scope.userFilter = function($query) {\n return User.$filter($query);\n };\n\n $scope.iCalendarAction = function(action) {\n var data;\n\n if (action == 'delegate') {\n data = {\n receiveUpdates: false,\n delegatedTo: $scope.delegatedTo.c_email\n };\n }\n\n $scope.viewer.message.$imipAction(vm.pathToAttachment, action, data);\n };\n }\n\n angular\n .module('SOGo.MailerUI')\n .controller('sgImipController', sgImipController)\n .directive('sgImip', sgImip);\n})();\n\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /*\n * sgZoomableImage - Toggle the 'sg-zoom' class when clicking on the image inside the container.\n * @memberof SOGo.MailerUI\n * @restrict attribute\n * @ngInject\n * @example:\n\n
\n \n \n \n
\n */\n function sgZoomableImage() {\n return {\n restrict: 'A',\n link: link\n };\n\n function link(scope, iElement, attrs, ctrl) {\n var parentNode = iElement.parent(),\n toggleClass;\n\n toggleClass = function(event) {\n if (event.target.tagName == 'IMG')\n parentNode.toggleClass('sg-zoom');\n };\n\n iElement.on('click', toggleClass);\n }\n }\n\n angular\n .module('SOGo.MailerUI')\n .directive('sgZoomableImage', sgZoomableImage);\n})();\n"]} \ No newline at end of file