Passed
Push — master ( c00d6f...a085a8 )
by Morris
09:54 queued 11s
created
lib/public/Contacts/IManager.php 1 patch
Indentation   +119 added lines, -119 removed lines patch added patch discarded remove patch
@@ -50,132 +50,132 @@
 block discarded – undo
50 50
  */
51 51
 interface IManager {
52 52
 
53
-	/**
54
-	 * This function is used to search and find contacts within the users address books.
55
-	 * In case $pattern is empty all contacts will be returned.
56
-	 *
57
-	 * Example:
58
-	 *  Following function shows how to search for contacts for the name and the email address.
59
-	 *
60
-	 *		public static function getMatchingRecipient($term) {
61
-	 *			$cm = \OC::$server->getContactsManager();
62
-	 *			// The API is not active -> nothing to do
63
-	 *			if (!$cm->isEnabled()) {
64
-	 *				return array();
65
-	 *			}
66
-	 *
67
-	 *			$result = $cm->search($term, array('FN', 'EMAIL'));
68
-	 *			$receivers = array();
69
-	 *			foreach ($result as $r) {
70
-	 *				$id = $r['id'];
71
-	 *				$fn = $r['FN'];
72
-	 *				$email = $r['EMAIL'];
73
-	 *				if (!is_array($email)) {
74
-	 *					$email = array($email);
75
-	 *				}
76
-	 *
77
-	 *				// loop through all email addresses of this contact
78
-	 *				foreach ($email as $e) {
79
-	 *				$displayName = $fn . " <$e>";
80
-	 *				$receivers[] = array(
81
-	 *					'id'    => $id,
82
-	 *					'label' => $displayName,
83
-	 *					'value' => $displayName);
84
-	 *				}
85
-	 *			}
86
-	 *
87
-	 *			return $receivers;
88
-	 *		}
89
-	 *
90
-	 *
91
-	 * @param string $pattern which should match within the $searchProperties
92
-	 * @param array $searchProperties defines the properties within the query pattern should match
93
-	 * @param array $options = array() to define the search behavior
94
-	 * 	- 'escape_like_param' - If set to false wildcards _ and % are not escaped
95
-	 * @return array an array of contacts which are arrays of key-value-pairs
96
-	 * @since 6.0.0
97
-	 */
98
-	public function search($pattern, $searchProperties = array(), $options = array());
53
+    /**
54
+     * This function is used to search and find contacts within the users address books.
55
+     * In case $pattern is empty all contacts will be returned.
56
+     *
57
+     * Example:
58
+     *  Following function shows how to search for contacts for the name and the email address.
59
+     *
60
+     *		public static function getMatchingRecipient($term) {
61
+     *			$cm = \OC::$server->getContactsManager();
62
+     *			// The API is not active -> nothing to do
63
+     *			if (!$cm->isEnabled()) {
64
+     *				return array();
65
+     *			}
66
+     *
67
+     *			$result = $cm->search($term, array('FN', 'EMAIL'));
68
+     *			$receivers = array();
69
+     *			foreach ($result as $r) {
70
+     *				$id = $r['id'];
71
+     *				$fn = $r['FN'];
72
+     *				$email = $r['EMAIL'];
73
+     *				if (!is_array($email)) {
74
+     *					$email = array($email);
75
+     *				}
76
+     *
77
+     *				// loop through all email addresses of this contact
78
+     *				foreach ($email as $e) {
79
+     *				$displayName = $fn . " <$e>";
80
+     *				$receivers[] = array(
81
+     *					'id'    => $id,
82
+     *					'label' => $displayName,
83
+     *					'value' => $displayName);
84
+     *				}
85
+     *			}
86
+     *
87
+     *			return $receivers;
88
+     *		}
89
+     *
90
+     *
91
+     * @param string $pattern which should match within the $searchProperties
92
+     * @param array $searchProperties defines the properties within the query pattern should match
93
+     * @param array $options = array() to define the search behavior
94
+     * 	- 'escape_like_param' - If set to false wildcards _ and % are not escaped
95
+     * @return array an array of contacts which are arrays of key-value-pairs
96
+     * @since 6.0.0
97
+     */
98
+    public function search($pattern, $searchProperties = array(), $options = array());
99 99
 
100
-	/**
101
-	 * This function can be used to delete the contact identified by the given id
102
-	 *
103
-	 * @param object $id the unique identifier to a contact
104
-	 * @param string $address_book_key identifier of the address book in which the contact shall be deleted
105
-	 * @return bool successful or not
106
-	 * @since 6.0.0
107
-	 */
108
-	public function delete($id, $address_book_key);
100
+    /**
101
+     * This function can be used to delete the contact identified by the given id
102
+     *
103
+     * @param object $id the unique identifier to a contact
104
+     * @param string $address_book_key identifier of the address book in which the contact shall be deleted
105
+     * @return bool successful or not
106
+     * @since 6.0.0
107
+     */
108
+    public function delete($id, $address_book_key);
109 109
 
110
-	/**
111
-	 * This function is used to create a new contact if 'id' is not given or not present.
112
-	 * Otherwise the contact will be updated by replacing the entire data set.
113
-	 *
114
-	 * @param array $properties this array if key-value-pairs defines a contact
115
-	 * @param string $address_book_key identifier of the address book in which the contact shall be created or updated
116
-	 * @return array an array representing the contact just created or updated
117
-	 * @since 6.0.0
118
-	 */
119
-	public function createOrUpdate($properties, $address_book_key);
110
+    /**
111
+     * This function is used to create a new contact if 'id' is not given or not present.
112
+     * Otherwise the contact will be updated by replacing the entire data set.
113
+     *
114
+     * @param array $properties this array if key-value-pairs defines a contact
115
+     * @param string $address_book_key identifier of the address book in which the contact shall be created or updated
116
+     * @return array an array representing the contact just created or updated
117
+     * @since 6.0.0
118
+     */
119
+    public function createOrUpdate($properties, $address_book_key);
120 120
 
121
-	/**
122
-	 * Check if contacts are available (e.g. contacts app enabled)
123
-	 *
124
-	 * @return bool true if enabled, false if not
125
-	 * @since 6.0.0
126
-	 */
127
-	public function isEnabled();
121
+    /**
122
+     * Check if contacts are available (e.g. contacts app enabled)
123
+     *
124
+     * @return bool true if enabled, false if not
125
+     * @since 6.0.0
126
+     */
127
+    public function isEnabled();
128 128
 
129
-	/**
130
-	 * Registers an address book
131
-	 *
132
-	 * @param \OCP\IAddressBook $address_book
133
-	 * @return void
134
-	 * @since 6.0.0
135
-	 */
136
-	public function registerAddressBook(\OCP\IAddressBook $address_book);
129
+    /**
130
+     * Registers an address book
131
+     *
132
+     * @param \OCP\IAddressBook $address_book
133
+     * @return void
134
+     * @since 6.0.0
135
+     */
136
+    public function registerAddressBook(\OCP\IAddressBook $address_book);
137 137
 
138
-	/**
139
-	 * Unregisters an address book
140
-	 *
141
-	 * @param \OCP\IAddressBook $address_book
142
-	 * @return void
143
-	 * @since 6.0.0
144
-	 */
145
-	public function unregisterAddressBook(\OCP\IAddressBook $address_book);
138
+    /**
139
+     * Unregisters an address book
140
+     *
141
+     * @param \OCP\IAddressBook $address_book
142
+     * @return void
143
+     * @since 6.0.0
144
+     */
145
+    public function unregisterAddressBook(\OCP\IAddressBook $address_book);
146 146
 
147
-	/**
148
-	 * In order to improve lazy loading a closure can be registered which will be called in case
149
-	 * address books are actually requested
150
-	 *
151
-	 * @param \Closure $callable
152
-	 * @return void
153
-	 * @since 6.0.0
154
-	 */
155
-	public function register(\Closure $callable);
147
+    /**
148
+     * In order to improve lazy loading a closure can be registered which will be called in case
149
+     * address books are actually requested
150
+     *
151
+     * @param \Closure $callable
152
+     * @return void
153
+     * @since 6.0.0
154
+     */
155
+    public function register(\Closure $callable);
156 156
 
157
-	/**
158
-	 * Return a list of the user's addressbooks display names
159
-	 * 
160
-	 * @return array
161
-	 * @since 6.0.0
162
-	 * @deprecated 16.0.0 - Use `$this->getUserAddressBooks()` instead
163
-	 */
164
-	public function getAddressBooks();
157
+    /**
158
+     * Return a list of the user's addressbooks display names
159
+     * 
160
+     * @return array
161
+     * @since 6.0.0
162
+     * @deprecated 16.0.0 - Use `$this->getUserAddressBooks()` instead
163
+     */
164
+    public function getAddressBooks();
165 165
 
166
-	/**
167
-	 * Return a list of the user's addressbooks
168
-	 * 
169
-	 * @return IAddressBook[]
170
-	 * @since 16.0.0
171
-	 */
172
-	public function getUserAddressBooks();
166
+    /**
167
+     * Return a list of the user's addressbooks
168
+     * 
169
+     * @return IAddressBook[]
170
+     * @since 16.0.0
171
+     */
172
+    public function getUserAddressBooks();
173 173
 
174
-	/**
175
-	 * removes all registered address book instances
176
-	 * 
177
-	 * @return void
178
-	 * @since 6.0.0
179
-	 */
180
-	public function clear();
174
+    /**
175
+     * removes all registered address book instances
176
+     * 
177
+     * @return void
178
+     * @since 6.0.0
179
+     */
180
+    public function clear();
181 181
 }
Please login to merge, or discard this patch.
lib/private/ContactsManager.php 1 patch
Indentation   +177 added lines, -177 removed lines patch added patch discarded remove patch
@@ -27,181 +27,181 @@
 block discarded – undo
27 27
 
28 28
 namespace OC {
29 29
 
30
-	class ContactsManager implements \OCP\Contacts\IManager {
31
-
32
-		/**
33
-		 * This function is used to search and find contacts within the users address books.
34
-		 * In case $pattern is empty all contacts will be returned.
35
-		 *
36
-		 * @param string $pattern which should match within the $searchProperties
37
-		 * @param array $searchProperties defines the properties within the query pattern should match
38
-		 * @param array $options = array() to define the search behavior
39
-		 * 	- 'escape_like_param' - If set to false wildcards _ and % are not escaped
40
-		 * @return array an array of contacts which are arrays of key-value-pairs
41
-		 */
42
-		public function search($pattern, $searchProperties = array(), $options = array()) {
43
-			$this->loadAddressBooks();
44
-			$result = array();
45
-			foreach($this->addressBooks as $addressBook) {
46
-				$r = $addressBook->search($pattern, $searchProperties, $options);
47
-				$contacts = array();
48
-				foreach($r as $c){
49
-					$c['addressbook-key'] = $addressBook->getKey();
50
-					$contacts[] = $c;
51
-				}
52
-				$result = array_merge($result, $contacts);
53
-			}
54
-
55
-			return $result;
56
-		}
57
-
58
-		/**
59
-		 * This function can be used to delete the contact identified by the given id
60
-		 *
61
-		 * @param object $id the unique identifier to a contact
62
-		 * @param string $addressBookKey identifier of the address book in which the contact shall be deleted
63
-		 * @return bool successful or not
64
-		 */
65
-		public function delete($id, $addressBookKey) {
66
-			$addressBook = $this->getAddressBook($addressBookKey);
67
-			if (!$addressBook) {
68
-				return null;
69
-			}
70
-
71
-			if ($addressBook->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
72
-				return $addressBook->delete($id);
73
-			}
74
-
75
-			return null;
76
-		}
77
-
78
-		/**
79
-		 * This function is used to create a new contact if 'id' is not given or not present.
80
-		 * Otherwise the contact will be updated by replacing the entire data set.
81
-		 *
82
-		 * @param array $properties this array if key-value-pairs defines a contact
83
-		 * @param string $addressBookKey identifier of the address book in which the contact shall be created or updated
84
-		 * @return array representing the contact just created or updated
85
-		 */
86
-		public function createOrUpdate($properties, $addressBookKey) {
87
-			$addressBook = $this->getAddressBook($addressBookKey);
88
-			if (!$addressBook) {
89
-				return null;
90
-			}
91
-
92
-			if ($addressBook->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
93
-				return $addressBook->createOrUpdate($properties);
94
-			}
95
-
96
-			return null;
97
-		}
98
-
99
-		/**
100
-		 * Check if contacts are available (e.g. contacts app enabled)
101
-		 *
102
-		 * @return bool true if enabled, false if not
103
-		 */
104
-		public function isEnabled() {
105
-			return !empty($this->addressBooks) || !empty($this->addressBookLoaders);
106
-		}
107
-
108
-		/**
109
-		 * @param \OCP\IAddressBook $addressBook
110
-		 */
111
-		public function registerAddressBook(\OCP\IAddressBook $addressBook) {
112
-			$this->addressBooks[$addressBook->getKey()] = $addressBook;
113
-		}
114
-
115
-		/**
116
-		 * @param \OCP\IAddressBook $addressBook
117
-		 */
118
-		public function unregisterAddressBook(\OCP\IAddressBook $addressBook) {
119
-			unset($this->addressBooks[$addressBook->getKey()]);
120
-		}
121
-
122
-		/**
123
-		 * Return a list of the user's addressbooks display names
124
-		 * ! The addressBook displayName are not unique, please use getUserAddressBooks
125
-		 * 
126
-		 * @return array
127
-		 * @since 6.0.0
128
-		 * @deprecated 16.0.0 - Use `$this->getUserAddressBooks()` instead
129
-		 */
130
-		public function getAddressBooks() {
131
-			$this->loadAddressBooks();
132
-			$result = array();
133
-			foreach($this->addressBooks as $addressBook) {
134
-				$result[$addressBook->getKey()] = $addressBook->getDisplayName();
135
-			}
136
-
137
-			return $result;
138
-		}
139
-
140
-		/**
141
-		 * Return a list of the user's addressbooks
142
-		 * 
143
-		 * @return IAddressBook[]
144
-		 * @since 16.0.0
145
-		 */
146
-		public function getUserAddressBooks(): Array {
147
-			$this->loadAddressBooks();
148
-			return $this->addressBooks;
149
-		}
150
-
151
-		/**
152
-		 * removes all registered address book instances
153
-		 */
154
-		public function clear() {
155
-			$this->addressBooks = array();
156
-			$this->addressBookLoaders = array();
157
-		}
158
-
159
-		/**
160
-		 * @var \OCP\IAddressBook[] which holds all registered address books
161
-		 */
162
-		private $addressBooks = array();
163
-
164
-		/**
165
-		 * @var \Closure[] to call to load/register address books
166
-		 */
167
-		private $addressBookLoaders = array();
168
-
169
-		/**
170
-		 * In order to improve lazy loading a closure can be registered which will be called in case
171
-		 * address books are actually requested
172
-		 *
173
-		 * @param \Closure $callable
174
-		 */
175
-		public function register(\Closure $callable)
176
-		{
177
-			$this->addressBookLoaders[] = $callable;
178
-		}
179
-
180
-		/**
181
-		 * Get (and load when needed) the address book for $key
182
-		 *
183
-		 * @param string $addressBookKey
184
-		 * @return \OCP\IAddressBook
185
-		 */
186
-		protected function getAddressBook($addressBookKey)
187
-		{
188
-			$this->loadAddressBooks();
189
-			if (!array_key_exists($addressBookKey, $this->addressBooks)) {
190
-				return null;
191
-			}
192
-
193
-			return $this->addressBooks[$addressBookKey];
194
-		}
195
-
196
-		/**
197
-		 * Load all address books registered with 'register'
198
-		 */
199
-		protected function loadAddressBooks()
200
-		{
201
-			foreach($this->addressBookLoaders as $callable) {
202
-				$callable($this);
203
-			}
204
-			$this->addressBookLoaders = array();
205
-		}
206
-	}
30
+    class ContactsManager implements \OCP\Contacts\IManager {
31
+
32
+        /**
33
+         * This function is used to search and find contacts within the users address books.
34
+         * In case $pattern is empty all contacts will be returned.
35
+         *
36
+         * @param string $pattern which should match within the $searchProperties
37
+         * @param array $searchProperties defines the properties within the query pattern should match
38
+         * @param array $options = array() to define the search behavior
39
+         * 	- 'escape_like_param' - If set to false wildcards _ and % are not escaped
40
+         * @return array an array of contacts which are arrays of key-value-pairs
41
+         */
42
+        public function search($pattern, $searchProperties = array(), $options = array()) {
43
+            $this->loadAddressBooks();
44
+            $result = array();
45
+            foreach($this->addressBooks as $addressBook) {
46
+                $r = $addressBook->search($pattern, $searchProperties, $options);
47
+                $contacts = array();
48
+                foreach($r as $c){
49
+                    $c['addressbook-key'] = $addressBook->getKey();
50
+                    $contacts[] = $c;
51
+                }
52
+                $result = array_merge($result, $contacts);
53
+            }
54
+
55
+            return $result;
56
+        }
57
+
58
+        /**
59
+         * This function can be used to delete the contact identified by the given id
60
+         *
61
+         * @param object $id the unique identifier to a contact
62
+         * @param string $addressBookKey identifier of the address book in which the contact shall be deleted
63
+         * @return bool successful or not
64
+         */
65
+        public function delete($id, $addressBookKey) {
66
+            $addressBook = $this->getAddressBook($addressBookKey);
67
+            if (!$addressBook) {
68
+                return null;
69
+            }
70
+
71
+            if ($addressBook->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
72
+                return $addressBook->delete($id);
73
+            }
74
+
75
+            return null;
76
+        }
77
+
78
+        /**
79
+         * This function is used to create a new contact if 'id' is not given or not present.
80
+         * Otherwise the contact will be updated by replacing the entire data set.
81
+         *
82
+         * @param array $properties this array if key-value-pairs defines a contact
83
+         * @param string $addressBookKey identifier of the address book in which the contact shall be created or updated
84
+         * @return array representing the contact just created or updated
85
+         */
86
+        public function createOrUpdate($properties, $addressBookKey) {
87
+            $addressBook = $this->getAddressBook($addressBookKey);
88
+            if (!$addressBook) {
89
+                return null;
90
+            }
91
+
92
+            if ($addressBook->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
93
+                return $addressBook->createOrUpdate($properties);
94
+            }
95
+
96
+            return null;
97
+        }
98
+
99
+        /**
100
+         * Check if contacts are available (e.g. contacts app enabled)
101
+         *
102
+         * @return bool true if enabled, false if not
103
+         */
104
+        public function isEnabled() {
105
+            return !empty($this->addressBooks) || !empty($this->addressBookLoaders);
106
+        }
107
+
108
+        /**
109
+         * @param \OCP\IAddressBook $addressBook
110
+         */
111
+        public function registerAddressBook(\OCP\IAddressBook $addressBook) {
112
+            $this->addressBooks[$addressBook->getKey()] = $addressBook;
113
+        }
114
+
115
+        /**
116
+         * @param \OCP\IAddressBook $addressBook
117
+         */
118
+        public function unregisterAddressBook(\OCP\IAddressBook $addressBook) {
119
+            unset($this->addressBooks[$addressBook->getKey()]);
120
+        }
121
+
122
+        /**
123
+         * Return a list of the user's addressbooks display names
124
+         * ! The addressBook displayName are not unique, please use getUserAddressBooks
125
+         * 
126
+         * @return array
127
+         * @since 6.0.0
128
+         * @deprecated 16.0.0 - Use `$this->getUserAddressBooks()` instead
129
+         */
130
+        public function getAddressBooks() {
131
+            $this->loadAddressBooks();
132
+            $result = array();
133
+            foreach($this->addressBooks as $addressBook) {
134
+                $result[$addressBook->getKey()] = $addressBook->getDisplayName();
135
+            }
136
+
137
+            return $result;
138
+        }
139
+
140
+        /**
141
+         * Return a list of the user's addressbooks
142
+         * 
143
+         * @return IAddressBook[]
144
+         * @since 16.0.0
145
+         */
146
+        public function getUserAddressBooks(): Array {
147
+            $this->loadAddressBooks();
148
+            return $this->addressBooks;
149
+        }
150
+
151
+        /**
152
+         * removes all registered address book instances
153
+         */
154
+        public function clear() {
155
+            $this->addressBooks = array();
156
+            $this->addressBookLoaders = array();
157
+        }
158
+
159
+        /**
160
+         * @var \OCP\IAddressBook[] which holds all registered address books
161
+         */
162
+        private $addressBooks = array();
163
+
164
+        /**
165
+         * @var \Closure[] to call to load/register address books
166
+         */
167
+        private $addressBookLoaders = array();
168
+
169
+        /**
170
+         * In order to improve lazy loading a closure can be registered which will be called in case
171
+         * address books are actually requested
172
+         *
173
+         * @param \Closure $callable
174
+         */
175
+        public function register(\Closure $callable)
176
+        {
177
+            $this->addressBookLoaders[] = $callable;
178
+        }
179
+
180
+        /**
181
+         * Get (and load when needed) the address book for $key
182
+         *
183
+         * @param string $addressBookKey
184
+         * @return \OCP\IAddressBook
185
+         */
186
+        protected function getAddressBook($addressBookKey)
187
+        {
188
+            $this->loadAddressBooks();
189
+            if (!array_key_exists($addressBookKey, $this->addressBooks)) {
190
+                return null;
191
+            }
192
+
193
+            return $this->addressBooks[$addressBookKey];
194
+        }
195
+
196
+        /**
197
+         * Load all address books registered with 'register'
198
+         */
199
+        protected function loadAddressBooks()
200
+        {
201
+            foreach($this->addressBookLoaders as $callable) {
202
+                $callable($this);
203
+            }
204
+            $this->addressBookLoaders = array();
205
+        }
206
+    }
207 207
 }
Please login to merge, or discard this patch.
apps/dav/lib/CardDAV/AddressBookImpl.php 1 patch
Indentation   +285 added lines, -285 removed lines patch added patch discarded remove patch
@@ -35,289 +35,289 @@
 block discarded – undo
35 35
 
36 36
 class AddressBookImpl implements IAddressBook {
37 37
 
38
-	/** @var CardDavBackend */
39
-	private $backend;
40
-
41
-	/** @var array */
42
-	private $addressBookInfo;
43
-
44
-	/** @var AddressBook */
45
-	private $addressBook;
46
-
47
-	/** @var IURLGenerator */
48
-	private $urlGenerator;
49
-
50
-	/**
51
-	 * AddressBookImpl constructor.
52
-	 *
53
-	 * @param AddressBook $addressBook
54
-	 * @param array $addressBookInfo
55
-	 * @param CardDavBackend $backend
56
-	 * @param IUrlGenerator $urlGenerator
57
-	 */
58
-	public function __construct(
59
-			AddressBook $addressBook,
60
-			array $addressBookInfo,
61
-			CardDavBackend $backend,
62
-			IURLGenerator $urlGenerator) {
63
-
64
-		$this->addressBook = $addressBook;
65
-		$this->addressBookInfo = $addressBookInfo;
66
-		$this->backend = $backend;
67
-		$this->urlGenerator = $urlGenerator;
68
-	}
69
-
70
-	/**
71
-	 * @return string defining the technical unique key
72
-	 * @since 5.0.0
73
-	 */
74
-	public function getKey() {
75
-		return $this->addressBookInfo['id'];
76
-	}
77
-
78
-	/**
79
-	 * @return string defining the unique uri
80
-	 * @since 16.0.0
81
-	 * @return string
82
-	 */
83
-	public function getUri(): string {
84
-		return $this->addressBookInfo['uri'];
85
-	}
86
-
87
-	/**
88
-	 * In comparison to getKey() this function returns a human readable (maybe translated) name
89
-	 *
90
-	 * @return mixed
91
-	 * @since 5.0.0
92
-	 */
93
-	public function getDisplayName() {
94
-		return $this->addressBookInfo['{DAV:}displayname'];
95
-	}
96
-
97
-	/**
98
-	 * @param string $pattern which should match within the $searchProperties
99
-	 * @param array $searchProperties defines the properties within the query pattern should match
100
-	 * @param array $options Options to define the output format and search behavior
101
-	 * 	- 'types' boolean (since 15.0.0) If set to true, fields that come with a TYPE property will be an array
102
-	 *    example: ['id' => 5, 'FN' => 'Thomas Tanghus', 'EMAIL' => ['type => 'HOME', 'value' => '[email protected]']]
103
-	 * 	- 'escape_like_param' - If set to false wildcards _ and % are not escaped
104
-	 * @return array an array of contacts which are arrays of key-value-pairs
105
-	 *  example result:
106
-	 *  [
107
-	 *		['id' => 0, 'FN' => 'Thomas Müller', 'EMAIL' => '[email protected]', 'GEO' => '37.386013;-122.082932'],
108
-	 *		['id' => 5, 'FN' => 'Thomas Tanghus', 'EMAIL' => ['[email protected]', '[email protected]']]
109
-	 *	]
110
-	 * @param array $options = array() 'escape_like_param' - to not escape wildcards _ and % - for future use. One should always have options!
111
-	 * @return array an array of contacts which are arrays of key-value-pairs
112
-	 * @since 5.0.0
113
-	 */
114
-	public function search($pattern, $searchProperties, $options) {
115
-		$results = $this->backend->search($this->getKey(), $pattern, $searchProperties, $options = $options);
116
-
117
-		$withTypes = \array_key_exists('types', $options) && $options['types'] === true;
118
-
119
-		$vCards = [];
120
-		foreach ($results as $result) {
121
-			$vCards[] = $this->vCard2Array($result['uri'], $this->readCard($result['carddata']), $withTypes);
122
-		}
123
-
124
-		return $vCards;
125
-	}
126
-
127
-	/**
128
-	 * @param array $properties this array if key-value-pairs defines a contact
129
-	 * @return array an array representing the contact just created or updated
130
-	 * @since 5.0.0
131
-	 */
132
-	public function createOrUpdate($properties) {
133
-		$update = false;
134
-		if (!isset($properties['URI'])) { // create a new contact
135
-			$uid = $this->createUid();
136
-			$uri = $uid . '.vcf';
137
-			$vCard = $this->createEmptyVCard($uid);
138
-		} else { // update existing contact
139
-			$uri = $properties['URI'];
140
-			$vCardData = $this->backend->getCard($this->getKey(), $uri);
141
-			$vCard = $this->readCard($vCardData['carddata']);
142
-			$update = true;
143
-		}
144
-
145
-		foreach ($properties as $key => $value) {
146
-			$vCard->$key = $vCard->createProperty($key, $value);
147
-		}
148
-
149
-		if ($update) {
150
-			$this->backend->updateCard($this->getKey(), $uri, $vCard->serialize());
151
-		} else {
152
-			$this->backend->createCard($this->getKey(), $uri, $vCard->serialize());
153
-		}
154
-
155
-		return $this->vCard2Array($uri, $vCard);
156
-
157
-	}
158
-
159
-	/**
160
-	 * @return mixed
161
-	 * @since 5.0.0
162
-	 */
163
-	public function getPermissions() {
164
-		$permissions = $this->addressBook->getACL();
165
-		$result = 0;
166
-		foreach ($permissions as $permission) {
167
-			switch($permission['privilege']) {
168
-				case '{DAV:}read':
169
-					$result |= Constants::PERMISSION_READ;
170
-					break;
171
-				case '{DAV:}write':
172
-					$result |= Constants::PERMISSION_CREATE;
173
-					$result |= Constants::PERMISSION_UPDATE;
174
-					break;
175
-				case '{DAV:}all':
176
-					$result |= Constants::PERMISSION_ALL;
177
-					break;
178
-			}
179
-		}
180
-
181
-		return $result;
182
-	}
183
-
184
-	/**
185
-	 * @param object $id the unique identifier to a contact
186
-	 * @return bool successful or not
187
-	 * @since 5.0.0
188
-	 */
189
-	public function delete($id) {
190
-		$uri = $this->backend->getCardUri($id);
191
-		return $this->backend->deleteCard($this->addressBookInfo['id'], $uri);
192
-	}
193
-
194
-	/**
195
-	 * read vCard data into a vCard object
196
-	 *
197
-	 * @param string $cardData
198
-	 * @return VCard
199
-	 */
200
-	protected function readCard($cardData) {
201
-		return  Reader::read($cardData);
202
-	}
203
-
204
-	/**
205
-	 * create UID for contact
206
-	 *
207
-	 * @return string
208
-	 */
209
-	protected function createUid() {
210
-		do {
211
-			$uid = $this->getUid();
212
-			$contact = $this->backend->getContact($this->getKey(), $uid . '.vcf');
213
-		} while (!empty($contact));
214
-
215
-		return $uid;
216
-	}
217
-
218
-	/**
219
-	 * getUid is only there for testing, use createUid instead
220
-	 */
221
-	protected function getUid() {
222
-		return UUIDUtil::getUUID();
223
-	}
224
-
225
-	/**
226
-	 * create empty vcard
227
-	 *
228
-	 * @param string $uid
229
-	 * @return VCard
230
-	 */
231
-	protected function createEmptyVCard($uid) {
232
-		$vCard = new VCard();
233
-		$vCard->UID = $uid;
234
-		return $vCard;
235
-	}
236
-
237
-	/**
238
-	 * create array with all vCard properties
239
-	 *
240
-	 * @param string $uri
241
-	 * @param VCard $vCard
242
-	 * @return array
243
-	 */
244
-	protected function vCard2Array($uri, VCard $vCard, $withTypes = false) {
245
-		$result = [
246
-			'URI' => $uri,
247
-		];
248
-
249
-		foreach ($vCard->children() as $property) {
250
-			if ($property->name === 'PHOTO' && $property->getValueType() === 'BINARY') {
251
-				$url = $this->urlGenerator->getAbsoluteURL(
252
-					$this->urlGenerator->linkTo('', 'remote.php') . '/dav/');
253
-				$url .= implode('/', [
254
-					'addressbooks',
255
-					substr($this->addressBookInfo['principaluri'], 11), //cut off 'principals/'
256
-					$this->addressBookInfo['uri'],
257
-					$uri
258
-				]) . '?photo';
259
-
260
-				$result['PHOTO'] = 'VALUE=uri:' . $url;
261
-
262
-			} else if ($property->name === 'X-SOCIALPROFILE') {
263
-				$type = $this->getTypeFromProperty($property);
264
-
265
-				// Type is the social network, when it's empty we don't need this.
266
-				if ($type !== null) {
267
-					if (!isset($result[$property->name])) {
268
-						$result[$property->name] = [];
269
-					}
270
-					$result[$property->name][$type] = $property->getValue();
271
-				}
272
-
273
-			// The following properties can be set multiple times
274
-			} else if (in_array($property->name, ['CLOUD', 'EMAIL', 'IMPP', 'TEL', 'URL', 'X-ADDRESSBOOKSERVER-MEMBER'])) {
275
-				if (!isset($result[$property->name])) {
276
-					$result[$property->name] = [];
277
-				}
278
-
279
-				$type = $this->getTypeFromProperty($property);
280
-				if ($withTypes) {
281
-					$result[$property->name][] = [
282
-						'type' => $type,
283
-						'value' => $property->getValue()
284
-						];
285
-				} else {
286
-					$result[$property->name][] = $property->getValue();
287
-				}
288
-
289
-
290
-			} else {
291
-				$result[$property->name] = $property->getValue();
292
-			}
293
-		}
294
-
295
-		if (
296
-			$this->addressBookInfo['principaluri'] === 'principals/system/system' && (
297
-				$this->addressBookInfo['uri'] === 'system' ||
298
-				$this->addressBookInfo['{DAV:}displayname'] === $this->urlGenerator->getBaseUrl()
299
-			)
300
-		) {
301
-			$result['isLocalSystemBook'] = true;
302
-		}
303
-		return $result;
304
-	}
305
-
306
-	/**
307
-	 * Get the type of the current property
308
-	 *
309
-	 * @param Property $property
310
-	 * @return null|string
311
-	 */
312
-	protected function getTypeFromProperty(Property $property) {
313
-		$parameters = $property->parameters();
314
-		// Type is the social network, when it's empty we don't need this.
315
-		if (isset($parameters['TYPE'])) {
316
-			/** @var \Sabre\VObject\Parameter $type */
317
-			$type = $parameters['TYPE'];
318
-			return $type->getValue();
319
-		}
320
-
321
-		return null;
322
-	}
38
+    /** @var CardDavBackend */
39
+    private $backend;
40
+
41
+    /** @var array */
42
+    private $addressBookInfo;
43
+
44
+    /** @var AddressBook */
45
+    private $addressBook;
46
+
47
+    /** @var IURLGenerator */
48
+    private $urlGenerator;
49
+
50
+    /**
51
+     * AddressBookImpl constructor.
52
+     *
53
+     * @param AddressBook $addressBook
54
+     * @param array $addressBookInfo
55
+     * @param CardDavBackend $backend
56
+     * @param IUrlGenerator $urlGenerator
57
+     */
58
+    public function __construct(
59
+            AddressBook $addressBook,
60
+            array $addressBookInfo,
61
+            CardDavBackend $backend,
62
+            IURLGenerator $urlGenerator) {
63
+
64
+        $this->addressBook = $addressBook;
65
+        $this->addressBookInfo = $addressBookInfo;
66
+        $this->backend = $backend;
67
+        $this->urlGenerator = $urlGenerator;
68
+    }
69
+
70
+    /**
71
+     * @return string defining the technical unique key
72
+     * @since 5.0.0
73
+     */
74
+    public function getKey() {
75
+        return $this->addressBookInfo['id'];
76
+    }
77
+
78
+    /**
79
+     * @return string defining the unique uri
80
+     * @since 16.0.0
81
+     * @return string
82
+     */
83
+    public function getUri(): string {
84
+        return $this->addressBookInfo['uri'];
85
+    }
86
+
87
+    /**
88
+     * In comparison to getKey() this function returns a human readable (maybe translated) name
89
+     *
90
+     * @return mixed
91
+     * @since 5.0.0
92
+     */
93
+    public function getDisplayName() {
94
+        return $this->addressBookInfo['{DAV:}displayname'];
95
+    }
96
+
97
+    /**
98
+     * @param string $pattern which should match within the $searchProperties
99
+     * @param array $searchProperties defines the properties within the query pattern should match
100
+     * @param array $options Options to define the output format and search behavior
101
+     * 	- 'types' boolean (since 15.0.0) If set to true, fields that come with a TYPE property will be an array
102
+     *    example: ['id' => 5, 'FN' => 'Thomas Tanghus', 'EMAIL' => ['type => 'HOME', 'value' => '[email protected]']]
103
+     * 	- 'escape_like_param' - If set to false wildcards _ and % are not escaped
104
+     * @return array an array of contacts which are arrays of key-value-pairs
105
+     *  example result:
106
+     *  [
107
+     *		['id' => 0, 'FN' => 'Thomas Müller', 'EMAIL' => '[email protected]', 'GEO' => '37.386013;-122.082932'],
108
+     *		['id' => 5, 'FN' => 'Thomas Tanghus', 'EMAIL' => ['[email protected]', '[email protected]']]
109
+     *	]
110
+     * @param array $options = array() 'escape_like_param' - to not escape wildcards _ and % - for future use. One should always have options!
111
+     * @return array an array of contacts which are arrays of key-value-pairs
112
+     * @since 5.0.0
113
+     */
114
+    public function search($pattern, $searchProperties, $options) {
115
+        $results = $this->backend->search($this->getKey(), $pattern, $searchProperties, $options = $options);
116
+
117
+        $withTypes = \array_key_exists('types', $options) && $options['types'] === true;
118
+
119
+        $vCards = [];
120
+        foreach ($results as $result) {
121
+            $vCards[] = $this->vCard2Array($result['uri'], $this->readCard($result['carddata']), $withTypes);
122
+        }
123
+
124
+        return $vCards;
125
+    }
126
+
127
+    /**
128
+     * @param array $properties this array if key-value-pairs defines a contact
129
+     * @return array an array representing the contact just created or updated
130
+     * @since 5.0.0
131
+     */
132
+    public function createOrUpdate($properties) {
133
+        $update = false;
134
+        if (!isset($properties['URI'])) { // create a new contact
135
+            $uid = $this->createUid();
136
+            $uri = $uid . '.vcf';
137
+            $vCard = $this->createEmptyVCard($uid);
138
+        } else { // update existing contact
139
+            $uri = $properties['URI'];
140
+            $vCardData = $this->backend->getCard($this->getKey(), $uri);
141
+            $vCard = $this->readCard($vCardData['carddata']);
142
+            $update = true;
143
+        }
144
+
145
+        foreach ($properties as $key => $value) {
146
+            $vCard->$key = $vCard->createProperty($key, $value);
147
+        }
148
+
149
+        if ($update) {
150
+            $this->backend->updateCard($this->getKey(), $uri, $vCard->serialize());
151
+        } else {
152
+            $this->backend->createCard($this->getKey(), $uri, $vCard->serialize());
153
+        }
154
+
155
+        return $this->vCard2Array($uri, $vCard);
156
+
157
+    }
158
+
159
+    /**
160
+     * @return mixed
161
+     * @since 5.0.0
162
+     */
163
+    public function getPermissions() {
164
+        $permissions = $this->addressBook->getACL();
165
+        $result = 0;
166
+        foreach ($permissions as $permission) {
167
+            switch($permission['privilege']) {
168
+                case '{DAV:}read':
169
+                    $result |= Constants::PERMISSION_READ;
170
+                    break;
171
+                case '{DAV:}write':
172
+                    $result |= Constants::PERMISSION_CREATE;
173
+                    $result |= Constants::PERMISSION_UPDATE;
174
+                    break;
175
+                case '{DAV:}all':
176
+                    $result |= Constants::PERMISSION_ALL;
177
+                    break;
178
+            }
179
+        }
180
+
181
+        return $result;
182
+    }
183
+
184
+    /**
185
+     * @param object $id the unique identifier to a contact
186
+     * @return bool successful or not
187
+     * @since 5.0.0
188
+     */
189
+    public function delete($id) {
190
+        $uri = $this->backend->getCardUri($id);
191
+        return $this->backend->deleteCard($this->addressBookInfo['id'], $uri);
192
+    }
193
+
194
+    /**
195
+     * read vCard data into a vCard object
196
+     *
197
+     * @param string $cardData
198
+     * @return VCard
199
+     */
200
+    protected function readCard($cardData) {
201
+        return  Reader::read($cardData);
202
+    }
203
+
204
+    /**
205
+     * create UID for contact
206
+     *
207
+     * @return string
208
+     */
209
+    protected function createUid() {
210
+        do {
211
+            $uid = $this->getUid();
212
+            $contact = $this->backend->getContact($this->getKey(), $uid . '.vcf');
213
+        } while (!empty($contact));
214
+
215
+        return $uid;
216
+    }
217
+
218
+    /**
219
+     * getUid is only there for testing, use createUid instead
220
+     */
221
+    protected function getUid() {
222
+        return UUIDUtil::getUUID();
223
+    }
224
+
225
+    /**
226
+     * create empty vcard
227
+     *
228
+     * @param string $uid
229
+     * @return VCard
230
+     */
231
+    protected function createEmptyVCard($uid) {
232
+        $vCard = new VCard();
233
+        $vCard->UID = $uid;
234
+        return $vCard;
235
+    }
236
+
237
+    /**
238
+     * create array with all vCard properties
239
+     *
240
+     * @param string $uri
241
+     * @param VCard $vCard
242
+     * @return array
243
+     */
244
+    protected function vCard2Array($uri, VCard $vCard, $withTypes = false) {
245
+        $result = [
246
+            'URI' => $uri,
247
+        ];
248
+
249
+        foreach ($vCard->children() as $property) {
250
+            if ($property->name === 'PHOTO' && $property->getValueType() === 'BINARY') {
251
+                $url = $this->urlGenerator->getAbsoluteURL(
252
+                    $this->urlGenerator->linkTo('', 'remote.php') . '/dav/');
253
+                $url .= implode('/', [
254
+                    'addressbooks',
255
+                    substr($this->addressBookInfo['principaluri'], 11), //cut off 'principals/'
256
+                    $this->addressBookInfo['uri'],
257
+                    $uri
258
+                ]) . '?photo';
259
+
260
+                $result['PHOTO'] = 'VALUE=uri:' . $url;
261
+
262
+            } else if ($property->name === 'X-SOCIALPROFILE') {
263
+                $type = $this->getTypeFromProperty($property);
264
+
265
+                // Type is the social network, when it's empty we don't need this.
266
+                if ($type !== null) {
267
+                    if (!isset($result[$property->name])) {
268
+                        $result[$property->name] = [];
269
+                    }
270
+                    $result[$property->name][$type] = $property->getValue();
271
+                }
272
+
273
+            // The following properties can be set multiple times
274
+            } else if (in_array($property->name, ['CLOUD', 'EMAIL', 'IMPP', 'TEL', 'URL', 'X-ADDRESSBOOKSERVER-MEMBER'])) {
275
+                if (!isset($result[$property->name])) {
276
+                    $result[$property->name] = [];
277
+                }
278
+
279
+                $type = $this->getTypeFromProperty($property);
280
+                if ($withTypes) {
281
+                    $result[$property->name][] = [
282
+                        'type' => $type,
283
+                        'value' => $property->getValue()
284
+                        ];
285
+                } else {
286
+                    $result[$property->name][] = $property->getValue();
287
+                }
288
+
289
+
290
+            } else {
291
+                $result[$property->name] = $property->getValue();
292
+            }
293
+        }
294
+
295
+        if (
296
+            $this->addressBookInfo['principaluri'] === 'principals/system/system' && (
297
+                $this->addressBookInfo['uri'] === 'system' ||
298
+                $this->addressBookInfo['{DAV:}displayname'] === $this->urlGenerator->getBaseUrl()
299
+            )
300
+        ) {
301
+            $result['isLocalSystemBook'] = true;
302
+        }
303
+        return $result;
304
+    }
305
+
306
+    /**
307
+     * Get the type of the current property
308
+     *
309
+     * @param Property $property
310
+     * @return null|string
311
+     */
312
+    protected function getTypeFromProperty(Property $property) {
313
+        $parameters = $property->parameters();
314
+        // Type is the social network, when it's empty we don't need this.
315
+        if (isset($parameters['TYPE'])) {
316
+            /** @var \Sabre\VObject\Parameter $type */
317
+            $type = $parameters['TYPE'];
318
+            return $type->getValue();
319
+        }
320
+
321
+        return null;
322
+    }
323 323
 }
Please login to merge, or discard this patch.
apps/dav/lib/CardDAV/CardDavBackend.php 2 patches
Indentation   +1118 added lines, -1118 removed lines patch added patch discarded remove patch
@@ -53,1122 +53,1122 @@
 block discarded – undo
53 53
 
54 54
 class CardDavBackend implements BackendInterface, SyncSupport {
55 55
 
56
-	const PERSONAL_ADDRESSBOOK_URI = 'contacts';
57
-	const PERSONAL_ADDRESSBOOK_NAME = 'Contacts';
58
-
59
-	/** @var Principal */
60
-	private $principalBackend;
61
-
62
-	/** @var string */
63
-	private $dbCardsTable = 'cards';
64
-
65
-	/** @var string */
66
-	private $dbCardsPropertiesTable = 'cards_properties';
67
-
68
-	/** @var IDBConnection */
69
-	private $db;
70
-
71
-	/** @var Backend */
72
-	private $sharingBackend;
73
-
74
-	/** @var array properties to index */
75
-	public static $indexProperties = array(
76
-			'BDAY', 'UID', 'N', 'FN', 'TITLE', 'ROLE', 'NOTE', 'NICKNAME',
77
-			'ORG', 'CATEGORIES', 'EMAIL', 'TEL', 'IMPP', 'ADR', 'URL', 'GEO', 'CLOUD');
78
-
79
-	/**
80
-	 * @var string[] Map of uid => display name
81
-	 */
82
-	protected $userDisplayNames;
83
-
84
-	/** @var IUserManager */
85
-	private $userManager;
86
-
87
-	/** @var EventDispatcherInterface */
88
-	private $dispatcher;
89
-
90
-	/**
91
-	 * CardDavBackend constructor.
92
-	 *
93
-	 * @param IDBConnection $db
94
-	 * @param Principal $principalBackend
95
-	 * @param IUserManager $userManager
96
-	 * @param IGroupManager $groupManager
97
-	 * @param EventDispatcherInterface $dispatcher
98
-	 */
99
-	public function __construct(IDBConnection $db,
100
-								Principal $principalBackend,
101
-								IUserManager $userManager,
102
-								IGroupManager $groupManager,
103
-								EventDispatcherInterface $dispatcher) {
104
-		$this->db = $db;
105
-		$this->principalBackend = $principalBackend;
106
-		$this->userManager = $userManager;
107
-		$this->dispatcher = $dispatcher;
108
-		$this->sharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'addressbook');
109
-	}
110
-
111
-	/**
112
-	 * Return the number of address books for a principal
113
-	 *
114
-	 * @param $principalUri
115
-	 * @return int
116
-	 */
117
-	public function getAddressBooksForUserCount($principalUri) {
118
-		$principalUri = $this->convertPrincipal($principalUri, true);
119
-		$query = $this->db->getQueryBuilder();
120
-		$query->select($query->func()->count('*'))
121
-			->from('addressbooks')
122
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
123
-
124
-		return (int)$query->execute()->fetchColumn();
125
-	}
126
-
127
-	/**
128
-	 * Returns the list of address books for a specific user.
129
-	 *
130
-	 * Every addressbook should have the following properties:
131
-	 *   id - an arbitrary unique id
132
-	 *   uri - the 'basename' part of the url
133
-	 *   principaluri - Same as the passed parameter
134
-	 *
135
-	 * Any additional clark-notation property may be passed besides this. Some
136
-	 * common ones are :
137
-	 *   {DAV:}displayname
138
-	 *   {urn:ietf:params:xml:ns:carddav}addressbook-description
139
-	 *   {http://calendarserver.org/ns/}getctag
140
-	 *
141
-	 * @param string $principalUri
142
-	 * @return array
143
-	 */
144
-	function getAddressBooksForUser($principalUri) {
145
-		$principalUriOriginal = $principalUri;
146
-		$principalUri = $this->convertPrincipal($principalUri, true);
147
-		$query = $this->db->getQueryBuilder();
148
-		$query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
149
-			->from('addressbooks')
150
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
151
-
152
-		$addressBooks = [];
153
-
154
-		$result = $query->execute();
155
-		while($row = $result->fetch()) {
156
-			$addressBooks[$row['id']] = [
157
-				'id'  => $row['id'],
158
-				'uri' => $row['uri'],
159
-				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
160
-				'{DAV:}displayname' => $row['displayname'],
161
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
162
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
163
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
164
-			];
165
-
166
-			$this->addOwnerPrincipal($addressBooks[$row['id']]);
167
-		}
168
-		$result->closeCursor();
169
-
170
-		// query for shared addressbooks
171
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
172
-		$principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
173
-
174
-		$principals = array_map(function($principal) {
175
-			return urldecode($principal);
176
-		}, $principals);
177
-		$principals[]= $principalUri;
178
-
179
-		$query = $this->db->getQueryBuilder();
180
-		$result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
181
-			->from('dav_shares', 's')
182
-			->join('s', 'addressbooks', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
183
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
184
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
185
-			->setParameter('type', 'addressbook')
186
-			->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
187
-			->execute();
188
-
189
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
190
-		while($row = $result->fetch()) {
191
-			if ($row['principaluri'] === $principalUri) {
192
-				continue;
193
-			}
194
-
195
-			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
196
-			if (isset($addressBooks[$row['id']])) {
197
-				if ($readOnly) {
198
-					// New share can not have more permissions then the old one.
199
-					continue;
200
-				}
201
-				if (isset($addressBooks[$row['id']][$readOnlyPropertyName]) &&
202
-					$addressBooks[$row['id']][$readOnlyPropertyName] === 0) {
203
-					// Old share is already read-write, no more permissions can be gained
204
-					continue;
205
-				}
206
-			}
207
-
208
-			list(, $name) = \Sabre\Uri\split($row['principaluri']);
209
-			$uri = $row['uri'] . '_shared_by_' . $name;
210
-			$displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
211
-
212
-			$addressBooks[$row['id']] = [
213
-				'id'  => $row['id'],
214
-				'uri' => $uri,
215
-				'principaluri' => $principalUriOriginal,
216
-				'{DAV:}displayname' => $displayName,
217
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
218
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
219
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
220
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
221
-				$readOnlyPropertyName => $readOnly,
222
-			];
223
-
224
-			$this->addOwnerPrincipal($addressBooks[$row['id']]);
225
-		}
226
-		$result->closeCursor();
227
-
228
-		return array_values($addressBooks);
229
-	}
230
-
231
-	public function getUsersOwnAddressBooks($principalUri) {
232
-		$principalUri = $this->convertPrincipal($principalUri, true);
233
-		$query = $this->db->getQueryBuilder();
234
-		$query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
235
-			  ->from('addressbooks')
236
-			  ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
237
-
238
-		$addressBooks = [];
239
-
240
-		$result = $query->execute();
241
-		while($row = $result->fetch()) {
242
-			$addressBooks[$row['id']] = [
243
-				'id'  => $row['id'],
244
-				'uri' => $row['uri'],
245
-				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
246
-				'{DAV:}displayname' => $row['displayname'],
247
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
248
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
249
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
250
-			];
251
-
252
-			$this->addOwnerPrincipal($addressBooks[$row['id']]);
253
-		}
254
-		$result->closeCursor();
255
-
256
-		return array_values($addressBooks);
257
-	}
258
-
259
-	private function getUserDisplayName($uid) {
260
-		if (!isset($this->userDisplayNames[$uid])) {
261
-			$user = $this->userManager->get($uid);
262
-
263
-			if ($user instanceof IUser) {
264
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
265
-			} else {
266
-				$this->userDisplayNames[$uid] = $uid;
267
-			}
268
-		}
269
-
270
-		return $this->userDisplayNames[$uid];
271
-	}
272
-
273
-	/**
274
-	 * @param int $addressBookId
275
-	 */
276
-	public function getAddressBookById($addressBookId) {
277
-		$query = $this->db->getQueryBuilder();
278
-		$result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
279
-			->from('addressbooks')
280
-			->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
281
-			->execute();
282
-
283
-		$row = $result->fetch();
284
-		$result->closeCursor();
285
-		if ($row === false) {
286
-			return null;
287
-		}
288
-
289
-		$addressBook = [
290
-			'id'  => $row['id'],
291
-			'uri' => $row['uri'],
292
-			'principaluri' => $row['principaluri'],
293
-			'{DAV:}displayname' => $row['displayname'],
294
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
295
-			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
296
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
297
-		];
298
-
299
-		$this->addOwnerPrincipal($addressBook);
300
-
301
-		return $addressBook;
302
-	}
303
-
304
-	/**
305
-	 * @param $addressBookUri
306
-	 * @return array|null
307
-	 */
308
-	public function getAddressBooksByUri($principal, $addressBookUri) {
309
-		$query = $this->db->getQueryBuilder();
310
-		$result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
311
-			->from('addressbooks')
312
-			->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
313
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
314
-			->setMaxResults(1)
315
-			->execute();
316
-
317
-		$row = $result->fetch();
318
-		$result->closeCursor();
319
-		if ($row === false) {
320
-			return null;
321
-		}
322
-
323
-		$addressBook = [
324
-			'id'  => $row['id'],
325
-			'uri' => $row['uri'],
326
-			'principaluri' => $row['principaluri'],
327
-			'{DAV:}displayname' => $row['displayname'],
328
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
329
-			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
330
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
331
-		];
332
-
333
-		$this->addOwnerPrincipal($addressBook);
334
-
335
-		return $addressBook;
336
-	}
337
-
338
-	/**
339
-	 * Updates properties for an address book.
340
-	 *
341
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
342
-	 * To do the actual updates, you must tell this object which properties
343
-	 * you're going to process with the handle() method.
344
-	 *
345
-	 * Calling the handle method is like telling the PropPatch object "I
346
-	 * promise I can handle updating this property".
347
-	 *
348
-	 * Read the PropPatch documentation for more info and examples.
349
-	 *
350
-	 * @param string $addressBookId
351
-	 * @param \Sabre\DAV\PropPatch $propPatch
352
-	 * @return void
353
-	 */
354
-	function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
355
-		$supportedProperties = [
356
-			'{DAV:}displayname',
357
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description',
358
-		];
359
-
360
-		/**
361
-		 * @suppress SqlInjectionChecker
362
-		 */
363
-		$propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
364
-
365
-			$updates = [];
366
-			foreach($mutations as $property=>$newValue) {
367
-
368
-				switch($property) {
369
-					case '{DAV:}displayname' :
370
-						$updates['displayname'] = $newValue;
371
-						break;
372
-					case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
373
-						$updates['description'] = $newValue;
374
-						break;
375
-				}
376
-			}
377
-			$query = $this->db->getQueryBuilder();
378
-			$query->update('addressbooks');
379
-
380
-			foreach($updates as $key=>$value) {
381
-				$query->set($key, $query->createNamedParameter($value));
382
-			}
383
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
384
-			->execute();
385
-
386
-			$this->addChange($addressBookId, "", 2);
387
-
388
-			return true;
389
-
390
-		});
391
-	}
392
-
393
-	/**
394
-	 * Creates a new address book
395
-	 *
396
-	 * @param string $principalUri
397
-	 * @param string $url Just the 'basename' of the url.
398
-	 * @param array $properties
399
-	 * @return int
400
-	 * @throws BadRequest
401
-	 */
402
-	function createAddressBook($principalUri, $url, array $properties) {
403
-		$values = [
404
-			'displayname' => null,
405
-			'description' => null,
406
-			'principaluri' => $principalUri,
407
-			'uri' => $url,
408
-			'synctoken' => 1
409
-		];
410
-
411
-		foreach($properties as $property=>$newValue) {
412
-
413
-			switch($property) {
414
-				case '{DAV:}displayname' :
415
-					$values['displayname'] = $newValue;
416
-					break;
417
-				case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
418
-					$values['description'] = $newValue;
419
-					break;
420
-				default :
421
-					throw new BadRequest('Unknown property: ' . $property);
422
-			}
423
-
424
-		}
425
-
426
-		// Fallback to make sure the displayname is set. Some clients may refuse
427
-		// to work with addressbooks not having a displayname.
428
-		if(is_null($values['displayname'])) {
429
-			$values['displayname'] = $url;
430
-		}
431
-
432
-		$query = $this->db->getQueryBuilder();
433
-		$query->insert('addressbooks')
434
-			->values([
435
-				'uri' => $query->createParameter('uri'),
436
-				'displayname' => $query->createParameter('displayname'),
437
-				'description' => $query->createParameter('description'),
438
-				'principaluri' => $query->createParameter('principaluri'),
439
-				'synctoken' => $query->createParameter('synctoken'),
440
-			])
441
-			->setParameters($values)
442
-			->execute();
443
-
444
-		return $query->getLastInsertId();
445
-	}
446
-
447
-	/**
448
-	 * Deletes an entire addressbook and all its contents
449
-	 *
450
-	 * @param mixed $addressBookId
451
-	 * @return void
452
-	 */
453
-	function deleteAddressBook($addressBookId) {
454
-		$query = $this->db->getQueryBuilder();
455
-		$query->delete('cards')
456
-			->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
457
-			->setParameter('addressbookid', $addressBookId)
458
-			->execute();
459
-
460
-		$query->delete('addressbookchanges')
461
-			->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
462
-			->setParameter('addressbookid', $addressBookId)
463
-			->execute();
464
-
465
-		$query->delete('addressbooks')
466
-			->where($query->expr()->eq('id', $query->createParameter('id')))
467
-			->setParameter('id', $addressBookId)
468
-			->execute();
469
-
470
-		$this->sharingBackend->deleteAllShares($addressBookId);
471
-
472
-		$query->delete($this->dbCardsPropertiesTable)
473
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
474
-			->execute();
475
-
476
-	}
477
-
478
-	/**
479
-	 * Returns all cards for a specific addressbook id.
480
-	 *
481
-	 * This method should return the following properties for each card:
482
-	 *   * carddata - raw vcard data
483
-	 *   * uri - Some unique url
484
-	 *   * lastmodified - A unix timestamp
485
-	 *
486
-	 * It's recommended to also return the following properties:
487
-	 *   * etag - A unique etag. This must change every time the card changes.
488
-	 *   * size - The size of the card in bytes.
489
-	 *
490
-	 * If these last two properties are provided, less time will be spent
491
-	 * calculating them. If they are specified, you can also ommit carddata.
492
-	 * This may speed up certain requests, especially with large cards.
493
-	 *
494
-	 * @param mixed $addressBookId
495
-	 * @return array
496
-	 */
497
-	function getCards($addressBookId) {
498
-		$query = $this->db->getQueryBuilder();
499
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
500
-			->from('cards')
501
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
502
-
503
-		$cards = [];
504
-
505
-		$result = $query->execute();
506
-		while($row = $result->fetch()) {
507
-			$row['etag'] = '"' . $row['etag'] . '"';
508
-			$row['carddata'] = $this->readBlob($row['carddata']);
509
-			$cards[] = $row;
510
-		}
511
-		$result->closeCursor();
512
-
513
-		return $cards;
514
-	}
515
-
516
-	/**
517
-	 * Returns a specific card.
518
-	 *
519
-	 * The same set of properties must be returned as with getCards. The only
520
-	 * exception is that 'carddata' is absolutely required.
521
-	 *
522
-	 * If the card does not exist, you must return false.
523
-	 *
524
-	 * @param mixed $addressBookId
525
-	 * @param string $cardUri
526
-	 * @return array
527
-	 */
528
-	function getCard($addressBookId, $cardUri) {
529
-		$query = $this->db->getQueryBuilder();
530
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
531
-			->from('cards')
532
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
533
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
534
-			->setMaxResults(1);
535
-
536
-		$result = $query->execute();
537
-		$row = $result->fetch();
538
-		if (!$row) {
539
-			return false;
540
-		}
541
-		$row['etag'] = '"' . $row['etag'] . '"';
542
-		$row['carddata'] = $this->readBlob($row['carddata']);
543
-
544
-		return $row;
545
-	}
546
-
547
-	/**
548
-	 * Returns a list of cards.
549
-	 *
550
-	 * This method should work identical to getCard, but instead return all the
551
-	 * cards in the list as an array.
552
-	 *
553
-	 * If the backend supports this, it may allow for some speed-ups.
554
-	 *
555
-	 * @param mixed $addressBookId
556
-	 * @param string[] $uris
557
-	 * @return array
558
-	 */
559
-	function getMultipleCards($addressBookId, array $uris) {
560
-		if (empty($uris)) {
561
-			return [];
562
-		}
563
-
564
-		$chunks = array_chunk($uris, 100);
565
-		$cards = [];
566
-
567
-		$query = $this->db->getQueryBuilder();
568
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
569
-			->from('cards')
570
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
571
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
572
-
573
-		foreach ($chunks as $uris) {
574
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
575
-			$result = $query->execute();
576
-
577
-			while ($row = $result->fetch()) {
578
-				$row['etag'] = '"' . $row['etag'] . '"';
579
-				$row['carddata'] = $this->readBlob($row['carddata']);
580
-				$cards[] = $row;
581
-			}
582
-			$result->closeCursor();
583
-		}
584
-		return $cards;
585
-	}
586
-
587
-	/**
588
-	 * Creates a new card.
589
-	 *
590
-	 * The addressbook id will be passed as the first argument. This is the
591
-	 * same id as it is returned from the getAddressBooksForUser method.
592
-	 *
593
-	 * The cardUri is a base uri, and doesn't include the full path. The
594
-	 * cardData argument is the vcard body, and is passed as a string.
595
-	 *
596
-	 * It is possible to return an ETag from this method. This ETag is for the
597
-	 * newly created resource, and must be enclosed with double quotes (that
598
-	 * is, the string itself must contain the double quotes).
599
-	 *
600
-	 * You should only return the ETag if you store the carddata as-is. If a
601
-	 * subsequent GET request on the same card does not have the same body,
602
-	 * byte-by-byte and you did return an ETag here, clients tend to get
603
-	 * confused.
604
-	 *
605
-	 * If you don't return an ETag, you can just return null.
606
-	 *
607
-	 * @param mixed $addressBookId
608
-	 * @param string $cardUri
609
-	 * @param string $cardData
610
-	 * @return string
611
-	 */
612
-	function createCard($addressBookId, $cardUri, $cardData) {
613
-		$etag = md5($cardData);
614
-		$uid = $this->getUID($cardData);
615
-
616
-		$q = $this->db->getQueryBuilder();
617
-		$q->select('uid')
618
-			->from('cards')
619
-			->where($q->expr()->eq('addressbookid', $q->createNamedParameter($addressBookId)))
620
-			->andWhere($q->expr()->eq('uid', $q->createNamedParameter($uid)))
621
-			->setMaxResults(1);
622
-		$result = $q->execute();
623
-		$count = (bool) $result->fetchColumn();
624
-		$result->closeCursor();
625
-		if ($count) {
626
-			throw new \Sabre\DAV\Exception\BadRequest('VCard object with uid already exists in this addressbook collection.');
627
-		}
628
-
629
-		$query = $this->db->getQueryBuilder();
630
-		$query->insert('cards')
631
-			->values([
632
-				'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
633
-				'uri' => $query->createNamedParameter($cardUri),
634
-				'lastmodified' => $query->createNamedParameter(time()),
635
-				'addressbookid' => $query->createNamedParameter($addressBookId),
636
-				'size' => $query->createNamedParameter(strlen($cardData)),
637
-				'etag' => $query->createNamedParameter($etag),
638
-				'uid' => $query->createNamedParameter($uid),
639
-			])
640
-			->execute();
641
-
642
-		$this->addChange($addressBookId, $cardUri, 1);
643
-		$this->updateProperties($addressBookId, $cardUri, $cardData);
644
-
645
-		$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
646
-			new GenericEvent(null, [
647
-				'addressBookId' => $addressBookId,
648
-				'cardUri' => $cardUri,
649
-				'cardData' => $cardData]));
650
-
651
-		return '"' . $etag . '"';
652
-	}
653
-
654
-	/**
655
-	 * Updates a card.
656
-	 *
657
-	 * The addressbook id will be passed as the first argument. This is the
658
-	 * same id as it is returned from the getAddressBooksForUser method.
659
-	 *
660
-	 * The cardUri is a base uri, and doesn't include the full path. The
661
-	 * cardData argument is the vcard body, and is passed as a string.
662
-	 *
663
-	 * It is possible to return an ETag from this method. This ETag should
664
-	 * match that of the updated resource, and must be enclosed with double
665
-	 * quotes (that is: the string itself must contain the actual quotes).
666
-	 *
667
-	 * You should only return the ETag if you store the carddata as-is. If a
668
-	 * subsequent GET request on the same card does not have the same body,
669
-	 * byte-by-byte and you did return an ETag here, clients tend to get
670
-	 * confused.
671
-	 *
672
-	 * If you don't return an ETag, you can just return null.
673
-	 *
674
-	 * @param mixed $addressBookId
675
-	 * @param string $cardUri
676
-	 * @param string $cardData
677
-	 * @return string
678
-	 */
679
-	function updateCard($addressBookId, $cardUri, $cardData) {
680
-
681
-		$uid = $this->getUID($cardData);
682
-		$etag = md5($cardData);
683
-		$query = $this->db->getQueryBuilder();
684
-		$query->update('cards')
685
-			->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
686
-			->set('lastmodified', $query->createNamedParameter(time()))
687
-			->set('size', $query->createNamedParameter(strlen($cardData)))
688
-			->set('etag', $query->createNamedParameter($etag))
689
-			->set('uid', $query->createNamedParameter($uid))
690
-			->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
691
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
692
-			->execute();
693
-
694
-		$this->addChange($addressBookId, $cardUri, 2);
695
-		$this->updateProperties($addressBookId, $cardUri, $cardData);
696
-
697
-		$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
698
-			new GenericEvent(null, [
699
-				'addressBookId' => $addressBookId,
700
-				'cardUri' => $cardUri,
701
-				'cardData' => $cardData]));
702
-
703
-		return '"' . $etag . '"';
704
-	}
705
-
706
-	/**
707
-	 * Deletes a card
708
-	 *
709
-	 * @param mixed $addressBookId
710
-	 * @param string $cardUri
711
-	 * @return bool
712
-	 */
713
-	function deleteCard($addressBookId, $cardUri) {
714
-		try {
715
-			$cardId = $this->getCardId($addressBookId, $cardUri);
716
-		} catch (\InvalidArgumentException $e) {
717
-			$cardId = null;
718
-		}
719
-		$query = $this->db->getQueryBuilder();
720
-		$ret = $query->delete('cards')
721
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
722
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
723
-			->execute();
724
-
725
-		$this->addChange($addressBookId, $cardUri, 3);
726
-
727
-		$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
728
-			new GenericEvent(null, [
729
-				'addressBookId' => $addressBookId,
730
-				'cardUri' => $cardUri]));
731
-
732
-		if ($ret === 1) {
733
-			if ($cardId !== null) {
734
-				$this->purgeProperties($addressBookId, $cardId);
735
-			}
736
-			return true;
737
-		}
738
-
739
-		return false;
740
-	}
741
-
742
-	/**
743
-	 * The getChanges method returns all the changes that have happened, since
744
-	 * the specified syncToken in the specified address book.
745
-	 *
746
-	 * This function should return an array, such as the following:
747
-	 *
748
-	 * [
749
-	 *   'syncToken' => 'The current synctoken',
750
-	 *   'added'   => [
751
-	 *      'new.txt',
752
-	 *   ],
753
-	 *   'modified'   => [
754
-	 *      'modified.txt',
755
-	 *   ],
756
-	 *   'deleted' => [
757
-	 *      'foo.php.bak',
758
-	 *      'old.txt'
759
-	 *   ]
760
-	 * ];
761
-	 *
762
-	 * The returned syncToken property should reflect the *current* syncToken
763
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
764
-	 * property. This is needed here too, to ensure the operation is atomic.
765
-	 *
766
-	 * If the $syncToken argument is specified as null, this is an initial
767
-	 * sync, and all members should be reported.
768
-	 *
769
-	 * The modified property is an array of nodenames that have changed since
770
-	 * the last token.
771
-	 *
772
-	 * The deleted property is an array with nodenames, that have been deleted
773
-	 * from collection.
774
-	 *
775
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
776
-	 * 1, you only have to report changes that happened only directly in
777
-	 * immediate descendants. If it's 2, it should also include changes from
778
-	 * the nodes below the child collections. (grandchildren)
779
-	 *
780
-	 * The $limit argument allows a client to specify how many results should
781
-	 * be returned at most. If the limit is not specified, it should be treated
782
-	 * as infinite.
783
-	 *
784
-	 * If the limit (infinite or not) is higher than you're willing to return,
785
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
786
-	 *
787
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
788
-	 * return null.
789
-	 *
790
-	 * The limit is 'suggestive'. You are free to ignore it.
791
-	 *
792
-	 * @param string $addressBookId
793
-	 * @param string $syncToken
794
-	 * @param int $syncLevel
795
-	 * @param int $limit
796
-	 * @return array
797
-	 */
798
-	function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
799
-		// Current synctoken
800
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
801
-		$stmt->execute([ $addressBookId ]);
802
-		$currentToken = $stmt->fetchColumn(0);
803
-
804
-		if (is_null($currentToken)) return null;
805
-
806
-		$result = [
807
-			'syncToken' => $currentToken,
808
-			'added'     => [],
809
-			'modified'  => [],
810
-			'deleted'   => [],
811
-		];
812
-
813
-		if ($syncToken) {
814
-
815
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
816
-			if ($limit>0) {
817
-				$query .= " LIMIT " . (int)$limit;
818
-			}
819
-
820
-			// Fetching all changes
821
-			$stmt = $this->db->prepare($query);
822
-			$stmt->execute([$syncToken, $currentToken, $addressBookId]);
823
-
824
-			$changes = [];
825
-
826
-			// This loop ensures that any duplicates are overwritten, only the
827
-			// last change on a node is relevant.
828
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
829
-
830
-				$changes[$row['uri']] = $row['operation'];
831
-
832
-			}
833
-
834
-			foreach($changes as $uri => $operation) {
835
-
836
-				switch($operation) {
837
-					case 1:
838
-						$result['added'][] = $uri;
839
-						break;
840
-					case 2:
841
-						$result['modified'][] = $uri;
842
-						break;
843
-					case 3:
844
-						$result['deleted'][] = $uri;
845
-						break;
846
-				}
847
-
848
-			}
849
-		} else {
850
-			// No synctoken supplied, this is the initial sync.
851
-			$query = "SELECT `uri` FROM `*PREFIX*cards` WHERE `addressbookid` = ?";
852
-			$stmt = $this->db->prepare($query);
853
-			$stmt->execute([$addressBookId]);
854
-
855
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
856
-		}
857
-		return $result;
858
-	}
859
-
860
-	/**
861
-	 * Adds a change record to the addressbookchanges table.
862
-	 *
863
-	 * @param mixed $addressBookId
864
-	 * @param string $objectUri
865
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete
866
-	 * @return void
867
-	 */
868
-	protected function addChange($addressBookId, $objectUri, $operation) {
869
-		$sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?';
870
-		$stmt = $this->db->prepare($sql);
871
-		$stmt->execute([
872
-			$objectUri,
873
-			$addressBookId,
874
-			$operation,
875
-			$addressBookId
876
-		]);
877
-		$stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
878
-		$stmt->execute([
879
-			$addressBookId
880
-		]);
881
-	}
882
-
883
-	private function readBlob($cardData) {
884
-		if (is_resource($cardData)) {
885
-			return stream_get_contents($cardData);
886
-		}
887
-
888
-		return $cardData;
889
-	}
890
-
891
-	/**
892
-	 * @param IShareable $shareable
893
-	 * @param string[] $add
894
-	 * @param string[] $remove
895
-	 */
896
-	public function updateShares(IShareable $shareable, $add, $remove) {
897
-		$this->sharingBackend->updateShares($shareable, $add, $remove);
898
-	}
899
-
900
-	/**
901
-	 * search contact
902
-	 *
903
-	 * @param int $addressBookId
904
-	 * @param string $pattern which should match within the $searchProperties
905
-	 * @param array $searchProperties defines the properties within the query pattern should match
906
-	 * @param array $options = array() to define the search behavior
907
-	 * 	- 'escape_like_param' - If set to false wildcards _ and % are not escaped, otherwise they are
908
-	 * @return array an array of contacts which are arrays of key-value-pairs
909
-	 */
910
-	public function search($addressBookId, $pattern, $searchProperties, $options = array()) {
911
-		$query = $this->db->getQueryBuilder();
912
-		$query2 = $this->db->getQueryBuilder();
913
-
914
-		$query2->selectDistinct('cp.cardid')->from($this->dbCardsPropertiesTable, 'cp');
915
-		$query2->andWhere($query2->expr()->eq('cp.addressbookid', $query->createNamedParameter($addressBookId)));
916
-		$or = $query2->expr()->orX();
917
-		foreach ($searchProperties as $property) {
918
-			$or->add($query2->expr()->eq('cp.name', $query->createNamedParameter($property)));
919
-		}
920
-		$query2->andWhere($or);
921
-
922
-		// No need for like when the pattern is empty
923
-		if ('' !== $pattern) {
924
-			if(\array_key_exists('escape_like_param', $options) && $options['escape_like_param'] === false) {
925
-				$query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter($pattern)));
926
-			} else {
927
-				$query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
928
-			}
929
-		}
930
-
931
-		$query->select('c.carddata', 'c.uri')->from($this->dbCardsTable, 'c')
932
-			->where($query->expr()->in('c.id', $query->createFunction($query2->getSQL())));
933
-
934
-		$result = $query->execute();
935
-		$cards = $result->fetchAll();
936
-
937
-		$result->closeCursor();
938
-
939
-		return array_map(function($array) {
940
-			$array['carddata'] = $this->readBlob($array['carddata']);
941
-			return $array;
942
-		}, $cards);
943
-	}
944
-
945
-	/**
946
-	 * @param int $bookId
947
-	 * @param string $name
948
-	 * @return array
949
-	 */
950
-	public function collectCardProperties($bookId, $name) {
951
-		$query = $this->db->getQueryBuilder();
952
-		$result = $query->selectDistinct('value')
953
-			->from($this->dbCardsPropertiesTable)
954
-			->where($query->expr()->eq('name', $query->createNamedParameter($name)))
955
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
956
-			->execute();
957
-
958
-		$all = $result->fetchAll(PDO::FETCH_COLUMN);
959
-		$result->closeCursor();
960
-
961
-		return $all;
962
-	}
963
-
964
-	/**
965
-	 * get URI from a given contact
966
-	 *
967
-	 * @param int $id
968
-	 * @return string
969
-	 */
970
-	public function getCardUri($id) {
971
-		$query = $this->db->getQueryBuilder();
972
-		$query->select('uri')->from($this->dbCardsTable)
973
-				->where($query->expr()->eq('id', $query->createParameter('id')))
974
-				->setParameter('id', $id);
975
-
976
-		$result = $query->execute();
977
-		$uri = $result->fetch();
978
-		$result->closeCursor();
979
-
980
-		if (!isset($uri['uri'])) {
981
-			throw new \InvalidArgumentException('Card does not exists: ' . $id);
982
-		}
983
-
984
-		return $uri['uri'];
985
-	}
986
-
987
-	/**
988
-	 * return contact with the given URI
989
-	 *
990
-	 * @param int $addressBookId
991
-	 * @param string $uri
992
-	 * @returns array
993
-	 */
994
-	public function getContact($addressBookId, $uri) {
995
-		$result = [];
996
-		$query = $this->db->getQueryBuilder();
997
-		$query->select('*')->from($this->dbCardsTable)
998
-				->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
999
-				->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1000
-		$queryResult = $query->execute();
1001
-		$contact = $queryResult->fetch();
1002
-		$queryResult->closeCursor();
1003
-
1004
-		if (is_array($contact)) {
1005
-			$result = $contact;
1006
-		}
1007
-
1008
-		return $result;
1009
-	}
1010
-
1011
-	/**
1012
-	 * Returns the list of people whom this address book is shared with.
1013
-	 *
1014
-	 * Every element in this array should have the following properties:
1015
-	 *   * href - Often a mailto: address
1016
-	 *   * commonName - Optional, for example a first + last name
1017
-	 *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
1018
-	 *   * readOnly - boolean
1019
-	 *   * summary - Optional, a description for the share
1020
-	 *
1021
-	 * @return array
1022
-	 */
1023
-	public function getShares($addressBookId) {
1024
-		return $this->sharingBackend->getShares($addressBookId);
1025
-	}
1026
-
1027
-	/**
1028
-	 * update properties table
1029
-	 *
1030
-	 * @param int $addressBookId
1031
-	 * @param string $cardUri
1032
-	 * @param string $vCardSerialized
1033
-	 */
1034
-	protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
1035
-		$cardId = $this->getCardId($addressBookId, $cardUri);
1036
-		$vCard = $this->readCard($vCardSerialized);
1037
-
1038
-		$this->purgeProperties($addressBookId, $cardId);
1039
-
1040
-		$query = $this->db->getQueryBuilder();
1041
-		$query->insert($this->dbCardsPropertiesTable)
1042
-			->values(
1043
-				[
1044
-					'addressbookid' => $query->createNamedParameter($addressBookId),
1045
-					'cardid' => $query->createNamedParameter($cardId),
1046
-					'name' => $query->createParameter('name'),
1047
-					'value' => $query->createParameter('value'),
1048
-					'preferred' => $query->createParameter('preferred')
1049
-				]
1050
-			);
1051
-
1052
-		foreach ($vCard->children() as $property) {
1053
-			if(!in_array($property->name, self::$indexProperties)) {
1054
-				continue;
1055
-			}
1056
-			$preferred = 0;
1057
-			foreach($property->parameters as $parameter) {
1058
-				if ($parameter->name === 'TYPE' && strtoupper($parameter->getValue()) === 'PREF') {
1059
-					$preferred = 1;
1060
-					break;
1061
-				}
1062
-			}
1063
-			$query->setParameter('name', $property->name);
1064
-			$query->setParameter('value', substr($property->getValue(), 0, 254));
1065
-			$query->setParameter('preferred', $preferred);
1066
-			$query->execute();
1067
-		}
1068
-	}
1069
-
1070
-	/**
1071
-	 * read vCard data into a vCard object
1072
-	 *
1073
-	 * @param string $cardData
1074
-	 * @return VCard
1075
-	 */
1076
-	protected function readCard($cardData) {
1077
-		return  Reader::read($cardData);
1078
-	}
1079
-
1080
-	/**
1081
-	 * delete all properties from a given card
1082
-	 *
1083
-	 * @param int $addressBookId
1084
-	 * @param int $cardId
1085
-	 */
1086
-	protected function purgeProperties($addressBookId, $cardId) {
1087
-		$query = $this->db->getQueryBuilder();
1088
-		$query->delete($this->dbCardsPropertiesTable)
1089
-			->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
1090
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1091
-		$query->execute();
1092
-	}
1093
-
1094
-	/**
1095
-	 * get ID from a given contact
1096
-	 *
1097
-	 * @param int $addressBookId
1098
-	 * @param string $uri
1099
-	 * @return int
1100
-	 */
1101
-	protected function getCardId($addressBookId, $uri) {
1102
-		$query = $this->db->getQueryBuilder();
1103
-		$query->select('id')->from($this->dbCardsTable)
1104
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1105
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1106
-
1107
-		$result = $query->execute();
1108
-		$cardIds = $result->fetch();
1109
-		$result->closeCursor();
1110
-
1111
-		if (!isset($cardIds['id'])) {
1112
-			throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1113
-		}
1114
-
1115
-		return (int)$cardIds['id'];
1116
-	}
1117
-
1118
-	/**
1119
-	 * For shared address books the sharee is set in the ACL of the address book
1120
-	 * @param $addressBookId
1121
-	 * @param $acl
1122
-	 * @return array
1123
-	 */
1124
-	public function applyShareAcl($addressBookId, $acl) {
1125
-		return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1126
-	}
1127
-
1128
-	private function convertPrincipal($principalUri, $toV2) {
1129
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1130
-			list(, $name) = \Sabre\Uri\split($principalUri);
1131
-			if ($toV2 === true) {
1132
-				return "principals/users/$name";
1133
-			}
1134
-			return "principals/$name";
1135
-		}
1136
-		return $principalUri;
1137
-	}
1138
-
1139
-	private function addOwnerPrincipal(&$addressbookInfo) {
1140
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
1141
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
1142
-		if (isset($addressbookInfo[$ownerPrincipalKey])) {
1143
-			$uri = $addressbookInfo[$ownerPrincipalKey];
1144
-		} else {
1145
-			$uri = $addressbookInfo['principaluri'];
1146
-		}
1147
-
1148
-		$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
1149
-		if (isset($principalInformation['{DAV:}displayname'])) {
1150
-			$addressbookInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
1151
-		}
1152
-	}
1153
-
1154
-	/**
1155
-	 * Extract UID from vcard
1156
-	 *
1157
-	 * @param string $cardData the vcard raw data
1158
-	 * @return string the uid
1159
-	 * @throws BadRequest if no UID is available
1160
-	 */
1161
-	private function getUID($cardData) {
1162
-		if ($cardData != '') {
1163
-			$vCard = Reader::read($cardData);
1164
-			if ($vCard->UID) {
1165
-				$uid = $vCard->UID->getValue();
1166
-				return $uid;
1167
-			}
1168
-			// should already be handled, but just in case
1169
-			throw new BadRequest('vCards on CardDAV servers MUST have a UID property');
1170
-		}
1171
-		// should already be handled, but just in case
1172
-		throw new BadRequest('vCard can not be empty');
1173
-	}
56
+    const PERSONAL_ADDRESSBOOK_URI = 'contacts';
57
+    const PERSONAL_ADDRESSBOOK_NAME = 'Contacts';
58
+
59
+    /** @var Principal */
60
+    private $principalBackend;
61
+
62
+    /** @var string */
63
+    private $dbCardsTable = 'cards';
64
+
65
+    /** @var string */
66
+    private $dbCardsPropertiesTable = 'cards_properties';
67
+
68
+    /** @var IDBConnection */
69
+    private $db;
70
+
71
+    /** @var Backend */
72
+    private $sharingBackend;
73
+
74
+    /** @var array properties to index */
75
+    public static $indexProperties = array(
76
+            'BDAY', 'UID', 'N', 'FN', 'TITLE', 'ROLE', 'NOTE', 'NICKNAME',
77
+            'ORG', 'CATEGORIES', 'EMAIL', 'TEL', 'IMPP', 'ADR', 'URL', 'GEO', 'CLOUD');
78
+
79
+    /**
80
+     * @var string[] Map of uid => display name
81
+     */
82
+    protected $userDisplayNames;
83
+
84
+    /** @var IUserManager */
85
+    private $userManager;
86
+
87
+    /** @var EventDispatcherInterface */
88
+    private $dispatcher;
89
+
90
+    /**
91
+     * CardDavBackend constructor.
92
+     *
93
+     * @param IDBConnection $db
94
+     * @param Principal $principalBackend
95
+     * @param IUserManager $userManager
96
+     * @param IGroupManager $groupManager
97
+     * @param EventDispatcherInterface $dispatcher
98
+     */
99
+    public function __construct(IDBConnection $db,
100
+                                Principal $principalBackend,
101
+                                IUserManager $userManager,
102
+                                IGroupManager $groupManager,
103
+                                EventDispatcherInterface $dispatcher) {
104
+        $this->db = $db;
105
+        $this->principalBackend = $principalBackend;
106
+        $this->userManager = $userManager;
107
+        $this->dispatcher = $dispatcher;
108
+        $this->sharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'addressbook');
109
+    }
110
+
111
+    /**
112
+     * Return the number of address books for a principal
113
+     *
114
+     * @param $principalUri
115
+     * @return int
116
+     */
117
+    public function getAddressBooksForUserCount($principalUri) {
118
+        $principalUri = $this->convertPrincipal($principalUri, true);
119
+        $query = $this->db->getQueryBuilder();
120
+        $query->select($query->func()->count('*'))
121
+            ->from('addressbooks')
122
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
123
+
124
+        return (int)$query->execute()->fetchColumn();
125
+    }
126
+
127
+    /**
128
+     * Returns the list of address books for a specific user.
129
+     *
130
+     * Every addressbook should have the following properties:
131
+     *   id - an arbitrary unique id
132
+     *   uri - the 'basename' part of the url
133
+     *   principaluri - Same as the passed parameter
134
+     *
135
+     * Any additional clark-notation property may be passed besides this. Some
136
+     * common ones are :
137
+     *   {DAV:}displayname
138
+     *   {urn:ietf:params:xml:ns:carddav}addressbook-description
139
+     *   {http://calendarserver.org/ns/}getctag
140
+     *
141
+     * @param string $principalUri
142
+     * @return array
143
+     */
144
+    function getAddressBooksForUser($principalUri) {
145
+        $principalUriOriginal = $principalUri;
146
+        $principalUri = $this->convertPrincipal($principalUri, true);
147
+        $query = $this->db->getQueryBuilder();
148
+        $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
149
+            ->from('addressbooks')
150
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
151
+
152
+        $addressBooks = [];
153
+
154
+        $result = $query->execute();
155
+        while($row = $result->fetch()) {
156
+            $addressBooks[$row['id']] = [
157
+                'id'  => $row['id'],
158
+                'uri' => $row['uri'],
159
+                'principaluri' => $this->convertPrincipal($row['principaluri'], false),
160
+                '{DAV:}displayname' => $row['displayname'],
161
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
162
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
163
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
164
+            ];
165
+
166
+            $this->addOwnerPrincipal($addressBooks[$row['id']]);
167
+        }
168
+        $result->closeCursor();
169
+
170
+        // query for shared addressbooks
171
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
172
+        $principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
173
+
174
+        $principals = array_map(function($principal) {
175
+            return urldecode($principal);
176
+        }, $principals);
177
+        $principals[]= $principalUri;
178
+
179
+        $query = $this->db->getQueryBuilder();
180
+        $result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
181
+            ->from('dav_shares', 's')
182
+            ->join('s', 'addressbooks', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
183
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
184
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
185
+            ->setParameter('type', 'addressbook')
186
+            ->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
187
+            ->execute();
188
+
189
+        $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
190
+        while($row = $result->fetch()) {
191
+            if ($row['principaluri'] === $principalUri) {
192
+                continue;
193
+            }
194
+
195
+            $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
196
+            if (isset($addressBooks[$row['id']])) {
197
+                if ($readOnly) {
198
+                    // New share can not have more permissions then the old one.
199
+                    continue;
200
+                }
201
+                if (isset($addressBooks[$row['id']][$readOnlyPropertyName]) &&
202
+                    $addressBooks[$row['id']][$readOnlyPropertyName] === 0) {
203
+                    // Old share is already read-write, no more permissions can be gained
204
+                    continue;
205
+                }
206
+            }
207
+
208
+            list(, $name) = \Sabre\Uri\split($row['principaluri']);
209
+            $uri = $row['uri'] . '_shared_by_' . $name;
210
+            $displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
211
+
212
+            $addressBooks[$row['id']] = [
213
+                'id'  => $row['id'],
214
+                'uri' => $uri,
215
+                'principaluri' => $principalUriOriginal,
216
+                '{DAV:}displayname' => $displayName,
217
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
218
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
219
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
220
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
221
+                $readOnlyPropertyName => $readOnly,
222
+            ];
223
+
224
+            $this->addOwnerPrincipal($addressBooks[$row['id']]);
225
+        }
226
+        $result->closeCursor();
227
+
228
+        return array_values($addressBooks);
229
+    }
230
+
231
+    public function getUsersOwnAddressBooks($principalUri) {
232
+        $principalUri = $this->convertPrincipal($principalUri, true);
233
+        $query = $this->db->getQueryBuilder();
234
+        $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
235
+                ->from('addressbooks')
236
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
237
+
238
+        $addressBooks = [];
239
+
240
+        $result = $query->execute();
241
+        while($row = $result->fetch()) {
242
+            $addressBooks[$row['id']] = [
243
+                'id'  => $row['id'],
244
+                'uri' => $row['uri'],
245
+                'principaluri' => $this->convertPrincipal($row['principaluri'], false),
246
+                '{DAV:}displayname' => $row['displayname'],
247
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
248
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
249
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
250
+            ];
251
+
252
+            $this->addOwnerPrincipal($addressBooks[$row['id']]);
253
+        }
254
+        $result->closeCursor();
255
+
256
+        return array_values($addressBooks);
257
+    }
258
+
259
+    private function getUserDisplayName($uid) {
260
+        if (!isset($this->userDisplayNames[$uid])) {
261
+            $user = $this->userManager->get($uid);
262
+
263
+            if ($user instanceof IUser) {
264
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
265
+            } else {
266
+                $this->userDisplayNames[$uid] = $uid;
267
+            }
268
+        }
269
+
270
+        return $this->userDisplayNames[$uid];
271
+    }
272
+
273
+    /**
274
+     * @param int $addressBookId
275
+     */
276
+    public function getAddressBookById($addressBookId) {
277
+        $query = $this->db->getQueryBuilder();
278
+        $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
279
+            ->from('addressbooks')
280
+            ->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
281
+            ->execute();
282
+
283
+        $row = $result->fetch();
284
+        $result->closeCursor();
285
+        if ($row === false) {
286
+            return null;
287
+        }
288
+
289
+        $addressBook = [
290
+            'id'  => $row['id'],
291
+            'uri' => $row['uri'],
292
+            'principaluri' => $row['principaluri'],
293
+            '{DAV:}displayname' => $row['displayname'],
294
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
295
+            '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
296
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
297
+        ];
298
+
299
+        $this->addOwnerPrincipal($addressBook);
300
+
301
+        return $addressBook;
302
+    }
303
+
304
+    /**
305
+     * @param $addressBookUri
306
+     * @return array|null
307
+     */
308
+    public function getAddressBooksByUri($principal, $addressBookUri) {
309
+        $query = $this->db->getQueryBuilder();
310
+        $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
311
+            ->from('addressbooks')
312
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
313
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
314
+            ->setMaxResults(1)
315
+            ->execute();
316
+
317
+        $row = $result->fetch();
318
+        $result->closeCursor();
319
+        if ($row === false) {
320
+            return null;
321
+        }
322
+
323
+        $addressBook = [
324
+            'id'  => $row['id'],
325
+            'uri' => $row['uri'],
326
+            'principaluri' => $row['principaluri'],
327
+            '{DAV:}displayname' => $row['displayname'],
328
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
329
+            '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
330
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
331
+        ];
332
+
333
+        $this->addOwnerPrincipal($addressBook);
334
+
335
+        return $addressBook;
336
+    }
337
+
338
+    /**
339
+     * Updates properties for an address book.
340
+     *
341
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
342
+     * To do the actual updates, you must tell this object which properties
343
+     * you're going to process with the handle() method.
344
+     *
345
+     * Calling the handle method is like telling the PropPatch object "I
346
+     * promise I can handle updating this property".
347
+     *
348
+     * Read the PropPatch documentation for more info and examples.
349
+     *
350
+     * @param string $addressBookId
351
+     * @param \Sabre\DAV\PropPatch $propPatch
352
+     * @return void
353
+     */
354
+    function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
355
+        $supportedProperties = [
356
+            '{DAV:}displayname',
357
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description',
358
+        ];
359
+
360
+        /**
361
+         * @suppress SqlInjectionChecker
362
+         */
363
+        $propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
364
+
365
+            $updates = [];
366
+            foreach($mutations as $property=>$newValue) {
367
+
368
+                switch($property) {
369
+                    case '{DAV:}displayname' :
370
+                        $updates['displayname'] = $newValue;
371
+                        break;
372
+                    case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
373
+                        $updates['description'] = $newValue;
374
+                        break;
375
+                }
376
+            }
377
+            $query = $this->db->getQueryBuilder();
378
+            $query->update('addressbooks');
379
+
380
+            foreach($updates as $key=>$value) {
381
+                $query->set($key, $query->createNamedParameter($value));
382
+            }
383
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
384
+            ->execute();
385
+
386
+            $this->addChange($addressBookId, "", 2);
387
+
388
+            return true;
389
+
390
+        });
391
+    }
392
+
393
+    /**
394
+     * Creates a new address book
395
+     *
396
+     * @param string $principalUri
397
+     * @param string $url Just the 'basename' of the url.
398
+     * @param array $properties
399
+     * @return int
400
+     * @throws BadRequest
401
+     */
402
+    function createAddressBook($principalUri, $url, array $properties) {
403
+        $values = [
404
+            'displayname' => null,
405
+            'description' => null,
406
+            'principaluri' => $principalUri,
407
+            'uri' => $url,
408
+            'synctoken' => 1
409
+        ];
410
+
411
+        foreach($properties as $property=>$newValue) {
412
+
413
+            switch($property) {
414
+                case '{DAV:}displayname' :
415
+                    $values['displayname'] = $newValue;
416
+                    break;
417
+                case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
418
+                    $values['description'] = $newValue;
419
+                    break;
420
+                default :
421
+                    throw new BadRequest('Unknown property: ' . $property);
422
+            }
423
+
424
+        }
425
+
426
+        // Fallback to make sure the displayname is set. Some clients may refuse
427
+        // to work with addressbooks not having a displayname.
428
+        if(is_null($values['displayname'])) {
429
+            $values['displayname'] = $url;
430
+        }
431
+
432
+        $query = $this->db->getQueryBuilder();
433
+        $query->insert('addressbooks')
434
+            ->values([
435
+                'uri' => $query->createParameter('uri'),
436
+                'displayname' => $query->createParameter('displayname'),
437
+                'description' => $query->createParameter('description'),
438
+                'principaluri' => $query->createParameter('principaluri'),
439
+                'synctoken' => $query->createParameter('synctoken'),
440
+            ])
441
+            ->setParameters($values)
442
+            ->execute();
443
+
444
+        return $query->getLastInsertId();
445
+    }
446
+
447
+    /**
448
+     * Deletes an entire addressbook and all its contents
449
+     *
450
+     * @param mixed $addressBookId
451
+     * @return void
452
+     */
453
+    function deleteAddressBook($addressBookId) {
454
+        $query = $this->db->getQueryBuilder();
455
+        $query->delete('cards')
456
+            ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
457
+            ->setParameter('addressbookid', $addressBookId)
458
+            ->execute();
459
+
460
+        $query->delete('addressbookchanges')
461
+            ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
462
+            ->setParameter('addressbookid', $addressBookId)
463
+            ->execute();
464
+
465
+        $query->delete('addressbooks')
466
+            ->where($query->expr()->eq('id', $query->createParameter('id')))
467
+            ->setParameter('id', $addressBookId)
468
+            ->execute();
469
+
470
+        $this->sharingBackend->deleteAllShares($addressBookId);
471
+
472
+        $query->delete($this->dbCardsPropertiesTable)
473
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
474
+            ->execute();
475
+
476
+    }
477
+
478
+    /**
479
+     * Returns all cards for a specific addressbook id.
480
+     *
481
+     * This method should return the following properties for each card:
482
+     *   * carddata - raw vcard data
483
+     *   * uri - Some unique url
484
+     *   * lastmodified - A unix timestamp
485
+     *
486
+     * It's recommended to also return the following properties:
487
+     *   * etag - A unique etag. This must change every time the card changes.
488
+     *   * size - The size of the card in bytes.
489
+     *
490
+     * If these last two properties are provided, less time will be spent
491
+     * calculating them. If they are specified, you can also ommit carddata.
492
+     * This may speed up certain requests, especially with large cards.
493
+     *
494
+     * @param mixed $addressBookId
495
+     * @return array
496
+     */
497
+    function getCards($addressBookId) {
498
+        $query = $this->db->getQueryBuilder();
499
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
500
+            ->from('cards')
501
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
502
+
503
+        $cards = [];
504
+
505
+        $result = $query->execute();
506
+        while($row = $result->fetch()) {
507
+            $row['etag'] = '"' . $row['etag'] . '"';
508
+            $row['carddata'] = $this->readBlob($row['carddata']);
509
+            $cards[] = $row;
510
+        }
511
+        $result->closeCursor();
512
+
513
+        return $cards;
514
+    }
515
+
516
+    /**
517
+     * Returns a specific card.
518
+     *
519
+     * The same set of properties must be returned as with getCards. The only
520
+     * exception is that 'carddata' is absolutely required.
521
+     *
522
+     * If the card does not exist, you must return false.
523
+     *
524
+     * @param mixed $addressBookId
525
+     * @param string $cardUri
526
+     * @return array
527
+     */
528
+    function getCard($addressBookId, $cardUri) {
529
+        $query = $this->db->getQueryBuilder();
530
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
531
+            ->from('cards')
532
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
533
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
534
+            ->setMaxResults(1);
535
+
536
+        $result = $query->execute();
537
+        $row = $result->fetch();
538
+        if (!$row) {
539
+            return false;
540
+        }
541
+        $row['etag'] = '"' . $row['etag'] . '"';
542
+        $row['carddata'] = $this->readBlob($row['carddata']);
543
+
544
+        return $row;
545
+    }
546
+
547
+    /**
548
+     * Returns a list of cards.
549
+     *
550
+     * This method should work identical to getCard, but instead return all the
551
+     * cards in the list as an array.
552
+     *
553
+     * If the backend supports this, it may allow for some speed-ups.
554
+     *
555
+     * @param mixed $addressBookId
556
+     * @param string[] $uris
557
+     * @return array
558
+     */
559
+    function getMultipleCards($addressBookId, array $uris) {
560
+        if (empty($uris)) {
561
+            return [];
562
+        }
563
+
564
+        $chunks = array_chunk($uris, 100);
565
+        $cards = [];
566
+
567
+        $query = $this->db->getQueryBuilder();
568
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
569
+            ->from('cards')
570
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
571
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
572
+
573
+        foreach ($chunks as $uris) {
574
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
575
+            $result = $query->execute();
576
+
577
+            while ($row = $result->fetch()) {
578
+                $row['etag'] = '"' . $row['etag'] . '"';
579
+                $row['carddata'] = $this->readBlob($row['carddata']);
580
+                $cards[] = $row;
581
+            }
582
+            $result->closeCursor();
583
+        }
584
+        return $cards;
585
+    }
586
+
587
+    /**
588
+     * Creates a new card.
589
+     *
590
+     * The addressbook id will be passed as the first argument. This is the
591
+     * same id as it is returned from the getAddressBooksForUser method.
592
+     *
593
+     * The cardUri is a base uri, and doesn't include the full path. The
594
+     * cardData argument is the vcard body, and is passed as a string.
595
+     *
596
+     * It is possible to return an ETag from this method. This ETag is for the
597
+     * newly created resource, and must be enclosed with double quotes (that
598
+     * is, the string itself must contain the double quotes).
599
+     *
600
+     * You should only return the ETag if you store the carddata as-is. If a
601
+     * subsequent GET request on the same card does not have the same body,
602
+     * byte-by-byte and you did return an ETag here, clients tend to get
603
+     * confused.
604
+     *
605
+     * If you don't return an ETag, you can just return null.
606
+     *
607
+     * @param mixed $addressBookId
608
+     * @param string $cardUri
609
+     * @param string $cardData
610
+     * @return string
611
+     */
612
+    function createCard($addressBookId, $cardUri, $cardData) {
613
+        $etag = md5($cardData);
614
+        $uid = $this->getUID($cardData);
615
+
616
+        $q = $this->db->getQueryBuilder();
617
+        $q->select('uid')
618
+            ->from('cards')
619
+            ->where($q->expr()->eq('addressbookid', $q->createNamedParameter($addressBookId)))
620
+            ->andWhere($q->expr()->eq('uid', $q->createNamedParameter($uid)))
621
+            ->setMaxResults(1);
622
+        $result = $q->execute();
623
+        $count = (bool) $result->fetchColumn();
624
+        $result->closeCursor();
625
+        if ($count) {
626
+            throw new \Sabre\DAV\Exception\BadRequest('VCard object with uid already exists in this addressbook collection.');
627
+        }
628
+
629
+        $query = $this->db->getQueryBuilder();
630
+        $query->insert('cards')
631
+            ->values([
632
+                'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
633
+                'uri' => $query->createNamedParameter($cardUri),
634
+                'lastmodified' => $query->createNamedParameter(time()),
635
+                'addressbookid' => $query->createNamedParameter($addressBookId),
636
+                'size' => $query->createNamedParameter(strlen($cardData)),
637
+                'etag' => $query->createNamedParameter($etag),
638
+                'uid' => $query->createNamedParameter($uid),
639
+            ])
640
+            ->execute();
641
+
642
+        $this->addChange($addressBookId, $cardUri, 1);
643
+        $this->updateProperties($addressBookId, $cardUri, $cardData);
644
+
645
+        $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
646
+            new GenericEvent(null, [
647
+                'addressBookId' => $addressBookId,
648
+                'cardUri' => $cardUri,
649
+                'cardData' => $cardData]));
650
+
651
+        return '"' . $etag . '"';
652
+    }
653
+
654
+    /**
655
+     * Updates a card.
656
+     *
657
+     * The addressbook id will be passed as the first argument. This is the
658
+     * same id as it is returned from the getAddressBooksForUser method.
659
+     *
660
+     * The cardUri is a base uri, and doesn't include the full path. The
661
+     * cardData argument is the vcard body, and is passed as a string.
662
+     *
663
+     * It is possible to return an ETag from this method. This ETag should
664
+     * match that of the updated resource, and must be enclosed with double
665
+     * quotes (that is: the string itself must contain the actual quotes).
666
+     *
667
+     * You should only return the ETag if you store the carddata as-is. If a
668
+     * subsequent GET request on the same card does not have the same body,
669
+     * byte-by-byte and you did return an ETag here, clients tend to get
670
+     * confused.
671
+     *
672
+     * If you don't return an ETag, you can just return null.
673
+     *
674
+     * @param mixed $addressBookId
675
+     * @param string $cardUri
676
+     * @param string $cardData
677
+     * @return string
678
+     */
679
+    function updateCard($addressBookId, $cardUri, $cardData) {
680
+
681
+        $uid = $this->getUID($cardData);
682
+        $etag = md5($cardData);
683
+        $query = $this->db->getQueryBuilder();
684
+        $query->update('cards')
685
+            ->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
686
+            ->set('lastmodified', $query->createNamedParameter(time()))
687
+            ->set('size', $query->createNamedParameter(strlen($cardData)))
688
+            ->set('etag', $query->createNamedParameter($etag))
689
+            ->set('uid', $query->createNamedParameter($uid))
690
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
691
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
692
+            ->execute();
693
+
694
+        $this->addChange($addressBookId, $cardUri, 2);
695
+        $this->updateProperties($addressBookId, $cardUri, $cardData);
696
+
697
+        $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
698
+            new GenericEvent(null, [
699
+                'addressBookId' => $addressBookId,
700
+                'cardUri' => $cardUri,
701
+                'cardData' => $cardData]));
702
+
703
+        return '"' . $etag . '"';
704
+    }
705
+
706
+    /**
707
+     * Deletes a card
708
+     *
709
+     * @param mixed $addressBookId
710
+     * @param string $cardUri
711
+     * @return bool
712
+     */
713
+    function deleteCard($addressBookId, $cardUri) {
714
+        try {
715
+            $cardId = $this->getCardId($addressBookId, $cardUri);
716
+        } catch (\InvalidArgumentException $e) {
717
+            $cardId = null;
718
+        }
719
+        $query = $this->db->getQueryBuilder();
720
+        $ret = $query->delete('cards')
721
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
722
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
723
+            ->execute();
724
+
725
+        $this->addChange($addressBookId, $cardUri, 3);
726
+
727
+        $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
728
+            new GenericEvent(null, [
729
+                'addressBookId' => $addressBookId,
730
+                'cardUri' => $cardUri]));
731
+
732
+        if ($ret === 1) {
733
+            if ($cardId !== null) {
734
+                $this->purgeProperties($addressBookId, $cardId);
735
+            }
736
+            return true;
737
+        }
738
+
739
+        return false;
740
+    }
741
+
742
+    /**
743
+     * The getChanges method returns all the changes that have happened, since
744
+     * the specified syncToken in the specified address book.
745
+     *
746
+     * This function should return an array, such as the following:
747
+     *
748
+     * [
749
+     *   'syncToken' => 'The current synctoken',
750
+     *   'added'   => [
751
+     *      'new.txt',
752
+     *   ],
753
+     *   'modified'   => [
754
+     *      'modified.txt',
755
+     *   ],
756
+     *   'deleted' => [
757
+     *      'foo.php.bak',
758
+     *      'old.txt'
759
+     *   ]
760
+     * ];
761
+     *
762
+     * The returned syncToken property should reflect the *current* syncToken
763
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
764
+     * property. This is needed here too, to ensure the operation is atomic.
765
+     *
766
+     * If the $syncToken argument is specified as null, this is an initial
767
+     * sync, and all members should be reported.
768
+     *
769
+     * The modified property is an array of nodenames that have changed since
770
+     * the last token.
771
+     *
772
+     * The deleted property is an array with nodenames, that have been deleted
773
+     * from collection.
774
+     *
775
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
776
+     * 1, you only have to report changes that happened only directly in
777
+     * immediate descendants. If it's 2, it should also include changes from
778
+     * the nodes below the child collections. (grandchildren)
779
+     *
780
+     * The $limit argument allows a client to specify how many results should
781
+     * be returned at most. If the limit is not specified, it should be treated
782
+     * as infinite.
783
+     *
784
+     * If the limit (infinite or not) is higher than you're willing to return,
785
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
786
+     *
787
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
788
+     * return null.
789
+     *
790
+     * The limit is 'suggestive'. You are free to ignore it.
791
+     *
792
+     * @param string $addressBookId
793
+     * @param string $syncToken
794
+     * @param int $syncLevel
795
+     * @param int $limit
796
+     * @return array
797
+     */
798
+    function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
799
+        // Current synctoken
800
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
801
+        $stmt->execute([ $addressBookId ]);
802
+        $currentToken = $stmt->fetchColumn(0);
803
+
804
+        if (is_null($currentToken)) return null;
805
+
806
+        $result = [
807
+            'syncToken' => $currentToken,
808
+            'added'     => [],
809
+            'modified'  => [],
810
+            'deleted'   => [],
811
+        ];
812
+
813
+        if ($syncToken) {
814
+
815
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
816
+            if ($limit>0) {
817
+                $query .= " LIMIT " . (int)$limit;
818
+            }
819
+
820
+            // Fetching all changes
821
+            $stmt = $this->db->prepare($query);
822
+            $stmt->execute([$syncToken, $currentToken, $addressBookId]);
823
+
824
+            $changes = [];
825
+
826
+            // This loop ensures that any duplicates are overwritten, only the
827
+            // last change on a node is relevant.
828
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
829
+
830
+                $changes[$row['uri']] = $row['operation'];
831
+
832
+            }
833
+
834
+            foreach($changes as $uri => $operation) {
835
+
836
+                switch($operation) {
837
+                    case 1:
838
+                        $result['added'][] = $uri;
839
+                        break;
840
+                    case 2:
841
+                        $result['modified'][] = $uri;
842
+                        break;
843
+                    case 3:
844
+                        $result['deleted'][] = $uri;
845
+                        break;
846
+                }
847
+
848
+            }
849
+        } else {
850
+            // No synctoken supplied, this is the initial sync.
851
+            $query = "SELECT `uri` FROM `*PREFIX*cards` WHERE `addressbookid` = ?";
852
+            $stmt = $this->db->prepare($query);
853
+            $stmt->execute([$addressBookId]);
854
+
855
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
856
+        }
857
+        return $result;
858
+    }
859
+
860
+    /**
861
+     * Adds a change record to the addressbookchanges table.
862
+     *
863
+     * @param mixed $addressBookId
864
+     * @param string $objectUri
865
+     * @param int $operation 1 = add, 2 = modify, 3 = delete
866
+     * @return void
867
+     */
868
+    protected function addChange($addressBookId, $objectUri, $operation) {
869
+        $sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?';
870
+        $stmt = $this->db->prepare($sql);
871
+        $stmt->execute([
872
+            $objectUri,
873
+            $addressBookId,
874
+            $operation,
875
+            $addressBookId
876
+        ]);
877
+        $stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
878
+        $stmt->execute([
879
+            $addressBookId
880
+        ]);
881
+    }
882
+
883
+    private function readBlob($cardData) {
884
+        if (is_resource($cardData)) {
885
+            return stream_get_contents($cardData);
886
+        }
887
+
888
+        return $cardData;
889
+    }
890
+
891
+    /**
892
+     * @param IShareable $shareable
893
+     * @param string[] $add
894
+     * @param string[] $remove
895
+     */
896
+    public function updateShares(IShareable $shareable, $add, $remove) {
897
+        $this->sharingBackend->updateShares($shareable, $add, $remove);
898
+    }
899
+
900
+    /**
901
+     * search contact
902
+     *
903
+     * @param int $addressBookId
904
+     * @param string $pattern which should match within the $searchProperties
905
+     * @param array $searchProperties defines the properties within the query pattern should match
906
+     * @param array $options = array() to define the search behavior
907
+     * 	- 'escape_like_param' - If set to false wildcards _ and % are not escaped, otherwise they are
908
+     * @return array an array of contacts which are arrays of key-value-pairs
909
+     */
910
+    public function search($addressBookId, $pattern, $searchProperties, $options = array()) {
911
+        $query = $this->db->getQueryBuilder();
912
+        $query2 = $this->db->getQueryBuilder();
913
+
914
+        $query2->selectDistinct('cp.cardid')->from($this->dbCardsPropertiesTable, 'cp');
915
+        $query2->andWhere($query2->expr()->eq('cp.addressbookid', $query->createNamedParameter($addressBookId)));
916
+        $or = $query2->expr()->orX();
917
+        foreach ($searchProperties as $property) {
918
+            $or->add($query2->expr()->eq('cp.name', $query->createNamedParameter($property)));
919
+        }
920
+        $query2->andWhere($or);
921
+
922
+        // No need for like when the pattern is empty
923
+        if ('' !== $pattern) {
924
+            if(\array_key_exists('escape_like_param', $options) && $options['escape_like_param'] === false) {
925
+                $query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter($pattern)));
926
+            } else {
927
+                $query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
928
+            }
929
+        }
930
+
931
+        $query->select('c.carddata', 'c.uri')->from($this->dbCardsTable, 'c')
932
+            ->where($query->expr()->in('c.id', $query->createFunction($query2->getSQL())));
933
+
934
+        $result = $query->execute();
935
+        $cards = $result->fetchAll();
936
+
937
+        $result->closeCursor();
938
+
939
+        return array_map(function($array) {
940
+            $array['carddata'] = $this->readBlob($array['carddata']);
941
+            return $array;
942
+        }, $cards);
943
+    }
944
+
945
+    /**
946
+     * @param int $bookId
947
+     * @param string $name
948
+     * @return array
949
+     */
950
+    public function collectCardProperties($bookId, $name) {
951
+        $query = $this->db->getQueryBuilder();
952
+        $result = $query->selectDistinct('value')
953
+            ->from($this->dbCardsPropertiesTable)
954
+            ->where($query->expr()->eq('name', $query->createNamedParameter($name)))
955
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
956
+            ->execute();
957
+
958
+        $all = $result->fetchAll(PDO::FETCH_COLUMN);
959
+        $result->closeCursor();
960
+
961
+        return $all;
962
+    }
963
+
964
+    /**
965
+     * get URI from a given contact
966
+     *
967
+     * @param int $id
968
+     * @return string
969
+     */
970
+    public function getCardUri($id) {
971
+        $query = $this->db->getQueryBuilder();
972
+        $query->select('uri')->from($this->dbCardsTable)
973
+                ->where($query->expr()->eq('id', $query->createParameter('id')))
974
+                ->setParameter('id', $id);
975
+
976
+        $result = $query->execute();
977
+        $uri = $result->fetch();
978
+        $result->closeCursor();
979
+
980
+        if (!isset($uri['uri'])) {
981
+            throw new \InvalidArgumentException('Card does not exists: ' . $id);
982
+        }
983
+
984
+        return $uri['uri'];
985
+    }
986
+
987
+    /**
988
+     * return contact with the given URI
989
+     *
990
+     * @param int $addressBookId
991
+     * @param string $uri
992
+     * @returns array
993
+     */
994
+    public function getContact($addressBookId, $uri) {
995
+        $result = [];
996
+        $query = $this->db->getQueryBuilder();
997
+        $query->select('*')->from($this->dbCardsTable)
998
+                ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
999
+                ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1000
+        $queryResult = $query->execute();
1001
+        $contact = $queryResult->fetch();
1002
+        $queryResult->closeCursor();
1003
+
1004
+        if (is_array($contact)) {
1005
+            $result = $contact;
1006
+        }
1007
+
1008
+        return $result;
1009
+    }
1010
+
1011
+    /**
1012
+     * Returns the list of people whom this address book is shared with.
1013
+     *
1014
+     * Every element in this array should have the following properties:
1015
+     *   * href - Often a mailto: address
1016
+     *   * commonName - Optional, for example a first + last name
1017
+     *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
1018
+     *   * readOnly - boolean
1019
+     *   * summary - Optional, a description for the share
1020
+     *
1021
+     * @return array
1022
+     */
1023
+    public function getShares($addressBookId) {
1024
+        return $this->sharingBackend->getShares($addressBookId);
1025
+    }
1026
+
1027
+    /**
1028
+     * update properties table
1029
+     *
1030
+     * @param int $addressBookId
1031
+     * @param string $cardUri
1032
+     * @param string $vCardSerialized
1033
+     */
1034
+    protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
1035
+        $cardId = $this->getCardId($addressBookId, $cardUri);
1036
+        $vCard = $this->readCard($vCardSerialized);
1037
+
1038
+        $this->purgeProperties($addressBookId, $cardId);
1039
+
1040
+        $query = $this->db->getQueryBuilder();
1041
+        $query->insert($this->dbCardsPropertiesTable)
1042
+            ->values(
1043
+                [
1044
+                    'addressbookid' => $query->createNamedParameter($addressBookId),
1045
+                    'cardid' => $query->createNamedParameter($cardId),
1046
+                    'name' => $query->createParameter('name'),
1047
+                    'value' => $query->createParameter('value'),
1048
+                    'preferred' => $query->createParameter('preferred')
1049
+                ]
1050
+            );
1051
+
1052
+        foreach ($vCard->children() as $property) {
1053
+            if(!in_array($property->name, self::$indexProperties)) {
1054
+                continue;
1055
+            }
1056
+            $preferred = 0;
1057
+            foreach($property->parameters as $parameter) {
1058
+                if ($parameter->name === 'TYPE' && strtoupper($parameter->getValue()) === 'PREF') {
1059
+                    $preferred = 1;
1060
+                    break;
1061
+                }
1062
+            }
1063
+            $query->setParameter('name', $property->name);
1064
+            $query->setParameter('value', substr($property->getValue(), 0, 254));
1065
+            $query->setParameter('preferred', $preferred);
1066
+            $query->execute();
1067
+        }
1068
+    }
1069
+
1070
+    /**
1071
+     * read vCard data into a vCard object
1072
+     *
1073
+     * @param string $cardData
1074
+     * @return VCard
1075
+     */
1076
+    protected function readCard($cardData) {
1077
+        return  Reader::read($cardData);
1078
+    }
1079
+
1080
+    /**
1081
+     * delete all properties from a given card
1082
+     *
1083
+     * @param int $addressBookId
1084
+     * @param int $cardId
1085
+     */
1086
+    protected function purgeProperties($addressBookId, $cardId) {
1087
+        $query = $this->db->getQueryBuilder();
1088
+        $query->delete($this->dbCardsPropertiesTable)
1089
+            ->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
1090
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1091
+        $query->execute();
1092
+    }
1093
+
1094
+    /**
1095
+     * get ID from a given contact
1096
+     *
1097
+     * @param int $addressBookId
1098
+     * @param string $uri
1099
+     * @return int
1100
+     */
1101
+    protected function getCardId($addressBookId, $uri) {
1102
+        $query = $this->db->getQueryBuilder();
1103
+        $query->select('id')->from($this->dbCardsTable)
1104
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1105
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1106
+
1107
+        $result = $query->execute();
1108
+        $cardIds = $result->fetch();
1109
+        $result->closeCursor();
1110
+
1111
+        if (!isset($cardIds['id'])) {
1112
+            throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1113
+        }
1114
+
1115
+        return (int)$cardIds['id'];
1116
+    }
1117
+
1118
+    /**
1119
+     * For shared address books the sharee is set in the ACL of the address book
1120
+     * @param $addressBookId
1121
+     * @param $acl
1122
+     * @return array
1123
+     */
1124
+    public function applyShareAcl($addressBookId, $acl) {
1125
+        return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1126
+    }
1127
+
1128
+    private function convertPrincipal($principalUri, $toV2) {
1129
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1130
+            list(, $name) = \Sabre\Uri\split($principalUri);
1131
+            if ($toV2 === true) {
1132
+                return "principals/users/$name";
1133
+            }
1134
+            return "principals/$name";
1135
+        }
1136
+        return $principalUri;
1137
+    }
1138
+
1139
+    private function addOwnerPrincipal(&$addressbookInfo) {
1140
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
1141
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
1142
+        if (isset($addressbookInfo[$ownerPrincipalKey])) {
1143
+            $uri = $addressbookInfo[$ownerPrincipalKey];
1144
+        } else {
1145
+            $uri = $addressbookInfo['principaluri'];
1146
+        }
1147
+
1148
+        $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
1149
+        if (isset($principalInformation['{DAV:}displayname'])) {
1150
+            $addressbookInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
1151
+        }
1152
+    }
1153
+
1154
+    /**
1155
+     * Extract UID from vcard
1156
+     *
1157
+     * @param string $cardData the vcard raw data
1158
+     * @return string the uid
1159
+     * @throws BadRequest if no UID is available
1160
+     */
1161
+    private function getUID($cardData) {
1162
+        if ($cardData != '') {
1163
+            $vCard = Reader::read($cardData);
1164
+            if ($vCard->UID) {
1165
+                $uid = $vCard->UID->getValue();
1166
+                return $uid;
1167
+            }
1168
+            // should already be handled, but just in case
1169
+            throw new BadRequest('vCards on CardDAV servers MUST have a UID property');
1170
+        }
1171
+        // should already be handled, but just in case
1172
+        throw new BadRequest('vCard can not be empty');
1173
+    }
1174 1174
 }
Please login to merge, or discard this patch.
Spacing   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -121,7 +121,7 @@  discard block
 block discarded – undo
121 121
 			->from('addressbooks')
122 122
 			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
123 123
 
124
-		return (int)$query->execute()->fetchColumn();
124
+		return (int) $query->execute()->fetchColumn();
125 125
 	}
126 126
 
127 127
 	/**
@@ -152,15 +152,15 @@  discard block
 block discarded – undo
152 152
 		$addressBooks = [];
153 153
 
154 154
 		$result = $query->execute();
155
-		while($row = $result->fetch()) {
155
+		while ($row = $result->fetch()) {
156 156
 			$addressBooks[$row['id']] = [
157 157
 				'id'  => $row['id'],
158 158
 				'uri' => $row['uri'],
159 159
 				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
160 160
 				'{DAV:}displayname' => $row['displayname'],
161
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
161
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
162 162
 				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
163
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
163
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
164 164
 			];
165 165
 
166 166
 			$this->addOwnerPrincipal($addressBooks[$row['id']]);
@@ -174,7 +174,7 @@  discard block
 block discarded – undo
174 174
 		$principals = array_map(function($principal) {
175 175
 			return urldecode($principal);
176 176
 		}, $principals);
177
-		$principals[]= $principalUri;
177
+		$principals[] = $principalUri;
178 178
 
179 179
 		$query = $this->db->getQueryBuilder();
180 180
 		$result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
@@ -186,8 +186,8 @@  discard block
 block discarded – undo
186 186
 			->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
187 187
 			->execute();
188 188
 
189
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
190
-		while($row = $result->fetch()) {
189
+		$readOnlyPropertyName = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only';
190
+		while ($row = $result->fetch()) {
191 191
 			if ($row['principaluri'] === $principalUri) {
192 192
 				continue;
193 193
 			}
@@ -206,18 +206,18 @@  discard block
 block discarded – undo
206 206
 			}
207 207
 
208 208
 			list(, $name) = \Sabre\Uri\split($row['principaluri']);
209
-			$uri = $row['uri'] . '_shared_by_' . $name;
210
-			$displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
209
+			$uri = $row['uri'].'_shared_by_'.$name;
210
+			$displayName = $row['displayname'].' ('.$this->getUserDisplayName($name).')';
211 211
 
212 212
 			$addressBooks[$row['id']] = [
213 213
 				'id'  => $row['id'],
214 214
 				'uri' => $uri,
215 215
 				'principaluri' => $principalUriOriginal,
216 216
 				'{DAV:}displayname' => $displayName,
217
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
217
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
218 218
 				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
219
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
220
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
219
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
220
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $row['principaluri'],
221 221
 				$readOnlyPropertyName => $readOnly,
222 222
 			];
223 223
 
@@ -238,15 +238,15 @@  discard block
 block discarded – undo
238 238
 		$addressBooks = [];
239 239
 
240 240
 		$result = $query->execute();
241
-		while($row = $result->fetch()) {
241
+		while ($row = $result->fetch()) {
242 242
 			$addressBooks[$row['id']] = [
243 243
 				'id'  => $row['id'],
244 244
 				'uri' => $row['uri'],
245 245
 				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
246 246
 				'{DAV:}displayname' => $row['displayname'],
247
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
247
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
248 248
 				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
249
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
249
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
250 250
 			];
251 251
 
252 252
 			$this->addOwnerPrincipal($addressBooks[$row['id']]);
@@ -291,9 +291,9 @@  discard block
 block discarded – undo
291 291
 			'uri' => $row['uri'],
292 292
 			'principaluri' => $row['principaluri'],
293 293
 			'{DAV:}displayname' => $row['displayname'],
294
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
294
+			'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
295 295
 			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
296
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
296
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
297 297
 		];
298 298
 
299 299
 		$this->addOwnerPrincipal($addressBook);
@@ -325,9 +325,9 @@  discard block
 block discarded – undo
325 325
 			'uri' => $row['uri'],
326 326
 			'principaluri' => $row['principaluri'],
327 327
 			'{DAV:}displayname' => $row['displayname'],
328
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
328
+			'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
329 329
 			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
330
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
330
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
331 331
 		];
332 332
 
333 333
 		$this->addOwnerPrincipal($addressBook);
@@ -354,7 +354,7 @@  discard block
 block discarded – undo
354 354
 	function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
355 355
 		$supportedProperties = [
356 356
 			'{DAV:}displayname',
357
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description',
357
+			'{'.Plugin::NS_CARDDAV.'}addressbook-description',
358 358
 		];
359 359
 
360 360
 		/**
@@ -363,13 +363,13 @@  discard block
 block discarded – undo
363 363
 		$propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
364 364
 
365 365
 			$updates = [];
366
-			foreach($mutations as $property=>$newValue) {
366
+			foreach ($mutations as $property=>$newValue) {
367 367
 
368
-				switch($property) {
368
+				switch ($property) {
369 369
 					case '{DAV:}displayname' :
370 370
 						$updates['displayname'] = $newValue;
371 371
 						break;
372
-					case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
372
+					case '{'.Plugin::NS_CARDDAV.'}addressbook-description' :
373 373
 						$updates['description'] = $newValue;
374 374
 						break;
375 375
 				}
@@ -377,7 +377,7 @@  discard block
 block discarded – undo
377 377
 			$query = $this->db->getQueryBuilder();
378 378
 			$query->update('addressbooks');
379 379
 
380
-			foreach($updates as $key=>$value) {
380
+			foreach ($updates as $key=>$value) {
381 381
 				$query->set($key, $query->createNamedParameter($value));
382 382
 			}
383 383
 			$query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
@@ -408,24 +408,24 @@  discard block
 block discarded – undo
408 408
 			'synctoken' => 1
409 409
 		];
410 410
 
411
-		foreach($properties as $property=>$newValue) {
411
+		foreach ($properties as $property=>$newValue) {
412 412
 
413
-			switch($property) {
413
+			switch ($property) {
414 414
 				case '{DAV:}displayname' :
415 415
 					$values['displayname'] = $newValue;
416 416
 					break;
417
-				case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
417
+				case '{'.Plugin::NS_CARDDAV.'}addressbook-description' :
418 418
 					$values['description'] = $newValue;
419 419
 					break;
420 420
 				default :
421
-					throw new BadRequest('Unknown property: ' . $property);
421
+					throw new BadRequest('Unknown property: '.$property);
422 422
 			}
423 423
 
424 424
 		}
425 425
 
426 426
 		// Fallback to make sure the displayname is set. Some clients may refuse
427 427
 		// to work with addressbooks not having a displayname.
428
-		if(is_null($values['displayname'])) {
428
+		if (is_null($values['displayname'])) {
429 429
 			$values['displayname'] = $url;
430 430
 		}
431 431
 
@@ -503,8 +503,8 @@  discard block
 block discarded – undo
503 503
 		$cards = [];
504 504
 
505 505
 		$result = $query->execute();
506
-		while($row = $result->fetch()) {
507
-			$row['etag'] = '"' . $row['etag'] . '"';
506
+		while ($row = $result->fetch()) {
507
+			$row['etag'] = '"'.$row['etag'].'"';
508 508
 			$row['carddata'] = $this->readBlob($row['carddata']);
509 509
 			$cards[] = $row;
510 510
 		}
@@ -538,7 +538,7 @@  discard block
 block discarded – undo
538 538
 		if (!$row) {
539 539
 			return false;
540 540
 		}
541
-		$row['etag'] = '"' . $row['etag'] . '"';
541
+		$row['etag'] = '"'.$row['etag'].'"';
542 542
 		$row['carddata'] = $this->readBlob($row['carddata']);
543 543
 
544 544
 		return $row;
@@ -575,7 +575,7 @@  discard block
 block discarded – undo
575 575
 			$result = $query->execute();
576 576
 
577 577
 			while ($row = $result->fetch()) {
578
-				$row['etag'] = '"' . $row['etag'] . '"';
578
+				$row['etag'] = '"'.$row['etag'].'"';
579 579
 				$row['carddata'] = $this->readBlob($row['carddata']);
580 580
 				$cards[] = $row;
581 581
 			}
@@ -648,7 +648,7 @@  discard block
 block discarded – undo
648 648
 				'cardUri' => $cardUri,
649 649
 				'cardData' => $cardData]));
650 650
 
651
-		return '"' . $etag . '"';
651
+		return '"'.$etag.'"';
652 652
 	}
653 653
 
654 654
 	/**
@@ -700,7 +700,7 @@  discard block
 block discarded – undo
700 700
 				'cardUri' => $cardUri,
701 701
 				'cardData' => $cardData]));
702 702
 
703
-		return '"' . $etag . '"';
703
+		return '"'.$etag.'"';
704 704
 	}
705 705
 
706 706
 	/**
@@ -798,7 +798,7 @@  discard block
 block discarded – undo
798 798
 	function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
799 799
 		// Current synctoken
800 800
 		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
801
-		$stmt->execute([ $addressBookId ]);
801
+		$stmt->execute([$addressBookId]);
802 802
 		$currentToken = $stmt->fetchColumn(0);
803 803
 
804 804
 		if (is_null($currentToken)) return null;
@@ -813,8 +813,8 @@  discard block
 block discarded – undo
813 813
 		if ($syncToken) {
814 814
 
815 815
 			$query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
816
-			if ($limit>0) {
817
-				$query .= " LIMIT " . (int)$limit;
816
+			if ($limit > 0) {
817
+				$query .= " LIMIT ".(int) $limit;
818 818
 			}
819 819
 
820 820
 			// Fetching all changes
@@ -825,15 +825,15 @@  discard block
 block discarded – undo
825 825
 
826 826
 			// This loop ensures that any duplicates are overwritten, only the
827 827
 			// last change on a node is relevant.
828
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
828
+			while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
829 829
 
830 830
 				$changes[$row['uri']] = $row['operation'];
831 831
 
832 832
 			}
833 833
 
834
-			foreach($changes as $uri => $operation) {
834
+			foreach ($changes as $uri => $operation) {
835 835
 
836
-				switch($operation) {
836
+				switch ($operation) {
837 837
 					case 1:
838 838
 						$result['added'][] = $uri;
839 839
 						break;
@@ -921,10 +921,10 @@  discard block
 block discarded – undo
921 921
 
922 922
 		// No need for like when the pattern is empty
923 923
 		if ('' !== $pattern) {
924
-			if(\array_key_exists('escape_like_param', $options) && $options['escape_like_param'] === false) {
924
+			if (\array_key_exists('escape_like_param', $options) && $options['escape_like_param'] === false) {
925 925
 				$query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter($pattern)));
926 926
 			} else {
927
-				$query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
927
+				$query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter('%'.$this->db->escapeLikeParameter($pattern).'%')));
928 928
 			}
929 929
 		}
930 930
 
@@ -978,7 +978,7 @@  discard block
 block discarded – undo
978 978
 		$result->closeCursor();
979 979
 
980 980
 		if (!isset($uri['uri'])) {
981
-			throw new \InvalidArgumentException('Card does not exists: ' . $id);
981
+			throw new \InvalidArgumentException('Card does not exists: '.$id);
982 982
 		}
983 983
 
984 984
 		return $uri['uri'];
@@ -1050,11 +1050,11 @@  discard block
 block discarded – undo
1050 1050
 			);
1051 1051
 
1052 1052
 		foreach ($vCard->children() as $property) {
1053
-			if(!in_array($property->name, self::$indexProperties)) {
1053
+			if (!in_array($property->name, self::$indexProperties)) {
1054 1054
 				continue;
1055 1055
 			}
1056 1056
 			$preferred = 0;
1057
-			foreach($property->parameters as $parameter) {
1057
+			foreach ($property->parameters as $parameter) {
1058 1058
 				if ($parameter->name === 'TYPE' && strtoupper($parameter->getValue()) === 'PREF') {
1059 1059
 					$preferred = 1;
1060 1060
 					break;
@@ -1109,10 +1109,10 @@  discard block
 block discarded – undo
1109 1109
 		$result->closeCursor();
1110 1110
 
1111 1111
 		if (!isset($cardIds['id'])) {
1112
-			throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1112
+			throw new \InvalidArgumentException('Card does not exists: '.$uri);
1113 1113
 		}
1114 1114
 
1115
-		return (int)$cardIds['id'];
1115
+		return (int) $cardIds['id'];
1116 1116
 	}
1117 1117
 
1118 1118
 	/**
@@ -1137,8 +1137,8 @@  discard block
 block discarded – undo
1137 1137
 	}
1138 1138
 
1139 1139
 	private function addOwnerPrincipal(&$addressbookInfo) {
1140
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
1141
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
1140
+		$ownerPrincipalKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal';
1141
+		$displaynameKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}owner-displayname';
1142 1142
 		if (isset($addressbookInfo[$ownerPrincipalKey])) {
1143 1143
 			$uri = $addressbookInfo[$ownerPrincipalKey];
1144 1144
 		} else {
Please login to merge, or discard this patch.