From fbfe8aab451db18b003461b56e3c209ce24deecb Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Tue, 11 Sep 2012 14:19:28 +0200 Subject: [PATCH 001/279] Transitional filter-by-category design take 1. --- ajax/contact/list.php | 2 + ajax/contact/listbycategory.php | 63 ++++++++++++++++ css/contacts.css | 2 +- js/contacts.js | 124 ++++++++++++++++++++++++-------- lib/app.php | 18 ++--- lib/vcard.php | 4 +- 6 files changed, 173 insertions(+), 40 deletions(-) create mode 100644 ajax/contact/listbycategory.php diff --git a/ajax/contact/list.php b/ajax/contact/list.php index ce030378..9c482dc1 100644 --- a/ajax/contact/list.php +++ b/ajax/contact/list.php @@ -41,6 +41,8 @@ foreach($active_addressbooks as $addressbook) { = array('contacts' => array('type' => 'book',)); $contacts_addressbook[$addressbook['id']]['displayname'] = $addressbook['displayname']; + $contacts_addressbook[$addressbook['id']]['description'] + = $addressbook['description']; $contacts_addressbook[$addressbook['id']]['permissions'] = $addressbook['permissions']; $contacts_addressbook[$addressbook['id']]['owner'] diff --git a/ajax/contact/listbycategory.php b/ajax/contact/listbycategory.php new file mode 100644 index 00000000..23517bc0 --- /dev/null +++ b/ajax/contact/listbycategory.php @@ -0,0 +1,63 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +function cmpcategories($a, $b) +{ + if (strtolower($a['name']) == strtolower($b['name'])) { + return 0; + } + return (strtolower($a['name']) < strtolower($b['name'])) ? -1 : 1; +} + +function cmpcontacts($a, $b) +{ + if (strtolower($a['fullname']) == strtolower($b['fullname'])) { + return 0; + } + return (strtolower($a['fullname']) < strtolower($b['fullname'])) ? -1 : 1; +} + +OCP\JSON::checkLoggedIn(); +OCP\JSON::checkAppEnabled('contacts'); + +$offset = isset($_GET['startat']) ? $_GET['startat'] : null; +$category = isset($_GET['category']) ? $_GET['category'] : null; + +$list = array(); + +$catmgr = OC_Contacts_App::getVCategories(); + +if(is_null($category)) { + $categories = $catmgr->categories(true); + uasort($categories, 'cmpcategories'); + foreach($categories as $category) { + $list[$category['id']] = array( + 'name' => $category['name'], + 'contacts' => $catmgr->itemsForCategory( + $category['name'], + array( + 'tablename' => '*PREFIX*contacts_cards', + 'fields' => array('id', 'addressbookid', 'fullname'), + ), + 50, + $offset) + ); + uasort($list[$category['id']]['contacts'], 'cmpcontacts'); + } +} else { + $list[$category] = $catmgr->itemsForCategory( + $category, + '*PREFIX*contacts_cards', + 50, + $offset); + uasort($list[$category], 'cmpcontacts'); +} + +session_write_close(); + +OCP\JSON::success(array('data' => array('categories' => $list))); diff --git a/css/contacts.css b/css/contacts.css index b83a8891..c46afbe7 100644 --- a/css/contacts.css +++ b/css/contacts.css @@ -156,4 +156,4 @@ input[type="checkbox"] { width: 20px; height: 20px; vertical-align: bottom; } .addressbooks-settings .actions input.name { width: 7em; } .addressbooks-settings a.action { opacity: 0.2; } .addressbooks-settings a.action:hover { opacity: 1; } -.addressbooks-settings td.active, .addressbooks-settings td.action { width: 20px; } +.addressbooks-settings td.active, .addressbooks-settings td.action { width: 20px; } \ No newline at end of file diff --git a/js/contacts.js b/js/contacts.js index ecf459a8..4c9add89 100644 --- a/js/contacts.js +++ b/js/contacts.js @@ -342,7 +342,7 @@ OC.Contacts={ bookid = parseInt(params.aid); } if(!bookid || !newid) { - bookid = parseInt($('#contacts h3').first().data('id')); + bookid = parseInt($('#contacts h3.addressbook').first().data('id')); newid = parseInt($('#contacts').find('li[data-bookid="'+bookid+'"]').first().data('id')); } console.log('newid: ' + newid + ' bookid: ' +bookid); @@ -357,7 +357,7 @@ OC.Contacts={ data:jsondata.data }); } - $('#contacts li[data-id="'+newid+'"],#contacts h3[data-id="'+bookid+'"]').addClass('active'); + $('#contacts li[data-id="'+newid+'"],#contacts h3.addressbook[data-id="'+bookid+'"]').addClass('active'); $('#contacts ul[data-id="'+bookid+'"]').slideDown(300); OC.Contacts.Card.loadContact(jsondata.data, bookid); OC.Contacts.Contacts.scrollTo(newid); @@ -380,7 +380,7 @@ OC.Contacts={ $('#firstrun').show(); $('#card').hide(); } - $('#contacts h3[data-id="'+bookid+'"]').addClass('active'); + $('#contacts h3.addressbook[data-id="'+bookid+'"]').addClass('active'); }, setEnabled:function(enabled) { console.log('setEnabled', enabled); @@ -414,7 +414,7 @@ OC.Contacts={ console.log('Adding ' + fn); $('#firstrun').hide(); $('#card').show(); - aid = aid?aid:$('#contacts h3.active').first().data('id'); + aid = aid?aid:$('#contacts h3.addressbook.active').first().data('id'); $.post(OC.filePath('contacts', 'ajax', 'contact/add.php'), { n: n, fn: fn, aid: aid, isnew: isnew }, function(jsondata) { if (jsondata.status == 'success'){ @@ -647,19 +647,19 @@ OC.Contacts={ $('#fn_select option').remove(); var names = [this.fn, this.fullname, this.givname + ' ' + this.famname, this.famname + ' ' + this.givname, this.famname + ', ' + this.givname]; if(this.data.ORG) { - names[names.length]=this.data.ORG[0].value; + names.push(this.data.ORG[0].value); } - $.each(names, function(key, value) { + $.each($.unique(names), function(key, value) { $('#fn_select') .append($('') .text(value)); }); - $('#fn_select').combobox('value', this.fn); - $('#contact_identity').find('*[data-element="N"]').data('checksum', this.data.N[0]['checksum']); - if(this.data.FN) { - $('#contact_identity').find('*[data-element="FN"]').data('checksum', this.data.FN[0]['checksum']); - } - $('#contact_identity').show(); + $('#fn_select').combobox('value', this.fn); + $('#contact_identity').find('*[data-element="N"]').data('checksum', this.data.N[0]['checksum']); + if(this.data.FN) { + $('#contact_identity').find('*[data-element="FN"]').data('checksum', this.data.FN[0]['checksum']); + } + $('#contact_identity').show(); }, hasCategory:function(category) { if(this.data.CATEGORIES) { @@ -967,11 +967,11 @@ OC.Contacts={ var tmp = [this.fullname, this.givname + ' ' + this.famname, this.famname + ' ' + this.givname, this.famname + ', ' + this.givname]; var names = new Array(); for(var name in tmp) { - if(names.indexOf(tmp[name]) == -1) { + if(tmp[name] && names.indexOf(tmp[name]) == -1) { names.push(tmp[name]); } } - $.each(names, function(key, value) { + $.each($.unique(names), function(key, value) { $('#fn_select') .append($('') .text(value)); @@ -1741,7 +1741,7 @@ OC.Contacts={ if(!params) { params = {}; } if(!params.start) { if(params.aid) { - $('#contacts h3[data-id="'+params.aid+'"],#contacts ul[data-id="'+params.aid+'"]').remove(); + $('#contacts h3.addressbook[data-id="'+params.aid+'"],#contacts ul[data-id="'+params.aid+'"]').remove(); } else { $('#contacts').empty(); } @@ -1754,27 +1754,27 @@ OC.Contacts={ if(params.aid) { opts['aid'] = params.aid; } - $.getJSON(OC.filePath('contacts', 'ajax', 'contact/list.php'),opts,function(jsondata){ + $.getJSON(OC.filePath('contacts', 'ajax', 'contact/list.php'),opts,function(jsondata) { if(jsondata.status == 'success'){ var books = jsondata.data.entries; $.each(books, function(b, book) { - if($('#contacts h3[data-id="'+b+'"]').length == 0) { + if($('#contacts h3.addressbook[data-id="'+b+'"]').length == 0) { firstrun = true; var sharedindicator = book.owner == OC.currentUser ? '' : '' - if($('#contacts h3').length == 0) { - $('#contacts').html('

' + book.displayname - + sharedindicator + '

'); } else { - if(!$('#contacts h3[data-id="' + b + '"]').length) { - var item = $('

' - + book.displayname+sharedindicator+'

'); var added = false; - $('#contacts h3').each(function(){ + $('#contacts h3.addressbook').each(function(){ if ($(this).text().toLowerCase().localeCompare(book.displayname.toLowerCase()) > 0) { $(this).before(item).fadeIn('fast'); added = true; @@ -1786,14 +1786,14 @@ OC.Contacts={ } } } - $('#contacts h3[data-id="'+b+'"]').on('click', function(event) { - $('#contacts h3').removeClass('active'); + $('#contacts h3.addressbook[data-id="'+b+'"]').on('click', function(event) { + $('#contacts h3.addressbook').removeClass('active'); $(this).addClass('active'); $('#contacts ul[data-id="'+b+'"]').slideToggle(300); return false; }); var accept = 'li:not([data-bookid="'+b+'"]),h3:not([data-id="'+b+'"])'; - $('#contacts h3[data-id="'+b+'"],#contacts ul[data-id="'+b+'"]').droppable({ + $('#contacts h3.addressbook[data-id="'+b+'"],#contacts ul[data-id="'+b+'"]').droppable({ drop: OC.Contacts.Contacts.drop, activeClass: 'ui-state-hover', accept: accept @@ -1837,6 +1837,74 @@ OC.Contacts={ } else { OC.Contacts.notify({message:t('contacts', 'Error')+': '+jsondata.data.message}); } + $.getJSON(OC.filePath('contacts', 'ajax', 'contact/listbycategory.php'),opts,function(jsondata) { + if(jsondata.status == 'success') { + var categories = jsondata.data.categories; + $.each(categories, function(catid, category) { + console.log('category', catid, category.name); + if(!$('#contacts h3.category[data-id="' + catid + '"]').length) { + var item = $('

' + + category.name + '

'); + var added = false; + $('#contacts h3.category').each(function(){ + if ($(this).text().toLowerCase().localeCompare(category.name.toLowerCase()) > 0) { + $(this).before(item).fadeIn('fast'); + added = true; + return false; + } + }); + if(!added) { + $('#contacts').append(item); + } + $('#contacts h3.category[data-id="'+catid+'"]').on('click', function(event) { + console.log('click'); + $('#contacts h3.category').removeClass('active'); + $(this).addClass('active'); + $('#contacts ul.category[data-id="'+catid+'"]').slideToggle(300); + return false; + }); + var contactlist = $('#contacts ul.category[data-id="'+catid+'"]'); + var contacts = $('#contacts ul.category[data-id="'+catid+'"] li'); + for(var c in category.contacts) { + if(category.contacts[c].id == undefined) { continue; } + if(!$('ul.category[data-id="'+catid+'"] li[data-id="'+category.contacts[c]['id']+'"]').length) { + var contact = $('
  • ' + + category.contacts[c].fullname+'
  • '); + var added = false; + var name = category.contacts[c].fullname.toLowerCase(); + if(contacts.length) { + contacts.each(function() { + if ($(this).text().toLowerCase().localeCompare(name) > 0) { + $(this).before(contact); + added = true; + return false; + } + }); + } + if(!added || !params.contacts) { + contactlist.append(contact); + } + /*var contact = OC.Contacts.Contacts.insertContact({contactlist:contactlist, contacts:contacts, data:categories.contacts[c]}); + if(c == self.batchnum-10) { + contact.bind('inview', function(event, isInView, visiblePartX, visiblePartY) { + $(this).unbind(event); + var bookid = $(this).data('bookid'); + var numsiblings = $('.contacts li[data-bookid="'+bookid+'"]').length; + if (isInView && numsiblings >= self.batchnum) { + console.log('This would be a good time to load more contacts.'); + OC.Contacts.Contacts.update({cid:params.cid, aid:bookid, start:$('#contacts li[data-bookid="'+bookid+'"]').length}); + } + }); + }*/ + } + } + } + }); + } + }); }); }, refreshThumbnail:function(id){ @@ -1922,7 +1990,7 @@ $(document).ready(function(){ OC.Contacts.Contacts.nextAddressbook(); break; case 79: // o - var aid = $('#contacts h3.active').first().data('id'); + var aid = $('#contacts h3.addressbook.active').first().data('id'); if(aid) { $('#contacts ul[data-id="'+aid+'"]').slideToggle(300); } diff --git a/lib/app.php b/lib/app.php index a51e4832..a60286a4 100644 --- a/lib/app.php +++ b/lib/app.php @@ -221,8 +221,11 @@ class OC_Contacts_App { * @brief returns the vcategories object of the user * @return (object) $vcategories */ - protected static function getVCategories() { + public static function getVCategories() { if (is_null(self::$categories)) { + if(OC_VCategories::isEmpty('contacts')) { + self::scanCategories(); + } self::$categories = new OC_VCategories('contacts', null, self::getDefaultCategories()); @@ -236,10 +239,6 @@ class OC_Contacts_App { */ public static function getCategories() { $categories = self::getVCategories()->categories(); - if(count($categories) == 0) { - self::scanCategories(); - $categories = self::$categories->categories(); - } return ($categories ? $categories : self::getDefaultCategories()); } @@ -281,18 +280,19 @@ class OC_Contacts_App { } $start = 0; $batchsize = 10; + $categories = new OC_VCategories('contacts'); while($vccontacts = OC_Contacts_VCard::all($vcaddressbookids, $start, $batchsize)) { $cards = array(); foreach($vccontacts as $vccontact) { - $cards[] = $vccontact['carddata']; + $cards[] = array($vccontact['id'], $vccontact['carddata']); } OCP\Util::writeLog('contacts', __CLASS__.'::'.__METHOD__ .', scanning: '.$batchsize.' starting from '.$start, OCP\Util::DEBUG); // only reset on first batch. - self::getVCategories()->rescan($cards, + $categories->rescan($cards, true, ($start == 0 ? true : false)); $start += $batchsize; @@ -305,8 +305,8 @@ class OC_Contacts_App { * check VCard for new categories. * @see OC_VCategories::loadFromVObject */ - public static function loadCategoriesFromVCard(OC_VObject $contact) { - self::getVCategories()->loadFromVObject($contact, true); + public static function loadCategoriesFromVCard($id, OC_VObject $contact) { + self::getVCategories()->loadFromVObject($id, $contact, true); } /** diff --git a/lib/vcard.php b/lib/vcard.php index 13dcde39..e98b32e7 100644 --- a/lib/vcard.php +++ b/lib/vcard.php @@ -304,7 +304,6 @@ class OC_Contacts_VCard { } } if(!$isChecked) { - OC_Contacts_App::loadCategoriesFromVCard($card); self::updateValuesFromAdd($aid, $card); } $card->setString('VERSION', '3.0'); @@ -337,6 +336,7 @@ class OC_Contacts_VCard { return false; } $newid = OCP\DB::insertid('*PREFIX*contacts_cards'); + OC_Contacts_App::loadCategoriesFromVCard($newid, $card); OC_Contacts_Addressbook::touch($aid); OC_Hook::emit('OC_Contacts_VCard', 'post_createVCard', $newid); @@ -432,7 +432,7 @@ class OC_Contacts_VCard { ); } } - OC_Contacts_App::loadCategoriesFromVCard($card); + OC_Contacts_App::loadCategoriesFromVCard($id, $card); $fn = $card->getAsString('FN'); if (empty($fn)) { From 740995ced35fb8e30e11f38f0f839bf96cc8cee9 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Tue, 11 Sep 2012 15:33:09 +0200 Subject: [PATCH 002/279] Use category format const. --- ajax/contact/listbycategory.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ajax/contact/listbycategory.php b/ajax/contact/listbycategory.php index 23517bc0..977f1fc9 100644 --- a/ajax/contact/listbycategory.php +++ b/ajax/contact/listbycategory.php @@ -33,7 +33,7 @@ $list = array(); $catmgr = OC_Contacts_App::getVCategories(); if(is_null($category)) { - $categories = $catmgr->categories(true); + $categories = $catmgr->categories(OC_VCategories::FORMAT_MAP); uasort($categories, 'cmpcategories'); foreach($categories as $category) { $list[$category['id']] = array( From 9571e4077ca537481e1fa3333a77b20a2a813137 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Mon, 17 Sep 2012 02:03:28 +0200 Subject: [PATCH 003/279] Use types (event/contact) instead of app names for vcategories. Also purge category/object relations on object deletion. --- lib/app.php | 4 ++-- lib/vcard.php | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/app.php b/lib/app.php index a60286a4..4ddf6062 100644 --- a/lib/app.php +++ b/lib/app.php @@ -223,10 +223,10 @@ class OC_Contacts_App { */ public static function getVCategories() { if (is_null(self::$categories)) { - if(OC_VCategories::isEmpty('contacts')) { + if(OC_VCategories::isEmpty('contact')) { self::scanCategories(); } - self::$categories = new OC_VCategories('contacts', + self::$categories = new OC_VCategories('contact', null, self::getDefaultCategories()); } diff --git a/lib/vcard.php b/lib/vcard.php index e98b32e7..e892c2b6 100644 --- a/lib/vcard.php +++ b/lib/vcard.php @@ -551,7 +551,7 @@ class OC_Contacts_VCard { ) ); } - + OC_Contacts_App::getVCategories()->purgeObject($id); return true; } From 993c8f36f13765396e904b7736c22aa32a63868c Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Mon, 17 Sep 2012 02:17:41 +0200 Subject: [PATCH 004/279] Missed one 'contacts' => 'contact' update. --- lib/app.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/app.php b/lib/app.php index 4ddf6062..ba333948 100644 --- a/lib/app.php +++ b/lib/app.php @@ -280,7 +280,7 @@ class OC_Contacts_App { } $start = 0; $batchsize = 10; - $categories = new OC_VCategories('contacts'); + $categories = new OC_VCategories('contact'); while($vccontacts = OC_Contacts_VCard::all($vcaddressbookids, $start, $batchsize)) { $cards = array(); From 6b77479899a85fe98fa1b01980f3f7cf947f9608 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Mon, 17 Sep 2012 16:15:31 +0200 Subject: [PATCH 005/279] First work on new Contacts js and group based UI. --- ajax/categories/list.php | 16 +- ajax/contact/list.php | 47 +- ajax/contact/listbycategory.php | 12 +- ajax/loghandler.php | 2 +- css/contacts.css | 153 +++- img/checkmark.png | Bin 0 -> 280 bytes index.php | 7 +- js/app.js | 871 +++++++++++++++++++ js/jquery.combobox.js | 31 +- js/modernizr.js | 1394 +++++++++++++++++++++++++++++++ js/settings.js | 6 +- lib/app.php | 6 +- lib/vcard.php | 35 +- templates/contacts.php | 203 +++++ thumbnail.php | 2 +- 15 files changed, 2697 insertions(+), 88 deletions(-) create mode 100644 img/checkmark.png create mode 100644 js/app.js create mode 100644 js/modernizr.js create mode 100644 templates/contacts.php diff --git a/ajax/categories/list.php b/ajax/categories/list.php index 06785c33..a588d853 100644 --- a/ajax/categories/list.php +++ b/ajax/categories/list.php @@ -10,6 +10,20 @@ OCP\JSON::checkLoggedIn(); OCP\JSON::checkAppEnabled('contacts'); -$categories = OC_Contacts_App::getCategories(); +$catmgr = OC_Contacts_App::getVCategories(); +$categories = $catmgr->categories(OC_VCategories::FORMAT_MAP); +foreach($categories as &$category) { + $ids = array(); + $contacts = $catmgr->itemsForCategory( + $category['name'], + array( + 'tablename' => '*PREFIX*contacts_cards', + 'fields' => array('id',), + )); + foreach($contacts as $contact) { + $ids[] = $contact['id']; + } + $category['contacts'] = $ids; +} OCP\JSON::success(array('data' => array('categories'=>$categories))); diff --git a/ajax/contact/list.php b/ajax/contact/list.php index 9c482dc1..bdf9d69f 100644 --- a/ajax/contact/list.php +++ b/ajax/contact/list.php @@ -8,18 +8,19 @@ function cmp($a, $b) { - if ($a['displayname'] == $b['displayname']) { + if ($a['fullname'] == $b['fullname']) { return 0; } - return ($a['displayname'] < $b['displayname']) ? -1 : 1; + return ($a['fullname'] < $b['fullname']) ? -1 : 1; } OCP\JSON::checkLoggedIn(); OCP\JSON::checkAppEnabled('contacts'); -$start = isset($_GET['startat'])?$_GET['startat']:0; +$offset = isset($_GET['offset']) ? $_GET['offset'] : 0; $aid = isset($_GET['aid'])?$_GET['aid']:null; +$active_addressbooks = array(); if(is_null($aid)) { // Called initially to get the active addressbooks. $active_addressbooks = OC_Contacts_Addressbook::active(OCP\USER::getUser()); @@ -36,7 +37,7 @@ $contacts_addressbook = array(); $ids = array(); foreach($active_addressbooks as $addressbook) { $ids[] = $addressbook['id']; - if(!isset($contacts_addressbook[$addressbook['id']])) { + /*if(!isset($contacts_addressbook[$addressbook['id']])) { $contacts_addressbook[$addressbook['id']] = array('contacts' => array('type' => 'book',)); $contacts_addressbook[$addressbook['id']]['displayname'] @@ -47,25 +48,45 @@ foreach($active_addressbooks as $addressbook) { = $addressbook['permissions']; $contacts_addressbook[$addressbook['id']]['owner'] = $addressbook['userid']; - } + }*/ } $contacts_alphabet = array(); // get next 50 for each addressbook. -foreach($ids as $id) { +$contacts_alphabet = array_merge( + $contacts_alphabet, + OC_Contacts_VCard::all($ids) +); +/*foreach($ids as $id) { if($id) { $contacts_alphabet = array_merge( $contacts_alphabet, - OC_Contacts_VCard::all($id, $start, 50) + OC_Contacts_VCard::all($id, $offset, 50) ); } -} +}*/ + +uasort($contacts_alphabet, 'cmp'); + +$contacts = array(); + + // Our new array for the contacts sorted by addressbook if($contacts_alphabet) { foreach($contacts_alphabet as $contact) { + $vcard = OC_VObject::parse($contact['carddata']); + if(is_null($vcard)) { + continue; + } + $details = OC_Contacts_VCard::structureContact($vcard); + $contacts[] = array( + 'id' => $contact['id'], + 'aid' => $contact['addressbookid'], + 'data' => $details, + ); // This should never execute. - if(!isset($contacts_addressbook[$contact['addressbookid']])) { + /*if(!isset($contacts_addressbook[$contact['addressbookid']])) { $contacts_addressbook[$contact['addressbookid']] = array( 'contacts' => array('type' => 'book',) ); @@ -89,10 +110,10 @@ if($contacts_alphabet) { isset($contacts_addressbook[$contact['addressbookid']]['permissions']) ? $contacts_addressbook[$contact['addressbookid']]['permissions'] : '0', - ); + );*/ } } -unset($contacts_alphabet); -uasort($contacts_addressbook, 'cmp'); +//unset($contacts_alphabet); +uasort($contacts_alphabet, 'cmp'); -OCP\JSON::success(array('data' => array('entries' => $contacts_addressbook))); +OCP\JSON::success(array('data' => array('contacts' => $contacts, 'addressbooks' => $active_addressbooks))); diff --git a/ajax/contact/listbycategory.php b/ajax/contact/listbycategory.php index 977f1fc9..a2197c14 100644 --- a/ajax/contact/listbycategory.php +++ b/ajax/contact/listbycategory.php @@ -25,7 +25,7 @@ function cmpcontacts($a, $b) OCP\JSON::checkLoggedIn(); OCP\JSON::checkAppEnabled('contacts'); -$offset = isset($_GET['startat']) ? $_GET['startat'] : null; +$offset = isset($_GET['offset']) ? $_GET['offset'] : null; $category = isset($_GET['category']) ? $_GET['category'] : null; $list = array(); @@ -36,19 +36,17 @@ if(is_null($category)) { $categories = $catmgr->categories(OC_VCategories::FORMAT_MAP); uasort($categories, 'cmpcategories'); foreach($categories as $category) { - $list[$category['id']] = array( + $list[] = array( 'name' => $category['name'], 'contacts' => $catmgr->itemsForCategory( $category['name'], array( 'tablename' => '*PREFIX*contacts_cards', - 'fields' => array('id', 'addressbookid', 'fullname'), - ), - 50, - $offset) + 'fields' => array('id',), + )) ); - uasort($list[$category['id']]['contacts'], 'cmpcontacts'); } + uasort($list['contacts'], 'cmpcontacts'); } else { $list[$category] = $catmgr->itemsForCategory( $category, diff --git a/ajax/loghandler.php b/ajax/loghandler.php index 2da668f5..4a80c807 100644 --- a/ajax/loghandler.php +++ b/ajax/loghandler.php @@ -34,7 +34,7 @@ function debug($msg, $tracelevel=0, $debuglevel=OCP\Util::DEBUG) } else { $call = debug_backtrace(false); } - error_log('trace: '.print_r($call, true)); + //error_log('trace: '.print_r($call, true)); $call = $call[$tracelevel]; if($debuglevel !== false) { OCP\Util::writeLog('contacts', diff --git a/css/contacts.css b/css/contacts.css index c46afbe7..3b34651e 100644 --- a/css/contacts.css +++ b/css/contacts.css @@ -1,15 +1,25 @@ /*dl > dt { font-weight: bold; }*/ +input[type=checkbox] { height: 14px; width: 14px; border: 1px solid #fff; -moz-appearance:none; -webkit-appearance: none; -moz-box-sizing:none; box-sizing:none; -moz-box-shadow: none; -webkit-box-shadow: none; box-shadow: none; -moz-border-radius: 2px; -webkit-border-radius: 2px; border-radius: 2px; } +input[type=checkbox]:hover { border: 1px solid #D4D4D4 !important; } +input[type=checkbox]:checked::after { + content: url('%appswebroot%/contacts/img/checkmark.png'); + display: block; + position: relative; + top: -8px; + left: -6px; +} +select { border: 1px solid silver; } +option { border-left: 1px solid silver; border-right: 1px solid silver; } +option:first-child { border-top: 1px solid silver; } +option:last-child { border-bottom: 1px solid silver; } #leftcontent { top: 3.5em !important; padding: 0; margin: 0; } #leftcontent a { padding: 0 0 0 25px; } -#rightcontent { top: 3.5em !important; padding-top: 5px; } #leftcontent h3 { cursor: pointer; -moz-transition: background 300ms ease 0s; background: none no-repeat scroll 1em center #eee; border-bottom: 1px solid #ddd; border-top: 1px solid #fff; display: block; max-width: 100%; padding: 0.5em 0.8em; color: #666; text-shadow: 0 1px 0 #f8f8f8; font-size: 1.2em; } #leftcontent h3:hover,#leftcontent h3:active,#leftcontent h3.active { background-color: #DBDBDB; border-bottom: 1px solid #CCCCCC; border-top: 1px solid #D4D4D4; color: #333333; font-weight: bold; } #leftcontent h3 img.shared { float: right; opacity: 0.4; } #leftcontent h3 img.shared:hover { opacity: 1; } -#contacts { position: fixed; background: #fff; max-width: 100%; width: 20em; left: 12.5em; top: 3.7em; bottom: 3em; overflow: auto; padding: 0; margin: 0; } -.contacts a { height: 23px; display: block; left: 12.5em; margin: 0 0 0 0; padding: 0 0 0 25px; } .contacts li.ui-draggable { height: 23px; } .ui-draggable-dragging { width: 17em; cursor: move; } .ui-state-hover { border: 1px solid dashed; } @@ -17,34 +27,23 @@ #bottomcontrols img { margin-top: 0.35em; } #uploadprogressbar { display: none; padding: 0; bottom: 3em; height:2em; width: 20em; margin:0; background:#eee; border:1px solid #ccc; position:fixed; } button.control { float: left; margin: 0.2em 0 0 1em; height: 2.4em; width: 2.4em; /* border: 0 none; border-radius: 0; -moz-box-shadow: none; box-shadow: none; outline: 0 none;*/ } -.settings { background:url('%webroot%/core/img/actions/settings.svg') no-repeat center; float: right !important; margin: 0.2em 1em 0 0 !important; } -.import { background:url('%webroot%/core/img/actions/upload.svg') no-repeat center; } -.newcontact { background:url('%appswebroot%/contacts/img/contact-new.svg') no-repeat center; } -#actionbar { clear: both; height: 30px;} #contacts_deletecard {position:relative; float:left; background:url('%webroot%/core/img/actions/delete.svg') no-repeat center; } #contacts_downloadcard {position:relative; float:left; background:url('%webroot%/core/img/actions/download.svg') no-repeat center; } -#contacts_propertymenu { clear: left; float:left; max-width: 15em; margin: 2em; } -#contacts_propertymenu_button { position:relative;top:0;left:0; margin: 0; } -#contacts_propertymenu_dropdown { background-color: #fff; position:relative; right:0; overflow:hidden; text-overflow:ellipsis; border: thin solid #1d2d44; box-shadow: 0 3px 5px #bbb; /* -moz-box-shadow:0 0 10px #000; -webkit-box-shadow:0 0 10px #000; box-shadow:0 0 10px #000; -moz-border-radius:0.5em; -webkit-border-radius:0.5em; border-radius:0.5em; -moz-border-radius:0.5em; -webkit-border-radius:0.5em;*/ border-radius: 3px; } -#contacts_propertymenu li { display: block; font-weight: bold; height: 20px; } -#contacts_propertymenu li a { padding: 3px; display: block } -#contacts_propertymenu li:hover { background-color: #1d2d44; } -#contacts_propertymenu li a:hover { color: #fff } -#card { width: auto; font-size: 10px; /*max-width: 70em; border: thin solid lightgray; display: block;*/ } +#contact { width: auto; font-size: 10px; /*max-width: 70em; border: thin solid lightgray; display: block;*/ } #firstrun { position: relative; top: 25%; left: 20%; right: 20%; width: 50%; font-weight:bold; text-align: center; color: #777; } #firstrun h3 { font-size:1.5em; text-align: center; margin-bottom: 1em; } #firstrun p { font-size:1.2em; text-align: } #firstrun #selections { font-size:0.8em; margin: 2em auto auto auto; clear: both; } -#card input[type="text"].contacts_property,input[type="email"].contacts_property,input[type="url"].contacts_property { width: 14em; float: left; font-weight: bold; } -.categories { float: left; width: 16em; } -#card input[type="checkbox"].contacts_property, #card input[type="text"], #card input[type="email"], #card input[type="url"], #card input[type="tel"], #card input[type="date"], #card select, #card textarea { background-color: #fefefe; border: 0 !important; -moz-appearance:none !important; -webkit-box-sizing:none !important; -moz-box-sizing:none !important; box-sizing:none !important; -moz-box-shadow: none; -webkit-box-shadow: none; box-shadow: none; -moz-border-radius: 0px; -webkit-border-radius: 0px; border-radius: 0px; float: left; } -#card input[type="text"]:hover, #card input[type="text"]:focus, #card input[type="text"]:active, input[type="email"]:hover, #card input[type="url"]:hover, #card input[type="tel"]:hover, #card input[type="date"]:hover, #card input[type="date"], #card input[type="date"]:hover, #card input[type="date"]:active, #card input[type="date"]:active, #card input[type="date"]:active, #card input[type="email"]:active, #card input[type="url"]:active, #card input[type="tel"]:active, #card textarea:focus, #card textarea:hover { border: 0 !important; -webkit-appearance:textfield; -moz-appearance:textfield; -webkit-box-sizing:content-box; -moz-box-sizing:content-box; box-sizing:content-box; background:#fff; color:#333; border:1px solid #ddd; -moz-box-shadow:0 1px 1px #ddd, 0 2px 0 #bbb inset; -webkit-box-shadow:0 1px 1px #ddd, 0 1px 0 #bbb inset; box-shadow:0 1px 1px #ddd, 0 1px 0 #bbb inset; -moz-border-radius:.5em; -webkit-border-radius:.5em; border-radius:.5em; outline:none; float: left; } -#card textarea { width: 80%; min-height: 5em; min-width: 30em; margin: 0 !important; padding: 0 !important; outline: 0 !important;} -dl.form { width: 100%; float: left; clear: right; margin: 0; padding: 0; cursor: normal; } +#contact input:not([type="checkbox"]), #contact select, #contact textarea { background-color: #fefefe; border: 1px solid #fff !important; -moz-appearance:none !important; -webkit-appearance: none !important; -webkit-box-sizing:none !important; -moz-box-sizing:none !important; box-sizing:none !important; -moz-box-shadow: none; -webkit-box-shadow: none; box-shadow: none; -moz-border-radius: 0px; -webkit-border-radius: 0px; border-radius: 0px; float: left; } +#contact input:hover:not([type="checkbox"]), #contact input:active:not([type="checkbox"]), #contact textarea:focus, #contact textarea:hover { border: 1px solid silver !important; -moz-border-radius:.3em; -webkit-border-radius:.3em; border-radius:.3em; outline:none; float: left; } + +#contact textarea { width: 80%; min-height: 5em; min-width: 30em; margin: 0 !important; padding: 0 !important; outline: 0 !important;} + +#contact input[type="checkbox"] { margin-top: 10px; vertical-align: bottom; float: left; } +dl.form { width: auto; margin: 0; padding: 0; cursor: normal; } .form dt { display: table-cell; clear: left; float: left; width: 7em; margin: 0; padding: 0.8em 0.5em 0 0; text-align:right; text-overflow:ellipsis; o-text-overflow: ellipsis; vertical-align: text-bottom; color: #bbb;/* white-space: pre-wrap; white-space: -moz-pre-wrap !important; white-space: -pre-wrap; white-space: -o-pre-wrap;*/ } -.form dd { display: table-cell; clear: right; float: left; margin: 0; padding: 0px; white-space: nowrap; vertical-align: text-bottom; } -label:hover, dt:hover { color: #333; } +.form dd { display: table-cell; clear: right; float: left; margin: 0; padding: 0; white-space: nowrap; vertical-align: text-bottom; } /*::-webkit-input-placeholder { color: #bbb; } :-moz-placeholder { color: #bbb; } :-ms-input-placeholder { color: #bbb; }*/ @@ -66,7 +65,6 @@ label:hover, dt:hover { color: #333; } .upload { background:url('%webroot%/core/img/actions/upload.svg') no-repeat center; } .download { background:url('%webroot%/core/img/actions/download.svg') no-repeat center; } .cloud { background:url('%webroot%/core/img/places/picture.svg') no-repeat center; } -/*.globe { background:url('../img/globe.svg') no-repeat center; }*/ .globe { background:url('%webroot%/core/img/actions/public.svg') no-repeat center; } .transparent{ opacity: 0.6; } #edit_name_dialog { padding:0; } @@ -74,19 +72,13 @@ label:hover, dt:hover { color: #333; } #edit_address_dialog { /*width: 30em;*/ } #edit_address_dialog > input { width: 15em; } #edit_photo_dialog_img { display: block; min-width: 150; min-height: 200; } -#fn { float: left !important; width: 18em !important; } -#name { /*position: absolute; top: 0px; left: 0px;*/ min-width: 25em; height: 2em; clear: right; display: block; } -#identityprops { /*position: absolute; top: 2.5em; left: 0px;*/ } -#contact_photo { float: left; margin: 1em; } -#contact_identity { min-width: 30em; padding: 0.5em;} -.contactsection { position: relative; float: left; width: 35em; padding: 0.5em; height: auto; } #cropbox { margin: auto; } #contacts_details_photo_wrapper { width: 150px; } #contacts_details_photo_wrapper.wait { opacity: 0.6; filter:alpha(opacity=0.6); z-index:1000; background: url('%webroot%/core/img/loading.gif') no-repeat center center; cursor: wait; } -.contacts_details_photo { border-radius: 0.5em; border: thin solid #bbb; margin: 0.3em; background: url('%webroot%/core/img/loading.gif') no-repeat center center; -moz-box-shadow: 0 1px 3px #777; -webkit-box-shadow: 0 1px 3px #777; box-shadow: 0 1px 3px #777; opacity: 1; } +.contacts_details_photo { border-radius: 0.3em; border: thin solid #bbb; margin: 0.3em; background: url('%webroot%/core/img/loading.gif') no-repeat center center; -moz-box-shadow: 0 1px 3px #777; -webkit-box-shadow: 0 1px 3px #777; box-shadow: 0 1px 3px #777; opacity: 1; } .contacts_details_photo:hover { background: #fff; cursor: default; } -#phototools { position:absolute; margin: 5px 0 0 10px; width:auto; height:22px; padding:0px; background-color:#fff; list-style-type:none; border-radius: 0.5em; -moz-box-shadow: 0 1px 3px #777; -webkit-box-shadow: 0 1px 3px #777; box-shadow: 0 1px 3px #777; } +#phototools { position:absolute; margin: 5px 0 0 10px; width:auto; height:22px; padding:0px; background-color:#fff; list-style-type:none; border-radius: 0.3em; -moz-box-shadow: 0 1px 3px #777; -webkit-box-shadow: 0 1px 3px #777; box-shadow: 0 1px 3px #777; } #phototools li { display: inline; } #phototools li a { float:left; cursor:pointer; width:22px; height:22px; opacity: 0.6; } #phototools li a:hover { opacity: 0.8; } @@ -118,24 +110,26 @@ dl.addresscard .action { float: right; } #file_upload_form { width: 0; height: 0; } #file_upload_target, #import_upload_target, #crop_target { display:none; } #file_upload_start, #import_upload_start { -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)"; filter:alpha(opacity=0); opacity:0; z-index:1001; width:0; height:0;} -input[type="checkbox"] { width: 20px; height: 20px; vertical-align: bottom; } .big { font-weight:bold; font-size:1.2em; } .huge { font-weight:bold; font-size:1.5em; } -.propertycontainer dd { float: left; width: 25em; } -/*.propertylist { clear: none; max-width: 33em; }*/ -.propertylist li.propertycontainer { white-space: nowrap; min-width: 35em; display: block; clear: both; } -.propertycontainer[data-element="EMAIL"] > input[type="email"],.propertycontainer[data-element="TEL"] > input[type="text"] { min-width: 12em !important; float: left; } -.propertylist li > input[type="checkbox"],input[type="radio"] { float: left; clear: left; width: 16px; height: 16px; vertical-align: middle; padding: 0; } + +.propertylist li.propertycontainer { white-space: nowrap; min-width: 38em; display: block; clear: both; } +.propertylist { float: left; } +.propertylist li > input[type="checkbox"],input[type="radio"] { float: left; } +.propertylist li > input.value:not([type="checkbox"]) { min-width: 16em; } .propertylist li > select { float: left; max-width: 8em; } .propertylist li > .select_wrapper { float: left; overflow: hidden; color: #bbb; font-size: 0.8em; } -.propertylist li > .select_wrapper select { float: left; overflow: hidden; color: #bbb; } +.propertylist li > .select_wrapper select { float: left; overflow: hidden; text-overflow: ellipsis; color: #bbb; width: 8em; } +.propertylist li > .select_wrapper select:hover { overflow: inherit; text-overflow: inherit; } .propertylist li > .select_wrapper select option { color: #777; } .propertylist li > .select_wrapper select:hover,.propertylist li > select:focus,.propertylist li > select:active { color: #777; } -.propertylist li > .select_wrapper select.impp { margin-left: -23px; direction: rtl; } +.propertylist li > .select_wrapper select.rtl { margin-left: -24px; direction: rtl; } .propertylist li > .select_wrapper select.types { margin-right: -23px; } .propertylist li > input[type="checkbox"].impp { clear: none; } .propertylist li > label.xab { display: block; color: #bbb; float:left; clear: both; padding: 0.5em 0 0 2.5em; } .propertylist li > label.xab:hover { color: #777; } +label, dt, .label { float: left; font-size: 0.7em; color: #bbb !important; max-width: 7em !important; border: 0; } +label:hover, .form dt:hover, input.label:hover { color: #777 !important; } .typelist[type="button"] { float: left; max-width: 8em; border: 0; background-color: #fff; color: #bbb; box-shadow: none; } /* for multiselect */ .typelist[type="button"]:hover { color: #777; } /* for multiselect */ .addresslist { clear: both; font-weight: bold; } @@ -156,4 +150,81 @@ input[type="checkbox"] { width: 20px; height: 20px; vertical-align: bottom; } .addressbooks-settings .actions input.name { width: 7em; } .addressbooks-settings a.action { opacity: 0.2; } .addressbooks-settings a.action:hover { opacity: 1; } -.addressbooks-settings td.active, .addressbooks-settings td.action { width: 20px; } \ No newline at end of file +.addressbooks-settings td.active, .addressbooks-settings td.action { width: 20px; } + +#toggle_all { position: absolute; bottom: .5em; left: .8em; } +.numcontacts { float: right; } +input.propertytype { float: left; font-size: .8em; width: 8em !important; direction: rtl;} +#rightcontent, .rightcontent { position:fixed; top: 7.5em; left: 32.5em; overflow-x:hidden; overflow-y: auto; } +#rightcontent table { position: relative; top: 0; left: 0; right: 0; } +#contactsheader { position: fixed; padding: 0; margin:0; top:3.5em; left: 32.5em; right: 0; height: 4em; border-bottom: 1px solid #DDDDDD; z-index: 50; } +#contactsheader div { padding: 0 0.5em; height: 100%; width: 90%; margin:0; } + +#contactsheader button { width: 26px; height: 26px; margin-right: .5em; top: .7em; opacity: 0.5; } +#contactsheader button:hover { opacity: 1; } +#contactsheader .settings { background:url('%webroot%/core/img/actions/settings.svg') no-repeat center; position: absolute; right: 1em; margin: 0; } +#contactsheader .import { background:url('%webroot%/core/img/actions/upload.svg') no-repeat center; } +#contactsheader .newcontact { background:url('%appswebroot%/contacts/img/contact-new.svg') no-repeat center; } +#contactsheader .delete { background:url('%webroot%/core/img/actions/delete.svg') no-repeat center; } +#contactsheader .add { background:url('%webroot%/core/img/actions/add.svg') no-repeat center; margin-left: 5em; } + +#contactlist tr { height: 3em; } +#contactlist tr td { text-overflow: ellipsis; border-bottom: 1px solid #DDDDDD; font-weight: normal; text-align: left; overflow: hidden; text-overflow: ellipsis; vertical-align: middle; white-space: nowrap; } +#contactlist tr td:hover { overflow: inherit; text-overflow: inherit; background-color: #fff; z-index: 200; } +#contactlist tr td:not(.adr) { width: 15%; } +#contactlist tr td.name>input[type=checkbox]:first-child { -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)"; filter:alpha(opacity=0); opacity:0; float:left; margin:.5em 0 0 1.2em; -webkit-transition:opacity 200ms; -moz-transition:opacity 200ms; -o-transition:opacity 200ms; transition:opacity 200ms; } +#contactlist tr td.name>input[type="checkbox"]:hover:first-child { -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=80)"; filter:alpha(opacity=80); opacity:.8; } +#contactlist tr td.name>input[type="checkbox"]:checked:first-child { -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=100)"; filter:alpha(opacity=100); opacity:1; } +#contactlist tr td.name { font-weight: bold; text-indent: 1.6em; -webkit-transition:background-image 500ms; -moz-transition:background-image 500ms; -o-transition:background-image 500ms; transition:background-image 500ms; position:relative; background-position:1em .5em !important; background-repeat:no-repeat !important; } +#contactlist tr td.email span { float: left; clear: none; } +#contactlist tr td a.mailto { float: right; cursor:pointer; width:22px; height:22px; z-index: 200; opacity: 0.6; background:url('%webroot%/core/img/actions/mail.svg') no-repeat center; } +#contactlist tr td a.mailto:hover { opacity: 0.8; } + +section#contact { position: relative; top: 0; left: 0; right: 0; } + +#contact figure { float: left; clear: none; } +#contact figure img { -moz-border-radius:.3em; -webkit-border-radius:.3em; border-radius:.3em; border: thin solid #bbb; margin: 0.3em; background: url('%webroot%/core/img/loading.gif') no-repeat center center; -moz-box-shadow: 0 1px 3px #777; -webkit-box-shadow: 0 1px 3px #777; box-shadow: 0 1px 3px #777; opacity: 1; } +#contact section { float: left; margin: 1em; } +#contact footer { clear: both; margin: 1em; } +#contact li { display: block; clear: both; white-space: nowrap; } +#contact span.adr { float: left; max-width: 14em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +#contact span.adr:hover { overflow: inherit; } +#contact .value {float: left; } + + +@media screen and (max-width: 1500px) { + #contactlist tr td.categories { display: none; } +} +@media screen and (max-width: 1400px) { + #contactlist tr td.adr { display: none; } +} +@media screen and (min-width: 1400px) { + ul.propertylist { + -moz-column-count: 3; + /*-webkit-columns: 3;*/ + -o-columns: 3; + columns: 3; + } +} +@media screen and (min-width: 1100) and (max-width: 1200px) { + #contactlist tr td.tel { display: none; } +} +@media screen and (min-width: 800px) and (max-width: 1400) { + ul.propertylist { + -moz-column-count: 2; + -webkit-columns: 2; + -o-columns: 2; + columns: 2; + } +} +@media screen and (max-width: 900px) { + #contactlist tr td.email { display: none; } +} +@media screen and (max-width: 400px) { + ul.propertylist { + -moz-column-count: 1; + -webkit-columns: 1; + -o-columns: 1; + columns: 1; + } +} diff --git a/img/checkmark.png b/img/checkmark.png new file mode 100644 index 0000000000000000000000000000000000000000..e00cc1d141414e17ec1257b6446dba954cfaafb8 GIT binary patch literal 280 zcmeAS@N?(olHy`uVBq!ia0vp^d?3uh1|;P@bT0xamSQK*5Dp-y;YjHK@;M7UB8!1) zj({-ZRBb+Kpx`b~7sn8diF+??^kZ@qX?@tQdeBtNM1WgFo11w?PS4b>`iGLEUO3-K zSgXdt+R`Q=yyQl7j@s%(X+Pu1)<4hhEKawWso8Q@AP(5a` zR?OHYsjH5+L@rbQ#assign('uploadMaxFilesize', $maxUploadFilesize, false); $tmpl->assign('uploadMaxHumanFilesize', OCP\Util::humanFileSize($maxUploadFilesize), false); $tmpl->assign('phone_types', $phone_types, false); $tmpl->assign('email_types', $email_types, false); +$tmpl->assign('adr_types', $adr_types, false); $tmpl->assign('impp_types', $impp_types, false); $tmpl->assign('categories', $categories, false); $tmpl->assign('im_protocols', $im_protocols, false); diff --git a/js/app.js b/js/app.js new file mode 100644 index 00000000..04a2ba1c --- /dev/null +++ b/js/app.js @@ -0,0 +1,871 @@ +if (typeof Object.create !== 'function') { + Object.create = function (o) { + function F() {} + F.prototype = o; + return new F(); + }; +} + +Array.prototype.clean = function(deleteValue) { + for (var i = 0; i < this.length; i++) { + if (this[i] == deleteValue) { + this.splice(i, 1); + i--; + } + } + return this; +}; + +OC.Contacts = OC.Contacts || { + init:function() { + this.ENTER_KEY = 13; + this.scrollTimeoutMiliSecs = 100; + this.isScrolling = false; + this.cacheElements(); + this.Contacts = new OC.Contacts.ContactList( + this.$contactList, + this.$contactListItemTemplate, + this.$contactFullTemplate, + this.detailTemplates + ); + this.bindEvents(); + }, + /** + * Arguments: + * message: The text message to show. + * timeout: The timeout in seconds before the notification disappears. Default 10. + * timeouthandler: A function to run on timeout. + * clickhandler: A function to run on click. If a timeouthandler is given it will be cancelled. + * data: An object that will be passed as argument to the timeouthandler and clickhandler functions. + * cancel: If set cancel all ongoing timer events and hide the notification. + */ + notify:function(params) { + var self = this; + if(!self.notifier) { + self.notifier = $('#notification'); + } + if(params.cancel) { + self.notifier.off('click'); + for(var id in self.notifier.data()) { + if($.isNumeric(id)) { + clearTimeout(parseInt(id)); + } + } + self.notifier.text('').fadeOut().removeData(); + return; + } + self.notifier.text(params.message); + self.notifier.fadeIn(); + self.notifier.on('click', function() { $(this).fadeOut();}); + var timer = setTimeout(function() { + if(!self || !self.notifier) { + var self = OC.Contacts; + self.notifier = $('#notification'); + } + self.notifier.fadeOut(); + if(params.timeouthandler && $.isFunction(params.timeouthandler)) { + params.timeouthandler(self.notifier.data(dataid)); + self.notifier.off('click'); + self.notifier.removeData(dataid); + } + }, params.timeout && $.isNumeric(params.timeout) ? parseInt(params.timeout)*1000 : 10000); + var dataid = timer.toString(); + if(params.data) { + self.notifier.data(dataid, params.data); + } + if(params.clickhandler && $.isFunction(params.clickhandler)) { + self.notifier.on('click', function() { + if(!self || !self.notifier) { + var self = OC.Contacts; + self.notifier = $(this); + } + clearTimeout(timer); + self.notifier.off('click'); + params.clickhandler(self.notifier.data(dataid)); + self.notifier.removeData(dataid); + }); + } + }, + loading:function(obj, state) { + if(state) { + $(obj).addClass('loading'); + } else { + $(obj).removeClass('loading'); + } + }, + cacheElements: function() { + var self = this; + this.detailTemplates = {}; + // Load templates for contact details. + // The weird double loading is because jquery apparently doesn't + // create a searchable object from a script element. + $.each($($('#contactDetailsTemplate').html()), function(idx, node) { + if(node.nodeType === Node.ELEMENT_NODE && node.nodeName === 'DIV') { + var $tmpl = $(node.innerHTML); + self.detailTemplates[$tmpl.data('element')] = $(node.outerHTML); + } + }); + this.$groupListItemTemplate = $('#groupListItemTemplate'); + this.$contactListItemTemplate = $('#contactListItemTemplate'); + this.$contactFullTemplate = $('#contactFullTemplate'); + this.$contactDetailsTemplate = $('#contactDetailsTemplate'); + this.$rightContent = $('#rightcontent'); + this.$header = $('#contactsheader'); + this.$groupList = $('#grouplist'); + this.$contactList = $('#contactlist'); + this.$contactListHeader = $('#contactlistheader'); + this.$toggleAll = $('#toggle_all'); + }, + bindEvents: function() { + var self = this; + this.$toggleAll.on('change', function() { + self.Contacts.toggleAll(this, self.$contactList.find('input:checkbox')); + }); + this.$contactList.on('change', 'input:checkbox', function(event) { + var id = parseInt($(this).parents('tr').first().data('id')); + self.Contacts.selectedContacts.push(id); + console.log('selected', id); + }); + $(document).bind('status.contact.deleted', function(e, data) { + var id = parseInt(data.id); + console.log('contact', data.id, 'deleted'); + // update counts on group list + self.$groupList.find('h3').each(function(i, group) { + if($(this).data('type') === 'all') { + $(this).find('.numcontacts').text(parseInt($(this).find('.numcontacts').text()-1)); + } else if($(this).data('type') === 'category') { + var contacts = $(this).data('contacts'); + console.log('contacts', contacts, contacts.indexOf(id), contacts.indexOf(String(id))); + if(contacts.indexOf(String(id)) !== -1) { + contacts.splice(contacts.indexOf(String(id)), 1); + console.log('contacts', contacts, contacts.indexOf(id), contacts.indexOf(String(id))); + $(this).data('contacts', contacts); + $(this).find('.numcontacts').text(contacts.length); + } + } + }); + }); + $(document).bind('status.contact.enabled', function(e, enabled) { + if(enabled) { + self.$header.find('.delete').show(); + } else { + self.$header.find('.delete').hide(); + } + }); + $(document).bind('status.contactsLoaded', function(e, result) { + console.log('contactsLoaded', result); + if(result.status !== true) { + alert('Error loading contacts!'); + } + self.numcontacts = result.numcontacts; + self.loadGroups(); + self.$rightContent.removeClass('loading'); + }); + // mark items whose title was hid under the top edge as read + /*this.$rightContent.scroll(function() { + // prevent too many scroll requests; + if(!self.isScrolling) { + self.isScrolling = true; + var num = self.$contactList.find('tr').length; + //console.log('num', num); + var offset = self.$contactList.find('tr:eq(' + (num-20) + ')').offset().top; + if(offset < self.$rightContent.height()) { + console.log('load more'); + self.Contacts.loadContacts(num, function() { + self.isScrolling = false; + }); + } else { + setTimeout(function() { + self.isScrolling = false; + }, self.scrollTimeoutMiliSecs); + } + //console.log('scroll, unseen:', offset, self.$rightContent.height()); + } + });*/ + this.$groupList.on('click', 'h3', function() { + console.log('Group click', $(this).data('id'), $(this).data('type')); + delete self.currentid; + self.$groupList.find('h3').removeClass('active'); + self.$contactList.show(); + self.$header.find('.list').show(); + self.$header.find('.single').hide(); + $('#contact').remove(); + $(this).addClass('active'); + if($(this).data('type') === 'category') { + self.Contacts.showContacts($(this).data('contacts')); + } else { + self.Contacts.showContacts($(this).data('id')); + } + }); + this.$contactList.on('click', 'tr', function(event) { + if($(event.target).is('input')) { + return; + } + if($(event.target).is('a.mailto')) { + console.log('mailto', $(this).find('.email').text().trim()); + window.location.href='mailto:' + $(this).find('.email').text().trim(); + return; + } + self.currentid = $(this).data('id'); + console.log('Contact click', self.currentid); + self.$contactList.hide(); + self.$header.find('.list').hide(); + self.$header.find('.single').show(); + self.$rightContent.prepend(self.Contacts.showContact(self.currentid)); + }); + this.$header.find('.delete').on('click keydown', function() { + console.log('delete'); + if(self.currentid) { + self.Contacts.delayedDeleteContact(self.currentid); + } else { + console.log('currentid is not set'); + } + }); + this.$header.find('.settings').on('click keydown', function() { + try { + //ninjahelp.hide(); + OC.appSettings({appid:'contacts', loadJS:true, cache:false}); + } catch(e) { + console.log('error:', e.message); + } + }); + this.$contactList.on('mouseenter', 'td.email', function(event) { + if($(this).text().trim().length > 3) { + $(this).find('.mailto').fadeIn(100); + } + }); + this.$contactList.on('mouseleave', 'td.email', function(event) { + $(this).find('.mailto').fadeOut(100); + }); + $('[title]').tipsy(); // find all with a title attribute and tipsy them + }, + update: function() { + console.log('update'); + }, + loadGroups: function() { + var self = this; + var groupList = this.$groupList; + var tmpl = this.$groupListItemTemplate; + + tmpl.octemplate({id: 'all', type: 'all', num: this.numcontacts, name: t('contacts', 'All')}).appendTo(groupList); + tmpl.octemplate({id: 'fav', type: 'fav', num: '', name: t('contacts', 'Favorites')}).appendTo(groupList); + $.getJSON(OC.filePath('contacts', 'ajax', 'categories/list.php'), {}, function(jsondata) { + if (jsondata && jsondata.status == 'success') { + self.categories = []; + $.each(jsondata.data.categories, function(c, category) { + var $elem = (tmpl).octemplate({ + id: category.id, + type: 'category', + num: category.contacts.length, + name: category.name, + }) + self.categories.push({id: category.id, name: category.name}); + $elem.data('contacts', category.contacts) + $elem.appendTo(groupList); + }); + } + }); + }, +}; + + +(function( $ ) { + /** + * An item which binds the appropriate html and event handlers + * @param parent the parent Contacts list + * @param data the data used to populate the contact + * @param template the jquery object used to render the contact + */ + var Contact = function(parent, id, access, data, listtemplate, fulltemplate, detailtemplates) { + //console.log('contact:', id, access); //parent, id, data, listtemplate, fulltemplate); + this.parent = parent, + this.id = id, + this.access = access, + this.data = data, + this.$listTemplate = listtemplate, + this.$fullTemplate = fulltemplate; + this.detailTemplates = detailtemplates; + var self = this; + this.multi_properties = ['EMAIL', 'TEL', 'IMPP', 'ADR', 'URL']; + } + + /** + * Act on change + * @param event + */ + Contact.prototype.save = function(self, obj) { + OC.Contacts.loading(obj, true); + var container = $(obj).hasClass('propertycontainer') + ? obj : self.propertyContainerFor(obj); + var element = container.data('element').toUpperCase(); + console.log('change', obj, element, container, container + .find('input.value,select.value,textarea.value'));//.serializeArray()); + var q = container.find('input.value,select.value,textarea.value').serialize(); + if(q == '' || q == undefined) { + $(document).trigger('status.contact', { + status: 'error', + message: t('contacts', 'Couldn\'t serialize elements.'), + }); + OC.Contacts.loading(obj, false); + return false; + } + q = q + '&id=' + self.id + '&name=' + element; + if(self.multi_properties.indexOf(element) !== -1) { + q = q + '&checksum=' + container.data('checksum'); + } + console.log(q); + OC.Contacts.loading(obj, false); + } + + /** + * Remove any open contact from the DOM and detach it's list + * element from the DOM. + */ + Contact.prototype.detach = function() { + if(this.$fullelem) { + this.$fullelem.remove(); + } + if(this.$listelem) { + return this.$listelem.detach(); + } + } + + /** + * Set a contact to en/disabled depending on its permissions. + * @param boolean enabled + */ + Contact.prototype.setEnabled = function(enabled) { + console.log('setEnabled', enabled); + if(enabled) { + this.$fullelem.find('#addproperty').show(); + } else { + this.$fullelem.find('#addproperty').hide(); + } + this.enabled = enabled; + this.$fullelem.find('.value,.action').each(function () { + console.log($(this)); + $(this).prop('disabled', !enabled); + }); + $(document).trigger('status.contact.enabled', false); + } + + /** + * Delete contact from data store and remove it from the DOM + */ + Contact.prototype.destroy = function(cb) { + var self = this; + $.post(OC.filePath('contacts', 'ajax', 'contact/delete.php'), + {id: this.id}, function(jsondata) { + if(jsondata && jsondata.status === 'success') { + if(self.$listelem) { + self.$listelem.remove(); + } + if(self.$fullelem) { + self.$fullelem.remove(); + } + } + if(typeof cb == 'function') { + cb({ + status: jsondata ? jsondata.status : 'error', + message: (jsondata && jsondata.data) ? jsondata.data.message : '', + }); + } + }); + } + + Contact.prototype.propertyContainerFor = function(obj) { + return $(obj).parents('.propertycontainer').first(); + } + + /** + * Render the list item + * @return A jquery object to be inserted in the DOM + */ + Contact.prototype.renderListItem = function() { + this.$listelem = this.$listTemplate.octemplate({ + id: this.id, + name: this.getPreferredValue('FN', ''), + email: this.getPreferredValue('EMAIL', ''), + tel: this.getPreferredValue('TEL', ''), + adr: this.getPreferredValue('ADR', []).clean('').join(', '), + categories: this.getPreferredValue('CATEGORIES', []) + .clean('').join(' / '), + }); + return this.$listelem; + } + + /** + * Render the full contact + * @return A jquery object to be inserted in the DOM + */ + Contact.prototype.renderContact = function() { + var self = this; + console.log('renderContact', this.data); + var values = this.data + ? { + id: this.id, + name: this.getPreferredValue('FN', ''), + nickname: this.getPreferredValue('NICKNAME', ''), + title: this.getPreferredValue('TITLE', ''), + org: this.getPreferredValue('ORG', []).clean('').join(', '), // TODO Add parts if more than one. + bday: this.getPreferredValue('BDAY', '').length >= 10 + ? $.datepicker.formatDate('dd-mm-yy', + $.datepicker.parseDate('yy-mm-dd', + this.getPreferredValue('BDAY', '').substring(0, 10))) + : '', + } + : {id: '', name: '', nickname: '', title: '', org: '', bday: ''}; + this.$fullelem = this.$fullTemplate.octemplate(values).data('contactobject', this); + this.$fullelem.on('change', '#addproperty', function(event) { + console.log('add', $(this).val()); + $(this).val('') + }); + this.$fullelem.on('change', '.value', function(event) { + console.log('change', event); + self.save(self, event.target); + }); + this.$fullelem.find('form').on('submit', function(event) { + console.log('submit', event); + return false; + }); + this.$fullelem.find('[data-element="bday"]') + .find('input').datepicker({ + dateFormat : 'dd-mm-yy' + }); + if(!this.data) { + // A new contact + this.setEnabled(true); + return this.$fullelem; + } + for(var value in values) { + console.log(value); + if(!values[value].length) { + this.$fullelem.find('[data-element="' + value + '"]').hide(); + } + } + $.each(this.multi_properties, function(idx, name) { + if(self.data[name]) { + var $list = self.$fullelem.find('ul.' + name.toLowerCase()); + $list.show(); + for(var p in self.data[name]) { + if(typeof self.data[name][p] === 'object') { + var property = self.data[name][p]; + console.log(name, p, property); + $property = null; + switch(name) { + case 'TEL': + case 'URL': + case 'EMAIL': + $property = self.renderStandardProperty(name.toLowerCase(), property); + break; + case 'ADR': + $property = self.renderAddressProperty(property); + break; + case 'IMPP': + $property = self.renderIMProperty(property); + break; + } + if(!$property) { + continue; + } + //console.log('$property', $property); + if(property.label) { + if(!property.parameters['TYPE']) { + property.parameters['TYPE'] = []; + } + property.parameters['TYPE'].push(property.label); + } + for(var param in property.parameters) { + //console.log('param', param); + if(param.toUpperCase() == 'PREF') { + $property.find('input[type="checkbox"]').attr('checked', 'checked') + } + else if(param.toUpperCase() == 'TYPE') { + for(etype in property.parameters[param]) { + var found = false; + var et = property.parameters[param][etype]; + if(typeof et !== 'string') { + continue; + } + //console.log('et', et); + if(et.toUpperCase() === 'INTERNET') { + continue; + } + $property.find('select.type option').each(function() { + if($(this).val().toUpperCase() === et.toUpperCase()) { + $(this).attr('selected', 'selected'); + found = true; + } + }); + if(!found) { + $property.find('select.type option:last-child').after(''); + } + } + } + else if(param.toUpperCase() == 'X-SERVICE-TYPE') { + //console.log('setting', $property.find('select.impp'), 'to', property.parameters[param].toLowerCase()); + $property.find('select.impp').val(property.parameters[param].toLowerCase()); + } + } + $property.find('select.type[name="parameters[TYPE][]"]') + .combobox({ + singleclick: true, + classes: ['propertytype', 'float', 'label'], + }); + $list.append($property); + } + } + } + }); + if(this.access.owner !== OC.currentUser + && !(this.access.permissions & OC.PERMISSION_UPDATE + || this.access.permissions & OC.PERMISSION_DELETE)) { + this.setEnabled(false); + } + return this.$fullelem; + } + + /** + * Render a simple property. Used for EMAIL and TEL. + * @return A jquery object to be injected in the DOM + */ + Contact.prototype.renderStandardProperty = function(name, property) { + if(!this.detailTemplates[name]) { + console.log('No template for', name); + return; + } + var values = { value: property.value, checksum: property.checksum }; + $elem = this.detailTemplates[name].octemplate(values); + return $elem; + } + + /** + * Render an ADR (address) property. + * @return A jquery object to be injected in the DOM + */ + Contact.prototype.renderAddressProperty = function(property) { + if(!this.detailTemplates['adr']) { + console.log('No template for adr', this.detailTemplates); + return; + } + var values = { + value: property.value.clean('').join(', '), + checksum: property.checksum, + adr0: property.value[0] || '', + adr1: property.value[1] || '', + adr2: property.value[2] || '', + adr3: property.value[3] || '', + adr4: property.value[4] || '', + adr5: property.value[5] || '', + }; + $elem = this.detailTemplates['adr'].octemplate(values); + return $elem; + } + + /** + * Render an IMPP (Instant Messaging) property. + * @return A jquery object to be injected in the DOM + */ + Contact.prototype.renderIMProperty = function(property) { + if(!this.detailTemplates['impp']) { + console.log('No template for impp', this.detailTemplates); + return; + } + var values = { + value: property.value, + checksum: property.checksum, + }; + $elem = this.detailTemplates['impp'].octemplate(values); + return $elem; + } + /** + * Get the jquery element associated with this object + */ + Contact.prototype.getListItemElement = function() { + if(!this.$listelem) { + this.renderListItem(); + } + return this.$listelem; + } + + /** + * Get the preferred value for a property. + * If a preferred value is not found the first one will be returned. + * @param string name The name of the property like EMAIL, TEL or ADR. + * @param def A default value to return if nothing is found. + */ + Contact.prototype.getPreferredValue = function(name, def) { + var pref = def, found = false; + if(this.data[name]) { + var props = this.data[name]; + //console.log('props', props); + $.each(props, function( i, prop ) { + //console.log('prop:', i, prop); + if(i === 0) { // Choose first to start with + pref = prop.value; + } + for(var param in prop.parameters) { + if(param.toUpperCase() == 'PREF') { + found = true; // + break; + } + } + if(found) { + return false; // break out of loop + } + }); + } + return pref; + } + + var ContactList = function(contactlist, contactlistitemtemplate, contactfulltemplate, contactdetailtemplates) { + //console.log('ContactList', contactlist, contactlistitemtemplate, contactfulltemplate, contactdetailtemplates); + var self = this; + this.contacts = {}; + this.deletionQueue = []; + this.selectedContacts = []; + this.$contactList = contactlist; + this.$contactListItemTemplate = contactlistitemtemplate; + this.$contactFullTemplate = contactfulltemplate; + this.contactDetailTemplates = contactdetailtemplates; + this.$contactList.scrollTop(0); + this.loadContacts(0); + + } + + /** + * Show contacts in list + * @param Array contacts. A list of contact ids. + */ + ContactList.prototype.showContacts = function(contacts) { + for(var contact in this.contacts) { + if(contacts === 'all') { + this.contacts[contact].getListItemElement().show(); + } else { + contact = parseInt(contact); + if(contacts.indexOf(String(contact)) === -1) { + this.contacts[contact].getListItemElement().hide(); + } else { + this.contacts[contact].getListItemElement().show(); + } + } + } + } + + /** + * Jumps to an element in the contact list + * FIXME: Use cached contact element. + * @param number the number of the item starting with 0 + */ + ContactList.prototype.jumpToElemenId = function(id) { + $elem = $('tr.contact_item[data-id="' + id + '"]'); + this.$contactList.scrollTop( + $elem.offset().top - this.$contactList.offset().top + + this.$contactList.scrollTop()); + }; + + /** + * Returns a Contact object by searching for its id + * @param id the id of the node + * @return the Contact object or undefined if not found. + * FIXME: If continious loading is reintroduced this will have + * to load the requested contact. + */ + ContactList.prototype.findById = function(id) { + return this.contacts[parseInt(id)]; + }; + + ContactList.prototype.warnNotDeleted = function(e) { + e = e || window.event; + var warn = t('contacts', 'Some contacts are marked for deletion, but not deleted yet. Please wait for them to be deleted.'); + if (e) { + e.returnValue = String(warn); + } + if(OC.Contacts.Contacts.deletionQueue.length > 0) { + setTimeout(OC.Contacts.Contacts.deleteFilesInQueue, 1); + } + return warn; + } + + ContactList.prototype.delayedDeleteContact = function(id) { + var self = this; + var listelem = this.contacts[parseInt(id)].detach(); + self.$contactList.show(); + this.deletionQueue.push(parseInt(id)); + console.log('deletionQueue', this.deletionQueue, listelem); + if(!window.onbeforeunload) { + window.onbeforeunload = this.warnNotDeleted; + } + // TODO: Check if there are anymore contacts, otherwise show intro. + OC.Contacts.notify({ + data:listelem, + message:t('contacts','Click to undo deletion of "') + listelem.find('td.name').text() + '"', + //timeout:5, + timeouthandler:function(listelem) { + console.log('timeout', listelem); + self.deleteContact(listelem.data('id'), true); + }, + clickhandler:function(listelem) { + self.insertContact({contact:listelem}); + OC.Contacts.notify({message:t('contacts', 'Cancelled deletion of: "') + listelem.find('a').text() + '"'}); + window.onbeforeunload = null; + } + }); + } + + /** + * Delete a contact with this id + * @param id the id of the contact + */ + ContactList.prototype.deleteContact = function(id, removeFromQueue) { + var self = this; + var id = parseInt(id); + console.log('deletionQueue', this.deletionQueue); + var updateQueue = function(id, remove) { + if(removeFromQueue) { + OC.Contacts.Contacts.deletionQueue.splice(OC.Contacts.Contacts.deletionQueue.indexOf(parseInt(id)), 1); + } + if(OC.Contacts.Contacts.deletionQueue.length == 0) { + window.onbeforeunload = null; + } + } + + if(OC.Contacts.Contacts.deletionQueue.indexOf(parseInt(id)) == -1 && removeFromQueue) { + console.log('returning'); + updateQueue(id, removeFromQueue); + if(typeof cb == 'function') { + window.onbeforeunload = null; + } + return; + } + + this.contacts[id].destroy(function(response) { + console.log('deleteContact', response); + if(response.status === 'success') { + delete self.contacts[parseInt(id)]; + updateQueue(id, removeFromQueue); + self.$contactList.show(); + window.onbeforeunload = null; + $(document).trigger('status.contact.deleted', { + id: id, + }); + } else { + OC.Contacts.notify({message:response.message}); + } + }); + } + + /** + * Opens the contact with this id in edit mode + * @param id the id of the contact + */ + ContactList.prototype.showContact = function(id) { + console.log('Contacts.showContact', id, this.contacts[parseInt(id)], this.contacts) + return this.contacts[parseInt(id)].renderContact(); + }; + + /** + * Toggle all checkboxes + */ + ContactList.prototype.toggleAll = function(toggler, togglees) { + var isChecked = $(toggler).is(':checked'); + console.log('toggleAll', isChecked, self); + $.each(togglees, function( i, item ) { + item.checked = isChecked; + }); + }; + + /** + * Insert a contact in the list + * @param jQuery object + */ + ContactList.prototype.insertContact = function(contact) { + console.log('insertContact', contact); + } + + /** + * Load contacts + * @param int offset + */ + ContactList.prototype.loadContacts = function(offset, cb) { + var self = this; + // Should the actual ajax call be in the controller? + $.getJSON(OC.filePath('contacts', 'ajax', 'contact/list.php'), {offset: offset}, function(jsondata) { + if (jsondata && jsondata.status == 'success') { + console.log('addressbooks', jsondata.data.addressbooks); + self.addressbooks = {}; + $.each(jsondata.data.addressbooks, function(i, book) { + self.addressbooks[parseInt(book.id)] = {owner: book.userid, permissions: parseInt(book.permissions)}; + }); + $.each(jsondata.data.contacts, function(c, contact) { + self.contacts[parseInt(contact.id)] + = new Contact( + self, + contact.id, + self.addressbooks[parseInt(contact.aid)], + contact.data, + self.$contactListItemTemplate, + self.$contactFullTemplate, + self.contactDetailTemplates + ); + var item = self.contacts[parseInt(contact.id)].renderListItem() + self.$contactList.append(item); + }); + $(document).trigger('status.contactsLoaded', { + status: true, + numcontacts: jsondata.data.contacts.length + }); + } + if(typeof cb === 'function') { + cb(); + } + }); + } + OC.Contacts.ContactList = ContactList; + + + /** + * Object Template + * Inspired by micro templating done by e.g. underscore.js + */ + var Template = { + init: function(options, elem) { + // Mix in the passed in options with the default options + this.options = $.extend({},this.options,options); + + // Save the element reference, both as a jQuery + // reference and a normal reference + this.elem = elem; + this.$elem = $(elem); + + var _html = this._build(this.options); + //console.log('html', this.$elem.html()); + return $(_html); + }, + // From stackoverflow.com/questions/1408289/best-way-to-do-variable-interpolation-in-javascript + _build: function(o){ + return this.$elem.html().replace(/{([^{}]*)}/g, + function (a, b) { + var r = o[b]; + return typeof r === 'string' || typeof r === 'number' ? r : a; + } + ); + }, + options: { + }, + }; + + $.fn.octemplate = function(options) { + if ( this.length ) { + var _template = Object.create(Template); + return _template.init(options, this); + } + }; + +})( jQuery ); + +$(document).ready(function() { + + OC.Contacts.init(); + +}); diff --git a/js/jquery.combobox.js b/js/jquery.combobox.js index c9ffb4c6..b7a5c748 100644 --- a/js/jquery.combobox.js +++ b/js/jquery.combobox.js @@ -6,18 +6,21 @@ $.widget('ui.combobox', { options: { id: null, - name: null, showButton: false, - editable: true + editable: true, + singleclick: false, }, _create: function() { var self = this, select = this.element.hide(), selected = select.children(':selected'), value = selected.val() ? selected.text() : ''; - var input = this.input = $('') + var name = this.element.attr('name'); + //this.element.attr('name', 'old_' + name) + var input = this.input = $('') .insertAfter( select ) .val( value ) + //.attr('name', name) .autocomplete({ delay: 0, minLength: 0, @@ -80,10 +83,20 @@ self._setOption(key, value); }); - input.dblclick(function() { - // pass empty string as value to search for, displaying all results - input.autocomplete('search', ''); - }); + var clickHandler = function(e) { + var w = self.input.autocomplete('widget'); + if(w.is(':visible')) { + self.input.autocomplete('close'); + } else { + input.autocomplete('search', ''); + } + } + + if(this.options['singleclick'] === true) { + input.click(clickHandler); + } else { + input.dblclick(clickHandler); + } if(this.options['showButton']) { this.button = $('') @@ -128,10 +141,6 @@ this.options['id'] = value; this.input.attr('id', value); break; - case 'name': - this.options['name'] = value; - this.input.attr('name', value); - break; case 'attributes': var input = this.input; $.each(this.options['attributes'], function(key, value) { diff --git a/js/modernizr.js b/js/modernizr.js new file mode 100644 index 00000000..ac23c55f --- /dev/null +++ b/js/modernizr.js @@ -0,0 +1,1394 @@ +/*! + * Modernizr v2.6.3pre + * www.modernizr.com + * + * Copyright (c) Faruk Ates, Paul Irish, Alex Sexton + * Available under the BSD and MIT licenses: www.modernizr.com/license/ + */ + +/* + * Modernizr tests which native CSS3 and HTML5 features are available in + * the current UA and makes the results available to you in two ways: + * as properties on a global Modernizr object, and as classes on the + * element. This information allows you to progressively enhance + * your pages with a granular level of control over the experience. + * + * Modernizr has an optional (not included) conditional resource loader + * called Modernizr.load(), based on Yepnope.js (yepnopejs.com). + * To get a build that includes Modernizr.load(), as well as choosing + * which tests to include, go to www.modernizr.com/download/ + * + * Authors Faruk Ates, Paul Irish, Alex Sexton + * Contributors Ryan Seddon, Ben Alman + */ + +window.Modernizr = (function( window, document, undefined ) { + + var version = '2.6.3pre', + + Modernizr = {}, + + /*>>cssclasses*/ + // option for enabling the HTML classes to be added + enableClasses = true, + /*>>cssclasses*/ + + docElement = document.documentElement, + + /** + * Create our "modernizr" element that we do most feature tests on. + */ + mod = 'modernizr', + modElem = document.createElement(mod), + mStyle = modElem.style, + + /** + * Create the input element for various Web Forms feature tests. + */ + inputElem /*>>inputelem*/ = document.createElement('input') /*>>inputelem*/ , + + /*>>smile*/ + smile = ':)', + /*>>smile*/ + + toString = {}.toString, + + // TODO :: make the prefixes more granular + /*>>prefixes*/ + // List of property values to set for css tests. See ticket #21 + prefixes = ' -webkit- -moz- -o- -ms- '.split(' '), + /*>>prefixes*/ + + /*>>domprefixes*/ + // Following spec is to expose vendor-specific style properties as: + // elem.style.WebkitBorderRadius + // and the following would be incorrect: + // elem.style.webkitBorderRadius + + // Webkit ghosts their properties in lowercase but Opera & Moz do not. + // Microsoft uses a lowercase `ms` instead of the correct `Ms` in IE8+ + // erik.eae.net/archives/2008/03/10/21.48.10/ + + // More here: github.com/Modernizr/Modernizr/issues/issue/21 + omPrefixes = 'Webkit Moz O ms', + + cssomPrefixes = omPrefixes.split(' '), + + domPrefixes = omPrefixes.toLowerCase().split(' '), + /*>>domprefixes*/ + + /*>>ns*/ + ns = {'svg': 'http://www.w3.org/2000/svg'}, + /*>>ns*/ + + tests = {}, + inputs = {}, + attrs = {}, + + classes = [], + + slice = classes.slice, + + featureName, // used in testing loop + + + /*>>teststyles*/ + // Inject element with style element and some CSS rules + injectElementWithStyles = function( rule, callback, nodes, testnames ) { + + var style, ret, node, docOverflow, + div = document.createElement('div'), + // After page load injecting a fake body doesn't work so check if body exists + body = document.body, + // IE6 and 7 won't return offsetWidth or offsetHeight unless it's in the body element, so we fake it. + fakeBody = body || document.createElement('body'); + + if ( parseInt(nodes, 10) ) { + // In order not to give false positives we create a node for each test + // This also allows the method to scale for unspecified uses + while ( nodes-- ) { + node = document.createElement('div'); + node.id = testnames ? testnames[nodes] : mod + (nodes + 1); + div.appendChild(node); + } + } + + // '].join(''); + div.id = mod; + // IE6 will false positive on some tests due to the style element inside the test div somehow interfering offsetHeight, so insert it into body or fakebody. + // Opera will act all quirky when injecting elements in documentElement when page is served as xml, needs fakebody too. #270 + (body ? div : fakeBody).innerHTML += style; + fakeBody.appendChild(div); + if ( !body ) { + //avoid crashing IE8, if background image is used + fakeBody.style.background = ''; + //Safari 5.13/5.1.4 OSX stops loading if ::-webkit-scrollbar is used and scrollbars are visible + fakeBody.style.overflow = 'hidden'; + docOverflow = docElement.style.overflow; + docElement.style.overflow = 'hidden'; + docElement.appendChild(fakeBody); + } + + ret = callback(div, rule); + // If this is done after page load we don't want to remove the body so check if body exists + if ( !body ) { + fakeBody.parentNode.removeChild(fakeBody); + docElement.style.overflow = docOverflow; + } else { + div.parentNode.removeChild(div); + } + + return !!ret; + + }, + /*>>teststyles*/ + + /*>>mq*/ + // adapted from matchMedia polyfill + // by Scott Jehl and Paul Irish + // gist.github.com/786768 + testMediaQuery = function( mq ) { + + var matchMedia = window.matchMedia || window.msMatchMedia; + if ( matchMedia ) { + return matchMedia(mq).matches; + } + + var bool; + + injectElementWithStyles('@media ' + mq + ' { #' + mod + ' { position: absolute; } }', function( node ) { + bool = (window.getComputedStyle ? + getComputedStyle(node, null) : + node.currentStyle)['position'] == 'absolute'; + }); + + return bool; + + }, + /*>>mq*/ + + + /*>>hasevent*/ + // + // isEventSupported determines if a given element supports the given event + // kangax.github.com/iseventsupported/ + // + // The following results are known incorrects: + // Modernizr.hasEvent("webkitTransitionEnd", elem) // false negative + // Modernizr.hasEvent("textInput") // in Webkit. github.com/Modernizr/Modernizr/issues/333 + // ... + isEventSupported = (function() { + + var TAGNAMES = { + 'select': 'input', 'change': 'input', + 'submit': 'form', 'reset': 'form', + 'error': 'img', 'load': 'img', 'abort': 'img' + }; + + function isEventSupported( eventName, element ) { + + element = element || document.createElement(TAGNAMES[eventName] || 'div'); + eventName = 'on' + eventName; + + // When using `setAttribute`, IE skips "unload", WebKit skips "unload" and "resize", whereas `in` "catches" those + var isSupported = eventName in element; + + if ( !isSupported ) { + // If it has no `setAttribute` (i.e. doesn't implement Node interface), try generic element + if ( !element.setAttribute ) { + element = document.createElement('div'); + } + if ( element.setAttribute && element.removeAttribute ) { + element.setAttribute(eventName, ''); + isSupported = is(element[eventName], 'function'); + + // If property was created, "remove it" (by setting value to `undefined`) + if ( !is(element[eventName], 'undefined') ) { + element[eventName] = undefined; + } + element.removeAttribute(eventName); + } + } + + element = null; + return isSupported; + } + return isEventSupported; + })(), + /*>>hasevent*/ + + // TODO :: Add flag for hasownprop ? didn't last time + + // hasOwnProperty shim by kangax needed for Safari 2.0 support + _hasOwnProperty = ({}).hasOwnProperty, hasOwnProp; + + if ( !is(_hasOwnProperty, 'undefined') && !is(_hasOwnProperty.call, 'undefined') ) { + hasOwnProp = function (object, property) { + return _hasOwnProperty.call(object, property); + }; + } + else { + hasOwnProp = function (object, property) { /* yes, this can give false positives/negatives, but most of the time we don't care about those */ + return ((property in object) && is(object.constructor.prototype[property], 'undefined')); + }; + } + + // Adapted from ES5-shim https://github.com/kriskowal/es5-shim/blob/master/es5-shim.js + // es5.github.com/#x15.3.4.5 + + if (!Function.prototype.bind) { + Function.prototype.bind = function bind(that) { + + var target = this; + + if (typeof target != "function") { + throw new TypeError(); + } + + var args = slice.call(arguments, 1), + bound = function () { + + if (this instanceof bound) { + + var F = function(){}; + F.prototype = target.prototype; + var self = new F(); + + var result = target.apply( + self, + args.concat(slice.call(arguments)) + ); + if (Object(result) === result) { + return result; + } + return self; + + } else { + + return target.apply( + that, + args.concat(slice.call(arguments)) + ); + + } + + }; + + return bound; + }; + } + + /** + * setCss applies given styles to the Modernizr DOM node. + */ + function setCss( str ) { + mStyle.cssText = str; + } + + /** + * setCssAll extrapolates all vendor-specific css strings. + */ + function setCssAll( str1, str2 ) { + return setCss(prefixes.join(str1 + ';') + ( str2 || '' )); + } + + /** + * is returns a boolean for if typeof obj is exactly type. + */ + function is( obj, type ) { + return typeof obj === type; + } + + /** + * contains returns a boolean for if substr is found within str. + */ + function contains( str, substr ) { + return !!~('' + str).indexOf(substr); + } + + /*>>testprop*/ + + // testProps is a generic CSS / DOM property test. + + // In testing support for a given CSS property, it's legit to test: + // `elem.style[styleName] !== undefined` + // If the property is supported it will return an empty string, + // if unsupported it will return undefined. + + // We'll take advantage of this quick test and skip setting a style + // on our modernizr element, but instead just testing undefined vs + // empty string. + + // Because the testing of the CSS property names (with "-", as + // opposed to the camelCase DOM properties) is non-portable and + // non-standard but works in WebKit and IE (but not Gecko or Opera), + // we explicitly reject properties with dashes so that authors + // developing in WebKit or IE first don't end up with + // browser-specific content by accident. + + function testProps( props, prefixed ) { + for ( var i in props ) { + var prop = props[i]; + if ( !contains(prop, "-") && mStyle[prop] !== undefined ) { + return prefixed == 'pfx' ? prop : true; + } + } + return false; + } + /*>>testprop*/ + + // TODO :: add testDOMProps + /** + * testDOMProps is a generic DOM property test; if a browser supports + * a certain property, it won't return undefined for it. + */ + function testDOMProps( props, obj, elem ) { + for ( var i in props ) { + var item = obj[props[i]]; + if ( item !== undefined) { + + // return the property name as a string + if (elem === false) return props[i]; + + // let's bind a function (and it has a bind method -- certain native objects that report that they are a + // function don't [such as webkitAudioContext]) + if (is(item, 'function') && 'bind' in item){ + // default to autobind unless override + return item.bind(elem || obj); + } + + // return the unbound function or obj or value + return item; + } + } + return false; + } + + /*>>testallprops*/ + /** + * testPropsAll tests a list of DOM properties we want to check against. + * We specify literally ALL possible (known and/or likely) properties on + * the element including the non-vendor prefixed one, for forward- + * compatibility. + */ + function testPropsAll( prop, prefixed, elem ) { + + var ucProp = prop.charAt(0).toUpperCase() + prop.slice(1), + props = (prop + ' ' + cssomPrefixes.join(ucProp + ' ') + ucProp).split(' '); + + // did they call .prefixed('boxSizing') or are we just testing a prop? + if(is(prefixed, "string") || is(prefixed, "undefined")) { + return testProps(props, prefixed); + + // otherwise, they called .prefixed('requestAnimationFrame', window[, elem]) + } else { + props = (prop + ' ' + (domPrefixes).join(ucProp + ' ') + ucProp).split(' '); + return testDOMProps(props, prefixed, elem); + } + } + /*>>testallprops*/ + + + /** + * Tests + * ----- + */ + + // The *new* flexbox + // dev.w3.org/csswg/css3-flexbox + + tests['flexbox'] = function() { + return testPropsAll('flexWrap'); + }; + + // The *old* flexbox + // www.w3.org/TR/2009/WD-css3-flexbox-20090723/ + + tests['flexboxlegacy'] = function() { + return testPropsAll('boxDirection'); + }; + + // On the S60 and BB Storm, getContext exists, but always returns undefined + // so we actually have to call getContext() to verify + // github.com/Modernizr/Modernizr/issues/issue/97/ + + tests['canvas'] = function() { + var elem = document.createElement('canvas'); + return !!(elem.getContext && elem.getContext('2d')); + }; + + tests['canvastext'] = function() { + return !!(Modernizr['canvas'] && is(document.createElement('canvas').getContext('2d').fillText, 'function')); + }; + + // webk.it/70117 is tracking a legit WebGL feature detect proposal + + // We do a soft detect which may false positive in order to avoid + // an expensive context creation: bugzil.la/732441 + + tests['webgl'] = function() { + return !!window.WebGLRenderingContext; + }; + + /* + * The Modernizr.touch test only indicates if the browser supports + * touch events, which does not necessarily reflect a touchscreen + * device, as evidenced by tablets running Windows 7 or, alas, + * the Palm Pre / WebOS (touch) phones. + * + * Additionally, Chrome (desktop) used to lie about its support on this, + * but that has since been rectified: crbug.com/36415 + * + * We also test for Firefox 4 Multitouch Support. + * + * For more info, see: modernizr.github.com/Modernizr/touch.html + */ + + tests['touch'] = function() { + var bool; + + if(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) { + bool = true; + } else { + injectElementWithStyles(['@media (',prefixes.join('touch-enabled),('),mod,')','{#modernizr{top:9px;position:absolute}}'].join(''), function( node ) { + bool = node.offsetTop === 9; + }); + } + + return bool; + }; + + + // geolocation is often considered a trivial feature detect... + // Turns out, it's quite tricky to get right: + // + // Using !!navigator.geolocation does two things we don't want. It: + // 1. Leaks memory in IE9: github.com/Modernizr/Modernizr/issues/513 + // 2. Disables page caching in WebKit: webk.it/43956 + // + // Meanwhile, in Firefox < 8, an about:config setting could expose + // a false positive that would throw an exception: bugzil.la/688158 + + tests['geolocation'] = function() { + return 'geolocation' in navigator; + }; + + + tests['postmessage'] = function() { + return !!window.postMessage; + }; + + + // Chrome incognito mode used to throw an exception when using openDatabase + // It doesn't anymore. + tests['websqldatabase'] = function() { + return !!window.openDatabase; + }; + + // Vendors had inconsistent prefixing with the experimental Indexed DB: + // - Webkit's implementation is accessible through webkitIndexedDB + // - Firefox shipped moz_indexedDB before FF4b9, but since then has been mozIndexedDB + // For speed, we don't test the legacy (and beta-only) indexedDB + tests['indexedDB'] = function() { + return !!testPropsAll("indexedDB", window); + }; + + // documentMode logic from YUI to filter out IE8 Compat Mode + // which false positives. + tests['hashchange'] = function() { + return isEventSupported('hashchange', window) && (document.documentMode === undefined || document.documentMode > 7); + }; + + // Per 1.6: + // This used to be Modernizr.historymanagement but the longer + // name has been deprecated in favor of a shorter and property-matching one. + // The old API is still available in 1.6, but as of 2.0 will throw a warning, + // and in the first release thereafter disappear entirely. + tests['history'] = function() { + return !!(window.history && history.pushState); + }; + + tests['draganddrop'] = function() { + var div = document.createElement('div'); + return ('draggable' in div) || ('ondragstart' in div && 'ondrop' in div); + }; + + // FF3.6 was EOL'ed on 4/24/12, but the ESR version of FF10 + // will be supported until FF19 (2/12/13), at which time, ESR becomes FF17. + // FF10 still uses prefixes, so check for it until then. + // for more ESR info, see: mozilla.org/en-US/firefox/organizations/faq/ + tests['websockets'] = function() { + return 'WebSocket' in window || 'MozWebSocket' in window; + }; + + + // css-tricks.com/rgba-browser-support/ + tests['rgba'] = function() { + // Set an rgba() color and check the returned value + + setCss('background-color:rgba(150,255,150,.5)'); + + return contains(mStyle.backgroundColor, 'rgba'); + }; + + tests['hsla'] = function() { + // Same as rgba(), in fact, browsers re-map hsla() to rgba() internally, + // except IE9 who retains it as hsla + + setCss('background-color:hsla(120,40%,100%,.5)'); + + return contains(mStyle.backgroundColor, 'rgba') || contains(mStyle.backgroundColor, 'hsla'); + }; + + tests['multiplebgs'] = function() { + // Setting multiple images AND a color on the background shorthand property + // and then querying the style.background property value for the number of + // occurrences of "url(" is a reliable method for detecting ACTUAL support for this! + + setCss('background:url(https://),url(https://),red url(https://)'); + + // If the UA supports multiple backgrounds, there should be three occurrences + // of the string "url(" in the return value for elemStyle.background + + return (/(url\s*\(.*?){3}/).test(mStyle.background); + }; + + + + // this will false positive in Opera Mini + // github.com/Modernizr/Modernizr/issues/396 + + tests['backgroundsize'] = function() { + return testPropsAll('backgroundSize'); + }; + + tests['borderimage'] = function() { + return testPropsAll('borderImage'); + }; + + + // Super comprehensive table about all the unique implementations of + // border-radius: muddledramblings.com/table-of-css3-border-radius-compliance + + tests['borderradius'] = function() { + return testPropsAll('borderRadius'); + }; + + // WebOS unfortunately false positives on this test. + tests['boxshadow'] = function() { + return testPropsAll('boxShadow'); + }; + + // FF3.0 will false positive on this test + tests['textshadow'] = function() { + return document.createElement('div').style.textShadow === ''; + }; + + + tests['opacity'] = function() { + // Browsers that actually have CSS Opacity implemented have done so + // according to spec, which means their return values are within the + // range of [0.0,1.0] - including the leading zero. + + setCssAll('opacity:.55'); + + // The non-literal . in this regex is intentional: + // German Chrome returns this value as 0,55 + // github.com/Modernizr/Modernizr/issues/#issue/59/comment/516632 + return (/^0.55$/).test(mStyle.opacity); + }; + + + // Note, Android < 4 will pass this test, but can only animate + // a single property at a time + // daneden.me/2011/12/putting-up-with-androids-bullshit/ + tests['cssanimations'] = function() { + return testPropsAll('animationName'); + }; + + + tests['csscolumns'] = function() { + return testPropsAll('columnCount'); + }; + + + tests['cssgradients'] = function() { + /** + * For CSS Gradients syntax, please see: + * webkit.org/blog/175/introducing-css-gradients/ + * developer.mozilla.org/en/CSS/-moz-linear-gradient + * developer.mozilla.org/en/CSS/-moz-radial-gradient + * dev.w3.org/csswg/css3-images/#gradients- + */ + + var str1 = 'background-image:', + str2 = 'gradient(linear,left top,right bottom,from(#9f9),to(white));', + str3 = 'linear-gradient(left top,#9f9, white);'; + + setCss( + // legacy webkit syntax (FIXME: remove when syntax not in use anymore) + (str1 + '-webkit- '.split(' ').join(str2 + str1) + + // standard syntax // trailing 'background-image:' + prefixes.join(str3 + str1)).slice(0, -str1.length) + ); + + return contains(mStyle.backgroundImage, 'gradient'); + }; + + + tests['cssreflections'] = function() { + return testPropsAll('boxReflect'); + }; + + + tests['csstransforms'] = function() { + return !!testPropsAll('transform'); + }; + + + tests['csstransforms3d'] = function() { + + var ret = !!testPropsAll('perspective'); + + // Webkit's 3D transforms are passed off to the browser's own graphics renderer. + // It works fine in Safari on Leopard and Snow Leopard, but not in Chrome in + // some conditions. As a result, Webkit typically recognizes the syntax but + // will sometimes throw a false positive, thus we must do a more thorough check: + if ( ret && 'webkitPerspective' in docElement.style ) { + + // Webkit allows this media query to succeed only if the feature is enabled. + // `@media (transform-3d),(-webkit-transform-3d){ ... }` + injectElementWithStyles('@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}', function( node, rule ) { + ret = node.offsetLeft === 9 && node.offsetHeight === 3; + }); + } + return ret; + }; + + + tests['csstransitions'] = function() { + return testPropsAll('transition'); + }; + + + /*>>fontface*/ + // @font-face detection routine by Diego Perini + // javascript.nwbox.com/CSSSupport/ + + // false positives: + // WebOS github.com/Modernizr/Modernizr/issues/342 + // WP7 github.com/Modernizr/Modernizr/issues/538 + tests['fontface'] = function() { + var bool; + + injectElementWithStyles('@font-face {font-family:"font";src:url("https://")}', function( node, rule ) { + var style = document.getElementById('smodernizr'), + sheet = style.sheet || style.styleSheet, + cssText = sheet ? (sheet.cssRules && sheet.cssRules[0] ? sheet.cssRules[0].cssText : sheet.cssText || '') : ''; + + bool = /src/i.test(cssText) && cssText.indexOf(rule.split(' ')[0]) === 0; + }); + + return bool; + }; + /*>>fontface*/ + + // CSS generated content detection + tests['generatedcontent'] = function() { + var bool; + + injectElementWithStyles(['#',mod,'{font:0/0 a}#',mod,':after{content:"',smile,'";visibility:hidden;font:3px/1 a}'].join(''), function( node ) { + bool = node.offsetHeight >= 3; + }); + + return bool; + }; + + + + // These tests evaluate support of the video/audio elements, as well as + // testing what types of content they support. + // + // We're using the Boolean constructor here, so that we can extend the value + // e.g. Modernizr.video // true + // Modernizr.video.ogg // 'probably' + // + // Codec values from : github.com/NielsLeenheer/html5test/blob/9106a8/index.html#L845 + // thx to NielsLeenheer and zcorpan + + // Note: in some older browsers, "no" was a return value instead of empty string. + // It was live in FF3.5.0 and 3.5.1, but fixed in 3.5.2 + // It was also live in Safari 4.0.0 - 4.0.4, but fixed in 4.0.5 + + tests['video'] = function() { + var elem = document.createElement('video'), + bool = false; + + // IE9 Running on Windows Server SKU can cause an exception to be thrown, bug #224 + try { + if ( bool = !!elem.canPlayType ) { + bool = new Boolean(bool); + bool.ogg = elem.canPlayType('video/ogg; codecs="theora"') .replace(/^no$/,''); + + // Without QuickTime, this value will be `undefined`. github.com/Modernizr/Modernizr/issues/546 + bool.h264 = elem.canPlayType('video/mp4; codecs="avc1.42E01E"') .replace(/^no$/,''); + + bool.webm = elem.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,''); + } + + } catch(e) { } + + return bool; + }; + + tests['audio'] = function() { + var elem = document.createElement('audio'), + bool = false; + + try { + if ( bool = !!elem.canPlayType ) { + bool = new Boolean(bool); + bool.ogg = elem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,''); + bool.mp3 = elem.canPlayType('audio/mpeg;') .replace(/^no$/,''); + + // Mimetypes accepted: + // developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements + // bit.ly/iphoneoscodecs + bool.wav = elem.canPlayType('audio/wav; codecs="1"') .replace(/^no$/,''); + bool.m4a = ( elem.canPlayType('audio/x-m4a;') || + elem.canPlayType('audio/aac;')) .replace(/^no$/,''); + } + } catch(e) { } + + return bool; + }; + + + // In FF4, if disabled, window.localStorage should === null. + + // Normally, we could not test that directly and need to do a + // `('localStorage' in window) && ` test first because otherwise Firefox will + // throw bugzil.la/365772 if cookies are disabled + + // Also in iOS5 Private Browsing mode, attempting to use localStorage.setItem + // will throw the exception: + // QUOTA_EXCEEDED_ERRROR DOM Exception 22. + // Peculiarly, getItem and removeItem calls do not throw. + + // Because we are forced to try/catch this, we'll go aggressive. + + // Just FWIW: IE8 Compat mode supports these features completely: + // www.quirksmode.org/dom/html5.html + // But IE8 doesn't support either with local files + + tests['localstorage'] = function() { + try { + localStorage.setItem(mod, mod); + localStorage.removeItem(mod); + return true; + } catch(e) { + return false; + } + }; + + tests['sessionstorage'] = function() { + try { + sessionStorage.setItem(mod, mod); + sessionStorage.removeItem(mod); + return true; + } catch(e) { + return false; + } + }; + + + tests['webworkers'] = function() { + return !!window.Worker; + }; + + + tests['applicationcache'] = function() { + return !!window.applicationCache; + }; + + + // Thanks to Erik Dahlstrom + tests['svg'] = function() { + return !!document.createElementNS && !!document.createElementNS(ns.svg, 'svg').createSVGRect; + }; + + // specifically for SVG inline in HTML, not within XHTML + // test page: paulirish.com/demo/inline-svg + tests['inlinesvg'] = function() { + var div = document.createElement('div'); + div.innerHTML = ''; + return (div.firstChild && div.firstChild.namespaceURI) == ns.svg; + }; + + // SVG SMIL animation + tests['smil'] = function() { + return !!document.createElementNS && /SVGAnimate/.test(toString.call(document.createElementNS(ns.svg, 'animate'))); + }; + + // This test is only for clip paths in SVG proper, not clip paths on HTML content + // demo: srufaculty.sru.edu/david.dailey/svg/newstuff/clipPath4.svg + + // However read the comments to dig into applying SVG clippaths to HTML content here: + // github.com/Modernizr/Modernizr/issues/213#issuecomment-1149491 + tests['svgclippaths'] = function() { + return !!document.createElementNS && /SVGClipPath/.test(toString.call(document.createElementNS(ns.svg, 'clipPath'))); + }; + + /*>>webforms*/ + // input features and input types go directly onto the ret object, bypassing the tests loop. + // Hold this guy to execute in a moment. + function webforms() { + /*>>input*/ + // Run through HTML5's new input attributes to see if the UA understands any. + // We're using f which is the element created early on + // Mike Taylr has created a comprehensive resource for testing these attributes + // when applied to all input types: + // miketaylr.com/code/input-type-attr.html + // spec: www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary + + // Only input placeholder is tested while textarea's placeholder is not. + // Currently Safari 4 and Opera 11 have support only for the input placeholder + // Both tests are available in feature-detects/forms-placeholder.js + Modernizr['input'] = (function( props ) { + for ( var i = 0, len = props.length; i < len; i++ ) { + attrs[ props[i] ] = !!(props[i] in inputElem); + } + if (attrs.list){ + // safari false positive's on datalist: webk.it/74252 + // see also github.com/Modernizr/Modernizr/issues/146 + attrs.list = !!(document.createElement('datalist') && window.HTMLDataListElement); + } + return attrs; + })('autocomplete autofocus list placeholder max min multiple pattern required step'.split(' ')); + /*>>input*/ + + /*>>inputtypes*/ + // Run through HTML5's new input types to see if the UA understands any. + // This is put behind the tests runloop because it doesn't return a + // true/false like all the other tests; instead, it returns an object + // containing each input type with its corresponding true/false value + + // Big thanks to @miketaylr for the html5 forms expertise. miketaylr.com/ + Modernizr['inputtypes'] = (function(props) { + + for ( var i = 0, bool, inputElemType, defaultView, len = props.length; i < len; i++ ) { + + inputElem.setAttribute('type', inputElemType = props[i]); + bool = inputElem.type !== 'text'; + + // We first check to see if the type we give it sticks.. + // If the type does, we feed it a textual value, which shouldn't be valid. + // If the value doesn't stick, we know there's input sanitization which infers a custom UI + if ( bool ) { + + inputElem.value = smile; + inputElem.style.cssText = 'position:absolute;visibility:hidden;'; + + if ( /^range$/.test(inputElemType) && inputElem.style.WebkitAppearance !== undefined ) { + + docElement.appendChild(inputElem); + defaultView = document.defaultView; + + // Safari 2-4 allows the smiley as a value, despite making a slider + bool = defaultView.getComputedStyle && + defaultView.getComputedStyle(inputElem, null).WebkitAppearance !== 'textfield' && + // Mobile android web browser has false positive, so must + // check the height to see if the widget is actually there. + (inputElem.offsetHeight !== 0); + + docElement.removeChild(inputElem); + + } else if ( /^(search|tel)$/.test(inputElemType) ){ + // Spec doesn't define any special parsing or detectable UI + // behaviors so we pass these through as true + + // Interestingly, opera fails the earlier test, so it doesn't + // even make it here. + + } else if ( /^(url|email)$/.test(inputElemType) ) { + // Real url and email support comes with prebaked validation. + bool = inputElem.checkValidity && inputElem.checkValidity() === false; + + } else { + // If the upgraded input compontent rejects the :) text, we got a winner + bool = inputElem.value != smile; + } + } + + inputs[ props[i] ] = !!bool; + } + return inputs; + })('search tel url email datetime date month week time datetime-local number range color'.split(' ')); + /*>>inputtypes*/ + } + /*>>webforms*/ + + + // End of test definitions + // ----------------------- + + + + // Run through all tests and detect their support in the current UA. + // todo: hypothetically we could be doing an array of tests and use a basic loop here. + for ( var feature in tests ) { + if ( hasOwnProp(tests, feature) ) { + // run the test, throw the return value into the Modernizr, + // then based on that boolean, define an appropriate className + // and push it into an array of classes we'll join later. + featureName = feature.toLowerCase(); + Modernizr[featureName] = tests[feature](); + + classes.push((Modernizr[featureName] ? '' : 'no-') + featureName); + } + } + + /*>>webforms*/ + // input tests need to run. + Modernizr.input || webforms(); + /*>>webforms*/ + + + /** + * addTest allows the user to define their own feature tests + * the result will be added onto the Modernizr object, + * as well as an appropriate className set on the html element + * + * @param feature - String naming the feature + * @param test - Function returning true if feature is supported, false if not + */ + Modernizr.addTest = function ( feature, test ) { + if ( typeof feature == 'object' ) { + for ( var key in feature ) { + if ( hasOwnProp( feature, key ) ) { + Modernizr.addTest( key, feature[ key ] ); + } + } + } else { + + feature = feature.toLowerCase(); + + if ( Modernizr[feature] !== undefined ) { + // we're going to quit if you're trying to overwrite an existing test + // if we were to allow it, we'd do this: + // var re = new RegExp("\\b(no-)?" + feature + "\\b"); + // docElement.className = docElement.className.replace( re, '' ); + // but, no rly, stuff 'em. + return Modernizr; + } + + test = typeof test == 'function' ? test() : test; + + if (typeof enableClasses !== "undefined" && enableClasses) { + docElement.className += ' ' + (test ? '' : 'no-') + feature; + } + Modernizr[feature] = test; + + } + + return Modernizr; // allow chaining. + }; + + + // Reset modElem.cssText to nothing to reduce memory footprint. + setCss(''); + modElem = inputElem = null; + + /*>>shiv*/ + /*! HTML5 Shiv v3.6.1 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed */ + ;(function(window, document) { + /*jshint evil:true */ + /** Preset options */ + var options = window.html5 || {}; + + /** Used to skip problem elements */ + var reSkip = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i; + + /** Not all elements can be cloned in IE **/ + var saveClones = /^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i; + + /** Detect whether the browser supports default html5 styles */ + var supportsHtml5Styles; + + /** Name of the expando, to work with multiple documents or to re-shiv one document */ + var expando = '_html5shiv'; + + /** The id for the the documents expando */ + var expanID = 0; + + /** Cached data for each document */ + var expandoData = {}; + + /** Detect whether the browser supports unknown elements */ + var supportsUnknownElements; + + (function() { + try { + var a = document.createElement('a'); + a.innerHTML = ''; + //if the hidden property is implemented we can assume, that the browser supports basic HTML5 Styles + supportsHtml5Styles = ('hidden' in a); + + supportsUnknownElements = a.childNodes.length == 1 || (function() { + // assign a false positive if unable to shiv + (document.createElement)('a'); + var frag = document.createDocumentFragment(); + return ( + typeof frag.cloneNode == 'undefined' || + typeof frag.createDocumentFragment == 'undefined' || + typeof frag.createElement == 'undefined' + ); + }()); + } catch(e) { + supportsHtml5Styles = true; + supportsUnknownElements = true; + } + + }()); + + /*--------------------------------------------------------------------------*/ + + /** + * Creates a style sheet with the given CSS text and adds it to the document. + * @private + * @param {Document} ownerDocument The document. + * @param {String} cssText The CSS text. + * @returns {StyleSheet} The style element. + */ + function addStyleSheet(ownerDocument, cssText) { + var p = ownerDocument.createElement('p'), + parent = ownerDocument.getElementsByTagName('head')[0] || ownerDocument.documentElement; + + p.innerHTML = 'x'; + return parent.insertBefore(p.lastChild, parent.firstChild); + } + + /** + * Returns the value of `html5.elements` as an array. + * @private + * @returns {Array} An array of shived element node names. + */ + function getElements() { + var elements = html5.elements; + return typeof elements == 'string' ? elements.split(' ') : elements; + } + + /** + * Returns the data associated to the given document + * @private + * @param {Document} ownerDocument The document. + * @returns {Object} An object of data. + */ + function getExpandoData(ownerDocument) { + var data = expandoData[ownerDocument[expando]]; + if (!data) { + data = {}; + expanID++; + ownerDocument[expando] = expanID; + expandoData[expanID] = data; + } + return data; + } + + /** + * returns a shived element for the given nodeName and document + * @memberOf html5 + * @param {String} nodeName name of the element + * @param {Document} ownerDocument The context document. + * @returns {Object} The shived element. + */ + function createElement(nodeName, ownerDocument, data){ + if (!ownerDocument) { + ownerDocument = document; + } + if(supportsUnknownElements){ + return ownerDocument.createElement(nodeName); + } + if (!data) { + data = getExpandoData(ownerDocument); + } + var node; + + if (data.cache[nodeName]) { + node = data.cache[nodeName].cloneNode(); + } else if (saveClones.test(nodeName)) { + node = (data.cache[nodeName] = data.createElem(nodeName)).cloneNode(); + } else { + node = data.createElem(nodeName); + } + + // Avoid adding some elements to fragments in IE < 9 because + // * Attributes like `name` or `type` cannot be set/changed once an element + // is inserted into a document/fragment + // * Link elements with `src` attributes that are inaccessible, as with + // a 403 response, will cause the tab/window to crash + // * Script elements appended to fragments will execute when their `src` + // or `text` property is set + return node.canHaveChildren && !reSkip.test(nodeName) ? data.frag.appendChild(node) : node; + } + + /** + * returns a shived DocumentFragment for the given document + * @memberOf html5 + * @param {Document} ownerDocument The context document. + * @returns {Object} The shived DocumentFragment. + */ + function createDocumentFragment(ownerDocument, data){ + if (!ownerDocument) { + ownerDocument = document; + } + if(supportsUnknownElements){ + return ownerDocument.createDocumentFragment(); + } + data = data || getExpandoData(ownerDocument); + var clone = data.frag.cloneNode(), + i = 0, + elems = getElements(), + l = elems.length; + for(;i>shiv*/ + + // Assign private properties to the return object with prefix + Modernizr._version = version; + + // expose these for the plugin API. Look in the source for how to join() them against your input + /*>>prefixes*/ + Modernizr._prefixes = prefixes; + /*>>prefixes*/ + /*>>domprefixes*/ + Modernizr._domPrefixes = domPrefixes; + Modernizr._cssomPrefixes = cssomPrefixes; + /*>>domprefixes*/ + + /*>>mq*/ + // Modernizr.mq tests a given media query, live against the current state of the window + // A few important notes: + // * If a browser does not support media queries at all (eg. oldIE) the mq() will always return false + // * A max-width or orientation query will be evaluated against the current state, which may change later. + // * You must specify values. Eg. If you are testing support for the min-width media query use: + // Modernizr.mq('(min-width:0)') + // usage: + // Modernizr.mq('only screen and (max-width:768)') + Modernizr.mq = testMediaQuery; + /*>>mq*/ + + /*>>hasevent*/ + // Modernizr.hasEvent() detects support for a given event, with an optional element to test on + // Modernizr.hasEvent('gesturestart', elem) + Modernizr.hasEvent = isEventSupported; + /*>>hasevent*/ + + /*>>testprop*/ + // Modernizr.testProp() investigates whether a given style property is recognized + // Note that the property names must be provided in the camelCase variant. + // Modernizr.testProp('pointerEvents') + Modernizr.testProp = function(prop){ + return testProps([prop]); + }; + /*>>testprop*/ + + /*>>testallprops*/ + // Modernizr.testAllProps() investigates whether a given style property, + // or any of its vendor-prefixed variants, is recognized + // Note that the property names must be provided in the camelCase variant. + // Modernizr.testAllProps('boxSizing') + Modernizr.testAllProps = testPropsAll; + /*>>testallprops*/ + + + /*>>teststyles*/ + // Modernizr.testStyles() allows you to add custom styles to the document and test an element afterwards + // Modernizr.testStyles('#modernizr { position:absolute }', function(elem, rule){ ... }) + Modernizr.testStyles = injectElementWithStyles; + /*>>teststyles*/ + + + /*>>prefixed*/ + // Modernizr.prefixed() returns the prefixed or nonprefixed property name variant of your input + // Modernizr.prefixed('boxSizing') // 'MozBoxSizing' + + // Properties must be passed as dom-style camelcase, rather than `box-sizing` hypentated style. + // Return values will also be the camelCase variant, if you need to translate that to hypenated style use: + // + // str.replace(/([A-Z])/g, function(str,m1){ return '-' + m1.toLowerCase(); }).replace(/^ms-/,'-ms-'); + + // If you're trying to ascertain which transition end event to bind to, you might do something like... + // + // var transEndEventNames = { + // 'WebkitTransition' : 'webkitTransitionEnd', + // 'MozTransition' : 'transitionend', + // 'OTransition' : 'oTransitionEnd', + // 'msTransition' : 'MSTransitionEnd', + // 'transition' : 'transitionend' + // }, + // transEndEventName = transEndEventNames[ Modernizr.prefixed('transition') ]; + + Modernizr.prefixed = function(prop, obj, elem){ + if(!obj) { + return testPropsAll(prop, 'pfx'); + } else { + // Testing DOM property e.g. Modernizr.prefixed('requestAnimationFrame', window) // 'mozRequestAnimationFrame' + return testPropsAll(prop, obj, elem); + } + }; + /*>>prefixed*/ + + + /*>>cssclasses*/ + // Remove "no-js" class from element, if it exists: + docElement.className = docElement.className.replace(/(^|\s)no-js(\s|$)/, '$1$2') + + + // Add the new classes to the element. + (enableClasses ? ' js ' + classes.join(' ') : ''); + /*>>cssclasses*/ + + return Modernizr; + +})(this, this.document); diff --git a/js/settings.js b/js/settings.js index 3dc18b6c..eea0d7eb 100644 --- a/js/settings.js +++ b/js/settings.js @@ -19,7 +19,7 @@ OC.Contacts.Settings = OC.Contacts.Settings || { if(!active) { $('#contacts h3[data-id="'+id+'"],#contacts ul[data-id="'+id+'"]').remove(); } else { - OC.Contacts.Contacts.update(); + OC.Contacts.update(); } } else { console.log('Error:', jsondata.data.message); @@ -41,7 +41,7 @@ OC.Contacts.Settings = OC.Contacts.Settings || { $('#contacts h3[data-id="'+id+'"],#contacts ul[data-id="'+id+'"]').remove(); row.remove() OC.Contacts.Settings.Addressbook.showActions(['new',]); - OC.Contacts.Contacts.update(); + OC.Contacts.update(); } else { OC.dialogs.alert(jsondata.data.message, t('contacts', 'Error')); } @@ -108,7 +108,7 @@ OC.Contacts.Settings = OC.Contacts.Settings || { row.find('td.name').text(jsondata.data.addressbook.displayname); row.find('td.description').text(jsondata.data.addressbook.description); } - OC.Contacts.Contacts.update(); + OC.Contacts.update(); } else { OC.dialogs.alert(jsondata.data.message, t('contacts', 'Error')); } diff --git a/lib/app.php b/lib/app.php index 4ddf6062..f8fcb9a5 100644 --- a/lib/app.php +++ b/lib/app.php @@ -237,8 +237,8 @@ class OC_Contacts_App { * @brief returns the categories for the user * @return (Array) $categories */ - public static function getCategories() { - $categories = self::getVCategories()->categories(); + public static function getCategories($format = null) { + $categories = self::getVCategories()->categories($format); return ($categories ? $categories : self::getDefaultCategories()); } @@ -280,7 +280,7 @@ class OC_Contacts_App { } $start = 0; $batchsize = 10; - $categories = new OC_VCategories('contacts'); + $categories = new OC_VCategories('contact'); while($vccontacts = OC_Contacts_VCard::all($vcaddressbookids, $start, $batchsize)) { $cards = array(); diff --git a/lib/vcard.php b/lib/vcard.php index e892c2b6..f851b2ae 100644 --- a/lib/vcard.php +++ b/lib/vcard.php @@ -645,6 +645,9 @@ class OC_Contacts_VCard { if($temp['label'] == '_$!!$_') { $temp['label'] = OC_Contacts_App::$l10n->t('Other'); } + if($temp['label'] == '_$!!$_') { + $temp['label'] = OC_Contacts_App::$l10n->t('HomePage'); + } } if(array_key_exists($pname, $details)) { $details[$pname][] = $temp; @@ -673,9 +676,12 @@ class OC_Contacts_VCard { public static function structureProperty($property) { $value = $property->value; //$value = htmlspecialchars($value); - if($property->name == 'ADR' || $property->name == 'N') { + if($property->name == 'ADR' || $property->name == 'N' || $property->name == 'ORG') { $value = self::unescapeDelimiters($value); - } elseif($property->name == 'BDAY') { + } elseif($property->name == 'CATEGORIES') { + $value = self::unescapeDelimiters($value, ','); + } + elseif($property->name == 'BDAY') { if(strpos($value, '-') === false) { if(strlen($value) >= 8) { $value = substr($value, 0, 4).'-'.substr($value, 4, 2).'-'.substr($value, 6, 2); @@ -684,6 +690,19 @@ class OC_Contacts_VCard { } } } + elseif($property->name == 'IMPP') { + if(strpos($value, ':') !== false) { + $value = explode(':', $value); + $protocol = array_shift($value); + if(!isset($property->parameters['X-SERVICE-TYPE'])) { + $property->add(new Sabre_VObject_Parameter( + 'X-SERVICE-TYPE', + strtoupper(strip_tags($protocol))) + ); + } + $value = implode('', $value); + } + } if(is_string($value)) { $value = strtr($value, array('\,' => ',', '\;' => ';')); } @@ -702,12 +721,18 @@ class OC_Contacts_VCard { } // NOTE: Apparently Sabre_VObject_Reader can't always deal with value list parameters // like TYPE=HOME,CELL,VOICE. Tanghus. - if (in_array($property->name, array('TEL', 'EMAIL')) && $parameter->name == 'TYPE') { + // TODO: Check if parameter is has commas and split + merge if so. + if ($parameter->name == 'TYPE') { + $pvalue = $parameter->value; + if(is_string($pvalue) && strpos($pvalue, ',') !== false) { + $pvalue = array_map('trim', explode(',', $pvalue)); + } + $pvalue = is_array($pvalue) ? $pvalue : array($pvalue); if (isset($temp['parameters'][$parameter->name])) { - $temp['parameters'][$parameter->name][] = $parameter->value; + $temp['parameters'][$parameter->name][] = $pvalue; } else { - $temp['parameters'][$parameter->name] = array($parameter->value); + $temp['parameters'][$parameter->name] = $pvalue; } } else{ diff --git a/templates/contacts.php b/templates/contacts.php new file mode 100644 index 00000000..82e603ed --- /dev/null +++ b/templates/contacts.php @@ -0,0 +1,203 @@ +
    + + +
    + + +
    +
    + + + +
    + + +
    + +
    +
    +
    +
    + + +
    + + +
    +
    + + + +
    +
    + + + + + + + diff --git a/thumbnail.php b/thumbnail.php index 1e3714ae..8a1b986b 100644 --- a/thumbnail.php +++ b/thumbnail.php @@ -53,7 +53,7 @@ if(is_null($contact)) { OCP\Response::enableCaching($caching); OC_Contacts_App::setLastModifiedHeader($contact); -$thumbnail_size = 23; +$thumbnail_size = 28; // Find the photo from VCard. $image = new OC_Image(); From 79b8a27ba0511c5e1934621adbf8a146fff632ed Mon Sep 17 00:00:00 2001 From: raghu Date: Tue, 25 Sep 2012 16:39:32 +0530 Subject: [PATCH 006/279] A Polyfill for Placeholders added to the contacts_rework branch --- index.php | 1 + js/placeholder.polyfill.jquery.js | 212 ++++++++++++++++++++++++++++++ 2 files changed, 213 insertions(+) create mode 100644 js/placeholder.polyfill.jquery.js diff --git a/index.php b/index.php index 2a3be9da..490d6de9 100644 --- a/index.php +++ b/index.php @@ -51,6 +51,7 @@ OCP\Util::addscript('', 'jquery.multiselect'); OCP\Util::addscript('', 'oc-vcategories'); OCP\Util::addscript('contacts', 'app'); OCP\Util::addscript('contacts', 'modernizr'); +OCP\Util::addscript('contacts', 'placeholder.polyfill.jquery'); OCP\Util::addscript('contacts', 'expanding'); OCP\Util::addscript('contacts', 'jquery.combobox'); OCP\Util::addscript('files', 'jquery.fileupload'); diff --git a/js/placeholder.polyfill.jquery.js b/js/placeholder.polyfill.jquery.js new file mode 100644 index 00000000..16969eb8 --- /dev/null +++ b/js/placeholder.polyfill.jquery.js @@ -0,0 +1,212 @@ +/** +* HTML5 placeholder polyfill +* @requires jQuery - tested with 1.6.2 but might as well work with older versions +* +* code: https://github.com/ginader/HTML5-placeholder-polyfill +* please report issues at: https://github.com/ginader/HTML5-placeholder-polyfill/issues +* +* Copyright (c) 2012 Dirk Ginader (ginader.de) +* Dual licensed under the MIT and GPL licenses: +* http://www.opensource.org/licenses/mit-license.php +* http://www.gnu.org/licenses/gpl.html +* +* Version: 2.0.3 +* +* History: +* * 1.0 initial release +* * 1.1 added support for multiline placeholders in textareas +* * 1.2 Allow label to wrap the input element by noah https://github.com/ginader/HTML5-placeholder-polyfill/pull/1 +* * 1.3 New option to read placeholder to Screenreaders. Turned on by default +* * 1.4 made placeholder more rubust to allow labels being offscreen + added minified version of the 3rd party libs +* * 1.5 emptying the native placeholder to prevent double rendering in Browsers with partial support +* * 1.6 optional reformat when a textarea is being resized - requires http://benalman.com/projects/jquery-resize-plugin/ +* * 1.7 feature detection is now included in the polyfill so you can simply include it without the need for Modernizr +* * 1.8 replacing the HTML5 Boilerplate .visuallyhidden technique with one that still allows the placeholder to be rendered +* * 1.8.1 bugfix for implicit labels +* * 1.9 New option "hideOnFocus" which, if set to false will mimic the behavior of mobile safari and chrome (remove label when typed instead of onfocus) +* * 1.9.1 added reformat event on window resize +* * 1.9.2 more flexible way to "fix" labels that are hidden using clip() thanks to grahambates: https://github.com/ginader/HTML5-placeholder-polyfill/issues/12 +* * 2.0 new easier configuration technique and new options forceApply and AutoInit and support for setters and getters +* * 2.0.1 changed check for empty field so a space character is no longer ignored +* * 2.0.2 allow rerun of the placeholder() to cover generated elements - existing polyfilled placeholder will be repositioned. Fixing: https://github.com/ginader/HTML5-placeholder-polyfill/issues/15 +* * 2.0.3 turn debugging of for production. fix https://github.com/ginader/HTML5-placeholder-polyfill/issues/18 +*/ + +(function($) { + var debug = false, + animId; + function showPlaceholderIfEmpty(input,options) { + if( input.val() === '' ){ + input.data('placeholder').removeClass(options.hideClass); + }else{ + input.data('placeholder').addClass(options.hideClass); + } + } + function hidePlaceholder(input,options){ + input.data('placeholder').addClass(options.hideClass); + } + function positionPlaceholder(placeholder,input){ + var ta = input.is('textarea'); + placeholder.css({ + width : input.innerWidth()-(ta ? 20 : 4), + height : input.innerHeight()-6, + lineHeight : input.css('line-height'), + whiteSpace : ta ? 'normal' : 'nowrap', + overflow : 'hidden' + }).offset(input.offset()); + } + function startFilledCheckChange(input,options){ + var input = input, + val = input.val(); + (function checkloop(){ + animId = requestAnimationFrame(checkloop); + if(input.val() != val){ + hidePlaceholder(input,options); + stopCheckChange(); + startEmptiedCheckChange(input,options); + } + })(); + } + function startEmptiedCheckChange(input,options){ + var input = input, + val = input.val(); + (function checkloop(){ + animId = requestAnimationFrame(checkloop); + showPlaceholderIfEmpty(input,options); + })(); + } + function stopCheckChange(){ + cancelAnimationFrame(animId); + } + function log(msg){ + if(debug && window.console && window.console.log){ + window.console.log(msg); + } + } + + $.fn.placeHolder = function(config) { + log('init placeHolder'); + var o = this; + var l = $(this).length; + this.options = $.extend({ + className: 'placeholder', // css class that is used to style the placeholder + visibleToScreenreaders : true, // expose the placeholder text to screenreaders or not + visibleToScreenreadersHideClass : 'placeholder-hide-except-screenreader', // css class is used to visually hide the placeholder + visibleToNoneHideClass : 'placeholder-hide', // css class used to hide the placeholder for all + hideOnFocus : false, // either hide the placeholder on focus or on type + removeLabelClass : 'visuallyhidden', // remove this class from a label (to fix hidden labels) + hiddenOverrideClass : 'visuallyhidden-with-placeholder', // replace the label above with this class + forceHiddenOverride : true, // allow the replace of the removeLabelClass with hiddenOverrideClass or not + forceApply : false, // apply the polyfill even for browser with native support + autoInit : true // init automatically or not + }, config); + this.options.hideClass = this.options.visibleToScreenreaders ? this.options.visibleToScreenreadersHideClass : this.options.visibleToNoneHideClass; + return $(this).each(function(index) { + var input = $(this), + text = input.attr('placeholder'), + id = input.attr('id'), + label,placeholder,titleNeeded,polyfilled; + label = input.closest('label'); + input.removeAttr('placeholder'); + if(!label.length && !id){ + log('the input element with the placeholder needs an id!'); + return; + } + label = label.length ? label : $('label[for="'+id+'"]').first(); + if(!label.length){ + log('the input element with the placeholder needs a label!'); + return; + } + polyfilled = $(label).find('.placeholder'); + if(polyfilled.length) { + //log('the input element already has a polyfilled placeholder!'); + positionPlaceholder(polyfilled,input); + return input; + } + + if(label.hasClass(o.options.removeLabelClass)){ + label.removeClass(o.options.removeLabelClass) + .addClass(o.options.hiddenOverrideClass); + } + + placeholder = $(''+text+'').appendTo(label); + + titleNeeded = (placeholder.width() > input.width()); + if(titleNeeded){ + placeholder.attr('title',text); + } + positionPlaceholder(placeholder,input); + input.data('placeholder',placeholder); + placeholder.data('input',placeholder); + placeholder.click(function(){ + $(this).data('input').focus(); + }); + input.focusin(function() { + if(!o.options.hideOnFocus && window.requestAnimationFrame){ + startFilledCheckChange(input,o.options); + }else{ + hidePlaceholder(input,o.options); + } + }); + input.focusout(function(){ + showPlaceholderIfEmpty($(this),o.options); + if(!o.options.hideOnFocus && window.cancelAnimationFrame){ + stopCheckChange(); + } + }); + showPlaceholderIfEmpty(input,o.options); + + // reformat on window resize and optional reformat on font resize - requires: http://www.tomdeater.com/jquery/onfontresize/ + $(document).bind("fontresize resize", function(){ + positionPlaceholder(placeholder,input); + }); + + // optional reformat when a textarea is being resized - requires http://benalman.com/projects/jquery-resize-plugin/ + if($.event.special.resize){ + $("textarea").bind("resize", function(e){ + positionPlaceholder(placeholder,input); + }); + }else{ + // we simply disable the resizeablilty of textareas when we can't react on them resizing + $("textarea").css('resize','none'); + } + + if(index >= l-1){ + $.attrHooks.placeholder = { + get: function(elem) { + if (elem.nodeName.toLowerCase() == 'input' || elem.nodeName.toLowerCase() == 'textarea') { + if( $(elem).data('placeholder') ){ + // has been polyfilled + return $( $(elem).data('placeholder') ).text(); + }else{ + // native / not yet polyfilled + return $(elem)[0].placeholder; + } + + }else{ + return undefined; + } + }, + set: function(elem, value){ + return $( $(elem).data('placeholder') ).text(value); + } + }; + } + }); + + + + }; + $(function(){ + var config = window.placeHolderConfig || {}; + if(config.autoInit === false){ + log('placeholder:abort because autoInit is off'); + return + } + if('placeholder' in $('')[0] && !config.forceApply){ // don't run the polyfill when the browser has native support + log('placeholder:abort because browser has native support'); + return; + } + $('input[placeholder], textarea[placeholder]').placeHolder(config); + }); +})(jQuery); \ No newline at end of file From 2bcb9647f8246e2dda35addb321ab1952db931a7 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Sun, 30 Sep 2012 06:35:43 +0200 Subject: [PATCH 007/279] Return contact structure after adding --- ajax/contact/add.php | 1 + 1 file changed, 1 insertion(+) diff --git a/ajax/contact/add.php b/ajax/contact/add.php index efb8cf93..b913f485 100644 --- a/ajax/contact/add.php +++ b/ajax/contact/add.php @@ -60,6 +60,7 @@ OCP\JSON::success(array( 'data' => array( 'id' => $id, 'aid' => $aid, + 'details' => OC_Contacts_VCard::structureContact($vcard), 'lastmodified' => $lastmodified->format('U') ) )); From ee544134195c8e9505547839b026fc814b1f228b Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Sun, 30 Sep 2012 06:37:16 +0200 Subject: [PATCH 008/279] Some work on the header styling --- css/contacts.css | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/css/contacts.css b/css/contacts.css index 3b34651e..e1588758 100644 --- a/css/contacts.css +++ b/css/contacts.css @@ -10,6 +10,7 @@ input[type=checkbox]:checked::after { top: -8px; left: -6px; } +textarea { font-family: inherit; } select { border: 1px solid silver; } option { border-left: 1px solid silver; border-right: 1px solid silver; } option:first-child { border-top: 1px solid silver; } @@ -160,13 +161,15 @@ input.propertytype { float: left; font-size: .8em; width: 8em !important; direct #contactsheader { position: fixed; padding: 0; margin:0; top:3.5em; left: 32.5em; right: 0; height: 4em; border-bottom: 1px solid #DDDDDD; z-index: 50; } #contactsheader div { padding: 0 0.5em; height: 100%; width: 90%; margin:0; } -#contactsheader button { width: 26px; height: 26px; margin-right: .5em; top: .7em; opacity: 0.5; } +#contactsheader button { position: relative; float: left; min-width: 26px; height: 26px; margin: .7em; padding: .2em; opacity: 0.5; clear: none; } #contactsheader button:hover { opacity: 1; } -#contactsheader .settings { background:url('%webroot%/core/img/actions/settings.svg') no-repeat center; position: absolute; right: 1em; margin: 0; } +#contactsheader .back { } #contactsheader .import { background:url('%webroot%/core/img/actions/upload.svg') no-repeat center; } #contactsheader .newcontact { background:url('%appswebroot%/contacts/img/contact-new.svg') no-repeat center; } #contactsheader .delete { background:url('%webroot%/core/img/actions/delete.svg') no-repeat center; } -#contactsheader .add { background:url('%webroot%/core/img/actions/add.svg') no-repeat center; margin-left: 5em; } +#contactsheader .add { background:url('%webroot%/core/img/actions/add.svg') no-repeat center; } +#contactsheader .list.add { margin-left: 5em; } +#contactsheader .settings { background:url('%webroot%/core/img/actions/settings.svg') no-repeat center; position: absolute; top: .7em; right: 1em; margin: 0; } #contactlist tr { height: 3em; } #contactlist tr td { text-overflow: ellipsis; border-bottom: 1px solid #DDDDDD; font-weight: normal; text-align: left; overflow: hidden; text-overflow: ellipsis; vertical-align: middle; white-space: nowrap; } From 68e409cac7b71e5fa0f19ba4a005d7e2864a60ff Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Sun, 30 Sep 2012 06:38:53 +0200 Subject: [PATCH 009/279] Insert a rendered contact in the list. --- js/app.js | 62 ++++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 52 insertions(+), 10 deletions(-) diff --git a/js/app.js b/js/app.js index 04a2ba1c..5dae3584 100644 --- a/js/app.js +++ b/js/app.js @@ -152,8 +152,8 @@ OC.Contacts = OC.Contacts || { self.$header.find('.delete').hide(); } }); - $(document).bind('status.contactsLoaded', function(e, result) { - console.log('contactsLoaded', result); + $(document).bind('status.contacts.loaded', function(e, result) { + console.log('status.contacts.loaded', result); if(result.status !== true) { alert('Error loading contacts!'); } @@ -213,6 +213,16 @@ OC.Contacts = OC.Contacts || { self.$header.find('.single').show(); self.$rightContent.prepend(self.Contacts.showContact(self.currentid)); }); + this.$header.find('.back').on('click keydown', function() { + console.log('back'); + var listelem = self.Contacts.contacts[parseInt(self.currentid)].detach().remove(); + self.$contactList.show(); + }); + this.$header.find('.add').on('click keydown', function() { + console.log('add'); + self.$contactList.hide(); + self.$rightContent.prepend(self.Contacts.addContact()); + }); this.$header.find('.delete').on('click keydown', function() { console.log('delete'); if(self.currentid) { @@ -706,8 +716,9 @@ OC.Contacts = OC.Contacts || { self.deleteContact(listelem.data('id'), true); }, clickhandler:function(listelem) { - self.insertContact({contact:listelem}); - OC.Contacts.notify({message:t('contacts', 'Cancelled deletion of: "') + listelem.find('a').text() + '"'}); + console.log('clickhandler', listelem); + self.insertContact(listelem); + OC.Contacts.notify({message:t('contacts', 'Cancelled deletion of: "') + listelem.find('td.name').text() + '"'}); window.onbeforeunload = null; } }); @@ -776,13 +787,43 @@ OC.Contacts = OC.Contacts || { }; /** - * Insert a contact in the list - * @param jQuery object - */ + * Insert a rendered contact list item into the list + * @param contact jQuery object. + */ ContactList.prototype.insertContact = function(contact) { - console.log('insertContact', contact); + //console.log('insertContact', contact); + var name = contact.find('td.name').text().toLowerCase(); + var added = false + this.$contactList.find('tr').each(function() { + if ($(this).find('td.name').text().toLowerCase().localeCompare(name) > 0) { + $(this).before(contact); + added = true; + return false; + } + }); + if(!added) { + this.$contactList.append(contact); + } + //this.contacts[id] = contact; + return contact; } + /** + * Add contact + * @param int offset + */ + ContactList.prototype.addContact = function() { + var contact = new Contact( + this, + null, + null, + null, + this.$contactListItemTemplate, + this.$contactFullTemplate, + this.contactDetailTemplates + ); + return contact.renderContact(); + } /** * Load contacts * @param int offset @@ -809,9 +850,10 @@ OC.Contacts = OC.Contacts || { self.contactDetailTemplates ); var item = self.contacts[parseInt(contact.id)].renderListItem() - self.$contactList.append(item); + //self.$contactList.append(item); + self.insertContact(item); }); - $(document).trigger('status.contactsLoaded', { + $(document).trigger('status.contacts.loaded', { status: true, numcontacts: jsondata.data.contacts.length }); From ce2535521b67d7145ae098181b56fc495630fad6 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Sun, 30 Sep 2012 06:40:04 +0200 Subject: [PATCH 010/279] Add 'Other' as standard email type. --- lib/app.php | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/app.php b/lib/app.php index f8fcb9a5..fb9c13eb 100644 --- a/lib/app.php +++ b/lib/app.php @@ -213,6 +213,7 @@ class OC_Contacts_App { 'WORK' => $l->t('Work'), 'HOME' => $l->t('Home'), 'INTERNET' => $l->t('Internet'), + 'OTHER' => $l->t('Other'), ); } } From 096a45b393818a63843efb5d638db61e3c9bdcc8 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Sun, 30 Sep 2012 06:40:57 +0200 Subject: [PATCH 011/279] Also show standard image if id is not set, for example when rendering not saved contact. --- photo.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/photo.php b/photo.php index 9d4dcb3b..75193c57 100644 --- a/photo.php +++ b/photo.php @@ -23,7 +23,7 @@ $id = isset($_GET['id']) ? $_GET['id'] : null; $etag = null; $caching = null; -if(is_null($id)) { +if(!$id) { getStandardImage(); } From 2a3a3241e3a800c72cd4aee7ff43cfaa2bc45895 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Sun, 30 Sep 2012 06:42:16 +0200 Subject: [PATCH 012/279] Added button to go back to list. --- templates/contacts.php | 1 + 1 file changed, 1 insertion(+) diff --git a/templates/contacts.php b/templates/contacts.php index 82e603ed..91a4d6b2 100644 --- a/templates/contacts.php +++ b/templates/contacts.php @@ -28,6 +28,7 @@ From 6785e2f2c1623c2f95af263e414b6b30cb8733a6 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Wed, 3 Oct 2012 22:03:29 +0200 Subject: [PATCH 013/279] Don't scan for categories/groups in shared addressbooks/calendars. --- lib/app.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/app.php b/lib/app.php index ba333948..ea090114 100644 --- a/lib/app.php +++ b/lib/app.php @@ -276,7 +276,9 @@ class OC_Contacts_App { if(count($vcaddressbooks) > 0) { $vcaddressbookids = array(); foreach($vcaddressbooks as $vcaddressbook) { - $vcaddressbookids[] = $vcaddressbook['id']; + if($vcaddressbook['userid'] === OCP\User::getUser()) { + $vcaddressbookids[] = $vcaddressbook['id']; + } } $start = 0; $batchsize = 10; From 6fbd4ddec83e8c7c59333b039a3a7da962a9be1e Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Wed, 3 Oct 2012 22:10:48 +0200 Subject: [PATCH 014/279] Make default groups/categories more relevant for contacts. --- lib/app.php | 17 +++-------------- 1 file changed, 3 insertions(+), 14 deletions(-) diff --git a/lib/app.php b/lib/app.php index ea090114..ce490815 100644 --- a/lib/app.php +++ b/lib/app.php @@ -248,21 +248,10 @@ class OC_Contacts_App { */ public static function getDefaultCategories() { return array( - (string)self::$l10n->t('Birthday'), - (string)self::$l10n->t('Business'), - (string)self::$l10n->t('Call'), - (string)self::$l10n->t('Clients'), - (string)self::$l10n->t('Deliverer'), - (string)self::$l10n->t('Holidays'), - (string)self::$l10n->t('Ideas'), - (string)self::$l10n->t('Journey'), - (string)self::$l10n->t('Jubilee'), - (string)self::$l10n->t('Meeting'), - (string)self::$l10n->t('Other'), - (string)self::$l10n->t('Personal'), - (string)self::$l10n->t('Projects'), - (string)self::$l10n->t('Questions'), + (string)self::$l10n->t('Friends'), + (string)self::$l10n->t('Family'), (string)self::$l10n->t('Work'), + (string)self::$l10n->t('Other'), ); } From d7354034aec18b705c9f84af5ae7b1913c178ca3 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Fri, 5 Oct 2012 05:05:49 +0200 Subject: [PATCH 015/279] Major rewrite almost done. --- ajax/addressbook/activate.php | 15 +- ajax/addressbook/add.php | 2 +- ajax/addressbook/update.php | 2 +- ajax/categories/addto.php | 34 + ajax/categories/removefrom.php | 34 + ajax/contact/list.php | 2 +- ajax/contact/move.php | 14 +- ajax/contact/saveproperty.php | 102 +- css/contacts.css | 208 ++- export.php | 26 +- import.php | 14 +- index.php | 1 + js/app.js | 1279 ++++++------- js/contacts.js | 3188 +++++++++----------------------- js/settings.js | 13 +- lib/app.php | 66 +- lib/hooks.php | 2 +- lib/vcard.php | 12 +- templates/contacts.php | 134 +- templates/settings.php | 8 +- 20 files changed, 1874 insertions(+), 3282 deletions(-) create mode 100644 ajax/categories/addto.php create mode 100644 ajax/categories/removefrom.php diff --git a/ajax/addressbook/activate.php b/ajax/addressbook/activate.php index a8dec21d..6ad522a3 100644 --- a/ajax/addressbook/activate.php +++ b/ajax/addressbook/activate.php @@ -13,7 +13,20 @@ OCP\JSON::checkAppEnabled('contacts'); OCP\JSON::callCheck(); $id = $_POST['id']; -$book = OC_Contacts_App::getAddressbook($id);// is owner access check + +try { + $book = OC_Contacts_Addressbook::find($id); // is owner access check +} catch(Exception $e) { + OCP\JSON::error( + array( + 'data' => array( + 'message' => $e->getMessage(), + 'file'=>$_POST['file'] + ) + ) + ); + exit(); +} if(!OC_Contacts_Addressbook::setActive($id, $_POST['active'])) { OCP\Util::writeLog('contacts', diff --git a/ajax/addressbook/add.php b/ajax/addressbook/add.php index 65077743..7f92c337 100644 --- a/ajax/addressbook/add.php +++ b/ajax/addressbook/add.php @@ -33,5 +33,5 @@ if(!$bookid) { if(!OC_Contacts_Addressbook::setActive($bookid, 1)) { bailOut('Error activating addressbook.'); } -$addressbook = OC_Contacts_App::getAddressbook($bookid); +$addressbook = OC_Contacts_Addressbook::find($bookid); OCP\JSON::success(array('data' => array('addressbook' => $addressbook))); diff --git a/ajax/addressbook/update.php b/ajax/addressbook/update.php index ce9ffa28..82a7a6c2 100644 --- a/ajax/addressbook/update.php +++ b/ajax/addressbook/update.php @@ -33,7 +33,7 @@ if(!OC_Contacts_Addressbook::setActive($id, $_POST['active'])) { bailOut(OC_Contacts_App::$l10n->t('Error (de)activating addressbook.')); } -$addressbook = OC_Contacts_App::getAddressbook($id); +$addressbook = OC_Contacts_Addressbook::find($id); OCP\JSON::success(array( 'data' => array('addressbook' => $addressbook), )); diff --git a/ajax/categories/addto.php b/ajax/categories/addto.php new file mode 100644 index 00000000..b87d1a90 --- /dev/null +++ b/ajax/categories/addto.php @@ -0,0 +1,34 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + + +OCP\JSON::checkLoggedIn(); +OCP\JSON::checkAppEnabled('contacts'); +OCP\JSON::callCheck(); + +require_once __DIR__.'/../loghandler.php'; + +$categoryid = isset($_POST['categoryid']) ? $_POST['categoryid'] : null; +$contactid = isset($_POST['contactid']) ? $_POST['contactid'] : null; + +if(is_null($categoryid)) { + bailOut(OC_Contacts_App::$l10n->t('Group ID missing from request.')); +} + +if(is_null($contactid)) { + bailOut(OC_Contacts_App::$l10n->t('Contact ID missing from request.')); +} + +debug('id: ' . $contactid .', categoryid: ' . $categoryid); + +$catmgr = OC_Contacts_App::getVCategories(); +if(!$catmgr->createRelation($contactid, $categoryid)) { + bailOut(OC_Contacts_App::$l10n->t('Error removing contact from group.')); +} + +OCP\JSON::success(); diff --git a/ajax/categories/removefrom.php b/ajax/categories/removefrom.php new file mode 100644 index 00000000..f3f8cc26 --- /dev/null +++ b/ajax/categories/removefrom.php @@ -0,0 +1,34 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + + +OCP\JSON::checkLoggedIn(); +OCP\JSON::checkAppEnabled('contacts'); +OCP\JSON::callCheck(); + +require_once __DIR__.'/../loghandler.php'; + +$categoryid = isset($_POST['categoryid']) ? $_POST['categoryid'] : null; +$contactid = isset($_POST['contactid']) ? $_POST['contactid'] : null; + +if(is_null($categoryid)) { + bailOut(OC_Contacts_App::$l10n->t('Group ID missing from request.')); +} + +if(is_null($contactid)) { + bailOut(OC_Contacts_App::$l10n->t('Contact ID missing from request.')); +} + +debug('id: ' . $contactid .', categoryid: ' . $categoryid); + +$catmgr = OC_Contacts_App::getVCategories(); +if(!$catmgr->removeRelation($contactid, $categoryid)) { + bailOut(OC_Contacts_App::$l10n->t('Error removing contact from group.')); +} + +OCP\JSON::success(); diff --git a/ajax/contact/list.php b/ajax/contact/list.php index bdf9d69f..adc027e4 100644 --- a/ajax/contact/list.php +++ b/ajax/contact/list.php @@ -114,6 +114,6 @@ if($contacts_alphabet) { } } //unset($contacts_alphabet); -uasort($contacts_alphabet, 'cmp'); +//uasort($contacts, 'cmp'); OCP\JSON::success(array('data' => array('contacts' => $contacts, 'addressbooks' => $active_addressbooks))); diff --git a/ajax/contact/move.php b/ajax/contact/move.php index 053343c4..61a6b580 100644 --- a/ajax/contact/move.php +++ b/ajax/contact/move.php @@ -17,7 +17,19 @@ $aid = intval($_POST['aid']); $isaddressbook = isset($_POST['isaddressbook']) ? true: false; // Ownership checking -OC_Contacts_App::getAddressbook($aid); +try { + OC_Contacts_Addressbook::find($id); // is owner access check +} catch(Exception $e) { + OCP\JSON::error( + array( + 'data' => array( + 'message' => $e->getMessage(), + ) + ) + ); + exit(); +} + try { OC_Contacts_VCard::moveToAddressBook($aid, $id, $isaddressbook); } catch (Exception $e) { diff --git a/ajax/contact/saveproperty.php b/ajax/contact/saveproperty.php index 0afd476f..ef67cc5c 100644 --- a/ajax/contact/saveproperty.php +++ b/ajax/contact/saveproperty.php @@ -32,13 +32,15 @@ $value = isset($_POST['value'])?$_POST['value']:null; $parameters = isset($_POST['parameters'])?$_POST['parameters']:null; $checksum = isset($_POST['checksum'])?$_POST['checksum']:null; +$multi_properties = array('EMAIL', 'TEL', 'IMPP', 'ADR', 'URL'); + if(!$name) { bailOut(OC_Contacts_App::$l10n->t('element name is not set.')); } if(!$id) { bailOut(OC_Contacts_App::$l10n->t('id is not set.')); } -if(!$checksum) { +if(!$checksum && in_array($name, $multi_properties)) { bailOut(OC_Contacts_App::$l10n->t('checksum is not set.')); } if(is_array($value)) { @@ -55,19 +57,31 @@ if(is_array($value)) { $value = trim(strip_tags($value)); } -$vcard = OC_Contacts_App::getContactVCard( $id ); -$line = OC_Contacts_App::getPropertyLineByChecksum($vcard, $checksum); -if(is_null($line)) { - bailOut(OC_Contacts_App::$l10n->t( - 'Information about vCard is incorrect. Please reload the page: ').$checksum - ); -} -$element = $vcard->children[$line]->name; +$vcard = OC_Contacts_App::getContactVCard($id); +$property = null; -if($element != $name) { - bailOut(OC_Contacts_App::$l10n->t( - 'Something went FUBAR. ').$name.' != '.$element - ); +if(in_array($name, $multi_properties)) { + if($checksum !== 'new') { + $line = OC_Contacts_App::getPropertyLineByChecksum($vcard, $checksum); + if(is_null($line)) { + bailOut(OC_Contacts_App::$l10n->t( + 'Information about vCard is incorrect. Please reload the page: ').$checksum + ); + } + $property = $vcard->children[$line]; + $element = $property->name; + + if($element != $name) { + bailOut(OC_Contacts_App::$l10n->t( + 'Something went FUBAR. ').$name.' != '.$element + ); + } + } else { + $element = $name; + $property = $vcard->addProperty($name, $value); + } +} else { + $element = $name; } /* preprocessing value */ @@ -100,33 +114,35 @@ switch($element) { break; } +// If empty remove the property if(!$value) { - unset($vcard->children[$line]); - $checksum = ''; + if(in_array($name, $multi_properties)) { + unset($vcard->children[$line]); + $checksum = ''; + } else { + $vcard->setString($name, ''); + } } else { /* setting value */ switch($element) { case 'BDAY': - // I don't use setDateTime() because that formats it as YYYYMMDD instead - // of YYYY-MM-DD which is what the RFC recommends. - $vcard->children[$line]->setValue($value); - $vcard->children[$line]->parameters = array(); - $vcard->children[$line]->add( - new Sabre_VObject_Parameter('VALUE', 'DATE') - ); - debug('Setting value:'.$name.' '.$vcard->children[$line]); - break; - case 'CATEGORIES': - debug('Setting string:'.$name.' '.$value); - $vcard->children[$line]->setValue($value); + $vcard->BDAY = $value; + + if(!isset($vcard->BDAY['VALUE'])) { + $vcard->BDAY->add('VALUE', 'DATE'); + } else { + $vcard->BDAY->VALUE = 'DATE'; + } break; case 'EMAIL': case 'TEL': case 'ADR': case 'IMPP': + case 'URL': debug('Setting element: (EMAIL/TEL/ADR)'.$element); - $vcard->children[$line]->setValue($value); - $vcard->children[$line]->parameters = array(); + $property->setValue($value); + // FIXME: Don't replace parameters, but update instead. + $property->parameters = array(); if(!is_null($parameters)) { debug('Setting parameters: '.$parameters); foreach($parameters as $key => $parameter) { @@ -135,7 +151,7 @@ if(!$value) { foreach($parameter as $val) { if(trim($val)) { debug('Adding parameter: '.$key.'=>'.$val); - $vcard->children[$line]->add(new Sabre_VObject_Parameter( + $property->add(new Sabre_VObject_Parameter( $key, strtoupper(strip_tags($val))) ); @@ -143,7 +159,7 @@ if(!$value) { } } else { if(trim($parameter)) { - $vcard->children[$line]->add(new Sabre_VObject_Parameter( + $property->add(new Sabre_VObject_Parameter( $key, strtoupper(strip_tags($parameter))) ); @@ -157,19 +173,27 @@ if(!$value) { break; } // Do checksum and be happy - $checksum = md5($vcard->children[$line]->serialize()); + if(in_array($name, $multi_properties)) { + $checksum = md5($property->serialize()); + } } //debug('New checksum: '.$checksum); - +//$vcard->children[$line] = $property; ??? try { OC_Contacts_VCard::edit($id, $vcard); } catch(Exception $e) { bailOut($e->getMessage()); } -OCP\JSON::success(array('data' => array( - 'line' => $line, - 'checksum' => $checksum, - 'oldchecksum' => $_POST['checksum'], - 'lastmodified' => OC_Contacts_App::lastModified($vcard)->format('U'), -))); +if(in_array($name, $multi_properties)) { + OCP\JSON::success(array('data' => array( + 'line' => $line, + 'checksum' => $checksum, + 'oldchecksum' => $_POST['checksum'], + 'lastmodified' => OC_Contacts_App::lastModified($vcard)->format('U'), + ))); +} else { + OCP\JSON::success(array('data' => array( + 'lastmodified' => OC_Contacts_App::lastModified($vcard)->format('U'), + ))); +} \ No newline at end of file diff --git a/css/contacts.css b/css/contacts.css index e1588758..ccb6e11f 100644 --- a/css/contacts.css +++ b/css/contacts.css @@ -1,6 +1,12 @@ /*dl > dt { font-weight: bold; }*/ + +/* General element settings */ +/*::-webkit-input-placeholder { color: #bbb; } +:-moz-placeholder { color: #bbb; } +:-ms-input-placeholder { color: #bbb; }*/ +li { cursor: default; } input[type=checkbox] { height: 14px; width: 14px; border: 1px solid #fff; -moz-appearance:none; -webkit-appearance: none; -moz-box-sizing:none; box-sizing:none; -moz-box-shadow: none; -webkit-box-shadow: none; box-shadow: none; -moz-border-radius: 2px; -webkit-border-radius: 2px; border-radius: 2px; } input[type=checkbox]:hover { border: 1px solid #D4D4D4 !important; } input[type=checkbox]:checked::after { @@ -15,49 +21,32 @@ select { border: 1px solid silver; } option { border-left: 1px solid silver; border-right: 1px solid silver; } option:first-child { border-top: 1px solid silver; } option:last-child { border-bottom: 1px solid silver; } + +/* Left content */ + #leftcontent { top: 3.5em !important; padding: 0; margin: 0; } #leftcontent a { padding: 0 0 0 25px; } #leftcontent h3 { cursor: pointer; -moz-transition: background 300ms ease 0s; background: none no-repeat scroll 1em center #eee; border-bottom: 1px solid #ddd; border-top: 1px solid #fff; display: block; max-width: 100%; padding: 0.5em 0.8em; color: #666; text-shadow: 0 1px 0 #f8f8f8; font-size: 1.2em; } #leftcontent h3:hover,#leftcontent h3:active,#leftcontent h3.active { background-color: #DBDBDB; border-bottom: 1px solid #CCCCCC; border-top: 1px solid #D4D4D4; color: #333333; font-weight: bold; } -#leftcontent h3 img.shared { float: right; opacity: 0.4; } -#leftcontent h3 img.shared:hover { opacity: 1; } -.contacts li.ui-draggable { height: 23px; } -.ui-draggable-dragging { width: 17em; cursor: move; } -.ui-state-hover { border: 1px solid dashed; } -#bottomcontrols { padding: 0; bottom:0px; height:2.8em; width: 20em; margin:0; background:#eee; border-top:1px solid #ccc; position:fixed; -moz-box-shadow: 0 -3px 3px -3px #000; -webkit-box-shadow: 0 -3px 3px -3px #000; box-shadow: 0 -3px 3px -3px #000;} -#bottomcontrols img { margin-top: 0.35em; } -#uploadprogressbar { display: none; padding: 0; bottom: 3em; height:2em; width: 20em; margin:0; background:#eee; border:1px solid #ccc; position:fixed; } -button.control { float: left; margin: 0.2em 0 0 1em; height: 2.4em; width: 2.4em; /* border: 0 none; border-radius: 0; -moz-box-shadow: none; box-shadow: none; outline: 0 none;*/ } -#contacts_deletecard {position:relative; float:left; background:url('%webroot%/core/img/actions/delete.svg') no-repeat center; } -#contacts_downloadcard {position:relative; float:left; background:url('%webroot%/core/img/actions/download.svg') no-repeat center; } -#contact { width: auto; font-size: 10px; /*max-width: 70em; border: thin solid lightgray; display: block;*/ } + +/* First run */ + #firstrun { position: relative; top: 25%; left: 20%; right: 20%; width: 50%; font-weight:bold; text-align: center; color: #777; } #firstrun h3 { font-size:1.5em; text-align: center; margin-bottom: 1em; } -#firstrun p { font-size:1.2em; text-align: } +#firstrun p { font-size:1.2em; } #firstrun #selections { font-size:0.8em; margin: 2em auto auto auto; clear: both; } -#contact input:not([type="checkbox"]), #contact select, #contact textarea { background-color: #fefefe; border: 1px solid #fff !important; -moz-appearance:none !important; -webkit-appearance: none !important; -webkit-box-sizing:none !important; -moz-box-sizing:none !important; box-sizing:none !important; -moz-box-shadow: none; -webkit-box-shadow: none; box-shadow: none; -moz-border-radius: 0px; -webkit-border-radius: 0px; border-radius: 0px; float: left; } -#contact input:hover:not([type="checkbox"]), #contact input:active:not([type="checkbox"]), #contact textarea:focus, #contact textarea:hover { border: 1px solid silver !important; -moz-border-radius:.3em; -webkit-border-radius:.3em; border-radius:.3em; outline:none; float: left; } +input:not([type="checkbox"]), select, textarea { background-color: #fefefe; border: 1px solid #fff !important; -moz-appearance:none !important; -webkit-appearance: none !important; -webkit-box-sizing:none !important; -moz-box-sizing:none !important; box-sizing:none !important; -moz-box-shadow: none; -webkit-box-shadow: none; box-shadow: none; -moz-border-radius: 0px; -webkit-border-radius: 0px; border-radius: 0px; float: left; } +input:hover:not([type="checkbox"]), input:active:not([type="checkbox"]), textarea:focus, textarea:hover { border: 1px solid silver !important; -moz-border-radius:.3em; -webkit-border-radius:.3em; border-radius:.3em; outline:none; float: left; } #contact textarea { width: 80%; min-height: 5em; min-width: 30em; margin: 0 !important; padding: 0 !important; outline: 0 !important;} #contact input[type="checkbox"] { margin-top: 10px; vertical-align: bottom; float: left; } -dl.form { width: auto; margin: 0; padding: 0; cursor: normal; } +dl.form { display: inline-block; width: auto; margin: 0; padding: 0; cursor: normal; } .form dt { display: table-cell; clear: left; float: left; width: 7em; margin: 0; padding: 0.8em 0.5em 0 0; text-align:right; text-overflow:ellipsis; o-text-overflow: ellipsis; vertical-align: text-bottom; color: #bbb;/* white-space: pre-wrap; white-space: -moz-pre-wrap !important; white-space: -pre-wrap; white-space: -o-pre-wrap;*/ } .form dd { display: table-cell; clear: right; float: left; margin: 0; padding: 0; white-space: nowrap; vertical-align: text-bottom; } -/*::-webkit-input-placeholder { color: #bbb; } -:-moz-placeholder { color: #bbb; } -:-ms-input-placeholder { color: #bbb; }*/ -.droptarget { margin: 0.5em; padding: 0.5em; border: thin solid #ccc; -moz-border-radius:.3em; -webkit-border-radius:.3em; border-radius:.3em; } -.droppable { margin: 0.5em; padding: 0.5em; border: thin dashed #333; -moz-border-radius:.3em; -webkit-border-radius:.3em; border-radius:.3em; } -.loading { background: url('%webroot%/core/img/loading.gif') no-repeat center !important; /*cursor: progress; */ cursor: wait; } -.ui-autocomplete-loading { background: url('%webroot%/core/img/loading.gif') right center no-repeat; } -.ui-autocomplete-input { margin-top: 0.5em; } /* Ugly hack */ -.float { float: left; } -.svg { border: inherit; background: inherit; } -.listactions { height: 1em; width:60px; float: left; clear: right; } -.add,.edit,.delete,.mail, .globe, .upload, .download, .cloud, .share { cursor: pointer; width: 20px; height: 20px; margin: 0; float: left; position:relative; opacity: 0.1; } -.add:hover,.edit:hover,.delete:hover,.mail:hover, .globe:hover, .upload:hover, .download:hover .cloud:hover { opacity: 1.0 } +.action { cursor: pointer; width: 20px; height: 20px; margin: 0; float: left; position:relative; opacity: 0.1; } +.action:hover { opacity: 1.0 } .add { background:url('%webroot%/core/img/actions/add.svg') no-repeat center; clear: both; } .delete { background:url('%webroot%/core/img/actions/delete.svg') no-repeat center; } .edit { background:url('%webroot%/core/img/actions/rename.svg') no-repeat center; } @@ -68,22 +57,18 @@ dl.form { width: auto; margin: 0; padding: 0; cursor: normal; } .cloud { background:url('%webroot%/core/img/places/picture.svg') no-repeat center; } .globe { background:url('%webroot%/core/img/actions/public.svg') no-repeat center; } .transparent{ opacity: 0.6; } -#edit_name_dialog { padding:0; } -#edit_name_dialog > input { width: 15em; } -#edit_address_dialog { /*width: 30em;*/ } -#edit_address_dialog > input { width: 15em; } -#edit_photo_dialog_img { display: block; min-width: 150; min-height: 200; } - -#cropbox { margin: auto; } -#contacts_details_photo_wrapper { width: 150px; } -#contacts_details_photo_wrapper.wait { opacity: 0.6; filter:alpha(opacity=0.6); z-index:1000; background: url('%webroot%/core/img/loading.gif') no-repeat center center; cursor: wait; } -.contacts_details_photo { border-radius: 0.3em; border: thin solid #bbb; margin: 0.3em; background: url('%webroot%/core/img/loading.gif') no-repeat center center; -moz-box-shadow: 0 1px 3px #777; -webkit-box-shadow: 0 1px 3px #777; box-shadow: 0 1px 3px #777; opacity: 1; } -.contacts_details_photo:hover { background: #fff; cursor: default; } -#phototools { position:absolute; margin: 5px 0 0 10px; width:auto; height:22px; padding:0px; background-color:#fff; list-style-type:none; border-radius: 0.3em; -moz-box-shadow: 0 1px 3px #777; -webkit-box-shadow: 0 1px 3px #777; box-shadow: 0 1px 3px #777; } -#phototools li { display: inline; } -#phototools li a { float:left; cursor:pointer; width:22px; height:22px; opacity: 0.6; } -#phototools li a:hover { opacity: 0.8; } - +.float { float: left; display: inline-block; } +.loading { background: url('%webroot%/core/img/loading.gif') no-repeat center !important; /*cursor: progress; */ cursor: wait; } +.control { + border: 1px solid #DDDDDD; + border-radius: 0.3em; + color: #555; + cursor: pointer; + font-weight: bold; + font-size: 1em; + width: auto; +} +.control > * { background: none repeat scroll 0 0 #F8F8F8; color: #555 !important; font-size: 100%; margin: 0px; } /* Address editor */ #addressdisplay { padding: 0.5em; } dl.addresscard { background-color: #fff; float: left; width: auto; margin: 0 0.3em 0.3em 0.3em; padding: 0; border: 0; } @@ -99,42 +84,37 @@ dl.addresscard .action { float: right; } #address input::-webkit-input-placeholder { color: #aaa; } #address input:-ms-input-placeholder { color: #aaa; } #address input:placeholder { color: #aaa; } -#adr_type {} /* Select */ -#adr_pobox {} -#adr_extended {} -#adr_street {} -#adr_city {} -#adr_region {} -#adr_zipcode {} -#adr_country {} -#file_upload_form { width: 0; height: 0; } -#file_upload_target, #import_upload_target, #crop_target { display:none; } -#file_upload_start, #import_upload_start { -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)"; filter:alpha(opacity=0); opacity:0; z-index:1001; width:0; height:0;} -.big { font-weight:bold; font-size:1.2em; } -.huge { font-weight:bold; font-size:1.5em; } +/* Properties */ + +.fullname { font-weight:bold; font-size:1.5em; width: auto; } .propertylist li.propertycontainer { white-space: nowrap; min-width: 38em; display: block; clear: both; } .propertylist { float: left; } -.propertylist li > input[type="checkbox"],input[type="radio"] { float: left; } -.propertylist li > input.value:not([type="checkbox"]) { min-width: 16em; } +.propertylist li > a { display: block; }} +.propertylist li > input[type="checkbox"],input[type="radio"] { display: inline-block; } +.propertylist li > input.value:not([type="checkbox"]) { min-width: 16em; display: inline-block; } .propertylist li > select { float: left; max-width: 8em; } -.propertylist li > .select_wrapper { float: left; overflow: hidden; color: #bbb; font-size: 0.8em; } -.propertylist li > .select_wrapper select { float: left; overflow: hidden; text-overflow: ellipsis; color: #bbb; width: 8em; } -.propertylist li > .select_wrapper select:hover { overflow: inherit; text-overflow: inherit; } -.propertylist li > .select_wrapper select option { color: #777; } -.propertylist li > .select_wrapper select:hover,.propertylist li > select:focus,.propertylist li > select:active { color: #777; } -.propertylist li > .select_wrapper select.rtl { margin-left: -24px; direction: rtl; } -.propertylist li > .select_wrapper select.types { margin-right: -23px; } +.select_wrapper { float: left; overflow: hidden; color: #bbb; font-size: 0.8em; } +.select_wrapper select { float: left; overflow: hidden; text-overflow: ellipsis; color: #bbb; width: 8em; } +.select_wrapper select:hover { overflow: inherit; text-overflow: inherit; } +.select_wrapper select option { color: #777; } +.select_wrapper select:hover,.propertylist li > select:focus,.propertylist li > select:active { color: #777; } +.select_wrapper select.rtl { margin-left: -24px; direction: rtl; } +.select_wrapper select.ltr { margin-right: -23px; } .propertylist li > input[type="checkbox"].impp { clear: none; } .propertylist li > label.xab { display: block; color: #bbb; float:left; clear: both; padding: 0.5em 0 0 2.5em; } .propertylist li > label.xab:hover { color: #777; } -label, dt, .label { float: left; font-size: 0.7em; color: #bbb !important; max-width: 7em !important; border: 0; } -label:hover, .form dt:hover, input.label:hover { color: #777 !important; } +#rightcontent label, #rightcontent dt, #rightcontent th, #rightcontent .label { float: left; font-size: 0.7em; font-weight: bold; color: #bbb !important; max-width: 7em !important; border: 0; } +#rightcontent label:hover, .form dt:hover, #rightcontent input.label:hover { color: #777 !important; } +#rightcontent input.label:hover, #rightcontent input.label:active { border: 0 none !important; border-radius: 0; cursor: pointer; } .typelist[type="button"] { float: left; max-width: 8em; border: 0; background-color: #fff; color: #bbb; box-shadow: none; } /* for multiselect */ .typelist[type="button"]:hover { color: #777; } /* for multiselect */ .addresslist { clear: both; font-weight: bold; } -#ninjahelp { position: absolute; bottom: 0; left: 0; right: 0; padding: 1em; margin: 1em; opacity: 0.9; } + +/* Help section */ + +#ninjahelp { position: relative; bottom: 0; left: 0; right: 0; padding: 1em; margin: 1em; opacity: 0.9; } #ninjahelp .close { position: absolute; top: 5px; right: 5px; height: 20px; width: 20px; } #ninjahelp h2, .help-section h3 { width: 100%; font-weight: bold; text-align: center; } #ninjahelp h2 { font-size: 1.4em; } @@ -143,26 +123,32 @@ label:hover, .form dt:hover, input.label:hover { color: #777 !important; } .help-section dl { width: 100%; float: left; clear: right; margin: 0; padding: 0; cursor: normal; } .help-section dt { display: table-cell; clear: left; float: left; width: 35%; margin: 0; padding: 0.2em; text-align: right; text-overflow: ellipsis; vertical-align: text-bottom; font-weight: bold: } .help-section dd { display: table-cell; clear: right; float: left; margin: 0; padding: 0.2em; white-space: nowrap; vertical-align: text-bottom; } + +/* Settings */ + .contacts-settings dl { width: 100%; } .addressbooks-settings table { width: 100%; } .addressbooks-settings .actions { width: 100%; white-space: nowrap; } .addressbooks-settings .actions * { float: left; } .addressbooks-settings .actions input.name { width: 5em; } .addressbooks-settings .actions input.name { width: 7em; } -.addressbooks-settings a.action { opacity: 0.2; } +.addressbooks-settings a.action { opacity: 0.5; } .addressbooks-settings a.action:hover { opacity: 1; } .addressbooks-settings td.active, .addressbooks-settings td.action { width: 20px; } +/* Single elements */ + #toggle_all { position: absolute; bottom: .5em; left: .8em; } .numcontacts { float: right; } input.propertytype { float: left; font-size: .8em; width: 8em !important; direction: rtl;} -#rightcontent, .rightcontent { position:fixed; top: 7.5em; left: 32.5em; overflow-x:hidden; overflow-y: auto; } -#rightcontent table { position: relative; top: 0; left: 0; right: 0; } -#contactsheader { position: fixed; padding: 0; margin:0; top:3.5em; left: 32.5em; right: 0; height: 4em; border-bottom: 1px solid #DDDDDD; z-index: 50; } -#contactsheader div { padding: 0 0.5em; height: 100%; width: 90%; margin:0; } +.contactphoto { float: left; display: inline-block; border-radius: 0.3em; border: thin solid #bbb; margin: 0.5em; background: url('%webroot%/core/img/loading.gif') no-repeat center center; -moz-box-shadow: 0 1px 3px #777; -webkit-box-shadow: 0 1px 3px #777; box-shadow: 0 1px 3px #777; opacity: 1; } +.contactphoto:hover { background: #fff; cursor: default; } -#contactsheader button { position: relative; float: left; min-width: 26px; height: 26px; margin: .7em; padding: .2em; opacity: 0.5; clear: none; } -#contactsheader button:hover { opacity: 1; } +/* Header */ + +#contactsheader { position: fixed; padding: 0; margin:0; top:3.5em; left: 32.5em; right: 0; height: 4em; border-bottom: 1px solid #DDDDDD; z-index: 50; } +#contactsheader div.actions { padding: 0 0.5em; margin: 0 auto; height: 100%; width: 90%; } +#contactsheader button, #contactsheader select { position: relative; float: left; min-width: 26px; height: 26px; margin: .7em; padding: .2em; clear: none; } #contactsheader .back { } #contactsheader .import { background:url('%webroot%/core/img/actions/upload.svg') no-repeat center; } #contactsheader .newcontact { background:url('%appswebroot%/contacts/img/contact-new.svg') no-repeat center; } @@ -171,30 +157,49 @@ input.propertytype { float: left; font-size: .8em; width: 8em !important; direct #contactsheader .list.add { margin-left: 5em; } #contactsheader .settings { background:url('%webroot%/core/img/actions/settings.svg') no-repeat center; position: absolute; top: .7em; right: 1em; margin: 0; } + +/* Right content layout */ + +#rightcontent, .rightcontent { position:fixed; top: 7.5em; left: 32.5em; overflow-x:hidden; overflow-y: auto; } + +/* Contact layout */ + +#contact > ul { + font-size: 10px; + /*display: table; + border-spacing: 1em; + border: thin solid black;*/ +} +#contact > ul > li { + display: inline-block; + padding: 1em; + /*display: table-cell;*/ +} + +#rightcontent footer { padding: 1em; } + +/* contact list */ + +#contactlist { position: relative; top: 0; left: 0; right: 0; width: 100%; } #contactlist tr { height: 3em; } -#contactlist tr td { text-overflow: ellipsis; border-bottom: 1px solid #DDDDDD; font-weight: normal; text-align: left; overflow: hidden; text-overflow: ellipsis; vertical-align: middle; white-space: nowrap; } -#contactlist tr td:hover { overflow: inherit; text-overflow: inherit; background-color: #fff; z-index: 200; } -#contactlist tr td:not(.adr) { width: 15%; } -#contactlist tr td.name>input[type=checkbox]:first-child { -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)"; filter:alpha(opacity=0); opacity:0; float:left; margin:.5em 0 0 1.2em; -webkit-transition:opacity 200ms; -moz-transition:opacity 200ms; -o-transition:opacity 200ms; transition:opacity 200ms; } -#contactlist tr td.name>input[type="checkbox"]:hover:first-child { -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=80)"; filter:alpha(opacity=80); opacity:.8; } -#contactlist tr td.name>input[type="checkbox"]:checked:first-child { -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=100)"; filter:alpha(opacity=100); opacity:1; } -#contactlist tr td.name { font-weight: bold; text-indent: 1.6em; -webkit-transition:background-image 500ms; -moz-transition:background-image 500ms; -o-transition:background-image 500ms; transition:background-image 500ms; position:relative; background-position:1em .5em !important; background-repeat:no-repeat !important; } -#contactlist tr td.email span { float: left; clear: none; } -#contactlist tr td a.mailto { float: right; cursor:pointer; width:22px; height:22px; z-index: 200; opacity: 0.6; background:url('%webroot%/core/img/actions/mail.svg') no-repeat center; } -#contactlist tr td a.mailto:hover { opacity: 0.8; } +#contactlist tr.active, #contactlist tr:hover { background-color: #eee; } +#contactlist tr > td { border-bottom: 1px solid #DDDDDD; font-weight: normal; text-align: left; overflow: hidden; text-overflow: ellipsis; vertical-align: middle; white-space: nowrap; } +#contactlist tr > td:hover { overflow: inherit; text-overflow: inherit; background-color: #fff; z-index: 200; } +#contactlist tr > td:not(.adr) { width: 15%; } +#contactlist tr > td.name>input[type=checkbox]:first-child { -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)"; filter:alpha(opacity=0); opacity:0; float:left; margin:.5em 0 0 1.2em; -webkit-transition:opacity 200ms; -moz-transition:opacity 200ms; -o-transition:opacity 200ms; transition:opacity 200ms; } +#contactlist tr > td.name>input[type="checkbox"]:hover:first-child { -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=80)"; filter:alpha(opacity=80); opacity:.8; } +#contactlist tr > td.name>input[type="checkbox"]:checked:first-child { -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=100)"; filter:alpha(opacity=100); opacity:1; } +#contactlist tr > td.name { font-weight: bold; text-indent: 1.6em; -webkit-transition:background-image 500ms; -moz-transition:background-image 500ms; -o-transition:background-image 500ms; transition:background-image 500ms; position:relative; background-position:1em .5em !important; background-repeat:no-repeat !important; } +#contactlist tr > td.email span { float: left; clear: none; } +#contactlist tr > td a.mailto { float: right; cursor:pointer; width:22px; height:22px; z-index: 200; opacity: 0.6; background:url('%webroot%/core/img/actions/mail.svg') no-repeat center; } +#contactlist tr > td a.mailto:hover { opacity: 0.8; } -section#contact { position: relative; top: 0; left: 0; right: 0; } - -#contact figure { float: left; clear: none; } #contact figure img { -moz-border-radius:.3em; -webkit-border-radius:.3em; border-radius:.3em; border: thin solid #bbb; margin: 0.3em; background: url('%webroot%/core/img/loading.gif') no-repeat center center; -moz-box-shadow: 0 1px 3px #777; -webkit-box-shadow: 0 1px 3px #777; box-shadow: 0 1px 3px #777; opacity: 1; } -#contact section { float: left; margin: 1em; } -#contact footer { clear: both; margin: 1em; } -#contact li { display: block; clear: both; white-space: nowrap; } -#contact span.adr { float: left; max-width: 14em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -#contact span.adr:hover { overflow: inherit; } -#contact .value {float: left; } +#contact span.adr { float: left; width: 16em; overflow: hidden; text-overflow: ellipsis; text-align: bottom; white-space: nowrap; } +#contact span.adr:hover { overflow: inherit; } + @media screen and (max-width: 1500px) { #contactlist tr td.categories { display: none; } } @@ -202,18 +207,19 @@ section#contact { position: relative; top: 0; left: 0; right: 0; } #contactlist tr td.adr { display: none; } } @media screen and (min-width: 1400px) { - ul.propertylist { + #contact > ul { -moz-column-count: 3; - /*-webkit-columns: 3;*/ + -webkit-columns: 3; -o-columns: 3; columns: 3; } } -@media screen and (min-width: 1100) and (max-width: 1200px) { +@media screen and (min-width: 1100px) and (max-width: 1200px) { #contactlist tr td.tel { display: none; } } @media screen and (min-width: 800px) and (max-width: 1400) { - ul.propertylist { + #singlevalues { max-width: 50%; } + #contact > ul { -moz-column-count: 2; -webkit-columns: 2; -o-columns: 2; @@ -224,7 +230,7 @@ section#contact { position: relative; top: 0; left: 0; right: 0; } #contactlist tr td.email { display: none; } } @media screen and (max-width: 400px) { - ul.propertylist { + #contact > ul { -moz-column-count: 1; -webkit-columns: 1; -o-columns: 1; diff --git a/export.php b/export.php index c092d6c5..aa9517b8 100644 --- a/export.php +++ b/export.php @@ -13,7 +13,18 @@ $bookid = isset($_GET['bookid']) ? $_GET['bookid'] : null; $contactid = isset($_GET['contactid']) ? $_GET['contactid'] : null; $nl = "\n"; if(isset($bookid)) { - $addressbook = OC_Contacts_App::getAddressbook($bookid); + try { + $addressbook = OC_Contacts_Addressbook::find($id); // is owner access check + } catch(Exception $e) { + OCP\JSON::error( + array( + 'data' => array( + 'message' => $e->getMessage(), + ) + ) + ); + exit(); + } //$cardobjects = OC_Contacts_VCard::all($bookid); header('Content-Type: text/directory'); header('Content-Disposition: inline; filename=' @@ -30,7 +41,18 @@ if(isset($bookid)) { $start += $batchsize; } }elseif(isset($contactid)) { - $data = OC_Contacts_App::getContactObject($contactid); + try { + $data = OC_Contacts_VCard::find($contactid); + } catch(Exception $e) { + OCP\JSON::error( + array( + 'data' => array( + 'message' => $e->getMessage(), + ) + ) + ); + exit(); + } header('Content-Type: text/vcard'); header('Content-Disposition: inline; filename=' . str_replace(' ', '_', $data['fullname']) . '.vcf'); diff --git a/import.php b/import.php index fa624be8..fdeb99d4 100644 --- a/import.php +++ b/import.php @@ -63,7 +63,19 @@ if(isset($_POST['method']) && $_POST['method'] == 'new') { ); exit(); } - OC_Contacts_App::getAddressbook($id); // is owner access check + try { + OC_Contacts_Addressbook::find($id); // is owner access check + } catch(Exception $e) { + OCP\JSON::error( + array( + 'data' => array( + 'message' => $e->getMessage(), + 'file'=>$_POST['file'] + ) + ) + ); + exit(); + } } //analyse the contacts file writeProgress('40'); diff --git a/index.php b/index.php index cf5e87fd..4ef1321e 100644 --- a/index.php +++ b/index.php @@ -50,6 +50,7 @@ $maxUploadFilesize = min($maxUploadFilesize, $freeSpace); OCP\Util::addscript('', 'jquery.multiselect'); OCP\Util::addscript('', 'oc-vcategories'); OCP\Util::addscript('contacts', 'app'); +OCP\Util::addscript('contacts', 'contacts'); OCP\Util::addscript('contacts', 'modernizr'); OCP\Util::addscript('contacts', 'placeholder.polyfill.jquery'); OCP\Util::addscript('contacts', 'expanding'); diff --git a/js/app.js b/js/app.js index 5dae3584..e6efec90 100644 --- a/js/app.js +++ b/js/app.js @@ -1,9 +1,22 @@ +function AssertException(message) { this.message = message; } +AssertException.prototype.toString = function () { + return 'AssertException: ' + this.message; +} + +// Usage: assert(obj != null, 'Object is null'); +function assert(exp, message) { + if (!exp) { + throw new AssertException(message); + } +} + + if (typeof Object.create !== 'function') { - Object.create = function (o) { - function F() {} - F.prototype = o; - return new F(); - }; + Object.create = function (o) { + function F() {} + F.prototype = o; + return new F(); + }; } Array.prototype.clean = function(deleteValue) { @@ -16,9 +29,166 @@ Array.prototype.clean = function(deleteValue) { return this; }; +// Keep it DRY ;) +var wrongKey = function(event) { + return (event.type === 'keydown' && (event.keyCode !== 32 && event.keyCode !== 13)); +} + +/** + * Simply notifier + * Arguments: + * @param message The text message to show. + * @param timeout The timeout in seconds before the notification disappears. Default 10. + * @param timeouthandler A function to run on timeout. + * @param clickhandler A function to run on click. If a timeouthandler is given it will be cancelled on click. + * @param data An object that will be passed as argument to the timeouthandler and clickhandler functions. + * @param cancel If set cancel all ongoing timer events and hide the notification. + */ +OC.notify = function(params) { + var self = this; + if(!self.notifier) { + self.notifier = $('#notification'); + if(!self.notifier.length) { + $('#content').prepend('
    '); + self.notifier = $('#notification'); + } + } + if(params.cancel) { + self.notifier.off('click'); + for(var id in self.notifier.data()) { + if($.isNumeric(id)) { + clearTimeout(parseInt(id)); + } + } + self.notifier.text('').fadeOut().removeData(); + return; + } + self.notifier.text(params.message); + self.notifier.fadeIn(); + self.notifier.on('click', function() { $(this).fadeOut();}); + var timer = setTimeout(function() { + /*if(!self || !self.notifier) { + var self = OC.Contacts; + self.notifier = $('#notification'); + }*/ + self.notifier.fadeOut(); + if(params.timeouthandler && $.isFunction(params.timeouthandler)) { + params.timeouthandler(self.notifier.data(dataid)); + self.notifier.off('click'); + self.notifier.removeData(dataid); + } + }, params.timeout && $.isNumeric(params.timeout) ? parseInt(params.timeout)*1000 : 10000); + var dataid = timer.toString(); + if(params.data) { + self.notifier.data(dataid, params.data); + } + if(params.clickhandler && $.isFunction(params.clickhandler)) { + self.notifier.on('click', function() { + /*if(!self || !self.notifier) { + var self = OC.Contacts; + self.notifier = $(this); + }*/ + clearTimeout(timer); + self.notifier.off('click'); + params.clickhandler(self.notifier.data(dataid)); + self.notifier.removeData(dataid); + }); + } +} + +var GroupList = function(groupList) { + this.$groupList = groupList; +} + +GroupList.prototype.findById = function(id) { + return this.$groupList.find('h3[data-id="' + id + '"]'); +} + +GroupList.prototype.addTo = function(contactid, groupid, cb) { + var $groupelem = this.findById(groupid); + var contacts = $groupelem.data('contacts'); + if(contacts.indexOf(String(contactid)) === -1) { + $.post(OC.filePath('contacts', 'ajax', 'categories/addto.php'), {contactid: contactid, categoryid: groupid},function(jsondata) { + if(!jsondata) { + OC.notify({message:t('contacts', 'Network or server error. Please inform administrator.')}); + if(typeof cb === 'function') { + cb('error'); + } + return; + } + if(jsondata.status === 'success') { + contacts.push(String(contactid)); + $groupelem.data('contacts', contacts); + $groupelem.find('.numcontacts').text(contacts.length); + if(typeof cb === 'function') { + cb('success'); + } + } else { + OC.notify({message:jsondata.data.message}); + if(typeof cb == 'function') { + cb('error'); + } + } + }); + } else { + OC.notify({message:t('contacts', 'Contact is already in this group.')}); + } +} + +GroupList.prototype.removeFrom = function(contactid, groupid, cb) { + console.log('GroupList.removeFrom', contactid, groupid); + var $groupelem = this.findById(groupid); + var contacts = $groupelem.data('contacts'); + // If the contact is in the category remove it from internal list. + if(!contacts) { + return; + } + if(contacts.indexOf(String(contactid)) !== -1) { + $.post(OC.filePath('contacts', 'ajax', 'categories/removefrom.php'), {contactid: contactid, categoryid: groupid},function(jsondata) { + if(!jsondata) { + OC.notify({message:t('contacts', 'Network or server error.')}); + if(typeof cb === 'function') { + cb('error'); + } + return; + } + if(jsondata.status === 'success') { + contacts.splice(contacts.indexOf(String(contactid)), 1); + //console.log('contacts', contacts, contacts.indexOf(id), contacts.indexOf(String(id))); + $groupelem.data('contacts', contacts); + $groupelem.find('.numcontacts').text(contacts.length); + if(typeof cb === 'function') { + cb('success'); + } + } else { + OC.notify({message:jsondata.data.message}); + if(typeof cb == 'function') { + cb('error'); + } + } + }); + } else { + console.log('Contact not in this group.', $groupelem); + OC.notify({message:t('contacts', 'Contact not in this group.')}); + } +} + +GroupList.prototype.removeFromAll = function(contactid, alsospecial) { + var self = this; + var selector = alsospecial ? 'h3' : 'h3[data-type="category"]'; + $.each(this.$groupList.find(selector), function(i, group) { + self.removeFrom(contactid, $(this).data('id')); + }); +} + OC.Contacts = OC.Contacts || { - init:function() { - this.ENTER_KEY = 13; + init:function(id) { + if(id) { + this.currentid = parseInt(id); + console.log('init, id:', id); + } + // Holds an array of {id,name} maps + this.categories = []; this.scrollTimeoutMiliSecs = 100; this.isScrolling = false; this.cacheElements(); @@ -28,63 +198,10 @@ OC.Contacts = OC.Contacts || { this.$contactFullTemplate, this.detailTemplates ); + this.Groups = new GroupList(this.$groupList); this.bindEvents(); - }, - /** - * Arguments: - * message: The text message to show. - * timeout: The timeout in seconds before the notification disappears. Default 10. - * timeouthandler: A function to run on timeout. - * clickhandler: A function to run on click. If a timeouthandler is given it will be cancelled. - * data: An object that will be passed as argument to the timeouthandler and clickhandler functions. - * cancel: If set cancel all ongoing timer events and hide the notification. - */ - notify:function(params) { - var self = this; - if(!self.notifier) { - self.notifier = $('#notification'); - } - if(params.cancel) { - self.notifier.off('click'); - for(var id in self.notifier.data()) { - if($.isNumeric(id)) { - clearTimeout(parseInt(id)); - } - } - self.notifier.text('').fadeOut().removeData(); - return; - } - self.notifier.text(params.message); - self.notifier.fadeIn(); - self.notifier.on('click', function() { $(this).fadeOut();}); - var timer = setTimeout(function() { - if(!self || !self.notifier) { - var self = OC.Contacts; - self.notifier = $('#notification'); - } - self.notifier.fadeOut(); - if(params.timeouthandler && $.isFunction(params.timeouthandler)) { - params.timeouthandler(self.notifier.data(dataid)); - self.notifier.off('click'); - self.notifier.removeData(dataid); - } - }, params.timeout && $.isNumeric(params.timeout) ? parseInt(params.timeout)*1000 : 10000); - var dataid = timer.toString(); - if(params.data) { - self.notifier.data(dataid, params.data); - } - if(params.clickhandler && $.isFunction(params.clickhandler)) { - self.notifier.on('click', function() { - if(!self || !self.notifier) { - var self = OC.Contacts; - self.notifier = $(this); - } - clearTimeout(timer); - self.notifier.off('click'); - params.clickhandler(self.notifier.data(dataid)); - self.notifier.removeData(dataid); - }); - } + this.$toggleAll.show(); + this.showActions(['add', 'delete']); }, loading:function(obj, state) { if(state) { @@ -93,6 +210,21 @@ OC.Contacts = OC.Contacts || { $(obj).removeClass('loading'); } }, + /** + * Show/hide elements in the header + * @param act An array of actions to show based on class name e.g ['add', 'delete'] + */ + showActions:function(act) { + this.$headeractions.children().hide(); + this.$headeractions.children('.'+act.join(',.')).show(); + }, + showAction:function(act, show) { + if(show) { + this.$headeractions.find('.' + act).show(); + } else { + this.$headeractions.find('.' + act).hide(); + } + }, cacheElements: function() { var self = this; this.detailTemplates = {}; @@ -111,55 +243,140 @@ OC.Contacts = OC.Contacts || { this.$contactDetailsTemplate = $('#contactDetailsTemplate'); this.$rightContent = $('#rightcontent'); this.$header = $('#contactsheader'); + this.$headeractions = this.$header.find('div.actions'); this.$groupList = $('#grouplist'); this.$contactList = $('#contactlist'); this.$contactListHeader = $('#contactlistheader'); this.$toggleAll = $('#toggle_all'); + this.$groups = this.$headeractions.find('.groups'); + this.$ninjahelp = $('#ninjahelp'); + + }, + // Build the select to add/remove from groups. + buildGroupSelect: function() { + if(this.currentid) { + var contact = this.Contacts.contacts[this.currentid]; + this.$groups.find('optgroup,option:not([value="-1"])').remove(); + var addopts = '', rmopts = ''; + $.each(this.categories, function(i, category) { + if(contact.inGroup(category.name)) { + rmopts += ''; + } else { + addopts += ''; + } + }); + if(addopts.length) { + $(addopts).appendTo(this.$groups) + .wrapAll(''); + } + if(rmopts.length) { + $(rmopts).appendTo(this.$groups) + .wrapAll(''); + } + } else { + this.$groups.find('optgroup,option:not([value="-1"])').remove(); + var addopts = '', rmopts = ''; + $.each(this.categories, function(i, category) { + rmopts += ''; + addopts += ''; + }); + $(addopts).appendTo(this.$groups) + .wrapAll(''); + $(rmopts).appendTo(this.$groups) + .wrapAll(''); + } + $('').appendTo(this.$groups); + this.$groups.val(-1); }, bindEvents: function() { var self = this; - this.$toggleAll.on('change', function() { - self.Contacts.toggleAll(this, self.$contactList.find('input:checkbox')); - }); - this.$contactList.on('change', 'input:checkbox', function(event) { - var id = parseInt($(this).parents('tr').first().data('id')); - self.Contacts.selectedContacts.push(id); - console.log('selected', id); - }); + + // App specific events $(document).bind('status.contact.deleted', function(e, data) { var id = parseInt(data.id); console.log('contact', data.id, 'deleted'); - // update counts on group list - self.$groupList.find('h3').each(function(i, group) { - if($(this).data('type') === 'all') { - $(this).find('.numcontacts').text(parseInt($(this).find('.numcontacts').text()-1)); - } else if($(this).data('type') === 'category') { - var contacts = $(this).data('contacts'); - console.log('contacts', contacts, contacts.indexOf(id), contacts.indexOf(String(id))); - if(contacts.indexOf(String(id)) !== -1) { - contacts.splice(contacts.indexOf(String(id)), 1); - console.log('contacts', contacts, contacts.indexOf(id), contacts.indexOf(String(id))); - $(this).data('contacts', contacts); - $(this).find('.numcontacts').text(contacts.length); - } - } - }); + // update counts on group lists + self.Groups.removeFromAll(data.id, true) + }); + $(document).bind('status.contact.error', function(e, data) { + OC.notify({message:data.message}); }); $(document).bind('status.contact.enabled', function(e, enabled) { + console.log('status.contact.enabled', enabled) if(enabled) { - self.$header.find('.delete').show(); + self.showActions(['back', 'add', 'download', 'delete', 'groups']); } else { - self.$header.find('.delete').hide(); + self.showActions(['back']); } }); $(document).bind('status.contacts.loaded', function(e, result) { console.log('status.contacts.loaded', result); if(result.status !== true) { alert('Error loading contacts!'); + } else { + self.numcontacts = result.numcontacts; + self.$rightContent.removeClass('loading'); +// var $firstelem = self.$contactList.find('tr:first-child'); +// self.currentlistid = $firstelem.data('id'); +// console.log('first element', self.currentlistid, $firstelem); +// $firstelem.addClass('active'); + self.loadGroups(function() { + $('#leftcontent').removeClass('loading'); + if(self.currentid) { + self.openContact(self.currentid); + } + }); } - self.numcontacts = result.numcontacts; - self.loadGroups(); - self.$rightContent.removeClass('loading'); + }); + $(document).bind('status.contact.currentlistitem', function(e, result) { + //console.log('status.contact.currentlistitem', result, self.$rightContent.height()); + if(self.dontScroll !== true) { + if(result.pos > self.$rightContent.height()) { + self.$rightContent.scrollTop(result.pos - self.$rightContent.height() + result.height); + } + else if(result.pos < self.$rightContent.offset().top) { + self.$rightContent.scrollTop(result.pos); + } + } else { + setTimeout(function() { + self.dontScroll = false; + }, 100); + } + self.currentlistid = result.id + }); + $(document).bind('status.contact.removedfromgroup', function(e, result) { + console.log('status.contact.removedfromgroup', result); + if(self.currentgroup == result.groupid) { + self.closeContact(result.contactid); + } + }); + $(document).bind('status.nomorecontacts', function(e, result) { + console.log('status.nomorecontacts', result); + self.$contactList = $('#contactlist').hide(); + // TODO: Show a first-run page. + }); + $(document).bind('status.visiblecontacts', function(e, result) { + console.log('status.visiblecontacts', result); + // TODO: To be decided. + }); + // A contact id was in the request + $(document).bind('request.loadcontact', function(e, result) { + console.log('request.loadcontact', result); + if(self.numcontacts) { + self.openContact(result.id); + } else { + // Contacts are not loaded yet, try again. + console.log('waiting for contacts to load'); + setTimeout(function() { + $(document).trigger('request.loadcontact', { + id: result.id, + }); + }, 1000); + } + }); + $(document).bind('request.addressbook.activate', function(e, result) { + console.log('request.addressbook.activate', result); + self.Contacts.showFromAddressbook(result.id, result.activate); }); // mark items whose title was hid under the top edge as read /*this.$rightContent.scroll(function() { @@ -182,14 +399,117 @@ OC.Contacts = OC.Contacts || { //console.log('scroll, unseen:', offset, self.$rightContent.height()); } });*/ + this.$ninjahelp.find('.close').on('click keydown',function(event) { + if(wrongKey(event)) { + return; + } + self.$ninjahelp.hide(); + }); + this.$toggleAll.on('change', function() { + var isChecked = self.Contacts.toggleAll(this, self.$contactList.find('input:checkbox:visible')); + if(self.$groups.find('option').length === 1) { + self.buildGroupSelect(); + } + self.showAction('groups', isChecked); + }); + this.$contactList.on('change', 'input:checkbox', function(event) { + if($(this).is(':checked')) { + if(self.$groups.find('option').length === 1) { + self.buildGroupSelect(); + } + self.showAction('groups', true); + } else if(self.Contacts.getSelectedContacts().length === 0) { + self.showAction('groups', false); + } + }); + this.$groups.on('change', function() { + var $opt = $(this).find('option:selected'); + var action = $opt.parent().data('action'); + var ids, buildnow = false; + + if($opt.val() === 'add') { + console.log('add group...'); + self.$groups.val(-1); + return; + } + + // If a contact is open the action is only applied to that, + // otherwise on all selected items. + if(self.currentid) { + ids = [self.currentid,]; + buildnow = true + } else { + ids = self.Contacts.getSelectedContacts(); + } + console.log('ids', ids); + if(action === 'add') { + $.each(ids, function(i, id) { + console.log('id', id); + self.Groups.addTo(id, $opt.val(), function(result) { + console.log('after add', result); + if(result === 'success') { + console.log('typeof', typeof parseInt(id), id); + self.Contacts.contacts[id].addToGroup($opt.text()); + if(buildnow) { + self.buildGroupSelect(); + } + $(document).trigger('status.contact.addedtogroup', { + contactid: id, + groupid: $opt.val(), + groupname: $opt.text(), + }); + } else { + OC.notify({message:t('contacts', t('contacts', 'Error adding to group.'))}); + } + }); + }); + if(!buildnow) { + self.$groups.val(-1).hide().find('optgroup,option:not([value="-1"])').remove(); + } + } else if(action === 'remove') { + $.each(ids, function(i, id) { + self.Groups.removeFrom(id, $opt.val(), function(result) { + console.log('after remove', result); + if(result === 'success') { + self.Contacts.contacts[id].removeFromGroup($opt.text()); + if(buildnow) { + self.buildGroupSelect(); + } + // If a group is selected the contact has to be removed from the list + $(document).trigger('status.contact.removedfromgroup', { + contactid: id, + groupid: $opt.val(), + groupname: $opt.text(), + }); + } else { + OC.notify({message:t('contacts', t('contacts', 'Error removing from group.'))}); + } + }); + }); + if(!buildnow) { + self.$groups.val(-1).hide().find('optgroup,option:not([value="-1"])').remove(); + } + } // else something's wrong ;) + $.each(self.$contactList.find('input:checkbox:checked'), function() { + console.log('unchecking', $(this)); + $(this).prop('checked', false); + }); + console.log('groups', $opt.parent().data('action'), $opt.val(), $opt.text()); + }); + // Group selected, only show contacts from that group this.$groupList.on('click', 'h3', function() { + self.currentgroup = $(this).data('id'); console.log('Group click', $(this).data('id'), $(this).data('type')); - delete self.currentid; + // Close any open contact. + if(self.currentid) { + var id = self.currentid; + self.closeContact(id); + self.Contacts.jumpToContact(id); + } self.$groupList.find('h3').removeClass('active'); self.$contactList.show(); - self.$header.find('.list').show(); - self.$header.find('.single').hide(); - $('#contact').remove(); + self.$toggleAll.show(); + self.showActions(['add', 'delete']); $(this).addClass('active'); if($(this).data('type') === 'category') { self.Contacts.showContacts($(this).data('contacts')); @@ -197,41 +517,77 @@ OC.Contacts = OC.Contacts || { self.Contacts.showContacts($(this).data('id')); } }); + // Contact list. Either open a contact or perform an action (mailto etc.) this.$contactList.on('click', 'tr', function(event) { if($(event.target).is('input')) { return; } - if($(event.target).is('a.mailto')) { - console.log('mailto', $(this).find('.email').text().trim()); - window.location.href='mailto:' + $(this).find('.email').text().trim(); + if(event.ctrlKey) { + event.stopPropagation(); + event.preventDefault(); + console.log('select', event); + self.dontScroll = true; + self.Contacts.select($(this).data('id'), true); return; } - self.currentid = $(this).data('id'); - console.log('Contact click', self.currentid); - self.$contactList.hide(); - self.$header.find('.list').hide(); - self.$header.find('.single').show(); - self.$rightContent.prepend(self.Contacts.showContact(self.currentid)); + if($(event.target).is('a.mailto')) { + var mailto = 'mailto:' + $(this).find('.email').text().trim(); + console.log('mailto', mailto); + try { + window.location.href=mailto; + } catch(e) { + alert(t('contacts', 'There was an error opening a mail composer.')); + } + return; + } + self.openContact($(this).data('id')); }); - this.$header.find('.back').on('click keydown', function() { + this.$header.on('click keydown', '.back', function(event) { + if(wrongKey(event)) { + return; + } console.log('back'); - var listelem = self.Contacts.contacts[parseInt(self.currentid)].detach().remove(); - self.$contactList.show(); + self.closeContact(self.currentid); + self.$toggleAll.show(); + self.showActions(['add', 'delete']); }); - this.$header.find('.add').on('click keydown', function() { + this.$header.on('click keydown', '.add', function(event) { + if(wrongKey(event)) { + return; + } console.log('add'); self.$contactList.hide(); + $(this).hide(); self.$rightContent.prepend(self.Contacts.addContact()); + self.showActions(['back']); }); - this.$header.find('.delete').on('click keydown', function() { + this.$header.on('click keydown', '.delete', function(event) { + if(wrongKey(event)) { + return; + } console.log('delete'); if(self.currentid) { self.Contacts.delayedDeleteContact(self.currentid); + self.showActions(['add', 'delete']); } else { console.log('currentid is not set'); } }); - this.$header.find('.settings').on('click keydown', function() { + this.$header.on('click keydown', '.download', function(event) { + if(wrongKey(event)) { + return; + } + console.log('download'); + if(self.currentid) { + document.location.href = OC.linkTo('contacts', 'export.php') + '?contactid=' + self.currentid; + } else { + console.log('currentid is not set'); + } + }); + this.$header.on('click keydown', '.settings', function(event) { + if(wrongKey(event)) { + return; + } try { //ninjahelp.hide(); OC.appSettings({appid:'contacts', loadJS:true, cache:false}); @@ -247,21 +603,120 @@ OC.Contacts = OC.Contacts || { this.$contactList.on('mouseleave', 'td.email', function(event) { $(this).find('.mailto').fadeOut(100); }); + + $(document).on('keyup', function(event) { + if(event.target.nodeName.toUpperCase() != 'BODY') { + return; + } + console.log(event.which + ' ' + event.target.nodeName); + /** + * To add: + * Shift-a: add addressbook + * u (85): hide/show leftcontent + * f (70): add field + */ + switch(event.which) { + case 13: // Enter? + console.log('Enter?'); + if(!self.currentid && self.currentlistid) { + self.openContact(self.currentlistid); + } + break; + case 27: // Esc + if(self.$ninjahelp.is(':visible')) { + self.$ninjahelp.hide(); + } else if(self.currentid) { + self.closeContact(self.currentid); + } + break; + case 46: // Delete + if(event.shiftKey) { + self.Contacts.delayedDeleteContact(self.currentid); + } + break; + case 40: // down + case 74: // j + console.log('next'); + if(!self.currentid && self.currentlistid) { + self.Contacts.contacts[self.currentlistid].next(); + } + break; + case 65: // a + if(event.shiftKey) { + console.log('add group?'); + break; + } + self.addContact(); + break; + case 38: // up + case 75: // k + console.log('previous'); + if(!self.currentid && self.currentlistid) { + self.Contacts.contacts[self.currentlistid].prev(); + } + break; + case 34: // PageDown + case 78: // n + console.log('page down') + break; + case 79: // o + console.log('open contact?'); + break; + case 33: // PageUp + case 80: // p + // prev addressbook + //OC.Contacts.Contacts.previousAddressbook(); + break; + case 82: // r + console.log('refresh - what?'); + break; + case 63: // ? German. + if(event.shiftKey) { + self.$ninjahelp.toggle('fast'); + } + break; + case 171: // ? Danish + case 191: // ? Standard qwerty + self.$ninjahelp.toggle('fast'); + break; + } + + }); + $('[title]').tipsy(); // find all with a title attribute and tipsy them }, + jumpToContact: function(id) { + this.$rightContent.scrollTop(this.Contacts.contactPos(id)); + }, + closeContact: function(id) { + if(this.currentid) { + delete this.currentid; + this.Contacts.findById(id).close(); + this.$contactList.show(); + this.jumpToContact(id); + } + this.$groups.find('optgroup,option:not([value="-1"])').remove(); + }, + openContact: function(id) { + this.currentid = parseInt(id); + this.$contactList.hide(); + this.$toggleAll.hide(); + var $contactelem = this.Contacts.showContact(this.currentid); + this.$rightContent.prepend($contactelem); + this.buildGroupSelect(); + }, update: function() { console.log('update'); }, - loadGroups: function() { + loadGroups: function(cb) { var self = this; - var groupList = this.$groupList; + var $groupList = this.$groupList; var tmpl = this.$groupListItemTemplate; - tmpl.octemplate({id: 'all', type: 'all', num: this.numcontacts, name: t('contacts', 'All')}).appendTo(groupList); - tmpl.octemplate({id: 'fav', type: 'fav', num: '', name: t('contacts', 'Favorites')}).appendTo(groupList); + tmpl.octemplate({id: 'all', type: 'all', num: this.numcontacts, name: t('contacts', 'All')}).appendTo($groupList); + tmpl.octemplate({id: 'fav', type: 'fav', num: '', name: t('contacts', 'Favorites')}).appendTo($groupList); $.getJSON(OC.filePath('contacts', 'ajax', 'categories/list.php'), {}, function(jsondata) { if (jsondata && jsondata.status == 'success') { - self.categories = []; $.each(jsondata.data.categories, function(c, category) { var $elem = (tmpl).octemplate({ id: category.id, @@ -271,600 +726,20 @@ OC.Contacts = OC.Contacts || { }) self.categories.push({id: category.id, name: category.name}); $elem.data('contacts', category.contacts) - $elem.appendTo(groupList); + $elem.data('name', category.name) + $elem.data('id', category.id) + $elem.appendTo($groupList); }); } + if(typeof cb === 'function') { + cb(); + } }); }, }; (function( $ ) { - /** - * An item which binds the appropriate html and event handlers - * @param parent the parent Contacts list - * @param data the data used to populate the contact - * @param template the jquery object used to render the contact - */ - var Contact = function(parent, id, access, data, listtemplate, fulltemplate, detailtemplates) { - //console.log('contact:', id, access); //parent, id, data, listtemplate, fulltemplate); - this.parent = parent, - this.id = id, - this.access = access, - this.data = data, - this.$listTemplate = listtemplate, - this.$fullTemplate = fulltemplate; - this.detailTemplates = detailtemplates; - var self = this; - this.multi_properties = ['EMAIL', 'TEL', 'IMPP', 'ADR', 'URL']; - } - - /** - * Act on change - * @param event - */ - Contact.prototype.save = function(self, obj) { - OC.Contacts.loading(obj, true); - var container = $(obj).hasClass('propertycontainer') - ? obj : self.propertyContainerFor(obj); - var element = container.data('element').toUpperCase(); - console.log('change', obj, element, container, container - .find('input.value,select.value,textarea.value'));//.serializeArray()); - var q = container.find('input.value,select.value,textarea.value').serialize(); - if(q == '' || q == undefined) { - $(document).trigger('status.contact', { - status: 'error', - message: t('contacts', 'Couldn\'t serialize elements.'), - }); - OC.Contacts.loading(obj, false); - return false; - } - q = q + '&id=' + self.id + '&name=' + element; - if(self.multi_properties.indexOf(element) !== -1) { - q = q + '&checksum=' + container.data('checksum'); - } - console.log(q); - OC.Contacts.loading(obj, false); - } - - /** - * Remove any open contact from the DOM and detach it's list - * element from the DOM. - */ - Contact.prototype.detach = function() { - if(this.$fullelem) { - this.$fullelem.remove(); - } - if(this.$listelem) { - return this.$listelem.detach(); - } - } - - /** - * Set a contact to en/disabled depending on its permissions. - * @param boolean enabled - */ - Contact.prototype.setEnabled = function(enabled) { - console.log('setEnabled', enabled); - if(enabled) { - this.$fullelem.find('#addproperty').show(); - } else { - this.$fullelem.find('#addproperty').hide(); - } - this.enabled = enabled; - this.$fullelem.find('.value,.action').each(function () { - console.log($(this)); - $(this).prop('disabled', !enabled); - }); - $(document).trigger('status.contact.enabled', false); - } - - /** - * Delete contact from data store and remove it from the DOM - */ - Contact.prototype.destroy = function(cb) { - var self = this; - $.post(OC.filePath('contacts', 'ajax', 'contact/delete.php'), - {id: this.id}, function(jsondata) { - if(jsondata && jsondata.status === 'success') { - if(self.$listelem) { - self.$listelem.remove(); - } - if(self.$fullelem) { - self.$fullelem.remove(); - } - } - if(typeof cb == 'function') { - cb({ - status: jsondata ? jsondata.status : 'error', - message: (jsondata && jsondata.data) ? jsondata.data.message : '', - }); - } - }); - } - - Contact.prototype.propertyContainerFor = function(obj) { - return $(obj).parents('.propertycontainer').first(); - } - - /** - * Render the list item - * @return A jquery object to be inserted in the DOM - */ - Contact.prototype.renderListItem = function() { - this.$listelem = this.$listTemplate.octemplate({ - id: this.id, - name: this.getPreferredValue('FN', ''), - email: this.getPreferredValue('EMAIL', ''), - tel: this.getPreferredValue('TEL', ''), - adr: this.getPreferredValue('ADR', []).clean('').join(', '), - categories: this.getPreferredValue('CATEGORIES', []) - .clean('').join(' / '), - }); - return this.$listelem; - } - - /** - * Render the full contact - * @return A jquery object to be inserted in the DOM - */ - Contact.prototype.renderContact = function() { - var self = this; - console.log('renderContact', this.data); - var values = this.data - ? { - id: this.id, - name: this.getPreferredValue('FN', ''), - nickname: this.getPreferredValue('NICKNAME', ''), - title: this.getPreferredValue('TITLE', ''), - org: this.getPreferredValue('ORG', []).clean('').join(', '), // TODO Add parts if more than one. - bday: this.getPreferredValue('BDAY', '').length >= 10 - ? $.datepicker.formatDate('dd-mm-yy', - $.datepicker.parseDate('yy-mm-dd', - this.getPreferredValue('BDAY', '').substring(0, 10))) - : '', - } - : {id: '', name: '', nickname: '', title: '', org: '', bday: ''}; - this.$fullelem = this.$fullTemplate.octemplate(values).data('contactobject', this); - this.$fullelem.on('change', '#addproperty', function(event) { - console.log('add', $(this).val()); - $(this).val('') - }); - this.$fullelem.on('change', '.value', function(event) { - console.log('change', event); - self.save(self, event.target); - }); - this.$fullelem.find('form').on('submit', function(event) { - console.log('submit', event); - return false; - }); - this.$fullelem.find('[data-element="bday"]') - .find('input').datepicker({ - dateFormat : 'dd-mm-yy' - }); - if(!this.data) { - // A new contact - this.setEnabled(true); - return this.$fullelem; - } - for(var value in values) { - console.log(value); - if(!values[value].length) { - this.$fullelem.find('[data-element="' + value + '"]').hide(); - } - } - $.each(this.multi_properties, function(idx, name) { - if(self.data[name]) { - var $list = self.$fullelem.find('ul.' + name.toLowerCase()); - $list.show(); - for(var p in self.data[name]) { - if(typeof self.data[name][p] === 'object') { - var property = self.data[name][p]; - console.log(name, p, property); - $property = null; - switch(name) { - case 'TEL': - case 'URL': - case 'EMAIL': - $property = self.renderStandardProperty(name.toLowerCase(), property); - break; - case 'ADR': - $property = self.renderAddressProperty(property); - break; - case 'IMPP': - $property = self.renderIMProperty(property); - break; - } - if(!$property) { - continue; - } - //console.log('$property', $property); - if(property.label) { - if(!property.parameters['TYPE']) { - property.parameters['TYPE'] = []; - } - property.parameters['TYPE'].push(property.label); - } - for(var param in property.parameters) { - //console.log('param', param); - if(param.toUpperCase() == 'PREF') { - $property.find('input[type="checkbox"]').attr('checked', 'checked') - } - else if(param.toUpperCase() == 'TYPE') { - for(etype in property.parameters[param]) { - var found = false; - var et = property.parameters[param][etype]; - if(typeof et !== 'string') { - continue; - } - //console.log('et', et); - if(et.toUpperCase() === 'INTERNET') { - continue; - } - $property.find('select.type option').each(function() { - if($(this).val().toUpperCase() === et.toUpperCase()) { - $(this).attr('selected', 'selected'); - found = true; - } - }); - if(!found) { - $property.find('select.type option:last-child').after(''); - } - } - } - else if(param.toUpperCase() == 'X-SERVICE-TYPE') { - //console.log('setting', $property.find('select.impp'), 'to', property.parameters[param].toLowerCase()); - $property.find('select.impp').val(property.parameters[param].toLowerCase()); - } - } - $property.find('select.type[name="parameters[TYPE][]"]') - .combobox({ - singleclick: true, - classes: ['propertytype', 'float', 'label'], - }); - $list.append($property); - } - } - } - }); - if(this.access.owner !== OC.currentUser - && !(this.access.permissions & OC.PERMISSION_UPDATE - || this.access.permissions & OC.PERMISSION_DELETE)) { - this.setEnabled(false); - } - return this.$fullelem; - } - - /** - * Render a simple property. Used for EMAIL and TEL. - * @return A jquery object to be injected in the DOM - */ - Contact.prototype.renderStandardProperty = function(name, property) { - if(!this.detailTemplates[name]) { - console.log('No template for', name); - return; - } - var values = { value: property.value, checksum: property.checksum }; - $elem = this.detailTemplates[name].octemplate(values); - return $elem; - } - - /** - * Render an ADR (address) property. - * @return A jquery object to be injected in the DOM - */ - Contact.prototype.renderAddressProperty = function(property) { - if(!this.detailTemplates['adr']) { - console.log('No template for adr', this.detailTemplates); - return; - } - var values = { - value: property.value.clean('').join(', '), - checksum: property.checksum, - adr0: property.value[0] || '', - adr1: property.value[1] || '', - adr2: property.value[2] || '', - adr3: property.value[3] || '', - adr4: property.value[4] || '', - adr5: property.value[5] || '', - }; - $elem = this.detailTemplates['adr'].octemplate(values); - return $elem; - } - - /** - * Render an IMPP (Instant Messaging) property. - * @return A jquery object to be injected in the DOM - */ - Contact.prototype.renderIMProperty = function(property) { - if(!this.detailTemplates['impp']) { - console.log('No template for impp', this.detailTemplates); - return; - } - var values = { - value: property.value, - checksum: property.checksum, - }; - $elem = this.detailTemplates['impp'].octemplate(values); - return $elem; - } - /** - * Get the jquery element associated with this object - */ - Contact.prototype.getListItemElement = function() { - if(!this.$listelem) { - this.renderListItem(); - } - return this.$listelem; - } - - /** - * Get the preferred value for a property. - * If a preferred value is not found the first one will be returned. - * @param string name The name of the property like EMAIL, TEL or ADR. - * @param def A default value to return if nothing is found. - */ - Contact.prototype.getPreferredValue = function(name, def) { - var pref = def, found = false; - if(this.data[name]) { - var props = this.data[name]; - //console.log('props', props); - $.each(props, function( i, prop ) { - //console.log('prop:', i, prop); - if(i === 0) { // Choose first to start with - pref = prop.value; - } - for(var param in prop.parameters) { - if(param.toUpperCase() == 'PREF') { - found = true; // - break; - } - } - if(found) { - return false; // break out of loop - } - }); - } - return pref; - } - - var ContactList = function(contactlist, contactlistitemtemplate, contactfulltemplate, contactdetailtemplates) { - //console.log('ContactList', contactlist, contactlistitemtemplate, contactfulltemplate, contactdetailtemplates); - var self = this; - this.contacts = {}; - this.deletionQueue = []; - this.selectedContacts = []; - this.$contactList = contactlist; - this.$contactListItemTemplate = contactlistitemtemplate; - this.$contactFullTemplate = contactfulltemplate; - this.contactDetailTemplates = contactdetailtemplates; - this.$contactList.scrollTop(0); - this.loadContacts(0); - - } - - /** - * Show contacts in list - * @param Array contacts. A list of contact ids. - */ - ContactList.prototype.showContacts = function(contacts) { - for(var contact in this.contacts) { - if(contacts === 'all') { - this.contacts[contact].getListItemElement().show(); - } else { - contact = parseInt(contact); - if(contacts.indexOf(String(contact)) === -1) { - this.contacts[contact].getListItemElement().hide(); - } else { - this.contacts[contact].getListItemElement().show(); - } - } - } - } - - /** - * Jumps to an element in the contact list - * FIXME: Use cached contact element. - * @param number the number of the item starting with 0 - */ - ContactList.prototype.jumpToElemenId = function(id) { - $elem = $('tr.contact_item[data-id="' + id + '"]'); - this.$contactList.scrollTop( - $elem.offset().top - this.$contactList.offset().top - + this.$contactList.scrollTop()); - }; - - /** - * Returns a Contact object by searching for its id - * @param id the id of the node - * @return the Contact object or undefined if not found. - * FIXME: If continious loading is reintroduced this will have - * to load the requested contact. - */ - ContactList.prototype.findById = function(id) { - return this.contacts[parseInt(id)]; - }; - - ContactList.prototype.warnNotDeleted = function(e) { - e = e || window.event; - var warn = t('contacts', 'Some contacts are marked for deletion, but not deleted yet. Please wait for them to be deleted.'); - if (e) { - e.returnValue = String(warn); - } - if(OC.Contacts.Contacts.deletionQueue.length > 0) { - setTimeout(OC.Contacts.Contacts.deleteFilesInQueue, 1); - } - return warn; - } - - ContactList.prototype.delayedDeleteContact = function(id) { - var self = this; - var listelem = this.contacts[parseInt(id)].detach(); - self.$contactList.show(); - this.deletionQueue.push(parseInt(id)); - console.log('deletionQueue', this.deletionQueue, listelem); - if(!window.onbeforeunload) { - window.onbeforeunload = this.warnNotDeleted; - } - // TODO: Check if there are anymore contacts, otherwise show intro. - OC.Contacts.notify({ - data:listelem, - message:t('contacts','Click to undo deletion of "') + listelem.find('td.name').text() + '"', - //timeout:5, - timeouthandler:function(listelem) { - console.log('timeout', listelem); - self.deleteContact(listelem.data('id'), true); - }, - clickhandler:function(listelem) { - console.log('clickhandler', listelem); - self.insertContact(listelem); - OC.Contacts.notify({message:t('contacts', 'Cancelled deletion of: "') + listelem.find('td.name').text() + '"'}); - window.onbeforeunload = null; - } - }); - } - - /** - * Delete a contact with this id - * @param id the id of the contact - */ - ContactList.prototype.deleteContact = function(id, removeFromQueue) { - var self = this; - var id = parseInt(id); - console.log('deletionQueue', this.deletionQueue); - var updateQueue = function(id, remove) { - if(removeFromQueue) { - OC.Contacts.Contacts.deletionQueue.splice(OC.Contacts.Contacts.deletionQueue.indexOf(parseInt(id)), 1); - } - if(OC.Contacts.Contacts.deletionQueue.length == 0) { - window.onbeforeunload = null; - } - } - - if(OC.Contacts.Contacts.deletionQueue.indexOf(parseInt(id)) == -1 && removeFromQueue) { - console.log('returning'); - updateQueue(id, removeFromQueue); - if(typeof cb == 'function') { - window.onbeforeunload = null; - } - return; - } - - this.contacts[id].destroy(function(response) { - console.log('deleteContact', response); - if(response.status === 'success') { - delete self.contacts[parseInt(id)]; - updateQueue(id, removeFromQueue); - self.$contactList.show(); - window.onbeforeunload = null; - $(document).trigger('status.contact.deleted', { - id: id, - }); - } else { - OC.Contacts.notify({message:response.message}); - } - }); - } - - /** - * Opens the contact with this id in edit mode - * @param id the id of the contact - */ - ContactList.prototype.showContact = function(id) { - console.log('Contacts.showContact', id, this.contacts[parseInt(id)], this.contacts) - return this.contacts[parseInt(id)].renderContact(); - }; - - /** - * Toggle all checkboxes - */ - ContactList.prototype.toggleAll = function(toggler, togglees) { - var isChecked = $(toggler).is(':checked'); - console.log('toggleAll', isChecked, self); - $.each(togglees, function( i, item ) { - item.checked = isChecked; - }); - }; - - /** - * Insert a rendered contact list item into the list - * @param contact jQuery object. - */ - ContactList.prototype.insertContact = function(contact) { - //console.log('insertContact', contact); - var name = contact.find('td.name').text().toLowerCase(); - var added = false - this.$contactList.find('tr').each(function() { - if ($(this).find('td.name').text().toLowerCase().localeCompare(name) > 0) { - $(this).before(contact); - added = true; - return false; - } - }); - if(!added) { - this.$contactList.append(contact); - } - //this.contacts[id] = contact; - return contact; - } - - /** - * Add contact - * @param int offset - */ - ContactList.prototype.addContact = function() { - var contact = new Contact( - this, - null, - null, - null, - this.$contactListItemTemplate, - this.$contactFullTemplate, - this.contactDetailTemplates - ); - return contact.renderContact(); - } - /** - * Load contacts - * @param int offset - */ - ContactList.prototype.loadContacts = function(offset, cb) { - var self = this; - // Should the actual ajax call be in the controller? - $.getJSON(OC.filePath('contacts', 'ajax', 'contact/list.php'), {offset: offset}, function(jsondata) { - if (jsondata && jsondata.status == 'success') { - console.log('addressbooks', jsondata.data.addressbooks); - self.addressbooks = {}; - $.each(jsondata.data.addressbooks, function(i, book) { - self.addressbooks[parseInt(book.id)] = {owner: book.userid, permissions: parseInt(book.permissions)}; - }); - $.each(jsondata.data.contacts, function(c, contact) { - self.contacts[parseInt(contact.id)] - = new Contact( - self, - contact.id, - self.addressbooks[parseInt(contact.aid)], - contact.data, - self.$contactListItemTemplate, - self.$contactFullTemplate, - self.contactDetailTemplates - ); - var item = self.contacts[parseInt(contact.id)].renderListItem() - //self.$contactList.append(item); - self.insertContact(item); - }); - $(document).trigger('status.contacts.loaded', { - status: true, - numcontacts: jsondata.data.contacts.length - }); - } - if(typeof cb === 'function') { - cb(); - } - }); - } - OC.Contacts.ContactList = ContactList; - /** * Object Template @@ -908,6 +783,6 @@ OC.Contacts = OC.Contacts || { $(document).ready(function() { - OC.Contacts.init(); + OC.Contacts.init(id); }); diff --git a/js/contacts.js b/js/contacts.js index 640576f5..22bdc438 100644 --- a/js/contacts.js +++ b/js/contacts.js @@ -1,2332 +1,918 @@ -function ucwords (str) { - return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) { - return $1.toUpperCase(); - }); -} +OC.Contacts = OC.Contacts || {}; -String.prototype.strip_tags = function(){ - tags = this; - stripped = tags.replace(/<(.|\n)*?>/g, ''); - return stripped; -}; -OC.Contacts={ +(function( $ ) { + /** - * Arguments: - * message: The text message to show. - * timeout: The timeout in seconds before the notification disappears. Default 10. - * timeouthandler: A function to run on timeout. - * clickhandler: A function to run on click. If a timeouthandler is given it will be cancelled. - * data: An object that will be passed as argument to the timeouthandler and clickhandler functions. - * cancel: If set cancel all ongoing timer events and hide the notification. - */ - notify:function(params) { + * An item which binds the appropriate html and event handlers + * @param parent the parent ContactList + * @param id The integer contact id. + * @param access An access object containing and 'owner' string variable and an integer 'permissions' variable. + * @param data the data used to populate the contact + * @param listtemplate the jquery object used to render the contact list item + * @param fulltemplate the jquery object used to render the entire contact + * @param detailtemplates A map of jquery objects used to render the contact parts e.g. EMAIL, TEL etc. + */ + var Contact = function(parent, id, access, data, listtemplate, fulltemplate, detailtemplates) { + //console.log('contact:', id, access); //parent, id, data, listtemplate, fulltemplate); + this.parent = parent, + this.id = id, + this.access = access, + this.data = data, + this.$listTemplate = listtemplate, + this.$fullTemplate = fulltemplate; + this.detailTemplates = detailtemplates; var self = this; - if(!self.notifier) { - self.notifier = $('#notification'); - } - if(params.cancel) { - self.notifier.off('click'); - for(var id in self.notifier.data()) { - if($.isNumeric(id)) { - clearTimeout(parseInt(id)); - } - } - self.notifier.text('').fadeOut().removeData(); + this.multi_properties = ['EMAIL', 'TEL', 'IMPP', 'ADR', 'URL']; + } + + Contact.prototype.setAsSaving = function(obj, state) { + if(!obj) { return; } - self.notifier.text(params.message); - self.notifier.fadeIn(); - self.notifier.on('click', function() { $(this).fadeOut();}); - var timer = setTimeout(function() { - if(!self || !self.notifier) { - var self = OC.Contacts; - self.notifier = $('#notification'); - } - self.notifier.fadeOut(); - if(params.timeouthandler && $.isFunction(params.timeouthandler)) { - params.timeouthandler(self.notifier.data(dataid)); - self.notifier.off('click'); - self.notifier.removeData(dataid); - } - }, params.timeout && $.isNumeric(params.timeout) ? parseInt(params.timeout)*1000 : 10000); - var dataid = timer.toString(); - if(params.data) { - self.notifier.data(dataid, params.data); - } - if(params.clickhandler && $.isFunction(params.clickhandler)) { - self.notifier.on('click', function() { - if(!self || !self.notifier) { - var self = OC.Contacts; - self.notifier = $(this); - } - clearTimeout(timer); - self.notifier.off('click'); - params.clickhandler(self.notifier.data(dataid)); - self.notifier.removeData(dataid); - }); - } - }, - notImplemented:function() { - OC.dialogs.alert(t('contacts', 'Sorry, this functionality has not been implemented yet'), t('contacts', 'Not implemented')); - }, - searchOSM:function(obj) { - var adr = OC.Contacts.propertyContainerFor(obj).find('.adr').val(); - if(adr == undefined) { - OC.dialogs.alert(t('contacts', 'Couldn\'t get a valid address.'), t('contacts', 'Error')); - return; - } - // FIXME: I suck at regexp. /Tanghus - var adrarr = adr.split(';'); - var adrstr = ''; - if(adrarr[2].trim() != '') { - adrstr = adrstr + adrarr[2].trim() + ','; - } - if(adrarr[3].trim() != '') { - adrstr = adrstr + adrarr[3].trim() + ','; - } - if(adrarr[4].trim() != '') { - adrstr = adrstr + adrarr[4].trim() + ','; - } - if(adrarr[5].trim() != '') { - adrstr = adrstr + adrarr[5].trim() + ','; - } - if(adrarr[6].trim() != '') { - adrstr = adrstr + adrarr[6].trim(); - } - adrstr = encodeURIComponent(adrstr); - var uri = 'http://open.mapquestapi.com/nominatim/v1/search.php?q=' + adrstr + '&limit=10&addressdetails=1&polygon=1&zoom='; - var newWindow = window.open(uri,'_blank'); - newWindow.focus(); - }, - mailTo:function(obj) { - var adr = OC.Contacts.propertyContainerFor($(obj)).find('input[type="email"]').val().trim(); - if(adr == '') { - OC.dialogs.alert(t('contacts', 'Please enter an email address.'), t('contacts', 'Error')); - return; - } - window.location.href='mailto:' + adr; - }, - propertyContainerFor:function(obj) { - return $(obj).parents('.propertycontainer').first(); - }, - checksumFor:function(obj) { - return $(obj).parents('.propertycontainer').first().data('checksum'); - }, - propertyTypeFor:function(obj) { - return $(obj).parents('.propertycontainer').first().data('element'); - }, - loading:function(obj, state) { + $(obj).prop('disabled', state); if(state) { $(obj).addClass('loading'); } else { $(obj).removeClass('loading'); } - }, - showCardDAVUrl:function(username, bookname){ - $('#carddav_url').val(totalurl + '/' + username + '/' + decodeURIComponent(bookname)); - $('#carddav_url').show(); - $('#carddav_url_close').show(); - }, - loadListHandlers:function() { - $('.propertylist li a.delete').unbind('click'); - $('.propertylist li a.delete').unbind('keydown'); - var deleteItem = function(obj) { - obj.tipsy('hide'); - OC.Contacts.Card.deleteProperty(obj, 'list'); - } - $('.propertylist li a.delete, .addresscard .delete').click(function() { deleteItem($(this)) }); - $('.propertylist li a.delete, .addresscard .delete').keydown(function() { deleteItem($(this)) }); - $('.addresscard .globe').click(function() { $(this).tipsy('hide');OC.Contacts.searchOSM(this); }); - $('.addresscard .globe').keydown(function() { $(this).tipsy('hide');OC.Contacts.searchOSM(this); }); - $('.addresscard .edit').click(function() { $(this).tipsy('hide');OC.Contacts.Card.editAddress(this, false); }); - $('.addresscard .edit').keydown(function() { $(this).tipsy('hide');OC.Contacts.Card.editAddress(this, false); }); - $('.addresscard,.propertylist li,.propertycontainer').hover( - function () { - $(this).find('.globe,.mail,.delete,.edit').animate({ opacity: 1.0 }, 200, function() {}); - }, - function () { - $(this).find('.globe,.mail,.delete,.edit').animate({ opacity: 0.1 }, 200, function() {}); - } - ); - }, - loadHandlers:function() { - var deleteItem = function(obj) { - obj.tipsy('hide'); - OC.Contacts.Card.deleteProperty(obj, 'single'); - } - var goToUrl = function(obj) { - var url = OC.Contacts.propertyContainerFor(obj).find('#url').val(); - if(url != '') { - var newWindow = window.open(url,'_blank'); - newWindow.focus(); - } - } + } - $('#identityprops a.delete').click( function() { deleteItem($(this)) }); - $('#identityprops a.delete').keydown( function() { deleteItem($(this)) }); - $('#categories_value a.edit').click( function() { $(this).tipsy('hide');OCCategories.edit(); } ); - $('#categories_value a.edit').keydown( function() { $(this).tipsy('hide');OCCategories.edit(); } ); - $('#url_value a.globe').click( function() { $(this).tipsy('hide');goToUrl($(this)); } ); - $('#url_value a.globe').keydown( function() { $(this).tipsy('hide');goToUrl($(this)); } ); - $('#fn_select').combobox({ - 'id': 'fn', - 'name': 'value', - 'classes': ['contacts_property', 'nonempty', 'huge', 'tip', 'float'], - 'attributes': {'placeholder': t('contacts', 'Enter name')}, - 'title': t('contacts', 'Format custom, Short name, Full name, Reverse or Reverse with comma')}); - $('#bday').datepicker({ - dateFormat : 'dd-mm-yy' - }); - // Style phone types - $('#phonelist').find('select.contacts_property').multiselect({ - noneSelectedText: t('contacts', 'Select type'), - header: false, - selectedList: 4, - classes: 'typelist' - }); - $('#edit_name').click(function(){OC.Contacts.Card.editName()}); - $('#edit_name').keydown(function(){OC.Contacts.Card.editName()}); - - $('#phototools li a').click(function() { - $(this).tipsy('hide'); - }); - $('#contacts_details_photo_wrapper').hover( - function () { - $('#phototools').slideDown(200); - }, - function () { - $('#phototools').slideUp(200); - } - ); - $('#phototools').hover( - function () { - $(this).removeClass('transparent'); - }, - function () { - $(this).addClass('transparent'); - } - ); - $('#phototools .upload').click(function() { - $('#file_upload_start').trigger('click'); - }); - $('#phototools .cloud').click(function() { - OC.dialogs.filepicker(t('contacts', 'Select photo'), OC.Contacts.Card.cloudPhotoSelected, false, 'image', true); - }); - /* Initialize the photo edit dialog */ - $('#edit_photo_dialog').dialog({ - autoOpen: false, modal: true, height: 'auto', width: 'auto' - }); - $('#edit_photo_dialog' ).dialog( 'option', 'buttons', [ - { - text: "Ok", - click: function() { - OC.Contacts.Card.savePhoto(this); - $(this).dialog('close'); - } - }, - { - text: "Cancel", - click: function() { $(this).dialog('close'); } - } - ] ); - - // Name has changed. Update it and reorder. - $('#fn').change(function(){ - var name = $('#fn').val().strip_tags(); - var item = $('.contacts li[data-id="'+OC.Contacts.Card.id+'"]').detach(); - $(item).find('a').html(name); - OC.Contacts.Card.fn = name; - OC.Contacts.Contacts.insertContact({contact:item}); - OC.Contacts.Contacts.scrollTo(OC.Contacts.Card.id); - }); - - $('#contacts_deletecard').click( function() { OC.Contacts.Card.delayedDelete();return false;} ); - $('#contacts_deletecard').keydown( function(event) { - if(event.which == 13 || event.which == 32) { - OC.Contacts.Card.delayedDelete(); - } - return false; - }); - - $('#contacts_downloadcard').click( function() { OC.Contacts.Card.doExport();return false;} ); - $('#contacts_downloadcard').keydown( function(event) { - if(event.which == 13 || event.which == 32) { - OC.Contacts.Card.doExport(); - } - return false; - }); - - // Profile picture upload handling - // New profile picture selected - $('#file_upload_start').change(function(){ - OC.Contacts.Card.uploadPhoto(this.files); - }); - $('#contacts_details_photo_wrapper').bind('dragover',function(event){ - $(event.target).addClass('droppable'); - event.stopPropagation(); - event.preventDefault(); - }); - $('#contacts_details_photo_wrapper').bind('dragleave',function(event){ - $(event.target).removeClass('droppable'); - }); - $('#contacts_details_photo_wrapper').bind('drop',function(event){ - event.stopPropagation(); - event.preventDefault(); - $(event.target).removeClass('droppable'); - $.fileUpload(event.originalEvent.dataTransfer.files); - }); - - $('#categories').multiple_autocomplete({source: categories}); - $('#contacts_deletecard').tipsy({gravity: 'ne'}); - $('#contacts_downloadcard').tipsy({gravity: 'ne'}); - $('#contacts_propertymenu_button').tipsy(); - $('#bottomcontrols button').tipsy({gravity: 'sw'}); - - $('body').click(function(e){ - if(!$(e.target).is('#contacts_propertymenu_button')) { - $('#contacts_propertymenu_dropdown').hide(); - } - }); - function propertyMenu(){ - var menu = $('#contacts_propertymenu_dropdown'); - if(menu.is(':hidden')) { - menu.show(); - menu.find('li').first().focus(); - } else { - menu.hide(); - } - } - $('#contacts_propertymenu_button').click(propertyMenu); - $('#contacts_propertymenu_button').keydown(propertyMenu); - function propertyMenuItem(){ - var type = $(this).data('type'); - OC.Contacts.Card.addProperty(type); - $('#contacts_propertymenu_dropdown').hide(); - } - $('#contacts_propertymenu_dropdown a').click(propertyMenuItem); - $('#contacts_propertymenu_dropdown a').keydown(propertyMenuItem); - }, - Card:{ - update:function(params) { // params {cid:int, aid:int} - if(!params) { params = {}; } - $('#contacts li,#contacts h3').removeClass('active'); - //console.log('Card, cid: ' + params.cid + ' aid: ' + params.aid); - var newid, bookid, firstitem; - if(!parseInt(params.cid) && !parseInt(params.aid)) { - firstitem = $('#contacts ul').find('li:first-child'); - if(firstitem.length > 0) { - if(firstitem.length > 1) { - firstitem = firstitem.first(); - } - newid = parseInt(firstitem.data('id')); - bookid = parseInt(firstitem.data('bookid')); - } - } else if(!parseInt(params.cid) && parseInt(params.aid)) { - bookid = parseInt(params.aid); - newid = parseInt($('#contacts').find('li[data-bookid="'+bookid+'"]').first().data('id')); - } else if(parseInt(params.cid) && !parseInt(params.aid)) { - newid = parseInt(params.cid); - var listitem = OC.Contacts.Contacts.getContact(newid); //$('#contacts li[data-id="'+newid+'"]'); - //console.log('Is contact in list? ' + listitem.length); - if(listitem.length) { - //bookid = parseInt($('#contacts li[data-id="'+newid+'"]').data('bookid')); - bookid = parseInt(OC.Contacts.Contacts.getContact(newid).data('bookid')); - } else { // contact isn't in list yet. - bookid = 'unknown'; - } - } else { - newid = parseInt(params.cid); - bookid = parseInt(params.aid); - } - if(!bookid || !newid) { - bookid = parseInt($('#contacts h3.addressbook').first().data('id')); - newid = parseInt($('#contacts').find('li[data-bookid="'+bookid+'"]').first().data('id')); - } - //console.log('newid: ' + newid + ' bookid: ' +bookid); - var localLoadContact = function(newid, bookid) { - if($('.contacts li').length > 0) { - $.getJSON(OC.filePath('contacts', 'ajax', 'contact/details.php'),{'id':newid},function(jsondata){ - if(jsondata.status == 'success'){ - if(bookid == 'unknown') { - bookid = jsondata.data.addressbookid; - var contact = OC.Contacts.Contacts.insertContact({ - contactlist:$('#contacts ul[data-id="'+bookid+'"]'), - data:jsondata.data - }); - } - $('#contacts li[data-id="'+newid+'"],#contacts h3.addressbook[data-id="'+bookid+'"]').addClass('active'); - $('#contacts ul[data-id="'+bookid+'"]').slideDown(300); - OC.Contacts.Card.loadContact(jsondata.data, bookid); - OC.Contacts.Contacts.scrollTo(newid); - } else { - OC.dialogs.alert(jsondata.data.message, t('contacts', 'Error')); - } - }); - } - } - - // Make sure proper DOM is loaded. - if(newid) { - //console.log('Loading card DOM'); - localLoadContact(newid, bookid); - $('#firstrun').hide(); - $('#card').show(); - } else if(!newid) { - //console.log('Loading intro'); - // show intro page - $('#firstrun').show(); - $('#card').hide(); - } - $('#contacts h3.addressbook[data-id="'+bookid+'"]').addClass('active'); - }, - setEnabled:function(enabled) { - //console.log('setEnabled', enabled); - $('.contacts_property,.action').each(function () { - $(this).prop('disabled', !enabled); - OC.Contacts.Card.enabled = enabled; - }); - }, - doExport:function() { - document.location.href = OC.linkTo('contacts', 'export.php') + '?contactid=' + this.id; - }, - editNew:function(){ // add a new contact - var book = $('#contacts h3.active'); - var permissions = parseInt(book.data('permissions')); - if(permissions == 0 - || permissions & OC.PERMISSION_UPDATE - || permissions & OC.PERMISSION_DELETE) { - with(this) { - delete id; delete fn; delete fullname; delete givname; delete famname; - delete addname; delete honpre; delete honsuf; - } - this.bookid = book.data('id'); - OC.Contacts.Card.add(';;;;;', '', '', true); - } else { - OC.dialogs.alert(t('contacts', 'You do not have permission to add contacts to ') - + book.text() + '. ' + t('contacts', 'Please select one of your own address books.'), t('contacts', 'Permission error')); - } - return false; - }, - add:function(n, fn, aid, isnew) { // add a new contact - //console.log('Adding ' + fn); - $('#firstrun').hide(); - $('#card').show(); - aid = aid?aid:$('#contacts h3.addressbook.active').first().data('id'); - $.post(OC.filePath('contacts', 'ajax', 'contact/add.php'), { n: n, fn: fn, aid: aid, isnew: isnew }, - function(jsondata) { - if (jsondata.status == 'success'){ - $('#rightcontent').data('id',jsondata.data.id); - var id = jsondata.data.id; - var aid = jsondata.data.aid; - $.getJSON(OC.filePath('contacts', 'ajax', 'contact/details.php'),{'id':id},function(jsondata){ - if(jsondata.status == 'success'){ - OC.Contacts.Card.loadContact(jsondata.data, aid); - var item = OC.Contacts.Contacts.insertContact({data:jsondata.data}); - $('#contacts li').removeClass('active'); - item.addClass('active'); - if(isnew) { // add some default properties - OC.Contacts.Card.addProperty('EMAIL'); - OC.Contacts.Card.addProperty('TEL'); - $('#fn').focus(); - } - } - else{ - OC.dialogs.alert(jsondata.data.message, t('contacts', 'Error')); - } - }); - $('#contact_identity').show(); - $('#actionbar').show(); - } - else{ - OC.dialogs.alert(jsondata.data.message, t('contacts', 'Error')); - } - }); - }, - delayedDelete:function() { - $('#contacts_deletecard').tipsy('hide'); - var newid = '', bookid; - var curlistitem = OC.Contacts.Contacts.getContact(this.id); - curlistitem.removeClass('active'); - var newlistitem = curlistitem.prev('li'); - if(!newlistitem) { - newlistitem = curlistitem.next('li'); - } - curlistitem.detach(); - if($(newlistitem).is('li')) { - newid = newlistitem.data('id'); - bookid = newlistitem.data('bookid'); - } - $('#rightcontent').data('id', newid); - - OC.Contacts.Contacts.deletionQueue.push(parseInt(this.id)); - if(!window.onbeforeunload) { - window.onbeforeunload = OC.Contacts.Contacts.warnNotDeleted; - } - - with(this) { - delete id; delete fn; delete fullname; delete shortname; delete famname; - delete givname; delete addname; delete honpre; delete honsuf; delete data; - } - - if($('.contacts li').length > 0) { - OC.Contacts.Card.update({cid:newid, aid:bookid}); - } else { - // load intro page - $('#firstrun').show(); - $('#card').hide(); - } - OC.Contacts.notify({ - data:curlistitem, - message:t('contacts','Click to undo deletion of "') + curlistitem.find('a').text() + '"', - //timeout:5, - timeouthandler:function(contact) { - //console.log('timeout'); - OC.Contacts.Card.doDelete(contact.data('id'), true, function(res) { - if(!res) { - OC.Contacts.Contacts.insertContact({contact:contact}); - } else { - delete contact; - } - }); - }, - clickhandler:function(contact) { - OC.Contacts.Contacts.insertContact({contact:contact}); - OC.Contacts.notify({message:t('contacts', 'Cancelled deletion of: "') + curlistitem.find('a').text() + '"'}); - window.onbeforeunload = null; - } - }); - }, - doDelete:function(id, removeFromQueue, cb) { - var updateQueue = function(id, remove) { - if(removeFromQueue) { - OC.Contacts.Contacts.deletionQueue.splice(OC.Contacts.Contacts.deletionQueue.indexOf(parseInt(id)), 1); - } - if(OC.Contacts.Contacts.deletionQueue.length == 0) { - window.onbeforeunload = null; - } - } - - if(OC.Contacts.Contacts.deletionQueue.indexOf(parseInt(id)) == -1 && removeFromQueue) { - //console.log('returning'); - updateQueue(id, removeFromQueue); - if(typeof cb == 'function') { - cb(true); - } - return; - } - $.post(OC.filePath('contacts', 'ajax', 'contact/delete.php'), {'id':id},function(jsondata) { - if(jsondata.status == 'error'){ - OC.Contacts.notify({message:jsondata.data.message}); - if(typeof cb == 'function') { - cb(false); - } - } - updateQueue(id, removeFromQueue); - }); - if(typeof cb == 'function') { - cb(true); - } - }, - loadContact:function(jsondata, bookid){ - this.data = jsondata; - this.id = this.data.id; - this.bookid = bookid; - $('#rightcontent').data('id',this.id); - this.populateNameFields(); - this.loadPhoto(); - this.loadMails(); - this.loadPhones(); - this.loadIMs(); - this.loadAddresses(); - this.loadSingleProperties(); - OC.Contacts.loadListHandlers(); - var note = $('#note'); - if(this.data.NOTE) { - note.data('checksum', this.data.NOTE[0]['checksum']); - var textarea = note.find('textarea'); - var txt = this.data.NOTE[0]['value']; - var nheight = txt.split('\n').length > 4 ? txt.split('\n').length+2 : 5; - textarea.css('min-height', nheight+'em'); - textarea.attr('rows', nheight); - textarea.val(txt); - $('#contact_note').show(); - textarea.expandingTextarea(); - $('#contacts_propertymenu_dropdown a[data-type="NOTE"]').parent().hide(); - } else { - note.removeData('checksum'); - note.find('textarea').val(''); - $('#contact_note').hide(); - $('#contacts_propertymenu_dropdown a[data-type="NOTE"]').parent().show(); - } - var permissions = OC.Contacts.Card.permissions = parseInt(this.data.permissions); - //console.log('permissions', permissions); - this.setEnabled(permissions == 0 - || permissions & OC.PERMISSION_UPDATE - || permissions & OC.PERMISSION_DELETE); - }, - loadSingleProperties:function() { - var props = ['BDAY', 'NICKNAME', 'ORG', 'URL', 'CATEGORIES']; - // Clear all elements - $('#ident .propertycontainer').each(function(){ - if(props.indexOf($(this).data('element')) > -1) { - $(this).data('checksum', ''); - $(this).find('input').val(''); - $(this).hide(); - $(this).prev().hide(); - } - }); - for(var prop in props) { - var propname = props[prop]; - if(this.data[propname] != undefined) { - $('#contacts_propertymenu_dropdown a[data-type="'+propname+'"]').parent().hide(); - var property = this.data[propname][0]; - var value = property['value'], checksum = property['checksum']; - - if(propname == 'BDAY') { - var val = $.datepicker.parseDate('yy-mm-dd', value.substring(0, 10)); - value = $.datepicker.formatDate('dd-mm-yy', val); - } - var identcontainer = $('#contact_identity'); - identcontainer.find('#'+propname.toLowerCase()).val(value); - identcontainer.find('#'+propname.toLowerCase()+'_value').data('checksum', checksum); - identcontainer.find('#'+propname.toLowerCase()+'_label').show(); - identcontainer.find('#'+propname.toLowerCase()+'_value').show(); - } else { - $('#contacts_propertymenu_dropdown a[data-type="'+propname+'"]').parent().show(); - } - } - }, - populateNameFields:function() { - var props = ['FN', 'N']; - // Clear all elements - $('#ident .propertycontainer').each(function(){ - if(props.indexOf($(this).data('element')) > -1) { - $(this).data('checksum', ''); - $(this).find('input').val(''); - } - }); - - with(this) { - delete fn; delete fullname; delete givname; delete famname; - delete addname; delete honpre; delete honsuf; - } - - if(this.data.FN) { - this.fn = this.data.FN[0]['value']; - } - else { - this.fn = ''; - } - if(this.data.N == undefined) { - narray = [this.fn,'','','','']; // Checking for non-existing 'N' property :-P - } else { - narray = this.data.N[0]['value']; - } - this.famname = narray[0] || ''; - this.givname = narray[1] || ''; - this.addname = narray[2] || ''; - this.honpre = narray[3] || ''; - this.honsuf = narray[4] || ''; - if(this.honpre.length > 0) { - this.fullname += this.honpre + ' '; - } - if(this.givname.length > 0) { - this.fullname += ' ' + this.givname; - } - if(this.addname.length > 0) { - this.fullname += ' ' + this.addname; - } - if(this.famname.length > 0) { - this.fullname += ' ' + this.famname; - } - if(this.honsuf.length > 0) { - this.fullname += ', ' + this.honsuf; - } - $('#n').val(narray.join(';')); - $('#fn_select option').remove(); - var names = [this.fn, this.fullname, this.givname + ' ' + this.famname, this.famname + ' ' + this.givname, this.famname + ', ' + this.givname]; - if(this.data.ORG) { - names.push(this.data.ORG[0].value); - } - $.each($.unique(names), function(key, value) { - $('#fn_select') - .append($('') - .text(value)); - }); - $('#fn_select').combobox('value', this.fn); - $('#contact_identity').find('*[data-element="N"]').data('checksum', this.data.N[0]['checksum']); - if(this.data.FN) { - $('#contact_identity').find('*[data-element="FN"]').data('checksum', this.data.FN[0]['checksum']); - } - $('#contact_identity').show(); - }, - hasCategory:function(category) { - if(this.data.CATEGORIES) { - var categories = this.data.CATEGORIES[0]['value'].split(/,\s*/); - for(var c in categories) { - var cat = this.data.CATEGORIES[0]['value'][c]; - if(typeof cat === 'string' && (cat.toUpperCase() === category.toUpperCase())) { - return true; - } - } - } - return false; - }, - categoriesChanged:function(newcategories) { // Categories added/deleted. - categories = $.map(newcategories, function(v) {return v;}); - $('#categories').multiple_autocomplete('option', 'source', categories); - var categorylist = $('#categories_value').find('input'); - $.getJSON(OC.filePath('contacts', 'ajax', 'categories/categoriesfor.php'),{'id':OC.Contacts.Card.id},function(jsondata){ - if(jsondata.status == 'success'){ - $('#categories_value').data('checksum', jsondata.data.checksum); - categorylist.val(jsondata.data.value); - } else { - OC.dialogs.alert(jsondata.data.message, t('contacts', 'Error')); - } - }); - }, - savePropertyInternal:function(name, fields, oldchecksum, checksum) { - // TODO: Add functionality for new fields. - //console.log('savePropertyInternal: ' + name + ', fields: ' + fields + 'checksum: ' + checksum); - //console.log('savePropertyInternal: ' + this.data[name]); - var multivalue = ['CATEGORIES']; - var params = {}; - var value = multivalue.indexOf(name) != -1 ? new Array() : undefined; - jQuery.each(fields, function(i, field){ - //.substring(11,'parameters[TYPE][]'.indexOf(']')) - if(field.name.substring(0, 5) === 'value') { - if(multivalue.indexOf(name) != -1) { - value.push(field.value); - } else { - value = field.value; - } - } else if(field.name.substring(0, 10) === 'parameters') { - var p = field.name.substring(11,'parameters[TYPE][]'.indexOf(']')); - if(!(p in params)) { - params[p] = []; - } - params[p].push(field.value); - } - }); - for(var i in this.data[name]) { - if(this.data[name][i]['checksum'] == oldchecksum) { - this.data[name][i]['checksum'] = checksum; - this.data[name][i]['value'] = value; - this.data[name][i]['parameters'] = params; - } - } - }, - saveProperty:function(obj) { - if(!$(obj).hasClass('contacts_property')) { - return false; - } - if($(obj).hasClass('nonempty') && $(obj).val().trim() == '') { - OC.dialogs.alert(t('contacts', 'This property has to be non-empty.'), t('contacts', 'Error')); - return false; - } - container = $(obj).parents('.propertycontainer').first(); // get the parent holding the metadata. - OC.Contacts.loading(obj, true); - var checksum = container.data('checksum'); - var name = container.data('element'); - var fields = container.find('input.contacts_property,select.contacts_property').serializeArray(); - switch(name) { - case 'FN': - var nempty = true; - for(var i in OC.Contacts.Card.data.N[0]['value']) { - if(OC.Contacts.Card.data.N[0]['value'][i] != '') { - nempty = false; - break; - } - } - if(nempty) { - $('#n').val(fields[0].value + ';;;;'); - OC.Contacts.Card.data.N[0]['value'] = Array(fields[0].value, '', '', '', ''); - setTimeout(function() {OC.Contacts.Card.saveProperty($('#n'))}, 500); - } - break; - } - var q = container.find('input.contacts_property,select.contacts_property,textarea.contacts_property').serialize(); - if(q == '' || q == undefined) { - OC.dialogs.alert(t('contacts', 'Couldn\'t serialize elements.'), t('contacts', 'Error')); - OC.Contacts.loading(obj, false); - return false; - } - q = q + '&id=' + this.id + '&name=' + name; - if(checksum != undefined && checksum != '') { // save - q = q + '&checksum=' + checksum; - //console.log('Saving: ' + q); - $(obj).attr('disabled', 'disabled'); - $.post(OC.filePath('contacts', 'ajax', 'contact/saveproperty.php'),q,function(jsondata){ - if(!jsondata) { - OC.dialogs.alert(t('contacts', 'Unknown error. Please check logs.'), t('contacts', 'Error')); - OC.Contacts.loading(obj, false); - $(obj).removeAttr('disabled'); - OC.Contacts.Card.update({cid:OC.Contacts.Card.id}); - return false; - } - if(jsondata.status == 'success'){ - container.data('checksum', jsondata.data.checksum); - OC.Contacts.Card.savePropertyInternal(name, fields, checksum, jsondata.data.checksum); - OC.Contacts.loading(obj, false); - $(obj).removeAttr('disabled'); - return true; - } - else{ - OC.dialogs.alert(jsondata.data.message, t('contacts', 'Error')); - OC.Contacts.loading(obj, false); - $(obj).removeAttr('disabled'); - OC.Contacts.Card.update({cid:OC.Contacts.Card.id}); - return false; - } - },'json'); - } else { // add - //console.log('Adding: ' + q); - $(obj).attr('disabled', 'disabled'); - $.post(OC.filePath('contacts', 'ajax', 'contact/addproperty.php'),q,function(jsondata){ - if(jsondata.status == 'success'){ - container.data('checksum', jsondata.data.checksum); - // TODO: savePropertyInternal doesn't know about new fields - //OC.Contacts.Card.savePropertyInternal(name, fields, checksum, jsondata.data.checksum); - OC.Contacts.loading(obj, false); - $(obj).removeAttr('disabled'); - return true; - } - else{ - OC.dialogs.alert(jsondata.data.message, t('contacts', 'Error')); - OC.Contacts.loading(obj, false); - $(obj).removeAttr('disabled'); - OC.Contacts.Card.update({cid:OC.Contacts.Card.id}); - return false; - } - },'json'); - } - }, - addProperty:function(type) { - if(!this.enabled) { - return; - } - switch (type) { - case 'NOTE': - $('#contacts_propertymenu_dropdown a[data-type="'+type+'"]').parent().hide(); - $('#note').find('textarea').expandingTextarea().show().focus(); - $('#contact_note').show(); - break; - case 'EMAIL': - if($('#emaillist>li').length == 1) { - $('#emails').show(); - } - OC.Contacts.Card.addMail(); - break; - case 'TEL': - if($('#phonelist>li').length == 1) { - $('#phones').show(); - } - OC.Contacts.Card.addPhone(); - break; - case 'IMPP': - if($('#imlist>li').length == 1) { - $('#ims').show(); - } - OC.Contacts.Card.addIM(); - break; - case 'ADR': - if($('addresses>dl').length == 1) { - $('#addresses').show(); - } - OC.Contacts.Card.editAddress('new', true); - break; - case 'NICKNAME': - case 'URL': - case 'ORG': - case 'BDAY': - case 'CATEGORIES': - $('dl dt[data-element="'+type+'"],dd[data-element="'+type+'"]').show(); - $('dd[data-element="'+type+'"]').find('input').focus(); - $('#contacts_propertymenu_dropdown a[data-type="'+type+'"]').parent().hide(); - break; - } - }, - deleteProperty:function(obj, type) { - //console.log('deleteProperty'); - if(!this.enabled) { - return; - } - OC.Contacts.loading(obj, true); - var checksum = OC.Contacts.checksumFor(obj); - if(checksum) { - $.post(OC.filePath('contacts', 'ajax', 'contact/deleteproperty.php'),{'id': this.id, 'checksum': checksum },function(jsondata){ - if(jsondata.status == 'success'){ - if(type == 'list') { - OC.Contacts.propertyContainerFor(obj).remove(); - } else if(type == 'single') { - var proptype = OC.Contacts.propertyTypeFor(obj); - OC.Contacts.Card.data[proptype] = null; - var othertypes = ['NOTE', 'PHOTO']; - if(othertypes.indexOf(proptype) != -1) { - OC.Contacts.propertyContainerFor(obj).data('checksum', ''); - if(proptype == 'PHOTO') { - OC.Contacts.Contacts.refreshThumbnail(OC.Contacts.Card.id); - OC.Contacts.Card.loadPhoto(); - } else if(proptype == 'NOTE') { - $('#note').find('textarea').val(''); - $('#contact_note').hide(); - OC.Contacts.propertyContainerFor(obj).hide(); - } - } else { - $('dl dt[data-element="'+proptype+'"],dd[data-element="'+proptype+'"]').hide(); - $('dl dd[data-element="'+proptype+'"]').data('checksum', '').find('input').val(''); - } - $('#contacts_propertymenu_dropdown a[data-type="'+proptype+'"]').parent().show(); - OC.Contacts.loading(obj, false); - } else { - OC.dialogs.alert(t('contacts', '\'deleteProperty\' called without type argument. Please report at bugs.owncloud.org'), t('contacts', 'Error')); - OC.Contacts.loading(obj, false); - } - } - else{ - OC.Contacts.loading(obj, false); - OC.dialogs.alert(jsondata.data.message, t('contacts', 'Error')); - } - }); - } else { // Property hasn't been saved so there's nothing to delete. - if(type == 'list') { - OC.Contacts.propertyContainerFor(obj).remove(); - } else if(type == 'single') { - var proptype = OC.Contacts.propertyTypeFor(obj); - $('dl dt[data-element="'+proptype+'"],dd[data-element="'+proptype+'"]').hide(); - $('#contacts_propertymenu_dropdown a[data-type="'+proptype+'"]').parent().show(); - OC.Contacts.loading(obj, false); - } else { - OC.dialogs.alert(t('contacts', '\'deleteProperty\' called without type argument. Please report at bugs.owncloud.org'), t('contacts', 'Error')); - } - } - }, - editName:function() { - if(!this.enabled) { - return; - } - var params = {id: this.id}; - /* Initialize the name edit dialog */ - if($('#edit_name_dialog').dialog('isOpen') == true) { - $('#edit_name_dialog').dialog('moveToTop'); - } else { - $.getJSON(OC.filePath('contacts', 'ajax', 'editname.php'),{id: this.id},function(jsondata) { - if(jsondata.status == 'success') { - $('body').append('
    '); - $('#name_dialog').html(jsondata.data.page).find('#edit_name_dialog' ).dialog({ - modal: true, - closeOnEscape: true, - title: t('contacts', 'Edit name'), - height: 'auto', width: 'auto', - buttons: { - 'Ok':function() { - OC.Contacts.Card.saveName(this); - $(this).dialog('close'); - }, - 'Cancel':function() { $(this).dialog('close'); } - }, - close: function(event, ui) { - $(this).dialog('destroy').remove(); - $('#name_dialog').remove(); - }, - open: function(event, ui) { - // load 'N' property - maybe :-P - } - }); - } else { - OC.dialogs.alert(jsondata.data.message, t('contacts', 'Error')); - } - }); - } - }, - saveName:function(dlg) { - if(!this.enabled) { - return; - } - //console.log('saveName, id: ' + this.id); - var n = new Array($(dlg).find('#fam').val().strip_tags(),$(dlg).find('#giv').val().strip_tags(),$(dlg).find('#add').val().strip_tags(),$(dlg).find('#pre').val().strip_tags(),$(dlg).find('#suf').val().strip_tags()); - this.famname = n[0]; - this.givname = n[1]; - this.addname = n[2]; - this.honpre = n[3]; - this.honsuf = n[4]; - this.fullname = ''; - - $('#n').val(n.join(';')); - if(n[3].length > 0) { - this.fullname = n[3] + ' '; - } - this.fullname += n[1] + ' ' + n[2] + ' ' + n[0]; - if(n[4].length > 0) { - this.fullname += ', ' + n[4]; - } - - $('#fn_select option').remove(); - //$('#fn_select').combobox('value', this.fn); - var tmp = [this.fullname, this.givname + ' ' + this.famname, this.famname + ' ' + this.givname, this.famname + ', ' + this.givname]; - var names = new Array(); - for(var name in tmp) { - if(tmp[name] && names.indexOf(tmp[name]) == -1) { - names.push(tmp[name]); - } - } - $.each($.unique(names), function(key, value) { - $('#fn_select') - .append($('') - .text(value)); - }); - - if(this.id == '') { - var aid = $(dlg).find('#aid').val(); - OC.Contacts.Card.add(n.join(';'), $('#short').text(), aid); - } else { - OC.Contacts.Card.saveProperty($('#n')); - } - }, - loadAddresses:function() { - $('#addresses').hide(); - $('#addresses dl.propertycontainer').remove(); - var addresscontainer = $('#addresses'); - for(var adr in this.data.ADR) { - addresscontainer.find('dl').first().clone().insertAfter($('#addresses dl').last()).show(); - addresscontainer.find('dl').last().removeClass('template').addClass('propertycontainer'); - addresscontainer.find('dl').last().data('checksum', this.data.ADR[adr]['checksum']); - var adrarray = this.data.ADR[adr]['value']; - var adrtxt = ''; - if(adrarray[0] && adrarray[0].length > 0) { - adrtxt = adrtxt + '
  • ' + adrarray[0].strip_tags() + '
  • '; - } - if(adrarray[1] && adrarray[1].length > 0) { - adrtxt = adrtxt + '
  • ' + adrarray[1].strip_tags() + '
  • '; - } - if(adrarray[2] && adrarray[2].length > 0) { - adrtxt = adrtxt + '
  • ' + adrarray[2].strip_tags() + '
  • '; - } - if((3 in adrarray && 5 in adrarray) && adrarray[3].length > 0 || adrarray[5].length > 0) { - adrtxt = adrtxt + '
  • ' + adrarray[5].strip_tags() + ' ' + adrarray[3].strip_tags() + '
  • '; - } - if(adrarray[4] && adrarray[4].length > 0) { - adrtxt = adrtxt + '
  • ' + adrarray[4].strip_tags() + '
  • '; - } - if(adrarray[6] && adrarray[6].length > 0) { - adrtxt = adrtxt + '
  • ' + adrarray[6].strip_tags() + '
  • '; - } - addresscontainer.find('dl').last().find('.addresslist').html(adrtxt); - var types = new Array(); - var ttypes = new Array(); - for(var param in this.data.ADR[adr]['parameters']) { - if(param.toUpperCase() == 'TYPE') { - types.push(t('contacts', ucwords(this.data.ADR[adr]['parameters'][param].toLowerCase()))); - ttypes.push(this.data.ADR[adr]['parameters'][param]); - } - } - addresscontainer.find('dl').last().find('.adr_type_label').text(types.join('/')); - addresscontainer.find('dl').last().find('.adr_type').val(ttypes.join(',')); - addresscontainer.find('dl').last().find('.adr').val(adrarray.join(';')); - addresscontainer.find('dl').last().data('checksum', this.data.ADR[adr]['checksum']); - } - if(addresscontainer.find('dl').length > 1) { - $('#addresses').show(); - } - return false; - }, - editAddress:function(obj, isnew){ - if(!this.enabled) { - return; - } - var container = undefined; - var params = {id: this.id}; - if(obj === 'new') { - isnew = true; - $('#addresses dl').first().clone(true).insertAfter($('#addresses dl').last()).show(); - container = $('#addresses dl').last(); - container.removeClass('template').addClass('propertycontainer'); - } else { - params['checksum'] = OC.Contacts.checksumFor(obj); - } - /* Initialize the address edit dialog */ - if($('#edit_address_dialog').dialog('isOpen') == true){ - $('#edit_address_dialog').dialog('moveToTop'); - }else{ - $.getJSON(OC.filePath('contacts', 'ajax', 'editaddress.php'),params,function(jsondata){ - if(jsondata.status == 'success'){ - $('body').append('
    '); - $('#address_dialog').html(jsondata.data.page).find('#edit_address_dialog' ).dialog({ - height: 'auto', width: 'auto', - buttons: { - 'Ok':function() { - if(isnew) { - OC.Contacts.Card.saveAddress(this, $('#addresses dl:last-child').find('input').first(), isnew); - } else { - OC.Contacts.Card.saveAddress(this, obj, isnew); - } - $(this).dialog('close'); - }, - 'Cancel':function() { - $(this).dialog('close'); - if(isnew) { - container.remove(); - } - } - }, - close : function(event, ui) { - $(this).dialog('destroy').remove(); - $('#address_dialog').remove(); - }, - open : function(event, ui) { - $( "#adr_city" ).autocomplete({ - source: function( request, response ) { - $.ajax({ - url: "http://ws.geonames.org/searchJSON", - dataType: "jsonp", - data: { - featureClass: "P", - style: "full", - maxRows: 12, - lang: lang, - name_startsWith: request.term - }, - success: function( data ) { - response( $.map( data.geonames, function( item ) { - return { - label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName, - value: item.name, - country: item.countryName - } - })); - } - }); - }, - minLength: 2, - select: function( event, ui ) { - if(ui.item && $('#adr_country').val().trim().length == 0) { - $('#adr_country').val(ui.item.country); - } - }, - open: function() { - $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" ); - }, - close: function() { - $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" ); - } - }); - $('#adr_country').autocomplete({ - source: function( request, response ) { - $.ajax({ - url: "http://ws.geonames.org/searchJSON", - dataType: "jsonp", - data: { - /*featureClass: "A",*/ - featureCode: "PCLI", - /*countryBias: "true",*/ - /*style: "full",*/ - lang: lang, - maxRows: 12, - name_startsWith: request.term - }, - success: function( data ) { - response( $.map( data.geonames, function( item ) { - return { - label: item.name, - value: item.name - } - })); - } - }); - }, - minLength: 2, - select: function( event, ui ) { - /*if(ui.item) { - $('#adr_country').val(ui.item.country); - } - log( ui.item ? - "Selected: " + ui.item.label : - "Nothing selected, input was " + this.value);*/ - }, - open: function() { - $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" ); - }, - close: function() { - $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" ); - } - }); - } - }); - } else { - alert(jsondata.data.message); - } - }); - } - }, - saveAddress:function(dlg, obj, isnew){ - if(!this.enabled) { - return; - } - if(isnew) { - container = $('#addresses dl').last(); - obj = container.find('input').first(); - } else { - checksum = OC.Contacts.checksumFor(obj); - container = OC.Contacts.propertyContainerFor(obj); - } - var adr = new Array( - $(dlg).find('#adr_pobox').val().strip_tags(), - $(dlg).find('#adr_extended').val().strip_tags(), - $(dlg).find('#adr_street').val().strip_tags(), - $(dlg).find('#adr_city').val().strip_tags(), - $(dlg).find('#adr_region').val().strip_tags(), - $(dlg).find('#adr_zipcode').val().strip_tags(), - $(dlg).find('#adr_country').val().strip_tags() - ); - container.find('.adr').val(adr.join(';')); - container.find('.adr_type').val($(dlg).find('#adr_type').val()); - container.find('.adr_type_label').html(t('contacts',ucwords($(dlg).find('#adr_type').val().toLowerCase()))); - OC.Contacts.Card.saveProperty($(container).find('input').first()); - var adrtxt = ''; - if(adr[0].length > 0) { - adrtxt = adrtxt + '
  • ' + adr[0] + '
  • '; - } - if(adr[1].length > 0) { - adrtxt = adrtxt + '
  • ' + adr[1] + '
  • '; - } - if(adr[2].length > 0) { - adrtxt = adrtxt + '
  • ' + adr[2] + '
  • '; - } - if(adr[3].length > 0 || adr[5].length > 0) { - adrtxt = adrtxt + '
  • ' + adr[5] + ' ' + adr[3] + '
  • '; - } - if(adr[4].length > 0) { - adrtxt = adrtxt + '
  • ' + adr[4] + '
  • '; - } - if(adr[6].length > 0) { - adrtxt = adrtxt + '
  • ' + adr[6] + '
  • '; - } - container.find('.addresslist').html(adrtxt); - }, - uploadPhoto:function(filelist) { - if(!this.enabled) { - return; - } - if(!filelist) { - OC.dialogs.alert(t('contacts','No files selected for upload.'), t('contacts', 'Error')); - return; - } - var file = filelist[0]; - var target = $('#file_upload_target'); - var form = $('#file_upload_form'); - var totalSize=0; - if(file.size > $('#max_upload').val()){ - OC.dialogs.alert(t('contacts','The file you are trying to upload exceed the maximum size for file uploads on this server.'), t('contacts', 'Error')); - return; - } else { - target.load(function(){ - var response=jQuery.parseJSON(target.contents().text()); - if(response != undefined && response.status == 'success'){ - OC.Contacts.Card.editPhoto(response.data.id, response.data.tmp); - //alert('File: ' + file.tmp + ' ' + file.name + ' ' + file.mime); - }else{ - OC.dialogs.alert(response.data.message, t('contacts', 'Error')); - } - }); - form.submit(); - } - }, - loadPhotoHandlers:function() { - var phototools = $('#phototools'); - phototools.find('li a').tipsy('hide'); - phototools.find('li a').tipsy(); - if(this.data.PHOTO) { - phototools.find('.delete').click(function() { - $(this).tipsy('hide'); - OC.Contacts.Card.deleteProperty($('#contacts_details_photo'), 'single'); - $(this).hide(); - }); - phototools.find('.edit').click(function() { - $(this).tipsy('hide'); - OC.Contacts.Card.editCurrentPhoto(); - }); - phototools.find('.delete').show(); - phototools.find('.edit').show(); - } else { - phototools.find('.delete').hide(); - phototools.find('.edit').hide(); - } - }, - cloudPhotoSelected:function(path){ - $.getJSON(OC.filePath('contacts', 'ajax', 'oc_photo.php'),{'path':path,'id':OC.Contacts.Card.id},function(jsondata){ - if(jsondata.status == 'success'){ - //alert(jsondata.data.page); - OC.Contacts.Card.editPhoto(jsondata.data.id, jsondata.data.tmp) - $('#edit_photo_dialog_img').html(jsondata.data.page); - } - else{ - OC.dialogs.alert(jsondata.data.message, t('contacts', 'Error')); - } - }); - }, - loadPhoto:function(){ - var self = this; - var refreshstr = '&refresh='+Math.random(); - $('#phototools li a').tipsy('hide'); - var wrapper = $('#contacts_details_photo_wrapper'); - wrapper.addClass('loading').addClass('wait'); - delete this.photo; - this.photo = new Image(); - $(this.photo).load(function () { - $('img.contacts_details_photo').remove() - $(this).addClass('contacts_details_photo'); - wrapper.css('width', $(this).get(0).width + 10); - wrapper.removeClass('loading').removeClass('wait'); - $(this).insertAfter($('#phototools')).fadeIn(); - }).error(function () { - // notify the user that the image could not be loaded - OC.Contacts.notify({message:t('contacts','Error loading profile picture.')}); - }).attr('src', OC.linkTo('contacts', 'photo.php')+'?id='+self.id+refreshstr); - this.loadPhotoHandlers() - }, - editCurrentPhoto:function(){ - if(!this.enabled) { - return; - } - $.getJSON(OC.filePath('contacts', 'ajax', 'currentphoto.php'),{'id':this.id},function(jsondata){ - if(jsondata.status == 'success'){ - //alert(jsondata.data.page); - OC.Contacts.Card.editPhoto(jsondata.data.id, jsondata.data.tmp) - $('#edit_photo_dialog_img').html(jsondata.data.page); - } - else{ - wrapper.removeClass('wait'); - OC.dialogs.alert(jsondata.data.message, t('contacts', 'Error')); - } - }); - }, - editPhoto:function(id, tmpkey){ - if(!this.enabled) { - return; - } - //alert('editPhoto: ' + tmpkey); - $.getJSON(OC.filePath('contacts', 'ajax', 'cropphoto.php'),{'tmpkey':tmpkey,'id':this.id, 'requesttoken':oc_requesttoken},function(jsondata){ - if(jsondata.status == 'success'){ - //alert(jsondata.data.page); - $('#edit_photo_dialog_img').html(jsondata.data.page); - } - else{ - OC.dialogs.alert(jsondata.data.message, t('contacts', 'Error')); - } - }); - if($('#edit_photo_dialog').dialog('isOpen') == true){ - $('#edit_photo_dialog').dialog('moveToTop'); - } else { - $('#edit_photo_dialog').dialog('open'); - } - }, - savePhoto:function() { - if(!this.enabled) { - return; - } - var target = $('#crop_target'); - var form = $('#cropform'); - var wrapper = $('#contacts_details_photo_wrapper'); - var self = this; - wrapper.addClass('wait'); - form.submit(); - target.load(function(){ - var response=jQuery.parseJSON(target.contents().text()); - if(response != undefined && response.status == 'success'){ - // load cropped photo. - self.loadPhoto(); - OC.Contacts.Card.data.PHOTO = true; - }else{ - OC.dialogs.alert(response.data.message, t('contacts', 'Error')); - wrapper.removeClass('wait'); - } - }); - OC.Contacts.Contacts.refreshThumbnail(this.id); - }, - addIM:function() { - //alert('addMail'); - var imlist = $('#imlist'); - imlist.find('li.template:first-child').clone(true).appendTo(imlist).show().find('a .tip').tipsy(); - imlist.find('li.template:last-child').find('select').addClass('contacts_property'); - imlist.find('li.template:last-child').removeClass('template').addClass('propertycontainer'); - imlist.find('li:last-child').find('input[type="text"]').focus(); - return false; - }, - loadIMs:function() { - //console.log('loadIMs'); - $('#ims').hide(); - $('#imlist li.propertycontainer').remove(); - var imlist = $('#imlist'); - for(var im in this.data.IMPP) { - this.addIM(); - var curim = imlist.find('li.propertycontainer:last-child'); - if(typeof this.data.IMPP[im].label != 'undefined') { - curim.prepend(''); - } - curim.data('checksum', this.data.IMPP[im]['checksum']) - curim.find('input[type="text"]').val(this.data.IMPP[im]['value'].split(':').pop()); - for(var param in this.data.IMPP[im]['parameters']) { - if(param.toUpperCase() == 'PREF') { - curim.find('input[type="checkbox"]').attr('checked', 'checked') - } - else if(param.toUpperCase() == 'TYPE') { - if(typeof this.data.IMPP[im]['parameters'][param] == 'string') { - var found = false; - var imt = this.data.IMPP[im]['parameters'][param]; - curim.find('select.types option').each(function(){ - if($(this).val().toUpperCase() == imt.toUpperCase()) { - $(this).attr('selected', 'selected'); - found = true; - } - }); - if(!found) { - curim.find('select.type option:last-child').after(''); - } - } else if(typeof this.data.IMPP[im]['parameters'][param] == 'object') { - for(imtype in this.data.IMPP[im]['parameters'][param]) { - var found = false; - var imt = this.data.IMPP[im]['parameters'][param][imtype]; - curim.find('select.types option').each(function(){ - if($(this).val().toUpperCase() == imt.toUpperCase().split(',')) { - $(this).attr('selected', 'selected'); - found = true; - } - }); - if(!found) { - curim.find('select.type option:last-child').after(''); - } - } - } - } - else if(param.toUpperCase() == 'X-SERVICE-TYPE') { - curim.find('select.impp').val(this.data.IMPP[im]['parameters'][param].toLowerCase()); - } - } - } - if($('#imlist li').length > 1) { - $('#ims').show(); - } - return false; - }, - addMail:function() { - var emaillist = $('#emaillist'); - emaillist.find('li.template:first-child').clone(true).appendTo(emaillist).show().find('a .tip').tipsy(); - emaillist.find('li.template:last-child').find('select').addClass('contacts_property'); - emaillist.find('li.template:last-child').removeClass('template').addClass('propertycontainer'); - var current = emaillist.find('li.propertycontainer:last-child'); - current.find('input[type="email"]').focus(); - current.find('select').multiselect({ - noneSelectedText: t('contacts', 'Select type'), - header: false, - selectedList: 4, - classes: 'typelist' - }); - current.find('a.mail').click(function() { OC.Contacts.mailTo(this) }); - current.find('a.mail').keydown(function() { OC.Contacts.mailTo(this) }); - return false; - }, - loadMails:function() { - $('#emails').hide(); - $('#emaillist li.propertycontainer').remove(); - var emaillist = $('#emaillist'); - for(var mail in this.data.EMAIL) { - this.addMail(); - emaillist.find('li:last-child').find('select').multiselect('destroy'); - var curemail = emaillist.find('li.propertycontainer:last-child'); - if(typeof this.data.EMAIL[mail].label != 'undefined') { - curemail.prepend(''); - } - curemail.data('checksum', this.data.EMAIL[mail]['checksum']) - curemail.find('input[type="email"]').val(this.data.EMAIL[mail]['value']); - for(var param in this.data.EMAIL[mail]['parameters']) { - if(param.toUpperCase() == 'PREF') { - curemail.find('input[type="checkbox"]').attr('checked', 'checked') - } - else if(param.toUpperCase() == 'TYPE') { - for(etype in this.data.EMAIL[mail]['parameters'][param]) { - var found = false; - var et = this.data.EMAIL[mail]['parameters'][param][etype]; - curemail.find('select option').each(function(){ - if($.inArray($(this).val().toUpperCase(), et.toUpperCase().split(',')) > -1) { - $(this).attr('selected', 'selected'); - found = true; - } - }); - if(!found) { - curemail.find('select option:last-child').after(''); - } - } - } - } - curemail.find('select').multiselect({ - noneSelectedText: t('contacts', 'Select type'), - header: false, - selectedList: 4, - classes: 'typelist' - }); - } - if($('#emaillist li').length > 1) { - $('#emails').show(); - } - $('#emaillist li:last-child').find('input[type="text"]').focus(); - return false; - }, - addPhone:function() { - var phonelist = $('#phonelist'); - phonelist.find('li.template:first-child').clone(true).appendTo(phonelist); //.show(); - phonelist.find('li.template:last-child').find('select').addClass('contacts_property'); - phonelist.find('li.template:last-child').removeClass('template').addClass('propertycontainer'); - phonelist.find('li:last-child').find('input[type="text"]').focus(); - phonelist.find('li:last-child').find('select').multiselect({ - noneSelectedText: t('contacts', 'Select type'), - header: false, - selectedList: 4, - classes: 'typelist' - }); - phonelist.find('li:last-child').show(); - return false; - }, - loadPhones:function() { - $('#phones').hide(); - $('#phonelist li.propertycontainer').remove(); - var phonelist = $('#phonelist'); - for(var phone in this.data.TEL) { - this.addPhone(); - var curphone = phonelist.find('li.propertycontainer:last-child'); - if(typeof this.data.TEL[phone].label != 'undefined') { - curphone.prepend(''); - } - curphone.find('select').multiselect('destroy'); - curphone.data('checksum', this.data.TEL[phone]['checksum']) - curphone.find('input[type="text"]').val(this.data.TEL[phone]['value']); - for(var param in this.data.TEL[phone]['parameters']) { - if(param.toUpperCase() == 'PREF') { - curphone.find('input[type="checkbox"]').attr('checked', 'checked'); - } - else if(param.toUpperCase() == 'TYPE') { - for(ptype in this.data.TEL[phone]['parameters'][param]) { - var found = false; - var pt = this.data.TEL[phone]['parameters'][param][ptype]; - curphone.find('select option').each(function() { - //if ($(this).val().toUpperCase() == pt.toUpperCase()) { - if ($.inArray($(this).val().toUpperCase(), pt.toUpperCase().split(',')) > -1) { - $(this).attr('selected', 'selected'); - found = true; - } - }); - if(!found) { - curphone.find('select option:last-child').after(''); - } - } - } - } - curphone.find('select').multiselect({ - noneSelectedText: t('contacts', 'Select type'), - header: false, - selectedList: 4, - classes: 'typelist' - }); - } - if(phonelist.find('li').length > 1) { - $('#phones').show(); - } - return false; - }, - }, - Contacts:{ - contacts:{}, - deletionQueue:[], - batchnum:50, - warnNotDeleted:function(e) { - e = e || window.event; - var warn = t('contacts', 'Some contacts are marked for deletion, but not deleted yet. Please wait for them to be deleted.'); - if (e) { - e.returnValue = String(warn); - } - if(OC.Contacts.Contacts.deletionQueue.length > 0) { - setTimeout(OC.Contacts.Contacts.deleteFilesInQueue, 1); - } - return warn; - }, - deleteFilesInQueue:function() { - var queue = OC.Contacts.Contacts.deletionQueue; - if(queue.length > 0) { - OC.Contacts.notify({cancel:true}); - while(queue.length > 0) { - var id = queue.pop(); - if(id) { - OC.Contacts.Card.doDelete(id, false); - } - } - } - }, - getContact:function(id) { - if(!this.contacts[id]) { - this.contacts[id] = $('#contacts li[data-id="'+id+'"]'); - if(!this.contacts[id]) { - self = this; - $.getJSON(OC.filePath('contacts', 'ajax', 'contactdetails.php'),{'id':id},function(jsondata){ - if(jsondata.status == 'success'){ - self.contacts[id] = self.insertContact({data:jsondata.data}); - } - else{ - OC.dialogs.alert(jsondata.data.message, t('contacts', 'Error')); - } - }); - } - } - return this.contacts[id]; - }, - drop:function(event, ui) { - var dragitem = ui.draggable, droptarget = $(this); - if(dragitem.is('li')) { - OC.Contacts.Contacts.dropContact(event, dragitem, droptarget); - } else { - OC.Contacts.Contacts.dropAddressbook(event, dragitem, droptarget); - } - }, - dropContact:function(event, dragitem, droptarget) { - if(dragitem.data('bookid') == droptarget.data('id')) { - return false; - } - var droplist = (droptarget.is('ul')) ? droptarget : droptarget.next(); - $.post(OC.filePath('contacts', 'ajax', 'contact/move.php'), - { - id: dragitem.data('id'), - aid: droptarget.data('id') - }, - function(jsondata){ - if(jsondata.status == 'success'){ - dragitem.attr('data-bookid', droptarget.data('id')) - dragitem.data('bookid', droptarget.data('id')); - OC.Contacts.Contacts.insertContact({ - contactlist:droplist, - contact:dragitem.detach() - }); - OC.Contacts.Contacts.scrollTo(dragitem.data('id')); - } else { - OC.dialogs.alert(jsondata.data.message, t('contacts', 'Error')); - } - }); - }, - dropAddressbook:function(event, dragitem, droptarget) { - if(confirm(t('contacts', 'Do you want to merge these address books?'))) { - if(dragitem.data('bookid') == droptarget.data('id')) { - return false; - } - var droplist = (droptarget.is('ul')) ? droptarget : droptarget.next(); - $.post(OC.filePath('contacts', 'ajax', 'contact/move.php'), - { - id: dragitem.data('id'), - aid: droptarget.data('id'), - isaddressbook: 1 - }, - function(jsondata){ - if(jsondata.status == 'success'){ - OC.Contacts.Contacts.update(); // Easier to refresh the whole bunch. - } else { - OC.dialogs.alert(jsondata.data.message, t('contacts', 'Error')); - } - }); - } else { - return false; - } - }, - /** - * @params params An object with the properties 'contactlist':a jquery object of the ul to insert into, - * 'contacts':a jquery object of all items in the list and either 'data': an object with the properties - * id, addressbookid and displayname or 'contact': a listitem to be inserted directly. - * If 'contactlist' or 'contacts' aren't defined they will be search for based in the properties in 'data'. - */ - insertContact:function(params) { - var id, bookid; - if(!params.contactlist) { - // FIXME: Check if contact really exists. - bookid = params.data ? params.data.addressbookid : params.contact.data('bookid'); - id = params.data ? params.data.id : params.contact.data('id'); - params.contactlist = $('#contacts ul[data-id="'+bookid+'"]'); - } - if(!params.contacts) { - bookid = params.data ? params.data.addressbookid : params.contact.data('bookid'); - id = params.data ? params.data.id : params.contact.data('id'); - params.contacts = $('#contacts ul[data-id="'+bookid+'"] li'); - } - var contact = params.data - ? $('
  • ' - + params.data.displayname+'
  • ') - : params.contact; - var added = false; - var name = params.data ? params.data.displayname.toLowerCase() : contact.find('a').text().toLowerCase(); - if(params.contacts) { - params.contacts.each(function() { - if ($(this).text().toLowerCase().localeCompare(name) > 0) { - $(this).before(contact); - added = true; - return false; - } - }); - } - if(!added || !params.contacts) { - params.contactlist.append(contact); - } - //this.contacts[id] = contact; - return contact; - }, - addAddressbook:function(name, description, cb) { - $.post(OC.filePath('contacts', 'ajax/addressbook', 'add.php'), { name: name, description: description, active: true }, - function(jsondata) { - if(jsondata.status == 'success'){ - if(cb && typeof cb == 'function') { - cb(jsondata.data.addressbook); - } - } else { - OC.dialogs.alert(jsondata.data.message, t('contacts', 'Error')); - return false; - } - }); - }, - doImport:function(file, aid, cb) { - $.post(OC.filePath('contacts', '', 'import.php'), { id: aid, file: file, fstype: 'OC_FilesystemView' }, - function(jsondata) { - if(jsondata.status != 'success'){ - OC.Contacts.notify({message:jsondata.data.message}); - } - if(typeof cb == 'function') { - cb(); - } - }); - return false; - }, - next:function(reverse) { - var curlistitem = this.getContact(OC.Contacts.Card.id); - var newlistitem = reverse ? curlistitem.prev('li') : curlistitem.next('li'); - if(newlistitem) { - curlistitem.removeClass('active'); - OC.Contacts.Card.update({ - cid:newlistitem.data('id'), - aid:newlistitem.data('bookid') - }); - } - }, - previous:function() { - this.next(true); - }, - nextAddressbook:function(reverse) { - //console.log('nextAddressbook', reverse); - var curlistitem = this.getContact(OC.Contacts.Card.id); - var parent = curlistitem.parent('ul'); - var newparent = reverse - ? parent.prevAll('ul').first() - : parent.nextAll('ul').first(); - if(newparent) { - newlistitem = newparent.find('li:first-child'); - if(newlistitem) { - parent.slideUp().prev('h3').removeClass('active'); - newparent.slideDown().prev('h3').addClass('active'); - curlistitem.removeClass('active'); - OC.Contacts.Card.update({ - cid:newlistitem.data('id'), - aid:newlistitem.data('bookid') - }); - } - } - }, - previousAddressbook:function() { - //console.log('previousAddressbook'); - this.nextAddressbook(true); - }, - // Reload the contacts list. - update:function(params){ - if(!params) { params = {}; } - if(!params.start) { - if(params.aid) { - $('#contacts h3.addressbook[data-id="'+params.aid+'"],#contacts ul[data-id="'+params.aid+'"]').remove(); - } else { - $('#contacts').empty(); - } - } - self = this; - //console.log('update: ' + params.cid + ' ' + params.aid + ' ' + params.start); - var firstrun = false; - var opts = {}; - opts['startat'] = (params.start?params.start:0); - if(params.aid) { - opts['aid'] = params.aid; - } - $.getJSON(OC.filePath('contacts', 'ajax', 'contact/list.php'),opts,function(jsondata) { - if(jsondata.status == 'success'){ - var books = jsondata.data.entries; - $.each(books, function(b, book) { - if($('#contacts h3.addressbook[data-id="'+b+'"]').length == 0) { - firstrun = true; - var sharedindicator = book.owner == OC.currentUser ? '' - : '' - if($('#contacts h3.addressbook').length == 0) { - $('#contacts').html('

    ' + book.displayname - + sharedindicator + '

    '); - } else { - if(!$('#contacts h3.addressbook[data-id="' + b + '"]').length) { - var item = $('

    ' - + book.displayname+sharedindicator+'

    '); - var added = false; - $('#contacts h3.addressbook').each(function(){ - if ($(this).text().toLowerCase().localeCompare(book.displayname.toLowerCase()) > 0) { - $(this).before(item).fadeIn('fast'); - added = true; - return false; - } - }); - if(!added) { - $('#contacts').append(item); - } - } - } - $('#contacts h3.addressbook[data-id="'+b+'"]').on('click', function(event) { - $('#contacts h3.addressbook').removeClass('active'); - $(this).addClass('active'); - $('#contacts ul[data-id="'+b+'"]').slideToggle(300); - return false; - }); - var accept = 'li:not([data-bookid="'+b+'"]),h3:not([data-id="'+b+'"])'; - $('#contacts h3.addressbook[data-id="'+b+'"],#contacts ul[data-id="'+b+'"]').droppable({ - drop: OC.Contacts.Contacts.drop, - activeClass: 'ui-state-hover', - accept: accept - }); - } - var contactlist = $('#contacts ul[data-id="'+b+'"]'); - var contacts = $('#contacts ul[data-id="'+b+'"] li'); - for(var c in book.contacts) { - if(book.contacts[c].id == undefined) { continue; } - if(!$('#contacts li[data-id="'+book.contacts[c]['id']+'"]').length) { - var contact = OC.Contacts.Contacts.insertContact({contactlist:contactlist, contacts:contacts, data:book.contacts[c]}); - if(c == self.batchnum-10) { - contact.bind('inview', function(event, isInView, visiblePartX, visiblePartY) { - $(this).unbind(event); - var bookid = $(this).data('bookid'); - var numsiblings = $('.contacts li[data-bookid="'+bookid+'"]').length; - if (isInView && numsiblings >= self.batchnum) { - //console.log('This would be a good time to load more contacts.'); - OC.Contacts.Contacts.update({cid:params.cid, aid:bookid, start:$('#contacts li[data-bookid="'+bookid+'"]').length}); - } - }); - } - } - } - }); - $('#contacts h3 img.shared').tipsy() - if($('#contacts h3').length > 1) { - $('#contacts li,#contacts h3').draggable({ - distance: 10, - revert: 'invalid', - axis: 'y', containment: '#contacts', - scroll: true, scrollSensitivity: 40, - opacity: 0.7, helper: 'clone' - }); - } else { - $('#contacts h3').first().addClass('active'); - } - if(opts['startat'] == 0) { // only update card on first load. - OC.Contacts.Card.update(params); - } - } else { - OC.Contacts.notify({message:t('contacts', 'Error')+': '+jsondata.data.message}); - } - $.getJSON(OC.filePath('contacts', 'ajax', 'contact/listbycategory.php'),opts,function(jsondata) { - if(jsondata.status == 'success') { - var categories = jsondata.data.categories; - $.each(categories, function(catid, category) { - console.log('category', catid, category.name); - if(!$('#contacts h3.category[data-id="' + catid + '"]').length) { - var item = $('

    ' - + category.name + '

    '); - var added = false; - $('#contacts h3.category').each(function(){ - if ($(this).text().toLowerCase().localeCompare(category.name.toLowerCase()) > 0) { - $(this).before(item).fadeIn('fast'); - added = true; - return false; - } - }); - if(!added) { - $('#contacts').append(item); - } - $('#contacts h3.category[data-id="'+catid+'"]').on('click', function(event) { - console.log('click'); - $('#contacts h3.category').removeClass('active'); - $(this).addClass('active'); - $('#contacts ul.category[data-id="'+catid+'"]').slideToggle(300); - return false; - }); - var contactlist = $('#contacts ul.category[data-id="'+catid+'"]'); - var contacts = $('#contacts ul.category[data-id="'+catid+'"] li'); - for(var c in category.contacts) { - if(category.contacts[c].id == undefined) { continue; } - if(!$('ul.category[data-id="'+catid+'"] li[data-id="'+category.contacts[c]['id']+'"]').length) { - var contact = $('
  • ' - + category.contacts[c].fullname+'
  • '); - var added = false; - var name = category.contacts[c].fullname.toLowerCase(); - if(contacts.length) { - contacts.each(function() { - if ($(this).text().toLowerCase().localeCompare(name) > 0) { - $(this).before(contact); - added = true; - return false; - } - }); - } - if(!added || !params.contacts) { - contactlist.append(contact); - } - /*var contact = OC.Contacts.Contacts.insertContact({contactlist:contactlist, contacts:contacts, data:categories.contacts[c]}); - if(c == self.batchnum-10) { - contact.bind('inview', function(event, isInView, visiblePartX, visiblePartY) { - $(this).unbind(event); - var bookid = $(this).data('bookid'); - var numsiblings = $('.contacts li[data-bookid="'+bookid+'"]').length; - if (isInView && numsiblings >= self.batchnum) { - console.log('This would be a good time to load more contacts.'); - OC.Contacts.Contacts.update({cid:params.cid, aid:bookid, start:$('#contacts li[data-bookid="'+bookid+'"]').length}); - } - }); - }*/ - } - } - } - }); - } - }); - }); - }, - refreshThumbnail:function(id){ - var item = $('.contacts li[data-id="'+id+'"]').find('a'); - item.html(OC.Contacts.Card.fn); - item.css('background','url('+OC.filePath('contacts', '', 'thumbnail.php')+'?id='+id+'&refresh=1'+Math.random()+') no-repeat'); - }, - scrollTo:function(id){ - var item = $('#contacts li[data-id="'+id+'"]'); - if(item && $.isNumeric(item.offset().top)) { - //console.log('scrollTo ' + parseInt(item.offset().top)); - $('#contacts').animate({ - scrollTop: parseInt(item.offset()).top-40}, 'slow','swing'); - } + Contact.prototype.removeProperty = function(obj) { + console.log('Contact.removeProperty', name) + } + + Contact.prototype.addProperty = function($option, name) { + console.log('Contact.addProperty', name) + switch(name) { + case 'NICKNAME': + case 'TITLE': + case 'ORG': + case 'BDAY': + this.$fullelem.find('[data-element="' + name.toLowerCase() + '"]').show(); + $option.prop('disabled', true); + break; + case 'TEL': + case 'URL': + case 'EMAIL': + $elem = this.renderStandardProperty(name.toLowerCase()); + var $list = this.$fullelem.find('ul.' + name.toLowerCase()); + $list.show(); + $list.append($elem); + break; + case 'ADR': + $elem = this.renderAddressProperty(); + var $list = this.$fullelem.find('ul.' + name.toLowerCase()); + $list.show(); + $list.append($elem); + break; + case 'IMPP': + $elem = this.renderIMProperty(); + var $list = this.$fullelem.find('ul.' + name.toLowerCase()); + $list.show(); + $list.append($elem); + break; } } -} -$(document).ready(function(){ - - OCCategories.changed = OC.Contacts.Card.categoriesChanged; - OCCategories.app = 'contacts'; - - var ninjahelp = $('#ninjahelp'); - - $('#bottomcontrols .settings').on('click keydown', function() { - try { - ninjahelp.hide(); - OC.appSettings({appid:'contacts', loadJS:true, cache:false}); - } catch(e) { - console.log('error:', e.message); + + /** + * @brief Act on change of a property. + * If this is a new contact it will first be saved to the datastore and a + * new datastructure will be added to the object. + * If the obj argument is not provided 'name' and 'value' MUST be provided + * and this is only allowed for single elements like N, FN, CATEGORIES. + * @param obj. The form form field that has changed. + * @param name. The optional name of the element. + * @param value. The optional value. + */ + Contact.prototype.saveProperty = function(params) { + console.log('Contact.saveProperty', params); + var obj = null; + var element = null; + var q = 'id=' + this.id + '&'; + if(params.obj) { + obj = params.obj; + q = this.queryStringFor(obj); + } else { + element = params.name; + q += 'value=' + encodeURIComponent(params.value) + '&name=' + element; } - }); - $('#bottomcontrols .import').click(function() { - $('#import_upload_start').trigger('click'); - }); - $('#contacts_newcontact').on('click keydown', OC.Contacts.Card.editNew); + console.log('q', q); + var self = this; + this.setAsSaving(obj, true); + $.post(OC.filePath('contacts', 'ajax', 'contact/saveproperty.php'), q, function(jsondata){ + if(!jsondata) { + $(document).trigger('status.contact.error', { + status: 'error', + message: t('contacts', 'Network or server error. Please inform administrator.'), + }); + self.setAsSaving(obj, false); + return false; + } + if(jsondata.status == 'success') { + if(self.multi_properties.indexOf(element) !== -1) { + $container.data('checksum', jsondata.data.checksum); + } + self.setAsSaving(obj, false); + return true; + } else { + $(document).trigger('status.contact.error', { + status: 'error', + message: jsondata.data.message, + }); + self.setAsSaving(obj, false); + return false; + } + },'json'); + } + + /** + * Remove any open contact from the DOM. + */ + Contact.prototype.close = function() { + console.log('Closing', this); + if(this.$fullelem) { + this.$fullelem.remove(); + } + } + + /** + * Remove any open contact from the DOM and detach it's list + * element from the DOM. + * @returns The list item jquery object. + */ + Contact.prototype.detach = function() { + if(this.$fullelem) { + this.$fullelem.remove(); + } + if(this.$listelem) { + return this.$listelem.detach(); + } + } + + /** + * Set a contact to en/disabled depending on its permissions. + * @param boolean enabled + */ + Contact.prototype.setEnabled = function(enabled) { + console.log('setEnabled', enabled); + if(enabled) { + this.$fullelem.find('#addproperty').show(); + } else { + this.$fullelem.find('#addproperty').hide(); + } + this.enabled = enabled; + this.$fullelem.find('.value,.action').each(function () { + $(this).prop('disabled', !enabled); + }); + $(document).trigger('status.contact.enabled', enabled); + } + + /** + * Delete contact from data store and remove it from the DOM + * @param cb Optional callback function which + * @returns An object with a variable 'status' of either success + * or 'error' + */ + Contact.prototype.destroy = function(cb) { + var self = this; + $.post(OC.filePath('contacts', 'ajax', 'contact/delete.php'), + {id: this.id}, function(jsondata) { + if(jsondata && jsondata.status === 'success') { + if(self.$listelem) { + self.$listelem.remove(); + } + if(self.$fullelem) { + self.$fullelem.remove(); + } + } + if(typeof cb == 'function') { + var retval = {status: jsondata ? jsondata.status : 'error'}; + if(jsondata) { + if(jsondata.status === 'success') { + retval['id'] = jsondata.id; + } else { + retval['message'] = jsondata.message; + } + } else { + retval['message'] = t('contacts', 'There was an unknown error when trying to delete this contact'); + retval['id'] = self.id; + } + cb(retval); + } + }); + } + + Contact.prototype.queryStringFor = function(obj) { + var q = 'id=' + this.id; + var ptype = this.propertyTypeFor(obj); + q += '&name=' + ptype; + + if(this.multi_properties.indexOf(ptype) !== -1) { + q += '&checksum=' + this.checksumFor(obj); + } + + if($(obj).hasClass('propertycontainer')) { + q += '&value=' + encodeURIComponent($(obj).val()); + } else { + q += '&' + this.propertyContainerFor(obj) + .find('input.value,select.value,textarea.value').serialize(); + } + return q; + } + + Contact.prototype.propertyContainerFor = function(obj) { + return $(obj).hasClass('.propertycontainer') + ? $(obj) + : $(obj).parents('.propertycontainer').first(); + } - ninjahelp.find('.close').on('click keydown',function() { - ninjahelp.hide(); - }); + Contact.prototype.checksumFor = function(obj) { + return this.propertyContainerFor(obj).data('checksum'); + } + + Contact.prototype.propertyTypeFor = function(obj) { + var ptype = this.propertyContainerFor(obj).data('element'); + return ptype ? ptype.toUpperCase() : null; + } + + /** + * Render the list item + * @return A jquery object to be inserted in the DOM + */ + Contact.prototype.renderListItem = function() { + this.$listelem = this.$listTemplate.octemplate({ + id: this.id, + name: this.getPreferredValue('FN', ''), + email: this.getPreferredValue('EMAIL', ''), + tel: this.getPreferredValue('TEL', ''), + adr: this.getPreferredValue('ADR', []).clean('').join(', '), + categories: this.getPreferredValue('CATEGORIES', []) + .clean('').join(' / '), + }); + if(this.access.owner !== OC.currentUser + && !(this.access.permissions & OC.PERMISSION_UPDATE + || this.access.permissions & OC.PERMISSION_DELETE)) { + this.$listelem.find('input:checkbox').prop('disabled', true).css('opacity', '0'); + } + return this.$listelem; + } - $(document).on('keyup', function(event) { - if(event.target.nodeName.toUpperCase() != 'BODY' - || $('#contacts li').length == 0 - || !OC.Contacts.Card.id) { + /** + * Render the full contact + * @return A jquery object to be inserted in the DOM + */ + Contact.prototype.renderContact = function() { + var self = this; + console.log('renderContact', this.data); + var values = this.data + ? { + id: this.id, + name: this.getPreferredValue('FN', ''), + nickname: this.getPreferredValue('NICKNAME', ''), + title: this.getPreferredValue('TITLE', ''), + org: this.getPreferredValue('ORG', []).clean('').join(', '), // TODO Add parts if more than one. + bday: this.getPreferredValue('BDAY', '').length >= 10 + ? $.datepicker.formatDate('dd-mm-yy', + $.datepicker.parseDate('yy-mm-dd', + this.getPreferredValue('BDAY', '').substring(0, 10))) + : '', + } + : {id: '', name: '', nickname: '', title: '', org: '', bday: ''}; + this.$fullelem = this.$fullTemplate.octemplate(values).data('contactobject', this); + this.$addMenu = this.$fullelem.find('#addproperty'); + this.$addMenu.on('change', function(event) { + console.log('add', $(this).val()); + var $opt = $(this).find('option:selected'); + self.addProperty($opt, $(this).val()); + $(this).val(''); + }); + this.$fullelem.on('change', '.value', function(event) { + console.log('change', event); + self.saveProperty({obj:event.target}); + }); + this.$fullelem.find('form').on('submit', function(event) { + console.log('submit', this, event); + return false; + }); + this.$fullelem.find('[data-element="bday"]') + .find('input').datepicker({ + dateFormat : 'dd-mm-yy' + }); + if(!this.data) { + // A new contact + this.setEnabled(true); + return this.$fullelem; + } + // Loop thru all single occurrence values. If not set hide the + // element, if set disable the add menu entry. + for(var value in values) { + if(this.multi_properties.indexOf(value.toUpperCase()) === -1) { + if(!values[value].length) { + console.log('hiding', value); + this.$fullelem.find('[data-element="' + value + '"]').hide(); + } else { + this.$addMenu.find('option[value="' + value.toUpperCase() + '"]').prop('disabled', true); + } + } + } + $.each(this.multi_properties, function(idx, name) { + if(self.data[name]) { + var $list = self.$fullelem.find('ul.' + name.toLowerCase()); + $list.show(); + for(var p in self.data[name]) { + if(typeof self.data[name][p] === 'object') { + var property = self.data[name][p]; + //console.log(name, p, property); + $property = null; + switch(name) { + case 'TEL': + case 'URL': + case 'EMAIL': + $property = self.renderStandardProperty(name.toLowerCase(), property); + break; + case 'ADR': + $property = self.renderAddressProperty(property); + break; + case 'IMPP': + $property = self.renderIMProperty(property); + break; + } + if(!$property) { + continue; + } + //console.log('$property', $property); + if(property.label) { + if(!property.parameters['TYPE']) { + property.parameters['TYPE'] = []; + } + property.parameters['TYPE'].push(property.label); + } + for(var param in property.parameters) { + //console.log('param', param); + if(param.toUpperCase() == 'PREF') { + $property.find('input[type="checkbox"]').attr('checked', 'checked') + } + else if(param.toUpperCase() == 'TYPE') { + for(etype in property.parameters[param]) { + var found = false; + var et = property.parameters[param][etype]; + if(typeof et !== 'string') { + continue; + } + //console.log('et', et); + if(et.toUpperCase() === 'INTERNET') { + continue; + } + $property.find('select.type option').each(function() { + if($(this).val().toUpperCase() === et.toUpperCase()) { + $(this).attr('selected', 'selected'); + found = true; + } + }); + if(!found) { + $property.find('select.type option:last-child').after(''); + } + } + } + else if(param.toUpperCase() == 'X-SERVICE-TYPE') { + //console.log('setting', $property.find('select.impp'), 'to', property.parameters[param].toLowerCase()); + $property.find('select.impp').val(property.parameters[param].toLowerCase()); + } + } + $property.find('select.type[name="parameters[TYPE][]"]') + .combobox({ + singleclick: true, + classes: ['propertytype', 'float', 'label'], + }); + $list.append($property); + } + } + } + }); + if(this.access.owner !== OC.currentUser + && !(this.access.permissions & OC.PERMISSION_UPDATE + || this.access.permissions & OC.PERMISSION_DELETE)) { + this.setEnabled(false); + } else { + this.setEnabled(true); + } + return this.$fullelem; + } + + /** + * Render a simple property. Used for EMAIL and TEL. + * @return A jquery object to be injected in the DOM + */ + Contact.prototype.renderStandardProperty = function(name, property) { + if(!this.detailTemplates[name]) { + console.log('No template for', name); return; } - //console.log(event.which + ' ' + event.target.nodeName); - /** - * To add: - * Shift-a: add addressbook - * u (85): hide/show leftcontent - * f (70): add field - */ - switch(event.which) { - case 27: // Esc - ninjahelp.hide(); - break; - case 46: // Delete - if(event.shiftKey) { - OC.Contacts.Card.delayedDelete(); - } - break; - case 40: // down - case 74: // j - OC.Contacts.Contacts.next(); - break; - case 65: // a - if(event.shiftKey) { - // add addressbook - OC.Contacts.notImplemented(); - break; - } - OC.Contacts.Card.editNew(); - break; - case 38: // up - case 75: // k - OC.Contacts.Contacts.previous(); - break; - case 34: // PageDown - case 78: // n - // next addressbook - OC.Contacts.Contacts.nextAddressbook(); - break; - case 79: // o - var aid = $('#contacts h3.addressbook.active').first().data('id'); - if(aid) { - $('#contacts ul[data-id="'+aid+'"]').slideToggle(300); - } - break; - case 33: // PageUp - case 80: // p - // prev addressbook - OC.Contacts.Contacts.previousAddressbook(); - break; - case 82: // r - OC.Contacts.Contacts.update({cid:OC.Contacts.Card.id}); - break; - case 63: // ? German. - if(event.shiftKey) { - ninjahelp.toggle('fast'); - } - break; - case 171: // ? Danish - case 191: // ? Standard qwerty - ninjahelp.toggle('fast'); - break; + var values = property + ? { value: property.value, checksum: property.checksum } + : { value: '', checksum: 'new' }; + $elem = this.detailTemplates[name].octemplate(values); + return $elem; + } + + /** + * Render an ADR (address) property. + * @return A jquery object to be injected in the DOM + */ + Contact.prototype.renderAddressProperty = function(property) { + if(!this.detailTemplates['adr']) { + console.log('No template for adr', this.detailTemplates); + return; } - - }); - - //$(window).on('beforeunload', OC.Contacts.Contacts.deleteFilesInQueue); - - // Load a contact. - $('.contacts').keydown(function(event) { - if(event.which == 13 || event.which == 32) { - $('.contacts').click(); - } - }); - $(document).on('click', '#contacts', function(event){ - var $tgt = $(event.target); - if ($tgt.is('li') || $tgt.is('a')) { - var item = $tgt.is('li')?$($tgt):($tgt).parent(); - var id = item.data('id'); - var bookid = item.data('bookid'); - item.addClass('active'); - var oldid = $('#rightcontent').data('id'); - if(oldid != 0){ - var olditem = $('.contacts li[data-id="'+oldid+'"]'); - var oldbookid = olditem.data('bookid'); - olditem.removeClass('active'); - if(oldbookid != bookid) { - $('#contacts h3[data-id="'+oldbookid+'"]').removeClass('active'); - $('#contacts h3[data-id="'+bookid+'"]').addClass('active'); - } + var values = property ? { + value: property.value.clean('').join(', '), + checksum: property.checksum, + adr0: property.value[0] || '', + adr1: property.value[1] || '', + adr2: property.value[2] || '', + adr3: property.value[3] || '', + adr4: property.value[4] || '', + adr5: property.value[5] || '', } - $.getJSON(OC.filePath('contacts', 'ajax', 'contact/details.php'),{'id':id},function(jsondata){ - if(jsondata.status == 'success'){ - OC.Contacts.Card.loadContact(jsondata.data, bookid); + : {value: '', checksum: 'new', adr0: '', adr1: '', adr2: '', adr3: '', adr4: '', adr5: ''}; + $elem = this.detailTemplates['adr'].octemplate(values); + return $elem; + } + + /** + * Render an IMPP (Instant Messaging) property. + * @return A jquery object to be injected in the DOM + */ + Contact.prototype.renderIMProperty = function(property) { + if(!this.detailTemplates['impp']) { + console.log('No template for impp', this.detailTemplates); + return; + } + var values = property ? { + value: property.value, + checksum: property.checksum, + } : {value: '', checksum: 'new'}; + $elem = this.detailTemplates['impp'].octemplate(values); + return $elem; + } + /** + * Get the jquery element associated with this object + */ + Contact.prototype.getListItemElement = function() { + if(!this.$listelem) { + this.renderListItem(); + } + return this.$listelem; + } + + /** + * Get the preferred value for a property. + * If a preferred value is not found the first one will be returned. + * @param string name The name of the property like EMAIL, TEL or ADR. + * @param def A default value to return if nothing is found. + */ + Contact.prototype.getPreferredValue = function(name, def) { + var pref = def, found = false; + if(this.data[name]) { + var props = this.data[name]; + //console.log('props', props); + $.each(props, function( i, prop ) { + //console.log('prop:', i, prop); + if(i === 0) { // Choose first to start with + pref = prop.value; } - else{ - OC.dialogs.alert(jsondata.data.message, t('contacts', 'Error')); + for(var param in prop.parameters) { + if(param.toUpperCase() == 'PREF') { + found = true; // + break; + } + } + if(found) { + return false; // break out of loop } }); } - return false; - }); - - $('.contacts_property').live('change', function(){ - OC.Contacts.Card.saveProperty(this); - }); - - $(function() { - // Upload function for dropped contact photos files. Should go in the Contacts class/object. - $.fileUpload = function(files){ - var file = files[0]; - if(file.size > $('#max_upload').val()){ - OC.dialogs.alert(t('contacts','The file you are trying to upload exceed the maximum size for file uploads on this server.'), t('contacts','Upload too large')); - return; - } - if (file.type.indexOf("image") != 0) { - OC.dialogs.alert(t('contacts','Only image files can be used as profile picture.'), t('contacts','Wrong file type')); - return; - } - var xhr = new XMLHttpRequest(); - - if (!xhr.upload) { - OC.dialogs.alert(t('contacts', 'Your browser doesn\'t support AJAX upload. Please click on the profile picture to select a photo to upload.'), t('contacts', 'Error')) - } - fileUpload = xhr.upload, - xhr.onreadystatechange = function() { - if (xhr.readyState == 4){ - response = $.parseJSON(xhr.responseText); - if(response.status == 'success') { - if(xhr.status == 200) { - OC.Contacts.Card.editPhoto(response.data.id, response.data.tmp); - } else { - OC.dialogs.alert(xhr.status + ': ' + xhr.responseText, t('contacts', 'Error')); - } - } else { - OC.dialogs.alert(response.data.message, t('contacts', 'Error')); - } - } - }; - - fileUpload.onprogress = function(e){ - if (e.lengthComputable){ - var _progress = Math.round((e.loaded * 100) / e.total); - //if (_progress != 100){ - //} - } - }; - xhr.open('POST', OC.filePath('contacts', 'ajax', 'uploadphoto.php')+'?id='+OC.Contacts.Card.id+'&requesttoken='+oc_requesttoken+'&imagefile='+encodeURIComponent(file.name), true); - xhr.setRequestHeader('Cache-Control', 'no-cache'); - xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); - xhr.setRequestHeader('X_FILE_NAME', encodeURIComponent(file.name)); - xhr.setRequestHeader('X-File-Size', file.size); - xhr.setRequestHeader('Content-Type', file.type); - xhr.send(file); - } - }); - - $(document).bind('drop dragover', function (e) { - e.preventDefault(); // prevent browser from doing anything, if file isn't dropped in dropZone - }); - - //add multiply file upload attribute to all browsers except konqueror (which crashes when it's used) - if(navigator.userAgent.search(/konqueror/i)==-1){ - $('#import_upload_start').attr('multiple','multiple') + return pref; + } + + /** + * Returns true/false depending on the contact being in the + * specified group. + * @param String name The group name (not case-sensitive) + * @returns Boolean + */ + Contact.prototype.inGroup = function(name) { + if(!this.data.CATEGORIES) { + return false; + } + + categories = this.data.CATEGORIES[0].value; + for(var i in categories) { + if(typeof categories[i] === 'string' && (name.toLowerCase() === categories[i].toLowerCase())) { + return true; + } + }; + return false; } - // Import using jquery.fileupload - $(function() { - var uploadingFiles = {}, numfiles = 0, uploadedfiles = 0, retries = 0; - var aid; - $('#import_upload_start').fileupload({ - dropZone: $('#contacts'), // restrict dropZone to contacts list. - acceptFileTypes: /^text\/(directory|vcard|x-vcard)$/i, - add: function(e, data) { - var files = data.files; - var totalSize=0; - if(files) { - numfiles += files.length; uploadedfiles = 0; - for(var i=0;i$('#max_upload').val()){ - OC.dialogs.alert(t('contacts','The file you are trying to upload exceed the maximum size for file uploads on this server.'), t('contacts','Upload too large')); - numfiles = uploadedfiles = retries = aid = 0; - uploadingFiles = {}; - return; - }else{ - if($.support.xhrFileUpload) { - for(var i=0;i 3) { - numfiles = uploadedfiles = retries = aid = 0; - uploadingFiles = {}; - $('#uploadprogressbar').fadeOut(); - OC.dialogs.alert(t('contacts', 'Something went wrong with the upload, please retry.'), t('contacts', 'Error')); - return; - } - setTimeout(function() { // Just to let any uploads finish - importFiles(aid, uploadingFiles); - }, 1000); - } - $('#uploadprogressbar').progressbar('value',50); - var todo = uploadedfiles; - $.each(fileList, function(fileName, data) { - OC.Contacts.Contacts.doImport(fileName, aid, function() { - delete fileList[fileName]; - numfiles -= 1; uploadedfiles -= 1; - $('#uploadprogressbar').progressbar('value',50+(50/(todo-uploadedfiles))); - }); - }) - OC.Contacts.notify({message:t('contacts', 'Importing...'), timeout:20}); - waitForImport(); - } - if(!aid) { - // Either selected with filepicker or dropped outside of an address book. - $.getJSON(OC.filePath('contacts', 'ajax', 'selectaddressbook.php'),{},function(jsondata) { - if(jsondata.status == 'success') { - if($('#selectaddressbook_dialog').dialog('isOpen') == true) { - $('#selectaddressbook_dialog').dialog('moveToTop'); - } else { - $('#dialog_holder').html(jsondata.data.page).ready(function($) { - var select_dlg = $('#selectaddressbook_dialog'); - select_dlg.dialog({ - modal: true, height: 'auto', width: 'auto', - buttons: { - 'Ok':function() { - aid = select_dlg.find('input:checked').val(); - if(aid == 'new') { - var displayname = select_dlg.find('input.name').val(); - var description = select_dlg.find('input.desc').val(); - if(!displayname.trim()) { - OC.dialogs.alert(t('contacts', 'The address book name cannot be empty.'), t('contacts', 'Error')); - return false; - } - $(this).dialog('close'); - OC.Contacts.Contacts.addAddressbook(displayname, description, function(addressbook) { - aid = addressbook.id; - setTimeout(function() { - importFiles(aid, uploadingFiles); - }, 500); - //console.log('aid ' + aid); - }); - } else { - setTimeout(function() { - importFiles(aid, uploadingFiles); - }, 500); - //console.log('aid ' + aid); - $(this).dialog('close'); - } - }, - 'Cancel':function() { - $(this).dialog('close'); - numfiles = uploadedfiles = retries = aid = 0; - uploadingFiles = {}; - $('#uploadprogressbar').fadeOut(); - } - }, - close: function(event, ui) { - // TODO: If numfiles != 0 delete tmp files after a timeout. - $(this).dialog('destroy').remove(); - } - }); - }); - } - } else { - $('#uploadprogressbar').fadeOut(); - OC.dialogs.alert(jsondata.data.message, t('contacts', 'Error')); - } - }); + /** + * Add this contact to a group + * @param String name The group name + */ + Contact.prototype.addToGroup = function(name) { + console.log('addToGroup', name); + if(!this.data.CATEGORIES) { + this.data.CATEGORIES = [{value:[name]},]; + } else { + this.data.CATEGORIES[0].value.push(name); + console.log('listelem categories', this.getPreferredValue('CATEGORIES', []).clean('').join(' / ')); + if(this.$listelem) { + this.$listelem.find('td.categories') + .text(this.getPreferredValue('CATEGORIES', []).clean('').join(' / ')); + } + } + this.saveProperty({name:'CATEGORIES', value:this.data.CATEGORIES[0].value.join(',') }); + } + + /** + * Remove this contact to a group + * @param String name The group name + */ + Contact.prototype.removeFromGroup = function(name) { + console.log('removeFromGroup', name); + if(!this.data.CATEGORIES) { + return; + } else { + this.data.CATEGORIES[0].value.splice(this.data.CATEGORIES[0].value.indexOf(name), 1); + if(this.$listelem) { + this.$listelem.find('td.categories') + .text(this.getPreferredValue('CATEGORIES', []).clean('').join(' / ')); + } + } + this.saveProperty({name:'CATEGORIES', value:this.data.CATEGORIES[0].value.join(',') }); + } + + Contact.prototype.setCurrent = function(on) { + if(on) { + this.$listelem.addClass('active'); + } else { + this.$listelem.removeClass('active'); + } + $(document).trigger('status.contact.currentlistitem', { + id: this.id, + pos: Math.round(this.$listelem.position().top), + height: Math.round(this.$listelem.height()), + }); + } + + Contact.prototype.next = function() { + var $next = this.$listelem.next('tr'); + if($next.length > 0) { + this.$listelem.removeClass('active'); + $next.addClass('active'); + $(document).trigger('status.contact.currentlistitem', { + id: parseInt($next.data('id')), + pos: Math.round($next.position().top), + height: Math.round($next.height()), + }); + } + } + + Contact.prototype.prev = function() { + var $prev = this.$listelem.prev('tr'); + if($prev.length > 0) { + this.$listelem.removeClass('active'); + $prev.addClass('active'); + $(document).trigger('status.contact.currentlistitem', { + id: parseInt($prev.data('id')), + pos: Math.round($prev.position().top), + height: Math.round($prev.height()), + }); + } + } + + var ContactList = function(contactlist, contactlistitemtemplate, contactfulltemplate, contactdetailtemplates) { + //console.log('ContactList', contactlist, contactlistitemtemplate, contactfulltemplate, contactdetailtemplates); + var self = this; + this.length = 0; + this.contacts = {}; + this.deletionQueue = []; + this.$contactList = contactlist; + this.$contactListItemTemplate = contactlistitemtemplate; + this.$contactFullTemplate = contactfulltemplate; + this.contactDetailTemplates = contactdetailtemplates; + this.$contactList.scrollTop(0); + this.loadContacts(0); + + } + + /** + * Show/hide contacts belonging to an addressbook. + * @param int aid. Addressbook id. + * @param boolean show. Whether to show or hide. + */ + ContactList.prototype.showFromAddressbook = function(aid, show) { + console.log('ContactList.showFromAddressbook', aid, show); + aid = parseInt(aid); + for(var contact in this.contacts) { + if(this.contacts[contact].access.aid === aid) { + if(show) { + this.contacts[contact].getListItemElement().show(); } else { - // Dropped on an address book or it's list. - setTimeout(function() { // Just to let any uploads finish - importFiles(aid, uploadingFiles); - }, 1000); - } - if(data.dataType != 'iframe ') { - $('#upload input.stop').hide(); + this.contacts[contact].getListItemElement().hide(); } } - }) - }); + } + } + + /** + * Show contacts in list + * @param Array contacts. A list of contact ids. + */ + ContactList.prototype.showContacts = function(contacts) { + for(var contact in this.contacts) { + if(contacts === 'all') { + this.contacts[contact].getListItemElement().show(); + } else { + contact = parseInt(contact); + if(contacts.indexOf(String(contact)) === -1) { + this.contacts[contact].getListItemElement().hide(); + } else { + this.contacts[contact].getListItemElement().show(); + } + } + } + } - OC.Contacts.loadHandlers(); - OC.Contacts.Contacts.update({cid:id}); -}); + ContactList.prototype.contactPos = function(id) { + if(!id) { + console.log('id missing'); + return false; + } + var $elem = this.contacts[parseInt(id)].getListItemElement(); + var pos = $elem.offset().top - this.$contactList.offset().top + this.$contactList.scrollTop(); + console.log('pos', pos); + return pos; + } + + ContactList.prototype.closeContact = function(id) { + this.contacts[parseInt(id)].close(); + } + + /** + * Jumps to an element in the contact list + * @param number the number of the item starting with 0 + */ + ContactList.prototype.jumpToContact = function(id) { + var pos = this.contactPos(id); + console.log('scrollTop', pos); + this.$contactList.scrollTop(pos); + }; + + /** + * Returns a Contact object by searching for its id + * @param id the id of the node + * @return the Contact object or undefined if not found. + * FIXME: If continious loading is reintroduced this will have + * to load the requested contact. + */ + ContactList.prototype.findById = function(id) { + return this.contacts[parseInt(id)]; + }; + + ContactList.prototype.warnNotDeleted = function(e) { + e = e || window.event; + var warn = t('contacts', 'Some contacts are marked for deletion, but not deleted yet. Please wait for them to be deleted.'); + if (e) { + e.returnValue = String(warn); + } + if(OC.Contacts.Contacts.deletionQueue.length > 0) { + // This is run almost instantly. It's just to allow us to + // show the warning. Only shows in Chrome afaik... + setTimeout(OC.Contacts.Contacts.deleteFilesInQueue, 1); + } + return warn; + } + + ContactList.prototype.delayedDeleteContact = function(id) { + var self = this; + this.currentContact = null; + var listelem = this.contacts[parseInt(id)].detach(); + self.$contactList.show(); + this.deletionQueue.push(parseInt(id)); + console.log('deletionQueue', this.deletionQueue, listelem); + if(!window.onbeforeunload) { + window.onbeforeunload = this.warnNotDeleted; + } + if(this.$contactList.find('tr:visible').length === 0) { + $(document).trigger('status.visiblecontacts'); + } + OC.notify({ + data:listelem, + message:t('contacts','Click to undo deletion of "') + listelem.find('td.name').text() + '"', + //timeout:5, + timeouthandler:function(listelem) { + console.log('timeout', listelem); + self.deleteContact(listelem.data('id'), true); + }, + clickhandler:function(listelem) { + console.log('clickhandler', listelem); + self.insertContact(listelem); + OC.notify({message:t('contacts', 'Cancelled deletion of: "') + listelem.find('td.name').text() + '"'}); + window.onbeforeunload = null; + } + }); + } + + /** + * Delete a contact with this id + * @param id the id of the contact + */ + ContactList.prototype.deleteContact = function(id, removeFromQueue) { + var self = this; + var id = parseInt(id); + console.log('deletionQueue', this.deletionQueue); + // Local function to update queue. + var updateQueue = function(id, remove) { + if(remove) { + console.log('Removing', id, 'from deletionQueue'); + OC.Contacts.Contacts.deletionQueue.splice(OC.Contacts.Contacts.deletionQueue.indexOf(parseInt(id)), 1); + } + if(OC.Contacts.Contacts.deletionQueue.length == 0) { + console.log('deletionQueue is empty'); + window.onbeforeunload = null; + } + } + + if(OC.Contacts.Contacts.deletionQueue.indexOf(parseInt(id)) == -1 && removeFromQueue) { + console.log('Already deleted, returning'); + updateQueue(id, removeFromQueue); + return; + } + + // Let contact remove itself. + this.contacts[id].destroy(function(response) { + console.log('deleteContact', response); + if(response.status === 'success') { + delete self.contacts[parseInt(id)]; + updateQueue(id, removeFromQueue); + self.$contactList.show(); + $(document).trigger('status.contact.deleted', { + id: id, + }); + self.length -= 1; + if(self.length === 0) { + $(document).trigger('status.nomorecontacts'); + } + } else { + OC.notify({message:response.message}); + } + }); + } + + /** + * Opens the contact with this id in edit mode + * @param id the id of the contact + */ + ContactList.prototype.showContact = function(id) { + this.currentContact = parseInt(id); + console.log('Contacts.showContact', id, this.contacts[this.currentContact], this.contacts) + return this.contacts[this.currentContact].renderContact(); + }; + + /** + * Toggle all checkboxes + */ + ContactList.prototype.toggleAll = function(toggler, togglees) { + var isChecked = $(toggler).is(':checked'); + console.log('toggleAll', isChecked, self); + $.each(togglees, function( i, item ) { + item.checked = isChecked; + }); + return isChecked; + }; + + /** + * Insert a rendered contact list item into the list + * @param contact jQuery object. + */ + ContactList.prototype.insertContact = function(contact) { + //console.log('insertContact', contact); + var name = contact.find('td.name').text().toLowerCase(); + var added = false + this.$contactList.find('tr').each(function() { + if ($(this).find('td.name').text().toLowerCase().localeCompare(name) > 0) { + $(this).before(contact); + added = true; + return false; + } + }); + if(!added) { + this.$contactList.append(contact); + } + return contact; + } + + /** + * Add contact + * @param int offset + */ + ContactList.prototype.addContact = function() { + var contact = new Contact( + this, + null, + null, + null, + this.$contactListItemTemplate, + this.$contactFullTemplate, + this.contactDetailTemplates + ); + if(this.currentContact) { + this.contacts[this.currentContact].close(); + } + return contact.renderContact(); + } + + ContactList.prototype.getSelectedContacts = function() { + var contacts = []; + + $.each(this.$contactList.find('tr > td > input:checkbox:visible:checked'), function(a, b) { + contacts.push(parseInt($(b).parents('tr').first().data('id'))); + }); + return contacts; + } + + ContactList.prototype.setCurrent = function(id, deselect_other) { + self = this; + if(deselect_other === true) { + $.each(this.contacts, function(contact) { + self.contacts[contact].setCurrent(false); + }); + } + this.contacts[parseInt(id)].setCurrent(true); + } + + // Should only be neccesary with progressive loading, but it's damn fast, so... ;) + ContactList.prototype.doSort = function() { + var self = this; + var rows = this.$contactList.find('tr').get(); + + rows.sort(function(a, b) { + return keyA = $(a).find('td.name').text().toUpperCase().localeCompare($(b).find('td.name').text().toUpperCase()); + }); + + $.each(rows, function(index, row) { + self.$contactList.append(row); + }); + } + + /** + * Load contacts + * @param int offset + */ + ContactList.prototype.loadContacts = function(offset, cb) { + var self = this; + // Should the actual ajax call be in the controller? + $.getJSON(OC.filePath('contacts', 'ajax', 'contact/list.php'), {offset: offset}, function(jsondata) { + if (jsondata && jsondata.status == 'success') { + console.log('addressbooks', jsondata.data.addressbooks); + self.addressbooks = {}; + $.each(jsondata.data.addressbooks, function(i, book) { + self.addressbooks[parseInt(book.id)] = { + owner: book.userid, + permissions: parseInt(book.permissions), + aid: parseInt(book.id), + }; + }); + $.each(jsondata.data.contacts, function(c, contact) { + self.contacts[parseInt(contact.id)] + = new Contact( + self, + contact.id, + self.addressbooks[parseInt(contact.aid)], + contact.data, + self.$contactListItemTemplate, + self.$contactFullTemplate, + self.contactDetailTemplates + ); + self.length +=1; + var item = self.contacts[parseInt(contact.id)].renderListItem() + self.$contactList.append(item); + //self.insertContact(item); + }); + self.doSort(); + $(document).trigger('status.contacts.loaded', { + status: true, + numcontacts: jsondata.data.contacts.length + }); + self.setCurrent(self.$contactList.find('tr:first-child').data('id'), false); + } + if(typeof cb === 'function') { + cb(); + } + }); + } + OC.Contacts.ContactList = ContactList; + +})( jQuery ); diff --git a/js/settings.js b/js/settings.js index 2eea3e54..bab136a8 100644 --- a/js/settings.js +++ b/js/settings.js @@ -15,12 +15,11 @@ OC.Contacts.Settings = OC.Contacts.Settings || { var active = tgt.is(':checked'); //console.log('doActivate: ', id, active); $.post(OC.filePath('contacts', 'ajax', 'addressbook/activate.php'), {id: id, active: Number(active)}, function(jsondata) { - if (jsondata.status == 'success'){ - if(!active) { - $('#contacts h3[data-id="'+id+'"],#contacts ul[data-id="'+id+'"]').remove(); - } else { - OC.Contacts.update(); - } + if (jsondata.status == 'success') { + $(document).trigger('request.addressbook.activate', { + id: id, + activate: active, + }); } else { //console.log('Error:', jsondata.data.message); OC.Contacts.notify(t('contacts', 'Error') + ': ' + jsondata.data.message); @@ -157,11 +156,9 @@ $(document).ready(function() { event.preventDefault(); if(OC.Contacts.Settings.Addressbook.adrsettings.is(':visible')) { OC.Contacts.Settings.Addressbook.adrsettings.slideUp(); - OC.Contacts.Settings.Addressbook.adrsettings.prev('dt').hide(); moreless.text(t('contacts', 'More...')); } else { OC.Contacts.Settings.Addressbook.adrsettings.slideDown(); - OC.Contacts.Settings.Addressbook.adrsettings.prev('dt').show(); moreless.text(t('contacts', 'Less...')); } }); diff --git a/lib/app.php b/lib/app.php index 30a0b58f..e9881652 100644 --- a/lib/app.php +++ b/lib/app.php @@ -21,71 +21,17 @@ class OC_Contacts_App { */ public static $categories = null; - public static function getAddressbook($id) { - // TODO: Throw an exception instead of returning json. - $addressbook = OC_Contacts_Addressbook::find( $id ); - if($addressbook === false || $addressbook['userid'] != OCP\USER::getUser()) { - if ($addressbook === false) { - OCP\Util::writeLog('contacts', - 'Addressbook not found: '. $id, - OCP\Util::ERROR); - //throw new Exception('Addressbook not found: '. $id); - OCP\JSON::error( - array( - 'data' => array( - 'message' => self::$l10n->t('Addressbook not found: ' . $id) - ) - ) - ); - } else { - $sharedAddressbook = OCP\Share::getItemSharedWithBySource('addressbook', $id, OC_Share_Backend_Addressbook::FORMAT_ADDRESSBOOKS); - if ($sharedAddressbook) { - return $sharedAddressbook[0]; - } else { - OCP\Util::writeLog('contacts', - 'Addressbook('.$id.') is not from '.OCP\USER::getUser(), - OCP\Util::ERROR); - //throw new Exception('This is not your addressbook.'); - OCP\JSON::error( - array( - 'data' => array( - 'message' => self::$l10n->t('This is not your addressbook.') - ) - ) - ); - } - } - } - return $addressbook; - } - - public static function getContactObject($id) { - $card = OC_Contacts_VCard::find( $id ); - if( $card === false ) { - OCP\Util::writeLog('contacts', - 'Contact could not be found: '.$id, - OCP\Util::ERROR); - OCP\JSON::error( - array( - 'data' => array( - 'message' => self::$l10n->t('Contact could not be found.') - .' '.print_r($id, true) - ) - ) - ); - exit(); - } - - self::getAddressbook( $card['addressbookid'] );//access check - return $card; - } - /** * @brief Gets the VCard as an OC_VObject * @returns The card or null if the card could not be parsed. */ public static function getContactVCard($id) { - $card = self::getContactObject( $id ); + $card = null; + try { + $card = OC_Contacts_VCard::find($id); + } catch(Exception $e) { + return null; + } $vcard = OC_VObject::parse($card['carddata']); if (!is_null($vcard) && !isset($vcard->REV)) { diff --git a/lib/hooks.php b/lib/hooks.php index 4c209954..46ad3180 100644 --- a/lib/hooks.php +++ b/lib/hooks.php @@ -80,7 +80,7 @@ class OC_Contacts_Hooks{ } $info = explode('_', $name); $aid = $info[1]; - OC_Contacts_App::getAddressbook($aid); + OC_Contacts_Addressbook::find($aid); foreach(OC_Contacts_VCard::all($aid) as $card) { $vcard = OC_VObject::parse($card['carddata']); if (!$vcard) { diff --git a/lib/vcard.php b/lib/vcard.php index 06f4a00f..4993e8c5 100644 --- a/lib/vcard.php +++ b/lib/vcard.php @@ -696,15 +696,15 @@ class OC_Contacts_VCard { if(strpos($value, ':') !== false) { $value = explode(':', $value); $protocol = array_shift($value); - if(!isset($property->parameters['X-SERVICE-TYPE'])) { - $property->add(new Sabre_VObject_Parameter( - 'X-SERVICE-TYPE', - strtoupper(strip_tags($protocol))) - ); + if(!isset($property['X-SERVICE-TYPE'])) { + $property['X-SERVICE-TYPE'] = strtoupper(strip_tags($protocol)); } $value = implode('', $value); } } + elseif($property->name == 'PHOTO') { + $property->value = true; + } if(is_string($value)) { $value = strtr($value, array('\,' => ',', '\;' => ';')); } @@ -752,7 +752,7 @@ class OC_Contacts_VCard { * */ public static function moveToAddressBook($aid, $id, $isAddressbook = false) { - OC_Contacts_App::getAddressbook($aid); // check for user ownership. + OC_Contacts_Addressbook::find($aid); $addressbook = OC_Contacts_Addressbook::find($aid); if ($addressbook['userid'] != OCP\User::getUser()) { $sharedAddressbook = OCP\Share::getItemSharedWithBySource('addressbook', $aid); diff --git a/templates/contacts.php b/templates/contacts.php index 91a4d6b2..9bd9a17e 100644 --- a/templates/contacts.php +++ b/templates/contacts.php @@ -6,39 +6,59 @@ var id = ''; var lang = ''; -
    +
    -
    -
    - - - -
    - - -
    - -
    -
    - - + +
    + + + + +
    - - +
    - - - -
    + +
    +
    +
    + + + + + +
    + + From 4b1739efc8c81ceee2a40ff20e9f5ce8b8790cbf Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Mon, 15 Oct 2012 21:34:22 +0200 Subject: [PATCH 018/279] Fix PHOTO handling in serializer method. --- lib/vcard.php | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/lib/vcard.php b/lib/vcard.php index 4993e8c5..471cfadf 100644 --- a/lib/vcard.php +++ b/lib/vcard.php @@ -690,7 +690,7 @@ class OC_Contacts_VCard { } } } elseif($property->name == 'PHOTO') { - $property->value = true; + $value = true; } elseif($property->name == 'IMPP') { if(strpos($value, ':') !== false) { @@ -702,9 +702,6 @@ class OC_Contacts_VCard { $value = implode('', $value); } } - elseif($property->name == 'PHOTO') { - $property->value = true; - } if(is_string($value)) { $value = strtr($value, array('\,' => ',', '\;' => ';')); } From 2e5a1d192eb8f4be732af1282d2b22b38f3f74c4 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Mon, 15 Oct 2012 21:35:34 +0200 Subject: [PATCH 019/279] Profile picure event handlers. --- js/contacts.js | 97 +++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 92 insertions(+), 5 deletions(-) diff --git a/js/contacts.js b/js/contacts.js index 22bdc438..98f53d87 100644 --- a/js/contacts.js +++ b/js/contacts.js @@ -1,7 +1,7 @@ OC.Contacts = OC.Contacts || {}; -(function( $ ) { +(function($) { /** * An item which binds the appropriate html and event handlers @@ -299,6 +299,7 @@ OC.Contacts = OC.Contacts || {}; .find('input').datepicker({ dateFormat : 'dd-mm-yy' }); + this.loadPhoto(); if(!this.data) { // A new contact this.setEnabled(true); @@ -380,11 +381,20 @@ OC.Contacts = OC.Contacts || {}; $property.find('select.impp').val(property.parameters[param].toLowerCase()); } } - $property.find('select.type[name="parameters[TYPE][]"]') - .combobox({ - singleclick: true, - classes: ['propertytype', 'float', 'label'], + if(self.access.owner === OC.currentUser + || self.access.permissions & OC.PERMISSION_UPDATE + || self.access.permissions & OC.PERMISSION_DELETE) { + $property.find('select.type[name="parameters[TYPE][]"]') + .combobox({ + singleclick: true, + classes: ['propertytype', 'float', 'label'], + }); + $property.on('mouseenter', function() { + $(this).find('.listactions').css('opacity', '1'); + }).on('mouseleave', function() { + $(this).find('.listactions').css('opacity', '0'); }); + } $list.append($property); } } @@ -400,6 +410,12 @@ OC.Contacts = OC.Contacts || {}; return this.$fullelem; } + Contact.prototype.isEditable = function() { + return ((this.access.owner === OC.currentUser) + || (this.access.permissions & OC.PERMISSION_UPDATE + || this.access.permissions & OC.PERMISSION_DELETE)); + } + /** * Render a simple property. Used for EMAIL and TEL. * @return A jquery object to be injected in the DOM @@ -456,6 +472,77 @@ OC.Contacts = OC.Contacts || {}; $elem = this.detailTemplates['impp'].octemplate(values); return $elem; } + + /** + * Render the PHOTO property. + */ + Contact.prototype.loadPhoto = function(dontloadhandlers) { + var self = this; + var refreshstr = '&refresh='+Math.random(); + this.$photowrapper = this.$fullelem.find('#photowrapper'); + this.$photowrapper.addClass('loading').addClass('wait'); + var $phototools = this.$fullelem.find('#phototools'); + console.log('photowrapper', this.$photowrapper.length); + delete this.photo; + this.photo = new Image(); + $(this.photo).load(function () { + $('img.contactphoto').remove() + $(this).addClass('contactphoto'); + self.$photowrapper.css('width', $(this).get(0).width + 10); + self.$photowrapper.removeClass('loading').removeClass('wait'); + $(this).insertAfter($phototools).fadeIn(); + }).error(function () { + OC.notify({message:t('contacts','Error loading profile picture.')}); + }).attr('src', OC.linkTo('contacts', 'photo.php')+'?id='+self.id+refreshstr); + + if(!dontloadhandlers && this.isEditable()) { + this.$photowrapper.on('mouseenter', function() { + $phototools.slideDown(200); + }).on('mouseleave', function() { + $phototools.slideUp(200); + }); + $phototools.hover( function () { + $(this).removeClass('transparent'); + }, function () { + $(this).addClass('transparent'); + }); + $phototools.find('li a').tipsy(); + + $phototools.find('.edit').on('click', function() { + console.log('TODO: edit photo'); + $(document).trigger('request.edit.contactphoto', { + id: self.id, + }); + }); + $phototools.find('.cloud').on('click', function() { + console.log('select photo from cloud'); + $(document).trigger('request.select.contactphoto.fromcloud', { + id: self.id, + }); + }); + $phototools.find('.upload').on('click', function() { + console.log('select photo from local'); + $(document).trigger('request.select.contactphoto.fromlocal', { + id: self.id, + }); + }); + if(this.data.PHOTO) { + $phototools.find('.delete').show(); + $phototools.find('.edit').show(); + } else { + $phototools.find('.delete').hide(); + $phototools.find('.edit').hide(); + } + $(document).bind('status.contact.photoupdated', function(e, result) { + console.log('Contact - photoupdated') + self.loadPhoto(true); + var refreshstr = '&refresh='+Math.random(); + self.getListItemElement().find('td.name') + .css('background', 'url(' + OC.linkTo('contacts', 'thumbnail.php')+'?id='+self.id+refreshstr + ')'); + }); + } + } + /** * Get the jquery element associated with this object */ From 0aa9e542f30f9927b793e5d0345babf1ec5669b0 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Mon, 15 Oct 2012 21:36:13 +0200 Subject: [PATCH 020/279] Misc. style fixes. --- css/contacts.css | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/css/contacts.css b/css/contacts.css index ccb6e11f..e6402744 100644 --- a/css/contacts.css +++ b/css/contacts.css @@ -45,8 +45,6 @@ input:hover:not([type="checkbox"]), input:active:not([type="checkbox"]), textare dl.form { display: inline-block; width: auto; margin: 0; padding: 0; cursor: normal; } .form dt { display: table-cell; clear: left; float: left; width: 7em; margin: 0; padding: 0.8em 0.5em 0 0; text-align:right; text-overflow:ellipsis; o-text-overflow: ellipsis; vertical-align: text-bottom; color: #bbb;/* white-space: pre-wrap; white-space: -moz-pre-wrap !important; white-space: -pre-wrap; white-space: -o-pre-wrap;*/ } .form dd { display: table-cell; clear: right; float: left; margin: 0; padding: 0; white-space: nowrap; vertical-align: text-bottom; } -.action { cursor: pointer; width: 20px; height: 20px; margin: 0; float: left; position:relative; opacity: 0.1; } -.action:hover { opacity: 1.0 } .add { background:url('%webroot%/core/img/actions/add.svg') no-repeat center; clear: both; } .delete { background:url('%webroot%/core/img/actions/delete.svg') no-repeat center; } .edit { background:url('%webroot%/core/img/actions/rename.svg') no-repeat center; } @@ -57,7 +55,8 @@ dl.form { display: inline-block; width: auto; margin: 0; padding: 0; cursor: nor .cloud { background:url('%webroot%/core/img/places/picture.svg') no-repeat center; } .globe { background:url('%webroot%/core/img/actions/public.svg') no-repeat center; } .transparent{ opacity: 0.6; } -.float { float: left; display: inline-block; } +.float { float: left; display: inline-block; width: auto; } +.break { clear: both; } .loading { background: url('%webroot%/core/img/loading.gif') no-repeat center !important; /*cursor: progress; */ cursor: wait; } .control { border: 1px solid #DDDDDD; @@ -87,11 +86,15 @@ dl.addresscard .action { float: right; } /* Properties */ -.fullname { font-weight:bold; font-size:1.5em; width: auto; } +.fullname { font-weight:bold; font-size:1.5em; width: 18em; } +.singleproperties{ display: inline-block; float: left; width: 20em;} .propertylist li.propertycontainer { white-space: nowrap; min-width: 38em; display: block; clear: both; } +.propertylist li.propertycontainer > .listactions { display: inline-block; position: absolute; clear: none; opacity: 0; } +.propertylist li.propertycontainer .listactions a { display: inline-block; float: left; clear: none; width: 20px; height: 20px; } + .propertylist { float: left; } -.propertylist li > a { display: block; }} +/*.propertylist li > a { display: block; }}*/ .propertylist li > input[type="checkbox"],input[type="radio"] { display: inline-block; } .propertylist li > input.value:not([type="checkbox"]) { min-width: 16em; display: inline-block; } .propertylist li > select { float: left; max-width: 8em; } @@ -143,6 +146,13 @@ dl.addresscard .action { float: right; } input.propertytype { float: left; font-size: .8em; width: 8em !important; direction: rtl;} .contactphoto { float: left; display: inline-block; border-radius: 0.3em; border: thin solid #bbb; margin: 0.5em; background: url('%webroot%/core/img/loading.gif') no-repeat center center; -moz-box-shadow: 0 1px 3px #777; -webkit-box-shadow: 0 1px 3px #777; box-shadow: 0 1px 3px #777; opacity: 1; } .contactphoto:hover { background: #fff; cursor: default; } +#photowrapper { display: inline-block; float: left; width: 150px; } +#photowrapper.wait { opacity: 0.6; filter:alpha(opacity=0.6); z-index:1000; background: url('%webroot%/core/img/loading.gif') no-repeat center; cursor: wait; } +#phototools { position:absolute; margin: 5px 0 0 10px; width:auto; height:22px; padding:0px; background-color:#fff; list-style-type:none; border-radius: 0.3em; -moz-box-shadow: 0 1px 3px #777; -webkit-box-shadow: 0 1px 3px #777; box-shadow: 0 1px 3px #777; } +#phototools li { display: inline; } +#phototools li a { float:left; cursor:pointer; width:22px; height:22px; opacity: 0.6; } +#phototools li a:hover { opacity: 0.8; } +#contactphoto_fileupload, #import_fileupload { -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)"; filter:alpha(opacity=0); opacity:0; z-index:1001; width:0; height:0;} /* Header */ @@ -190,15 +200,14 @@ input.propertytype { float: left; font-size: .8em; width: 8em !important; direct #contactlist tr > td.name>input[type="checkbox"]:hover:first-child { -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=80)"; filter:alpha(opacity=80); opacity:.8; } #contactlist tr > td.name>input[type="checkbox"]:checked:first-child { -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=100)"; filter:alpha(opacity=100); opacity:1; } #contactlist tr > td.name { font-weight: bold; text-indent: 1.6em; -webkit-transition:background-image 500ms; -moz-transition:background-image 500ms; -o-transition:background-image 500ms; transition:background-image 500ms; position:relative; background-position:1em .5em !important; background-repeat:no-repeat !important; } -#contactlist tr > td.email span { float: left; clear: none; } -#contactlist tr > td a.mailto { float: right; cursor:pointer; width:22px; height:22px; z-index: 200; opacity: 0.6; background:url('%webroot%/core/img/actions/mail.svg') no-repeat center; } +#contactlist tr > td a.mailto { position: absolute; float: right; clear: none; cursor:pointer; width:22px; height:22px; z-index: 200; opacity: 0.6; background:url('%webroot%/core/img/actions/mail.svg') no-repeat center; } #contactlist tr > td a.mailto:hover { opacity: 0.8; } #contact figure img { -moz-border-radius:.3em; -webkit-border-radius:.3em; border-radius:.3em; border: thin solid #bbb; margin: 0.3em; background: url('%webroot%/core/img/loading.gif') no-repeat center center; -moz-box-shadow: 0 1px 3px #777; -webkit-box-shadow: 0 1px 3px #777; box-shadow: 0 1px 3px #777; opacity: 1; } -#contact span.adr { float: left; width: 16em; overflow: hidden; text-overflow: ellipsis; text-align: bottom; white-space: nowrap; } -#contact span.adr:hover { overflow: inherit; } +#contact span.adr { float: left; width: 16em; padding-top: .5em; overflow: hidden; text-overflow: ellipsis; text-align: bottom; white-space: nowrap; } +#contact span.adr:hover { /*overflow: inherit;*/ white-space: pre-wrap; } @media screen and (max-width: 1500px) { #contactlist tr td.categories { display: none; } From 6ae693b219ac06b1546eee0066cf74e783df6670 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Fri, 19 Oct 2012 00:22:31 +0200 Subject: [PATCH 021/279] Remove 'app/' prefix from class paths. --- appinfo/app.php | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/appinfo/app.php b/appinfo/app.php index 261fcc65..692ea821 100644 --- a/appinfo/app.php +++ b/appinfo/app.php @@ -1,17 +1,17 @@ Date: Fri, 19 Oct 2012 00:23:32 +0200 Subject: [PATCH 022/279] Updated category poc for Contacts. --- ajax/contact/saveproperty.php | 5 ++++ js/contacts.js | 49 ++++++++++++++++++++++++++--------- 2 files changed, 42 insertions(+), 12 deletions(-) diff --git a/ajax/contact/saveproperty.php b/ajax/contact/saveproperty.php index 0afd476f..ba3b847a 100644 --- a/ajax/contact/saveproperty.php +++ b/ajax/contact/saveproperty.php @@ -118,6 +118,11 @@ if(!$value) { break; case 'CATEGORIES': debug('Setting string:'.$name.' '.$value); + $catmgr = OC_Contacts_App::getVCategories(); + $catmgr->purgeObject($id, 'contact'); + foreach(array_map('trim', explode(',', $value)) as $category) { + $catmgr->addToCategory($id, $category); + } $vcard->children[$line]->setValue($value); break; case 'EMAIL': diff --git a/js/contacts.js b/js/contacts.js index 6ca4c66c..e3a2c43a 100644 --- a/js/contacts.js +++ b/js/contacts.js @@ -732,6 +732,9 @@ OC.Contacts={ var name = container.data('element'); var fields = container.find('input.contacts_property,select.contacts_property').serializeArray(); switch(name) { + case 'CATEGORIES': + OC.Contacts.Contacts.updateCategories(this.id, $('#categories').val()); + break; case 'FN': var nempty = true; for(var i in OC.Contacts.Card.data.N[0]['value']) { @@ -1634,6 +1637,40 @@ OC.Contacts={ return false; } }, + updateCategories:function(id, catstr) { + var categories = $.map(catstr.split(','), function(category) {return category.trim();}); + console.log('updateCategories', id, categories); + + // Not pretty, but only proof of concept + $('#contacts ul.category').each(function() { + console.log('Updating category', $(this).prev('h3').text()) + if(categories.indexOf($(this).prev('h3').text()) === -1) { + console.log($(this).prev('h3').text(), 'not in ', categories); + $(this).find('li[data-id="' + id + '"]').remove(); + } else { + if($(this).find('li[data-id="' + id + '"]').length === 0) { + var contacts = $(this).children(); + var contact = $('
  • ' + + OC.Contacts.Card.fn+'
  • '); + + var added = false; + contacts.each(function() { + if($(this).text().toLowerCase().localeCompare(OC.Contacts.Card.fn.toLowerCase()) > 0) { + $(this).before(contact); + added = true; + return false; // break out of loop + } + }); + if(!added || !contacts.length) { + $(this).append(contact); + } + } + } + }); + }, /** * @params params An object with the properties 'contactlist':a jquery object of the ul to insert into, * 'contacts':a jquery object of all items in the list and either 'data': an object with the properties @@ -1891,18 +1928,6 @@ OC.Contacts={ if(!added || !params.contacts) { contactlist.append(contact); } - /*var contact = OC.Contacts.Contacts.insertContact({contactlist:contactlist, contacts:contacts, data:categories.contacts[c]}); - if(c == self.batchnum-10) { - contact.bind('inview', function(event, isInView, visiblePartX, visiblePartY) { - $(this).unbind(event); - var bookid = $(this).data('bookid'); - var numsiblings = $('.contacts li[data-bookid="'+bookid+'"]').length; - if (isInView && numsiblings >= self.batchnum) { - console.log('This would be a good time to load more contacts.'); - OC.Contacts.Contacts.update({cid:params.cid, aid:bookid, start:$('#contacts li[data-bookid="'+bookid+'"]').length}); - } - }); - }*/ } } } From f877dd73399ea607c4f7eb5b724b389b001835fa Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Fri, 19 Oct 2012 00:36:58 +0200 Subject: [PATCH 023/279] Update Calendar and Contacts js to also use type with OCCategories. --- js/contacts.js | 1 + 1 file changed, 1 insertion(+) diff --git a/js/contacts.js b/js/contacts.js index e3a2c43a..7aa3ad57 100644 --- a/js/contacts.js +++ b/js/contacts.js @@ -1955,6 +1955,7 @@ $(document).ready(function(){ OCCategories.changed = OC.Contacts.Card.categoriesChanged; OCCategories.app = 'contacts'; + OCCategories.type = 'contact'; var ninjahelp = $('#ninjahelp'); From 4890bdf705d467c8a48a4799696e00a960a12e37 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Fri, 19 Oct 2012 02:27:37 +0200 Subject: [PATCH 024/279] Don't set checksum for non-existing property. --- ajax/categories/categoriesfor.php | 30 +++++++++++++++++------------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/ajax/categories/categoriesfor.php b/ajax/categories/categoriesfor.php index c747f3be..ffd6f0e5 100644 --- a/ajax/categories/categoriesfor.php +++ b/ajax/categories/categoriesfor.php @@ -18,17 +18,21 @@ if(is_null($id)) { exit(); } $vcard = OC_Contacts_App::getContactVCard( $id ); -foreach($vcard->children as $property) { - if($property->name == 'CATEGORIES') { - $checksum = md5($property->serialize()); - OCP\JSON::success(array( - 'data' => array( - 'value' => $property->value, - 'checksum' => $checksum, - ))); - exit(); +if(isset($vcard->CATEGORIES)) { + foreach($vcard->children as $property) { + if($property->name == 'CATEGORIES') { + $checksum = md5($property->serialize()); + OCP\JSON::success(array( + 'data' => array( + 'value' => $property->value, + 'checksum' => $checksum, + ))); + exit(); + } } -} -OCP\JSON::error(array( - 'data' => array( - 'message' => OC_Contacts_App::$l10n->t('Error setting checksum.')))); + OCP\JSON::error(array( + 'data' => array( + 'message' => OC_Contacts_App::$l10n->t('Error setting checksum.')))); +} else { + OCP\JSON::success(); +} \ No newline at end of file From 451716dbba67128a1f7a5badfa7eec47a481c36f Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Fri, 19 Oct 2012 02:28:27 +0200 Subject: [PATCH 025/279] Use type, not app for categories. --- ajax/categories/delete.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ajax/categories/delete.php b/ajax/categories/delete.php index 53423426..0001992e 100644 --- a/ajax/categories/delete.php +++ b/ajax/categories/delete.php @@ -41,7 +41,7 @@ foreach($contacts as $contact) { debug('Before delete: '.print_r($categories, true)); -$catman = new OC_VCategories('contacts'); +$catman = new OC_VCategories('contact'); $catman->delete($categories, $cards); debug('After delete: '.print_r($catman->categories(), true)); OC_Contacts_VCard::updateDataByID($cards); From 4c473249a07e65d19fda45333a67f9d6f4da0a02 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Fri, 19 Oct 2012 02:28:52 +0200 Subject: [PATCH 026/279] More updates for categories poc. --- js/contacts.js | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/js/contacts.js b/js/contacts.js index 7aa3ad57..3cf3bfe9 100644 --- a/js/contacts.js +++ b/js/contacts.js @@ -676,12 +676,20 @@ OC.Contacts={ }, categoriesChanged:function(newcategories) { // Categories added/deleted. categories = $.map(newcategories, function(v) {return v;}); + $('#contacts h3.category').each(function() { + if(categories.indexOf($(this).text()) === -1) { + $(this).next('ul').remove(); + $(this).remove(); + } + }); $('#categories').multiple_autocomplete('option', 'source', categories); var categorylist = $('#categories_value').find('input'); $.getJSON(OC.filePath('contacts', 'ajax', 'categories/categoriesfor.php'),{'id':OC.Contacts.Card.id},function(jsondata){ - if(jsondata.status == 'success'){ - $('#categories_value').data('checksum', jsondata.data.checksum); - categorylist.val(jsondata.data.value); + if(jsondata.status == 'success') { + if(jsondata.data) { + $('#categories_value').data('checksum', jsondata.data.checksum); + categorylist.val(jsondata.data.value); + } } else { OC.dialogs.alert(jsondata.data.message, t('contacts', 'Error')); } @@ -1639,13 +1647,10 @@ OC.Contacts={ }, updateCategories:function(id, catstr) { var categories = $.map(catstr.split(','), function(category) {return category.trim();}); - console.log('updateCategories', id, categories); // Not pretty, but only proof of concept $('#contacts ul.category').each(function() { - console.log('Updating category', $(this).prev('h3').text()) if(categories.indexOf($(this).prev('h3').text()) === -1) { - console.log($(this).prev('h3').text(), 'not in ', categories); $(this).find('li[data-id="' + id + '"]').remove(); } else { if($(this).find('li[data-id="' + id + '"]').length === 0) { From 3479f711cfc1d9a33baedc1fe3fdc3b13132cc5d Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Fri, 19 Oct 2012 21:38:40 +0200 Subject: [PATCH 027/279] Trying to save some ajax files from git disaster. --- ajax/categories/add.php | 29 +++++++++++++++++++++++++++++ ajax/categories/addto.php | 4 ++-- ajax/categories/removefrom.php | 2 +- 3 files changed, 32 insertions(+), 3 deletions(-) create mode 100644 ajax/categories/add.php diff --git a/ajax/categories/add.php b/ajax/categories/add.php new file mode 100644 index 00000000..fc3cb3fd --- /dev/null +++ b/ajax/categories/add.php @@ -0,0 +1,29 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + + +OCP\JSON::checkLoggedIn(); +OCP\JSON::checkAppEnabled('contacts'); +OCP\JSON::callCheck(); + +require_once __DIR__.'/../loghandler.php'; + +$category = isset($_POST['category']) ? $_POST['category'] : null; + +if(is_null($category)) { + bailOut(OC_Contacts_App::$l10n->t('No category name given.')); +} + +$catman = new OC_VCategories('contact'); +$id = $catman->add($category); + +if($id !== false) { + OCP\JSON::success(array('data' => array('id'=>$id))); +} else { + bailOut(OC_Contacts_App::$l10n->t('Error adding group.')); +} diff --git a/ajax/categories/addto.php b/ajax/categories/addto.php index b87d1a90..9760baa8 100644 --- a/ajax/categories/addto.php +++ b/ajax/categories/addto.php @@ -27,8 +27,8 @@ if(is_null($contactid)) { debug('id: ' . $contactid .', categoryid: ' . $categoryid); $catmgr = OC_Contacts_App::getVCategories(); -if(!$catmgr->createRelation($contactid, $categoryid)) { - bailOut(OC_Contacts_App::$l10n->t('Error removing contact from group.')); +if(!$catmgr->addToCategory($contactid, $categoryid)) { + bailOut(OC_Contacts_App::$l10n->t('Error adding contact to group.')); } OCP\JSON::success(); diff --git a/ajax/categories/removefrom.php b/ajax/categories/removefrom.php index f3f8cc26..9ce0f60e 100644 --- a/ajax/categories/removefrom.php +++ b/ajax/categories/removefrom.php @@ -27,7 +27,7 @@ if(is_null($contactid)) { debug('id: ' . $contactid .', categoryid: ' . $categoryid); $catmgr = OC_Contacts_App::getVCategories(); -if(!$catmgr->removeRelation($contactid, $categoryid)) { +if(!$catmgr->removeFromCategory($contactid, $categoryid)) { bailOut(OC_Contacts_App::$l10n->t('Error removing contact from group.')); } From 3e1dedf8ac7a57a90e427d9d195a0d869986a29e Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Fri, 19 Oct 2012 22:09:59 +0200 Subject: [PATCH 028/279] Add contact(s) to group while creating it. And use ints as keys instead of strings. --- js/app.js | 120 +++++++++++++++++++++++++++++++++++++++++++++---- js/contacts.js | 2 +- 2 files changed, 113 insertions(+), 9 deletions(-) diff --git a/js/app.js b/js/app.js index 9234a56d..6d756c97 100644 --- a/js/app.js +++ b/js/app.js @@ -102,6 +102,10 @@ var GroupList = function(groupList, listItemTmpl) { this.categories = []; } +GroupList.prototype.nameById = function(id) { + return this.findById(id).contents().filter(function(){ return(this.nodeType == 3); }).text().trim() +} + GroupList.prototype.findById = function(id) { return this.$groupList.find('h3[data-id="' + id + '"]'); } @@ -119,7 +123,7 @@ GroupList.prototype.addTo = function(contactid, groupid, cb) { return; } if(jsondata.status === 'success') { - contacts.push(String(contactid)); + contacts.push(contactid); $groupelem.data('contacts', contacts); $groupelem.find('.numcontacts').text(contacts.length); if(typeof cb === 'function') { @@ -145,7 +149,7 @@ GroupList.prototype.removeFrom = function(contactid, groupid, cb) { if(!contacts) { return; } - if(contacts.indexOf(String(contactid)) !== -1) { + if(contacts.indexOf(contactid) !== -1) { $.post(OC.filePath('contacts', 'ajax', 'categories/removefrom.php'), {contactid: contactid, categoryid: groupid},function(jsondata) { if(!jsondata) { OC.notify({message:t('contacts', 'Network or server error.')}); @@ -155,7 +159,7 @@ GroupList.prototype.removeFrom = function(contactid, groupid, cb) { return; } if(jsondata.status === 'success') { - contacts.splice(contacts.indexOf(String(contactid)), 1); + contacts.splice(contacts.indexOf(contactid), 1); //console.log('contacts', contacts, contacts.indexOf(id), contacts.indexOf(String(id))); $groupelem.data('contacts', contacts); $groupelem.find('.numcontacts').text(contacts.length); @@ -183,6 +187,61 @@ GroupList.prototype.removeFromAll = function(contactid, alsospecial) { }); } +GroupList.prototype.categoriesChanged = function(newcategories) { + console.log('GroupList.categoriesChanged, I should do something'); +} + +GroupList.prototype.addGroup = function(name, contacts, cb) { + console.log('GroupList.addGroup', name); + contacts = $.map(contacts, function(c) {return parseInt(c)}); + var self = this, exists = false; + self.$groupList.find('h3[data-type="category"]').each(function() { + if ($(this).data('name').toLowerCase() === name.toLowerCase()) { + exists = true; + return false; //break out of loop + } + }); + if(exists) { + if(typeof cb === 'function') { + cb({result:'error', message:t('contacts', 'A group named {group} already exists', {group: name})}); + } + return; + } + $.post(OC.filePath('contacts', 'ajax', 'categories/add.php'), {category: name}, function(jsondata) { + if (jsondata && jsondata.status == 'success') { + var tmpl = self.$groupListItemTemplate; + var $elem = (tmpl).octemplate({ + id: jsondata.data.id, + type: 'category', + num: contacts.length, + name: name, + }) + self.categories.push({id: jsondata.data.id, name: name}); + $elem.data('contacts', contacts) + $elem.data('name', name) + $elem.data('id', jsondata.data.id) + var added = false; + self.$groupList.find('h3.group[data-type="category"]').each(function() { + if ($(this).data('name').toLowerCase().localeCompare(name.toLowerCase()) > 0) { + $(this).before($elem); + added = true; + return false; + } + }); + if(!added) { + $elem.appendTo(self.$groupList); + } + if(typeof cb === 'function') { + cb({result:'success', id:jsondata.data.id, name:name}); + } + } else { + if(typeof cb === 'function') { + cb({result:'error', message:jsondata.data.message}); + } + } + }); +} + GroupList.prototype.loadGroups = function(numcontacts, cb) { var self = this; var $groupList = this.$groupList; @@ -193,19 +252,20 @@ GroupList.prototype.loadGroups = function(numcontacts, cb) { $.getJSON(OC.filePath('contacts', 'ajax', 'categories/list.php'), {}, function(jsondata) { if (jsondata && jsondata.status == 'success') { $.each(jsondata.data.categories, function(c, category) { + var contacts = $.map(category.contacts, function(c) {return parseInt(c)}); var $elem = (tmpl).octemplate({ id: category.id, type: 'category', - num: category.contacts.length, + num: contacts.length, name: category.name, }) self.categories.push({id: category.id, name: category.name}); - $elem.data('contacts', category.contacts) + $elem.data('contacts', contacts) $elem.data('name', category.name) $elem.data('id', category.id) $elem.appendTo($groupList); }); - } + } // TODO: else if(typeof cb === 'function') { cb(); } @@ -229,6 +289,9 @@ OC.Contacts = OC.Contacts || { this.detailTemplates ); this.Groups = new GroupList(this.$groupList, this.$groupListItemTemplate); + OCCategories.changed = this.Groups.categoriesChanged; + OCCategories.app = 'contacts'; + OCCategories.type = 'contact'; this.bindEvents(); this.$toggleAll.show(); this.showActions(['add', 'delete']); @@ -475,6 +538,47 @@ OC.Contacts = OC.Contacts || { if($opt.val() === 'add') { console.log('add group...'); self.$groups.val(-1); + if(!this.$addGroupTmpl) { + this.$addGroupTmpl = $('#addGroupTemplate'); + } + $('body').append('
    '); + var $dlg = this.$addGroupTmpl.octemplate(); + $('#add_group_dialog').html($dlg).dialog({ + modal: true, + closeOnEscape: true, + title: t('contacts', 'Add group'), + height: 'auto', width: 'auto', + buttons: { + 'Ok':function() { + var contacts = self.Contacts.getSelectedContacts(); + self.Groups.addGroup( + $dlg.find('input:text').val(), + contacts, + function(response) { + if(response.result === 'success') { + for(var id in contacts) { + if(typeof contacts[id] === 'number') { + console.log('add', contacts[id], 'to', response.name); + self.Contacts.contacts[contacts[id]].addToGroup(response.name); + } + } + } else { + OC.notify({message: response.message}); + } + }); + $(this).dialog('close'); + }, + 'Cancel':function() { $(this).dialog('close'); } + }, + close: function(event, ui) { + $(this).dialog('destroy').remove(); + $('#add_group_dialog').remove(); + $.each(self.$contactList.find('input:checkbox:checked'), function() { + console.log('unchecking', $(this)); + $(this).prop('checked', false); + }); + }, + }); return; } @@ -557,6 +661,7 @@ OC.Contacts = OC.Contacts || { self.showActions(['add', 'delete']); $(this).addClass('active'); if($(this).data('type') === 'category') { + console.log('contacts', $(this).data('contacts')); self.Contacts.showContacts($(this).data('contacts')); } else { self.Contacts.showContacts($(this).data('id')); @@ -838,7 +943,7 @@ OC.Contacts = OC.Contacts || { }, close: function(event, ui) { $(this).dialog('destroy').remove(); - $('#name_dialog').remove(); + $('#edit_photo_dialog').remove(); }, open: function(event, ui) { // Jcrop maybe? @@ -870,7 +975,6 @@ OC.Contacts = OC.Contacts || { }); }, }; - (function( $ ) { diff --git a/js/contacts.js b/js/contacts.js index 98f53d87..a7b7e563 100644 --- a/js/contacts.js +++ b/js/contacts.js @@ -723,7 +723,7 @@ OC.Contacts = OC.Contacts || {}; this.contacts[contact].getListItemElement().show(); } else { contact = parseInt(contact); - if(contacts.indexOf(String(contact)) === -1) { + if(contacts.indexOf(contact) === -1) { this.contacts[contact].getListItemElement().hide(); } else { this.contacts[contact].getListItemElement().show(); From 15e64b86b843f4df1fdfddd2e39d57e760e059de Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Fri, 19 Oct 2012 22:19:05 +0200 Subject: [PATCH 029/279] Delete photo *before* adding it, not after... --- js/contacts.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/contacts.js b/js/contacts.js index a7b7e563..ae21c6d3 100644 --- a/js/contacts.js +++ b/js/contacts.js @@ -484,9 +484,9 @@ OC.Contacts = OC.Contacts || {}; var $phototools = this.$fullelem.find('#phototools'); console.log('photowrapper', this.$photowrapper.length); delete this.photo; + $('img.contactphoto').remove() this.photo = new Image(); $(this.photo).load(function () { - $('img.contactphoto').remove() $(this).addClass('contactphoto'); self.$photowrapper.css('width', $(this).get(0).width + 10); self.$photowrapper.removeClass('loading').removeClass('wait'); From fa62f3528e24b6ceb0b6522f6d1122b9d680e624 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Sat, 20 Oct 2012 02:04:59 +0200 Subject: [PATCH 030/279] Maybe about time to add my name to the app. --- appinfo/info.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/appinfo/info.xml b/appinfo/info.xml index 02a55883..2dc93439 100644 --- a/appinfo/info.xml +++ b/appinfo/info.xml @@ -3,7 +3,7 @@ contacts Contacts AGPL - Jakob Sack + Jakob Sack, Thomas Tanghus 4.9 true Address book with CardDAV support. From a9f57aff4829da76afcbaf09f5ea71f0a132e41e Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Mon, 22 Oct 2012 15:25:12 +0200 Subject: [PATCH 031/279] Spacing. --- ajax/categories/addto.php | 1 + 1 file changed, 1 insertion(+) diff --git a/ajax/categories/addto.php b/ajax/categories/addto.php index 9760baa8..0d2c8049 100644 --- a/ajax/categories/addto.php +++ b/ajax/categories/addto.php @@ -27,6 +27,7 @@ if(is_null($contactid)) { debug('id: ' . $contactid .', categoryid: ' . $categoryid); $catmgr = OC_Contacts_App::getVCategories(); + if(!$catmgr->addToCategory($contactid, $categoryid)) { bailOut(OC_Contacts_App::$l10n->t('Error adding contact to group.')); } From 5b972b74a899b1545e21e46aa61d5ee5ca7c9694 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Mon, 22 Oct 2012 15:26:28 +0200 Subject: [PATCH 032/279] Added ajax file to set user preferences. --- ajax/setpreference.php | 55 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 ajax/setpreference.php diff --git a/ajax/setpreference.php b/ajax/setpreference.php new file mode 100644 index 00000000..6f485bba --- /dev/null +++ b/ajax/setpreference.php @@ -0,0 +1,55 @@ + + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU AFFERO GENERAL PUBLIC LICENSE for more details. + * + * You should have received a copy of the GNU Affero General Public + * License along with this library. If not, see . + * + */ + +/** + * @brief Set user preference. + * @param $key + * @param $value + */ + +OCP\JSON::checkLoggedIn(); +OCP\JSON::checkAppEnabled('contacts'); +OCP\JSON::callCheck(); + +require_once 'loghandler.php'; + +$key = isset($_POST['key'])?$_POST['key']:null; +$value = isset($_POST['value'])?$_POST['value']:null; +if(is_null($key)) { + bailOut(OC_Contacts_App::$l10n->t('Key is not set for: '.$value)); +} + +if(is_null($value)) { + bailOut(OC_Contacts_App::$l10n->t('Value is not set for: '.$key)); +} + +if(OCP\Config::setUserValue(OCP\USER::getUser(), 'contacts', $key, $value)) { + OCP\JSON::success(array( + 'data' => array( + 'key' => $key, + 'value' => $value) + ) + ); +} else { + bailOut(OC_Contacts_App::$l10n->t( + 'Could not set preference: ' . $key . ':' . $value) + ); +} From 73e15ac78b17fcc4f98c800b88761e0b6a9d81ac Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Mon, 22 Oct 2012 15:32:03 +0200 Subject: [PATCH 033/279] Added icons for favorites. --- img/active_star.png | Bin 0 -> 527 bytes img/inactive_star.png | Bin 0 -> 583 bytes img/starred.png | Bin 0 -> 727 bytes 3 files changed, 0 insertions(+), 0 deletions(-) create mode 100644 img/active_star.png create mode 100644 img/inactive_star.png create mode 100644 img/starred.png diff --git a/img/active_star.png b/img/active_star.png new file mode 100644 index 0000000000000000000000000000000000000000..287ffa65dc5b1ff435e6698f4d1b1534ee582786 GIT binary patch literal 527 zcmV+q0`UEbP)y~h1lG0S^@O`TJ?K8T5I_7+Q-<`u>uHpa=*>9<;yaJe# zdO+i4yz zFg+oxBeSR;`5;hU>~=bV*Em%HTa&r09-Yx(d2Jf;5pO1N_pS)r9@y8y1i%a11jfG-m zb&VjXh+uP_rC_C~wTPuf;8f7Ye?TNV*&?;Y6&}cWHX@eObV^!5CihNnGDWw4+ggdHwYmr_lb2uCh8j}b*FQ-{vo@wHv@?@BKC4nX1kJ|8VHNZ!+D(lZjwJ16$A!SiXb*M{)d&tz?r%s1>vc08! zVgqxS@0E(caUPE8?cUpe*hYSif_j&1RgZcoIWXlJF}ipyrlm0-b@oledgH_qsS zZy|nu`pOqgBc#m}ip()N9VRq0%jD|`KHKIZyxN$>sl04*;=NfnPYO;?3b{so>;n^{ zZ#k?)gqB+6ZQjeh;(Q910yWz3C?j3{G+ghM_ewu0djcx$crD$P+X<*8f))h&h8gI1 z$f3SL`2nD!k6vD$a-6HD^FRebtI5hoH0TP`kkHdkuZ$q^{O$$1 z0gJIdrVkO(l9O04``p!T>>?7A7XwsEC8WC9yaZsrQp#%7V}NxP6y#*EK3bazv+!${ z`DiVBEm@T%Y%tcxTn>Rkb~;zEIOy?@OgtE(ZC;4f?&6}puPz6c@*+xs@wmXuv_HEz zHI3H)oI4$lIQ#gCdgaUl=BAd2yTZm)(q=Z()ydg1TQi zLEW4CynA|!XE9q69r*pEUpdKDzaPiHV7dp(SarFT8-O!f{|)68CdhZZVweB`002ov JPDHLkV1l6kMPdK| literal 0 HcmV?d00001 From c94d4feb26f564a68bbafffc69e6b459760b840a Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Mon, 22 Oct 2012 15:32:32 +0200 Subject: [PATCH 034/279] Remove trailing white space. --- js/contacts.js | 100 ++++++++++++++++++++++++------------------------- 1 file changed, 50 insertions(+), 50 deletions(-) diff --git a/js/contacts.js b/js/contacts.js index ae21c6d3..dd914f20 100644 --- a/js/contacts.js +++ b/js/contacts.js @@ -15,17 +15,17 @@ OC.Contacts = OC.Contacts || {}; */ var Contact = function(parent, id, access, data, listtemplate, fulltemplate, detailtemplates) { //console.log('contact:', id, access); //parent, id, data, listtemplate, fulltemplate); - this.parent = parent, - this.id = id, + this.parent = parent, + this.id = id, this.access = access, - this.data = data, + this.data = data, this.$listTemplate = listtemplate, this.$fullTemplate = fulltemplate; this.detailTemplates = detailtemplates; var self = this; this.multi_properties = ['EMAIL', 'TEL', 'IMPP', 'ADR', 'URL']; } - + Contact.prototype.setAsSaving = function(obj, state) { if(!obj) { return; @@ -41,7 +41,7 @@ OC.Contacts = OC.Contacts || {}; Contact.prototype.removeProperty = function(obj) { console.log('Contact.removeProperty', name) } - + Contact.prototype.addProperty = function($option, name) { console.log('Contact.addProperty', name) switch(name) { @@ -74,7 +74,7 @@ OC.Contacts = OC.Contacts || {}; break; } } - + /** * @brief Act on change of a property. * If this is a new contact it will first be saved to the datastore and a @@ -103,8 +103,8 @@ OC.Contacts = OC.Contacts || {}; $.post(OC.filePath('contacts', 'ajax', 'contact/saveproperty.php'), q, function(jsondata){ if(!jsondata) { $(document).trigger('status.contact.error', { - status: 'error', - message: t('contacts', 'Network or server error. Please inform administrator.'), + status: 'error', + message: t('contacts', 'Network or server error. Please inform administrator.'), }); self.setAsSaving(obj, false); return false; @@ -117,7 +117,7 @@ OC.Contacts = OC.Contacts || {}; return true; } else { $(document).trigger('status.contact.error', { - status: 'error', + status: 'error', message: jsondata.data.message, }); self.setAsSaving(obj, false); @@ -125,7 +125,7 @@ OC.Contacts = OC.Contacts || {}; } },'json'); } - + /** * Remove any open contact from the DOM. */ @@ -135,7 +135,7 @@ OC.Contacts = OC.Contacts || {}; this.$fullelem.remove(); } } - + /** * Remove any open contact from the DOM and detach it's list * element from the DOM. @@ -149,7 +149,7 @@ OC.Contacts = OC.Contacts || {}; return this.$listelem.detach(); } } - + /** * Set a contact to en/disabled depending on its permissions. * @param boolean enabled @@ -167,16 +167,16 @@ OC.Contacts = OC.Contacts || {}; }); $(document).trigger('status.contact.enabled', enabled); } - + /** * Delete contact from data store and remove it from the DOM * @param cb Optional callback function which * @returns An object with a variable 'status' of either success - * or 'error' + * or 'error' */ Contact.prototype.destroy = function(cb) { var self = this; - $.post(OC.filePath('contacts', 'ajax', 'contact/delete.php'), + $.post(OC.filePath('contacts', 'ajax', 'contact/delete.php'), {id: this.id}, function(jsondata) { if(jsondata && jsondata.status === 'success') { if(self.$listelem) { @@ -202,16 +202,16 @@ OC.Contacts = OC.Contacts || {}; } }); } - + Contact.prototype.queryStringFor = function(obj) { var q = 'id=' + this.id; var ptype = this.propertyTypeFor(obj); q += '&name=' + ptype; - + if(this.multi_properties.indexOf(ptype) !== -1) { q += '&checksum=' + this.checksumFor(obj); } - + if($(obj).hasClass('propertycontainer')) { q += '&value=' + encodeURIComponent($(obj).val()); } else { @@ -220,22 +220,22 @@ OC.Contacts = OC.Contacts || {}; } return q; } - + Contact.prototype.propertyContainerFor = function(obj) { - return $(obj).hasClass('.propertycontainer') - ? $(obj) + return $(obj).hasClass('.propertycontainer') + ? $(obj) : $(obj).parents('.propertycontainer').first(); } Contact.prototype.checksumFor = function(obj) { return this.propertyContainerFor(obj).data('checksum'); } - + Contact.prototype.propertyTypeFor = function(obj) { var ptype = this.propertyContainerFor(obj).data('element'); return ptype ? ptype.toUpperCase() : null; } - + /** * Render the list item * @return A jquery object to be inserted in the DOM @@ -250,7 +250,7 @@ OC.Contacts = OC.Contacts || {}; categories: this.getPreferredValue('CATEGORIES', []) .clean('').join(' / '), }); - if(this.access.owner !== OC.currentUser + if(this.access.owner !== OC.currentUser && !(this.access.permissions & OC.PERMISSION_UPDATE || this.access.permissions & OC.PERMISSION_DELETE)) { this.$listelem.find('input:checkbox').prop('disabled', true).css('opacity', '0'); @@ -272,9 +272,9 @@ OC.Contacts = OC.Contacts || {}; nickname: this.getPreferredValue('NICKNAME', ''), title: this.getPreferredValue('TITLE', ''), org: this.getPreferredValue('ORG', []).clean('').join(', '), // TODO Add parts if more than one. - bday: this.getPreferredValue('BDAY', '').length >= 10 - ? $.datepicker.formatDate('dd-mm-yy', - $.datepicker.parseDate('yy-mm-dd', + bday: this.getPreferredValue('BDAY', '').length >= 10 + ? $.datepicker.formatDate('dd-mm-yy', + $.datepicker.parseDate('yy-mm-dd', this.getPreferredValue('BDAY', '').substring(0, 10))) : '', } @@ -742,11 +742,11 @@ OC.Contacts = OC.Contacts || {}; console.log('pos', pos); return pos; } - + ContactList.prototype.closeContact = function(id) { this.contacts[parseInt(id)].close(); } - + /** * Jumps to an element in the contact list * @param number the number of the item starting with 0 @@ -756,7 +756,7 @@ OC.Contacts = OC.Contacts || {}; console.log('scrollTop', pos); this.$contactList.scrollTop(pos); }; - + /** * Returns a Contact object by searching for its id * @param id the id of the node @@ -781,7 +781,7 @@ OC.Contacts = OC.Contacts || {}; } return warn; } - + ContactList.prototype.delayedDeleteContact = function(id) { var self = this; this.currentContact = null; @@ -837,7 +837,7 @@ OC.Contacts = OC.Contacts || {}; updateQueue(id, removeFromQueue); return; } - + // Let contact remove itself. this.contacts[id].destroy(function(response) { console.log('deleteContact', response); @@ -857,7 +857,7 @@ OC.Contacts = OC.Contacts || {}; } }); } - + /** * Opens the contact with this id in edit mode * @param id the id of the contact @@ -900,18 +900,18 @@ OC.Contacts = OC.Contacts || {}; } return contact; } - + /** * Add contact * @param int offset */ ContactList.prototype.addContact = function() { var contact = new Contact( - this, + this, null, null, - null, - this.$contactListItemTemplate, + null, + this.$contactListItemTemplate, this.$contactFullTemplate, this.contactDetailTemplates ); @@ -920,16 +920,16 @@ OC.Contacts = OC.Contacts || {}; } return contact.renderContact(); } - + ContactList.prototype.getSelectedContacts = function() { var contacts = []; - + $.each(this.$contactList.find('tr > td > input:checkbox:visible:checked'), function(a, b) { contacts.push(parseInt($(b).parents('tr').first().data('id'))); }); return contacts; } - + ContactList.prototype.setCurrent = function(id, deselect_other) { self = this; if(deselect_other === true) { @@ -939,7 +939,7 @@ OC.Contacts = OC.Contacts || {}; } this.contacts[parseInt(id)].setCurrent(true); } - + // Should only be neccesary with progressive loading, but it's damn fast, so... ;) ContactList.prototype.doSort = function() { var self = this; @@ -948,12 +948,12 @@ OC.Contacts = OC.Contacts || {}; rows.sort(function(a, b) { return keyA = $(a).find('td.name').text().toUpperCase().localeCompare($(b).find('td.name').text().toUpperCase()); }); - + $.each(rows, function(index, row) { self.$contactList.append(row); }); } - + /** * Load contacts * @param int offset @@ -967,19 +967,19 @@ OC.Contacts = OC.Contacts || {}; self.addressbooks = {}; $.each(jsondata.data.addressbooks, function(i, book) { self.addressbooks[parseInt(book.id)] = { - owner: book.userid, + owner: book.userid, permissions: parseInt(book.permissions), aid: parseInt(book.id), }; }); $.each(jsondata.data.contacts, function(c, contact) { - self.contacts[parseInt(contact.id)] + self.contacts[parseInt(contact.id)] = new Contact( - self, + self, contact.id, self.addressbooks[parseInt(contact.aid)], - contact.data, - self.$contactListItemTemplate, + contact.data, + self.$contactListItemTemplate, self.$contactFullTemplate, self.contactDetailTemplates ); @@ -990,8 +990,8 @@ OC.Contacts = OC.Contacts || {}; }); self.doSort(); $(document).trigger('status.contacts.loaded', { - status: true, - numcontacts: jsondata.data.contacts.length + status: true, + numcontacts: jsondata.data.contacts.length }); self.setCurrent(self.$contactList.find('tr:first-child').data('id'), false); } From 6badc525d935011bfdf5b9e03866af9ddbe95780 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Mon, 22 Oct 2012 15:33:44 +0200 Subject: [PATCH 035/279] Remove trailing white space. --- js/contacts.js | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/js/contacts.js b/js/contacts.js index dd914f20..3e498381 100644 --- a/js/contacts.js +++ b/js/contacts.js @@ -381,7 +381,7 @@ OC.Contacts = OC.Contacts || {}; $property.find('select.impp').val(property.parameters[param].toLowerCase()); } } - if(self.access.owner === OC.currentUser + if(self.access.owner === OC.currentUser || self.access.permissions & OC.PERMISSION_UPDATE || self.access.permissions & OC.PERMISSION_DELETE) { $property.find('select.type[name="parameters[TYPE][]"]') @@ -400,7 +400,7 @@ OC.Contacts = OC.Contacts || {}; } } }); - if(this.access.owner !== OC.currentUser + if(this.access.owner !== OC.currentUser && !(this.access.permissions & OC.PERMISSION_UPDATE || this.access.permissions & OC.PERMISSION_DELETE)) { this.setEnabled(false); @@ -411,11 +411,11 @@ OC.Contacts = OC.Contacts || {}; } Contact.prototype.isEditable = function() { - return ((this.access.owner === OC.currentUser) + return ((this.access.owner === OC.currentUser) || (this.access.permissions & OC.PERMISSION_UPDATE || this.access.permissions & OC.PERMISSION_DELETE)); } - + /** * Render a simple property. Used for EMAIL and TEL. * @return A jquery object to be injected in the DOM @@ -425,7 +425,7 @@ OC.Contacts = OC.Contacts || {}; console.log('No template for', name); return; } - var values = property + var values = property ? { value: property.value, checksum: property.checksum } : { value: '', checksum: 'new' }; $elem = this.detailTemplates[name].octemplate(values); @@ -441,8 +441,8 @@ OC.Contacts = OC.Contacts || {}; console.log('No template for adr', this.detailTemplates); return; } - var values = property ? { - value: property.value.clean('').join(', '), + var values = property ? { + value: property.value.clean('').join(', '), checksum: property.checksum, adr0: property.value[0] || '', adr1: property.value[1] || '', @@ -465,14 +465,14 @@ OC.Contacts = OC.Contacts || {}; console.log('No template for impp', this.detailTemplates); return; } - var values = property ? { + var values = property ? { value: property.value, checksum: property.checksum, } : {value: '', checksum: 'new'}; $elem = this.detailTemplates['impp'].octemplate(values); return $elem; } - + /** * Render the PHOTO property. */ @@ -494,7 +494,7 @@ OC.Contacts = OC.Contacts || {}; }).error(function () { OC.notify({message:t('contacts','Error loading profile picture.')}); }).attr('src', OC.linkTo('contacts', 'photo.php')+'?id='+self.id+refreshstr); - + if(!dontloadhandlers && this.isEditable()) { this.$photowrapper.on('mouseenter', function() { $phototools.slideDown(200); @@ -511,19 +511,19 @@ OC.Contacts = OC.Contacts || {}; $phototools.find('.edit').on('click', function() { console.log('TODO: edit photo'); $(document).trigger('request.edit.contactphoto', { - id: self.id, + id: self.id, }); }); $phototools.find('.cloud').on('click', function() { console.log('select photo from cloud'); $(document).trigger('request.select.contactphoto.fromcloud', { - id: self.id, + id: self.id, }); }); $phototools.find('.upload').on('click', function() { console.log('select photo from local'); $(document).trigger('request.select.contactphoto.fromlocal', { - id: self.id, + id: self.id, }); }); if(this.data.PHOTO) { @@ -552,7 +552,7 @@ OC.Contacts = OC.Contacts || {}; } return this.$listelem; } - + /** * Get the preferred value for a property. * If a preferred value is not found the first one will be returned. @@ -582,7 +582,7 @@ OC.Contacts = OC.Contacts || {}; } return pref; } - + /** * Returns true/false depending on the contact being in the * specified group. @@ -593,7 +593,7 @@ OC.Contacts = OC.Contacts || {}; if(!this.data.CATEGORIES) { return false; } - + categories = this.data.CATEGORIES[0].value; for(var i in categories) { if(typeof categories[i] === 'string' && (name.toLowerCase() === categories[i].toLowerCase())) { @@ -691,7 +691,7 @@ OC.Contacts = OC.Contacts || {}; this.contactDetailTemplates = contactdetailtemplates; this.$contactList.scrollTop(0); this.loadContacts(0); - + } /** From 3bbf951fda00a17650d708c75c3dae0cc28d72b4 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Mon, 22 Oct 2012 15:34:15 +0200 Subject: [PATCH 036/279] Add method to show/hide shared addressbooks. --- js/contacts.js | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/js/contacts.js b/js/contacts.js index 3e498381..d2dc47e3 100644 --- a/js/contacts.js +++ b/js/contacts.js @@ -712,7 +712,24 @@ OC.Contacts = OC.Contacts || {}; } } } - + + /** + * Show/hide contacts belonging to shared addressbooks. + * @param boolean show. Whether to show or hide. + */ + ContactList.prototype.showSharedAddressbooks = function(show) { + console.log('ContactList.showSharedAddressbooks', show); + for(var contact in this.contacts) { + if(this.contacts[contact].access.owner !== OC.currentUser) { + if(show) { + this.contacts[contact].getListItemElement().show(); + } else { + this.contacts[contact].getListItemElement().hide(); + } + } + } + } + /** * Show contacts in list * @param Array contacts. A list of contact ids. From 148c69ac331ee7eba2af243c174be6555afbe127 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Mon, 22 Oct 2012 15:35:33 +0200 Subject: [PATCH 037/279] Finished implementing favorites. --- ajax/categories/list.php | 12 +++- css/contacts.css | 14 ++-- js/app.js | 139 ++++++++++++++++++++++++++++++++------- js/contacts.js | 31 +++++++++ templates/contacts.php | 1 + 5 files changed, 168 insertions(+), 29 deletions(-) diff --git a/ajax/categories/list.php b/ajax/categories/list.php index a588d853..1af6a8b5 100644 --- a/ajax/categories/list.php +++ b/ajax/categories/list.php @@ -15,7 +15,7 @@ $categories = $catmgr->categories(OC_VCategories::FORMAT_MAP); foreach($categories as &$category) { $ids = array(); $contacts = $catmgr->itemsForCategory( - $category['name'], + $category['name'], array( 'tablename' => '*PREFIX*contacts_cards', 'fields' => array('id',), @@ -26,4 +26,12 @@ foreach($categories as &$category) { $category['contacts'] = $ids; } -OCP\JSON::success(array('data' => array('categories'=>$categories))); +$favorites = $catmgr->getFavorites(); + +OCP\JSON::success(array( + 'data' => array( + 'categories' => $categories, + 'favorites' => $favorites, + ) + ) +); diff --git a/css/contacts.css b/css/contacts.css index e6402744..125ccf3d 100644 --- a/css/contacts.css +++ b/css/contacts.css @@ -54,10 +54,12 @@ dl.form { display: inline-block; width: auto; margin: 0; padding: 0; cursor: nor .download { background:url('%webroot%/core/img/actions/download.svg') no-repeat center; } .cloud { background:url('%webroot%/core/img/places/picture.svg') no-repeat center; } .globe { background:url('%webroot%/core/img/actions/public.svg') no-repeat center; } +.starred { display: inline-block; height: 22px; width: 22px; padding: 0; margin: 0; background:url('%appswebroot%/contacts/img/starred.png') no-repeat center; } .transparent{ opacity: 0.6; } .float { float: left; display: inline-block; width: auto; } .break { clear: both; } .loading { background: url('%webroot%/core/img/loading.gif') no-repeat center !important; /*cursor: progress; */ cursor: wait; } +.wait { opacity: cursor: wait; } .control { border: 1px solid #DDDDDD; border-radius: 0.3em; @@ -87,7 +89,7 @@ dl.addresscard .action { float: right; } /* Properties */ .fullname { font-weight:bold; font-size:1.5em; width: 18em; } -.singleproperties{ display: inline-block; float: left; width: 20em;} +.singleproperties{ display: inline-block; float: left; width: 25em;} .propertylist li.propertycontainer { white-space: nowrap; min-width: 38em; display: block; clear: both; } .propertylist li.propertycontainer > .listactions { display: inline-block; position: absolute; clear: none; opacity: 0; } @@ -153,7 +155,9 @@ input.propertytype { float: left; font-size: .8em; width: 8em !important; direct #phototools li a { float:left; cursor:pointer; width:22px; height:22px; opacity: 0.6; } #phototools li a:hover { opacity: 0.8; } #contactphoto_fileupload, #import_fileupload { -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)"; filter:alpha(opacity=0); opacity:0; z-index:1001; width:0; height:0;} - +.favorite { display: inline-block; float: left; height: 20px; width: 20px; background:url('%appswebroot%/contacts/img/inactive_star.png') no-repeat center; } +.favorite.active, .favorite:hover { background:url('%appswebroot%/contacts/img/active_star.png') no-repeat center; } +.favorite.inactive { background:url('%appswebroot%/contacts/img/inactive_star.png') no-repeat center; } /* Header */ #contactsheader { position: fixed; padding: 0; margin:0; top:3.5em; left: 32.5em; right: 0; height: 4em; border-bottom: 1px solid #DDDDDD; z-index: 50; } @@ -174,8 +178,8 @@ input.propertytype { float: left; font-size: .8em; width: 8em !important; direct /* Contact layout */ -#contact > ul { - font-size: 10px; +#contact > ul { + font-size: 10px; /*display: table; border-spacing: 1em; border: thin solid black;*/ @@ -184,7 +188,7 @@ input.propertytype { float: left; font-size: .8em; width: 8em !important; direct display: inline-block; padding: 1em; /*display: table-cell;*/ -} +} #rightcontent footer { padding: 1em; } diff --git a/js/app.js b/js/app.js index 6d756c97..22a8af9b 100644 --- a/js/app.js +++ b/js/app.js @@ -21,7 +21,7 @@ if (typeof Object.create !== 'function') { Array.prototype.clean = function(deleteValue) { for (var i = 0; i < this.length; i++) { - if (this[i] == deleteValue) { + if (this[i] == deleteValue) { this.splice(i, 1); i--; } @@ -110,10 +110,57 @@ GroupList.prototype.findById = function(id) { return this.$groupList.find('h3[data-id="' + id + '"]'); } +GroupList.prototype.isFavorite = function(contactid) { + var $groupelem = this.findById('fav'); + var contacts = $groupelem.data('contacts'); + return (contacts.indexOf(contactid) !== -1); +} + +GroupList.prototype.setAsFavorite = function(contactid, state, cb) { + contactid = parseInt(contactid); + var $groupelem = this.findById('fav'); + var contacts = $groupelem.data('contacts'); + if(state) { + OCCategories.addToFavorites(contactid, 'contact', function(jsondata) { + if(jsondata.status === 'success') { + contacts.push(contactid); + $groupelem.data('contacts', contacts); + $groupelem.find('.numcontacts').text(contacts.length); + if(contacts.length > 0 && $groupelem.is(':hidden')) { + $groupelem.show(); + } + } + if(typeof cb === 'function') { + cb(jsondata); + } else if(jsondata.status !== 'success') { + OC.notify({message:t('contacts', jsondata.data.message)}); + } + }); + } else { + OCCategories.removeFromFavorites(contactid, 'contact', function(jsondata) { + if(jsondata.status === 'success') { + contacts.splice(contacts.indexOf(contactid), 1); + //console.log('contacts', contacts, contacts.indexOf(id), contacts.indexOf(String(id))); + $groupelem.data('contacts', contacts); + $groupelem.find('.numcontacts').text(contacts.length); + if(contacts.length === 0 && $groupelem.is(':visible')) { + $groupelem.hide(); + } + } + if(typeof cb === 'function') { + cb(jsondata); + } else if(jsondata.status !== 'success') { + OC.notify({message:t('contacts', jsondata.data.message)}); + } + }); + } +} + GroupList.prototype.addTo = function(contactid, groupid, cb) { + console.log('GroupList.addTo', contactid, groupid); var $groupelem = this.findById(groupid); var contacts = $groupelem.data('contacts'); - if(contacts.indexOf(String(contactid)) === -1) { + if(contacts.indexOf(contactid) === -1) { $.post(OC.filePath('contacts', 'ajax', 'categories/addto.php'), {contactid: contactid, categoryid: groupid},function(jsondata) { if(!jsondata) { OC.notify({message:t('contacts', 'Network or server error. Please inform administrator.')}); @@ -211,8 +258,8 @@ GroupList.prototype.addGroup = function(name, contacts, cb) { if (jsondata && jsondata.status == 'success') { var tmpl = self.$groupListItemTemplate; var $elem = (tmpl).octemplate({ - id: jsondata.data.id, - type: 'category', + id: jsondata.data.id, + type: 'category', num: contacts.length, name: name, }) @@ -246,19 +293,32 @@ GroupList.prototype.loadGroups = function(numcontacts, cb) { var self = this; var $groupList = this.$groupList; var tmpl = this.$groupListItemTemplate; - + tmpl.octemplate({id: 'all', type: 'all', num: numcontacts, name: t('contacts', 'All')}).appendTo($groupList); - tmpl.octemplate({id: 'fav', type: 'fav', num: '', name: t('contacts', 'Favorites')}).appendTo($groupList); $.getJSON(OC.filePath('contacts', 'ajax', 'categories/list.php'), {}, function(jsondata) { if (jsondata && jsondata.status == 'success') { + // Favorites + var contacts = $.map(jsondata.data.favorites, function(c) {return parseInt(c)}); + var $elem = tmpl.octemplate({ + id: 'fav', + type: 'fav', + num: contacts.length, + name: t('contacts', 'Favorites') + }).appendTo($groupList); + $elem.data('contacts', contacts).find('.numcontacts').before(''); + if(contacts.length === 0) { + $elem.hide(); + } + console.log('favorites', $elem.data('contacts')); + // Normal groups $.each(jsondata.data.categories, function(c, category) { var contacts = $.map(category.contacts, function(c) {return parseInt(c)}); var $elem = (tmpl).octemplate({ - id: category.id, - type: 'category', + id: category.id, + type: 'category', num: contacts.length, name: category.name, - }) + }); self.categories.push({id: category.id, name: category.name}); $elem.data('contacts', contacts) $elem.data('name', category.name) @@ -283,8 +343,8 @@ OC.Contacts = OC.Contacts || { this.isScrolling = false; this.cacheElements(); this.Contacts = new OC.Contacts.ContactList( - this.$contactList, - this.$contactListItemTemplate, + this.$contactList, + this.$contactListItemTemplate, this.$contactFullTemplate, this.detailTemplates ); @@ -384,7 +444,7 @@ OC.Contacts = OC.Contacts || { }, bindEvents: function() { var self = this; - + // App specific events $(document).bind('status.contact.deleted', function(e, data) { var id = parseInt(data.id); @@ -486,6 +546,24 @@ OC.Contacts = OC.Contacts || { console.log('request.addressbook.activate', result); self.Contacts.showFromAddressbook(result.id, result.activate); }); + + $(document).bind('request.setasfavorite', function(e, result) { + console.log('request.setasfavorite', result); + self.Groups.setAsFavorite(result.id, result.state, function(jsondata) { + if(jsondata.status === 'success') { + $(document).trigger('status.contact.favoritestate', { + status: 'success', + id: result.id, + state: result.state, + }); + } else { + OC.notify({message:t('contacts', jsondata.data.message)}); + $(document).trigger('status.contact.favoritestate', { + status: 'error', + }); + } + }); + }); // mark items whose title was hid under the top edge as read /*this.$rightContent.scroll(function() { // prevent too many scroll requests; @@ -534,7 +612,7 @@ OC.Contacts = OC.Contacts || { var $opt = $(this).find('option:selected'); var action = $opt.parent().data('action'); var ids, buildnow = false; - + if($opt.val() === 'add') { console.log('add group...'); self.$groups.val(-1); @@ -553,7 +631,7 @@ OC.Contacts = OC.Contacts || { var contacts = self.Contacts.getSelectedContacts(); self.Groups.addGroup( $dlg.find('input:text').val(), - contacts, + contacts, function(response) { if(response.result === 'success') { for(var id in contacts) { @@ -581,7 +659,7 @@ OC.Contacts = OC.Contacts || { }); return; } - + // If a contact is open the action is only applied to that, // otherwise on all selected items. if(self.currentid) { @@ -660,12 +738,19 @@ OC.Contacts = OC.Contacts || { self.$toggleAll.show(); self.showActions(['add', 'delete']); $(this).addClass('active'); - if($(this).data('type') === 'category') { + var gtype = $(this).data('type'); + var gid = $(this).data('id'); + if(gtype === 'category' || gtype === 'fav') { console.log('contacts', $(this).data('contacts')); self.Contacts.showContacts($(this).data('contacts')); } else { - self.Contacts.showContacts($(this).data('id')); + self.Contacts.showContacts(gid); } + $.post(OC.filePath('contacts', 'ajax', 'setpreference.php'), {'key':'lastgroup', 'value':gid}, function(jsondata) { + if(jsondata.status !== 'success') { + OC.notify({message: jsondata.data.message}); + } + }); self.$rightContent.scrollTop(0); }); // Contact list. Either open a contact or perform an action (mailto etc.) @@ -833,7 +918,7 @@ OC.Contacts = OC.Contacts || { } }); - + $('[title]').tipsy(); // find all with a title attribute and tipsy them }, jumpToContact: function(id) { @@ -853,6 +938,16 @@ OC.Contacts = OC.Contacts || { this.$contactList.hide(); this.$toggleAll.hide(); var $contactelem = this.Contacts.showContact(this.currentid); + var self = this; + // FIXME: This should (maybe) be an argument to the Contact + setTimeout(function() { + var state = self.Groups.isFavorite(self.currentid); + $(document).trigger('status.contact.favoritestate', { + status: 'success', + id: self.currentid, + state: state, + }); + }, 2000); this.$rightContent.prepend($contactelem); this.buildGroupSelect(); }, @@ -862,7 +957,7 @@ OC.Contacts = OC.Contacts || { cloudPhotoSelected:function(id, path) { var self = this; console.log('cloudPhotoSelected, id', id) - $.getJSON(OC.filePath('contacts', 'ajax', 'oc_photo.php'), + $.getJSON(OC.filePath('contacts', 'ajax', 'oc_photo.php'), {path: path, id: id},function(jsondata) { if(jsondata.status == 'success') { //alert(jsondata.data.page); @@ -905,7 +1000,7 @@ OC.Contacts = OC.Contacts || { var clearCoords = function() { $('#coords input').val(''); }; - + var self = this; if(!this.$cropBoxTmpl) { this.$cropBoxTmpl = $('#cropBoxTemplate'); @@ -963,7 +1058,7 @@ OC.Contacts = OC.Contacts || { if(jsondata && jsondata.status === 'success') { // load cropped photo. $(document).trigger('status.contact.photoupdated', { - id: jsondata.data.id, + id: jsondata.data.id, }); } else { if(!jsondata) { @@ -1012,7 +1107,7 @@ OC.Contacts = OC.Contacts || { $.fn.octemplate = function(options) { if ( this.length ) { var _template = Object.create(Template); - return _template.init(options, this); + return _template.init(options, this); } }; diff --git a/js/contacts.js b/js/contacts.js index d2dc47e3..86f5e53c 100644 --- a/js/contacts.js +++ b/js/contacts.js @@ -291,6 +291,37 @@ OC.Contacts = OC.Contacts || {}; console.log('change', event); self.saveProperty({obj:event.target}); }); + this.$fullelem.on('click', '.favorite', function(event) { + if(typeof self.is_favorite === 'undefined') { + console.log('Favorite state not set yet.'); + self.is_favorite == false; + } + console.log('favorite', event); + $(this).addClass('wait'); + $(document).trigger('request.setasfavorite', { + id: self.id, + state: !self.is_favorite, + }); + }); + $(document).bind('status.contact.favoritestate', function(e, result) { + console.log('status.contact.favoritestate', result); + if(parseInt(result.id) !== parseInt(self.id)) { + console.log(result.id, 'is not me:', self.id); + return; + } + var $favstar = self.$fullelem.find('.favorite'); + $favstar.removeClass('wait'); + if(result.status === 'success') { + self.is_favorite = result.state; + if(result.state === true) { + $favstar.removeClass('inactive').addClass('active'); + } else { + $favstar.removeClass('active').addClass('inactive'); + } + } else { + // TODO:... + } + }); this.$fullelem.find('form').on('submit', function(event) { console.log('submit', this, event); return false; diff --git a/templates/contacts.php b/templates/contacts.php index 6f9966a5..38cc4bc5 100644 --- a/templates/contacts.php +++ b/templates/contacts.php @@ -120,6 +120,7 @@
  • +
    From 3600c6c74a65e68b01aa3e49adb22c61624895ad Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Tue, 23 Oct 2012 06:24:22 +0200 Subject: [PATCH 038/279] Added method to test if a contact is in a group. --- js/app.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/js/app.js b/js/app.js index 22a8af9b..59cb92cd 100644 --- a/js/app.js +++ b/js/app.js @@ -111,7 +111,11 @@ GroupList.prototype.findById = function(id) { } GroupList.prototype.isFavorite = function(contactid) { - var $groupelem = this.findById('fav'); + return this.inGroup(contactid, 'fav'); +} + +GroupList.prototype.inGroup = function(contactid, groupid) { + var $groupelem = this.findById(groupid); var contacts = $groupelem.data('contacts'); return (contacts.indexOf(contactid) !== -1); } From 7e52c45675100798bd25259d73fa4df9d7e75bce Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Tue, 23 Oct 2012 06:26:51 +0200 Subject: [PATCH 039/279] Added method to get value from an element in the DOM. --- js/contacts.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/js/contacts.js b/js/contacts.js index 86f5e53c..f220918d 100644 --- a/js/contacts.js +++ b/js/contacts.js @@ -231,6 +231,10 @@ OC.Contacts = OC.Contacts || {}; return this.propertyContainerFor(obj).data('checksum'); } + Contact.prototype.valueFor = function(obj) { + return this.propertyContainerFor(obj).find('input.value').val(); + } + Contact.prototype.propertyTypeFor = function(obj) { var ptype = this.propertyContainerFor(obj).data('element'); return ptype ? ptype.toUpperCase() : null; From 2dba1d3672ed1b57c672e9b751d33e3e04380bd8 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Tue, 23 Oct 2012 06:27:22 +0200 Subject: [PATCH 040/279] Re-added deleting properties. --- ajax/contact/deleteproperty.php | 35 ++++++++++---- css/contacts.css | 3 +- js/contacts.js | 81 ++++++++++++++++++++++++++++++--- templates/contacts.php | 28 +++++++----- 4 files changed, 119 insertions(+), 28 deletions(-) diff --git a/ajax/contact/deleteproperty.php b/ajax/contact/deleteproperty.php index b76b6e55..dbb93a31 100644 --- a/ajax/contact/deleteproperty.php +++ b/ajax/contact/deleteproperty.php @@ -27,18 +27,37 @@ OCP\JSON::callCheck(); require_once __DIR__.'/../loghandler.php'; -$id = $_POST['id']; -$checksum = $_POST['checksum']; +$id = isset($_POST['id']) ? $_POST['id'] : null; +$name = isset($_POST['name']) ? $_POST['name'] : null; +$checksum = isset($_POST['checksum']) ? $_POST['checksum'] : null; $l10n = OC_Contacts_App::$l10n; -$vcard = OC_Contacts_App::getContactVCard( $id ); -$line = OC_Contacts_App::getPropertyLineByChecksum($vcard, $checksum); -if(is_null($line)) { - bailOut($l10n->t('Information about vCard is incorrect. Please reload the page.')); - exit(); +$multi_properties = array('EMAIL', 'TEL', 'IMPP', 'ADR', 'URL'); + +if(!$id) { + bailOut(OC_Contacts_App::$l10n->t('id is not set.')); } -unset($vcard->children[$line]); +if(!$name) { + bailOut(OC_Contacts_App::$l10n->t('element name is not set.')); +} + +if(!$checksum && in_array($name, $multi_properties)) { + bailOut(OC_Contacts_App::$l10n->t('checksum is not set.')); +} + +$vcard = OC_Contacts_App::getContactVCard( $id ); + +if(!is_null($checksum)) { + $line = OC_Contacts_App::getPropertyLineByChecksum($vcard, $checksum); + if(is_null($line)) { + bailOut($l10n->t('Information about vCard is incorrect. Please reload the page.')); + exit(); + } + unset($vcard->children[$line]); +} else { + unset($vcard->{$name}); +} try { OC_Contacts_VCard::edit($id, $vcard); diff --git a/css/contacts.css b/css/contacts.css index 125ccf3d..37ee29ec 100644 --- a/css/contacts.css +++ b/css/contacts.css @@ -45,8 +45,9 @@ input:hover:not([type="checkbox"]), input:active:not([type="checkbox"]), textare dl.form { display: inline-block; width: auto; margin: 0; padding: 0; cursor: normal; } .form dt { display: table-cell; clear: left; float: left; width: 7em; margin: 0; padding: 0.8em 0.5em 0 0; text-align:right; text-overflow:ellipsis; o-text-overflow: ellipsis; vertical-align: text-bottom; color: #bbb;/* white-space: pre-wrap; white-space: -moz-pre-wrap !important; white-space: -pre-wrap; white-space: -o-pre-wrap;*/ } .form dd { display: table-cell; clear: right; float: left; margin: 0; padding: 0; white-space: nowrap; vertical-align: text-bottom; } +.action { display: inline-block; } .add { background:url('%webroot%/core/img/actions/add.svg') no-repeat center; clear: both; } -.delete { background:url('%webroot%/core/img/actions/delete.svg') no-repeat center; } +.delete { background:url('%webroot%/core/img/actions/delete.png') no-repeat center; } .edit { background:url('%webroot%/core/img/actions/rename.svg') no-repeat center; } .share { background:url('%webroot%/core/img/actions/share.svg') no-repeat center; } .mail { background:url('%webroot%/core/img/actions/mail.svg') no-repeat center; } diff --git a/js/contacts.js b/js/contacts.js index f220918d..1dbdf387 100644 --- a/js/contacts.js +++ b/js/contacts.js @@ -38,10 +38,6 @@ OC.Contacts = OC.Contacts || {}; } } - Contact.prototype.removeProperty = function(obj) { - console.log('Contact.removeProperty', name) - } - Contact.prototype.addProperty = function($option, name) { console.log('Contact.addProperty', name) switch(name) { @@ -75,6 +71,54 @@ OC.Contacts = OC.Contacts || {}; } } + Contact.prototype.deleteProperty = function(params) { + var obj = params.obj; + if(!this.enabled) { + return; + } + var element = this.propertyTypeFor(obj); + var $container = this.propertyContainerFor(obj); + console.log('Contact.deleteProperty, element', element, $container); + var params = { + name: element, + id: this.id + }; + if(this.multi_properties.indexOf(element) !== -1) { + params['checksum'] = this.checksumFor(obj); + } + this.setAsSaving(obj, true); + var self = this; + $.post(OC.filePath('contacts', 'ajax', 'contact/deleteproperty.php'), params, function(jsondata) { + if(!jsondata) { + $(document).trigger('status.contact.error', { + status: 'error', + message: t('contacts', 'Network or server error. Please inform administrator.'), + }); + self.setAsSaving(obj, false); + return false; + } + if(jsondata.status == 'success') { + // TODO: Remove from internal data structure + if(self.multi_properties.indexOf(element) !== -1) { + $container.remove(); + } else { + self.setAsSaving(obj, false); + self.$fullelem.find('[data-element="' + element.toLowerCase() + '"]').hide(); + $container.find('input.value').val(''); + self.$addMenu.find('option[value="' + element.toUpperCase() + '"]').prop('disabled', false); + } + return true; + } else { + $(document).trigger('status.contact.error', { + status: 'error', + message: jsondata.data.message, + }); + self.setAsSaving(obj, false); + return false; + } + },'json'); + } + /** * @brief Act on change of a property. * If this is a new contact it will first be saved to the datastore and a @@ -93,6 +137,7 @@ OC.Contacts = OC.Contacts || {}; if(params.obj) { obj = params.obj; q = this.queryStringFor(obj); + element = this.propertyTypeFor(obj); } else { element = params.name; q += 'value=' + encodeURIComponent(params.value) + '&name=' + element; @@ -110,8 +155,15 @@ OC.Contacts = OC.Contacts || {}; return false; } if(jsondata.status == 'success') { + console.log(self.data[element]); + if(!self.data[element]) { + self.data[element] = []; + } if(self.multi_properties.indexOf(element) !== -1) { - $container.data('checksum', jsondata.data.checksum); + self.propertyContainerFor(obj).data('checksum', jsondata.data.checksum); + } else { + // TODO: Save value and parameters internally + self.data[element][0] = {name: element}; } self.setAsSaving(obj, false); return true; @@ -216,7 +268,7 @@ OC.Contacts = OC.Contacts || {}; q += '&value=' + encodeURIComponent($(obj).val()); } else { q += '&' + this.propertyContainerFor(obj) - .find('input.value,select.value,textarea.value').serialize(); + .find('input.value,select.value,textarea.value,.parameter').serialize(); } return q; } @@ -291,7 +343,22 @@ OC.Contacts = OC.Contacts || {}; self.addProperty($opt, $(this).val()); $(this).val(''); }); - this.$fullelem.on('change', '.value', function(event) { + var $singleelements = this.$fullelem.find('dd.propertycontainer'); + $singleelements.find('.action').css('opacity', '0'); + $singleelements.on('mouseenter', function() { + $(this).find('.action').css('opacity', '1'); + }).on('mouseleave', function() { + $(this).find('.action').css('opacity', '0'); + }); + this.$fullelem.on('click keydown', '.delete', function(event) { + console.log('delete', event); + $('.tipsy').remove(); + if(wrongKey(event)) { + return; + } + self.deleteProperty({obj:event.target}); + }); + this.$fullelem.on('change', '.value,.parameter', function(event) { console.log('change', event); self.saveProperty({obj:event.target}); }); diff --git a/templates/contacts.php b/templates/contacts.php index 38cc4bc5..2885e70a 100644 --- a/templates/contacts.php +++ b/templates/contacts.php @@ -89,7 +89,7 @@ + + + + From 1706fe341248639b499e0a1276b6b78eda02b431 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Fri, 7 Dec 2012 14:59:28 +0100 Subject: [PATCH 199/279] Contacts: Add/remove address book structure. --- js/contacts.js | 32 ++++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/js/contacts.js b/js/contacts.js index 0fde124d..a1ed7a5a 100644 --- a/js/contacts.js +++ b/js/contacts.js @@ -1380,6 +1380,29 @@ OC.Contacts = OC.Contacts || {}; }); } + /** + * Save addressbook data + * @param int id + */ + ContactList.prototype.unsetAddressbook = function(id) { + delete this.addressbooks[id]; + } + + /** + * Save addressbook data + * @param object book + */ + ContactList.prototype.setAddressbook = function(book) { + this.addressbooks[parseInt(book.id)] = { + owner: book.userid, + uri: book.uri, + permissions: parseInt(book.permissions), + id: parseInt(book.id), + displayname: book.displayname, + description: book.description, + active: Boolean(parseInt(book.active)), + }; + } /** * Load contacts * @param int offset @@ -1392,14 +1415,7 @@ OC.Contacts = OC.Contacts || {}; console.log('ContactList.loadContacts', jsondata.data); self.addressbooks = {}; $.each(jsondata.data.addressbooks, function(i, book) { - self.addressbooks[parseInt(book.id)] = { - owner: book.userid, - permissions: parseInt(book.permissions), - id: parseInt(book.id), - displayname: book.displayname, - description: book.description, - active: Boolean(parseInt(book.active)), - }; + self.setAddressbook(book); }); $.each(jsondata.data.contacts, function(c, contact) { self.contacts[parseInt(contact.id)] From 62ba93729614fe80c926e1108d58611fdc8cfad9 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Fri, 7 Dec 2012 15:00:09 +0100 Subject: [PATCH 200/279] Contacts: Remove unused method. --- js/contacts.js | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/js/contacts.js b/js/contacts.js index a1ed7a5a..563e2d28 100644 --- a/js/contacts.js +++ b/js/contacts.js @@ -1172,16 +1172,6 @@ OC.Contacts = OC.Contacts || {}; this.contacts[parseInt(id)].close(); } - /** - * Jumps to an element in the contact list - * @param number the number of the item starting with 0 - */ - ContactList.prototype.jumpToContact = function(id) { - var pos = this.contactPos(id); - console.log('scrollTop', pos); - this.$contactList.scrollTop(pos); - }; - /** * Returns a Contact object by searching for its id * @param id the id of the node From 0d863fe1b5e703e5dc77a24ee9ab93f2088c1f85 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Fri, 7 Dec 2012 15:03:42 +0100 Subject: [PATCH 201/279] Contacts: Move delete button. --- css/contacts.css | 16 +++++++++++++--- templates/contacts.php | 2 +- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/css/contacts.css b/css/contacts.css index 8a7f19d5..71f1b874 100644 --- a/css/contacts.css +++ b/css/contacts.css @@ -285,12 +285,22 @@ input.propertytype { float: left; font-size: .8em; width: 8em !important; direct .favorite.inactive { background:url('%appswebroot%/contacts/img/inactive_star.png') no-repeat center; } /* Header */ -#contactsheader { position: fixed; box-sizing: border-box; padding: 0; margin:0; top:3.5em; left: 32.5em; right: 0; height: 4em; border-bottom: 1px solid #DDDDDD; z-index: 50; } -#contactsheader div.actions { padding: 0 0.5em; margin: 0 auto; height: 100%; width: 90%; } +#contactsheader { + position: fixed; + -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; + padding: 0; margin:0; + top:3.5em; left: 32.5em; right: 0; height: 4em; + border-bottom: 1px solid #DDDDDD; z-index: 50; +} +#contactsheader div.actions { + -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; + padding: 0 .5em 0 4em; margin: 0 auto; + height: 100%; width: 100%; +} #contactsheader button, #contactsheader select { position: relative; float: left; min-width: 26px; height: 26px; margin: .7em; padding: .2em; clear: none; } #contactsheader .back { } #contactsheader .import { background:url('%webroot%/core/img/actions/upload.svg') no-repeat center; } -#contactsheader .delete { background:url('%webroot%/core/img/actions/delete.svg') no-repeat center; } +#contactsheader .delete { background:url('%webroot%/core/img/actions/delete.svg') no-repeat center; float: right;} #contactsheader .list.add { margin-left: 5em; } diff --git a/templates/contacts.php b/templates/contacts.php index d6399536..f36ae6d1 100644 --- a/templates/contacts.php +++ b/templates/contacts.php @@ -62,11 +62,11 @@ - +
    From d2ef4c169336cc2733dbe2b41b369b5742bb5d29 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Fri, 7 Dec 2012 15:06:01 +0100 Subject: [PATCH 202/279] Contacts: css cleanup. --- css/contacts.css | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/css/contacts.css b/css/contacts.css index 71f1b874..9d5c8a1d 100644 --- a/css/contacts.css +++ b/css/contacts.css @@ -5,7 +5,6 @@ height: 14px; width: 14px; border: 1px solid #fff; -moz-appearance:none; -webkit-appearance: none; - -moz-box-sizing:none; box-sizing:none; -moz-box-shadow: none; -webkit-box-shadow: none; box-shadow: none; -moz-border-radius: 2px; -webkit-border-radius: 2px; border-radius: 2px; } @@ -104,12 +103,11 @@ #content input:not([type="checkbox"]), #content select, #content textarea { background-color: #fefefe; border: 1px solid #fff !important; -moz-appearance:none !important; -webkit-appearance: none !important; - -webkit-box-sizing:none !important; -moz-box-sizing:none !important; box-sizing:none !important; -moz-box-shadow: none; -webkit-box-shadow: none; box-shadow: none; -moz-border-radius: 0px; -webkit-border-radius: 0px; border-radius: 0px; float: left; } -#content input:invalid, #content input:hover:not([type="checkbox"]), #content input:active:not([type="checkbox"]), #content input:focus:not([type="checkbox"]), #content textarea:focus, #content textarea:hover { +#content input:invalid, #content input:hover:not([type="checkbox"]), #content input:active:not([type="checkbox"]), #content input:focus:not([type="checkbox"]), #content input.active, #content textarea:focus, #content textarea:hover { border: 1px solid silver !important; -moz-border-radius:.3em; -webkit-border-radius:.3em; border-radius:.3em; outline:none; float: left; @@ -122,10 +120,9 @@ dl.form { display: inline-block; width: auto; margin: 0; padding: 0; cursor: normal; } .form dt { display: table-cell; clear: left; float: left; width: 7em; margin: 0; padding: 0.8em 0.5em 0 0; text-align:right; text-overflow:ellipsis; o-text-overflow: ellipsis; vertical-align: text-bottom; color: #bbb;/* white-space: pre-wrap; white-space: -moz-pre-wrap !important; white-space: -pre-wrap; white-space: -o-pre-wrap;*/ } .form dd { display: table-cell; clear: right; float: left; margin: 0; padding: 0; white-space: nowrap; vertical-align: text-bottom; } -.action { display: inline-block; width: 20px; height: 20px; } -.action.share { height: 20px !important; width: 20px; float: right !important; clear: right; } +.action { display: inline-block; width: 22px; height: 22px; padding: 0; margin: 0; cursor: pointer; } /* override the default margin on share dropdown */ -#dropdown { margin: 1.5em 0; -moz-box-sizing: border-box; box-sizing: border-box; width: 100%; } +#dropdown { margin: 1.5em 0; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; width: 100%; } .add { background:url('%webroot%/core/img/actions/add.svg') no-repeat center; clear: both; } .delete { background:url('%webroot%/core/img/actions/delete.png') no-repeat center; } .edit { background:url('%webroot%/core/img/actions/rename.svg') no-repeat center; } @@ -219,13 +216,14 @@ dl.form { display: inline-block; width: auto; margin: 0; padding: 0; cursor: nor #contacts-settings .settings { width: 20px; height: 20px; - float: right; + float: left; background:url('%webroot%/core/img/actions/settings.svg') no-repeat center; } #contacts-settings.open { height: auto; } #contacts-settings { + -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; background: none repeat scroll 0 0 #EEEEEE; @@ -241,6 +239,8 @@ dl.form { display: inline-block; width: auto; margin: 0; padding: 0; cursor: nor z-index: 2; } #contacts-settings li,#contacts-settings li:hover { background-color: transparent; white-space: nowrap; } +#contacts-settings a.action { width: 20px; height: 20px; } +#contacts-settings .actions { float: right; } .multiselectoptions label { display: block; } /* Single elements */ @@ -339,7 +339,7 @@ input.propertytype { float: left; font-size: .8em; width: 8em !important; direct .adr.edit input.value.zip { width: 5em; } .adr.edit input.value.city { width: 10em; } -#rightcontent footer { padding: 1em; width: 100%; box-sizing: border-box; clear: both; } +#rightcontent footer { padding: 1em; width: 100%; -moz-box-sizing: border-box; box-sizing: border-box; clear: both; } #rightcontent footer > { display: inline-block; } /* contact list */ @@ -368,6 +368,14 @@ input.propertytype { float: left; font-size: .8em; width: 8em !important; direct } #contact span.adr:hover { /*overflow: inherit;*/ white-space: pre-wrap; } +#contact > ul.propertylist { + -webkit-transition: all 0.5s ease-in-out; + -moz-transition: all 0.5s ease-in-out; + -o-transition: all 0.5s ease-in-out; + -ms-transition: all 0.5s ease-out; + transition: all 0.5s ease-in-out; +} + @media screen and (min-width: 1400px) { #contact > ul.propertylist { -moz-column-count: 3; @@ -376,7 +384,7 @@ input.propertytype { float: left; font-size: .8em; width: 8em !important; direct columns: 3; } } -@media screen and (min-width: 800px) and (max-width: 1400) { +@media screen and (min-width: 800px) and (max-width: 1400px) { #singlevalues { max-width: 50%; } #contact > ul.propertylist { -moz-column-count: 2; From b968a602d957f80be5619a94a5a8623032fdb018 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Fri, 7 Dec 2012 15:08:25 +0100 Subject: [PATCH 203/279] Contact: Minor fixes. --- js/app.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/js/app.js b/js/app.js index 8ae296ca..ca4c24de 100644 --- a/js/app.js +++ b/js/app.js @@ -599,7 +599,7 @@ GroupList.prototype.loadGroups = function(numcontacts, cb) { name: t('contacts', 'Favorites') }).appendTo($groupList); $elem.data('obj', self); - $elem.data('contacts', contacts).find('.numcontacts').before(''); + $elem.data('contacts', contacts).find('.numcontacts').before(''); $elem.droppable({ drop: self.contactDropped, activeClass: 'ui-state-active', @@ -987,7 +987,7 @@ OC.Contacts = OC.Contacts || { if(self.currentid) { var id = self.currentid; self.closeContact(id); - self.Contacts.jumpToContact(id); + self.jumpToContact(id); } self.$contactList.show(); self.$toggleAll.show(); @@ -1758,7 +1758,7 @@ OC.Contacts = OC.Contacts || { }); }, jumpToContact: function(id) { - this.$rightContent.scrollTop(this.Contacts.contactPos(id)); + this.$rightContent.scrollTop(this.Contacts.contactPos(id)+10); }, closeContact: function(id) { if(typeof this.currentid === 'number') { From 1a4ba6afade50284a72407dd5d6d69850afe8324 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Fri, 7 Dec 2012 15:15:17 +0100 Subject: [PATCH 204/279] Contacts: Don't hide checkmark. --- css/contacts.css | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/css/contacts.css b/css/contacts.css index 9d5c8a1d..0376e31b 100644 --- a/css/contacts.css +++ b/css/contacts.css @@ -88,7 +88,7 @@ } #grouplist { z-index: 100; } -#grouplist h3 .action:not(.starred) { float: right; display: none; padding: 0; margin: auto; } +#grouplist h3 .action:not(.starred):not(.checked) { float: right; display: none; padding: 0; margin: auto; } #grouplist h3:not([data-type="shared"]):not(.editing):hover .action.numcontacts, #grouplist h3:not([data-type="shared"]):not(.editing) .active.action.numcontacts { display: inline-block; } #grouplist h3[data-type="category"]:not(.editing):hover .action.delete { display: inline-block; } #grouplist h3:not(.editing) .action.delete { width: 20px; height: 20px; } From c45476936367929d840457a208d0a07978d3f0f6 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Fri, 7 Dec 2012 15:40:07 +0100 Subject: [PATCH 205/279] css fix. --- css/contacts.css | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/css/contacts.css b/css/contacts.css index 0376e31b..5b8659b0 100644 --- a/css/contacts.css +++ b/css/contacts.css @@ -38,12 +38,12 @@ /* Left content */ #leftcontent { top: 3.5em !important; padding: 0; margin: 0; } -#leftcontent a { display: inline-block; } +#leftcontent a { display: inline-block; padding: 0; margin: 0; } #leftcontent h3 { cursor: pointer; -moz-transition: background 300ms ease 0s; background: none no-repeat scroll 1em center #eee; - border-bottom: 1px solid #ddd; border-top: 1px solid #fff; + border-bottom: 1px solid #ddd; border-top: 1px solid #fff; display: block; max-width: 100%; height: 2em; From 13f5ba47fdfcbebdb360a7ab6e4fab34c0019488 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Fri, 7 Dec 2012 15:42:42 +0100 Subject: [PATCH 206/279] Contacts: Cancel editing new group on escape. --- js/app.js | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/js/app.js b/js/app.js index ca4c24de..bd54d4d9 100644 --- a/js/app.js +++ b/js/app.js @@ -490,9 +490,12 @@ GroupList.prototype.editGroup = function(id) { $(this).next('.checked').addClass('disabled'); } }); - $input.on('keypress', function(event) { - if(event.keyCode === 13) { + $input.on('keyup', function(event) { + var keyCode = Math.max(event.keyCode, event.which); + if(keyCode === 13) { saveChanges($elem, $(this)); + } else if(keyCode === 27) { + $elem.remove(); } }); $input.next('.checked').on('click keydown', function(event) { From f9336480231d6d4a8cbdb5e493af5a4a7b1b300d Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Fri, 7 Dec 2012 15:45:01 +0100 Subject: [PATCH 207/279] Contacts: Add -webkit prefix for box-sizing. --- css/contacts.css | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/css/contacts.css b/css/contacts.css index 5b8659b0..21dada6a 100644 --- a/css/contacts.css +++ b/css/contacts.css @@ -66,11 +66,11 @@ width: 100%; font-size: .8em; float: left; - -moz-box-sizing: border-box; box-sizing: border-box; + -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; margin: auto 0 auto .3em; } -#groupactions { -moz-box-sizing: border-box; box-sizing: border-box; height: 4em; border-bottom: 1px solid #DDDDDD; } +#groupactions { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; height: 4em; border-bottom: 1px solid #DDDDDD; } #groupactions > button, .addcontact, .import-upload-button, .doImport { -moz-border-bottom-colors: none; -moz-border-left-colors: none; From ced3309fd3140e5b39deebdec3237253790f74b0 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Fri, 7 Dec 2012 16:21:59 +0100 Subject: [PATCH 208/279] Contacts: Added missing files. --- css/multiselect.css | 78 +++++++++++ img/checkmark-gray.png | Bin 0 -> 742 bytes img/checkmark-gray.svg | 110 ++++++++++++++++ img/checkmark-green.png | Bin 0 -> 618 bytes img/checkmark-green.svg | 109 ++++++++++++++++ img/starred.svg | 78 +++++++++++ index.php | 6 +- js/multiselect.js | 282 ++++++++++++++++++++++++++++++++++++++++ 8 files changed, 660 insertions(+), 3 deletions(-) create mode 100644 css/multiselect.css create mode 100644 img/checkmark-gray.png create mode 100644 img/checkmark-gray.svg create mode 100644 img/checkmark-green.png create mode 100644 img/checkmark-green.svg create mode 100644 img/starred.svg create mode 100644 js/multiselect.js diff --git a/css/multiselect.css b/css/multiselect.css new file mode 100644 index 00000000..31c8ef88 --- /dev/null +++ b/css/multiselect.css @@ -0,0 +1,78 @@ +/* Copyright (c) 2011, Jan-Christoph Borchardt, http://jancborchardt.net + This file is licensed under the Affero General Public License version 3 or later. + See the COPYING-README file. */ + + ul.multiselectoptions { + background-color:#fff; + border:1px solid #ddd; + border-top:none; + box-shadow:0 1px 1px #ddd; + padding-top:.5em; + position:absolute; + max-height: 20em; + overflow-y: auto; + z-index:49; + } + + ul.multiselectoptions.down { + border-bottom-left-radius:.5em; + border-bottom-right-radius:.5em; + } + + ul.multiselectoptions.up { + border-top-left-radius:.5em; + border-top-right-radius:.5em; + } + + ul.multiselectoptions>li { + overflow:hidden; + white-space:nowrap; + } + + div.multiselect { + display:inline-block; + max-width:400px; + min-width:100px; + padding-right:.6em; + position:relative; + vertical-align:bottom; + } + + div.multiselect.active { + background-color:#fff; + position:relative; + z-index:50; + } + + div.multiselect.up { + border-top:0 none; + border-top-left-radius:0; + border-top-right-radius:0; + } + + div.multiselect.down { + border-bottom:none; + border-bottom-left-radius:0; + border-bottom-right-radius:0; + } + + div.multiselect>span:first-child { + float:left; + margin-right:2em; + overflow:hidden; + text-overflow:ellipsis; + width:90%; + } + + div.multiselect>span:last-child { + position:absolute; + right:.8em; + } + + ul.multiselectoptions input.new { + border-top-left-radius:0; + border-top-right-radius:0; + padding-bottom:.2em; + padding-top:.2em; + margin:0; + } \ No newline at end of file diff --git a/img/checkmark-gray.png b/img/checkmark-gray.png new file mode 100644 index 0000000000000000000000000000000000000000..8198e8131d0e1bdcaabbb19b02b507de3432dd76 GIT binary patch literal 742 zcmVv5ONy6vn?dyGA(SK#XD|{sBj@I=cfE8-r+=-CLEwi6>ZGHYo%P zt00P}T%lYD5)iEf*<45nvAE`H8^OXtQ5&t4D@1ZjHnQ_9E_-e^SudM`Dc<+q{N6V+ zkC++LF556p64BGN5Le2M(+2=CHB8DQAld|w+g9qOWmy^k&@>M3EG-@C?d)uU=yael z^Q)hlc0I8}BBGw_*2A!Yo0q)l&4sTcL21IyqV5qvgLAF1;WG*S%^vm_F4D+ zt6|s>@SbI*;$TH7&jDBnNxuPHdeUtEiq`G{x0PxYP4ihPn>{!}6yk0uQcRSuY;1fS z*IWmHl4;r)jDnh(NddSS6ch|&UJ#uRVgepi>h(_CZG>%_a}2D74lEZ<^VUCeL+-x7 zbsxsT0DuaHu|>eyh~6h5765cvsSmq-0Ajwl-e|n}A5a|deM!J$0KJf&Vx<~NsYd|} zKxaSLpy}=$7IL{0nyxn(m>*N;k?+r~H=AGg1MdBDwblCW_4{W4j666KtxWBRt=)Df1%jE!?v=&G%&CtN;K2 literal 0 HcmV?d00001 diff --git a/img/checkmark-gray.svg b/img/checkmark-gray.svg new file mode 100644 index 00000000..4692e5a1 --- /dev/null +++ b/img/checkmark-gray.svg @@ -0,0 +1,110 @@ + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + diff --git a/img/checkmark-green.png b/img/checkmark-green.png new file mode 100644 index 0000000000000000000000000000000000000000..9a8a43616ae9ece3587f41482c9e349c46747a39 GIT binary patch literal 618 zcmV-w0+s!VP)6Bd{Lc5DbMNin>GgV68&SnN z+`(Ly{0b9mfORmBGk6qLOs)xt8#q?458_EwG1*zo$Wg^Ct`A5(8ygr^?7%y8Td6NN z*%n8M+XG-9aVSeJjs=V=j$mI)ev9cW`58tYIjWe#BDOW;CG5_UpZdZ$w|uDu`+>tv z*vK756`PTmYRD(D-&(%&E!fRLu$2y@id}e(^>~2;S#r7FXk*>o zrn=@O_V@Gcn20Ji;6V+8y|~u!%rsy>F*6L-ANdNlxAfVl;tihSLPNimB|i*<^?_IM zy)JB?(>(5DYyG`cd;b|Lw;WY$sUg!tyhpR-!;yhCw2ON<)$+Z{l6(FKqxG<}-}>Z+_G{}d0RR9107*qoM6N<$ Eg0OrHJ^%m! literal 0 HcmV?d00001 diff --git a/img/checkmark-green.svg b/img/checkmark-green.svg new file mode 100644 index 00000000..bc73c822 --- /dev/null +++ b/img/checkmark-green.svg @@ -0,0 +1,109 @@ + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + diff --git a/img/starred.svg b/img/starred.svg new file mode 100644 index 00000000..ba96cccb --- /dev/null +++ b/img/starred.svg @@ -0,0 +1,78 @@ + + + + + + + + + + image/svg+xml + + + + + + + + + diff --git a/index.php b/index.php index 13520aad..55e7baae 100644 --- a/index.php +++ b/index.php @@ -47,7 +47,7 @@ $freeSpace=OC_Filesystem::free_space('/'); $freeSpace=max($freeSpace, 0); $maxUploadFilesize = min($maxUploadFilesize, $freeSpace); -OCP\Util::addscript('', 'multiselect'); +OCP\Util::addscript('contacts', 'multiselect'); OCP\Util::addscript('', 'oc-vcategories'); OCP\Util::addscript('contacts', 'app'); OCP\Util::addscript('contacts', 'contacts'); @@ -56,10 +56,10 @@ OCP\Util::addscript('contacts', 'placeholder.polyfill.jquery'); OCP\Util::addscript('contacts', 'expanding'); OCP\Util::addscript('contacts', 'jquery.combobox'); OCP\Util::addscript('files', 'jquery.fileupload'); -OCP\Util::addscript('core', 'jquery.inview'); +//OCP\Util::addscript('core', 'jquery.inview'); OCP\Util::addscript('contacts', 'jquery.Jcrop'); OCP\Util::addscript('contacts', 'jquery.multi-autocomplete'); -OCP\Util::addStyle('', 'jquery.multiselect'); +OCP\Util::addStyle('contacts', 'multiselect'); OCP\Util::addStyle('contacts', 'jquery.combobox'); OCP\Util::addStyle('contacts', 'jquery.Jcrop'); OCP\Util::addStyle('contacts', 'contacts'); diff --git a/js/multiselect.js b/js/multiselect.js new file mode 100644 index 00000000..6bfad9b0 --- /dev/null +++ b/js/multiselect.js @@ -0,0 +1,282 @@ +/** + * @param 'createCallback' A function to be called when a new entry is created. Two arguments are supplied to this function: + * The select element used and the value of the option. If the function returns false addition will be cancelled. If it returns + * anything else it will be used as the value of the newly added option. + * @param 'createText' The placeholder text for the create action. + * @param 'title' The title to show if no options are selected. + * @param 'checked' An array containing values for options that should be checked. Any options which are already selected will be added to this array. + * @param 'labels' The corresponding labels to show for the checked items. + * @param 'oncheck' Callback function which will be called when a checkbox/radiobutton is selected. If the function returns false the input will be unchecked. + * @param 'onuncheck' @see 'oncheck'. + * @param 'singleSelect' If true radiobuttons will be used instead of checkboxes. + */ +(function( $ ){ + var multiSelectId=-1; + $.fn.multiSelect=function(options) { + multiSelectId++; + var settings = { + 'createCallback':false, + 'createText':false, + 'singleSelect':false, + 'title':this.attr('title'), + 'checked':[], + 'labels':[], + 'oncheck':false, + 'onuncheck':false, + 'minWidth': 'default;', + }; + $(this).attr('data-msid', multiSelectId); + $.extend(settings,options); + $.each(this.children(),function(i,option) { + // If the option is selected, but not in the checked array, add it. + if($(option).attr('selected') && settings.checked.indexOf($(option).val()) === -1) { + settings.checked.push($(option).val()); + settings.labels.push($(option).text().trim()); + } + // If the option is in the checked array but not selected, select it. + else if(settings.checked.indexOf($(option).val()) !== -1 && !$(option).attr('selected')) { + $(option).attr('selected', 'selected'); + settings.labels.push($(option).text().trim()); + } + }); + var button=$('
    '+settings.title+'
    '); + var span=$(''); + span.append(button); + button.data('id',multiSelectId); + button.selectedItems=[]; + this.hide(); + this.before(span); + if(settings.minWidth=='default') { + settings.minWidth=button.width(); + } + button.css('min-width',settings.minWidth); + settings.minOuterWidth=button.outerWidth()-2; + button.data('settings',settings); + + if(!settings.singleSelect && settings.checked.length>0) { + button.children('span').first().text(settings.labels.join(', ')); + } else if(settings.singleSelect) { + button.children('span').first().text(this.find(':selected').text()); + } + + var self = this; + self.menuDirection = 'down'; + button.click(function(event){ + + var button=$(this); + if(button.parent().children('ul').length>0) { + if(self.menuDirection === 'down') { + button.parent().children('ul').slideUp(400,function() { + button.parent().children('ul').remove(); + button.removeClass('active'); + }); + } else { + button.parent().children('ul').fadeOut(400,function() { + button.parent().children('ul').remove(); + button.removeClass('active').removeClass('up'); + }); + } + return; + } + var lists=$('ul.multiselectoptions'); + lists.slideUp(400,function(){ + lists.remove(); + $('div.multiselect').removeClass('active'); + button.addClass('active'); + }); + button.addClass('active'); + event.stopPropagation(); + var options=$(this).parent().next().children(); + var list=$('
      ').hide().appendTo($(this).parent()); + var inputType = settings.singleSelect ? 'radio' : 'checkbox'; + function createItem(element, checked){ + element=$(element); + var item=element.val(); + var id='ms'+multiSelectId+'-option-'+item; + var input=$(''); + input.attr('id',id); + if(settings.singleSelect) { + input.attr('name', 'ms'+multiSelectId+'-option'); + } + var label=$('
    - + +
    @@ -278,72 +284,88 @@