Completed
Pull Request — master (#3813)
by Maxence
12:19
created
apps/files_sharing/lib/Cache.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -110,6 +110,9 @@
 block discarded – undo
110 110
 		return parent::moveFromCache($sourceCache, $sourcePath, $targetPath);
111 111
 	}
112 112
 
113
+	/**
114
+	 * @param ICacheEntry $entry
115
+	 */
113 116
 	protected function formatCacheEntry($entry) {
114 117
 		$path = isset($entry['path']) ? $entry['path'] : '';
115 118
 		$entry = parent::formatCacheEntry($entry);
Please login to merge, or discard this patch.
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -29,7 +29,6 @@
 block discarded – undo
29 29
 
30 30
 use OC\Files\Cache\Wrapper\CacheJail;
31 31
 use OCP\Files\Cache\ICacheEntry;
32
-use OCP\Files\Storage\IStorage;
33 32
 
34 33
 /**
35 34
  * Metadata cache for shared files
Please login to merge, or discard this patch.
Indentation   +99 added lines, -99 removed lines patch added patch discarded remove patch
@@ -37,103 +37,103 @@
 block discarded – undo
37 37
  * don't use this class directly if you need to get metadata, use \OC\Files\Filesystem::getFileInfo instead
38 38
  */
39 39
 class Cache extends CacheJail {
40
-	/**
41
-	 * @var \OCA\Files_Sharing\SharedStorage
42
-	 */
43
-	private $storage;
44
-
45
-	/**
46
-	 * @var ICacheEntry
47
-	 */
48
-	private $sourceRootInfo;
49
-
50
-	private $rootUnchanged = true;
51
-
52
-	private $ownerDisplayName;
53
-
54
-	/**
55
-	 * @param \OCA\Files_Sharing\SharedStorage $storage
56
-	 * @param ICacheEntry $sourceRootInfo
57
-	 */
58
-	public function __construct($storage, ICacheEntry $sourceRootInfo) {
59
-		$this->storage = $storage;
60
-		$this->sourceRootInfo = $sourceRootInfo;
61
-		parent::__construct(
62
-			null,
63
-			$this->sourceRootInfo->getPath()
64
-		);
65
-	}
66
-
67
-	public function getCache() {
68
-		if (is_null($this->cache)) {
69
-			$this->cache = $this->storage->getSourceStorage()->getCache();
70
-		}
71
-		return $this->cache;
72
-	}
73
-
74
-	public function getNumericStorageId() {
75
-		if (isset($this->numericId)) {
76
-			return $this->numericId;
77
-		} else {
78
-			return false;
79
-		}
80
-	}
81
-
82
-	public function get($file) {
83
-		if ($this->rootUnchanged && ($file === '' || $file === $this->sourceRootInfo->getId())) {
84
-			return $this->formatCacheEntry(clone $this->sourceRootInfo);
85
-		}
86
-		return parent::get($file);
87
-	}
88
-
89
-	public function update($id, array $data) {
90
-		$this->rootUnchanged = false;
91
-		parent::update($id, $data);
92
-	}
93
-
94
-	public function insert($file, array $data) {
95
-		$this->rootUnchanged = false;
96
-		return parent::insert($file, $data);
97
-	}
98
-
99
-	public function remove($file) {
100
-		$this->rootUnchanged = false;
101
-		parent::remove($file);
102
-	}
103
-
104
-	public function moveFromCache(\OCP\Files\Cache\ICache $sourceCache, $sourcePath, $targetPath) {
105
-		$this->rootUnchanged = false;
106
-		return parent::moveFromCache($sourceCache, $sourcePath, $targetPath);
107
-	}
108
-
109
-	protected function formatCacheEntry($entry) {
110
-		$path = isset($entry['path']) ? $entry['path'] : '';
111
-		$entry = parent::formatCacheEntry($entry);
112
-		$sharePermissions = $this->storage->getPermissions($path);
113
-		if (isset($entry['permissions'])) {
114
-			$entry['permissions'] &= $sharePermissions;
115
-		} else {
116
-			$entry['permissions'] = $sharePermissions;
117
-		}
118
-		$entry['uid_owner'] = $this->storage->getOwner($path);
119
-		$entry['displayname_owner'] = $this->getOwnerDisplayName();
120
-		if ($path === '') {
121
-			$entry['is_share_mount_point'] = true;
122
-		}
123
-		return $entry;
124
-	}
125
-
126
-	private function getOwnerDisplayName() {
127
-		if (!$this->ownerDisplayName) {
128
-			$this->ownerDisplayName = \OC_User::getDisplayName($this->storage->getOwner(''));
129
-		}
130
-		return $this->ownerDisplayName;
131
-	}
132
-
133
-	/**
134
-	 * remove all entries for files that are stored on the storage from the cache
135
-	 */
136
-	public function clear() {
137
-		// Not a valid action for Shared Cache
138
-	}
40
+    /**
41
+     * @var \OCA\Files_Sharing\SharedStorage
42
+     */
43
+    private $storage;
44
+
45
+    /**
46
+     * @var ICacheEntry
47
+     */
48
+    private $sourceRootInfo;
49
+
50
+    private $rootUnchanged = true;
51
+
52
+    private $ownerDisplayName;
53
+
54
+    /**
55
+     * @param \OCA\Files_Sharing\SharedStorage $storage
56
+     * @param ICacheEntry $sourceRootInfo
57
+     */
58
+    public function __construct($storage, ICacheEntry $sourceRootInfo) {
59
+        $this->storage = $storage;
60
+        $this->sourceRootInfo = $sourceRootInfo;
61
+        parent::__construct(
62
+            null,
63
+            $this->sourceRootInfo->getPath()
64
+        );
65
+    }
66
+
67
+    public function getCache() {
68
+        if (is_null($this->cache)) {
69
+            $this->cache = $this->storage->getSourceStorage()->getCache();
70
+        }
71
+        return $this->cache;
72
+    }
73
+
74
+    public function getNumericStorageId() {
75
+        if (isset($this->numericId)) {
76
+            return $this->numericId;
77
+        } else {
78
+            return false;
79
+        }
80
+    }
81
+
82
+    public function get($file) {
83
+        if ($this->rootUnchanged && ($file === '' || $file === $this->sourceRootInfo->getId())) {
84
+            return $this->formatCacheEntry(clone $this->sourceRootInfo);
85
+        }
86
+        return parent::get($file);
87
+    }
88
+
89
+    public function update($id, array $data) {
90
+        $this->rootUnchanged = false;
91
+        parent::update($id, $data);
92
+    }
93
+
94
+    public function insert($file, array $data) {
95
+        $this->rootUnchanged = false;
96
+        return parent::insert($file, $data);
97
+    }
98
+
99
+    public function remove($file) {
100
+        $this->rootUnchanged = false;
101
+        parent::remove($file);
102
+    }
103
+
104
+    public function moveFromCache(\OCP\Files\Cache\ICache $sourceCache, $sourcePath, $targetPath) {
105
+        $this->rootUnchanged = false;
106
+        return parent::moveFromCache($sourceCache, $sourcePath, $targetPath);
107
+    }
108
+
109
+    protected function formatCacheEntry($entry) {
110
+        $path = isset($entry['path']) ? $entry['path'] : '';
111
+        $entry = parent::formatCacheEntry($entry);
112
+        $sharePermissions = $this->storage->getPermissions($path);
113
+        if (isset($entry['permissions'])) {
114
+            $entry['permissions'] &= $sharePermissions;
115
+        } else {
116
+            $entry['permissions'] = $sharePermissions;
117
+        }
118
+        $entry['uid_owner'] = $this->storage->getOwner($path);
119
+        $entry['displayname_owner'] = $this->getOwnerDisplayName();
120
+        if ($path === '') {
121
+            $entry['is_share_mount_point'] = true;
122
+        }
123
+        return $entry;
124
+    }
125
+
126
+    private function getOwnerDisplayName() {
127
+        if (!$this->ownerDisplayName) {
128
+            $this->ownerDisplayName = \OC_User::getDisplayName($this->storage->getOwner(''));
129
+        }
130
+        return $this->ownerDisplayName;
131
+    }
132
+
133
+    /**
134
+     * remove all entries for files that are stored on the storage from the cache
135
+     */
136
+    public function clear() {
137
+        // Not a valid action for Shared Cache
138
+    }
139 139
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/CalDavBackend.php 4 patches
Doc Comments   +9 added lines, -3 removed lines patch added patch discarded remove patch
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
 	 *
159 159
 	 * By default this excludes the automatically generated birthday calendar
160 160
 	 *
161
-	 * @param $principalUri
161
+	 * @param string $principalUri
162 162
 	 * @param bool $excludeBirthday
163 163
 	 * @return int
164 164
 	 */
@@ -304,6 +304,9 @@  discard block
 block discarded – undo
304 304
 		return array_values($calendars);
305 305
 	}
306 306
 
307
+	/**
308
+	 * @param string $principalUri
309
+	 */
307 310
 	public function getUsersOwnCalendars($principalUri) {
308 311
 		$principalUri = $this->convertPrincipal($principalUri, true);
309 312
 		$fields = array_values($this->propertyMap);
@@ -878,7 +881,7 @@  discard block
 block discarded – undo
878 881
 	 * calendar-data. If the result of a subsequent GET to this object is not
879 882
 	 * the exact same as this request body, you should omit the ETag.
880 883
 	 *
881
-	 * @param mixed $calendarId
884
+	 * @param integer $calendarId
882 885
 	 * @param string $objectUri
883 886
 	 * @param string $calendarData
884 887
 	 * @return string
@@ -1370,7 +1373,7 @@  discard block
 block discarded – undo
1370 1373
 	 * @param string $principalUri
1371 1374
 	 * @param string $uri
1372 1375
 	 * @param array $properties
1373
-	 * @return mixed
1376
+	 * @return integer
1374 1377
 	 */
1375 1378
 	function createSubscription($principalUri, $uri, array $properties) {
1376 1379
 
@@ -1783,6 +1786,9 @@  discard block
 block discarded – undo
1783 1786
 		return $this->sharingBackend->applyShareAcl($resourceId, $acl);
1784 1787
 	}
1785 1788
 
1789
+	/**
1790
+	 * @param boolean $toV2
1791
+	 */
1786 1792
 	private function convertPrincipal($principalUri, $toV2) {
1787 1793
 		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1788 1794
 			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
@@ -808,7 +808,9 @@
 block discarded – undo
808 808
 		$stmt = $query->execute();
809 809
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
810 810
 
811
-		if(!$row) return null;
811
+		if(!$row) {
812
+		    return null;
813
+		}
812 814
 
813 815
 		return [
814 816
 				'id'            => $row['id'],
Please login to merge, or discard this patch.
Indentation   +1751 added lines, -1751 removed lines patch added patch discarded remove patch
@@ -59,1756 +59,1756 @@
 block discarded – undo
59 59
  */
60 60
 class CalDavBackend extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport {
61 61
 
62
-	const PERSONAL_CALENDAR_URI = 'personal';
63
-	const PERSONAL_CALENDAR_NAME = 'Personal';
64
-
65
-	/**
66
-	 * We need to specify a max date, because we need to stop *somewhere*
67
-	 *
68
-	 * On 32 bit system the maximum for a signed integer is 2147483647, so
69
-	 * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
70
-	 * in 2038-01-19 to avoid problems when the date is converted
71
-	 * to a unix timestamp.
72
-	 */
73
-	const MAX_DATE = '2038-01-01';
74
-
75
-	const ACCESS_PUBLIC = 4;
76
-	const CLASSIFICATION_PUBLIC = 0;
77
-	const CLASSIFICATION_PRIVATE = 1;
78
-	const CLASSIFICATION_CONFIDENTIAL = 2;
79
-
80
-	/**
81
-	 * List of CalDAV properties, and how they map to database field names
82
-	 * Add your own properties by simply adding on to this array.
83
-	 *
84
-	 * Note that only string-based properties are supported here.
85
-	 *
86
-	 * @var array
87
-	 */
88
-	public $propertyMap = [
89
-		'{DAV:}displayname'                          => 'displayname',
90
-		'{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
91
-		'{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
92
-		'{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
93
-		'{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
94
-	];
95
-
96
-	/**
97
-	 * List of subscription properties, and how they map to database field names.
98
-	 *
99
-	 * @var array
100
-	 */
101
-	public $subscriptionPropertyMap = [
102
-		'{DAV:}displayname'                                           => 'displayname',
103
-		'{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
104
-		'{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
105
-		'{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
106
-		'{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
107
-		'{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
108
-		'{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
109
-	];
110
-
111
-	/**
112
-	 * @var string[] Map of uid => display name
113
-	 */
114
-	protected $userDisplayNames;
115
-
116
-	/** @var IDBConnection */
117
-	private $db;
118
-
119
-	/** @var Backend */
120
-	private $sharingBackend;
121
-
122
-	/** @var Principal */
123
-	private $principalBackend;
124
-
125
-	/** @var IUserManager */
126
-	private $userManager;
127
-
128
-	/** @var ISecureRandom */
129
-	private $random;
130
-
131
-	/** @var EventDispatcherInterface */
132
-	private $dispatcher;
133
-
134
-	/** @var bool */
135
-	private $legacyEndpoint;
136
-
137
-	/**
138
-	 * CalDavBackend constructor.
139
-	 *
140
-	 * @param IDBConnection $db
141
-	 * @param Principal $principalBackend
142
-	 * @param IUserManager $userManager
143
-	 * @param ISecureRandom $random
144
-	 * @param EventDispatcherInterface $dispatcher
145
-	 * @param bool $legacyEndpoint
146
-	 */
147
-	public function __construct(IDBConnection $db,
148
-								Principal $principalBackend,
149
-								IUserManager $userManager,
150
-								ISecureRandom $random,
151
-								EventDispatcherInterface $dispatcher,
152
-								$legacyEndpoint = false) {
153
-		$this->db = $db;
154
-		$this->principalBackend = $principalBackend;
155
-		$this->userManager = $userManager;
156
-		$this->sharingBackend = new Backend($this->db, $principalBackend, 'calendar');
157
-		$this->random = $random;
158
-		$this->dispatcher = $dispatcher;
159
-		$this->legacyEndpoint = $legacyEndpoint;
160
-	}
161
-
162
-	/**
163
-	 * Return the number of calendars for a principal
164
-	 *
165
-	 * By default this excludes the automatically generated birthday calendar
166
-	 *
167
-	 * @param $principalUri
168
-	 * @param bool $excludeBirthday
169
-	 * @return int
170
-	 */
171
-	public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
172
-		$principalUri = $this->convertPrincipal($principalUri, true);
173
-		$query = $this->db->getQueryBuilder();
174
-		$query->select($query->createFunction('COUNT(*)'))
175
-			->from('calendars')
176
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
177
-
178
-		if ($excludeBirthday) {
179
-			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
180
-		}
181
-
182
-		return (int)$query->execute()->fetchColumn();
183
-	}
184
-
185
-	/**
186
-	 * Returns a list of calendars for a principal.
187
-	 *
188
-	 * Every project is an array with the following keys:
189
-	 *  * id, a unique id that will be used by other functions to modify the
190
-	 *    calendar. This can be the same as the uri or a database key.
191
-	 *  * uri, which the basename of the uri with which the calendar is
192
-	 *    accessed.
193
-	 *  * principaluri. The owner of the calendar. Almost always the same as
194
-	 *    principalUri passed to this method.
195
-	 *
196
-	 * Furthermore it can contain webdav properties in clark notation. A very
197
-	 * common one is '{DAV:}displayname'.
198
-	 *
199
-	 * Many clients also require:
200
-	 * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
201
-	 * For this property, you can just return an instance of
202
-	 * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
203
-	 *
204
-	 * If you return {http://sabredav.org/ns}read-only and set the value to 1,
205
-	 * ACL will automatically be put in read-only mode.
206
-	 *
207
-	 * @param string $principalUri
208
-	 * @return array
209
-	 */
210
-	function getCalendarsForUser($principalUri) {
211
-		$principalUriOriginal = $principalUri;
212
-		$principalUri = $this->convertPrincipal($principalUri, true);
213
-		$fields = array_values($this->propertyMap);
214
-		$fields[] = 'id';
215
-		$fields[] = 'uri';
216
-		$fields[] = 'synctoken';
217
-		$fields[] = 'components';
218
-		$fields[] = 'principaluri';
219
-		$fields[] = 'transparent';
220
-
221
-		// Making fields a comma-delimited list
222
-		$query = $this->db->getQueryBuilder();
223
-		$query->select($fields)->from('calendars')
224
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
225
-				->orderBy('calendarorder', 'ASC');
226
-		$stmt = $query->execute();
227
-
228
-		$calendars = [];
229
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
230
-
231
-			$components = [];
232
-			if ($row['components']) {
233
-				$components = explode(',',$row['components']);
234
-			}
235
-
236
-			$calendar = [
237
-				'id' => $row['id'],
238
-				'uri' => $row['uri'],
239
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
240
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
241
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
242
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
243
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
244
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
245
-			];
246
-
247
-			foreach($this->propertyMap as $xmlName=>$dbName) {
248
-				$calendar[$xmlName] = $row[$dbName];
249
-			}
250
-
251
-			if (!isset($calendars[$calendar['id']])) {
252
-				$calendars[$calendar['id']] = $calendar;
253
-			}
254
-		}
255
-
256
-		$stmt->closeCursor();
257
-
258
-		// query for shared calendars
259
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
260
-		$principals[]= $principalUri;
261
-
262
-		$fields = array_values($this->propertyMap);
263
-		$fields[] = 'a.id';
264
-		$fields[] = 'a.uri';
265
-		$fields[] = 'a.synctoken';
266
-		$fields[] = 'a.components';
267
-		$fields[] = 'a.principaluri';
268
-		$fields[] = 'a.transparent';
269
-		$fields[] = 's.access';
270
-		$query = $this->db->getQueryBuilder();
271
-		$result = $query->select($fields)
272
-			->from('dav_shares', 's')
273
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
274
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
275
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
276
-			->setParameter('type', 'calendar')
277
-			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
278
-			->execute();
279
-
280
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
281
-		while($row = $result->fetch()) {
282
-			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
283
-			if (isset($calendars[$row['id']])) {
284
-				if ($readOnly) {
285
-					// New share can not have more permissions then the old one.
286
-					continue;
287
-				}
288
-				if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
289
-					$calendars[$row['id']][$readOnlyPropertyName] === 0) {
290
-					// Old share is already read-write, no more permissions can be gained
291
-					continue;
292
-				}
293
-			}
294
-
295
-			list(, $name) = URLUtil::splitPath($row['principaluri']);
296
-			$uri = $row['uri'] . '_shared_by_' . $name;
297
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
298
-			$components = [];
299
-			if ($row['components']) {
300
-				$components = explode(',',$row['components']);
301
-			}
302
-			$calendar = [
303
-				'id' => $row['id'],
304
-				'uri' => $uri,
305
-				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
306
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
307
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
308
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
309
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
310
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
311
-				$readOnlyPropertyName => $readOnly,
312
-			];
313
-
314
-			foreach($this->propertyMap as $xmlName=>$dbName) {
315
-				$calendar[$xmlName] = $row[$dbName];
316
-			}
317
-
318
-			$calendars[$calendar['id']] = $calendar;
319
-		}
320
-		$result->closeCursor();
321
-
322
-		return array_values($calendars);
323
-	}
324
-
325
-	public function getUsersOwnCalendars($principalUri) {
326
-		$principalUri = $this->convertPrincipal($principalUri, true);
327
-		$fields = array_values($this->propertyMap);
328
-		$fields[] = 'id';
329
-		$fields[] = 'uri';
330
-		$fields[] = 'synctoken';
331
-		$fields[] = 'components';
332
-		$fields[] = 'principaluri';
333
-		$fields[] = 'transparent';
334
-		// Making fields a comma-delimited list
335
-		$query = $this->db->getQueryBuilder();
336
-		$query->select($fields)->from('calendars')
337
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
338
-			->orderBy('calendarorder', 'ASC');
339
-		$stmt = $query->execute();
340
-		$calendars = [];
341
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
342
-			$components = [];
343
-			if ($row['components']) {
344
-				$components = explode(',',$row['components']);
345
-			}
346
-			$calendar = [
347
-				'id' => $row['id'],
348
-				'uri' => $row['uri'],
349
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
350
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
351
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
352
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
353
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
354
-			];
355
-			foreach($this->propertyMap as $xmlName=>$dbName) {
356
-				$calendar[$xmlName] = $row[$dbName];
357
-			}
358
-			if (!isset($calendars[$calendar['id']])) {
359
-				$calendars[$calendar['id']] = $calendar;
360
-			}
361
-		}
362
-		$stmt->closeCursor();
363
-		return array_values($calendars);
364
-	}
365
-
366
-
367
-	private function getUserDisplayName($uid) {
368
-		if (!isset($this->userDisplayNames[$uid])) {
369
-			$user = $this->userManager->get($uid);
370
-
371
-			if ($user instanceof IUser) {
372
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
373
-			} else {
374
-				$this->userDisplayNames[$uid] = $uid;
375
-			}
376
-		}
377
-
378
-		return $this->userDisplayNames[$uid];
379
-	}
62
+    const PERSONAL_CALENDAR_URI = 'personal';
63
+    const PERSONAL_CALENDAR_NAME = 'Personal';
64
+
65
+    /**
66
+     * We need to specify a max date, because we need to stop *somewhere*
67
+     *
68
+     * On 32 bit system the maximum for a signed integer is 2147483647, so
69
+     * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
70
+     * in 2038-01-19 to avoid problems when the date is converted
71
+     * to a unix timestamp.
72
+     */
73
+    const MAX_DATE = '2038-01-01';
74
+
75
+    const ACCESS_PUBLIC = 4;
76
+    const CLASSIFICATION_PUBLIC = 0;
77
+    const CLASSIFICATION_PRIVATE = 1;
78
+    const CLASSIFICATION_CONFIDENTIAL = 2;
79
+
80
+    /**
81
+     * List of CalDAV properties, and how they map to database field names
82
+     * Add your own properties by simply adding on to this array.
83
+     *
84
+     * Note that only string-based properties are supported here.
85
+     *
86
+     * @var array
87
+     */
88
+    public $propertyMap = [
89
+        '{DAV:}displayname'                          => 'displayname',
90
+        '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
91
+        '{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
92
+        '{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
93
+        '{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
94
+    ];
95
+
96
+    /**
97
+     * List of subscription properties, and how they map to database field names.
98
+     *
99
+     * @var array
100
+     */
101
+    public $subscriptionPropertyMap = [
102
+        '{DAV:}displayname'                                           => 'displayname',
103
+        '{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
104
+        '{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
105
+        '{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
106
+        '{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
107
+        '{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
108
+        '{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
109
+    ];
110
+
111
+    /**
112
+     * @var string[] Map of uid => display name
113
+     */
114
+    protected $userDisplayNames;
115
+
116
+    /** @var IDBConnection */
117
+    private $db;
118
+
119
+    /** @var Backend */
120
+    private $sharingBackend;
121
+
122
+    /** @var Principal */
123
+    private $principalBackend;
124
+
125
+    /** @var IUserManager */
126
+    private $userManager;
127
+
128
+    /** @var ISecureRandom */
129
+    private $random;
130
+
131
+    /** @var EventDispatcherInterface */
132
+    private $dispatcher;
133
+
134
+    /** @var bool */
135
+    private $legacyEndpoint;
136
+
137
+    /**
138
+     * CalDavBackend constructor.
139
+     *
140
+     * @param IDBConnection $db
141
+     * @param Principal $principalBackend
142
+     * @param IUserManager $userManager
143
+     * @param ISecureRandom $random
144
+     * @param EventDispatcherInterface $dispatcher
145
+     * @param bool $legacyEndpoint
146
+     */
147
+    public function __construct(IDBConnection $db,
148
+                                Principal $principalBackend,
149
+                                IUserManager $userManager,
150
+                                ISecureRandom $random,
151
+                                EventDispatcherInterface $dispatcher,
152
+                                $legacyEndpoint = false) {
153
+        $this->db = $db;
154
+        $this->principalBackend = $principalBackend;
155
+        $this->userManager = $userManager;
156
+        $this->sharingBackend = new Backend($this->db, $principalBackend, 'calendar');
157
+        $this->random = $random;
158
+        $this->dispatcher = $dispatcher;
159
+        $this->legacyEndpoint = $legacyEndpoint;
160
+    }
161
+
162
+    /**
163
+     * Return the number of calendars for a principal
164
+     *
165
+     * By default this excludes the automatically generated birthday calendar
166
+     *
167
+     * @param $principalUri
168
+     * @param bool $excludeBirthday
169
+     * @return int
170
+     */
171
+    public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
172
+        $principalUri = $this->convertPrincipal($principalUri, true);
173
+        $query = $this->db->getQueryBuilder();
174
+        $query->select($query->createFunction('COUNT(*)'))
175
+            ->from('calendars')
176
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
177
+
178
+        if ($excludeBirthday) {
179
+            $query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
180
+        }
181
+
182
+        return (int)$query->execute()->fetchColumn();
183
+    }
184
+
185
+    /**
186
+     * Returns a list of calendars for a principal.
187
+     *
188
+     * Every project is an array with the following keys:
189
+     *  * id, a unique id that will be used by other functions to modify the
190
+     *    calendar. This can be the same as the uri or a database key.
191
+     *  * uri, which the basename of the uri with which the calendar is
192
+     *    accessed.
193
+     *  * principaluri. The owner of the calendar. Almost always the same as
194
+     *    principalUri passed to this method.
195
+     *
196
+     * Furthermore it can contain webdav properties in clark notation. A very
197
+     * common one is '{DAV:}displayname'.
198
+     *
199
+     * Many clients also require:
200
+     * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
201
+     * For this property, you can just return an instance of
202
+     * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
203
+     *
204
+     * If you return {http://sabredav.org/ns}read-only and set the value to 1,
205
+     * ACL will automatically be put in read-only mode.
206
+     *
207
+     * @param string $principalUri
208
+     * @return array
209
+     */
210
+    function getCalendarsForUser($principalUri) {
211
+        $principalUriOriginal = $principalUri;
212
+        $principalUri = $this->convertPrincipal($principalUri, true);
213
+        $fields = array_values($this->propertyMap);
214
+        $fields[] = 'id';
215
+        $fields[] = 'uri';
216
+        $fields[] = 'synctoken';
217
+        $fields[] = 'components';
218
+        $fields[] = 'principaluri';
219
+        $fields[] = 'transparent';
220
+
221
+        // Making fields a comma-delimited list
222
+        $query = $this->db->getQueryBuilder();
223
+        $query->select($fields)->from('calendars')
224
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
225
+                ->orderBy('calendarorder', 'ASC');
226
+        $stmt = $query->execute();
227
+
228
+        $calendars = [];
229
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
230
+
231
+            $components = [];
232
+            if ($row['components']) {
233
+                $components = explode(',',$row['components']);
234
+            }
235
+
236
+            $calendar = [
237
+                'id' => $row['id'],
238
+                'uri' => $row['uri'],
239
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
240
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
241
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
242
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
243
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
244
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
245
+            ];
246
+
247
+            foreach($this->propertyMap as $xmlName=>$dbName) {
248
+                $calendar[$xmlName] = $row[$dbName];
249
+            }
250
+
251
+            if (!isset($calendars[$calendar['id']])) {
252
+                $calendars[$calendar['id']] = $calendar;
253
+            }
254
+        }
255
+
256
+        $stmt->closeCursor();
257
+
258
+        // query for shared calendars
259
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
260
+        $principals[]= $principalUri;
261
+
262
+        $fields = array_values($this->propertyMap);
263
+        $fields[] = 'a.id';
264
+        $fields[] = 'a.uri';
265
+        $fields[] = 'a.synctoken';
266
+        $fields[] = 'a.components';
267
+        $fields[] = 'a.principaluri';
268
+        $fields[] = 'a.transparent';
269
+        $fields[] = 's.access';
270
+        $query = $this->db->getQueryBuilder();
271
+        $result = $query->select($fields)
272
+            ->from('dav_shares', 's')
273
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
274
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
275
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
276
+            ->setParameter('type', 'calendar')
277
+            ->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
278
+            ->execute();
279
+
280
+        $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
281
+        while($row = $result->fetch()) {
282
+            $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
283
+            if (isset($calendars[$row['id']])) {
284
+                if ($readOnly) {
285
+                    // New share can not have more permissions then the old one.
286
+                    continue;
287
+                }
288
+                if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
289
+                    $calendars[$row['id']][$readOnlyPropertyName] === 0) {
290
+                    // Old share is already read-write, no more permissions can be gained
291
+                    continue;
292
+                }
293
+            }
294
+
295
+            list(, $name) = URLUtil::splitPath($row['principaluri']);
296
+            $uri = $row['uri'] . '_shared_by_' . $name;
297
+            $row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
298
+            $components = [];
299
+            if ($row['components']) {
300
+                $components = explode(',',$row['components']);
301
+            }
302
+            $calendar = [
303
+                'id' => $row['id'],
304
+                'uri' => $uri,
305
+                'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
306
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
307
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
308
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
309
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
310
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
311
+                $readOnlyPropertyName => $readOnly,
312
+            ];
313
+
314
+            foreach($this->propertyMap as $xmlName=>$dbName) {
315
+                $calendar[$xmlName] = $row[$dbName];
316
+            }
317
+
318
+            $calendars[$calendar['id']] = $calendar;
319
+        }
320
+        $result->closeCursor();
321
+
322
+        return array_values($calendars);
323
+    }
324
+
325
+    public function getUsersOwnCalendars($principalUri) {
326
+        $principalUri = $this->convertPrincipal($principalUri, true);
327
+        $fields = array_values($this->propertyMap);
328
+        $fields[] = 'id';
329
+        $fields[] = 'uri';
330
+        $fields[] = 'synctoken';
331
+        $fields[] = 'components';
332
+        $fields[] = 'principaluri';
333
+        $fields[] = 'transparent';
334
+        // Making fields a comma-delimited list
335
+        $query = $this->db->getQueryBuilder();
336
+        $query->select($fields)->from('calendars')
337
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
338
+            ->orderBy('calendarorder', 'ASC');
339
+        $stmt = $query->execute();
340
+        $calendars = [];
341
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
342
+            $components = [];
343
+            if ($row['components']) {
344
+                $components = explode(',',$row['components']);
345
+            }
346
+            $calendar = [
347
+                'id' => $row['id'],
348
+                'uri' => $row['uri'],
349
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
350
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
351
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
352
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
353
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
354
+            ];
355
+            foreach($this->propertyMap as $xmlName=>$dbName) {
356
+                $calendar[$xmlName] = $row[$dbName];
357
+            }
358
+            if (!isset($calendars[$calendar['id']])) {
359
+                $calendars[$calendar['id']] = $calendar;
360
+            }
361
+        }
362
+        $stmt->closeCursor();
363
+        return array_values($calendars);
364
+    }
365
+
366
+
367
+    private function getUserDisplayName($uid) {
368
+        if (!isset($this->userDisplayNames[$uid])) {
369
+            $user = $this->userManager->get($uid);
370
+
371
+            if ($user instanceof IUser) {
372
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
373
+            } else {
374
+                $this->userDisplayNames[$uid] = $uid;
375
+            }
376
+        }
377
+
378
+        return $this->userDisplayNames[$uid];
379
+    }
380 380
 	
381
-	/**
382
-	 * @return array
383
-	 */
384
-	public function getPublicCalendars() {
385
-		$fields = array_values($this->propertyMap);
386
-		$fields[] = 'a.id';
387
-		$fields[] = 'a.uri';
388
-		$fields[] = 'a.synctoken';
389
-		$fields[] = 'a.components';
390
-		$fields[] = 'a.principaluri';
391
-		$fields[] = 'a.transparent';
392
-		$fields[] = 's.access';
393
-		$fields[] = 's.publicuri';
394
-		$calendars = [];
395
-		$query = $this->db->getQueryBuilder();
396
-		$result = $query->select($fields)
397
-			->from('dav_shares', 's')
398
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
399
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
400
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
401
-			->execute();
402
-
403
-		while($row = $result->fetch()) {
404
-			list(, $name) = URLUtil::splitPath($row['principaluri']);
405
-			$row['displayname'] = $row['displayname'] . "($name)";
406
-			$components = [];
407
-			if ($row['components']) {
408
-				$components = explode(',',$row['components']);
409
-			}
410
-			$calendar = [
411
-				'id' => $row['id'],
412
-				'uri' => $row['publicuri'],
413
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
414
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
415
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
416
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
417
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
418
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
419
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
420
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
421
-			];
422
-
423
-			foreach($this->propertyMap as $xmlName=>$dbName) {
424
-				$calendar[$xmlName] = $row[$dbName];
425
-			}
426
-
427
-			if (!isset($calendars[$calendar['id']])) {
428
-				$calendars[$calendar['id']] = $calendar;
429
-			}
430
-		}
431
-		$result->closeCursor();
432
-
433
-		return array_values($calendars);
434
-	}
435
-
436
-	/**
437
-	 * @param string $uri
438
-	 * @return array
439
-	 * @throws NotFound
440
-	 */
441
-	public function getPublicCalendar($uri) {
442
-		$fields = array_values($this->propertyMap);
443
-		$fields[] = 'a.id';
444
-		$fields[] = 'a.uri';
445
-		$fields[] = 'a.synctoken';
446
-		$fields[] = 'a.components';
447
-		$fields[] = 'a.principaluri';
448
-		$fields[] = 'a.transparent';
449
-		$fields[] = 's.access';
450
-		$fields[] = 's.publicuri';
451
-		$query = $this->db->getQueryBuilder();
452
-		$result = $query->select($fields)
453
-			->from('dav_shares', 's')
454
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
455
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
456
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
457
-			->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
458
-			->execute();
459
-
460
-		$row = $result->fetch(\PDO::FETCH_ASSOC);
461
-
462
-		$result->closeCursor();
463
-
464
-		if ($row === false) {
465
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
466
-		}
467
-
468
-		list(, $name) = URLUtil::splitPath($row['principaluri']);
469
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
470
-		$components = [];
471
-		if ($row['components']) {
472
-			$components = explode(',',$row['components']);
473
-		}
474
-		$calendar = [
475
-			'id' => $row['id'],
476
-			'uri' => $row['publicuri'],
477
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
478
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
479
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
480
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
481
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
482
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
483
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
484
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
485
-		];
486
-
487
-		foreach($this->propertyMap as $xmlName=>$dbName) {
488
-			$calendar[$xmlName] = $row[$dbName];
489
-		}
490
-
491
-		return $calendar;
492
-
493
-	}
494
-
495
-	/**
496
-	 * @param string $principal
497
-	 * @param string $uri
498
-	 * @return array|null
499
-	 */
500
-	public function getCalendarByUri($principal, $uri) {
501
-		$fields = array_values($this->propertyMap);
502
-		$fields[] = 'id';
503
-		$fields[] = 'uri';
504
-		$fields[] = 'synctoken';
505
-		$fields[] = 'components';
506
-		$fields[] = 'principaluri';
507
-		$fields[] = 'transparent';
508
-
509
-		// Making fields a comma-delimited list
510
-		$query = $this->db->getQueryBuilder();
511
-		$query->select($fields)->from('calendars')
512
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
513
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
514
-			->setMaxResults(1);
515
-		$stmt = $query->execute();
516
-
517
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
518
-		$stmt->closeCursor();
519
-		if ($row === false) {
520
-			return null;
521
-		}
522
-
523
-		$components = [];
524
-		if ($row['components']) {
525
-			$components = explode(',',$row['components']);
526
-		}
527
-
528
-		$calendar = [
529
-			'id' => $row['id'],
530
-			'uri' => $row['uri'],
531
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
532
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
533
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
534
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
535
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
536
-		];
537
-
538
-		foreach($this->propertyMap as $xmlName=>$dbName) {
539
-			$calendar[$xmlName] = $row[$dbName];
540
-		}
541
-
542
-		return $calendar;
543
-	}
544
-
545
-	public function getCalendarById($calendarId) {
546
-		$fields = array_values($this->propertyMap);
547
-		$fields[] = 'id';
548
-		$fields[] = 'uri';
549
-		$fields[] = 'synctoken';
550
-		$fields[] = 'components';
551
-		$fields[] = 'principaluri';
552
-		$fields[] = 'transparent';
553
-
554
-		// Making fields a comma-delimited list
555
-		$query = $this->db->getQueryBuilder();
556
-		$query->select($fields)->from('calendars')
557
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
558
-			->setMaxResults(1);
559
-		$stmt = $query->execute();
560
-
561
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
562
-		$stmt->closeCursor();
563
-		if ($row === false) {
564
-			return null;
565
-		}
566
-
567
-		$components = [];
568
-		if ($row['components']) {
569
-			$components = explode(',',$row['components']);
570
-		}
571
-
572
-		$calendar = [
573
-			'id' => $row['id'],
574
-			'uri' => $row['uri'],
575
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
576
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
577
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
578
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
579
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
580
-		];
581
-
582
-		foreach($this->propertyMap as $xmlName=>$dbName) {
583
-			$calendar[$xmlName] = $row[$dbName];
584
-		}
585
-
586
-		return $calendar;
587
-	}
588
-
589
-	/**
590
-	 * Creates a new calendar for a principal.
591
-	 *
592
-	 * If the creation was a success, an id must be returned that can be used to reference
593
-	 * this calendar in other methods, such as updateCalendar.
594
-	 *
595
-	 * @param string $principalUri
596
-	 * @param string $calendarUri
597
-	 * @param array $properties
598
-	 * @return int
599
-	 */
600
-	function createCalendar($principalUri, $calendarUri, array $properties) {
601
-		$values = [
602
-			'principaluri' => $this->convertPrincipal($principalUri, true),
603
-			'uri'          => $calendarUri,
604
-			'synctoken'    => 1,
605
-			'transparent'  => 0,
606
-			'components'   => 'VEVENT,VTODO',
607
-			'displayname'  => $calendarUri
608
-		];
609
-
610
-		// Default value
611
-		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
612
-		if (isset($properties[$sccs])) {
613
-			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
614
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
615
-			}
616
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
617
-		}
618
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
619
-		if (isset($properties[$transp])) {
620
-			$values['transparent'] = $properties[$transp]->getValue()==='transparent';
621
-		}
622
-
623
-		foreach($this->propertyMap as $xmlName=>$dbName) {
624
-			if (isset($properties[$xmlName])) {
625
-				$values[$dbName] = $properties[$xmlName];
626
-			}
627
-		}
628
-
629
-		$query = $this->db->getQueryBuilder();
630
-		$query->insert('calendars');
631
-		foreach($values as $column => $value) {
632
-			$query->setValue($column, $query->createNamedParameter($value));
633
-		}
634
-		$query->execute();
635
-		$calendarId = $query->getLastInsertId();
636
-
637
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
638
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
639
-			[
640
-				'calendarId' => $calendarId,
641
-				'calendarData' => $this->getCalendarById($calendarId),
642
-		]));
643
-
644
-		return $calendarId;
645
-	}
646
-
647
-	/**
648
-	 * Updates properties for a calendar.
649
-	 *
650
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
651
-	 * To do the actual updates, you must tell this object which properties
652
-	 * you're going to process with the handle() method.
653
-	 *
654
-	 * Calling the handle method is like telling the PropPatch object "I
655
-	 * promise I can handle updating this property".
656
-	 *
657
-	 * Read the PropPatch documentation for more info and examples.
658
-	 *
659
-	 * @param PropPatch $propPatch
660
-	 * @return void
661
-	 */
662
-	function updateCalendar($calendarId, PropPatch $propPatch) {
663
-		$supportedProperties = array_keys($this->propertyMap);
664
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
665
-
666
-		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
667
-			$newValues = [];
668
-			foreach ($mutations as $propertyName => $propertyValue) {
669
-
670
-				switch ($propertyName) {
671
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
672
-						$fieldName = 'transparent';
673
-						$newValues[$fieldName] = $propertyValue->getValue() === 'transparent';
674
-						break;
675
-					default :
676
-						$fieldName = $this->propertyMap[$propertyName];
677
-						$newValues[$fieldName] = $propertyValue;
678
-						break;
679
-				}
680
-
681
-			}
682
-			$query = $this->db->getQueryBuilder();
683
-			$query->update('calendars');
684
-			foreach ($newValues as $fieldName => $value) {
685
-				$query->set($fieldName, $query->createNamedParameter($value));
686
-			}
687
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
688
-			$query->execute();
689
-
690
-			$this->addChange($calendarId, "", 2);
691
-
692
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
693
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
694
-				[
695
-					'calendarId' => $calendarId,
696
-					'calendarData' => $this->getCalendarById($calendarId),
697
-					'shares' => $this->getShares($calendarId),
698
-					'propertyMutations' => $mutations,
699
-			]));
700
-
701
-			return true;
702
-		});
703
-	}
704
-
705
-	/**
706
-	 * Delete a calendar and all it's objects
707
-	 *
708
-	 * @param mixed $calendarId
709
-	 * @return void
710
-	 */
711
-	function deleteCalendar($calendarId) {
712
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
713
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
714
-			[
715
-				'calendarId' => $calendarId,
716
-				'calendarData' => $this->getCalendarById($calendarId),
717
-				'shares' => $this->getShares($calendarId),
718
-		]));
719
-
720
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?');
721
-		$stmt->execute([$calendarId]);
722
-
723
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
724
-		$stmt->execute([$calendarId]);
725
-
726
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ?');
727
-		$stmt->execute([$calendarId]);
728
-
729
-		$this->sharingBackend->deleteAllShares($calendarId);
730
-	}
731
-
732
-	/**
733
-	 * Delete all of an user's shares
734
-	 *
735
-	 * @param string $principaluri
736
-	 * @return void
737
-	 */
738
-	function deleteAllSharesByUser($principaluri) {
739
-		$this->sharingBackend->deleteAllSharesByUser($principaluri);
740
-	}
741
-
742
-	/**
743
-	 * Returns all calendar objects within a calendar.
744
-	 *
745
-	 * Every item contains an array with the following keys:
746
-	 *   * calendardata - The iCalendar-compatible calendar data
747
-	 *   * uri - a unique key which will be used to construct the uri. This can
748
-	 *     be any arbitrary string, but making sure it ends with '.ics' is a
749
-	 *     good idea. This is only the basename, or filename, not the full
750
-	 *     path.
751
-	 *   * lastmodified - a timestamp of the last modification time
752
-	 *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
753
-	 *   '"abcdef"')
754
-	 *   * size - The size of the calendar objects, in bytes.
755
-	 *   * component - optional, a string containing the type of object, such
756
-	 *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
757
-	 *     the Content-Type header.
758
-	 *
759
-	 * Note that the etag is optional, but it's highly encouraged to return for
760
-	 * speed reasons.
761
-	 *
762
-	 * The calendardata is also optional. If it's not returned
763
-	 * 'getCalendarObject' will be called later, which *is* expected to return
764
-	 * calendardata.
765
-	 *
766
-	 * If neither etag or size are specified, the calendardata will be
767
-	 * used/fetched to determine these numbers. If both are specified the
768
-	 * amount of times this is needed is reduced by a great degree.
769
-	 *
770
-	 * @param mixed $calendarId
771
-	 * @return array
772
-	 */
773
-	function getCalendarObjects($calendarId) {
774
-		$query = $this->db->getQueryBuilder();
775
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
776
-			->from('calendarobjects')
777
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
778
-		$stmt = $query->execute();
779
-
780
-		$result = [];
781
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
782
-			$result[] = [
783
-					'id'           => $row['id'],
784
-					'uri'          => $row['uri'],
785
-					'lastmodified' => $row['lastmodified'],
786
-					'etag'         => '"' . $row['etag'] . '"',
787
-					'calendarid'   => $row['calendarid'],
788
-					'size'         => (int)$row['size'],
789
-					'component'    => strtolower($row['componenttype']),
790
-					'classification'=> (int)$row['classification']
791
-			];
792
-		}
793
-
794
-		return $result;
795
-	}
796
-
797
-	/**
798
-	 * Returns information from a single calendar object, based on it's object
799
-	 * uri.
800
-	 *
801
-	 * The object uri is only the basename, or filename and not a full path.
802
-	 *
803
-	 * The returned array must have the same keys as getCalendarObjects. The
804
-	 * 'calendardata' object is required here though, while it's not required
805
-	 * for getCalendarObjects.
806
-	 *
807
-	 * This method must return null if the object did not exist.
808
-	 *
809
-	 * @param mixed $calendarId
810
-	 * @param string $objectUri
811
-	 * @return array|null
812
-	 */
813
-	function getCalendarObject($calendarId, $objectUri) {
814
-
815
-		$query = $this->db->getQueryBuilder();
816
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
817
-				->from('calendarobjects')
818
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
819
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)));
820
-		$stmt = $query->execute();
821
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
822
-
823
-		if(!$row) return null;
824
-
825
-		return [
826
-				'id'            => $row['id'],
827
-				'uri'           => $row['uri'],
828
-				'lastmodified'  => $row['lastmodified'],
829
-				'etag'          => '"' . $row['etag'] . '"',
830
-				'calendarid'    => $row['calendarid'],
831
-				'size'          => (int)$row['size'],
832
-				'calendardata'  => $this->readBlob($row['calendardata']),
833
-				'component'     => strtolower($row['componenttype']),
834
-				'classification'=> (int)$row['classification']
835
-		];
836
-	}
837
-
838
-	/**
839
-	 * Returns a list of calendar objects.
840
-	 *
841
-	 * This method should work identical to getCalendarObject, but instead
842
-	 * return all the calendar objects in the list as an array.
843
-	 *
844
-	 * If the backend supports this, it may allow for some speed-ups.
845
-	 *
846
-	 * @param mixed $calendarId
847
-	 * @param string[] $uris
848
-	 * @return array
849
-	 */
850
-	function getMultipleCalendarObjects($calendarId, array $uris) {
851
-		if (empty($uris)) {
852
-			return [];
853
-		}
854
-
855
-		$chunks = array_chunk($uris, 100);
856
-		$objects = [];
857
-
858
-		$query = $this->db->getQueryBuilder();
859
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
860
-			->from('calendarobjects')
861
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
862
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
863
-
864
-		foreach ($chunks as $uris) {
865
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
866
-			$result = $query->execute();
867
-
868
-			while ($row = $result->fetch()) {
869
-				$objects[] = [
870
-					'id'           => $row['id'],
871
-					'uri'          => $row['uri'],
872
-					'lastmodified' => $row['lastmodified'],
873
-					'etag'         => '"' . $row['etag'] . '"',
874
-					'calendarid'   => $row['calendarid'],
875
-					'size'         => (int)$row['size'],
876
-					'calendardata' => $this->readBlob($row['calendardata']),
877
-					'component'    => strtolower($row['componenttype']),
878
-					'classification' => (int)$row['classification']
879
-				];
880
-			}
881
-			$result->closeCursor();
882
-		}
883
-		return $objects;
884
-	}
885
-
886
-	/**
887
-	 * Creates a new calendar object.
888
-	 *
889
-	 * The object uri is only the basename, or filename and not a full path.
890
-	 *
891
-	 * It is possible return an etag from this function, which will be used in
892
-	 * the response to this PUT request. Note that the ETag must be surrounded
893
-	 * by double-quotes.
894
-	 *
895
-	 * However, you should only really return this ETag if you don't mangle the
896
-	 * calendar-data. If the result of a subsequent GET to this object is not
897
-	 * the exact same as this request body, you should omit the ETag.
898
-	 *
899
-	 * @param mixed $calendarId
900
-	 * @param string $objectUri
901
-	 * @param string $calendarData
902
-	 * @return string
903
-	 */
904
-	function createCalendarObject($calendarId, $objectUri, $calendarData) {
905
-		$extraData = $this->getDenormalizedData($calendarData);
906
-
907
-		$query = $this->db->getQueryBuilder();
908
-		$query->insert('calendarobjects')
909
-			->values([
910
-				'calendarid' => $query->createNamedParameter($calendarId),
911
-				'uri' => $query->createNamedParameter($objectUri),
912
-				'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
913
-				'lastmodified' => $query->createNamedParameter(time()),
914
-				'etag' => $query->createNamedParameter($extraData['etag']),
915
-				'size' => $query->createNamedParameter($extraData['size']),
916
-				'componenttype' => $query->createNamedParameter($extraData['componentType']),
917
-				'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
918
-				'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
919
-				'classification' => $query->createNamedParameter($extraData['classification']),
920
-				'uid' => $query->createNamedParameter($extraData['uid']),
921
-			])
922
-			->execute();
923
-
924
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
925
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
926
-			[
927
-				'calendarId' => $calendarId,
928
-				'calendarData' => $this->getCalendarById($calendarId),
929
-				'shares' => $this->getShares($calendarId),
930
-				'objectData' => $this->getCalendarObject($calendarId, $objectUri),
931
-			]
932
-		));
933
-		$this->addChange($calendarId, $objectUri, 1);
934
-
935
-		return '"' . $extraData['etag'] . '"';
936
-	}
937
-
938
-	/**
939
-	 * Updates an existing calendarobject, based on it's uri.
940
-	 *
941
-	 * The object uri is only the basename, or filename and not a full path.
942
-	 *
943
-	 * It is possible return an etag from this function, which will be used in
944
-	 * the response to this PUT request. Note that the ETag must be surrounded
945
-	 * by double-quotes.
946
-	 *
947
-	 * However, you should only really return this ETag if you don't mangle the
948
-	 * calendar-data. If the result of a subsequent GET to this object is not
949
-	 * the exact same as this request body, you should omit the ETag.
950
-	 *
951
-	 * @param mixed $calendarId
952
-	 * @param string $objectUri
953
-	 * @param string $calendarData
954
-	 * @return string
955
-	 */
956
-	function updateCalendarObject($calendarId, $objectUri, $calendarData) {
957
-		$extraData = $this->getDenormalizedData($calendarData);
958
-
959
-		$query = $this->db->getQueryBuilder();
960
-		$query->update('calendarobjects')
961
-				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
962
-				->set('lastmodified', $query->createNamedParameter(time()))
963
-				->set('etag', $query->createNamedParameter($extraData['etag']))
964
-				->set('size', $query->createNamedParameter($extraData['size']))
965
-				->set('componenttype', $query->createNamedParameter($extraData['componentType']))
966
-				->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
967
-				->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
968
-				->set('classification', $query->createNamedParameter($extraData['classification']))
969
-				->set('uid', $query->createNamedParameter($extraData['uid']))
970
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
971
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
972
-			->execute();
973
-
974
-		$data = $this->getCalendarObject($calendarId, $objectUri);
975
-		if (is_array($data)) {
976
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
977
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
978
-				[
979
-					'calendarId' => $calendarId,
980
-					'calendarData' => $this->getCalendarById($calendarId),
981
-					'shares' => $this->getShares($calendarId),
982
-					'objectData' => $data,
983
-				]
984
-			));
985
-		}
986
-		$this->addChange($calendarId, $objectUri, 2);
987
-
988
-		return '"' . $extraData['etag'] . '"';
989
-	}
990
-
991
-	/**
992
-	 * @param int $calendarObjectId
993
-	 * @param int $classification
994
-	 */
995
-	public function setClassification($calendarObjectId, $classification) {
996
-		if (!in_array($classification, [
997
-			self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
998
-		])) {
999
-			throw new \InvalidArgumentException();
1000
-		}
1001
-		$query = $this->db->getQueryBuilder();
1002
-		$query->update('calendarobjects')
1003
-			->set('classification', $query->createNamedParameter($classification))
1004
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1005
-			->execute();
1006
-	}
1007
-
1008
-	/**
1009
-	 * Deletes an existing calendar object.
1010
-	 *
1011
-	 * The object uri is only the basename, or filename and not a full path.
1012
-	 *
1013
-	 * @param mixed $calendarId
1014
-	 * @param string $objectUri
1015
-	 * @return void
1016
-	 */
1017
-	function deleteCalendarObject($calendarId, $objectUri) {
1018
-		$data = $this->getCalendarObject($calendarId, $objectUri);
1019
-		if (is_array($data)) {
1020
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1021
-				'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1022
-				[
1023
-					'calendarId' => $calendarId,
1024
-					'calendarData' => $this->getCalendarById($calendarId),
1025
-					'shares' => $this->getShares($calendarId),
1026
-					'objectData' => $data,
1027
-				]
1028
-			));
1029
-		}
1030
-
1031
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ?');
1032
-		$stmt->execute([$calendarId, $objectUri]);
1033
-
1034
-		$this->addChange($calendarId, $objectUri, 3);
1035
-	}
1036
-
1037
-	/**
1038
-	 * Performs a calendar-query on the contents of this calendar.
1039
-	 *
1040
-	 * The calendar-query is defined in RFC4791 : CalDAV. Using the
1041
-	 * calendar-query it is possible for a client to request a specific set of
1042
-	 * object, based on contents of iCalendar properties, date-ranges and
1043
-	 * iCalendar component types (VTODO, VEVENT).
1044
-	 *
1045
-	 * This method should just return a list of (relative) urls that match this
1046
-	 * query.
1047
-	 *
1048
-	 * The list of filters are specified as an array. The exact array is
1049
-	 * documented by Sabre\CalDAV\CalendarQueryParser.
1050
-	 *
1051
-	 * Note that it is extremely likely that getCalendarObject for every path
1052
-	 * returned from this method will be called almost immediately after. You
1053
-	 * may want to anticipate this to speed up these requests.
1054
-	 *
1055
-	 * This method provides a default implementation, which parses *all* the
1056
-	 * iCalendar objects in the specified calendar.
1057
-	 *
1058
-	 * This default may well be good enough for personal use, and calendars
1059
-	 * that aren't very large. But if you anticipate high usage, big calendars
1060
-	 * or high loads, you are strongly advised to optimize certain paths.
1061
-	 *
1062
-	 * The best way to do so is override this method and to optimize
1063
-	 * specifically for 'common filters'.
1064
-	 *
1065
-	 * Requests that are extremely common are:
1066
-	 *   * requests for just VEVENTS
1067
-	 *   * requests for just VTODO
1068
-	 *   * requests with a time-range-filter on either VEVENT or VTODO.
1069
-	 *
1070
-	 * ..and combinations of these requests. It may not be worth it to try to
1071
-	 * handle every possible situation and just rely on the (relatively
1072
-	 * easy to use) CalendarQueryValidator to handle the rest.
1073
-	 *
1074
-	 * Note that especially time-range-filters may be difficult to parse. A
1075
-	 * time-range filter specified on a VEVENT must for instance also handle
1076
-	 * recurrence rules correctly.
1077
-	 * A good example of how to interprete all these filters can also simply
1078
-	 * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1079
-	 * as possible, so it gives you a good idea on what type of stuff you need
1080
-	 * to think of.
1081
-	 *
1082
-	 * @param mixed $calendarId
1083
-	 * @param array $filters
1084
-	 * @return array
1085
-	 */
1086
-	function calendarQuery($calendarId, array $filters) {
1087
-		$componentType = null;
1088
-		$requirePostFilter = true;
1089
-		$timeRange = null;
1090
-
1091
-		// if no filters were specified, we don't need to filter after a query
1092
-		if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1093
-			$requirePostFilter = false;
1094
-		}
1095
-
1096
-		// Figuring out if there's a component filter
1097
-		if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1098
-			$componentType = $filters['comp-filters'][0]['name'];
1099
-
1100
-			// Checking if we need post-filters
1101
-			if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1102
-				$requirePostFilter = false;
1103
-			}
1104
-			// There was a time-range filter
1105
-			if ($componentType == 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1106
-				$timeRange = $filters['comp-filters'][0]['time-range'];
1107
-
1108
-				// If start time OR the end time is not specified, we can do a
1109
-				// 100% accurate mysql query.
1110
-				if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1111
-					$requirePostFilter = false;
1112
-				}
1113
-			}
1114
-
1115
-		}
1116
-		$columns = ['uri'];
1117
-		if ($requirePostFilter) {
1118
-			$columns = ['uri', 'calendardata'];
1119
-		}
1120
-		$query = $this->db->getQueryBuilder();
1121
-		$query->select($columns)
1122
-			->from('calendarobjects')
1123
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
1124
-
1125
-		if ($componentType) {
1126
-			$query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1127
-		}
1128
-
1129
-		if ($timeRange && $timeRange['start']) {
1130
-			$query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1131
-		}
1132
-		if ($timeRange && $timeRange['end']) {
1133
-			$query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1134
-		}
1135
-
1136
-		$stmt = $query->execute();
1137
-
1138
-		$result = [];
1139
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1140
-			if ($requirePostFilter) {
1141
-				if (!$this->validateFilterForObject($row, $filters)) {
1142
-					continue;
1143
-				}
1144
-			}
1145
-			$result[] = $row['uri'];
1146
-		}
1147
-
1148
-		return $result;
1149
-	}
1150
-
1151
-	/**
1152
-	 * Searches through all of a users calendars and calendar objects to find
1153
-	 * an object with a specific UID.
1154
-	 *
1155
-	 * This method should return the path to this object, relative to the
1156
-	 * calendar home, so this path usually only contains two parts:
1157
-	 *
1158
-	 * calendarpath/objectpath.ics
1159
-	 *
1160
-	 * If the uid is not found, return null.
1161
-	 *
1162
-	 * This method should only consider * objects that the principal owns, so
1163
-	 * any calendars owned by other principals that also appear in this
1164
-	 * collection should be ignored.
1165
-	 *
1166
-	 * @param string $principalUri
1167
-	 * @param string $uid
1168
-	 * @return string|null
1169
-	 */
1170
-	function getCalendarObjectByUID($principalUri, $uid) {
1171
-
1172
-		$query = $this->db->getQueryBuilder();
1173
-		$query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1174
-			->from('calendarobjects', 'co')
1175
-			->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1176
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1177
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1178
-
1179
-		$stmt = $query->execute();
1180
-
1181
-		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1182
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1183
-		}
1184
-
1185
-		return null;
1186
-	}
1187
-
1188
-	/**
1189
-	 * The getChanges method returns all the changes that have happened, since
1190
-	 * the specified syncToken in the specified calendar.
1191
-	 *
1192
-	 * This function should return an array, such as the following:
1193
-	 *
1194
-	 * [
1195
-	 *   'syncToken' => 'The current synctoken',
1196
-	 *   'added'   => [
1197
-	 *      'new.txt',
1198
-	 *   ],
1199
-	 *   'modified'   => [
1200
-	 *      'modified.txt',
1201
-	 *   ],
1202
-	 *   'deleted' => [
1203
-	 *      'foo.php.bak',
1204
-	 *      'old.txt'
1205
-	 *   ]
1206
-	 * );
1207
-	 *
1208
-	 * The returned syncToken property should reflect the *current* syncToken
1209
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1210
-	 * property This is * needed here too, to ensure the operation is atomic.
1211
-	 *
1212
-	 * If the $syncToken argument is specified as null, this is an initial
1213
-	 * sync, and all members should be reported.
1214
-	 *
1215
-	 * The modified property is an array of nodenames that have changed since
1216
-	 * the last token.
1217
-	 *
1218
-	 * The deleted property is an array with nodenames, that have been deleted
1219
-	 * from collection.
1220
-	 *
1221
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
1222
-	 * 1, you only have to report changes that happened only directly in
1223
-	 * immediate descendants. If it's 2, it should also include changes from
1224
-	 * the nodes below the child collections. (grandchildren)
1225
-	 *
1226
-	 * The $limit argument allows a client to specify how many results should
1227
-	 * be returned at most. If the limit is not specified, it should be treated
1228
-	 * as infinite.
1229
-	 *
1230
-	 * If the limit (infinite or not) is higher than you're willing to return,
1231
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1232
-	 *
1233
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
1234
-	 * return null.
1235
-	 *
1236
-	 * The limit is 'suggestive'. You are free to ignore it.
1237
-	 *
1238
-	 * @param string $calendarId
1239
-	 * @param string $syncToken
1240
-	 * @param int $syncLevel
1241
-	 * @param int $limit
1242
-	 * @return array
1243
-	 */
1244
-	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1245
-		// Current synctoken
1246
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1247
-		$stmt->execute([ $calendarId ]);
1248
-		$currentToken = $stmt->fetchColumn(0);
1249
-
1250
-		if (is_null($currentToken)) {
1251
-			return null;
1252
-		}
1253
-
1254
-		$result = [
1255
-			'syncToken' => $currentToken,
1256
-			'added'     => [],
1257
-			'modified'  => [],
1258
-			'deleted'   => [],
1259
-		];
1260
-
1261
-		if ($syncToken) {
1262
-
1263
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1264
-			if ($limit>0) {
1265
-				$query.= " `LIMIT` " . (int)$limit;
1266
-			}
1267
-
1268
-			// Fetching all changes
1269
-			$stmt = $this->db->prepare($query);
1270
-			$stmt->execute([$syncToken, $currentToken, $calendarId]);
1271
-
1272
-			$changes = [];
1273
-
1274
-			// This loop ensures that any duplicates are overwritten, only the
1275
-			// last change on a node is relevant.
1276
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1277
-
1278
-				$changes[$row['uri']] = $row['operation'];
1279
-
1280
-			}
1281
-
1282
-			foreach($changes as $uri => $operation) {
1283
-
1284
-				switch($operation) {
1285
-					case 1 :
1286
-						$result['added'][] = $uri;
1287
-						break;
1288
-					case 2 :
1289
-						$result['modified'][] = $uri;
1290
-						break;
1291
-					case 3 :
1292
-						$result['deleted'][] = $uri;
1293
-						break;
1294
-				}
1295
-
1296
-			}
1297
-		} else {
1298
-			// No synctoken supplied, this is the initial sync.
1299
-			$query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?";
1300
-			$stmt = $this->db->prepare($query);
1301
-			$stmt->execute([$calendarId]);
1302
-
1303
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1304
-		}
1305
-		return $result;
1306
-
1307
-	}
1308
-
1309
-	/**
1310
-	 * Returns a list of subscriptions for a principal.
1311
-	 *
1312
-	 * Every subscription is an array with the following keys:
1313
-	 *  * id, a unique id that will be used by other functions to modify the
1314
-	 *    subscription. This can be the same as the uri or a database key.
1315
-	 *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1316
-	 *  * principaluri. The owner of the subscription. Almost always the same as
1317
-	 *    principalUri passed to this method.
1318
-	 *
1319
-	 * Furthermore, all the subscription info must be returned too:
1320
-	 *
1321
-	 * 1. {DAV:}displayname
1322
-	 * 2. {http://apple.com/ns/ical/}refreshrate
1323
-	 * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1324
-	 *    should not be stripped).
1325
-	 * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1326
-	 *    should not be stripped).
1327
-	 * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1328
-	 *    attachments should not be stripped).
1329
-	 * 6. {http://calendarserver.org/ns/}source (Must be a
1330
-	 *     Sabre\DAV\Property\Href).
1331
-	 * 7. {http://apple.com/ns/ical/}calendar-color
1332
-	 * 8. {http://apple.com/ns/ical/}calendar-order
1333
-	 * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1334
-	 *    (should just be an instance of
1335
-	 *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1336
-	 *    default components).
1337
-	 *
1338
-	 * @param string $principalUri
1339
-	 * @return array
1340
-	 */
1341
-	function getSubscriptionsForUser($principalUri) {
1342
-		$fields = array_values($this->subscriptionPropertyMap);
1343
-		$fields[] = 'id';
1344
-		$fields[] = 'uri';
1345
-		$fields[] = 'source';
1346
-		$fields[] = 'principaluri';
1347
-		$fields[] = 'lastmodified';
1348
-
1349
-		$query = $this->db->getQueryBuilder();
1350
-		$query->select($fields)
1351
-			->from('calendarsubscriptions')
1352
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1353
-			->orderBy('calendarorder', 'asc');
1354
-		$stmt =$query->execute();
1355
-
1356
-		$subscriptions = [];
1357
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1358
-
1359
-			$subscription = [
1360
-				'id'           => $row['id'],
1361
-				'uri'          => $row['uri'],
1362
-				'principaluri' => $row['principaluri'],
1363
-				'source'       => $row['source'],
1364
-				'lastmodified' => $row['lastmodified'],
1365
-
1366
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1367
-			];
1368
-
1369
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1370
-				if (!is_null($row[$dbName])) {
1371
-					$subscription[$xmlName] = $row[$dbName];
1372
-				}
1373
-			}
1374
-
1375
-			$subscriptions[] = $subscription;
1376
-
1377
-		}
1378
-
1379
-		return $subscriptions;
1380
-	}
1381
-
1382
-	/**
1383
-	 * Creates a new subscription for a principal.
1384
-	 *
1385
-	 * If the creation was a success, an id must be returned that can be used to reference
1386
-	 * this subscription in other methods, such as updateSubscription.
1387
-	 *
1388
-	 * @param string $principalUri
1389
-	 * @param string $uri
1390
-	 * @param array $properties
1391
-	 * @return mixed
1392
-	 */
1393
-	function createSubscription($principalUri, $uri, array $properties) {
1394
-
1395
-		if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1396
-			throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1397
-		}
1398
-
1399
-		$values = [
1400
-			'principaluri' => $principalUri,
1401
-			'uri'          => $uri,
1402
-			'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1403
-			'lastmodified' => time(),
1404
-		];
1405
-
1406
-		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1407
-
1408
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1409
-			if (array_key_exists($xmlName, $properties)) {
1410
-					$values[$dbName] = $properties[$xmlName];
1411
-					if (in_array($dbName, $propertiesBoolean)) {
1412
-						$values[$dbName] = true;
1413
-				}
1414
-			}
1415
-		}
1416
-
1417
-		$valuesToInsert = array();
1418
-
1419
-		$query = $this->db->getQueryBuilder();
1420
-
1421
-		foreach (array_keys($values) as $name) {
1422
-			$valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1423
-		}
1424
-
1425
-		$query->insert('calendarsubscriptions')
1426
-			->values($valuesToInsert)
1427
-			->execute();
1428
-
1429
-		return $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1430
-	}
1431
-
1432
-	/**
1433
-	 * Updates a subscription
1434
-	 *
1435
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1436
-	 * To do the actual updates, you must tell this object which properties
1437
-	 * you're going to process with the handle() method.
1438
-	 *
1439
-	 * Calling the handle method is like telling the PropPatch object "I
1440
-	 * promise I can handle updating this property".
1441
-	 *
1442
-	 * Read the PropPatch documentation for more info and examples.
1443
-	 *
1444
-	 * @param mixed $subscriptionId
1445
-	 * @param PropPatch $propPatch
1446
-	 * @return void
1447
-	 */
1448
-	function updateSubscription($subscriptionId, PropPatch $propPatch) {
1449
-		$supportedProperties = array_keys($this->subscriptionPropertyMap);
1450
-		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
1451
-
1452
-		$propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1453
-
1454
-			$newValues = [];
1455
-
1456
-			foreach($mutations as $propertyName=>$propertyValue) {
1457
-				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1458
-					$newValues['source'] = $propertyValue->getHref();
1459
-				} else {
1460
-					$fieldName = $this->subscriptionPropertyMap[$propertyName];
1461
-					$newValues[$fieldName] = $propertyValue;
1462
-				}
1463
-			}
1464
-
1465
-			$query = $this->db->getQueryBuilder();
1466
-			$query->update('calendarsubscriptions')
1467
-				->set('lastmodified', $query->createNamedParameter(time()));
1468
-			foreach($newValues as $fieldName=>$value) {
1469
-				$query->set($fieldName, $query->createNamedParameter($value));
1470
-			}
1471
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1472
-				->execute();
1473
-
1474
-			return true;
1475
-
1476
-		});
1477
-	}
1478
-
1479
-	/**
1480
-	 * Deletes a subscription.
1481
-	 *
1482
-	 * @param mixed $subscriptionId
1483
-	 * @return void
1484
-	 */
1485
-	function deleteSubscription($subscriptionId) {
1486
-		$query = $this->db->getQueryBuilder();
1487
-		$query->delete('calendarsubscriptions')
1488
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1489
-			->execute();
1490
-	}
1491
-
1492
-	/**
1493
-	 * Returns a single scheduling object for the inbox collection.
1494
-	 *
1495
-	 * The returned array should contain the following elements:
1496
-	 *   * uri - A unique basename for the object. This will be used to
1497
-	 *           construct a full uri.
1498
-	 *   * calendardata - The iCalendar object
1499
-	 *   * lastmodified - The last modification date. Can be an int for a unix
1500
-	 *                    timestamp, or a PHP DateTime object.
1501
-	 *   * etag - A unique token that must change if the object changed.
1502
-	 *   * size - The size of the object, in bytes.
1503
-	 *
1504
-	 * @param string $principalUri
1505
-	 * @param string $objectUri
1506
-	 * @return array
1507
-	 */
1508
-	function getSchedulingObject($principalUri, $objectUri) {
1509
-		$query = $this->db->getQueryBuilder();
1510
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1511
-			->from('schedulingobjects')
1512
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1513
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1514
-			->execute();
1515
-
1516
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
1517
-
1518
-		if(!$row) {
1519
-			return null;
1520
-		}
1521
-
1522
-		return [
1523
-				'uri'          => $row['uri'],
1524
-				'calendardata' => $row['calendardata'],
1525
-				'lastmodified' => $row['lastmodified'],
1526
-				'etag'         => '"' . $row['etag'] . '"',
1527
-				'size'         => (int)$row['size'],
1528
-		];
1529
-	}
1530
-
1531
-	/**
1532
-	 * Returns all scheduling objects for the inbox collection.
1533
-	 *
1534
-	 * These objects should be returned as an array. Every item in the array
1535
-	 * should follow the same structure as returned from getSchedulingObject.
1536
-	 *
1537
-	 * The main difference is that 'calendardata' is optional.
1538
-	 *
1539
-	 * @param string $principalUri
1540
-	 * @return array
1541
-	 */
1542
-	function getSchedulingObjects($principalUri) {
1543
-		$query = $this->db->getQueryBuilder();
1544
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1545
-				->from('schedulingobjects')
1546
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1547
-				->execute();
1548
-
1549
-		$result = [];
1550
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1551
-			$result[] = [
1552
-					'calendardata' => $row['calendardata'],
1553
-					'uri'          => $row['uri'],
1554
-					'lastmodified' => $row['lastmodified'],
1555
-					'etag'         => '"' . $row['etag'] . '"',
1556
-					'size'         => (int)$row['size'],
1557
-			];
1558
-		}
1559
-
1560
-		return $result;
1561
-	}
1562
-
1563
-	/**
1564
-	 * Deletes a scheduling object from the inbox collection.
1565
-	 *
1566
-	 * @param string $principalUri
1567
-	 * @param string $objectUri
1568
-	 * @return void
1569
-	 */
1570
-	function deleteSchedulingObject($principalUri, $objectUri) {
1571
-		$query = $this->db->getQueryBuilder();
1572
-		$query->delete('schedulingobjects')
1573
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1574
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1575
-				->execute();
1576
-	}
1577
-
1578
-	/**
1579
-	 * Creates a new scheduling object. This should land in a users' inbox.
1580
-	 *
1581
-	 * @param string $principalUri
1582
-	 * @param string $objectUri
1583
-	 * @param string $objectData
1584
-	 * @return void
1585
-	 */
1586
-	function createSchedulingObject($principalUri, $objectUri, $objectData) {
1587
-		$query = $this->db->getQueryBuilder();
1588
-		$query->insert('schedulingobjects')
1589
-			->values([
1590
-				'principaluri' => $query->createNamedParameter($principalUri),
1591
-				'calendardata' => $query->createNamedParameter($objectData),
1592
-				'uri' => $query->createNamedParameter($objectUri),
1593
-				'lastmodified' => $query->createNamedParameter(time()),
1594
-				'etag' => $query->createNamedParameter(md5($objectData)),
1595
-				'size' => $query->createNamedParameter(strlen($objectData))
1596
-			])
1597
-			->execute();
1598
-	}
1599
-
1600
-	/**
1601
-	 * Adds a change record to the calendarchanges table.
1602
-	 *
1603
-	 * @param mixed $calendarId
1604
-	 * @param string $objectUri
1605
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete.
1606
-	 * @return void
1607
-	 */
1608
-	protected function addChange($calendarId, $objectUri, $operation) {
1609
-
1610
-		$stmt = $this->db->prepare('INSERT INTO `*PREFIX*calendarchanges` (`uri`, `synctoken`, `calendarid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*calendars` WHERE `id` = ?');
1611
-		$stmt->execute([
1612
-			$objectUri,
1613
-			$calendarId,
1614
-			$operation,
1615
-			$calendarId
1616
-		]);
1617
-		$stmt = $this->db->prepare('UPDATE `*PREFIX*calendars` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
1618
-		$stmt->execute([
1619
-			$calendarId
1620
-		]);
1621
-
1622
-	}
1623
-
1624
-	/**
1625
-	 * Parses some information from calendar objects, used for optimized
1626
-	 * calendar-queries.
1627
-	 *
1628
-	 * Returns an array with the following keys:
1629
-	 *   * etag - An md5 checksum of the object without the quotes.
1630
-	 *   * size - Size of the object in bytes
1631
-	 *   * componentType - VEVENT, VTODO or VJOURNAL
1632
-	 *   * firstOccurence
1633
-	 *   * lastOccurence
1634
-	 *   * uid - value of the UID property
1635
-	 *
1636
-	 * @param string $calendarData
1637
-	 * @return array
1638
-	 */
1639
-	public function getDenormalizedData($calendarData) {
1640
-
1641
-		$vObject = Reader::read($calendarData);
1642
-		$componentType = null;
1643
-		$component = null;
1644
-		$firstOccurrence = null;
1645
-		$lastOccurrence = null;
1646
-		$uid = null;
1647
-		$classification = self::CLASSIFICATION_PUBLIC;
1648
-		foreach($vObject->getComponents() as $component) {
1649
-			if ($component->name!=='VTIMEZONE') {
1650
-				$componentType = $component->name;
1651
-				$uid = (string)$component->UID;
1652
-				break;
1653
-			}
1654
-		}
1655
-		if (!$componentType) {
1656
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
1657
-		}
1658
-		if ($componentType === 'VEVENT' && $component->DTSTART) {
1659
-			$firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
1660
-			// Finding the last occurrence is a bit harder
1661
-			if (!isset($component->RRULE)) {
1662
-				if (isset($component->DTEND)) {
1663
-					$lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
1664
-				} elseif (isset($component->DURATION)) {
1665
-					$endDate = clone $component->DTSTART->getDateTime();
1666
-					$endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
1667
-					$lastOccurrence = $endDate->getTimeStamp();
1668
-				} elseif (!$component->DTSTART->hasTime()) {
1669
-					$endDate = clone $component->DTSTART->getDateTime();
1670
-					$endDate->modify('+1 day');
1671
-					$lastOccurrence = $endDate->getTimeStamp();
1672
-				} else {
1673
-					$lastOccurrence = $firstOccurrence;
1674
-				}
1675
-			} else {
1676
-				$it = new EventIterator($vObject, (string)$component->UID);
1677
-				$maxDate = new \DateTime(self::MAX_DATE);
1678
-				if ($it->isInfinite()) {
1679
-					$lastOccurrence = $maxDate->getTimestamp();
1680
-				} else {
1681
-					$end = $it->getDtEnd();
1682
-					while($it->valid() && $end < $maxDate) {
1683
-						$end = $it->getDtEnd();
1684
-						$it->next();
1685
-
1686
-					}
1687
-					$lastOccurrence = $end->getTimestamp();
1688
-				}
1689
-
1690
-			}
1691
-		}
1692
-
1693
-		if ($component->CLASS) {
1694
-			$classification = CalDavBackend::CLASSIFICATION_PRIVATE;
1695
-			switch ($component->CLASS->getValue()) {
1696
-				case 'PUBLIC':
1697
-					$classification = CalDavBackend::CLASSIFICATION_PUBLIC;
1698
-					break;
1699
-				case 'CONFIDENTIAL':
1700
-					$classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
1701
-					break;
1702
-			}
1703
-		}
1704
-		return [
1705
-			'etag' => md5($calendarData),
1706
-			'size' => strlen($calendarData),
1707
-			'componentType' => $componentType,
1708
-			'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
1709
-			'lastOccurence'  => $lastOccurrence,
1710
-			'uid' => $uid,
1711
-			'classification' => $classification
1712
-		];
1713
-
1714
-	}
1715
-
1716
-	private function readBlob($cardData) {
1717
-		if (is_resource($cardData)) {
1718
-			return stream_get_contents($cardData);
1719
-		}
1720
-
1721
-		return $cardData;
1722
-	}
1723
-
1724
-	/**
1725
-	 * @param IShareable $shareable
1726
-	 * @param array $add
1727
-	 * @param array $remove
1728
-	 */
1729
-	public function updateShares($shareable, $add, $remove) {
1730
-		$calendarId = $shareable->getResourceId();
1731
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
1732
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
1733
-			[
1734
-				'calendarId' => $calendarId,
1735
-				'calendarData' => $this->getCalendarById($calendarId),
1736
-				'shares' => $this->getShares($calendarId),
1737
-				'add' => $add,
1738
-				'remove' => $remove,
1739
-			]));
1740
-		$this->sharingBackend->updateShares($shareable, $add, $remove);
1741
-	}
1742
-
1743
-	/**
1744
-	 * @param int $resourceId
1745
-	 * @return array
1746
-	 */
1747
-	public function getShares($resourceId) {
1748
-		return $this->sharingBackend->getShares($resourceId);
1749
-	}
1750
-
1751
-	/**
1752
-	 * @param boolean $value
1753
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
1754
-	 * @return string|null
1755
-	 */
1756
-	public function setPublishStatus($value, $calendar) {
1757
-		$query = $this->db->getQueryBuilder();
1758
-		if ($value) {
1759
-			$publicUri = $this->random->generate(16, ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_DIGITS);
1760
-			$query->insert('dav_shares')
1761
-				->values([
1762
-					'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
1763
-					'type' => $query->createNamedParameter('calendar'),
1764
-					'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
1765
-					'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
1766
-					'publicuri' => $query->createNamedParameter($publicUri)
1767
-				]);
1768
-			$query->execute();
1769
-			return $publicUri;
1770
-		}
1771
-		$query->delete('dav_shares')
1772
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1773
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
1774
-		$query->execute();
1775
-		return null;
1776
-	}
1777
-
1778
-	/**
1779
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
1780
-	 * @return mixed
1781
-	 */
1782
-	public function getPublishStatus($calendar) {
1783
-		$query = $this->db->getQueryBuilder();
1784
-		$result = $query->select('publicuri')
1785
-			->from('dav_shares')
1786
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1787
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
1788
-			->execute();
1789
-
1790
-		$row = $result->fetch();
1791
-		$result->closeCursor();
1792
-		return $row ? reset($row) : false;
1793
-	}
1794
-
1795
-	/**
1796
-	 * @param int $resourceId
1797
-	 * @param array $acl
1798
-	 * @return array
1799
-	 */
1800
-	public function applyShareAcl($resourceId, $acl) {
1801
-		return $this->sharingBackend->applyShareAcl($resourceId, $acl);
1802
-	}
1803
-
1804
-	private function convertPrincipal($principalUri, $toV2) {
1805
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1806
-			list(, $name) = URLUtil::splitPath($principalUri);
1807
-			if ($toV2 === true) {
1808
-				return "principals/users/$name";
1809
-			}
1810
-			return "principals/$name";
1811
-		}
1812
-		return $principalUri;
1813
-	}
381
+    /**
382
+     * @return array
383
+     */
384
+    public function getPublicCalendars() {
385
+        $fields = array_values($this->propertyMap);
386
+        $fields[] = 'a.id';
387
+        $fields[] = 'a.uri';
388
+        $fields[] = 'a.synctoken';
389
+        $fields[] = 'a.components';
390
+        $fields[] = 'a.principaluri';
391
+        $fields[] = 'a.transparent';
392
+        $fields[] = 's.access';
393
+        $fields[] = 's.publicuri';
394
+        $calendars = [];
395
+        $query = $this->db->getQueryBuilder();
396
+        $result = $query->select($fields)
397
+            ->from('dav_shares', 's')
398
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
399
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
400
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
401
+            ->execute();
402
+
403
+        while($row = $result->fetch()) {
404
+            list(, $name) = URLUtil::splitPath($row['principaluri']);
405
+            $row['displayname'] = $row['displayname'] . "($name)";
406
+            $components = [];
407
+            if ($row['components']) {
408
+                $components = explode(',',$row['components']);
409
+            }
410
+            $calendar = [
411
+                'id' => $row['id'],
412
+                'uri' => $row['publicuri'],
413
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
414
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
415
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
416
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
417
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
418
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
419
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
420
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
421
+            ];
422
+
423
+            foreach($this->propertyMap as $xmlName=>$dbName) {
424
+                $calendar[$xmlName] = $row[$dbName];
425
+            }
426
+
427
+            if (!isset($calendars[$calendar['id']])) {
428
+                $calendars[$calendar['id']] = $calendar;
429
+            }
430
+        }
431
+        $result->closeCursor();
432
+
433
+        return array_values($calendars);
434
+    }
435
+
436
+    /**
437
+     * @param string $uri
438
+     * @return array
439
+     * @throws NotFound
440
+     */
441
+    public function getPublicCalendar($uri) {
442
+        $fields = array_values($this->propertyMap);
443
+        $fields[] = 'a.id';
444
+        $fields[] = 'a.uri';
445
+        $fields[] = 'a.synctoken';
446
+        $fields[] = 'a.components';
447
+        $fields[] = 'a.principaluri';
448
+        $fields[] = 'a.transparent';
449
+        $fields[] = 's.access';
450
+        $fields[] = 's.publicuri';
451
+        $query = $this->db->getQueryBuilder();
452
+        $result = $query->select($fields)
453
+            ->from('dav_shares', 's')
454
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
455
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
456
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
457
+            ->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
458
+            ->execute();
459
+
460
+        $row = $result->fetch(\PDO::FETCH_ASSOC);
461
+
462
+        $result->closeCursor();
463
+
464
+        if ($row === false) {
465
+            throw new NotFound('Node with name \'' . $uri . '\' could not be found');
466
+        }
467
+
468
+        list(, $name) = URLUtil::splitPath($row['principaluri']);
469
+        $row['displayname'] = $row['displayname'] . ' ' . "($name)";
470
+        $components = [];
471
+        if ($row['components']) {
472
+            $components = explode(',',$row['components']);
473
+        }
474
+        $calendar = [
475
+            'id' => $row['id'],
476
+            'uri' => $row['publicuri'],
477
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
478
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
479
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
480
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
481
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
482
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
483
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
484
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
485
+        ];
486
+
487
+        foreach($this->propertyMap as $xmlName=>$dbName) {
488
+            $calendar[$xmlName] = $row[$dbName];
489
+        }
490
+
491
+        return $calendar;
492
+
493
+    }
494
+
495
+    /**
496
+     * @param string $principal
497
+     * @param string $uri
498
+     * @return array|null
499
+     */
500
+    public function getCalendarByUri($principal, $uri) {
501
+        $fields = array_values($this->propertyMap);
502
+        $fields[] = 'id';
503
+        $fields[] = 'uri';
504
+        $fields[] = 'synctoken';
505
+        $fields[] = 'components';
506
+        $fields[] = 'principaluri';
507
+        $fields[] = 'transparent';
508
+
509
+        // Making fields a comma-delimited list
510
+        $query = $this->db->getQueryBuilder();
511
+        $query->select($fields)->from('calendars')
512
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
513
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
514
+            ->setMaxResults(1);
515
+        $stmt = $query->execute();
516
+
517
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
518
+        $stmt->closeCursor();
519
+        if ($row === false) {
520
+            return null;
521
+        }
522
+
523
+        $components = [];
524
+        if ($row['components']) {
525
+            $components = explode(',',$row['components']);
526
+        }
527
+
528
+        $calendar = [
529
+            'id' => $row['id'],
530
+            'uri' => $row['uri'],
531
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
532
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
533
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
534
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
535
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
536
+        ];
537
+
538
+        foreach($this->propertyMap as $xmlName=>$dbName) {
539
+            $calendar[$xmlName] = $row[$dbName];
540
+        }
541
+
542
+        return $calendar;
543
+    }
544
+
545
+    public function getCalendarById($calendarId) {
546
+        $fields = array_values($this->propertyMap);
547
+        $fields[] = 'id';
548
+        $fields[] = 'uri';
549
+        $fields[] = 'synctoken';
550
+        $fields[] = 'components';
551
+        $fields[] = 'principaluri';
552
+        $fields[] = 'transparent';
553
+
554
+        // Making fields a comma-delimited list
555
+        $query = $this->db->getQueryBuilder();
556
+        $query->select($fields)->from('calendars')
557
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
558
+            ->setMaxResults(1);
559
+        $stmt = $query->execute();
560
+
561
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
562
+        $stmt->closeCursor();
563
+        if ($row === false) {
564
+            return null;
565
+        }
566
+
567
+        $components = [];
568
+        if ($row['components']) {
569
+            $components = explode(',',$row['components']);
570
+        }
571
+
572
+        $calendar = [
573
+            'id' => $row['id'],
574
+            'uri' => $row['uri'],
575
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
576
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
577
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
578
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
579
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
580
+        ];
581
+
582
+        foreach($this->propertyMap as $xmlName=>$dbName) {
583
+            $calendar[$xmlName] = $row[$dbName];
584
+        }
585
+
586
+        return $calendar;
587
+    }
588
+
589
+    /**
590
+     * Creates a new calendar for a principal.
591
+     *
592
+     * If the creation was a success, an id must be returned that can be used to reference
593
+     * this calendar in other methods, such as updateCalendar.
594
+     *
595
+     * @param string $principalUri
596
+     * @param string $calendarUri
597
+     * @param array $properties
598
+     * @return int
599
+     */
600
+    function createCalendar($principalUri, $calendarUri, array $properties) {
601
+        $values = [
602
+            'principaluri' => $this->convertPrincipal($principalUri, true),
603
+            'uri'          => $calendarUri,
604
+            'synctoken'    => 1,
605
+            'transparent'  => 0,
606
+            'components'   => 'VEVENT,VTODO',
607
+            'displayname'  => $calendarUri
608
+        ];
609
+
610
+        // Default value
611
+        $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
612
+        if (isset($properties[$sccs])) {
613
+            if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
614
+                throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
615
+            }
616
+            $values['components'] = implode(',',$properties[$sccs]->getValue());
617
+        }
618
+        $transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
619
+        if (isset($properties[$transp])) {
620
+            $values['transparent'] = $properties[$transp]->getValue()==='transparent';
621
+        }
622
+
623
+        foreach($this->propertyMap as $xmlName=>$dbName) {
624
+            if (isset($properties[$xmlName])) {
625
+                $values[$dbName] = $properties[$xmlName];
626
+            }
627
+        }
628
+
629
+        $query = $this->db->getQueryBuilder();
630
+        $query->insert('calendars');
631
+        foreach($values as $column => $value) {
632
+            $query->setValue($column, $query->createNamedParameter($value));
633
+        }
634
+        $query->execute();
635
+        $calendarId = $query->getLastInsertId();
636
+
637
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
638
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
639
+            [
640
+                'calendarId' => $calendarId,
641
+                'calendarData' => $this->getCalendarById($calendarId),
642
+        ]));
643
+
644
+        return $calendarId;
645
+    }
646
+
647
+    /**
648
+     * Updates properties for a calendar.
649
+     *
650
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
651
+     * To do the actual updates, you must tell this object which properties
652
+     * you're going to process with the handle() method.
653
+     *
654
+     * Calling the handle method is like telling the PropPatch object "I
655
+     * promise I can handle updating this property".
656
+     *
657
+     * Read the PropPatch documentation for more info and examples.
658
+     *
659
+     * @param PropPatch $propPatch
660
+     * @return void
661
+     */
662
+    function updateCalendar($calendarId, PropPatch $propPatch) {
663
+        $supportedProperties = array_keys($this->propertyMap);
664
+        $supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
665
+
666
+        $propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
667
+            $newValues = [];
668
+            foreach ($mutations as $propertyName => $propertyValue) {
669
+
670
+                switch ($propertyName) {
671
+                    case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
672
+                        $fieldName = 'transparent';
673
+                        $newValues[$fieldName] = $propertyValue->getValue() === 'transparent';
674
+                        break;
675
+                    default :
676
+                        $fieldName = $this->propertyMap[$propertyName];
677
+                        $newValues[$fieldName] = $propertyValue;
678
+                        break;
679
+                }
680
+
681
+            }
682
+            $query = $this->db->getQueryBuilder();
683
+            $query->update('calendars');
684
+            foreach ($newValues as $fieldName => $value) {
685
+                $query->set($fieldName, $query->createNamedParameter($value));
686
+            }
687
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
688
+            $query->execute();
689
+
690
+            $this->addChange($calendarId, "", 2);
691
+
692
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
693
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
694
+                [
695
+                    'calendarId' => $calendarId,
696
+                    'calendarData' => $this->getCalendarById($calendarId),
697
+                    'shares' => $this->getShares($calendarId),
698
+                    'propertyMutations' => $mutations,
699
+            ]));
700
+
701
+            return true;
702
+        });
703
+    }
704
+
705
+    /**
706
+     * Delete a calendar and all it's objects
707
+     *
708
+     * @param mixed $calendarId
709
+     * @return void
710
+     */
711
+    function deleteCalendar($calendarId) {
712
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
713
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
714
+            [
715
+                'calendarId' => $calendarId,
716
+                'calendarData' => $this->getCalendarById($calendarId),
717
+                'shares' => $this->getShares($calendarId),
718
+        ]));
719
+
720
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?');
721
+        $stmt->execute([$calendarId]);
722
+
723
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
724
+        $stmt->execute([$calendarId]);
725
+
726
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ?');
727
+        $stmt->execute([$calendarId]);
728
+
729
+        $this->sharingBackend->deleteAllShares($calendarId);
730
+    }
731
+
732
+    /**
733
+     * Delete all of an user's shares
734
+     *
735
+     * @param string $principaluri
736
+     * @return void
737
+     */
738
+    function deleteAllSharesByUser($principaluri) {
739
+        $this->sharingBackend->deleteAllSharesByUser($principaluri);
740
+    }
741
+
742
+    /**
743
+     * Returns all calendar objects within a calendar.
744
+     *
745
+     * Every item contains an array with the following keys:
746
+     *   * calendardata - The iCalendar-compatible calendar data
747
+     *   * uri - a unique key which will be used to construct the uri. This can
748
+     *     be any arbitrary string, but making sure it ends with '.ics' is a
749
+     *     good idea. This is only the basename, or filename, not the full
750
+     *     path.
751
+     *   * lastmodified - a timestamp of the last modification time
752
+     *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
753
+     *   '"abcdef"')
754
+     *   * size - The size of the calendar objects, in bytes.
755
+     *   * component - optional, a string containing the type of object, such
756
+     *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
757
+     *     the Content-Type header.
758
+     *
759
+     * Note that the etag is optional, but it's highly encouraged to return for
760
+     * speed reasons.
761
+     *
762
+     * The calendardata is also optional. If it's not returned
763
+     * 'getCalendarObject' will be called later, which *is* expected to return
764
+     * calendardata.
765
+     *
766
+     * If neither etag or size are specified, the calendardata will be
767
+     * used/fetched to determine these numbers. If both are specified the
768
+     * amount of times this is needed is reduced by a great degree.
769
+     *
770
+     * @param mixed $calendarId
771
+     * @return array
772
+     */
773
+    function getCalendarObjects($calendarId) {
774
+        $query = $this->db->getQueryBuilder();
775
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
776
+            ->from('calendarobjects')
777
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
778
+        $stmt = $query->execute();
779
+
780
+        $result = [];
781
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
782
+            $result[] = [
783
+                    'id'           => $row['id'],
784
+                    'uri'          => $row['uri'],
785
+                    'lastmodified' => $row['lastmodified'],
786
+                    'etag'         => '"' . $row['etag'] . '"',
787
+                    'calendarid'   => $row['calendarid'],
788
+                    'size'         => (int)$row['size'],
789
+                    'component'    => strtolower($row['componenttype']),
790
+                    'classification'=> (int)$row['classification']
791
+            ];
792
+        }
793
+
794
+        return $result;
795
+    }
796
+
797
+    /**
798
+     * Returns information from a single calendar object, based on it's object
799
+     * uri.
800
+     *
801
+     * The object uri is only the basename, or filename and not a full path.
802
+     *
803
+     * The returned array must have the same keys as getCalendarObjects. The
804
+     * 'calendardata' object is required here though, while it's not required
805
+     * for getCalendarObjects.
806
+     *
807
+     * This method must return null if the object did not exist.
808
+     *
809
+     * @param mixed $calendarId
810
+     * @param string $objectUri
811
+     * @return array|null
812
+     */
813
+    function getCalendarObject($calendarId, $objectUri) {
814
+
815
+        $query = $this->db->getQueryBuilder();
816
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
817
+                ->from('calendarobjects')
818
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
819
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)));
820
+        $stmt = $query->execute();
821
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
822
+
823
+        if(!$row) return null;
824
+
825
+        return [
826
+                'id'            => $row['id'],
827
+                'uri'           => $row['uri'],
828
+                'lastmodified'  => $row['lastmodified'],
829
+                'etag'          => '"' . $row['etag'] . '"',
830
+                'calendarid'    => $row['calendarid'],
831
+                'size'          => (int)$row['size'],
832
+                'calendardata'  => $this->readBlob($row['calendardata']),
833
+                'component'     => strtolower($row['componenttype']),
834
+                'classification'=> (int)$row['classification']
835
+        ];
836
+    }
837
+
838
+    /**
839
+     * Returns a list of calendar objects.
840
+     *
841
+     * This method should work identical to getCalendarObject, but instead
842
+     * return all the calendar objects in the list as an array.
843
+     *
844
+     * If the backend supports this, it may allow for some speed-ups.
845
+     *
846
+     * @param mixed $calendarId
847
+     * @param string[] $uris
848
+     * @return array
849
+     */
850
+    function getMultipleCalendarObjects($calendarId, array $uris) {
851
+        if (empty($uris)) {
852
+            return [];
853
+        }
854
+
855
+        $chunks = array_chunk($uris, 100);
856
+        $objects = [];
857
+
858
+        $query = $this->db->getQueryBuilder();
859
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
860
+            ->from('calendarobjects')
861
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
862
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
863
+
864
+        foreach ($chunks as $uris) {
865
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
866
+            $result = $query->execute();
867
+
868
+            while ($row = $result->fetch()) {
869
+                $objects[] = [
870
+                    'id'           => $row['id'],
871
+                    'uri'          => $row['uri'],
872
+                    'lastmodified' => $row['lastmodified'],
873
+                    'etag'         => '"' . $row['etag'] . '"',
874
+                    'calendarid'   => $row['calendarid'],
875
+                    'size'         => (int)$row['size'],
876
+                    'calendardata' => $this->readBlob($row['calendardata']),
877
+                    'component'    => strtolower($row['componenttype']),
878
+                    'classification' => (int)$row['classification']
879
+                ];
880
+            }
881
+            $result->closeCursor();
882
+        }
883
+        return $objects;
884
+    }
885
+
886
+    /**
887
+     * Creates a new calendar object.
888
+     *
889
+     * The object uri is only the basename, or filename and not a full path.
890
+     *
891
+     * It is possible return an etag from this function, which will be used in
892
+     * the response to this PUT request. Note that the ETag must be surrounded
893
+     * by double-quotes.
894
+     *
895
+     * However, you should only really return this ETag if you don't mangle the
896
+     * calendar-data. If the result of a subsequent GET to this object is not
897
+     * the exact same as this request body, you should omit the ETag.
898
+     *
899
+     * @param mixed $calendarId
900
+     * @param string $objectUri
901
+     * @param string $calendarData
902
+     * @return string
903
+     */
904
+    function createCalendarObject($calendarId, $objectUri, $calendarData) {
905
+        $extraData = $this->getDenormalizedData($calendarData);
906
+
907
+        $query = $this->db->getQueryBuilder();
908
+        $query->insert('calendarobjects')
909
+            ->values([
910
+                'calendarid' => $query->createNamedParameter($calendarId),
911
+                'uri' => $query->createNamedParameter($objectUri),
912
+                'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
913
+                'lastmodified' => $query->createNamedParameter(time()),
914
+                'etag' => $query->createNamedParameter($extraData['etag']),
915
+                'size' => $query->createNamedParameter($extraData['size']),
916
+                'componenttype' => $query->createNamedParameter($extraData['componentType']),
917
+                'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
918
+                'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
919
+                'classification' => $query->createNamedParameter($extraData['classification']),
920
+                'uid' => $query->createNamedParameter($extraData['uid']),
921
+            ])
922
+            ->execute();
923
+
924
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
925
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
926
+            [
927
+                'calendarId' => $calendarId,
928
+                'calendarData' => $this->getCalendarById($calendarId),
929
+                'shares' => $this->getShares($calendarId),
930
+                'objectData' => $this->getCalendarObject($calendarId, $objectUri),
931
+            ]
932
+        ));
933
+        $this->addChange($calendarId, $objectUri, 1);
934
+
935
+        return '"' . $extraData['etag'] . '"';
936
+    }
937
+
938
+    /**
939
+     * Updates an existing calendarobject, based on it's uri.
940
+     *
941
+     * The object uri is only the basename, or filename and not a full path.
942
+     *
943
+     * It is possible return an etag from this function, which will be used in
944
+     * the response to this PUT request. Note that the ETag must be surrounded
945
+     * by double-quotes.
946
+     *
947
+     * However, you should only really return this ETag if you don't mangle the
948
+     * calendar-data. If the result of a subsequent GET to this object is not
949
+     * the exact same as this request body, you should omit the ETag.
950
+     *
951
+     * @param mixed $calendarId
952
+     * @param string $objectUri
953
+     * @param string $calendarData
954
+     * @return string
955
+     */
956
+    function updateCalendarObject($calendarId, $objectUri, $calendarData) {
957
+        $extraData = $this->getDenormalizedData($calendarData);
958
+
959
+        $query = $this->db->getQueryBuilder();
960
+        $query->update('calendarobjects')
961
+                ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
962
+                ->set('lastmodified', $query->createNamedParameter(time()))
963
+                ->set('etag', $query->createNamedParameter($extraData['etag']))
964
+                ->set('size', $query->createNamedParameter($extraData['size']))
965
+                ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
966
+                ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
967
+                ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
968
+                ->set('classification', $query->createNamedParameter($extraData['classification']))
969
+                ->set('uid', $query->createNamedParameter($extraData['uid']))
970
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
971
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
972
+            ->execute();
973
+
974
+        $data = $this->getCalendarObject($calendarId, $objectUri);
975
+        if (is_array($data)) {
976
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
977
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
978
+                [
979
+                    'calendarId' => $calendarId,
980
+                    'calendarData' => $this->getCalendarById($calendarId),
981
+                    'shares' => $this->getShares($calendarId),
982
+                    'objectData' => $data,
983
+                ]
984
+            ));
985
+        }
986
+        $this->addChange($calendarId, $objectUri, 2);
987
+
988
+        return '"' . $extraData['etag'] . '"';
989
+    }
990
+
991
+    /**
992
+     * @param int $calendarObjectId
993
+     * @param int $classification
994
+     */
995
+    public function setClassification($calendarObjectId, $classification) {
996
+        if (!in_array($classification, [
997
+            self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
998
+        ])) {
999
+            throw new \InvalidArgumentException();
1000
+        }
1001
+        $query = $this->db->getQueryBuilder();
1002
+        $query->update('calendarobjects')
1003
+            ->set('classification', $query->createNamedParameter($classification))
1004
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1005
+            ->execute();
1006
+    }
1007
+
1008
+    /**
1009
+     * Deletes an existing calendar object.
1010
+     *
1011
+     * The object uri is only the basename, or filename and not a full path.
1012
+     *
1013
+     * @param mixed $calendarId
1014
+     * @param string $objectUri
1015
+     * @return void
1016
+     */
1017
+    function deleteCalendarObject($calendarId, $objectUri) {
1018
+        $data = $this->getCalendarObject($calendarId, $objectUri);
1019
+        if (is_array($data)) {
1020
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1021
+                '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1022
+                [
1023
+                    'calendarId' => $calendarId,
1024
+                    'calendarData' => $this->getCalendarById($calendarId),
1025
+                    'shares' => $this->getShares($calendarId),
1026
+                    'objectData' => $data,
1027
+                ]
1028
+            ));
1029
+        }
1030
+
1031
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ?');
1032
+        $stmt->execute([$calendarId, $objectUri]);
1033
+
1034
+        $this->addChange($calendarId, $objectUri, 3);
1035
+    }
1036
+
1037
+    /**
1038
+     * Performs a calendar-query on the contents of this calendar.
1039
+     *
1040
+     * The calendar-query is defined in RFC4791 : CalDAV. Using the
1041
+     * calendar-query it is possible for a client to request a specific set of
1042
+     * object, based on contents of iCalendar properties, date-ranges and
1043
+     * iCalendar component types (VTODO, VEVENT).
1044
+     *
1045
+     * This method should just return a list of (relative) urls that match this
1046
+     * query.
1047
+     *
1048
+     * The list of filters are specified as an array. The exact array is
1049
+     * documented by Sabre\CalDAV\CalendarQueryParser.
1050
+     *
1051
+     * Note that it is extremely likely that getCalendarObject for every path
1052
+     * returned from this method will be called almost immediately after. You
1053
+     * may want to anticipate this to speed up these requests.
1054
+     *
1055
+     * This method provides a default implementation, which parses *all* the
1056
+     * iCalendar objects in the specified calendar.
1057
+     *
1058
+     * This default may well be good enough for personal use, and calendars
1059
+     * that aren't very large. But if you anticipate high usage, big calendars
1060
+     * or high loads, you are strongly advised to optimize certain paths.
1061
+     *
1062
+     * The best way to do so is override this method and to optimize
1063
+     * specifically for 'common filters'.
1064
+     *
1065
+     * Requests that are extremely common are:
1066
+     *   * requests for just VEVENTS
1067
+     *   * requests for just VTODO
1068
+     *   * requests with a time-range-filter on either VEVENT or VTODO.
1069
+     *
1070
+     * ..and combinations of these requests. It may not be worth it to try to
1071
+     * handle every possible situation and just rely on the (relatively
1072
+     * easy to use) CalendarQueryValidator to handle the rest.
1073
+     *
1074
+     * Note that especially time-range-filters may be difficult to parse. A
1075
+     * time-range filter specified on a VEVENT must for instance also handle
1076
+     * recurrence rules correctly.
1077
+     * A good example of how to interprete all these filters can also simply
1078
+     * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1079
+     * as possible, so it gives you a good idea on what type of stuff you need
1080
+     * to think of.
1081
+     *
1082
+     * @param mixed $calendarId
1083
+     * @param array $filters
1084
+     * @return array
1085
+     */
1086
+    function calendarQuery($calendarId, array $filters) {
1087
+        $componentType = null;
1088
+        $requirePostFilter = true;
1089
+        $timeRange = null;
1090
+
1091
+        // if no filters were specified, we don't need to filter after a query
1092
+        if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1093
+            $requirePostFilter = false;
1094
+        }
1095
+
1096
+        // Figuring out if there's a component filter
1097
+        if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1098
+            $componentType = $filters['comp-filters'][0]['name'];
1099
+
1100
+            // Checking if we need post-filters
1101
+            if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1102
+                $requirePostFilter = false;
1103
+            }
1104
+            // There was a time-range filter
1105
+            if ($componentType == 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1106
+                $timeRange = $filters['comp-filters'][0]['time-range'];
1107
+
1108
+                // If start time OR the end time is not specified, we can do a
1109
+                // 100% accurate mysql query.
1110
+                if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1111
+                    $requirePostFilter = false;
1112
+                }
1113
+            }
1114
+
1115
+        }
1116
+        $columns = ['uri'];
1117
+        if ($requirePostFilter) {
1118
+            $columns = ['uri', 'calendardata'];
1119
+        }
1120
+        $query = $this->db->getQueryBuilder();
1121
+        $query->select($columns)
1122
+            ->from('calendarobjects')
1123
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
1124
+
1125
+        if ($componentType) {
1126
+            $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1127
+        }
1128
+
1129
+        if ($timeRange && $timeRange['start']) {
1130
+            $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1131
+        }
1132
+        if ($timeRange && $timeRange['end']) {
1133
+            $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1134
+        }
1135
+
1136
+        $stmt = $query->execute();
1137
+
1138
+        $result = [];
1139
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1140
+            if ($requirePostFilter) {
1141
+                if (!$this->validateFilterForObject($row, $filters)) {
1142
+                    continue;
1143
+                }
1144
+            }
1145
+            $result[] = $row['uri'];
1146
+        }
1147
+
1148
+        return $result;
1149
+    }
1150
+
1151
+    /**
1152
+     * Searches through all of a users calendars and calendar objects to find
1153
+     * an object with a specific UID.
1154
+     *
1155
+     * This method should return the path to this object, relative to the
1156
+     * calendar home, so this path usually only contains two parts:
1157
+     *
1158
+     * calendarpath/objectpath.ics
1159
+     *
1160
+     * If the uid is not found, return null.
1161
+     *
1162
+     * This method should only consider * objects that the principal owns, so
1163
+     * any calendars owned by other principals that also appear in this
1164
+     * collection should be ignored.
1165
+     *
1166
+     * @param string $principalUri
1167
+     * @param string $uid
1168
+     * @return string|null
1169
+     */
1170
+    function getCalendarObjectByUID($principalUri, $uid) {
1171
+
1172
+        $query = $this->db->getQueryBuilder();
1173
+        $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1174
+            ->from('calendarobjects', 'co')
1175
+            ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1176
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1177
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1178
+
1179
+        $stmt = $query->execute();
1180
+
1181
+        if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1182
+            return $row['calendaruri'] . '/' . $row['objecturi'];
1183
+        }
1184
+
1185
+        return null;
1186
+    }
1187
+
1188
+    /**
1189
+     * The getChanges method returns all the changes that have happened, since
1190
+     * the specified syncToken in the specified calendar.
1191
+     *
1192
+     * This function should return an array, such as the following:
1193
+     *
1194
+     * [
1195
+     *   'syncToken' => 'The current synctoken',
1196
+     *   'added'   => [
1197
+     *      'new.txt',
1198
+     *   ],
1199
+     *   'modified'   => [
1200
+     *      'modified.txt',
1201
+     *   ],
1202
+     *   'deleted' => [
1203
+     *      'foo.php.bak',
1204
+     *      'old.txt'
1205
+     *   ]
1206
+     * );
1207
+     *
1208
+     * The returned syncToken property should reflect the *current* syncToken
1209
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1210
+     * property This is * needed here too, to ensure the operation is atomic.
1211
+     *
1212
+     * If the $syncToken argument is specified as null, this is an initial
1213
+     * sync, and all members should be reported.
1214
+     *
1215
+     * The modified property is an array of nodenames that have changed since
1216
+     * the last token.
1217
+     *
1218
+     * The deleted property is an array with nodenames, that have been deleted
1219
+     * from collection.
1220
+     *
1221
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
1222
+     * 1, you only have to report changes that happened only directly in
1223
+     * immediate descendants. If it's 2, it should also include changes from
1224
+     * the nodes below the child collections. (grandchildren)
1225
+     *
1226
+     * The $limit argument allows a client to specify how many results should
1227
+     * be returned at most. If the limit is not specified, it should be treated
1228
+     * as infinite.
1229
+     *
1230
+     * If the limit (infinite or not) is higher than you're willing to return,
1231
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1232
+     *
1233
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
1234
+     * return null.
1235
+     *
1236
+     * The limit is 'suggestive'. You are free to ignore it.
1237
+     *
1238
+     * @param string $calendarId
1239
+     * @param string $syncToken
1240
+     * @param int $syncLevel
1241
+     * @param int $limit
1242
+     * @return array
1243
+     */
1244
+    function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1245
+        // Current synctoken
1246
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1247
+        $stmt->execute([ $calendarId ]);
1248
+        $currentToken = $stmt->fetchColumn(0);
1249
+
1250
+        if (is_null($currentToken)) {
1251
+            return null;
1252
+        }
1253
+
1254
+        $result = [
1255
+            'syncToken' => $currentToken,
1256
+            'added'     => [],
1257
+            'modified'  => [],
1258
+            'deleted'   => [],
1259
+        ];
1260
+
1261
+        if ($syncToken) {
1262
+
1263
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1264
+            if ($limit>0) {
1265
+                $query.= " `LIMIT` " . (int)$limit;
1266
+            }
1267
+
1268
+            // Fetching all changes
1269
+            $stmt = $this->db->prepare($query);
1270
+            $stmt->execute([$syncToken, $currentToken, $calendarId]);
1271
+
1272
+            $changes = [];
1273
+
1274
+            // This loop ensures that any duplicates are overwritten, only the
1275
+            // last change on a node is relevant.
1276
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1277
+
1278
+                $changes[$row['uri']] = $row['operation'];
1279
+
1280
+            }
1281
+
1282
+            foreach($changes as $uri => $operation) {
1283
+
1284
+                switch($operation) {
1285
+                    case 1 :
1286
+                        $result['added'][] = $uri;
1287
+                        break;
1288
+                    case 2 :
1289
+                        $result['modified'][] = $uri;
1290
+                        break;
1291
+                    case 3 :
1292
+                        $result['deleted'][] = $uri;
1293
+                        break;
1294
+                }
1295
+
1296
+            }
1297
+        } else {
1298
+            // No synctoken supplied, this is the initial sync.
1299
+            $query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?";
1300
+            $stmt = $this->db->prepare($query);
1301
+            $stmt->execute([$calendarId]);
1302
+
1303
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1304
+        }
1305
+        return $result;
1306
+
1307
+    }
1308
+
1309
+    /**
1310
+     * Returns a list of subscriptions for a principal.
1311
+     *
1312
+     * Every subscription is an array with the following keys:
1313
+     *  * id, a unique id that will be used by other functions to modify the
1314
+     *    subscription. This can be the same as the uri or a database key.
1315
+     *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1316
+     *  * principaluri. The owner of the subscription. Almost always the same as
1317
+     *    principalUri passed to this method.
1318
+     *
1319
+     * Furthermore, all the subscription info must be returned too:
1320
+     *
1321
+     * 1. {DAV:}displayname
1322
+     * 2. {http://apple.com/ns/ical/}refreshrate
1323
+     * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1324
+     *    should not be stripped).
1325
+     * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1326
+     *    should not be stripped).
1327
+     * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1328
+     *    attachments should not be stripped).
1329
+     * 6. {http://calendarserver.org/ns/}source (Must be a
1330
+     *     Sabre\DAV\Property\Href).
1331
+     * 7. {http://apple.com/ns/ical/}calendar-color
1332
+     * 8. {http://apple.com/ns/ical/}calendar-order
1333
+     * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1334
+     *    (should just be an instance of
1335
+     *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1336
+     *    default components).
1337
+     *
1338
+     * @param string $principalUri
1339
+     * @return array
1340
+     */
1341
+    function getSubscriptionsForUser($principalUri) {
1342
+        $fields = array_values($this->subscriptionPropertyMap);
1343
+        $fields[] = 'id';
1344
+        $fields[] = 'uri';
1345
+        $fields[] = 'source';
1346
+        $fields[] = 'principaluri';
1347
+        $fields[] = 'lastmodified';
1348
+
1349
+        $query = $this->db->getQueryBuilder();
1350
+        $query->select($fields)
1351
+            ->from('calendarsubscriptions')
1352
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1353
+            ->orderBy('calendarorder', 'asc');
1354
+        $stmt =$query->execute();
1355
+
1356
+        $subscriptions = [];
1357
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1358
+
1359
+            $subscription = [
1360
+                'id'           => $row['id'],
1361
+                'uri'          => $row['uri'],
1362
+                'principaluri' => $row['principaluri'],
1363
+                'source'       => $row['source'],
1364
+                'lastmodified' => $row['lastmodified'],
1365
+
1366
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1367
+            ];
1368
+
1369
+            foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1370
+                if (!is_null($row[$dbName])) {
1371
+                    $subscription[$xmlName] = $row[$dbName];
1372
+                }
1373
+            }
1374
+
1375
+            $subscriptions[] = $subscription;
1376
+
1377
+        }
1378
+
1379
+        return $subscriptions;
1380
+    }
1381
+
1382
+    /**
1383
+     * Creates a new subscription for a principal.
1384
+     *
1385
+     * If the creation was a success, an id must be returned that can be used to reference
1386
+     * this subscription in other methods, such as updateSubscription.
1387
+     *
1388
+     * @param string $principalUri
1389
+     * @param string $uri
1390
+     * @param array $properties
1391
+     * @return mixed
1392
+     */
1393
+    function createSubscription($principalUri, $uri, array $properties) {
1394
+
1395
+        if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1396
+            throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1397
+        }
1398
+
1399
+        $values = [
1400
+            'principaluri' => $principalUri,
1401
+            'uri'          => $uri,
1402
+            'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1403
+            'lastmodified' => time(),
1404
+        ];
1405
+
1406
+        $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1407
+
1408
+        foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1409
+            if (array_key_exists($xmlName, $properties)) {
1410
+                    $values[$dbName] = $properties[$xmlName];
1411
+                    if (in_array($dbName, $propertiesBoolean)) {
1412
+                        $values[$dbName] = true;
1413
+                }
1414
+            }
1415
+        }
1416
+
1417
+        $valuesToInsert = array();
1418
+
1419
+        $query = $this->db->getQueryBuilder();
1420
+
1421
+        foreach (array_keys($values) as $name) {
1422
+            $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1423
+        }
1424
+
1425
+        $query->insert('calendarsubscriptions')
1426
+            ->values($valuesToInsert)
1427
+            ->execute();
1428
+
1429
+        return $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1430
+    }
1431
+
1432
+    /**
1433
+     * Updates a subscription
1434
+     *
1435
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1436
+     * To do the actual updates, you must tell this object which properties
1437
+     * you're going to process with the handle() method.
1438
+     *
1439
+     * Calling the handle method is like telling the PropPatch object "I
1440
+     * promise I can handle updating this property".
1441
+     *
1442
+     * Read the PropPatch documentation for more info and examples.
1443
+     *
1444
+     * @param mixed $subscriptionId
1445
+     * @param PropPatch $propPatch
1446
+     * @return void
1447
+     */
1448
+    function updateSubscription($subscriptionId, PropPatch $propPatch) {
1449
+        $supportedProperties = array_keys($this->subscriptionPropertyMap);
1450
+        $supportedProperties[] = '{http://calendarserver.org/ns/}source';
1451
+
1452
+        $propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1453
+
1454
+            $newValues = [];
1455
+
1456
+            foreach($mutations as $propertyName=>$propertyValue) {
1457
+                if ($propertyName === '{http://calendarserver.org/ns/}source') {
1458
+                    $newValues['source'] = $propertyValue->getHref();
1459
+                } else {
1460
+                    $fieldName = $this->subscriptionPropertyMap[$propertyName];
1461
+                    $newValues[$fieldName] = $propertyValue;
1462
+                }
1463
+            }
1464
+
1465
+            $query = $this->db->getQueryBuilder();
1466
+            $query->update('calendarsubscriptions')
1467
+                ->set('lastmodified', $query->createNamedParameter(time()));
1468
+            foreach($newValues as $fieldName=>$value) {
1469
+                $query->set($fieldName, $query->createNamedParameter($value));
1470
+            }
1471
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1472
+                ->execute();
1473
+
1474
+            return true;
1475
+
1476
+        });
1477
+    }
1478
+
1479
+    /**
1480
+     * Deletes a subscription.
1481
+     *
1482
+     * @param mixed $subscriptionId
1483
+     * @return void
1484
+     */
1485
+    function deleteSubscription($subscriptionId) {
1486
+        $query = $this->db->getQueryBuilder();
1487
+        $query->delete('calendarsubscriptions')
1488
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1489
+            ->execute();
1490
+    }
1491
+
1492
+    /**
1493
+     * Returns a single scheduling object for the inbox collection.
1494
+     *
1495
+     * The returned array should contain the following elements:
1496
+     *   * uri - A unique basename for the object. This will be used to
1497
+     *           construct a full uri.
1498
+     *   * calendardata - The iCalendar object
1499
+     *   * lastmodified - The last modification date. Can be an int for a unix
1500
+     *                    timestamp, or a PHP DateTime object.
1501
+     *   * etag - A unique token that must change if the object changed.
1502
+     *   * size - The size of the object, in bytes.
1503
+     *
1504
+     * @param string $principalUri
1505
+     * @param string $objectUri
1506
+     * @return array
1507
+     */
1508
+    function getSchedulingObject($principalUri, $objectUri) {
1509
+        $query = $this->db->getQueryBuilder();
1510
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1511
+            ->from('schedulingobjects')
1512
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1513
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1514
+            ->execute();
1515
+
1516
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
1517
+
1518
+        if(!$row) {
1519
+            return null;
1520
+        }
1521
+
1522
+        return [
1523
+                'uri'          => $row['uri'],
1524
+                'calendardata' => $row['calendardata'],
1525
+                'lastmodified' => $row['lastmodified'],
1526
+                'etag'         => '"' . $row['etag'] . '"',
1527
+                'size'         => (int)$row['size'],
1528
+        ];
1529
+    }
1530
+
1531
+    /**
1532
+     * Returns all scheduling objects for the inbox collection.
1533
+     *
1534
+     * These objects should be returned as an array. Every item in the array
1535
+     * should follow the same structure as returned from getSchedulingObject.
1536
+     *
1537
+     * The main difference is that 'calendardata' is optional.
1538
+     *
1539
+     * @param string $principalUri
1540
+     * @return array
1541
+     */
1542
+    function getSchedulingObjects($principalUri) {
1543
+        $query = $this->db->getQueryBuilder();
1544
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1545
+                ->from('schedulingobjects')
1546
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1547
+                ->execute();
1548
+
1549
+        $result = [];
1550
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1551
+            $result[] = [
1552
+                    'calendardata' => $row['calendardata'],
1553
+                    'uri'          => $row['uri'],
1554
+                    'lastmodified' => $row['lastmodified'],
1555
+                    'etag'         => '"' . $row['etag'] . '"',
1556
+                    'size'         => (int)$row['size'],
1557
+            ];
1558
+        }
1559
+
1560
+        return $result;
1561
+    }
1562
+
1563
+    /**
1564
+     * Deletes a scheduling object from the inbox collection.
1565
+     *
1566
+     * @param string $principalUri
1567
+     * @param string $objectUri
1568
+     * @return void
1569
+     */
1570
+    function deleteSchedulingObject($principalUri, $objectUri) {
1571
+        $query = $this->db->getQueryBuilder();
1572
+        $query->delete('schedulingobjects')
1573
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1574
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1575
+                ->execute();
1576
+    }
1577
+
1578
+    /**
1579
+     * Creates a new scheduling object. This should land in a users' inbox.
1580
+     *
1581
+     * @param string $principalUri
1582
+     * @param string $objectUri
1583
+     * @param string $objectData
1584
+     * @return void
1585
+     */
1586
+    function createSchedulingObject($principalUri, $objectUri, $objectData) {
1587
+        $query = $this->db->getQueryBuilder();
1588
+        $query->insert('schedulingobjects')
1589
+            ->values([
1590
+                'principaluri' => $query->createNamedParameter($principalUri),
1591
+                'calendardata' => $query->createNamedParameter($objectData),
1592
+                'uri' => $query->createNamedParameter($objectUri),
1593
+                'lastmodified' => $query->createNamedParameter(time()),
1594
+                'etag' => $query->createNamedParameter(md5($objectData)),
1595
+                'size' => $query->createNamedParameter(strlen($objectData))
1596
+            ])
1597
+            ->execute();
1598
+    }
1599
+
1600
+    /**
1601
+     * Adds a change record to the calendarchanges table.
1602
+     *
1603
+     * @param mixed $calendarId
1604
+     * @param string $objectUri
1605
+     * @param int $operation 1 = add, 2 = modify, 3 = delete.
1606
+     * @return void
1607
+     */
1608
+    protected function addChange($calendarId, $objectUri, $operation) {
1609
+
1610
+        $stmt = $this->db->prepare('INSERT INTO `*PREFIX*calendarchanges` (`uri`, `synctoken`, `calendarid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*calendars` WHERE `id` = ?');
1611
+        $stmt->execute([
1612
+            $objectUri,
1613
+            $calendarId,
1614
+            $operation,
1615
+            $calendarId
1616
+        ]);
1617
+        $stmt = $this->db->prepare('UPDATE `*PREFIX*calendars` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
1618
+        $stmt->execute([
1619
+            $calendarId
1620
+        ]);
1621
+
1622
+    }
1623
+
1624
+    /**
1625
+     * Parses some information from calendar objects, used for optimized
1626
+     * calendar-queries.
1627
+     *
1628
+     * Returns an array with the following keys:
1629
+     *   * etag - An md5 checksum of the object without the quotes.
1630
+     *   * size - Size of the object in bytes
1631
+     *   * componentType - VEVENT, VTODO or VJOURNAL
1632
+     *   * firstOccurence
1633
+     *   * lastOccurence
1634
+     *   * uid - value of the UID property
1635
+     *
1636
+     * @param string $calendarData
1637
+     * @return array
1638
+     */
1639
+    public function getDenormalizedData($calendarData) {
1640
+
1641
+        $vObject = Reader::read($calendarData);
1642
+        $componentType = null;
1643
+        $component = null;
1644
+        $firstOccurrence = null;
1645
+        $lastOccurrence = null;
1646
+        $uid = null;
1647
+        $classification = self::CLASSIFICATION_PUBLIC;
1648
+        foreach($vObject->getComponents() as $component) {
1649
+            if ($component->name!=='VTIMEZONE') {
1650
+                $componentType = $component->name;
1651
+                $uid = (string)$component->UID;
1652
+                break;
1653
+            }
1654
+        }
1655
+        if (!$componentType) {
1656
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
1657
+        }
1658
+        if ($componentType === 'VEVENT' && $component->DTSTART) {
1659
+            $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
1660
+            // Finding the last occurrence is a bit harder
1661
+            if (!isset($component->RRULE)) {
1662
+                if (isset($component->DTEND)) {
1663
+                    $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
1664
+                } elseif (isset($component->DURATION)) {
1665
+                    $endDate = clone $component->DTSTART->getDateTime();
1666
+                    $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
1667
+                    $lastOccurrence = $endDate->getTimeStamp();
1668
+                } elseif (!$component->DTSTART->hasTime()) {
1669
+                    $endDate = clone $component->DTSTART->getDateTime();
1670
+                    $endDate->modify('+1 day');
1671
+                    $lastOccurrence = $endDate->getTimeStamp();
1672
+                } else {
1673
+                    $lastOccurrence = $firstOccurrence;
1674
+                }
1675
+            } else {
1676
+                $it = new EventIterator($vObject, (string)$component->UID);
1677
+                $maxDate = new \DateTime(self::MAX_DATE);
1678
+                if ($it->isInfinite()) {
1679
+                    $lastOccurrence = $maxDate->getTimestamp();
1680
+                } else {
1681
+                    $end = $it->getDtEnd();
1682
+                    while($it->valid() && $end < $maxDate) {
1683
+                        $end = $it->getDtEnd();
1684
+                        $it->next();
1685
+
1686
+                    }
1687
+                    $lastOccurrence = $end->getTimestamp();
1688
+                }
1689
+
1690
+            }
1691
+        }
1692
+
1693
+        if ($component->CLASS) {
1694
+            $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
1695
+            switch ($component->CLASS->getValue()) {
1696
+                case 'PUBLIC':
1697
+                    $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
1698
+                    break;
1699
+                case 'CONFIDENTIAL':
1700
+                    $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
1701
+                    break;
1702
+            }
1703
+        }
1704
+        return [
1705
+            'etag' => md5($calendarData),
1706
+            'size' => strlen($calendarData),
1707
+            'componentType' => $componentType,
1708
+            'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
1709
+            'lastOccurence'  => $lastOccurrence,
1710
+            'uid' => $uid,
1711
+            'classification' => $classification
1712
+        ];
1713
+
1714
+    }
1715
+
1716
+    private function readBlob($cardData) {
1717
+        if (is_resource($cardData)) {
1718
+            return stream_get_contents($cardData);
1719
+        }
1720
+
1721
+        return $cardData;
1722
+    }
1723
+
1724
+    /**
1725
+     * @param IShareable $shareable
1726
+     * @param array $add
1727
+     * @param array $remove
1728
+     */
1729
+    public function updateShares($shareable, $add, $remove) {
1730
+        $calendarId = $shareable->getResourceId();
1731
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
1732
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
1733
+            [
1734
+                'calendarId' => $calendarId,
1735
+                'calendarData' => $this->getCalendarById($calendarId),
1736
+                'shares' => $this->getShares($calendarId),
1737
+                'add' => $add,
1738
+                'remove' => $remove,
1739
+            ]));
1740
+        $this->sharingBackend->updateShares($shareable, $add, $remove);
1741
+    }
1742
+
1743
+    /**
1744
+     * @param int $resourceId
1745
+     * @return array
1746
+     */
1747
+    public function getShares($resourceId) {
1748
+        return $this->sharingBackend->getShares($resourceId);
1749
+    }
1750
+
1751
+    /**
1752
+     * @param boolean $value
1753
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
1754
+     * @return string|null
1755
+     */
1756
+    public function setPublishStatus($value, $calendar) {
1757
+        $query = $this->db->getQueryBuilder();
1758
+        if ($value) {
1759
+            $publicUri = $this->random->generate(16, ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_DIGITS);
1760
+            $query->insert('dav_shares')
1761
+                ->values([
1762
+                    'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
1763
+                    'type' => $query->createNamedParameter('calendar'),
1764
+                    'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
1765
+                    'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
1766
+                    'publicuri' => $query->createNamedParameter($publicUri)
1767
+                ]);
1768
+            $query->execute();
1769
+            return $publicUri;
1770
+        }
1771
+        $query->delete('dav_shares')
1772
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1773
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
1774
+        $query->execute();
1775
+        return null;
1776
+    }
1777
+
1778
+    /**
1779
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
1780
+     * @return mixed
1781
+     */
1782
+    public function getPublishStatus($calendar) {
1783
+        $query = $this->db->getQueryBuilder();
1784
+        $result = $query->select('publicuri')
1785
+            ->from('dav_shares')
1786
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1787
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
1788
+            ->execute();
1789
+
1790
+        $row = $result->fetch();
1791
+        $result->closeCursor();
1792
+        return $row ? reset($row) : false;
1793
+    }
1794
+
1795
+    /**
1796
+     * @param int $resourceId
1797
+     * @param array $acl
1798
+     * @return array
1799
+     */
1800
+    public function applyShareAcl($resourceId, $acl) {
1801
+        return $this->sharingBackend->applyShareAcl($resourceId, $acl);
1802
+    }
1803
+
1804
+    private function convertPrincipal($principalUri, $toV2) {
1805
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1806
+            list(, $name) = URLUtil::splitPath($principalUri);
1807
+            if ($toV2 === true) {
1808
+                return "principals/users/$name";
1809
+            }
1810
+            return "principals/$name";
1811
+        }
1812
+        return $principalUri;
1813
+    }
1814 1814
 }
Please login to merge, or discard this patch.
Spacing   +109 added lines, -109 removed lines patch added patch discarded remove patch
@@ -179,7 +179,7 @@  discard block
 block discarded – undo
179 179
 			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
180 180
 		}
181 181
 
182
-		return (int)$query->execute()->fetchColumn();
182
+		return (int) $query->execute()->fetchColumn();
183 183
 	}
184 184
 
185 185
 	/**
@@ -226,25 +226,25 @@  discard block
 block discarded – undo
226 226
 		$stmt = $query->execute();
227 227
 
228 228
 		$calendars = [];
229
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
229
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
230 230
 
231 231
 			$components = [];
232 232
 			if ($row['components']) {
233
-				$components = explode(',',$row['components']);
233
+				$components = explode(',', $row['components']);
234 234
 			}
235 235
 
236 236
 			$calendar = [
237 237
 				'id' => $row['id'],
238 238
 				'uri' => $row['uri'],
239 239
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
240
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
241
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
242
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
243
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
244
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
240
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
241
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
242
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
243
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
244
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
245 245
 			];
246 246
 
247
-			foreach($this->propertyMap as $xmlName=>$dbName) {
247
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
248 248
 				$calendar[$xmlName] = $row[$dbName];
249 249
 			}
250 250
 
@@ -257,7 +257,7 @@  discard block
 block discarded – undo
257 257
 
258 258
 		// query for shared calendars
259 259
 		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
260
-		$principals[]= $principalUri;
260
+		$principals[] = $principalUri;
261 261
 
262 262
 		$fields = array_values($this->propertyMap);
263 263
 		$fields[] = 'a.id';
@@ -277,8 +277,8 @@  discard block
 block discarded – undo
277 277
 			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
278 278
 			->execute();
279 279
 
280
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
281
-		while($row = $result->fetch()) {
280
+		$readOnlyPropertyName = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only';
281
+		while ($row = $result->fetch()) {
282 282
 			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
283 283
 			if (isset($calendars[$row['id']])) {
284 284
 				if ($readOnly) {
@@ -293,25 +293,25 @@  discard block
 block discarded – undo
293 293
 			}
294 294
 
295 295
 			list(, $name) = URLUtil::splitPath($row['principaluri']);
296
-			$uri = $row['uri'] . '_shared_by_' . $name;
297
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
296
+			$uri = $row['uri'].'_shared_by_'.$name;
297
+			$row['displayname'] = $row['displayname'].' ('.$this->getUserDisplayName($name).')';
298 298
 			$components = [];
299 299
 			if ($row['components']) {
300
-				$components = explode(',',$row['components']);
300
+				$components = explode(',', $row['components']);
301 301
 			}
302 302
 			$calendar = [
303 303
 				'id' => $row['id'],
304 304
 				'uri' => $uri,
305 305
 				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
306
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
307
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
308
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
309
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
310
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
306
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
307
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
308
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
309
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
310
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
311 311
 				$readOnlyPropertyName => $readOnly,
312 312
 			];
313 313
 
314
-			foreach($this->propertyMap as $xmlName=>$dbName) {
314
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
315 315
 				$calendar[$xmlName] = $row[$dbName];
316 316
 			}
317 317
 
@@ -338,21 +338,21 @@  discard block
 block discarded – undo
338 338
 			->orderBy('calendarorder', 'ASC');
339 339
 		$stmt = $query->execute();
340 340
 		$calendars = [];
341
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
341
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
342 342
 			$components = [];
343 343
 			if ($row['components']) {
344
-				$components = explode(',',$row['components']);
344
+				$components = explode(',', $row['components']);
345 345
 			}
346 346
 			$calendar = [
347 347
 				'id' => $row['id'],
348 348
 				'uri' => $row['uri'],
349 349
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
350
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
351
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
352
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
353
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
350
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
351
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
352
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
353
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
354 354
 			];
355
-			foreach($this->propertyMap as $xmlName=>$dbName) {
355
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
356 356
 				$calendar[$xmlName] = $row[$dbName];
357 357
 			}
358 358
 			if (!isset($calendars[$calendar['id']])) {
@@ -400,27 +400,27 @@  discard block
 block discarded – undo
400 400
 			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
401 401
 			->execute();
402 402
 
403
-		while($row = $result->fetch()) {
403
+		while ($row = $result->fetch()) {
404 404
 			list(, $name) = URLUtil::splitPath($row['principaluri']);
405
-			$row['displayname'] = $row['displayname'] . "($name)";
405
+			$row['displayname'] = $row['displayname']."($name)";
406 406
 			$components = [];
407 407
 			if ($row['components']) {
408
-				$components = explode(',',$row['components']);
408
+				$components = explode(',', $row['components']);
409 409
 			}
410 410
 			$calendar = [
411 411
 				'id' => $row['id'],
412 412
 				'uri' => $row['publicuri'],
413 413
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
414
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
415
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
416
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
417
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
418
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
419
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
420
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
414
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
415
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
416
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
417
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
418
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
419
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
420
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
421 421
 			];
422 422
 
423
-			foreach($this->propertyMap as $xmlName=>$dbName) {
423
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
424 424
 				$calendar[$xmlName] = $row[$dbName];
425 425
 			}
426 426
 
@@ -462,29 +462,29 @@  discard block
 block discarded – undo
462 462
 		$result->closeCursor();
463 463
 
464 464
 		if ($row === false) {
465
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
465
+			throw new NotFound('Node with name \''.$uri.'\' could not be found');
466 466
 		}
467 467
 
468 468
 		list(, $name) = URLUtil::splitPath($row['principaluri']);
469
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
469
+		$row['displayname'] = $row['displayname'].' '."($name)";
470 470
 		$components = [];
471 471
 		if ($row['components']) {
472
-			$components = explode(',',$row['components']);
472
+			$components = explode(',', $row['components']);
473 473
 		}
474 474
 		$calendar = [
475 475
 			'id' => $row['id'],
476 476
 			'uri' => $row['publicuri'],
477 477
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
478
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
479
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
480
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
481
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
482
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
483
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
484
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
478
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
479
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
480
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
481
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
482
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
483
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
484
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
485 485
 		];
486 486
 
487
-		foreach($this->propertyMap as $xmlName=>$dbName) {
487
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
488 488
 			$calendar[$xmlName] = $row[$dbName];
489 489
 		}
490 490
 
@@ -522,20 +522,20 @@  discard block
 block discarded – undo
522 522
 
523 523
 		$components = [];
524 524
 		if ($row['components']) {
525
-			$components = explode(',',$row['components']);
525
+			$components = explode(',', $row['components']);
526 526
 		}
527 527
 
528 528
 		$calendar = [
529 529
 			'id' => $row['id'],
530 530
 			'uri' => $row['uri'],
531 531
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
532
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
533
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
534
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
535
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
532
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
533
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
534
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
535
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
536 536
 		];
537 537
 
538
-		foreach($this->propertyMap as $xmlName=>$dbName) {
538
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
539 539
 			$calendar[$xmlName] = $row[$dbName];
540 540
 		}
541 541
 
@@ -566,20 +566,20 @@  discard block
 block discarded – undo
566 566
 
567 567
 		$components = [];
568 568
 		if ($row['components']) {
569
-			$components = explode(',',$row['components']);
569
+			$components = explode(',', $row['components']);
570 570
 		}
571 571
 
572 572
 		$calendar = [
573 573
 			'id' => $row['id'],
574 574
 			'uri' => $row['uri'],
575 575
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
576
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
577
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
578
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
579
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
576
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
577
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
578
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
579
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
580 580
 		];
581 581
 
582
-		foreach($this->propertyMap as $xmlName=>$dbName) {
582
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
583 583
 			$calendar[$xmlName] = $row[$dbName];
584 584
 		}
585 585
 
@@ -611,16 +611,16 @@  discard block
 block discarded – undo
611 611
 		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
612 612
 		if (isset($properties[$sccs])) {
613 613
 			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
614
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
614
+				throw new DAV\Exception('The '.$sccs.' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
615 615
 			}
616
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
616
+			$values['components'] = implode(',', $properties[$sccs]->getValue());
617 617
 		}
618
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
618
+		$transp = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
619 619
 		if (isset($properties[$transp])) {
620
-			$values['transparent'] = $properties[$transp]->getValue()==='transparent';
620
+			$values['transparent'] = $properties[$transp]->getValue() === 'transparent';
621 621
 		}
622 622
 
623
-		foreach($this->propertyMap as $xmlName=>$dbName) {
623
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
624 624
 			if (isset($properties[$xmlName])) {
625 625
 				$values[$dbName] = $properties[$xmlName];
626 626
 			}
@@ -628,7 +628,7 @@  discard block
 block discarded – undo
628 628
 
629 629
 		$query = $this->db->getQueryBuilder();
630 630
 		$query->insert('calendars');
631
-		foreach($values as $column => $value) {
631
+		foreach ($values as $column => $value) {
632 632
 			$query->setValue($column, $query->createNamedParameter($value));
633 633
 		}
634 634
 		$query->execute();
@@ -661,14 +661,14 @@  discard block
 block discarded – undo
661 661
 	 */
662 662
 	function updateCalendar($calendarId, PropPatch $propPatch) {
663 663
 		$supportedProperties = array_keys($this->propertyMap);
664
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
664
+		$supportedProperties[] = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
665 665
 
666 666
 		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
667 667
 			$newValues = [];
668 668
 			foreach ($mutations as $propertyName => $propertyValue) {
669 669
 
670 670
 				switch ($propertyName) {
671
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
671
+					case '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' :
672 672
 						$fieldName = 'transparent';
673 673
 						$newValues[$fieldName] = $propertyValue->getValue() === 'transparent';
674 674
 						break;
@@ -778,16 +778,16 @@  discard block
 block discarded – undo
778 778
 		$stmt = $query->execute();
779 779
 
780 780
 		$result = [];
781
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
781
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
782 782
 			$result[] = [
783 783
 					'id'           => $row['id'],
784 784
 					'uri'          => $row['uri'],
785 785
 					'lastmodified' => $row['lastmodified'],
786
-					'etag'         => '"' . $row['etag'] . '"',
786
+					'etag'         => '"'.$row['etag'].'"',
787 787
 					'calendarid'   => $row['calendarid'],
788
-					'size'         => (int)$row['size'],
788
+					'size'         => (int) $row['size'],
789 789
 					'component'    => strtolower($row['componenttype']),
790
-					'classification'=> (int)$row['classification']
790
+					'classification'=> (int) $row['classification']
791 791
 			];
792 792
 		}
793 793
 
@@ -820,18 +820,18 @@  discard block
 block discarded – undo
820 820
 		$stmt = $query->execute();
821 821
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
822 822
 
823
-		if(!$row) return null;
823
+		if (!$row) return null;
824 824
 
825 825
 		return [
826 826
 				'id'            => $row['id'],
827 827
 				'uri'           => $row['uri'],
828 828
 				'lastmodified'  => $row['lastmodified'],
829
-				'etag'          => '"' . $row['etag'] . '"',
829
+				'etag'          => '"'.$row['etag'].'"',
830 830
 				'calendarid'    => $row['calendarid'],
831
-				'size'          => (int)$row['size'],
831
+				'size'          => (int) $row['size'],
832 832
 				'calendardata'  => $this->readBlob($row['calendardata']),
833 833
 				'component'     => strtolower($row['componenttype']),
834
-				'classification'=> (int)$row['classification']
834
+				'classification'=> (int) $row['classification']
835 835
 		];
836 836
 	}
837 837
 
@@ -870,12 +870,12 @@  discard block
 block discarded – undo
870 870
 					'id'           => $row['id'],
871 871
 					'uri'          => $row['uri'],
872 872
 					'lastmodified' => $row['lastmodified'],
873
-					'etag'         => '"' . $row['etag'] . '"',
873
+					'etag'         => '"'.$row['etag'].'"',
874 874
 					'calendarid'   => $row['calendarid'],
875
-					'size'         => (int)$row['size'],
875
+					'size'         => (int) $row['size'],
876 876
 					'calendardata' => $this->readBlob($row['calendardata']),
877 877
 					'component'    => strtolower($row['componenttype']),
878
-					'classification' => (int)$row['classification']
878
+					'classification' => (int) $row['classification']
879 879
 				];
880 880
 			}
881 881
 			$result->closeCursor();
@@ -932,7 +932,7 @@  discard block
 block discarded – undo
932 932
 		));
933 933
 		$this->addChange($calendarId, $objectUri, 1);
934 934
 
935
-		return '"' . $extraData['etag'] . '"';
935
+		return '"'.$extraData['etag'].'"';
936 936
 	}
937 937
 
938 938
 	/**
@@ -985,7 +985,7 @@  discard block
 block discarded – undo
985 985
 		}
986 986
 		$this->addChange($calendarId, $objectUri, 2);
987 987
 
988
-		return '"' . $extraData['etag'] . '"';
988
+		return '"'.$extraData['etag'].'"';
989 989
 	}
990 990
 
991 991
 	/**
@@ -1136,7 +1136,7 @@  discard block
 block discarded – undo
1136 1136
 		$stmt = $query->execute();
1137 1137
 
1138 1138
 		$result = [];
1139
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1139
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1140 1140
 			if ($requirePostFilter) {
1141 1141
 				if (!$this->validateFilterForObject($row, $filters)) {
1142 1142
 					continue;
@@ -1179,7 +1179,7 @@  discard block
 block discarded – undo
1179 1179
 		$stmt = $query->execute();
1180 1180
 
1181 1181
 		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1182
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1182
+			return $row['calendaruri'].'/'.$row['objecturi'];
1183 1183
 		}
1184 1184
 
1185 1185
 		return null;
@@ -1244,7 +1244,7 @@  discard block
 block discarded – undo
1244 1244
 	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1245 1245
 		// Current synctoken
1246 1246
 		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1247
-		$stmt->execute([ $calendarId ]);
1247
+		$stmt->execute([$calendarId]);
1248 1248
 		$currentToken = $stmt->fetchColumn(0);
1249 1249
 
1250 1250
 		if (is_null($currentToken)) {
@@ -1261,8 +1261,8 @@  discard block
 block discarded – undo
1261 1261
 		if ($syncToken) {
1262 1262
 
1263 1263
 			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1264
-			if ($limit>0) {
1265
-				$query.= " `LIMIT` " . (int)$limit;
1264
+			if ($limit > 0) {
1265
+				$query .= " `LIMIT` ".(int) $limit;
1266 1266
 			}
1267 1267
 
1268 1268
 			// Fetching all changes
@@ -1273,15 +1273,15 @@  discard block
 block discarded – undo
1273 1273
 
1274 1274
 			// This loop ensures that any duplicates are overwritten, only the
1275 1275
 			// last change on a node is relevant.
1276
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1276
+			while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1277 1277
 
1278 1278
 				$changes[$row['uri']] = $row['operation'];
1279 1279
 
1280 1280
 			}
1281 1281
 
1282
-			foreach($changes as $uri => $operation) {
1282
+			foreach ($changes as $uri => $operation) {
1283 1283
 
1284
-				switch($operation) {
1284
+				switch ($operation) {
1285 1285
 					case 1 :
1286 1286
 						$result['added'][] = $uri;
1287 1287
 						break;
@@ -1351,10 +1351,10 @@  discard block
 block discarded – undo
1351 1351
 			->from('calendarsubscriptions')
1352 1352
 			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1353 1353
 			->orderBy('calendarorder', 'asc');
1354
-		$stmt =$query->execute();
1354
+		$stmt = $query->execute();
1355 1355
 
1356 1356
 		$subscriptions = [];
1357
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1357
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1358 1358
 
1359 1359
 			$subscription = [
1360 1360
 				'id'           => $row['id'],
@@ -1363,10 +1363,10 @@  discard block
 block discarded – undo
1363 1363
 				'source'       => $row['source'],
1364 1364
 				'lastmodified' => $row['lastmodified'],
1365 1365
 
1366
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1366
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1367 1367
 			];
1368 1368
 
1369
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1369
+			foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1370 1370
 				if (!is_null($row[$dbName])) {
1371 1371
 					$subscription[$xmlName] = $row[$dbName];
1372 1372
 				}
@@ -1405,7 +1405,7 @@  discard block
 block discarded – undo
1405 1405
 
1406 1406
 		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1407 1407
 
1408
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1408
+		foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1409 1409
 			if (array_key_exists($xmlName, $properties)) {
1410 1410
 					$values[$dbName] = $properties[$xmlName];
1411 1411
 					if (in_array($dbName, $propertiesBoolean)) {
@@ -1453,7 +1453,7 @@  discard block
 block discarded – undo
1453 1453
 
1454 1454
 			$newValues = [];
1455 1455
 
1456
-			foreach($mutations as $propertyName=>$propertyValue) {
1456
+			foreach ($mutations as $propertyName=>$propertyValue) {
1457 1457
 				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1458 1458
 					$newValues['source'] = $propertyValue->getHref();
1459 1459
 				} else {
@@ -1465,7 +1465,7 @@  discard block
 block discarded – undo
1465 1465
 			$query = $this->db->getQueryBuilder();
1466 1466
 			$query->update('calendarsubscriptions')
1467 1467
 				->set('lastmodified', $query->createNamedParameter(time()));
1468
-			foreach($newValues as $fieldName=>$value) {
1468
+			foreach ($newValues as $fieldName=>$value) {
1469 1469
 				$query->set($fieldName, $query->createNamedParameter($value));
1470 1470
 			}
1471 1471
 			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
@@ -1515,7 +1515,7 @@  discard block
 block discarded – undo
1515 1515
 
1516 1516
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
1517 1517
 
1518
-		if(!$row) {
1518
+		if (!$row) {
1519 1519
 			return null;
1520 1520
 		}
1521 1521
 
@@ -1523,8 +1523,8 @@  discard block
 block discarded – undo
1523 1523
 				'uri'          => $row['uri'],
1524 1524
 				'calendardata' => $row['calendardata'],
1525 1525
 				'lastmodified' => $row['lastmodified'],
1526
-				'etag'         => '"' . $row['etag'] . '"',
1527
-				'size'         => (int)$row['size'],
1526
+				'etag'         => '"'.$row['etag'].'"',
1527
+				'size'         => (int) $row['size'],
1528 1528
 		];
1529 1529
 	}
1530 1530
 
@@ -1547,13 +1547,13 @@  discard block
 block discarded – undo
1547 1547
 				->execute();
1548 1548
 
1549 1549
 		$result = [];
1550
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1550
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1551 1551
 			$result[] = [
1552 1552
 					'calendardata' => $row['calendardata'],
1553 1553
 					'uri'          => $row['uri'],
1554 1554
 					'lastmodified' => $row['lastmodified'],
1555
-					'etag'         => '"' . $row['etag'] . '"',
1556
-					'size'         => (int)$row['size'],
1555
+					'etag'         => '"'.$row['etag'].'"',
1556
+					'size'         => (int) $row['size'],
1557 1557
 			];
1558 1558
 		}
1559 1559
 
@@ -1645,10 +1645,10 @@  discard block
 block discarded – undo
1645 1645
 		$lastOccurrence = null;
1646 1646
 		$uid = null;
1647 1647
 		$classification = self::CLASSIFICATION_PUBLIC;
1648
-		foreach($vObject->getComponents() as $component) {
1649
-			if ($component->name!=='VTIMEZONE') {
1648
+		foreach ($vObject->getComponents() as $component) {
1649
+			if ($component->name !== 'VTIMEZONE') {
1650 1650
 				$componentType = $component->name;
1651
-				$uid = (string)$component->UID;
1651
+				$uid = (string) $component->UID;
1652 1652
 				break;
1653 1653
 			}
1654 1654
 		}
@@ -1673,13 +1673,13 @@  discard block
 block discarded – undo
1673 1673
 					$lastOccurrence = $firstOccurrence;
1674 1674
 				}
1675 1675
 			} else {
1676
-				$it = new EventIterator($vObject, (string)$component->UID);
1676
+				$it = new EventIterator($vObject, (string) $component->UID);
1677 1677
 				$maxDate = new \DateTime(self::MAX_DATE);
1678 1678
 				if ($it->isInfinite()) {
1679 1679
 					$lastOccurrence = $maxDate->getTimestamp();
1680 1680
 				} else {
1681 1681
 					$end = $it->getDtEnd();
1682
-					while($it->valid() && $end < $maxDate) {
1682
+					while ($it->valid() && $end < $maxDate) {
1683 1683
 						$end = $it->getDtEnd();
1684 1684
 						$it->next();
1685 1685
 
Please login to merge, or discard this patch.
lib/private/Files/Filesystem.php 4 patches
Doc Comments   +31 added lines, -2 removed lines patch added patch discarded remove patch
@@ -360,6 +360,9 @@  discard block
 block discarded – undo
360 360
 		}
361 361
 	}
362 362
 
363
+	/**
364
+	 * @param string $root
365
+	 */
363 366
 	static public function init($user, $root) {
364 367
 		if (self::$defaultInstance) {
365 368
 			return false;
@@ -528,7 +531,7 @@  discard block
 block discarded – undo
528 531
 	/**
529 532
 	 * mount an \OC\Files\Storage\Storage in our virtual filesystem
530 533
 	 *
531
-	 * @param \OC\Files\Storage\Storage|string $class
534
+	 * @param string $class
532 535
 	 * @param array $arguments
533 536
 	 * @param string $mountpoint
534 537
 	 */
@@ -660,6 +663,9 @@  discard block
 block discarded – undo
660 663
 		return self::$defaultInstance->is_dir($path);
661 664
 	}
662 665
 
666
+	/**
667
+	 * @param string $path
668
+	 */
663 669
 	static public function is_file($path) {
664 670
 		return self::$defaultInstance->is_file($path);
665 671
 	}
@@ -672,6 +678,9 @@  discard block
 block discarded – undo
672 678
 		return self::$defaultInstance->filetype($path);
673 679
 	}
674 680
 
681
+	/**
682
+	 * @param string $path
683
+	 */
675 684
 	static public function filesize($path) {
676 685
 		return self::$defaultInstance->filesize($path);
677 686
 	}
@@ -684,6 +693,9 @@  discard block
 block discarded – undo
684 693
 		return self::$defaultInstance->isCreatable($path);
685 694
 	}
686 695
 
696
+	/**
697
+	 * @param string $path
698
+	 */
687 699
 	static public function isReadable($path) {
688 700
 		return self::$defaultInstance->isReadable($path);
689 701
 	}
@@ -696,6 +708,9 @@  discard block
 block discarded – undo
696 708
 		return self::$defaultInstance->isDeletable($path);
697 709
 	}
698 710
 
711
+	/**
712
+	 * @param string $path
713
+	 */
699 714
 	static public function isSharable($path) {
700 715
 		return self::$defaultInstance->isSharable($path);
701 716
 	}
@@ -704,6 +719,9 @@  discard block
 block discarded – undo
704 719
 		return self::$defaultInstance->file_exists($path);
705 720
 	}
706 721
 
722
+	/**
723
+	 * @param string $path
724
+	 */
707 725
 	static public function filemtime($path) {
708 726
 		return self::$defaultInstance->filemtime($path);
709 727
 	}
@@ -713,6 +731,7 @@  discard block
 block discarded – undo
713 731
 	}
714 732
 
715 733
 	/**
734
+	 * @param string $path
716 735
 	 * @return string
717 736
 	 */
718 737
 	static public function file_get_contents($path) {
@@ -735,6 +754,10 @@  discard block
 block discarded – undo
735 754
 		return self::$defaultInstance->copy($path1, $path2);
736 755
 	}
737 756
 
757
+	/**
758
+	 * @param string $path
759
+	 * @param string $mode
760
+	 */
738 761
 	static public function fopen($path, $mode) {
739 762
 		return self::$defaultInstance->fopen($path, $mode);
740 763
 	}
@@ -750,6 +773,9 @@  discard block
 block discarded – undo
750 773
 		return self::$defaultInstance->fromTmpFile($tmpFile, $path);
751 774
 	}
752 775
 
776
+	/**
777
+	 * @param string $path
778
+	 */
753 779
 	static public function getMimeType($path) {
754 780
 		return self::$defaultInstance->getMimeType($path);
755 781
 	}
@@ -762,6 +788,9 @@  discard block
 block discarded – undo
762 788
 		return self::$defaultInstance->free_space($path);
763 789
 	}
764 790
 
791
+	/**
792
+	 * @param string $query
793
+	 */
765 794
 	static public function search($query) {
766 795
 		return self::$defaultInstance->search($query);
767 796
 	}
@@ -870,7 +899,7 @@  discard block
 block discarded – undo
870 899
 	 * @param string $path
871 900
 	 * @param boolean $includeMountPoints whether to add mountpoint sizes,
872 901
 	 * defaults to true
873
-	 * @return \OC\Files\FileInfo|bool False if file does not exist
902
+	 * @return \OCP\Files\FileInfo|null False if file does not exist
874 903
 	 */
875 904
 	public static function getFileInfo($path, $includeMountPoints = true) {
876 905
 		return self::$defaultInstance->getFileInfo($path, $includeMountPoints);
Please login to merge, or discard this patch.
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -64,7 +64,6 @@
 block discarded – undo
64 64
 use OC\Files\Storage\StorageFactory;
65 65
 use OC\Lockdown\Filesystem\NullStorage;
66 66
 use OCP\Files\Config\IMountProvider;
67
-use OCP\Files\Mount\IMountPoint;
68 67
 use OCP\Files\NotFoundException;
69 68
 use OCP\IUserManager;
70 69
 
Please login to merge, or discard this patch.
Indentation   +862 added lines, -862 removed lines patch added patch discarded remove patch
@@ -70,866 +70,866 @@
 block discarded – undo
70 70
 
71 71
 class Filesystem {
72 72
 
73
-	/**
74
-	 * @var Mount\Manager $mounts
75
-	 */
76
-	private static $mounts;
77
-
78
-	public static $loaded = false;
79
-	/**
80
-	 * @var \OC\Files\View $defaultInstance
81
-	 */
82
-	static private $defaultInstance;
83
-
84
-	static private $usersSetup = array();
85
-
86
-	static private $normalizedPathCache = null;
87
-
88
-	static private $listeningForProviders = false;
89
-
90
-	/**
91
-	 * classname which used for hooks handling
92
-	 * used as signalclass in OC_Hooks::emit()
93
-	 */
94
-	const CLASSNAME = 'OC_Filesystem';
95
-
96
-	/**
97
-	 * signalname emitted before file renaming
98
-	 *
99
-	 * @param string $oldpath
100
-	 * @param string $newpath
101
-	 */
102
-	const signal_rename = 'rename';
103
-
104
-	/**
105
-	 * signal emitted after file renaming
106
-	 *
107
-	 * @param string $oldpath
108
-	 * @param string $newpath
109
-	 */
110
-	const signal_post_rename = 'post_rename';
111
-
112
-	/**
113
-	 * signal emitted before file/dir creation
114
-	 *
115
-	 * @param string $path
116
-	 * @param bool $run changing this flag to false in hook handler will cancel event
117
-	 */
118
-	const signal_create = 'create';
119
-
120
-	/**
121
-	 * signal emitted after file/dir creation
122
-	 *
123
-	 * @param string $path
124
-	 * @param bool $run changing this flag to false in hook handler will cancel event
125
-	 */
126
-	const signal_post_create = 'post_create';
127
-
128
-	/**
129
-	 * signal emits before file/dir copy
130
-	 *
131
-	 * @param string $oldpath
132
-	 * @param string $newpath
133
-	 * @param bool $run changing this flag to false in hook handler will cancel event
134
-	 */
135
-	const signal_copy = 'copy';
136
-
137
-	/**
138
-	 * signal emits after file/dir copy
139
-	 *
140
-	 * @param string $oldpath
141
-	 * @param string $newpath
142
-	 */
143
-	const signal_post_copy = 'post_copy';
144
-
145
-	/**
146
-	 * signal emits before file/dir save
147
-	 *
148
-	 * @param string $path
149
-	 * @param bool $run changing this flag to false in hook handler will cancel event
150
-	 */
151
-	const signal_write = 'write';
152
-
153
-	/**
154
-	 * signal emits after file/dir save
155
-	 *
156
-	 * @param string $path
157
-	 */
158
-	const signal_post_write = 'post_write';
159
-
160
-	/**
161
-	 * signal emitted before file/dir update
162
-	 *
163
-	 * @param string $path
164
-	 * @param bool $run changing this flag to false in hook handler will cancel event
165
-	 */
166
-	const signal_update = 'update';
167
-
168
-	/**
169
-	 * signal emitted after file/dir update
170
-	 *
171
-	 * @param string $path
172
-	 * @param bool $run changing this flag to false in hook handler will cancel event
173
-	 */
174
-	const signal_post_update = 'post_update';
175
-
176
-	/**
177
-	 * signal emits when reading file/dir
178
-	 *
179
-	 * @param string $path
180
-	 */
181
-	const signal_read = 'read';
182
-
183
-	/**
184
-	 * signal emits when removing file/dir
185
-	 *
186
-	 * @param string $path
187
-	 */
188
-	const signal_delete = 'delete';
189
-
190
-	/**
191
-	 * parameters definitions for signals
192
-	 */
193
-	const signal_param_path = 'path';
194
-	const signal_param_oldpath = 'oldpath';
195
-	const signal_param_newpath = 'newpath';
196
-
197
-	/**
198
-	 * run - changing this flag to false in hook handler will cancel event
199
-	 */
200
-	const signal_param_run = 'run';
201
-
202
-	const signal_create_mount = 'create_mount';
203
-	const signal_delete_mount = 'delete_mount';
204
-	const signal_param_mount_type = 'mounttype';
205
-	const signal_param_users = 'users';
206
-
207
-	/**
208
-	 * @var \OC\Files\Storage\StorageFactory $loader
209
-	 */
210
-	private static $loader;
211
-
212
-	/** @var bool */
213
-	private static $logWarningWhenAddingStorageWrapper = true;
214
-
215
-	/**
216
-	 * @param bool $shouldLog
217
-	 * @return bool previous value
218
-	 * @internal
219
-	 */
220
-	public static function logWarningWhenAddingStorageWrapper($shouldLog) {
221
-		$previousValue = self::$logWarningWhenAddingStorageWrapper;
222
-		self::$logWarningWhenAddingStorageWrapper = (bool) $shouldLog;
223
-		return $previousValue;
224
-	}
225
-
226
-	/**
227
-	 * @param string $wrapperName
228
-	 * @param callable $wrapper
229
-	 * @param int $priority
230
-	 */
231
-	public static function addStorageWrapper($wrapperName, $wrapper, $priority = 50) {
232
-		if (self::$logWarningWhenAddingStorageWrapper) {
233
-			\OC::$server->getLogger()->warning("Storage wrapper '{wrapper}' was not registered via the 'OC_Filesystem - preSetup' hook which could cause potential problems.", [
234
-				'wrapper' => $wrapperName,
235
-				'app' => 'filesystem',
236
-			]);
237
-		}
238
-
239
-		$mounts = self::getMountManager()->getAll();
240
-		if (!self::getLoader()->addStorageWrapper($wrapperName, $wrapper, $priority, $mounts)) {
241
-			// do not re-wrap if storage with this name already existed
242
-			return;
243
-		}
244
-	}
245
-
246
-	/**
247
-	 * Returns the storage factory
248
-	 *
249
-	 * @return \OCP\Files\Storage\IStorageFactory
250
-	 */
251
-	public static function getLoader() {
252
-		if (!self::$loader) {
253
-			self::$loader = new StorageFactory();
254
-		}
255
-		return self::$loader;
256
-	}
257
-
258
-	/**
259
-	 * Returns the mount manager
260
-	 *
261
-	 * @return \OC\Files\Mount\Manager
262
-	 */
263
-	public static function getMountManager($user = '') {
264
-		if (!self::$mounts) {
265
-			\OC_Util::setupFS($user);
266
-		}
267
-		return self::$mounts;
268
-	}
269
-
270
-	/**
271
-	 * get the mountpoint of the storage object for a path
272
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
273
-	 * returned mountpoint is relative to the absolute root of the filesystem
274
-	 * and doesn't take the chroot into account )
275
-	 *
276
-	 * @param string $path
277
-	 * @return string
278
-	 */
279
-	static public function getMountPoint($path) {
280
-		if (!self::$mounts) {
281
-			\OC_Util::setupFS();
282
-		}
283
-		$mount = self::$mounts->find($path);
284
-		if ($mount) {
285
-			return $mount->getMountPoint();
286
-		} else {
287
-			return '';
288
-		}
289
-	}
290
-
291
-	/**
292
-	 * get a list of all mount points in a directory
293
-	 *
294
-	 * @param string $path
295
-	 * @return string[]
296
-	 */
297
-	static public function getMountPoints($path) {
298
-		if (!self::$mounts) {
299
-			\OC_Util::setupFS();
300
-		}
301
-		$result = array();
302
-		$mounts = self::$mounts->findIn($path);
303
-		foreach ($mounts as $mount) {
304
-			$result[] = $mount->getMountPoint();
305
-		}
306
-		return $result;
307
-	}
308
-
309
-	/**
310
-	 * get the storage mounted at $mountPoint
311
-	 *
312
-	 * @param string $mountPoint
313
-	 * @return \OC\Files\Storage\Storage
314
-	 */
315
-	public static function getStorage($mountPoint) {
316
-		if (!self::$mounts) {
317
-			\OC_Util::setupFS();
318
-		}
319
-		$mount = self::$mounts->find($mountPoint);
320
-		return $mount->getStorage();
321
-	}
322
-
323
-	/**
324
-	 * @param string $id
325
-	 * @return Mount\MountPoint[]
326
-	 */
327
-	public static function getMountByStorageId($id) {
328
-		if (!self::$mounts) {
329
-			\OC_Util::setupFS();
330
-		}
331
-		return self::$mounts->findByStorageId($id);
332
-	}
333
-
334
-	/**
335
-	 * @param int $id
336
-	 * @return Mount\MountPoint[]
337
-	 */
338
-	public static function getMountByNumericId($id) {
339
-		if (!self::$mounts) {
340
-			\OC_Util::setupFS();
341
-		}
342
-		return self::$mounts->findByNumericId($id);
343
-	}
344
-
345
-	/**
346
-	 * resolve a path to a storage and internal path
347
-	 *
348
-	 * @param string $path
349
-	 * @return array an array consisting of the storage and the internal path
350
-	 */
351
-	static public function resolvePath($path) {
352
-		if (!self::$mounts) {
353
-			\OC_Util::setupFS();
354
-		}
355
-		$mount = self::$mounts->find($path);
356
-		if ($mount) {
357
-			return array($mount->getStorage(), rtrim($mount->getInternalPath($path), '/'));
358
-		} else {
359
-			return array(null, null);
360
-		}
361
-	}
362
-
363
-	static public function init($user, $root) {
364
-		if (self::$defaultInstance) {
365
-			return false;
366
-		}
367
-		self::getLoader();
368
-		self::$defaultInstance = new View($root);
369
-
370
-		if (!self::$mounts) {
371
-			self::$mounts = \OC::$server->getMountManager();
372
-		}
373
-
374
-		//load custom mount config
375
-		self::initMountPoints($user);
376
-
377
-		self::$loaded = true;
378
-
379
-		return true;
380
-	}
381
-
382
-	static public function initMountManager() {
383
-		if (!self::$mounts) {
384
-			self::$mounts = \OC::$server->getMountManager();
385
-		}
386
-	}
387
-
388
-	/**
389
-	 * Initialize system and personal mount points for a user
390
-	 *
391
-	 * @param string $user
392
-	 * @throws \OC\User\NoUserException if the user is not available
393
-	 */
394
-	public static function initMountPoints($user = '') {
395
-		if ($user == '') {
396
-			$user = \OC_User::getUser();
397
-		}
398
-		if ($user === null || $user === false || $user === '') {
399
-			throw new \OC\User\NoUserException('Attempted to initialize mount points for null user and no user in session');
400
-		}
401
-
402
-		if (isset(self::$usersSetup[$user])) {
403
-			return;
404
-		}
405
-
406
-		self::$usersSetup[$user] = true;
407
-
408
-		$userManager = \OC::$server->getUserManager();
409
-		$userObject = $userManager->get($user);
410
-
411
-		if (is_null($userObject)) {
412
-			\OCP\Util::writeLog('files', ' Backends provided no user object for ' . $user, \OCP\Util::ERROR);
413
-			// reset flag, this will make it possible to rethrow the exception if called again
414
-			unset(self::$usersSetup[$user]);
415
-			throw new \OC\User\NoUserException('Backends provided no user object for ' . $user);
416
-		}
417
-
418
-		$realUid = $userObject->getUID();
419
-		// workaround in case of different casings
420
-		if ($user !== $realUid) {
421
-			$stack = json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 50));
422
-			\OCP\Util::writeLog('files', 'initMountPoints() called with wrong user casing. This could be a bug. Expected: "' . $realUid . '" got "' . $user . '". Stack: ' . $stack, \OCP\Util::WARN);
423
-			$user = $realUid;
424
-
425
-			// again with the correct casing
426
-			if (isset(self::$usersSetup[$user])) {
427
-				return;
428
-			}
429
-
430
-			self::$usersSetup[$user] = true;
431
-		}
432
-
433
-		if (\OC::$server->getLockdownManager()->canAccessFilesystem()) {
434
-			/** @var \OC\Files\Config\MountProviderCollection $mountConfigManager */
435
-			$mountConfigManager = \OC::$server->getMountProviderCollection();
436
-
437
-			// home mounts are handled seperate since we need to ensure this is mounted before we call the other mount providers
438
-			$homeMount = $mountConfigManager->getHomeMountForUser($userObject);
439
-
440
-			self::getMountManager()->addMount($homeMount);
441
-
442
-			\OC\Files\Filesystem::getStorage($user);
443
-
444
-			// Chance to mount for other storages
445
-			if ($userObject) {
446
-				$mounts = $mountConfigManager->getMountsForUser($userObject);
447
-				array_walk($mounts, array(self::$mounts, 'addMount'));
448
-				$mounts[] = $homeMount;
449
-				$mountConfigManager->registerMounts($userObject, $mounts);
450
-			}
451
-
452
-			self::listenForNewMountProviders($mountConfigManager, $userManager);
453
-		} else {
454
-			self::getMountManager()->addMount(new MountPoint(
455
-				new NullStorage([]),
456
-				'/' . $user
457
-			));
458
-			self::getMountManager()->addMount(new MountPoint(
459
-				new NullStorage([]),
460
-				'/' . $user . '/files'
461
-			));
462
-		}
463
-		\OC_Hook::emit('OC_Filesystem', 'post_initMountPoints', array('user' => $user));
464
-	}
465
-
466
-	/**
467
-	 * Get mounts from mount providers that are registered after setup
468
-	 *
469
-	 * @param MountProviderCollection $mountConfigManager
470
-	 * @param IUserManager $userManager
471
-	 */
472
-	private static function listenForNewMountProviders(MountProviderCollection $mountConfigManager, IUserManager $userManager) {
473
-		if (!self::$listeningForProviders) {
474
-			self::$listeningForProviders = true;
475
-			$mountConfigManager->listen('\OC\Files\Config', 'registerMountProvider', function (IMountProvider $provider) use ($userManager) {
476
-				foreach (Filesystem::$usersSetup as $user => $setup) {
477
-					$userObject = $userManager->get($user);
478
-					if ($userObject) {
479
-						$mounts = $provider->getMountsForUser($userObject, Filesystem::getLoader());
480
-						array_walk($mounts, array(self::$mounts, 'addMount'));
481
-					}
482
-				}
483
-			});
484
-		}
485
-	}
486
-
487
-	/**
488
-	 * get the default filesystem view
489
-	 *
490
-	 * @return View
491
-	 */
492
-	static public function getView() {
493
-		return self::$defaultInstance;
494
-	}
495
-
496
-	/**
497
-	 * tear down the filesystem, removing all storage providers
498
-	 */
499
-	static public function tearDown() {
500
-		self::clearMounts();
501
-		self::$defaultInstance = null;
502
-	}
503
-
504
-	/**
505
-	 * get the relative path of the root data directory for the current user
506
-	 *
507
-	 * @return string
508
-	 *
509
-	 * Returns path like /admin/files
510
-	 */
511
-	static public function getRoot() {
512
-		if (!self::$defaultInstance) {
513
-			return null;
514
-		}
515
-		return self::$defaultInstance->getRoot();
516
-	}
517
-
518
-	/**
519
-	 * clear all mounts and storage backends
520
-	 */
521
-	public static function clearMounts() {
522
-		if (self::$mounts) {
523
-			self::$usersSetup = array();
524
-			self::$mounts->clear();
525
-		}
526
-	}
527
-
528
-	/**
529
-	 * mount an \OC\Files\Storage\Storage in our virtual filesystem
530
-	 *
531
-	 * @param \OC\Files\Storage\Storage|string $class
532
-	 * @param array $arguments
533
-	 * @param string $mountpoint
534
-	 */
535
-	static public function mount($class, $arguments, $mountpoint) {
536
-		if (!self::$mounts) {
537
-			\OC_Util::setupFS();
538
-		}
539
-		$mount = new Mount\MountPoint($class, $mountpoint, $arguments, self::getLoader());
540
-		self::$mounts->addMount($mount);
541
-	}
542
-
543
-	/**
544
-	 * return the path to a local version of the file
545
-	 * we need this because we can't know if a file is stored local or not from
546
-	 * outside the filestorage and for some purposes a local file is needed
547
-	 *
548
-	 * @param string $path
549
-	 * @return string
550
-	 */
551
-	static public function getLocalFile($path) {
552
-		return self::$defaultInstance->getLocalFile($path);
553
-	}
554
-
555
-	/**
556
-	 * @param string $path
557
-	 * @return string
558
-	 */
559
-	static public function getLocalFolder($path) {
560
-		return self::$defaultInstance->getLocalFolder($path);
561
-	}
562
-
563
-	/**
564
-	 * return path to file which reflects one visible in browser
565
-	 *
566
-	 * @param string $path
567
-	 * @return string
568
-	 */
569
-	static public function getLocalPath($path) {
570
-		$datadir = \OC_User::getHome(\OC_User::getUser()) . '/files';
571
-		$newpath = $path;
572
-		if (strncmp($newpath, $datadir, strlen($datadir)) == 0) {
573
-			$newpath = substr($path, strlen($datadir));
574
-		}
575
-		return $newpath;
576
-	}
577
-
578
-	/**
579
-	 * check if the requested path is valid
580
-	 *
581
-	 * @param string $path
582
-	 * @return bool
583
-	 */
584
-	static public function isValidPath($path) {
585
-		$path = self::normalizePath($path);
586
-		if (!$path || $path[0] !== '/') {
587
-			$path = '/' . $path;
588
-		}
589
-		if (strpos($path, '/../') !== false || strrchr($path, '/') === '/..') {
590
-			return false;
591
-		}
592
-		return true;
593
-	}
594
-
595
-	/**
596
-	 * checks if a file is blacklisted for storage in the filesystem
597
-	 * Listens to write and rename hooks
598
-	 *
599
-	 * @param array $data from hook
600
-	 */
601
-	static public function isBlacklisted($data) {
602
-		if (isset($data['path'])) {
603
-			$path = $data['path'];
604
-		} else if (isset($data['newpath'])) {
605
-			$path = $data['newpath'];
606
-		}
607
-		if (isset($path)) {
608
-			if (self::isFileBlacklisted($path)) {
609
-				$data['run'] = false;
610
-			}
611
-		}
612
-	}
613
-
614
-	/**
615
-	 * @param string $filename
616
-	 * @return bool
617
-	 */
618
-	static public function isFileBlacklisted($filename) {
619
-		$filename = self::normalizePath($filename);
620
-
621
-		$blacklist = \OC::$server->getConfig()->getSystemValue('blacklisted_files', array('.htaccess'));
622
-		$filename = strtolower(basename($filename));
623
-		return in_array($filename, $blacklist);
624
-	}
625
-
626
-	/**
627
-	 * check if the directory should be ignored when scanning
628
-	 * NOTE: the special directories . and .. would cause never ending recursion
629
-	 *
630
-	 * @param String $dir
631
-	 * @return boolean
632
-	 */
633
-	static public function isIgnoredDir($dir) {
634
-		if ($dir === '.' || $dir === '..') {
635
-			return true;
636
-		}
637
-		return false;
638
-	}
639
-
640
-	/**
641
-	 * following functions are equivalent to their php builtin equivalents for arguments/return values.
642
-	 */
643
-	static public function mkdir($path) {
644
-		return self::$defaultInstance->mkdir($path);
645
-	}
646
-
647
-	static public function rmdir($path) {
648
-		return self::$defaultInstance->rmdir($path);
649
-	}
650
-
651
-	static public function opendir($path) {
652
-		return self::$defaultInstance->opendir($path);
653
-	}
654
-
655
-	static public function readdir($path) {
656
-		return self::$defaultInstance->readdir($path);
657
-	}
658
-
659
-	static public function is_dir($path) {
660
-		return self::$defaultInstance->is_dir($path);
661
-	}
662
-
663
-	static public function is_file($path) {
664
-		return self::$defaultInstance->is_file($path);
665
-	}
666
-
667
-	static public function stat($path) {
668
-		return self::$defaultInstance->stat($path);
669
-	}
670
-
671
-	static public function filetype($path) {
672
-		return self::$defaultInstance->filetype($path);
673
-	}
674
-
675
-	static public function filesize($path) {
676
-		return self::$defaultInstance->filesize($path);
677
-	}
678
-
679
-	static public function readfile($path) {
680
-		return self::$defaultInstance->readfile($path);
681
-	}
682
-
683
-	static public function isCreatable($path) {
684
-		return self::$defaultInstance->isCreatable($path);
685
-	}
686
-
687
-	static public function isReadable($path) {
688
-		return self::$defaultInstance->isReadable($path);
689
-	}
690
-
691
-	static public function isUpdatable($path) {
692
-		return self::$defaultInstance->isUpdatable($path);
693
-	}
694
-
695
-	static public function isDeletable($path) {
696
-		return self::$defaultInstance->isDeletable($path);
697
-	}
698
-
699
-	static public function isSharable($path) {
700
-		return self::$defaultInstance->isSharable($path);
701
-	}
702
-
703
-	static public function file_exists($path) {
704
-		return self::$defaultInstance->file_exists($path);
705
-	}
706
-
707
-	static public function filemtime($path) {
708
-		return self::$defaultInstance->filemtime($path);
709
-	}
710
-
711
-	static public function touch($path, $mtime = null) {
712
-		return self::$defaultInstance->touch($path, $mtime);
713
-	}
714
-
715
-	/**
716
-	 * @return string
717
-	 */
718
-	static public function file_get_contents($path) {
719
-		return self::$defaultInstance->file_get_contents($path);
720
-	}
721
-
722
-	static public function file_put_contents($path, $data) {
723
-		return self::$defaultInstance->file_put_contents($path, $data);
724
-	}
725
-
726
-	static public function unlink($path) {
727
-		return self::$defaultInstance->unlink($path);
728
-	}
729
-
730
-	static public function rename($path1, $path2) {
731
-		return self::$defaultInstance->rename($path1, $path2);
732
-	}
733
-
734
-	static public function copy($path1, $path2) {
735
-		return self::$defaultInstance->copy($path1, $path2);
736
-	}
737
-
738
-	static public function fopen($path, $mode) {
739
-		return self::$defaultInstance->fopen($path, $mode);
740
-	}
741
-
742
-	/**
743
-	 * @return string
744
-	 */
745
-	static public function toTmpFile($path) {
746
-		return self::$defaultInstance->toTmpFile($path);
747
-	}
748
-
749
-	static public function fromTmpFile($tmpFile, $path) {
750
-		return self::$defaultInstance->fromTmpFile($tmpFile, $path);
751
-	}
752
-
753
-	static public function getMimeType($path) {
754
-		return self::$defaultInstance->getMimeType($path);
755
-	}
756
-
757
-	static public function hash($type, $path, $raw = false) {
758
-		return self::$defaultInstance->hash($type, $path, $raw);
759
-	}
760
-
761
-	static public function free_space($path = '/') {
762
-		return self::$defaultInstance->free_space($path);
763
-	}
764
-
765
-	static public function search($query) {
766
-		return self::$defaultInstance->search($query);
767
-	}
768
-
769
-	/**
770
-	 * @param string $query
771
-	 */
772
-	static public function searchByMime($query) {
773
-		return self::$defaultInstance->searchByMime($query);
774
-	}
775
-
776
-	/**
777
-	 * @param string|int $tag name or tag id
778
-	 * @param string $userId owner of the tags
779
-	 * @return FileInfo[] array or file info
780
-	 */
781
-	static public function searchByTag($tag, $userId) {
782
-		return self::$defaultInstance->searchByTag($tag, $userId);
783
-	}
784
-
785
-	/**
786
-	 * check if a file or folder has been updated since $time
787
-	 *
788
-	 * @param string $path
789
-	 * @param int $time
790
-	 * @return bool
791
-	 */
792
-	static public function hasUpdated($path, $time) {
793
-		return self::$defaultInstance->hasUpdated($path, $time);
794
-	}
795
-
796
-	/**
797
-	 * Fix common problems with a file path
798
-	 *
799
-	 * @param string $path
800
-	 * @param bool $stripTrailingSlash whether to strip the trailing slash
801
-	 * @param bool $isAbsolutePath whether the given path is absolute
802
-	 * @param bool $keepUnicode true to disable unicode normalization
803
-	 * @return string
804
-	 */
805
-	public static function normalizePath($path, $stripTrailingSlash = true, $isAbsolutePath = false, $keepUnicode = false) {
806
-		if (is_null(self::$normalizedPathCache)) {
807
-			self::$normalizedPathCache = new CappedMemoryCache();
808
-		}
809
-
810
-		/**
811
-		 * FIXME: This is a workaround for existing classes and files which call
812
-		 *        this function with another type than a valid string. This
813
-		 *        conversion should get removed as soon as all existing
814
-		 *        function calls have been fixed.
815
-		 */
816
-		$path = (string)$path;
817
-
818
-		$cacheKey = json_encode([$path, $stripTrailingSlash, $isAbsolutePath, $keepUnicode]);
819
-
820
-		if (isset(self::$normalizedPathCache[$cacheKey])) {
821
-			return self::$normalizedPathCache[$cacheKey];
822
-		}
823
-
824
-		if ($path == '') {
825
-			return '/';
826
-		}
827
-
828
-		//normalize unicode if possible
829
-		if (!$keepUnicode) {
830
-			$path = \OC_Util::normalizeUnicode($path);
831
-		}
832
-
833
-		//no windows style slashes
834
-		$path = str_replace('\\', '/', $path);
835
-
836
-		//add leading slash
837
-		if ($path[0] !== '/') {
838
-			$path = '/' . $path;
839
-		}
840
-
841
-		// remove '/./'
842
-		// ugly, but str_replace() can't replace them all in one go
843
-		// as the replacement itself is part of the search string
844
-		// which will only be found during the next iteration
845
-		while (strpos($path, '/./') !== false) {
846
-			$path = str_replace('/./', '/', $path);
847
-		}
848
-		// remove sequences of slashes
849
-		$path = preg_replace('#/{2,}#', '/', $path);
850
-
851
-		//remove trailing slash
852
-		if ($stripTrailingSlash and strlen($path) > 1 and substr($path, -1, 1) === '/') {
853
-			$path = substr($path, 0, -1);
854
-		}
855
-
856
-		// remove trailing '/.'
857
-		if (substr($path, -2) == '/.') {
858
-			$path = substr($path, 0, -2);
859
-		}
860
-
861
-		$normalizedPath = $path;
862
-		self::$normalizedPathCache[$cacheKey] = $normalizedPath;
863
-
864
-		return $normalizedPath;
865
-	}
866
-
867
-	/**
868
-	 * get the filesystem info
869
-	 *
870
-	 * @param string $path
871
-	 * @param boolean $includeMountPoints whether to add mountpoint sizes,
872
-	 * defaults to true
873
-	 * @return \OC\Files\FileInfo|bool False if file does not exist
874
-	 */
875
-	public static function getFileInfo($path, $includeMountPoints = true) {
876
-		return self::$defaultInstance->getFileInfo($path, $includeMountPoints);
877
-	}
878
-
879
-	/**
880
-	 * change file metadata
881
-	 *
882
-	 * @param string $path
883
-	 * @param array $data
884
-	 * @return int
885
-	 *
886
-	 * returns the fileid of the updated file
887
-	 */
888
-	public static function putFileInfo($path, $data) {
889
-		return self::$defaultInstance->putFileInfo($path, $data);
890
-	}
891
-
892
-	/**
893
-	 * get the content of a directory
894
-	 *
895
-	 * @param string $directory path under datadirectory
896
-	 * @param string $mimetype_filter limit returned content to this mimetype or mimepart
897
-	 * @return \OC\Files\FileInfo[]
898
-	 */
899
-	public static function getDirectoryContent($directory, $mimetype_filter = '') {
900
-		return self::$defaultInstance->getDirectoryContent($directory, $mimetype_filter);
901
-	}
902
-
903
-	/**
904
-	 * Get the path of a file by id
905
-	 *
906
-	 * Note that the resulting path is not guaranteed to be unique for the id, multiple paths can point to the same file
907
-	 *
908
-	 * @param int $id
909
-	 * @throws NotFoundException
910
-	 * @return string
911
-	 */
912
-	public static function getPath($id) {
913
-		return self::$defaultInstance->getPath($id);
914
-	}
915
-
916
-	/**
917
-	 * Get the owner for a file or folder
918
-	 *
919
-	 * @param string $path
920
-	 * @return string
921
-	 */
922
-	public static function getOwner($path) {
923
-		return self::$defaultInstance->getOwner($path);
924
-	}
925
-
926
-	/**
927
-	 * get the ETag for a file or folder
928
-	 *
929
-	 * @param string $path
930
-	 * @return string
931
-	 */
932
-	static public function getETag($path) {
933
-		return self::$defaultInstance->getETag($path);
934
-	}
73
+    /**
74
+     * @var Mount\Manager $mounts
75
+     */
76
+    private static $mounts;
77
+
78
+    public static $loaded = false;
79
+    /**
80
+     * @var \OC\Files\View $defaultInstance
81
+     */
82
+    static private $defaultInstance;
83
+
84
+    static private $usersSetup = array();
85
+
86
+    static private $normalizedPathCache = null;
87
+
88
+    static private $listeningForProviders = false;
89
+
90
+    /**
91
+     * classname which used for hooks handling
92
+     * used as signalclass in OC_Hooks::emit()
93
+     */
94
+    const CLASSNAME = 'OC_Filesystem';
95
+
96
+    /**
97
+     * signalname emitted before file renaming
98
+     *
99
+     * @param string $oldpath
100
+     * @param string $newpath
101
+     */
102
+    const signal_rename = 'rename';
103
+
104
+    /**
105
+     * signal emitted after file renaming
106
+     *
107
+     * @param string $oldpath
108
+     * @param string $newpath
109
+     */
110
+    const signal_post_rename = 'post_rename';
111
+
112
+    /**
113
+     * signal emitted before file/dir creation
114
+     *
115
+     * @param string $path
116
+     * @param bool $run changing this flag to false in hook handler will cancel event
117
+     */
118
+    const signal_create = 'create';
119
+
120
+    /**
121
+     * signal emitted after file/dir creation
122
+     *
123
+     * @param string $path
124
+     * @param bool $run changing this flag to false in hook handler will cancel event
125
+     */
126
+    const signal_post_create = 'post_create';
127
+
128
+    /**
129
+     * signal emits before file/dir copy
130
+     *
131
+     * @param string $oldpath
132
+     * @param string $newpath
133
+     * @param bool $run changing this flag to false in hook handler will cancel event
134
+     */
135
+    const signal_copy = 'copy';
136
+
137
+    /**
138
+     * signal emits after file/dir copy
139
+     *
140
+     * @param string $oldpath
141
+     * @param string $newpath
142
+     */
143
+    const signal_post_copy = 'post_copy';
144
+
145
+    /**
146
+     * signal emits before file/dir save
147
+     *
148
+     * @param string $path
149
+     * @param bool $run changing this flag to false in hook handler will cancel event
150
+     */
151
+    const signal_write = 'write';
152
+
153
+    /**
154
+     * signal emits after file/dir save
155
+     *
156
+     * @param string $path
157
+     */
158
+    const signal_post_write = 'post_write';
159
+
160
+    /**
161
+     * signal emitted before file/dir update
162
+     *
163
+     * @param string $path
164
+     * @param bool $run changing this flag to false in hook handler will cancel event
165
+     */
166
+    const signal_update = 'update';
167
+
168
+    /**
169
+     * signal emitted after file/dir update
170
+     *
171
+     * @param string $path
172
+     * @param bool $run changing this flag to false in hook handler will cancel event
173
+     */
174
+    const signal_post_update = 'post_update';
175
+
176
+    /**
177
+     * signal emits when reading file/dir
178
+     *
179
+     * @param string $path
180
+     */
181
+    const signal_read = 'read';
182
+
183
+    /**
184
+     * signal emits when removing file/dir
185
+     *
186
+     * @param string $path
187
+     */
188
+    const signal_delete = 'delete';
189
+
190
+    /**
191
+     * parameters definitions for signals
192
+     */
193
+    const signal_param_path = 'path';
194
+    const signal_param_oldpath = 'oldpath';
195
+    const signal_param_newpath = 'newpath';
196
+
197
+    /**
198
+     * run - changing this flag to false in hook handler will cancel event
199
+     */
200
+    const signal_param_run = 'run';
201
+
202
+    const signal_create_mount = 'create_mount';
203
+    const signal_delete_mount = 'delete_mount';
204
+    const signal_param_mount_type = 'mounttype';
205
+    const signal_param_users = 'users';
206
+
207
+    /**
208
+     * @var \OC\Files\Storage\StorageFactory $loader
209
+     */
210
+    private static $loader;
211
+
212
+    /** @var bool */
213
+    private static $logWarningWhenAddingStorageWrapper = true;
214
+
215
+    /**
216
+     * @param bool $shouldLog
217
+     * @return bool previous value
218
+     * @internal
219
+     */
220
+    public static function logWarningWhenAddingStorageWrapper($shouldLog) {
221
+        $previousValue = self::$logWarningWhenAddingStorageWrapper;
222
+        self::$logWarningWhenAddingStorageWrapper = (bool) $shouldLog;
223
+        return $previousValue;
224
+    }
225
+
226
+    /**
227
+     * @param string $wrapperName
228
+     * @param callable $wrapper
229
+     * @param int $priority
230
+     */
231
+    public static function addStorageWrapper($wrapperName, $wrapper, $priority = 50) {
232
+        if (self::$logWarningWhenAddingStorageWrapper) {
233
+            \OC::$server->getLogger()->warning("Storage wrapper '{wrapper}' was not registered via the 'OC_Filesystem - preSetup' hook which could cause potential problems.", [
234
+                'wrapper' => $wrapperName,
235
+                'app' => 'filesystem',
236
+            ]);
237
+        }
238
+
239
+        $mounts = self::getMountManager()->getAll();
240
+        if (!self::getLoader()->addStorageWrapper($wrapperName, $wrapper, $priority, $mounts)) {
241
+            // do not re-wrap if storage with this name already existed
242
+            return;
243
+        }
244
+    }
245
+
246
+    /**
247
+     * Returns the storage factory
248
+     *
249
+     * @return \OCP\Files\Storage\IStorageFactory
250
+     */
251
+    public static function getLoader() {
252
+        if (!self::$loader) {
253
+            self::$loader = new StorageFactory();
254
+        }
255
+        return self::$loader;
256
+    }
257
+
258
+    /**
259
+     * Returns the mount manager
260
+     *
261
+     * @return \OC\Files\Mount\Manager
262
+     */
263
+    public static function getMountManager($user = '') {
264
+        if (!self::$mounts) {
265
+            \OC_Util::setupFS($user);
266
+        }
267
+        return self::$mounts;
268
+    }
269
+
270
+    /**
271
+     * get the mountpoint of the storage object for a path
272
+     * ( note: because a storage is not always mounted inside the fakeroot, the
273
+     * returned mountpoint is relative to the absolute root of the filesystem
274
+     * and doesn't take the chroot into account )
275
+     *
276
+     * @param string $path
277
+     * @return string
278
+     */
279
+    static public function getMountPoint($path) {
280
+        if (!self::$mounts) {
281
+            \OC_Util::setupFS();
282
+        }
283
+        $mount = self::$mounts->find($path);
284
+        if ($mount) {
285
+            return $mount->getMountPoint();
286
+        } else {
287
+            return '';
288
+        }
289
+    }
290
+
291
+    /**
292
+     * get a list of all mount points in a directory
293
+     *
294
+     * @param string $path
295
+     * @return string[]
296
+     */
297
+    static public function getMountPoints($path) {
298
+        if (!self::$mounts) {
299
+            \OC_Util::setupFS();
300
+        }
301
+        $result = array();
302
+        $mounts = self::$mounts->findIn($path);
303
+        foreach ($mounts as $mount) {
304
+            $result[] = $mount->getMountPoint();
305
+        }
306
+        return $result;
307
+    }
308
+
309
+    /**
310
+     * get the storage mounted at $mountPoint
311
+     *
312
+     * @param string $mountPoint
313
+     * @return \OC\Files\Storage\Storage
314
+     */
315
+    public static function getStorage($mountPoint) {
316
+        if (!self::$mounts) {
317
+            \OC_Util::setupFS();
318
+        }
319
+        $mount = self::$mounts->find($mountPoint);
320
+        return $mount->getStorage();
321
+    }
322
+
323
+    /**
324
+     * @param string $id
325
+     * @return Mount\MountPoint[]
326
+     */
327
+    public static function getMountByStorageId($id) {
328
+        if (!self::$mounts) {
329
+            \OC_Util::setupFS();
330
+        }
331
+        return self::$mounts->findByStorageId($id);
332
+    }
333
+
334
+    /**
335
+     * @param int $id
336
+     * @return Mount\MountPoint[]
337
+     */
338
+    public static function getMountByNumericId($id) {
339
+        if (!self::$mounts) {
340
+            \OC_Util::setupFS();
341
+        }
342
+        return self::$mounts->findByNumericId($id);
343
+    }
344
+
345
+    /**
346
+     * resolve a path to a storage and internal path
347
+     *
348
+     * @param string $path
349
+     * @return array an array consisting of the storage and the internal path
350
+     */
351
+    static public function resolvePath($path) {
352
+        if (!self::$mounts) {
353
+            \OC_Util::setupFS();
354
+        }
355
+        $mount = self::$mounts->find($path);
356
+        if ($mount) {
357
+            return array($mount->getStorage(), rtrim($mount->getInternalPath($path), '/'));
358
+        } else {
359
+            return array(null, null);
360
+        }
361
+    }
362
+
363
+    static public function init($user, $root) {
364
+        if (self::$defaultInstance) {
365
+            return false;
366
+        }
367
+        self::getLoader();
368
+        self::$defaultInstance = new View($root);
369
+
370
+        if (!self::$mounts) {
371
+            self::$mounts = \OC::$server->getMountManager();
372
+        }
373
+
374
+        //load custom mount config
375
+        self::initMountPoints($user);
376
+
377
+        self::$loaded = true;
378
+
379
+        return true;
380
+    }
381
+
382
+    static public function initMountManager() {
383
+        if (!self::$mounts) {
384
+            self::$mounts = \OC::$server->getMountManager();
385
+        }
386
+    }
387
+
388
+    /**
389
+     * Initialize system and personal mount points for a user
390
+     *
391
+     * @param string $user
392
+     * @throws \OC\User\NoUserException if the user is not available
393
+     */
394
+    public static function initMountPoints($user = '') {
395
+        if ($user == '') {
396
+            $user = \OC_User::getUser();
397
+        }
398
+        if ($user === null || $user === false || $user === '') {
399
+            throw new \OC\User\NoUserException('Attempted to initialize mount points for null user and no user in session');
400
+        }
401
+
402
+        if (isset(self::$usersSetup[$user])) {
403
+            return;
404
+        }
405
+
406
+        self::$usersSetup[$user] = true;
407
+
408
+        $userManager = \OC::$server->getUserManager();
409
+        $userObject = $userManager->get($user);
410
+
411
+        if (is_null($userObject)) {
412
+            \OCP\Util::writeLog('files', ' Backends provided no user object for ' . $user, \OCP\Util::ERROR);
413
+            // reset flag, this will make it possible to rethrow the exception if called again
414
+            unset(self::$usersSetup[$user]);
415
+            throw new \OC\User\NoUserException('Backends provided no user object for ' . $user);
416
+        }
417
+
418
+        $realUid = $userObject->getUID();
419
+        // workaround in case of different casings
420
+        if ($user !== $realUid) {
421
+            $stack = json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 50));
422
+            \OCP\Util::writeLog('files', 'initMountPoints() called with wrong user casing. This could be a bug. Expected: "' . $realUid . '" got "' . $user . '". Stack: ' . $stack, \OCP\Util::WARN);
423
+            $user = $realUid;
424
+
425
+            // again with the correct casing
426
+            if (isset(self::$usersSetup[$user])) {
427
+                return;
428
+            }
429
+
430
+            self::$usersSetup[$user] = true;
431
+        }
432
+
433
+        if (\OC::$server->getLockdownManager()->canAccessFilesystem()) {
434
+            /** @var \OC\Files\Config\MountProviderCollection $mountConfigManager */
435
+            $mountConfigManager = \OC::$server->getMountProviderCollection();
436
+
437
+            // home mounts are handled seperate since we need to ensure this is mounted before we call the other mount providers
438
+            $homeMount = $mountConfigManager->getHomeMountForUser($userObject);
439
+
440
+            self::getMountManager()->addMount($homeMount);
441
+
442
+            \OC\Files\Filesystem::getStorage($user);
443
+
444
+            // Chance to mount for other storages
445
+            if ($userObject) {
446
+                $mounts = $mountConfigManager->getMountsForUser($userObject);
447
+                array_walk($mounts, array(self::$mounts, 'addMount'));
448
+                $mounts[] = $homeMount;
449
+                $mountConfigManager->registerMounts($userObject, $mounts);
450
+            }
451
+
452
+            self::listenForNewMountProviders($mountConfigManager, $userManager);
453
+        } else {
454
+            self::getMountManager()->addMount(new MountPoint(
455
+                new NullStorage([]),
456
+                '/' . $user
457
+            ));
458
+            self::getMountManager()->addMount(new MountPoint(
459
+                new NullStorage([]),
460
+                '/' . $user . '/files'
461
+            ));
462
+        }
463
+        \OC_Hook::emit('OC_Filesystem', 'post_initMountPoints', array('user' => $user));
464
+    }
465
+
466
+    /**
467
+     * Get mounts from mount providers that are registered after setup
468
+     *
469
+     * @param MountProviderCollection $mountConfigManager
470
+     * @param IUserManager $userManager
471
+     */
472
+    private static function listenForNewMountProviders(MountProviderCollection $mountConfigManager, IUserManager $userManager) {
473
+        if (!self::$listeningForProviders) {
474
+            self::$listeningForProviders = true;
475
+            $mountConfigManager->listen('\OC\Files\Config', 'registerMountProvider', function (IMountProvider $provider) use ($userManager) {
476
+                foreach (Filesystem::$usersSetup as $user => $setup) {
477
+                    $userObject = $userManager->get($user);
478
+                    if ($userObject) {
479
+                        $mounts = $provider->getMountsForUser($userObject, Filesystem::getLoader());
480
+                        array_walk($mounts, array(self::$mounts, 'addMount'));
481
+                    }
482
+                }
483
+            });
484
+        }
485
+    }
486
+
487
+    /**
488
+     * get the default filesystem view
489
+     *
490
+     * @return View
491
+     */
492
+    static public function getView() {
493
+        return self::$defaultInstance;
494
+    }
495
+
496
+    /**
497
+     * tear down the filesystem, removing all storage providers
498
+     */
499
+    static public function tearDown() {
500
+        self::clearMounts();
501
+        self::$defaultInstance = null;
502
+    }
503
+
504
+    /**
505
+     * get the relative path of the root data directory for the current user
506
+     *
507
+     * @return string
508
+     *
509
+     * Returns path like /admin/files
510
+     */
511
+    static public function getRoot() {
512
+        if (!self::$defaultInstance) {
513
+            return null;
514
+        }
515
+        return self::$defaultInstance->getRoot();
516
+    }
517
+
518
+    /**
519
+     * clear all mounts and storage backends
520
+     */
521
+    public static function clearMounts() {
522
+        if (self::$mounts) {
523
+            self::$usersSetup = array();
524
+            self::$mounts->clear();
525
+        }
526
+    }
527
+
528
+    /**
529
+     * mount an \OC\Files\Storage\Storage in our virtual filesystem
530
+     *
531
+     * @param \OC\Files\Storage\Storage|string $class
532
+     * @param array $arguments
533
+     * @param string $mountpoint
534
+     */
535
+    static public function mount($class, $arguments, $mountpoint) {
536
+        if (!self::$mounts) {
537
+            \OC_Util::setupFS();
538
+        }
539
+        $mount = new Mount\MountPoint($class, $mountpoint, $arguments, self::getLoader());
540
+        self::$mounts->addMount($mount);
541
+    }
542
+
543
+    /**
544
+     * return the path to a local version of the file
545
+     * we need this because we can't know if a file is stored local or not from
546
+     * outside the filestorage and for some purposes a local file is needed
547
+     *
548
+     * @param string $path
549
+     * @return string
550
+     */
551
+    static public function getLocalFile($path) {
552
+        return self::$defaultInstance->getLocalFile($path);
553
+    }
554
+
555
+    /**
556
+     * @param string $path
557
+     * @return string
558
+     */
559
+    static public function getLocalFolder($path) {
560
+        return self::$defaultInstance->getLocalFolder($path);
561
+    }
562
+
563
+    /**
564
+     * return path to file which reflects one visible in browser
565
+     *
566
+     * @param string $path
567
+     * @return string
568
+     */
569
+    static public function getLocalPath($path) {
570
+        $datadir = \OC_User::getHome(\OC_User::getUser()) . '/files';
571
+        $newpath = $path;
572
+        if (strncmp($newpath, $datadir, strlen($datadir)) == 0) {
573
+            $newpath = substr($path, strlen($datadir));
574
+        }
575
+        return $newpath;
576
+    }
577
+
578
+    /**
579
+     * check if the requested path is valid
580
+     *
581
+     * @param string $path
582
+     * @return bool
583
+     */
584
+    static public function isValidPath($path) {
585
+        $path = self::normalizePath($path);
586
+        if (!$path || $path[0] !== '/') {
587
+            $path = '/' . $path;
588
+        }
589
+        if (strpos($path, '/../') !== false || strrchr($path, '/') === '/..') {
590
+            return false;
591
+        }
592
+        return true;
593
+    }
594
+
595
+    /**
596
+     * checks if a file is blacklisted for storage in the filesystem
597
+     * Listens to write and rename hooks
598
+     *
599
+     * @param array $data from hook
600
+     */
601
+    static public function isBlacklisted($data) {
602
+        if (isset($data['path'])) {
603
+            $path = $data['path'];
604
+        } else if (isset($data['newpath'])) {
605
+            $path = $data['newpath'];
606
+        }
607
+        if (isset($path)) {
608
+            if (self::isFileBlacklisted($path)) {
609
+                $data['run'] = false;
610
+            }
611
+        }
612
+    }
613
+
614
+    /**
615
+     * @param string $filename
616
+     * @return bool
617
+     */
618
+    static public function isFileBlacklisted($filename) {
619
+        $filename = self::normalizePath($filename);
620
+
621
+        $blacklist = \OC::$server->getConfig()->getSystemValue('blacklisted_files', array('.htaccess'));
622
+        $filename = strtolower(basename($filename));
623
+        return in_array($filename, $blacklist);
624
+    }
625
+
626
+    /**
627
+     * check if the directory should be ignored when scanning
628
+     * NOTE: the special directories . and .. would cause never ending recursion
629
+     *
630
+     * @param String $dir
631
+     * @return boolean
632
+     */
633
+    static public function isIgnoredDir($dir) {
634
+        if ($dir === '.' || $dir === '..') {
635
+            return true;
636
+        }
637
+        return false;
638
+    }
639
+
640
+    /**
641
+     * following functions are equivalent to their php builtin equivalents for arguments/return values.
642
+     */
643
+    static public function mkdir($path) {
644
+        return self::$defaultInstance->mkdir($path);
645
+    }
646
+
647
+    static public function rmdir($path) {
648
+        return self::$defaultInstance->rmdir($path);
649
+    }
650
+
651
+    static public function opendir($path) {
652
+        return self::$defaultInstance->opendir($path);
653
+    }
654
+
655
+    static public function readdir($path) {
656
+        return self::$defaultInstance->readdir($path);
657
+    }
658
+
659
+    static public function is_dir($path) {
660
+        return self::$defaultInstance->is_dir($path);
661
+    }
662
+
663
+    static public function is_file($path) {
664
+        return self::$defaultInstance->is_file($path);
665
+    }
666
+
667
+    static public function stat($path) {
668
+        return self::$defaultInstance->stat($path);
669
+    }
670
+
671
+    static public function filetype($path) {
672
+        return self::$defaultInstance->filetype($path);
673
+    }
674
+
675
+    static public function filesize($path) {
676
+        return self::$defaultInstance->filesize($path);
677
+    }
678
+
679
+    static public function readfile($path) {
680
+        return self::$defaultInstance->readfile($path);
681
+    }
682
+
683
+    static public function isCreatable($path) {
684
+        return self::$defaultInstance->isCreatable($path);
685
+    }
686
+
687
+    static public function isReadable($path) {
688
+        return self::$defaultInstance->isReadable($path);
689
+    }
690
+
691
+    static public function isUpdatable($path) {
692
+        return self::$defaultInstance->isUpdatable($path);
693
+    }
694
+
695
+    static public function isDeletable($path) {
696
+        return self::$defaultInstance->isDeletable($path);
697
+    }
698
+
699
+    static public function isSharable($path) {
700
+        return self::$defaultInstance->isSharable($path);
701
+    }
702
+
703
+    static public function file_exists($path) {
704
+        return self::$defaultInstance->file_exists($path);
705
+    }
706
+
707
+    static public function filemtime($path) {
708
+        return self::$defaultInstance->filemtime($path);
709
+    }
710
+
711
+    static public function touch($path, $mtime = null) {
712
+        return self::$defaultInstance->touch($path, $mtime);
713
+    }
714
+
715
+    /**
716
+     * @return string
717
+     */
718
+    static public function file_get_contents($path) {
719
+        return self::$defaultInstance->file_get_contents($path);
720
+    }
721
+
722
+    static public function file_put_contents($path, $data) {
723
+        return self::$defaultInstance->file_put_contents($path, $data);
724
+    }
725
+
726
+    static public function unlink($path) {
727
+        return self::$defaultInstance->unlink($path);
728
+    }
729
+
730
+    static public function rename($path1, $path2) {
731
+        return self::$defaultInstance->rename($path1, $path2);
732
+    }
733
+
734
+    static public function copy($path1, $path2) {
735
+        return self::$defaultInstance->copy($path1, $path2);
736
+    }
737
+
738
+    static public function fopen($path, $mode) {
739
+        return self::$defaultInstance->fopen($path, $mode);
740
+    }
741
+
742
+    /**
743
+     * @return string
744
+     */
745
+    static public function toTmpFile($path) {
746
+        return self::$defaultInstance->toTmpFile($path);
747
+    }
748
+
749
+    static public function fromTmpFile($tmpFile, $path) {
750
+        return self::$defaultInstance->fromTmpFile($tmpFile, $path);
751
+    }
752
+
753
+    static public function getMimeType($path) {
754
+        return self::$defaultInstance->getMimeType($path);
755
+    }
756
+
757
+    static public function hash($type, $path, $raw = false) {
758
+        return self::$defaultInstance->hash($type, $path, $raw);
759
+    }
760
+
761
+    static public function free_space($path = '/') {
762
+        return self::$defaultInstance->free_space($path);
763
+    }
764
+
765
+    static public function search($query) {
766
+        return self::$defaultInstance->search($query);
767
+    }
768
+
769
+    /**
770
+     * @param string $query
771
+     */
772
+    static public function searchByMime($query) {
773
+        return self::$defaultInstance->searchByMime($query);
774
+    }
775
+
776
+    /**
777
+     * @param string|int $tag name or tag id
778
+     * @param string $userId owner of the tags
779
+     * @return FileInfo[] array or file info
780
+     */
781
+    static public function searchByTag($tag, $userId) {
782
+        return self::$defaultInstance->searchByTag($tag, $userId);
783
+    }
784
+
785
+    /**
786
+     * check if a file or folder has been updated since $time
787
+     *
788
+     * @param string $path
789
+     * @param int $time
790
+     * @return bool
791
+     */
792
+    static public function hasUpdated($path, $time) {
793
+        return self::$defaultInstance->hasUpdated($path, $time);
794
+    }
795
+
796
+    /**
797
+     * Fix common problems with a file path
798
+     *
799
+     * @param string $path
800
+     * @param bool $stripTrailingSlash whether to strip the trailing slash
801
+     * @param bool $isAbsolutePath whether the given path is absolute
802
+     * @param bool $keepUnicode true to disable unicode normalization
803
+     * @return string
804
+     */
805
+    public static function normalizePath($path, $stripTrailingSlash = true, $isAbsolutePath = false, $keepUnicode = false) {
806
+        if (is_null(self::$normalizedPathCache)) {
807
+            self::$normalizedPathCache = new CappedMemoryCache();
808
+        }
809
+
810
+        /**
811
+         * FIXME: This is a workaround for existing classes and files which call
812
+         *        this function with another type than a valid string. This
813
+         *        conversion should get removed as soon as all existing
814
+         *        function calls have been fixed.
815
+         */
816
+        $path = (string)$path;
817
+
818
+        $cacheKey = json_encode([$path, $stripTrailingSlash, $isAbsolutePath, $keepUnicode]);
819
+
820
+        if (isset(self::$normalizedPathCache[$cacheKey])) {
821
+            return self::$normalizedPathCache[$cacheKey];
822
+        }
823
+
824
+        if ($path == '') {
825
+            return '/';
826
+        }
827
+
828
+        //normalize unicode if possible
829
+        if (!$keepUnicode) {
830
+            $path = \OC_Util::normalizeUnicode($path);
831
+        }
832
+
833
+        //no windows style slashes
834
+        $path = str_replace('\\', '/', $path);
835
+
836
+        //add leading slash
837
+        if ($path[0] !== '/') {
838
+            $path = '/' . $path;
839
+        }
840
+
841
+        // remove '/./'
842
+        // ugly, but str_replace() can't replace them all in one go
843
+        // as the replacement itself is part of the search string
844
+        // which will only be found during the next iteration
845
+        while (strpos($path, '/./') !== false) {
846
+            $path = str_replace('/./', '/', $path);
847
+        }
848
+        // remove sequences of slashes
849
+        $path = preg_replace('#/{2,}#', '/', $path);
850
+
851
+        //remove trailing slash
852
+        if ($stripTrailingSlash and strlen($path) > 1 and substr($path, -1, 1) === '/') {
853
+            $path = substr($path, 0, -1);
854
+        }
855
+
856
+        // remove trailing '/.'
857
+        if (substr($path, -2) == '/.') {
858
+            $path = substr($path, 0, -2);
859
+        }
860
+
861
+        $normalizedPath = $path;
862
+        self::$normalizedPathCache[$cacheKey] = $normalizedPath;
863
+
864
+        return $normalizedPath;
865
+    }
866
+
867
+    /**
868
+     * get the filesystem info
869
+     *
870
+     * @param string $path
871
+     * @param boolean $includeMountPoints whether to add mountpoint sizes,
872
+     * defaults to true
873
+     * @return \OC\Files\FileInfo|bool False if file does not exist
874
+     */
875
+    public static function getFileInfo($path, $includeMountPoints = true) {
876
+        return self::$defaultInstance->getFileInfo($path, $includeMountPoints);
877
+    }
878
+
879
+    /**
880
+     * change file metadata
881
+     *
882
+     * @param string $path
883
+     * @param array $data
884
+     * @return int
885
+     *
886
+     * returns the fileid of the updated file
887
+     */
888
+    public static function putFileInfo($path, $data) {
889
+        return self::$defaultInstance->putFileInfo($path, $data);
890
+    }
891
+
892
+    /**
893
+     * get the content of a directory
894
+     *
895
+     * @param string $directory path under datadirectory
896
+     * @param string $mimetype_filter limit returned content to this mimetype or mimepart
897
+     * @return \OC\Files\FileInfo[]
898
+     */
899
+    public static function getDirectoryContent($directory, $mimetype_filter = '') {
900
+        return self::$defaultInstance->getDirectoryContent($directory, $mimetype_filter);
901
+    }
902
+
903
+    /**
904
+     * Get the path of a file by id
905
+     *
906
+     * Note that the resulting path is not guaranteed to be unique for the id, multiple paths can point to the same file
907
+     *
908
+     * @param int $id
909
+     * @throws NotFoundException
910
+     * @return string
911
+     */
912
+    public static function getPath($id) {
913
+        return self::$defaultInstance->getPath($id);
914
+    }
915
+
916
+    /**
917
+     * Get the owner for a file or folder
918
+     *
919
+     * @param string $path
920
+     * @return string
921
+     */
922
+    public static function getOwner($path) {
923
+        return self::$defaultInstance->getOwner($path);
924
+    }
925
+
926
+    /**
927
+     * get the ETag for a file or folder
928
+     *
929
+     * @param string $path
930
+     * @return string
931
+     */
932
+    static public function getETag($path) {
933
+        return self::$defaultInstance->getETag($path);
934
+    }
935 935
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -409,17 +409,17 @@  discard block
 block discarded – undo
409 409
 		$userObject = $userManager->get($user);
410 410
 
411 411
 		if (is_null($userObject)) {
412
-			\OCP\Util::writeLog('files', ' Backends provided no user object for ' . $user, \OCP\Util::ERROR);
412
+			\OCP\Util::writeLog('files', ' Backends provided no user object for '.$user, \OCP\Util::ERROR);
413 413
 			// reset flag, this will make it possible to rethrow the exception if called again
414 414
 			unset(self::$usersSetup[$user]);
415
-			throw new \OC\User\NoUserException('Backends provided no user object for ' . $user);
415
+			throw new \OC\User\NoUserException('Backends provided no user object for '.$user);
416 416
 		}
417 417
 
418 418
 		$realUid = $userObject->getUID();
419 419
 		// workaround in case of different casings
420 420
 		if ($user !== $realUid) {
421 421
 			$stack = json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 50));
422
-			\OCP\Util::writeLog('files', 'initMountPoints() called with wrong user casing. This could be a bug. Expected: "' . $realUid . '" got "' . $user . '". Stack: ' . $stack, \OCP\Util::WARN);
422
+			\OCP\Util::writeLog('files', 'initMountPoints() called with wrong user casing. This could be a bug. Expected: "'.$realUid.'" got "'.$user.'". Stack: '.$stack, \OCP\Util::WARN);
423 423
 			$user = $realUid;
424 424
 
425 425
 			// again with the correct casing
@@ -453,11 +453,11 @@  discard block
 block discarded – undo
453 453
 		} else {
454 454
 			self::getMountManager()->addMount(new MountPoint(
455 455
 				new NullStorage([]),
456
-				'/' . $user
456
+				'/'.$user
457 457
 			));
458 458
 			self::getMountManager()->addMount(new MountPoint(
459 459
 				new NullStorage([]),
460
-				'/' . $user . '/files'
460
+				'/'.$user.'/files'
461 461
 			));
462 462
 		}
463 463
 		\OC_Hook::emit('OC_Filesystem', 'post_initMountPoints', array('user' => $user));
@@ -472,7 +472,7 @@  discard block
 block discarded – undo
472 472
 	private static function listenForNewMountProviders(MountProviderCollection $mountConfigManager, IUserManager $userManager) {
473 473
 		if (!self::$listeningForProviders) {
474 474
 			self::$listeningForProviders = true;
475
-			$mountConfigManager->listen('\OC\Files\Config', 'registerMountProvider', function (IMountProvider $provider) use ($userManager) {
475
+			$mountConfigManager->listen('\OC\Files\Config', 'registerMountProvider', function(IMountProvider $provider) use ($userManager) {
476 476
 				foreach (Filesystem::$usersSetup as $user => $setup) {
477 477
 					$userObject = $userManager->get($user);
478 478
 					if ($userObject) {
@@ -567,7 +567,7 @@  discard block
 block discarded – undo
567 567
 	 * @return string
568 568
 	 */
569 569
 	static public function getLocalPath($path) {
570
-		$datadir = \OC_User::getHome(\OC_User::getUser()) . '/files';
570
+		$datadir = \OC_User::getHome(\OC_User::getUser()).'/files';
571 571
 		$newpath = $path;
572 572
 		if (strncmp($newpath, $datadir, strlen($datadir)) == 0) {
573 573
 			$newpath = substr($path, strlen($datadir));
@@ -584,7 +584,7 @@  discard block
 block discarded – undo
584 584
 	static public function isValidPath($path) {
585 585
 		$path = self::normalizePath($path);
586 586
 		if (!$path || $path[0] !== '/') {
587
-			$path = '/' . $path;
587
+			$path = '/'.$path;
588 588
 		}
589 589
 		if (strpos($path, '/../') !== false || strrchr($path, '/') === '/..') {
590 590
 			return false;
@@ -813,7 +813,7 @@  discard block
 block discarded – undo
813 813
 		 *        conversion should get removed as soon as all existing
814 814
 		 *        function calls have been fixed.
815 815
 		 */
816
-		$path = (string)$path;
816
+		$path = (string) $path;
817 817
 
818 818
 		$cacheKey = json_encode([$path, $stripTrailingSlash, $isAbsolutePath, $keepUnicode]);
819 819
 
@@ -835,7 +835,7 @@  discard block
 block discarded – undo
835 835
 
836 836
 		//add leading slash
837 837
 		if ($path[0] !== '/') {
838
-			$path = '/' . $path;
838
+			$path = '/'.$path;
839 839
 		}
840 840
 
841 841
 		// remove '/./'
Please login to merge, or discard this patch.
lib/private/Files/Storage/Wrapper/Encryption.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -984,7 +984,7 @@  discard block
 block discarded – undo
984 984
 	/**
985 985
 	 * check if path points to a files version
986 986
 	 *
987
-	 * @param $path
987
+	 * @param string $path
988 988
 	 * @return bool
989 989
 	 */
990 990
 	protected function isVersion($path) {
@@ -995,7 +995,7 @@  discard block
 block discarded – undo
995 995
 	/**
996 996
 	 * check if the given storage should be encrypted or not
997 997
 	 *
998
-	 * @param $path
998
+	 * @param string $path
999 999
 	 * @return bool
1000 1000
 	 */
1001 1001
 	protected function shouldEncrypt($path) {
Please login to merge, or discard this patch.
Indentation   +972 added lines, -972 removed lines patch added patch discarded remove patch
@@ -46,977 +46,977 @@
 block discarded – undo
46 46
 
47 47
 class Encryption extends Wrapper {
48 48
 
49
-	use LocalTempFileTrait;
50
-
51
-	/** @var string */
52
-	private $mountPoint;
53
-
54
-	/** @var \OC\Encryption\Util */
55
-	private $util;
56
-
57
-	/** @var \OCP\Encryption\IManager */
58
-	private $encryptionManager;
59
-
60
-	/** @var \OCP\ILogger */
61
-	private $logger;
62
-
63
-	/** @var string */
64
-	private $uid;
65
-
66
-	/** @var array */
67
-	protected $unencryptedSize;
68
-
69
-	/** @var \OCP\Encryption\IFile */
70
-	private $fileHelper;
71
-
72
-	/** @var IMountPoint */
73
-	private $mount;
74
-
75
-	/** @var IStorage */
76
-	private $keyStorage;
77
-
78
-	/** @var Update */
79
-	private $update;
80
-
81
-	/** @var Manager */
82
-	private $mountManager;
83
-
84
-	/** @var array remember for which path we execute the repair step to avoid recursions */
85
-	private $fixUnencryptedSizeOf = array();
86
-
87
-	/** @var  ArrayCache */
88
-	private $arrayCache;
89
-
90
-	/**
91
-	 * @param array $parameters
92
-	 * @param IManager $encryptionManager
93
-	 * @param Util $util
94
-	 * @param ILogger $logger
95
-	 * @param IFile $fileHelper
96
-	 * @param string $uid
97
-	 * @param IStorage $keyStorage
98
-	 * @param Update $update
99
-	 * @param Manager $mountManager
100
-	 * @param ArrayCache $arrayCache
101
-	 */
102
-	public function __construct(
103
-			$parameters,
104
-			IManager $encryptionManager = null,
105
-			Util $util = null,
106
-			ILogger $logger = null,
107
-			IFile $fileHelper = null,
108
-			$uid = null,
109
-			IStorage $keyStorage = null,
110
-			Update $update = null,
111
-			Manager $mountManager = null,
112
-			ArrayCache $arrayCache = null
113
-		) {
114
-
115
-		$this->mountPoint = $parameters['mountPoint'];
116
-		$this->mount = $parameters['mount'];
117
-		$this->encryptionManager = $encryptionManager;
118
-		$this->util = $util;
119
-		$this->logger = $logger;
120
-		$this->uid = $uid;
121
-		$this->fileHelper = $fileHelper;
122
-		$this->keyStorage = $keyStorage;
123
-		$this->unencryptedSize = array();
124
-		$this->update = $update;
125
-		$this->mountManager = $mountManager;
126
-		$this->arrayCache = $arrayCache;
127
-		parent::__construct($parameters);
128
-	}
129
-
130
-	/**
131
-	 * see http://php.net/manual/en/function.filesize.php
132
-	 * The result for filesize when called on a folder is required to be 0
133
-	 *
134
-	 * @param string $path
135
-	 * @return int
136
-	 */
137
-	public function filesize($path) {
138
-		$fullPath = $this->getFullPath($path);
139
-
140
-		/** @var CacheEntry $info */
141
-		$info = $this->getCache()->get($path);
142
-		if (isset($this->unencryptedSize[$fullPath])) {
143
-			$size = $this->unencryptedSize[$fullPath];
144
-			// update file cache
145
-			if ($info instanceof ICacheEntry) {
146
-				$info = $info->getData();
147
-				$info['encrypted'] = $info['encryptedVersion'];
148
-			} else {
149
-				if (!is_array($info)) {
150
-					$info = [];
151
-				}
152
-				$info['encrypted'] = true;
153
-			}
154
-
155
-			$info['size'] = $size;
156
-			$this->getCache()->put($path, $info);
157
-
158
-			return $size;
159
-		}
160
-
161
-		if (isset($info['fileid']) && $info['encrypted']) {
162
-			return $this->verifyUnencryptedSize($path, $info['size']);
163
-		}
164
-
165
-		return $this->storage->filesize($path);
166
-	}
167
-
168
-	/**
169
-	 * @param string $path
170
-	 * @return array
171
-	 */
172
-	public function getMetaData($path) {
173
-		$data = $this->storage->getMetaData($path);
174
-		if (is_null($data)) {
175
-			return null;
176
-		}
177
-		$fullPath = $this->getFullPath($path);
178
-		$info = $this->getCache()->get($path);
179
-
180
-		if (isset($this->unencryptedSize[$fullPath])) {
181
-			$data['encrypted'] = true;
182
-			$data['size'] = $this->unencryptedSize[$fullPath];
183
-		} else {
184
-			if (isset($info['fileid']) && $info['encrypted']) {
185
-				$data['size'] = $this->verifyUnencryptedSize($path, $info['size']);
186
-				$data['encrypted'] = true;
187
-			}
188
-		}
189
-
190
-		if (isset($info['encryptedVersion']) && $info['encryptedVersion'] > 1) {
191
-			$data['encryptedVersion'] = $info['encryptedVersion'];
192
-		}
193
-
194
-		return $data;
195
-	}
196
-
197
-	/**
198
-	 * see http://php.net/manual/en/function.file_get_contents.php
199
-	 *
200
-	 * @param string $path
201
-	 * @return string
202
-	 */
203
-	public function file_get_contents($path) {
204
-
205
-		$encryptionModule = $this->getEncryptionModule($path);
206
-
207
-		if ($encryptionModule) {
208
-			$handle = $this->fopen($path, "r");
209
-			if (!$handle) {
210
-				return false;
211
-			}
212
-			$data = stream_get_contents($handle);
213
-			fclose($handle);
214
-			return $data;
215
-		}
216
-		return $this->storage->file_get_contents($path);
217
-	}
218
-
219
-	/**
220
-	 * see http://php.net/manual/en/function.file_put_contents.php
221
-	 *
222
-	 * @param string $path
223
-	 * @param string $data
224
-	 * @return bool
225
-	 */
226
-	public function file_put_contents($path, $data) {
227
-		// file put content will always be translated to a stream write
228
-		$handle = $this->fopen($path, 'w');
229
-		if (is_resource($handle)) {
230
-			$written = fwrite($handle, $data);
231
-			fclose($handle);
232
-			return $written;
233
-		}
234
-
235
-		return false;
236
-	}
237
-
238
-	/**
239
-	 * see http://php.net/manual/en/function.unlink.php
240
-	 *
241
-	 * @param string $path
242
-	 * @return bool
243
-	 */
244
-	public function unlink($path) {
245
-		$fullPath = $this->getFullPath($path);
246
-		if ($this->util->isExcluded($fullPath)) {
247
-			return $this->storage->unlink($path);
248
-		}
249
-
250
-		$encryptionModule = $this->getEncryptionModule($path);
251
-		if ($encryptionModule) {
252
-			$this->keyStorage->deleteAllFileKeys($this->getFullPath($path));
253
-		}
254
-
255
-		return $this->storage->unlink($path);
256
-	}
257
-
258
-	/**
259
-	 * see http://php.net/manual/en/function.rename.php
260
-	 *
261
-	 * @param string $path1
262
-	 * @param string $path2
263
-	 * @return bool
264
-	 */
265
-	public function rename($path1, $path2) {
266
-
267
-		$result = $this->storage->rename($path1, $path2);
268
-
269
-		if ($result &&
270
-			// versions always use the keys from the original file, so we can skip
271
-			// this step for versions
272
-			$this->isVersion($path2) === false &&
273
-			$this->encryptionManager->isEnabled()) {
274
-			$source = $this->getFullPath($path1);
275
-			if (!$this->util->isExcluded($source)) {
276
-				$target = $this->getFullPath($path2);
277
-				if (isset($this->unencryptedSize[$source])) {
278
-					$this->unencryptedSize[$target] = $this->unencryptedSize[$source];
279
-				}
280
-				$this->keyStorage->renameKeys($source, $target);
281
-				$module = $this->getEncryptionModule($path2);
282
-				if ($module) {
283
-					$module->update($target, $this->uid, []);
284
-				}
285
-			}
286
-		}
287
-
288
-		return $result;
289
-	}
290
-
291
-	/**
292
-	 * see http://php.net/manual/en/function.rmdir.php
293
-	 *
294
-	 * @param string $path
295
-	 * @return bool
296
-	 */
297
-	public function rmdir($path) {
298
-		$result = $this->storage->rmdir($path);
299
-		$fullPath = $this->getFullPath($path);
300
-		if ($result &&
301
-			$this->util->isExcluded($fullPath) === false &&
302
-			$this->encryptionManager->isEnabled()
303
-		) {
304
-			$this->keyStorage->deleteAllFileKeys($fullPath);
305
-		}
306
-
307
-		return $result;
308
-	}
309
-
310
-	/**
311
-	 * check if a file can be read
312
-	 *
313
-	 * @param string $path
314
-	 * @return bool
315
-	 */
316
-	public function isReadable($path) {
317
-
318
-		$isReadable = true;
319
-
320
-		$metaData = $this->getMetaData($path);
321
-		if (
322
-			!$this->is_dir($path) &&
323
-			isset($metaData['encrypted']) &&
324
-			$metaData['encrypted'] === true
325
-		) {
326
-			$fullPath = $this->getFullPath($path);
327
-			$module = $this->getEncryptionModule($path);
328
-			$isReadable = $module->isReadable($fullPath, $this->uid);
329
-		}
330
-
331
-		return $this->storage->isReadable($path) && $isReadable;
332
-	}
333
-
334
-	/**
335
-	 * see http://php.net/manual/en/function.copy.php
336
-	 *
337
-	 * @param string $path1
338
-	 * @param string $path2
339
-	 * @return bool
340
-	 */
341
-	public function copy($path1, $path2) {
342
-
343
-		$source = $this->getFullPath($path1);
344
-
345
-		if ($this->util->isExcluded($source)) {
346
-			return $this->storage->copy($path1, $path2);
347
-		}
348
-
349
-		// need to stream copy file by file in case we copy between a encrypted
350
-		// and a unencrypted storage
351
-		$this->unlink($path2);
352
-		$result = $this->copyFromStorage($this, $path1, $path2);
353
-
354
-		return $result;
355
-	}
356
-
357
-	/**
358
-	 * see http://php.net/manual/en/function.fopen.php
359
-	 *
360
-	 * @param string $path
361
-	 * @param string $mode
362
-	 * @return resource|bool
363
-	 * @throws GenericEncryptionException
364
-	 * @throws ModuleDoesNotExistsException
365
-	 */
366
-	public function fopen($path, $mode) {
367
-
368
-		// check if the file is stored in the array cache, this means that we
369
-		// copy a file over to the versions folder, in this case we don't want to
370
-		// decrypt it
371
-		if ($this->arrayCache->hasKey('encryption_copy_version_' . $path)) {
372
-			$this->arrayCache->remove('encryption_copy_version_' . $path);
373
-			return $this->storage->fopen($path, $mode);
374
-		}
375
-
376
-		$encryptionEnabled = $this->encryptionManager->isEnabled();
377
-		$shouldEncrypt = false;
378
-		$encryptionModule = null;
379
-		$header = $this->getHeader($path);
380
-		$signed = (isset($header['signed']) && $header['signed'] === 'true') ? true : false;
381
-		$fullPath = $this->getFullPath($path);
382
-		$encryptionModuleId = $this->util->getEncryptionModuleId($header);
383
-
384
-		if ($this->util->isExcluded($fullPath) === false) {
385
-
386
-			$size = $unencryptedSize = 0;
387
-			$realFile = $this->util->stripPartialFileExtension($path);
388
-			$targetExists = $this->file_exists($realFile) || $this->file_exists($path);
389
-			$targetIsEncrypted = false;
390
-			if ($targetExists) {
391
-				// in case the file exists we require the explicit module as
392
-				// specified in the file header - otherwise we need to fail hard to
393
-				// prevent data loss on client side
394
-				if (!empty($encryptionModuleId)) {
395
-					$targetIsEncrypted = true;
396
-					$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
397
-				}
398
-
399
-				if ($this->file_exists($path)) {
400
-					$size = $this->storage->filesize($path);
401
-					$unencryptedSize = $this->filesize($path);
402
-				} else {
403
-					$size = $unencryptedSize = 0;
404
-				}
405
-			}
406
-
407
-			try {
408
-
409
-				if (
410
-					$mode === 'w'
411
-					|| $mode === 'w+'
412
-					|| $mode === 'wb'
413
-					|| $mode === 'wb+'
414
-				) {
415
-					// don't overwrite encrypted files if encryption is not enabled
416
-					if ($targetIsEncrypted && $encryptionEnabled === false) {
417
-						throw new GenericEncryptionException('Tried to access encrypted file but encryption is not enabled');
418
-					}
419
-					if ($encryptionEnabled) {
420
-						// if $encryptionModuleId is empty, the default module will be used
421
-						$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
422
-						$shouldEncrypt = $encryptionModule->shouldEncrypt($fullPath);
423
-						$signed = true;
424
-					}
425
-				} else {
426
-					$info = $this->getCache()->get($path);
427
-					// only get encryption module if we found one in the header
428
-					// or if file should be encrypted according to the file cache
429
-					if (!empty($encryptionModuleId)) {
430
-						$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
431
-						$shouldEncrypt = true;
432
-					} else if (empty($encryptionModuleId) && $info['encrypted'] === true) {
433
-						// we come from a old installation. No header and/or no module defined
434
-						// but the file is encrypted. In this case we need to use the
435
-						// OC_DEFAULT_MODULE to read the file
436
-						$encryptionModule = $this->encryptionManager->getEncryptionModule('OC_DEFAULT_MODULE');
437
-						$shouldEncrypt = true;
438
-						$targetIsEncrypted = true;
439
-					}
440
-				}
441
-			} catch (ModuleDoesNotExistsException $e) {
442
-				$this->logger->warning('Encryption module "' . $encryptionModuleId .
443
-					'" not found, file will be stored unencrypted (' . $e->getMessage() . ')');
444
-			}
445
-
446
-			// encryption disabled on write of new file and write to existing unencrypted file -> don't encrypt
447
-			if (!$encryptionEnabled || !$this->shouldEncrypt($path)) {
448
-				if (!$targetExists || !$targetIsEncrypted) {
449
-					$shouldEncrypt = false;
450
-				}
451
-			}
452
-
453
-			if ($shouldEncrypt === true && $encryptionModule !== null) {
454
-				$headerSize = $this->getHeaderSize($path);
455
-				$source = $this->storage->fopen($path, $mode);
456
-				if (!is_resource($source)) {
457
-					return false;
458
-				}
459
-				$handle = \OC\Files\Stream\Encryption::wrap($source, $path, $fullPath, $header,
460
-					$this->uid, $encryptionModule, $this->storage, $this, $this->util, $this->fileHelper, $mode,
461
-					$size, $unencryptedSize, $headerSize, $signed);
462
-				return $handle;
463
-			}
464
-
465
-		}
466
-
467
-		return $this->storage->fopen($path, $mode);
468
-	}
469
-
470
-
471
-	/**
472
-	 * perform some plausibility checks if the the unencrypted size is correct.
473
-	 * If not, we calculate the correct unencrypted size and return it
474
-	 *
475
-	 * @param string $path internal path relative to the storage root
476
-	 * @param int $unencryptedSize size of the unencrypted file
477
-	 *
478
-	 * @return int unencrypted size
479
-	 */
480
-	protected function verifyUnencryptedSize($path, $unencryptedSize) {
481
-
482
-		$size = $this->storage->filesize($path);
483
-		$result = $unencryptedSize;
484
-
485
-		if ($unencryptedSize < 0 ||
486
-			($size > 0 && $unencryptedSize === $size)
487
-		) {
488
-			// check if we already calculate the unencrypted size for the
489
-			// given path to avoid recursions
490
-			if (isset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]) === false) {
491
-				$this->fixUnencryptedSizeOf[$this->getFullPath($path)] = true;
492
-				try {
493
-					$result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
494
-				} catch (\Exception $e) {
495
-					$this->logger->error('Couldn\'t re-calculate unencrypted size for '. $path);
496
-					$this->logger->logException($e);
497
-				}
498
-				unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
499
-			}
500
-		}
501
-
502
-		return $result;
503
-	}
504
-
505
-	/**
506
-	 * calculate the unencrypted size
507
-	 *
508
-	 * @param string $path internal path relative to the storage root
509
-	 * @param int $size size of the physical file
510
-	 * @param int $unencryptedSize size of the unencrypted file
511
-	 *
512
-	 * @return int calculated unencrypted size
513
-	 */
514
-	protected function fixUnencryptedSize($path, $size, $unencryptedSize) {
515
-
516
-		$headerSize = $this->getHeaderSize($path);
517
-		$header = $this->getHeader($path);
518
-		$encryptionModule = $this->getEncryptionModule($path);
519
-
520
-		$stream = $this->storage->fopen($path, 'r');
521
-
522
-		// if we couldn't open the file we return the old unencrypted size
523
-		if (!is_resource($stream)) {
524
-			$this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
525
-			return $unencryptedSize;
526
-		}
527
-
528
-		$newUnencryptedSize = 0;
529
-		$size -= $headerSize;
530
-		$blockSize = $this->util->getBlockSize();
531
-
532
-		// if a header exists we skip it
533
-		if ($headerSize > 0) {
534
-			fread($stream, $headerSize);
535
-		}
536
-
537
-		// fast path, else the calculation for $lastChunkNr is bogus
538
-		if ($size === 0) {
539
-			return 0;
540
-		}
541
-
542
-		$signed = (isset($header['signed']) && $header['signed'] === 'true') ? true : false;
543
-		$unencryptedBlockSize = $encryptionModule->getUnencryptedBlockSize($signed);
544
-
545
-		// calculate last chunk nr
546
-		// next highest is end of chunks, one subtracted is last one
547
-		// we have to read the last chunk, we can't just calculate it (because of padding etc)
548
-
549
-		$lastChunkNr = ceil($size/ $blockSize)-1;
550
-		// calculate last chunk position
551
-		$lastChunkPos = ($lastChunkNr * $blockSize);
552
-		// try to fseek to the last chunk, if it fails we have to read the whole file
553
-		if (@fseek($stream, $lastChunkPos, SEEK_CUR) === 0) {
554
-			$newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
555
-		}
556
-
557
-		$lastChunkContentEncrypted='';
558
-		$count = $blockSize;
559
-
560
-		while ($count > 0) {
561
-			$data=fread($stream, $blockSize);
562
-			$count=strlen($data);
563
-			$lastChunkContentEncrypted .= $data;
564
-			if(strlen($lastChunkContentEncrypted) > $blockSize) {
565
-				$newUnencryptedSize += $unencryptedBlockSize;
566
-				$lastChunkContentEncrypted=substr($lastChunkContentEncrypted, $blockSize);
567
-			}
568
-		}
569
-
570
-		fclose($stream);
571
-
572
-		// we have to decrypt the last chunk to get it actual size
573
-		$encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
574
-		$decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
575
-		$decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
576
-
577
-		// calc the real file size with the size of the last chunk
578
-		$newUnencryptedSize += strlen($decryptedLastChunk);
579
-
580
-		$this->updateUnencryptedSize($this->getFullPath($path), $newUnencryptedSize);
581
-
582
-		// write to cache if applicable
583
-		$cache = $this->storage->getCache();
584
-		if ($cache) {
585
-			$entry = $cache->get($path);
586
-			$cache->update($entry['fileid'], ['size' => $newUnencryptedSize]);
587
-		}
588
-
589
-		return $newUnencryptedSize;
590
-	}
591
-
592
-	/**
593
-	 * @param Storage $sourceStorage
594
-	 * @param string $sourceInternalPath
595
-	 * @param string $targetInternalPath
596
-	 * @param bool $preserveMtime
597
-	 * @return bool
598
-	 */
599
-	public function moveFromStorage(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = true) {
600
-		if ($sourceStorage === $this) {
601
-			return $this->rename($sourceInternalPath, $targetInternalPath);
602
-		}
603
-
604
-		// TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
605
-		// - call $this->storage->moveFromStorage() instead of $this->copyBetweenStorage
606
-		// - copy the file cache update from  $this->copyBetweenStorage to this method
607
-		// - copy the copyKeys() call from  $this->copyBetweenStorage to this method
608
-		// - remove $this->copyBetweenStorage
609
-
610
-		if (!$sourceStorage->isDeletable($sourceInternalPath)) {
611
-			return false;
612
-		}
613
-
614
-		$result = $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, true);
615
-		if ($result) {
616
-			if ($sourceStorage->is_dir($sourceInternalPath)) {
617
-				$result &= $sourceStorage->rmdir($sourceInternalPath);
618
-			} else {
619
-				$result &= $sourceStorage->unlink($sourceInternalPath);
620
-			}
621
-		}
622
-		return $result;
623
-	}
624
-
625
-
626
-	/**
627
-	 * @param Storage $sourceStorage
628
-	 * @param string $sourceInternalPath
629
-	 * @param string $targetInternalPath
630
-	 * @param bool $preserveMtime
631
-	 * @param bool $isRename
632
-	 * @return bool
633
-	 */
634
-	public function copyFromStorage(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false, $isRename = false) {
635
-
636
-		// TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
637
-		// - call $this->storage->copyFromStorage() instead of $this->copyBetweenStorage
638
-		// - copy the file cache update from  $this->copyBetweenStorage to this method
639
-		// - copy the copyKeys() call from  $this->copyBetweenStorage to this method
640
-		// - remove $this->copyBetweenStorage
641
-
642
-		return $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename);
643
-	}
644
-
645
-	/**
646
-	 * Update the encrypted cache version in the database
647
-	 *
648
-	 * @param Storage $sourceStorage
649
-	 * @param string $sourceInternalPath
650
-	 * @param string $targetInternalPath
651
-	 * @param bool $isRename
652
-	 */
653
-	private function updateEncryptedVersion(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename) {
654
-		$isEncrypted = $this->encryptionManager->isEnabled() && $this->shouldEncrypt($targetInternalPath) ? 1 : 0;
655
-		$cacheInformation = [
656
-			'encrypted' => (bool)$isEncrypted,
657
-		];
658
-		if($isEncrypted === 1) {
659
-			$encryptedVersion = $sourceStorage->getCache()->get($sourceInternalPath)['encryptedVersion'];
660
-
661
-			// In case of a move operation from an unencrypted to an encrypted
662
-			// storage the old encrypted version would stay with "0" while the
663
-			// correct value would be "1". Thus we manually set the value to "1"
664
-			// for those cases.
665
-			// See also https://github.com/owncloud/core/issues/23078
666
-			if($encryptedVersion === 0) {
667
-				$encryptedVersion = 1;
668
-			}
669
-
670
-			$cacheInformation['encryptedVersion'] = $encryptedVersion;
671
-		}
672
-
673
-		// in case of a rename we need to manipulate the source cache because
674
-		// this information will be kept for the new target
675
-		if ($isRename) {
676
-			$sourceStorage->getCache()->put($sourceInternalPath, $cacheInformation);
677
-		} else {
678
-			$this->getCache()->put($targetInternalPath, $cacheInformation);
679
-		}
680
-	}
681
-
682
-	/**
683
-	 * copy file between two storages
684
-	 *
685
-	 * @param Storage $sourceStorage
686
-	 * @param string $sourceInternalPath
687
-	 * @param string $targetInternalPath
688
-	 * @param bool $preserveMtime
689
-	 * @param bool $isRename
690
-	 * @return bool
691
-	 * @throws \Exception
692
-	 */
693
-	private function copyBetweenStorage(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename) {
694
-
695
-		// for versions we have nothing to do, because versions should always use the
696
-		// key from the original file. Just create a 1:1 copy and done
697
-		if ($this->isVersion($targetInternalPath) ||
698
-			$this->isVersion($sourceInternalPath)) {
699
-			// remember that we try to create a version so that we can detect it during
700
-			// fopen($sourceInternalPath) and by-pass the encryption in order to
701
-			// create a 1:1 copy of the file
702
-			$this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
703
-			$result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
704
-			$this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
705
-			if ($result) {
706
-				$info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
707
-				// make sure that we update the unencrypted size for the version
708
-				if (isset($info['encrypted']) && $info['encrypted'] === true) {
709
-					$this->updateUnencryptedSize(
710
-						$this->getFullPath($targetInternalPath),
711
-						$info['size']
712
-					);
713
-				}
714
-				$this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename);
715
-			}
716
-			return $result;
717
-		}
718
-
719
-		// first copy the keys that we reuse the existing file key on the target location
720
-		// and don't create a new one which would break versions for example.
721
-		$mount = $this->mountManager->findByStorageId($sourceStorage->getId());
722
-		if (count($mount) === 1) {
723
-			$mountPoint = $mount[0]->getMountPoint();
724
-			$source = $mountPoint . '/' . $sourceInternalPath;
725
-			$target = $this->getFullPath($targetInternalPath);
726
-			$this->copyKeys($source, $target);
727
-		} else {
728
-			$this->logger->error('Could not find mount point, can\'t keep encryption keys');
729
-		}
730
-
731
-		if ($sourceStorage->is_dir($sourceInternalPath)) {
732
-			$dh = $sourceStorage->opendir($sourceInternalPath);
733
-			$result = $this->mkdir($targetInternalPath);
734
-			if (is_resource($dh)) {
735
-				while ($result and ($file = readdir($dh)) !== false) {
736
-					if (!Filesystem::isIgnoredDir($file)) {
737
-						$result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, false, $isRename);
738
-					}
739
-				}
740
-			}
741
-		} else {
742
-			try {
743
-				$source = $sourceStorage->fopen($sourceInternalPath, 'r');
744
-				$target = $this->fopen($targetInternalPath, 'w');
745
-				list(, $result) = \OC_Helper::streamCopy($source, $target);
746
-				fclose($source);
747
-				fclose($target);
748
-			} catch (\Exception $e) {
749
-				fclose($source);
750
-				fclose($target);
751
-				throw $e;
752
-			}
753
-			if($result) {
754
-				if ($preserveMtime) {
755
-					$this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
756
-				}
757
-				$this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename);
758
-			} else {
759
-				// delete partially written target file
760
-				$this->unlink($targetInternalPath);
761
-				// delete cache entry that was created by fopen
762
-				$this->getCache()->remove($targetInternalPath);
763
-			}
764
-		}
765
-		return (bool)$result;
766
-
767
-	}
768
-
769
-	/**
770
-	 * get the path to a local version of the file.
771
-	 * The local version of the file can be temporary and doesn't have to be persistent across requests
772
-	 *
773
-	 * @param string $path
774
-	 * @return string
775
-	 */
776
-	public function getLocalFile($path) {
777
-		if ($this->encryptionManager->isEnabled()) {
778
-			$cachedFile = $this->getCachedFile($path);
779
-			if (is_string($cachedFile)) {
780
-				return $cachedFile;
781
-			}
782
-		}
783
-		return $this->storage->getLocalFile($path);
784
-	}
785
-
786
-	/**
787
-	 * Returns the wrapped storage's value for isLocal()
788
-	 *
789
-	 * @return bool wrapped storage's isLocal() value
790
-	 */
791
-	public function isLocal() {
792
-		if ($this->encryptionManager->isEnabled()) {
793
-			return false;
794
-		}
795
-		return $this->storage->isLocal();
796
-	}
797
-
798
-	/**
799
-	 * see http://php.net/manual/en/function.stat.php
800
-	 * only the following keys are required in the result: size and mtime
801
-	 *
802
-	 * @param string $path
803
-	 * @return array
804
-	 */
805
-	public function stat($path) {
806
-		$stat = $this->storage->stat($path);
807
-		$fileSize = $this->filesize($path);
808
-		$stat['size'] = $fileSize;
809
-		$stat[7] = $fileSize;
810
-		return $stat;
811
-	}
812
-
813
-	/**
814
-	 * see http://php.net/manual/en/function.hash.php
815
-	 *
816
-	 * @param string $type
817
-	 * @param string $path
818
-	 * @param bool $raw
819
-	 * @return string
820
-	 */
821
-	public function hash($type, $path, $raw = false) {
822
-		$fh = $this->fopen($path, 'rb');
823
-		$ctx = hash_init($type);
824
-		hash_update_stream($ctx, $fh);
825
-		fclose($fh);
826
-		return hash_final($ctx, $raw);
827
-	}
828
-
829
-	/**
830
-	 * return full path, including mount point
831
-	 *
832
-	 * @param string $path relative to mount point
833
-	 * @return string full path including mount point
834
-	 */
835
-	protected function getFullPath($path) {
836
-		return Filesystem::normalizePath($this->mountPoint . '/' . $path);
837
-	}
838
-
839
-	/**
840
-	 * read first block of encrypted file, typically this will contain the
841
-	 * encryption header
842
-	 *
843
-	 * @param string $path
844
-	 * @return string
845
-	 */
846
-	protected function readFirstBlock($path) {
847
-		$firstBlock = '';
848
-		if ($this->storage->file_exists($path)) {
849
-			$handle = $this->storage->fopen($path, 'r');
850
-			$firstBlock = fread($handle, $this->util->getHeaderSize());
851
-			fclose($handle);
852
-		}
853
-		return $firstBlock;
854
-	}
855
-
856
-	/**
857
-	 * return header size of given file
858
-	 *
859
-	 * @param string $path
860
-	 * @return int
861
-	 */
862
-	protected function getHeaderSize($path) {
863
-		$headerSize = 0;
864
-		$realFile = $this->util->stripPartialFileExtension($path);
865
-		if ($this->storage->file_exists($realFile)) {
866
-			$path = $realFile;
867
-		}
868
-		$firstBlock = $this->readFirstBlock($path);
869
-
870
-		if (substr($firstBlock, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
871
-			$headerSize = $this->util->getHeaderSize();
872
-		}
873
-
874
-		return $headerSize;
875
-	}
876
-
877
-	/**
878
-	 * parse raw header to array
879
-	 *
880
-	 * @param string $rawHeader
881
-	 * @return array
882
-	 */
883
-	protected function parseRawHeader($rawHeader) {
884
-		$result = array();
885
-		if (substr($rawHeader, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
886
-			$header = $rawHeader;
887
-			$endAt = strpos($header, Util::HEADER_END);
888
-			if ($endAt !== false) {
889
-				$header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
890
-
891
-				// +1 to not start with an ':' which would result in empty element at the beginning
892
-				$exploded = explode(':', substr($header, strlen(Util::HEADER_START)+1));
893
-
894
-				$element = array_shift($exploded);
895
-				while ($element !== Util::HEADER_END) {
896
-					$result[$element] = array_shift($exploded);
897
-					$element = array_shift($exploded);
898
-				}
899
-			}
900
-		}
901
-
902
-		return $result;
903
-	}
904
-
905
-	/**
906
-	 * read header from file
907
-	 *
908
-	 * @param string $path
909
-	 * @return array
910
-	 */
911
-	protected function getHeader($path) {
912
-		$realFile = $this->util->stripPartialFileExtension($path);
913
-		if ($this->storage->file_exists($realFile)) {
914
-			$path = $realFile;
915
-		}
916
-
917
-		$firstBlock = $this->readFirstBlock($path);
918
-		$result = $this->parseRawHeader($firstBlock);
919
-
920
-		// if the header doesn't contain a encryption module we check if it is a
921
-		// legacy file. If true, we add the default encryption module
922
-		if (!isset($result[Util::HEADER_ENCRYPTION_MODULE_KEY])) {
923
-			if (!empty($result)) {
924
-				$result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
925
-			} else {
926
-				// if the header was empty we have to check first if it is a encrypted file at all
927
-				$info = $this->getCache()->get($path);
928
-				if (isset($info['encrypted']) && $info['encrypted'] === true) {
929
-					$result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
930
-				}
931
-			}
932
-		}
933
-
934
-		return $result;
935
-	}
936
-
937
-	/**
938
-	 * read encryption module needed to read/write the file located at $path
939
-	 *
940
-	 * @param string $path
941
-	 * @return null|\OCP\Encryption\IEncryptionModule
942
-	 * @throws ModuleDoesNotExistsException
943
-	 * @throws \Exception
944
-	 */
945
-	protected function getEncryptionModule($path) {
946
-		$encryptionModule = null;
947
-		$header = $this->getHeader($path);
948
-		$encryptionModuleId = $this->util->getEncryptionModuleId($header);
949
-		if (!empty($encryptionModuleId)) {
950
-			try {
951
-				$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
952
-			} catch (ModuleDoesNotExistsException $e) {
953
-				$this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
954
-				throw $e;
955
-			}
956
-		}
957
-
958
-		return $encryptionModule;
959
-	}
960
-
961
-	/**
962
-	 * @param string $path
963
-	 * @param int $unencryptedSize
964
-	 */
965
-	public function updateUnencryptedSize($path, $unencryptedSize) {
966
-		$this->unencryptedSize[$path] = $unencryptedSize;
967
-	}
968
-
969
-	/**
970
-	 * copy keys to new location
971
-	 *
972
-	 * @param string $source path relative to data/
973
-	 * @param string $target path relative to data/
974
-	 * @return bool
975
-	 */
976
-	protected function copyKeys($source, $target) {
977
-		if (!$this->util->isExcluded($source)) {
978
-			return $this->keyStorage->copyKeys($source, $target);
979
-		}
980
-
981
-		return false;
982
-	}
983
-
984
-	/**
985
-	 * check if path points to a files version
986
-	 *
987
-	 * @param $path
988
-	 * @return bool
989
-	 */
990
-	protected function isVersion($path) {
991
-		$normalized = Filesystem::normalizePath($path);
992
-		return substr($normalized, 0, strlen('/files_versions/')) === '/files_versions/';
993
-	}
994
-
995
-	/**
996
-	 * check if the given storage should be encrypted or not
997
-	 *
998
-	 * @param $path
999
-	 * @return bool
1000
-	 */
1001
-	protected function shouldEncrypt($path) {
1002
-		$fullPath = $this->getFullPath($path);
1003
-		$mountPointConfig = $this->mount->getOption('encrypt', true);
1004
-		if ($mountPointConfig === false) {
1005
-			return false;
1006
-		}
1007
-
1008
-		try {
1009
-			$encryptionModule = $this->getEncryptionModule($fullPath);
1010
-		} catch (ModuleDoesNotExistsException $e) {
1011
-			return false;
1012
-		}
1013
-
1014
-		if ($encryptionModule === null) {
1015
-			$encryptionModule = $this->encryptionManager->getEncryptionModule();
1016
-		}
1017
-
1018
-		return $encryptionModule->shouldEncrypt($fullPath);
1019
-
1020
-	}
49
+    use LocalTempFileTrait;
50
+
51
+    /** @var string */
52
+    private $mountPoint;
53
+
54
+    /** @var \OC\Encryption\Util */
55
+    private $util;
56
+
57
+    /** @var \OCP\Encryption\IManager */
58
+    private $encryptionManager;
59
+
60
+    /** @var \OCP\ILogger */
61
+    private $logger;
62
+
63
+    /** @var string */
64
+    private $uid;
65
+
66
+    /** @var array */
67
+    protected $unencryptedSize;
68
+
69
+    /** @var \OCP\Encryption\IFile */
70
+    private $fileHelper;
71
+
72
+    /** @var IMountPoint */
73
+    private $mount;
74
+
75
+    /** @var IStorage */
76
+    private $keyStorage;
77
+
78
+    /** @var Update */
79
+    private $update;
80
+
81
+    /** @var Manager */
82
+    private $mountManager;
83
+
84
+    /** @var array remember for which path we execute the repair step to avoid recursions */
85
+    private $fixUnencryptedSizeOf = array();
86
+
87
+    /** @var  ArrayCache */
88
+    private $arrayCache;
89
+
90
+    /**
91
+     * @param array $parameters
92
+     * @param IManager $encryptionManager
93
+     * @param Util $util
94
+     * @param ILogger $logger
95
+     * @param IFile $fileHelper
96
+     * @param string $uid
97
+     * @param IStorage $keyStorage
98
+     * @param Update $update
99
+     * @param Manager $mountManager
100
+     * @param ArrayCache $arrayCache
101
+     */
102
+    public function __construct(
103
+            $parameters,
104
+            IManager $encryptionManager = null,
105
+            Util $util = null,
106
+            ILogger $logger = null,
107
+            IFile $fileHelper = null,
108
+            $uid = null,
109
+            IStorage $keyStorage = null,
110
+            Update $update = null,
111
+            Manager $mountManager = null,
112
+            ArrayCache $arrayCache = null
113
+        ) {
114
+
115
+        $this->mountPoint = $parameters['mountPoint'];
116
+        $this->mount = $parameters['mount'];
117
+        $this->encryptionManager = $encryptionManager;
118
+        $this->util = $util;
119
+        $this->logger = $logger;
120
+        $this->uid = $uid;
121
+        $this->fileHelper = $fileHelper;
122
+        $this->keyStorage = $keyStorage;
123
+        $this->unencryptedSize = array();
124
+        $this->update = $update;
125
+        $this->mountManager = $mountManager;
126
+        $this->arrayCache = $arrayCache;
127
+        parent::__construct($parameters);
128
+    }
129
+
130
+    /**
131
+     * see http://php.net/manual/en/function.filesize.php
132
+     * The result for filesize when called on a folder is required to be 0
133
+     *
134
+     * @param string $path
135
+     * @return int
136
+     */
137
+    public function filesize($path) {
138
+        $fullPath = $this->getFullPath($path);
139
+
140
+        /** @var CacheEntry $info */
141
+        $info = $this->getCache()->get($path);
142
+        if (isset($this->unencryptedSize[$fullPath])) {
143
+            $size = $this->unencryptedSize[$fullPath];
144
+            // update file cache
145
+            if ($info instanceof ICacheEntry) {
146
+                $info = $info->getData();
147
+                $info['encrypted'] = $info['encryptedVersion'];
148
+            } else {
149
+                if (!is_array($info)) {
150
+                    $info = [];
151
+                }
152
+                $info['encrypted'] = true;
153
+            }
154
+
155
+            $info['size'] = $size;
156
+            $this->getCache()->put($path, $info);
157
+
158
+            return $size;
159
+        }
160
+
161
+        if (isset($info['fileid']) && $info['encrypted']) {
162
+            return $this->verifyUnencryptedSize($path, $info['size']);
163
+        }
164
+
165
+        return $this->storage->filesize($path);
166
+    }
167
+
168
+    /**
169
+     * @param string $path
170
+     * @return array
171
+     */
172
+    public function getMetaData($path) {
173
+        $data = $this->storage->getMetaData($path);
174
+        if (is_null($data)) {
175
+            return null;
176
+        }
177
+        $fullPath = $this->getFullPath($path);
178
+        $info = $this->getCache()->get($path);
179
+
180
+        if (isset($this->unencryptedSize[$fullPath])) {
181
+            $data['encrypted'] = true;
182
+            $data['size'] = $this->unencryptedSize[$fullPath];
183
+        } else {
184
+            if (isset($info['fileid']) && $info['encrypted']) {
185
+                $data['size'] = $this->verifyUnencryptedSize($path, $info['size']);
186
+                $data['encrypted'] = true;
187
+            }
188
+        }
189
+
190
+        if (isset($info['encryptedVersion']) && $info['encryptedVersion'] > 1) {
191
+            $data['encryptedVersion'] = $info['encryptedVersion'];
192
+        }
193
+
194
+        return $data;
195
+    }
196
+
197
+    /**
198
+     * see http://php.net/manual/en/function.file_get_contents.php
199
+     *
200
+     * @param string $path
201
+     * @return string
202
+     */
203
+    public function file_get_contents($path) {
204
+
205
+        $encryptionModule = $this->getEncryptionModule($path);
206
+
207
+        if ($encryptionModule) {
208
+            $handle = $this->fopen($path, "r");
209
+            if (!$handle) {
210
+                return false;
211
+            }
212
+            $data = stream_get_contents($handle);
213
+            fclose($handle);
214
+            return $data;
215
+        }
216
+        return $this->storage->file_get_contents($path);
217
+    }
218
+
219
+    /**
220
+     * see http://php.net/manual/en/function.file_put_contents.php
221
+     *
222
+     * @param string $path
223
+     * @param string $data
224
+     * @return bool
225
+     */
226
+    public function file_put_contents($path, $data) {
227
+        // file put content will always be translated to a stream write
228
+        $handle = $this->fopen($path, 'w');
229
+        if (is_resource($handle)) {
230
+            $written = fwrite($handle, $data);
231
+            fclose($handle);
232
+            return $written;
233
+        }
234
+
235
+        return false;
236
+    }
237
+
238
+    /**
239
+     * see http://php.net/manual/en/function.unlink.php
240
+     *
241
+     * @param string $path
242
+     * @return bool
243
+     */
244
+    public function unlink($path) {
245
+        $fullPath = $this->getFullPath($path);
246
+        if ($this->util->isExcluded($fullPath)) {
247
+            return $this->storage->unlink($path);
248
+        }
249
+
250
+        $encryptionModule = $this->getEncryptionModule($path);
251
+        if ($encryptionModule) {
252
+            $this->keyStorage->deleteAllFileKeys($this->getFullPath($path));
253
+        }
254
+
255
+        return $this->storage->unlink($path);
256
+    }
257
+
258
+    /**
259
+     * see http://php.net/manual/en/function.rename.php
260
+     *
261
+     * @param string $path1
262
+     * @param string $path2
263
+     * @return bool
264
+     */
265
+    public function rename($path1, $path2) {
266
+
267
+        $result = $this->storage->rename($path1, $path2);
268
+
269
+        if ($result &&
270
+            // versions always use the keys from the original file, so we can skip
271
+            // this step for versions
272
+            $this->isVersion($path2) === false &&
273
+            $this->encryptionManager->isEnabled()) {
274
+            $source = $this->getFullPath($path1);
275
+            if (!$this->util->isExcluded($source)) {
276
+                $target = $this->getFullPath($path2);
277
+                if (isset($this->unencryptedSize[$source])) {
278
+                    $this->unencryptedSize[$target] = $this->unencryptedSize[$source];
279
+                }
280
+                $this->keyStorage->renameKeys($source, $target);
281
+                $module = $this->getEncryptionModule($path2);
282
+                if ($module) {
283
+                    $module->update($target, $this->uid, []);
284
+                }
285
+            }
286
+        }
287
+
288
+        return $result;
289
+    }
290
+
291
+    /**
292
+     * see http://php.net/manual/en/function.rmdir.php
293
+     *
294
+     * @param string $path
295
+     * @return bool
296
+     */
297
+    public function rmdir($path) {
298
+        $result = $this->storage->rmdir($path);
299
+        $fullPath = $this->getFullPath($path);
300
+        if ($result &&
301
+            $this->util->isExcluded($fullPath) === false &&
302
+            $this->encryptionManager->isEnabled()
303
+        ) {
304
+            $this->keyStorage->deleteAllFileKeys($fullPath);
305
+        }
306
+
307
+        return $result;
308
+    }
309
+
310
+    /**
311
+     * check if a file can be read
312
+     *
313
+     * @param string $path
314
+     * @return bool
315
+     */
316
+    public function isReadable($path) {
317
+
318
+        $isReadable = true;
319
+
320
+        $metaData = $this->getMetaData($path);
321
+        if (
322
+            !$this->is_dir($path) &&
323
+            isset($metaData['encrypted']) &&
324
+            $metaData['encrypted'] === true
325
+        ) {
326
+            $fullPath = $this->getFullPath($path);
327
+            $module = $this->getEncryptionModule($path);
328
+            $isReadable = $module->isReadable($fullPath, $this->uid);
329
+        }
330
+
331
+        return $this->storage->isReadable($path) && $isReadable;
332
+    }
333
+
334
+    /**
335
+     * see http://php.net/manual/en/function.copy.php
336
+     *
337
+     * @param string $path1
338
+     * @param string $path2
339
+     * @return bool
340
+     */
341
+    public function copy($path1, $path2) {
342
+
343
+        $source = $this->getFullPath($path1);
344
+
345
+        if ($this->util->isExcluded($source)) {
346
+            return $this->storage->copy($path1, $path2);
347
+        }
348
+
349
+        // need to stream copy file by file in case we copy between a encrypted
350
+        // and a unencrypted storage
351
+        $this->unlink($path2);
352
+        $result = $this->copyFromStorage($this, $path1, $path2);
353
+
354
+        return $result;
355
+    }
356
+
357
+    /**
358
+     * see http://php.net/manual/en/function.fopen.php
359
+     *
360
+     * @param string $path
361
+     * @param string $mode
362
+     * @return resource|bool
363
+     * @throws GenericEncryptionException
364
+     * @throws ModuleDoesNotExistsException
365
+     */
366
+    public function fopen($path, $mode) {
367
+
368
+        // check if the file is stored in the array cache, this means that we
369
+        // copy a file over to the versions folder, in this case we don't want to
370
+        // decrypt it
371
+        if ($this->arrayCache->hasKey('encryption_copy_version_' . $path)) {
372
+            $this->arrayCache->remove('encryption_copy_version_' . $path);
373
+            return $this->storage->fopen($path, $mode);
374
+        }
375
+
376
+        $encryptionEnabled = $this->encryptionManager->isEnabled();
377
+        $shouldEncrypt = false;
378
+        $encryptionModule = null;
379
+        $header = $this->getHeader($path);
380
+        $signed = (isset($header['signed']) && $header['signed'] === 'true') ? true : false;
381
+        $fullPath = $this->getFullPath($path);
382
+        $encryptionModuleId = $this->util->getEncryptionModuleId($header);
383
+
384
+        if ($this->util->isExcluded($fullPath) === false) {
385
+
386
+            $size = $unencryptedSize = 0;
387
+            $realFile = $this->util->stripPartialFileExtension($path);
388
+            $targetExists = $this->file_exists($realFile) || $this->file_exists($path);
389
+            $targetIsEncrypted = false;
390
+            if ($targetExists) {
391
+                // in case the file exists we require the explicit module as
392
+                // specified in the file header - otherwise we need to fail hard to
393
+                // prevent data loss on client side
394
+                if (!empty($encryptionModuleId)) {
395
+                    $targetIsEncrypted = true;
396
+                    $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
397
+                }
398
+
399
+                if ($this->file_exists($path)) {
400
+                    $size = $this->storage->filesize($path);
401
+                    $unencryptedSize = $this->filesize($path);
402
+                } else {
403
+                    $size = $unencryptedSize = 0;
404
+                }
405
+            }
406
+
407
+            try {
408
+
409
+                if (
410
+                    $mode === 'w'
411
+                    || $mode === 'w+'
412
+                    || $mode === 'wb'
413
+                    || $mode === 'wb+'
414
+                ) {
415
+                    // don't overwrite encrypted files if encryption is not enabled
416
+                    if ($targetIsEncrypted && $encryptionEnabled === false) {
417
+                        throw new GenericEncryptionException('Tried to access encrypted file but encryption is not enabled');
418
+                    }
419
+                    if ($encryptionEnabled) {
420
+                        // if $encryptionModuleId is empty, the default module will be used
421
+                        $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
422
+                        $shouldEncrypt = $encryptionModule->shouldEncrypt($fullPath);
423
+                        $signed = true;
424
+                    }
425
+                } else {
426
+                    $info = $this->getCache()->get($path);
427
+                    // only get encryption module if we found one in the header
428
+                    // or if file should be encrypted according to the file cache
429
+                    if (!empty($encryptionModuleId)) {
430
+                        $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
431
+                        $shouldEncrypt = true;
432
+                    } else if (empty($encryptionModuleId) && $info['encrypted'] === true) {
433
+                        // we come from a old installation. No header and/or no module defined
434
+                        // but the file is encrypted. In this case we need to use the
435
+                        // OC_DEFAULT_MODULE to read the file
436
+                        $encryptionModule = $this->encryptionManager->getEncryptionModule('OC_DEFAULT_MODULE');
437
+                        $shouldEncrypt = true;
438
+                        $targetIsEncrypted = true;
439
+                    }
440
+                }
441
+            } catch (ModuleDoesNotExistsException $e) {
442
+                $this->logger->warning('Encryption module "' . $encryptionModuleId .
443
+                    '" not found, file will be stored unencrypted (' . $e->getMessage() . ')');
444
+            }
445
+
446
+            // encryption disabled on write of new file and write to existing unencrypted file -> don't encrypt
447
+            if (!$encryptionEnabled || !$this->shouldEncrypt($path)) {
448
+                if (!$targetExists || !$targetIsEncrypted) {
449
+                    $shouldEncrypt = false;
450
+                }
451
+            }
452
+
453
+            if ($shouldEncrypt === true && $encryptionModule !== null) {
454
+                $headerSize = $this->getHeaderSize($path);
455
+                $source = $this->storage->fopen($path, $mode);
456
+                if (!is_resource($source)) {
457
+                    return false;
458
+                }
459
+                $handle = \OC\Files\Stream\Encryption::wrap($source, $path, $fullPath, $header,
460
+                    $this->uid, $encryptionModule, $this->storage, $this, $this->util, $this->fileHelper, $mode,
461
+                    $size, $unencryptedSize, $headerSize, $signed);
462
+                return $handle;
463
+            }
464
+
465
+        }
466
+
467
+        return $this->storage->fopen($path, $mode);
468
+    }
469
+
470
+
471
+    /**
472
+     * perform some plausibility checks if the the unencrypted size is correct.
473
+     * If not, we calculate the correct unencrypted size and return it
474
+     *
475
+     * @param string $path internal path relative to the storage root
476
+     * @param int $unencryptedSize size of the unencrypted file
477
+     *
478
+     * @return int unencrypted size
479
+     */
480
+    protected function verifyUnencryptedSize($path, $unencryptedSize) {
481
+
482
+        $size = $this->storage->filesize($path);
483
+        $result = $unencryptedSize;
484
+
485
+        if ($unencryptedSize < 0 ||
486
+            ($size > 0 && $unencryptedSize === $size)
487
+        ) {
488
+            // check if we already calculate the unencrypted size for the
489
+            // given path to avoid recursions
490
+            if (isset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]) === false) {
491
+                $this->fixUnencryptedSizeOf[$this->getFullPath($path)] = true;
492
+                try {
493
+                    $result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
494
+                } catch (\Exception $e) {
495
+                    $this->logger->error('Couldn\'t re-calculate unencrypted size for '. $path);
496
+                    $this->logger->logException($e);
497
+                }
498
+                unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
499
+            }
500
+        }
501
+
502
+        return $result;
503
+    }
504
+
505
+    /**
506
+     * calculate the unencrypted size
507
+     *
508
+     * @param string $path internal path relative to the storage root
509
+     * @param int $size size of the physical file
510
+     * @param int $unencryptedSize size of the unencrypted file
511
+     *
512
+     * @return int calculated unencrypted size
513
+     */
514
+    protected function fixUnencryptedSize($path, $size, $unencryptedSize) {
515
+
516
+        $headerSize = $this->getHeaderSize($path);
517
+        $header = $this->getHeader($path);
518
+        $encryptionModule = $this->getEncryptionModule($path);
519
+
520
+        $stream = $this->storage->fopen($path, 'r');
521
+
522
+        // if we couldn't open the file we return the old unencrypted size
523
+        if (!is_resource($stream)) {
524
+            $this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
525
+            return $unencryptedSize;
526
+        }
527
+
528
+        $newUnencryptedSize = 0;
529
+        $size -= $headerSize;
530
+        $blockSize = $this->util->getBlockSize();
531
+
532
+        // if a header exists we skip it
533
+        if ($headerSize > 0) {
534
+            fread($stream, $headerSize);
535
+        }
536
+
537
+        // fast path, else the calculation for $lastChunkNr is bogus
538
+        if ($size === 0) {
539
+            return 0;
540
+        }
541
+
542
+        $signed = (isset($header['signed']) && $header['signed'] === 'true') ? true : false;
543
+        $unencryptedBlockSize = $encryptionModule->getUnencryptedBlockSize($signed);
544
+
545
+        // calculate last chunk nr
546
+        // next highest is end of chunks, one subtracted is last one
547
+        // we have to read the last chunk, we can't just calculate it (because of padding etc)
548
+
549
+        $lastChunkNr = ceil($size/ $blockSize)-1;
550
+        // calculate last chunk position
551
+        $lastChunkPos = ($lastChunkNr * $blockSize);
552
+        // try to fseek to the last chunk, if it fails we have to read the whole file
553
+        if (@fseek($stream, $lastChunkPos, SEEK_CUR) === 0) {
554
+            $newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
555
+        }
556
+
557
+        $lastChunkContentEncrypted='';
558
+        $count = $blockSize;
559
+
560
+        while ($count > 0) {
561
+            $data=fread($stream, $blockSize);
562
+            $count=strlen($data);
563
+            $lastChunkContentEncrypted .= $data;
564
+            if(strlen($lastChunkContentEncrypted) > $blockSize) {
565
+                $newUnencryptedSize += $unencryptedBlockSize;
566
+                $lastChunkContentEncrypted=substr($lastChunkContentEncrypted, $blockSize);
567
+            }
568
+        }
569
+
570
+        fclose($stream);
571
+
572
+        // we have to decrypt the last chunk to get it actual size
573
+        $encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
574
+        $decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
575
+        $decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
576
+
577
+        // calc the real file size with the size of the last chunk
578
+        $newUnencryptedSize += strlen($decryptedLastChunk);
579
+
580
+        $this->updateUnencryptedSize($this->getFullPath($path), $newUnencryptedSize);
581
+
582
+        // write to cache if applicable
583
+        $cache = $this->storage->getCache();
584
+        if ($cache) {
585
+            $entry = $cache->get($path);
586
+            $cache->update($entry['fileid'], ['size' => $newUnencryptedSize]);
587
+        }
588
+
589
+        return $newUnencryptedSize;
590
+    }
591
+
592
+    /**
593
+     * @param Storage $sourceStorage
594
+     * @param string $sourceInternalPath
595
+     * @param string $targetInternalPath
596
+     * @param bool $preserveMtime
597
+     * @return bool
598
+     */
599
+    public function moveFromStorage(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = true) {
600
+        if ($sourceStorage === $this) {
601
+            return $this->rename($sourceInternalPath, $targetInternalPath);
602
+        }
603
+
604
+        // TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
605
+        // - call $this->storage->moveFromStorage() instead of $this->copyBetweenStorage
606
+        // - copy the file cache update from  $this->copyBetweenStorage to this method
607
+        // - copy the copyKeys() call from  $this->copyBetweenStorage to this method
608
+        // - remove $this->copyBetweenStorage
609
+
610
+        if (!$sourceStorage->isDeletable($sourceInternalPath)) {
611
+            return false;
612
+        }
613
+
614
+        $result = $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, true);
615
+        if ($result) {
616
+            if ($sourceStorage->is_dir($sourceInternalPath)) {
617
+                $result &= $sourceStorage->rmdir($sourceInternalPath);
618
+            } else {
619
+                $result &= $sourceStorage->unlink($sourceInternalPath);
620
+            }
621
+        }
622
+        return $result;
623
+    }
624
+
625
+
626
+    /**
627
+     * @param Storage $sourceStorage
628
+     * @param string $sourceInternalPath
629
+     * @param string $targetInternalPath
630
+     * @param bool $preserveMtime
631
+     * @param bool $isRename
632
+     * @return bool
633
+     */
634
+    public function copyFromStorage(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false, $isRename = false) {
635
+
636
+        // TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
637
+        // - call $this->storage->copyFromStorage() instead of $this->copyBetweenStorage
638
+        // - copy the file cache update from  $this->copyBetweenStorage to this method
639
+        // - copy the copyKeys() call from  $this->copyBetweenStorage to this method
640
+        // - remove $this->copyBetweenStorage
641
+
642
+        return $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename);
643
+    }
644
+
645
+    /**
646
+     * Update the encrypted cache version in the database
647
+     *
648
+     * @param Storage $sourceStorage
649
+     * @param string $sourceInternalPath
650
+     * @param string $targetInternalPath
651
+     * @param bool $isRename
652
+     */
653
+    private function updateEncryptedVersion(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename) {
654
+        $isEncrypted = $this->encryptionManager->isEnabled() && $this->shouldEncrypt($targetInternalPath) ? 1 : 0;
655
+        $cacheInformation = [
656
+            'encrypted' => (bool)$isEncrypted,
657
+        ];
658
+        if($isEncrypted === 1) {
659
+            $encryptedVersion = $sourceStorage->getCache()->get($sourceInternalPath)['encryptedVersion'];
660
+
661
+            // In case of a move operation from an unencrypted to an encrypted
662
+            // storage the old encrypted version would stay with "0" while the
663
+            // correct value would be "1". Thus we manually set the value to "1"
664
+            // for those cases.
665
+            // See also https://github.com/owncloud/core/issues/23078
666
+            if($encryptedVersion === 0) {
667
+                $encryptedVersion = 1;
668
+            }
669
+
670
+            $cacheInformation['encryptedVersion'] = $encryptedVersion;
671
+        }
672
+
673
+        // in case of a rename we need to manipulate the source cache because
674
+        // this information will be kept for the new target
675
+        if ($isRename) {
676
+            $sourceStorage->getCache()->put($sourceInternalPath, $cacheInformation);
677
+        } else {
678
+            $this->getCache()->put($targetInternalPath, $cacheInformation);
679
+        }
680
+    }
681
+
682
+    /**
683
+     * copy file between two storages
684
+     *
685
+     * @param Storage $sourceStorage
686
+     * @param string $sourceInternalPath
687
+     * @param string $targetInternalPath
688
+     * @param bool $preserveMtime
689
+     * @param bool $isRename
690
+     * @return bool
691
+     * @throws \Exception
692
+     */
693
+    private function copyBetweenStorage(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename) {
694
+
695
+        // for versions we have nothing to do, because versions should always use the
696
+        // key from the original file. Just create a 1:1 copy and done
697
+        if ($this->isVersion($targetInternalPath) ||
698
+            $this->isVersion($sourceInternalPath)) {
699
+            // remember that we try to create a version so that we can detect it during
700
+            // fopen($sourceInternalPath) and by-pass the encryption in order to
701
+            // create a 1:1 copy of the file
702
+            $this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
703
+            $result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
704
+            $this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
705
+            if ($result) {
706
+                $info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
707
+                // make sure that we update the unencrypted size for the version
708
+                if (isset($info['encrypted']) && $info['encrypted'] === true) {
709
+                    $this->updateUnencryptedSize(
710
+                        $this->getFullPath($targetInternalPath),
711
+                        $info['size']
712
+                    );
713
+                }
714
+                $this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename);
715
+            }
716
+            return $result;
717
+        }
718
+
719
+        // first copy the keys that we reuse the existing file key on the target location
720
+        // and don't create a new one which would break versions for example.
721
+        $mount = $this->mountManager->findByStorageId($sourceStorage->getId());
722
+        if (count($mount) === 1) {
723
+            $mountPoint = $mount[0]->getMountPoint();
724
+            $source = $mountPoint . '/' . $sourceInternalPath;
725
+            $target = $this->getFullPath($targetInternalPath);
726
+            $this->copyKeys($source, $target);
727
+        } else {
728
+            $this->logger->error('Could not find mount point, can\'t keep encryption keys');
729
+        }
730
+
731
+        if ($sourceStorage->is_dir($sourceInternalPath)) {
732
+            $dh = $sourceStorage->opendir($sourceInternalPath);
733
+            $result = $this->mkdir($targetInternalPath);
734
+            if (is_resource($dh)) {
735
+                while ($result and ($file = readdir($dh)) !== false) {
736
+                    if (!Filesystem::isIgnoredDir($file)) {
737
+                        $result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, false, $isRename);
738
+                    }
739
+                }
740
+            }
741
+        } else {
742
+            try {
743
+                $source = $sourceStorage->fopen($sourceInternalPath, 'r');
744
+                $target = $this->fopen($targetInternalPath, 'w');
745
+                list(, $result) = \OC_Helper::streamCopy($source, $target);
746
+                fclose($source);
747
+                fclose($target);
748
+            } catch (\Exception $e) {
749
+                fclose($source);
750
+                fclose($target);
751
+                throw $e;
752
+            }
753
+            if($result) {
754
+                if ($preserveMtime) {
755
+                    $this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
756
+                }
757
+                $this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename);
758
+            } else {
759
+                // delete partially written target file
760
+                $this->unlink($targetInternalPath);
761
+                // delete cache entry that was created by fopen
762
+                $this->getCache()->remove($targetInternalPath);
763
+            }
764
+        }
765
+        return (bool)$result;
766
+
767
+    }
768
+
769
+    /**
770
+     * get the path to a local version of the file.
771
+     * The local version of the file can be temporary and doesn't have to be persistent across requests
772
+     *
773
+     * @param string $path
774
+     * @return string
775
+     */
776
+    public function getLocalFile($path) {
777
+        if ($this->encryptionManager->isEnabled()) {
778
+            $cachedFile = $this->getCachedFile($path);
779
+            if (is_string($cachedFile)) {
780
+                return $cachedFile;
781
+            }
782
+        }
783
+        return $this->storage->getLocalFile($path);
784
+    }
785
+
786
+    /**
787
+     * Returns the wrapped storage's value for isLocal()
788
+     *
789
+     * @return bool wrapped storage's isLocal() value
790
+     */
791
+    public function isLocal() {
792
+        if ($this->encryptionManager->isEnabled()) {
793
+            return false;
794
+        }
795
+        return $this->storage->isLocal();
796
+    }
797
+
798
+    /**
799
+     * see http://php.net/manual/en/function.stat.php
800
+     * only the following keys are required in the result: size and mtime
801
+     *
802
+     * @param string $path
803
+     * @return array
804
+     */
805
+    public function stat($path) {
806
+        $stat = $this->storage->stat($path);
807
+        $fileSize = $this->filesize($path);
808
+        $stat['size'] = $fileSize;
809
+        $stat[7] = $fileSize;
810
+        return $stat;
811
+    }
812
+
813
+    /**
814
+     * see http://php.net/manual/en/function.hash.php
815
+     *
816
+     * @param string $type
817
+     * @param string $path
818
+     * @param bool $raw
819
+     * @return string
820
+     */
821
+    public function hash($type, $path, $raw = false) {
822
+        $fh = $this->fopen($path, 'rb');
823
+        $ctx = hash_init($type);
824
+        hash_update_stream($ctx, $fh);
825
+        fclose($fh);
826
+        return hash_final($ctx, $raw);
827
+    }
828
+
829
+    /**
830
+     * return full path, including mount point
831
+     *
832
+     * @param string $path relative to mount point
833
+     * @return string full path including mount point
834
+     */
835
+    protected function getFullPath($path) {
836
+        return Filesystem::normalizePath($this->mountPoint . '/' . $path);
837
+    }
838
+
839
+    /**
840
+     * read first block of encrypted file, typically this will contain the
841
+     * encryption header
842
+     *
843
+     * @param string $path
844
+     * @return string
845
+     */
846
+    protected function readFirstBlock($path) {
847
+        $firstBlock = '';
848
+        if ($this->storage->file_exists($path)) {
849
+            $handle = $this->storage->fopen($path, 'r');
850
+            $firstBlock = fread($handle, $this->util->getHeaderSize());
851
+            fclose($handle);
852
+        }
853
+        return $firstBlock;
854
+    }
855
+
856
+    /**
857
+     * return header size of given file
858
+     *
859
+     * @param string $path
860
+     * @return int
861
+     */
862
+    protected function getHeaderSize($path) {
863
+        $headerSize = 0;
864
+        $realFile = $this->util->stripPartialFileExtension($path);
865
+        if ($this->storage->file_exists($realFile)) {
866
+            $path = $realFile;
867
+        }
868
+        $firstBlock = $this->readFirstBlock($path);
869
+
870
+        if (substr($firstBlock, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
871
+            $headerSize = $this->util->getHeaderSize();
872
+        }
873
+
874
+        return $headerSize;
875
+    }
876
+
877
+    /**
878
+     * parse raw header to array
879
+     *
880
+     * @param string $rawHeader
881
+     * @return array
882
+     */
883
+    protected function parseRawHeader($rawHeader) {
884
+        $result = array();
885
+        if (substr($rawHeader, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
886
+            $header = $rawHeader;
887
+            $endAt = strpos($header, Util::HEADER_END);
888
+            if ($endAt !== false) {
889
+                $header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
890
+
891
+                // +1 to not start with an ':' which would result in empty element at the beginning
892
+                $exploded = explode(':', substr($header, strlen(Util::HEADER_START)+1));
893
+
894
+                $element = array_shift($exploded);
895
+                while ($element !== Util::HEADER_END) {
896
+                    $result[$element] = array_shift($exploded);
897
+                    $element = array_shift($exploded);
898
+                }
899
+            }
900
+        }
901
+
902
+        return $result;
903
+    }
904
+
905
+    /**
906
+     * read header from file
907
+     *
908
+     * @param string $path
909
+     * @return array
910
+     */
911
+    protected function getHeader($path) {
912
+        $realFile = $this->util->stripPartialFileExtension($path);
913
+        if ($this->storage->file_exists($realFile)) {
914
+            $path = $realFile;
915
+        }
916
+
917
+        $firstBlock = $this->readFirstBlock($path);
918
+        $result = $this->parseRawHeader($firstBlock);
919
+
920
+        // if the header doesn't contain a encryption module we check if it is a
921
+        // legacy file. If true, we add the default encryption module
922
+        if (!isset($result[Util::HEADER_ENCRYPTION_MODULE_KEY])) {
923
+            if (!empty($result)) {
924
+                $result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
925
+            } else {
926
+                // if the header was empty we have to check first if it is a encrypted file at all
927
+                $info = $this->getCache()->get($path);
928
+                if (isset($info['encrypted']) && $info['encrypted'] === true) {
929
+                    $result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
930
+                }
931
+            }
932
+        }
933
+
934
+        return $result;
935
+    }
936
+
937
+    /**
938
+     * read encryption module needed to read/write the file located at $path
939
+     *
940
+     * @param string $path
941
+     * @return null|\OCP\Encryption\IEncryptionModule
942
+     * @throws ModuleDoesNotExistsException
943
+     * @throws \Exception
944
+     */
945
+    protected function getEncryptionModule($path) {
946
+        $encryptionModule = null;
947
+        $header = $this->getHeader($path);
948
+        $encryptionModuleId = $this->util->getEncryptionModuleId($header);
949
+        if (!empty($encryptionModuleId)) {
950
+            try {
951
+                $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
952
+            } catch (ModuleDoesNotExistsException $e) {
953
+                $this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
954
+                throw $e;
955
+            }
956
+        }
957
+
958
+        return $encryptionModule;
959
+    }
960
+
961
+    /**
962
+     * @param string $path
963
+     * @param int $unencryptedSize
964
+     */
965
+    public function updateUnencryptedSize($path, $unencryptedSize) {
966
+        $this->unencryptedSize[$path] = $unencryptedSize;
967
+    }
968
+
969
+    /**
970
+     * copy keys to new location
971
+     *
972
+     * @param string $source path relative to data/
973
+     * @param string $target path relative to data/
974
+     * @return bool
975
+     */
976
+    protected function copyKeys($source, $target) {
977
+        if (!$this->util->isExcluded($source)) {
978
+            return $this->keyStorage->copyKeys($source, $target);
979
+        }
980
+
981
+        return false;
982
+    }
983
+
984
+    /**
985
+     * check if path points to a files version
986
+     *
987
+     * @param $path
988
+     * @return bool
989
+     */
990
+    protected function isVersion($path) {
991
+        $normalized = Filesystem::normalizePath($path);
992
+        return substr($normalized, 0, strlen('/files_versions/')) === '/files_versions/';
993
+    }
994
+
995
+    /**
996
+     * check if the given storage should be encrypted or not
997
+     *
998
+     * @param $path
999
+     * @return bool
1000
+     */
1001
+    protected function shouldEncrypt($path) {
1002
+        $fullPath = $this->getFullPath($path);
1003
+        $mountPointConfig = $this->mount->getOption('encrypt', true);
1004
+        if ($mountPointConfig === false) {
1005
+            return false;
1006
+        }
1007
+
1008
+        try {
1009
+            $encryptionModule = $this->getEncryptionModule($fullPath);
1010
+        } catch (ModuleDoesNotExistsException $e) {
1011
+            return false;
1012
+        }
1013
+
1014
+        if ($encryptionModule === null) {
1015
+            $encryptionModule = $this->encryptionManager->getEncryptionModule();
1016
+        }
1017
+
1018
+        return $encryptionModule->shouldEncrypt($fullPath);
1019
+
1020
+    }
1021 1021
 
1022 1022
 }
Please login to merge, or discard this patch.
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -368,8 +368,8 @@  discard block
 block discarded – undo
368 368
 		// check if the file is stored in the array cache, this means that we
369 369
 		// copy a file over to the versions folder, in this case we don't want to
370 370
 		// decrypt it
371
-		if ($this->arrayCache->hasKey('encryption_copy_version_' . $path)) {
372
-			$this->arrayCache->remove('encryption_copy_version_' . $path);
371
+		if ($this->arrayCache->hasKey('encryption_copy_version_'.$path)) {
372
+			$this->arrayCache->remove('encryption_copy_version_'.$path);
373 373
 			return $this->storage->fopen($path, $mode);
374 374
 		}
375 375
 
@@ -439,8 +439,8 @@  discard block
 block discarded – undo
439 439
 					}
440 440
 				}
441 441
 			} catch (ModuleDoesNotExistsException $e) {
442
-				$this->logger->warning('Encryption module "' . $encryptionModuleId .
443
-					'" not found, file will be stored unencrypted (' . $e->getMessage() . ')');
442
+				$this->logger->warning('Encryption module "'.$encryptionModuleId.
443
+					'" not found, file will be stored unencrypted ('.$e->getMessage().')');
444 444
 			}
445 445
 
446 446
 			// encryption disabled on write of new file and write to existing unencrypted file -> don't encrypt
@@ -492,7 +492,7 @@  discard block
 block discarded – undo
492 492
 				try {
493 493
 					$result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
494 494
 				} catch (\Exception $e) {
495
-					$this->logger->error('Couldn\'t re-calculate unencrypted size for '. $path);
495
+					$this->logger->error('Couldn\'t re-calculate unencrypted size for '.$path);
496 496
 					$this->logger->logException($e);
497 497
 				}
498 498
 				unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
@@ -521,7 +521,7 @@  discard block
 block discarded – undo
521 521
 
522 522
 		// if we couldn't open the file we return the old unencrypted size
523 523
 		if (!is_resource($stream)) {
524
-			$this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
524
+			$this->logger->error('Could not open '.$path.'. Recalculation of unencrypted size aborted.');
525 525
 			return $unencryptedSize;
526 526
 		}
527 527
 
@@ -546,7 +546,7 @@  discard block
 block discarded – undo
546 546
 		// next highest is end of chunks, one subtracted is last one
547 547
 		// we have to read the last chunk, we can't just calculate it (because of padding etc)
548 548
 
549
-		$lastChunkNr = ceil($size/ $blockSize)-1;
549
+		$lastChunkNr = ceil($size / $blockSize) - 1;
550 550
 		// calculate last chunk position
551 551
 		$lastChunkPos = ($lastChunkNr * $blockSize);
552 552
 		// try to fseek to the last chunk, if it fails we have to read the whole file
@@ -554,16 +554,16 @@  discard block
 block discarded – undo
554 554
 			$newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
555 555
 		}
556 556
 
557
-		$lastChunkContentEncrypted='';
557
+		$lastChunkContentEncrypted = '';
558 558
 		$count = $blockSize;
559 559
 
560 560
 		while ($count > 0) {
561
-			$data=fread($stream, $blockSize);
562
-			$count=strlen($data);
561
+			$data = fread($stream, $blockSize);
562
+			$count = strlen($data);
563 563
 			$lastChunkContentEncrypted .= $data;
564
-			if(strlen($lastChunkContentEncrypted) > $blockSize) {
564
+			if (strlen($lastChunkContentEncrypted) > $blockSize) {
565 565
 				$newUnencryptedSize += $unencryptedBlockSize;
566
-				$lastChunkContentEncrypted=substr($lastChunkContentEncrypted, $blockSize);
566
+				$lastChunkContentEncrypted = substr($lastChunkContentEncrypted, $blockSize);
567 567
 			}
568 568
 		}
569 569
 
@@ -571,8 +571,8 @@  discard block
 block discarded – undo
571 571
 
572 572
 		// we have to decrypt the last chunk to get it actual size
573 573
 		$encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
574
-		$decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
575
-		$decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
574
+		$decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr.'end');
575
+		$decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr.'end');
576 576
 
577 577
 		// calc the real file size with the size of the last chunk
578 578
 		$newUnencryptedSize += strlen($decryptedLastChunk);
@@ -653,9 +653,9 @@  discard block
 block discarded – undo
653 653
 	private function updateEncryptedVersion(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename) {
654 654
 		$isEncrypted = $this->encryptionManager->isEnabled() && $this->shouldEncrypt($targetInternalPath) ? 1 : 0;
655 655
 		$cacheInformation = [
656
-			'encrypted' => (bool)$isEncrypted,
656
+			'encrypted' => (bool) $isEncrypted,
657 657
 		];
658
-		if($isEncrypted === 1) {
658
+		if ($isEncrypted === 1) {
659 659
 			$encryptedVersion = $sourceStorage->getCache()->get($sourceInternalPath)['encryptedVersion'];
660 660
 
661 661
 			// In case of a move operation from an unencrypted to an encrypted
@@ -663,7 +663,7 @@  discard block
 block discarded – undo
663 663
 			// correct value would be "1". Thus we manually set the value to "1"
664 664
 			// for those cases.
665 665
 			// See also https://github.com/owncloud/core/issues/23078
666
-			if($encryptedVersion === 0) {
666
+			if ($encryptedVersion === 0) {
667 667
 				$encryptedVersion = 1;
668 668
 			}
669 669
 
@@ -699,9 +699,9 @@  discard block
 block discarded – undo
699 699
 			// remember that we try to create a version so that we can detect it during
700 700
 			// fopen($sourceInternalPath) and by-pass the encryption in order to
701 701
 			// create a 1:1 copy of the file
702
-			$this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
702
+			$this->arrayCache->set('encryption_copy_version_'.$sourceInternalPath, true);
703 703
 			$result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
704
-			$this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
704
+			$this->arrayCache->remove('encryption_copy_version_'.$sourceInternalPath);
705 705
 			if ($result) {
706 706
 				$info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
707 707
 				// make sure that we update the unencrypted size for the version
@@ -721,7 +721,7 @@  discard block
 block discarded – undo
721 721
 		$mount = $this->mountManager->findByStorageId($sourceStorage->getId());
722 722
 		if (count($mount) === 1) {
723 723
 			$mountPoint = $mount[0]->getMountPoint();
724
-			$source = $mountPoint . '/' . $sourceInternalPath;
724
+			$source = $mountPoint.'/'.$sourceInternalPath;
725 725
 			$target = $this->getFullPath($targetInternalPath);
726 726
 			$this->copyKeys($source, $target);
727 727
 		} else {
@@ -734,7 +734,7 @@  discard block
 block discarded – undo
734 734
 			if (is_resource($dh)) {
735 735
 				while ($result and ($file = readdir($dh)) !== false) {
736 736
 					if (!Filesystem::isIgnoredDir($file)) {
737
-						$result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, false, $isRename);
737
+						$result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath.'/'.$file, $targetInternalPath.'/'.$file, false, $isRename);
738 738
 					}
739 739
 				}
740 740
 			}
@@ -750,7 +750,7 @@  discard block
 block discarded – undo
750 750
 				fclose($target);
751 751
 				throw $e;
752 752
 			}
753
-			if($result) {
753
+			if ($result) {
754 754
 				if ($preserveMtime) {
755 755
 					$this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
756 756
 				}
@@ -762,7 +762,7 @@  discard block
 block discarded – undo
762 762
 				$this->getCache()->remove($targetInternalPath);
763 763
 			}
764 764
 		}
765
-		return (bool)$result;
765
+		return (bool) $result;
766 766
 
767 767
 	}
768 768
 
@@ -833,7 +833,7 @@  discard block
 block discarded – undo
833 833
 	 * @return string full path including mount point
834 834
 	 */
835 835
 	protected function getFullPath($path) {
836
-		return Filesystem::normalizePath($this->mountPoint . '/' . $path);
836
+		return Filesystem::normalizePath($this->mountPoint.'/'.$path);
837 837
 	}
838 838
 
839 839
 	/**
@@ -889,7 +889,7 @@  discard block
 block discarded – undo
889 889
 				$header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
890 890
 
891 891
 				// +1 to not start with an ':' which would result in empty element at the beginning
892
-				$exploded = explode(':', substr($header, strlen(Util::HEADER_START)+1));
892
+				$exploded = explode(':', substr($header, strlen(Util::HEADER_START) + 1));
893 893
 
894 894
 				$element = array_shift($exploded);
895 895
 				while ($element !== Util::HEADER_END) {
@@ -950,7 +950,7 @@  discard block
 block discarded – undo
950 950
 			try {
951 951
 				$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
952 952
 			} catch (ModuleDoesNotExistsException $e) {
953
-				$this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
953
+				$this->logger->critical('Encryption module defined in "'.$path.'" not loaded!');
954 954
 				throw $e;
955 955
 			}
956 956
 		}
Please login to merge, or discard this patch.
apps/dav/lib/AppInfo/Application.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -25,7 +25,6 @@
 block discarded – undo
25 25
 namespace OCA\DAV\AppInfo;
26 26
 
27 27
 use OCA\DAV\CalDAV\Activity\Backend;
28
-use OCA\DAV\CalDAV\Activity\Extension;
29 28
 use OCA\DAV\CalDAV\Activity\Provider\Event;
30 29
 use OCA\DAV\CalDAV\BirthdayService;
31 30
 use OCA\DAV\Capabilities;
Please login to merge, or discard this patch.
Indentation   +126 added lines, -126 removed lines patch added patch discarded remove patch
@@ -39,134 +39,134 @@
 block discarded – undo
39 39
 
40 40
 class Application extends App {
41 41
 
42
-	/**
43
-	 * Application constructor.
44
-	 */
45
-	public function __construct() {
46
-		parent::__construct('dav');
42
+    /**
43
+     * Application constructor.
44
+     */
45
+    public function __construct() {
46
+        parent::__construct('dav');
47 47
 
48
-		/*
48
+        /*
49 49
 		 * Register capabilities
50 50
 		 */
51
-		$this->getContainer()->registerCapability(Capabilities::class);
52
-	}
53
-
54
-	/**
55
-	 * @param IManager $contactsManager
56
-	 * @param string $userID
57
-	 */
58
-	public function setupContactsProvider(IManager $contactsManager, $userID) {
59
-		/** @var ContactsManager $cm */
60
-		$cm = $this->getContainer()->query(ContactsManager::class);
61
-		$urlGenerator = $this->getContainer()->getServer()->getURLGenerator();
62
-		$cm->setupContactsProvider($contactsManager, $userID, $urlGenerator);
63
-	}
64
-
65
-	public function registerHooks() {
66
-		/** @var HookManager $hm */
67
-		$hm = $this->getContainer()->query(HookManager::class);
68
-		$hm->setup();
69
-
70
-		$dispatcher = $this->getContainer()->getServer()->getEventDispatcher();
71
-
72
-		// first time login event setup
73
-		$dispatcher->addListener(IUser::class . '::firstLogin', function ($event) use ($hm) {
74
-			if ($event instanceof GenericEvent) {
75
-				$hm->firstLogin($event->getSubject());
76
-			}
77
-		});
78
-
79
-		// carddav/caldav sync event setup
80
-		$listener = function($event) {
81
-			if ($event instanceof GenericEvent) {
82
-				/** @var BirthdayService $b */
83
-				$b = $this->getContainer()->query(BirthdayService::class);
84
-				$b->onCardChanged(
85
-					$event->getArgument('addressBookId'),
86
-					$event->getArgument('cardUri'),
87
-					$event->getArgument('cardData')
88
-				);
89
-			}
90
-		};
91
-
92
-		$dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::createCard', $listener);
93
-		$dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::updateCard', $listener);
94
-		$dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::deleteCard', function($event) {
95
-			if ($event instanceof GenericEvent) {
96
-				/** @var BirthdayService $b */
97
-				$b = $this->getContainer()->query(BirthdayService::class);
98
-				$b->onCardDeleted(
99
-					$event->getArgument('addressBookId'),
100
-					$event->getArgument('cardUri')
101
-				);
102
-			}
103
-		});
104
-
105
-		$dispatcher->addListener('OC\AccountManager::userUpdated', function(GenericEvent $event) {
106
-			$user = $event->getSubject();
107
-			$syncService = $this->getContainer()->query(SyncService::class);
108
-			$syncService->updateUser($user);
109
-		});
110
-
111
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', function(GenericEvent $event) {
112
-			/** @var Backend $backend */
113
-			$backend = $this->getContainer()->query(Backend::class);
114
-			$backend->onCalendarAdd(
115
-				$event->getArgument('calendarData')
116
-			);
117
-		});
118
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', function(GenericEvent $event) {
119
-			/** @var Backend $backend */
120
-			$backend = $this->getContainer()->query(Backend::class);
121
-			$backend->onCalendarUpdate(
122
-				$event->getArgument('calendarData'),
123
-				$event->getArgument('shares'),
124
-				$event->getArgument('propertyMutations')
125
-			);
126
-		});
127
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', function(GenericEvent $event) {
128
-			/** @var Backend $backend */
129
-			$backend = $this->getContainer()->query(Backend::class);
130
-			$backend->onCalendarDelete(
131
-				$event->getArgument('calendarData'),
132
-				$event->getArgument('shares')
133
-			);
134
-		});
135
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::updateShares', function(GenericEvent $event) {
136
-			/** @var Backend $backend */
137
-			$backend = $this->getContainer()->query(Backend::class);
138
-			$backend->onCalendarUpdateShares(
139
-				$event->getArgument('calendarData'),
140
-				$event->getArgument('shares'),
141
-				$event->getArgument('add'),
142
-				$event->getArgument('remove')
143
-			);
144
-		});
145
-
146
-		$listener = function(GenericEvent $event, $eventName) {
147
-			/** @var Backend $backend */
148
-			$backend = $this->getContainer()->query(Backend::class);
149
-
150
-			$subject = Event::SUBJECT_OBJECT_ADD;
151
-			if ($eventName === '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject') {
152
-				$subject = Event::SUBJECT_OBJECT_UPDATE;
153
-			} else if ($eventName === '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject') {
154
-				$subject = Event::SUBJECT_OBJECT_DELETE;
155
-			}
156
-			$backend->onTouchCalendarObject(
157
-				$subject,
158
-				$event->getArgument('calendarData'),
159
-				$event->getArgument('shares'),
160
-				$event->getArgument('objectData')
161
-			);
162
-		};
163
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', $listener);
164
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', $listener);
165
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', $listener);
166
-	}
167
-
168
-	public function getSyncService() {
169
-		return $this->getContainer()->query(SyncService::class);
170
-	}
51
+        $this->getContainer()->registerCapability(Capabilities::class);
52
+    }
53
+
54
+    /**
55
+     * @param IManager $contactsManager
56
+     * @param string $userID
57
+     */
58
+    public function setupContactsProvider(IManager $contactsManager, $userID) {
59
+        /** @var ContactsManager $cm */
60
+        $cm = $this->getContainer()->query(ContactsManager::class);
61
+        $urlGenerator = $this->getContainer()->getServer()->getURLGenerator();
62
+        $cm->setupContactsProvider($contactsManager, $userID, $urlGenerator);
63
+    }
64
+
65
+    public function registerHooks() {
66
+        /** @var HookManager $hm */
67
+        $hm = $this->getContainer()->query(HookManager::class);
68
+        $hm->setup();
69
+
70
+        $dispatcher = $this->getContainer()->getServer()->getEventDispatcher();
71
+
72
+        // first time login event setup
73
+        $dispatcher->addListener(IUser::class . '::firstLogin', function ($event) use ($hm) {
74
+            if ($event instanceof GenericEvent) {
75
+                $hm->firstLogin($event->getSubject());
76
+            }
77
+        });
78
+
79
+        // carddav/caldav sync event setup
80
+        $listener = function($event) {
81
+            if ($event instanceof GenericEvent) {
82
+                /** @var BirthdayService $b */
83
+                $b = $this->getContainer()->query(BirthdayService::class);
84
+                $b->onCardChanged(
85
+                    $event->getArgument('addressBookId'),
86
+                    $event->getArgument('cardUri'),
87
+                    $event->getArgument('cardData')
88
+                );
89
+            }
90
+        };
91
+
92
+        $dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::createCard', $listener);
93
+        $dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::updateCard', $listener);
94
+        $dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::deleteCard', function($event) {
95
+            if ($event instanceof GenericEvent) {
96
+                /** @var BirthdayService $b */
97
+                $b = $this->getContainer()->query(BirthdayService::class);
98
+                $b->onCardDeleted(
99
+                    $event->getArgument('addressBookId'),
100
+                    $event->getArgument('cardUri')
101
+                );
102
+            }
103
+        });
104
+
105
+        $dispatcher->addListener('OC\AccountManager::userUpdated', function(GenericEvent $event) {
106
+            $user = $event->getSubject();
107
+            $syncService = $this->getContainer()->query(SyncService::class);
108
+            $syncService->updateUser($user);
109
+        });
110
+
111
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', function(GenericEvent $event) {
112
+            /** @var Backend $backend */
113
+            $backend = $this->getContainer()->query(Backend::class);
114
+            $backend->onCalendarAdd(
115
+                $event->getArgument('calendarData')
116
+            );
117
+        });
118
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', function(GenericEvent $event) {
119
+            /** @var Backend $backend */
120
+            $backend = $this->getContainer()->query(Backend::class);
121
+            $backend->onCalendarUpdate(
122
+                $event->getArgument('calendarData'),
123
+                $event->getArgument('shares'),
124
+                $event->getArgument('propertyMutations')
125
+            );
126
+        });
127
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', function(GenericEvent $event) {
128
+            /** @var Backend $backend */
129
+            $backend = $this->getContainer()->query(Backend::class);
130
+            $backend->onCalendarDelete(
131
+                $event->getArgument('calendarData'),
132
+                $event->getArgument('shares')
133
+            );
134
+        });
135
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::updateShares', function(GenericEvent $event) {
136
+            /** @var Backend $backend */
137
+            $backend = $this->getContainer()->query(Backend::class);
138
+            $backend->onCalendarUpdateShares(
139
+                $event->getArgument('calendarData'),
140
+                $event->getArgument('shares'),
141
+                $event->getArgument('add'),
142
+                $event->getArgument('remove')
143
+            );
144
+        });
145
+
146
+        $listener = function(GenericEvent $event, $eventName) {
147
+            /** @var Backend $backend */
148
+            $backend = $this->getContainer()->query(Backend::class);
149
+
150
+            $subject = Event::SUBJECT_OBJECT_ADD;
151
+            if ($eventName === '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject') {
152
+                $subject = Event::SUBJECT_OBJECT_UPDATE;
153
+            } else if ($eventName === '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject') {
154
+                $subject = Event::SUBJECT_OBJECT_DELETE;
155
+            }
156
+            $backend->onTouchCalendarObject(
157
+                $subject,
158
+                $event->getArgument('calendarData'),
159
+                $event->getArgument('shares'),
160
+                $event->getArgument('objectData')
161
+            );
162
+        };
163
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', $listener);
164
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', $listener);
165
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', $listener);
166
+    }
167
+
168
+    public function getSyncService() {
169
+        return $this->getContainer()->query(SyncService::class);
170
+    }
171 171
 
172 172
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -70,7 +70,7 @@
 block discarded – undo
70 70
 		$dispatcher = $this->getContainer()->getServer()->getEventDispatcher();
71 71
 
72 72
 		// first time login event setup
73
-		$dispatcher->addListener(IUser::class . '::firstLogin', function ($event) use ($hm) {
73
+		$dispatcher->addListener(IUser::class.'::firstLogin', function($event) use ($hm) {
74 74
 			if ($event instanceof GenericEvent) {
75 75
 				$hm->firstLogin($event->getSubject());
76 76
 			}
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/Storage/AmazonS3.php 3 patches
Doc Comments   +6 added lines patch added patch discarded remove patch
@@ -191,6 +191,9 @@  discard block
 block discarded – undo
191 191
 		return false;
192 192
 	}
193 193
 
194
+	/**
195
+	 * @param string $path
196
+	 */
194 197
 	private function batchDelete ($path = null) {
195 198
 		$params = array(
196 199
 			'Bucket' => $this->bucket
@@ -516,6 +519,9 @@  discard block
 block discarded – undo
516 519
 		return $this->id;
517 520
 	}
518 521
 
522
+	/**
523
+	 * @param string $path
524
+	 */
519 525
 	public function writeBack($tmpFile, $path) {
520 526
 		try {
521 527
 			$this->getConnection()->putObject(array(
Please login to merge, or discard this patch.
Indentation   +494 added lines, -494 removed lines patch added patch discarded remove patch
@@ -37,7 +37,7 @@  discard block
 block discarded – undo
37 37
 namespace OCA\Files_External\Lib\Storage;
38 38
 
39 39
 set_include_path(get_include_path() . PATH_SEPARATOR .
40
-	\OC_App::getAppPath('files_external') . '/3rdparty/aws-sdk-php');
40
+    \OC_App::getAppPath('files_external') . '/3rdparty/aws-sdk-php');
41 41
 require_once 'aws-autoloader.php';
42 42
 
43 43
 use Aws\S3\S3Client;
@@ -47,498 +47,498 @@  discard block
 block discarded – undo
47 47
 use OC\Files\ObjectStore\S3ConnectionTrait;
48 48
 
49 49
 class AmazonS3 extends \OC\Files\Storage\Common {
50
-	use S3ConnectionTrait;
51
-
52
-	/**
53
-	 * @var array
54
-	 */
55
-	private static $tmpFiles = array();
56
-
57
-	/**
58
-	 * @var int in seconds
59
-	 */
60
-	private $rescanDelay = 10;
61
-
62
-	public function __construct($parameters) {
63
-		parent::__construct($parameters);
64
-		$this->parseParams($parameters);
65
-	}
66
-
67
-	/**
68
-	 * @param string $path
69
-	 * @return string correctly encoded path
70
-	 */
71
-	private function normalizePath($path) {
72
-		$path = trim($path, '/');
73
-
74
-		if (!$path) {
75
-			$path = '.';
76
-		}
77
-
78
-		return $path;
79
-	}
80
-
81
-	private function isRoot($path) {
82
-		return $path === '.';
83
-	}
84
-
85
-	private function cleanKey($path) {
86
-		if ($this->isRoot($path)) {
87
-			return '/';
88
-		}
89
-		return $path;
90
-	}
91
-
92
-	/**
93
-	 * Updates old storage ids (v0.2.1 and older) that are based on key and secret to new ones based on the bucket name.
94
-	 * TODO Do this in an update.php. requires iterating over all users and loading the mount.json from their home
95
-	 *
96
-	 * @param array $params
97
-	 */
98
-	public function updateLegacyId (array $params) {
99
-		$oldId = 'amazon::' . $params['key'] . md5($params['secret']);
100
-
101
-		// find by old id or bucket
102
-		$stmt = \OC::$server->getDatabaseConnection()->prepare(
103
-			'SELECT `numeric_id`, `id` FROM `*PREFIX*storages` WHERE `id` IN (?, ?)'
104
-		);
105
-		$stmt->execute(array($oldId, $this->id));
106
-		while ($row = $stmt->fetch()) {
107
-			$storages[$row['id']] = $row['numeric_id'];
108
-		}
109
-
110
-		if (isset($storages[$this->id]) && isset($storages[$oldId])) {
111
-			// if both ids exist, delete the old storage and corresponding filecache entries
112
-			\OC\Files\Cache\Storage::remove($oldId);
113
-		} else if (isset($storages[$oldId])) {
114
-			// if only the old id exists do an update
115
-			$stmt = \OC::$server->getDatabaseConnection()->prepare(
116
-				'UPDATE `*PREFIX*storages` SET `id` = ? WHERE `id` = ?'
117
-			);
118
-			$stmt->execute(array($this->id, $oldId));
119
-		}
120
-		// only the bucket based id may exist, do nothing
121
-	}
122
-
123
-	/**
124
-	 * Remove a file or folder
125
-	 *
126
-	 * @param string $path
127
-	 * @return bool
128
-	 */
129
-	protected function remove($path) {
130
-		// remember fileType to reduce http calls
131
-		$fileType = $this->filetype($path);
132
-		if ($fileType === 'dir') {
133
-			return $this->rmdir($path);
134
-		} else if ($fileType === 'file') {
135
-			return $this->unlink($path);
136
-		} else {
137
-			return false;
138
-		}
139
-	}
140
-
141
-	public function mkdir($path) {
142
-		$path = $this->normalizePath($path);
143
-
144
-		if ($this->is_dir($path)) {
145
-			return false;
146
-		}
147
-
148
-		try {
149
-			$this->getConnection()->putObject(array(
150
-				'Bucket' => $this->bucket,
151
-				'Key' => $path . '/',
152
-				'Body' => '',
153
-				'ContentType' => 'httpd/unix-directory'
154
-			));
155
-			$this->testTimeout();
156
-		} catch (S3Exception $e) {
157
-			\OCP\Util::logException('files_external', $e);
158
-			return false;
159
-		}
160
-
161
-		return true;
162
-	}
163
-
164
-	public function file_exists($path) {
165
-		return $this->filetype($path) !== false;
166
-	}
167
-
168
-
169
-	public function rmdir($path) {
170
-		$path = $this->normalizePath($path);
171
-
172
-		if ($this->isRoot($path)) {
173
-			return $this->clearBucket();
174
-		}
175
-
176
-		if (!$this->file_exists($path)) {
177
-			return false;
178
-		}
179
-
180
-		return $this->batchDelete($path);
181
-	}
182
-
183
-	protected function clearBucket() {
184
-		try {
185
-			$this->getConnection()->clearBucket($this->bucket);
186
-			return true;
187
-			// clearBucket() is not working with Ceph, so if it fails we try the slower approach
188
-		} catch (\Exception $e) {
189
-			return $this->batchDelete();
190
-		}
191
-		return false;
192
-	}
193
-
194
-	private function batchDelete ($path = null) {
195
-		$params = array(
196
-			'Bucket' => $this->bucket
197
-		);
198
-		if ($path !== null) {
199
-			$params['Prefix'] = $path . '/';
200
-		}
201
-		try {
202
-			// Since there are no real directories on S3, we need
203
-			// to delete all objects prefixed with the path.
204
-			do {
205
-				// instead of the iterator, manually loop over the list ...
206
-				$objects = $this->getConnection()->listObjects($params);
207
-				// ... so we can delete the files in batches
208
-				$this->getConnection()->deleteObjects(array(
209
-					'Bucket' => $this->bucket,
210
-					'Objects' => $objects['Contents']
211
-				));
212
-				$this->testTimeout();
213
-				// we reached the end when the list is no longer truncated
214
-			} while ($objects['IsTruncated']);
215
-		} catch (S3Exception $e) {
216
-			\OCP\Util::logException('files_external', $e);
217
-			return false;
218
-		}
219
-		return true;
220
-	}
221
-
222
-	public function opendir($path) {
223
-		$path = $this->normalizePath($path);
224
-
225
-		if ($this->isRoot($path)) {
226
-			$path = '';
227
-		} else {
228
-			$path .= '/';
229
-		}
230
-
231
-		try {
232
-			$files = array();
233
-			$result = $this->getConnection()->getIterator('ListObjects', array(
234
-				'Bucket' => $this->bucket,
235
-				'Delimiter' => '/',
236
-				'Prefix' => $path
237
-			), array('return_prefixes' => true));
238
-
239
-			foreach ($result as $object) {
240
-				if (isset($object['Key']) && $object['Key'] === $path) {
241
-					// it's the directory itself, skip
242
-					continue;
243
-				}
244
-				$file = basename(
245
-					isset($object['Key']) ? $object['Key'] : $object['Prefix']
246
-				);
247
-				$files[] = $file;
248
-			}
249
-
250
-			return IteratorDirectory::wrap($files);
251
-		} catch (S3Exception $e) {
252
-			\OCP\Util::logException('files_external', $e);
253
-			return false;
254
-		}
255
-	}
256
-
257
-	public function stat($path) {
258
-		$path = $this->normalizePath($path);
259
-
260
-		try {
261
-			$stat = array();
262
-			if ($this->is_dir($path)) {
263
-				//folders don't really exist
264
-				$stat['size'] = -1; //unknown
265
-				$stat['mtime'] = time() - $this->rescanDelay * 1000;
266
-			} else {
267
-				$result = $this->getConnection()->headObject(array(
268
-					'Bucket' => $this->bucket,
269
-					'Key' => $path
270
-				));
271
-
272
-				$stat['size'] = $result['ContentLength'] ? $result['ContentLength'] : 0;
273
-				if ($result['Metadata']['lastmodified']) {
274
-					$stat['mtime'] = strtotime($result['Metadata']['lastmodified']);
275
-				} else {
276
-					$stat['mtime'] = strtotime($result['LastModified']);
277
-				}
278
-			}
279
-			$stat['atime'] = time();
280
-
281
-			return $stat;
282
-		} catch(S3Exception $e) {
283
-			\OCP\Util::logException('files_external', $e);
284
-			return false;
285
-		}
286
-	}
287
-
288
-	public function filetype($path) {
289
-		$path = $this->normalizePath($path);
290
-
291
-		if ($this->isRoot($path)) {
292
-			return 'dir';
293
-		}
294
-
295
-		try {
296
-			if ($this->getConnection()->doesObjectExist($this->bucket, $path)) {
297
-				return 'file';
298
-			}
299
-			if ($this->getConnection()->doesObjectExist($this->bucket, $path.'/')) {
300
-				return 'dir';
301
-			}
302
-		} catch (S3Exception $e) {
303
-			\OCP\Util::logException('files_external', $e);
304
-			return false;
305
-		}
306
-
307
-		return false;
308
-	}
309
-
310
-	public function unlink($path) {
311
-		$path = $this->normalizePath($path);
312
-
313
-		if ($this->is_dir($path)) {
314
-			return $this->rmdir($path);
315
-		}
316
-
317
-		try {
318
-			$this->getConnection()->deleteObject(array(
319
-				'Bucket' => $this->bucket,
320
-				'Key' => $path
321
-			));
322
-			$this->testTimeout();
323
-		} catch (S3Exception $e) {
324
-			\OCP\Util::logException('files_external', $e);
325
-			return false;
326
-		}
327
-
328
-		return true;
329
-	}
330
-
331
-	public function fopen($path, $mode) {
332
-		$path = $this->normalizePath($path);
333
-
334
-		switch ($mode) {
335
-			case 'r':
336
-			case 'rb':
337
-				$tmpFile = \OCP\Files::tmpFile();
338
-				self::$tmpFiles[$tmpFile] = $path;
339
-
340
-				try {
341
-					$this->getConnection()->getObject(array(
342
-						'Bucket' => $this->bucket,
343
-						'Key' => $path,
344
-						'SaveAs' => $tmpFile
345
-					));
346
-				} catch (S3Exception $e) {
347
-					\OCP\Util::logException('files_external', $e);
348
-					return false;
349
-				}
350
-
351
-				return fopen($tmpFile, 'r');
352
-			case 'w':
353
-			case 'wb':
354
-			case 'a':
355
-			case 'ab':
356
-			case 'r+':
357
-			case 'w+':
358
-			case 'wb+':
359
-			case 'a+':
360
-			case 'x':
361
-			case 'x+':
362
-			case 'c':
363
-			case 'c+':
364
-				if (strrpos($path, '.') !== false) {
365
-					$ext = substr($path, strrpos($path, '.'));
366
-				} else {
367
-					$ext = '';
368
-				}
369
-				$tmpFile = \OCP\Files::tmpFile($ext);
370
-				if ($this->file_exists($path)) {
371
-					$source = $this->fopen($path, 'r');
372
-					file_put_contents($tmpFile, $source);
373
-				}
374
-
375
-				$handle = fopen($tmpFile, $mode);
376
-				return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
377
-					$this->writeBack($tmpFile, $path);
378
-				});
379
-		}
380
-		return false;
381
-	}
382
-
383
-	public function touch($path, $mtime = null) {
384
-		$path = $this->normalizePath($path);
385
-
386
-		$metadata = array();
387
-		if (is_null($mtime)) {
388
-			$mtime = time();
389
-		}
390
-		$metadata = [
391
-			'lastmodified' => gmdate(\Aws\Common\Enum\DateFormat::RFC1123, $mtime)
392
-		];
393
-
394
-		$fileType = $this->filetype($path);
395
-		try {
396
-			if ($fileType !== false) {
397
-				if ($fileType === 'dir' && ! $this->isRoot($path)) {
398
-					$path .= '/';
399
-				}
400
-				$this->getConnection()->copyObject([
401
-					'Bucket' => $this->bucket,
402
-					'Key' => $this->cleanKey($path),
403
-					'Metadata' => $metadata,
404
-					'CopySource' => $this->bucket . '/' . $path,
405
-					'MetadataDirective' => 'REPLACE',
406
-				]);
407
-				$this->testTimeout();
408
-			} else {
409
-				$mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
410
-				$this->getConnection()->putObject([
411
-					'Bucket' => $this->bucket,
412
-					'Key' => $this->cleanKey($path),
413
-					'Metadata' => $metadata,
414
-					'Body' => '',
415
-					'ContentType' => $mimeType,
416
-					'MetadataDirective' => 'REPLACE',
417
-				]);
418
-				$this->testTimeout();
419
-			}
420
-		} catch (S3Exception $e) {
421
-			\OCP\Util::logException('files_external', $e);
422
-			return false;
423
-		}
424
-
425
-		return true;
426
-	}
427
-
428
-	public function copy($path1, $path2) {
429
-		$path1 = $this->normalizePath($path1);
430
-		$path2 = $this->normalizePath($path2);
431
-
432
-		if ($this->is_file($path1)) {
433
-			try {
434
-				$this->getConnection()->copyObject(array(
435
-					'Bucket' => $this->bucket,
436
-					'Key' => $this->cleanKey($path2),
437
-					'CopySource' => S3Client::encodeKey($this->bucket . '/' . $path1)
438
-				));
439
-				$this->testTimeout();
440
-			} catch (S3Exception $e) {
441
-				\OCP\Util::logException('files_external', $e);
442
-				return false;
443
-			}
444
-		} else {
445
-			$this->remove($path2);
446
-
447
-			try {
448
-				$this->getConnection()->copyObject(array(
449
-					'Bucket' => $this->bucket,
450
-					'Key' => $path2 . '/',
451
-					'CopySource' => S3Client::encodeKey($this->bucket . '/' . $path1 . '/')
452
-				));
453
-				$this->testTimeout();
454
-			} catch (S3Exception $e) {
455
-				\OCP\Util::logException('files_external', $e);
456
-				return false;
457
-			}
458
-
459
-			$dh = $this->opendir($path1);
460
-			if (is_resource($dh)) {
461
-				while (($file = readdir($dh)) !== false) {
462
-					if (\OC\Files\Filesystem::isIgnoredDir($file)) {
463
-						continue;
464
-					}
465
-
466
-					$source = $path1 . '/' . $file;
467
-					$target = $path2 . '/' . $file;
468
-					$this->copy($source, $target);
469
-				}
470
-			}
471
-		}
472
-
473
-		return true;
474
-	}
475
-
476
-	public function rename($path1, $path2) {
477
-		$path1 = $this->normalizePath($path1);
478
-		$path2 = $this->normalizePath($path2);
479
-
480
-		if ($this->is_file($path1)) {
481
-
482
-			if ($this->copy($path1, $path2) === false) {
483
-				return false;
484
-			}
485
-
486
-			if ($this->unlink($path1) === false) {
487
-				$this->unlink($path2);
488
-				return false;
489
-			}
490
-		} else {
491
-
492
-			if ($this->copy($path1, $path2) === false) {
493
-				return false;
494
-			}
495
-
496
-			if ($this->rmdir($path1) === false) {
497
-				$this->rmdir($path2);
498
-				return false;
499
-			}
500
-		}
501
-
502
-		return true;
503
-	}
504
-
505
-	public function test() {
506
-		$test = $this->getConnection()->getBucketAcl(array(
507
-			'Bucket' => $this->bucket,
508
-		));
509
-		if (isset($test) && !is_null($test->getPath('Owner/ID'))) {
510
-			return true;
511
-		}
512
-		return false;
513
-	}
514
-
515
-	public function getId() {
516
-		return $this->id;
517
-	}
518
-
519
-	public function writeBack($tmpFile, $path) {
520
-		try {
521
-			$this->getConnection()->putObject(array(
522
-				'Bucket' => $this->bucket,
523
-				'Key' => $this->cleanKey($path),
524
-				'SourceFile' => $tmpFile,
525
-				'ContentType' => \OC::$server->getMimeTypeDetector()->detect($tmpFile),
526
-				'ContentLength' => filesize($tmpFile)
527
-			));
528
-			$this->testTimeout();
529
-
530
-			unlink($tmpFile);
531
-		} catch (S3Exception $e) {
532
-			\OCP\Util::logException('files_external', $e);
533
-			return false;
534
-		}
535
-	}
536
-
537
-	/**
538
-	 * check if curl is installed
539
-	 */
540
-	public static function checkDependencies() {
541
-		return true;
542
-	}
50
+    use S3ConnectionTrait;
51
+
52
+    /**
53
+     * @var array
54
+     */
55
+    private static $tmpFiles = array();
56
+
57
+    /**
58
+     * @var int in seconds
59
+     */
60
+    private $rescanDelay = 10;
61
+
62
+    public function __construct($parameters) {
63
+        parent::__construct($parameters);
64
+        $this->parseParams($parameters);
65
+    }
66
+
67
+    /**
68
+     * @param string $path
69
+     * @return string correctly encoded path
70
+     */
71
+    private function normalizePath($path) {
72
+        $path = trim($path, '/');
73
+
74
+        if (!$path) {
75
+            $path = '.';
76
+        }
77
+
78
+        return $path;
79
+    }
80
+
81
+    private function isRoot($path) {
82
+        return $path === '.';
83
+    }
84
+
85
+    private function cleanKey($path) {
86
+        if ($this->isRoot($path)) {
87
+            return '/';
88
+        }
89
+        return $path;
90
+    }
91
+
92
+    /**
93
+     * Updates old storage ids (v0.2.1 and older) that are based on key and secret to new ones based on the bucket name.
94
+     * TODO Do this in an update.php. requires iterating over all users and loading the mount.json from their home
95
+     *
96
+     * @param array $params
97
+     */
98
+    public function updateLegacyId (array $params) {
99
+        $oldId = 'amazon::' . $params['key'] . md5($params['secret']);
100
+
101
+        // find by old id or bucket
102
+        $stmt = \OC::$server->getDatabaseConnection()->prepare(
103
+            'SELECT `numeric_id`, `id` FROM `*PREFIX*storages` WHERE `id` IN (?, ?)'
104
+        );
105
+        $stmt->execute(array($oldId, $this->id));
106
+        while ($row = $stmt->fetch()) {
107
+            $storages[$row['id']] = $row['numeric_id'];
108
+        }
109
+
110
+        if (isset($storages[$this->id]) && isset($storages[$oldId])) {
111
+            // if both ids exist, delete the old storage and corresponding filecache entries
112
+            \OC\Files\Cache\Storage::remove($oldId);
113
+        } else if (isset($storages[$oldId])) {
114
+            // if only the old id exists do an update
115
+            $stmt = \OC::$server->getDatabaseConnection()->prepare(
116
+                'UPDATE `*PREFIX*storages` SET `id` = ? WHERE `id` = ?'
117
+            );
118
+            $stmt->execute(array($this->id, $oldId));
119
+        }
120
+        // only the bucket based id may exist, do nothing
121
+    }
122
+
123
+    /**
124
+     * Remove a file or folder
125
+     *
126
+     * @param string $path
127
+     * @return bool
128
+     */
129
+    protected function remove($path) {
130
+        // remember fileType to reduce http calls
131
+        $fileType = $this->filetype($path);
132
+        if ($fileType === 'dir') {
133
+            return $this->rmdir($path);
134
+        } else if ($fileType === 'file') {
135
+            return $this->unlink($path);
136
+        } else {
137
+            return false;
138
+        }
139
+    }
140
+
141
+    public function mkdir($path) {
142
+        $path = $this->normalizePath($path);
143
+
144
+        if ($this->is_dir($path)) {
145
+            return false;
146
+        }
147
+
148
+        try {
149
+            $this->getConnection()->putObject(array(
150
+                'Bucket' => $this->bucket,
151
+                'Key' => $path . '/',
152
+                'Body' => '',
153
+                'ContentType' => 'httpd/unix-directory'
154
+            ));
155
+            $this->testTimeout();
156
+        } catch (S3Exception $e) {
157
+            \OCP\Util::logException('files_external', $e);
158
+            return false;
159
+        }
160
+
161
+        return true;
162
+    }
163
+
164
+    public function file_exists($path) {
165
+        return $this->filetype($path) !== false;
166
+    }
167
+
168
+
169
+    public function rmdir($path) {
170
+        $path = $this->normalizePath($path);
171
+
172
+        if ($this->isRoot($path)) {
173
+            return $this->clearBucket();
174
+        }
175
+
176
+        if (!$this->file_exists($path)) {
177
+            return false;
178
+        }
179
+
180
+        return $this->batchDelete($path);
181
+    }
182
+
183
+    protected function clearBucket() {
184
+        try {
185
+            $this->getConnection()->clearBucket($this->bucket);
186
+            return true;
187
+            // clearBucket() is not working with Ceph, so if it fails we try the slower approach
188
+        } catch (\Exception $e) {
189
+            return $this->batchDelete();
190
+        }
191
+        return false;
192
+    }
193
+
194
+    private function batchDelete ($path = null) {
195
+        $params = array(
196
+            'Bucket' => $this->bucket
197
+        );
198
+        if ($path !== null) {
199
+            $params['Prefix'] = $path . '/';
200
+        }
201
+        try {
202
+            // Since there are no real directories on S3, we need
203
+            // to delete all objects prefixed with the path.
204
+            do {
205
+                // instead of the iterator, manually loop over the list ...
206
+                $objects = $this->getConnection()->listObjects($params);
207
+                // ... so we can delete the files in batches
208
+                $this->getConnection()->deleteObjects(array(
209
+                    'Bucket' => $this->bucket,
210
+                    'Objects' => $objects['Contents']
211
+                ));
212
+                $this->testTimeout();
213
+                // we reached the end when the list is no longer truncated
214
+            } while ($objects['IsTruncated']);
215
+        } catch (S3Exception $e) {
216
+            \OCP\Util::logException('files_external', $e);
217
+            return false;
218
+        }
219
+        return true;
220
+    }
221
+
222
+    public function opendir($path) {
223
+        $path = $this->normalizePath($path);
224
+
225
+        if ($this->isRoot($path)) {
226
+            $path = '';
227
+        } else {
228
+            $path .= '/';
229
+        }
230
+
231
+        try {
232
+            $files = array();
233
+            $result = $this->getConnection()->getIterator('ListObjects', array(
234
+                'Bucket' => $this->bucket,
235
+                'Delimiter' => '/',
236
+                'Prefix' => $path
237
+            ), array('return_prefixes' => true));
238
+
239
+            foreach ($result as $object) {
240
+                if (isset($object['Key']) && $object['Key'] === $path) {
241
+                    // it's the directory itself, skip
242
+                    continue;
243
+                }
244
+                $file = basename(
245
+                    isset($object['Key']) ? $object['Key'] : $object['Prefix']
246
+                );
247
+                $files[] = $file;
248
+            }
249
+
250
+            return IteratorDirectory::wrap($files);
251
+        } catch (S3Exception $e) {
252
+            \OCP\Util::logException('files_external', $e);
253
+            return false;
254
+        }
255
+    }
256
+
257
+    public function stat($path) {
258
+        $path = $this->normalizePath($path);
259
+
260
+        try {
261
+            $stat = array();
262
+            if ($this->is_dir($path)) {
263
+                //folders don't really exist
264
+                $stat['size'] = -1; //unknown
265
+                $stat['mtime'] = time() - $this->rescanDelay * 1000;
266
+            } else {
267
+                $result = $this->getConnection()->headObject(array(
268
+                    'Bucket' => $this->bucket,
269
+                    'Key' => $path
270
+                ));
271
+
272
+                $stat['size'] = $result['ContentLength'] ? $result['ContentLength'] : 0;
273
+                if ($result['Metadata']['lastmodified']) {
274
+                    $stat['mtime'] = strtotime($result['Metadata']['lastmodified']);
275
+                } else {
276
+                    $stat['mtime'] = strtotime($result['LastModified']);
277
+                }
278
+            }
279
+            $stat['atime'] = time();
280
+
281
+            return $stat;
282
+        } catch(S3Exception $e) {
283
+            \OCP\Util::logException('files_external', $e);
284
+            return false;
285
+        }
286
+    }
287
+
288
+    public function filetype($path) {
289
+        $path = $this->normalizePath($path);
290
+
291
+        if ($this->isRoot($path)) {
292
+            return 'dir';
293
+        }
294
+
295
+        try {
296
+            if ($this->getConnection()->doesObjectExist($this->bucket, $path)) {
297
+                return 'file';
298
+            }
299
+            if ($this->getConnection()->doesObjectExist($this->bucket, $path.'/')) {
300
+                return 'dir';
301
+            }
302
+        } catch (S3Exception $e) {
303
+            \OCP\Util::logException('files_external', $e);
304
+            return false;
305
+        }
306
+
307
+        return false;
308
+    }
309
+
310
+    public function unlink($path) {
311
+        $path = $this->normalizePath($path);
312
+
313
+        if ($this->is_dir($path)) {
314
+            return $this->rmdir($path);
315
+        }
316
+
317
+        try {
318
+            $this->getConnection()->deleteObject(array(
319
+                'Bucket' => $this->bucket,
320
+                'Key' => $path
321
+            ));
322
+            $this->testTimeout();
323
+        } catch (S3Exception $e) {
324
+            \OCP\Util::logException('files_external', $e);
325
+            return false;
326
+        }
327
+
328
+        return true;
329
+    }
330
+
331
+    public function fopen($path, $mode) {
332
+        $path = $this->normalizePath($path);
333
+
334
+        switch ($mode) {
335
+            case 'r':
336
+            case 'rb':
337
+                $tmpFile = \OCP\Files::tmpFile();
338
+                self::$tmpFiles[$tmpFile] = $path;
339
+
340
+                try {
341
+                    $this->getConnection()->getObject(array(
342
+                        'Bucket' => $this->bucket,
343
+                        'Key' => $path,
344
+                        'SaveAs' => $tmpFile
345
+                    ));
346
+                } catch (S3Exception $e) {
347
+                    \OCP\Util::logException('files_external', $e);
348
+                    return false;
349
+                }
350
+
351
+                return fopen($tmpFile, 'r');
352
+            case 'w':
353
+            case 'wb':
354
+            case 'a':
355
+            case 'ab':
356
+            case 'r+':
357
+            case 'w+':
358
+            case 'wb+':
359
+            case 'a+':
360
+            case 'x':
361
+            case 'x+':
362
+            case 'c':
363
+            case 'c+':
364
+                if (strrpos($path, '.') !== false) {
365
+                    $ext = substr($path, strrpos($path, '.'));
366
+                } else {
367
+                    $ext = '';
368
+                }
369
+                $tmpFile = \OCP\Files::tmpFile($ext);
370
+                if ($this->file_exists($path)) {
371
+                    $source = $this->fopen($path, 'r');
372
+                    file_put_contents($tmpFile, $source);
373
+                }
374
+
375
+                $handle = fopen($tmpFile, $mode);
376
+                return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
377
+                    $this->writeBack($tmpFile, $path);
378
+                });
379
+        }
380
+        return false;
381
+    }
382
+
383
+    public function touch($path, $mtime = null) {
384
+        $path = $this->normalizePath($path);
385
+
386
+        $metadata = array();
387
+        if (is_null($mtime)) {
388
+            $mtime = time();
389
+        }
390
+        $metadata = [
391
+            'lastmodified' => gmdate(\Aws\Common\Enum\DateFormat::RFC1123, $mtime)
392
+        ];
393
+
394
+        $fileType = $this->filetype($path);
395
+        try {
396
+            if ($fileType !== false) {
397
+                if ($fileType === 'dir' && ! $this->isRoot($path)) {
398
+                    $path .= '/';
399
+                }
400
+                $this->getConnection()->copyObject([
401
+                    'Bucket' => $this->bucket,
402
+                    'Key' => $this->cleanKey($path),
403
+                    'Metadata' => $metadata,
404
+                    'CopySource' => $this->bucket . '/' . $path,
405
+                    'MetadataDirective' => 'REPLACE',
406
+                ]);
407
+                $this->testTimeout();
408
+            } else {
409
+                $mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
410
+                $this->getConnection()->putObject([
411
+                    'Bucket' => $this->bucket,
412
+                    'Key' => $this->cleanKey($path),
413
+                    'Metadata' => $metadata,
414
+                    'Body' => '',
415
+                    'ContentType' => $mimeType,
416
+                    'MetadataDirective' => 'REPLACE',
417
+                ]);
418
+                $this->testTimeout();
419
+            }
420
+        } catch (S3Exception $e) {
421
+            \OCP\Util::logException('files_external', $e);
422
+            return false;
423
+        }
424
+
425
+        return true;
426
+    }
427
+
428
+    public function copy($path1, $path2) {
429
+        $path1 = $this->normalizePath($path1);
430
+        $path2 = $this->normalizePath($path2);
431
+
432
+        if ($this->is_file($path1)) {
433
+            try {
434
+                $this->getConnection()->copyObject(array(
435
+                    'Bucket' => $this->bucket,
436
+                    'Key' => $this->cleanKey($path2),
437
+                    'CopySource' => S3Client::encodeKey($this->bucket . '/' . $path1)
438
+                ));
439
+                $this->testTimeout();
440
+            } catch (S3Exception $e) {
441
+                \OCP\Util::logException('files_external', $e);
442
+                return false;
443
+            }
444
+        } else {
445
+            $this->remove($path2);
446
+
447
+            try {
448
+                $this->getConnection()->copyObject(array(
449
+                    'Bucket' => $this->bucket,
450
+                    'Key' => $path2 . '/',
451
+                    'CopySource' => S3Client::encodeKey($this->bucket . '/' . $path1 . '/')
452
+                ));
453
+                $this->testTimeout();
454
+            } catch (S3Exception $e) {
455
+                \OCP\Util::logException('files_external', $e);
456
+                return false;
457
+            }
458
+
459
+            $dh = $this->opendir($path1);
460
+            if (is_resource($dh)) {
461
+                while (($file = readdir($dh)) !== false) {
462
+                    if (\OC\Files\Filesystem::isIgnoredDir($file)) {
463
+                        continue;
464
+                    }
465
+
466
+                    $source = $path1 . '/' . $file;
467
+                    $target = $path2 . '/' . $file;
468
+                    $this->copy($source, $target);
469
+                }
470
+            }
471
+        }
472
+
473
+        return true;
474
+    }
475
+
476
+    public function rename($path1, $path2) {
477
+        $path1 = $this->normalizePath($path1);
478
+        $path2 = $this->normalizePath($path2);
479
+
480
+        if ($this->is_file($path1)) {
481
+
482
+            if ($this->copy($path1, $path2) === false) {
483
+                return false;
484
+            }
485
+
486
+            if ($this->unlink($path1) === false) {
487
+                $this->unlink($path2);
488
+                return false;
489
+            }
490
+        } else {
491
+
492
+            if ($this->copy($path1, $path2) === false) {
493
+                return false;
494
+            }
495
+
496
+            if ($this->rmdir($path1) === false) {
497
+                $this->rmdir($path2);
498
+                return false;
499
+            }
500
+        }
501
+
502
+        return true;
503
+    }
504
+
505
+    public function test() {
506
+        $test = $this->getConnection()->getBucketAcl(array(
507
+            'Bucket' => $this->bucket,
508
+        ));
509
+        if (isset($test) && !is_null($test->getPath('Owner/ID'))) {
510
+            return true;
511
+        }
512
+        return false;
513
+    }
514
+
515
+    public function getId() {
516
+        return $this->id;
517
+    }
518
+
519
+    public function writeBack($tmpFile, $path) {
520
+        try {
521
+            $this->getConnection()->putObject(array(
522
+                'Bucket' => $this->bucket,
523
+                'Key' => $this->cleanKey($path),
524
+                'SourceFile' => $tmpFile,
525
+                'ContentType' => \OC::$server->getMimeTypeDetector()->detect($tmpFile),
526
+                'ContentLength' => filesize($tmpFile)
527
+            ));
528
+            $this->testTimeout();
529
+
530
+            unlink($tmpFile);
531
+        } catch (S3Exception $e) {
532
+            \OCP\Util::logException('files_external', $e);
533
+            return false;
534
+        }
535
+    }
536
+
537
+    /**
538
+     * check if curl is installed
539
+     */
540
+    public static function checkDependencies() {
541
+        return true;
542
+    }
543 543
 
544 544
 }
Please login to merge, or discard this patch.
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -36,8 +36,8 @@  discard block
 block discarded – undo
36 36
 
37 37
 namespace OCA\Files_External\Lib\Storage;
38 38
 
39
-set_include_path(get_include_path() . PATH_SEPARATOR .
40
-	\OC_App::getAppPath('files_external') . '/3rdparty/aws-sdk-php');
39
+set_include_path(get_include_path().PATH_SEPARATOR.
40
+	\OC_App::getAppPath('files_external').'/3rdparty/aws-sdk-php');
41 41
 require_once 'aws-autoloader.php';
42 42
 
43 43
 use Aws\S3\S3Client;
@@ -95,8 +95,8 @@  discard block
 block discarded – undo
95 95
 	 *
96 96
 	 * @param array $params
97 97
 	 */
98
-	public function updateLegacyId (array $params) {
99
-		$oldId = 'amazon::' . $params['key'] . md5($params['secret']);
98
+	public function updateLegacyId(array $params) {
99
+		$oldId = 'amazon::'.$params['key'].md5($params['secret']);
100 100
 
101 101
 		// find by old id or bucket
102 102
 		$stmt = \OC::$server->getDatabaseConnection()->prepare(
@@ -148,7 +148,7 @@  discard block
 block discarded – undo
148 148
 		try {
149 149
 			$this->getConnection()->putObject(array(
150 150
 				'Bucket' => $this->bucket,
151
-				'Key' => $path . '/',
151
+				'Key' => $path.'/',
152 152
 				'Body' => '',
153 153
 				'ContentType' => 'httpd/unix-directory'
154 154
 			));
@@ -191,12 +191,12 @@  discard block
 block discarded – undo
191 191
 		return false;
192 192
 	}
193 193
 
194
-	private function batchDelete ($path = null) {
194
+	private function batchDelete($path = null) {
195 195
 		$params = array(
196 196
 			'Bucket' => $this->bucket
197 197
 		);
198 198
 		if ($path !== null) {
199
-			$params['Prefix'] = $path . '/';
199
+			$params['Prefix'] = $path.'/';
200 200
 		}
201 201
 		try {
202 202
 			// Since there are no real directories on S3, we need
@@ -279,7 +279,7 @@  discard block
 block discarded – undo
279 279
 			$stat['atime'] = time();
280 280
 
281 281
 			return $stat;
282
-		} catch(S3Exception $e) {
282
+		} catch (S3Exception $e) {
283 283
 			\OCP\Util::logException('files_external', $e);
284 284
 			return false;
285 285
 		}
@@ -394,14 +394,14 @@  discard block
 block discarded – undo
394 394
 		$fileType = $this->filetype($path);
395 395
 		try {
396 396
 			if ($fileType !== false) {
397
-				if ($fileType === 'dir' && ! $this->isRoot($path)) {
397
+				if ($fileType === 'dir' && !$this->isRoot($path)) {
398 398
 					$path .= '/';
399 399
 				}
400 400
 				$this->getConnection()->copyObject([
401 401
 					'Bucket' => $this->bucket,
402 402
 					'Key' => $this->cleanKey($path),
403 403
 					'Metadata' => $metadata,
404
-					'CopySource' => $this->bucket . '/' . $path,
404
+					'CopySource' => $this->bucket.'/'.$path,
405 405
 					'MetadataDirective' => 'REPLACE',
406 406
 				]);
407 407
 				$this->testTimeout();
@@ -434,7 +434,7 @@  discard block
 block discarded – undo
434 434
 				$this->getConnection()->copyObject(array(
435 435
 					'Bucket' => $this->bucket,
436 436
 					'Key' => $this->cleanKey($path2),
437
-					'CopySource' => S3Client::encodeKey($this->bucket . '/' . $path1)
437
+					'CopySource' => S3Client::encodeKey($this->bucket.'/'.$path1)
438 438
 				));
439 439
 				$this->testTimeout();
440 440
 			} catch (S3Exception $e) {
@@ -447,8 +447,8 @@  discard block
 block discarded – undo
447 447
 			try {
448 448
 				$this->getConnection()->copyObject(array(
449 449
 					'Bucket' => $this->bucket,
450
-					'Key' => $path2 . '/',
451
-					'CopySource' => S3Client::encodeKey($this->bucket . '/' . $path1 . '/')
450
+					'Key' => $path2.'/',
451
+					'CopySource' => S3Client::encodeKey($this->bucket.'/'.$path1.'/')
452 452
 				));
453 453
 				$this->testTimeout();
454 454
 			} catch (S3Exception $e) {
@@ -463,8 +463,8 @@  discard block
 block discarded – undo
463 463
 						continue;
464 464
 					}
465 465
 
466
-					$source = $path1 . '/' . $file;
467
-					$target = $path2 . '/' . $file;
466
+					$source = $path1.'/'.$file;
467
+					$target = $path2.'/'.$file;
468 468
 					$this->copy($source, $target);
469 469
 				}
470 470
 			}
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/Storage/Dropbox.php 3 patches
Doc Comments   +6 added lines patch added patch discarded remove patch
@@ -76,6 +76,9 @@  discard block
 block discarded – undo
76 76
 		return false;
77 77
 	}
78 78
 
79
+	/**
80
+	 * @param string $path
81
+	 */
79 82
 	private function setMetaData($path, $metaData) {
80 83
 		$this->metaData[ltrim($path, '/')] = $metaData;
81 84
 	}
@@ -316,6 +319,9 @@  discard block
 block discarded – undo
316 319
 		return false;
317 320
 	}
318 321
 
322
+	/**
323
+	 * @param string $path
324
+	 */
319 325
 	public function writeBack($tmpFile, $path) {
320 326
 		$handle = fopen($tmpFile, 'r');
321 327
 		try {
Please login to merge, or discard this patch.
Indentation   +290 added lines, -290 removed lines patch added patch discarded remove patch
@@ -40,317 +40,317 @@
 block discarded – undo
40 40
 
41 41
 class Dropbox extends \OC\Files\Storage\Common {
42 42
 
43
-	private $dropbox;
44
-	private $root;
45
-	private $id;
46
-	private $metaData = array();
47
-	private $oauth;
43
+    private $dropbox;
44
+    private $root;
45
+    private $id;
46
+    private $metaData = array();
47
+    private $oauth;
48 48
 
49
-	public function __construct($params) {
50
-		if (isset($params['configured']) && $params['configured'] == 'true'
51
-			&& isset($params['app_key'])
52
-			&& isset($params['app_secret'])
53
-			&& isset($params['token'])
54
-			&& isset($params['token_secret'])
55
-		) {
56
-			$this->root = isset($params['root']) ? $params['root'] : '';
57
-			$this->id = 'dropbox::'.$params['app_key'] . $params['token']. '/' . $this->root;
58
-			$this->oauth = new \Dropbox_OAuth_Curl($params['app_key'], $params['app_secret']);
59
-			$this->oauth->setToken($params['token'], $params['token_secret']);
60
-			// note: Dropbox_API connection is lazy
61
-			$this->dropbox = new \Dropbox_API($this->oauth, 'auto');
62
-		} else {
63
-			throw new \Exception('Creating Dropbox storage failed');
64
-		}
65
-	}
49
+    public function __construct($params) {
50
+        if (isset($params['configured']) && $params['configured'] == 'true'
51
+            && isset($params['app_key'])
52
+            && isset($params['app_secret'])
53
+            && isset($params['token'])
54
+            && isset($params['token_secret'])
55
+        ) {
56
+            $this->root = isset($params['root']) ? $params['root'] : '';
57
+            $this->id = 'dropbox::'.$params['app_key'] . $params['token']. '/' . $this->root;
58
+            $this->oauth = new \Dropbox_OAuth_Curl($params['app_key'], $params['app_secret']);
59
+            $this->oauth->setToken($params['token'], $params['token_secret']);
60
+            // note: Dropbox_API connection is lazy
61
+            $this->dropbox = new \Dropbox_API($this->oauth, 'auto');
62
+        } else {
63
+            throw new \Exception('Creating Dropbox storage failed');
64
+        }
65
+    }
66 66
 
67
-	/**
68
-	 * @param string $path
69
-	 */
70
-	private function deleteMetaData($path) {
71
-		$path = ltrim($this->root.$path, '/');
72
-		if (isset($this->metaData[$path])) {
73
-			unset($this->metaData[$path]);
74
-			return true;
75
-		}
76
-		return false;
77
-	}
67
+    /**
68
+     * @param string $path
69
+     */
70
+    private function deleteMetaData($path) {
71
+        $path = ltrim($this->root.$path, '/');
72
+        if (isset($this->metaData[$path])) {
73
+            unset($this->metaData[$path]);
74
+            return true;
75
+        }
76
+        return false;
77
+    }
78 78
 
79
-	private function setMetaData($path, $metaData) {
80
-		$this->metaData[ltrim($path, '/')] = $metaData;
81
-	}
79
+    private function setMetaData($path, $metaData) {
80
+        $this->metaData[ltrim($path, '/')] = $metaData;
81
+    }
82 82
 
83
-	/**
84
-	 * Returns the path's metadata
85
-	 * @param string $path path for which to return the metadata
86
-	 * @param bool $list if true, also return the directory's contents
87
-	 * @return mixed directory contents if $list is true, file metadata if $list is
88
-	 * false, null if the file doesn't exist or "false" if the operation failed
89
-	 */
90
-	private function getDropBoxMetaData($path, $list = false) {
91
-		$path = ltrim($this->root.$path, '/');
92
-		if ( ! $list && isset($this->metaData[$path])) {
93
-			return $this->metaData[$path];
94
-		} else {
95
-			if ($list) {
96
-				try {
97
-					$response = $this->dropbox->getMetaData($path);
98
-				} catch (\Dropbox_Exception_Forbidden $e) {
99
-					throw new StorageNotAvailableException('Dropbox API rate limit exceeded', StorageNotAvailableException::STATUS_ERROR, $e);
100
-				} catch (\Exception $exception) {
101
-					\OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
102
-					return false;
103
-				}
104
-				$contents = array();
105
-				if ($response && isset($response['contents'])) {
106
-					// Cache folder's contents
107
-					foreach ($response['contents'] as $file) {
108
-						if (!isset($file['is_deleted']) || !$file['is_deleted']) {
109
-							$this->setMetaData($path.'/'.basename($file['path']), $file);
110
-							$contents[] = $file;
111
-						}
112
-					}
113
-					unset($response['contents']);
114
-				}
115
-				if (!isset($response['is_deleted']) || !$response['is_deleted']) {
116
-					$this->setMetaData($path, $response);
117
-				}
118
-				// Return contents of folder only
119
-				return $contents;
120
-			} else {
121
-				try {
122
-					$requestPath = $path;
123
-					if ($path === '.') {
124
-						$requestPath = '';
125
-					}
83
+    /**
84
+     * Returns the path's metadata
85
+     * @param string $path path for which to return the metadata
86
+     * @param bool $list if true, also return the directory's contents
87
+     * @return mixed directory contents if $list is true, file metadata if $list is
88
+     * false, null if the file doesn't exist or "false" if the operation failed
89
+     */
90
+    private function getDropBoxMetaData($path, $list = false) {
91
+        $path = ltrim($this->root.$path, '/');
92
+        if ( ! $list && isset($this->metaData[$path])) {
93
+            return $this->metaData[$path];
94
+        } else {
95
+            if ($list) {
96
+                try {
97
+                    $response = $this->dropbox->getMetaData($path);
98
+                } catch (\Dropbox_Exception_Forbidden $e) {
99
+                    throw new StorageNotAvailableException('Dropbox API rate limit exceeded', StorageNotAvailableException::STATUS_ERROR, $e);
100
+                } catch (\Exception $exception) {
101
+                    \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
102
+                    return false;
103
+                }
104
+                $contents = array();
105
+                if ($response && isset($response['contents'])) {
106
+                    // Cache folder's contents
107
+                    foreach ($response['contents'] as $file) {
108
+                        if (!isset($file['is_deleted']) || !$file['is_deleted']) {
109
+                            $this->setMetaData($path.'/'.basename($file['path']), $file);
110
+                            $contents[] = $file;
111
+                        }
112
+                    }
113
+                    unset($response['contents']);
114
+                }
115
+                if (!isset($response['is_deleted']) || !$response['is_deleted']) {
116
+                    $this->setMetaData($path, $response);
117
+                }
118
+                // Return contents of folder only
119
+                return $contents;
120
+            } else {
121
+                try {
122
+                    $requestPath = $path;
123
+                    if ($path === '.') {
124
+                        $requestPath = '';
125
+                    }
126 126
 
127
-					$response = $this->dropbox->getMetaData($requestPath, 'false');
128
-					if (!isset($response['is_deleted']) || !$response['is_deleted']) {
129
-						$this->setMetaData($path, $response);
130
-						return $response;
131
-					}
132
-					return null;
133
-				} catch (\Dropbox_Exception_Forbidden $e) {
134
-					throw new StorageNotAvailableException('Dropbox API rate limit exceeded', StorageNotAvailableException::STATUS_ERROR, $e);
135
-				} catch (\Exception $exception) {
136
-					if ($exception instanceof \Dropbox_Exception_NotFound) {
137
-						// don't log, might be a file_exist check
138
-						return false;
139
-					}
140
-					\OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
141
-					return false;
142
-				}
143
-			}
144
-		}
145
-	}
127
+                    $response = $this->dropbox->getMetaData($requestPath, 'false');
128
+                    if (!isset($response['is_deleted']) || !$response['is_deleted']) {
129
+                        $this->setMetaData($path, $response);
130
+                        return $response;
131
+                    }
132
+                    return null;
133
+                } catch (\Dropbox_Exception_Forbidden $e) {
134
+                    throw new StorageNotAvailableException('Dropbox API rate limit exceeded', StorageNotAvailableException::STATUS_ERROR, $e);
135
+                } catch (\Exception $exception) {
136
+                    if ($exception instanceof \Dropbox_Exception_NotFound) {
137
+                        // don't log, might be a file_exist check
138
+                        return false;
139
+                    }
140
+                    \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
141
+                    return false;
142
+                }
143
+            }
144
+        }
145
+    }
146 146
 
147
-	public function getId(){
148
-		return $this->id;
149
-	}
147
+    public function getId(){
148
+        return $this->id;
149
+    }
150 150
 
151
-	public function mkdir($path) {
152
-		$path = $this->root.$path;
153
-		try {
154
-			$this->dropbox->createFolder($path);
155
-			return true;
156
-		} catch (\Exception $exception) {
157
-			\OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
158
-			return false;
159
-		}
160
-	}
151
+    public function mkdir($path) {
152
+        $path = $this->root.$path;
153
+        try {
154
+            $this->dropbox->createFolder($path);
155
+            return true;
156
+        } catch (\Exception $exception) {
157
+            \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
158
+            return false;
159
+        }
160
+    }
161 161
 
162
-	public function rmdir($path) {
163
-		return $this->unlink($path);
164
-	}
162
+    public function rmdir($path) {
163
+        return $this->unlink($path);
164
+    }
165 165
 
166
-	public function opendir($path) {
167
-		$contents = $this->getDropBoxMetaData($path, true);
168
-		if ($contents !== false) {
169
-			$files = array();
170
-			foreach ($contents as $file) {
171
-				$files[] = basename($file['path']);
172
-			}
173
-			return IteratorDirectory::wrap($files);
174
-		}
175
-		return false;
176
-	}
166
+    public function opendir($path) {
167
+        $contents = $this->getDropBoxMetaData($path, true);
168
+        if ($contents !== false) {
169
+            $files = array();
170
+            foreach ($contents as $file) {
171
+                $files[] = basename($file['path']);
172
+            }
173
+            return IteratorDirectory::wrap($files);
174
+        }
175
+        return false;
176
+    }
177 177
 
178
-	public function stat($path) {
179
-		$metaData = $this->getDropBoxMetaData($path);
180
-		if ($metaData) {
181
-			$stat['size'] = $metaData['bytes'];
182
-			$stat['atime'] = time();
183
-			$stat['mtime'] = (isset($metaData['modified'])) ? strtotime($metaData['modified']) : time();
184
-			return $stat;
185
-		}
186
-		return false;
187
-	}
178
+    public function stat($path) {
179
+        $metaData = $this->getDropBoxMetaData($path);
180
+        if ($metaData) {
181
+            $stat['size'] = $metaData['bytes'];
182
+            $stat['atime'] = time();
183
+            $stat['mtime'] = (isset($metaData['modified'])) ? strtotime($metaData['modified']) : time();
184
+            return $stat;
185
+        }
186
+        return false;
187
+    }
188 188
 
189
-	public function filetype($path) {
190
-		if ($path == '' || $path == '/') {
191
-			return 'dir';
192
-		} else {
193
-			$metaData = $this->getDropBoxMetaData($path);
194
-			if ($metaData) {
195
-				if ($metaData['is_dir'] == 'true') {
196
-					return 'dir';
197
-				} else {
198
-					return 'file';
199
-				}
200
-			}
201
-		}
202
-		return false;
203
-	}
189
+    public function filetype($path) {
190
+        if ($path == '' || $path == '/') {
191
+            return 'dir';
192
+        } else {
193
+            $metaData = $this->getDropBoxMetaData($path);
194
+            if ($metaData) {
195
+                if ($metaData['is_dir'] == 'true') {
196
+                    return 'dir';
197
+                } else {
198
+                    return 'file';
199
+                }
200
+            }
201
+        }
202
+        return false;
203
+    }
204 204
 
205
-	public function file_exists($path) {
206
-		if ($path == '' || $path == '/') {
207
-			return true;
208
-		}
209
-		if ($this->getDropBoxMetaData($path)) {
210
-			return true;
211
-		}
212
-		return false;
213
-	}
205
+    public function file_exists($path) {
206
+        if ($path == '' || $path == '/') {
207
+            return true;
208
+        }
209
+        if ($this->getDropBoxMetaData($path)) {
210
+            return true;
211
+        }
212
+        return false;
213
+    }
214 214
 
215
-	public function unlink($path) {
216
-		try {
217
-			$this->dropbox->delete($this->root.$path);
218
-			$this->deleteMetaData($path);
219
-			return true;
220
-		} catch (\Exception $exception) {
221
-			\OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
222
-			return false;
223
-		}
224
-	}
215
+    public function unlink($path) {
216
+        try {
217
+            $this->dropbox->delete($this->root.$path);
218
+            $this->deleteMetaData($path);
219
+            return true;
220
+        } catch (\Exception $exception) {
221
+            \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
222
+            return false;
223
+        }
224
+    }
225 225
 
226
-	public function rename($path1, $path2) {
227
-		try {
228
-			// overwrite if target file exists and is not a directory
229
-			$destMetaData = $this->getDropBoxMetaData($path2);
230
-			if (isset($destMetaData) && $destMetaData !== false && !$destMetaData['is_dir']) {
231
-				$this->unlink($path2);
232
-			}
233
-			$this->dropbox->move($this->root.$path1, $this->root.$path2);
234
-			$this->deleteMetaData($path1);
235
-			return true;
236
-		} catch (\Exception $exception) {
237
-			\OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
238
-			return false;
239
-		}
240
-	}
226
+    public function rename($path1, $path2) {
227
+        try {
228
+            // overwrite if target file exists and is not a directory
229
+            $destMetaData = $this->getDropBoxMetaData($path2);
230
+            if (isset($destMetaData) && $destMetaData !== false && !$destMetaData['is_dir']) {
231
+                $this->unlink($path2);
232
+            }
233
+            $this->dropbox->move($this->root.$path1, $this->root.$path2);
234
+            $this->deleteMetaData($path1);
235
+            return true;
236
+        } catch (\Exception $exception) {
237
+            \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
238
+            return false;
239
+        }
240
+    }
241 241
 
242
-	public function copy($path1, $path2) {
243
-		$path1 = $this->root.$path1;
244
-		$path2 = $this->root.$path2;
245
-		try {
246
-			$this->dropbox->copy($path1, $path2);
247
-			return true;
248
-		} catch (\Exception $exception) {
249
-			\OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
250
-			return false;
251
-		}
252
-	}
242
+    public function copy($path1, $path2) {
243
+        $path1 = $this->root.$path1;
244
+        $path2 = $this->root.$path2;
245
+        try {
246
+            $this->dropbox->copy($path1, $path2);
247
+            return true;
248
+        } catch (\Exception $exception) {
249
+            \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
250
+            return false;
251
+        }
252
+    }
253 253
 
254
-	public function fopen($path, $mode) {
255
-		$path = $this->root.$path;
256
-		switch ($mode) {
257
-			case 'r':
258
-			case 'rb':
259
-				try {
260
-					// slashes need to stay
261
-					$encodedPath = str_replace('%2F', '/', rawurlencode(trim($path, '/')));
262
-					$downloadUrl = 'https://api-content.dropbox.com/1/files/auto/' . $encodedPath;
263
-					$headers = $this->oauth->getOAuthHeader($downloadUrl, [], 'GET');
254
+    public function fopen($path, $mode) {
255
+        $path = $this->root.$path;
256
+        switch ($mode) {
257
+            case 'r':
258
+            case 'rb':
259
+                try {
260
+                    // slashes need to stay
261
+                    $encodedPath = str_replace('%2F', '/', rawurlencode(trim($path, '/')));
262
+                    $downloadUrl = 'https://api-content.dropbox.com/1/files/auto/' . $encodedPath;
263
+                    $headers = $this->oauth->getOAuthHeader($downloadUrl, [], 'GET');
264 264
 
265
-					$client = \OC::$server->getHTTPClientService()->newClient();
266
-					try {
267
-						$response = $client->get($downloadUrl, [
268
-							'headers' => $headers,
269
-							'stream' => true,
270
-						]);
271
-					} catch (RequestException $e) {
272
-						if (!is_null($e->getResponse())) {
273
-							if ($e->getResponse()->getStatusCode() === 404) {
274
-								return false;
275
-							} else {
276
-								throw $e;
277
-							}
278
-						} else {
279
-							throw $e;
280
-						}
281
-					}
265
+                    $client = \OC::$server->getHTTPClientService()->newClient();
266
+                    try {
267
+                        $response = $client->get($downloadUrl, [
268
+                            'headers' => $headers,
269
+                            'stream' => true,
270
+                        ]);
271
+                    } catch (RequestException $e) {
272
+                        if (!is_null($e->getResponse())) {
273
+                            if ($e->getResponse()->getStatusCode() === 404) {
274
+                                return false;
275
+                            } else {
276
+                                throw $e;
277
+                            }
278
+                        } else {
279
+                            throw $e;
280
+                        }
281
+                    }
282 282
 
283
-					$handle = $response->getBody();
284
-					return RetryWrapper::wrap($handle);
285
-				} catch (\Exception $exception) {
286
-					\OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
287
-					return false;
288
-				}
289
-			case 'w':
290
-			case 'wb':
291
-			case 'a':
292
-			case 'ab':
293
-			case 'r+':
294
-			case 'w+':
295
-			case 'wb+':
296
-			case 'a+':
297
-			case 'x':
298
-			case 'x+':
299
-			case 'c':
300
-			case 'c+':
301
-				if (strrpos($path, '.') !== false) {
302
-					$ext = substr($path, strrpos($path, '.'));
303
-				} else {
304
-					$ext = '';
305
-				}
306
-				$tmpFile = \OCP\Files::tmpFile($ext);
307
-				if ($this->file_exists($path)) {
308
-					$source = $this->fopen($path, 'r');
309
-					file_put_contents($tmpFile, $source);
310
-				}
311
-			$handle = fopen($tmpFile, $mode);
312
-			return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
313
-				$this->writeBack($tmpFile, $path);
314
-			});
315
-		}
316
-		return false;
317
-	}
283
+                    $handle = $response->getBody();
284
+                    return RetryWrapper::wrap($handle);
285
+                } catch (\Exception $exception) {
286
+                    \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
287
+                    return false;
288
+                }
289
+            case 'w':
290
+            case 'wb':
291
+            case 'a':
292
+            case 'ab':
293
+            case 'r+':
294
+            case 'w+':
295
+            case 'wb+':
296
+            case 'a+':
297
+            case 'x':
298
+            case 'x+':
299
+            case 'c':
300
+            case 'c+':
301
+                if (strrpos($path, '.') !== false) {
302
+                    $ext = substr($path, strrpos($path, '.'));
303
+                } else {
304
+                    $ext = '';
305
+                }
306
+                $tmpFile = \OCP\Files::tmpFile($ext);
307
+                if ($this->file_exists($path)) {
308
+                    $source = $this->fopen($path, 'r');
309
+                    file_put_contents($tmpFile, $source);
310
+                }
311
+            $handle = fopen($tmpFile, $mode);
312
+            return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
313
+                $this->writeBack($tmpFile, $path);
314
+            });
315
+        }
316
+        return false;
317
+    }
318 318
 
319
-	public function writeBack($tmpFile, $path) {
320
-		$handle = fopen($tmpFile, 'r');
321
-		try {
322
-			$this->dropbox->putFile($path, $handle);
323
-			unlink($tmpFile);
324
-			$this->deleteMetaData($path);
325
-		} catch (\Exception $exception) {
326
-			\OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
327
-		}
328
-	}
319
+    public function writeBack($tmpFile, $path) {
320
+        $handle = fopen($tmpFile, 'r');
321
+        try {
322
+            $this->dropbox->putFile($path, $handle);
323
+            unlink($tmpFile);
324
+            $this->deleteMetaData($path);
325
+        } catch (\Exception $exception) {
326
+            \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
327
+        }
328
+    }
329 329
 
330
-	public function free_space($path) {
331
-		try {
332
-			$info = $this->dropbox->getAccountInfo();
333
-			return $info['quota_info']['quota'] - $info['quota_info']['normal'];
334
-		} catch (\Exception $exception) {
335
-			\OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
336
-			return false;
337
-		}
338
-	}
330
+    public function free_space($path) {
331
+        try {
332
+            $info = $this->dropbox->getAccountInfo();
333
+            return $info['quota_info']['quota'] - $info['quota_info']['normal'];
334
+        } catch (\Exception $exception) {
335
+            \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
336
+            return false;
337
+        }
338
+    }
339 339
 
340
-	public function touch($path, $mtime = null) {
341
-		if ($this->file_exists($path)) {
342
-			return false;
343
-		} else {
344
-			$this->file_put_contents($path, '');
345
-		}
346
-		return true;
347
-	}
340
+    public function touch($path, $mtime = null) {
341
+        if ($this->file_exists($path)) {
342
+            return false;
343
+        } else {
344
+            $this->file_put_contents($path, '');
345
+        }
346
+        return true;
347
+    }
348 348
 
349
-	/**
350
-	 * check if curl is installed
351
-	 */
352
-	public static function checkDependencies() {
353
-		return true;
354
-	}
349
+    /**
350
+     * check if curl is installed
351
+     */
352
+    public static function checkDependencies() {
353
+        return true;
354
+    }
355 355
 
356 356
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -36,7 +36,7 @@  discard block
 block discarded – undo
36 36
 use Icewind\Streams\RetryWrapper;
37 37
 use OCP\Files\StorageNotAvailableException;
38 38
 
39
-require_once __DIR__ . '/../../../3rdparty/Dropbox/autoload.php';
39
+require_once __DIR__.'/../../../3rdparty/Dropbox/autoload.php';
40 40
 
41 41
 class Dropbox extends \OC\Files\Storage\Common {
42 42
 
@@ -54,7 +54,7 @@  discard block
 block discarded – undo
54 54
 			&& isset($params['token_secret'])
55 55
 		) {
56 56
 			$this->root = isset($params['root']) ? $params['root'] : '';
57
-			$this->id = 'dropbox::'.$params['app_key'] . $params['token']. '/' . $this->root;
57
+			$this->id = 'dropbox::'.$params['app_key'].$params['token'].'/'.$this->root;
58 58
 			$this->oauth = new \Dropbox_OAuth_Curl($params['app_key'], $params['app_secret']);
59 59
 			$this->oauth->setToken($params['token'], $params['token_secret']);
60 60
 			// note: Dropbox_API connection is lazy
@@ -89,7 +89,7 @@  discard block
 block discarded – undo
89 89
 	 */
90 90
 	private function getDropBoxMetaData($path, $list = false) {
91 91
 		$path = ltrim($this->root.$path, '/');
92
-		if ( ! $list && isset($this->metaData[$path])) {
92
+		if (!$list && isset($this->metaData[$path])) {
93 93
 			return $this->metaData[$path];
94 94
 		} else {
95 95
 			if ($list) {
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
 		}
145 145
 	}
146 146
 
147
-	public function getId(){
147
+	public function getId() {
148 148
 		return $this->id;
149 149
 	}
150 150
 
@@ -259,7 +259,7 @@  discard block
 block discarded – undo
259 259
 				try {
260 260
 					// slashes need to stay
261 261
 					$encodedPath = str_replace('%2F', '/', rawurlencode(trim($path, '/')));
262
-					$downloadUrl = 'https://api-content.dropbox.com/1/files/auto/' . $encodedPath;
262
+					$downloadUrl = 'https://api-content.dropbox.com/1/files/auto/'.$encodedPath;
263 263
 					$headers = $this->oauth->getOAuthHeader($downloadUrl, [], 'GET');
264 264
 
265 265
 					$client = \OC::$server->getHTTPClientService()->newClient();
@@ -309,7 +309,7 @@  discard block
 block discarded – undo
309 309
 					file_put_contents($tmpFile, $source);
310 310
 				}
311 311
 			$handle = fopen($tmpFile, $mode);
312
-			return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
312
+			return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
313 313
 				$this->writeBack($tmpFile, $path);
314 314
 			});
315 315
 		}
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/Storage/Google.php 3 patches
Doc Comments   +4 added lines, -1 removed lines patch added patch discarded remove patch
@@ -216,7 +216,7 @@  discard block
 block discarded – undo
216 216
 	 *
217 217
 	 * @param \Google_Service_Drive_DriveFile
218 218
 	 *
219
-	 * @return true if the file is a Google Doc file, false otherwise
219
+	 * @return boolean if the file is a Google Doc file, false otherwise
220 220
 	 */
221 221
 	private function isGoogleDocFile($file) {
222 222
 		return $this->getGoogleDocExtension($file->getMimeType()) !== '';
@@ -505,6 +505,9 @@  discard block
 block discarded – undo
505 505
 		}
506 506
 	}
507 507
 
508
+	/**
509
+	 * @param string $path
510
+	 */
508 511
 	public function writeBack($tmpFile, $path) {
509 512
 		$parentFolder = $this->getDriveFile(dirname($path));
510 513
 		if ($parentFolder) {
Please login to merge, or discard this patch.
Indentation   +675 added lines, -675 removed lines patch added patch discarded remove patch
@@ -41,684 +41,684 @@
 block discarded – undo
41 41
 use Icewind\Streams\RetryWrapper;
42 42
 
43 43
 set_include_path(get_include_path().PATH_SEPARATOR.
44
-	\OC_App::getAppPath('files_external').'/3rdparty/google-api-php-client/src');
44
+    \OC_App::getAppPath('files_external').'/3rdparty/google-api-php-client/src');
45 45
 require_once 'Google/autoload.php';
46 46
 
47 47
 class Google extends \OC\Files\Storage\Common {
48 48
 
49
-	private $client;
50
-	private $id;
51
-	private $service;
52
-	private $driveFiles;
53
-
54
-	// Google Doc mimetypes
55
-	const FOLDER = 'application/vnd.google-apps.folder';
56
-	const DOCUMENT = 'application/vnd.google-apps.document';
57
-	const SPREADSHEET = 'application/vnd.google-apps.spreadsheet';
58
-	const DRAWING = 'application/vnd.google-apps.drawing';
59
-	const PRESENTATION = 'application/vnd.google-apps.presentation';
60
-	const MAP = 'application/vnd.google-apps.map';
61
-
62
-	public function __construct($params) {
63
-		if (isset($params['configured']) && $params['configured'] === 'true'
64
-			&& isset($params['client_id']) && isset($params['client_secret'])
65
-			&& isset($params['token'])
66
-		) {
67
-			$this->client = new \Google_Client();
68
-			$this->client->setClientId($params['client_id']);
69
-			$this->client->setClientSecret($params['client_secret']);
70
-			$this->client->setScopes(array('https://www.googleapis.com/auth/drive'));
71
-			$this->client->setAccessToken($params['token']);
72
-			// if curl isn't available we're likely to run into
73
-			// https://github.com/google/google-api-php-client/issues/59
74
-			// - disable gzip to avoid it.
75
-			if (!function_exists('curl_version') || !function_exists('curl_exec')) {
76
-				$this->client->setClassConfig("Google_Http_Request", "disable_gzip", true);
77
-			}
78
-			// note: API connection is lazy
79
-			$this->service = new \Google_Service_Drive($this->client);
80
-			$token = json_decode($params['token'], true);
81
-			$this->id = 'google::'.substr($params['client_id'], 0, 30).$token['created'];
82
-		} else {
83
-			throw new \Exception('Creating Google storage failed');
84
-		}
85
-	}
86
-
87
-	public function getId() {
88
-		return $this->id;
89
-	}
90
-
91
-	/**
92
-	 * Get the Google_Service_Drive_DriveFile object for the specified path.
93
-	 * Returns false on failure.
94
-	 * @param string $path
95
-	 * @return \Google_Service_Drive_DriveFile|false
96
-	 */
97
-	private function getDriveFile($path) {
98
-		// Remove leading and trailing slashes
99
-		$path = trim($path, '/');
100
-		if ($path === '.') {
101
-			$path = '';
102
-		}
103
-		if (isset($this->driveFiles[$path])) {
104
-			return $this->driveFiles[$path];
105
-		} else if ($path === '') {
106
-			$root = $this->service->files->get('root');
107
-			$this->driveFiles[$path] = $root;
108
-			return $root;
109
-		} else {
110
-			// Google Drive SDK does not have methods for retrieving files by path
111
-			// Instead we must find the id of the parent folder of the file
112
-			$parentId = $this->getDriveFile('')->getId();
113
-			$folderNames = explode('/', $path);
114
-			$path = '';
115
-			// Loop through each folder of this path to get to the file
116
-			foreach ($folderNames as $name) {
117
-				// Reconstruct path from beginning
118
-				if ($path === '') {
119
-					$path .= $name;
120
-				} else {
121
-					$path .= '/'.$name;
122
-				}
123
-				if (isset($this->driveFiles[$path])) {
124
-					$parentId = $this->driveFiles[$path]->getId();
125
-				} else {
126
-					$q = "title='" . str_replace("'","\\'", $name) . "' and '" . str_replace("'","\\'", $parentId) . "' in parents and trashed = false";
127
-					$result = $this->service->files->listFiles(array('q' => $q))->getItems();
128
-					if (!empty($result)) {
129
-						// Google Drive allows files with the same name, ownCloud doesn't
130
-						if (count($result) > 1) {
131
-							$this->onDuplicateFileDetected($path);
132
-							return false;
133
-						} else {
134
-							$file = current($result);
135
-							$this->driveFiles[$path] = $file;
136
-							$parentId = $file->getId();
137
-						}
138
-					} else {
139
-						// Google Docs have no extension in their title, so try without extension
140
-						$pos = strrpos($path, '.');
141
-						if ($pos !== false) {
142
-							$pathWithoutExt = substr($path, 0, $pos);
143
-							$file = $this->getDriveFile($pathWithoutExt);
144
-							if ($file && $this->isGoogleDocFile($file)) {
145
-								// Switch cached Google_Service_Drive_DriveFile to the correct index
146
-								unset($this->driveFiles[$pathWithoutExt]);
147
-								$this->driveFiles[$path] = $file;
148
-								$parentId = $file->getId();
149
-							} else {
150
-								return false;
151
-							}
152
-						} else {
153
-							return false;
154
-						}
155
-					}
156
-				}
157
-			}
158
-			return $this->driveFiles[$path];
159
-		}
160
-	}
161
-
162
-	/**
163
-	 * Set the Google_Service_Drive_DriveFile object in the cache
164
-	 * @param string $path
165
-	 * @param \Google_Service_Drive_DriveFile|false $file
166
-	 */
167
-	private function setDriveFile($path, $file) {
168
-		$path = trim($path, '/');
169
-		$this->driveFiles[$path] = $file;
170
-		if ($file === false) {
171
-			// Remove all children
172
-			$len = strlen($path);
173
-			foreach ($this->driveFiles as $key => $file) {
174
-				if (substr($key, 0, $len) === $path) {
175
-					unset($this->driveFiles[$key]);
176
-				}
177
-			}
178
-		}
179
-	}
180
-
181
-	/**
182
-	 * Write a log message to inform about duplicate file names
183
-	 * @param string $path
184
-	 */
185
-	private function onDuplicateFileDetected($path) {
186
-		$about = $this->service->about->get();
187
-		$user = $about->getName();
188
-		\OCP\Util::writeLog('files_external',
189
-			'Ignoring duplicate file name: '.$path.' on Google Drive for Google user: '.$user,
190
-			\OCP\Util::INFO
191
-		);
192
-	}
193
-
194
-	/**
195
-	 * Generate file extension for a Google Doc, choosing Open Document formats for download
196
-	 * @param string $mimetype
197
-	 * @return string
198
-	 */
199
-	private function getGoogleDocExtension($mimetype) {
200
-		if ($mimetype === self::DOCUMENT) {
201
-			return 'odt';
202
-		} else if ($mimetype === self::SPREADSHEET) {
203
-			return 'ods';
204
-		} else if ($mimetype === self::DRAWING) {
205
-			return 'jpg';
206
-		} else if ($mimetype === self::PRESENTATION) {
207
-			// Download as .odp is not available
208
-			return 'pdf';
209
-		} else {
210
-			return '';
211
-		}
212
-	}
213
-
214
-	/**
215
-	 * Returns whether the given drive file is a Google Doc file
216
-	 *
217
-	 * @param \Google_Service_Drive_DriveFile
218
-	 *
219
-	 * @return true if the file is a Google Doc file, false otherwise
220
-	 */
221
-	private function isGoogleDocFile($file) {
222
-		return $this->getGoogleDocExtension($file->getMimeType()) !== '';
223
-	}
224
-
225
-	public function mkdir($path) {
226
-		if (!$this->is_dir($path)) {
227
-			$parentFolder = $this->getDriveFile(dirname($path));
228
-			if ($parentFolder) {
229
-				$folder = new \Google_Service_Drive_DriveFile();
230
-				$folder->setTitle(basename($path));
231
-				$folder->setMimeType(self::FOLDER);
232
-				$parent = new \Google_Service_Drive_ParentReference();
233
-				$parent->setId($parentFolder->getId());
234
-				$folder->setParents(array($parent));
235
-				$result = $this->service->files->insert($folder);
236
-				if ($result) {
237
-					$this->setDriveFile($path, $result);
238
-				}
239
-				return (bool)$result;
240
-			}
241
-		}
242
-		return false;
243
-	}
244
-
245
-	public function rmdir($path) {
246
-		if (!$this->isDeletable($path)) {
247
-			return false;
248
-		}
249
-		if (trim($path, '/') === '') {
250
-			$dir = $this->opendir($path);
251
-			if(is_resource($dir)) {
252
-				while (($file = readdir($dir)) !== false) {
253
-					if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
254
-						if (!$this->unlink($path.'/'.$file)) {
255
-							return false;
256
-						}
257
-					}
258
-				}
259
-				closedir($dir);
260
-			}
261
-			$this->driveFiles = array();
262
-			return true;
263
-		} else {
264
-			return $this->unlink($path);
265
-		}
266
-	}
267
-
268
-	public function opendir($path) {
269
-		$folder = $this->getDriveFile($path);
270
-		if ($folder) {
271
-			$files = array();
272
-			$duplicates = array();
273
-			$pageToken = true;
274
-			while ($pageToken) {
275
-				$params = array();
276
-				if ($pageToken !== true) {
277
-					$params['pageToken'] = $pageToken;
278
-				}
279
-				$params['q'] = "'" . str_replace("'","\\'", $folder->getId()) . "' in parents and trashed = false";
280
-				$children = $this->service->files->listFiles($params);
281
-				foreach ($children->getItems() as $child) {
282
-					$name = $child->getTitle();
283
-					// Check if this is a Google Doc i.e. no extension in name
284
-					$extension = $child->getFileExtension();
285
-					if (empty($extension)) {
286
-						if ($child->getMimeType() === self::MAP) {
287
-							continue; // No method known to transfer map files, ignore it
288
-						} else if ($child->getMimeType() !== self::FOLDER) {
289
-							$name .= '.'.$this->getGoogleDocExtension($child->getMimeType());
290
-						}
291
-					}
292
-					if ($path === '') {
293
-						$filepath = $name;
294
-					} else {
295
-						$filepath = $path.'/'.$name;
296
-					}
297
-					// Google Drive allows files with the same name, ownCloud doesn't
298
-					// Prevent opendir() from returning any duplicate files
299
-					$key = array_search($name, $files);
300
-					if ($key !== false || isset($duplicates[$filepath])) {
301
-						if (!isset($duplicates[$filepath])) {
302
-							$duplicates[$filepath] = true;
303
-							$this->setDriveFile($filepath, false);
304
-							unset($files[$key]);
305
-							$this->onDuplicateFileDetected($filepath);
306
-						}
307
-					} else {
308
-						// Cache the Google_Service_Drive_DriveFile for future use
309
-						$this->setDriveFile($filepath, $child);
310
-						$files[] = $name;
311
-					}
312
-				}
313
-				$pageToken = $children->getNextPageToken();
314
-			}
315
-			return IteratorDirectory::wrap($files);
316
-		} else {
317
-			return false;
318
-		}
319
-	}
320
-
321
-	public function stat($path) {
322
-		$file = $this->getDriveFile($path);
323
-		if ($file) {
324
-			$stat = array();
325
-			if ($this->filetype($path) === 'dir') {
326
-				$stat['size'] = 0;
327
-			} else {
328
-				// Check if this is a Google Doc
329
-				if ($this->isGoogleDocFile($file)) {
330
-					// Return unknown file size
331
-					$stat['size'] = \OCP\Files\FileInfo::SPACE_UNKNOWN;
332
-				} else {
333
-					$stat['size'] = $file->getFileSize();
334
-				}
335
-			}
336
-			$stat['atime'] = strtotime($file->getLastViewedByMeDate());
337
-			$stat['mtime'] = strtotime($file->getModifiedDate());
338
-			$stat['ctime'] = strtotime($file->getCreatedDate());
339
-			return $stat;
340
-		} else {
341
-			return false;
342
-		}
343
-	}
344
-
345
-	public function filetype($path) {
346
-		if ($path === '') {
347
-			return 'dir';
348
-		} else {
349
-			$file = $this->getDriveFile($path);
350
-			if ($file) {
351
-				if ($file->getMimeType() === self::FOLDER) {
352
-					return 'dir';
353
-				} else {
354
-					return 'file';
355
-				}
356
-			} else {
357
-				return false;
358
-			}
359
-		}
360
-	}
361
-
362
-	public function isUpdatable($path) {
363
-		$file = $this->getDriveFile($path);
364
-		if ($file) {
365
-			return $file->getEditable();
366
-		} else {
367
-			return false;
368
-		}
369
-	}
370
-
371
-	public function file_exists($path) {
372
-		return (bool)$this->getDriveFile($path);
373
-	}
374
-
375
-	public function unlink($path) {
376
-		$file = $this->getDriveFile($path);
377
-		if ($file) {
378
-			$result = $this->service->files->trash($file->getId());
379
-			if ($result) {
380
-				$this->setDriveFile($path, false);
381
-			}
382
-			return (bool)$result;
383
-		} else {
384
-			return false;
385
-		}
386
-	}
387
-
388
-	public function rename($path1, $path2) {
389
-		$file = $this->getDriveFile($path1);
390
-		if ($file) {
391
-			$newFile = $this->getDriveFile($path2);
392
-			if (dirname($path1) === dirname($path2)) {
393
-				if ($newFile) {
394
-					// rename to the name of the target file, could be an office file without extension
395
-					$file->setTitle($newFile->getTitle());
396
-				} else {
397
-					$file->setTitle(basename(($path2)));
398
-				}
399
-			} else {
400
-				// Change file parent
401
-				$parentFolder2 = $this->getDriveFile(dirname($path2));
402
-				if ($parentFolder2) {
403
-					$parent = new \Google_Service_Drive_ParentReference();
404
-					$parent->setId($parentFolder2->getId());
405
-					$file->setParents(array($parent));
406
-				} else {
407
-					return false;
408
-				}
409
-			}
410
-			// We need to get the object for the existing file with the same
411
-			// name (if there is one) before we do the patch. If oldfile
412
-			// exists and is a directory we have to delete it before we
413
-			// do the rename too.
414
-			$oldfile = $this->getDriveFile($path2);
415
-			if ($oldfile && $this->is_dir($path2)) {
416
-				$this->rmdir($path2);
417
-				$oldfile = false;
418
-			}
419
-			$result = $this->service->files->patch($file->getId(), $file);
420
-			if ($result) {
421
-				$this->setDriveFile($path1, false);
422
-				$this->setDriveFile($path2, $result);
423
-				if ($oldfile && $newFile) {
424
-					// only delete if they have a different id (same id can happen for part files)
425
-					if ($newFile->getId() !== $oldfile->getId()) {
426
-						$this->service->files->delete($oldfile->getId());
427
-					}
428
-				}
429
-			}
430
-			return (bool)$result;
431
-		} else {
432
-			return false;
433
-		}
434
-	}
435
-
436
-	public function fopen($path, $mode) {
437
-		$pos = strrpos($path, '.');
438
-		if ($pos !== false) {
439
-			$ext = substr($path, $pos);
440
-		} else {
441
-			$ext = '';
442
-		}
443
-		switch ($mode) {
444
-			case 'r':
445
-			case 'rb':
446
-				$file = $this->getDriveFile($path);
447
-				if ($file) {
448
-					$exportLinks = $file->getExportLinks();
449
-					$mimetype = $this->getMimeType($path);
450
-					$downloadUrl = null;
451
-					if ($exportLinks && isset($exportLinks[$mimetype])) {
452
-						$downloadUrl = $exportLinks[$mimetype];
453
-					} else {
454
-						$downloadUrl = $file->getDownloadUrl();
455
-					}
456
-					if (isset($downloadUrl)) {
457
-						$request = new \Google_Http_Request($downloadUrl, 'GET', null, null);
458
-						$httpRequest = $this->client->getAuth()->sign($request);
459
-						// the library's service doesn't support streaming, so we use Guzzle instead
460
-						$client = \OC::$server->getHTTPClientService()->newClient();
461
-						try {
462
-							$response = $client->get($downloadUrl, [
463
-								'headers' => $httpRequest->getRequestHeaders(),
464
-								'stream' => true,
465
-								'verify' => realpath(__DIR__ . '/../../../3rdparty/google-api-php-client/src/Google/IO/cacerts.pem'),
466
-							]);
467
-						} catch (RequestException $e) {
468
-							if(!is_null($e->getResponse())) {
469
-								if ($e->getResponse()->getStatusCode() === 404) {
470
-									return false;
471
-								} else {
472
-									throw $e;
473
-								}
474
-							} else {
475
-								throw $e;
476
-							}
477
-						}
478
-
479
-						$handle = $response->getBody();
480
-						return RetryWrapper::wrap($handle);
481
-					}
482
-				}
483
-				return false;
484
-			case 'w':
485
-			case 'wb':
486
-			case 'a':
487
-			case 'ab':
488
-			case 'r+':
489
-			case 'w+':
490
-			case 'wb+':
491
-			case 'a+':
492
-			case 'x':
493
-			case 'x+':
494
-			case 'c':
495
-			case 'c+':
496
-				$tmpFile = \OCP\Files::tmpFile($ext);
497
-				if ($this->file_exists($path)) {
498
-					$source = $this->fopen($path, 'rb');
499
-					file_put_contents($tmpFile, $source);
500
-				}
501
-				$handle = fopen($tmpFile, $mode);
502
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
503
-					$this->writeBack($tmpFile, $path);
504
-				});
505
-		}
506
-	}
507
-
508
-	public function writeBack($tmpFile, $path) {
509
-		$parentFolder = $this->getDriveFile(dirname($path));
510
-		if ($parentFolder) {
511
-			$mimetype = \OC::$server->getMimeTypeDetector()->detect($tmpFile);
512
-			$params = array(
513
-				'mimeType' => $mimetype,
514
-				'uploadType' => 'media'
515
-			);
516
-			$result = false;
517
-
518
-			$chunkSizeBytes = 10 * 1024 * 1024;
519
-
520
-			$useChunking = false;
521
-			$size = filesize($tmpFile);
522
-			if ($size > $chunkSizeBytes) {
523
-				$useChunking = true;
524
-			} else {
525
-				$params['data'] = file_get_contents($tmpFile);
526
-			}
527
-
528
-			if ($this->file_exists($path)) {
529
-				$file = $this->getDriveFile($path);
530
-				$this->client->setDefer($useChunking);
531
-				$request = $this->service->files->update($file->getId(), $file, $params);
532
-			} else {
533
-				$file = new \Google_Service_Drive_DriveFile();
534
-				$file->setTitle(basename($path));
535
-				$file->setMimeType($mimetype);
536
-				$parent = new \Google_Service_Drive_ParentReference();
537
-				$parent->setId($parentFolder->getId());
538
-				$file->setParents(array($parent));
539
-				$this->client->setDefer($useChunking);
540
-				$request = $this->service->files->insert($file, $params);
541
-			}
542
-
543
-			if ($useChunking) {
544
-				// Create a media file upload to represent our upload process.
545
-				$media = new \Google_Http_MediaFileUpload(
546
-					$this->client,
547
-					$request,
548
-					'text/plain',
549
-					null,
550
-					true,
551
-					$chunkSizeBytes
552
-				);
553
-				$media->setFileSize($size);
554
-
555
-				// Upload the various chunks. $status will be false until the process is
556
-				// complete.
557
-				$status = false;
558
-				$handle = fopen($tmpFile, 'rb');
559
-				while (!$status && !feof($handle)) {
560
-					$chunk = fread($handle, $chunkSizeBytes);
561
-					$status = $media->nextChunk($chunk);
562
-				}
563
-
564
-				// The final value of $status will be the data from the API for the object
565
-				// that has been uploaded.
566
-				$result = false;
567
-				if ($status !== false) {
568
-					$result = $status;
569
-				}
570
-
571
-				fclose($handle);
572
-			} else {
573
-				$result = $request;
574
-			}
575
-
576
-			// Reset to the client to execute requests immediately in the future.
577
-			$this->client->setDefer(false);
578
-
579
-			if ($result) {
580
-				$this->setDriveFile($path, $result);
581
-			}
582
-		}
583
-	}
584
-
585
-	public function getMimeType($path) {
586
-		$file = $this->getDriveFile($path);
587
-		if ($file) {
588
-			$mimetype = $file->getMimeType();
589
-			// Convert Google Doc mimetypes, choosing Open Document formats for download
590
-			if ($mimetype === self::FOLDER) {
591
-				return 'httpd/unix-directory';
592
-			} else if ($mimetype === self::DOCUMENT) {
593
-				return 'application/vnd.oasis.opendocument.text';
594
-			} else if ($mimetype === self::SPREADSHEET) {
595
-				return 'application/x-vnd.oasis.opendocument.spreadsheet';
596
-			} else if ($mimetype === self::DRAWING) {
597
-				return 'image/jpeg';
598
-			} else if ($mimetype === self::PRESENTATION) {
599
-				// Download as .odp is not available
600
-				return 'application/pdf';
601
-			} else {
602
-				// use extension-based detection, could be an encrypted file
603
-				return parent::getMimeType($path);
604
-			}
605
-		} else {
606
-			return false;
607
-		}
608
-	}
609
-
610
-	public function free_space($path) {
611
-		$about = $this->service->about->get();
612
-		return $about->getQuotaBytesTotal() - $about->getQuotaBytesUsed();
613
-	}
614
-
615
-	public function touch($path, $mtime = null) {
616
-		$file = $this->getDriveFile($path);
617
-		$result = false;
618
-		if ($file) {
619
-			if (isset($mtime)) {
620
-				// This is just RFC3339, but frustratingly, GDrive's API *requires*
621
-				// the fractions portion be present, while no handy PHP constant
622
-				// for RFC3339 or ISO8601 includes it. So we do it ourselves.
623
-				$file->setModifiedDate(date('Y-m-d\TH:i:s.uP', $mtime));
624
-				$result = $this->service->files->patch($file->getId(), $file, array(
625
-					'setModifiedDate' => true,
626
-				));
627
-			} else {
628
-				$result = $this->service->files->touch($file->getId());
629
-			}
630
-		} else {
631
-			$parentFolder = $this->getDriveFile(dirname($path));
632
-			if ($parentFolder) {
633
-				$file = new \Google_Service_Drive_DriveFile();
634
-				$file->setTitle(basename($path));
635
-				$parent = new \Google_Service_Drive_ParentReference();
636
-				$parent->setId($parentFolder->getId());
637
-				$file->setParents(array($parent));
638
-				$result = $this->service->files->insert($file);
639
-			}
640
-		}
641
-		if ($result) {
642
-			$this->setDriveFile($path, $result);
643
-		}
644
-		return (bool)$result;
645
-	}
646
-
647
-	public function test() {
648
-		if ($this->free_space('')) {
649
-			return true;
650
-		}
651
-		return false;
652
-	}
653
-
654
-	public function hasUpdated($path, $time) {
655
-		$appConfig = \OC::$server->getAppConfig();
656
-		if ($this->is_file($path)) {
657
-			return parent::hasUpdated($path, $time);
658
-		} else {
659
-			// Google Drive doesn't change modified times of folders when files inside are updated
660
-			// Instead we use the Changes API to see if folders have been updated, and it's a pain
661
-			$folder = $this->getDriveFile($path);
662
-			if ($folder) {
663
-				$result = false;
664
-				$folderId = $folder->getId();
665
-				$startChangeId = $appConfig->getValue('files_external', $this->getId().'cId');
666
-				$params = array(
667
-					'includeDeleted' => true,
668
-					'includeSubscribed' => true,
669
-				);
670
-				if (isset($startChangeId)) {
671
-					$startChangeId = (int)$startChangeId;
672
-					$largestChangeId = $startChangeId;
673
-					$params['startChangeId'] = $startChangeId + 1;
674
-				} else {
675
-					$largestChangeId = 0;
676
-				}
677
-				$pageToken = true;
678
-				while ($pageToken) {
679
-					if ($pageToken !== true) {
680
-						$params['pageToken'] = $pageToken;
681
-					}
682
-					$changes = $this->service->changes->listChanges($params);
683
-					if ($largestChangeId === 0 || $largestChangeId === $startChangeId) {
684
-						$largestChangeId = $changes->getLargestChangeId();
685
-					}
686
-					if (isset($startChangeId)) {
687
-						// Check if a file in this folder has been updated
688
-						// There is no way to filter by folder at the API level...
689
-						foreach ($changes->getItems() as $change) {
690
-							$file = $change->getFile();
691
-							if ($file) {
692
-								foreach ($file->getParents() as $parent) {
693
-									if ($parent->getId() === $folderId) {
694
-										$result = true;
695
-									// Check if there are changes in different folders
696
-									} else if ($change->getId() <= $largestChangeId) {
697
-										// Decrement id so this change is fetched when called again
698
-										$largestChangeId = $change->getId();
699
-										$largestChangeId--;
700
-									}
701
-								}
702
-							}
703
-						}
704
-						$pageToken = $changes->getNextPageToken();
705
-					} else {
706
-						// Assuming the initial scan just occurred and changes are negligible
707
-						break;
708
-					}
709
-				}
710
-				$appConfig->setValue('files_external', $this->getId().'cId', $largestChangeId);
711
-				return $result;
712
-			}
713
-		}
714
-		return false;
715
-	}
716
-
717
-	/**
718
-	 * check if curl is installed
719
-	 */
720
-	public static function checkDependencies() {
721
-		return true;
722
-	}
49
+    private $client;
50
+    private $id;
51
+    private $service;
52
+    private $driveFiles;
53
+
54
+    // Google Doc mimetypes
55
+    const FOLDER = 'application/vnd.google-apps.folder';
56
+    const DOCUMENT = 'application/vnd.google-apps.document';
57
+    const SPREADSHEET = 'application/vnd.google-apps.spreadsheet';
58
+    const DRAWING = 'application/vnd.google-apps.drawing';
59
+    const PRESENTATION = 'application/vnd.google-apps.presentation';
60
+    const MAP = 'application/vnd.google-apps.map';
61
+
62
+    public function __construct($params) {
63
+        if (isset($params['configured']) && $params['configured'] === 'true'
64
+            && isset($params['client_id']) && isset($params['client_secret'])
65
+            && isset($params['token'])
66
+        ) {
67
+            $this->client = new \Google_Client();
68
+            $this->client->setClientId($params['client_id']);
69
+            $this->client->setClientSecret($params['client_secret']);
70
+            $this->client->setScopes(array('https://www.googleapis.com/auth/drive'));
71
+            $this->client->setAccessToken($params['token']);
72
+            // if curl isn't available we're likely to run into
73
+            // https://github.com/google/google-api-php-client/issues/59
74
+            // - disable gzip to avoid it.
75
+            if (!function_exists('curl_version') || !function_exists('curl_exec')) {
76
+                $this->client->setClassConfig("Google_Http_Request", "disable_gzip", true);
77
+            }
78
+            // note: API connection is lazy
79
+            $this->service = new \Google_Service_Drive($this->client);
80
+            $token = json_decode($params['token'], true);
81
+            $this->id = 'google::'.substr($params['client_id'], 0, 30).$token['created'];
82
+        } else {
83
+            throw new \Exception('Creating Google storage failed');
84
+        }
85
+    }
86
+
87
+    public function getId() {
88
+        return $this->id;
89
+    }
90
+
91
+    /**
92
+     * Get the Google_Service_Drive_DriveFile object for the specified path.
93
+     * Returns false on failure.
94
+     * @param string $path
95
+     * @return \Google_Service_Drive_DriveFile|false
96
+     */
97
+    private function getDriveFile($path) {
98
+        // Remove leading and trailing slashes
99
+        $path = trim($path, '/');
100
+        if ($path === '.') {
101
+            $path = '';
102
+        }
103
+        if (isset($this->driveFiles[$path])) {
104
+            return $this->driveFiles[$path];
105
+        } else if ($path === '') {
106
+            $root = $this->service->files->get('root');
107
+            $this->driveFiles[$path] = $root;
108
+            return $root;
109
+        } else {
110
+            // Google Drive SDK does not have methods for retrieving files by path
111
+            // Instead we must find the id of the parent folder of the file
112
+            $parentId = $this->getDriveFile('')->getId();
113
+            $folderNames = explode('/', $path);
114
+            $path = '';
115
+            // Loop through each folder of this path to get to the file
116
+            foreach ($folderNames as $name) {
117
+                // Reconstruct path from beginning
118
+                if ($path === '') {
119
+                    $path .= $name;
120
+                } else {
121
+                    $path .= '/'.$name;
122
+                }
123
+                if (isset($this->driveFiles[$path])) {
124
+                    $parentId = $this->driveFiles[$path]->getId();
125
+                } else {
126
+                    $q = "title='" . str_replace("'","\\'", $name) . "' and '" . str_replace("'","\\'", $parentId) . "' in parents and trashed = false";
127
+                    $result = $this->service->files->listFiles(array('q' => $q))->getItems();
128
+                    if (!empty($result)) {
129
+                        // Google Drive allows files with the same name, ownCloud doesn't
130
+                        if (count($result) > 1) {
131
+                            $this->onDuplicateFileDetected($path);
132
+                            return false;
133
+                        } else {
134
+                            $file = current($result);
135
+                            $this->driveFiles[$path] = $file;
136
+                            $parentId = $file->getId();
137
+                        }
138
+                    } else {
139
+                        // Google Docs have no extension in their title, so try without extension
140
+                        $pos = strrpos($path, '.');
141
+                        if ($pos !== false) {
142
+                            $pathWithoutExt = substr($path, 0, $pos);
143
+                            $file = $this->getDriveFile($pathWithoutExt);
144
+                            if ($file && $this->isGoogleDocFile($file)) {
145
+                                // Switch cached Google_Service_Drive_DriveFile to the correct index
146
+                                unset($this->driveFiles[$pathWithoutExt]);
147
+                                $this->driveFiles[$path] = $file;
148
+                                $parentId = $file->getId();
149
+                            } else {
150
+                                return false;
151
+                            }
152
+                        } else {
153
+                            return false;
154
+                        }
155
+                    }
156
+                }
157
+            }
158
+            return $this->driveFiles[$path];
159
+        }
160
+    }
161
+
162
+    /**
163
+     * Set the Google_Service_Drive_DriveFile object in the cache
164
+     * @param string $path
165
+     * @param \Google_Service_Drive_DriveFile|false $file
166
+     */
167
+    private function setDriveFile($path, $file) {
168
+        $path = trim($path, '/');
169
+        $this->driveFiles[$path] = $file;
170
+        if ($file === false) {
171
+            // Remove all children
172
+            $len = strlen($path);
173
+            foreach ($this->driveFiles as $key => $file) {
174
+                if (substr($key, 0, $len) === $path) {
175
+                    unset($this->driveFiles[$key]);
176
+                }
177
+            }
178
+        }
179
+    }
180
+
181
+    /**
182
+     * Write a log message to inform about duplicate file names
183
+     * @param string $path
184
+     */
185
+    private function onDuplicateFileDetected($path) {
186
+        $about = $this->service->about->get();
187
+        $user = $about->getName();
188
+        \OCP\Util::writeLog('files_external',
189
+            'Ignoring duplicate file name: '.$path.' on Google Drive for Google user: '.$user,
190
+            \OCP\Util::INFO
191
+        );
192
+    }
193
+
194
+    /**
195
+     * Generate file extension for a Google Doc, choosing Open Document formats for download
196
+     * @param string $mimetype
197
+     * @return string
198
+     */
199
+    private function getGoogleDocExtension($mimetype) {
200
+        if ($mimetype === self::DOCUMENT) {
201
+            return 'odt';
202
+        } else if ($mimetype === self::SPREADSHEET) {
203
+            return 'ods';
204
+        } else if ($mimetype === self::DRAWING) {
205
+            return 'jpg';
206
+        } else if ($mimetype === self::PRESENTATION) {
207
+            // Download as .odp is not available
208
+            return 'pdf';
209
+        } else {
210
+            return '';
211
+        }
212
+    }
213
+
214
+    /**
215
+     * Returns whether the given drive file is a Google Doc file
216
+     *
217
+     * @param \Google_Service_Drive_DriveFile
218
+     *
219
+     * @return true if the file is a Google Doc file, false otherwise
220
+     */
221
+    private function isGoogleDocFile($file) {
222
+        return $this->getGoogleDocExtension($file->getMimeType()) !== '';
223
+    }
224
+
225
+    public function mkdir($path) {
226
+        if (!$this->is_dir($path)) {
227
+            $parentFolder = $this->getDriveFile(dirname($path));
228
+            if ($parentFolder) {
229
+                $folder = new \Google_Service_Drive_DriveFile();
230
+                $folder->setTitle(basename($path));
231
+                $folder->setMimeType(self::FOLDER);
232
+                $parent = new \Google_Service_Drive_ParentReference();
233
+                $parent->setId($parentFolder->getId());
234
+                $folder->setParents(array($parent));
235
+                $result = $this->service->files->insert($folder);
236
+                if ($result) {
237
+                    $this->setDriveFile($path, $result);
238
+                }
239
+                return (bool)$result;
240
+            }
241
+        }
242
+        return false;
243
+    }
244
+
245
+    public function rmdir($path) {
246
+        if (!$this->isDeletable($path)) {
247
+            return false;
248
+        }
249
+        if (trim($path, '/') === '') {
250
+            $dir = $this->opendir($path);
251
+            if(is_resource($dir)) {
252
+                while (($file = readdir($dir)) !== false) {
253
+                    if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
254
+                        if (!$this->unlink($path.'/'.$file)) {
255
+                            return false;
256
+                        }
257
+                    }
258
+                }
259
+                closedir($dir);
260
+            }
261
+            $this->driveFiles = array();
262
+            return true;
263
+        } else {
264
+            return $this->unlink($path);
265
+        }
266
+    }
267
+
268
+    public function opendir($path) {
269
+        $folder = $this->getDriveFile($path);
270
+        if ($folder) {
271
+            $files = array();
272
+            $duplicates = array();
273
+            $pageToken = true;
274
+            while ($pageToken) {
275
+                $params = array();
276
+                if ($pageToken !== true) {
277
+                    $params['pageToken'] = $pageToken;
278
+                }
279
+                $params['q'] = "'" . str_replace("'","\\'", $folder->getId()) . "' in parents and trashed = false";
280
+                $children = $this->service->files->listFiles($params);
281
+                foreach ($children->getItems() as $child) {
282
+                    $name = $child->getTitle();
283
+                    // Check if this is a Google Doc i.e. no extension in name
284
+                    $extension = $child->getFileExtension();
285
+                    if (empty($extension)) {
286
+                        if ($child->getMimeType() === self::MAP) {
287
+                            continue; // No method known to transfer map files, ignore it
288
+                        } else if ($child->getMimeType() !== self::FOLDER) {
289
+                            $name .= '.'.$this->getGoogleDocExtension($child->getMimeType());
290
+                        }
291
+                    }
292
+                    if ($path === '') {
293
+                        $filepath = $name;
294
+                    } else {
295
+                        $filepath = $path.'/'.$name;
296
+                    }
297
+                    // Google Drive allows files with the same name, ownCloud doesn't
298
+                    // Prevent opendir() from returning any duplicate files
299
+                    $key = array_search($name, $files);
300
+                    if ($key !== false || isset($duplicates[$filepath])) {
301
+                        if (!isset($duplicates[$filepath])) {
302
+                            $duplicates[$filepath] = true;
303
+                            $this->setDriveFile($filepath, false);
304
+                            unset($files[$key]);
305
+                            $this->onDuplicateFileDetected($filepath);
306
+                        }
307
+                    } else {
308
+                        // Cache the Google_Service_Drive_DriveFile for future use
309
+                        $this->setDriveFile($filepath, $child);
310
+                        $files[] = $name;
311
+                    }
312
+                }
313
+                $pageToken = $children->getNextPageToken();
314
+            }
315
+            return IteratorDirectory::wrap($files);
316
+        } else {
317
+            return false;
318
+        }
319
+    }
320
+
321
+    public function stat($path) {
322
+        $file = $this->getDriveFile($path);
323
+        if ($file) {
324
+            $stat = array();
325
+            if ($this->filetype($path) === 'dir') {
326
+                $stat['size'] = 0;
327
+            } else {
328
+                // Check if this is a Google Doc
329
+                if ($this->isGoogleDocFile($file)) {
330
+                    // Return unknown file size
331
+                    $stat['size'] = \OCP\Files\FileInfo::SPACE_UNKNOWN;
332
+                } else {
333
+                    $stat['size'] = $file->getFileSize();
334
+                }
335
+            }
336
+            $stat['atime'] = strtotime($file->getLastViewedByMeDate());
337
+            $stat['mtime'] = strtotime($file->getModifiedDate());
338
+            $stat['ctime'] = strtotime($file->getCreatedDate());
339
+            return $stat;
340
+        } else {
341
+            return false;
342
+        }
343
+    }
344
+
345
+    public function filetype($path) {
346
+        if ($path === '') {
347
+            return 'dir';
348
+        } else {
349
+            $file = $this->getDriveFile($path);
350
+            if ($file) {
351
+                if ($file->getMimeType() === self::FOLDER) {
352
+                    return 'dir';
353
+                } else {
354
+                    return 'file';
355
+                }
356
+            } else {
357
+                return false;
358
+            }
359
+        }
360
+    }
361
+
362
+    public function isUpdatable($path) {
363
+        $file = $this->getDriveFile($path);
364
+        if ($file) {
365
+            return $file->getEditable();
366
+        } else {
367
+            return false;
368
+        }
369
+    }
370
+
371
+    public function file_exists($path) {
372
+        return (bool)$this->getDriveFile($path);
373
+    }
374
+
375
+    public function unlink($path) {
376
+        $file = $this->getDriveFile($path);
377
+        if ($file) {
378
+            $result = $this->service->files->trash($file->getId());
379
+            if ($result) {
380
+                $this->setDriveFile($path, false);
381
+            }
382
+            return (bool)$result;
383
+        } else {
384
+            return false;
385
+        }
386
+    }
387
+
388
+    public function rename($path1, $path2) {
389
+        $file = $this->getDriveFile($path1);
390
+        if ($file) {
391
+            $newFile = $this->getDriveFile($path2);
392
+            if (dirname($path1) === dirname($path2)) {
393
+                if ($newFile) {
394
+                    // rename to the name of the target file, could be an office file without extension
395
+                    $file->setTitle($newFile->getTitle());
396
+                } else {
397
+                    $file->setTitle(basename(($path2)));
398
+                }
399
+            } else {
400
+                // Change file parent
401
+                $parentFolder2 = $this->getDriveFile(dirname($path2));
402
+                if ($parentFolder2) {
403
+                    $parent = new \Google_Service_Drive_ParentReference();
404
+                    $parent->setId($parentFolder2->getId());
405
+                    $file->setParents(array($parent));
406
+                } else {
407
+                    return false;
408
+                }
409
+            }
410
+            // We need to get the object for the existing file with the same
411
+            // name (if there is one) before we do the patch. If oldfile
412
+            // exists and is a directory we have to delete it before we
413
+            // do the rename too.
414
+            $oldfile = $this->getDriveFile($path2);
415
+            if ($oldfile && $this->is_dir($path2)) {
416
+                $this->rmdir($path2);
417
+                $oldfile = false;
418
+            }
419
+            $result = $this->service->files->patch($file->getId(), $file);
420
+            if ($result) {
421
+                $this->setDriveFile($path1, false);
422
+                $this->setDriveFile($path2, $result);
423
+                if ($oldfile && $newFile) {
424
+                    // only delete if they have a different id (same id can happen for part files)
425
+                    if ($newFile->getId() !== $oldfile->getId()) {
426
+                        $this->service->files->delete($oldfile->getId());
427
+                    }
428
+                }
429
+            }
430
+            return (bool)$result;
431
+        } else {
432
+            return false;
433
+        }
434
+    }
435
+
436
+    public function fopen($path, $mode) {
437
+        $pos = strrpos($path, '.');
438
+        if ($pos !== false) {
439
+            $ext = substr($path, $pos);
440
+        } else {
441
+            $ext = '';
442
+        }
443
+        switch ($mode) {
444
+            case 'r':
445
+            case 'rb':
446
+                $file = $this->getDriveFile($path);
447
+                if ($file) {
448
+                    $exportLinks = $file->getExportLinks();
449
+                    $mimetype = $this->getMimeType($path);
450
+                    $downloadUrl = null;
451
+                    if ($exportLinks && isset($exportLinks[$mimetype])) {
452
+                        $downloadUrl = $exportLinks[$mimetype];
453
+                    } else {
454
+                        $downloadUrl = $file->getDownloadUrl();
455
+                    }
456
+                    if (isset($downloadUrl)) {
457
+                        $request = new \Google_Http_Request($downloadUrl, 'GET', null, null);
458
+                        $httpRequest = $this->client->getAuth()->sign($request);
459
+                        // the library's service doesn't support streaming, so we use Guzzle instead
460
+                        $client = \OC::$server->getHTTPClientService()->newClient();
461
+                        try {
462
+                            $response = $client->get($downloadUrl, [
463
+                                'headers' => $httpRequest->getRequestHeaders(),
464
+                                'stream' => true,
465
+                                'verify' => realpath(__DIR__ . '/../../../3rdparty/google-api-php-client/src/Google/IO/cacerts.pem'),
466
+                            ]);
467
+                        } catch (RequestException $e) {
468
+                            if(!is_null($e->getResponse())) {
469
+                                if ($e->getResponse()->getStatusCode() === 404) {
470
+                                    return false;
471
+                                } else {
472
+                                    throw $e;
473
+                                }
474
+                            } else {
475
+                                throw $e;
476
+                            }
477
+                        }
478
+
479
+                        $handle = $response->getBody();
480
+                        return RetryWrapper::wrap($handle);
481
+                    }
482
+                }
483
+                return false;
484
+            case 'w':
485
+            case 'wb':
486
+            case 'a':
487
+            case 'ab':
488
+            case 'r+':
489
+            case 'w+':
490
+            case 'wb+':
491
+            case 'a+':
492
+            case 'x':
493
+            case 'x+':
494
+            case 'c':
495
+            case 'c+':
496
+                $tmpFile = \OCP\Files::tmpFile($ext);
497
+                if ($this->file_exists($path)) {
498
+                    $source = $this->fopen($path, 'rb');
499
+                    file_put_contents($tmpFile, $source);
500
+                }
501
+                $handle = fopen($tmpFile, $mode);
502
+                return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
503
+                    $this->writeBack($tmpFile, $path);
504
+                });
505
+        }
506
+    }
507
+
508
+    public function writeBack($tmpFile, $path) {
509
+        $parentFolder = $this->getDriveFile(dirname($path));
510
+        if ($parentFolder) {
511
+            $mimetype = \OC::$server->getMimeTypeDetector()->detect($tmpFile);
512
+            $params = array(
513
+                'mimeType' => $mimetype,
514
+                'uploadType' => 'media'
515
+            );
516
+            $result = false;
517
+
518
+            $chunkSizeBytes = 10 * 1024 * 1024;
519
+
520
+            $useChunking = false;
521
+            $size = filesize($tmpFile);
522
+            if ($size > $chunkSizeBytes) {
523
+                $useChunking = true;
524
+            } else {
525
+                $params['data'] = file_get_contents($tmpFile);
526
+            }
527
+
528
+            if ($this->file_exists($path)) {
529
+                $file = $this->getDriveFile($path);
530
+                $this->client->setDefer($useChunking);
531
+                $request = $this->service->files->update($file->getId(), $file, $params);
532
+            } else {
533
+                $file = new \Google_Service_Drive_DriveFile();
534
+                $file->setTitle(basename($path));
535
+                $file->setMimeType($mimetype);
536
+                $parent = new \Google_Service_Drive_ParentReference();
537
+                $parent->setId($parentFolder->getId());
538
+                $file->setParents(array($parent));
539
+                $this->client->setDefer($useChunking);
540
+                $request = $this->service->files->insert($file, $params);
541
+            }
542
+
543
+            if ($useChunking) {
544
+                // Create a media file upload to represent our upload process.
545
+                $media = new \Google_Http_MediaFileUpload(
546
+                    $this->client,
547
+                    $request,
548
+                    'text/plain',
549
+                    null,
550
+                    true,
551
+                    $chunkSizeBytes
552
+                );
553
+                $media->setFileSize($size);
554
+
555
+                // Upload the various chunks. $status will be false until the process is
556
+                // complete.
557
+                $status = false;
558
+                $handle = fopen($tmpFile, 'rb');
559
+                while (!$status && !feof($handle)) {
560
+                    $chunk = fread($handle, $chunkSizeBytes);
561
+                    $status = $media->nextChunk($chunk);
562
+                }
563
+
564
+                // The final value of $status will be the data from the API for the object
565
+                // that has been uploaded.
566
+                $result = false;
567
+                if ($status !== false) {
568
+                    $result = $status;
569
+                }
570
+
571
+                fclose($handle);
572
+            } else {
573
+                $result = $request;
574
+            }
575
+
576
+            // Reset to the client to execute requests immediately in the future.
577
+            $this->client->setDefer(false);
578
+
579
+            if ($result) {
580
+                $this->setDriveFile($path, $result);
581
+            }
582
+        }
583
+    }
584
+
585
+    public function getMimeType($path) {
586
+        $file = $this->getDriveFile($path);
587
+        if ($file) {
588
+            $mimetype = $file->getMimeType();
589
+            // Convert Google Doc mimetypes, choosing Open Document formats for download
590
+            if ($mimetype === self::FOLDER) {
591
+                return 'httpd/unix-directory';
592
+            } else if ($mimetype === self::DOCUMENT) {
593
+                return 'application/vnd.oasis.opendocument.text';
594
+            } else if ($mimetype === self::SPREADSHEET) {
595
+                return 'application/x-vnd.oasis.opendocument.spreadsheet';
596
+            } else if ($mimetype === self::DRAWING) {
597
+                return 'image/jpeg';
598
+            } else if ($mimetype === self::PRESENTATION) {
599
+                // Download as .odp is not available
600
+                return 'application/pdf';
601
+            } else {
602
+                // use extension-based detection, could be an encrypted file
603
+                return parent::getMimeType($path);
604
+            }
605
+        } else {
606
+            return false;
607
+        }
608
+    }
609
+
610
+    public function free_space($path) {
611
+        $about = $this->service->about->get();
612
+        return $about->getQuotaBytesTotal() - $about->getQuotaBytesUsed();
613
+    }
614
+
615
+    public function touch($path, $mtime = null) {
616
+        $file = $this->getDriveFile($path);
617
+        $result = false;
618
+        if ($file) {
619
+            if (isset($mtime)) {
620
+                // This is just RFC3339, but frustratingly, GDrive's API *requires*
621
+                // the fractions portion be present, while no handy PHP constant
622
+                // for RFC3339 or ISO8601 includes it. So we do it ourselves.
623
+                $file->setModifiedDate(date('Y-m-d\TH:i:s.uP', $mtime));
624
+                $result = $this->service->files->patch($file->getId(), $file, array(
625
+                    'setModifiedDate' => true,
626
+                ));
627
+            } else {
628
+                $result = $this->service->files->touch($file->getId());
629
+            }
630
+        } else {
631
+            $parentFolder = $this->getDriveFile(dirname($path));
632
+            if ($parentFolder) {
633
+                $file = new \Google_Service_Drive_DriveFile();
634
+                $file->setTitle(basename($path));
635
+                $parent = new \Google_Service_Drive_ParentReference();
636
+                $parent->setId($parentFolder->getId());
637
+                $file->setParents(array($parent));
638
+                $result = $this->service->files->insert($file);
639
+            }
640
+        }
641
+        if ($result) {
642
+            $this->setDriveFile($path, $result);
643
+        }
644
+        return (bool)$result;
645
+    }
646
+
647
+    public function test() {
648
+        if ($this->free_space('')) {
649
+            return true;
650
+        }
651
+        return false;
652
+    }
653
+
654
+    public function hasUpdated($path, $time) {
655
+        $appConfig = \OC::$server->getAppConfig();
656
+        if ($this->is_file($path)) {
657
+            return parent::hasUpdated($path, $time);
658
+        } else {
659
+            // Google Drive doesn't change modified times of folders when files inside are updated
660
+            // Instead we use the Changes API to see if folders have been updated, and it's a pain
661
+            $folder = $this->getDriveFile($path);
662
+            if ($folder) {
663
+                $result = false;
664
+                $folderId = $folder->getId();
665
+                $startChangeId = $appConfig->getValue('files_external', $this->getId().'cId');
666
+                $params = array(
667
+                    'includeDeleted' => true,
668
+                    'includeSubscribed' => true,
669
+                );
670
+                if (isset($startChangeId)) {
671
+                    $startChangeId = (int)$startChangeId;
672
+                    $largestChangeId = $startChangeId;
673
+                    $params['startChangeId'] = $startChangeId + 1;
674
+                } else {
675
+                    $largestChangeId = 0;
676
+                }
677
+                $pageToken = true;
678
+                while ($pageToken) {
679
+                    if ($pageToken !== true) {
680
+                        $params['pageToken'] = $pageToken;
681
+                    }
682
+                    $changes = $this->service->changes->listChanges($params);
683
+                    if ($largestChangeId === 0 || $largestChangeId === $startChangeId) {
684
+                        $largestChangeId = $changes->getLargestChangeId();
685
+                    }
686
+                    if (isset($startChangeId)) {
687
+                        // Check if a file in this folder has been updated
688
+                        // There is no way to filter by folder at the API level...
689
+                        foreach ($changes->getItems() as $change) {
690
+                            $file = $change->getFile();
691
+                            if ($file) {
692
+                                foreach ($file->getParents() as $parent) {
693
+                                    if ($parent->getId() === $folderId) {
694
+                                        $result = true;
695
+                                    // Check if there are changes in different folders
696
+                                    } else if ($change->getId() <= $largestChangeId) {
697
+                                        // Decrement id so this change is fetched when called again
698
+                                        $largestChangeId = $change->getId();
699
+                                        $largestChangeId--;
700
+                                    }
701
+                                }
702
+                            }
703
+                        }
704
+                        $pageToken = $changes->getNextPageToken();
705
+                    } else {
706
+                        // Assuming the initial scan just occurred and changes are negligible
707
+                        break;
708
+                    }
709
+                }
710
+                $appConfig->setValue('files_external', $this->getId().'cId', $largestChangeId);
711
+                return $result;
712
+            }
713
+        }
714
+        return false;
715
+    }
716
+
717
+    /**
718
+     * check if curl is installed
719
+     */
720
+    public static function checkDependencies() {
721
+        return true;
722
+    }
723 723
 
724 724
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
 				if (isset($this->driveFiles[$path])) {
124 124
 					$parentId = $this->driveFiles[$path]->getId();
125 125
 				} else {
126
-					$q = "title='" . str_replace("'","\\'", $name) . "' and '" . str_replace("'","\\'", $parentId) . "' in parents and trashed = false";
126
+					$q = "title='".str_replace("'", "\\'", $name)."' and '".str_replace("'", "\\'", $parentId)."' in parents and trashed = false";
127 127
 					$result = $this->service->files->listFiles(array('q' => $q))->getItems();
128 128
 					if (!empty($result)) {
129 129
 						// Google Drive allows files with the same name, ownCloud doesn't
@@ -236,7 +236,7 @@  discard block
 block discarded – undo
236 236
 				if ($result) {
237 237
 					$this->setDriveFile($path, $result);
238 238
 				}
239
-				return (bool)$result;
239
+				return (bool) $result;
240 240
 			}
241 241
 		}
242 242
 		return false;
@@ -248,7 +248,7 @@  discard block
 block discarded – undo
248 248
 		}
249 249
 		if (trim($path, '/') === '') {
250 250
 			$dir = $this->opendir($path);
251
-			if(is_resource($dir)) {
251
+			if (is_resource($dir)) {
252 252
 				while (($file = readdir($dir)) !== false) {
253 253
 					if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
254 254
 						if (!$this->unlink($path.'/'.$file)) {
@@ -276,7 +276,7 @@  discard block
 block discarded – undo
276 276
 				if ($pageToken !== true) {
277 277
 					$params['pageToken'] = $pageToken;
278 278
 				}
279
-				$params['q'] = "'" . str_replace("'","\\'", $folder->getId()) . "' in parents and trashed = false";
279
+				$params['q'] = "'".str_replace("'", "\\'", $folder->getId())."' in parents and trashed = false";
280 280
 				$children = $this->service->files->listFiles($params);
281 281
 				foreach ($children->getItems() as $child) {
282 282
 					$name = $child->getTitle();
@@ -369,7 +369,7 @@  discard block
 block discarded – undo
369 369
 	}
370 370
 
371 371
 	public function file_exists($path) {
372
-		return (bool)$this->getDriveFile($path);
372
+		return (bool) $this->getDriveFile($path);
373 373
 	}
374 374
 
375 375
 	public function unlink($path) {
@@ -379,7 +379,7 @@  discard block
 block discarded – undo
379 379
 			if ($result) {
380 380
 				$this->setDriveFile($path, false);
381 381
 			}
382
-			return (bool)$result;
382
+			return (bool) $result;
383 383
 		} else {
384 384
 			return false;
385 385
 		}
@@ -427,7 +427,7 @@  discard block
 block discarded – undo
427 427
 					}
428 428
 				}
429 429
 			}
430
-			return (bool)$result;
430
+			return (bool) $result;
431 431
 		} else {
432 432
 			return false;
433 433
 		}
@@ -462,10 +462,10 @@  discard block
 block discarded – undo
462 462
 							$response = $client->get($downloadUrl, [
463 463
 								'headers' => $httpRequest->getRequestHeaders(),
464 464
 								'stream' => true,
465
-								'verify' => realpath(__DIR__ . '/../../../3rdparty/google-api-php-client/src/Google/IO/cacerts.pem'),
465
+								'verify' => realpath(__DIR__.'/../../../3rdparty/google-api-php-client/src/Google/IO/cacerts.pem'),
466 466
 							]);
467 467
 						} catch (RequestException $e) {
468
-							if(!is_null($e->getResponse())) {
468
+							if (!is_null($e->getResponse())) {
469 469
 								if ($e->getResponse()->getStatusCode() === 404) {
470 470
 									return false;
471 471
 								} else {
@@ -499,7 +499,7 @@  discard block
 block discarded – undo
499 499
 					file_put_contents($tmpFile, $source);
500 500
 				}
501 501
 				$handle = fopen($tmpFile, $mode);
502
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
502
+				return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
503 503
 					$this->writeBack($tmpFile, $path);
504 504
 				});
505 505
 		}
@@ -641,7 +641,7 @@  discard block
 block discarded – undo
641 641
 		if ($result) {
642 642
 			$this->setDriveFile($path, $result);
643 643
 		}
644
-		return (bool)$result;
644
+		return (bool) $result;
645 645
 	}
646 646
 
647 647
 	public function test() {
@@ -668,7 +668,7 @@  discard block
 block discarded – undo
668 668
 					'includeSubscribed' => true,
669 669
 				);
670 670
 				if (isset($startChangeId)) {
671
-					$startChangeId = (int)$startChangeId;
671
+					$startChangeId = (int) $startChangeId;
672 672
 					$largestChangeId = $startChangeId;
673 673
 					$params['startChangeId'] = $startChangeId + 1;
674 674
 				} else {
Please login to merge, or discard this patch.
lib/private/Archive/TAR.php 3 patches
Doc Comments   +1 added lines patch added patch discarded remove patch
@@ -370,6 +370,7 @@
 block discarded – undo
370 370
 
371 371
 	/**
372 372
 	 * write back temporary files
373
+	 * @param string $path
373 374
 	 */
374 375
 	function writeBack($tmpFile, $path) {
375 376
 		$this->addFile($path, $tmpFile);
Please login to merge, or discard this patch.
Indentation   +331 added lines, -331 removed lines patch added patch discarded remove patch
@@ -36,355 +36,355 @@
 block discarded – undo
36 36
 use Icewind\Streams\CallbackWrapper;
37 37
 
38 38
 class TAR extends Archive {
39
-	const PLAIN = 0;
40
-	const GZIP = 1;
41
-	const BZIP = 2;
39
+    const PLAIN = 0;
40
+    const GZIP = 1;
41
+    const BZIP = 2;
42 42
 
43
-	private $fileList;
44
-	private $cachedHeaders;
43
+    private $fileList;
44
+    private $cachedHeaders;
45 45
 
46
-	/**
47
-	 * @var \Archive_Tar tar
48
-	 */
49
-	private $tar = null;
50
-	private $path;
46
+    /**
47
+     * @var \Archive_Tar tar
48
+     */
49
+    private $tar = null;
50
+    private $path;
51 51
 
52
-	/**
53
-	 * @param string $source
54
-	 */
55
-	function __construct($source) {
56
-		$types = array(null, 'gz', 'bz2');
57
-		$this->path = $source;
58
-		$this->tar = new \Archive_Tar($source, $types[self::getTarType($source)]);
59
-	}
52
+    /**
53
+     * @param string $source
54
+     */
55
+    function __construct($source) {
56
+        $types = array(null, 'gz', 'bz2');
57
+        $this->path = $source;
58
+        $this->tar = new \Archive_Tar($source, $types[self::getTarType($source)]);
59
+    }
60 60
 
61
-	/**
62
-	 * try to detect the type of tar compression
63
-	 *
64
-	 * @param string $file
65
-	 * @return integer
66
-	 */
67
-	static public function getTarType($file) {
68
-		if (strpos($file, '.')) {
69
-			$extension = substr($file, strrpos($file, '.'));
70
-			switch ($extension) {
71
-				case '.gz':
72
-				case '.tgz':
73
-					return self::GZIP;
74
-				case '.bz':
75
-				case '.bz2':
76
-					return self::BZIP;
77
-				case '.tar':
78
-					return self::PLAIN;
79
-				default:
80
-					return self::PLAIN;
81
-			}
82
-		} else {
83
-			return self::PLAIN;
84
-		}
85
-	}
61
+    /**
62
+     * try to detect the type of tar compression
63
+     *
64
+     * @param string $file
65
+     * @return integer
66
+     */
67
+    static public function getTarType($file) {
68
+        if (strpos($file, '.')) {
69
+            $extension = substr($file, strrpos($file, '.'));
70
+            switch ($extension) {
71
+                case '.gz':
72
+                case '.tgz':
73
+                    return self::GZIP;
74
+                case '.bz':
75
+                case '.bz2':
76
+                    return self::BZIP;
77
+                case '.tar':
78
+                    return self::PLAIN;
79
+                default:
80
+                    return self::PLAIN;
81
+            }
82
+        } else {
83
+            return self::PLAIN;
84
+        }
85
+    }
86 86
 
87
-	/**
88
-	 * add an empty folder to the archive
89
-	 *
90
-	 * @param string $path
91
-	 * @return bool
92
-	 */
93
-	function addFolder($path) {
94
-		$tmpBase = \OC::$server->getTempManager()->getTemporaryFolder();
95
-		if (substr($path, -1, 1) != '/') {
96
-			$path .= '/';
97
-		}
98
-		if ($this->fileExists($path)) {
99
-			return false;
100
-		}
101
-		$parts = explode('/', $path);
102
-		$folder = $tmpBase;
103
-		foreach ($parts as $part) {
104
-			$folder .= '/' . $part;
105
-			if (!is_dir($folder)) {
106
-				mkdir($folder);
107
-			}
108
-		}
109
-		$result = $this->tar->addModify(array($tmpBase . $path), '', $tmpBase);
110
-		rmdir($tmpBase . $path);
111
-		$this->fileList = false;
112
-		$this->cachedHeaders = false;
113
-		return $result;
114
-	}
87
+    /**
88
+     * add an empty folder to the archive
89
+     *
90
+     * @param string $path
91
+     * @return bool
92
+     */
93
+    function addFolder($path) {
94
+        $tmpBase = \OC::$server->getTempManager()->getTemporaryFolder();
95
+        if (substr($path, -1, 1) != '/') {
96
+            $path .= '/';
97
+        }
98
+        if ($this->fileExists($path)) {
99
+            return false;
100
+        }
101
+        $parts = explode('/', $path);
102
+        $folder = $tmpBase;
103
+        foreach ($parts as $part) {
104
+            $folder .= '/' . $part;
105
+            if (!is_dir($folder)) {
106
+                mkdir($folder);
107
+            }
108
+        }
109
+        $result = $this->tar->addModify(array($tmpBase . $path), '', $tmpBase);
110
+        rmdir($tmpBase . $path);
111
+        $this->fileList = false;
112
+        $this->cachedHeaders = false;
113
+        return $result;
114
+    }
115 115
 
116
-	/**
117
-	 * add a file to the archive
118
-	 *
119
-	 * @param string $path
120
-	 * @param string $source either a local file or string data
121
-	 * @return bool
122
-	 */
123
-	function addFile($path, $source = '') {
124
-		if ($this->fileExists($path)) {
125
-			$this->remove($path);
126
-		}
127
-		if ($source and $source[0] == '/' and file_exists($source)) {
128
-			$source = file_get_contents($source);
129
-		}
130
-		$result = $this->tar->addString($path, $source);
131
-		$this->fileList = false;
132
-		$this->cachedHeaders = false;
133
-		return $result;
134
-	}
116
+    /**
117
+     * add a file to the archive
118
+     *
119
+     * @param string $path
120
+     * @param string $source either a local file or string data
121
+     * @return bool
122
+     */
123
+    function addFile($path, $source = '') {
124
+        if ($this->fileExists($path)) {
125
+            $this->remove($path);
126
+        }
127
+        if ($source and $source[0] == '/' and file_exists($source)) {
128
+            $source = file_get_contents($source);
129
+        }
130
+        $result = $this->tar->addString($path, $source);
131
+        $this->fileList = false;
132
+        $this->cachedHeaders = false;
133
+        return $result;
134
+    }
135 135
 
136
-	/**
137
-	 * rename a file or folder in the archive
138
-	 *
139
-	 * @param string $source
140
-	 * @param string $dest
141
-	 * @return bool
142
-	 */
143
-	function rename($source, $dest) {
144
-		//no proper way to delete, rename entire archive, rename file and remake archive
145
-		$tmp = \OCP\Files::tmpFolder();
146
-		$this->tar->extract($tmp);
147
-		rename($tmp . $source, $tmp . $dest);
148
-		$this->tar = null;
149
-		unlink($this->path);
150
-		$types = array(null, 'gz', 'bz');
151
-		$this->tar = new \Archive_Tar($this->path, $types[self::getTarType($this->path)]);
152
-		$this->tar->createModify(array($tmp), '', $tmp . '/');
153
-		$this->fileList = false;
154
-		$this->cachedHeaders = false;
155
-		return true;
156
-	}
136
+    /**
137
+     * rename a file or folder in the archive
138
+     *
139
+     * @param string $source
140
+     * @param string $dest
141
+     * @return bool
142
+     */
143
+    function rename($source, $dest) {
144
+        //no proper way to delete, rename entire archive, rename file and remake archive
145
+        $tmp = \OCP\Files::tmpFolder();
146
+        $this->tar->extract($tmp);
147
+        rename($tmp . $source, $tmp . $dest);
148
+        $this->tar = null;
149
+        unlink($this->path);
150
+        $types = array(null, 'gz', 'bz');
151
+        $this->tar = new \Archive_Tar($this->path, $types[self::getTarType($this->path)]);
152
+        $this->tar->createModify(array($tmp), '', $tmp . '/');
153
+        $this->fileList = false;
154
+        $this->cachedHeaders = false;
155
+        return true;
156
+    }
157 157
 
158
-	/**
159
-	 * @param string $file
160
-	 */
161
-	private function getHeader($file) {
162
-		if (!$this->cachedHeaders) {
163
-			$this->cachedHeaders = $this->tar->listContent();
164
-		}
165
-		foreach ($this->cachedHeaders as $header) {
166
-			if ($file == $header['filename']
167
-				or $file . '/' == $header['filename']
168
-				or '/' . $file . '/' == $header['filename']
169
-				or '/' . $file == $header['filename']
170
-			) {
171
-				return $header;
172
-			}
173
-		}
174
-		return null;
175
-	}
158
+    /**
159
+     * @param string $file
160
+     */
161
+    private function getHeader($file) {
162
+        if (!$this->cachedHeaders) {
163
+            $this->cachedHeaders = $this->tar->listContent();
164
+        }
165
+        foreach ($this->cachedHeaders as $header) {
166
+            if ($file == $header['filename']
167
+                or $file . '/' == $header['filename']
168
+                or '/' . $file . '/' == $header['filename']
169
+                or '/' . $file == $header['filename']
170
+            ) {
171
+                return $header;
172
+            }
173
+        }
174
+        return null;
175
+    }
176 176
 
177
-	/**
178
-	 * get the uncompressed size of a file in the archive
179
-	 *
180
-	 * @param string $path
181
-	 * @return int
182
-	 */
183
-	function filesize($path) {
184
-		$stat = $this->getHeader($path);
185
-		return $stat['size'];
186
-	}
177
+    /**
178
+     * get the uncompressed size of a file in the archive
179
+     *
180
+     * @param string $path
181
+     * @return int
182
+     */
183
+    function filesize($path) {
184
+        $stat = $this->getHeader($path);
185
+        return $stat['size'];
186
+    }
187 187
 
188
-	/**
189
-	 * get the last modified time of a file in the archive
190
-	 *
191
-	 * @param string $path
192
-	 * @return int
193
-	 */
194
-	function mtime($path) {
195
-		$stat = $this->getHeader($path);
196
-		return $stat['mtime'];
197
-	}
188
+    /**
189
+     * get the last modified time of a file in the archive
190
+     *
191
+     * @param string $path
192
+     * @return int
193
+     */
194
+    function mtime($path) {
195
+        $stat = $this->getHeader($path);
196
+        return $stat['mtime'];
197
+    }
198 198
 
199
-	/**
200
-	 * get the files in a folder
201
-	 *
202
-	 * @param string $path
203
-	 * @return array
204
-	 */
205
-	function getFolder($path) {
206
-		$files = $this->getFiles();
207
-		$folderContent = array();
208
-		$pathLength = strlen($path);
209
-		foreach ($files as $file) {
210
-			if ($file[0] == '/') {
211
-				$file = substr($file, 1);
212
-			}
213
-			if (substr($file, 0, $pathLength) == $path and $file != $path) {
214
-				$result = substr($file, $pathLength);
215
-				if ($pos = strpos($result, '/')) {
216
-					$result = substr($result, 0, $pos + 1);
217
-				}
218
-				if (array_search($result, $folderContent) === false) {
219
-					$folderContent[] = $result;
220
-				}
221
-			}
222
-		}
223
-		return $folderContent;
224
-	}
199
+    /**
200
+     * get the files in a folder
201
+     *
202
+     * @param string $path
203
+     * @return array
204
+     */
205
+    function getFolder($path) {
206
+        $files = $this->getFiles();
207
+        $folderContent = array();
208
+        $pathLength = strlen($path);
209
+        foreach ($files as $file) {
210
+            if ($file[0] == '/') {
211
+                $file = substr($file, 1);
212
+            }
213
+            if (substr($file, 0, $pathLength) == $path and $file != $path) {
214
+                $result = substr($file, $pathLength);
215
+                if ($pos = strpos($result, '/')) {
216
+                    $result = substr($result, 0, $pos + 1);
217
+                }
218
+                if (array_search($result, $folderContent) === false) {
219
+                    $folderContent[] = $result;
220
+                }
221
+            }
222
+        }
223
+        return $folderContent;
224
+    }
225 225
 
226
-	/**
227
-	 * get all files in the archive
228
-	 *
229
-	 * @return array
230
-	 */
231
-	function getFiles() {
232
-		if ($this->fileList) {
233
-			return $this->fileList;
234
-		}
235
-		if (!$this->cachedHeaders) {
236
-			$this->cachedHeaders = $this->tar->listContent();
237
-		}
238
-		$files = array();
239
-		foreach ($this->cachedHeaders as $header) {
240
-			$files[] = $header['filename'];
241
-		}
242
-		$this->fileList = $files;
243
-		return $files;
244
-	}
226
+    /**
227
+     * get all files in the archive
228
+     *
229
+     * @return array
230
+     */
231
+    function getFiles() {
232
+        if ($this->fileList) {
233
+            return $this->fileList;
234
+        }
235
+        if (!$this->cachedHeaders) {
236
+            $this->cachedHeaders = $this->tar->listContent();
237
+        }
238
+        $files = array();
239
+        foreach ($this->cachedHeaders as $header) {
240
+            $files[] = $header['filename'];
241
+        }
242
+        $this->fileList = $files;
243
+        return $files;
244
+    }
245 245
 
246
-	/**
247
-	 * get the content of a file
248
-	 *
249
-	 * @param string $path
250
-	 * @return string
251
-	 */
252
-	function getFile($path) {
253
-		return $this->tar->extractInString($path);
254
-	}
246
+    /**
247
+     * get the content of a file
248
+     *
249
+     * @param string $path
250
+     * @return string
251
+     */
252
+    function getFile($path) {
253
+        return $this->tar->extractInString($path);
254
+    }
255 255
 
256
-	/**
257
-	 * extract a single file from the archive
258
-	 *
259
-	 * @param string $path
260
-	 * @param string $dest
261
-	 * @return bool
262
-	 */
263
-	function extractFile($path, $dest) {
264
-		$tmp = \OCP\Files::tmpFolder();
265
-		if (!$this->fileExists($path)) {
266
-			return false;
267
-		}
268
-		if ($this->fileExists('/' . $path)) {
269
-			$success = $this->tar->extractList(array('/' . $path), $tmp);
270
-		} else {
271
-			$success = $this->tar->extractList(array($path), $tmp);
272
-		}
273
-		if ($success) {
274
-			rename($tmp . $path, $dest);
275
-		}
276
-		\OCP\Files::rmdirr($tmp);
277
-		return $success;
278
-	}
256
+    /**
257
+     * extract a single file from the archive
258
+     *
259
+     * @param string $path
260
+     * @param string $dest
261
+     * @return bool
262
+     */
263
+    function extractFile($path, $dest) {
264
+        $tmp = \OCP\Files::tmpFolder();
265
+        if (!$this->fileExists($path)) {
266
+            return false;
267
+        }
268
+        if ($this->fileExists('/' . $path)) {
269
+            $success = $this->tar->extractList(array('/' . $path), $tmp);
270
+        } else {
271
+            $success = $this->tar->extractList(array($path), $tmp);
272
+        }
273
+        if ($success) {
274
+            rename($tmp . $path, $dest);
275
+        }
276
+        \OCP\Files::rmdirr($tmp);
277
+        return $success;
278
+    }
279 279
 
280
-	/**
281
-	 * extract the archive
282
-	 *
283
-	 * @param string $dest
284
-	 * @return bool
285
-	 */
286
-	function extract($dest) {
287
-		return $this->tar->extract($dest);
288
-	}
280
+    /**
281
+     * extract the archive
282
+     *
283
+     * @param string $dest
284
+     * @return bool
285
+     */
286
+    function extract($dest) {
287
+        return $this->tar->extract($dest);
288
+    }
289 289
 
290
-	/**
291
-	 * check if a file or folder exists in the archive
292
-	 *
293
-	 * @param string $path
294
-	 * @return bool
295
-	 */
296
-	function fileExists($path) {
297
-		$files = $this->getFiles();
298
-		if ((array_search($path, $files) !== false) or (array_search($path . '/', $files) !== false)) {
299
-			return true;
300
-		} else {
301
-			$folderPath = $path;
302
-			if (substr($folderPath, -1, 1) != '/') {
303
-				$folderPath .= '/';
304
-			}
305
-			$pathLength = strlen($folderPath);
306
-			foreach ($files as $file) {
307
-				if (strlen($file) > $pathLength and substr($file, 0, $pathLength) == $folderPath) {
308
-					return true;
309
-				}
310
-			}
311
-		}
312
-		if ($path[0] != '/') { //not all programs agree on the use of a leading /
313
-			return $this->fileExists('/' . $path);
314
-		} else {
315
-			return false;
316
-		}
317
-	}
290
+    /**
291
+     * check if a file or folder exists in the archive
292
+     *
293
+     * @param string $path
294
+     * @return bool
295
+     */
296
+    function fileExists($path) {
297
+        $files = $this->getFiles();
298
+        if ((array_search($path, $files) !== false) or (array_search($path . '/', $files) !== false)) {
299
+            return true;
300
+        } else {
301
+            $folderPath = $path;
302
+            if (substr($folderPath, -1, 1) != '/') {
303
+                $folderPath .= '/';
304
+            }
305
+            $pathLength = strlen($folderPath);
306
+            foreach ($files as $file) {
307
+                if (strlen($file) > $pathLength and substr($file, 0, $pathLength) == $folderPath) {
308
+                    return true;
309
+                }
310
+            }
311
+        }
312
+        if ($path[0] != '/') { //not all programs agree on the use of a leading /
313
+            return $this->fileExists('/' . $path);
314
+        } else {
315
+            return false;
316
+        }
317
+    }
318 318
 
319
-	/**
320
-	 * remove a file or folder from the archive
321
-	 *
322
-	 * @param string $path
323
-	 * @return bool
324
-	 */
325
-	function remove($path) {
326
-		if (!$this->fileExists($path)) {
327
-			return false;
328
-		}
329
-		$this->fileList = false;
330
-		$this->cachedHeaders = false;
331
-		//no proper way to delete, extract entire archive, delete file and remake archive
332
-		$tmp = \OCP\Files::tmpFolder();
333
-		$this->tar->extract($tmp);
334
-		\OCP\Files::rmdirr($tmp . $path);
335
-		$this->tar = null;
336
-		unlink($this->path);
337
-		$this->reopen();
338
-		$this->tar->createModify(array($tmp), '', $tmp);
339
-		return true;
340
-	}
319
+    /**
320
+     * remove a file or folder from the archive
321
+     *
322
+     * @param string $path
323
+     * @return bool
324
+     */
325
+    function remove($path) {
326
+        if (!$this->fileExists($path)) {
327
+            return false;
328
+        }
329
+        $this->fileList = false;
330
+        $this->cachedHeaders = false;
331
+        //no proper way to delete, extract entire archive, delete file and remake archive
332
+        $tmp = \OCP\Files::tmpFolder();
333
+        $this->tar->extract($tmp);
334
+        \OCP\Files::rmdirr($tmp . $path);
335
+        $this->tar = null;
336
+        unlink($this->path);
337
+        $this->reopen();
338
+        $this->tar->createModify(array($tmp), '', $tmp);
339
+        return true;
340
+    }
341 341
 
342
-	/**
343
-	 * get a file handler
344
-	 *
345
-	 * @param string $path
346
-	 * @param string $mode
347
-	 * @return resource
348
-	 */
349
-	function getStream($path, $mode) {
350
-		if (strrpos($path, '.') !== false) {
351
-			$ext = substr($path, strrpos($path, '.'));
352
-		} else {
353
-			$ext = '';
354
-		}
355
-		$tmpFile = \OCP\Files::tmpFile($ext);
356
-		if ($this->fileExists($path)) {
357
-			$this->extractFile($path, $tmpFile);
358
-		} elseif ($mode == 'r' or $mode == 'rb') {
359
-			return false;
360
-		}
361
-		if ($mode == 'r' or $mode == 'rb') {
362
-			return fopen($tmpFile, $mode);
363
-		} else {
364
-			$handle = fopen($tmpFile, $mode);
365
-			return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
366
-				$this->writeBack($tmpFile, $path);
367
-			});
368
-		}
369
-	}
342
+    /**
343
+     * get a file handler
344
+     *
345
+     * @param string $path
346
+     * @param string $mode
347
+     * @return resource
348
+     */
349
+    function getStream($path, $mode) {
350
+        if (strrpos($path, '.') !== false) {
351
+            $ext = substr($path, strrpos($path, '.'));
352
+        } else {
353
+            $ext = '';
354
+        }
355
+        $tmpFile = \OCP\Files::tmpFile($ext);
356
+        if ($this->fileExists($path)) {
357
+            $this->extractFile($path, $tmpFile);
358
+        } elseif ($mode == 'r' or $mode == 'rb') {
359
+            return false;
360
+        }
361
+        if ($mode == 'r' or $mode == 'rb') {
362
+            return fopen($tmpFile, $mode);
363
+        } else {
364
+            $handle = fopen($tmpFile, $mode);
365
+            return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
366
+                $this->writeBack($tmpFile, $path);
367
+            });
368
+        }
369
+    }
370 370
 
371
-	/**
372
-	 * write back temporary files
373
-	 */
374
-	function writeBack($tmpFile, $path) {
375
-		$this->addFile($path, $tmpFile);
376
-		unlink($tmpFile);
377
-	}
371
+    /**
372
+     * write back temporary files
373
+     */
374
+    function writeBack($tmpFile, $path) {
375
+        $this->addFile($path, $tmpFile);
376
+        unlink($tmpFile);
377
+    }
378 378
 
379
-	/**
380
-	 * reopen the archive to ensure everything is written
381
-	 */
382
-	private function reopen() {
383
-		if ($this->tar) {
384
-			$this->tar->_close();
385
-			$this->tar = null;
386
-		}
387
-		$types = array(null, 'gz', 'bz');
388
-		$this->tar = new \Archive_Tar($this->path, $types[self::getTarType($this->path)]);
389
-	}
379
+    /**
380
+     * reopen the archive to ensure everything is written
381
+     */
382
+    private function reopen() {
383
+        if ($this->tar) {
384
+            $this->tar->_close();
385
+            $this->tar = null;
386
+        }
387
+        $types = array(null, 'gz', 'bz');
388
+        $this->tar = new \Archive_Tar($this->path, $types[self::getTarType($this->path)]);
389
+    }
390 390
 }
Please login to merge, or discard this patch.
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -101,13 +101,13 @@  discard block
 block discarded – undo
101 101
 		$parts = explode('/', $path);
102 102
 		$folder = $tmpBase;
103 103
 		foreach ($parts as $part) {
104
-			$folder .= '/' . $part;
104
+			$folder .= '/'.$part;
105 105
 			if (!is_dir($folder)) {
106 106
 				mkdir($folder);
107 107
 			}
108 108
 		}
109
-		$result = $this->tar->addModify(array($tmpBase . $path), '', $tmpBase);
110
-		rmdir($tmpBase . $path);
109
+		$result = $this->tar->addModify(array($tmpBase.$path), '', $tmpBase);
110
+		rmdir($tmpBase.$path);
111 111
 		$this->fileList = false;
112 112
 		$this->cachedHeaders = false;
113 113
 		return $result;
@@ -144,12 +144,12 @@  discard block
 block discarded – undo
144 144
 		//no proper way to delete, rename entire archive, rename file and remake archive
145 145
 		$tmp = \OCP\Files::tmpFolder();
146 146
 		$this->tar->extract($tmp);
147
-		rename($tmp . $source, $tmp . $dest);
147
+		rename($tmp.$source, $tmp.$dest);
148 148
 		$this->tar = null;
149 149
 		unlink($this->path);
150 150
 		$types = array(null, 'gz', 'bz');
151 151
 		$this->tar = new \Archive_Tar($this->path, $types[self::getTarType($this->path)]);
152
-		$this->tar->createModify(array($tmp), '', $tmp . '/');
152
+		$this->tar->createModify(array($tmp), '', $tmp.'/');
153 153
 		$this->fileList = false;
154 154
 		$this->cachedHeaders = false;
155 155
 		return true;
@@ -164,9 +164,9 @@  discard block
 block discarded – undo
164 164
 		}
165 165
 		foreach ($this->cachedHeaders as $header) {
166 166
 			if ($file == $header['filename']
167
-				or $file . '/' == $header['filename']
168
-				or '/' . $file . '/' == $header['filename']
169
-				or '/' . $file == $header['filename']
167
+				or $file.'/' == $header['filename']
168
+				or '/'.$file.'/' == $header['filename']
169
+				or '/'.$file == $header['filename']
170 170
 			) {
171 171
 				return $header;
172 172
 			}
@@ -265,13 +265,13 @@  discard block
 block discarded – undo
265 265
 		if (!$this->fileExists($path)) {
266 266
 			return false;
267 267
 		}
268
-		if ($this->fileExists('/' . $path)) {
269
-			$success = $this->tar->extractList(array('/' . $path), $tmp);
268
+		if ($this->fileExists('/'.$path)) {
269
+			$success = $this->tar->extractList(array('/'.$path), $tmp);
270 270
 		} else {
271 271
 			$success = $this->tar->extractList(array($path), $tmp);
272 272
 		}
273 273
 		if ($success) {
274
-			rename($tmp . $path, $dest);
274
+			rename($tmp.$path, $dest);
275 275
 		}
276 276
 		\OCP\Files::rmdirr($tmp);
277 277
 		return $success;
@@ -295,7 +295,7 @@  discard block
 block discarded – undo
295 295
 	 */
296 296
 	function fileExists($path) {
297 297
 		$files = $this->getFiles();
298
-		if ((array_search($path, $files) !== false) or (array_search($path . '/', $files) !== false)) {
298
+		if ((array_search($path, $files) !== false) or (array_search($path.'/', $files) !== false)) {
299 299
 			return true;
300 300
 		} else {
301 301
 			$folderPath = $path;
@@ -310,7 +310,7 @@  discard block
 block discarded – undo
310 310
 			}
311 311
 		}
312 312
 		if ($path[0] != '/') { //not all programs agree on the use of a leading /
313
-			return $this->fileExists('/' . $path);
313
+			return $this->fileExists('/'.$path);
314 314
 		} else {
315 315
 			return false;
316 316
 		}
@@ -331,7 +331,7 @@  discard block
 block discarded – undo
331 331
 		//no proper way to delete, extract entire archive, delete file and remake archive
332 332
 		$tmp = \OCP\Files::tmpFolder();
333 333
 		$this->tar->extract($tmp);
334
-		\OCP\Files::rmdirr($tmp . $path);
334
+		\OCP\Files::rmdirr($tmp.$path);
335 335
 		$this->tar = null;
336 336
 		unlink($this->path);
337 337
 		$this->reopen();
@@ -362,7 +362,7 @@  discard block
 block discarded – undo
362 362
 			return fopen($tmpFile, $mode);
363 363
 		} else {
364 364
 			$handle = fopen($tmpFile, $mode);
365
-			return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
365
+			return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
366 366
 				$this->writeBack($tmpFile, $path);
367 367
 			});
368 368
 		}
Please login to merge, or discard this patch.