Passed
Push — master ( 514185...41ff00 )
by Roeland
28:32 queued 13:41
created

AddressBookImpl   A

Complexity

Total Complexity 36

Size/Duplication

Total Lines 275
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 103
dl 0
loc 275
rs 9.52
c 0
b 0
f 0
wmc 36

13 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 1
A getKey() 0 2 1
A getDisplayName() 0 2 1
A readCard() 0 2 1
A getTypeFromProperty() 0 10 2
A delete() 0 3 1
A createUid() 0 7 2
C vCard2Array() 0 60 13
A getPermissions() 0 19 5
A getUid() 0 2 1
A search() 0 11 3
A createOrUpdate() 0 24 4
A createEmptyVCard() 0 4 1
1
<?php
2
/**
3
 * @copyright Copyright (c) 2016, ownCloud, Inc.
4
 *
5
 * @author Björn Schießle <[email protected]>
6
 * @author Georg Ehrke <[email protected]>
7
 * @author Joas Schilling <[email protected]>
8
 * @author Thomas Müller <[email protected]>
9
 *
10
 * @license AGPL-3.0
11
 *
12
 * This code is free software: you can redistribute it and/or modify
13
 * it under the terms of the GNU Affero General Public License, version 3,
14
 * as published by the Free Software Foundation.
15
 *
16
 * This program is distributed in the hope that it will be useful,
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19
 * GNU Affero General Public License for more details.
20
 *
21
 * You should have received a copy of the GNU Affero General Public License, version 3,
22
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
23
 *
24
 */
25
26
namespace OCA\DAV\CardDAV;
27
28
use OCP\Constants;
29
use OCP\IAddressBook;
30
use OCP\IURLGenerator;
31
use Sabre\VObject\Component\VCard;
32
use Sabre\VObject\Property;
33
use Sabre\VObject\Reader;
34
use Sabre\VObject\UUIDUtil;
35
36
class AddressBookImpl implements IAddressBook {
37
38
	/** @var CardDavBackend */
39
	private $backend;
40
41
	/** @var array */
42
	private $addressBookInfo;
43
44
	/** @var AddressBook */
45
	private $addressBook;
46
47
	/** @var IURLGenerator */
48
	private $urlGenerator;
49
50
	/**
51
	 * AddressBookImpl constructor.
52
	 *
53
	 * @param AddressBook $addressBook
54
	 * @param array $addressBookInfo
55
	 * @param CardDavBackend $backend
56
	 * @param IUrlGenerator $urlGenerator
57
	 */
58
	public function __construct(
59
			AddressBook $addressBook,
60
			array $addressBookInfo,
61
			CardDavBackend $backend,
62
			IURLGenerator $urlGenerator) {
63
64
		$this->addressBook = $addressBook;
65
		$this->addressBookInfo = $addressBookInfo;
66
		$this->backend = $backend;
67
		$this->urlGenerator = $urlGenerator;
68
	}
69
70
	/**
71
	 * @return string defining the technical unique key
72
	 * @since 5.0.0
73
	 */
74
	public function getKey() {
75
		return $this->addressBookInfo['id'];
76
	}
77
78
	/**
79
	 * In comparison to getKey() this function returns a human readable (maybe translated) name
80
	 *
81
	 * @return mixed
82
	 * @since 5.0.0
83
	 */
84
	public function getDisplayName() {
85
		return $this->addressBookInfo['{DAV:}displayname'];
86
	}
87
88
	/**
89
	 * @param string $pattern which should match within the $searchProperties
90
	 * @param array $searchProperties defines the properties within the query pattern should match
91
	 * @param array $options Options to define the output format
92
	 * 	- types boolean (since 15.0.0) If set to true, fields that come with a TYPE property will be an array
93
	 *    example: ['id' => 5, 'FN' => 'Thomas Tanghus', 'EMAIL' => ['type => 'HOME', 'value' => '[email protected]']]
94
	 * @return array an array of contacts which are arrays of key-value-pairs
95
	 *  example result:
96
	 *  [
97
	 *		['id' => 0, 'FN' => 'Thomas Müller', 'EMAIL' => '[email protected]', 'GEO' => '37.386013;-122.082932'],
98
	 *		['id' => 5, 'FN' => 'Thomas Tanghus', 'EMAIL' => ['[email protected]', '[email protected]']]
99
	 *	]
100
	 * @return array an array of contacts which are arrays of key-value-pairs
101
	 * @since 5.0.0
102
	 */
103
	public function search($pattern, $searchProperties, $options) {
104
		$results = $this->backend->search($this->getKey(), $pattern, $searchProperties);
0 ignored issues
show
Bug introduced by
$this->getKey() of type string is incompatible with the type integer expected by parameter $addressBookId of OCA\DAV\CardDAV\CardDavBackend::search(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

104
		$results = $this->backend->search(/** @scrutinizer ignore-type */ $this->getKey(), $pattern, $searchProperties);
Loading history...
105
106
		$withTypes = \array_key_exists('types', $options) && $options['types'] === true;
107
108
		$vCards = [];
109
		foreach ($results as $result) {
110
			$vCards[] = $this->vCard2Array($result['uri'], $this->readCard($result['carddata']), $withTypes);
111
		}
112
113
		return $vCards;
114
	}
115
116
	/**
117
	 * @param array $properties this array if key-value-pairs defines a contact
118
	 * @return array an array representing the contact just created or updated
119
	 * @since 5.0.0
120
	 */
121
	public function createOrUpdate($properties) {
122
		$update = false;
123
		if (!isset($properties['URI'])) { // create a new contact
124
			$uid = $this->createUid();
125
			$uri = $uid . '.vcf';
126
			$vCard = $this->createEmptyVCard($uid);
127
		} else { // update existing contact
128
			$uri = $properties['URI'];
129
			$vCardData = $this->backend->getCard($this->getKey(), $uri);
130
			$vCard = $this->readCard($vCardData['carddata']);
131
			$update = true;
132
		}
133
134
		foreach ($properties as $key => $value) {
135
			$vCard->$key = $vCard->createProperty($key, $value);
136
		}
137
138
		if ($update) {
139
			$this->backend->updateCard($this->getKey(), $uri, $vCard->serialize());
140
		} else {
141
			$this->backend->createCard($this->getKey(), $uri, $vCard->serialize());
142
		}
143
144
		return $this->vCard2Array($uri, $vCard);
145
146
	}
147
148
	/**
149
	 * @return mixed
150
	 * @since 5.0.0
151
	 */
152
	public function getPermissions() {
153
		$permissions = $this->addressBook->getACL();
154
		$result = 0;
155
		foreach ($permissions as $permission) {
156
			switch($permission['privilege']) {
157
				case '{DAV:}read':
158
					$result |= Constants::PERMISSION_READ;
159
					break;
160
				case '{DAV:}write':
161
					$result |= Constants::PERMISSION_CREATE;
162
					$result |= Constants::PERMISSION_UPDATE;
163
					break;
164
				case '{DAV:}all':
165
					$result |= Constants::PERMISSION_ALL;
166
					break;
167
			}
168
		}
169
170
		return $result;
171
	}
172
173
	/**
174
	 * @param object $id the unique identifier to a contact
175
	 * @return bool successful or not
176
	 * @since 5.0.0
177
	 */
178
	public function delete($id) {
179
		$uri = $this->backend->getCardUri($id);
0 ignored issues
show
Bug introduced by
$id of type object is incompatible with the type integer expected by parameter $id of OCA\DAV\CardDAV\CardDavBackend::getCardUri(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

179
		$uri = $this->backend->getCardUri(/** @scrutinizer ignore-type */ $id);
Loading history...
180
		return $this->backend->deleteCard($this->addressBookInfo['id'], $uri);
181
	}
182
183
	/**
184
	 * read vCard data into a vCard object
185
	 *
186
	 * @param string $cardData
187
	 * @return VCard
188
	 */
189
	protected function readCard($cardData) {
190
		return  Reader::read($cardData);
191
	}
192
193
	/**
194
	 * create UID for contact
195
	 *
196
	 * @return string
197
	 */
198
	protected function createUid() {
199
		do {
200
			$uid = $this->getUid();
201
			$contact = $this->backend->getContact($this->getKey(), $uid . '.vcf');
0 ignored issues
show
Bug introduced by
$this->getKey() of type string is incompatible with the type integer expected by parameter $addressBookId of OCA\DAV\CardDAV\CardDavBackend::getContact(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

201
			$contact = $this->backend->getContact(/** @scrutinizer ignore-type */ $this->getKey(), $uid . '.vcf');
Loading history...
202
		} while (!empty($contact));
203
204
		return $uid;
205
	}
206
207
	/**
208
	 * getUid is only there for testing, use createUid instead
209
	 */
210
	protected function getUid() {
211
		return UUIDUtil::getUUID();
212
	}
213
214
	/**
215
	 * create empty vcard
216
	 *
217
	 * @param string $uid
218
	 * @return VCard
219
	 */
220
	protected function createEmptyVCard($uid) {
221
		$vCard = new VCard();
222
		$vCard->UID = $uid;
0 ignored issues
show
Bug Best Practice introduced by
The property UID does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
223
		return $vCard;
224
	}
225
226
	/**
227
	 * create array with all vCard properties
228
	 *
229
	 * @param string $uri
230
	 * @param VCard $vCard
231
	 * @return array
232
	 */
233
	protected function vCard2Array($uri, VCard $vCard, $withTypes = false) {
234
		$result = [
235
			'URI' => $uri,
236
		];
237
238
		foreach ($vCard->children() as $property) {
239
			if ($property->name === 'PHOTO' && $property->getValueType() === 'BINARY') {
240
				$url = $this->urlGenerator->getAbsoluteURL(
241
					$this->urlGenerator->linkTo('', 'remote.php') . '/dav/');
242
				$url .= implode('/', [
243
					'addressbooks',
244
					substr($this->addressBookInfo['principaluri'], 11), //cut off 'principals/'
245
					$this->addressBookInfo['uri'],
246
					$uri
247
				]) . '?photo';
248
249
				$result['PHOTO'] = 'VALUE=uri:' . $url;
250
251
			} else if ($property->name === 'X-SOCIALPROFILE') {
252
				$type = $this->getTypeFromProperty($property);
253
254
				// Type is the social network, when it's empty we don't need this.
255
				if ($type !== null) {
256
					if (!isset($result[$property->name])) {
257
						$result[$property->name] = [];
258
					}
259
					$result[$property->name][$type] = $property->getValue();
260
				}
261
262
			// The following properties can be set multiple times
263
			} else if (in_array($property->name, ['CLOUD', 'EMAIL', 'IMPP', 'TEL', 'URL'])) {
264
				if (!isset($result[$property->name])) {
265
					$result[$property->name] = [];
266
				}
267
268
				$type = $this->getTypeFromProperty($property);
269
				if ($withTypes) {
270
					$result[$property->name][] = [
271
						'type' => $type,
272
						'value' => $property->getValue()
273
						];
274
				} else {
275
					$result[$property->name][] = $property->getValue();
276
				}
277
278
279
			} else {
280
				$result[$property->name] = $property->getValue();
281
			}
282
		}
283
284
		if (
285
			$this->addressBookInfo['principaluri'] === 'principals/system/system' && (
286
				$this->addressBookInfo['uri'] === 'system' ||
287
				$this->addressBookInfo['{DAV:}displayname'] === $this->urlGenerator->getBaseUrl()
288
			)
289
		) {
290
			$result['isLocalSystemBook'] = true;
291
		}
292
		return $result;
293
	}
294
295
	/**
296
	 * Get the type of the current property
297
	 *
298
	 * @param Property $property
299
	 * @return null|string
300
	 */
301
	protected function getTypeFromProperty(Property $property) {
302
		$parameters = $property->parameters();
303
		// Type is the social network, when it's empty we don't need this.
304
		if (isset($parameters['TYPE'])) {
305
			/** @var \Sabre\VObject\Parameter $type */
306
			$type = $parameters['TYPE'];
307
			return $type->getValue();
308
		}
309
310
		return null;
311
	}
312
}
313