Completed
Push — master ( f38d36...9039b7 )
by Lukas
21:28 queued 09:01
created
lib/private/Files/Storage/Storage.php 2 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -100,6 +100,7 @@  discard block
 block discarded – undo
100 100
 	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
101 101
 	 * @param \OCP\Lock\ILockingProvider $provider
102 102
 	 * @throws \OCP\Lock\LockedException
103
+	 * @return void
103 104
 	 */
104 105
 	public function acquireLock($path, $type, ILockingProvider $provider);
105 106
 
@@ -108,6 +109,7 @@  discard block
 block discarded – undo
108 109
 	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
109 110
 	 * @param \OCP\Lock\ILockingProvider $provider
110 111
 	 * @throws \OCP\Lock\LockedException
112
+	 * @return void
111 113
 	 */
112 114
 	public function releaseLock($path, $type, ILockingProvider $provider);
113 115
 
@@ -116,6 +118,7 @@  discard block
 block discarded – undo
116 118
 	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
117 119
 	 * @param \OCP\Lock\ILockingProvider $provider
118 120
 	 * @throws \OCP\Lock\LockedException
121
+	 * @return void
119 122
 	 */
120 123
 	public function changeLock($path, $type, ILockingProvider $provider);
121 124
 }
Please login to merge, or discard this patch.
Indentation   +75 added lines, -75 removed lines patch added patch discarded remove patch
@@ -32,90 +32,90 @@
 block discarded – undo
32 32
  */
33 33
 interface Storage extends \OCP\Files\Storage {
34 34
 
35
-	/**
36
-	 * get a cache instance for the storage
37
-	 *
38
-	 * @param string $path
39
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the cache
40
-	 * @return \OC\Files\Cache\Cache
41
-	 */
42
-	public function getCache($path = '', $storage = null);
35
+    /**
36
+     * get a cache instance for the storage
37
+     *
38
+     * @param string $path
39
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the cache
40
+     * @return \OC\Files\Cache\Cache
41
+     */
42
+    public function getCache($path = '', $storage = null);
43 43
 
44
-	/**
45
-	 * get a scanner instance for the storage
46
-	 *
47
-	 * @param string $path
48
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the scanner
49
-	 * @return \OC\Files\Cache\Scanner
50
-	 */
51
-	public function getScanner($path = '', $storage = null);
44
+    /**
45
+     * get a scanner instance for the storage
46
+     *
47
+     * @param string $path
48
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the scanner
49
+     * @return \OC\Files\Cache\Scanner
50
+     */
51
+    public function getScanner($path = '', $storage = null);
52 52
 
53 53
 
54
-	/**
55
-	 * get the user id of the owner of a file or folder
56
-	 *
57
-	 * @param string $path
58
-	 * @return string
59
-	 */
60
-	public function getOwner($path);
54
+    /**
55
+     * get the user id of the owner of a file or folder
56
+     *
57
+     * @param string $path
58
+     * @return string
59
+     */
60
+    public function getOwner($path);
61 61
 
62
-	/**
63
-	 * get a watcher instance for the cache
64
-	 *
65
-	 * @param string $path
66
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
67
-	 * @return \OC\Files\Cache\Watcher
68
-	 */
69
-	public function getWatcher($path = '', $storage = null);
62
+    /**
63
+     * get a watcher instance for the cache
64
+     *
65
+     * @param string $path
66
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
67
+     * @return \OC\Files\Cache\Watcher
68
+     */
69
+    public function getWatcher($path = '', $storage = null);
70 70
 
71
-	/**
72
-	 * get a propagator instance for the cache
73
-	 *
74
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
75
-	 * @return \OC\Files\Cache\Propagator
76
-	 */
77
-	public function getPropagator($storage = null);
71
+    /**
72
+     * get a propagator instance for the cache
73
+     *
74
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
75
+     * @return \OC\Files\Cache\Propagator
76
+     */
77
+    public function getPropagator($storage = null);
78 78
 
79
-	/**
80
-	 * get a updater instance for the cache
81
-	 *
82
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
83
-	 * @return \OC\Files\Cache\Updater
84
-	 */
85
-	public function getUpdater($storage = null);
79
+    /**
80
+     * get a updater instance for the cache
81
+     *
82
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
83
+     * @return \OC\Files\Cache\Updater
84
+     */
85
+    public function getUpdater($storage = null);
86 86
 
87
-	/**
88
-	 * @return \OC\Files\Cache\Storage
89
-	 */
90
-	public function getStorageCache();
87
+    /**
88
+     * @return \OC\Files\Cache\Storage
89
+     */
90
+    public function getStorageCache();
91 91
 
92
-	/**
93
-	 * @param string $path
94
-	 * @return array
95
-	 */
96
-	public function getMetaData($path);
92
+    /**
93
+     * @param string $path
94
+     * @return array
95
+     */
96
+    public function getMetaData($path);
97 97
 
98
-	/**
99
-	 * @param string $path The path of the file to acquire the lock for
100
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
101
-	 * @param \OCP\Lock\ILockingProvider $provider
102
-	 * @throws \OCP\Lock\LockedException
103
-	 */
104
-	public function acquireLock($path, $type, ILockingProvider $provider);
98
+    /**
99
+     * @param string $path The path of the file to acquire the lock for
100
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
101
+     * @param \OCP\Lock\ILockingProvider $provider
102
+     * @throws \OCP\Lock\LockedException
103
+     */
104
+    public function acquireLock($path, $type, ILockingProvider $provider);
105 105
 
106
-	/**
107
-	 * @param string $path The path of the file to release the lock for
108
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
109
-	 * @param \OCP\Lock\ILockingProvider $provider
110
-	 * @throws \OCP\Lock\LockedException
111
-	 */
112
-	public function releaseLock($path, $type, ILockingProvider $provider);
106
+    /**
107
+     * @param string $path The path of the file to release the lock for
108
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
109
+     * @param \OCP\Lock\ILockingProvider $provider
110
+     * @throws \OCP\Lock\LockedException
111
+     */
112
+    public function releaseLock($path, $type, ILockingProvider $provider);
113 113
 
114
-	/**
115
-	 * @param string $path The path of the file to change the lock for
116
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
117
-	 * @param \OCP\Lock\ILockingProvider $provider
118
-	 * @throws \OCP\Lock\LockedException
119
-	 */
120
-	public function changeLock($path, $type, ILockingProvider $provider);
114
+    /**
115
+     * @param string $path The path of the file to change the lock for
116
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
117
+     * @param \OCP\Lock\ILockingProvider $provider
118
+     * @throws \OCP\Lock\LockedException
119
+     */
120
+    public function changeLock($path, $type, ILockingProvider $provider);
121 121
 }
Please login to merge, or discard this patch.
apps/dav/lib/CardDAV/CardDavBackend.php 4 patches
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) {
@@ -195,6 +195,9 @@  discard block
 block discarded – undo
195 195
 		return array_values($addressBooks);
196 196
 	}
197 197
 
198
+	/**
199
+	 * @param string $principalUri
200
+	 */
198 201
 	public function getUsersOwnAddressBooks($principalUri) {
199 202
 		$principalUriOriginal = $principalUri;
200 203
 		$principalUri = $this->convertPrincipal($principalUri, true);
@@ -264,7 +267,8 @@  discard block
 block discarded – undo
264 267
 	}
265 268
 
266 269
 	/**
267
-	 * @param $addressBookUri
270
+	 * @param string $addressBookUri
271
+	 * @param string $principal
268 272
 	 * @return array|null
269 273
 	 */
270 274
 	public function getAddressBooksByUri($principal, $addressBookUri) {
@@ -953,6 +957,7 @@  discard block
 block discarded – undo
953 957
 	 *   * readOnly - boolean
954 958
 	 *   * summary - Optional, a description for the share
955 959
 	 *
960
+	 * @param integer $addressBookId
956 961
 	 * @return array
957 962
 	 */
958 963
 	public function getShares($addressBookId) {
@@ -1052,7 +1057,7 @@  discard block
 block discarded – undo
1052 1057
 
1053 1058
 	/**
1054 1059
 	 * For shared address books the sharee is set in the ACL of the address book
1055
-	 * @param $addressBookId
1060
+	 * @param integer $addressBookId
1056 1061
 	 * @param $acl
1057 1062
 	 * @return array
1058 1063
 	 */
@@ -1060,6 +1065,9 @@  discard block
 block discarded – undo
1060 1065
 		return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1061 1066
 	}
1062 1067
 
1068
+	/**
1069
+	 * @param boolean $toV2
1070
+	 */
1063 1071
 	private function convertPrincipal($principalUri, $toV2) {
1064 1072
 		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1065 1073
 			list(, $name) = URLUtil::splitPath($principalUri);
Please login to merge, or discard this patch.
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.
Indentation   +1035 added lines, -1035 removed lines patch added patch discarded remove patch
@@ -48,1039 +48,1039 @@
 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 = null) {
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
-		$result->closeCursor();
160
-
161
-		// query for shared calendars
162
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
163
-		$principals[]= $principalUri;
164
-
165
-		$query = $this->db->getQueryBuilder();
166
-		$result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
167
-			->from('dav_shares', 's')
168
-			->join('s', 'addressbooks', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
169
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
170
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
171
-			->setParameter('type', 'addressbook')
172
-			->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
173
-			->execute();
174
-
175
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
176
-		while($row = $result->fetch()) {
177
-			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
178
-			if (isset($addressBooks[$row['id']])) {
179
-				if ($readOnly) {
180
-					// New share can not have more permissions then the old one.
181
-					continue;
182
-				}
183
-				if (isset($addressBooks[$row['id']][$readOnlyPropertyName]) &&
184
-					$addressBooks[$row['id']][$readOnlyPropertyName] === 0) {
185
-					// Old share is already read-write, no more permissions can be gained
186
-					continue;
187
-				}
188
-			}
189
-
190
-			list(, $name) = URLUtil::splitPath($row['principaluri']);
191
-			$uri = $row['uri'] . '_shared_by_' . $name;
192
-			$displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
193
-
194
-			$addressBooks[$row['id']] = [
195
-				'id'  => $row['id'],
196
-				'uri' => $uri,
197
-				'principaluri' => $principalUriOriginal,
198
-				'{DAV:}displayname' => $displayName,
199
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
200
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
201
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
202
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
203
-				$readOnlyPropertyName => $readOnly,
204
-			];
205
-		}
206
-		$result->closeCursor();
207
-
208
-		return array_values($addressBooks);
209
-	}
210
-
211
-	public function getUsersOwnAddressBooks($principalUri) {
212
-		$principalUriOriginal = $principalUri;
213
-		$principalUri = $this->convertPrincipal($principalUri, true);
214
-		$query = $this->db->getQueryBuilder();
215
-		$query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
216
-			  ->from('addressbooks')
217
-			  ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
218
-
219
-		$addressBooks = [];
220
-
221
-		$result = $query->execute();
222
-		while($row = $result->fetch()) {
223
-			$addressBooks[$row['id']] = [
224
-				'id'  => $row['id'],
225
-				'uri' => $row['uri'],
226
-				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
227
-				'{DAV:}displayname' => $row['displayname'],
228
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
229
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
230
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
231
-			];
232
-		}
233
-		$result->closeCursor();
234
-
235
-		return array_values($addressBooks);
236
-	}
237
-
238
-	private function getUserDisplayName($uid) {
239
-		if (!isset($this->userDisplayNames[$uid])) {
240
-			$user = $this->userManager->get($uid);
241
-
242
-			if ($user instanceof IUser) {
243
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
244
-			} else {
245
-				$this->userDisplayNames[$uid] = $uid;
246
-			}
247
-		}
248
-
249
-		return $this->userDisplayNames[$uid];
250
-	}
251
-
252
-	/**
253
-	 * @param int $addressBookId
254
-	 */
255
-	public function getAddressBookById($addressBookId) {
256
-		$query = $this->db->getQueryBuilder();
257
-		$result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
258
-			->from('addressbooks')
259
-			->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
260
-			->execute();
261
-
262
-		$row = $result->fetch();
263
-		$result->closeCursor();
264
-		if ($row === false) {
265
-			return null;
266
-		}
267
-
268
-		return [
269
-			'id'  => $row['id'],
270
-			'uri' => $row['uri'],
271
-			'principaluri' => $row['principaluri'],
272
-			'{DAV:}displayname' => $row['displayname'],
273
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
274
-			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
275
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
276
-		];
277
-	}
278
-
279
-	/**
280
-	 * @param $addressBookUri
281
-	 * @return array|null
282
-	 */
283
-	public function getAddressBooksByUri($principal, $addressBookUri) {
284
-		$query = $this->db->getQueryBuilder();
285
-		$result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
286
-			->from('addressbooks')
287
-			->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
288
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
289
-			->setMaxResults(1)
290
-			->execute();
291
-
292
-		$row = $result->fetch();
293
-		$result->closeCursor();
294
-		if ($row === false) {
295
-			return null;
296
-		}
297
-
298
-		return [
299
-				'id'  => $row['id'],
300
-				'uri' => $row['uri'],
301
-				'principaluri' => $row['principaluri'],
302
-				'{DAV:}displayname' => $row['displayname'],
303
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
304
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
305
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
306
-			];
307
-	}
308
-
309
-	/**
310
-	 * Updates properties for an address book.
311
-	 *
312
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
313
-	 * To do the actual updates, you must tell this object which properties
314
-	 * you're going to process with the handle() method.
315
-	 *
316
-	 * Calling the handle method is like telling the PropPatch object "I
317
-	 * promise I can handle updating this property".
318
-	 *
319
-	 * Read the PropPatch documentation for more info and examples.
320
-	 *
321
-	 * @param string $addressBookId
322
-	 * @param \Sabre\DAV\PropPatch $propPatch
323
-	 * @return void
324
-	 */
325
-	function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
326
-		$supportedProperties = [
327
-			'{DAV:}displayname',
328
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description',
329
-		];
330
-
331
-		$propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
332
-
333
-			$updates = [];
334
-			foreach($mutations as $property=>$newValue) {
335
-
336
-				switch($property) {
337
-					case '{DAV:}displayname' :
338
-						$updates['displayname'] = $newValue;
339
-						break;
340
-					case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
341
-						$updates['description'] = $newValue;
342
-						break;
343
-				}
344
-			}
345
-			$query = $this->db->getQueryBuilder();
346
-			$query->update('addressbooks');
347
-
348
-			foreach($updates as $key=>$value) {
349
-				$query->set($key, $query->createNamedParameter($value));
350
-			}
351
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
352
-			->execute();
353
-
354
-			$this->addChange($addressBookId, "", 2);
355
-
356
-			return true;
357
-
358
-		});
359
-	}
360
-
361
-	/**
362
-	 * Creates a new address book
363
-	 *
364
-	 * @param string $principalUri
365
-	 * @param string $url Just the 'basename' of the url.
366
-	 * @param array $properties
367
-	 * @return int
368
-	 * @throws BadRequest
369
-	 */
370
-	function createAddressBook($principalUri, $url, array $properties) {
371
-		$values = [
372
-			'displayname' => null,
373
-			'description' => null,
374
-			'principaluri' => $principalUri,
375
-			'uri' => $url,
376
-			'synctoken' => 1
377
-		];
378
-
379
-		foreach($properties as $property=>$newValue) {
380
-
381
-			switch($property) {
382
-				case '{DAV:}displayname' :
383
-					$values['displayname'] = $newValue;
384
-					break;
385
-				case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
386
-					$values['description'] = $newValue;
387
-					break;
388
-				default :
389
-					throw new BadRequest('Unknown property: ' . $property);
390
-			}
391
-
392
-		}
393
-
394
-		// Fallback to make sure the displayname is set. Some clients may refuse
395
-		// to work with addressbooks not having a displayname.
396
-		if(is_null($values['displayname'])) {
397
-			$values['displayname'] = $url;
398
-		}
399
-
400
-		$query = $this->db->getQueryBuilder();
401
-		$query->insert('addressbooks')
402
-			->values([
403
-				'uri' => $query->createParameter('uri'),
404
-				'displayname' => $query->createParameter('displayname'),
405
-				'description' => $query->createParameter('description'),
406
-				'principaluri' => $query->createParameter('principaluri'),
407
-				'synctoken' => $query->createParameter('synctoken'),
408
-			])
409
-			->setParameters($values)
410
-			->execute();
411
-
412
-		return $query->getLastInsertId();
413
-	}
414
-
415
-	/**
416
-	 * Deletes an entire addressbook and all its contents
417
-	 *
418
-	 * @param mixed $addressBookId
419
-	 * @return void
420
-	 */
421
-	function deleteAddressBook($addressBookId) {
422
-		$query = $this->db->getQueryBuilder();
423
-		$query->delete('cards')
424
-			->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
425
-			->setParameter('addressbookid', $addressBookId)
426
-			->execute();
427
-
428
-		$query->delete('addressbookchanges')
429
-			->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
430
-			->setParameter('addressbookid', $addressBookId)
431
-			->execute();
432
-
433
-		$query->delete('addressbooks')
434
-			->where($query->expr()->eq('id', $query->createParameter('id')))
435
-			->setParameter('id', $addressBookId)
436
-			->execute();
437
-
438
-		$this->sharingBackend->deleteAllShares($addressBookId);
439
-
440
-		$query->delete($this->dbCardsPropertiesTable)
441
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
442
-			->execute();
443
-
444
-	}
445
-
446
-	/**
447
-	 * Returns all cards for a specific addressbook id.
448
-	 *
449
-	 * This method should return the following properties for each card:
450
-	 *   * carddata - raw vcard data
451
-	 *   * uri - Some unique url
452
-	 *   * lastmodified - A unix timestamp
453
-	 *
454
-	 * It's recommended to also return the following properties:
455
-	 *   * etag - A unique etag. This must change every time the card changes.
456
-	 *   * size - The size of the card in bytes.
457
-	 *
458
-	 * If these last two properties are provided, less time will be spent
459
-	 * calculating them. If they are specified, you can also ommit carddata.
460
-	 * This may speed up certain requests, especially with large cards.
461
-	 *
462
-	 * @param mixed $addressBookId
463
-	 * @return array
464
-	 */
465
-	function getCards($addressBookId) {
466
-		$query = $this->db->getQueryBuilder();
467
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
468
-			->from('cards')
469
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
470
-
471
-		$cards = [];
472
-
473
-		$result = $query->execute();
474
-		while($row = $result->fetch()) {
475
-			$row['etag'] = '"' . $row['etag'] . '"';
476
-			$row['carddata'] = $this->readBlob($row['carddata']);
477
-			$cards[] = $row;
478
-		}
479
-		$result->closeCursor();
480
-
481
-		return $cards;
482
-	}
483
-
484
-	/**
485
-	 * Returns a specific card.
486
-	 *
487
-	 * The same set of properties must be returned as with getCards. The only
488
-	 * exception is that 'carddata' is absolutely required.
489
-	 *
490
-	 * If the card does not exist, you must return false.
491
-	 *
492
-	 * @param mixed $addressBookId
493
-	 * @param string $cardUri
494
-	 * @return array
495
-	 */
496
-	function getCard($addressBookId, $cardUri) {
497
-		$query = $this->db->getQueryBuilder();
498
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
499
-			->from('cards')
500
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
501
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
502
-			->setMaxResults(1);
503
-
504
-		$result = $query->execute();
505
-		$row = $result->fetch();
506
-		if (!$row) {
507
-			return false;
508
-		}
509
-		$row['etag'] = '"' . $row['etag'] . '"';
510
-		$row['carddata'] = $this->readBlob($row['carddata']);
511
-
512
-		return $row;
513
-	}
514
-
515
-	/**
516
-	 * Returns a list of cards.
517
-	 *
518
-	 * This method should work identical to getCard, but instead return all the
519
-	 * cards in the list as an array.
520
-	 *
521
-	 * If the backend supports this, it may allow for some speed-ups.
522
-	 *
523
-	 * @param mixed $addressBookId
524
-	 * @param string[] $uris
525
-	 * @return array
526
-	 */
527
-	function getMultipleCards($addressBookId, array $uris) {
528
-		if (empty($uris)) {
529
-			return [];
530
-		}
531
-
532
-		$chunks = array_chunk($uris, 100);
533
-		$cards = [];
534
-
535
-		$query = $this->db->getQueryBuilder();
536
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
537
-			->from('cards')
538
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
539
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
540
-
541
-		foreach ($chunks as $uris) {
542
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
543
-			$result = $query->execute();
544
-
545
-			while ($row = $result->fetch()) {
546
-				$row['etag'] = '"' . $row['etag'] . '"';
547
-				$row['carddata'] = $this->readBlob($row['carddata']);
548
-				$cards[] = $row;
549
-			}
550
-			$result->closeCursor();
551
-		}
552
-		return $cards;
553
-	}
554
-
555
-	/**
556
-	 * Creates a new card.
557
-	 *
558
-	 * The addressbook id will be passed as the first argument. This is the
559
-	 * same id as it is returned from the getAddressBooksForUser method.
560
-	 *
561
-	 * The cardUri is a base uri, and doesn't include the full path. The
562
-	 * cardData argument is the vcard body, and is passed as a string.
563
-	 *
564
-	 * It is possible to return an ETag from this method. This ETag is for the
565
-	 * newly created resource, and must be enclosed with double quotes (that
566
-	 * is, the string itself must contain the double quotes).
567
-	 *
568
-	 * You should only return the ETag if you store the carddata as-is. If a
569
-	 * subsequent GET request on the same card does not have the same body,
570
-	 * byte-by-byte and you did return an ETag here, clients tend to get
571
-	 * confused.
572
-	 *
573
-	 * If you don't return an ETag, you can just return null.
574
-	 *
575
-	 * @param mixed $addressBookId
576
-	 * @param string $cardUri
577
-	 * @param string $cardData
578
-	 * @return string
579
-	 */
580
-	function createCard($addressBookId, $cardUri, $cardData) {
581
-		$etag = md5($cardData);
582
-
583
-		$query = $this->db->getQueryBuilder();
584
-		$query->insert('cards')
585
-			->values([
586
-				'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
587
-				'uri' => $query->createNamedParameter($cardUri),
588
-				'lastmodified' => $query->createNamedParameter(time()),
589
-				'addressbookid' => $query->createNamedParameter($addressBookId),
590
-				'size' => $query->createNamedParameter(strlen($cardData)),
591
-				'etag' => $query->createNamedParameter($etag),
592
-			])
593
-			->execute();
594
-
595
-		$this->addChange($addressBookId, $cardUri, 1);
596
-		$this->updateProperties($addressBookId, $cardUri, $cardData);
597
-
598
-		if (!is_null($this->dispatcher)) {
599
-			$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
600
-				new GenericEvent(null, [
601
-					'addressBookId' => $addressBookId,
602
-					'cardUri' => $cardUri,
603
-					'cardData' => $cardData]));
604
-		}
605
-
606
-		return '"' . $etag . '"';
607
-	}
608
-
609
-	/**
610
-	 * Updates a card.
611
-	 *
612
-	 * The addressbook id will be passed as the first argument. This is the
613
-	 * same id as it is returned from the getAddressBooksForUser method.
614
-	 *
615
-	 * The cardUri is a base uri, and doesn't include the full path. The
616
-	 * cardData argument is the vcard body, and is passed as a string.
617
-	 *
618
-	 * It is possible to return an ETag from this method. This ETag should
619
-	 * match that of the updated resource, and must be enclosed with double
620
-	 * quotes (that is: the string itself must contain the actual quotes).
621
-	 *
622
-	 * You should only return the ETag if you store the carddata as-is. If a
623
-	 * subsequent GET request on the same card does not have the same body,
624
-	 * byte-by-byte and you did return an ETag here, clients tend to get
625
-	 * confused.
626
-	 *
627
-	 * If you don't return an ETag, you can just return null.
628
-	 *
629
-	 * @param mixed $addressBookId
630
-	 * @param string $cardUri
631
-	 * @param string $cardData
632
-	 * @return string
633
-	 */
634
-	function updateCard($addressBookId, $cardUri, $cardData) {
635
-
636
-		$etag = md5($cardData);
637
-		$query = $this->db->getQueryBuilder();
638
-		$query->update('cards')
639
-			->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
640
-			->set('lastmodified', $query->createNamedParameter(time()))
641
-			->set('size', $query->createNamedParameter(strlen($cardData)))
642
-			->set('etag', $query->createNamedParameter($etag))
643
-			->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
644
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
645
-			->execute();
646
-
647
-		$this->addChange($addressBookId, $cardUri, 2);
648
-		$this->updateProperties($addressBookId, $cardUri, $cardData);
649
-
650
-		if (!is_null($this->dispatcher)) {
651
-			$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
652
-				new GenericEvent(null, [
653
-					'addressBookId' => $addressBookId,
654
-					'cardUri' => $cardUri,
655
-					'cardData' => $cardData]));
656
-		}
657
-
658
-		return '"' . $etag . '"';
659
-	}
660
-
661
-	/**
662
-	 * Deletes a card
663
-	 *
664
-	 * @param mixed $addressBookId
665
-	 * @param string $cardUri
666
-	 * @return bool
667
-	 */
668
-	function deleteCard($addressBookId, $cardUri) {
669
-		try {
670
-			$cardId = $this->getCardId($addressBookId, $cardUri);
671
-		} catch (\InvalidArgumentException $e) {
672
-			$cardId = null;
673
-		}
674
-		$query = $this->db->getQueryBuilder();
675
-		$ret = $query->delete('cards')
676
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
677
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
678
-			->execute();
679
-
680
-		$this->addChange($addressBookId, $cardUri, 3);
681
-
682
-		if (!is_null($this->dispatcher)) {
683
-			$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
684
-				new GenericEvent(null, [
685
-					'addressBookId' => $addressBookId,
686
-					'cardUri' => $cardUri]));
687
-		}
688
-
689
-		if ($ret === 1) {
690
-			if ($cardId !== null) {
691
-				$this->purgeProperties($addressBookId, $cardId);
692
-			}
693
-			return true;
694
-		}
695
-
696
-		return false;
697
-	}
698
-
699
-	/**
700
-	 * The getChanges method returns all the changes that have happened, since
701
-	 * the specified syncToken in the specified address book.
702
-	 *
703
-	 * This function should return an array, such as the following:
704
-	 *
705
-	 * [
706
-	 *   'syncToken' => 'The current synctoken',
707
-	 *   'added'   => [
708
-	 *      'new.txt',
709
-	 *   ],
710
-	 *   'modified'   => [
711
-	 *      'modified.txt',
712
-	 *   ],
713
-	 *   'deleted' => [
714
-	 *      'foo.php.bak',
715
-	 *      'old.txt'
716
-	 *   ]
717
-	 * ];
718
-	 *
719
-	 * The returned syncToken property should reflect the *current* syncToken
720
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
721
-	 * property. This is needed here too, to ensure the operation is atomic.
722
-	 *
723
-	 * If the $syncToken argument is specified as null, this is an initial
724
-	 * sync, and all members should be reported.
725
-	 *
726
-	 * The modified property is an array of nodenames that have changed since
727
-	 * the last token.
728
-	 *
729
-	 * The deleted property is an array with nodenames, that have been deleted
730
-	 * from collection.
731
-	 *
732
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
733
-	 * 1, you only have to report changes that happened only directly in
734
-	 * immediate descendants. If it's 2, it should also include changes from
735
-	 * the nodes below the child collections. (grandchildren)
736
-	 *
737
-	 * The $limit argument allows a client to specify how many results should
738
-	 * be returned at most. If the limit is not specified, it should be treated
739
-	 * as infinite.
740
-	 *
741
-	 * If the limit (infinite or not) is higher than you're willing to return,
742
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
743
-	 *
744
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
745
-	 * return null.
746
-	 *
747
-	 * The limit is 'suggestive'. You are free to ignore it.
748
-	 *
749
-	 * @param string $addressBookId
750
-	 * @param string $syncToken
751
-	 * @param int $syncLevel
752
-	 * @param int $limit
753
-	 * @return array
754
-	 */
755
-	function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
756
-		// Current synctoken
757
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
758
-		$stmt->execute([ $addressBookId ]);
759
-		$currentToken = $stmt->fetchColumn(0);
760
-
761
-		if (is_null($currentToken)) return null;
762
-
763
-		$result = [
764
-			'syncToken' => $currentToken,
765
-			'added'     => [],
766
-			'modified'  => [],
767
-			'deleted'   => [],
768
-		];
769
-
770
-		if ($syncToken) {
771
-
772
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
773
-			if ($limit>0) {
774
-				$query .= " `LIMIT` " . (int)$limit;
775
-			}
776
-
777
-			// Fetching all changes
778
-			$stmt = $this->db->prepare($query);
779
-			$stmt->execute([$syncToken, $currentToken, $addressBookId]);
780
-
781
-			$changes = [];
782
-
783
-			// This loop ensures that any duplicates are overwritten, only the
784
-			// last change on a node is relevant.
785
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
786
-
787
-				$changes[$row['uri']] = $row['operation'];
788
-
789
-			}
790
-
791
-			foreach($changes as $uri => $operation) {
792
-
793
-				switch($operation) {
794
-					case 1:
795
-						$result['added'][] = $uri;
796
-						break;
797
-					case 2:
798
-						$result['modified'][] = $uri;
799
-						break;
800
-					case 3:
801
-						$result['deleted'][] = $uri;
802
-						break;
803
-				}
804
-
805
-			}
806
-		} else {
807
-			// No synctoken supplied, this is the initial sync.
808
-			$query = "SELECT `uri` FROM `*PREFIX*cards` WHERE `addressbookid` = ?";
809
-			$stmt = $this->db->prepare($query);
810
-			$stmt->execute([$addressBookId]);
811
-
812
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
813
-		}
814
-		return $result;
815
-	}
816
-
817
-	/**
818
-	 * Adds a change record to the addressbookchanges table.
819
-	 *
820
-	 * @param mixed $addressBookId
821
-	 * @param string $objectUri
822
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete
823
-	 * @return void
824
-	 */
825
-	protected function addChange($addressBookId, $objectUri, $operation) {
826
-		$sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?';
827
-		$stmt = $this->db->prepare($sql);
828
-		$stmt->execute([
829
-			$objectUri,
830
-			$addressBookId,
831
-			$operation,
832
-			$addressBookId
833
-		]);
834
-		$stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
835
-		$stmt->execute([
836
-			$addressBookId
837
-		]);
838
-	}
839
-
840
-	private function readBlob($cardData) {
841
-		if (is_resource($cardData)) {
842
-			return stream_get_contents($cardData);
843
-		}
844
-
845
-		return $cardData;
846
-	}
847
-
848
-	/**
849
-	 * @param IShareable $shareable
850
-	 * @param string[] $add
851
-	 * @param string[] $remove
852
-	 */
853
-	public function updateShares(IShareable $shareable, $add, $remove) {
854
-		$this->sharingBackend->updateShares($shareable, $add, $remove);
855
-	}
856
-
857
-	/**
858
-	 * search contact
859
-	 *
860
-	 * @param int $addressBookId
861
-	 * @param string $pattern which should match within the $searchProperties
862
-	 * @param array $searchProperties defines the properties within the query pattern should match
863
-	 * @return array an array of contacts which are arrays of key-value-pairs
864
-	 */
865
-	public function search($addressBookId, $pattern, $searchProperties) {
866
-		$query = $this->db->getQueryBuilder();
867
-		$query2 = $this->db->getQueryBuilder();
868
-		$query2->selectDistinct('cp.cardid')->from($this->dbCardsPropertiesTable, 'cp');
869
-		foreach ($searchProperties as $property) {
870
-			$query2->orWhere(
871
-				$query2->expr()->andX(
872
-					$query2->expr()->eq('cp.name', $query->createNamedParameter($property)),
873
-					$query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%'))
874
-				)
875
-			);
876
-		}
877
-		$query2->andWhere($query2->expr()->eq('cp.addressbookid', $query->createNamedParameter($addressBookId)));
878
-
879
-		$query->select('c.carddata', 'c.uri')->from($this->dbCardsTable, 'c')
880
-			->where($query->expr()->in('c.id', $query->createFunction($query2->getSQL())));
881
-
882
-		$result = $query->execute();
883
-		$cards = $result->fetchAll();
884
-
885
-		$result->closeCursor();
886
-
887
-		return array_map(function($array) {
888
-			$array['carddata'] = $this->readBlob($array['carddata']);
889
-			return $array;
890
-		}, $cards);
891
-	}
892
-
893
-	/**
894
-	 * @param int $bookId
895
-	 * @param string $name
896
-	 * @return array
897
-	 */
898
-	public function collectCardProperties($bookId, $name) {
899
-		$query = $this->db->getQueryBuilder();
900
-		$result = $query->selectDistinct('value')
901
-			->from($this->dbCardsPropertiesTable)
902
-			->where($query->expr()->eq('name', $query->createNamedParameter($name)))
903
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
904
-			->execute();
905
-
906
-		$all = $result->fetchAll(PDO::FETCH_COLUMN);
907
-		$result->closeCursor();
908
-
909
-		return $all;
910
-	}
911
-
912
-	/**
913
-	 * get URI from a given contact
914
-	 *
915
-	 * @param int $id
916
-	 * @return string
917
-	 */
918
-	public function getCardUri($id) {
919
-		$query = $this->db->getQueryBuilder();
920
-		$query->select('uri')->from($this->dbCardsTable)
921
-				->where($query->expr()->eq('id', $query->createParameter('id')))
922
-				->setParameter('id', $id);
923
-
924
-		$result = $query->execute();
925
-		$uri = $result->fetch();
926
-		$result->closeCursor();
927
-
928
-		if (!isset($uri['uri'])) {
929
-			throw new \InvalidArgumentException('Card does not exists: ' . $id);
930
-		}
931
-
932
-		return $uri['uri'];
933
-	}
934
-
935
-	/**
936
-	 * return contact with the given URI
937
-	 *
938
-	 * @param int $addressBookId
939
-	 * @param string $uri
940
-	 * @returns array
941
-	 */
942
-	public function getContact($addressBookId, $uri) {
943
-		$result = [];
944
-		$query = $this->db->getQueryBuilder();
945
-		$query->select('*')->from($this->dbCardsTable)
946
-				->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
947
-				->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
948
-		$queryResult = $query->execute();
949
-		$contact = $queryResult->fetch();
950
-		$queryResult->closeCursor();
951
-
952
-		if (is_array($contact)) {
953
-			$result = $contact;
954
-		}
955
-
956
-		return $result;
957
-	}
958
-
959
-	/**
960
-	 * Returns the list of people whom this address book is shared with.
961
-	 *
962
-	 * Every element in this array should have the following properties:
963
-	 *   * href - Often a mailto: address
964
-	 *   * commonName - Optional, for example a first + last name
965
-	 *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
966
-	 *   * readOnly - boolean
967
-	 *   * summary - Optional, a description for the share
968
-	 *
969
-	 * @return array
970
-	 */
971
-	public function getShares($addressBookId) {
972
-		return $this->sharingBackend->getShares($addressBookId);
973
-	}
974
-
975
-	/**
976
-	 * update properties table
977
-	 *
978
-	 * @param int $addressBookId
979
-	 * @param string $cardUri
980
-	 * @param string $vCardSerialized
981
-	 */
982
-	protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
983
-		$cardId = $this->getCardId($addressBookId, $cardUri);
984
-		$vCard = $this->readCard($vCardSerialized);
985
-
986
-		$this->purgeProperties($addressBookId, $cardId);
987
-
988
-		$query = $this->db->getQueryBuilder();
989
-		$query->insert($this->dbCardsPropertiesTable)
990
-			->values(
991
-				[
992
-					'addressbookid' => $query->createNamedParameter($addressBookId),
993
-					'cardid' => $query->createNamedParameter($cardId),
994
-					'name' => $query->createParameter('name'),
995
-					'value' => $query->createParameter('value'),
996
-					'preferred' => $query->createParameter('preferred')
997
-				]
998
-			);
999
-
1000
-		foreach ($vCard->children() as $property) {
1001
-			if(!in_array($property->name, self::$indexProperties)) {
1002
-				continue;
1003
-			}
1004
-			$preferred = 0;
1005
-			foreach($property->parameters as $parameter) {
1006
-				if ($parameter->name == 'TYPE' && strtoupper($parameter->getValue()) == 'PREF') {
1007
-					$preferred = 1;
1008
-					break;
1009
-				}
1010
-			}
1011
-			$query->setParameter('name', $property->name);
1012
-			$query->setParameter('value', substr($property->getValue(), 0, 254));
1013
-			$query->setParameter('preferred', $preferred);
1014
-			$query->execute();
1015
-		}
1016
-	}
1017
-
1018
-	/**
1019
-	 * read vCard data into a vCard object
1020
-	 *
1021
-	 * @param string $cardData
1022
-	 * @return VCard
1023
-	 */
1024
-	protected function readCard($cardData) {
1025
-		return  Reader::read($cardData);
1026
-	}
1027
-
1028
-	/**
1029
-	 * delete all properties from a given card
1030
-	 *
1031
-	 * @param int $addressBookId
1032
-	 * @param int $cardId
1033
-	 */
1034
-	protected function purgeProperties($addressBookId, $cardId) {
1035
-		$query = $this->db->getQueryBuilder();
1036
-		$query->delete($this->dbCardsPropertiesTable)
1037
-			->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
1038
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1039
-		$query->execute();
1040
-	}
1041
-
1042
-	/**
1043
-	 * get ID from a given contact
1044
-	 *
1045
-	 * @param int $addressBookId
1046
-	 * @param string $uri
1047
-	 * @return int
1048
-	 */
1049
-	protected function getCardId($addressBookId, $uri) {
1050
-		$query = $this->db->getQueryBuilder();
1051
-		$query->select('id')->from($this->dbCardsTable)
1052
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1053
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1054
-
1055
-		$result = $query->execute();
1056
-		$cardIds = $result->fetch();
1057
-		$result->closeCursor();
1058
-
1059
-		if (!isset($cardIds['id'])) {
1060
-			throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1061
-		}
1062
-
1063
-		return (int)$cardIds['id'];
1064
-	}
1065
-
1066
-	/**
1067
-	 * For shared address books the sharee is set in the ACL of the address book
1068
-	 * @param $addressBookId
1069
-	 * @param $acl
1070
-	 * @return array
1071
-	 */
1072
-	public function applyShareAcl($addressBookId, $acl) {
1073
-		return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1074
-	}
1075
-
1076
-	private function convertPrincipal($principalUri, $toV2) {
1077
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1078
-			list(, $name) = URLUtil::splitPath($principalUri);
1079
-			if ($toV2 === true) {
1080
-				return "principals/users/$name";
1081
-			}
1082
-			return "principals/$name";
1083
-		}
1084
-		return $principalUri;
1085
-	}
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 = null) {
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
+        $result->closeCursor();
160
+
161
+        // query for shared calendars
162
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
163
+        $principals[]= $principalUri;
164
+
165
+        $query = $this->db->getQueryBuilder();
166
+        $result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
167
+            ->from('dav_shares', 's')
168
+            ->join('s', 'addressbooks', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
169
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
170
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
171
+            ->setParameter('type', 'addressbook')
172
+            ->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
173
+            ->execute();
174
+
175
+        $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
176
+        while($row = $result->fetch()) {
177
+            $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
178
+            if (isset($addressBooks[$row['id']])) {
179
+                if ($readOnly) {
180
+                    // New share can not have more permissions then the old one.
181
+                    continue;
182
+                }
183
+                if (isset($addressBooks[$row['id']][$readOnlyPropertyName]) &&
184
+                    $addressBooks[$row['id']][$readOnlyPropertyName] === 0) {
185
+                    // Old share is already read-write, no more permissions can be gained
186
+                    continue;
187
+                }
188
+            }
189
+
190
+            list(, $name) = URLUtil::splitPath($row['principaluri']);
191
+            $uri = $row['uri'] . '_shared_by_' . $name;
192
+            $displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
193
+
194
+            $addressBooks[$row['id']] = [
195
+                'id'  => $row['id'],
196
+                'uri' => $uri,
197
+                'principaluri' => $principalUriOriginal,
198
+                '{DAV:}displayname' => $displayName,
199
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
200
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
201
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
202
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
203
+                $readOnlyPropertyName => $readOnly,
204
+            ];
205
+        }
206
+        $result->closeCursor();
207
+
208
+        return array_values($addressBooks);
209
+    }
210
+
211
+    public function getUsersOwnAddressBooks($principalUri) {
212
+        $principalUriOriginal = $principalUri;
213
+        $principalUri = $this->convertPrincipal($principalUri, true);
214
+        $query = $this->db->getQueryBuilder();
215
+        $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
216
+                ->from('addressbooks')
217
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
218
+
219
+        $addressBooks = [];
220
+
221
+        $result = $query->execute();
222
+        while($row = $result->fetch()) {
223
+            $addressBooks[$row['id']] = [
224
+                'id'  => $row['id'],
225
+                'uri' => $row['uri'],
226
+                'principaluri' => $this->convertPrincipal($row['principaluri'], false),
227
+                '{DAV:}displayname' => $row['displayname'],
228
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
229
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
230
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
231
+            ];
232
+        }
233
+        $result->closeCursor();
234
+
235
+        return array_values($addressBooks);
236
+    }
237
+
238
+    private function getUserDisplayName($uid) {
239
+        if (!isset($this->userDisplayNames[$uid])) {
240
+            $user = $this->userManager->get($uid);
241
+
242
+            if ($user instanceof IUser) {
243
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
244
+            } else {
245
+                $this->userDisplayNames[$uid] = $uid;
246
+            }
247
+        }
248
+
249
+        return $this->userDisplayNames[$uid];
250
+    }
251
+
252
+    /**
253
+     * @param int $addressBookId
254
+     */
255
+    public function getAddressBookById($addressBookId) {
256
+        $query = $this->db->getQueryBuilder();
257
+        $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
258
+            ->from('addressbooks')
259
+            ->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
260
+            ->execute();
261
+
262
+        $row = $result->fetch();
263
+        $result->closeCursor();
264
+        if ($row === false) {
265
+            return null;
266
+        }
267
+
268
+        return [
269
+            'id'  => $row['id'],
270
+            'uri' => $row['uri'],
271
+            'principaluri' => $row['principaluri'],
272
+            '{DAV:}displayname' => $row['displayname'],
273
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
274
+            '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
275
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
276
+        ];
277
+    }
278
+
279
+    /**
280
+     * @param $addressBookUri
281
+     * @return array|null
282
+     */
283
+    public function getAddressBooksByUri($principal, $addressBookUri) {
284
+        $query = $this->db->getQueryBuilder();
285
+        $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
286
+            ->from('addressbooks')
287
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
288
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
289
+            ->setMaxResults(1)
290
+            ->execute();
291
+
292
+        $row = $result->fetch();
293
+        $result->closeCursor();
294
+        if ($row === false) {
295
+            return null;
296
+        }
297
+
298
+        return [
299
+                'id'  => $row['id'],
300
+                'uri' => $row['uri'],
301
+                'principaluri' => $row['principaluri'],
302
+                '{DAV:}displayname' => $row['displayname'],
303
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
304
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
305
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
306
+            ];
307
+    }
308
+
309
+    /**
310
+     * Updates properties for an address book.
311
+     *
312
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
313
+     * To do the actual updates, you must tell this object which properties
314
+     * you're going to process with the handle() method.
315
+     *
316
+     * Calling the handle method is like telling the PropPatch object "I
317
+     * promise I can handle updating this property".
318
+     *
319
+     * Read the PropPatch documentation for more info and examples.
320
+     *
321
+     * @param string $addressBookId
322
+     * @param \Sabre\DAV\PropPatch $propPatch
323
+     * @return void
324
+     */
325
+    function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
326
+        $supportedProperties = [
327
+            '{DAV:}displayname',
328
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description',
329
+        ];
330
+
331
+        $propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
332
+
333
+            $updates = [];
334
+            foreach($mutations as $property=>$newValue) {
335
+
336
+                switch($property) {
337
+                    case '{DAV:}displayname' :
338
+                        $updates['displayname'] = $newValue;
339
+                        break;
340
+                    case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
341
+                        $updates['description'] = $newValue;
342
+                        break;
343
+                }
344
+            }
345
+            $query = $this->db->getQueryBuilder();
346
+            $query->update('addressbooks');
347
+
348
+            foreach($updates as $key=>$value) {
349
+                $query->set($key, $query->createNamedParameter($value));
350
+            }
351
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
352
+            ->execute();
353
+
354
+            $this->addChange($addressBookId, "", 2);
355
+
356
+            return true;
357
+
358
+        });
359
+    }
360
+
361
+    /**
362
+     * Creates a new address book
363
+     *
364
+     * @param string $principalUri
365
+     * @param string $url Just the 'basename' of the url.
366
+     * @param array $properties
367
+     * @return int
368
+     * @throws BadRequest
369
+     */
370
+    function createAddressBook($principalUri, $url, array $properties) {
371
+        $values = [
372
+            'displayname' => null,
373
+            'description' => null,
374
+            'principaluri' => $principalUri,
375
+            'uri' => $url,
376
+            'synctoken' => 1
377
+        ];
378
+
379
+        foreach($properties as $property=>$newValue) {
380
+
381
+            switch($property) {
382
+                case '{DAV:}displayname' :
383
+                    $values['displayname'] = $newValue;
384
+                    break;
385
+                case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
386
+                    $values['description'] = $newValue;
387
+                    break;
388
+                default :
389
+                    throw new BadRequest('Unknown property: ' . $property);
390
+            }
391
+
392
+        }
393
+
394
+        // Fallback to make sure the displayname is set. Some clients may refuse
395
+        // to work with addressbooks not having a displayname.
396
+        if(is_null($values['displayname'])) {
397
+            $values['displayname'] = $url;
398
+        }
399
+
400
+        $query = $this->db->getQueryBuilder();
401
+        $query->insert('addressbooks')
402
+            ->values([
403
+                'uri' => $query->createParameter('uri'),
404
+                'displayname' => $query->createParameter('displayname'),
405
+                'description' => $query->createParameter('description'),
406
+                'principaluri' => $query->createParameter('principaluri'),
407
+                'synctoken' => $query->createParameter('synctoken'),
408
+            ])
409
+            ->setParameters($values)
410
+            ->execute();
411
+
412
+        return $query->getLastInsertId();
413
+    }
414
+
415
+    /**
416
+     * Deletes an entire addressbook and all its contents
417
+     *
418
+     * @param mixed $addressBookId
419
+     * @return void
420
+     */
421
+    function deleteAddressBook($addressBookId) {
422
+        $query = $this->db->getQueryBuilder();
423
+        $query->delete('cards')
424
+            ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
425
+            ->setParameter('addressbookid', $addressBookId)
426
+            ->execute();
427
+
428
+        $query->delete('addressbookchanges')
429
+            ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
430
+            ->setParameter('addressbookid', $addressBookId)
431
+            ->execute();
432
+
433
+        $query->delete('addressbooks')
434
+            ->where($query->expr()->eq('id', $query->createParameter('id')))
435
+            ->setParameter('id', $addressBookId)
436
+            ->execute();
437
+
438
+        $this->sharingBackend->deleteAllShares($addressBookId);
439
+
440
+        $query->delete($this->dbCardsPropertiesTable)
441
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
442
+            ->execute();
443
+
444
+    }
445
+
446
+    /**
447
+     * Returns all cards for a specific addressbook id.
448
+     *
449
+     * This method should return the following properties for each card:
450
+     *   * carddata - raw vcard data
451
+     *   * uri - Some unique url
452
+     *   * lastmodified - A unix timestamp
453
+     *
454
+     * It's recommended to also return the following properties:
455
+     *   * etag - A unique etag. This must change every time the card changes.
456
+     *   * size - The size of the card in bytes.
457
+     *
458
+     * If these last two properties are provided, less time will be spent
459
+     * calculating them. If they are specified, you can also ommit carddata.
460
+     * This may speed up certain requests, especially with large cards.
461
+     *
462
+     * @param mixed $addressBookId
463
+     * @return array
464
+     */
465
+    function getCards($addressBookId) {
466
+        $query = $this->db->getQueryBuilder();
467
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
468
+            ->from('cards')
469
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
470
+
471
+        $cards = [];
472
+
473
+        $result = $query->execute();
474
+        while($row = $result->fetch()) {
475
+            $row['etag'] = '"' . $row['etag'] . '"';
476
+            $row['carddata'] = $this->readBlob($row['carddata']);
477
+            $cards[] = $row;
478
+        }
479
+        $result->closeCursor();
480
+
481
+        return $cards;
482
+    }
483
+
484
+    /**
485
+     * Returns a specific card.
486
+     *
487
+     * The same set of properties must be returned as with getCards. The only
488
+     * exception is that 'carddata' is absolutely required.
489
+     *
490
+     * If the card does not exist, you must return false.
491
+     *
492
+     * @param mixed $addressBookId
493
+     * @param string $cardUri
494
+     * @return array
495
+     */
496
+    function getCard($addressBookId, $cardUri) {
497
+        $query = $this->db->getQueryBuilder();
498
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
499
+            ->from('cards')
500
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
501
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
502
+            ->setMaxResults(1);
503
+
504
+        $result = $query->execute();
505
+        $row = $result->fetch();
506
+        if (!$row) {
507
+            return false;
508
+        }
509
+        $row['etag'] = '"' . $row['etag'] . '"';
510
+        $row['carddata'] = $this->readBlob($row['carddata']);
511
+
512
+        return $row;
513
+    }
514
+
515
+    /**
516
+     * Returns a list of cards.
517
+     *
518
+     * This method should work identical to getCard, but instead return all the
519
+     * cards in the list as an array.
520
+     *
521
+     * If the backend supports this, it may allow for some speed-ups.
522
+     *
523
+     * @param mixed $addressBookId
524
+     * @param string[] $uris
525
+     * @return array
526
+     */
527
+    function getMultipleCards($addressBookId, array $uris) {
528
+        if (empty($uris)) {
529
+            return [];
530
+        }
531
+
532
+        $chunks = array_chunk($uris, 100);
533
+        $cards = [];
534
+
535
+        $query = $this->db->getQueryBuilder();
536
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
537
+            ->from('cards')
538
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
539
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
540
+
541
+        foreach ($chunks as $uris) {
542
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
543
+            $result = $query->execute();
544
+
545
+            while ($row = $result->fetch()) {
546
+                $row['etag'] = '"' . $row['etag'] . '"';
547
+                $row['carddata'] = $this->readBlob($row['carddata']);
548
+                $cards[] = $row;
549
+            }
550
+            $result->closeCursor();
551
+        }
552
+        return $cards;
553
+    }
554
+
555
+    /**
556
+     * Creates a new card.
557
+     *
558
+     * The addressbook id will be passed as the first argument. This is the
559
+     * same id as it is returned from the getAddressBooksForUser method.
560
+     *
561
+     * The cardUri is a base uri, and doesn't include the full path. The
562
+     * cardData argument is the vcard body, and is passed as a string.
563
+     *
564
+     * It is possible to return an ETag from this method. This ETag is for the
565
+     * newly created resource, and must be enclosed with double quotes (that
566
+     * is, the string itself must contain the double quotes).
567
+     *
568
+     * You should only return the ETag if you store the carddata as-is. If a
569
+     * subsequent GET request on the same card does not have the same body,
570
+     * byte-by-byte and you did return an ETag here, clients tend to get
571
+     * confused.
572
+     *
573
+     * If you don't return an ETag, you can just return null.
574
+     *
575
+     * @param mixed $addressBookId
576
+     * @param string $cardUri
577
+     * @param string $cardData
578
+     * @return string
579
+     */
580
+    function createCard($addressBookId, $cardUri, $cardData) {
581
+        $etag = md5($cardData);
582
+
583
+        $query = $this->db->getQueryBuilder();
584
+        $query->insert('cards')
585
+            ->values([
586
+                'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
587
+                'uri' => $query->createNamedParameter($cardUri),
588
+                'lastmodified' => $query->createNamedParameter(time()),
589
+                'addressbookid' => $query->createNamedParameter($addressBookId),
590
+                'size' => $query->createNamedParameter(strlen($cardData)),
591
+                'etag' => $query->createNamedParameter($etag),
592
+            ])
593
+            ->execute();
594
+
595
+        $this->addChange($addressBookId, $cardUri, 1);
596
+        $this->updateProperties($addressBookId, $cardUri, $cardData);
597
+
598
+        if (!is_null($this->dispatcher)) {
599
+            $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
600
+                new GenericEvent(null, [
601
+                    'addressBookId' => $addressBookId,
602
+                    'cardUri' => $cardUri,
603
+                    'cardData' => $cardData]));
604
+        }
605
+
606
+        return '"' . $etag . '"';
607
+    }
608
+
609
+    /**
610
+     * Updates a card.
611
+     *
612
+     * The addressbook id will be passed as the first argument. This is the
613
+     * same id as it is returned from the getAddressBooksForUser method.
614
+     *
615
+     * The cardUri is a base uri, and doesn't include the full path. The
616
+     * cardData argument is the vcard body, and is passed as a string.
617
+     *
618
+     * It is possible to return an ETag from this method. This ETag should
619
+     * match that of the updated resource, and must be enclosed with double
620
+     * quotes (that is: the string itself must contain the actual quotes).
621
+     *
622
+     * You should only return the ETag if you store the carddata as-is. If a
623
+     * subsequent GET request on the same card does not have the same body,
624
+     * byte-by-byte and you did return an ETag here, clients tend to get
625
+     * confused.
626
+     *
627
+     * If you don't return an ETag, you can just return null.
628
+     *
629
+     * @param mixed $addressBookId
630
+     * @param string $cardUri
631
+     * @param string $cardData
632
+     * @return string
633
+     */
634
+    function updateCard($addressBookId, $cardUri, $cardData) {
635
+
636
+        $etag = md5($cardData);
637
+        $query = $this->db->getQueryBuilder();
638
+        $query->update('cards')
639
+            ->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
640
+            ->set('lastmodified', $query->createNamedParameter(time()))
641
+            ->set('size', $query->createNamedParameter(strlen($cardData)))
642
+            ->set('etag', $query->createNamedParameter($etag))
643
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
644
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
645
+            ->execute();
646
+
647
+        $this->addChange($addressBookId, $cardUri, 2);
648
+        $this->updateProperties($addressBookId, $cardUri, $cardData);
649
+
650
+        if (!is_null($this->dispatcher)) {
651
+            $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
652
+                new GenericEvent(null, [
653
+                    'addressBookId' => $addressBookId,
654
+                    'cardUri' => $cardUri,
655
+                    'cardData' => $cardData]));
656
+        }
657
+
658
+        return '"' . $etag . '"';
659
+    }
660
+
661
+    /**
662
+     * Deletes a card
663
+     *
664
+     * @param mixed $addressBookId
665
+     * @param string $cardUri
666
+     * @return bool
667
+     */
668
+    function deleteCard($addressBookId, $cardUri) {
669
+        try {
670
+            $cardId = $this->getCardId($addressBookId, $cardUri);
671
+        } catch (\InvalidArgumentException $e) {
672
+            $cardId = null;
673
+        }
674
+        $query = $this->db->getQueryBuilder();
675
+        $ret = $query->delete('cards')
676
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
677
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
678
+            ->execute();
679
+
680
+        $this->addChange($addressBookId, $cardUri, 3);
681
+
682
+        if (!is_null($this->dispatcher)) {
683
+            $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
684
+                new GenericEvent(null, [
685
+                    'addressBookId' => $addressBookId,
686
+                    'cardUri' => $cardUri]));
687
+        }
688
+
689
+        if ($ret === 1) {
690
+            if ($cardId !== null) {
691
+                $this->purgeProperties($addressBookId, $cardId);
692
+            }
693
+            return true;
694
+        }
695
+
696
+        return false;
697
+    }
698
+
699
+    /**
700
+     * The getChanges method returns all the changes that have happened, since
701
+     * the specified syncToken in the specified address book.
702
+     *
703
+     * This function should return an array, such as the following:
704
+     *
705
+     * [
706
+     *   'syncToken' => 'The current synctoken',
707
+     *   'added'   => [
708
+     *      'new.txt',
709
+     *   ],
710
+     *   'modified'   => [
711
+     *      'modified.txt',
712
+     *   ],
713
+     *   'deleted' => [
714
+     *      'foo.php.bak',
715
+     *      'old.txt'
716
+     *   ]
717
+     * ];
718
+     *
719
+     * The returned syncToken property should reflect the *current* syncToken
720
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
721
+     * property. This is needed here too, to ensure the operation is atomic.
722
+     *
723
+     * If the $syncToken argument is specified as null, this is an initial
724
+     * sync, and all members should be reported.
725
+     *
726
+     * The modified property is an array of nodenames that have changed since
727
+     * the last token.
728
+     *
729
+     * The deleted property is an array with nodenames, that have been deleted
730
+     * from collection.
731
+     *
732
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
733
+     * 1, you only have to report changes that happened only directly in
734
+     * immediate descendants. If it's 2, it should also include changes from
735
+     * the nodes below the child collections. (grandchildren)
736
+     *
737
+     * The $limit argument allows a client to specify how many results should
738
+     * be returned at most. If the limit is not specified, it should be treated
739
+     * as infinite.
740
+     *
741
+     * If the limit (infinite or not) is higher than you're willing to return,
742
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
743
+     *
744
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
745
+     * return null.
746
+     *
747
+     * The limit is 'suggestive'. You are free to ignore it.
748
+     *
749
+     * @param string $addressBookId
750
+     * @param string $syncToken
751
+     * @param int $syncLevel
752
+     * @param int $limit
753
+     * @return array
754
+     */
755
+    function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
756
+        // Current synctoken
757
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
758
+        $stmt->execute([ $addressBookId ]);
759
+        $currentToken = $stmt->fetchColumn(0);
760
+
761
+        if (is_null($currentToken)) return null;
762
+
763
+        $result = [
764
+            'syncToken' => $currentToken,
765
+            'added'     => [],
766
+            'modified'  => [],
767
+            'deleted'   => [],
768
+        ];
769
+
770
+        if ($syncToken) {
771
+
772
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
773
+            if ($limit>0) {
774
+                $query .= " `LIMIT` " . (int)$limit;
775
+            }
776
+
777
+            // Fetching all changes
778
+            $stmt = $this->db->prepare($query);
779
+            $stmt->execute([$syncToken, $currentToken, $addressBookId]);
780
+
781
+            $changes = [];
782
+
783
+            // This loop ensures that any duplicates are overwritten, only the
784
+            // last change on a node is relevant.
785
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
786
+
787
+                $changes[$row['uri']] = $row['operation'];
788
+
789
+            }
790
+
791
+            foreach($changes as $uri => $operation) {
792
+
793
+                switch($operation) {
794
+                    case 1:
795
+                        $result['added'][] = $uri;
796
+                        break;
797
+                    case 2:
798
+                        $result['modified'][] = $uri;
799
+                        break;
800
+                    case 3:
801
+                        $result['deleted'][] = $uri;
802
+                        break;
803
+                }
804
+
805
+            }
806
+        } else {
807
+            // No synctoken supplied, this is the initial sync.
808
+            $query = "SELECT `uri` FROM `*PREFIX*cards` WHERE `addressbookid` = ?";
809
+            $stmt = $this->db->prepare($query);
810
+            $stmt->execute([$addressBookId]);
811
+
812
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
813
+        }
814
+        return $result;
815
+    }
816
+
817
+    /**
818
+     * Adds a change record to the addressbookchanges table.
819
+     *
820
+     * @param mixed $addressBookId
821
+     * @param string $objectUri
822
+     * @param int $operation 1 = add, 2 = modify, 3 = delete
823
+     * @return void
824
+     */
825
+    protected function addChange($addressBookId, $objectUri, $operation) {
826
+        $sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?';
827
+        $stmt = $this->db->prepare($sql);
828
+        $stmt->execute([
829
+            $objectUri,
830
+            $addressBookId,
831
+            $operation,
832
+            $addressBookId
833
+        ]);
834
+        $stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
835
+        $stmt->execute([
836
+            $addressBookId
837
+        ]);
838
+    }
839
+
840
+    private function readBlob($cardData) {
841
+        if (is_resource($cardData)) {
842
+            return stream_get_contents($cardData);
843
+        }
844
+
845
+        return $cardData;
846
+    }
847
+
848
+    /**
849
+     * @param IShareable $shareable
850
+     * @param string[] $add
851
+     * @param string[] $remove
852
+     */
853
+    public function updateShares(IShareable $shareable, $add, $remove) {
854
+        $this->sharingBackend->updateShares($shareable, $add, $remove);
855
+    }
856
+
857
+    /**
858
+     * search contact
859
+     *
860
+     * @param int $addressBookId
861
+     * @param string $pattern which should match within the $searchProperties
862
+     * @param array $searchProperties defines the properties within the query pattern should match
863
+     * @return array an array of contacts which are arrays of key-value-pairs
864
+     */
865
+    public function search($addressBookId, $pattern, $searchProperties) {
866
+        $query = $this->db->getQueryBuilder();
867
+        $query2 = $this->db->getQueryBuilder();
868
+        $query2->selectDistinct('cp.cardid')->from($this->dbCardsPropertiesTable, 'cp');
869
+        foreach ($searchProperties as $property) {
870
+            $query2->orWhere(
871
+                $query2->expr()->andX(
872
+                    $query2->expr()->eq('cp.name', $query->createNamedParameter($property)),
873
+                    $query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%'))
874
+                )
875
+            );
876
+        }
877
+        $query2->andWhere($query2->expr()->eq('cp.addressbookid', $query->createNamedParameter($addressBookId)));
878
+
879
+        $query->select('c.carddata', 'c.uri')->from($this->dbCardsTable, 'c')
880
+            ->where($query->expr()->in('c.id', $query->createFunction($query2->getSQL())));
881
+
882
+        $result = $query->execute();
883
+        $cards = $result->fetchAll();
884
+
885
+        $result->closeCursor();
886
+
887
+        return array_map(function($array) {
888
+            $array['carddata'] = $this->readBlob($array['carddata']);
889
+            return $array;
890
+        }, $cards);
891
+    }
892
+
893
+    /**
894
+     * @param int $bookId
895
+     * @param string $name
896
+     * @return array
897
+     */
898
+    public function collectCardProperties($bookId, $name) {
899
+        $query = $this->db->getQueryBuilder();
900
+        $result = $query->selectDistinct('value')
901
+            ->from($this->dbCardsPropertiesTable)
902
+            ->where($query->expr()->eq('name', $query->createNamedParameter($name)))
903
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
904
+            ->execute();
905
+
906
+        $all = $result->fetchAll(PDO::FETCH_COLUMN);
907
+        $result->closeCursor();
908
+
909
+        return $all;
910
+    }
911
+
912
+    /**
913
+     * get URI from a given contact
914
+     *
915
+     * @param int $id
916
+     * @return string
917
+     */
918
+    public function getCardUri($id) {
919
+        $query = $this->db->getQueryBuilder();
920
+        $query->select('uri')->from($this->dbCardsTable)
921
+                ->where($query->expr()->eq('id', $query->createParameter('id')))
922
+                ->setParameter('id', $id);
923
+
924
+        $result = $query->execute();
925
+        $uri = $result->fetch();
926
+        $result->closeCursor();
927
+
928
+        if (!isset($uri['uri'])) {
929
+            throw new \InvalidArgumentException('Card does not exists: ' . $id);
930
+        }
931
+
932
+        return $uri['uri'];
933
+    }
934
+
935
+    /**
936
+     * return contact with the given URI
937
+     *
938
+     * @param int $addressBookId
939
+     * @param string $uri
940
+     * @returns array
941
+     */
942
+    public function getContact($addressBookId, $uri) {
943
+        $result = [];
944
+        $query = $this->db->getQueryBuilder();
945
+        $query->select('*')->from($this->dbCardsTable)
946
+                ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
947
+                ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
948
+        $queryResult = $query->execute();
949
+        $contact = $queryResult->fetch();
950
+        $queryResult->closeCursor();
951
+
952
+        if (is_array($contact)) {
953
+            $result = $contact;
954
+        }
955
+
956
+        return $result;
957
+    }
958
+
959
+    /**
960
+     * Returns the list of people whom this address book is shared with.
961
+     *
962
+     * Every element in this array should have the following properties:
963
+     *   * href - Often a mailto: address
964
+     *   * commonName - Optional, for example a first + last name
965
+     *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
966
+     *   * readOnly - boolean
967
+     *   * summary - Optional, a description for the share
968
+     *
969
+     * @return array
970
+     */
971
+    public function getShares($addressBookId) {
972
+        return $this->sharingBackend->getShares($addressBookId);
973
+    }
974
+
975
+    /**
976
+     * update properties table
977
+     *
978
+     * @param int $addressBookId
979
+     * @param string $cardUri
980
+     * @param string $vCardSerialized
981
+     */
982
+    protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
983
+        $cardId = $this->getCardId($addressBookId, $cardUri);
984
+        $vCard = $this->readCard($vCardSerialized);
985
+
986
+        $this->purgeProperties($addressBookId, $cardId);
987
+
988
+        $query = $this->db->getQueryBuilder();
989
+        $query->insert($this->dbCardsPropertiesTable)
990
+            ->values(
991
+                [
992
+                    'addressbookid' => $query->createNamedParameter($addressBookId),
993
+                    'cardid' => $query->createNamedParameter($cardId),
994
+                    'name' => $query->createParameter('name'),
995
+                    'value' => $query->createParameter('value'),
996
+                    'preferred' => $query->createParameter('preferred')
997
+                ]
998
+            );
999
+
1000
+        foreach ($vCard->children() as $property) {
1001
+            if(!in_array($property->name, self::$indexProperties)) {
1002
+                continue;
1003
+            }
1004
+            $preferred = 0;
1005
+            foreach($property->parameters as $parameter) {
1006
+                if ($parameter->name == 'TYPE' && strtoupper($parameter->getValue()) == 'PREF') {
1007
+                    $preferred = 1;
1008
+                    break;
1009
+                }
1010
+            }
1011
+            $query->setParameter('name', $property->name);
1012
+            $query->setParameter('value', substr($property->getValue(), 0, 254));
1013
+            $query->setParameter('preferred', $preferred);
1014
+            $query->execute();
1015
+        }
1016
+    }
1017
+
1018
+    /**
1019
+     * read vCard data into a vCard object
1020
+     *
1021
+     * @param string $cardData
1022
+     * @return VCard
1023
+     */
1024
+    protected function readCard($cardData) {
1025
+        return  Reader::read($cardData);
1026
+    }
1027
+
1028
+    /**
1029
+     * delete all properties from a given card
1030
+     *
1031
+     * @param int $addressBookId
1032
+     * @param int $cardId
1033
+     */
1034
+    protected function purgeProperties($addressBookId, $cardId) {
1035
+        $query = $this->db->getQueryBuilder();
1036
+        $query->delete($this->dbCardsPropertiesTable)
1037
+            ->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
1038
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1039
+        $query->execute();
1040
+    }
1041
+
1042
+    /**
1043
+     * get ID from a given contact
1044
+     *
1045
+     * @param int $addressBookId
1046
+     * @param string $uri
1047
+     * @return int
1048
+     */
1049
+    protected function getCardId($addressBookId, $uri) {
1050
+        $query = $this->db->getQueryBuilder();
1051
+        $query->select('id')->from($this->dbCardsTable)
1052
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1053
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1054
+
1055
+        $result = $query->execute();
1056
+        $cardIds = $result->fetch();
1057
+        $result->closeCursor();
1058
+
1059
+        if (!isset($cardIds['id'])) {
1060
+            throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1061
+        }
1062
+
1063
+        return (int)$cardIds['id'];
1064
+    }
1065
+
1066
+    /**
1067
+     * For shared address books the sharee is set in the ACL of the address book
1068
+     * @param $addressBookId
1069
+     * @param $acl
1070
+     * @return array
1071
+     */
1072
+    public function applyShareAcl($addressBookId, $acl) {
1073
+        return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1074
+    }
1075
+
1076
+    private function convertPrincipal($principalUri, $toV2) {
1077
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1078
+            list(, $name) = URLUtil::splitPath($principalUri);
1079
+            if ($toV2 === true) {
1080
+                return "principals/users/$name";
1081
+            }
1082
+            return "principals/$name";
1083
+        }
1084
+        return $principalUri;
1085
+    }
1086 1086
 }
Please login to merge, or discard this patch.
Spacing   +47 added lines, -47 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,22 +145,22 @@  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
 		$result->closeCursor();
160 160
 
161 161
 		// query for shared calendars
162 162
 		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
163
-		$principals[]= $principalUri;
163
+		$principals[] = $principalUri;
164 164
 
165 165
 		$query = $this->db->getQueryBuilder();
166 166
 		$result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
@@ -172,8 +172,8 @@  discard block
 block discarded – undo
172 172
 			->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
173 173
 			->execute();
174 174
 
175
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
176
-		while($row = $result->fetch()) {
175
+		$readOnlyPropertyName = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only';
176
+		while ($row = $result->fetch()) {
177 177
 			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
178 178
 			if (isset($addressBooks[$row['id']])) {
179 179
 				if ($readOnly) {
@@ -188,18 +188,18 @@  discard block
 block discarded – undo
188 188
 			}
189 189
 
190 190
 			list(, $name) = URLUtil::splitPath($row['principaluri']);
191
-			$uri = $row['uri'] . '_shared_by_' . $name;
192
-			$displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
191
+			$uri = $row['uri'].'_shared_by_'.$name;
192
+			$displayName = $row['displayname'].' ('.$this->getUserDisplayName($name).')';
193 193
 
194 194
 			$addressBooks[$row['id']] = [
195 195
 				'id'  => $row['id'],
196 196
 				'uri' => $uri,
197 197
 				'principaluri' => $principalUriOriginal,
198 198
 				'{DAV:}displayname' => $displayName,
199
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
199
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
200 200
 				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
201
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
202
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
201
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
202
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $row['principaluri'],
203 203
 				$readOnlyPropertyName => $readOnly,
204 204
 			];
205 205
 		}
@@ -219,15 +219,15 @@  discard block
 block discarded – undo
219 219
 		$addressBooks = [];
220 220
 
221 221
 		$result = $query->execute();
222
-		while($row = $result->fetch()) {
222
+		while ($row = $result->fetch()) {
223 223
 			$addressBooks[$row['id']] = [
224 224
 				'id'  => $row['id'],
225 225
 				'uri' => $row['uri'],
226 226
 				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
227 227
 				'{DAV:}displayname' => $row['displayname'],
228
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
228
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
229 229
 				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
230
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
230
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
231 231
 			];
232 232
 		}
233 233
 		$result->closeCursor();
@@ -270,9 +270,9 @@  discard block
 block discarded – undo
270 270
 			'uri' => $row['uri'],
271 271
 			'principaluri' => $row['principaluri'],
272 272
 			'{DAV:}displayname' => $row['displayname'],
273
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
273
+			'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
274 274
 			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
275
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
275
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
276 276
 		];
277 277
 	}
278 278
 
@@ -300,9 +300,9 @@  discard block
 block discarded – undo
300 300
 				'uri' => $row['uri'],
301 301
 				'principaluri' => $row['principaluri'],
302 302
 				'{DAV:}displayname' => $row['displayname'],
303
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
303
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
304 304
 				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
305
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
305
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
306 306
 			];
307 307
 	}
308 308
 
@@ -325,19 +325,19 @@  discard block
 block discarded – undo
325 325
 	function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
326 326
 		$supportedProperties = [
327 327
 			'{DAV:}displayname',
328
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description',
328
+			'{'.Plugin::NS_CARDDAV.'}addressbook-description',
329 329
 		];
330 330
 
331 331
 		$propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
332 332
 
333 333
 			$updates = [];
334
-			foreach($mutations as $property=>$newValue) {
334
+			foreach ($mutations as $property=>$newValue) {
335 335
 
336
-				switch($property) {
336
+				switch ($property) {
337 337
 					case '{DAV:}displayname' :
338 338
 						$updates['displayname'] = $newValue;
339 339
 						break;
340
-					case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
340
+					case '{'.Plugin::NS_CARDDAV.'}addressbook-description' :
341 341
 						$updates['description'] = $newValue;
342 342
 						break;
343 343
 				}
@@ -345,7 +345,7 @@  discard block
 block discarded – undo
345 345
 			$query = $this->db->getQueryBuilder();
346 346
 			$query->update('addressbooks');
347 347
 
348
-			foreach($updates as $key=>$value) {
348
+			foreach ($updates as $key=>$value) {
349 349
 				$query->set($key, $query->createNamedParameter($value));
350 350
 			}
351 351
 			$query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
@@ -376,24 +376,24 @@  discard block
 block discarded – undo
376 376
 			'synctoken' => 1
377 377
 		];
378 378
 
379
-		foreach($properties as $property=>$newValue) {
379
+		foreach ($properties as $property=>$newValue) {
380 380
 
381
-			switch($property) {
381
+			switch ($property) {
382 382
 				case '{DAV:}displayname' :
383 383
 					$values['displayname'] = $newValue;
384 384
 					break;
385
-				case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
385
+				case '{'.Plugin::NS_CARDDAV.'}addressbook-description' :
386 386
 					$values['description'] = $newValue;
387 387
 					break;
388 388
 				default :
389
-					throw new BadRequest('Unknown property: ' . $property);
389
+					throw new BadRequest('Unknown property: '.$property);
390 390
 			}
391 391
 
392 392
 		}
393 393
 
394 394
 		// Fallback to make sure the displayname is set. Some clients may refuse
395 395
 		// to work with addressbooks not having a displayname.
396
-		if(is_null($values['displayname'])) {
396
+		if (is_null($values['displayname'])) {
397 397
 			$values['displayname'] = $url;
398 398
 		}
399 399
 
@@ -471,8 +471,8 @@  discard block
 block discarded – undo
471 471
 		$cards = [];
472 472
 
473 473
 		$result = $query->execute();
474
-		while($row = $result->fetch()) {
475
-			$row['etag'] = '"' . $row['etag'] . '"';
474
+		while ($row = $result->fetch()) {
475
+			$row['etag'] = '"'.$row['etag'].'"';
476 476
 			$row['carddata'] = $this->readBlob($row['carddata']);
477 477
 			$cards[] = $row;
478 478
 		}
@@ -506,7 +506,7 @@  discard block
 block discarded – undo
506 506
 		if (!$row) {
507 507
 			return false;
508 508
 		}
509
-		$row['etag'] = '"' . $row['etag'] . '"';
509
+		$row['etag'] = '"'.$row['etag'].'"';
510 510
 		$row['carddata'] = $this->readBlob($row['carddata']);
511 511
 
512 512
 		return $row;
@@ -543,7 +543,7 @@  discard block
 block discarded – undo
543 543
 			$result = $query->execute();
544 544
 
545 545
 			while ($row = $result->fetch()) {
546
-				$row['etag'] = '"' . $row['etag'] . '"';
546
+				$row['etag'] = '"'.$row['etag'].'"';
547 547
 				$row['carddata'] = $this->readBlob($row['carddata']);
548 548
 				$cards[] = $row;
549 549
 			}
@@ -603,7 +603,7 @@  discard block
 block discarded – undo
603 603
 					'cardData' => $cardData]));
604 604
 		}
605 605
 
606
-		return '"' . $etag . '"';
606
+		return '"'.$etag.'"';
607 607
 	}
608 608
 
609 609
 	/**
@@ -655,7 +655,7 @@  discard block
 block discarded – undo
655 655
 					'cardData' => $cardData]));
656 656
 		}
657 657
 
658
-		return '"' . $etag . '"';
658
+		return '"'.$etag.'"';
659 659
 	}
660 660
 
661 661
 	/**
@@ -755,7 +755,7 @@  discard block
 block discarded – undo
755 755
 	function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
756 756
 		// Current synctoken
757 757
 		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
758
-		$stmt->execute([ $addressBookId ]);
758
+		$stmt->execute([$addressBookId]);
759 759
 		$currentToken = $stmt->fetchColumn(0);
760 760
 
761 761
 		if (is_null($currentToken)) return null;
@@ -770,8 +770,8 @@  discard block
 block discarded – undo
770 770
 		if ($syncToken) {
771 771
 
772 772
 			$query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
773
-			if ($limit>0) {
774
-				$query .= " `LIMIT` " . (int)$limit;
773
+			if ($limit > 0) {
774
+				$query .= " `LIMIT` ".(int) $limit;
775 775
 			}
776 776
 
777 777
 			// Fetching all changes
@@ -782,15 +782,15 @@  discard block
 block discarded – undo
782 782
 
783 783
 			// This loop ensures that any duplicates are overwritten, only the
784 784
 			// last change on a node is relevant.
785
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
785
+			while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
786 786
 
787 787
 				$changes[$row['uri']] = $row['operation'];
788 788
 
789 789
 			}
790 790
 
791
-			foreach($changes as $uri => $operation) {
791
+			foreach ($changes as $uri => $operation) {
792 792
 
793
-				switch($operation) {
793
+				switch ($operation) {
794 794
 					case 1:
795 795
 						$result['added'][] = $uri;
796 796
 						break;
@@ -870,7 +870,7 @@  discard block
 block discarded – undo
870 870
 			$query2->orWhere(
871 871
 				$query2->expr()->andX(
872 872
 					$query2->expr()->eq('cp.name', $query->createNamedParameter($property)),
873
-					$query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%'))
873
+					$query2->expr()->ilike('cp.value', $query->createNamedParameter('%'.$this->db->escapeLikeParameter($pattern).'%'))
874 874
 				)
875 875
 			);
876 876
 		}
@@ -926,7 +926,7 @@  discard block
 block discarded – undo
926 926
 		$result->closeCursor();
927 927
 
928 928
 		if (!isset($uri['uri'])) {
929
-			throw new \InvalidArgumentException('Card does not exists: ' . $id);
929
+			throw new \InvalidArgumentException('Card does not exists: '.$id);
930 930
 		}
931 931
 
932 932
 		return $uri['uri'];
@@ -998,11 +998,11 @@  discard block
 block discarded – undo
998 998
 			);
999 999
 
1000 1000
 		foreach ($vCard->children() as $property) {
1001
-			if(!in_array($property->name, self::$indexProperties)) {
1001
+			if (!in_array($property->name, self::$indexProperties)) {
1002 1002
 				continue;
1003 1003
 			}
1004 1004
 			$preferred = 0;
1005
-			foreach($property->parameters as $parameter) {
1005
+			foreach ($property->parameters as $parameter) {
1006 1006
 				if ($parameter->name == 'TYPE' && strtoupper($parameter->getValue()) == 'PREF') {
1007 1007
 					$preferred = 1;
1008 1008
 					break;
@@ -1057,10 +1057,10 @@  discard block
 block discarded – undo
1057 1057
 		$result->closeCursor();
1058 1058
 
1059 1059
 		if (!isset($cardIds['id'])) {
1060
-			throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1060
+			throw new \InvalidArgumentException('Card does not exists: '.$uri);
1061 1061
 		}
1062 1062
 
1063
-		return (int)$cardIds['id'];
1063
+		return (int) $cardIds['id'];
1064 1064
 	}
1065 1065
 
1066 1066
 	/**
Please login to merge, or discard this patch.
apps/files/lib/Controller/ViewController.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -35,7 +35,6 @@
 block discarded – undo
35 35
 use OCP\Files\NotFoundException;
36 36
 use OCP\IConfig;
37 37
 use OCP\IL10N;
38
-use OCP\INavigationManager;
39 38
 use OCP\IRequest;
40 39
 use OCP\IURLGenerator;
41 40
 use OCP\IUserSession;
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
 	protected function renderScript($appName, $scriptName) {
110 110
 		$content = '';
111 111
 		$appPath = \OC_App::getAppPath($appName);
112
-		$scriptPath = $appPath . '/' . $scriptName;
112
+		$scriptPath = $appPath.'/'.$scriptName;
113 113
 		if (file_exists($scriptPath)) {
114 114
 			// TODO: sanitize path / script name ?
115 115
 			ob_start();
@@ -226,7 +226,7 @@  discard block
 block discarded – undo
226 226
 		$this->eventDispatcher->dispatch('OCA\Files::loadAdditionalScripts');
227 227
 
228 228
 		$params = [];
229
-		$params['usedSpacePercent'] = (int)$storageInfo['relative'];
229
+		$params['usedSpacePercent'] = (int) $storageInfo['relative'];
230 230
 		$params['owner'] = $storageInfo['owner'];
231 231
 		$params['ownerDisplayName'] = $storageInfo['ownerDisplayName'];
232 232
 		$params['isPublic'] = false;
@@ -266,7 +266,7 @@  discard block
 block discarded – undo
266 266
 		$params = [];
267 267
 
268 268
 		if (empty($files) && $this->appManager->isEnabledForUser('files_trashbin')) {
269
-			$baseFolder = $this->rootFolder->get($uid . '/files_trashbin/files/');
269
+			$baseFolder = $this->rootFolder->get($uid.'/files_trashbin/files/');
270 270
 			$files = $baseFolder->getById($fileId);
271 271
 			$params['view'] = 'trashbin';
272 272
 		}
Please login to merge, or discard this patch.
Indentation   +212 added lines, -212 removed lines patch added patch discarded remove patch
@@ -49,238 +49,238 @@
 block discarded – undo
49 49
  * @package OCA\Files\Controller
50 50
  */
51 51
 class ViewController extends Controller {
52
-	/** @var string */
53
-	protected $appName;
54
-	/** @var IRequest */
55
-	protected $request;
56
-	/** @var IURLGenerator */
57
-	protected $urlGenerator;
58
-	/** @var IL10N */
59
-	protected $l10n;
60
-	/** @var IConfig */
61
-	protected $config;
62
-	/** @var EventDispatcherInterface */
63
-	protected $eventDispatcher;
64
-	/** @var IUserSession */
65
-	protected $userSession;
66
-	/** @var IAppManager */
67
-	protected $appManager;
68
-	/** @var IRootFolder */
69
-	protected $rootFolder;
52
+    /** @var string */
53
+    protected $appName;
54
+    /** @var IRequest */
55
+    protected $request;
56
+    /** @var IURLGenerator */
57
+    protected $urlGenerator;
58
+    /** @var IL10N */
59
+    protected $l10n;
60
+    /** @var IConfig */
61
+    protected $config;
62
+    /** @var EventDispatcherInterface */
63
+    protected $eventDispatcher;
64
+    /** @var IUserSession */
65
+    protected $userSession;
66
+    /** @var IAppManager */
67
+    protected $appManager;
68
+    /** @var IRootFolder */
69
+    protected $rootFolder;
70 70
 
71
-	/**
72
-	 * @param string $appName
73
-	 * @param IRequest $request
74
-	 * @param IURLGenerator $urlGenerator
75
-	 * @param IL10N $l10n
76
-	 * @param IConfig $config
77
-	 * @param EventDispatcherInterface $eventDispatcherInterface
78
-	 * @param IUserSession $userSession
79
-	 * @param IAppManager $appManager
80
-	 * @param IRootFolder $rootFolder
81
-	 */
82
-	public function __construct($appName,
83
-								IRequest $request,
84
-								IURLGenerator $urlGenerator,
85
-								IL10N $l10n,
86
-								IConfig $config,
87
-								EventDispatcherInterface $eventDispatcherInterface,
88
-								IUserSession $userSession,
89
-								IAppManager $appManager,
90
-								IRootFolder $rootFolder
91
-	) {
92
-		parent::__construct($appName, $request);
93
-		$this->appName = $appName;
94
-		$this->request = $request;
95
-		$this->urlGenerator = $urlGenerator;
96
-		$this->l10n = $l10n;
97
-		$this->config = $config;
98
-		$this->eventDispatcher = $eventDispatcherInterface;
99
-		$this->userSession = $userSession;
100
-		$this->appManager = $appManager;
101
-		$this->rootFolder = $rootFolder;
102
-	}
71
+    /**
72
+     * @param string $appName
73
+     * @param IRequest $request
74
+     * @param IURLGenerator $urlGenerator
75
+     * @param IL10N $l10n
76
+     * @param IConfig $config
77
+     * @param EventDispatcherInterface $eventDispatcherInterface
78
+     * @param IUserSession $userSession
79
+     * @param IAppManager $appManager
80
+     * @param IRootFolder $rootFolder
81
+     */
82
+    public function __construct($appName,
83
+                                IRequest $request,
84
+                                IURLGenerator $urlGenerator,
85
+                                IL10N $l10n,
86
+                                IConfig $config,
87
+                                EventDispatcherInterface $eventDispatcherInterface,
88
+                                IUserSession $userSession,
89
+                                IAppManager $appManager,
90
+                                IRootFolder $rootFolder
91
+    ) {
92
+        parent::__construct($appName, $request);
93
+        $this->appName = $appName;
94
+        $this->request = $request;
95
+        $this->urlGenerator = $urlGenerator;
96
+        $this->l10n = $l10n;
97
+        $this->config = $config;
98
+        $this->eventDispatcher = $eventDispatcherInterface;
99
+        $this->userSession = $userSession;
100
+        $this->appManager = $appManager;
101
+        $this->rootFolder = $rootFolder;
102
+    }
103 103
 
104
-	/**
105
-	 * @param string $appName
106
-	 * @param string $scriptName
107
-	 * @return string
108
-	 */
109
-	protected function renderScript($appName, $scriptName) {
110
-		$content = '';
111
-		$appPath = \OC_App::getAppPath($appName);
112
-		$scriptPath = $appPath . '/' . $scriptName;
113
-		if (file_exists($scriptPath)) {
114
-			// TODO: sanitize path / script name ?
115
-			ob_start();
116
-			include $scriptPath;
117
-			$content = ob_get_contents();
118
-			@ob_end_clean();
119
-		}
120
-		return $content;
121
-	}
104
+    /**
105
+     * @param string $appName
106
+     * @param string $scriptName
107
+     * @return string
108
+     */
109
+    protected function renderScript($appName, $scriptName) {
110
+        $content = '';
111
+        $appPath = \OC_App::getAppPath($appName);
112
+        $scriptPath = $appPath . '/' . $scriptName;
113
+        if (file_exists($scriptPath)) {
114
+            // TODO: sanitize path / script name ?
115
+            ob_start();
116
+            include $scriptPath;
117
+            $content = ob_get_contents();
118
+            @ob_end_clean();
119
+        }
120
+        return $content;
121
+    }
122 122
 
123
-	/**
124
-	 * FIXME: Replace with non static code
125
-	 *
126
-	 * @return array
127
-	 * @throws \OCP\Files\NotFoundException
128
-	 */
129
-	protected function getStorageInfo() {
130
-		$dirInfo = \OC\Files\Filesystem::getFileInfo('/', false);
131
-		return \OC_Helper::getStorageInfo('/', $dirInfo);
132
-	}
123
+    /**
124
+     * FIXME: Replace with non static code
125
+     *
126
+     * @return array
127
+     * @throws \OCP\Files\NotFoundException
128
+     */
129
+    protected function getStorageInfo() {
130
+        $dirInfo = \OC\Files\Filesystem::getFileInfo('/', false);
131
+        return \OC_Helper::getStorageInfo('/', $dirInfo);
132
+    }
133 133
 
134
-	/**
135
-	 * @NoCSRFRequired
136
-	 * @NoAdminRequired
137
-	 *
138
-	 * @param string $dir
139
-	 * @param string $view
140
-	 * @param string $fileid
141
-	 * @return TemplateResponse|RedirectResponse
142
-	 */
143
-	public function index($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
144
-		if ($fileid !== null) {
145
-			try {
146
-				return $this->showFile($fileid);
147
-			} catch (NotFoundException $e) {
148
-				return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', ['fileNotFound' => true]));
149
-			}
150
-		}
134
+    /**
135
+     * @NoCSRFRequired
136
+     * @NoAdminRequired
137
+     *
138
+     * @param string $dir
139
+     * @param string $view
140
+     * @param string $fileid
141
+     * @return TemplateResponse|RedirectResponse
142
+     */
143
+    public function index($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
144
+        if ($fileid !== null) {
145
+            try {
146
+                return $this->showFile($fileid);
147
+            } catch (NotFoundException $e) {
148
+                return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', ['fileNotFound' => true]));
149
+            }
150
+        }
151 151
 
152
-		$nav = new \OCP\Template('files', 'appnavigation', '');
152
+        $nav = new \OCP\Template('files', 'appnavigation', '');
153 153
 
154
-		// Load the files we need
155
-		\OCP\Util::addScript('files', 'app');
156
-		\OCP\Util::addScript('files', 'file-upload');
157
-		\OCP\Util::addScript('files', 'newfilemenu');
158
-		\OCP\Util::addScript('files', 'jquery.fileupload');
159
-		\OCP\Util::addScript('files', 'jquery-visibility');
160
-		\OCP\Util::addScript('files', 'fileinfomodel');
161
-		\OCP\Util::addScript('files', 'filesummary');
162
-		\OCP\Util::addScript('files', 'breadcrumb');
163
-		\OCP\Util::addScript('files', 'filelist');
164
-		\OCP\Util::addScript('files', 'search');
154
+        // Load the files we need
155
+        \OCP\Util::addScript('files', 'app');
156
+        \OCP\Util::addScript('files', 'file-upload');
157
+        \OCP\Util::addScript('files', 'newfilemenu');
158
+        \OCP\Util::addScript('files', 'jquery.fileupload');
159
+        \OCP\Util::addScript('files', 'jquery-visibility');
160
+        \OCP\Util::addScript('files', 'fileinfomodel');
161
+        \OCP\Util::addScript('files', 'filesummary');
162
+        \OCP\Util::addScript('files', 'breadcrumb');
163
+        \OCP\Util::addScript('files', 'filelist');
164
+        \OCP\Util::addScript('files', 'search');
165 165
 
166
-		\OCP\Util::addScript('files', 'favoritesfilelist');
167
-		\OCP\Util::addScript('files', 'recentfilelist');
168
-		\OCP\Util::addScript('files', 'tagsplugin');
169
-		\OCP\Util::addScript('files', 'gotoplugin');
170
-		\OCP\Util::addScript('files', 'favoritesplugin');
171
-		\OCP\Util::addScript('files', 'recentplugin');
166
+        \OCP\Util::addScript('files', 'favoritesfilelist');
167
+        \OCP\Util::addScript('files', 'recentfilelist');
168
+        \OCP\Util::addScript('files', 'tagsplugin');
169
+        \OCP\Util::addScript('files', 'gotoplugin');
170
+        \OCP\Util::addScript('files', 'favoritesplugin');
171
+        \OCP\Util::addScript('files', 'recentplugin');
172 172
 
173
-		\OCP\Util::addScript('files', 'detailfileinfoview');
174
-		\OCP\Util::addScript('files', 'sidebarpreviewmanager');
175
-		\OCP\Util::addScript('files', 'sidebarpreviewtext');
176
-		\OCP\Util::addScript('files', 'detailtabview');
177
-		\OCP\Util::addScript('files', 'mainfileinfodetailview');
178
-		\OCP\Util::addScript('files', 'detailsview');
179
-		\OCP\Util::addStyle('files', 'merged');
173
+        \OCP\Util::addScript('files', 'detailfileinfoview');
174
+        \OCP\Util::addScript('files', 'sidebarpreviewmanager');
175
+        \OCP\Util::addScript('files', 'sidebarpreviewtext');
176
+        \OCP\Util::addScript('files', 'detailtabview');
177
+        \OCP\Util::addScript('files', 'mainfileinfodetailview');
178
+        \OCP\Util::addScript('files', 'detailsview');
179
+        \OCP\Util::addStyle('files', 'merged');
180 180
 
181
-		\OC_Util::addVendorScript('core', 'handlebars/handlebars');
181
+        \OC_Util::addVendorScript('core', 'handlebars/handlebars');
182 182
 
183
-		\OCP\Util::addScript('files', 'fileactions');
184
-		\OCP\Util::addScript('files', 'fileactionsmenu');
185
-		\OCP\Util::addScript('files', 'files');
186
-		\OCP\Util::addScript('files', 'keyboardshortcuts');
187
-		\OCP\Util::addScript('files', 'navigation');
183
+        \OCP\Util::addScript('files', 'fileactions');
184
+        \OCP\Util::addScript('files', 'fileactionsmenu');
185
+        \OCP\Util::addScript('files', 'files');
186
+        \OCP\Util::addScript('files', 'keyboardshortcuts');
187
+        \OCP\Util::addScript('files', 'navigation');
188 188
 
189
-		// mostly for the home storage's free space
190
-		// FIXME: Make non static
191
-		$storageInfo = $this->getStorageInfo();
189
+        // mostly for the home storage's free space
190
+        // FIXME: Make non static
191
+        $storageInfo = $this->getStorageInfo();
192 192
 
193
-		\OCA\Files\App::getNavigationManager()->add(
194
-			[
195
-				'id' => 'favorites',
196
-				'appname' => 'files',
197
-				'script' => 'simplelist.php',
198
-				'order' => 5,
199
-				'name' => $this->l10n->t('Favorites')
200
-			]
201
-		);
193
+        \OCA\Files\App::getNavigationManager()->add(
194
+            [
195
+                'id' => 'favorites',
196
+                'appname' => 'files',
197
+                'script' => 'simplelist.php',
198
+                'order' => 5,
199
+                'name' => $this->l10n->t('Favorites')
200
+            ]
201
+        );
202 202
 
203
-		$navItems = \OCA\Files\App::getNavigationManager()->getAll();
204
-		usort($navItems, function($item1, $item2) {
205
-			return $item1['order'] - $item2['order'];
206
-		});
207
-		$nav->assign('navigationItems', $navItems);
203
+        $navItems = \OCA\Files\App::getNavigationManager()->getAll();
204
+        usort($navItems, function($item1, $item2) {
205
+            return $item1['order'] - $item2['order'];
206
+        });
207
+        $nav->assign('navigationItems', $navItems);
208 208
 
209
-		$contentItems = [];
209
+        $contentItems = [];
210 210
 
211
-		// render the container content for every navigation item
212
-		foreach ($navItems as $item) {
213
-			$content = '';
214
-			if (isset($item['script'])) {
215
-				$content = $this->renderScript($item['appname'], $item['script']);
216
-			}
217
-			$contentItem = [];
218
-			$contentItem['id'] = $item['id'];
219
-			$contentItem['content'] = $content;
220
-			$contentItems[] = $contentItem;
221
-		}
211
+        // render the container content for every navigation item
212
+        foreach ($navItems as $item) {
213
+            $content = '';
214
+            if (isset($item['script'])) {
215
+                $content = $this->renderScript($item['appname'], $item['script']);
216
+            }
217
+            $contentItem = [];
218
+            $contentItem['id'] = $item['id'];
219
+            $contentItem['content'] = $content;
220
+            $contentItems[] = $contentItem;
221
+        }
222 222
 
223
-		$this->eventDispatcher->dispatch('OCA\Files::loadAdditionalScripts');
223
+        $this->eventDispatcher->dispatch('OCA\Files::loadAdditionalScripts');
224 224
 
225
-		$params = [];
226
-		$params['usedSpacePercent'] = (int)$storageInfo['relative'];
227
-		$params['owner'] = $storageInfo['owner'];
228
-		$params['ownerDisplayName'] = $storageInfo['ownerDisplayName'];
229
-		$params['isPublic'] = false;
230
-		$params['allowShareWithLink'] = $this->config->getAppValue('core', 'shareapi_allow_links', 'yes');
231
-		$user = $this->userSession->getUser()->getUID();
232
-		$params['defaultFileSorting'] = $this->config->getUserValue($user, 'files', 'file_sorting', 'name');
233
-		$params['defaultFileSortingDirection'] = $this->config->getUserValue($user, 'files', 'file_sorting_direction', 'asc');
234
-		$showHidden = (bool) $this->config->getUserValue($this->userSession->getUser()->getUID(), 'files', 'show_hidden', false);
235
-		$params['showHiddenFiles'] = $showHidden ? 1 : 0;
236
-		$params['fileNotFound'] = $fileNotFound ? 1 : 0;
237
-		$params['appNavigation'] = $nav;
238
-		$params['appContents'] = $contentItems;
225
+        $params = [];
226
+        $params['usedSpacePercent'] = (int)$storageInfo['relative'];
227
+        $params['owner'] = $storageInfo['owner'];
228
+        $params['ownerDisplayName'] = $storageInfo['ownerDisplayName'];
229
+        $params['isPublic'] = false;
230
+        $params['allowShareWithLink'] = $this->config->getAppValue('core', 'shareapi_allow_links', 'yes');
231
+        $user = $this->userSession->getUser()->getUID();
232
+        $params['defaultFileSorting'] = $this->config->getUserValue($user, 'files', 'file_sorting', 'name');
233
+        $params['defaultFileSortingDirection'] = $this->config->getUserValue($user, 'files', 'file_sorting_direction', 'asc');
234
+        $showHidden = (bool) $this->config->getUserValue($this->userSession->getUser()->getUID(), 'files', 'show_hidden', false);
235
+        $params['showHiddenFiles'] = $showHidden ? 1 : 0;
236
+        $params['fileNotFound'] = $fileNotFound ? 1 : 0;
237
+        $params['appNavigation'] = $nav;
238
+        $params['appContents'] = $contentItems;
239 239
 
240
-		$response = new TemplateResponse(
241
-			$this->appName,
242
-			'index',
243
-			$params
244
-		);
245
-		$policy = new ContentSecurityPolicy();
246
-		$policy->addAllowedFrameDomain('\'self\'');
247
-		$response->setContentSecurityPolicy($policy);
240
+        $response = new TemplateResponse(
241
+            $this->appName,
242
+            'index',
243
+            $params
244
+        );
245
+        $policy = new ContentSecurityPolicy();
246
+        $policy->addAllowedFrameDomain('\'self\'');
247
+        $response->setContentSecurityPolicy($policy);
248 248
 
249
-		return $response;
250
-	}
249
+        return $response;
250
+    }
251 251
 
252
-	/**
253
-	 * Redirects to the file list and highlight the given file id
254
-	 *
255
-	 * @param string $fileId file id to show
256
-	 * @return RedirectResponse redirect response or not found response
257
-	 * @throws \OCP\Files\NotFoundException
258
-	 */
259
-	private function showFile($fileId) {
260
-		$uid = $this->userSession->getUser()->getUID();
261
-		$baseFolder = $this->rootFolder->getUserFolder($uid);
262
-		$files = $baseFolder->getById($fileId);
263
-		$params = [];
252
+    /**
253
+     * Redirects to the file list and highlight the given file id
254
+     *
255
+     * @param string $fileId file id to show
256
+     * @return RedirectResponse redirect response or not found response
257
+     * @throws \OCP\Files\NotFoundException
258
+     */
259
+    private function showFile($fileId) {
260
+        $uid = $this->userSession->getUser()->getUID();
261
+        $baseFolder = $this->rootFolder->getUserFolder($uid);
262
+        $files = $baseFolder->getById($fileId);
263
+        $params = [];
264 264
 
265
-		if (empty($files) && $this->appManager->isEnabledForUser('files_trashbin')) {
266
-			$baseFolder = $this->rootFolder->get($uid . '/files_trashbin/files/');
267
-			$files = $baseFolder->getById($fileId);
268
-			$params['view'] = 'trashbin';
269
-		}
265
+        if (empty($files) && $this->appManager->isEnabledForUser('files_trashbin')) {
266
+            $baseFolder = $this->rootFolder->get($uid . '/files_trashbin/files/');
267
+            $files = $baseFolder->getById($fileId);
268
+            $params['view'] = 'trashbin';
269
+        }
270 270
 
271
-		if (!empty($files)) {
272
-			$file = current($files);
273
-			if ($file instanceof Folder) {
274
-				// set the full path to enter the folder
275
-				$params['dir'] = $baseFolder->getRelativePath($file->getPath());
276
-			} else {
277
-				// set parent path as dir
278
-				$params['dir'] = $baseFolder->getRelativePath($file->getParent()->getPath());
279
-				// and scroll to the entry
280
-				$params['scrollto'] = $file->getName();
281
-			}
282
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', $params));
283
-		}
284
-		throw new \OCP\Files\NotFoundException();
285
-	}
271
+        if (!empty($files)) {
272
+            $file = current($files);
273
+            if ($file instanceof Folder) {
274
+                // set the full path to enter the folder
275
+                $params['dir'] = $baseFolder->getRelativePath($file->getPath());
276
+            } else {
277
+                // set parent path as dir
278
+                $params['dir'] = $baseFolder->getRelativePath($file->getParent()->getPath());
279
+                // and scroll to the entry
280
+                $params['scrollto'] = $file->getName();
281
+            }
282
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', $params));
283
+        }
284
+        throw new \OCP\Files\NotFoundException();
285
+    }
286 286
 }
Please login to merge, or discard this patch.
apps/files/templates/admin.php 2 patches
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -2,17 +2,17 @@
 block discarded – undo
2 2
 
3 3
 	<div class="section">
4 4
 		<h2><?php p($l->t('File handling')); ?></h2>
5
-		<label for="maxUploadSize"><?php p($l->t( 'Maximum upload size' )); ?> </label>
5
+		<label for="maxUploadSize"><?php p($l->t('Maximum upload size')); ?> </label>
6 6
 		<span id="maxUploadSizeSettingsMsg" class="msg"></span>
7 7
 		<br />
8
-		<input type="text" name='maxUploadSize' id="maxUploadSize" value='<?php p($_['uploadMaxFilesize']) ?>' <?php if(!$_['uploadChangable']) { p('disabled'); } ?> />
9
-		<?php if($_['displayMaxPossibleUploadSize']):?>
8
+		<input type="text" name='maxUploadSize' id="maxUploadSize" value='<?php p($_['uploadMaxFilesize']) ?>' <?php if (!$_['uploadChangable']) { p('disabled'); } ?> />
9
+		<?php if ($_['displayMaxPossibleUploadSize']):?>
10 10
 			(<?php p($l->t('max. possible: ')); p($_['maxPossibleUploadSize']) ?>)
11
-		<?php endif;?>
11
+		<?php endif; ?>
12 12
 		<input type="hidden" value="<?php p($_['requesttoken']); ?>" name="requesttoken" />
13
-		<?php if($_['uploadChangable']): ?>
13
+		<?php if ($_['uploadChangable']): ?>
14 14
 			<input type="submit" id="submitMaxUpload"
15
-				   value="<?php p($l->t( 'Save' )); ?>"/>
15
+				   value="<?php p($l->t('Save')); ?>"/>
16 16
 			<p><em><?php p($l->t('With PHP-FPM it might take 5 minutes for changes to be applied.')); ?></em></p>
17 17
 		<?php else: ?>
18 18
 			<p><em><?php p($l->t('Missing permissions to edit from here.')); ?></em></p>
Please login to merge, or discard this patch.
Braces   +5 added lines, -2 removed lines patch added patch discarded remove patch
@@ -14,7 +14,10 @@
 block discarded – undo
14 14
 			<input type="submit" id="submitMaxUpload"
15 15
 				   value="<?php p($l->t( 'Save' )); ?>"/>
16 16
 			<p><em><?php p($l->t('With PHP-FPM it might take 5 minutes for changes to be applied.')); ?></em></p>
17
-		<?php else: ?>
18
-			<p><em><?php p($l->t('Missing permissions to edit from here.')); ?></em></p>
17
+		<?php else {
18
+    : ?>
19
+			<p><em><?php p($l->t('Missing permissions to edit from here.'));
20
+}
21
+?></em></p>
19 22
 		<?php endif; ?>
20 23
 	</div>
Please login to merge, or discard this patch.
apps/files/templates/list.php 1 patch
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -2,7 +2,7 @@  discard block
 block discarded – undo
2 2
 		<div class="actions creatable hidden">
3 3
 			<div id="uploadprogresswrapper">
4 4
 				<div id="uploadprogressbar">
5
-					<em class="label outer" style="display:none"><span class="desktop"><?php p($l->t('Uploading...'));?></span><span class="mobile"><?php p($l->t('...'));?></span></em>
5
+					<em class="label outer" style="display:none"><span class="desktop"><?php p($l->t('Uploading...')); ?></span><span class="mobile"><?php p($l->t('...')); ?></span></em>
6 6
 				</div>
7 7
 				<input type="button" class="stop icon-close" style="display:none" value="" />
8 8
 			</div>
@@ -16,10 +16,10 @@  discard block
 block discarded – undo
16 16
 	*/ ?>
17 17
 	<input type="hidden" name="permissions" value="" id="permissions">
18 18
 	<input type="hidden" id="free_space" value="<?php isset($_['freeSpace']) ? p($_['freeSpace']) : '' ?>">
19
-	<?php if(isset($_['dirToken'])):?>
19
+	<?php if (isset($_['dirToken'])):?>
20 20
 	<input type="hidden" id="publicUploadRequestToken" name="requesttoken" value="<?php p($_['requesttoken']) ?>" />
21 21
 	<input type="hidden" id="dirToken" name="dirToken" value="<?php p($_['dirToken']) ?>" />
22
-	<?php endif;?>
22
+	<?php endif; ?>
23 23
 	<input type="hidden" class="max_human_file_size"
24 24
 		   value="(max <?php isset($_['uploadMaxHumanFilesize']) ? p($_['uploadMaxHumanFilesize']) : ''; ?>)">
25 25
 </div>
@@ -45,7 +45,7 @@  discard block
 block discarded – undo
45 45
 					<label for="select_all_files">
46 46
 						<span class="hidden-visually"><?php p($l->t('Select all'))?></span>
47 47
 					</label>
48
-					<a class="name sort columntitle" data-sort="name"><span><?php p($l->t( 'Name' )); ?></span><span class="sort-indicator"></span></a>
48
+					<a class="name sort columntitle" data-sort="name"><span><?php p($l->t('Name')); ?></span><span class="sort-indicator"></span></a>
49 49
 					<span id="selectedActionsList" class="selectedActions">
50 50
 						<a href="" class="download">
51 51
 							<span class="icon icon-download"></span>
@@ -58,7 +58,7 @@  discard block
 block discarded – undo
58 58
 				<a class="size sort columntitle" data-sort="size"><span><?php p($l->t('Size')); ?></span><span class="sort-indicator"></span></a>
59 59
 			</th>
60 60
 			<th id="headerDate" class="hidden column-mtime">
61
-				<a id="modified" class="columntitle" data-sort="mtime"><span><?php p($l->t( 'Modified' )); ?></span><span class="sort-indicator"></span></a>
61
+				<a id="modified" class="columntitle" data-sort="mtime"><span><?php p($l->t('Modified')); ?></span><span class="sort-indicator"></span></a>
62 62
 					<span class="selectedActions"><a href="" class="delete-selected">
63 63
 						<span><?php p($l->t('Delete'))?></span>
64 64
 						<span class="icon icon-delete"></span>
@@ -78,6 +78,6 @@  discard block
 block discarded – undo
78 78
 <div id="editor"></div><!-- FIXME Do not use this div in your app! It is deprecated and will be removed in the future! -->
79 79
 <div id="uploadsize-message" title="<?php p($l->t('Upload too large'))?>">
80 80
 	<p>
81
-	<?php p($l->t('The files you are trying to upload exceed the maximum size for file uploads on this server.'));?>
81
+	<?php p($l->t('The files you are trying to upload exceed the maximum size for file uploads on this server.')); ?>
82 82
 	</p>
83 83
 </div>
Please login to merge, or discard this patch.
apps/files/templates/simplelist.php 1 patch
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -19,14 +19,14 @@
 block discarded – undo
19 19
 		<tr>
20 20
 			<th id='headerName' class="hidden column-name">
21 21
 				<div id="headerName-container">
22
-					<a class="name sort columntitle" data-sort="name"><span><?php p($l->t( 'Name' )); ?></span><span class="sort-indicator"></span></a>
22
+					<a class="name sort columntitle" data-sort="name"><span><?php p($l->t('Name')); ?></span><span class="sort-indicator"></span></a>
23 23
 				</div>
24 24
 			</th>
25 25
 			<th id="headerSize" class="hidden column-size">
26 26
 				<a class="size sort columntitle" data-sort="size"><span><?php p($l->t('Size')); ?></span><span class="sort-indicator"></span></a>
27 27
 			</th>
28 28
 			<th id="headerDate" class="hidden column-mtime">
29
-				<a id="modified" class="columntitle" data-sort="mtime"><span><?php p($l->t( 'Modified' )); ?></span><span class="sort-indicator"></span></a>
29
+				<a id="modified" class="columntitle" data-sort="mtime"><span><?php p($l->t('Modified')); ?></span><span class="sort-indicator"></span></a>
30 30
 					<span class="selectedActions"><a href="" class="delete-selected">
31 31
 						<?php p($l->t('Delete'))?>
32 32
 						<img class="svg" alt="<?php p($l->t('Delete'))?>"
Please login to merge, or discard this patch.
apps/files/templates/appnavigation.php 1 patch
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -4,7 +4,7 @@  discard block
 block discarded – undo
4 4
 		<li data-id="<?php p($item['id']) ?>" class="nav-<?php p($item['id']) ?>">
5 5
 			<a href="<?php p(isset($item['href']) ? $item['href'] : '#') ?>"
6 6
 				class="nav-icon-<?php p($item['icon'] !== '' ? $item['icon'] : $item['id']) ?> svg">
7
-				<?php p($item['name']);?>
7
+				<?php p($item['name']); ?>
8 8
 			</a>
9 9
 		</li>
10 10
 		<?php } ?>
@@ -12,7 +12,7 @@  discard block
 block discarded – undo
12 12
 	<div id="app-settings">
13 13
 		<div id="app-settings-header">
14 14
 			<button class="settings-button" data-apps-slide-toggle="#app-settings-content">
15
-				<?php p($l->t('Settings'));?>
15
+				<?php p($l->t('Settings')); ?>
16 16
 			</button>
17 17
 		</div>
18 18
 		<div id="app-settings-content">
@@ -20,9 +20,9 @@  discard block
 block discarded – undo
20 20
 				<input class="checkbox" id="showhiddenfilesToggle" checked="checked" type="checkbox">
21 21
 				<label for="showhiddenfilesToggle"><?php p($l->t('Show hidden files')); ?></label>
22 22
 			</div>
23
-			<label for="webdavurl"><?php p($l->t('WebDAV'));?></label>
23
+			<label for="webdavurl"><?php p($l->t('WebDAV')); ?></label>
24 24
 			<input id="webdavurl" type="text" readonly="readonly" value="<?php p(\OCP\Util::linkToRemote('webdav')); ?>" />
25
-			<em><?php print_unescaped($l->t('Use this address to <a href="%s" target="_blank" rel="noreferrer">access your Files via WebDAV</a>', array(link_to_docs('user-webdav'))));?></em>
25
+			<em><?php print_unescaped($l->t('Use this address to <a href="%s" target="_blank" rel="noreferrer">access your Files via WebDAV</a>', array(link_to_docs('user-webdav')))); ?></em>
26 26
 		</div>
27 27
 	</div>
28 28
 </div>
Please login to merge, or discard this patch.
apps/files/ajax/getstoragestats.php 2 patches
Indentation   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -26,7 +26,7 @@  discard block
 block discarded – undo
26 26
 $dir = '/';
27 27
 
28 28
 if (isset($_GET['dir'])) {
29
-	$dir = (string)$_GET['dir'];
29
+    $dir = (string)$_GET['dir'];
30 30
 }
31 31
 
32 32
 OCP\JSON::checkLoggedIn();
@@ -34,7 +34,7 @@  discard block
 block discarded – undo
34 34
 
35 35
 // send back json
36 36
 try {
37
-	OCP\JSON::success(array('data' => \OCA\Files\Helper::buildFileStorageStatistics($dir)));
37
+    OCP\JSON::success(array('data' => \OCA\Files\Helper::buildFileStorageStatistics($dir)));
38 38
 } catch (\OCP\Files\NotFoundException $e) {
39
-	OCP\JSON::error(['data' => ['message' => 'Folder not found']]);
39
+    OCP\JSON::error(['data' => ['message' => 'Folder not found']]);
40 40
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -26,7 +26,7 @@
 block discarded – undo
26 26
 $dir = '/';
27 27
 
28 28
 if (isset($_GET['dir'])) {
29
-	$dir = (string)$_GET['dir'];
29
+	$dir = (string) $_GET['dir'];
30 30
 }
31 31
 
32 32
 OCP\JSON::checkLoggedIn();
Please login to merge, or discard this patch.
apps/files/ajax/list.php 2 patches
Indentation   +57 added lines, -57 removed lines patch added patch discarded remove patch
@@ -32,73 +32,73 @@
 block discarded – undo
32 32
 $dir = \OC\Files\Filesystem::normalizePath($dir);
33 33
 
34 34
 try {
35
-	$dirInfo = \OC\Files\Filesystem::getFileInfo($dir);
36
-	if (!$dirInfo || !$dirInfo->getType() === 'dir') {
37
-		header("HTTP/1.0 404 Not Found");
38
-		exit();
39
-	}
35
+    $dirInfo = \OC\Files\Filesystem::getFileInfo($dir);
36
+    if (!$dirInfo || !$dirInfo->getType() === 'dir') {
37
+        header("HTTP/1.0 404 Not Found");
38
+        exit();
39
+    }
40 40
 
41
-	$data = array();
42
-	$baseUrl = OCP\Util::linkTo('files', 'index.php') . '?dir=';
41
+    $data = array();
42
+    $baseUrl = OCP\Util::linkTo('files', 'index.php') . '?dir=';
43 43
 
44
-	$permissions = $dirInfo->getPermissions();
44
+    $permissions = $dirInfo->getPermissions();
45 45
 
46
-	$sortAttribute = isset($_GET['sort']) ? (string)$_GET['sort'] : 'name';
47
-	$sortDirection = isset($_GET['sortdirection']) ? ($_GET['sortdirection'] === 'desc') : false;
48
-	$mimetypeFilters = isset($_GET['mimetypes']) ? json_decode($_GET['mimetypes']) : '';
46
+    $sortAttribute = isset($_GET['sort']) ? (string)$_GET['sort'] : 'name';
47
+    $sortDirection = isset($_GET['sortdirection']) ? ($_GET['sortdirection'] === 'desc') : false;
48
+    $mimetypeFilters = isset($_GET['mimetypes']) ? json_decode($_GET['mimetypes']) : '';
49 49
 
50
-	$files = [];
51
-	// Clean up duplicates from array
52
-	if (is_array($mimetypeFilters) && count($mimetypeFilters)) {
53
-		$mimetypeFilters = array_unique($mimetypeFilters);
50
+    $files = [];
51
+    // Clean up duplicates from array
52
+    if (is_array($mimetypeFilters) && count($mimetypeFilters)) {
53
+        $mimetypeFilters = array_unique($mimetypeFilters);
54 54
 
55
-		if (!in_array('httpd/unix-directory', $mimetypeFilters)) {
56
-			// append folder filter to be able to browse folders
57
-			$mimetypeFilters[] = 'httpd/unix-directory';
58
-		}
55
+        if (!in_array('httpd/unix-directory', $mimetypeFilters)) {
56
+            // append folder filter to be able to browse folders
57
+            $mimetypeFilters[] = 'httpd/unix-directory';
58
+        }
59 59
 
60
-		// create filelist with mimetype filter - as getFiles only supports on
61
-		// mimetype filter at once we will filter this folder for each
62
-		// mimetypeFilter
63
-		foreach ($mimetypeFilters as $mimetypeFilter) {
64
-			$files = array_merge($files, \OCA\Files\Helper::getFiles($dir, $sortAttribute, $sortDirection, $mimetypeFilter));
65
-		}
60
+        // create filelist with mimetype filter - as getFiles only supports on
61
+        // mimetype filter at once we will filter this folder for each
62
+        // mimetypeFilter
63
+        foreach ($mimetypeFilters as $mimetypeFilter) {
64
+            $files = array_merge($files, \OCA\Files\Helper::getFiles($dir, $sortAttribute, $sortDirection, $mimetypeFilter));
65
+        }
66 66
 
67
-		// sort the files accordingly
68
-		$files = \OCA\Files\Helper::sortFiles($files, $sortAttribute, $sortDirection);
69
-	} else {
70
-		// create file list without mimetype filter
71
-		$files = \OCA\Files\Helper::getFiles($dir, $sortAttribute, $sortDirection);
72
-	}
67
+        // sort the files accordingly
68
+        $files = \OCA\Files\Helper::sortFiles($files, $sortAttribute, $sortDirection);
69
+    } else {
70
+        // create file list without mimetype filter
71
+        $files = \OCA\Files\Helper::getFiles($dir, $sortAttribute, $sortDirection);
72
+    }
73 73
 
74
-	$files = \OCA\Files\Helper::populateTags($files);
75
-	$data['directory'] = $dir;
76
-	$data['files'] = \OCA\Files\Helper::formatFileInfos($files);
77
-	$data['permissions'] = $permissions;
74
+    $files = \OCA\Files\Helper::populateTags($files);
75
+    $data['directory'] = $dir;
76
+    $data['files'] = \OCA\Files\Helper::formatFileInfos($files);
77
+    $data['permissions'] = $permissions;
78 78
 
79
-	OCP\JSON::success(array('data' => $data));
79
+    OCP\JSON::success(array('data' => $data));
80 80
 } catch (\OCP\Files\StorageNotAvailableException $e) {
81
-	\OCP\Util::logException('files', $e);
82
-	OCP\JSON::error([
83
-		'data' => [
84
-			'exception' => '\OCP\Files\StorageNotAvailableException',
85
-			'message' => $l->t('Storage is temporarily not available')
86
-		]
87
-	]);
81
+    \OCP\Util::logException('files', $e);
82
+    OCP\JSON::error([
83
+        'data' => [
84
+            'exception' => '\OCP\Files\StorageNotAvailableException',
85
+            'message' => $l->t('Storage is temporarily not available')
86
+        ]
87
+    ]);
88 88
 } catch (\OCP\Files\StorageInvalidException $e) {
89
-	\OCP\Util::logException('files', $e);
90
-	OCP\JSON::error(array(
91
-		'data' => array(
92
-			'exception' => '\OCP\Files\StorageInvalidException',
93
-			'message' => $l->t('Storage invalid')
94
-		)
95
-	));
89
+    \OCP\Util::logException('files', $e);
90
+    OCP\JSON::error(array(
91
+        'data' => array(
92
+            'exception' => '\OCP\Files\StorageInvalidException',
93
+            'message' => $l->t('Storage invalid')
94
+        )
95
+    ));
96 96
 } catch (\Exception $e) {
97
-	\OCP\Util::logException('files', $e);
98
-	OCP\JSON::error(array(
99
-		'data' => array(
100
-			'exception' => '\Exception',
101
-			'message' => $l->t('Unknown error')
102
-		)
103
-	));
97
+    \OCP\Util::logException('files', $e);
98
+    OCP\JSON::error(array(
99
+        'data' => array(
100
+            'exception' => '\Exception',
101
+            'message' => $l->t('Unknown error')
102
+        )
103
+    ));
104 104
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -28,7 +28,7 @@  discard block
 block discarded – undo
28 28
 $l = \OC::$server->getL10N('files');
29 29
 
30 30
 // Load the files
31
-$dir = isset($_GET['dir']) ? (string)$_GET['dir'] : '';
31
+$dir = isset($_GET['dir']) ? (string) $_GET['dir'] : '';
32 32
 $dir = \OC\Files\Filesystem::normalizePath($dir);
33 33
 
34 34
 try {
@@ -39,11 +39,11 @@  discard block
 block discarded – undo
39 39
 	}
40 40
 
41 41
 	$data = array();
42
-	$baseUrl = OCP\Util::linkTo('files', 'index.php') . '?dir=';
42
+	$baseUrl = OCP\Util::linkTo('files', 'index.php').'?dir=';
43 43
 
44 44
 	$permissions = $dirInfo->getPermissions();
45 45
 
46
-	$sortAttribute = isset($_GET['sort']) ? (string)$_GET['sort'] : 'name';
46
+	$sortAttribute = isset($_GET['sort']) ? (string) $_GET['sort'] : 'name';
47 47
 	$sortDirection = isset($_GET['sortdirection']) ? ($_GET['sortdirection'] === 'desc') : false;
48 48
 	$mimetypeFilters = isset($_GET['mimetypes']) ? json_decode($_GET['mimetypes']) : '';
49 49
 
Please login to merge, or discard this patch.