Completed
Pull Request — master (#4212)
by Individual IT
13:52
created
apps/dav/lib/CalDAV/CalDavBackend.php 4 patches
Doc Comments   +10 added lines, -4 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
 	 */
@@ -303,6 +303,9 @@  discard block
 block discarded – undo
303 303
 		return array_values($calendars);
304 304
 	}
305 305
 
306
+	/**
307
+	 * @param string $principalUri
308
+	 */
306 309
 	public function getUsersOwnCalendars($principalUri) {
307 310
 		$principalUri = $this->convertPrincipal($principalUri, true);
308 311
 		$fields = array_values($this->propertyMap);
@@ -851,7 +854,7 @@  discard block
 block discarded – undo
851 854
 	 * calendar-data. If the result of a subsequent GET to this object is not
852 855
 	 * the exact same as this request body, you should omit the ETag.
853 856
 	 *
854
-	 * @param mixed $calendarId
857
+	 * @param integer $calendarId
855 858
 	 * @param string $objectUri
856 859
 	 * @param string $calendarData
857 860
 	 * @return string
@@ -894,7 +897,7 @@  discard block
 block discarded – undo
894 897
 	 * calendar-data. If the result of a subsequent GET to this object is not
895 898
 	 * the exact same as this request body, you should omit the ETag.
896 899
 	 *
897
-	 * @param mixed $calendarId
900
+	 * @param integer $calendarId
898 901
 	 * @param string $objectUri
899 902
 	 * @param string $calendarData
900 903
 	 * @return string
@@ -1309,7 +1312,7 @@  discard block
 block discarded – undo
1309 1312
 	 * @param string $principalUri
1310 1313
 	 * @param string $uri
1311 1314
 	 * @param array $properties
1312
-	 * @return mixed
1315
+	 * @return integer
1313 1316
 	 */
1314 1317
 	function createSubscription($principalUri, $uri, array $properties) {
1315 1318
 
@@ -1712,6 +1715,9 @@  discard block
 block discarded – undo
1712 1715
 		return $this->sharingBackend->applyShareAcl($resourceId, $acl);
1713 1716
 	}
1714 1717
 
1718
+	/**
1719
+	 * @param boolean $toV2
1720
+	 */
1715 1721
 	private function convertPrincipal($principalUri, $toV2) {
1716 1722
 		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1717 1723
 			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   +1755 added lines, -1755 removed lines patch added patch discarded remove patch
@@ -59,1760 +59,1760 @@
 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
-			if ($row['principaluri'] === $principalUri) {
283
-				continue;
284
-			}
285
-
286
-			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
287
-			if (isset($calendars[$row['id']])) {
288
-				if ($readOnly) {
289
-					// New share can not have more permissions then the old one.
290
-					continue;
291
-				}
292
-				if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
293
-					$calendars[$row['id']][$readOnlyPropertyName] === 0) {
294
-					// Old share is already read-write, no more permissions can be gained
295
-					continue;
296
-				}
297
-			}
298
-
299
-			list(, $name) = URLUtil::splitPath($row['principaluri']);
300
-			$uri = $row['uri'] . '_shared_by_' . $name;
301
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
302
-			$components = [];
303
-			if ($row['components']) {
304
-				$components = explode(',',$row['components']);
305
-			}
306
-			$calendar = [
307
-				'id' => $row['id'],
308
-				'uri' => $uri,
309
-				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
310
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
311
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
312
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
313
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
314
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
315
-				$readOnlyPropertyName => $readOnly,
316
-			];
317
-
318
-			foreach($this->propertyMap as $xmlName=>$dbName) {
319
-				$calendar[$xmlName] = $row[$dbName];
320
-			}
321
-
322
-			$calendars[$calendar['id']] = $calendar;
323
-		}
324
-		$result->closeCursor();
325
-
326
-		return array_values($calendars);
327
-	}
328
-
329
-	public function getUsersOwnCalendars($principalUri) {
330
-		$principalUri = $this->convertPrincipal($principalUri, true);
331
-		$fields = array_values($this->propertyMap);
332
-		$fields[] = 'id';
333
-		$fields[] = 'uri';
334
-		$fields[] = 'synctoken';
335
-		$fields[] = 'components';
336
-		$fields[] = 'principaluri';
337
-		$fields[] = 'transparent';
338
-		// Making fields a comma-delimited list
339
-		$query = $this->db->getQueryBuilder();
340
-		$query->select($fields)->from('calendars')
341
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
342
-			->orderBy('calendarorder', 'ASC');
343
-		$stmt = $query->execute();
344
-		$calendars = [];
345
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
346
-			$components = [];
347
-			if ($row['components']) {
348
-				$components = explode(',',$row['components']);
349
-			}
350
-			$calendar = [
351
-				'id' => $row['id'],
352
-				'uri' => $row['uri'],
353
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
354
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
355
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
356
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
357
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
358
-			];
359
-			foreach($this->propertyMap as $xmlName=>$dbName) {
360
-				$calendar[$xmlName] = $row[$dbName];
361
-			}
362
-			if (!isset($calendars[$calendar['id']])) {
363
-				$calendars[$calendar['id']] = $calendar;
364
-			}
365
-		}
366
-		$stmt->closeCursor();
367
-		return array_values($calendars);
368
-	}
369
-
370
-
371
-	private function getUserDisplayName($uid) {
372
-		if (!isset($this->userDisplayNames[$uid])) {
373
-			$user = $this->userManager->get($uid);
374
-
375
-			if ($user instanceof IUser) {
376
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
377
-			} else {
378
-				$this->userDisplayNames[$uid] = $uid;
379
-			}
380
-		}
381
-
382
-		return $this->userDisplayNames[$uid];
383
-	}
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
+            if ($row['principaluri'] === $principalUri) {
283
+                continue;
284
+            }
285
+
286
+            $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
287
+            if (isset($calendars[$row['id']])) {
288
+                if ($readOnly) {
289
+                    // New share can not have more permissions then the old one.
290
+                    continue;
291
+                }
292
+                if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
293
+                    $calendars[$row['id']][$readOnlyPropertyName] === 0) {
294
+                    // Old share is already read-write, no more permissions can be gained
295
+                    continue;
296
+                }
297
+            }
298
+
299
+            list(, $name) = URLUtil::splitPath($row['principaluri']);
300
+            $uri = $row['uri'] . '_shared_by_' . $name;
301
+            $row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
302
+            $components = [];
303
+            if ($row['components']) {
304
+                $components = explode(',',$row['components']);
305
+            }
306
+            $calendar = [
307
+                'id' => $row['id'],
308
+                'uri' => $uri,
309
+                'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
310
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
311
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
312
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
313
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
314
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
315
+                $readOnlyPropertyName => $readOnly,
316
+            ];
317
+
318
+            foreach($this->propertyMap as $xmlName=>$dbName) {
319
+                $calendar[$xmlName] = $row[$dbName];
320
+            }
321
+
322
+            $calendars[$calendar['id']] = $calendar;
323
+        }
324
+        $result->closeCursor();
325
+
326
+        return array_values($calendars);
327
+    }
328
+
329
+    public function getUsersOwnCalendars($principalUri) {
330
+        $principalUri = $this->convertPrincipal($principalUri, true);
331
+        $fields = array_values($this->propertyMap);
332
+        $fields[] = 'id';
333
+        $fields[] = 'uri';
334
+        $fields[] = 'synctoken';
335
+        $fields[] = 'components';
336
+        $fields[] = 'principaluri';
337
+        $fields[] = 'transparent';
338
+        // Making fields a comma-delimited list
339
+        $query = $this->db->getQueryBuilder();
340
+        $query->select($fields)->from('calendars')
341
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
342
+            ->orderBy('calendarorder', 'ASC');
343
+        $stmt = $query->execute();
344
+        $calendars = [];
345
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
346
+            $components = [];
347
+            if ($row['components']) {
348
+                $components = explode(',',$row['components']);
349
+            }
350
+            $calendar = [
351
+                'id' => $row['id'],
352
+                'uri' => $row['uri'],
353
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
354
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
355
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
356
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
357
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
358
+            ];
359
+            foreach($this->propertyMap as $xmlName=>$dbName) {
360
+                $calendar[$xmlName] = $row[$dbName];
361
+            }
362
+            if (!isset($calendars[$calendar['id']])) {
363
+                $calendars[$calendar['id']] = $calendar;
364
+            }
365
+        }
366
+        $stmt->closeCursor();
367
+        return array_values($calendars);
368
+    }
369
+
370
+
371
+    private function getUserDisplayName($uid) {
372
+        if (!isset($this->userDisplayNames[$uid])) {
373
+            $user = $this->userManager->get($uid);
374
+
375
+            if ($user instanceof IUser) {
376
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
377
+            } else {
378
+                $this->userDisplayNames[$uid] = $uid;
379
+            }
380
+        }
381
+
382
+        return $this->userDisplayNames[$uid];
383
+    }
384 384
 	
385
-	/**
386
-	 * @return array
387
-	 */
388
-	public function getPublicCalendars() {
389
-		$fields = array_values($this->propertyMap);
390
-		$fields[] = 'a.id';
391
-		$fields[] = 'a.uri';
392
-		$fields[] = 'a.synctoken';
393
-		$fields[] = 'a.components';
394
-		$fields[] = 'a.principaluri';
395
-		$fields[] = 'a.transparent';
396
-		$fields[] = 's.access';
397
-		$fields[] = 's.publicuri';
398
-		$calendars = [];
399
-		$query = $this->db->getQueryBuilder();
400
-		$result = $query->select($fields)
401
-			->from('dav_shares', 's')
402
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
403
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
404
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
405
-			->execute();
406
-
407
-		while($row = $result->fetch()) {
408
-			list(, $name) = URLUtil::splitPath($row['principaluri']);
409
-			$row['displayname'] = $row['displayname'] . "($name)";
410
-			$components = [];
411
-			if ($row['components']) {
412
-				$components = explode(',',$row['components']);
413
-			}
414
-			$calendar = [
415
-				'id' => $row['id'],
416
-				'uri' => $row['publicuri'],
417
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
418
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
419
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
420
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
421
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
422
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
423
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
424
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
425
-			];
426
-
427
-			foreach($this->propertyMap as $xmlName=>$dbName) {
428
-				$calendar[$xmlName] = $row[$dbName];
429
-			}
430
-
431
-			if (!isset($calendars[$calendar['id']])) {
432
-				$calendars[$calendar['id']] = $calendar;
433
-			}
434
-		}
435
-		$result->closeCursor();
436
-
437
-		return array_values($calendars);
438
-	}
439
-
440
-	/**
441
-	 * @param string $uri
442
-	 * @return array
443
-	 * @throws NotFound
444
-	 */
445
-	public function getPublicCalendar($uri) {
446
-		$fields = array_values($this->propertyMap);
447
-		$fields[] = 'a.id';
448
-		$fields[] = 'a.uri';
449
-		$fields[] = 'a.synctoken';
450
-		$fields[] = 'a.components';
451
-		$fields[] = 'a.principaluri';
452
-		$fields[] = 'a.transparent';
453
-		$fields[] = 's.access';
454
-		$fields[] = 's.publicuri';
455
-		$query = $this->db->getQueryBuilder();
456
-		$result = $query->select($fields)
457
-			->from('dav_shares', 's')
458
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
459
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
460
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
461
-			->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
462
-			->execute();
463
-
464
-		$row = $result->fetch(\PDO::FETCH_ASSOC);
465
-
466
-		$result->closeCursor();
467
-
468
-		if ($row === false) {
469
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
470
-		}
471
-
472
-		list(, $name) = URLUtil::splitPath($row['principaluri']);
473
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
474
-		$components = [];
475
-		if ($row['components']) {
476
-			$components = explode(',',$row['components']);
477
-		}
478
-		$calendar = [
479
-			'id' => $row['id'],
480
-			'uri' => $row['publicuri'],
481
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
482
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
483
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
484
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
485
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
486
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
487
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
488
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
489
-		];
490
-
491
-		foreach($this->propertyMap as $xmlName=>$dbName) {
492
-			$calendar[$xmlName] = $row[$dbName];
493
-		}
494
-
495
-		return $calendar;
496
-
497
-	}
498
-
499
-	/**
500
-	 * @param string $principal
501
-	 * @param string $uri
502
-	 * @return array|null
503
-	 */
504
-	public function getCalendarByUri($principal, $uri) {
505
-		$fields = array_values($this->propertyMap);
506
-		$fields[] = 'id';
507
-		$fields[] = 'uri';
508
-		$fields[] = 'synctoken';
509
-		$fields[] = 'components';
510
-		$fields[] = 'principaluri';
511
-		$fields[] = 'transparent';
512
-
513
-		// Making fields a comma-delimited list
514
-		$query = $this->db->getQueryBuilder();
515
-		$query->select($fields)->from('calendars')
516
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
517
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
518
-			->setMaxResults(1);
519
-		$stmt = $query->execute();
520
-
521
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
522
-		$stmt->closeCursor();
523
-		if ($row === false) {
524
-			return null;
525
-		}
526
-
527
-		$components = [];
528
-		if ($row['components']) {
529
-			$components = explode(',',$row['components']);
530
-		}
531
-
532
-		$calendar = [
533
-			'id' => $row['id'],
534
-			'uri' => $row['uri'],
535
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
536
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
537
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
538
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
539
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
540
-		];
541
-
542
-		foreach($this->propertyMap as $xmlName=>$dbName) {
543
-			$calendar[$xmlName] = $row[$dbName];
544
-		}
545
-
546
-		return $calendar;
547
-	}
548
-
549
-	public function getCalendarById($calendarId) {
550
-		$fields = array_values($this->propertyMap);
551
-		$fields[] = 'id';
552
-		$fields[] = 'uri';
553
-		$fields[] = 'synctoken';
554
-		$fields[] = 'components';
555
-		$fields[] = 'principaluri';
556
-		$fields[] = 'transparent';
557
-
558
-		// Making fields a comma-delimited list
559
-		$query = $this->db->getQueryBuilder();
560
-		$query->select($fields)->from('calendars')
561
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
562
-			->setMaxResults(1);
563
-		$stmt = $query->execute();
564
-
565
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
566
-		$stmt->closeCursor();
567
-		if ($row === false) {
568
-			return null;
569
-		}
570
-
571
-		$components = [];
572
-		if ($row['components']) {
573
-			$components = explode(',',$row['components']);
574
-		}
575
-
576
-		$calendar = [
577
-			'id' => $row['id'],
578
-			'uri' => $row['uri'],
579
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
580
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
581
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
582
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
583
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
584
-		];
585
-
586
-		foreach($this->propertyMap as $xmlName=>$dbName) {
587
-			$calendar[$xmlName] = $row[$dbName];
588
-		}
589
-
590
-		return $calendar;
591
-	}
592
-
593
-	/**
594
-	 * Creates a new calendar for a principal.
595
-	 *
596
-	 * If the creation was a success, an id must be returned that can be used to reference
597
-	 * this calendar in other methods, such as updateCalendar.
598
-	 *
599
-	 * @param string $principalUri
600
-	 * @param string $calendarUri
601
-	 * @param array $properties
602
-	 * @return int
603
-	 */
604
-	function createCalendar($principalUri, $calendarUri, array $properties) {
605
-		$values = [
606
-			'principaluri' => $this->convertPrincipal($principalUri, true),
607
-			'uri'          => $calendarUri,
608
-			'synctoken'    => 1,
609
-			'transparent'  => 0,
610
-			'components'   => 'VEVENT,VTODO',
611
-			'displayname'  => $calendarUri
612
-		];
613
-
614
-		// Default value
615
-		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
616
-		if (isset($properties[$sccs])) {
617
-			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
618
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
619
-			}
620
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
621
-		}
622
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
623
-		if (isset($properties[$transp])) {
624
-			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
625
-		}
626
-
627
-		foreach($this->propertyMap as $xmlName=>$dbName) {
628
-			if (isset($properties[$xmlName])) {
629
-				$values[$dbName] = $properties[$xmlName];
630
-			}
631
-		}
632
-
633
-		$query = $this->db->getQueryBuilder();
634
-		$query->insert('calendars');
635
-		foreach($values as $column => $value) {
636
-			$query->setValue($column, $query->createNamedParameter($value));
637
-		}
638
-		$query->execute();
639
-		$calendarId = $query->getLastInsertId();
640
-
641
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
642
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
643
-			[
644
-				'calendarId' => $calendarId,
645
-				'calendarData' => $this->getCalendarById($calendarId),
646
-		]));
647
-
648
-		return $calendarId;
649
-	}
650
-
651
-	/**
652
-	 * Updates properties for a calendar.
653
-	 *
654
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
655
-	 * To do the actual updates, you must tell this object which properties
656
-	 * you're going to process with the handle() method.
657
-	 *
658
-	 * Calling the handle method is like telling the PropPatch object "I
659
-	 * promise I can handle updating this property".
660
-	 *
661
-	 * Read the PropPatch documentation for more info and examples.
662
-	 *
663
-	 * @param PropPatch $propPatch
664
-	 * @return void
665
-	 */
666
-	function updateCalendar($calendarId, PropPatch $propPatch) {
667
-		$supportedProperties = array_keys($this->propertyMap);
668
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
669
-
670
-		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
671
-			$newValues = [];
672
-			foreach ($mutations as $propertyName => $propertyValue) {
673
-
674
-				switch ($propertyName) {
675
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
676
-						$fieldName = 'transparent';
677
-						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
678
-						break;
679
-					default :
680
-						$fieldName = $this->propertyMap[$propertyName];
681
-						$newValues[$fieldName] = $propertyValue;
682
-						break;
683
-				}
684
-
685
-			}
686
-			$query = $this->db->getQueryBuilder();
687
-			$query->update('calendars');
688
-			foreach ($newValues as $fieldName => $value) {
689
-				$query->set($fieldName, $query->createNamedParameter($value));
690
-			}
691
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
692
-			$query->execute();
693
-
694
-			$this->addChange($calendarId, "", 2);
695
-
696
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
697
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
698
-				[
699
-					'calendarId' => $calendarId,
700
-					'calendarData' => $this->getCalendarById($calendarId),
701
-					'shares' => $this->getShares($calendarId),
702
-					'propertyMutations' => $mutations,
703
-			]));
704
-
705
-			return true;
706
-		});
707
-	}
708
-
709
-	/**
710
-	 * Delete a calendar and all it's objects
711
-	 *
712
-	 * @param mixed $calendarId
713
-	 * @return void
714
-	 */
715
-	function deleteCalendar($calendarId) {
716
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
717
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
718
-			[
719
-				'calendarId' => $calendarId,
720
-				'calendarData' => $this->getCalendarById($calendarId),
721
-				'shares' => $this->getShares($calendarId),
722
-		]));
723
-
724
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?');
725
-		$stmt->execute([$calendarId]);
726
-
727
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
728
-		$stmt->execute([$calendarId]);
729
-
730
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ?');
731
-		$stmt->execute([$calendarId]);
732
-
733
-		$this->sharingBackend->deleteAllShares($calendarId);
734
-	}
735
-
736
-	/**
737
-	 * Delete all of an user's shares
738
-	 *
739
-	 * @param string $principaluri
740
-	 * @return void
741
-	 */
742
-	function deleteAllSharesByUser($principaluri) {
743
-		$this->sharingBackend->deleteAllSharesByUser($principaluri);
744
-	}
745
-
746
-	/**
747
-	 * Returns all calendar objects within a calendar.
748
-	 *
749
-	 * Every item contains an array with the following keys:
750
-	 *   * calendardata - The iCalendar-compatible calendar data
751
-	 *   * uri - a unique key which will be used to construct the uri. This can
752
-	 *     be any arbitrary string, but making sure it ends with '.ics' is a
753
-	 *     good idea. This is only the basename, or filename, not the full
754
-	 *     path.
755
-	 *   * lastmodified - a timestamp of the last modification time
756
-	 *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
757
-	 *   '"abcdef"')
758
-	 *   * size - The size of the calendar objects, in bytes.
759
-	 *   * component - optional, a string containing the type of object, such
760
-	 *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
761
-	 *     the Content-Type header.
762
-	 *
763
-	 * Note that the etag is optional, but it's highly encouraged to return for
764
-	 * speed reasons.
765
-	 *
766
-	 * The calendardata is also optional. If it's not returned
767
-	 * 'getCalendarObject' will be called later, which *is* expected to return
768
-	 * calendardata.
769
-	 *
770
-	 * If neither etag or size are specified, the calendardata will be
771
-	 * used/fetched to determine these numbers. If both are specified the
772
-	 * amount of times this is needed is reduced by a great degree.
773
-	 *
774
-	 * @param mixed $calendarId
775
-	 * @return array
776
-	 */
777
-	function getCalendarObjects($calendarId) {
778
-		$query = $this->db->getQueryBuilder();
779
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
780
-			->from('calendarobjects')
781
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
782
-		$stmt = $query->execute();
783
-
784
-		$result = [];
785
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
786
-			$result[] = [
787
-					'id'           => $row['id'],
788
-					'uri'          => $row['uri'],
789
-					'lastmodified' => $row['lastmodified'],
790
-					'etag'         => '"' . $row['etag'] . '"',
791
-					'calendarid'   => $row['calendarid'],
792
-					'size'         => (int)$row['size'],
793
-					'component'    => strtolower($row['componenttype']),
794
-					'classification'=> (int)$row['classification']
795
-			];
796
-		}
797
-
798
-		return $result;
799
-	}
800
-
801
-	/**
802
-	 * Returns information from a single calendar object, based on it's object
803
-	 * uri.
804
-	 *
805
-	 * The object uri is only the basename, or filename and not a full path.
806
-	 *
807
-	 * The returned array must have the same keys as getCalendarObjects. The
808
-	 * 'calendardata' object is required here though, while it's not required
809
-	 * for getCalendarObjects.
810
-	 *
811
-	 * This method must return null if the object did not exist.
812
-	 *
813
-	 * @param mixed $calendarId
814
-	 * @param string $objectUri
815
-	 * @return array|null
816
-	 */
817
-	function getCalendarObject($calendarId, $objectUri) {
818
-
819
-		$query = $this->db->getQueryBuilder();
820
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
821
-				->from('calendarobjects')
822
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
823
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)));
824
-		$stmt = $query->execute();
825
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
826
-
827
-		if(!$row) return null;
828
-
829
-		return [
830
-				'id'            => $row['id'],
831
-				'uri'           => $row['uri'],
832
-				'lastmodified'  => $row['lastmodified'],
833
-				'etag'          => '"' . $row['etag'] . '"',
834
-				'calendarid'    => $row['calendarid'],
835
-				'size'          => (int)$row['size'],
836
-				'calendardata'  => $this->readBlob($row['calendardata']),
837
-				'component'     => strtolower($row['componenttype']),
838
-				'classification'=> (int)$row['classification']
839
-		];
840
-	}
841
-
842
-	/**
843
-	 * Returns a list of calendar objects.
844
-	 *
845
-	 * This method should work identical to getCalendarObject, but instead
846
-	 * return all the calendar objects in the list as an array.
847
-	 *
848
-	 * If the backend supports this, it may allow for some speed-ups.
849
-	 *
850
-	 * @param mixed $calendarId
851
-	 * @param string[] $uris
852
-	 * @return array
853
-	 */
854
-	function getMultipleCalendarObjects($calendarId, array $uris) {
855
-		if (empty($uris)) {
856
-			return [];
857
-		}
858
-
859
-		$chunks = array_chunk($uris, 100);
860
-		$objects = [];
861
-
862
-		$query = $this->db->getQueryBuilder();
863
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
864
-			->from('calendarobjects')
865
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
866
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
867
-
868
-		foreach ($chunks as $uris) {
869
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
870
-			$result = $query->execute();
871
-
872
-			while ($row = $result->fetch()) {
873
-				$objects[] = [
874
-					'id'           => $row['id'],
875
-					'uri'          => $row['uri'],
876
-					'lastmodified' => $row['lastmodified'],
877
-					'etag'         => '"' . $row['etag'] . '"',
878
-					'calendarid'   => $row['calendarid'],
879
-					'size'         => (int)$row['size'],
880
-					'calendardata' => $this->readBlob($row['calendardata']),
881
-					'component'    => strtolower($row['componenttype']),
882
-					'classification' => (int)$row['classification']
883
-				];
884
-			}
885
-			$result->closeCursor();
886
-		}
887
-		return $objects;
888
-	}
889
-
890
-	/**
891
-	 * Creates a new calendar object.
892
-	 *
893
-	 * The object uri is only the basename, or filename and not a full path.
894
-	 *
895
-	 * It is possible return an etag from this function, which will be used in
896
-	 * the response to this PUT request. Note that the ETag must be surrounded
897
-	 * by double-quotes.
898
-	 *
899
-	 * However, you should only really return this ETag if you don't mangle the
900
-	 * calendar-data. If the result of a subsequent GET to this object is not
901
-	 * the exact same as this request body, you should omit the ETag.
902
-	 *
903
-	 * @param mixed $calendarId
904
-	 * @param string $objectUri
905
-	 * @param string $calendarData
906
-	 * @return string
907
-	 */
908
-	function createCalendarObject($calendarId, $objectUri, $calendarData) {
909
-		$extraData = $this->getDenormalizedData($calendarData);
910
-
911
-		$query = $this->db->getQueryBuilder();
912
-		$query->insert('calendarobjects')
913
-			->values([
914
-				'calendarid' => $query->createNamedParameter($calendarId),
915
-				'uri' => $query->createNamedParameter($objectUri),
916
-				'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
917
-				'lastmodified' => $query->createNamedParameter(time()),
918
-				'etag' => $query->createNamedParameter($extraData['etag']),
919
-				'size' => $query->createNamedParameter($extraData['size']),
920
-				'componenttype' => $query->createNamedParameter($extraData['componentType']),
921
-				'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
922
-				'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
923
-				'classification' => $query->createNamedParameter($extraData['classification']),
924
-				'uid' => $query->createNamedParameter($extraData['uid']),
925
-			])
926
-			->execute();
927
-
928
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
929
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
930
-			[
931
-				'calendarId' => $calendarId,
932
-				'calendarData' => $this->getCalendarById($calendarId),
933
-				'shares' => $this->getShares($calendarId),
934
-				'objectData' => $this->getCalendarObject($calendarId, $objectUri),
935
-			]
936
-		));
937
-		$this->addChange($calendarId, $objectUri, 1);
938
-
939
-		return '"' . $extraData['etag'] . '"';
940
-	}
941
-
942
-	/**
943
-	 * Updates an existing calendarobject, based on it's uri.
944
-	 *
945
-	 * The object uri is only the basename, or filename and not a full path.
946
-	 *
947
-	 * It is possible return an etag from this function, which will be used in
948
-	 * the response to this PUT request. Note that the ETag must be surrounded
949
-	 * by double-quotes.
950
-	 *
951
-	 * However, you should only really return this ETag if you don't mangle the
952
-	 * calendar-data. If the result of a subsequent GET to this object is not
953
-	 * the exact same as this request body, you should omit the ETag.
954
-	 *
955
-	 * @param mixed $calendarId
956
-	 * @param string $objectUri
957
-	 * @param string $calendarData
958
-	 * @return string
959
-	 */
960
-	function updateCalendarObject($calendarId, $objectUri, $calendarData) {
961
-		$extraData = $this->getDenormalizedData($calendarData);
962
-
963
-		$query = $this->db->getQueryBuilder();
964
-		$query->update('calendarobjects')
965
-				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
966
-				->set('lastmodified', $query->createNamedParameter(time()))
967
-				->set('etag', $query->createNamedParameter($extraData['etag']))
968
-				->set('size', $query->createNamedParameter($extraData['size']))
969
-				->set('componenttype', $query->createNamedParameter($extraData['componentType']))
970
-				->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
971
-				->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
972
-				->set('classification', $query->createNamedParameter($extraData['classification']))
973
-				->set('uid', $query->createNamedParameter($extraData['uid']))
974
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
975
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
976
-			->execute();
977
-
978
-		$data = $this->getCalendarObject($calendarId, $objectUri);
979
-		if (is_array($data)) {
980
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
981
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
982
-				[
983
-					'calendarId' => $calendarId,
984
-					'calendarData' => $this->getCalendarById($calendarId),
985
-					'shares' => $this->getShares($calendarId),
986
-					'objectData' => $data,
987
-				]
988
-			));
989
-		}
990
-		$this->addChange($calendarId, $objectUri, 2);
991
-
992
-		return '"' . $extraData['etag'] . '"';
993
-	}
994
-
995
-	/**
996
-	 * @param int $calendarObjectId
997
-	 * @param int $classification
998
-	 */
999
-	public function setClassification($calendarObjectId, $classification) {
1000
-		if (!in_array($classification, [
1001
-			self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1002
-		])) {
1003
-			throw new \InvalidArgumentException();
1004
-		}
1005
-		$query = $this->db->getQueryBuilder();
1006
-		$query->update('calendarobjects')
1007
-			->set('classification', $query->createNamedParameter($classification))
1008
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1009
-			->execute();
1010
-	}
1011
-
1012
-	/**
1013
-	 * Deletes an existing calendar object.
1014
-	 *
1015
-	 * The object uri is only the basename, or filename and not a full path.
1016
-	 *
1017
-	 * @param mixed $calendarId
1018
-	 * @param string $objectUri
1019
-	 * @return void
1020
-	 */
1021
-	function deleteCalendarObject($calendarId, $objectUri) {
1022
-		$data = $this->getCalendarObject($calendarId, $objectUri);
1023
-		if (is_array($data)) {
1024
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1025
-				'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1026
-				[
1027
-					'calendarId' => $calendarId,
1028
-					'calendarData' => $this->getCalendarById($calendarId),
1029
-					'shares' => $this->getShares($calendarId),
1030
-					'objectData' => $data,
1031
-				]
1032
-			));
1033
-		}
1034
-
1035
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ?');
1036
-		$stmt->execute([$calendarId, $objectUri]);
1037
-
1038
-		$this->addChange($calendarId, $objectUri, 3);
1039
-	}
1040
-
1041
-	/**
1042
-	 * Performs a calendar-query on the contents of this calendar.
1043
-	 *
1044
-	 * The calendar-query is defined in RFC4791 : CalDAV. Using the
1045
-	 * calendar-query it is possible for a client to request a specific set of
1046
-	 * object, based on contents of iCalendar properties, date-ranges and
1047
-	 * iCalendar component types (VTODO, VEVENT).
1048
-	 *
1049
-	 * This method should just return a list of (relative) urls that match this
1050
-	 * query.
1051
-	 *
1052
-	 * The list of filters are specified as an array. The exact array is
1053
-	 * documented by Sabre\CalDAV\CalendarQueryParser.
1054
-	 *
1055
-	 * Note that it is extremely likely that getCalendarObject for every path
1056
-	 * returned from this method will be called almost immediately after. You
1057
-	 * may want to anticipate this to speed up these requests.
1058
-	 *
1059
-	 * This method provides a default implementation, which parses *all* the
1060
-	 * iCalendar objects in the specified calendar.
1061
-	 *
1062
-	 * This default may well be good enough for personal use, and calendars
1063
-	 * that aren't very large. But if you anticipate high usage, big calendars
1064
-	 * or high loads, you are strongly advised to optimize certain paths.
1065
-	 *
1066
-	 * The best way to do so is override this method and to optimize
1067
-	 * specifically for 'common filters'.
1068
-	 *
1069
-	 * Requests that are extremely common are:
1070
-	 *   * requests for just VEVENTS
1071
-	 *   * requests for just VTODO
1072
-	 *   * requests with a time-range-filter on either VEVENT or VTODO.
1073
-	 *
1074
-	 * ..and combinations of these requests. It may not be worth it to try to
1075
-	 * handle every possible situation and just rely on the (relatively
1076
-	 * easy to use) CalendarQueryValidator to handle the rest.
1077
-	 *
1078
-	 * Note that especially time-range-filters may be difficult to parse. A
1079
-	 * time-range filter specified on a VEVENT must for instance also handle
1080
-	 * recurrence rules correctly.
1081
-	 * A good example of how to interprete all these filters can also simply
1082
-	 * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1083
-	 * as possible, so it gives you a good idea on what type of stuff you need
1084
-	 * to think of.
1085
-	 *
1086
-	 * @param mixed $calendarId
1087
-	 * @param array $filters
1088
-	 * @return array
1089
-	 */
1090
-	function calendarQuery($calendarId, array $filters) {
1091
-		$componentType = null;
1092
-		$requirePostFilter = true;
1093
-		$timeRange = null;
1094
-
1095
-		// if no filters were specified, we don't need to filter after a query
1096
-		if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1097
-			$requirePostFilter = false;
1098
-		}
1099
-
1100
-		// Figuring out if there's a component filter
1101
-		if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1102
-			$componentType = $filters['comp-filters'][0]['name'];
1103
-
1104
-			// Checking if we need post-filters
1105
-			if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1106
-				$requirePostFilter = false;
1107
-			}
1108
-			// There was a time-range filter
1109
-			if ($componentType == 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1110
-				$timeRange = $filters['comp-filters'][0]['time-range'];
1111
-
1112
-				// If start time OR the end time is not specified, we can do a
1113
-				// 100% accurate mysql query.
1114
-				if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1115
-					$requirePostFilter = false;
1116
-				}
1117
-			}
1118
-
1119
-		}
1120
-		$columns = ['uri'];
1121
-		if ($requirePostFilter) {
1122
-			$columns = ['uri', 'calendardata'];
1123
-		}
1124
-		$query = $this->db->getQueryBuilder();
1125
-		$query->select($columns)
1126
-			->from('calendarobjects')
1127
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
1128
-
1129
-		if ($componentType) {
1130
-			$query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1131
-		}
1132
-
1133
-		if ($timeRange && $timeRange['start']) {
1134
-			$query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1135
-		}
1136
-		if ($timeRange && $timeRange['end']) {
1137
-			$query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1138
-		}
1139
-
1140
-		$stmt = $query->execute();
1141
-
1142
-		$result = [];
1143
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1144
-			if ($requirePostFilter) {
1145
-				if (!$this->validateFilterForObject($row, $filters)) {
1146
-					continue;
1147
-				}
1148
-			}
1149
-			$result[] = $row['uri'];
1150
-		}
1151
-
1152
-		return $result;
1153
-	}
1154
-
1155
-	/**
1156
-	 * Searches through all of a users calendars and calendar objects to find
1157
-	 * an object with a specific UID.
1158
-	 *
1159
-	 * This method should return the path to this object, relative to the
1160
-	 * calendar home, so this path usually only contains two parts:
1161
-	 *
1162
-	 * calendarpath/objectpath.ics
1163
-	 *
1164
-	 * If the uid is not found, return null.
1165
-	 *
1166
-	 * This method should only consider * objects that the principal owns, so
1167
-	 * any calendars owned by other principals that also appear in this
1168
-	 * collection should be ignored.
1169
-	 *
1170
-	 * @param string $principalUri
1171
-	 * @param string $uid
1172
-	 * @return string|null
1173
-	 */
1174
-	function getCalendarObjectByUID($principalUri, $uid) {
1175
-
1176
-		$query = $this->db->getQueryBuilder();
1177
-		$query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1178
-			->from('calendarobjects', 'co')
1179
-			->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1180
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1181
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1182
-
1183
-		$stmt = $query->execute();
1184
-
1185
-		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1186
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1187
-		}
1188
-
1189
-		return null;
1190
-	}
1191
-
1192
-	/**
1193
-	 * The getChanges method returns all the changes that have happened, since
1194
-	 * the specified syncToken in the specified calendar.
1195
-	 *
1196
-	 * This function should return an array, such as the following:
1197
-	 *
1198
-	 * [
1199
-	 *   'syncToken' => 'The current synctoken',
1200
-	 *   'added'   => [
1201
-	 *      'new.txt',
1202
-	 *   ],
1203
-	 *   'modified'   => [
1204
-	 *      'modified.txt',
1205
-	 *   ],
1206
-	 *   'deleted' => [
1207
-	 *      'foo.php.bak',
1208
-	 *      'old.txt'
1209
-	 *   ]
1210
-	 * );
1211
-	 *
1212
-	 * The returned syncToken property should reflect the *current* syncToken
1213
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1214
-	 * property This is * needed here too, to ensure the operation is atomic.
1215
-	 *
1216
-	 * If the $syncToken argument is specified as null, this is an initial
1217
-	 * sync, and all members should be reported.
1218
-	 *
1219
-	 * The modified property is an array of nodenames that have changed since
1220
-	 * the last token.
1221
-	 *
1222
-	 * The deleted property is an array with nodenames, that have been deleted
1223
-	 * from collection.
1224
-	 *
1225
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
1226
-	 * 1, you only have to report changes that happened only directly in
1227
-	 * immediate descendants. If it's 2, it should also include changes from
1228
-	 * the nodes below the child collections. (grandchildren)
1229
-	 *
1230
-	 * The $limit argument allows a client to specify how many results should
1231
-	 * be returned at most. If the limit is not specified, it should be treated
1232
-	 * as infinite.
1233
-	 *
1234
-	 * If the limit (infinite or not) is higher than you're willing to return,
1235
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1236
-	 *
1237
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
1238
-	 * return null.
1239
-	 *
1240
-	 * The limit is 'suggestive'. You are free to ignore it.
1241
-	 *
1242
-	 * @param string $calendarId
1243
-	 * @param string $syncToken
1244
-	 * @param int $syncLevel
1245
-	 * @param int $limit
1246
-	 * @return array
1247
-	 */
1248
-	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1249
-		// Current synctoken
1250
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1251
-		$stmt->execute([ $calendarId ]);
1252
-		$currentToken = $stmt->fetchColumn(0);
1253
-
1254
-		if (is_null($currentToken)) {
1255
-			return null;
1256
-		}
1257
-
1258
-		$result = [
1259
-			'syncToken' => $currentToken,
1260
-			'added'     => [],
1261
-			'modified'  => [],
1262
-			'deleted'   => [],
1263
-		];
1264
-
1265
-		if ($syncToken) {
1266
-
1267
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1268
-			if ($limit>0) {
1269
-				$query.= " `LIMIT` " . (int)$limit;
1270
-			}
1271
-
1272
-			// Fetching all changes
1273
-			$stmt = $this->db->prepare($query);
1274
-			$stmt->execute([$syncToken, $currentToken, $calendarId]);
1275
-
1276
-			$changes = [];
1277
-
1278
-			// This loop ensures that any duplicates are overwritten, only the
1279
-			// last change on a node is relevant.
1280
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1281
-
1282
-				$changes[$row['uri']] = $row['operation'];
1283
-
1284
-			}
1285
-
1286
-			foreach($changes as $uri => $operation) {
1287
-
1288
-				switch($operation) {
1289
-					case 1 :
1290
-						$result['added'][] = $uri;
1291
-						break;
1292
-					case 2 :
1293
-						$result['modified'][] = $uri;
1294
-						break;
1295
-					case 3 :
1296
-						$result['deleted'][] = $uri;
1297
-						break;
1298
-				}
1299
-
1300
-			}
1301
-		} else {
1302
-			// No synctoken supplied, this is the initial sync.
1303
-			$query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?";
1304
-			$stmt = $this->db->prepare($query);
1305
-			$stmt->execute([$calendarId]);
1306
-
1307
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1308
-		}
1309
-		return $result;
1310
-
1311
-	}
1312
-
1313
-	/**
1314
-	 * Returns a list of subscriptions for a principal.
1315
-	 *
1316
-	 * Every subscription is an array with the following keys:
1317
-	 *  * id, a unique id that will be used by other functions to modify the
1318
-	 *    subscription. This can be the same as the uri or a database key.
1319
-	 *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1320
-	 *  * principaluri. The owner of the subscription. Almost always the same as
1321
-	 *    principalUri passed to this method.
1322
-	 *
1323
-	 * Furthermore, all the subscription info must be returned too:
1324
-	 *
1325
-	 * 1. {DAV:}displayname
1326
-	 * 2. {http://apple.com/ns/ical/}refreshrate
1327
-	 * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1328
-	 *    should not be stripped).
1329
-	 * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1330
-	 *    should not be stripped).
1331
-	 * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1332
-	 *    attachments should not be stripped).
1333
-	 * 6. {http://calendarserver.org/ns/}source (Must be a
1334
-	 *     Sabre\DAV\Property\Href).
1335
-	 * 7. {http://apple.com/ns/ical/}calendar-color
1336
-	 * 8. {http://apple.com/ns/ical/}calendar-order
1337
-	 * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1338
-	 *    (should just be an instance of
1339
-	 *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1340
-	 *    default components).
1341
-	 *
1342
-	 * @param string $principalUri
1343
-	 * @return array
1344
-	 */
1345
-	function getSubscriptionsForUser($principalUri) {
1346
-		$fields = array_values($this->subscriptionPropertyMap);
1347
-		$fields[] = 'id';
1348
-		$fields[] = 'uri';
1349
-		$fields[] = 'source';
1350
-		$fields[] = 'principaluri';
1351
-		$fields[] = 'lastmodified';
1352
-
1353
-		$query = $this->db->getQueryBuilder();
1354
-		$query->select($fields)
1355
-			->from('calendarsubscriptions')
1356
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1357
-			->orderBy('calendarorder', 'asc');
1358
-		$stmt =$query->execute();
1359
-
1360
-		$subscriptions = [];
1361
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1362
-
1363
-			$subscription = [
1364
-				'id'           => $row['id'],
1365
-				'uri'          => $row['uri'],
1366
-				'principaluri' => $row['principaluri'],
1367
-				'source'       => $row['source'],
1368
-				'lastmodified' => $row['lastmodified'],
1369
-
1370
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1371
-			];
1372
-
1373
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1374
-				if (!is_null($row[$dbName])) {
1375
-					$subscription[$xmlName] = $row[$dbName];
1376
-				}
1377
-			}
1378
-
1379
-			$subscriptions[] = $subscription;
1380
-
1381
-		}
1382
-
1383
-		return $subscriptions;
1384
-	}
1385
-
1386
-	/**
1387
-	 * Creates a new subscription for a principal.
1388
-	 *
1389
-	 * If the creation was a success, an id must be returned that can be used to reference
1390
-	 * this subscription in other methods, such as updateSubscription.
1391
-	 *
1392
-	 * @param string $principalUri
1393
-	 * @param string $uri
1394
-	 * @param array $properties
1395
-	 * @return mixed
1396
-	 */
1397
-	function createSubscription($principalUri, $uri, array $properties) {
1398
-
1399
-		if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1400
-			throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1401
-		}
1402
-
1403
-		$values = [
1404
-			'principaluri' => $principalUri,
1405
-			'uri'          => $uri,
1406
-			'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1407
-			'lastmodified' => time(),
1408
-		];
1409
-
1410
-		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1411
-
1412
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1413
-			if (array_key_exists($xmlName, $properties)) {
1414
-					$values[$dbName] = $properties[$xmlName];
1415
-					if (in_array($dbName, $propertiesBoolean)) {
1416
-						$values[$dbName] = true;
1417
-				}
1418
-			}
1419
-		}
1420
-
1421
-		$valuesToInsert = array();
1422
-
1423
-		$query = $this->db->getQueryBuilder();
1424
-
1425
-		foreach (array_keys($values) as $name) {
1426
-			$valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1427
-		}
1428
-
1429
-		$query->insert('calendarsubscriptions')
1430
-			->values($valuesToInsert)
1431
-			->execute();
1432
-
1433
-		return $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1434
-	}
1435
-
1436
-	/**
1437
-	 * Updates a subscription
1438
-	 *
1439
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1440
-	 * To do the actual updates, you must tell this object which properties
1441
-	 * you're going to process with the handle() method.
1442
-	 *
1443
-	 * Calling the handle method is like telling the PropPatch object "I
1444
-	 * promise I can handle updating this property".
1445
-	 *
1446
-	 * Read the PropPatch documentation for more info and examples.
1447
-	 *
1448
-	 * @param mixed $subscriptionId
1449
-	 * @param PropPatch $propPatch
1450
-	 * @return void
1451
-	 */
1452
-	function updateSubscription($subscriptionId, PropPatch $propPatch) {
1453
-		$supportedProperties = array_keys($this->subscriptionPropertyMap);
1454
-		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
1455
-
1456
-		$propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1457
-
1458
-			$newValues = [];
1459
-
1460
-			foreach($mutations as $propertyName=>$propertyValue) {
1461
-				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1462
-					$newValues['source'] = $propertyValue->getHref();
1463
-				} else {
1464
-					$fieldName = $this->subscriptionPropertyMap[$propertyName];
1465
-					$newValues[$fieldName] = $propertyValue;
1466
-				}
1467
-			}
1468
-
1469
-			$query = $this->db->getQueryBuilder();
1470
-			$query->update('calendarsubscriptions')
1471
-				->set('lastmodified', $query->createNamedParameter(time()));
1472
-			foreach($newValues as $fieldName=>$value) {
1473
-				$query->set($fieldName, $query->createNamedParameter($value));
1474
-			}
1475
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1476
-				->execute();
1477
-
1478
-			return true;
1479
-
1480
-		});
1481
-	}
1482
-
1483
-	/**
1484
-	 * Deletes a subscription.
1485
-	 *
1486
-	 * @param mixed $subscriptionId
1487
-	 * @return void
1488
-	 */
1489
-	function deleteSubscription($subscriptionId) {
1490
-		$query = $this->db->getQueryBuilder();
1491
-		$query->delete('calendarsubscriptions')
1492
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1493
-			->execute();
1494
-	}
1495
-
1496
-	/**
1497
-	 * Returns a single scheduling object for the inbox collection.
1498
-	 *
1499
-	 * The returned array should contain the following elements:
1500
-	 *   * uri - A unique basename for the object. This will be used to
1501
-	 *           construct a full uri.
1502
-	 *   * calendardata - The iCalendar object
1503
-	 *   * lastmodified - The last modification date. Can be an int for a unix
1504
-	 *                    timestamp, or a PHP DateTime object.
1505
-	 *   * etag - A unique token that must change if the object changed.
1506
-	 *   * size - The size of the object, in bytes.
1507
-	 *
1508
-	 * @param string $principalUri
1509
-	 * @param string $objectUri
1510
-	 * @return array
1511
-	 */
1512
-	function getSchedulingObject($principalUri, $objectUri) {
1513
-		$query = $this->db->getQueryBuilder();
1514
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1515
-			->from('schedulingobjects')
1516
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1517
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1518
-			->execute();
1519
-
1520
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
1521
-
1522
-		if(!$row) {
1523
-			return null;
1524
-		}
1525
-
1526
-		return [
1527
-				'uri'          => $row['uri'],
1528
-				'calendardata' => $row['calendardata'],
1529
-				'lastmodified' => $row['lastmodified'],
1530
-				'etag'         => '"' . $row['etag'] . '"',
1531
-				'size'         => (int)$row['size'],
1532
-		];
1533
-	}
1534
-
1535
-	/**
1536
-	 * Returns all scheduling objects for the inbox collection.
1537
-	 *
1538
-	 * These objects should be returned as an array. Every item in the array
1539
-	 * should follow the same structure as returned from getSchedulingObject.
1540
-	 *
1541
-	 * The main difference is that 'calendardata' is optional.
1542
-	 *
1543
-	 * @param string $principalUri
1544
-	 * @return array
1545
-	 */
1546
-	function getSchedulingObjects($principalUri) {
1547
-		$query = $this->db->getQueryBuilder();
1548
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1549
-				->from('schedulingobjects')
1550
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1551
-				->execute();
1552
-
1553
-		$result = [];
1554
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1555
-			$result[] = [
1556
-					'calendardata' => $row['calendardata'],
1557
-					'uri'          => $row['uri'],
1558
-					'lastmodified' => $row['lastmodified'],
1559
-					'etag'         => '"' . $row['etag'] . '"',
1560
-					'size'         => (int)$row['size'],
1561
-			];
1562
-		}
1563
-
1564
-		return $result;
1565
-	}
1566
-
1567
-	/**
1568
-	 * Deletes a scheduling object from the inbox collection.
1569
-	 *
1570
-	 * @param string $principalUri
1571
-	 * @param string $objectUri
1572
-	 * @return void
1573
-	 */
1574
-	function deleteSchedulingObject($principalUri, $objectUri) {
1575
-		$query = $this->db->getQueryBuilder();
1576
-		$query->delete('schedulingobjects')
1577
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1578
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1579
-				->execute();
1580
-	}
1581
-
1582
-	/**
1583
-	 * Creates a new scheduling object. This should land in a users' inbox.
1584
-	 *
1585
-	 * @param string $principalUri
1586
-	 * @param string $objectUri
1587
-	 * @param string $objectData
1588
-	 * @return void
1589
-	 */
1590
-	function createSchedulingObject($principalUri, $objectUri, $objectData) {
1591
-		$query = $this->db->getQueryBuilder();
1592
-		$query->insert('schedulingobjects')
1593
-			->values([
1594
-				'principaluri' => $query->createNamedParameter($principalUri),
1595
-				'calendardata' => $query->createNamedParameter($objectData),
1596
-				'uri' => $query->createNamedParameter($objectUri),
1597
-				'lastmodified' => $query->createNamedParameter(time()),
1598
-				'etag' => $query->createNamedParameter(md5($objectData)),
1599
-				'size' => $query->createNamedParameter(strlen($objectData))
1600
-			])
1601
-			->execute();
1602
-	}
1603
-
1604
-	/**
1605
-	 * Adds a change record to the calendarchanges table.
1606
-	 *
1607
-	 * @param mixed $calendarId
1608
-	 * @param string $objectUri
1609
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete.
1610
-	 * @return void
1611
-	 */
1612
-	protected function addChange($calendarId, $objectUri, $operation) {
1613
-
1614
-		$stmt = $this->db->prepare('INSERT INTO `*PREFIX*calendarchanges` (`uri`, `synctoken`, `calendarid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*calendars` WHERE `id` = ?');
1615
-		$stmt->execute([
1616
-			$objectUri,
1617
-			$calendarId,
1618
-			$operation,
1619
-			$calendarId
1620
-		]);
1621
-		$stmt = $this->db->prepare('UPDATE `*PREFIX*calendars` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
1622
-		$stmt->execute([
1623
-			$calendarId
1624
-		]);
1625
-
1626
-	}
1627
-
1628
-	/**
1629
-	 * Parses some information from calendar objects, used for optimized
1630
-	 * calendar-queries.
1631
-	 *
1632
-	 * Returns an array with the following keys:
1633
-	 *   * etag - An md5 checksum of the object without the quotes.
1634
-	 *   * size - Size of the object in bytes
1635
-	 *   * componentType - VEVENT, VTODO or VJOURNAL
1636
-	 *   * firstOccurence
1637
-	 *   * lastOccurence
1638
-	 *   * uid - value of the UID property
1639
-	 *
1640
-	 * @param string $calendarData
1641
-	 * @return array
1642
-	 */
1643
-	public function getDenormalizedData($calendarData) {
1644
-
1645
-		$vObject = Reader::read($calendarData);
1646
-		$componentType = null;
1647
-		$component = null;
1648
-		$firstOccurrence = null;
1649
-		$lastOccurrence = null;
1650
-		$uid = null;
1651
-		$classification = self::CLASSIFICATION_PUBLIC;
1652
-		foreach($vObject->getComponents() as $component) {
1653
-			if ($component->name!=='VTIMEZONE') {
1654
-				$componentType = $component->name;
1655
-				$uid = (string)$component->UID;
1656
-				break;
1657
-			}
1658
-		}
1659
-		if (!$componentType) {
1660
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
1661
-		}
1662
-		if ($componentType === 'VEVENT' && $component->DTSTART) {
1663
-			$firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
1664
-			// Finding the last occurrence is a bit harder
1665
-			if (!isset($component->RRULE)) {
1666
-				if (isset($component->DTEND)) {
1667
-					$lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
1668
-				} elseif (isset($component->DURATION)) {
1669
-					$endDate = clone $component->DTSTART->getDateTime();
1670
-					$endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
1671
-					$lastOccurrence = $endDate->getTimeStamp();
1672
-				} elseif (!$component->DTSTART->hasTime()) {
1673
-					$endDate = clone $component->DTSTART->getDateTime();
1674
-					$endDate->modify('+1 day');
1675
-					$lastOccurrence = $endDate->getTimeStamp();
1676
-				} else {
1677
-					$lastOccurrence = $firstOccurrence;
1678
-				}
1679
-			} else {
1680
-				$it = new EventIterator($vObject, (string)$component->UID);
1681
-				$maxDate = new \DateTime(self::MAX_DATE);
1682
-				if ($it->isInfinite()) {
1683
-					$lastOccurrence = $maxDate->getTimestamp();
1684
-				} else {
1685
-					$end = $it->getDtEnd();
1686
-					while($it->valid() && $end < $maxDate) {
1687
-						$end = $it->getDtEnd();
1688
-						$it->next();
1689
-
1690
-					}
1691
-					$lastOccurrence = $end->getTimestamp();
1692
-				}
1693
-
1694
-			}
1695
-		}
1696
-
1697
-		if ($component->CLASS) {
1698
-			$classification = CalDavBackend::CLASSIFICATION_PRIVATE;
1699
-			switch ($component->CLASS->getValue()) {
1700
-				case 'PUBLIC':
1701
-					$classification = CalDavBackend::CLASSIFICATION_PUBLIC;
1702
-					break;
1703
-				case 'CONFIDENTIAL':
1704
-					$classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
1705
-					break;
1706
-			}
1707
-		}
1708
-		return [
1709
-			'etag' => md5($calendarData),
1710
-			'size' => strlen($calendarData),
1711
-			'componentType' => $componentType,
1712
-			'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
1713
-			'lastOccurence'  => $lastOccurrence,
1714
-			'uid' => $uid,
1715
-			'classification' => $classification
1716
-		];
1717
-
1718
-	}
1719
-
1720
-	private function readBlob($cardData) {
1721
-		if (is_resource($cardData)) {
1722
-			return stream_get_contents($cardData);
1723
-		}
1724
-
1725
-		return $cardData;
1726
-	}
1727
-
1728
-	/**
1729
-	 * @param IShareable $shareable
1730
-	 * @param array $add
1731
-	 * @param array $remove
1732
-	 */
1733
-	public function updateShares($shareable, $add, $remove) {
1734
-		$calendarId = $shareable->getResourceId();
1735
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
1736
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
1737
-			[
1738
-				'calendarId' => $calendarId,
1739
-				'calendarData' => $this->getCalendarById($calendarId),
1740
-				'shares' => $this->getShares($calendarId),
1741
-				'add' => $add,
1742
-				'remove' => $remove,
1743
-			]));
1744
-		$this->sharingBackend->updateShares($shareable, $add, $remove);
1745
-	}
1746
-
1747
-	/**
1748
-	 * @param int $resourceId
1749
-	 * @return array
1750
-	 */
1751
-	public function getShares($resourceId) {
1752
-		return $this->sharingBackend->getShares($resourceId);
1753
-	}
1754
-
1755
-	/**
1756
-	 * @param boolean $value
1757
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
1758
-	 * @return string|null
1759
-	 */
1760
-	public function setPublishStatus($value, $calendar) {
1761
-		$query = $this->db->getQueryBuilder();
1762
-		if ($value) {
1763
-			$publicUri = $this->random->generate(16, ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_DIGITS);
1764
-			$query->insert('dav_shares')
1765
-				->values([
1766
-					'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
1767
-					'type' => $query->createNamedParameter('calendar'),
1768
-					'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
1769
-					'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
1770
-					'publicuri' => $query->createNamedParameter($publicUri)
1771
-				]);
1772
-			$query->execute();
1773
-			return $publicUri;
1774
-		}
1775
-		$query->delete('dav_shares')
1776
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1777
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
1778
-		$query->execute();
1779
-		return null;
1780
-	}
1781
-
1782
-	/**
1783
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
1784
-	 * @return mixed
1785
-	 */
1786
-	public function getPublishStatus($calendar) {
1787
-		$query = $this->db->getQueryBuilder();
1788
-		$result = $query->select('publicuri')
1789
-			->from('dav_shares')
1790
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1791
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
1792
-			->execute();
1793
-
1794
-		$row = $result->fetch();
1795
-		$result->closeCursor();
1796
-		return $row ? reset($row) : false;
1797
-	}
1798
-
1799
-	/**
1800
-	 * @param int $resourceId
1801
-	 * @param array $acl
1802
-	 * @return array
1803
-	 */
1804
-	public function applyShareAcl($resourceId, $acl) {
1805
-		return $this->sharingBackend->applyShareAcl($resourceId, $acl);
1806
-	}
1807
-
1808
-	private function convertPrincipal($principalUri, $toV2) {
1809
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1810
-			list(, $name) = URLUtil::splitPath($principalUri);
1811
-			if ($toV2 === true) {
1812
-				return "principals/users/$name";
1813
-			}
1814
-			return "principals/$name";
1815
-		}
1816
-		return $principalUri;
1817
-	}
385
+    /**
386
+     * @return array
387
+     */
388
+    public function getPublicCalendars() {
389
+        $fields = array_values($this->propertyMap);
390
+        $fields[] = 'a.id';
391
+        $fields[] = 'a.uri';
392
+        $fields[] = 'a.synctoken';
393
+        $fields[] = 'a.components';
394
+        $fields[] = 'a.principaluri';
395
+        $fields[] = 'a.transparent';
396
+        $fields[] = 's.access';
397
+        $fields[] = 's.publicuri';
398
+        $calendars = [];
399
+        $query = $this->db->getQueryBuilder();
400
+        $result = $query->select($fields)
401
+            ->from('dav_shares', 's')
402
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
403
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
404
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
405
+            ->execute();
406
+
407
+        while($row = $result->fetch()) {
408
+            list(, $name) = URLUtil::splitPath($row['principaluri']);
409
+            $row['displayname'] = $row['displayname'] . "($name)";
410
+            $components = [];
411
+            if ($row['components']) {
412
+                $components = explode(',',$row['components']);
413
+            }
414
+            $calendar = [
415
+                'id' => $row['id'],
416
+                'uri' => $row['publicuri'],
417
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
418
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
419
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
420
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
421
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
422
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
423
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
424
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
425
+            ];
426
+
427
+            foreach($this->propertyMap as $xmlName=>$dbName) {
428
+                $calendar[$xmlName] = $row[$dbName];
429
+            }
430
+
431
+            if (!isset($calendars[$calendar['id']])) {
432
+                $calendars[$calendar['id']] = $calendar;
433
+            }
434
+        }
435
+        $result->closeCursor();
436
+
437
+        return array_values($calendars);
438
+    }
439
+
440
+    /**
441
+     * @param string $uri
442
+     * @return array
443
+     * @throws NotFound
444
+     */
445
+    public function getPublicCalendar($uri) {
446
+        $fields = array_values($this->propertyMap);
447
+        $fields[] = 'a.id';
448
+        $fields[] = 'a.uri';
449
+        $fields[] = 'a.synctoken';
450
+        $fields[] = 'a.components';
451
+        $fields[] = 'a.principaluri';
452
+        $fields[] = 'a.transparent';
453
+        $fields[] = 's.access';
454
+        $fields[] = 's.publicuri';
455
+        $query = $this->db->getQueryBuilder();
456
+        $result = $query->select($fields)
457
+            ->from('dav_shares', 's')
458
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
459
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
460
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
461
+            ->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
462
+            ->execute();
463
+
464
+        $row = $result->fetch(\PDO::FETCH_ASSOC);
465
+
466
+        $result->closeCursor();
467
+
468
+        if ($row === false) {
469
+            throw new NotFound('Node with name \'' . $uri . '\' could not be found');
470
+        }
471
+
472
+        list(, $name) = URLUtil::splitPath($row['principaluri']);
473
+        $row['displayname'] = $row['displayname'] . ' ' . "($name)";
474
+        $components = [];
475
+        if ($row['components']) {
476
+            $components = explode(',',$row['components']);
477
+        }
478
+        $calendar = [
479
+            'id' => $row['id'],
480
+            'uri' => $row['publicuri'],
481
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
482
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
483
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
484
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
485
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
486
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
487
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
488
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
489
+        ];
490
+
491
+        foreach($this->propertyMap as $xmlName=>$dbName) {
492
+            $calendar[$xmlName] = $row[$dbName];
493
+        }
494
+
495
+        return $calendar;
496
+
497
+    }
498
+
499
+    /**
500
+     * @param string $principal
501
+     * @param string $uri
502
+     * @return array|null
503
+     */
504
+    public function getCalendarByUri($principal, $uri) {
505
+        $fields = array_values($this->propertyMap);
506
+        $fields[] = 'id';
507
+        $fields[] = 'uri';
508
+        $fields[] = 'synctoken';
509
+        $fields[] = 'components';
510
+        $fields[] = 'principaluri';
511
+        $fields[] = 'transparent';
512
+
513
+        // Making fields a comma-delimited list
514
+        $query = $this->db->getQueryBuilder();
515
+        $query->select($fields)->from('calendars')
516
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
517
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
518
+            ->setMaxResults(1);
519
+        $stmt = $query->execute();
520
+
521
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
522
+        $stmt->closeCursor();
523
+        if ($row === false) {
524
+            return null;
525
+        }
526
+
527
+        $components = [];
528
+        if ($row['components']) {
529
+            $components = explode(',',$row['components']);
530
+        }
531
+
532
+        $calendar = [
533
+            'id' => $row['id'],
534
+            'uri' => $row['uri'],
535
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
536
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
537
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
538
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
539
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
540
+        ];
541
+
542
+        foreach($this->propertyMap as $xmlName=>$dbName) {
543
+            $calendar[$xmlName] = $row[$dbName];
544
+        }
545
+
546
+        return $calendar;
547
+    }
548
+
549
+    public function getCalendarById($calendarId) {
550
+        $fields = array_values($this->propertyMap);
551
+        $fields[] = 'id';
552
+        $fields[] = 'uri';
553
+        $fields[] = 'synctoken';
554
+        $fields[] = 'components';
555
+        $fields[] = 'principaluri';
556
+        $fields[] = 'transparent';
557
+
558
+        // Making fields a comma-delimited list
559
+        $query = $this->db->getQueryBuilder();
560
+        $query->select($fields)->from('calendars')
561
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
562
+            ->setMaxResults(1);
563
+        $stmt = $query->execute();
564
+
565
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
566
+        $stmt->closeCursor();
567
+        if ($row === false) {
568
+            return null;
569
+        }
570
+
571
+        $components = [];
572
+        if ($row['components']) {
573
+            $components = explode(',',$row['components']);
574
+        }
575
+
576
+        $calendar = [
577
+            'id' => $row['id'],
578
+            'uri' => $row['uri'],
579
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
580
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
581
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
582
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
583
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
584
+        ];
585
+
586
+        foreach($this->propertyMap as $xmlName=>$dbName) {
587
+            $calendar[$xmlName] = $row[$dbName];
588
+        }
589
+
590
+        return $calendar;
591
+    }
592
+
593
+    /**
594
+     * Creates a new calendar for a principal.
595
+     *
596
+     * If the creation was a success, an id must be returned that can be used to reference
597
+     * this calendar in other methods, such as updateCalendar.
598
+     *
599
+     * @param string $principalUri
600
+     * @param string $calendarUri
601
+     * @param array $properties
602
+     * @return int
603
+     */
604
+    function createCalendar($principalUri, $calendarUri, array $properties) {
605
+        $values = [
606
+            'principaluri' => $this->convertPrincipal($principalUri, true),
607
+            'uri'          => $calendarUri,
608
+            'synctoken'    => 1,
609
+            'transparent'  => 0,
610
+            'components'   => 'VEVENT,VTODO',
611
+            'displayname'  => $calendarUri
612
+        ];
613
+
614
+        // Default value
615
+        $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
616
+        if (isset($properties[$sccs])) {
617
+            if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
618
+                throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
619
+            }
620
+            $values['components'] = implode(',',$properties[$sccs]->getValue());
621
+        }
622
+        $transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
623
+        if (isset($properties[$transp])) {
624
+            $values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
625
+        }
626
+
627
+        foreach($this->propertyMap as $xmlName=>$dbName) {
628
+            if (isset($properties[$xmlName])) {
629
+                $values[$dbName] = $properties[$xmlName];
630
+            }
631
+        }
632
+
633
+        $query = $this->db->getQueryBuilder();
634
+        $query->insert('calendars');
635
+        foreach($values as $column => $value) {
636
+            $query->setValue($column, $query->createNamedParameter($value));
637
+        }
638
+        $query->execute();
639
+        $calendarId = $query->getLastInsertId();
640
+
641
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
642
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
643
+            [
644
+                'calendarId' => $calendarId,
645
+                'calendarData' => $this->getCalendarById($calendarId),
646
+        ]));
647
+
648
+        return $calendarId;
649
+    }
650
+
651
+    /**
652
+     * Updates properties for a calendar.
653
+     *
654
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
655
+     * To do the actual updates, you must tell this object which properties
656
+     * you're going to process with the handle() method.
657
+     *
658
+     * Calling the handle method is like telling the PropPatch object "I
659
+     * promise I can handle updating this property".
660
+     *
661
+     * Read the PropPatch documentation for more info and examples.
662
+     *
663
+     * @param PropPatch $propPatch
664
+     * @return void
665
+     */
666
+    function updateCalendar($calendarId, PropPatch $propPatch) {
667
+        $supportedProperties = array_keys($this->propertyMap);
668
+        $supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
669
+
670
+        $propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
671
+            $newValues = [];
672
+            foreach ($mutations as $propertyName => $propertyValue) {
673
+
674
+                switch ($propertyName) {
675
+                    case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
676
+                        $fieldName = 'transparent';
677
+                        $newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
678
+                        break;
679
+                    default :
680
+                        $fieldName = $this->propertyMap[$propertyName];
681
+                        $newValues[$fieldName] = $propertyValue;
682
+                        break;
683
+                }
684
+
685
+            }
686
+            $query = $this->db->getQueryBuilder();
687
+            $query->update('calendars');
688
+            foreach ($newValues as $fieldName => $value) {
689
+                $query->set($fieldName, $query->createNamedParameter($value));
690
+            }
691
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
692
+            $query->execute();
693
+
694
+            $this->addChange($calendarId, "", 2);
695
+
696
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
697
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
698
+                [
699
+                    'calendarId' => $calendarId,
700
+                    'calendarData' => $this->getCalendarById($calendarId),
701
+                    'shares' => $this->getShares($calendarId),
702
+                    'propertyMutations' => $mutations,
703
+            ]));
704
+
705
+            return true;
706
+        });
707
+    }
708
+
709
+    /**
710
+     * Delete a calendar and all it's objects
711
+     *
712
+     * @param mixed $calendarId
713
+     * @return void
714
+     */
715
+    function deleteCalendar($calendarId) {
716
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
717
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
718
+            [
719
+                'calendarId' => $calendarId,
720
+                'calendarData' => $this->getCalendarById($calendarId),
721
+                'shares' => $this->getShares($calendarId),
722
+        ]));
723
+
724
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?');
725
+        $stmt->execute([$calendarId]);
726
+
727
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
728
+        $stmt->execute([$calendarId]);
729
+
730
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ?');
731
+        $stmt->execute([$calendarId]);
732
+
733
+        $this->sharingBackend->deleteAllShares($calendarId);
734
+    }
735
+
736
+    /**
737
+     * Delete all of an user's shares
738
+     *
739
+     * @param string $principaluri
740
+     * @return void
741
+     */
742
+    function deleteAllSharesByUser($principaluri) {
743
+        $this->sharingBackend->deleteAllSharesByUser($principaluri);
744
+    }
745
+
746
+    /**
747
+     * Returns all calendar objects within a calendar.
748
+     *
749
+     * Every item contains an array with the following keys:
750
+     *   * calendardata - The iCalendar-compatible calendar data
751
+     *   * uri - a unique key which will be used to construct the uri. This can
752
+     *     be any arbitrary string, but making sure it ends with '.ics' is a
753
+     *     good idea. This is only the basename, or filename, not the full
754
+     *     path.
755
+     *   * lastmodified - a timestamp of the last modification time
756
+     *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
757
+     *   '"abcdef"')
758
+     *   * size - The size of the calendar objects, in bytes.
759
+     *   * component - optional, a string containing the type of object, such
760
+     *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
761
+     *     the Content-Type header.
762
+     *
763
+     * Note that the etag is optional, but it's highly encouraged to return for
764
+     * speed reasons.
765
+     *
766
+     * The calendardata is also optional. If it's not returned
767
+     * 'getCalendarObject' will be called later, which *is* expected to return
768
+     * calendardata.
769
+     *
770
+     * If neither etag or size are specified, the calendardata will be
771
+     * used/fetched to determine these numbers. If both are specified the
772
+     * amount of times this is needed is reduced by a great degree.
773
+     *
774
+     * @param mixed $calendarId
775
+     * @return array
776
+     */
777
+    function getCalendarObjects($calendarId) {
778
+        $query = $this->db->getQueryBuilder();
779
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
780
+            ->from('calendarobjects')
781
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
782
+        $stmt = $query->execute();
783
+
784
+        $result = [];
785
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
786
+            $result[] = [
787
+                    'id'           => $row['id'],
788
+                    'uri'          => $row['uri'],
789
+                    'lastmodified' => $row['lastmodified'],
790
+                    'etag'         => '"' . $row['etag'] . '"',
791
+                    'calendarid'   => $row['calendarid'],
792
+                    'size'         => (int)$row['size'],
793
+                    'component'    => strtolower($row['componenttype']),
794
+                    'classification'=> (int)$row['classification']
795
+            ];
796
+        }
797
+
798
+        return $result;
799
+    }
800
+
801
+    /**
802
+     * Returns information from a single calendar object, based on it's object
803
+     * uri.
804
+     *
805
+     * The object uri is only the basename, or filename and not a full path.
806
+     *
807
+     * The returned array must have the same keys as getCalendarObjects. The
808
+     * 'calendardata' object is required here though, while it's not required
809
+     * for getCalendarObjects.
810
+     *
811
+     * This method must return null if the object did not exist.
812
+     *
813
+     * @param mixed $calendarId
814
+     * @param string $objectUri
815
+     * @return array|null
816
+     */
817
+    function getCalendarObject($calendarId, $objectUri) {
818
+
819
+        $query = $this->db->getQueryBuilder();
820
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
821
+                ->from('calendarobjects')
822
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
823
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)));
824
+        $stmt = $query->execute();
825
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
826
+
827
+        if(!$row) return null;
828
+
829
+        return [
830
+                'id'            => $row['id'],
831
+                'uri'           => $row['uri'],
832
+                'lastmodified'  => $row['lastmodified'],
833
+                'etag'          => '"' . $row['etag'] . '"',
834
+                'calendarid'    => $row['calendarid'],
835
+                'size'          => (int)$row['size'],
836
+                'calendardata'  => $this->readBlob($row['calendardata']),
837
+                'component'     => strtolower($row['componenttype']),
838
+                'classification'=> (int)$row['classification']
839
+        ];
840
+    }
841
+
842
+    /**
843
+     * Returns a list of calendar objects.
844
+     *
845
+     * This method should work identical to getCalendarObject, but instead
846
+     * return all the calendar objects in the list as an array.
847
+     *
848
+     * If the backend supports this, it may allow for some speed-ups.
849
+     *
850
+     * @param mixed $calendarId
851
+     * @param string[] $uris
852
+     * @return array
853
+     */
854
+    function getMultipleCalendarObjects($calendarId, array $uris) {
855
+        if (empty($uris)) {
856
+            return [];
857
+        }
858
+
859
+        $chunks = array_chunk($uris, 100);
860
+        $objects = [];
861
+
862
+        $query = $this->db->getQueryBuilder();
863
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
864
+            ->from('calendarobjects')
865
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
866
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
867
+
868
+        foreach ($chunks as $uris) {
869
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
870
+            $result = $query->execute();
871
+
872
+            while ($row = $result->fetch()) {
873
+                $objects[] = [
874
+                    'id'           => $row['id'],
875
+                    'uri'          => $row['uri'],
876
+                    'lastmodified' => $row['lastmodified'],
877
+                    'etag'         => '"' . $row['etag'] . '"',
878
+                    'calendarid'   => $row['calendarid'],
879
+                    'size'         => (int)$row['size'],
880
+                    'calendardata' => $this->readBlob($row['calendardata']),
881
+                    'component'    => strtolower($row['componenttype']),
882
+                    'classification' => (int)$row['classification']
883
+                ];
884
+            }
885
+            $result->closeCursor();
886
+        }
887
+        return $objects;
888
+    }
889
+
890
+    /**
891
+     * Creates a new calendar object.
892
+     *
893
+     * The object uri is only the basename, or filename and not a full path.
894
+     *
895
+     * It is possible return an etag from this function, which will be used in
896
+     * the response to this PUT request. Note that the ETag must be surrounded
897
+     * by double-quotes.
898
+     *
899
+     * However, you should only really return this ETag if you don't mangle the
900
+     * calendar-data. If the result of a subsequent GET to this object is not
901
+     * the exact same as this request body, you should omit the ETag.
902
+     *
903
+     * @param mixed $calendarId
904
+     * @param string $objectUri
905
+     * @param string $calendarData
906
+     * @return string
907
+     */
908
+    function createCalendarObject($calendarId, $objectUri, $calendarData) {
909
+        $extraData = $this->getDenormalizedData($calendarData);
910
+
911
+        $query = $this->db->getQueryBuilder();
912
+        $query->insert('calendarobjects')
913
+            ->values([
914
+                'calendarid' => $query->createNamedParameter($calendarId),
915
+                'uri' => $query->createNamedParameter($objectUri),
916
+                'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
917
+                'lastmodified' => $query->createNamedParameter(time()),
918
+                'etag' => $query->createNamedParameter($extraData['etag']),
919
+                'size' => $query->createNamedParameter($extraData['size']),
920
+                'componenttype' => $query->createNamedParameter($extraData['componentType']),
921
+                'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
922
+                'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
923
+                'classification' => $query->createNamedParameter($extraData['classification']),
924
+                'uid' => $query->createNamedParameter($extraData['uid']),
925
+            ])
926
+            ->execute();
927
+
928
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
929
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
930
+            [
931
+                'calendarId' => $calendarId,
932
+                'calendarData' => $this->getCalendarById($calendarId),
933
+                'shares' => $this->getShares($calendarId),
934
+                'objectData' => $this->getCalendarObject($calendarId, $objectUri),
935
+            ]
936
+        ));
937
+        $this->addChange($calendarId, $objectUri, 1);
938
+
939
+        return '"' . $extraData['etag'] . '"';
940
+    }
941
+
942
+    /**
943
+     * Updates an existing calendarobject, based on it's uri.
944
+     *
945
+     * The object uri is only the basename, or filename and not a full path.
946
+     *
947
+     * It is possible return an etag from this function, which will be used in
948
+     * the response to this PUT request. Note that the ETag must be surrounded
949
+     * by double-quotes.
950
+     *
951
+     * However, you should only really return this ETag if you don't mangle the
952
+     * calendar-data. If the result of a subsequent GET to this object is not
953
+     * the exact same as this request body, you should omit the ETag.
954
+     *
955
+     * @param mixed $calendarId
956
+     * @param string $objectUri
957
+     * @param string $calendarData
958
+     * @return string
959
+     */
960
+    function updateCalendarObject($calendarId, $objectUri, $calendarData) {
961
+        $extraData = $this->getDenormalizedData($calendarData);
962
+
963
+        $query = $this->db->getQueryBuilder();
964
+        $query->update('calendarobjects')
965
+                ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
966
+                ->set('lastmodified', $query->createNamedParameter(time()))
967
+                ->set('etag', $query->createNamedParameter($extraData['etag']))
968
+                ->set('size', $query->createNamedParameter($extraData['size']))
969
+                ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
970
+                ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
971
+                ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
972
+                ->set('classification', $query->createNamedParameter($extraData['classification']))
973
+                ->set('uid', $query->createNamedParameter($extraData['uid']))
974
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
975
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
976
+            ->execute();
977
+
978
+        $data = $this->getCalendarObject($calendarId, $objectUri);
979
+        if (is_array($data)) {
980
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
981
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
982
+                [
983
+                    'calendarId' => $calendarId,
984
+                    'calendarData' => $this->getCalendarById($calendarId),
985
+                    'shares' => $this->getShares($calendarId),
986
+                    'objectData' => $data,
987
+                ]
988
+            ));
989
+        }
990
+        $this->addChange($calendarId, $objectUri, 2);
991
+
992
+        return '"' . $extraData['etag'] . '"';
993
+    }
994
+
995
+    /**
996
+     * @param int $calendarObjectId
997
+     * @param int $classification
998
+     */
999
+    public function setClassification($calendarObjectId, $classification) {
1000
+        if (!in_array($classification, [
1001
+            self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1002
+        ])) {
1003
+            throw new \InvalidArgumentException();
1004
+        }
1005
+        $query = $this->db->getQueryBuilder();
1006
+        $query->update('calendarobjects')
1007
+            ->set('classification', $query->createNamedParameter($classification))
1008
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1009
+            ->execute();
1010
+    }
1011
+
1012
+    /**
1013
+     * Deletes an existing calendar object.
1014
+     *
1015
+     * The object uri is only the basename, or filename and not a full path.
1016
+     *
1017
+     * @param mixed $calendarId
1018
+     * @param string $objectUri
1019
+     * @return void
1020
+     */
1021
+    function deleteCalendarObject($calendarId, $objectUri) {
1022
+        $data = $this->getCalendarObject($calendarId, $objectUri);
1023
+        if (is_array($data)) {
1024
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1025
+                '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1026
+                [
1027
+                    'calendarId' => $calendarId,
1028
+                    'calendarData' => $this->getCalendarById($calendarId),
1029
+                    'shares' => $this->getShares($calendarId),
1030
+                    'objectData' => $data,
1031
+                ]
1032
+            ));
1033
+        }
1034
+
1035
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ?');
1036
+        $stmt->execute([$calendarId, $objectUri]);
1037
+
1038
+        $this->addChange($calendarId, $objectUri, 3);
1039
+    }
1040
+
1041
+    /**
1042
+     * Performs a calendar-query on the contents of this calendar.
1043
+     *
1044
+     * The calendar-query is defined in RFC4791 : CalDAV. Using the
1045
+     * calendar-query it is possible for a client to request a specific set of
1046
+     * object, based on contents of iCalendar properties, date-ranges and
1047
+     * iCalendar component types (VTODO, VEVENT).
1048
+     *
1049
+     * This method should just return a list of (relative) urls that match this
1050
+     * query.
1051
+     *
1052
+     * The list of filters are specified as an array. The exact array is
1053
+     * documented by Sabre\CalDAV\CalendarQueryParser.
1054
+     *
1055
+     * Note that it is extremely likely that getCalendarObject for every path
1056
+     * returned from this method will be called almost immediately after. You
1057
+     * may want to anticipate this to speed up these requests.
1058
+     *
1059
+     * This method provides a default implementation, which parses *all* the
1060
+     * iCalendar objects in the specified calendar.
1061
+     *
1062
+     * This default may well be good enough for personal use, and calendars
1063
+     * that aren't very large. But if you anticipate high usage, big calendars
1064
+     * or high loads, you are strongly advised to optimize certain paths.
1065
+     *
1066
+     * The best way to do so is override this method and to optimize
1067
+     * specifically for 'common filters'.
1068
+     *
1069
+     * Requests that are extremely common are:
1070
+     *   * requests for just VEVENTS
1071
+     *   * requests for just VTODO
1072
+     *   * requests with a time-range-filter on either VEVENT or VTODO.
1073
+     *
1074
+     * ..and combinations of these requests. It may not be worth it to try to
1075
+     * handle every possible situation and just rely on the (relatively
1076
+     * easy to use) CalendarQueryValidator to handle the rest.
1077
+     *
1078
+     * Note that especially time-range-filters may be difficult to parse. A
1079
+     * time-range filter specified on a VEVENT must for instance also handle
1080
+     * recurrence rules correctly.
1081
+     * A good example of how to interprete all these filters can also simply
1082
+     * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1083
+     * as possible, so it gives you a good idea on what type of stuff you need
1084
+     * to think of.
1085
+     *
1086
+     * @param mixed $calendarId
1087
+     * @param array $filters
1088
+     * @return array
1089
+     */
1090
+    function calendarQuery($calendarId, array $filters) {
1091
+        $componentType = null;
1092
+        $requirePostFilter = true;
1093
+        $timeRange = null;
1094
+
1095
+        // if no filters were specified, we don't need to filter after a query
1096
+        if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1097
+            $requirePostFilter = false;
1098
+        }
1099
+
1100
+        // Figuring out if there's a component filter
1101
+        if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1102
+            $componentType = $filters['comp-filters'][0]['name'];
1103
+
1104
+            // Checking if we need post-filters
1105
+            if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1106
+                $requirePostFilter = false;
1107
+            }
1108
+            // There was a time-range filter
1109
+            if ($componentType == 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1110
+                $timeRange = $filters['comp-filters'][0]['time-range'];
1111
+
1112
+                // If start time OR the end time is not specified, we can do a
1113
+                // 100% accurate mysql query.
1114
+                if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1115
+                    $requirePostFilter = false;
1116
+                }
1117
+            }
1118
+
1119
+        }
1120
+        $columns = ['uri'];
1121
+        if ($requirePostFilter) {
1122
+            $columns = ['uri', 'calendardata'];
1123
+        }
1124
+        $query = $this->db->getQueryBuilder();
1125
+        $query->select($columns)
1126
+            ->from('calendarobjects')
1127
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
1128
+
1129
+        if ($componentType) {
1130
+            $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1131
+        }
1132
+
1133
+        if ($timeRange && $timeRange['start']) {
1134
+            $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1135
+        }
1136
+        if ($timeRange && $timeRange['end']) {
1137
+            $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1138
+        }
1139
+
1140
+        $stmt = $query->execute();
1141
+
1142
+        $result = [];
1143
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1144
+            if ($requirePostFilter) {
1145
+                if (!$this->validateFilterForObject($row, $filters)) {
1146
+                    continue;
1147
+                }
1148
+            }
1149
+            $result[] = $row['uri'];
1150
+        }
1151
+
1152
+        return $result;
1153
+    }
1154
+
1155
+    /**
1156
+     * Searches through all of a users calendars and calendar objects to find
1157
+     * an object with a specific UID.
1158
+     *
1159
+     * This method should return the path to this object, relative to the
1160
+     * calendar home, so this path usually only contains two parts:
1161
+     *
1162
+     * calendarpath/objectpath.ics
1163
+     *
1164
+     * If the uid is not found, return null.
1165
+     *
1166
+     * This method should only consider * objects that the principal owns, so
1167
+     * any calendars owned by other principals that also appear in this
1168
+     * collection should be ignored.
1169
+     *
1170
+     * @param string $principalUri
1171
+     * @param string $uid
1172
+     * @return string|null
1173
+     */
1174
+    function getCalendarObjectByUID($principalUri, $uid) {
1175
+
1176
+        $query = $this->db->getQueryBuilder();
1177
+        $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1178
+            ->from('calendarobjects', 'co')
1179
+            ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1180
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1181
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1182
+
1183
+        $stmt = $query->execute();
1184
+
1185
+        if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1186
+            return $row['calendaruri'] . '/' . $row['objecturi'];
1187
+        }
1188
+
1189
+        return null;
1190
+    }
1191
+
1192
+    /**
1193
+     * The getChanges method returns all the changes that have happened, since
1194
+     * the specified syncToken in the specified calendar.
1195
+     *
1196
+     * This function should return an array, such as the following:
1197
+     *
1198
+     * [
1199
+     *   'syncToken' => 'The current synctoken',
1200
+     *   'added'   => [
1201
+     *      'new.txt',
1202
+     *   ],
1203
+     *   'modified'   => [
1204
+     *      'modified.txt',
1205
+     *   ],
1206
+     *   'deleted' => [
1207
+     *      'foo.php.bak',
1208
+     *      'old.txt'
1209
+     *   ]
1210
+     * );
1211
+     *
1212
+     * The returned syncToken property should reflect the *current* syncToken
1213
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1214
+     * property This is * needed here too, to ensure the operation is atomic.
1215
+     *
1216
+     * If the $syncToken argument is specified as null, this is an initial
1217
+     * sync, and all members should be reported.
1218
+     *
1219
+     * The modified property is an array of nodenames that have changed since
1220
+     * the last token.
1221
+     *
1222
+     * The deleted property is an array with nodenames, that have been deleted
1223
+     * from collection.
1224
+     *
1225
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
1226
+     * 1, you only have to report changes that happened only directly in
1227
+     * immediate descendants. If it's 2, it should also include changes from
1228
+     * the nodes below the child collections. (grandchildren)
1229
+     *
1230
+     * The $limit argument allows a client to specify how many results should
1231
+     * be returned at most. If the limit is not specified, it should be treated
1232
+     * as infinite.
1233
+     *
1234
+     * If the limit (infinite or not) is higher than you're willing to return,
1235
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1236
+     *
1237
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
1238
+     * return null.
1239
+     *
1240
+     * The limit is 'suggestive'. You are free to ignore it.
1241
+     *
1242
+     * @param string $calendarId
1243
+     * @param string $syncToken
1244
+     * @param int $syncLevel
1245
+     * @param int $limit
1246
+     * @return array
1247
+     */
1248
+    function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1249
+        // Current synctoken
1250
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1251
+        $stmt->execute([ $calendarId ]);
1252
+        $currentToken = $stmt->fetchColumn(0);
1253
+
1254
+        if (is_null($currentToken)) {
1255
+            return null;
1256
+        }
1257
+
1258
+        $result = [
1259
+            'syncToken' => $currentToken,
1260
+            'added'     => [],
1261
+            'modified'  => [],
1262
+            'deleted'   => [],
1263
+        ];
1264
+
1265
+        if ($syncToken) {
1266
+
1267
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1268
+            if ($limit>0) {
1269
+                $query.= " `LIMIT` " . (int)$limit;
1270
+            }
1271
+
1272
+            // Fetching all changes
1273
+            $stmt = $this->db->prepare($query);
1274
+            $stmt->execute([$syncToken, $currentToken, $calendarId]);
1275
+
1276
+            $changes = [];
1277
+
1278
+            // This loop ensures that any duplicates are overwritten, only the
1279
+            // last change on a node is relevant.
1280
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1281
+
1282
+                $changes[$row['uri']] = $row['operation'];
1283
+
1284
+            }
1285
+
1286
+            foreach($changes as $uri => $operation) {
1287
+
1288
+                switch($operation) {
1289
+                    case 1 :
1290
+                        $result['added'][] = $uri;
1291
+                        break;
1292
+                    case 2 :
1293
+                        $result['modified'][] = $uri;
1294
+                        break;
1295
+                    case 3 :
1296
+                        $result['deleted'][] = $uri;
1297
+                        break;
1298
+                }
1299
+
1300
+            }
1301
+        } else {
1302
+            // No synctoken supplied, this is the initial sync.
1303
+            $query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?";
1304
+            $stmt = $this->db->prepare($query);
1305
+            $stmt->execute([$calendarId]);
1306
+
1307
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1308
+        }
1309
+        return $result;
1310
+
1311
+    }
1312
+
1313
+    /**
1314
+     * Returns a list of subscriptions for a principal.
1315
+     *
1316
+     * Every subscription is an array with the following keys:
1317
+     *  * id, a unique id that will be used by other functions to modify the
1318
+     *    subscription. This can be the same as the uri or a database key.
1319
+     *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1320
+     *  * principaluri. The owner of the subscription. Almost always the same as
1321
+     *    principalUri passed to this method.
1322
+     *
1323
+     * Furthermore, all the subscription info must be returned too:
1324
+     *
1325
+     * 1. {DAV:}displayname
1326
+     * 2. {http://apple.com/ns/ical/}refreshrate
1327
+     * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1328
+     *    should not be stripped).
1329
+     * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1330
+     *    should not be stripped).
1331
+     * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1332
+     *    attachments should not be stripped).
1333
+     * 6. {http://calendarserver.org/ns/}source (Must be a
1334
+     *     Sabre\DAV\Property\Href).
1335
+     * 7. {http://apple.com/ns/ical/}calendar-color
1336
+     * 8. {http://apple.com/ns/ical/}calendar-order
1337
+     * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1338
+     *    (should just be an instance of
1339
+     *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1340
+     *    default components).
1341
+     *
1342
+     * @param string $principalUri
1343
+     * @return array
1344
+     */
1345
+    function getSubscriptionsForUser($principalUri) {
1346
+        $fields = array_values($this->subscriptionPropertyMap);
1347
+        $fields[] = 'id';
1348
+        $fields[] = 'uri';
1349
+        $fields[] = 'source';
1350
+        $fields[] = 'principaluri';
1351
+        $fields[] = 'lastmodified';
1352
+
1353
+        $query = $this->db->getQueryBuilder();
1354
+        $query->select($fields)
1355
+            ->from('calendarsubscriptions')
1356
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1357
+            ->orderBy('calendarorder', 'asc');
1358
+        $stmt =$query->execute();
1359
+
1360
+        $subscriptions = [];
1361
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1362
+
1363
+            $subscription = [
1364
+                'id'           => $row['id'],
1365
+                'uri'          => $row['uri'],
1366
+                'principaluri' => $row['principaluri'],
1367
+                'source'       => $row['source'],
1368
+                'lastmodified' => $row['lastmodified'],
1369
+
1370
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1371
+            ];
1372
+
1373
+            foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1374
+                if (!is_null($row[$dbName])) {
1375
+                    $subscription[$xmlName] = $row[$dbName];
1376
+                }
1377
+            }
1378
+
1379
+            $subscriptions[] = $subscription;
1380
+
1381
+        }
1382
+
1383
+        return $subscriptions;
1384
+    }
1385
+
1386
+    /**
1387
+     * Creates a new subscription for a principal.
1388
+     *
1389
+     * If the creation was a success, an id must be returned that can be used to reference
1390
+     * this subscription in other methods, such as updateSubscription.
1391
+     *
1392
+     * @param string $principalUri
1393
+     * @param string $uri
1394
+     * @param array $properties
1395
+     * @return mixed
1396
+     */
1397
+    function createSubscription($principalUri, $uri, array $properties) {
1398
+
1399
+        if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1400
+            throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1401
+        }
1402
+
1403
+        $values = [
1404
+            'principaluri' => $principalUri,
1405
+            'uri'          => $uri,
1406
+            'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1407
+            'lastmodified' => time(),
1408
+        ];
1409
+
1410
+        $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1411
+
1412
+        foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1413
+            if (array_key_exists($xmlName, $properties)) {
1414
+                    $values[$dbName] = $properties[$xmlName];
1415
+                    if (in_array($dbName, $propertiesBoolean)) {
1416
+                        $values[$dbName] = true;
1417
+                }
1418
+            }
1419
+        }
1420
+
1421
+        $valuesToInsert = array();
1422
+
1423
+        $query = $this->db->getQueryBuilder();
1424
+
1425
+        foreach (array_keys($values) as $name) {
1426
+            $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1427
+        }
1428
+
1429
+        $query->insert('calendarsubscriptions')
1430
+            ->values($valuesToInsert)
1431
+            ->execute();
1432
+
1433
+        return $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1434
+    }
1435
+
1436
+    /**
1437
+     * Updates a subscription
1438
+     *
1439
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1440
+     * To do the actual updates, you must tell this object which properties
1441
+     * you're going to process with the handle() method.
1442
+     *
1443
+     * Calling the handle method is like telling the PropPatch object "I
1444
+     * promise I can handle updating this property".
1445
+     *
1446
+     * Read the PropPatch documentation for more info and examples.
1447
+     *
1448
+     * @param mixed $subscriptionId
1449
+     * @param PropPatch $propPatch
1450
+     * @return void
1451
+     */
1452
+    function updateSubscription($subscriptionId, PropPatch $propPatch) {
1453
+        $supportedProperties = array_keys($this->subscriptionPropertyMap);
1454
+        $supportedProperties[] = '{http://calendarserver.org/ns/}source';
1455
+
1456
+        $propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1457
+
1458
+            $newValues = [];
1459
+
1460
+            foreach($mutations as $propertyName=>$propertyValue) {
1461
+                if ($propertyName === '{http://calendarserver.org/ns/}source') {
1462
+                    $newValues['source'] = $propertyValue->getHref();
1463
+                } else {
1464
+                    $fieldName = $this->subscriptionPropertyMap[$propertyName];
1465
+                    $newValues[$fieldName] = $propertyValue;
1466
+                }
1467
+            }
1468
+
1469
+            $query = $this->db->getQueryBuilder();
1470
+            $query->update('calendarsubscriptions')
1471
+                ->set('lastmodified', $query->createNamedParameter(time()));
1472
+            foreach($newValues as $fieldName=>$value) {
1473
+                $query->set($fieldName, $query->createNamedParameter($value));
1474
+            }
1475
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1476
+                ->execute();
1477
+
1478
+            return true;
1479
+
1480
+        });
1481
+    }
1482
+
1483
+    /**
1484
+     * Deletes a subscription.
1485
+     *
1486
+     * @param mixed $subscriptionId
1487
+     * @return void
1488
+     */
1489
+    function deleteSubscription($subscriptionId) {
1490
+        $query = $this->db->getQueryBuilder();
1491
+        $query->delete('calendarsubscriptions')
1492
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1493
+            ->execute();
1494
+    }
1495
+
1496
+    /**
1497
+     * Returns a single scheduling object for the inbox collection.
1498
+     *
1499
+     * The returned array should contain the following elements:
1500
+     *   * uri - A unique basename for the object. This will be used to
1501
+     *           construct a full uri.
1502
+     *   * calendardata - The iCalendar object
1503
+     *   * lastmodified - The last modification date. Can be an int for a unix
1504
+     *                    timestamp, or a PHP DateTime object.
1505
+     *   * etag - A unique token that must change if the object changed.
1506
+     *   * size - The size of the object, in bytes.
1507
+     *
1508
+     * @param string $principalUri
1509
+     * @param string $objectUri
1510
+     * @return array
1511
+     */
1512
+    function getSchedulingObject($principalUri, $objectUri) {
1513
+        $query = $this->db->getQueryBuilder();
1514
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1515
+            ->from('schedulingobjects')
1516
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1517
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1518
+            ->execute();
1519
+
1520
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
1521
+
1522
+        if(!$row) {
1523
+            return null;
1524
+        }
1525
+
1526
+        return [
1527
+                'uri'          => $row['uri'],
1528
+                'calendardata' => $row['calendardata'],
1529
+                'lastmodified' => $row['lastmodified'],
1530
+                'etag'         => '"' . $row['etag'] . '"',
1531
+                'size'         => (int)$row['size'],
1532
+        ];
1533
+    }
1534
+
1535
+    /**
1536
+     * Returns all scheduling objects for the inbox collection.
1537
+     *
1538
+     * These objects should be returned as an array. Every item in the array
1539
+     * should follow the same structure as returned from getSchedulingObject.
1540
+     *
1541
+     * The main difference is that 'calendardata' is optional.
1542
+     *
1543
+     * @param string $principalUri
1544
+     * @return array
1545
+     */
1546
+    function getSchedulingObjects($principalUri) {
1547
+        $query = $this->db->getQueryBuilder();
1548
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1549
+                ->from('schedulingobjects')
1550
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1551
+                ->execute();
1552
+
1553
+        $result = [];
1554
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1555
+            $result[] = [
1556
+                    'calendardata' => $row['calendardata'],
1557
+                    'uri'          => $row['uri'],
1558
+                    'lastmodified' => $row['lastmodified'],
1559
+                    'etag'         => '"' . $row['etag'] . '"',
1560
+                    'size'         => (int)$row['size'],
1561
+            ];
1562
+        }
1563
+
1564
+        return $result;
1565
+    }
1566
+
1567
+    /**
1568
+     * Deletes a scheduling object from the inbox collection.
1569
+     *
1570
+     * @param string $principalUri
1571
+     * @param string $objectUri
1572
+     * @return void
1573
+     */
1574
+    function deleteSchedulingObject($principalUri, $objectUri) {
1575
+        $query = $this->db->getQueryBuilder();
1576
+        $query->delete('schedulingobjects')
1577
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1578
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1579
+                ->execute();
1580
+    }
1581
+
1582
+    /**
1583
+     * Creates a new scheduling object. This should land in a users' inbox.
1584
+     *
1585
+     * @param string $principalUri
1586
+     * @param string $objectUri
1587
+     * @param string $objectData
1588
+     * @return void
1589
+     */
1590
+    function createSchedulingObject($principalUri, $objectUri, $objectData) {
1591
+        $query = $this->db->getQueryBuilder();
1592
+        $query->insert('schedulingobjects')
1593
+            ->values([
1594
+                'principaluri' => $query->createNamedParameter($principalUri),
1595
+                'calendardata' => $query->createNamedParameter($objectData),
1596
+                'uri' => $query->createNamedParameter($objectUri),
1597
+                'lastmodified' => $query->createNamedParameter(time()),
1598
+                'etag' => $query->createNamedParameter(md5($objectData)),
1599
+                'size' => $query->createNamedParameter(strlen($objectData))
1600
+            ])
1601
+            ->execute();
1602
+    }
1603
+
1604
+    /**
1605
+     * Adds a change record to the calendarchanges table.
1606
+     *
1607
+     * @param mixed $calendarId
1608
+     * @param string $objectUri
1609
+     * @param int $operation 1 = add, 2 = modify, 3 = delete.
1610
+     * @return void
1611
+     */
1612
+    protected function addChange($calendarId, $objectUri, $operation) {
1613
+
1614
+        $stmt = $this->db->prepare('INSERT INTO `*PREFIX*calendarchanges` (`uri`, `synctoken`, `calendarid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*calendars` WHERE `id` = ?');
1615
+        $stmt->execute([
1616
+            $objectUri,
1617
+            $calendarId,
1618
+            $operation,
1619
+            $calendarId
1620
+        ]);
1621
+        $stmt = $this->db->prepare('UPDATE `*PREFIX*calendars` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
1622
+        $stmt->execute([
1623
+            $calendarId
1624
+        ]);
1625
+
1626
+    }
1627
+
1628
+    /**
1629
+     * Parses some information from calendar objects, used for optimized
1630
+     * calendar-queries.
1631
+     *
1632
+     * Returns an array with the following keys:
1633
+     *   * etag - An md5 checksum of the object without the quotes.
1634
+     *   * size - Size of the object in bytes
1635
+     *   * componentType - VEVENT, VTODO or VJOURNAL
1636
+     *   * firstOccurence
1637
+     *   * lastOccurence
1638
+     *   * uid - value of the UID property
1639
+     *
1640
+     * @param string $calendarData
1641
+     * @return array
1642
+     */
1643
+    public function getDenormalizedData($calendarData) {
1644
+
1645
+        $vObject = Reader::read($calendarData);
1646
+        $componentType = null;
1647
+        $component = null;
1648
+        $firstOccurrence = null;
1649
+        $lastOccurrence = null;
1650
+        $uid = null;
1651
+        $classification = self::CLASSIFICATION_PUBLIC;
1652
+        foreach($vObject->getComponents() as $component) {
1653
+            if ($component->name!=='VTIMEZONE') {
1654
+                $componentType = $component->name;
1655
+                $uid = (string)$component->UID;
1656
+                break;
1657
+            }
1658
+        }
1659
+        if (!$componentType) {
1660
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
1661
+        }
1662
+        if ($componentType === 'VEVENT' && $component->DTSTART) {
1663
+            $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
1664
+            // Finding the last occurrence is a bit harder
1665
+            if (!isset($component->RRULE)) {
1666
+                if (isset($component->DTEND)) {
1667
+                    $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
1668
+                } elseif (isset($component->DURATION)) {
1669
+                    $endDate = clone $component->DTSTART->getDateTime();
1670
+                    $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
1671
+                    $lastOccurrence = $endDate->getTimeStamp();
1672
+                } elseif (!$component->DTSTART->hasTime()) {
1673
+                    $endDate = clone $component->DTSTART->getDateTime();
1674
+                    $endDate->modify('+1 day');
1675
+                    $lastOccurrence = $endDate->getTimeStamp();
1676
+                } else {
1677
+                    $lastOccurrence = $firstOccurrence;
1678
+                }
1679
+            } else {
1680
+                $it = new EventIterator($vObject, (string)$component->UID);
1681
+                $maxDate = new \DateTime(self::MAX_DATE);
1682
+                if ($it->isInfinite()) {
1683
+                    $lastOccurrence = $maxDate->getTimestamp();
1684
+                } else {
1685
+                    $end = $it->getDtEnd();
1686
+                    while($it->valid() && $end < $maxDate) {
1687
+                        $end = $it->getDtEnd();
1688
+                        $it->next();
1689
+
1690
+                    }
1691
+                    $lastOccurrence = $end->getTimestamp();
1692
+                }
1693
+
1694
+            }
1695
+        }
1696
+
1697
+        if ($component->CLASS) {
1698
+            $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
1699
+            switch ($component->CLASS->getValue()) {
1700
+                case 'PUBLIC':
1701
+                    $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
1702
+                    break;
1703
+                case 'CONFIDENTIAL':
1704
+                    $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
1705
+                    break;
1706
+            }
1707
+        }
1708
+        return [
1709
+            'etag' => md5($calendarData),
1710
+            'size' => strlen($calendarData),
1711
+            'componentType' => $componentType,
1712
+            'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
1713
+            'lastOccurence'  => $lastOccurrence,
1714
+            'uid' => $uid,
1715
+            'classification' => $classification
1716
+        ];
1717
+
1718
+    }
1719
+
1720
+    private function readBlob($cardData) {
1721
+        if (is_resource($cardData)) {
1722
+            return stream_get_contents($cardData);
1723
+        }
1724
+
1725
+        return $cardData;
1726
+    }
1727
+
1728
+    /**
1729
+     * @param IShareable $shareable
1730
+     * @param array $add
1731
+     * @param array $remove
1732
+     */
1733
+    public function updateShares($shareable, $add, $remove) {
1734
+        $calendarId = $shareable->getResourceId();
1735
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
1736
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
1737
+            [
1738
+                'calendarId' => $calendarId,
1739
+                'calendarData' => $this->getCalendarById($calendarId),
1740
+                'shares' => $this->getShares($calendarId),
1741
+                'add' => $add,
1742
+                'remove' => $remove,
1743
+            ]));
1744
+        $this->sharingBackend->updateShares($shareable, $add, $remove);
1745
+    }
1746
+
1747
+    /**
1748
+     * @param int $resourceId
1749
+     * @return array
1750
+     */
1751
+    public function getShares($resourceId) {
1752
+        return $this->sharingBackend->getShares($resourceId);
1753
+    }
1754
+
1755
+    /**
1756
+     * @param boolean $value
1757
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
1758
+     * @return string|null
1759
+     */
1760
+    public function setPublishStatus($value, $calendar) {
1761
+        $query = $this->db->getQueryBuilder();
1762
+        if ($value) {
1763
+            $publicUri = $this->random->generate(16, ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_DIGITS);
1764
+            $query->insert('dav_shares')
1765
+                ->values([
1766
+                    'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
1767
+                    'type' => $query->createNamedParameter('calendar'),
1768
+                    'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
1769
+                    'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
1770
+                    'publicuri' => $query->createNamedParameter($publicUri)
1771
+                ]);
1772
+            $query->execute();
1773
+            return $publicUri;
1774
+        }
1775
+        $query->delete('dav_shares')
1776
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1777
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
1778
+        $query->execute();
1779
+        return null;
1780
+    }
1781
+
1782
+    /**
1783
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
1784
+     * @return mixed
1785
+     */
1786
+    public function getPublishStatus($calendar) {
1787
+        $query = $this->db->getQueryBuilder();
1788
+        $result = $query->select('publicuri')
1789
+            ->from('dav_shares')
1790
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1791
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
1792
+            ->execute();
1793
+
1794
+        $row = $result->fetch();
1795
+        $result->closeCursor();
1796
+        return $row ? reset($row) : false;
1797
+    }
1798
+
1799
+    /**
1800
+     * @param int $resourceId
1801
+     * @param array $acl
1802
+     * @return array
1803
+     */
1804
+    public function applyShareAcl($resourceId, $acl) {
1805
+        return $this->sharingBackend->applyShareAcl($resourceId, $acl);
1806
+    }
1807
+
1808
+    private function convertPrincipal($principalUri, $toV2) {
1809
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1810
+            list(, $name) = URLUtil::splitPath($principalUri);
1811
+            if ($toV2 === true) {
1812
+                return "principals/users/$name";
1813
+            }
1814
+            return "principals/$name";
1815
+        }
1816
+        return $principalUri;
1817
+    }
1818 1818
 }
Please login to merge, or discard this patch.
Spacing   +108 added lines, -108 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
 			if ($row['principaluri'] === $principalUri) {
283 283
 				continue;
284 284
 			}
@@ -297,25 +297,25 @@  discard block
 block discarded – undo
297 297
 			}
298 298
 
299 299
 			list(, $name) = URLUtil::splitPath($row['principaluri']);
300
-			$uri = $row['uri'] . '_shared_by_' . $name;
301
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
300
+			$uri = $row['uri'].'_shared_by_'.$name;
301
+			$row['displayname'] = $row['displayname'].' ('.$this->getUserDisplayName($name).')';
302 302
 			$components = [];
303 303
 			if ($row['components']) {
304
-				$components = explode(',',$row['components']);
304
+				$components = explode(',', $row['components']);
305 305
 			}
306 306
 			$calendar = [
307 307
 				'id' => $row['id'],
308 308
 				'uri' => $uri,
309 309
 				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
310
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
311
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
312
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
313
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
314
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
310
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
311
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
312
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
313
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
314
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
315 315
 				$readOnlyPropertyName => $readOnly,
316 316
 			];
317 317
 
318
-			foreach($this->propertyMap as $xmlName=>$dbName) {
318
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
319 319
 				$calendar[$xmlName] = $row[$dbName];
320 320
 			}
321 321
 
@@ -342,21 +342,21 @@  discard block
 block discarded – undo
342 342
 			->orderBy('calendarorder', 'ASC');
343 343
 		$stmt = $query->execute();
344 344
 		$calendars = [];
345
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
345
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
346 346
 			$components = [];
347 347
 			if ($row['components']) {
348
-				$components = explode(',',$row['components']);
348
+				$components = explode(',', $row['components']);
349 349
 			}
350 350
 			$calendar = [
351 351
 				'id' => $row['id'],
352 352
 				'uri' => $row['uri'],
353 353
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
354
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
355
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
356
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
357
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
354
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
355
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
356
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
357
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
358 358
 			];
359
-			foreach($this->propertyMap as $xmlName=>$dbName) {
359
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
360 360
 				$calendar[$xmlName] = $row[$dbName];
361 361
 			}
362 362
 			if (!isset($calendars[$calendar['id']])) {
@@ -404,27 +404,27 @@  discard block
 block discarded – undo
404 404
 			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
405 405
 			->execute();
406 406
 
407
-		while($row = $result->fetch()) {
407
+		while ($row = $result->fetch()) {
408 408
 			list(, $name) = URLUtil::splitPath($row['principaluri']);
409
-			$row['displayname'] = $row['displayname'] . "($name)";
409
+			$row['displayname'] = $row['displayname']."($name)";
410 410
 			$components = [];
411 411
 			if ($row['components']) {
412
-				$components = explode(',',$row['components']);
412
+				$components = explode(',', $row['components']);
413 413
 			}
414 414
 			$calendar = [
415 415
 				'id' => $row['id'],
416 416
 				'uri' => $row['publicuri'],
417 417
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
418
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
419
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
420
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
421
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
422
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
423
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
424
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
418
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
419
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
420
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
421
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
422
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
423
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
424
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
425 425
 			];
426 426
 
427
-			foreach($this->propertyMap as $xmlName=>$dbName) {
427
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
428 428
 				$calendar[$xmlName] = $row[$dbName];
429 429
 			}
430 430
 
@@ -466,29 +466,29 @@  discard block
 block discarded – undo
466 466
 		$result->closeCursor();
467 467
 
468 468
 		if ($row === false) {
469
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
469
+			throw new NotFound('Node with name \''.$uri.'\' could not be found');
470 470
 		}
471 471
 
472 472
 		list(, $name) = URLUtil::splitPath($row['principaluri']);
473
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
473
+		$row['displayname'] = $row['displayname'].' '."($name)";
474 474
 		$components = [];
475 475
 		if ($row['components']) {
476
-			$components = explode(',',$row['components']);
476
+			$components = explode(',', $row['components']);
477 477
 		}
478 478
 		$calendar = [
479 479
 			'id' => $row['id'],
480 480
 			'uri' => $row['publicuri'],
481 481
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
482
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
483
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
484
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
485
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
486
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
487
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
488
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
482
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
483
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
484
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
485
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
486
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
487
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
488
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
489 489
 		];
490 490
 
491
-		foreach($this->propertyMap as $xmlName=>$dbName) {
491
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
492 492
 			$calendar[$xmlName] = $row[$dbName];
493 493
 		}
494 494
 
@@ -526,20 +526,20 @@  discard block
 block discarded – undo
526 526
 
527 527
 		$components = [];
528 528
 		if ($row['components']) {
529
-			$components = explode(',',$row['components']);
529
+			$components = explode(',', $row['components']);
530 530
 		}
531 531
 
532 532
 		$calendar = [
533 533
 			'id' => $row['id'],
534 534
 			'uri' => $row['uri'],
535 535
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
536
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
537
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
538
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
539
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
536
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
537
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
538
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
539
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
540 540
 		];
541 541
 
542
-		foreach($this->propertyMap as $xmlName=>$dbName) {
542
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
543 543
 			$calendar[$xmlName] = $row[$dbName];
544 544
 		}
545 545
 
@@ -570,20 +570,20 @@  discard block
 block discarded – undo
570 570
 
571 571
 		$components = [];
572 572
 		if ($row['components']) {
573
-			$components = explode(',',$row['components']);
573
+			$components = explode(',', $row['components']);
574 574
 		}
575 575
 
576 576
 		$calendar = [
577 577
 			'id' => $row['id'],
578 578
 			'uri' => $row['uri'],
579 579
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
580
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
581
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
582
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
583
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
580
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
581
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
582
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
583
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
584 584
 		];
585 585
 
586
-		foreach($this->propertyMap as $xmlName=>$dbName) {
586
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
587 587
 			$calendar[$xmlName] = $row[$dbName];
588 588
 		}
589 589
 
@@ -615,16 +615,16 @@  discard block
 block discarded – undo
615 615
 		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
616 616
 		if (isset($properties[$sccs])) {
617 617
 			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
618
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
618
+				throw new DAV\Exception('The '.$sccs.' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
619 619
 			}
620
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
620
+			$values['components'] = implode(',', $properties[$sccs]->getValue());
621 621
 		}
622
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
622
+		$transp = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
623 623
 		if (isset($properties[$transp])) {
624 624
 			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
625 625
 		}
626 626
 
627
-		foreach($this->propertyMap as $xmlName=>$dbName) {
627
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
628 628
 			if (isset($properties[$xmlName])) {
629 629
 				$values[$dbName] = $properties[$xmlName];
630 630
 			}
@@ -632,7 +632,7 @@  discard block
 block discarded – undo
632 632
 
633 633
 		$query = $this->db->getQueryBuilder();
634 634
 		$query->insert('calendars');
635
-		foreach($values as $column => $value) {
635
+		foreach ($values as $column => $value) {
636 636
 			$query->setValue($column, $query->createNamedParameter($value));
637 637
 		}
638 638
 		$query->execute();
@@ -665,14 +665,14 @@  discard block
 block discarded – undo
665 665
 	 */
666 666
 	function updateCalendar($calendarId, PropPatch $propPatch) {
667 667
 		$supportedProperties = array_keys($this->propertyMap);
668
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
668
+		$supportedProperties[] = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
669 669
 
670 670
 		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
671 671
 			$newValues = [];
672 672
 			foreach ($mutations as $propertyName => $propertyValue) {
673 673
 
674 674
 				switch ($propertyName) {
675
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
675
+					case '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' :
676 676
 						$fieldName = 'transparent';
677 677
 						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
678 678
 						break;
@@ -782,16 +782,16 @@  discard block
 block discarded – undo
782 782
 		$stmt = $query->execute();
783 783
 
784 784
 		$result = [];
785
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
785
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
786 786
 			$result[] = [
787 787
 					'id'           => $row['id'],
788 788
 					'uri'          => $row['uri'],
789 789
 					'lastmodified' => $row['lastmodified'],
790
-					'etag'         => '"' . $row['etag'] . '"',
790
+					'etag'         => '"'.$row['etag'].'"',
791 791
 					'calendarid'   => $row['calendarid'],
792
-					'size'         => (int)$row['size'],
792
+					'size'         => (int) $row['size'],
793 793
 					'component'    => strtolower($row['componenttype']),
794
-					'classification'=> (int)$row['classification']
794
+					'classification'=> (int) $row['classification']
795 795
 			];
796 796
 		}
797 797
 
@@ -824,18 +824,18 @@  discard block
 block discarded – undo
824 824
 		$stmt = $query->execute();
825 825
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
826 826
 
827
-		if(!$row) return null;
827
+		if (!$row) return null;
828 828
 
829 829
 		return [
830 830
 				'id'            => $row['id'],
831 831
 				'uri'           => $row['uri'],
832 832
 				'lastmodified'  => $row['lastmodified'],
833
-				'etag'          => '"' . $row['etag'] . '"',
833
+				'etag'          => '"'.$row['etag'].'"',
834 834
 				'calendarid'    => $row['calendarid'],
835
-				'size'          => (int)$row['size'],
835
+				'size'          => (int) $row['size'],
836 836
 				'calendardata'  => $this->readBlob($row['calendardata']),
837 837
 				'component'     => strtolower($row['componenttype']),
838
-				'classification'=> (int)$row['classification']
838
+				'classification'=> (int) $row['classification']
839 839
 		];
840 840
 	}
841 841
 
@@ -874,12 +874,12 @@  discard block
 block discarded – undo
874 874
 					'id'           => $row['id'],
875 875
 					'uri'          => $row['uri'],
876 876
 					'lastmodified' => $row['lastmodified'],
877
-					'etag'         => '"' . $row['etag'] . '"',
877
+					'etag'         => '"'.$row['etag'].'"',
878 878
 					'calendarid'   => $row['calendarid'],
879
-					'size'         => (int)$row['size'],
879
+					'size'         => (int) $row['size'],
880 880
 					'calendardata' => $this->readBlob($row['calendardata']),
881 881
 					'component'    => strtolower($row['componenttype']),
882
-					'classification' => (int)$row['classification']
882
+					'classification' => (int) $row['classification']
883 883
 				];
884 884
 			}
885 885
 			$result->closeCursor();
@@ -936,7 +936,7 @@  discard block
 block discarded – undo
936 936
 		));
937 937
 		$this->addChange($calendarId, $objectUri, 1);
938 938
 
939
-		return '"' . $extraData['etag'] . '"';
939
+		return '"'.$extraData['etag'].'"';
940 940
 	}
941 941
 
942 942
 	/**
@@ -989,7 +989,7 @@  discard block
 block discarded – undo
989 989
 		}
990 990
 		$this->addChange($calendarId, $objectUri, 2);
991 991
 
992
-		return '"' . $extraData['etag'] . '"';
992
+		return '"'.$extraData['etag'].'"';
993 993
 	}
994 994
 
995 995
 	/**
@@ -1140,7 +1140,7 @@  discard block
 block discarded – undo
1140 1140
 		$stmt = $query->execute();
1141 1141
 
1142 1142
 		$result = [];
1143
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1143
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1144 1144
 			if ($requirePostFilter) {
1145 1145
 				if (!$this->validateFilterForObject($row, $filters)) {
1146 1146
 					continue;
@@ -1183,7 +1183,7 @@  discard block
 block discarded – undo
1183 1183
 		$stmt = $query->execute();
1184 1184
 
1185 1185
 		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1186
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1186
+			return $row['calendaruri'].'/'.$row['objecturi'];
1187 1187
 		}
1188 1188
 
1189 1189
 		return null;
@@ -1248,7 +1248,7 @@  discard block
 block discarded – undo
1248 1248
 	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1249 1249
 		// Current synctoken
1250 1250
 		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1251
-		$stmt->execute([ $calendarId ]);
1251
+		$stmt->execute([$calendarId]);
1252 1252
 		$currentToken = $stmt->fetchColumn(0);
1253 1253
 
1254 1254
 		if (is_null($currentToken)) {
@@ -1265,8 +1265,8 @@  discard block
 block discarded – undo
1265 1265
 		if ($syncToken) {
1266 1266
 
1267 1267
 			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1268
-			if ($limit>0) {
1269
-				$query.= " `LIMIT` " . (int)$limit;
1268
+			if ($limit > 0) {
1269
+				$query .= " `LIMIT` ".(int) $limit;
1270 1270
 			}
1271 1271
 
1272 1272
 			// Fetching all changes
@@ -1277,15 +1277,15 @@  discard block
 block discarded – undo
1277 1277
 
1278 1278
 			// This loop ensures that any duplicates are overwritten, only the
1279 1279
 			// last change on a node is relevant.
1280
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1280
+			while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1281 1281
 
1282 1282
 				$changes[$row['uri']] = $row['operation'];
1283 1283
 
1284 1284
 			}
1285 1285
 
1286
-			foreach($changes as $uri => $operation) {
1286
+			foreach ($changes as $uri => $operation) {
1287 1287
 
1288
-				switch($operation) {
1288
+				switch ($operation) {
1289 1289
 					case 1 :
1290 1290
 						$result['added'][] = $uri;
1291 1291
 						break;
@@ -1355,10 +1355,10 @@  discard block
 block discarded – undo
1355 1355
 			->from('calendarsubscriptions')
1356 1356
 			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1357 1357
 			->orderBy('calendarorder', 'asc');
1358
-		$stmt =$query->execute();
1358
+		$stmt = $query->execute();
1359 1359
 
1360 1360
 		$subscriptions = [];
1361
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1361
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1362 1362
 
1363 1363
 			$subscription = [
1364 1364
 				'id'           => $row['id'],
@@ -1367,10 +1367,10 @@  discard block
 block discarded – undo
1367 1367
 				'source'       => $row['source'],
1368 1368
 				'lastmodified' => $row['lastmodified'],
1369 1369
 
1370
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1370
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1371 1371
 			];
1372 1372
 
1373
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1373
+			foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1374 1374
 				if (!is_null($row[$dbName])) {
1375 1375
 					$subscription[$xmlName] = $row[$dbName];
1376 1376
 				}
@@ -1409,7 +1409,7 @@  discard block
 block discarded – undo
1409 1409
 
1410 1410
 		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1411 1411
 
1412
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1412
+		foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1413 1413
 			if (array_key_exists($xmlName, $properties)) {
1414 1414
 					$values[$dbName] = $properties[$xmlName];
1415 1415
 					if (in_array($dbName, $propertiesBoolean)) {
@@ -1457,7 +1457,7 @@  discard block
 block discarded – undo
1457 1457
 
1458 1458
 			$newValues = [];
1459 1459
 
1460
-			foreach($mutations as $propertyName=>$propertyValue) {
1460
+			foreach ($mutations as $propertyName=>$propertyValue) {
1461 1461
 				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1462 1462
 					$newValues['source'] = $propertyValue->getHref();
1463 1463
 				} else {
@@ -1469,7 +1469,7 @@  discard block
 block discarded – undo
1469 1469
 			$query = $this->db->getQueryBuilder();
1470 1470
 			$query->update('calendarsubscriptions')
1471 1471
 				->set('lastmodified', $query->createNamedParameter(time()));
1472
-			foreach($newValues as $fieldName=>$value) {
1472
+			foreach ($newValues as $fieldName=>$value) {
1473 1473
 				$query->set($fieldName, $query->createNamedParameter($value));
1474 1474
 			}
1475 1475
 			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
@@ -1519,7 +1519,7 @@  discard block
 block discarded – undo
1519 1519
 
1520 1520
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
1521 1521
 
1522
-		if(!$row) {
1522
+		if (!$row) {
1523 1523
 			return null;
1524 1524
 		}
1525 1525
 
@@ -1527,8 +1527,8 @@  discard block
 block discarded – undo
1527 1527
 				'uri'          => $row['uri'],
1528 1528
 				'calendardata' => $row['calendardata'],
1529 1529
 				'lastmodified' => $row['lastmodified'],
1530
-				'etag'         => '"' . $row['etag'] . '"',
1531
-				'size'         => (int)$row['size'],
1530
+				'etag'         => '"'.$row['etag'].'"',
1531
+				'size'         => (int) $row['size'],
1532 1532
 		];
1533 1533
 	}
1534 1534
 
@@ -1551,13 +1551,13 @@  discard block
 block discarded – undo
1551 1551
 				->execute();
1552 1552
 
1553 1553
 		$result = [];
1554
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1554
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1555 1555
 			$result[] = [
1556 1556
 					'calendardata' => $row['calendardata'],
1557 1557
 					'uri'          => $row['uri'],
1558 1558
 					'lastmodified' => $row['lastmodified'],
1559
-					'etag'         => '"' . $row['etag'] . '"',
1560
-					'size'         => (int)$row['size'],
1559
+					'etag'         => '"'.$row['etag'].'"',
1560
+					'size'         => (int) $row['size'],
1561 1561
 			];
1562 1562
 		}
1563 1563
 
@@ -1649,10 +1649,10 @@  discard block
 block discarded – undo
1649 1649
 		$lastOccurrence = null;
1650 1650
 		$uid = null;
1651 1651
 		$classification = self::CLASSIFICATION_PUBLIC;
1652
-		foreach($vObject->getComponents() as $component) {
1653
-			if ($component->name!=='VTIMEZONE') {
1652
+		foreach ($vObject->getComponents() as $component) {
1653
+			if ($component->name !== 'VTIMEZONE') {
1654 1654
 				$componentType = $component->name;
1655
-				$uid = (string)$component->UID;
1655
+				$uid = (string) $component->UID;
1656 1656
 				break;
1657 1657
 			}
1658 1658
 		}
@@ -1677,13 +1677,13 @@  discard block
 block discarded – undo
1677 1677
 					$lastOccurrence = $firstOccurrence;
1678 1678
 				}
1679 1679
 			} else {
1680
-				$it = new EventIterator($vObject, (string)$component->UID);
1680
+				$it = new EventIterator($vObject, (string) $component->UID);
1681 1681
 				$maxDate = new \DateTime(self::MAX_DATE);
1682 1682
 				if ($it->isInfinite()) {
1683 1683
 					$lastOccurrence = $maxDate->getTimestamp();
1684 1684
 				} else {
1685 1685
 					$end = $it->getDtEnd();
1686
-					while($it->valid() && $end < $maxDate) {
1686
+					while ($it->valid() && $end < $maxDate) {
1687 1687
 						$end = $it->getDtEnd();
1688 1688
 						$it->next();
1689 1689
 
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/ShareTypeList.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -61,7 +61,7 @@
 block discarded – undo
61 61
 	 * The deserialize method is called during xml parsing.
62 62
 	 *
63 63
 	 * @param Reader $reader
64
-	 * @return mixed
64
+	 * @return null|ShareTypeList
65 65
 	 */
66 66
 	static function xmlDeserialize(Reader $reader) {
67 67
 		$shareTypes = [];
Please login to merge, or discard this patch.
Indentation   +51 added lines, -51 removed lines patch added patch discarded remove patch
@@ -32,61 +32,61 @@
 block discarded – undo
32 32
  * This property contains multiple "share-type" elements, each containing a share type.
33 33
  */
34 34
 class ShareTypeList implements Element {
35
-	const NS_OWNCLOUD = 'http://owncloud.org/ns';
35
+    const NS_OWNCLOUD = 'http://owncloud.org/ns';
36 36
 
37
-	/**
38
-	 * Share types
39
-	 *
40
-	 * @var int[]
41
-	 */
42
-	private $shareTypes;
37
+    /**
38
+     * Share types
39
+     *
40
+     * @var int[]
41
+     */
42
+    private $shareTypes;
43 43
 
44
-	/**
45
-	 * @param int[] $shareTypes
46
-	 */
47
-	public function __construct($shareTypes) {
48
-		$this->shareTypes = $shareTypes;
49
-	}
44
+    /**
45
+     * @param int[] $shareTypes
46
+     */
47
+    public function __construct($shareTypes) {
48
+        $this->shareTypes = $shareTypes;
49
+    }
50 50
 
51
-	/**
52
-	 * Returns the share types
53
-	 *
54
-	 * @return int[]
55
-	 */
56
-	public function getShareTypes() {
57
-		return $this->shareTypes;
58
-	}
51
+    /**
52
+     * Returns the share types
53
+     *
54
+     * @return int[]
55
+     */
56
+    public function getShareTypes() {
57
+        return $this->shareTypes;
58
+    }
59 59
 
60
-	/**
61
-	 * The deserialize method is called during xml parsing.
62
-	 *
63
-	 * @param Reader $reader
64
-	 * @return mixed
65
-	 */
66
-	static function xmlDeserialize(Reader $reader) {
67
-		$shareTypes = [];
60
+    /**
61
+     * The deserialize method is called during xml parsing.
62
+     *
63
+     * @param Reader $reader
64
+     * @return mixed
65
+     */
66
+    static function xmlDeserialize(Reader $reader) {
67
+        $shareTypes = [];
68 68
 
69
-		$tree = $reader->parseInnerTree();
70
-		if ($tree === null) {
71
-			return null;
72
-		}
73
-		foreach ($tree as $elem) {
74
-			if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}share-type') {
75
-				$shareTypes[] = (int)$elem['value'];
76
-			}
77
-		}
78
-		return new self($shareTypes);
79
-	}
69
+        $tree = $reader->parseInnerTree();
70
+        if ($tree === null) {
71
+            return null;
72
+        }
73
+        foreach ($tree as $elem) {
74
+            if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}share-type') {
75
+                $shareTypes[] = (int)$elem['value'];
76
+            }
77
+        }
78
+        return new self($shareTypes);
79
+    }
80 80
 
81
-	/**
82
-	 * The xmlSerialize metod is called during xml writing.
83
-	 *
84
-	 * @param Writer $writer
85
-	 * @return void
86
-	 */
87
-	function xmlSerialize(Writer $writer) {
88
-		foreach ($this->shareTypes as $shareType) {
89
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}share-type', $shareType);
90
-		}
91
-	}
81
+    /**
82
+     * The xmlSerialize metod is called during xml writing.
83
+     *
84
+     * @param Writer $writer
85
+     * @return void
86
+     */
87
+    function xmlSerialize(Writer $writer) {
88
+        foreach ($this->shareTypes as $shareType) {
89
+            $writer->writeElement('{' . self::NS_OWNCLOUD . '}share-type', $shareType);
90
+        }
91
+    }
92 92
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -71,8 +71,8 @@  discard block
 block discarded – undo
71 71
 			return null;
72 72
 		}
73 73
 		foreach ($tree as $elem) {
74
-			if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}share-type') {
75
-				$shareTypes[] = (int)$elem['value'];
74
+			if ($elem['name'] === '{'.self::NS_OWNCLOUD.'}share-type') {
75
+				$shareTypes[] = (int) $elem['value'];
76 76
 			}
77 77
 		}
78 78
 		return new self($shareTypes);
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
 	 */
87 87
 	function xmlSerialize(Writer $writer) {
88 88
 		foreach ($this->shareTypes as $shareType) {
89
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}share-type', $shareType);
89
+			$writer->writeElement('{'.self::NS_OWNCLOUD.'}share-type', $shareType);
90 90
 		}
91 91
 	}
92 92
 }
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/TagList.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -80,7 +80,7 @@
 block discarded – undo
80 80
 	 * the next element.
81 81
 	 *
82 82
 	 * @param Reader $reader
83
-	 * @return mixed
83
+	 * @return null|TagList
84 84
 	 */
85 85
 	static function xmlDeserialize(Reader $reader) {
86 86
 		$tags = [];
Please login to merge, or discard this patch.
Indentation   +79 added lines, -79 removed lines patch added patch discarded remove patch
@@ -34,92 +34,92 @@
 block discarded – undo
34 34
  * This property contains multiple "tag" elements, each containing a tag name.
35 35
  */
36 36
 class TagList implements Element {
37
-	const NS_OWNCLOUD = 'http://owncloud.org/ns';
37
+    const NS_OWNCLOUD = 'http://owncloud.org/ns';
38 38
 
39
-	/**
40
-	 * tags
41
-	 *
42
-	 * @var array
43
-	 */
44
-	private $tags;
39
+    /**
40
+     * tags
41
+     *
42
+     * @var array
43
+     */
44
+    private $tags;
45 45
 
46
-	/**
47
-	 * @param array $tags
48
-	 */
49
-	public function __construct(array $tags) {
50
-		$this->tags = $tags;
51
-	}
46
+    /**
47
+     * @param array $tags
48
+     */
49
+    public function __construct(array $tags) {
50
+        $this->tags = $tags;
51
+    }
52 52
 
53
-	/**
54
-	 * Returns the tags
55
-	 *
56
-	 * @return array
57
-	 */
58
-	public function getTags() {
53
+    /**
54
+     * Returns the tags
55
+     *
56
+     * @return array
57
+     */
58
+    public function getTags() {
59 59
 
60
-		return $this->tags;
60
+        return $this->tags;
61 61
 
62
-	}
62
+    }
63 63
 
64
-	/**
65
-	 * The deserialize method is called during xml parsing.
66
-	 *
67
-	 * This method is called statictly, this is because in theory this method
68
-	 * may be used as a type of constructor, or factory method.
69
-	 *
70
-	 * Often you want to return an instance of the current class, but you are
71
-	 * free to return other data as well.
72
-	 *
73
-	 * You are responsible for advancing the reader to the next element. Not
74
-	 * doing anything will result in a never-ending loop.
75
-	 *
76
-	 * If you just want to skip parsing for this element altogether, you can
77
-	 * just call $reader->next();
78
-	 *
79
-	 * $reader->parseInnerTree() will parse the entire sub-tree, and advance to
80
-	 * the next element.
81
-	 *
82
-	 * @param Reader $reader
83
-	 * @return mixed
84
-	 */
85
-	static function xmlDeserialize(Reader $reader) {
86
-		$tags = [];
64
+    /**
65
+     * The deserialize method is called during xml parsing.
66
+     *
67
+     * This method is called statictly, this is because in theory this method
68
+     * may be used as a type of constructor, or factory method.
69
+     *
70
+     * Often you want to return an instance of the current class, but you are
71
+     * free to return other data as well.
72
+     *
73
+     * You are responsible for advancing the reader to the next element. Not
74
+     * doing anything will result in a never-ending loop.
75
+     *
76
+     * If you just want to skip parsing for this element altogether, you can
77
+     * just call $reader->next();
78
+     *
79
+     * $reader->parseInnerTree() will parse the entire sub-tree, and advance to
80
+     * the next element.
81
+     *
82
+     * @param Reader $reader
83
+     * @return mixed
84
+     */
85
+    static function xmlDeserialize(Reader $reader) {
86
+        $tags = [];
87 87
 
88
-		$tree = $reader->parseInnerTree();
89
-		if ($tree === null) {
90
-			return null;
91
-		}
92
-		foreach ($tree as $elem) {
93
-			if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}tag') {
94
-				$tags[] = $elem['value'];
95
-			}
96
-		}
97
-		return new self($tags);
98
-	}
88
+        $tree = $reader->parseInnerTree();
89
+        if ($tree === null) {
90
+            return null;
91
+        }
92
+        foreach ($tree as $elem) {
93
+            if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}tag') {
94
+                $tags[] = $elem['value'];
95
+            }
96
+        }
97
+        return new self($tags);
98
+    }
99 99
 
100
-	/**
101
-	 * The xmlSerialize metod is called during xml writing.
102
-	 *
103
-	 * Use the $writer argument to write its own xml serialization.
104
-	 *
105
-	 * An important note: do _not_ create a parent element. Any element
106
-	 * implementing XmlSerializble should only ever write what's considered
107
-	 * its 'inner xml'.
108
-	 *
109
-	 * The parent of the current element is responsible for writing a
110
-	 * containing element.
111
-	 *
112
-	 * This allows serializers to be re-used for different element names.
113
-	 *
114
-	 * If you are opening new elements, you must also close them again.
115
-	 *
116
-	 * @param Writer $writer
117
-	 * @return void
118
-	 */
119
-	function xmlSerialize(Writer $writer) {
100
+    /**
101
+     * The xmlSerialize metod is called during xml writing.
102
+     *
103
+     * Use the $writer argument to write its own xml serialization.
104
+     *
105
+     * An important note: do _not_ create a parent element. Any element
106
+     * implementing XmlSerializble should only ever write what's considered
107
+     * its 'inner xml'.
108
+     *
109
+     * The parent of the current element is responsible for writing a
110
+     * containing element.
111
+     *
112
+     * This allows serializers to be re-used for different element names.
113
+     *
114
+     * If you are opening new elements, you must also close them again.
115
+     *
116
+     * @param Writer $writer
117
+     * @return void
118
+     */
119
+    function xmlSerialize(Writer $writer) {
120 120
 
121
-		foreach ($this->tags as $tag) {
122
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}tag', $tag);
123
-		}
124
-	}
121
+        foreach ($this->tags as $tag) {
122
+            $writer->writeElement('{' . self::NS_OWNCLOUD . '}tag', $tag);
123
+        }
124
+    }
125 125
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -90,7 +90,7 @@  discard block
 block discarded – undo
90 90
 			return null;
91 91
 		}
92 92
 		foreach ($tree as $elem) {
93
-			if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}tag') {
93
+			if ($elem['name'] === '{'.self::NS_OWNCLOUD.'}tag') {
94 94
 				$tags[] = $elem['value'];
95 95
 			}
96 96
 		}
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
 	function xmlSerialize(Writer $writer) {
120 120
 
121 121
 		foreach ($this->tags as $tag) {
122
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}tag', $tag);
122
+			$writer->writeElement('{'.self::NS_OWNCLOUD.'}tag', $tag);
123 123
 		}
124 124
 	}
125 125
 }
Please login to merge, or discard this patch.
lib/private/Share/MailNotifications.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -30,7 +30,6 @@
 block discarded – undo
30 30
 
31 31
 namespace OC\Share;
32 32
 
33
-use DateTime;
34 33
 use OCP\IL10N;
35 34
 use OCP\IURLGenerator;
36 35
 use OCP\IUser;
Please login to merge, or discard this patch.
Indentation   +100 added lines, -100 removed lines patch added patch discarded remove patch
@@ -46,113 +46,113 @@
 block discarded – undo
46 46
  */
47 47
 class MailNotifications {
48 48
 
49
-	/** @var IUser sender userId */
50
-	private $user;
51
-	/** @var string sender email address */
52
-	private $replyTo;
53
-	/** @var string */
54
-	private $senderDisplayName;
55
-	/** @var IL10N */
56
-	private $l;
57
-	/** @var IMailer */
58
-	private $mailer;
59
-	/** @var Defaults */
60
-	private $defaults;
61
-	/** @var ILogger */
62
-	private $logger;
63
-	/** @var IURLGenerator */
64
-	private $urlGenerator;
49
+    /** @var IUser sender userId */
50
+    private $user;
51
+    /** @var string sender email address */
52
+    private $replyTo;
53
+    /** @var string */
54
+    private $senderDisplayName;
55
+    /** @var IL10N */
56
+    private $l;
57
+    /** @var IMailer */
58
+    private $mailer;
59
+    /** @var Defaults */
60
+    private $defaults;
61
+    /** @var ILogger */
62
+    private $logger;
63
+    /** @var IURLGenerator */
64
+    private $urlGenerator;
65 65
 
66
-	/**
67
-	 * @param IUser $user
68
-	 * @param IL10N $l10n
69
-	 * @param IMailer $mailer
70
-	 * @param ILogger $logger
71
-	 * @param Defaults $defaults
72
-	 * @param IURLGenerator $urlGenerator
73
-	 */
74
-	public function __construct(IUser $user,
75
-								IL10N $l10n,
76
-								IMailer $mailer,
77
-								ILogger $logger,
78
-								Defaults $defaults,
79
-								IURLGenerator $urlGenerator) {
80
-		$this->l = $l10n;
81
-		$this->user = $user;
82
-		$this->mailer = $mailer;
83
-		$this->logger = $logger;
84
-		$this->defaults = $defaults;
85
-		$this->urlGenerator = $urlGenerator;
66
+    /**
67
+     * @param IUser $user
68
+     * @param IL10N $l10n
69
+     * @param IMailer $mailer
70
+     * @param ILogger $logger
71
+     * @param Defaults $defaults
72
+     * @param IURLGenerator $urlGenerator
73
+     */
74
+    public function __construct(IUser $user,
75
+                                IL10N $l10n,
76
+                                IMailer $mailer,
77
+                                ILogger $logger,
78
+                                Defaults $defaults,
79
+                                IURLGenerator $urlGenerator) {
80
+        $this->l = $l10n;
81
+        $this->user = $user;
82
+        $this->mailer = $mailer;
83
+        $this->logger = $logger;
84
+        $this->defaults = $defaults;
85
+        $this->urlGenerator = $urlGenerator;
86 86
 
87
-		$this->replyTo = $this->user->getEMailAddress();
88
-		$this->senderDisplayName = $this->user->getDisplayName();
89
-	}
87
+        $this->replyTo = $this->user->getEMailAddress();
88
+        $this->senderDisplayName = $this->user->getDisplayName();
89
+    }
90 90
 
91
-	/**
92
-	 * inform recipient about public link share
93
-	 *
94
-	 * @param string $recipient recipient email address
95
-	 * @param string $filename the shared file
96
-	 * @param string $link the public link
97
-	 * @param int $expiration expiration date (timestamp)
98
-	 * @return string[] $result of failed recipients
99
-	 */
100
-	public function sendLinkShareMail($recipient, $filename, $link, $expiration) {
101
-		$subject = (string)$this->l->t('%s shared »%s« with you', [$this->senderDisplayName, $filename]);
102
-		list($htmlBody, $textBody) = $this->createMailBody($filename, $link, $expiration);
91
+    /**
92
+     * inform recipient about public link share
93
+     *
94
+     * @param string $recipient recipient email address
95
+     * @param string $filename the shared file
96
+     * @param string $link the public link
97
+     * @param int $expiration expiration date (timestamp)
98
+     * @return string[] $result of failed recipients
99
+     */
100
+    public function sendLinkShareMail($recipient, $filename, $link, $expiration) {
101
+        $subject = (string)$this->l->t('%s shared »%s« with you', [$this->senderDisplayName, $filename]);
102
+        list($htmlBody, $textBody) = $this->createMailBody($filename, $link, $expiration);
103 103
 
104
-		$recipient = str_replace([', ', '; ', ',', ';', ' '], ',', $recipient);
105
-		$recipients = explode(',', $recipient);
106
-		try {
107
-			$message = $this->mailer->createMessage();
108
-			$message->setSubject($subject);
109
-			$message->setTo($recipients);
110
-			$message->setHtmlBody($htmlBody);
111
-			$message->setPlainBody($textBody);
112
-			$message->setFrom([
113
-				Util::getDefaultEmailAddress('sharing-noreply') =>
114
-					(string)$this->l->t('%s via %s', [
115
-						$this->senderDisplayName,
116
-						$this->defaults->getName()
117
-					]),
118
-			]);
119
-			if(!is_null($this->replyTo)) {
120
-				$message->setReplyTo([$this->replyTo]);
121
-			}
104
+        $recipient = str_replace([', ', '; ', ',', ';', ' '], ',', $recipient);
105
+        $recipients = explode(',', $recipient);
106
+        try {
107
+            $message = $this->mailer->createMessage();
108
+            $message->setSubject($subject);
109
+            $message->setTo($recipients);
110
+            $message->setHtmlBody($htmlBody);
111
+            $message->setPlainBody($textBody);
112
+            $message->setFrom([
113
+                Util::getDefaultEmailAddress('sharing-noreply') =>
114
+                    (string)$this->l->t('%s via %s', [
115
+                        $this->senderDisplayName,
116
+                        $this->defaults->getName()
117
+                    ]),
118
+            ]);
119
+            if(!is_null($this->replyTo)) {
120
+                $message->setReplyTo([$this->replyTo]);
121
+            }
122 122
 
123
-			return $this->mailer->send($message);
124
-		} catch (\Exception $e) {
125
-			$this->logger->error("Can't send mail with public link to $recipient: ".$e->getMessage(), ['app' => 'sharing']);
126
-			return [$recipient];
127
-		}
128
-	}
123
+            return $this->mailer->send($message);
124
+        } catch (\Exception $e) {
125
+            $this->logger->error("Can't send mail with public link to $recipient: ".$e->getMessage(), ['app' => 'sharing']);
126
+            return [$recipient];
127
+        }
128
+    }
129 129
 
130
-	/**
131
-	 * create mail body for plain text and html mail
132
-	 *
133
-	 * @param string $filename the shared file
134
-	 * @param string $link link to the shared file
135
-	 * @param int $expiration expiration date (timestamp)
136
-	 * @param string $prefix prefix of mail template files
137
-	 * @return array an array of the html mail body and the plain text mail body
138
-	 */
139
-	private function createMailBody($filename, $link, $expiration, $prefix = '') {
140
-		$formattedDate = $expiration ? $this->l->l('date', $expiration) : null;
130
+    /**
131
+     * create mail body for plain text and html mail
132
+     *
133
+     * @param string $filename the shared file
134
+     * @param string $link link to the shared file
135
+     * @param int $expiration expiration date (timestamp)
136
+     * @param string $prefix prefix of mail template files
137
+     * @return array an array of the html mail body and the plain text mail body
138
+     */
139
+    private function createMailBody($filename, $link, $expiration, $prefix = '') {
140
+        $formattedDate = $expiration ? $this->l->l('date', $expiration) : null;
141 141
 
142
-		$html = new \OC_Template('core', $prefix . 'mail', '');
143
-		$html->assign ('link', $link);
144
-		$html->assign ('user_displayname', $this->senderDisplayName);
145
-		$html->assign ('filename', $filename);
146
-		$html->assign('expiration',  $formattedDate);
147
-		$htmlMail = $html->fetchPage();
142
+        $html = new \OC_Template('core', $prefix . 'mail', '');
143
+        $html->assign ('link', $link);
144
+        $html->assign ('user_displayname', $this->senderDisplayName);
145
+        $html->assign ('filename', $filename);
146
+        $html->assign('expiration',  $formattedDate);
147
+        $htmlMail = $html->fetchPage();
148 148
 
149
-		$plainText = new \OC_Template('core', $prefix . 'altmail', '');
150
-		$plainText->assign ('link', $link);
151
-		$plainText->assign ('user_displayname', $this->senderDisplayName);
152
-		$plainText->assign ('filename', $filename);
153
-		$plainText->assign('expiration', $formattedDate);
154
-		$plainTextMail = $plainText->fetchPage();
149
+        $plainText = new \OC_Template('core', $prefix . 'altmail', '');
150
+        $plainText->assign ('link', $link);
151
+        $plainText->assign ('user_displayname', $this->senderDisplayName);
152
+        $plainText->assign ('filename', $filename);
153
+        $plainText->assign('expiration', $formattedDate);
154
+        $plainTextMail = $plainText->fetchPage();
155 155
 
156
-		return [$htmlMail, $plainTextMail];
157
-	}
156
+        return [$htmlMail, $plainTextMail];
157
+    }
158 158
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -98,7 +98,7 @@  discard block
 block discarded – undo
98 98
 	 * @return string[] $result of failed recipients
99 99
 	 */
100 100
 	public function sendLinkShareMail($recipient, $filename, $link, $expiration) {
101
-		$subject = (string)$this->l->t('%s shared »%s« with you', [$this->senderDisplayName, $filename]);
101
+		$subject = (string) $this->l->t('%s shared »%s« with you', [$this->senderDisplayName, $filename]);
102 102
 		list($htmlBody, $textBody) = $this->createMailBody($filename, $link, $expiration);
103 103
 
104 104
 		$recipient = str_replace([', ', '; ', ',', ';', ' '], ',', $recipient);
@@ -111,12 +111,12 @@  discard block
 block discarded – undo
111 111
 			$message->setPlainBody($textBody);
112 112
 			$message->setFrom([
113 113
 				Util::getDefaultEmailAddress('sharing-noreply') =>
114
-					(string)$this->l->t('%s via %s', [
114
+					(string) $this->l->t('%s via %s', [
115 115
 						$this->senderDisplayName,
116 116
 						$this->defaults->getName()
117 117
 					]),
118 118
 			]);
119
-			if(!is_null($this->replyTo)) {
119
+			if (!is_null($this->replyTo)) {
120 120
 				$message->setReplyTo([$this->replyTo]);
121 121
 			}
122 122
 
@@ -139,17 +139,17 @@  discard block
 block discarded – undo
139 139
 	private function createMailBody($filename, $link, $expiration, $prefix = '') {
140 140
 		$formattedDate = $expiration ? $this->l->l('date', $expiration) : null;
141 141
 
142
-		$html = new \OC_Template('core', $prefix . 'mail', '');
143
-		$html->assign ('link', $link);
144
-		$html->assign ('user_displayname', $this->senderDisplayName);
145
-		$html->assign ('filename', $filename);
146
-		$html->assign('expiration',  $formattedDate);
142
+		$html = new \OC_Template('core', $prefix.'mail', '');
143
+		$html->assign('link', $link);
144
+		$html->assign('user_displayname', $this->senderDisplayName);
145
+		$html->assign('filename', $filename);
146
+		$html->assign('expiration', $formattedDate);
147 147
 		$htmlMail = $html->fetchPage();
148 148
 
149
-		$plainText = new \OC_Template('core', $prefix . 'altmail', '');
150
-		$plainText->assign ('link', $link);
151
-		$plainText->assign ('user_displayname', $this->senderDisplayName);
152
-		$plainText->assign ('filename', $filename);
149
+		$plainText = new \OC_Template('core', $prefix.'altmail', '');
150
+		$plainText->assign('link', $link);
151
+		$plainText->assign('user_displayname', $this->senderDisplayName);
152
+		$plainText->assign('filename', $filename);
153 153
 		$plainText->assign('expiration', $formattedDate);
154 154
 		$plainTextMail = $plainText->fetchPage();
155 155
 
Please login to merge, or discard this patch.
lib/private/legacy/app.php 4 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -51,7 +51,6 @@
 block discarded – undo
51 51
 use OC\App\InfoParser;
52 52
 use OC\App\Platform;
53 53
 use OC\Installer;
54
-use OC\OCSClient;
55 54
 use OC\Repair;
56 55
 use OCP\App\ManagerEvent;
57 56
 
Please login to merge, or discard this patch.
Doc Comments   +6 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1063,7 +1063,7 @@  discard block
 block discarded – undo
1063 1063
 	 * @param string $app
1064 1064
 	 * @param \OCP\IConfig $config
1065 1065
 	 * @param \OCP\IL10N $l
1066
-	 * @return bool
1066
+	 * @return string
1067 1067
 	 *
1068 1068
 	 * @throws Exception if app is not compatible with this version of ownCloud
1069 1069
 	 * @throws Exception if no app-name was specified
@@ -1243,6 +1243,11 @@  discard block
 block discarded – undo
1243 1243
 		}
1244 1244
 	}
1245 1245
 
1246
+	/**
1247
+	 * @param string $lang
1248
+	 *
1249
+	 * @return string
1250
+	 */
1246 1251
 	protected static function findBestL10NOption($options, $lang) {
1247 1252
 		$fallback = $similarLangFallback = $englishFallback = false;
1248 1253
 
Please login to merge, or discard this patch.
Indentation   +1276 added lines, -1276 removed lines patch added patch discarded remove patch
@@ -61,1280 +61,1280 @@
 block discarded – undo
61 61
  * upgrading and removing apps.
62 62
  */
63 63
 class OC_App {
64
-	static private $appVersion = [];
65
-	static private $adminForms = array();
66
-	static private $personalForms = array();
67
-	static private $appInfo = array();
68
-	static private $appTypes = array();
69
-	static private $loadedApps = array();
70
-	static private $altLogin = array();
71
-	static private $alreadyRegistered = [];
72
-	const officialApp = 200;
73
-
74
-	/**
75
-	 * clean the appId
76
-	 *
77
-	 * @param string|boolean $app AppId that needs to be cleaned
78
-	 * @return string
79
-	 */
80
-	public static function cleanAppId($app) {
81
-		return str_replace(array('\0', '/', '\\', '..'), '', $app);
82
-	}
83
-
84
-	/**
85
-	 * Check if an app is loaded
86
-	 *
87
-	 * @param string $app
88
-	 * @return bool
89
-	 */
90
-	public static function isAppLoaded($app) {
91
-		return in_array($app, self::$loadedApps, true);
92
-	}
93
-
94
-	/**
95
-	 * loads all apps
96
-	 *
97
-	 * @param string[] | string | null $types
98
-	 * @return bool
99
-	 *
100
-	 * This function walks through the ownCloud directory and loads all apps
101
-	 * it can find. A directory contains an app if the file /appinfo/info.xml
102
-	 * exists.
103
-	 *
104
-	 * if $types is set, only apps of those types will be loaded
105
-	 */
106
-	public static function loadApps($types = null) {
107
-		if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) {
108
-			return false;
109
-		}
110
-		// Load the enabled apps here
111
-		$apps = self::getEnabledApps();
112
-
113
-		// Add each apps' folder as allowed class path
114
-		foreach($apps as $app) {
115
-			$path = self::getAppPath($app);
116
-			if($path !== false) {
117
-				self::registerAutoloading($app, $path);
118
-			}
119
-		}
120
-
121
-		// prevent app.php from printing output
122
-		ob_start();
123
-		foreach ($apps as $app) {
124
-			if ((is_null($types) or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
125
-				self::loadApp($app);
126
-			}
127
-		}
128
-		ob_end_clean();
129
-
130
-		return true;
131
-	}
132
-
133
-	/**
134
-	 * load a single app
135
-	 *
136
-	 * @param string $app
137
-	 */
138
-	public static function loadApp($app) {
139
-		self::$loadedApps[] = $app;
140
-		$appPath = self::getAppPath($app);
141
-		if($appPath === false) {
142
-			return;
143
-		}
144
-
145
-		// in case someone calls loadApp() directly
146
-		self::registerAutoloading($app, $appPath);
147
-
148
-		if (is_file($appPath . '/appinfo/app.php')) {
149
-			\OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
150
-			self::requireAppFile($app);
151
-			if (self::isType($app, array('authentication'))) {
152
-				// since authentication apps affect the "is app enabled for group" check,
153
-				// the enabled apps cache needs to be cleared to make sure that the
154
-				// next time getEnableApps() is called it will also include apps that were
155
-				// enabled for groups
156
-				self::$enabledAppsCache = array();
157
-			}
158
-			\OC::$server->getEventLogger()->end('load_app_' . $app);
159
-		}
160
-
161
-		$info = self::getAppInfo($app);
162
-		if (!empty($info['activity']['filters'])) {
163
-			foreach ($info['activity']['filters'] as $filter) {
164
-				\OC::$server->getActivityManager()->registerFilter($filter);
165
-			}
166
-		}
167
-		if (!empty($info['activity']['settings'])) {
168
-			foreach ($info['activity']['settings'] as $setting) {
169
-				\OC::$server->getActivityManager()->registerSetting($setting);
170
-			}
171
-		}
172
-		if (!empty($info['activity']['providers'])) {
173
-			foreach ($info['activity']['providers'] as $provider) {
174
-				\OC::$server->getActivityManager()->registerProvider($provider);
175
-			}
176
-		}
177
-	}
178
-
179
-	/**
180
-	 * @internal
181
-	 * @param string $app
182
-	 * @param string $path
183
-	 */
184
-	public static function registerAutoloading($app, $path) {
185
-		$key = $app . '-' . $path;
186
-		if(isset(self::$alreadyRegistered[$key])) {
187
-			return;
188
-		}
189
-		self::$alreadyRegistered[$key] = true;
190
-		// Register on PSR-4 composer autoloader
191
-		$appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
192
-		\OC::$server->registerNamespace($app, $appNamespace);
193
-		\OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
194
-		if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
195
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
196
-		}
197
-
198
-		// Register on legacy autoloader
199
-		\OC::$loader->addValidRoot($path);
200
-	}
201
-
202
-	/**
203
-	 * Load app.php from the given app
204
-	 *
205
-	 * @param string $app app name
206
-	 */
207
-	private static function requireAppFile($app) {
208
-		try {
209
-			// encapsulated here to avoid variable scope conflicts
210
-			require_once $app . '/appinfo/app.php';
211
-		} catch (Error $ex) {
212
-			\OC::$server->getLogger()->logException($ex);
213
-			$blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
214
-			if (!in_array($app, $blacklist)) {
215
-				self::disable($app);
216
-			}
217
-		}
218
-	}
219
-
220
-	/**
221
-	 * check if an app is of a specific type
222
-	 *
223
-	 * @param string $app
224
-	 * @param string|array $types
225
-	 * @return bool
226
-	 */
227
-	public static function isType($app, $types) {
228
-		if (is_string($types)) {
229
-			$types = array($types);
230
-		}
231
-		$appTypes = self::getAppTypes($app);
232
-		foreach ($types as $type) {
233
-			if (array_search($type, $appTypes) !== false) {
234
-				return true;
235
-			}
236
-		}
237
-		return false;
238
-	}
239
-
240
-	/**
241
-	 * get the types of an app
242
-	 *
243
-	 * @param string $app
244
-	 * @return array
245
-	 */
246
-	private static function getAppTypes($app) {
247
-		//load the cache
248
-		if (count(self::$appTypes) == 0) {
249
-			self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
250
-		}
251
-
252
-		if (isset(self::$appTypes[$app])) {
253
-			return explode(',', self::$appTypes[$app]);
254
-		} else {
255
-			return array();
256
-		}
257
-	}
258
-
259
-	/**
260
-	 * read app types from info.xml and cache them in the database
261
-	 */
262
-	public static function setAppTypes($app) {
263
-		$appData = self::getAppInfo($app);
264
-		if(!is_array($appData)) {
265
-			return;
266
-		}
267
-
268
-		if (isset($appData['types'])) {
269
-			$appTypes = implode(',', $appData['types']);
270
-		} else {
271
-			$appTypes = '';
272
-			$appData['types'] = [];
273
-		}
274
-
275
-		\OC::$server->getAppConfig()->setValue($app, 'types', $appTypes);
276
-
277
-		if (\OC::$server->getAppManager()->hasProtectedAppType($appData['types'])) {
278
-			$enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'yes');
279
-			if ($enabled !== 'yes' && $enabled !== 'no') {
280
-				\OC::$server->getAppConfig()->setValue($app, 'enabled', 'yes');
281
-			}
282
-		}
283
-	}
284
-
285
-	/**
286
-	 * check if app is shipped
287
-	 *
288
-	 * @param string $appId the id of the app to check
289
-	 * @return bool
290
-	 *
291
-	 * Check if an app that is installed is a shipped app or installed from the appstore.
292
-	 */
293
-	public static function isShipped($appId) {
294
-		return \OC::$server->getAppManager()->isShipped($appId);
295
-	}
296
-
297
-	/**
298
-	 * get all enabled apps
299
-	 */
300
-	protected static $enabledAppsCache = array();
301
-
302
-	/**
303
-	 * Returns apps enabled for the current user.
304
-	 *
305
-	 * @param bool $forceRefresh whether to refresh the cache
306
-	 * @param bool $all whether to return apps for all users, not only the
307
-	 * currently logged in one
308
-	 * @return string[]
309
-	 */
310
-	public static function getEnabledApps($forceRefresh = false, $all = false) {
311
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
312
-			return array();
313
-		}
314
-		// in incognito mode or when logged out, $user will be false,
315
-		// which is also the case during an upgrade
316
-		$appManager = \OC::$server->getAppManager();
317
-		if ($all) {
318
-			$user = null;
319
-		} else {
320
-			$user = \OC::$server->getUserSession()->getUser();
321
-		}
322
-
323
-		if (is_null($user)) {
324
-			$apps = $appManager->getInstalledApps();
325
-		} else {
326
-			$apps = $appManager->getEnabledAppsForUser($user);
327
-		}
328
-		$apps = array_filter($apps, function ($app) {
329
-			return $app !== 'files';//we add this manually
330
-		});
331
-		sort($apps);
332
-		array_unshift($apps, 'files');
333
-		return $apps;
334
-	}
335
-
336
-	/**
337
-	 * checks whether or not an app is enabled
338
-	 *
339
-	 * @param string $app app
340
-	 * @return bool
341
-	 *
342
-	 * This function checks whether or not an app is enabled.
343
-	 */
344
-	public static function isEnabled($app) {
345
-		return \OC::$server->getAppManager()->isEnabledForUser($app);
346
-	}
347
-
348
-	/**
349
-	 * enables an app
350
-	 *
351
-	 * @param string $appId
352
-	 * @param array $groups (optional) when set, only these groups will have access to the app
353
-	 * @throws \Exception
354
-	 * @return void
355
-	 *
356
-	 * This function set an app as enabled in appconfig.
357
-	 */
358
-	public function enable($appId,
359
-						   $groups = null) {
360
-		self::$enabledAppsCache = []; // flush
361
-		$l = \OC::$server->getL10N('core');
362
-		$config = \OC::$server->getConfig();
363
-
364
-		// Check if app is already downloaded
365
-		$installer = new Installer(
366
-			\OC::$server->getAppFetcher(),
367
-			\OC::$server->getHTTPClientService(),
368
-			\OC::$server->getTempManager(),
369
-			\OC::$server->getLogger()
370
-		);
371
-		$isDownloaded = $installer->isDownloaded($appId);
372
-
373
-		if(!$isDownloaded) {
374
-			$installer->downloadApp($appId);
375
-		}
376
-
377
-		if (!Installer::isInstalled($appId)) {
378
-			$appId = self::installApp(
379
-				$appId,
380
-				$config,
381
-				$l
382
-			);
383
-			$appPath = self::getAppPath($appId);
384
-			self::registerAutoloading($appId, $appPath);
385
-			$installer->installApp($appId);
386
-		} else {
387
-			// check for required dependencies
388
-			$info = self::getAppInfo($appId);
389
-			self::checkAppDependencies($config, $l, $info);
390
-			$appPath = self::getAppPath($appId);
391
-			self::registerAutoloading($appId, $appPath);
392
-			$installer->installApp($appId);
393
-		}
394
-
395
-		$appManager = \OC::$server->getAppManager();
396
-		if (!is_null($groups)) {
397
-			$groupManager = \OC::$server->getGroupManager();
398
-			$groupsList = [];
399
-			foreach ($groups as $group) {
400
-				$groupItem = $groupManager->get($group);
401
-				if ($groupItem instanceof \OCP\IGroup) {
402
-					$groupsList[] = $groupManager->get($group);
403
-				}
404
-			}
405
-			$appManager->enableAppForGroups($appId, $groupsList);
406
-		} else {
407
-			$appManager->enableApp($appId);
408
-		}
409
-
410
-		$info = self::getAppInfo($appId);
411
-		if(isset($info['settings']) && is_array($info['settings'])) {
412
-			$appPath = self::getAppPath($appId);
413
-			self::registerAutoloading($appId, $appPath);
414
-			\OC::$server->getSettingsManager()->setupSettings($info['settings']);
415
-		}
416
-	}
417
-
418
-	/**
419
-	 * @param string $app
420
-	 * @return bool
421
-	 */
422
-	public static function removeApp($app) {
423
-		if (self::isShipped($app)) {
424
-			return false;
425
-		}
426
-
427
-		$installer = new Installer(
428
-			\OC::$server->getAppFetcher(),
429
-			\OC::$server->getHTTPClientService(),
430
-			\OC::$server->getTempManager(),
431
-			\OC::$server->getLogger()
432
-		);
433
-		return $installer->removeApp($app);
434
-	}
435
-
436
-	/**
437
-	 * This function set an app as disabled in appconfig.
438
-	 *
439
-	 * @param string $app app
440
-	 * @throws Exception
441
-	 */
442
-	public static function disable($app) {
443
-		// flush
444
-		self::$enabledAppsCache = array();
445
-
446
-		// run uninstall steps
447
-		$appData = OC_App::getAppInfo($app);
448
-		if (!is_null($appData)) {
449
-			OC_App::executeRepairSteps($app, $appData['repair-steps']['uninstall']);
450
-		}
451
-
452
-		// emit disable hook - needed anymore ?
453
-		\OC_Hook::emit('OC_App', 'pre_disable', array('app' => $app));
454
-
455
-		// finally disable it
456
-		$appManager = \OC::$server->getAppManager();
457
-		$appManager->disableApp($app);
458
-	}
459
-
460
-	// This is private as well. It simply works, so don't ask for more details
461
-	private static function proceedNavigation($list) {
462
-		usort($list, function($a, $b) {
463
-			if (isset($a['order']) && isset($b['order'])) {
464
-				return ($a['order'] < $b['order']) ? -1 : 1;
465
-			} else if (isset($a['order']) || isset($b['order'])) {
466
-				return isset($a['order']) ? -1 : 1;
467
-			} else {
468
-				return ($a['name'] < $b['name']) ? -1 : 1;
469
-			}
470
-		});
471
-
472
-		$activeAppIndex = -1;
473
-		$activeApp = OC::$server->getNavigationManager()->getActiveEntry();
474
-		foreach ($list as $index => &$navEntry) {
475
-			$navEntry['showInHeader'] = true;
476
-			if ($navEntry['id'] == $activeApp) {
477
-				$navEntry['active'] = true;
478
-				$activeAppIndex = $index;
479
-			} else {
480
-				$navEntry['active'] = false;
481
-			}
482
-		}
483
-		unset($navEntry);
484
-
485
-		if (count($list) <= 8) {
486
-			return $list;
487
-		}
488
-
489
-		$headerIconCount = 7;
490
-		if($activeAppIndex > ($headerIconCount-1)) {
491
-			$active = $list[$activeAppIndex];
492
-			$lastInHeader = $list[$headerIconCount-1];
493
-			$list[$headerIconCount-1] = $active;
494
-			$list[$activeAppIndex] = $lastInHeader;
495
-		}
496
-
497
-		foreach ($list as $index => &$navEntry) {
498
-			if($index >= $headerIconCount) {
499
-				$navEntry['showInHeader'] = false;
500
-			}
501
-		}
502
-
503
-		return $list;
504
-	}
505
-
506
-	public static function proceedAppNavigation($entries) {
507
-		$activeAppIndex = -1;
508
-		$list = self::proceedNavigation($entries);
509
-
510
-		$activeApp = OC::$server->getNavigationManager()->getActiveEntry();
511
-		foreach ($list as $index => &$navEntry) {
512
-			if ($navEntry['id'] == $activeApp) {
513
-				$navEntry['active'] = true;
514
-				$activeAppIndex = $index;
515
-			} else {
516
-				$navEntry['active'] = false;
517
-			}
518
-		}
519
-
520
-
521
-		if (count($list) <= 8) {
522
-			return $list;
523
-		}
524
-
525
-		$headerIconCount = 7;
526
-		// move active item to last position
527
-		if($activeAppIndex > ($headerIconCount-1)) {
528
-			$active = $list[$activeAppIndex];
529
-			$lastInHeader = $list[$headerIconCount-1];
530
-			$list[$headerIconCount-1] = $active;
531
-			$list[$activeAppIndex] = $lastInHeader;
532
-		}
533
-		$list = array_slice($list, 0, $headerIconCount);
534
-
535
-		return $list;
536
-	}
537
-
538
-	/**
539
-	 * Get the path where to install apps
540
-	 *
541
-	 * @return string|false
542
-	 */
543
-	public static function getInstallPath() {
544
-		if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
545
-			return false;
546
-		}
547
-
548
-		foreach (OC::$APPSROOTS as $dir) {
549
-			if (isset($dir['writable']) && $dir['writable'] === true) {
550
-				return $dir['path'];
551
-			}
552
-		}
553
-
554
-		\OCP\Util::writeLog('core', 'No application directories are marked as writable.', \OCP\Util::ERROR);
555
-		return null;
556
-	}
557
-
558
-
559
-	/**
560
-	 * search for an app in all app-directories
561
-	 *
562
-	 * @param string $appId
563
-	 * @return false|string
564
-	 */
565
-	public static function findAppInDirectories($appId) {
566
-		$sanitizedAppId = self::cleanAppId($appId);
567
-		if($sanitizedAppId !== $appId) {
568
-			return false;
569
-		}
570
-		static $app_dir = array();
571
-
572
-		if (isset($app_dir[$appId])) {
573
-			return $app_dir[$appId];
574
-		}
575
-
576
-		$possibleApps = array();
577
-		foreach (OC::$APPSROOTS as $dir) {
578
-			if (file_exists($dir['path'] . '/' . $appId)) {
579
-				$possibleApps[] = $dir;
580
-			}
581
-		}
582
-
583
-		if (empty($possibleApps)) {
584
-			return false;
585
-		} elseif (count($possibleApps) === 1) {
586
-			$dir = array_shift($possibleApps);
587
-			$app_dir[$appId] = $dir;
588
-			return $dir;
589
-		} else {
590
-			$versionToLoad = array();
591
-			foreach ($possibleApps as $possibleApp) {
592
-				$version = self::getAppVersionByPath($possibleApp['path']);
593
-				if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
594
-					$versionToLoad = array(
595
-						'dir' => $possibleApp,
596
-						'version' => $version,
597
-					);
598
-				}
599
-			}
600
-			$app_dir[$appId] = $versionToLoad['dir'];
601
-			return $versionToLoad['dir'];
602
-			//TODO - write test
603
-		}
604
-	}
605
-
606
-	/**
607
-	 * Get the directory for the given app.
608
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
609
-	 *
610
-	 * @param string $appId
611
-	 * @return string|false
612
-	 */
613
-	public static function getAppPath($appId) {
614
-		if ($appId === null || trim($appId) === '') {
615
-			return false;
616
-		}
617
-
618
-		if (($dir = self::findAppInDirectories($appId)) != false) {
619
-			return $dir['path'] . '/' . $appId;
620
-		}
621
-		return false;
622
-	}
623
-
624
-	/**
625
-	 * Get the path for the given app on the access
626
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
627
-	 *
628
-	 * @param string $appId
629
-	 * @return string|false
630
-	 */
631
-	public static function getAppWebPath($appId) {
632
-		if (($dir = self::findAppInDirectories($appId)) != false) {
633
-			return OC::$WEBROOT . $dir['url'] . '/' . $appId;
634
-		}
635
-		return false;
636
-	}
637
-
638
-	/**
639
-	 * get the last version of the app from appinfo/info.xml
640
-	 *
641
-	 * @param string $appId
642
-	 * @param bool $useCache
643
-	 * @return string
644
-	 */
645
-	public static function getAppVersion($appId, $useCache = true) {
646
-		if($useCache && isset(self::$appVersion[$appId])) {
647
-			return self::$appVersion[$appId];
648
-		}
649
-
650
-		$file = self::getAppPath($appId);
651
-		self::$appVersion[$appId] = ($file !== false) ? self::getAppVersionByPath($file) : '0';
652
-		return self::$appVersion[$appId];
653
-	}
654
-
655
-	/**
656
-	 * get app's version based on it's path
657
-	 *
658
-	 * @param string $path
659
-	 * @return string
660
-	 */
661
-	public static function getAppVersionByPath($path) {
662
-		$infoFile = $path . '/appinfo/info.xml';
663
-		$appData = self::getAppInfo($infoFile, true);
664
-		return isset($appData['version']) ? $appData['version'] : '';
665
-	}
666
-
667
-
668
-	/**
669
-	 * Read all app metadata from the info.xml file
670
-	 *
671
-	 * @param string $appId id of the app or the path of the info.xml file
672
-	 * @param bool $path
673
-	 * @param string $lang
674
-	 * @return array|null
675
-	 * @note all data is read from info.xml, not just pre-defined fields
676
-	 */
677
-	public static function getAppInfo($appId, $path = false, $lang = null) {
678
-		if ($path) {
679
-			$file = $appId;
680
-		} else {
681
-			if ($lang === null && isset(self::$appInfo[$appId])) {
682
-				return self::$appInfo[$appId];
683
-			}
684
-			$appPath = self::getAppPath($appId);
685
-			if($appPath === false) {
686
-				return null;
687
-			}
688
-			$file = $appPath . '/appinfo/info.xml';
689
-		}
690
-
691
-		$parser = new InfoParser(\OC::$server->getMemCacheFactory()->create('core.appinfo'));
692
-		$data = $parser->parse($file);
693
-
694
-		if (is_array($data)) {
695
-			$data = OC_App::parseAppInfo($data, $lang);
696
-		}
697
-		if(isset($data['ocsid'])) {
698
-			$storedId = \OC::$server->getConfig()->getAppValue($appId, 'ocsid');
699
-			if($storedId !== '' && $storedId !== $data['ocsid']) {
700
-				$data['ocsid'] = $storedId;
701
-			}
702
-		}
703
-
704
-		if ($lang === null) {
705
-			self::$appInfo[$appId] = $data;
706
-		}
707
-
708
-		return $data;
709
-	}
710
-
711
-	/**
712
-	 * Returns the navigation
713
-	 *
714
-	 * @return array
715
-	 *
716
-	 * This function returns an array containing all entries added. The
717
-	 * entries are sorted by the key 'order' ascending. Additional to the keys
718
-	 * given for each app the following keys exist:
719
-	 *   - active: boolean, signals if the user is on this navigation entry
720
-	 */
721
-	public static function getNavigation() {
722
-		$entries = OC::$server->getNavigationManager()->getAll();
723
-		return self::proceedNavigation($entries);
724
-	}
725
-
726
-	/**
727
-	 * Returns the navigation inside the header bar
728
-	 *
729
-	 * @return array
730
-	 *
731
-	 * This function returns an array containing all entries added. The
732
-	 * entries are sorted by the key 'order' ascending. Additional to the keys
733
-	 * given for each app the following keys exist:
734
-	 *   - active: boolean, signals if the user is on this navigation entry
735
-	 */
736
-	public static function getHeaderNavigation() {
737
-		$entries = OC::$server->getNavigationManager()->getAll();
738
-		return self::proceedAppNavigation($entries);
739
-	}
740
-
741
-	/**
742
-	 * Returns the Settings Navigation
743
-	 *
744
-	 * @return string[]
745
-	 *
746
-	 * This function returns an array containing all settings pages added. The
747
-	 * entries are sorted by the key 'order' ascending.
748
-	 */
749
-	public static function getSettingsNavigation() {
750
-		$entries = OC::$server->getNavigationManager()->getAll('settings');
751
-		return self::proceedNavigation($entries);
752
-	}
753
-
754
-	/**
755
-	 * get the id of loaded app
756
-	 *
757
-	 * @return string
758
-	 */
759
-	public static function getCurrentApp() {
760
-		$request = \OC::$server->getRequest();
761
-		$script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
762
-		$topFolder = substr($script, 0, strpos($script, '/'));
763
-		if (empty($topFolder)) {
764
-			$path_info = $request->getPathInfo();
765
-			if ($path_info) {
766
-				$topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
767
-			}
768
-		}
769
-		if ($topFolder == 'apps') {
770
-			$length = strlen($topFolder);
771
-			return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1);
772
-		} else {
773
-			return $topFolder;
774
-		}
775
-	}
776
-
777
-	/**
778
-	 * @param string $type
779
-	 * @return array
780
-	 */
781
-	public static function getForms($type) {
782
-		$forms = array();
783
-		switch ($type) {
784
-			case 'admin':
785
-				$source = self::$adminForms;
786
-				break;
787
-			case 'personal':
788
-				$source = self::$personalForms;
789
-				break;
790
-			default:
791
-				return array();
792
-		}
793
-		foreach ($source as $form) {
794
-			$forms[] = include $form;
795
-		}
796
-		return $forms;
797
-	}
798
-
799
-	/**
800
-	 * register an admin form to be shown
801
-	 *
802
-	 * @param string $app
803
-	 * @param string $page
804
-	 */
805
-	public static function registerAdmin($app, $page) {
806
-		self::$adminForms[] = $app . '/' . $page . '.php';
807
-	}
808
-
809
-	/**
810
-	 * register a personal form to be shown
811
-	 * @param string $app
812
-	 * @param string $page
813
-	 */
814
-	public static function registerPersonal($app, $page) {
815
-		self::$personalForms[] = $app . '/' . $page . '.php';
816
-	}
817
-
818
-	/**
819
-	 * @param array $entry
820
-	 */
821
-	public static function registerLogIn(array $entry) {
822
-		self::$altLogin[] = $entry;
823
-	}
824
-
825
-	/**
826
-	 * @return array
827
-	 */
828
-	public static function getAlternativeLogIns() {
829
-		return self::$altLogin;
830
-	}
831
-
832
-	/**
833
-	 * get a list of all apps in the apps folder
834
-	 *
835
-	 * @return array an array of app names (string IDs)
836
-	 * @todo: change the name of this method to getInstalledApps, which is more accurate
837
-	 */
838
-	public static function getAllApps() {
839
-
840
-		$apps = array();
841
-
842
-		foreach (OC::$APPSROOTS as $apps_dir) {
843
-			if (!is_readable($apps_dir['path'])) {
844
-				\OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN);
845
-				continue;
846
-			}
847
-			$dh = opendir($apps_dir['path']);
848
-
849
-			if (is_resource($dh)) {
850
-				while (($file = readdir($dh)) !== false) {
851
-
852
-					if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
853
-
854
-						$apps[] = $file;
855
-					}
856
-				}
857
-			}
858
-		}
859
-
860
-		return $apps;
861
-	}
862
-
863
-	/**
864
-	 * List all apps, this is used in apps.php
865
-	 *
866
-	 * @return array
867
-	 */
868
-	public function listAllApps() {
869
-		$installedApps = OC_App::getAllApps();
870
-
871
-		//we don't want to show configuration for these
872
-		$blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
873
-		$appList = array();
874
-		$langCode = \OC::$server->getL10N('core')->getLanguageCode();
875
-		$urlGenerator = \OC::$server->getURLGenerator();
876
-
877
-		foreach ($installedApps as $app) {
878
-			if (array_search($app, $blacklist) === false) {
879
-
880
-				$info = OC_App::getAppInfo($app, false, $langCode);
881
-				if (!is_array($info)) {
882
-					\OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR);
883
-					continue;
884
-				}
885
-
886
-				if (!isset($info['name'])) {
887
-					\OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR);
888
-					continue;
889
-				}
890
-
891
-				$enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'no');
892
-				$info['groups'] = null;
893
-				if ($enabled === 'yes') {
894
-					$active = true;
895
-				} else if ($enabled === 'no') {
896
-					$active = false;
897
-				} else {
898
-					$active = true;
899
-					$info['groups'] = $enabled;
900
-				}
901
-
902
-				$info['active'] = $active;
903
-
904
-				if (self::isShipped($app)) {
905
-					$info['internal'] = true;
906
-					$info['level'] = self::officialApp;
907
-					$info['removable'] = false;
908
-				} else {
909
-					$info['internal'] = false;
910
-					$info['removable'] = true;
911
-				}
912
-
913
-				$appPath = self::getAppPath($app);
914
-				if($appPath !== false) {
915
-					$appIcon = $appPath . '/img/' . $app . '.svg';
916
-					if (file_exists($appIcon)) {
917
-						$info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, $app . '.svg');
918
-						$info['previewAsIcon'] = true;
919
-					} else {
920
-						$appIcon = $appPath . '/img/app.svg';
921
-						if (file_exists($appIcon)) {
922
-							$info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, 'app.svg');
923
-							$info['previewAsIcon'] = true;
924
-						}
925
-					}
926
-				}
927
-				// fix documentation
928
-				if (isset($info['documentation']) && is_array($info['documentation'])) {
929
-					foreach ($info['documentation'] as $key => $url) {
930
-						// If it is not an absolute URL we assume it is a key
931
-						// i.e. admin-ldap will get converted to go.php?to=admin-ldap
932
-						if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
933
-							$url = $urlGenerator->linkToDocs($url);
934
-						}
935
-
936
-						$info['documentation'][$key] = $url;
937
-					}
938
-				}
939
-
940
-				$info['version'] = OC_App::getAppVersion($app);
941
-				$appList[] = $info;
942
-			}
943
-		}
944
-
945
-		return $appList;
946
-	}
947
-
948
-	/**
949
-	 * Returns the internal app ID or false
950
-	 * @param string $ocsID
951
-	 * @return string|false
952
-	 */
953
-	public static function getInternalAppIdByOcs($ocsID) {
954
-		if(is_numeric($ocsID)) {
955
-			$idArray = \OC::$server->getAppConfig()->getValues(false, 'ocsid');
956
-			if(array_search($ocsID, $idArray)) {
957
-				return array_search($ocsID, $idArray);
958
-			}
959
-		}
960
-		return false;
961
-	}
962
-
963
-	public static function shouldUpgrade($app) {
964
-		$versions = self::getAppVersions();
965
-		$currentVersion = OC_App::getAppVersion($app);
966
-		if ($currentVersion && isset($versions[$app])) {
967
-			$installedVersion = $versions[$app];
968
-			if (!version_compare($currentVersion, $installedVersion, '=')) {
969
-				return true;
970
-			}
971
-		}
972
-		return false;
973
-	}
974
-
975
-	/**
976
-	 * Adjust the number of version parts of $version1 to match
977
-	 * the number of version parts of $version2.
978
-	 *
979
-	 * @param string $version1 version to adjust
980
-	 * @param string $version2 version to take the number of parts from
981
-	 * @return string shortened $version1
982
-	 */
983
-	private static function adjustVersionParts($version1, $version2) {
984
-		$version1 = explode('.', $version1);
985
-		$version2 = explode('.', $version2);
986
-		// reduce $version1 to match the number of parts in $version2
987
-		while (count($version1) > count($version2)) {
988
-			array_pop($version1);
989
-		}
990
-		// if $version1 does not have enough parts, add some
991
-		while (count($version1) < count($version2)) {
992
-			$version1[] = '0';
993
-		}
994
-		return implode('.', $version1);
995
-	}
996
-
997
-	/**
998
-	 * Check whether the current ownCloud version matches the given
999
-	 * application's version requirements.
1000
-	 *
1001
-	 * The comparison is made based on the number of parts that the
1002
-	 * app info version has. For example for ownCloud 6.0.3 if the
1003
-	 * app info version is expecting version 6.0, the comparison is
1004
-	 * made on the first two parts of the ownCloud version.
1005
-	 * This means that it's possible to specify "requiremin" => 6
1006
-	 * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
1007
-	 *
1008
-	 * @param string $ocVersion ownCloud version to check against
1009
-	 * @param array $appInfo app info (from xml)
1010
-	 *
1011
-	 * @return boolean true if compatible, otherwise false
1012
-	 */
1013
-	public static function isAppCompatible($ocVersion, $appInfo) {
1014
-		$requireMin = '';
1015
-		$requireMax = '';
1016
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
1017
-			$requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
1018
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
1019
-			$requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
1020
-		} else if (isset($appInfo['requiremin'])) {
1021
-			$requireMin = $appInfo['requiremin'];
1022
-		} else if (isset($appInfo['require'])) {
1023
-			$requireMin = $appInfo['require'];
1024
-		}
1025
-
1026
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
1027
-			$requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
1028
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
1029
-			$requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
1030
-		} else if (isset($appInfo['requiremax'])) {
1031
-			$requireMax = $appInfo['requiremax'];
1032
-		}
1033
-
1034
-		if (is_array($ocVersion)) {
1035
-			$ocVersion = implode('.', $ocVersion);
1036
-		}
1037
-
1038
-		if (!empty($requireMin)
1039
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
1040
-		) {
1041
-
1042
-			return false;
1043
-		}
1044
-
1045
-		if (!empty($requireMax)
1046
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
1047
-		) {
1048
-			return false;
1049
-		}
1050
-
1051
-		return true;
1052
-	}
1053
-
1054
-	/**
1055
-	 * get the installed version of all apps
1056
-	 */
1057
-	public static function getAppVersions() {
1058
-		static $versions;
1059
-
1060
-		if(!$versions) {
1061
-			$appConfig = \OC::$server->getAppConfig();
1062
-			$versions = $appConfig->getValues(false, 'installed_version');
1063
-		}
1064
-		return $versions;
1065
-	}
1066
-
1067
-	/**
1068
-	 * @param string $app
1069
-	 * @param \OCP\IConfig $config
1070
-	 * @param \OCP\IL10N $l
1071
-	 * @return bool
1072
-	 *
1073
-	 * @throws Exception if app is not compatible with this version of ownCloud
1074
-	 * @throws Exception if no app-name was specified
1075
-	 */
1076
-	public function installApp($app,
1077
-							   \OCP\IConfig $config,
1078
-							   \OCP\IL10N $l) {
1079
-		if ($app !== false) {
1080
-			// check if the app is compatible with this version of ownCloud
1081
-			$info = self::getAppInfo($app);
1082
-			if(!is_array($info)) {
1083
-				throw new \Exception(
1084
-					$l->t('App "%s" cannot be installed because appinfo file cannot be read.',
1085
-						[$info['name']]
1086
-					)
1087
-				);
1088
-			}
1089
-
1090
-			$version = \OCP\Util::getVersion();
1091
-			if (!self::isAppCompatible($version, $info)) {
1092
-				throw new \Exception(
1093
-					$l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
1094
-						array($info['name'])
1095
-					)
1096
-				);
1097
-			}
1098
-
1099
-			// check for required dependencies
1100
-			self::checkAppDependencies($config, $l, $info);
1101
-
1102
-			$config->setAppValue($app, 'enabled', 'yes');
1103
-			if (isset($appData['id'])) {
1104
-				$config->setAppValue($app, 'ocsid', $appData['id']);
1105
-			}
1106
-
1107
-			if(isset($info['settings']) && is_array($info['settings'])) {
1108
-				$appPath = self::getAppPath($app);
1109
-				self::registerAutoloading($app, $appPath);
1110
-				\OC::$server->getSettingsManager()->setupSettings($info['settings']);
1111
-			}
1112
-
1113
-			\OC_Hook::emit('OC_App', 'post_enable', array('app' => $app));
1114
-		} else {
1115
-			if(empty($appName) ) {
1116
-				throw new \Exception($l->t("No app name specified"));
1117
-			} else {
1118
-				throw new \Exception($l->t("App '%s' could not be installed!", $appName));
1119
-			}
1120
-		}
1121
-
1122
-		return $app;
1123
-	}
1124
-
1125
-	/**
1126
-	 * update the database for the app and call the update script
1127
-	 *
1128
-	 * @param string $appId
1129
-	 * @return bool
1130
-	 */
1131
-	public static function updateApp($appId) {
1132
-		$appPath = self::getAppPath($appId);
1133
-		if($appPath === false) {
1134
-			return false;
1135
-		}
1136
-		$appData = self::getAppInfo($appId);
1137
-		self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
1138
-		if (file_exists($appPath . '/appinfo/database.xml')) {
1139
-			OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
1140
-		}
1141
-		self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
1142
-		self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
1143
-		unset(self::$appVersion[$appId]);
1144
-		// run upgrade code
1145
-		if (file_exists($appPath . '/appinfo/update.php')) {
1146
-			self::loadApp($appId);
1147
-			include $appPath . '/appinfo/update.php';
1148
-		}
1149
-		self::setupBackgroundJobs($appData['background-jobs']);
1150
-		if(isset($appData['settings']) && is_array($appData['settings'])) {
1151
-			$appPath = self::getAppPath($appId);
1152
-			self::registerAutoloading($appId, $appPath);
1153
-			\OC::$server->getSettingsManager()->setupSettings($appData['settings']);
1154
-		}
1155
-
1156
-		//set remote/public handlers
1157
-		if (array_key_exists('ocsid', $appData)) {
1158
-			\OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
1159
-		} elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1160
-			\OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
1161
-		}
1162
-		foreach ($appData['remote'] as $name => $path) {
1163
-			\OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
1164
-		}
1165
-		foreach ($appData['public'] as $name => $path) {
1166
-			\OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
1167
-		}
1168
-
1169
-		self::setAppTypes($appId);
1170
-
1171
-		$version = \OC_App::getAppVersion($appId);
1172
-		\OC::$server->getAppConfig()->setValue($appId, 'installed_version', $version);
1173
-
1174
-		\OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
1175
-			ManagerEvent::EVENT_APP_UPDATE, $appId
1176
-		));
1177
-
1178
-		return true;
1179
-	}
1180
-
1181
-	/**
1182
-	 * @param string $appId
1183
-	 * @param string[] $steps
1184
-	 * @throws \OC\NeedsUpdateException
1185
-	 */
1186
-	public static function executeRepairSteps($appId, array $steps) {
1187
-		if (empty($steps)) {
1188
-			return;
1189
-		}
1190
-		// load the app
1191
-		self::loadApp($appId);
1192
-
1193
-		$dispatcher = OC::$server->getEventDispatcher();
1194
-
1195
-		// load the steps
1196
-		$r = new Repair([], $dispatcher);
1197
-		foreach ($steps as $step) {
1198
-			try {
1199
-				$r->addStep($step);
1200
-			} catch (Exception $ex) {
1201
-				$r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
1202
-				\OC::$server->getLogger()->logException($ex);
1203
-			}
1204
-		}
1205
-		// run the steps
1206
-		$r->run();
1207
-	}
1208
-
1209
-	public static function setupBackgroundJobs(array $jobs) {
1210
-		$queue = \OC::$server->getJobList();
1211
-		foreach ($jobs as $job) {
1212
-			$queue->add($job);
1213
-		}
1214
-	}
1215
-
1216
-	/**
1217
-	 * @param string $appId
1218
-	 * @param string[] $steps
1219
-	 */
1220
-	private static function setupLiveMigrations($appId, array $steps) {
1221
-		$queue = \OC::$server->getJobList();
1222
-		foreach ($steps as $step) {
1223
-			$queue->add('OC\Migration\BackgroundRepair', [
1224
-				'app' => $appId,
1225
-				'step' => $step]);
1226
-		}
1227
-	}
1228
-
1229
-	/**
1230
-	 * @param string $appId
1231
-	 * @return \OC\Files\View|false
1232
-	 */
1233
-	public static function getStorage($appId) {
1234
-		if (OC_App::isEnabled($appId)) { //sanity check
1235
-			if (\OC::$server->getUserSession()->isLoggedIn()) {
1236
-				$view = new \OC\Files\View('/' . OC_User::getUser());
1237
-				if (!$view->file_exists($appId)) {
1238
-					$view->mkdir($appId);
1239
-				}
1240
-				return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1241
-			} else {
1242
-				\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR);
1243
-				return false;
1244
-			}
1245
-		} else {
1246
-			\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR);
1247
-			return false;
1248
-		}
1249
-	}
1250
-
1251
-	protected static function findBestL10NOption($options, $lang) {
1252
-		$fallback = $similarLangFallback = $englishFallback = false;
1253
-
1254
-		$lang = strtolower($lang);
1255
-		$similarLang = $lang;
1256
-		if (strpos($similarLang, '_')) {
1257
-			// For "de_DE" we want to find "de" and the other way around
1258
-			$similarLang = substr($lang, 0, strpos($lang, '_'));
1259
-		}
1260
-
1261
-		foreach ($options as $option) {
1262
-			if (is_array($option)) {
1263
-				if ($fallback === false) {
1264
-					$fallback = $option['@value'];
1265
-				}
1266
-
1267
-				if (!isset($option['@attributes']['lang'])) {
1268
-					continue;
1269
-				}
1270
-
1271
-				$attributeLang = strtolower($option['@attributes']['lang']);
1272
-				if ($attributeLang === $lang) {
1273
-					return $option['@value'];
1274
-				}
1275
-
1276
-				if ($attributeLang === $similarLang) {
1277
-					$similarLangFallback = $option['@value'];
1278
-				} else if (strpos($attributeLang, $similarLang . '_') === 0) {
1279
-					if ($similarLangFallback === false) {
1280
-						$similarLangFallback =  $option['@value'];
1281
-					}
1282
-				}
1283
-			} else {
1284
-				$englishFallback = $option;
1285
-			}
1286
-		}
1287
-
1288
-		if ($similarLangFallback !== false) {
1289
-			return $similarLangFallback;
1290
-		} else if ($englishFallback !== false) {
1291
-			return $englishFallback;
1292
-		}
1293
-		return (string) $fallback;
1294
-	}
1295
-
1296
-	/**
1297
-	 * parses the app data array and enhanced the 'description' value
1298
-	 *
1299
-	 * @param array $data the app data
1300
-	 * @param string $lang
1301
-	 * @return array improved app data
1302
-	 */
1303
-	public static function parseAppInfo(array $data, $lang = null) {
1304
-
1305
-		if ($lang && isset($data['name']) && is_array($data['name'])) {
1306
-			$data['name'] = self::findBestL10NOption($data['name'], $lang);
1307
-		}
1308
-		if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1309
-			$data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1310
-		}
1311
-		if ($lang && isset($data['description']) && is_array($data['description'])) {
1312
-			$data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1313
-		} else if (isset($data['description']) && is_string($data['description'])) {
1314
-			$data['description'] = trim($data['description']);
1315
-		} else  {
1316
-			$data['description'] = '';
1317
-		}
1318
-
1319
-		return $data;
1320
-	}
1321
-
1322
-	/**
1323
-	 * @param \OCP\IConfig $config
1324
-	 * @param \OCP\IL10N $l
1325
-	 * @param array $info
1326
-	 * @throws \Exception
1327
-	 */
1328
-	protected static function checkAppDependencies($config, $l, $info) {
1329
-		$dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1330
-		$missing = $dependencyAnalyzer->analyze($info);
1331
-		if (!empty($missing)) {
1332
-			$missingMsg = join(PHP_EOL, $missing);
1333
-			throw new \Exception(
1334
-				$l->t('App "%s" cannot be installed because the following dependencies are not fulfilled: %s',
1335
-					[$info['name'], $missingMsg]
1336
-				)
1337
-			);
1338
-		}
1339
-	}
64
+    static private $appVersion = [];
65
+    static private $adminForms = array();
66
+    static private $personalForms = array();
67
+    static private $appInfo = array();
68
+    static private $appTypes = array();
69
+    static private $loadedApps = array();
70
+    static private $altLogin = array();
71
+    static private $alreadyRegistered = [];
72
+    const officialApp = 200;
73
+
74
+    /**
75
+     * clean the appId
76
+     *
77
+     * @param string|boolean $app AppId that needs to be cleaned
78
+     * @return string
79
+     */
80
+    public static function cleanAppId($app) {
81
+        return str_replace(array('\0', '/', '\\', '..'), '', $app);
82
+    }
83
+
84
+    /**
85
+     * Check if an app is loaded
86
+     *
87
+     * @param string $app
88
+     * @return bool
89
+     */
90
+    public static function isAppLoaded($app) {
91
+        return in_array($app, self::$loadedApps, true);
92
+    }
93
+
94
+    /**
95
+     * loads all apps
96
+     *
97
+     * @param string[] | string | null $types
98
+     * @return bool
99
+     *
100
+     * This function walks through the ownCloud directory and loads all apps
101
+     * it can find. A directory contains an app if the file /appinfo/info.xml
102
+     * exists.
103
+     *
104
+     * if $types is set, only apps of those types will be loaded
105
+     */
106
+    public static function loadApps($types = null) {
107
+        if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) {
108
+            return false;
109
+        }
110
+        // Load the enabled apps here
111
+        $apps = self::getEnabledApps();
112
+
113
+        // Add each apps' folder as allowed class path
114
+        foreach($apps as $app) {
115
+            $path = self::getAppPath($app);
116
+            if($path !== false) {
117
+                self::registerAutoloading($app, $path);
118
+            }
119
+        }
120
+
121
+        // prevent app.php from printing output
122
+        ob_start();
123
+        foreach ($apps as $app) {
124
+            if ((is_null($types) or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
125
+                self::loadApp($app);
126
+            }
127
+        }
128
+        ob_end_clean();
129
+
130
+        return true;
131
+    }
132
+
133
+    /**
134
+     * load a single app
135
+     *
136
+     * @param string $app
137
+     */
138
+    public static function loadApp($app) {
139
+        self::$loadedApps[] = $app;
140
+        $appPath = self::getAppPath($app);
141
+        if($appPath === false) {
142
+            return;
143
+        }
144
+
145
+        // in case someone calls loadApp() directly
146
+        self::registerAutoloading($app, $appPath);
147
+
148
+        if (is_file($appPath . '/appinfo/app.php')) {
149
+            \OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
150
+            self::requireAppFile($app);
151
+            if (self::isType($app, array('authentication'))) {
152
+                // since authentication apps affect the "is app enabled for group" check,
153
+                // the enabled apps cache needs to be cleared to make sure that the
154
+                // next time getEnableApps() is called it will also include apps that were
155
+                // enabled for groups
156
+                self::$enabledAppsCache = array();
157
+            }
158
+            \OC::$server->getEventLogger()->end('load_app_' . $app);
159
+        }
160
+
161
+        $info = self::getAppInfo($app);
162
+        if (!empty($info['activity']['filters'])) {
163
+            foreach ($info['activity']['filters'] as $filter) {
164
+                \OC::$server->getActivityManager()->registerFilter($filter);
165
+            }
166
+        }
167
+        if (!empty($info['activity']['settings'])) {
168
+            foreach ($info['activity']['settings'] as $setting) {
169
+                \OC::$server->getActivityManager()->registerSetting($setting);
170
+            }
171
+        }
172
+        if (!empty($info['activity']['providers'])) {
173
+            foreach ($info['activity']['providers'] as $provider) {
174
+                \OC::$server->getActivityManager()->registerProvider($provider);
175
+            }
176
+        }
177
+    }
178
+
179
+    /**
180
+     * @internal
181
+     * @param string $app
182
+     * @param string $path
183
+     */
184
+    public static function registerAutoloading($app, $path) {
185
+        $key = $app . '-' . $path;
186
+        if(isset(self::$alreadyRegistered[$key])) {
187
+            return;
188
+        }
189
+        self::$alreadyRegistered[$key] = true;
190
+        // Register on PSR-4 composer autoloader
191
+        $appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
192
+        \OC::$server->registerNamespace($app, $appNamespace);
193
+        \OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
194
+        if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
195
+            \OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
196
+        }
197
+
198
+        // Register on legacy autoloader
199
+        \OC::$loader->addValidRoot($path);
200
+    }
201
+
202
+    /**
203
+     * Load app.php from the given app
204
+     *
205
+     * @param string $app app name
206
+     */
207
+    private static function requireAppFile($app) {
208
+        try {
209
+            // encapsulated here to avoid variable scope conflicts
210
+            require_once $app . '/appinfo/app.php';
211
+        } catch (Error $ex) {
212
+            \OC::$server->getLogger()->logException($ex);
213
+            $blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
214
+            if (!in_array($app, $blacklist)) {
215
+                self::disable($app);
216
+            }
217
+        }
218
+    }
219
+
220
+    /**
221
+     * check if an app is of a specific type
222
+     *
223
+     * @param string $app
224
+     * @param string|array $types
225
+     * @return bool
226
+     */
227
+    public static function isType($app, $types) {
228
+        if (is_string($types)) {
229
+            $types = array($types);
230
+        }
231
+        $appTypes = self::getAppTypes($app);
232
+        foreach ($types as $type) {
233
+            if (array_search($type, $appTypes) !== false) {
234
+                return true;
235
+            }
236
+        }
237
+        return false;
238
+    }
239
+
240
+    /**
241
+     * get the types of an app
242
+     *
243
+     * @param string $app
244
+     * @return array
245
+     */
246
+    private static function getAppTypes($app) {
247
+        //load the cache
248
+        if (count(self::$appTypes) == 0) {
249
+            self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
250
+        }
251
+
252
+        if (isset(self::$appTypes[$app])) {
253
+            return explode(',', self::$appTypes[$app]);
254
+        } else {
255
+            return array();
256
+        }
257
+    }
258
+
259
+    /**
260
+     * read app types from info.xml and cache them in the database
261
+     */
262
+    public static function setAppTypes($app) {
263
+        $appData = self::getAppInfo($app);
264
+        if(!is_array($appData)) {
265
+            return;
266
+        }
267
+
268
+        if (isset($appData['types'])) {
269
+            $appTypes = implode(',', $appData['types']);
270
+        } else {
271
+            $appTypes = '';
272
+            $appData['types'] = [];
273
+        }
274
+
275
+        \OC::$server->getAppConfig()->setValue($app, 'types', $appTypes);
276
+
277
+        if (\OC::$server->getAppManager()->hasProtectedAppType($appData['types'])) {
278
+            $enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'yes');
279
+            if ($enabled !== 'yes' && $enabled !== 'no') {
280
+                \OC::$server->getAppConfig()->setValue($app, 'enabled', 'yes');
281
+            }
282
+        }
283
+    }
284
+
285
+    /**
286
+     * check if app is shipped
287
+     *
288
+     * @param string $appId the id of the app to check
289
+     * @return bool
290
+     *
291
+     * Check if an app that is installed is a shipped app or installed from the appstore.
292
+     */
293
+    public static function isShipped($appId) {
294
+        return \OC::$server->getAppManager()->isShipped($appId);
295
+    }
296
+
297
+    /**
298
+     * get all enabled apps
299
+     */
300
+    protected static $enabledAppsCache = array();
301
+
302
+    /**
303
+     * Returns apps enabled for the current user.
304
+     *
305
+     * @param bool $forceRefresh whether to refresh the cache
306
+     * @param bool $all whether to return apps for all users, not only the
307
+     * currently logged in one
308
+     * @return string[]
309
+     */
310
+    public static function getEnabledApps($forceRefresh = false, $all = false) {
311
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
312
+            return array();
313
+        }
314
+        // in incognito mode or when logged out, $user will be false,
315
+        // which is also the case during an upgrade
316
+        $appManager = \OC::$server->getAppManager();
317
+        if ($all) {
318
+            $user = null;
319
+        } else {
320
+            $user = \OC::$server->getUserSession()->getUser();
321
+        }
322
+
323
+        if (is_null($user)) {
324
+            $apps = $appManager->getInstalledApps();
325
+        } else {
326
+            $apps = $appManager->getEnabledAppsForUser($user);
327
+        }
328
+        $apps = array_filter($apps, function ($app) {
329
+            return $app !== 'files';//we add this manually
330
+        });
331
+        sort($apps);
332
+        array_unshift($apps, 'files');
333
+        return $apps;
334
+    }
335
+
336
+    /**
337
+     * checks whether or not an app is enabled
338
+     *
339
+     * @param string $app app
340
+     * @return bool
341
+     *
342
+     * This function checks whether or not an app is enabled.
343
+     */
344
+    public static function isEnabled($app) {
345
+        return \OC::$server->getAppManager()->isEnabledForUser($app);
346
+    }
347
+
348
+    /**
349
+     * enables an app
350
+     *
351
+     * @param string $appId
352
+     * @param array $groups (optional) when set, only these groups will have access to the app
353
+     * @throws \Exception
354
+     * @return void
355
+     *
356
+     * This function set an app as enabled in appconfig.
357
+     */
358
+    public function enable($appId,
359
+                            $groups = null) {
360
+        self::$enabledAppsCache = []; // flush
361
+        $l = \OC::$server->getL10N('core');
362
+        $config = \OC::$server->getConfig();
363
+
364
+        // Check if app is already downloaded
365
+        $installer = new Installer(
366
+            \OC::$server->getAppFetcher(),
367
+            \OC::$server->getHTTPClientService(),
368
+            \OC::$server->getTempManager(),
369
+            \OC::$server->getLogger()
370
+        );
371
+        $isDownloaded = $installer->isDownloaded($appId);
372
+
373
+        if(!$isDownloaded) {
374
+            $installer->downloadApp($appId);
375
+        }
376
+
377
+        if (!Installer::isInstalled($appId)) {
378
+            $appId = self::installApp(
379
+                $appId,
380
+                $config,
381
+                $l
382
+            );
383
+            $appPath = self::getAppPath($appId);
384
+            self::registerAutoloading($appId, $appPath);
385
+            $installer->installApp($appId);
386
+        } else {
387
+            // check for required dependencies
388
+            $info = self::getAppInfo($appId);
389
+            self::checkAppDependencies($config, $l, $info);
390
+            $appPath = self::getAppPath($appId);
391
+            self::registerAutoloading($appId, $appPath);
392
+            $installer->installApp($appId);
393
+        }
394
+
395
+        $appManager = \OC::$server->getAppManager();
396
+        if (!is_null($groups)) {
397
+            $groupManager = \OC::$server->getGroupManager();
398
+            $groupsList = [];
399
+            foreach ($groups as $group) {
400
+                $groupItem = $groupManager->get($group);
401
+                if ($groupItem instanceof \OCP\IGroup) {
402
+                    $groupsList[] = $groupManager->get($group);
403
+                }
404
+            }
405
+            $appManager->enableAppForGroups($appId, $groupsList);
406
+        } else {
407
+            $appManager->enableApp($appId);
408
+        }
409
+
410
+        $info = self::getAppInfo($appId);
411
+        if(isset($info['settings']) && is_array($info['settings'])) {
412
+            $appPath = self::getAppPath($appId);
413
+            self::registerAutoloading($appId, $appPath);
414
+            \OC::$server->getSettingsManager()->setupSettings($info['settings']);
415
+        }
416
+    }
417
+
418
+    /**
419
+     * @param string $app
420
+     * @return bool
421
+     */
422
+    public static function removeApp($app) {
423
+        if (self::isShipped($app)) {
424
+            return false;
425
+        }
426
+
427
+        $installer = new Installer(
428
+            \OC::$server->getAppFetcher(),
429
+            \OC::$server->getHTTPClientService(),
430
+            \OC::$server->getTempManager(),
431
+            \OC::$server->getLogger()
432
+        );
433
+        return $installer->removeApp($app);
434
+    }
435
+
436
+    /**
437
+     * This function set an app as disabled in appconfig.
438
+     *
439
+     * @param string $app app
440
+     * @throws Exception
441
+     */
442
+    public static function disable($app) {
443
+        // flush
444
+        self::$enabledAppsCache = array();
445
+
446
+        // run uninstall steps
447
+        $appData = OC_App::getAppInfo($app);
448
+        if (!is_null($appData)) {
449
+            OC_App::executeRepairSteps($app, $appData['repair-steps']['uninstall']);
450
+        }
451
+
452
+        // emit disable hook - needed anymore ?
453
+        \OC_Hook::emit('OC_App', 'pre_disable', array('app' => $app));
454
+
455
+        // finally disable it
456
+        $appManager = \OC::$server->getAppManager();
457
+        $appManager->disableApp($app);
458
+    }
459
+
460
+    // This is private as well. It simply works, so don't ask for more details
461
+    private static function proceedNavigation($list) {
462
+        usort($list, function($a, $b) {
463
+            if (isset($a['order']) && isset($b['order'])) {
464
+                return ($a['order'] < $b['order']) ? -1 : 1;
465
+            } else if (isset($a['order']) || isset($b['order'])) {
466
+                return isset($a['order']) ? -1 : 1;
467
+            } else {
468
+                return ($a['name'] < $b['name']) ? -1 : 1;
469
+            }
470
+        });
471
+
472
+        $activeAppIndex = -1;
473
+        $activeApp = OC::$server->getNavigationManager()->getActiveEntry();
474
+        foreach ($list as $index => &$navEntry) {
475
+            $navEntry['showInHeader'] = true;
476
+            if ($navEntry['id'] == $activeApp) {
477
+                $navEntry['active'] = true;
478
+                $activeAppIndex = $index;
479
+            } else {
480
+                $navEntry['active'] = false;
481
+            }
482
+        }
483
+        unset($navEntry);
484
+
485
+        if (count($list) <= 8) {
486
+            return $list;
487
+        }
488
+
489
+        $headerIconCount = 7;
490
+        if($activeAppIndex > ($headerIconCount-1)) {
491
+            $active = $list[$activeAppIndex];
492
+            $lastInHeader = $list[$headerIconCount-1];
493
+            $list[$headerIconCount-1] = $active;
494
+            $list[$activeAppIndex] = $lastInHeader;
495
+        }
496
+
497
+        foreach ($list as $index => &$navEntry) {
498
+            if($index >= $headerIconCount) {
499
+                $navEntry['showInHeader'] = false;
500
+            }
501
+        }
502
+
503
+        return $list;
504
+    }
505
+
506
+    public static function proceedAppNavigation($entries) {
507
+        $activeAppIndex = -1;
508
+        $list = self::proceedNavigation($entries);
509
+
510
+        $activeApp = OC::$server->getNavigationManager()->getActiveEntry();
511
+        foreach ($list as $index => &$navEntry) {
512
+            if ($navEntry['id'] == $activeApp) {
513
+                $navEntry['active'] = true;
514
+                $activeAppIndex = $index;
515
+            } else {
516
+                $navEntry['active'] = false;
517
+            }
518
+        }
519
+
520
+
521
+        if (count($list) <= 8) {
522
+            return $list;
523
+        }
524
+
525
+        $headerIconCount = 7;
526
+        // move active item to last position
527
+        if($activeAppIndex > ($headerIconCount-1)) {
528
+            $active = $list[$activeAppIndex];
529
+            $lastInHeader = $list[$headerIconCount-1];
530
+            $list[$headerIconCount-1] = $active;
531
+            $list[$activeAppIndex] = $lastInHeader;
532
+        }
533
+        $list = array_slice($list, 0, $headerIconCount);
534
+
535
+        return $list;
536
+    }
537
+
538
+    /**
539
+     * Get the path where to install apps
540
+     *
541
+     * @return string|false
542
+     */
543
+    public static function getInstallPath() {
544
+        if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
545
+            return false;
546
+        }
547
+
548
+        foreach (OC::$APPSROOTS as $dir) {
549
+            if (isset($dir['writable']) && $dir['writable'] === true) {
550
+                return $dir['path'];
551
+            }
552
+        }
553
+
554
+        \OCP\Util::writeLog('core', 'No application directories are marked as writable.', \OCP\Util::ERROR);
555
+        return null;
556
+    }
557
+
558
+
559
+    /**
560
+     * search for an app in all app-directories
561
+     *
562
+     * @param string $appId
563
+     * @return false|string
564
+     */
565
+    public static function findAppInDirectories($appId) {
566
+        $sanitizedAppId = self::cleanAppId($appId);
567
+        if($sanitizedAppId !== $appId) {
568
+            return false;
569
+        }
570
+        static $app_dir = array();
571
+
572
+        if (isset($app_dir[$appId])) {
573
+            return $app_dir[$appId];
574
+        }
575
+
576
+        $possibleApps = array();
577
+        foreach (OC::$APPSROOTS as $dir) {
578
+            if (file_exists($dir['path'] . '/' . $appId)) {
579
+                $possibleApps[] = $dir;
580
+            }
581
+        }
582
+
583
+        if (empty($possibleApps)) {
584
+            return false;
585
+        } elseif (count($possibleApps) === 1) {
586
+            $dir = array_shift($possibleApps);
587
+            $app_dir[$appId] = $dir;
588
+            return $dir;
589
+        } else {
590
+            $versionToLoad = array();
591
+            foreach ($possibleApps as $possibleApp) {
592
+                $version = self::getAppVersionByPath($possibleApp['path']);
593
+                if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
594
+                    $versionToLoad = array(
595
+                        'dir' => $possibleApp,
596
+                        'version' => $version,
597
+                    );
598
+                }
599
+            }
600
+            $app_dir[$appId] = $versionToLoad['dir'];
601
+            return $versionToLoad['dir'];
602
+            //TODO - write test
603
+        }
604
+    }
605
+
606
+    /**
607
+     * Get the directory for the given app.
608
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
609
+     *
610
+     * @param string $appId
611
+     * @return string|false
612
+     */
613
+    public static function getAppPath($appId) {
614
+        if ($appId === null || trim($appId) === '') {
615
+            return false;
616
+        }
617
+
618
+        if (($dir = self::findAppInDirectories($appId)) != false) {
619
+            return $dir['path'] . '/' . $appId;
620
+        }
621
+        return false;
622
+    }
623
+
624
+    /**
625
+     * Get the path for the given app on the access
626
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
627
+     *
628
+     * @param string $appId
629
+     * @return string|false
630
+     */
631
+    public static function getAppWebPath($appId) {
632
+        if (($dir = self::findAppInDirectories($appId)) != false) {
633
+            return OC::$WEBROOT . $dir['url'] . '/' . $appId;
634
+        }
635
+        return false;
636
+    }
637
+
638
+    /**
639
+     * get the last version of the app from appinfo/info.xml
640
+     *
641
+     * @param string $appId
642
+     * @param bool $useCache
643
+     * @return string
644
+     */
645
+    public static function getAppVersion($appId, $useCache = true) {
646
+        if($useCache && isset(self::$appVersion[$appId])) {
647
+            return self::$appVersion[$appId];
648
+        }
649
+
650
+        $file = self::getAppPath($appId);
651
+        self::$appVersion[$appId] = ($file !== false) ? self::getAppVersionByPath($file) : '0';
652
+        return self::$appVersion[$appId];
653
+    }
654
+
655
+    /**
656
+     * get app's version based on it's path
657
+     *
658
+     * @param string $path
659
+     * @return string
660
+     */
661
+    public static function getAppVersionByPath($path) {
662
+        $infoFile = $path . '/appinfo/info.xml';
663
+        $appData = self::getAppInfo($infoFile, true);
664
+        return isset($appData['version']) ? $appData['version'] : '';
665
+    }
666
+
667
+
668
+    /**
669
+     * Read all app metadata from the info.xml file
670
+     *
671
+     * @param string $appId id of the app or the path of the info.xml file
672
+     * @param bool $path
673
+     * @param string $lang
674
+     * @return array|null
675
+     * @note all data is read from info.xml, not just pre-defined fields
676
+     */
677
+    public static function getAppInfo($appId, $path = false, $lang = null) {
678
+        if ($path) {
679
+            $file = $appId;
680
+        } else {
681
+            if ($lang === null && isset(self::$appInfo[$appId])) {
682
+                return self::$appInfo[$appId];
683
+            }
684
+            $appPath = self::getAppPath($appId);
685
+            if($appPath === false) {
686
+                return null;
687
+            }
688
+            $file = $appPath . '/appinfo/info.xml';
689
+        }
690
+
691
+        $parser = new InfoParser(\OC::$server->getMemCacheFactory()->create('core.appinfo'));
692
+        $data = $parser->parse($file);
693
+
694
+        if (is_array($data)) {
695
+            $data = OC_App::parseAppInfo($data, $lang);
696
+        }
697
+        if(isset($data['ocsid'])) {
698
+            $storedId = \OC::$server->getConfig()->getAppValue($appId, 'ocsid');
699
+            if($storedId !== '' && $storedId !== $data['ocsid']) {
700
+                $data['ocsid'] = $storedId;
701
+            }
702
+        }
703
+
704
+        if ($lang === null) {
705
+            self::$appInfo[$appId] = $data;
706
+        }
707
+
708
+        return $data;
709
+    }
710
+
711
+    /**
712
+     * Returns the navigation
713
+     *
714
+     * @return array
715
+     *
716
+     * This function returns an array containing all entries added. The
717
+     * entries are sorted by the key 'order' ascending. Additional to the keys
718
+     * given for each app the following keys exist:
719
+     *   - active: boolean, signals if the user is on this navigation entry
720
+     */
721
+    public static function getNavigation() {
722
+        $entries = OC::$server->getNavigationManager()->getAll();
723
+        return self::proceedNavigation($entries);
724
+    }
725
+
726
+    /**
727
+     * Returns the navigation inside the header bar
728
+     *
729
+     * @return array
730
+     *
731
+     * This function returns an array containing all entries added. The
732
+     * entries are sorted by the key 'order' ascending. Additional to the keys
733
+     * given for each app the following keys exist:
734
+     *   - active: boolean, signals if the user is on this navigation entry
735
+     */
736
+    public static function getHeaderNavigation() {
737
+        $entries = OC::$server->getNavigationManager()->getAll();
738
+        return self::proceedAppNavigation($entries);
739
+    }
740
+
741
+    /**
742
+     * Returns the Settings Navigation
743
+     *
744
+     * @return string[]
745
+     *
746
+     * This function returns an array containing all settings pages added. The
747
+     * entries are sorted by the key 'order' ascending.
748
+     */
749
+    public static function getSettingsNavigation() {
750
+        $entries = OC::$server->getNavigationManager()->getAll('settings');
751
+        return self::proceedNavigation($entries);
752
+    }
753
+
754
+    /**
755
+     * get the id of loaded app
756
+     *
757
+     * @return string
758
+     */
759
+    public static function getCurrentApp() {
760
+        $request = \OC::$server->getRequest();
761
+        $script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
762
+        $topFolder = substr($script, 0, strpos($script, '/'));
763
+        if (empty($topFolder)) {
764
+            $path_info = $request->getPathInfo();
765
+            if ($path_info) {
766
+                $topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
767
+            }
768
+        }
769
+        if ($topFolder == 'apps') {
770
+            $length = strlen($topFolder);
771
+            return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1);
772
+        } else {
773
+            return $topFolder;
774
+        }
775
+    }
776
+
777
+    /**
778
+     * @param string $type
779
+     * @return array
780
+     */
781
+    public static function getForms($type) {
782
+        $forms = array();
783
+        switch ($type) {
784
+            case 'admin':
785
+                $source = self::$adminForms;
786
+                break;
787
+            case 'personal':
788
+                $source = self::$personalForms;
789
+                break;
790
+            default:
791
+                return array();
792
+        }
793
+        foreach ($source as $form) {
794
+            $forms[] = include $form;
795
+        }
796
+        return $forms;
797
+    }
798
+
799
+    /**
800
+     * register an admin form to be shown
801
+     *
802
+     * @param string $app
803
+     * @param string $page
804
+     */
805
+    public static function registerAdmin($app, $page) {
806
+        self::$adminForms[] = $app . '/' . $page . '.php';
807
+    }
808
+
809
+    /**
810
+     * register a personal form to be shown
811
+     * @param string $app
812
+     * @param string $page
813
+     */
814
+    public static function registerPersonal($app, $page) {
815
+        self::$personalForms[] = $app . '/' . $page . '.php';
816
+    }
817
+
818
+    /**
819
+     * @param array $entry
820
+     */
821
+    public static function registerLogIn(array $entry) {
822
+        self::$altLogin[] = $entry;
823
+    }
824
+
825
+    /**
826
+     * @return array
827
+     */
828
+    public static function getAlternativeLogIns() {
829
+        return self::$altLogin;
830
+    }
831
+
832
+    /**
833
+     * get a list of all apps in the apps folder
834
+     *
835
+     * @return array an array of app names (string IDs)
836
+     * @todo: change the name of this method to getInstalledApps, which is more accurate
837
+     */
838
+    public static function getAllApps() {
839
+
840
+        $apps = array();
841
+
842
+        foreach (OC::$APPSROOTS as $apps_dir) {
843
+            if (!is_readable($apps_dir['path'])) {
844
+                \OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN);
845
+                continue;
846
+            }
847
+            $dh = opendir($apps_dir['path']);
848
+
849
+            if (is_resource($dh)) {
850
+                while (($file = readdir($dh)) !== false) {
851
+
852
+                    if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
853
+
854
+                        $apps[] = $file;
855
+                    }
856
+                }
857
+            }
858
+        }
859
+
860
+        return $apps;
861
+    }
862
+
863
+    /**
864
+     * List all apps, this is used in apps.php
865
+     *
866
+     * @return array
867
+     */
868
+    public function listAllApps() {
869
+        $installedApps = OC_App::getAllApps();
870
+
871
+        //we don't want to show configuration for these
872
+        $blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
873
+        $appList = array();
874
+        $langCode = \OC::$server->getL10N('core')->getLanguageCode();
875
+        $urlGenerator = \OC::$server->getURLGenerator();
876
+
877
+        foreach ($installedApps as $app) {
878
+            if (array_search($app, $blacklist) === false) {
879
+
880
+                $info = OC_App::getAppInfo($app, false, $langCode);
881
+                if (!is_array($info)) {
882
+                    \OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR);
883
+                    continue;
884
+                }
885
+
886
+                if (!isset($info['name'])) {
887
+                    \OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR);
888
+                    continue;
889
+                }
890
+
891
+                $enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'no');
892
+                $info['groups'] = null;
893
+                if ($enabled === 'yes') {
894
+                    $active = true;
895
+                } else if ($enabled === 'no') {
896
+                    $active = false;
897
+                } else {
898
+                    $active = true;
899
+                    $info['groups'] = $enabled;
900
+                }
901
+
902
+                $info['active'] = $active;
903
+
904
+                if (self::isShipped($app)) {
905
+                    $info['internal'] = true;
906
+                    $info['level'] = self::officialApp;
907
+                    $info['removable'] = false;
908
+                } else {
909
+                    $info['internal'] = false;
910
+                    $info['removable'] = true;
911
+                }
912
+
913
+                $appPath = self::getAppPath($app);
914
+                if($appPath !== false) {
915
+                    $appIcon = $appPath . '/img/' . $app . '.svg';
916
+                    if (file_exists($appIcon)) {
917
+                        $info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, $app . '.svg');
918
+                        $info['previewAsIcon'] = true;
919
+                    } else {
920
+                        $appIcon = $appPath . '/img/app.svg';
921
+                        if (file_exists($appIcon)) {
922
+                            $info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, 'app.svg');
923
+                            $info['previewAsIcon'] = true;
924
+                        }
925
+                    }
926
+                }
927
+                // fix documentation
928
+                if (isset($info['documentation']) && is_array($info['documentation'])) {
929
+                    foreach ($info['documentation'] as $key => $url) {
930
+                        // If it is not an absolute URL we assume it is a key
931
+                        // i.e. admin-ldap will get converted to go.php?to=admin-ldap
932
+                        if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
933
+                            $url = $urlGenerator->linkToDocs($url);
934
+                        }
935
+
936
+                        $info['documentation'][$key] = $url;
937
+                    }
938
+                }
939
+
940
+                $info['version'] = OC_App::getAppVersion($app);
941
+                $appList[] = $info;
942
+            }
943
+        }
944
+
945
+        return $appList;
946
+    }
947
+
948
+    /**
949
+     * Returns the internal app ID or false
950
+     * @param string $ocsID
951
+     * @return string|false
952
+     */
953
+    public static function getInternalAppIdByOcs($ocsID) {
954
+        if(is_numeric($ocsID)) {
955
+            $idArray = \OC::$server->getAppConfig()->getValues(false, 'ocsid');
956
+            if(array_search($ocsID, $idArray)) {
957
+                return array_search($ocsID, $idArray);
958
+            }
959
+        }
960
+        return false;
961
+    }
962
+
963
+    public static function shouldUpgrade($app) {
964
+        $versions = self::getAppVersions();
965
+        $currentVersion = OC_App::getAppVersion($app);
966
+        if ($currentVersion && isset($versions[$app])) {
967
+            $installedVersion = $versions[$app];
968
+            if (!version_compare($currentVersion, $installedVersion, '=')) {
969
+                return true;
970
+            }
971
+        }
972
+        return false;
973
+    }
974
+
975
+    /**
976
+     * Adjust the number of version parts of $version1 to match
977
+     * the number of version parts of $version2.
978
+     *
979
+     * @param string $version1 version to adjust
980
+     * @param string $version2 version to take the number of parts from
981
+     * @return string shortened $version1
982
+     */
983
+    private static function adjustVersionParts($version1, $version2) {
984
+        $version1 = explode('.', $version1);
985
+        $version2 = explode('.', $version2);
986
+        // reduce $version1 to match the number of parts in $version2
987
+        while (count($version1) > count($version2)) {
988
+            array_pop($version1);
989
+        }
990
+        // if $version1 does not have enough parts, add some
991
+        while (count($version1) < count($version2)) {
992
+            $version1[] = '0';
993
+        }
994
+        return implode('.', $version1);
995
+    }
996
+
997
+    /**
998
+     * Check whether the current ownCloud version matches the given
999
+     * application's version requirements.
1000
+     *
1001
+     * The comparison is made based on the number of parts that the
1002
+     * app info version has. For example for ownCloud 6.0.3 if the
1003
+     * app info version is expecting version 6.0, the comparison is
1004
+     * made on the first two parts of the ownCloud version.
1005
+     * This means that it's possible to specify "requiremin" => 6
1006
+     * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
1007
+     *
1008
+     * @param string $ocVersion ownCloud version to check against
1009
+     * @param array $appInfo app info (from xml)
1010
+     *
1011
+     * @return boolean true if compatible, otherwise false
1012
+     */
1013
+    public static function isAppCompatible($ocVersion, $appInfo) {
1014
+        $requireMin = '';
1015
+        $requireMax = '';
1016
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
1017
+            $requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
1018
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
1019
+            $requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
1020
+        } else if (isset($appInfo['requiremin'])) {
1021
+            $requireMin = $appInfo['requiremin'];
1022
+        } else if (isset($appInfo['require'])) {
1023
+            $requireMin = $appInfo['require'];
1024
+        }
1025
+
1026
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
1027
+            $requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
1028
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
1029
+            $requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
1030
+        } else if (isset($appInfo['requiremax'])) {
1031
+            $requireMax = $appInfo['requiremax'];
1032
+        }
1033
+
1034
+        if (is_array($ocVersion)) {
1035
+            $ocVersion = implode('.', $ocVersion);
1036
+        }
1037
+
1038
+        if (!empty($requireMin)
1039
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
1040
+        ) {
1041
+
1042
+            return false;
1043
+        }
1044
+
1045
+        if (!empty($requireMax)
1046
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
1047
+        ) {
1048
+            return false;
1049
+        }
1050
+
1051
+        return true;
1052
+    }
1053
+
1054
+    /**
1055
+     * get the installed version of all apps
1056
+     */
1057
+    public static function getAppVersions() {
1058
+        static $versions;
1059
+
1060
+        if(!$versions) {
1061
+            $appConfig = \OC::$server->getAppConfig();
1062
+            $versions = $appConfig->getValues(false, 'installed_version');
1063
+        }
1064
+        return $versions;
1065
+    }
1066
+
1067
+    /**
1068
+     * @param string $app
1069
+     * @param \OCP\IConfig $config
1070
+     * @param \OCP\IL10N $l
1071
+     * @return bool
1072
+     *
1073
+     * @throws Exception if app is not compatible with this version of ownCloud
1074
+     * @throws Exception if no app-name was specified
1075
+     */
1076
+    public function installApp($app,
1077
+                                \OCP\IConfig $config,
1078
+                                \OCP\IL10N $l) {
1079
+        if ($app !== false) {
1080
+            // check if the app is compatible with this version of ownCloud
1081
+            $info = self::getAppInfo($app);
1082
+            if(!is_array($info)) {
1083
+                throw new \Exception(
1084
+                    $l->t('App "%s" cannot be installed because appinfo file cannot be read.',
1085
+                        [$info['name']]
1086
+                    )
1087
+                );
1088
+            }
1089
+
1090
+            $version = \OCP\Util::getVersion();
1091
+            if (!self::isAppCompatible($version, $info)) {
1092
+                throw new \Exception(
1093
+                    $l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
1094
+                        array($info['name'])
1095
+                    )
1096
+                );
1097
+            }
1098
+
1099
+            // check for required dependencies
1100
+            self::checkAppDependencies($config, $l, $info);
1101
+
1102
+            $config->setAppValue($app, 'enabled', 'yes');
1103
+            if (isset($appData['id'])) {
1104
+                $config->setAppValue($app, 'ocsid', $appData['id']);
1105
+            }
1106
+
1107
+            if(isset($info['settings']) && is_array($info['settings'])) {
1108
+                $appPath = self::getAppPath($app);
1109
+                self::registerAutoloading($app, $appPath);
1110
+                \OC::$server->getSettingsManager()->setupSettings($info['settings']);
1111
+            }
1112
+
1113
+            \OC_Hook::emit('OC_App', 'post_enable', array('app' => $app));
1114
+        } else {
1115
+            if(empty($appName) ) {
1116
+                throw new \Exception($l->t("No app name specified"));
1117
+            } else {
1118
+                throw new \Exception($l->t("App '%s' could not be installed!", $appName));
1119
+            }
1120
+        }
1121
+
1122
+        return $app;
1123
+    }
1124
+
1125
+    /**
1126
+     * update the database for the app and call the update script
1127
+     *
1128
+     * @param string $appId
1129
+     * @return bool
1130
+     */
1131
+    public static function updateApp($appId) {
1132
+        $appPath = self::getAppPath($appId);
1133
+        if($appPath === false) {
1134
+            return false;
1135
+        }
1136
+        $appData = self::getAppInfo($appId);
1137
+        self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
1138
+        if (file_exists($appPath . '/appinfo/database.xml')) {
1139
+            OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
1140
+        }
1141
+        self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
1142
+        self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
1143
+        unset(self::$appVersion[$appId]);
1144
+        // run upgrade code
1145
+        if (file_exists($appPath . '/appinfo/update.php')) {
1146
+            self::loadApp($appId);
1147
+            include $appPath . '/appinfo/update.php';
1148
+        }
1149
+        self::setupBackgroundJobs($appData['background-jobs']);
1150
+        if(isset($appData['settings']) && is_array($appData['settings'])) {
1151
+            $appPath = self::getAppPath($appId);
1152
+            self::registerAutoloading($appId, $appPath);
1153
+            \OC::$server->getSettingsManager()->setupSettings($appData['settings']);
1154
+        }
1155
+
1156
+        //set remote/public handlers
1157
+        if (array_key_exists('ocsid', $appData)) {
1158
+            \OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
1159
+        } elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1160
+            \OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
1161
+        }
1162
+        foreach ($appData['remote'] as $name => $path) {
1163
+            \OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
1164
+        }
1165
+        foreach ($appData['public'] as $name => $path) {
1166
+            \OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
1167
+        }
1168
+
1169
+        self::setAppTypes($appId);
1170
+
1171
+        $version = \OC_App::getAppVersion($appId);
1172
+        \OC::$server->getAppConfig()->setValue($appId, 'installed_version', $version);
1173
+
1174
+        \OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
1175
+            ManagerEvent::EVENT_APP_UPDATE, $appId
1176
+        ));
1177
+
1178
+        return true;
1179
+    }
1180
+
1181
+    /**
1182
+     * @param string $appId
1183
+     * @param string[] $steps
1184
+     * @throws \OC\NeedsUpdateException
1185
+     */
1186
+    public static function executeRepairSteps($appId, array $steps) {
1187
+        if (empty($steps)) {
1188
+            return;
1189
+        }
1190
+        // load the app
1191
+        self::loadApp($appId);
1192
+
1193
+        $dispatcher = OC::$server->getEventDispatcher();
1194
+
1195
+        // load the steps
1196
+        $r = new Repair([], $dispatcher);
1197
+        foreach ($steps as $step) {
1198
+            try {
1199
+                $r->addStep($step);
1200
+            } catch (Exception $ex) {
1201
+                $r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
1202
+                \OC::$server->getLogger()->logException($ex);
1203
+            }
1204
+        }
1205
+        // run the steps
1206
+        $r->run();
1207
+    }
1208
+
1209
+    public static function setupBackgroundJobs(array $jobs) {
1210
+        $queue = \OC::$server->getJobList();
1211
+        foreach ($jobs as $job) {
1212
+            $queue->add($job);
1213
+        }
1214
+    }
1215
+
1216
+    /**
1217
+     * @param string $appId
1218
+     * @param string[] $steps
1219
+     */
1220
+    private static function setupLiveMigrations($appId, array $steps) {
1221
+        $queue = \OC::$server->getJobList();
1222
+        foreach ($steps as $step) {
1223
+            $queue->add('OC\Migration\BackgroundRepair', [
1224
+                'app' => $appId,
1225
+                'step' => $step]);
1226
+        }
1227
+    }
1228
+
1229
+    /**
1230
+     * @param string $appId
1231
+     * @return \OC\Files\View|false
1232
+     */
1233
+    public static function getStorage($appId) {
1234
+        if (OC_App::isEnabled($appId)) { //sanity check
1235
+            if (\OC::$server->getUserSession()->isLoggedIn()) {
1236
+                $view = new \OC\Files\View('/' . OC_User::getUser());
1237
+                if (!$view->file_exists($appId)) {
1238
+                    $view->mkdir($appId);
1239
+                }
1240
+                return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1241
+            } else {
1242
+                \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR);
1243
+                return false;
1244
+            }
1245
+        } else {
1246
+            \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR);
1247
+            return false;
1248
+        }
1249
+    }
1250
+
1251
+    protected static function findBestL10NOption($options, $lang) {
1252
+        $fallback = $similarLangFallback = $englishFallback = false;
1253
+
1254
+        $lang = strtolower($lang);
1255
+        $similarLang = $lang;
1256
+        if (strpos($similarLang, '_')) {
1257
+            // For "de_DE" we want to find "de" and the other way around
1258
+            $similarLang = substr($lang, 0, strpos($lang, '_'));
1259
+        }
1260
+
1261
+        foreach ($options as $option) {
1262
+            if (is_array($option)) {
1263
+                if ($fallback === false) {
1264
+                    $fallback = $option['@value'];
1265
+                }
1266
+
1267
+                if (!isset($option['@attributes']['lang'])) {
1268
+                    continue;
1269
+                }
1270
+
1271
+                $attributeLang = strtolower($option['@attributes']['lang']);
1272
+                if ($attributeLang === $lang) {
1273
+                    return $option['@value'];
1274
+                }
1275
+
1276
+                if ($attributeLang === $similarLang) {
1277
+                    $similarLangFallback = $option['@value'];
1278
+                } else if (strpos($attributeLang, $similarLang . '_') === 0) {
1279
+                    if ($similarLangFallback === false) {
1280
+                        $similarLangFallback =  $option['@value'];
1281
+                    }
1282
+                }
1283
+            } else {
1284
+                $englishFallback = $option;
1285
+            }
1286
+        }
1287
+
1288
+        if ($similarLangFallback !== false) {
1289
+            return $similarLangFallback;
1290
+        } else if ($englishFallback !== false) {
1291
+            return $englishFallback;
1292
+        }
1293
+        return (string) $fallback;
1294
+    }
1295
+
1296
+    /**
1297
+     * parses the app data array and enhanced the 'description' value
1298
+     *
1299
+     * @param array $data the app data
1300
+     * @param string $lang
1301
+     * @return array improved app data
1302
+     */
1303
+    public static function parseAppInfo(array $data, $lang = null) {
1304
+
1305
+        if ($lang && isset($data['name']) && is_array($data['name'])) {
1306
+            $data['name'] = self::findBestL10NOption($data['name'], $lang);
1307
+        }
1308
+        if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1309
+            $data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1310
+        }
1311
+        if ($lang && isset($data['description']) && is_array($data['description'])) {
1312
+            $data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1313
+        } else if (isset($data['description']) && is_string($data['description'])) {
1314
+            $data['description'] = trim($data['description']);
1315
+        } else  {
1316
+            $data['description'] = '';
1317
+        }
1318
+
1319
+        return $data;
1320
+    }
1321
+
1322
+    /**
1323
+     * @param \OCP\IConfig $config
1324
+     * @param \OCP\IL10N $l
1325
+     * @param array $info
1326
+     * @throws \Exception
1327
+     */
1328
+    protected static function checkAppDependencies($config, $l, $info) {
1329
+        $dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1330
+        $missing = $dependencyAnalyzer->analyze($info);
1331
+        if (!empty($missing)) {
1332
+            $missingMsg = join(PHP_EOL, $missing);
1333
+            throw new \Exception(
1334
+                $l->t('App "%s" cannot be installed because the following dependencies are not fulfilled: %s',
1335
+                    [$info['name'], $missingMsg]
1336
+                )
1337
+            );
1338
+        }
1339
+    }
1340 1340
 }
Please login to merge, or discard this patch.
Spacing   +65 added lines, -65 removed lines patch added patch discarded remove patch
@@ -111,9 +111,9 @@  discard block
 block discarded – undo
111 111
 		$apps = self::getEnabledApps();
112 112
 
113 113
 		// Add each apps' folder as allowed class path
114
-		foreach($apps as $app) {
114
+		foreach ($apps as $app) {
115 115
 			$path = self::getAppPath($app);
116
-			if($path !== false) {
116
+			if ($path !== false) {
117 117
 				self::registerAutoloading($app, $path);
118 118
 			}
119 119
 		}
@@ -138,15 +138,15 @@  discard block
 block discarded – undo
138 138
 	public static function loadApp($app) {
139 139
 		self::$loadedApps[] = $app;
140 140
 		$appPath = self::getAppPath($app);
141
-		if($appPath === false) {
141
+		if ($appPath === false) {
142 142
 			return;
143 143
 		}
144 144
 
145 145
 		// in case someone calls loadApp() directly
146 146
 		self::registerAutoloading($app, $appPath);
147 147
 
148
-		if (is_file($appPath . '/appinfo/app.php')) {
149
-			\OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
148
+		if (is_file($appPath.'/appinfo/app.php')) {
149
+			\OC::$server->getEventLogger()->start('load_app_'.$app, 'Load app: '.$app);
150 150
 			self::requireAppFile($app);
151 151
 			if (self::isType($app, array('authentication'))) {
152 152
 				// since authentication apps affect the "is app enabled for group" check,
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
 				// enabled for groups
156 156
 				self::$enabledAppsCache = array();
157 157
 			}
158
-			\OC::$server->getEventLogger()->end('load_app_' . $app);
158
+			\OC::$server->getEventLogger()->end('load_app_'.$app);
159 159
 		}
160 160
 
161 161
 		$info = self::getAppInfo($app);
@@ -182,17 +182,17 @@  discard block
 block discarded – undo
182 182
 	 * @param string $path
183 183
 	 */
184 184
 	public static function registerAutoloading($app, $path) {
185
-		$key = $app . '-' . $path;
186
-		if(isset(self::$alreadyRegistered[$key])) {
185
+		$key = $app.'-'.$path;
186
+		if (isset(self::$alreadyRegistered[$key])) {
187 187
 			return;
188 188
 		}
189 189
 		self::$alreadyRegistered[$key] = true;
190 190
 		// Register on PSR-4 composer autoloader
191 191
 		$appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
192 192
 		\OC::$server->registerNamespace($app, $appNamespace);
193
-		\OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
193
+		\OC::$composerAutoloader->addPsr4($appNamespace.'\\', $path.'/lib/', true);
194 194
 		if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
195
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
195
+			\OC::$composerAutoloader->addPsr4($appNamespace.'\\Tests\\', $path.'/tests/', true);
196 196
 		}
197 197
 
198 198
 		// Register on legacy autoloader
@@ -207,7 +207,7 @@  discard block
 block discarded – undo
207 207
 	private static function requireAppFile($app) {
208 208
 		try {
209 209
 			// encapsulated here to avoid variable scope conflicts
210
-			require_once $app . '/appinfo/app.php';
210
+			require_once $app.'/appinfo/app.php';
211 211
 		} catch (Error $ex) {
212 212
 			\OC::$server->getLogger()->logException($ex);
213 213
 			$blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
@@ -261,7 +261,7 @@  discard block
 block discarded – undo
261 261
 	 */
262 262
 	public static function setAppTypes($app) {
263 263
 		$appData = self::getAppInfo($app);
264
-		if(!is_array($appData)) {
264
+		if (!is_array($appData)) {
265 265
 			return;
266 266
 		}
267 267
 
@@ -325,8 +325,8 @@  discard block
 block discarded – undo
325 325
 		} else {
326 326
 			$apps = $appManager->getEnabledAppsForUser($user);
327 327
 		}
328
-		$apps = array_filter($apps, function ($app) {
329
-			return $app !== 'files';//we add this manually
328
+		$apps = array_filter($apps, function($app) {
329
+			return $app !== 'files'; //we add this manually
330 330
 		});
331 331
 		sort($apps);
332 332
 		array_unshift($apps, 'files');
@@ -370,7 +370,7 @@  discard block
 block discarded – undo
370 370
 		);
371 371
 		$isDownloaded = $installer->isDownloaded($appId);
372 372
 
373
-		if(!$isDownloaded) {
373
+		if (!$isDownloaded) {
374 374
 			$installer->downloadApp($appId);
375 375
 		}
376 376
 
@@ -408,7 +408,7 @@  discard block
 block discarded – undo
408 408
 		}
409 409
 
410 410
 		$info = self::getAppInfo($appId);
411
-		if(isset($info['settings']) && is_array($info['settings'])) {
411
+		if (isset($info['settings']) && is_array($info['settings'])) {
412 412
 			$appPath = self::getAppPath($appId);
413 413
 			self::registerAutoloading($appId, $appPath);
414 414
 			\OC::$server->getSettingsManager()->setupSettings($info['settings']);
@@ -487,15 +487,15 @@  discard block
 block discarded – undo
487 487
 		}
488 488
 
489 489
 		$headerIconCount = 7;
490
-		if($activeAppIndex > ($headerIconCount-1)) {
490
+		if ($activeAppIndex > ($headerIconCount - 1)) {
491 491
 			$active = $list[$activeAppIndex];
492
-			$lastInHeader = $list[$headerIconCount-1];
493
-			$list[$headerIconCount-1] = $active;
492
+			$lastInHeader = $list[$headerIconCount - 1];
493
+			$list[$headerIconCount - 1] = $active;
494 494
 			$list[$activeAppIndex] = $lastInHeader;
495 495
 		}
496 496
 
497 497
 		foreach ($list as $index => &$navEntry) {
498
-			if($index >= $headerIconCount) {
498
+			if ($index >= $headerIconCount) {
499 499
 				$navEntry['showInHeader'] = false;
500 500
 			}
501 501
 		}
@@ -524,10 +524,10 @@  discard block
 block discarded – undo
524 524
 
525 525
 		$headerIconCount = 7;
526 526
 		// move active item to last position
527
-		if($activeAppIndex > ($headerIconCount-1)) {
527
+		if ($activeAppIndex > ($headerIconCount - 1)) {
528 528
 			$active = $list[$activeAppIndex];
529
-			$lastInHeader = $list[$headerIconCount-1];
530
-			$list[$headerIconCount-1] = $active;
529
+			$lastInHeader = $list[$headerIconCount - 1];
530
+			$list[$headerIconCount - 1] = $active;
531 531
 			$list[$activeAppIndex] = $lastInHeader;
532 532
 		}
533 533
 		$list = array_slice($list, 0, $headerIconCount);
@@ -564,7 +564,7 @@  discard block
 block discarded – undo
564 564
 	 */
565 565
 	public static function findAppInDirectories($appId) {
566 566
 		$sanitizedAppId = self::cleanAppId($appId);
567
-		if($sanitizedAppId !== $appId) {
567
+		if ($sanitizedAppId !== $appId) {
568 568
 			return false;
569 569
 		}
570 570
 		static $app_dir = array();
@@ -575,7 +575,7 @@  discard block
 block discarded – undo
575 575
 
576 576
 		$possibleApps = array();
577 577
 		foreach (OC::$APPSROOTS as $dir) {
578
-			if (file_exists($dir['path'] . '/' . $appId)) {
578
+			if (file_exists($dir['path'].'/'.$appId)) {
579 579
 				$possibleApps[] = $dir;
580 580
 			}
581 581
 		}
@@ -616,7 +616,7 @@  discard block
 block discarded – undo
616 616
 		}
617 617
 
618 618
 		if (($dir = self::findAppInDirectories($appId)) != false) {
619
-			return $dir['path'] . '/' . $appId;
619
+			return $dir['path'].'/'.$appId;
620 620
 		}
621 621
 		return false;
622 622
 	}
@@ -630,7 +630,7 @@  discard block
 block discarded – undo
630 630
 	 */
631 631
 	public static function getAppWebPath($appId) {
632 632
 		if (($dir = self::findAppInDirectories($appId)) != false) {
633
-			return OC::$WEBROOT . $dir['url'] . '/' . $appId;
633
+			return OC::$WEBROOT.$dir['url'].'/'.$appId;
634 634
 		}
635 635
 		return false;
636 636
 	}
@@ -643,7 +643,7 @@  discard block
 block discarded – undo
643 643
 	 * @return string
644 644
 	 */
645 645
 	public static function getAppVersion($appId, $useCache = true) {
646
-		if($useCache && isset(self::$appVersion[$appId])) {
646
+		if ($useCache && isset(self::$appVersion[$appId])) {
647 647
 			return self::$appVersion[$appId];
648 648
 		}
649 649
 
@@ -659,7 +659,7 @@  discard block
 block discarded – undo
659 659
 	 * @return string
660 660
 	 */
661 661
 	public static function getAppVersionByPath($path) {
662
-		$infoFile = $path . '/appinfo/info.xml';
662
+		$infoFile = $path.'/appinfo/info.xml';
663 663
 		$appData = self::getAppInfo($infoFile, true);
664 664
 		return isset($appData['version']) ? $appData['version'] : '';
665 665
 	}
@@ -682,10 +682,10 @@  discard block
 block discarded – undo
682 682
 				return self::$appInfo[$appId];
683 683
 			}
684 684
 			$appPath = self::getAppPath($appId);
685
-			if($appPath === false) {
685
+			if ($appPath === false) {
686 686
 				return null;
687 687
 			}
688
-			$file = $appPath . '/appinfo/info.xml';
688
+			$file = $appPath.'/appinfo/info.xml';
689 689
 		}
690 690
 
691 691
 		$parser = new InfoParser(\OC::$server->getMemCacheFactory()->create('core.appinfo'));
@@ -694,9 +694,9 @@  discard block
 block discarded – undo
694 694
 		if (is_array($data)) {
695 695
 			$data = OC_App::parseAppInfo($data, $lang);
696 696
 		}
697
-		if(isset($data['ocsid'])) {
697
+		if (isset($data['ocsid'])) {
698 698
 			$storedId = \OC::$server->getConfig()->getAppValue($appId, 'ocsid');
699
-			if($storedId !== '' && $storedId !== $data['ocsid']) {
699
+			if ($storedId !== '' && $storedId !== $data['ocsid']) {
700 700
 				$data['ocsid'] = $storedId;
701 701
 			}
702 702
 		}
@@ -803,7 +803,7 @@  discard block
 block discarded – undo
803 803
 	 * @param string $page
804 804
 	 */
805 805
 	public static function registerAdmin($app, $page) {
806
-		self::$adminForms[] = $app . '/' . $page . '.php';
806
+		self::$adminForms[] = $app.'/'.$page.'.php';
807 807
 	}
808 808
 
809 809
 	/**
@@ -812,7 +812,7 @@  discard block
 block discarded – undo
812 812
 	 * @param string $page
813 813
 	 */
814 814
 	public static function registerPersonal($app, $page) {
815
-		self::$personalForms[] = $app . '/' . $page . '.php';
815
+		self::$personalForms[] = $app.'/'.$page.'.php';
816 816
 	}
817 817
 
818 818
 	/**
@@ -841,7 +841,7 @@  discard block
 block discarded – undo
841 841
 
842 842
 		foreach (OC::$APPSROOTS as $apps_dir) {
843 843
 			if (!is_readable($apps_dir['path'])) {
844
-				\OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN);
844
+				\OCP\Util::writeLog('core', 'unable to read app folder : '.$apps_dir['path'], \OCP\Util::WARN);
845 845
 				continue;
846 846
 			}
847 847
 			$dh = opendir($apps_dir['path']);
@@ -849,7 +849,7 @@  discard block
 block discarded – undo
849 849
 			if (is_resource($dh)) {
850 850
 				while (($file = readdir($dh)) !== false) {
851 851
 
852
-					if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
852
+					if ($file[0] != '.' and is_dir($apps_dir['path'].'/'.$file) and is_file($apps_dir['path'].'/'.$file.'/appinfo/info.xml')) {
853 853
 
854 854
 						$apps[] = $file;
855 855
 					}
@@ -879,12 +879,12 @@  discard block
 block discarded – undo
879 879
 
880 880
 				$info = OC_App::getAppInfo($app, false, $langCode);
881 881
 				if (!is_array($info)) {
882
-					\OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR);
882
+					\OCP\Util::writeLog('core', 'Could not read app info file for app "'.$app.'"', \OCP\Util::ERROR);
883 883
 					continue;
884 884
 				}
885 885
 
886 886
 				if (!isset($info['name'])) {
887
-					\OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR);
887
+					\OCP\Util::writeLog('core', 'App id "'.$app.'" has no name in appinfo', \OCP\Util::ERROR);
888 888
 					continue;
889 889
 				}
890 890
 
@@ -911,13 +911,13 @@  discard block
 block discarded – undo
911 911
 				}
912 912
 
913 913
 				$appPath = self::getAppPath($app);
914
-				if($appPath !== false) {
915
-					$appIcon = $appPath . '/img/' . $app . '.svg';
914
+				if ($appPath !== false) {
915
+					$appIcon = $appPath.'/img/'.$app.'.svg';
916 916
 					if (file_exists($appIcon)) {
917
-						$info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, $app . '.svg');
917
+						$info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, $app.'.svg');
918 918
 						$info['previewAsIcon'] = true;
919 919
 					} else {
920
-						$appIcon = $appPath . '/img/app.svg';
920
+						$appIcon = $appPath.'/img/app.svg';
921 921
 						if (file_exists($appIcon)) {
922 922
 							$info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, 'app.svg');
923 923
 							$info['previewAsIcon'] = true;
@@ -951,9 +951,9 @@  discard block
 block discarded – undo
951 951
 	 * @return string|false
952 952
 	 */
953 953
 	public static function getInternalAppIdByOcs($ocsID) {
954
-		if(is_numeric($ocsID)) {
954
+		if (is_numeric($ocsID)) {
955 955
 			$idArray = \OC::$server->getAppConfig()->getValues(false, 'ocsid');
956
-			if(array_search($ocsID, $idArray)) {
956
+			if (array_search($ocsID, $idArray)) {
957 957
 				return array_search($ocsID, $idArray);
958 958
 			}
959 959
 		}
@@ -1057,7 +1057,7 @@  discard block
 block discarded – undo
1057 1057
 	public static function getAppVersions() {
1058 1058
 		static $versions;
1059 1059
 
1060
-		if(!$versions) {
1060
+		if (!$versions) {
1061 1061
 			$appConfig = \OC::$server->getAppConfig();
1062 1062
 			$versions = $appConfig->getValues(false, 'installed_version');
1063 1063
 		}
@@ -1079,7 +1079,7 @@  discard block
 block discarded – undo
1079 1079
 		if ($app !== false) {
1080 1080
 			// check if the app is compatible with this version of ownCloud
1081 1081
 			$info = self::getAppInfo($app);
1082
-			if(!is_array($info)) {
1082
+			if (!is_array($info)) {
1083 1083
 				throw new \Exception(
1084 1084
 					$l->t('App "%s" cannot be installed because appinfo file cannot be read.',
1085 1085
 						[$info['name']]
@@ -1104,7 +1104,7 @@  discard block
 block discarded – undo
1104 1104
 				$config->setAppValue($app, 'ocsid', $appData['id']);
1105 1105
 			}
1106 1106
 
1107
-			if(isset($info['settings']) && is_array($info['settings'])) {
1107
+			if (isset($info['settings']) && is_array($info['settings'])) {
1108 1108
 				$appPath = self::getAppPath($app);
1109 1109
 				self::registerAutoloading($app, $appPath);
1110 1110
 				\OC::$server->getSettingsManager()->setupSettings($info['settings']);
@@ -1112,7 +1112,7 @@  discard block
 block discarded – undo
1112 1112
 
1113 1113
 			\OC_Hook::emit('OC_App', 'post_enable', array('app' => $app));
1114 1114
 		} else {
1115
-			if(empty($appName) ) {
1115
+			if (empty($appName)) {
1116 1116
 				throw new \Exception($l->t("No app name specified"));
1117 1117
 			} else {
1118 1118
 				throw new \Exception($l->t("App '%s' could not be installed!", $appName));
@@ -1130,24 +1130,24 @@  discard block
 block discarded – undo
1130 1130
 	 */
1131 1131
 	public static function updateApp($appId) {
1132 1132
 		$appPath = self::getAppPath($appId);
1133
-		if($appPath === false) {
1133
+		if ($appPath === false) {
1134 1134
 			return false;
1135 1135
 		}
1136 1136
 		$appData = self::getAppInfo($appId);
1137 1137
 		self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
1138
-		if (file_exists($appPath . '/appinfo/database.xml')) {
1139
-			OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
1138
+		if (file_exists($appPath.'/appinfo/database.xml')) {
1139
+			OC_DB::updateDbFromStructure($appPath.'/appinfo/database.xml');
1140 1140
 		}
1141 1141
 		self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
1142 1142
 		self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
1143 1143
 		unset(self::$appVersion[$appId]);
1144 1144
 		// run upgrade code
1145
-		if (file_exists($appPath . '/appinfo/update.php')) {
1145
+		if (file_exists($appPath.'/appinfo/update.php')) {
1146 1146
 			self::loadApp($appId);
1147
-			include $appPath . '/appinfo/update.php';
1147
+			include $appPath.'/appinfo/update.php';
1148 1148
 		}
1149 1149
 		self::setupBackgroundJobs($appData['background-jobs']);
1150
-		if(isset($appData['settings']) && is_array($appData['settings'])) {
1150
+		if (isset($appData['settings']) && is_array($appData['settings'])) {
1151 1151
 			$appPath = self::getAppPath($appId);
1152 1152
 			self::registerAutoloading($appId, $appPath);
1153 1153
 			\OC::$server->getSettingsManager()->setupSettings($appData['settings']);
@@ -1156,14 +1156,14 @@  discard block
 block discarded – undo
1156 1156
 		//set remote/public handlers
1157 1157
 		if (array_key_exists('ocsid', $appData)) {
1158 1158
 			\OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
1159
-		} elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1159
+		} elseif (\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1160 1160
 			\OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
1161 1161
 		}
1162 1162
 		foreach ($appData['remote'] as $name => $path) {
1163
-			\OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
1163
+			\OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $appId.'/'.$path);
1164 1164
 		}
1165 1165
 		foreach ($appData['public'] as $name => $path) {
1166
-			\OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
1166
+			\OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $appId.'/'.$path);
1167 1167
 		}
1168 1168
 
1169 1169
 		self::setAppTypes($appId);
@@ -1233,17 +1233,17 @@  discard block
 block discarded – undo
1233 1233
 	public static function getStorage($appId) {
1234 1234
 		if (OC_App::isEnabled($appId)) { //sanity check
1235 1235
 			if (\OC::$server->getUserSession()->isLoggedIn()) {
1236
-				$view = new \OC\Files\View('/' . OC_User::getUser());
1236
+				$view = new \OC\Files\View('/'.OC_User::getUser());
1237 1237
 				if (!$view->file_exists($appId)) {
1238 1238
 					$view->mkdir($appId);
1239 1239
 				}
1240
-				return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1240
+				return new \OC\Files\View('/'.OC_User::getUser().'/'.$appId);
1241 1241
 			} else {
1242
-				\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR);
1242
+				\OCP\Util::writeLog('core', 'Can\'t get app storage, app '.$appId.', user not logged in', \OCP\Util::ERROR);
1243 1243
 				return false;
1244 1244
 			}
1245 1245
 		} else {
1246
-			\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR);
1246
+			\OCP\Util::writeLog('core', 'Can\'t get app storage, app '.$appId.' not enabled', \OCP\Util::ERROR);
1247 1247
 			return false;
1248 1248
 		}
1249 1249
 	}
@@ -1275,9 +1275,9 @@  discard block
 block discarded – undo
1275 1275
 
1276 1276
 				if ($attributeLang === $similarLang) {
1277 1277
 					$similarLangFallback = $option['@value'];
1278
-				} else if (strpos($attributeLang, $similarLang . '_') === 0) {
1278
+				} else if (strpos($attributeLang, $similarLang.'_') === 0) {
1279 1279
 					if ($similarLangFallback === false) {
1280
-						$similarLangFallback =  $option['@value'];
1280
+						$similarLangFallback = $option['@value'];
1281 1281
 					}
1282 1282
 				}
1283 1283
 			} else {
@@ -1312,7 +1312,7 @@  discard block
 block discarded – undo
1312 1312
 			$data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1313 1313
 		} else if (isset($data['description']) && is_string($data['description'])) {
1314 1314
 			$data['description'] = trim($data['description']);
1315
-		} else  {
1315
+		} else {
1316 1316
 			$data['description'] = '';
1317 1317
 		}
1318 1318
 
Please login to merge, or discard this patch.
lib/private/L10N/Factory.php 3 patches
Doc Comments   +5 added lines patch added patch discarded remove patch
@@ -318,6 +318,11 @@
 block discarded – undo
318 318
 	 */
319 319
 	// FIXME This method is only public, until OC_L10N does not need it anymore,
320 320
 	// FIXME This is also the reason, why it is not in the public interface
321
+
322
+	/**
323
+	 * @param string $app
324
+	 * @param string $lang
325
+	 */
321 326
 	public function getL10nFilesForApp($app, $lang) {
322 327
 		$languageFiles = [];
323 328
 
Please login to merge, or discard this patch.
Indentation   +387 added lines, -387 removed lines patch added patch discarded remove patch
@@ -40,391 +40,391 @@
 block discarded – undo
40 40
  */
41 41
 class Factory implements IFactory {
42 42
 
43
-	/** @var string */
44
-	protected $requestLanguage = '';
45
-
46
-	/**
47
-	 * cached instances
48
-	 * @var array Structure: Lang => App => \OCP\IL10N
49
-	 */
50
-	protected $instances = [];
51
-
52
-	/**
53
-	 * @var array Structure: App => string[]
54
-	 */
55
-	protected $availableLanguages = [];
56
-
57
-	/**
58
-	 * @var array Structure: string => callable
59
-	 */
60
-	protected $pluralFunctions = [];
61
-
62
-	/** @var IConfig */
63
-	protected $config;
64
-
65
-	/** @var IRequest */
66
-	protected $request;
67
-
68
-	/** @var IUserSession */
69
-	protected $userSession;
70
-
71
-	/** @var string */
72
-	protected $serverRoot;
73
-
74
-	/**
75
-	 * @param IConfig $config
76
-	 * @param IRequest $request
77
-	 * @param IUserSession $userSession
78
-	 * @param string $serverRoot
79
-	 */
80
-	public function __construct(IConfig $config,
81
-								IRequest $request,
82
-								IUserSession $userSession,
83
-								$serverRoot) {
84
-		$this->config = $config;
85
-		$this->request = $request;
86
-		$this->userSession = $userSession;
87
-		$this->serverRoot = $serverRoot;
88
-	}
89
-
90
-	/**
91
-	 * Get a language instance
92
-	 *
93
-	 * @param string $app
94
-	 * @param string|null $lang
95
-	 * @return \OCP\IL10N
96
-	 */
97
-	public function get($app, $lang = null) {
98
-		$app = \OC_App::cleanAppId($app);
99
-		if ($lang !== null) {
100
-			$lang = str_replace(array('\0', '/', '\\', '..'), '', (string) $lang);
101
-		}
102
-		if ($lang === null || !$this->languageExists($app, $lang)) {
103
-			$lang = $this->findLanguage($app);
104
-		}
105
-
106
-		if (!isset($this->instances[$lang][$app])) {
107
-			$this->instances[$lang][$app] = new L10N(
108
-				$this, $app, $lang,
109
-				$this->getL10nFilesForApp($app, $lang)
110
-			);
111
-		}
112
-
113
-		return $this->instances[$lang][$app];
114
-	}
115
-
116
-	/**
117
-	 * Find the best language
118
-	 *
119
-	 * @param string|null $app App id or null for core
120
-	 * @return string language If nothing works it returns 'en'
121
-	 */
122
-	public function findLanguage($app = null) {
123
-		if ($this->requestLanguage !== '' && $this->languageExists($app, $this->requestLanguage)) {
124
-			return $this->requestLanguage;
125
-		}
126
-
127
-		/**
128
-		 * At this point ownCloud might not yet be installed and thus the lookup
129
-		 * in the preferences table might fail. For this reason we need to check
130
-		 * whether the instance has already been installed
131
-		 *
132
-		 * @link https://github.com/owncloud/core/issues/21955
133
-		 */
134
-		if($this->config->getSystemValue('installed', false)) {
135
-			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
136
-			if(!is_null($userId)) {
137
-				$userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
138
-			} else {
139
-				$userLang = null;
140
-			}
141
-		} else {
142
-			$userId = null;
143
-			$userLang = null;
144
-		}
145
-
146
-		if ($userLang) {
147
-			$this->requestLanguage = $userLang;
148
-			if ($this->languageExists($app, $userLang)) {
149
-				return $userLang;
150
-			}
151
-		}
152
-
153
-		try {
154
-			// Try to get the language from the Request
155
-			$lang = $this->getLanguageFromRequest($app);
156
-			if ($userId !== null && $app === null && !$userLang) {
157
-				$this->config->setUserValue($userId, 'core', 'lang', $lang);
158
-			}
159
-			return $lang;
160
-		} catch (LanguageNotFoundException $e) {
161
-			// Finding language from request failed fall back to default language
162
-			$defaultLanguage = $this->config->getSystemValue('default_language', false);
163
-			if ($defaultLanguage !== false && $this->languageExists($app, $defaultLanguage)) {
164
-				return $defaultLanguage;
165
-			}
166
-		}
167
-
168
-		// We could not find any language so fall back to english
169
-		return 'en';
170
-	}
171
-
172
-	/**
173
-	 * Find all available languages for an app
174
-	 *
175
-	 * @param string|null $app App id or null for core
176
-	 * @return array an array of available languages
177
-	 */
178
-	public function findAvailableLanguages($app = null) {
179
-		$key = $app;
180
-		if ($key === null) {
181
-			$key = 'null';
182
-		}
183
-
184
-		// also works with null as key
185
-		if (!empty($this->availableLanguages[$key])) {
186
-			return $this->availableLanguages[$key];
187
-		}
188
-
189
-		$available = ['en']; //english is always available
190
-		$dir = $this->findL10nDir($app);
191
-		if (is_dir($dir)) {
192
-			$files = scandir($dir);
193
-			if ($files !== false) {
194
-				foreach ($files as $file) {
195
-					if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
196
-						$available[] = substr($file, 0, -5);
197
-					}
198
-				}
199
-			}
200
-		}
201
-
202
-		// merge with translations from theme
203
-		$theme = $this->config->getSystemValue('theme');
204
-		if (!empty($theme)) {
205
-			$themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
206
-
207
-			if (is_dir($themeDir)) {
208
-				$files = scandir($themeDir);
209
-				if ($files !== false) {
210
-					foreach ($files as $file) {
211
-						if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
212
-							$available[] = substr($file, 0, -5);
213
-						}
214
-					}
215
-				}
216
-			}
217
-		}
218
-
219
-		$this->availableLanguages[$key] = $available;
220
-		return $available;
221
-	}
222
-
223
-	/**
224
-	 * @param string|null $app App id or null for core
225
-	 * @param string $lang
226
-	 * @return bool
227
-	 */
228
-	public function languageExists($app, $lang) {
229
-		if ($lang === 'en') {//english is always available
230
-			return true;
231
-		}
232
-
233
-		$languages = $this->findAvailableLanguages($app);
234
-		return array_search($lang, $languages) !== false;
235
-	}
236
-
237
-	/**
238
-	 * @param string|null $app
239
-	 * @return string
240
-	 * @throws LanguageNotFoundException
241
-	 */
242
-	private function getLanguageFromRequest($app) {
243
-		$header = $this->request->getHeader('ACCEPT_LANGUAGE');
244
-		if ($header) {
245
-			$available = $this->findAvailableLanguages($app);
246
-
247
-			// E.g. make sure that 'de' is before 'de_DE'.
248
-			sort($available);
249
-
250
-			$preferences = preg_split('/,\s*/', strtolower($header));
251
-			foreach ($preferences as $preference) {
252
-				list($preferred_language) = explode(';', $preference);
253
-				$preferred_language = str_replace('-', '_', $preferred_language);
254
-
255
-				foreach ($available as $available_language) {
256
-					if ($preferred_language === strtolower($available_language)) {
257
-						return $available_language;
258
-					}
259
-				}
260
-
261
-				// Fallback from de_De to de
262
-				foreach ($available as $available_language) {
263
-					if (substr($preferred_language, 0, 2) === $available_language) {
264
-						return $available_language;
265
-					}
266
-				}
267
-			}
268
-		}
269
-
270
-		throw new LanguageNotFoundException();
271
-	}
272
-
273
-	/**
274
-	 * @param string|null $app App id or null for core
275
-	 * @return string
276
-	 */
277
-	public function setLanguageFromRequest($app = null) {
278
-
279
-		try {
280
-			$requestLanguage = $this->getLanguageFromRequest($app);
281
-		} catch (LanguageNotFoundException $e) {
282
-			$requestLanguage = 'en';
283
-		}
284
-
285
-		if ($app === null && !$this->requestLanguage) {
286
-			$this->requestLanguage = $requestLanguage;
287
-		}
288
-		return $requestLanguage;
289
-	}
290
-
291
-	/**
292
-	 * Checks if $sub is a subdirectory of $parent
293
-	 *
294
-	 * @param string $sub
295
-	 * @param string $parent
296
-	 * @return bool
297
-	 */
298
-	private function isSubDirectory($sub, $parent) {
299
-		// Check whether $sub contains no ".."
300
-		if(strpos($sub, '..') !== false) {
301
-			return false;
302
-		}
303
-
304
-		// Check whether $sub is a subdirectory of $parent
305
-		if (strpos($sub, $parent) === 0) {
306
-			return true;
307
-		}
308
-
309
-		return false;
310
-	}
311
-
312
-	/**
313
-	 * Get a list of language files that should be loaded
314
-	 *
315
-	 * @param string $app
316
-	 * @param string $lang
317
-	 * @return string[]
318
-	 */
319
-	// FIXME This method is only public, until OC_L10N does not need it anymore,
320
-	// FIXME This is also the reason, why it is not in the public interface
321
-	public function getL10nFilesForApp($app, $lang) {
322
-		$languageFiles = [];
323
-
324
-		$i18nDir = $this->findL10nDir($app);
325
-		$transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
326
-
327
-		if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
328
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
329
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
330
-				|| $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
331
-			)
332
-			&& file_exists($transFile)) {
333
-			// load the translations file
334
-			$languageFiles[] = $transFile;
335
-		}
336
-
337
-		// merge with translations from theme
338
-		$theme = $this->config->getSystemValue('theme');
339
-		if (!empty($theme)) {
340
-			$transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
341
-			if (file_exists($transFile)) {
342
-				$languageFiles[] = $transFile;
343
-			}
344
-		}
345
-
346
-		return $languageFiles;
347
-	}
348
-
349
-	/**
350
-	 * find the l10n directory
351
-	 *
352
-	 * @param string $app App id or empty string for core
353
-	 * @return string directory
354
-	 */
355
-	protected function findL10nDir($app = null) {
356
-		if (in_array($app, ['core', 'lib', 'settings'])) {
357
-			if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
358
-				return $this->serverRoot . '/' . $app . '/l10n/';
359
-			}
360
-		} else if ($app && \OC_App::getAppPath($app) !== false) {
361
-			// Check if the app is in the app folder
362
-			return \OC_App::getAppPath($app) . '/l10n/';
363
-		}
364
-		return $this->serverRoot . '/core/l10n/';
365
-	}
366
-
367
-
368
-	/**
369
-	 * Creates a function from the plural string
370
-	 *
371
-	 * Parts of the code is copied from Habari:
372
-	 * https://github.com/habari/system/blob/master/classes/locale.php
373
-	 * @param string $string
374
-	 * @return string
375
-	 */
376
-	public function createPluralFunction($string) {
377
-		if (isset($this->pluralFunctions[$string])) {
378
-			return $this->pluralFunctions[$string];
379
-		}
380
-
381
-		if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
382
-			// sanitize
383
-			$nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
384
-			$plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
385
-
386
-			$body = str_replace(
387
-				array( 'plural', 'n', '$n$plurals', ),
388
-				array( '$plural', '$n', '$nplurals', ),
389
-				'nplurals='. $nplurals . '; plural=' . $plural
390
-			);
391
-
392
-			// add parents
393
-			// important since PHP's ternary evaluates from left to right
394
-			$body .= ';';
395
-			$res = '';
396
-			$p = 0;
397
-			for($i = 0; $i < strlen($body); $i++) {
398
-				$ch = $body[$i];
399
-				switch ( $ch ) {
400
-					case '?':
401
-						$res .= ' ? (';
402
-						$p++;
403
-						break;
404
-					case ':':
405
-						$res .= ') : (';
406
-						break;
407
-					case ';':
408
-						$res .= str_repeat( ')', $p ) . ';';
409
-						$p = 0;
410
-						break;
411
-					default:
412
-						$res .= $ch;
413
-				}
414
-			}
415
-
416
-			$body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
417
-			$function = create_function('$n', $body);
418
-			$this->pluralFunctions[$string] = $function;
419
-			return $function;
420
-		} else {
421
-			// default: one plural form for all cases but n==1 (english)
422
-			$function = create_function(
423
-				'$n',
424
-				'$nplurals=2;$plural=($n==1?0:1);return ($plural>=$nplurals?$nplurals-1:$plural);'
425
-			);
426
-			$this->pluralFunctions[$string] = $function;
427
-			return $function;
428
-		}
429
-	}
43
+    /** @var string */
44
+    protected $requestLanguage = '';
45
+
46
+    /**
47
+     * cached instances
48
+     * @var array Structure: Lang => App => \OCP\IL10N
49
+     */
50
+    protected $instances = [];
51
+
52
+    /**
53
+     * @var array Structure: App => string[]
54
+     */
55
+    protected $availableLanguages = [];
56
+
57
+    /**
58
+     * @var array Structure: string => callable
59
+     */
60
+    protected $pluralFunctions = [];
61
+
62
+    /** @var IConfig */
63
+    protected $config;
64
+
65
+    /** @var IRequest */
66
+    protected $request;
67
+
68
+    /** @var IUserSession */
69
+    protected $userSession;
70
+
71
+    /** @var string */
72
+    protected $serverRoot;
73
+
74
+    /**
75
+     * @param IConfig $config
76
+     * @param IRequest $request
77
+     * @param IUserSession $userSession
78
+     * @param string $serverRoot
79
+     */
80
+    public function __construct(IConfig $config,
81
+                                IRequest $request,
82
+                                IUserSession $userSession,
83
+                                $serverRoot) {
84
+        $this->config = $config;
85
+        $this->request = $request;
86
+        $this->userSession = $userSession;
87
+        $this->serverRoot = $serverRoot;
88
+    }
89
+
90
+    /**
91
+     * Get a language instance
92
+     *
93
+     * @param string $app
94
+     * @param string|null $lang
95
+     * @return \OCP\IL10N
96
+     */
97
+    public function get($app, $lang = null) {
98
+        $app = \OC_App::cleanAppId($app);
99
+        if ($lang !== null) {
100
+            $lang = str_replace(array('\0', '/', '\\', '..'), '', (string) $lang);
101
+        }
102
+        if ($lang === null || !$this->languageExists($app, $lang)) {
103
+            $lang = $this->findLanguage($app);
104
+        }
105
+
106
+        if (!isset($this->instances[$lang][$app])) {
107
+            $this->instances[$lang][$app] = new L10N(
108
+                $this, $app, $lang,
109
+                $this->getL10nFilesForApp($app, $lang)
110
+            );
111
+        }
112
+
113
+        return $this->instances[$lang][$app];
114
+    }
115
+
116
+    /**
117
+     * Find the best language
118
+     *
119
+     * @param string|null $app App id or null for core
120
+     * @return string language If nothing works it returns 'en'
121
+     */
122
+    public function findLanguage($app = null) {
123
+        if ($this->requestLanguage !== '' && $this->languageExists($app, $this->requestLanguage)) {
124
+            return $this->requestLanguage;
125
+        }
126
+
127
+        /**
128
+         * At this point ownCloud might not yet be installed and thus the lookup
129
+         * in the preferences table might fail. For this reason we need to check
130
+         * whether the instance has already been installed
131
+         *
132
+         * @link https://github.com/owncloud/core/issues/21955
133
+         */
134
+        if($this->config->getSystemValue('installed', false)) {
135
+            $userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
136
+            if(!is_null($userId)) {
137
+                $userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
138
+            } else {
139
+                $userLang = null;
140
+            }
141
+        } else {
142
+            $userId = null;
143
+            $userLang = null;
144
+        }
145
+
146
+        if ($userLang) {
147
+            $this->requestLanguage = $userLang;
148
+            if ($this->languageExists($app, $userLang)) {
149
+                return $userLang;
150
+            }
151
+        }
152
+
153
+        try {
154
+            // Try to get the language from the Request
155
+            $lang = $this->getLanguageFromRequest($app);
156
+            if ($userId !== null && $app === null && !$userLang) {
157
+                $this->config->setUserValue($userId, 'core', 'lang', $lang);
158
+            }
159
+            return $lang;
160
+        } catch (LanguageNotFoundException $e) {
161
+            // Finding language from request failed fall back to default language
162
+            $defaultLanguage = $this->config->getSystemValue('default_language', false);
163
+            if ($defaultLanguage !== false && $this->languageExists($app, $defaultLanguage)) {
164
+                return $defaultLanguage;
165
+            }
166
+        }
167
+
168
+        // We could not find any language so fall back to english
169
+        return 'en';
170
+    }
171
+
172
+    /**
173
+     * Find all available languages for an app
174
+     *
175
+     * @param string|null $app App id or null for core
176
+     * @return array an array of available languages
177
+     */
178
+    public function findAvailableLanguages($app = null) {
179
+        $key = $app;
180
+        if ($key === null) {
181
+            $key = 'null';
182
+        }
183
+
184
+        // also works with null as key
185
+        if (!empty($this->availableLanguages[$key])) {
186
+            return $this->availableLanguages[$key];
187
+        }
188
+
189
+        $available = ['en']; //english is always available
190
+        $dir = $this->findL10nDir($app);
191
+        if (is_dir($dir)) {
192
+            $files = scandir($dir);
193
+            if ($files !== false) {
194
+                foreach ($files as $file) {
195
+                    if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
196
+                        $available[] = substr($file, 0, -5);
197
+                    }
198
+                }
199
+            }
200
+        }
201
+
202
+        // merge with translations from theme
203
+        $theme = $this->config->getSystemValue('theme');
204
+        if (!empty($theme)) {
205
+            $themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
206
+
207
+            if (is_dir($themeDir)) {
208
+                $files = scandir($themeDir);
209
+                if ($files !== false) {
210
+                    foreach ($files as $file) {
211
+                        if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
212
+                            $available[] = substr($file, 0, -5);
213
+                        }
214
+                    }
215
+                }
216
+            }
217
+        }
218
+
219
+        $this->availableLanguages[$key] = $available;
220
+        return $available;
221
+    }
222
+
223
+    /**
224
+     * @param string|null $app App id or null for core
225
+     * @param string $lang
226
+     * @return bool
227
+     */
228
+    public function languageExists($app, $lang) {
229
+        if ($lang === 'en') {//english is always available
230
+            return true;
231
+        }
232
+
233
+        $languages = $this->findAvailableLanguages($app);
234
+        return array_search($lang, $languages) !== false;
235
+    }
236
+
237
+    /**
238
+     * @param string|null $app
239
+     * @return string
240
+     * @throws LanguageNotFoundException
241
+     */
242
+    private function getLanguageFromRequest($app) {
243
+        $header = $this->request->getHeader('ACCEPT_LANGUAGE');
244
+        if ($header) {
245
+            $available = $this->findAvailableLanguages($app);
246
+
247
+            // E.g. make sure that 'de' is before 'de_DE'.
248
+            sort($available);
249
+
250
+            $preferences = preg_split('/,\s*/', strtolower($header));
251
+            foreach ($preferences as $preference) {
252
+                list($preferred_language) = explode(';', $preference);
253
+                $preferred_language = str_replace('-', '_', $preferred_language);
254
+
255
+                foreach ($available as $available_language) {
256
+                    if ($preferred_language === strtolower($available_language)) {
257
+                        return $available_language;
258
+                    }
259
+                }
260
+
261
+                // Fallback from de_De to de
262
+                foreach ($available as $available_language) {
263
+                    if (substr($preferred_language, 0, 2) === $available_language) {
264
+                        return $available_language;
265
+                    }
266
+                }
267
+            }
268
+        }
269
+
270
+        throw new LanguageNotFoundException();
271
+    }
272
+
273
+    /**
274
+     * @param string|null $app App id or null for core
275
+     * @return string
276
+     */
277
+    public function setLanguageFromRequest($app = null) {
278
+
279
+        try {
280
+            $requestLanguage = $this->getLanguageFromRequest($app);
281
+        } catch (LanguageNotFoundException $e) {
282
+            $requestLanguage = 'en';
283
+        }
284
+
285
+        if ($app === null && !$this->requestLanguage) {
286
+            $this->requestLanguage = $requestLanguage;
287
+        }
288
+        return $requestLanguage;
289
+    }
290
+
291
+    /**
292
+     * Checks if $sub is a subdirectory of $parent
293
+     *
294
+     * @param string $sub
295
+     * @param string $parent
296
+     * @return bool
297
+     */
298
+    private function isSubDirectory($sub, $parent) {
299
+        // Check whether $sub contains no ".."
300
+        if(strpos($sub, '..') !== false) {
301
+            return false;
302
+        }
303
+
304
+        // Check whether $sub is a subdirectory of $parent
305
+        if (strpos($sub, $parent) === 0) {
306
+            return true;
307
+        }
308
+
309
+        return false;
310
+    }
311
+
312
+    /**
313
+     * Get a list of language files that should be loaded
314
+     *
315
+     * @param string $app
316
+     * @param string $lang
317
+     * @return string[]
318
+     */
319
+    // FIXME This method is only public, until OC_L10N does not need it anymore,
320
+    // FIXME This is also the reason, why it is not in the public interface
321
+    public function getL10nFilesForApp($app, $lang) {
322
+        $languageFiles = [];
323
+
324
+        $i18nDir = $this->findL10nDir($app);
325
+        $transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
326
+
327
+        if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
328
+                || $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
329
+                || $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
330
+                || $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
331
+            )
332
+            && file_exists($transFile)) {
333
+            // load the translations file
334
+            $languageFiles[] = $transFile;
335
+        }
336
+
337
+        // merge with translations from theme
338
+        $theme = $this->config->getSystemValue('theme');
339
+        if (!empty($theme)) {
340
+            $transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
341
+            if (file_exists($transFile)) {
342
+                $languageFiles[] = $transFile;
343
+            }
344
+        }
345
+
346
+        return $languageFiles;
347
+    }
348
+
349
+    /**
350
+     * find the l10n directory
351
+     *
352
+     * @param string $app App id or empty string for core
353
+     * @return string directory
354
+     */
355
+    protected function findL10nDir($app = null) {
356
+        if (in_array($app, ['core', 'lib', 'settings'])) {
357
+            if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
358
+                return $this->serverRoot . '/' . $app . '/l10n/';
359
+            }
360
+        } else if ($app && \OC_App::getAppPath($app) !== false) {
361
+            // Check if the app is in the app folder
362
+            return \OC_App::getAppPath($app) . '/l10n/';
363
+        }
364
+        return $this->serverRoot . '/core/l10n/';
365
+    }
366
+
367
+
368
+    /**
369
+     * Creates a function from the plural string
370
+     *
371
+     * Parts of the code is copied from Habari:
372
+     * https://github.com/habari/system/blob/master/classes/locale.php
373
+     * @param string $string
374
+     * @return string
375
+     */
376
+    public function createPluralFunction($string) {
377
+        if (isset($this->pluralFunctions[$string])) {
378
+            return $this->pluralFunctions[$string];
379
+        }
380
+
381
+        if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
382
+            // sanitize
383
+            $nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
384
+            $plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
385
+
386
+            $body = str_replace(
387
+                array( 'plural', 'n', '$n$plurals', ),
388
+                array( '$plural', '$n', '$nplurals', ),
389
+                'nplurals='. $nplurals . '; plural=' . $plural
390
+            );
391
+
392
+            // add parents
393
+            // important since PHP's ternary evaluates from left to right
394
+            $body .= ';';
395
+            $res = '';
396
+            $p = 0;
397
+            for($i = 0; $i < strlen($body); $i++) {
398
+                $ch = $body[$i];
399
+                switch ( $ch ) {
400
+                    case '?':
401
+                        $res .= ' ? (';
402
+                        $p++;
403
+                        break;
404
+                    case ':':
405
+                        $res .= ') : (';
406
+                        break;
407
+                    case ';':
408
+                        $res .= str_repeat( ')', $p ) . ';';
409
+                        $p = 0;
410
+                        break;
411
+                    default:
412
+                        $res .= $ch;
413
+                }
414
+            }
415
+
416
+            $body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
417
+            $function = create_function('$n', $body);
418
+            $this->pluralFunctions[$string] = $function;
419
+            return $function;
420
+        } else {
421
+            // default: one plural form for all cases but n==1 (english)
422
+            $function = create_function(
423
+                '$n',
424
+                '$nplurals=2;$plural=($n==1?0:1);return ($plural>=$nplurals?$nplurals-1:$plural);'
425
+            );
426
+            $this->pluralFunctions[$string] = $function;
427
+            return $function;
428
+        }
429
+    }
430 430
 }
Please login to merge, or discard this patch.
Spacing   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -131,9 +131,9 @@  discard block
 block discarded – undo
131 131
 		 *
132 132
 		 * @link https://github.com/owncloud/core/issues/21955
133 133
 		 */
134
-		if($this->config->getSystemValue('installed', false)) {
135
-			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
136
-			if(!is_null($userId)) {
134
+		if ($this->config->getSystemValue('installed', false)) {
135
+			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() : null;
136
+			if (!is_null($userId)) {
137 137
 				$userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
138 138
 			} else {
139 139
 				$userLang = null;
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
 		// merge with translations from theme
203 203
 		$theme = $this->config->getSystemValue('theme');
204 204
 		if (!empty($theme)) {
205
-			$themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
205
+			$themeDir = $this->serverRoot.'/themes/'.$theme.substr($dir, strlen($this->serverRoot));
206 206
 
207 207
 			if (is_dir($themeDir)) {
208 208
 				$files = scandir($themeDir);
@@ -297,7 +297,7 @@  discard block
 block discarded – undo
297 297
 	 */
298 298
 	private function isSubDirectory($sub, $parent) {
299 299
 		// Check whether $sub contains no ".."
300
-		if(strpos($sub, '..') !== false) {
300
+		if (strpos($sub, '..') !== false) {
301 301
 			return false;
302 302
 		}
303 303
 
@@ -322,12 +322,12 @@  discard block
 block discarded – undo
322 322
 		$languageFiles = [];
323 323
 
324 324
 		$i18nDir = $this->findL10nDir($app);
325
-		$transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
325
+		$transFile = strip_tags($i18nDir).strip_tags($lang).'.json';
326 326
 
327
-		if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
328
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
329
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
330
-				|| $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
327
+		if (($this->isSubDirectory($transFile, $this->serverRoot.'/core/l10n/')
328
+				|| $this->isSubDirectory($transFile, $this->serverRoot.'/lib/l10n/')
329
+				|| $this->isSubDirectory($transFile, $this->serverRoot.'/settings/l10n/')
330
+				|| $this->isSubDirectory($transFile, \OC_App::getAppPath($app).'/l10n/')
331 331
 			)
332 332
 			&& file_exists($transFile)) {
333 333
 			// load the translations file
@@ -337,7 +337,7 @@  discard block
 block discarded – undo
337 337
 		// merge with translations from theme
338 338
 		$theme = $this->config->getSystemValue('theme');
339 339
 		if (!empty($theme)) {
340
-			$transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
340
+			$transFile = $this->serverRoot.'/themes/'.$theme.substr($transFile, strlen($this->serverRoot));
341 341
 			if (file_exists($transFile)) {
342 342
 				$languageFiles[] = $transFile;
343 343
 			}
@@ -354,14 +354,14 @@  discard block
 block discarded – undo
354 354
 	 */
355 355
 	protected function findL10nDir($app = null) {
356 356
 		if (in_array($app, ['core', 'lib', 'settings'])) {
357
-			if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
358
-				return $this->serverRoot . '/' . $app . '/l10n/';
357
+			if (file_exists($this->serverRoot.'/'.$app.'/l10n/')) {
358
+				return $this->serverRoot.'/'.$app.'/l10n/';
359 359
 			}
360 360
 		} else if ($app && \OC_App::getAppPath($app) !== false) {
361 361
 			// Check if the app is in the app folder
362
-			return \OC_App::getAppPath($app) . '/l10n/';
362
+			return \OC_App::getAppPath($app).'/l10n/';
363 363
 		}
364
-		return $this->serverRoot . '/core/l10n/';
364
+		return $this->serverRoot.'/core/l10n/';
365 365
 	}
366 366
 
367 367
 
@@ -378,15 +378,15 @@  discard block
 block discarded – undo
378 378
 			return $this->pluralFunctions[$string];
379 379
 		}
380 380
 
381
-		if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
381
+		if (preg_match('/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
382 382
 			// sanitize
383
-			$nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
384
-			$plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
383
+			$nplurals = preg_replace('/[^0-9]/', '', $matches[1]);
384
+			$plural = preg_replace('#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2]);
385 385
 
386 386
 			$body = str_replace(
387
-				array( 'plural', 'n', '$n$plurals', ),
388
-				array( '$plural', '$n', '$nplurals', ),
389
-				'nplurals='. $nplurals . '; plural=' . $plural
387
+				array('plural', 'n', '$n$plurals',),
388
+				array('$plural', '$n', '$nplurals',),
389
+				'nplurals='.$nplurals.'; plural='.$plural
390 390
 			);
391 391
 
392 392
 			// add parents
@@ -394,9 +394,9 @@  discard block
 block discarded – undo
394 394
 			$body .= ';';
395 395
 			$res = '';
396 396
 			$p = 0;
397
-			for($i = 0; $i < strlen($body); $i++) {
397
+			for ($i = 0; $i < strlen($body); $i++) {
398 398
 				$ch = $body[$i];
399
-				switch ( $ch ) {
399
+				switch ($ch) {
400 400
 					case '?':
401 401
 						$res .= ' ? (';
402 402
 						$p++;
@@ -405,7 +405,7 @@  discard block
 block discarded – undo
405 405
 						$res .= ') : (';
406 406
 						break;
407 407
 					case ';':
408
-						$res .= str_repeat( ')', $p ) . ';';
408
+						$res .= str_repeat(')', $p).';';
409 409
 						$p = 0;
410 410
 						break;
411 411
 					default:
@@ -413,7 +413,7 @@  discard block
 block discarded – undo
413 413
 				}
414 414
 			}
415 415
 
416
-			$body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
416
+			$body = $res.'return ($plural>=$nplurals?$nplurals-1:$plural);';
417 417
 			$function = create_function('$n', $body);
418 418
 			$this->pluralFunctions[$string] = $function;
419 419
 			return $function;
Please login to merge, or discard this patch.
lib/private/Installer.php 4 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -45,7 +45,6 @@
 block discarded – undo
45 45
 use OC\App\CodeChecker\CodeChecker;
46 46
 use OC\App\CodeChecker\EmptyCheck;
47 47
 use OC\App\CodeChecker\PrivateCheck;
48
-use OC\Archive\Archive;
49 48
 use OC\Archive\TAR;
50 49
 use OC_App;
51 50
 use OC_DB;
Please login to merge, or discard this patch.
Indentation   +489 added lines, -489 removed lines patch added patch discarded remove patch
@@ -60,493 +60,493 @@
 block discarded – undo
60 60
  * This class provides the functionality needed to install, update and remove apps
61 61
  */
62 62
 class Installer {
63
-	/** @var AppFetcher */
64
-	private $appFetcher;
65
-	/** @var IClientService */
66
-	private $clientService;
67
-	/** @var ITempManager */
68
-	private $tempManager;
69
-	/** @var ILogger */
70
-	private $logger;
71
-
72
-	/**
73
-	 * @param AppFetcher $appFetcher
74
-	 * @param IClientService $clientService
75
-	 * @param ITempManager $tempManager
76
-	 * @param ILogger $logger
77
-	 */
78
-	public function __construct(AppFetcher $appFetcher,
79
-								IClientService $clientService,
80
-								ITempManager $tempManager,
81
-								ILogger $logger) {
82
-		$this->appFetcher = $appFetcher;
83
-		$this->clientService = $clientService;
84
-		$this->tempManager = $tempManager;
85
-		$this->logger = $logger;
86
-	}
87
-
88
-	/**
89
-	 * Installs an app that is located in one of the app folders already
90
-	 *
91
-	 * @param string $appId App to install
92
-	 * @throws \Exception
93
-	 * @return integer
94
-	 */
95
-	public function installApp($appId) {
96
-		$app = \OC_App::findAppInDirectories($appId);
97
-		if($app === false) {
98
-			throw new \Exception('App not found in any app directory');
99
-		}
100
-
101
-		$basedir = $app['path'].'/'.$appId;
102
-		$info = OC_App::getAppInfo($basedir.'/appinfo/info.xml', true);
103
-
104
-		//install the database
105
-		if(is_file($basedir.'/appinfo/database.xml')) {
106
-			if (\OC::$server->getAppConfig()->getValue($info['id'], 'installed_version') === null) {
107
-				OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
108
-			} else {
109
-				OC_DB::updateDbFromStructure($basedir.'/appinfo/database.xml');
110
-			}
111
-		}
112
-
113
-		\OC_App::setupBackgroundJobs($info['background-jobs']);
114
-
115
-		//run appinfo/install.php
116
-		if((!isset($data['noinstall']) or $data['noinstall']==false)) {
117
-			self::includeAppScript($basedir . '/appinfo/install.php');
118
-		}
119
-
120
-		$appData = OC_App::getAppInfo($appId);
121
-		OC_App::executeRepairSteps($appId, $appData['repair-steps']['install']);
122
-
123
-		//set the installed version
124
-		\OC::$server->getConfig()->setAppValue($info['id'], 'installed_version', OC_App::getAppVersion($info['id'], false));
125
-		\OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
126
-
127
-		//set remote/public handlers
128
-		foreach($info['remote'] as $name=>$path) {
129
-			\OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
130
-		}
131
-		foreach($info['public'] as $name=>$path) {
132
-			\OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
133
-		}
134
-
135
-		OC_App::setAppTypes($info['id']);
136
-
137
-		return $info['id'];
138
-	}
139
-
140
-	/**
141
-	 * @brief checks whether or not an app is installed
142
-	 * @param string $app app
143
-	 * @returns bool
144
-	 *
145
-	 * Checks whether or not an app is installed, i.e. registered in apps table.
146
-	 */
147
-	public static function isInstalled( $app ) {
148
-		return (\OC::$server->getConfig()->getAppValue($app, "installed_version", null) !== null);
149
-	}
150
-
151
-	/**
152
-	 * Updates the specified app from the appstore
153
-	 *
154
-	 * @param string $appId
155
-	 * @return bool
156
-	 */
157
-	public function updateAppstoreApp($appId) {
158
-		if(self::isUpdateAvailable($appId, $this->appFetcher)) {
159
-			try {
160
-				$this->downloadApp($appId);
161
-			} catch (\Exception $e) {
162
-				$this->logger->error($e->getMessage(), ['app' => 'core']);
163
-				return false;
164
-			}
165
-			return OC_App::updateApp($appId);
166
-		}
167
-
168
-		return false;
169
-	}
170
-
171
-	/**
172
-	 * Downloads an app and puts it into the app directory
173
-	 *
174
-	 * @param string $appId
175
-	 *
176
-	 * @throws \Exception If the installation was not successful
177
-	 */
178
-	public function downloadApp($appId) {
179
-		$appId = strtolower($appId);
180
-
181
-		$apps = $this->appFetcher->get();
182
-		foreach($apps as $app) {
183
-			if($app['id'] === $appId) {
184
-				// Load the certificate
185
-				$certificate = new X509();
186
-				$certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
187
-				$loadedCertificate = $certificate->loadX509($app['certificate']);
188
-
189
-				// Verify if the certificate has been revoked
190
-				$crl = new X509();
191
-				$crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
192
-				$crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
193
-				if($crl->validateSignature() !== true) {
194
-					throw new \Exception('Could not validate CRL signature');
195
-				}
196
-				$csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
197
-				$revoked = $crl->getRevoked($csn);
198
-				if ($revoked !== false) {
199
-					throw new \Exception(
200
-						sprintf(
201
-							'Certificate "%s" has been revoked',
202
-							$csn
203
-						)
204
-					);
205
-				}
206
-
207
-				// Verify if the certificate has been issued by the Nextcloud Code Authority CA
208
-				if($certificate->validateSignature() !== true) {
209
-					throw new \Exception(
210
-						sprintf(
211
-							'App with id %s has a certificate not issued by a trusted Code Signing Authority',
212
-							$appId
213
-						)
214
-					);
215
-				}
216
-
217
-				// Verify if the certificate is issued for the requested app id
218
-				$certInfo = openssl_x509_parse($app['certificate']);
219
-				if(!isset($certInfo['subject']['CN'])) {
220
-					throw new \Exception(
221
-						sprintf(
222
-							'App with id %s has a cert with no CN',
223
-							$appId
224
-						)
225
-					);
226
-				}
227
-				if($certInfo['subject']['CN'] !== $appId) {
228
-					throw new \Exception(
229
-						sprintf(
230
-							'App with id %s has a cert issued to %s',
231
-							$appId,
232
-							$certInfo['subject']['CN']
233
-						)
234
-					);
235
-				}
236
-
237
-				// Download the release
238
-				$tempFile = $this->tempManager->getTemporaryFile('.tar.gz');
239
-				$client = $this->clientService->newClient();
240
-				$client->get($app['releases'][0]['download'], ['save_to' => $tempFile]);
241
-
242
-				// Check if the signature actually matches the downloaded content
243
-				$certificate = openssl_get_publickey($app['certificate']);
244
-				$verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
245
-				openssl_free_key($certificate);
246
-
247
-				if($verified === true) {
248
-					// Seems to match, let's proceed
249
-					$extractDir = $this->tempManager->getTemporaryFolder();
250
-					$archive = new TAR($tempFile);
251
-
252
-					if($archive) {
253
-						$archive->extract($extractDir);
254
-						$allFiles = scandir($extractDir);
255
-						$folders = array_diff($allFiles, ['.', '..']);
256
-						$folders = array_values($folders);
257
-
258
-						if(count($folders) > 1) {
259
-							throw new \Exception(
260
-								sprintf(
261
-									'Extracted app %s has more than 1 folder',
262
-									$appId
263
-								)
264
-							);
265
-						}
266
-
267
-						// Check if appinfo/info.xml has the same app ID as well
268
-						$loadEntities = libxml_disable_entity_loader(false);
269
-						$xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
270
-						libxml_disable_entity_loader($loadEntities);
271
-						if((string)$xml->id !== $appId) {
272
-							throw new \Exception(
273
-								sprintf(
274
-									'App for id %s has a wrong app ID in info.xml: %s',
275
-									$appId,
276
-									(string)$xml->id
277
-								)
278
-							);
279
-						}
280
-
281
-						// Check if the version is lower than before
282
-						$currentVersion = OC_App::getAppVersion($appId);
283
-						$newVersion = (string)$xml->version;
284
-						if(version_compare($currentVersion, $newVersion) === 1) {
285
-							throw new \Exception(
286
-								sprintf(
287
-									'App for id %s has version %s and tried to update to lower version %s',
288
-									$appId,
289
-									$currentVersion,
290
-									$newVersion
291
-								)
292
-							);
293
-						}
294
-
295
-						$baseDir = OC_App::getInstallPath() . '/' . $appId;
296
-						// Remove old app with the ID if existent
297
-						OC_Helper::rmdirr($baseDir);
298
-						// Move to app folder
299
-						if(@mkdir($baseDir)) {
300
-							$extractDir .= '/' . $folders[0];
301
-							OC_Helper::copyr($extractDir, $baseDir);
302
-						}
303
-						OC_Helper::copyr($extractDir, $baseDir);
304
-						OC_Helper::rmdirr($extractDir);
305
-						return;
306
-					} else {
307
-						throw new \Exception(
308
-							sprintf(
309
-								'Could not extract app with ID %s to %s',
310
-								$appId,
311
-								$extractDir
312
-							)
313
-						);
314
-					}
315
-				} else {
316
-					// Signature does not match
317
-					throw new \Exception(
318
-						sprintf(
319
-							'App with id %s has invalid signature',
320
-							$appId
321
-						)
322
-					);
323
-				}
324
-			}
325
-		}
326
-
327
-		throw new \Exception(
328
-			sprintf(
329
-				'Could not download app %s',
330
-				$appId
331
-			)
332
-		);
333
-	}
334
-
335
-	/**
336
-	 * Check if an update for the app is available
337
-	 *
338
-	 * @param string $appId
339
-	 * @param AppFetcher $appFetcher
340
-	 * @return string|false false or the version number of the update
341
-	 */
342
-	public static function isUpdateAvailable($appId,
343
-									  AppFetcher $appFetcher) {
344
-		static $isInstanceReadyForUpdates = null;
345
-
346
-		if ($isInstanceReadyForUpdates === null) {
347
-			$installPath = OC_App::getInstallPath();
348
-			if ($installPath === false || $installPath === null) {
349
-				$isInstanceReadyForUpdates = false;
350
-			} else {
351
-				$isInstanceReadyForUpdates = true;
352
-			}
353
-		}
354
-
355
-		if ($isInstanceReadyForUpdates === false) {
356
-			return false;
357
-		}
358
-
359
-		$apps = $appFetcher->get();
360
-		foreach($apps as $app) {
361
-			if($app['id'] === $appId) {
362
-				$currentVersion = OC_App::getAppVersion($appId);
363
-				$newestVersion = $app['releases'][0]['version'];
364
-				if (version_compare($newestVersion, $currentVersion, '>')) {
365
-					return $newestVersion;
366
-				} else {
367
-					return false;
368
-				}
369
-			}
370
-		}
371
-
372
-		return false;
373
-	}
374
-
375
-	/**
376
-	 * Check if app is already downloaded
377
-	 * @param string $name name of the application to remove
378
-	 * @return boolean
379
-	 *
380
-	 * The function will check if the app is already downloaded in the apps repository
381
-	 */
382
-	public function isDownloaded($name) {
383
-		foreach(\OC::$APPSROOTS as $dir) {
384
-			$dirToTest  = $dir['path'];
385
-			$dirToTest .= '/';
386
-			$dirToTest .= $name;
387
-			$dirToTest .= '/';
388
-
389
-			if (is_dir($dirToTest)) {
390
-				return true;
391
-			}
392
-		}
393
-
394
-		return false;
395
-	}
396
-
397
-	/**
398
-	 * Removes an app
399
-	 * @param string $appId ID of the application to remove
400
-	 * @return boolean
401
-	 *
402
-	 *
403
-	 * This function works as follows
404
-	 *   -# call uninstall repair steps
405
-	 *   -# removing the files
406
-	 *
407
-	 * The function will not delete preferences, tables and the configuration,
408
-	 * this has to be done by the function oc_app_uninstall().
409
-	 */
410
-	public function removeApp($appId) {
411
-		if($this->isDownloaded( $appId )) {
412
-			$appDir = OC_App::getInstallPath() . '/' . $appId;
413
-			OC_Helper::rmdirr($appDir);
414
-			return true;
415
-		}else{
416
-			\OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', \OCP\Util::ERROR);
417
-
418
-			return false;
419
-		}
420
-
421
-	}
422
-
423
-	/**
424
-	 * Installs shipped apps
425
-	 *
426
-	 * This function installs all apps found in the 'apps' directory that should be enabled by default;
427
-	 * @param bool $softErrors When updating we ignore errors and simply log them, better to have a
428
-	 *                         working ownCloud at the end instead of an aborted update.
429
-	 * @return array Array of error messages (appid => Exception)
430
-	 */
431
-	public static function installShippedApps($softErrors = false) {
432
-		$errors = [];
433
-		foreach(\OC::$APPSROOTS as $app_dir) {
434
-			if($dir = opendir( $app_dir['path'] )) {
435
-				while( false !== ( $filename = readdir( $dir ))) {
436
-					if( substr( $filename, 0, 1 ) != '.' and is_dir($app_dir['path']."/$filename") ) {
437
-						if( file_exists( $app_dir['path']."/$filename/appinfo/info.xml" )) {
438
-							if(!Installer::isInstalled($filename)) {
439
-								$info=OC_App::getAppInfo($filename);
440
-								$enabled = isset($info['default_enable']);
441
-								if (($enabled || in_array($filename, \OC::$server->getAppManager()->getAlwaysEnabledApps()))
442
-									  && \OC::$server->getConfig()->getAppValue($filename, 'enabled') !== 'no') {
443
-									if ($softErrors) {
444
-										try {
445
-											Installer::installShippedApp($filename);
446
-										} catch (HintException $e) {
447
-											if ($e->getPrevious() instanceof TableExistsException) {
448
-												$errors[$filename] = $e;
449
-												continue;
450
-											}
451
-											throw $e;
452
-										}
453
-									} else {
454
-										Installer::installShippedApp($filename);
455
-									}
456
-									\OC::$server->getConfig()->setAppValue($filename, 'enabled', 'yes');
457
-								}
458
-							}
459
-						}
460
-					}
461
-				}
462
-				closedir( $dir );
463
-			}
464
-		}
465
-
466
-		return $errors;
467
-	}
468
-
469
-	/**
470
-	 * install an app already placed in the app folder
471
-	 * @param string $app id of the app to install
472
-	 * @return integer
473
-	 */
474
-	public static function installShippedApp($app) {
475
-		//install the database
476
-		$appPath = OC_App::getAppPath($app);
477
-		if(is_file("$appPath/appinfo/database.xml")) {
478
-			try {
479
-				OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
480
-			} catch (TableExistsException $e) {
481
-				throw new HintException(
482
-					'Failed to enable app ' . $app,
483
-					'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer">support channels</a>.',
484
-					0, $e
485
-				);
486
-			}
487
-		}
488
-
489
-		//run appinfo/install.php
490
-		\OC_App::registerAutoloading($app, $appPath);
491
-		self::includeAppScript("$appPath/appinfo/install.php");
492
-
493
-		$info = OC_App::getAppInfo($app);
494
-		if (is_null($info)) {
495
-			return false;
496
-		}
497
-		\OC_App::setupBackgroundJobs($info['background-jobs']);
498
-
499
-		OC_App::executeRepairSteps($app, $info['repair-steps']['install']);
500
-
501
-		$config = \OC::$server->getConfig();
502
-
503
-		$config->setAppValue($app, 'installed_version', OC_App::getAppVersion($app));
504
-		if (array_key_exists('ocsid', $info)) {
505
-			$config->setAppValue($app, 'ocsid', $info['ocsid']);
506
-		}
507
-
508
-		//set remote/public handlers
509
-		foreach($info['remote'] as $name=>$path) {
510
-			$config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
511
-		}
512
-		foreach($info['public'] as $name=>$path) {
513
-			$config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
514
-		}
515
-
516
-		OC_App::setAppTypes($info['id']);
517
-
518
-		if(isset($info['settings']) && is_array($info['settings'])) {
519
-			// requires that autoloading was registered for the app,
520
-			// as happens before running the install.php some lines above
521
-			\OC::$server->getSettingsManager()->setupSettings($info['settings']);
522
-		}
523
-
524
-		return $info['id'];
525
-	}
526
-
527
-	/**
528
-	 * check the code of an app with some static code checks
529
-	 * @param string $folder the folder of the app to check
530
-	 * @return boolean true for app is o.k. and false for app is not o.k.
531
-	 */
532
-	public static function checkCode($folder) {
533
-		// is the code checker enabled?
534
-		if(!\OC::$server->getConfig()->getSystemValue('appcodechecker', false)) {
535
-			return true;
536
-		}
537
-
538
-		$codeChecker = new CodeChecker(new PrivateCheck(new EmptyCheck()));
539
-		$errors = $codeChecker->analyseFolder(basename($folder), $folder);
540
-
541
-		return empty($errors);
542
-	}
543
-
544
-	/**
545
-	 * @param string $script
546
-	 */
547
-	private static function includeAppScript($script) {
548
-		if ( file_exists($script) ){
549
-			include $script;
550
-		}
551
-	}
63
+    /** @var AppFetcher */
64
+    private $appFetcher;
65
+    /** @var IClientService */
66
+    private $clientService;
67
+    /** @var ITempManager */
68
+    private $tempManager;
69
+    /** @var ILogger */
70
+    private $logger;
71
+
72
+    /**
73
+     * @param AppFetcher $appFetcher
74
+     * @param IClientService $clientService
75
+     * @param ITempManager $tempManager
76
+     * @param ILogger $logger
77
+     */
78
+    public function __construct(AppFetcher $appFetcher,
79
+                                IClientService $clientService,
80
+                                ITempManager $tempManager,
81
+                                ILogger $logger) {
82
+        $this->appFetcher = $appFetcher;
83
+        $this->clientService = $clientService;
84
+        $this->tempManager = $tempManager;
85
+        $this->logger = $logger;
86
+    }
87
+
88
+    /**
89
+     * Installs an app that is located in one of the app folders already
90
+     *
91
+     * @param string $appId App to install
92
+     * @throws \Exception
93
+     * @return integer
94
+     */
95
+    public function installApp($appId) {
96
+        $app = \OC_App::findAppInDirectories($appId);
97
+        if($app === false) {
98
+            throw new \Exception('App not found in any app directory');
99
+        }
100
+
101
+        $basedir = $app['path'].'/'.$appId;
102
+        $info = OC_App::getAppInfo($basedir.'/appinfo/info.xml', true);
103
+
104
+        //install the database
105
+        if(is_file($basedir.'/appinfo/database.xml')) {
106
+            if (\OC::$server->getAppConfig()->getValue($info['id'], 'installed_version') === null) {
107
+                OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
108
+            } else {
109
+                OC_DB::updateDbFromStructure($basedir.'/appinfo/database.xml');
110
+            }
111
+        }
112
+
113
+        \OC_App::setupBackgroundJobs($info['background-jobs']);
114
+
115
+        //run appinfo/install.php
116
+        if((!isset($data['noinstall']) or $data['noinstall']==false)) {
117
+            self::includeAppScript($basedir . '/appinfo/install.php');
118
+        }
119
+
120
+        $appData = OC_App::getAppInfo($appId);
121
+        OC_App::executeRepairSteps($appId, $appData['repair-steps']['install']);
122
+
123
+        //set the installed version
124
+        \OC::$server->getConfig()->setAppValue($info['id'], 'installed_version', OC_App::getAppVersion($info['id'], false));
125
+        \OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
126
+
127
+        //set remote/public handlers
128
+        foreach($info['remote'] as $name=>$path) {
129
+            \OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
130
+        }
131
+        foreach($info['public'] as $name=>$path) {
132
+            \OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
133
+        }
134
+
135
+        OC_App::setAppTypes($info['id']);
136
+
137
+        return $info['id'];
138
+    }
139
+
140
+    /**
141
+     * @brief checks whether or not an app is installed
142
+     * @param string $app app
143
+     * @returns bool
144
+     *
145
+     * Checks whether or not an app is installed, i.e. registered in apps table.
146
+     */
147
+    public static function isInstalled( $app ) {
148
+        return (\OC::$server->getConfig()->getAppValue($app, "installed_version", null) !== null);
149
+    }
150
+
151
+    /**
152
+     * Updates the specified app from the appstore
153
+     *
154
+     * @param string $appId
155
+     * @return bool
156
+     */
157
+    public function updateAppstoreApp($appId) {
158
+        if(self::isUpdateAvailable($appId, $this->appFetcher)) {
159
+            try {
160
+                $this->downloadApp($appId);
161
+            } catch (\Exception $e) {
162
+                $this->logger->error($e->getMessage(), ['app' => 'core']);
163
+                return false;
164
+            }
165
+            return OC_App::updateApp($appId);
166
+        }
167
+
168
+        return false;
169
+    }
170
+
171
+    /**
172
+     * Downloads an app and puts it into the app directory
173
+     *
174
+     * @param string $appId
175
+     *
176
+     * @throws \Exception If the installation was not successful
177
+     */
178
+    public function downloadApp($appId) {
179
+        $appId = strtolower($appId);
180
+
181
+        $apps = $this->appFetcher->get();
182
+        foreach($apps as $app) {
183
+            if($app['id'] === $appId) {
184
+                // Load the certificate
185
+                $certificate = new X509();
186
+                $certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
187
+                $loadedCertificate = $certificate->loadX509($app['certificate']);
188
+
189
+                // Verify if the certificate has been revoked
190
+                $crl = new X509();
191
+                $crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
192
+                $crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
193
+                if($crl->validateSignature() !== true) {
194
+                    throw new \Exception('Could not validate CRL signature');
195
+                }
196
+                $csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
197
+                $revoked = $crl->getRevoked($csn);
198
+                if ($revoked !== false) {
199
+                    throw new \Exception(
200
+                        sprintf(
201
+                            'Certificate "%s" has been revoked',
202
+                            $csn
203
+                        )
204
+                    );
205
+                }
206
+
207
+                // Verify if the certificate has been issued by the Nextcloud Code Authority CA
208
+                if($certificate->validateSignature() !== true) {
209
+                    throw new \Exception(
210
+                        sprintf(
211
+                            'App with id %s has a certificate not issued by a trusted Code Signing Authority',
212
+                            $appId
213
+                        )
214
+                    );
215
+                }
216
+
217
+                // Verify if the certificate is issued for the requested app id
218
+                $certInfo = openssl_x509_parse($app['certificate']);
219
+                if(!isset($certInfo['subject']['CN'])) {
220
+                    throw new \Exception(
221
+                        sprintf(
222
+                            'App with id %s has a cert with no CN',
223
+                            $appId
224
+                        )
225
+                    );
226
+                }
227
+                if($certInfo['subject']['CN'] !== $appId) {
228
+                    throw new \Exception(
229
+                        sprintf(
230
+                            'App with id %s has a cert issued to %s',
231
+                            $appId,
232
+                            $certInfo['subject']['CN']
233
+                        )
234
+                    );
235
+                }
236
+
237
+                // Download the release
238
+                $tempFile = $this->tempManager->getTemporaryFile('.tar.gz');
239
+                $client = $this->clientService->newClient();
240
+                $client->get($app['releases'][0]['download'], ['save_to' => $tempFile]);
241
+
242
+                // Check if the signature actually matches the downloaded content
243
+                $certificate = openssl_get_publickey($app['certificate']);
244
+                $verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
245
+                openssl_free_key($certificate);
246
+
247
+                if($verified === true) {
248
+                    // Seems to match, let's proceed
249
+                    $extractDir = $this->tempManager->getTemporaryFolder();
250
+                    $archive = new TAR($tempFile);
251
+
252
+                    if($archive) {
253
+                        $archive->extract($extractDir);
254
+                        $allFiles = scandir($extractDir);
255
+                        $folders = array_diff($allFiles, ['.', '..']);
256
+                        $folders = array_values($folders);
257
+
258
+                        if(count($folders) > 1) {
259
+                            throw new \Exception(
260
+                                sprintf(
261
+                                    'Extracted app %s has more than 1 folder',
262
+                                    $appId
263
+                                )
264
+                            );
265
+                        }
266
+
267
+                        // Check if appinfo/info.xml has the same app ID as well
268
+                        $loadEntities = libxml_disable_entity_loader(false);
269
+                        $xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
270
+                        libxml_disable_entity_loader($loadEntities);
271
+                        if((string)$xml->id !== $appId) {
272
+                            throw new \Exception(
273
+                                sprintf(
274
+                                    'App for id %s has a wrong app ID in info.xml: %s',
275
+                                    $appId,
276
+                                    (string)$xml->id
277
+                                )
278
+                            );
279
+                        }
280
+
281
+                        // Check if the version is lower than before
282
+                        $currentVersion = OC_App::getAppVersion($appId);
283
+                        $newVersion = (string)$xml->version;
284
+                        if(version_compare($currentVersion, $newVersion) === 1) {
285
+                            throw new \Exception(
286
+                                sprintf(
287
+                                    'App for id %s has version %s and tried to update to lower version %s',
288
+                                    $appId,
289
+                                    $currentVersion,
290
+                                    $newVersion
291
+                                )
292
+                            );
293
+                        }
294
+
295
+                        $baseDir = OC_App::getInstallPath() . '/' . $appId;
296
+                        // Remove old app with the ID if existent
297
+                        OC_Helper::rmdirr($baseDir);
298
+                        // Move to app folder
299
+                        if(@mkdir($baseDir)) {
300
+                            $extractDir .= '/' . $folders[0];
301
+                            OC_Helper::copyr($extractDir, $baseDir);
302
+                        }
303
+                        OC_Helper::copyr($extractDir, $baseDir);
304
+                        OC_Helper::rmdirr($extractDir);
305
+                        return;
306
+                    } else {
307
+                        throw new \Exception(
308
+                            sprintf(
309
+                                'Could not extract app with ID %s to %s',
310
+                                $appId,
311
+                                $extractDir
312
+                            )
313
+                        );
314
+                    }
315
+                } else {
316
+                    // Signature does not match
317
+                    throw new \Exception(
318
+                        sprintf(
319
+                            'App with id %s has invalid signature',
320
+                            $appId
321
+                        )
322
+                    );
323
+                }
324
+            }
325
+        }
326
+
327
+        throw new \Exception(
328
+            sprintf(
329
+                'Could not download app %s',
330
+                $appId
331
+            )
332
+        );
333
+    }
334
+
335
+    /**
336
+     * Check if an update for the app is available
337
+     *
338
+     * @param string $appId
339
+     * @param AppFetcher $appFetcher
340
+     * @return string|false false or the version number of the update
341
+     */
342
+    public static function isUpdateAvailable($appId,
343
+                                        AppFetcher $appFetcher) {
344
+        static $isInstanceReadyForUpdates = null;
345
+
346
+        if ($isInstanceReadyForUpdates === null) {
347
+            $installPath = OC_App::getInstallPath();
348
+            if ($installPath === false || $installPath === null) {
349
+                $isInstanceReadyForUpdates = false;
350
+            } else {
351
+                $isInstanceReadyForUpdates = true;
352
+            }
353
+        }
354
+
355
+        if ($isInstanceReadyForUpdates === false) {
356
+            return false;
357
+        }
358
+
359
+        $apps = $appFetcher->get();
360
+        foreach($apps as $app) {
361
+            if($app['id'] === $appId) {
362
+                $currentVersion = OC_App::getAppVersion($appId);
363
+                $newestVersion = $app['releases'][0]['version'];
364
+                if (version_compare($newestVersion, $currentVersion, '>')) {
365
+                    return $newestVersion;
366
+                } else {
367
+                    return false;
368
+                }
369
+            }
370
+        }
371
+
372
+        return false;
373
+    }
374
+
375
+    /**
376
+     * Check if app is already downloaded
377
+     * @param string $name name of the application to remove
378
+     * @return boolean
379
+     *
380
+     * The function will check if the app is already downloaded in the apps repository
381
+     */
382
+    public function isDownloaded($name) {
383
+        foreach(\OC::$APPSROOTS as $dir) {
384
+            $dirToTest  = $dir['path'];
385
+            $dirToTest .= '/';
386
+            $dirToTest .= $name;
387
+            $dirToTest .= '/';
388
+
389
+            if (is_dir($dirToTest)) {
390
+                return true;
391
+            }
392
+        }
393
+
394
+        return false;
395
+    }
396
+
397
+    /**
398
+     * Removes an app
399
+     * @param string $appId ID of the application to remove
400
+     * @return boolean
401
+     *
402
+     *
403
+     * This function works as follows
404
+     *   -# call uninstall repair steps
405
+     *   -# removing the files
406
+     *
407
+     * The function will not delete preferences, tables and the configuration,
408
+     * this has to be done by the function oc_app_uninstall().
409
+     */
410
+    public function removeApp($appId) {
411
+        if($this->isDownloaded( $appId )) {
412
+            $appDir = OC_App::getInstallPath() . '/' . $appId;
413
+            OC_Helper::rmdirr($appDir);
414
+            return true;
415
+        }else{
416
+            \OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', \OCP\Util::ERROR);
417
+
418
+            return false;
419
+        }
420
+
421
+    }
422
+
423
+    /**
424
+     * Installs shipped apps
425
+     *
426
+     * This function installs all apps found in the 'apps' directory that should be enabled by default;
427
+     * @param bool $softErrors When updating we ignore errors and simply log them, better to have a
428
+     *                         working ownCloud at the end instead of an aborted update.
429
+     * @return array Array of error messages (appid => Exception)
430
+     */
431
+    public static function installShippedApps($softErrors = false) {
432
+        $errors = [];
433
+        foreach(\OC::$APPSROOTS as $app_dir) {
434
+            if($dir = opendir( $app_dir['path'] )) {
435
+                while( false !== ( $filename = readdir( $dir ))) {
436
+                    if( substr( $filename, 0, 1 ) != '.' and is_dir($app_dir['path']."/$filename") ) {
437
+                        if( file_exists( $app_dir['path']."/$filename/appinfo/info.xml" )) {
438
+                            if(!Installer::isInstalled($filename)) {
439
+                                $info=OC_App::getAppInfo($filename);
440
+                                $enabled = isset($info['default_enable']);
441
+                                if (($enabled || in_array($filename, \OC::$server->getAppManager()->getAlwaysEnabledApps()))
442
+                                      && \OC::$server->getConfig()->getAppValue($filename, 'enabled') !== 'no') {
443
+                                    if ($softErrors) {
444
+                                        try {
445
+                                            Installer::installShippedApp($filename);
446
+                                        } catch (HintException $e) {
447
+                                            if ($e->getPrevious() instanceof TableExistsException) {
448
+                                                $errors[$filename] = $e;
449
+                                                continue;
450
+                                            }
451
+                                            throw $e;
452
+                                        }
453
+                                    } else {
454
+                                        Installer::installShippedApp($filename);
455
+                                    }
456
+                                    \OC::$server->getConfig()->setAppValue($filename, 'enabled', 'yes');
457
+                                }
458
+                            }
459
+                        }
460
+                    }
461
+                }
462
+                closedir( $dir );
463
+            }
464
+        }
465
+
466
+        return $errors;
467
+    }
468
+
469
+    /**
470
+     * install an app already placed in the app folder
471
+     * @param string $app id of the app to install
472
+     * @return integer
473
+     */
474
+    public static function installShippedApp($app) {
475
+        //install the database
476
+        $appPath = OC_App::getAppPath($app);
477
+        if(is_file("$appPath/appinfo/database.xml")) {
478
+            try {
479
+                OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
480
+            } catch (TableExistsException $e) {
481
+                throw new HintException(
482
+                    'Failed to enable app ' . $app,
483
+                    'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer">support channels</a>.',
484
+                    0, $e
485
+                );
486
+            }
487
+        }
488
+
489
+        //run appinfo/install.php
490
+        \OC_App::registerAutoloading($app, $appPath);
491
+        self::includeAppScript("$appPath/appinfo/install.php");
492
+
493
+        $info = OC_App::getAppInfo($app);
494
+        if (is_null($info)) {
495
+            return false;
496
+        }
497
+        \OC_App::setupBackgroundJobs($info['background-jobs']);
498
+
499
+        OC_App::executeRepairSteps($app, $info['repair-steps']['install']);
500
+
501
+        $config = \OC::$server->getConfig();
502
+
503
+        $config->setAppValue($app, 'installed_version', OC_App::getAppVersion($app));
504
+        if (array_key_exists('ocsid', $info)) {
505
+            $config->setAppValue($app, 'ocsid', $info['ocsid']);
506
+        }
507
+
508
+        //set remote/public handlers
509
+        foreach($info['remote'] as $name=>$path) {
510
+            $config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
511
+        }
512
+        foreach($info['public'] as $name=>$path) {
513
+            $config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
514
+        }
515
+
516
+        OC_App::setAppTypes($info['id']);
517
+
518
+        if(isset($info['settings']) && is_array($info['settings'])) {
519
+            // requires that autoloading was registered for the app,
520
+            // as happens before running the install.php some lines above
521
+            \OC::$server->getSettingsManager()->setupSettings($info['settings']);
522
+        }
523
+
524
+        return $info['id'];
525
+    }
526
+
527
+    /**
528
+     * check the code of an app with some static code checks
529
+     * @param string $folder the folder of the app to check
530
+     * @return boolean true for app is o.k. and false for app is not o.k.
531
+     */
532
+    public static function checkCode($folder) {
533
+        // is the code checker enabled?
534
+        if(!\OC::$server->getConfig()->getSystemValue('appcodechecker', false)) {
535
+            return true;
536
+        }
537
+
538
+        $codeChecker = new CodeChecker(new PrivateCheck(new EmptyCheck()));
539
+        $errors = $codeChecker->analyseFolder(basename($folder), $folder);
540
+
541
+        return empty($errors);
542
+    }
543
+
544
+    /**
545
+     * @param string $script
546
+     */
547
+    private static function includeAppScript($script) {
548
+        if ( file_exists($script) ){
549
+            include $script;
550
+        }
551
+    }
552 552
 }
Please login to merge, or discard this patch.
Spacing   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -94,7 +94,7 @@  discard block
 block discarded – undo
94 94
 	 */
95 95
 	public function installApp($appId) {
96 96
 		$app = \OC_App::findAppInDirectories($appId);
97
-		if($app === false) {
97
+		if ($app === false) {
98 98
 			throw new \Exception('App not found in any app directory');
99 99
 		}
100 100
 
@@ -102,7 +102,7 @@  discard block
 block discarded – undo
102 102
 		$info = OC_App::getAppInfo($basedir.'/appinfo/info.xml', true);
103 103
 
104 104
 		//install the database
105
-		if(is_file($basedir.'/appinfo/database.xml')) {
105
+		if (is_file($basedir.'/appinfo/database.xml')) {
106 106
 			if (\OC::$server->getAppConfig()->getValue($info['id'], 'installed_version') === null) {
107 107
 				OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
108 108
 			} else {
@@ -113,8 +113,8 @@  discard block
 block discarded – undo
113 113
 		\OC_App::setupBackgroundJobs($info['background-jobs']);
114 114
 
115 115
 		//run appinfo/install.php
116
-		if((!isset($data['noinstall']) or $data['noinstall']==false)) {
117
-			self::includeAppScript($basedir . '/appinfo/install.php');
116
+		if ((!isset($data['noinstall']) or $data['noinstall'] == false)) {
117
+			self::includeAppScript($basedir.'/appinfo/install.php');
118 118
 		}
119 119
 
120 120
 		$appData = OC_App::getAppInfo($appId);
@@ -125,10 +125,10 @@  discard block
 block discarded – undo
125 125
 		\OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
126 126
 
127 127
 		//set remote/public handlers
128
-		foreach($info['remote'] as $name=>$path) {
128
+		foreach ($info['remote'] as $name=>$path) {
129 129
 			\OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
130 130
 		}
131
-		foreach($info['public'] as $name=>$path) {
131
+		foreach ($info['public'] as $name=>$path) {
132 132
 			\OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
133 133
 		}
134 134
 
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
 	 *
145 145
 	 * Checks whether or not an app is installed, i.e. registered in apps table.
146 146
 	 */
147
-	public static function isInstalled( $app ) {
147
+	public static function isInstalled($app) {
148 148
 		return (\OC::$server->getConfig()->getAppValue($app, "installed_version", null) !== null);
149 149
 	}
150 150
 
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
 	 * @return bool
156 156
 	 */
157 157
 	public function updateAppstoreApp($appId) {
158
-		if(self::isUpdateAvailable($appId, $this->appFetcher)) {
158
+		if (self::isUpdateAvailable($appId, $this->appFetcher)) {
159 159
 			try {
160 160
 				$this->downloadApp($appId);
161 161
 			} catch (\Exception $e) {
@@ -179,18 +179,18 @@  discard block
 block discarded – undo
179 179
 		$appId = strtolower($appId);
180 180
 
181 181
 		$apps = $this->appFetcher->get();
182
-		foreach($apps as $app) {
183
-			if($app['id'] === $appId) {
182
+		foreach ($apps as $app) {
183
+			if ($app['id'] === $appId) {
184 184
 				// Load the certificate
185 185
 				$certificate = new X509();
186
-				$certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
186
+				$certificate->loadCA(file_get_contents(__DIR__.'/../../resources/codesigning/root.crt'));
187 187
 				$loadedCertificate = $certificate->loadX509($app['certificate']);
188 188
 
189 189
 				// Verify if the certificate has been revoked
190 190
 				$crl = new X509();
191
-				$crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
192
-				$crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
193
-				if($crl->validateSignature() !== true) {
191
+				$crl->loadCA(file_get_contents(__DIR__.'/../../resources/codesigning/root.crt'));
192
+				$crl->loadCRL(file_get_contents(__DIR__.'/../../resources/codesigning/root.crl'));
193
+				if ($crl->validateSignature() !== true) {
194 194
 					throw new \Exception('Could not validate CRL signature');
195 195
 				}
196 196
 				$csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
@@ -205,7 +205,7 @@  discard block
 block discarded – undo
205 205
 				}
206 206
 
207 207
 				// Verify if the certificate has been issued by the Nextcloud Code Authority CA
208
-				if($certificate->validateSignature() !== true) {
208
+				if ($certificate->validateSignature() !== true) {
209 209
 					throw new \Exception(
210 210
 						sprintf(
211 211
 							'App with id %s has a certificate not issued by a trusted Code Signing Authority',
@@ -216,7 +216,7 @@  discard block
 block discarded – undo
216 216
 
217 217
 				// Verify if the certificate is issued for the requested app id
218 218
 				$certInfo = openssl_x509_parse($app['certificate']);
219
-				if(!isset($certInfo['subject']['CN'])) {
219
+				if (!isset($certInfo['subject']['CN'])) {
220 220
 					throw new \Exception(
221 221
 						sprintf(
222 222
 							'App with id %s has a cert with no CN',
@@ -224,7 +224,7 @@  discard block
 block discarded – undo
224 224
 						)
225 225
 					);
226 226
 				}
227
-				if($certInfo['subject']['CN'] !== $appId) {
227
+				if ($certInfo['subject']['CN'] !== $appId) {
228 228
 					throw new \Exception(
229 229
 						sprintf(
230 230
 							'App with id %s has a cert issued to %s',
@@ -241,21 +241,21 @@  discard block
 block discarded – undo
241 241
 
242 242
 				// Check if the signature actually matches the downloaded content
243 243
 				$certificate = openssl_get_publickey($app['certificate']);
244
-				$verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
244
+				$verified = (bool) openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
245 245
 				openssl_free_key($certificate);
246 246
 
247
-				if($verified === true) {
247
+				if ($verified === true) {
248 248
 					// Seems to match, let's proceed
249 249
 					$extractDir = $this->tempManager->getTemporaryFolder();
250 250
 					$archive = new TAR($tempFile);
251 251
 
252
-					if($archive) {
252
+					if ($archive) {
253 253
 						$archive->extract($extractDir);
254 254
 						$allFiles = scandir($extractDir);
255 255
 						$folders = array_diff($allFiles, ['.', '..']);
256 256
 						$folders = array_values($folders);
257 257
 
258
-						if(count($folders) > 1) {
258
+						if (count($folders) > 1) {
259 259
 							throw new \Exception(
260 260
 								sprintf(
261 261
 									'Extracted app %s has more than 1 folder',
@@ -266,22 +266,22 @@  discard block
 block discarded – undo
266 266
 
267 267
 						// Check if appinfo/info.xml has the same app ID as well
268 268
 						$loadEntities = libxml_disable_entity_loader(false);
269
-						$xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
269
+						$xml = simplexml_load_file($extractDir.'/'.$folders[0].'/appinfo/info.xml');
270 270
 						libxml_disable_entity_loader($loadEntities);
271
-						if((string)$xml->id !== $appId) {
271
+						if ((string) $xml->id !== $appId) {
272 272
 							throw new \Exception(
273 273
 								sprintf(
274 274
 									'App for id %s has a wrong app ID in info.xml: %s',
275 275
 									$appId,
276
-									(string)$xml->id
276
+									(string) $xml->id
277 277
 								)
278 278
 							);
279 279
 						}
280 280
 
281 281
 						// Check if the version is lower than before
282 282
 						$currentVersion = OC_App::getAppVersion($appId);
283
-						$newVersion = (string)$xml->version;
284
-						if(version_compare($currentVersion, $newVersion) === 1) {
283
+						$newVersion = (string) $xml->version;
284
+						if (version_compare($currentVersion, $newVersion) === 1) {
285 285
 							throw new \Exception(
286 286
 								sprintf(
287 287
 									'App for id %s has version %s and tried to update to lower version %s',
@@ -292,12 +292,12 @@  discard block
 block discarded – undo
292 292
 							);
293 293
 						}
294 294
 
295
-						$baseDir = OC_App::getInstallPath() . '/' . $appId;
295
+						$baseDir = OC_App::getInstallPath().'/'.$appId;
296 296
 						// Remove old app with the ID if existent
297 297
 						OC_Helper::rmdirr($baseDir);
298 298
 						// Move to app folder
299
-						if(@mkdir($baseDir)) {
300
-							$extractDir .= '/' . $folders[0];
299
+						if (@mkdir($baseDir)) {
300
+							$extractDir .= '/'.$folders[0];
301 301
 							OC_Helper::copyr($extractDir, $baseDir);
302 302
 						}
303 303
 						OC_Helper::copyr($extractDir, $baseDir);
@@ -357,8 +357,8 @@  discard block
 block discarded – undo
357 357
 		}
358 358
 
359 359
 		$apps = $appFetcher->get();
360
-		foreach($apps as $app) {
361
-			if($app['id'] === $appId) {
360
+		foreach ($apps as $app) {
361
+			if ($app['id'] === $appId) {
362 362
 				$currentVersion = OC_App::getAppVersion($appId);
363 363
 				$newestVersion = $app['releases'][0]['version'];
364 364
 				if (version_compare($newestVersion, $currentVersion, '>')) {
@@ -380,7 +380,7 @@  discard block
 block discarded – undo
380 380
 	 * The function will check if the app is already downloaded in the apps repository
381 381
 	 */
382 382
 	public function isDownloaded($name) {
383
-		foreach(\OC::$APPSROOTS as $dir) {
383
+		foreach (\OC::$APPSROOTS as $dir) {
384 384
 			$dirToTest  = $dir['path'];
385 385
 			$dirToTest .= '/';
386 386
 			$dirToTest .= $name;
@@ -408,11 +408,11 @@  discard block
 block discarded – undo
408 408
 	 * this has to be done by the function oc_app_uninstall().
409 409
 	 */
410 410
 	public function removeApp($appId) {
411
-		if($this->isDownloaded( $appId )) {
412
-			$appDir = OC_App::getInstallPath() . '/' . $appId;
411
+		if ($this->isDownloaded($appId)) {
412
+			$appDir = OC_App::getInstallPath().'/'.$appId;
413 413
 			OC_Helper::rmdirr($appDir);
414 414
 			return true;
415
-		}else{
415
+		} else {
416 416
 			\OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', \OCP\Util::ERROR);
417 417
 
418 418
 			return false;
@@ -430,13 +430,13 @@  discard block
 block discarded – undo
430 430
 	 */
431 431
 	public static function installShippedApps($softErrors = false) {
432 432
 		$errors = [];
433
-		foreach(\OC::$APPSROOTS as $app_dir) {
434
-			if($dir = opendir( $app_dir['path'] )) {
435
-				while( false !== ( $filename = readdir( $dir ))) {
436
-					if( substr( $filename, 0, 1 ) != '.' and is_dir($app_dir['path']."/$filename") ) {
437
-						if( file_exists( $app_dir['path']."/$filename/appinfo/info.xml" )) {
438
-							if(!Installer::isInstalled($filename)) {
439
-								$info=OC_App::getAppInfo($filename);
433
+		foreach (\OC::$APPSROOTS as $app_dir) {
434
+			if ($dir = opendir($app_dir['path'])) {
435
+				while (false !== ($filename = readdir($dir))) {
436
+					if (substr($filename, 0, 1) != '.' and is_dir($app_dir['path']."/$filename")) {
437
+						if (file_exists($app_dir['path']."/$filename/appinfo/info.xml")) {
438
+							if (!Installer::isInstalled($filename)) {
439
+								$info = OC_App::getAppInfo($filename);
440 440
 								$enabled = isset($info['default_enable']);
441 441
 								if (($enabled || in_array($filename, \OC::$server->getAppManager()->getAlwaysEnabledApps()))
442 442
 									  && \OC::$server->getConfig()->getAppValue($filename, 'enabled') !== 'no') {
@@ -459,7 +459,7 @@  discard block
 block discarded – undo
459 459
 						}
460 460
 					}
461 461
 				}
462
-				closedir( $dir );
462
+				closedir($dir);
463 463
 			}
464 464
 		}
465 465
 
@@ -474,12 +474,12 @@  discard block
 block discarded – undo
474 474
 	public static function installShippedApp($app) {
475 475
 		//install the database
476 476
 		$appPath = OC_App::getAppPath($app);
477
-		if(is_file("$appPath/appinfo/database.xml")) {
477
+		if (is_file("$appPath/appinfo/database.xml")) {
478 478
 			try {
479 479
 				OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
480 480
 			} catch (TableExistsException $e) {
481 481
 				throw new HintException(
482
-					'Failed to enable app ' . $app,
482
+					'Failed to enable app '.$app,
483 483
 					'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer">support channels</a>.',
484 484
 					0, $e
485 485
 				);
@@ -506,16 +506,16 @@  discard block
 block discarded – undo
506 506
 		}
507 507
 
508 508
 		//set remote/public handlers
509
-		foreach($info['remote'] as $name=>$path) {
509
+		foreach ($info['remote'] as $name=>$path) {
510 510
 			$config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
511 511
 		}
512
-		foreach($info['public'] as $name=>$path) {
512
+		foreach ($info['public'] as $name=>$path) {
513 513
 			$config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
514 514
 		}
515 515
 
516 516
 		OC_App::setAppTypes($info['id']);
517 517
 
518
-		if(isset($info['settings']) && is_array($info['settings'])) {
518
+		if (isset($info['settings']) && is_array($info['settings'])) {
519 519
 			// requires that autoloading was registered for the app,
520 520
 			// as happens before running the install.php some lines above
521 521
 			\OC::$server->getSettingsManager()->setupSettings($info['settings']);
@@ -531,7 +531,7 @@  discard block
 block discarded – undo
531 531
 	 */
532 532
 	public static function checkCode($folder) {
533 533
 		// is the code checker enabled?
534
-		if(!\OC::$server->getConfig()->getSystemValue('appcodechecker', false)) {
534
+		if (!\OC::$server->getConfig()->getSystemValue('appcodechecker', false)) {
535 535
 			return true;
536 536
 		}
537 537
 
@@ -545,7 +545,7 @@  discard block
 block discarded – undo
545 545
 	 * @param string $script
546 546
 	 */
547 547
 	private static function includeAppScript($script) {
548
-		if ( file_exists($script) ){
548
+		if (file_exists($script)) {
549 549
 			include $script;
550 550
 		}
551 551
 	}
Please login to merge, or discard this patch.
Braces   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -412,7 +412,7 @@
 block discarded – undo
412 412
 			$appDir = OC_App::getInstallPath() . '/' . $appId;
413 413
 			OC_Helper::rmdirr($appDir);
414 414
 			return true;
415
-		}else{
415
+		} else{
416 416
 			\OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', \OCP\Util::ERROR);
417 417
 
418 418
 			return false;
Please login to merge, or discard this patch.
apps/dav/lib/HookManager.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -28,7 +28,6 @@
 block discarded – undo
28 28
 use OCP\IUserManager;
29 29
 use OCP\Util;
30 30
 use Symfony\Component\EventDispatcher\EventDispatcher;
31
-use Symfony\Component\EventDispatcher\GenericEvent;
32 31
 
33 32
 class HookManager {
34 33
 
Please login to merge, or discard this patch.
Indentation   +111 added lines, -111 removed lines patch added patch discarded remove patch
@@ -32,115 +32,115 @@
 block discarded – undo
32 32
 
33 33
 class HookManager {
34 34
 
35
-	/** @var IUserManager */
36
-	private $userManager;
37
-
38
-	/** @var SyncService */
39
-	private $syncService;
40
-
41
-	/** @var IUser[] */
42
-	private $usersToDelete;
43
-
44
-	/** @var CalDavBackend */
45
-	private $calDav;
46
-
47
-	/** @var CardDavBackend */
48
-	private $cardDav;
49
-
50
-	/** @var array */
51
-	private $calendarsToDelete;
52
-
53
-	/** @var array */
54
-	private $addressBooksToDelete;
55
-
56
-	/** @var EventDispatcher */
57
-	private $eventDispatcher;
58
-
59
-	public function __construct(IUserManager $userManager,
60
-								SyncService $syncService,
61
-								CalDavBackend $calDav,
62
-								CardDavBackend $cardDav,
63
-								EventDispatcher $eventDispatcher) {
64
-		$this->userManager = $userManager;
65
-		$this->syncService = $syncService;
66
-		$this->calDav = $calDav;
67
-		$this->cardDav = $cardDav;
68
-		$this->eventDispatcher = $eventDispatcher;
69
-	}
70
-
71
-	public function setup() {
72
-		Util::connectHook('OC_User',
73
-			'post_createUser',
74
-			$this,
75
-			'postCreateUser');
76
-		Util::connectHook('OC_User',
77
-			'pre_deleteUser',
78
-			$this,
79
-			'preDeleteUser');
80
-		Util::connectHook('OC_User',
81
-			'post_deleteUser',
82
-			$this,
83
-			'postDeleteUser');
84
-		Util::connectHook('OC_User',
85
-			'changeUser',
86
-			$this,
87
-			'changeUser');
88
-	}
89
-
90
-	public function postCreateUser($params) {
91
-		$user = $this->userManager->get($params['uid']);
92
-		$this->syncService->updateUser($user);
93
-	}
94
-
95
-	public function preDeleteUser($params) {
96
-		$uid = $params['uid'];
97
-		$this->usersToDelete[$uid] = $this->userManager->get($uid);
98
-		$this->calendarsToDelete = $this->calDav->getUsersOwnCalendars('principals/users/' . $uid);
99
-		$this->addressBooksToDelete = $this->cardDav->getUsersOwnAddressBooks('principals/users/' . $uid);
100
-	}
101
-
102
-	public function postDeleteUser($params) {
103
-		$uid = $params['uid'];
104
-		if (isset($this->usersToDelete[$uid])){
105
-			$this->syncService->deleteUser($this->usersToDelete[$uid]);
106
-		}
107
-
108
-		foreach ($this->calendarsToDelete as $calendar) {
109
-			$this->calDav->deleteCalendar($calendar['id']);
110
-		}
111
-		$this->calDav->deleteAllSharesByUser('principals/users/' . $uid);
112
-
113
-		foreach ($this->addressBooksToDelete as $addressBook) {
114
-			$this->cardDav->deleteAddressBook($addressBook['id']);
115
-		}
116
-	}
117
-
118
-	public function changeUser($params) {
119
-		$user = $params['user'];
120
-		$this->syncService->updateUser($user);
121
-	}
122
-
123
-	public function firstLogin(IUser $user = null) {
124
-		if (!is_null($user)) {
125
-			$principal = 'principals/users/' . $user->getUID();
126
-			if ($this->calDav->getCalendarsForUserCount($principal) === 0) {
127
-				try {
128
-					$this->calDav->createCalendar($principal, CalDavBackend::PERSONAL_CALENDAR_URI, [
129
-						'{DAV:}displayname' => CalDavBackend::PERSONAL_CALENDAR_NAME,
130
-					]);
131
-				} catch (\Exception $ex) {
132
-					\OC::$server->getLogger()->logException($ex);
133
-				}
134
-			}
135
-			if ($this->cardDav->getAddressBooksForUserCount($principal) === 0) {
136
-				try {
137
-					$this->cardDav->createAddressBook($principal, CardDavBackend::PERSONAL_ADDRESSBOOK_URI, [
138
-						'{DAV:}displayname' => CardDavBackend::PERSONAL_ADDRESSBOOK_NAME,
139
-					]);
140
-				} catch (\Exception $ex) {
141
-					\OC::$server->getLogger()->logException($ex);
142
-				}
143
-			}
144
-		}
145
-	}
35
+    /** @var IUserManager */
36
+    private $userManager;
37
+
38
+    /** @var SyncService */
39
+    private $syncService;
40
+
41
+    /** @var IUser[] */
42
+    private $usersToDelete;
43
+
44
+    /** @var CalDavBackend */
45
+    private $calDav;
46
+
47
+    /** @var CardDavBackend */
48
+    private $cardDav;
49
+
50
+    /** @var array */
51
+    private $calendarsToDelete;
52
+
53
+    /** @var array */
54
+    private $addressBooksToDelete;
55
+
56
+    /** @var EventDispatcher */
57
+    private $eventDispatcher;
58
+
59
+    public function __construct(IUserManager $userManager,
60
+                                SyncService $syncService,
61
+                                CalDavBackend $calDav,
62
+                                CardDavBackend $cardDav,
63
+                                EventDispatcher $eventDispatcher) {
64
+        $this->userManager = $userManager;
65
+        $this->syncService = $syncService;
66
+        $this->calDav = $calDav;
67
+        $this->cardDav = $cardDav;
68
+        $this->eventDispatcher = $eventDispatcher;
69
+    }
70
+
71
+    public function setup() {
72
+        Util::connectHook('OC_User',
73
+            'post_createUser',
74
+            $this,
75
+            'postCreateUser');
76
+        Util::connectHook('OC_User',
77
+            'pre_deleteUser',
78
+            $this,
79
+            'preDeleteUser');
80
+        Util::connectHook('OC_User',
81
+            'post_deleteUser',
82
+            $this,
83
+            'postDeleteUser');
84
+        Util::connectHook('OC_User',
85
+            'changeUser',
86
+            $this,
87
+            'changeUser');
88
+    }
89
+
90
+    public function postCreateUser($params) {
91
+        $user = $this->userManager->get($params['uid']);
92
+        $this->syncService->updateUser($user);
93
+    }
94
+
95
+    public function preDeleteUser($params) {
96
+        $uid = $params['uid'];
97
+        $this->usersToDelete[$uid] = $this->userManager->get($uid);
98
+        $this->calendarsToDelete = $this->calDav->getUsersOwnCalendars('principals/users/' . $uid);
99
+        $this->addressBooksToDelete = $this->cardDav->getUsersOwnAddressBooks('principals/users/' . $uid);
100
+    }
101
+
102
+    public function postDeleteUser($params) {
103
+        $uid = $params['uid'];
104
+        if (isset($this->usersToDelete[$uid])){
105
+            $this->syncService->deleteUser($this->usersToDelete[$uid]);
106
+        }
107
+
108
+        foreach ($this->calendarsToDelete as $calendar) {
109
+            $this->calDav->deleteCalendar($calendar['id']);
110
+        }
111
+        $this->calDav->deleteAllSharesByUser('principals/users/' . $uid);
112
+
113
+        foreach ($this->addressBooksToDelete as $addressBook) {
114
+            $this->cardDav->deleteAddressBook($addressBook['id']);
115
+        }
116
+    }
117
+
118
+    public function changeUser($params) {
119
+        $user = $params['user'];
120
+        $this->syncService->updateUser($user);
121
+    }
122
+
123
+    public function firstLogin(IUser $user = null) {
124
+        if (!is_null($user)) {
125
+            $principal = 'principals/users/' . $user->getUID();
126
+            if ($this->calDav->getCalendarsForUserCount($principal) === 0) {
127
+                try {
128
+                    $this->calDav->createCalendar($principal, CalDavBackend::PERSONAL_CALENDAR_URI, [
129
+                        '{DAV:}displayname' => CalDavBackend::PERSONAL_CALENDAR_NAME,
130
+                    ]);
131
+                } catch (\Exception $ex) {
132
+                    \OC::$server->getLogger()->logException($ex);
133
+                }
134
+            }
135
+            if ($this->cardDav->getAddressBooksForUserCount($principal) === 0) {
136
+                try {
137
+                    $this->cardDav->createAddressBook($principal, CardDavBackend::PERSONAL_ADDRESSBOOK_URI, [
138
+                        '{DAV:}displayname' => CardDavBackend::PERSONAL_ADDRESSBOOK_NAME,
139
+                    ]);
140
+                } catch (\Exception $ex) {
141
+                    \OC::$server->getLogger()->logException($ex);
142
+                }
143
+            }
144
+        }
145
+    }
146 146
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -95,20 +95,20 @@  discard block
 block discarded – undo
95 95
 	public function preDeleteUser($params) {
96 96
 		$uid = $params['uid'];
97 97
 		$this->usersToDelete[$uid] = $this->userManager->get($uid);
98
-		$this->calendarsToDelete = $this->calDav->getUsersOwnCalendars('principals/users/' . $uid);
99
-		$this->addressBooksToDelete = $this->cardDav->getUsersOwnAddressBooks('principals/users/' . $uid);
98
+		$this->calendarsToDelete = $this->calDav->getUsersOwnCalendars('principals/users/'.$uid);
99
+		$this->addressBooksToDelete = $this->cardDav->getUsersOwnAddressBooks('principals/users/'.$uid);
100 100
 	}
101 101
 
102 102
 	public function postDeleteUser($params) {
103 103
 		$uid = $params['uid'];
104
-		if (isset($this->usersToDelete[$uid])){
104
+		if (isset($this->usersToDelete[$uid])) {
105 105
 			$this->syncService->deleteUser($this->usersToDelete[$uid]);
106 106
 		}
107 107
 
108 108
 		foreach ($this->calendarsToDelete as $calendar) {
109 109
 			$this->calDav->deleteCalendar($calendar['id']);
110 110
 		}
111
-		$this->calDav->deleteAllSharesByUser('principals/users/' . $uid);
111
+		$this->calDav->deleteAllSharesByUser('principals/users/'.$uid);
112 112
 
113 113
 		foreach ($this->addressBooksToDelete as $addressBook) {
114 114
 			$this->cardDav->deleteAddressBook($addressBook['id']);
@@ -122,7 +122,7 @@  discard block
 block discarded – undo
122 122
 
123 123
 	public function firstLogin(IUser $user = null) {
124 124
 		if (!is_null($user)) {
125
-			$principal = 'principals/users/' . $user->getUID();
125
+			$principal = 'principals/users/'.$user->getUID();
126 126
 			if ($this->calDav->getCalendarsForUserCount($principal) === 0) {
127 127
 				try {
128 128
 					$this->calDav->createCalendar($principal, CalDavBackend::PERSONAL_CALENDAR_URI, [
Please login to merge, or discard this patch.
apps/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   +102 added lines, -102 removed lines patch added patch discarded remove patch
@@ -37,106 +37,106 @@
 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
-	private $numericId;
55
-
56
-	/**
57
-	 * @param \OCA\Files_Sharing\SharedStorage $storage
58
-	 * @param ICacheEntry $sourceRootInfo
59
-	 */
60
-	public function __construct($storage, ICacheEntry $sourceRootInfo) {
61
-		$this->storage = $storage;
62
-		$this->sourceRootInfo = $sourceRootInfo;
63
-		$this->numericId = $sourceRootInfo->getStorageId();
64
-		parent::__construct(
65
-			null,
66
-			$this->sourceRootInfo->getPath()
67
-		);
68
-	}
69
-
70
-	public function getCache() {
71
-		if (is_null($this->cache)) {
72
-			$this->cache = $this->storage->getSourceStorage()->getCache();
73
-		}
74
-		return $this->cache;
75
-	}
76
-
77
-	public function getNumericStorageId() {
78
-		if (isset($this->numericId)) {
79
-			return $this->numericId;
80
-		} else {
81
-			return false;
82
-		}
83
-	}
84
-
85
-	public function get($file) {
86
-		if ($this->rootUnchanged && ($file === '' || $file === $this->sourceRootInfo->getId())) {
87
-			return $this->formatCacheEntry(clone $this->sourceRootInfo);
88
-		}
89
-		return parent::get($file);
90
-	}
91
-
92
-	public function update($id, array $data) {
93
-		$this->rootUnchanged = false;
94
-		parent::update($id, $data);
95
-	}
96
-
97
-	public function insert($file, array $data) {
98
-		$this->rootUnchanged = false;
99
-		return parent::insert($file, $data);
100
-	}
101
-
102
-	public function remove($file) {
103
-		$this->rootUnchanged = false;
104
-		parent::remove($file);
105
-	}
106
-
107
-	public function moveFromCache(\OCP\Files\Cache\ICache $sourceCache, $sourcePath, $targetPath) {
108
-		$this->rootUnchanged = false;
109
-		return parent::moveFromCache($sourceCache, $sourcePath, $targetPath);
110
-	}
111
-
112
-	protected function formatCacheEntry($entry) {
113
-		$path = isset($entry['path']) ? $entry['path'] : '';
114
-		$entry = parent::formatCacheEntry($entry);
115
-		$sharePermissions = $this->storage->getPermissions($path);
116
-		if (isset($entry['permissions'])) {
117
-			$entry['permissions'] &= $sharePermissions;
118
-		} else {
119
-			$entry['permissions'] = $sharePermissions;
120
-		}
121
-		$entry['uid_owner'] = $this->storage->getOwner($path);
122
-		$entry['displayname_owner'] = $this->getOwnerDisplayName();
123
-		if ($path === '') {
124
-			$entry['is_share_mount_point'] = true;
125
-		}
126
-		return $entry;
127
-	}
128
-
129
-	private function getOwnerDisplayName() {
130
-		if (!$this->ownerDisplayName) {
131
-			$this->ownerDisplayName = \OC_User::getDisplayName($this->storage->getOwner(''));
132
-		}
133
-		return $this->ownerDisplayName;
134
-	}
135
-
136
-	/**
137
-	 * remove all entries for files that are stored on the storage from the cache
138
-	 */
139
-	public function clear() {
140
-		// Not a valid action for Shared Cache
141
-	}
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
+    private $numericId;
55
+
56
+    /**
57
+     * @param \OCA\Files_Sharing\SharedStorage $storage
58
+     * @param ICacheEntry $sourceRootInfo
59
+     */
60
+    public function __construct($storage, ICacheEntry $sourceRootInfo) {
61
+        $this->storage = $storage;
62
+        $this->sourceRootInfo = $sourceRootInfo;
63
+        $this->numericId = $sourceRootInfo->getStorageId();
64
+        parent::__construct(
65
+            null,
66
+            $this->sourceRootInfo->getPath()
67
+        );
68
+    }
69
+
70
+    public function getCache() {
71
+        if (is_null($this->cache)) {
72
+            $this->cache = $this->storage->getSourceStorage()->getCache();
73
+        }
74
+        return $this->cache;
75
+    }
76
+
77
+    public function getNumericStorageId() {
78
+        if (isset($this->numericId)) {
79
+            return $this->numericId;
80
+        } else {
81
+            return false;
82
+        }
83
+    }
84
+
85
+    public function get($file) {
86
+        if ($this->rootUnchanged && ($file === '' || $file === $this->sourceRootInfo->getId())) {
87
+            return $this->formatCacheEntry(clone $this->sourceRootInfo);
88
+        }
89
+        return parent::get($file);
90
+    }
91
+
92
+    public function update($id, array $data) {
93
+        $this->rootUnchanged = false;
94
+        parent::update($id, $data);
95
+    }
96
+
97
+    public function insert($file, array $data) {
98
+        $this->rootUnchanged = false;
99
+        return parent::insert($file, $data);
100
+    }
101
+
102
+    public function remove($file) {
103
+        $this->rootUnchanged = false;
104
+        parent::remove($file);
105
+    }
106
+
107
+    public function moveFromCache(\OCP\Files\Cache\ICache $sourceCache, $sourcePath, $targetPath) {
108
+        $this->rootUnchanged = false;
109
+        return parent::moveFromCache($sourceCache, $sourcePath, $targetPath);
110
+    }
111
+
112
+    protected function formatCacheEntry($entry) {
113
+        $path = isset($entry['path']) ? $entry['path'] : '';
114
+        $entry = parent::formatCacheEntry($entry);
115
+        $sharePermissions = $this->storage->getPermissions($path);
116
+        if (isset($entry['permissions'])) {
117
+            $entry['permissions'] &= $sharePermissions;
118
+        } else {
119
+            $entry['permissions'] = $sharePermissions;
120
+        }
121
+        $entry['uid_owner'] = $this->storage->getOwner($path);
122
+        $entry['displayname_owner'] = $this->getOwnerDisplayName();
123
+        if ($path === '') {
124
+            $entry['is_share_mount_point'] = true;
125
+        }
126
+        return $entry;
127
+    }
128
+
129
+    private function getOwnerDisplayName() {
130
+        if (!$this->ownerDisplayName) {
131
+            $this->ownerDisplayName = \OC_User::getDisplayName($this->storage->getOwner(''));
132
+        }
133
+        return $this->ownerDisplayName;
134
+    }
135
+
136
+    /**
137
+     * remove all entries for files that are stored on the storage from the cache
138
+     */
139
+    public function clear() {
140
+        // Not a valid action for Shared Cache
141
+    }
142 142
 }
Please login to merge, or discard this patch.