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