Completed
Pull Request — master (#6840)
by Georg
34:18 queued 18:05
created
lib/public/Calendar/IManager.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -67,7 +67,7 @@
 block discarded – undo
67 67
 	 * @return array an array of events/journals/todos which are arrays of arrays of key-value-pairs
68 68
 	 * @since 13.0.0
69 69
 	 */
70
-	public function search($pattern, array $searchProperties=[], array $options=[], $limit=null, $offset=null);
70
+	public function search($pattern, array $searchProperties = [], array $options = [], $limit = null, $offset = null);
71 71
 
72 72
 	/**
73 73
 	 * Check if calendars are available
Please login to merge, or discard this patch.
Indentation   +57 added lines, -57 removed lines patch added patch discarded remove patch
@@ -55,67 +55,67 @@
 block discarded – undo
55 55
  */
56 56
 interface IManager {
57 57
 
58
-	/**
59
-	 * This function is used to search and find objects within the user's calendars.
60
-	 * In case $pattern is empty all events/journals/todos will be returned.
61
-	 *
62
-	 * @param string $pattern which should match within the $searchProperties
63
-	 * @param array $searchProperties defines the properties within the query pattern should match
64
-	 * @param array $options - optional parameters:
65
-	 * 	['timerange' => ['start' => new DateTime(...), 'end' => new DateTime(...)]]
66
-	 * @param integer|null $limit - limit number of search results
67
-	 * @param integer|null $offset - offset for paging of search results
68
-	 * @return array an array of events/journals/todos which are arrays of arrays of key-value-pairs
69
-	 * @since 13.0.0
70
-	 */
71
-	public function search($pattern, array $searchProperties=[], array $options=[], $limit=null, $offset=null);
58
+    /**
59
+     * This function is used to search and find objects within the user's calendars.
60
+     * In case $pattern is empty all events/journals/todos will be returned.
61
+     *
62
+     * @param string $pattern which should match within the $searchProperties
63
+     * @param array $searchProperties defines the properties within the query pattern should match
64
+     * @param array $options - optional parameters:
65
+     * 	['timerange' => ['start' => new DateTime(...), 'end' => new DateTime(...)]]
66
+     * @param integer|null $limit - limit number of search results
67
+     * @param integer|null $offset - offset for paging of search results
68
+     * @return array an array of events/journals/todos which are arrays of arrays of key-value-pairs
69
+     * @since 13.0.0
70
+     */
71
+    public function search($pattern, array $searchProperties=[], array $options=[], $limit=null, $offset=null);
72 72
 
73
-	/**
74
-	 * Check if calendars are available
75
-	 *
76
-	 * @return bool true if enabled, false if not
77
-	 * @since 13.0.0
78
-	 */
79
-	public function isEnabled();
73
+    /**
74
+     * Check if calendars are available
75
+     *
76
+     * @return bool true if enabled, false if not
77
+     * @since 13.0.0
78
+     */
79
+    public function isEnabled();
80 80
 
81
-	/**
82
-	 * Registers a calendar
83
-	 *
84
-	 * @param ICalendar $calendar
85
-	 * @return void
86
-	 * @since 13.0.0
87
-	 */
88
-	public function registerCalendar(ICalendar $calendar);
81
+    /**
82
+     * Registers a calendar
83
+     *
84
+     * @param ICalendar $calendar
85
+     * @return void
86
+     * @since 13.0.0
87
+     */
88
+    public function registerCalendar(ICalendar $calendar);
89 89
 
90
-	/**
91
-	 * Unregisters a calendar
92
-	 *
93
-	 * @param ICalendar $calendar
94
-	 * @return void
95
-	 * @since 13.0.0
96
-	 */
97
-	public function unregisterCalendar(ICalendar $calendar);
90
+    /**
91
+     * Unregisters a calendar
92
+     *
93
+     * @param ICalendar $calendar
94
+     * @return void
95
+     * @since 13.0.0
96
+     */
97
+    public function unregisterCalendar(ICalendar $calendar);
98 98
 
99
-	/**
100
-	 * In order to improve lazy loading a closure can be registered which will be called in case
101
-	 * calendars are actually requested
102
-	 *
103
-	 * @param \Closure $callable
104
-	 * @return void
105
-	 * @since 13.0.0
106
-	 */
107
-	public function register(\Closure $callable);
99
+    /**
100
+     * In order to improve lazy loading a closure can be registered which will be called in case
101
+     * calendars are actually requested
102
+     *
103
+     * @param \Closure $callable
104
+     * @return void
105
+     * @since 13.0.0
106
+     */
107
+    public function register(\Closure $callable);
108 108
 
109
-	/**
110
-	 * @return ICalendar[]
111
-	 * @since 13.0.0
112
-	 */
113
-	public function getCalendars();
109
+    /**
110
+     * @return ICalendar[]
111
+     * @since 13.0.0
112
+     */
113
+    public function getCalendars();
114 114
 
115
-	/**
116
-	 * removes all registered calendar instances
117
-	 * @return void
118
-	 * @since 13.0.0
119
-	 */
120
-	public function clear();
115
+    /**
116
+     * removes all registered calendar instances
117
+     * @return void
118
+     * @since 13.0.0
119
+     */
120
+    public function clear();
121 121
 }
Please login to merge, or discard this patch.
lib/public/Calendar/ICalendar.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -54,7 +54,7 @@
 block discarded – undo
54 54
 	 * @return array an array of events/journals/todos which are arrays of key-value-pairs
55 55
 	 * @since 13.0.0
56 56
 	 */
57
-	public function search($pattern, array $searchProperties=[], array $options=[], $limit=null, $offset=null);
57
+	public function search($pattern, array $searchProperties = [], array $options = [], $limit = null, $offset = null);
58 58
 
59 59
 	/**
60 60
 	 * @return integer build up using \OCP\Constants
Please login to merge, or discard this patch.
Indentation   +33 added lines, -33 removed lines patch added patch discarded remove patch
@@ -31,41 +31,41 @@
 block discarded – undo
31 31
  */
32 32
 interface ICalendar {
33 33
 
34
-	/**
35
-	 * @return string defining the technical unique key
36
-	 * @since 13.0.0
37
-	 */
38
-	public function getKey();
34
+    /**
35
+     * @return string defining the technical unique key
36
+     * @since 13.0.0
37
+     */
38
+    public function getKey();
39 39
 
40
-	/**
41
-	 * In comparison to getKey() this function returns a human readable (maybe translated) name
42
-	 * @return null|string
43
-	 * @since 13.0.0
44
-	 */
45
-	public function getDisplayName();
40
+    /**
41
+     * In comparison to getKey() this function returns a human readable (maybe translated) name
42
+     * @return null|string
43
+     * @since 13.0.0
44
+     */
45
+    public function getDisplayName();
46 46
 
47
-	/**
48
-	 * Calendar color
49
-	 * @return null|string
50
-	 * @since 13.0.0
51
-	 */
52
-	public function getDisplayColor();
47
+    /**
48
+     * Calendar color
49
+     * @return null|string
50
+     * @since 13.0.0
51
+     */
52
+    public function getDisplayColor();
53 53
 
54
-	/**
55
-	 * @param string $pattern which should match within the $searchProperties
56
-	 * @param array $searchProperties defines the properties within the query pattern should match
57
-	 * @param array $options - optional parameters:
58
-	 * 	['timerange' => ['start' => new DateTime(...), 'end' => new DateTime(...)]]
59
-	 * @param integer|null $limit - limit number of search results
60
-	 * @param integer|null $offset - offset for paging of search results
61
-	 * @return array an array of events/journals/todos which are arrays of key-value-pairs
62
-	 * @since 13.0.0
63
-	 */
64
-	public function search($pattern, array $searchProperties=[], array $options=[], $limit=null, $offset=null);
54
+    /**
55
+     * @param string $pattern which should match within the $searchProperties
56
+     * @param array $searchProperties defines the properties within the query pattern should match
57
+     * @param array $options - optional parameters:
58
+     * 	['timerange' => ['start' => new DateTime(...), 'end' => new DateTime(...)]]
59
+     * @param integer|null $limit - limit number of search results
60
+     * @param integer|null $offset - offset for paging of search results
61
+     * @return array an array of events/journals/todos which are arrays of key-value-pairs
62
+     * @since 13.0.0
63
+     */
64
+    public function search($pattern, array $searchProperties=[], array $options=[], $limit=null, $offset=null);
65 65
 
66
-	/**
67
-	 * @return integer build up using \OCP\Constants
68
-	 * @since 13.0.0
69
-	 */
70
-	public function getPermissions();
66
+    /**
67
+     * @return integer build up using \OCP\Constants
68
+     * @since 13.0.0
69
+     */
70
+    public function getPermissions();
71 71
 }
Please login to merge, or discard this patch.
apps/dav/appinfo/app.php 1 patch
Indentation   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -31,35 +31,35 @@
 block discarded – undo
31 31
 $app->registerHooks();
32 32
 
33 33
 \OC::$server->registerService('CardDAVSyncService', function() use ($app) {
34
-	return $app->getSyncService();
34
+    return $app->getSyncService();
35 35
 });
36 36
 
37 37
 $eventDispatcher = \OC::$server->getEventDispatcher();
38 38
 
39 39
 $eventDispatcher->addListener('OCP\Federation\TrustedServerEvent::remove',
40
-	function(GenericEvent $event) use ($app) {
41
-		/** @var CardDavBackend $cardDavBackend */
42
-		$cardDavBackend = $app->getContainer()->query(CardDavBackend::class);
43
-		$addressBookUri = $event->getSubject();
44
-		$addressBook = $cardDavBackend->getAddressBooksByUri('principals/system/system', $addressBookUri);
45
-		if (!is_null($addressBook)) {
46
-			$cardDavBackend->deleteAddressBook($addressBook['id']);
47
-		}
48
-	}
40
+    function(GenericEvent $event) use ($app) {
41
+        /** @var CardDavBackend $cardDavBackend */
42
+        $cardDavBackend = $app->getContainer()->query(CardDavBackend::class);
43
+        $addressBookUri = $event->getSubject();
44
+        $addressBook = $cardDavBackend->getAddressBooksByUri('principals/system/system', $addressBookUri);
45
+        if (!is_null($addressBook)) {
46
+            $cardDavBackend->deleteAddressBook($addressBook['id']);
47
+        }
48
+    }
49 49
 );
50 50
 
51 51
 $cm = \OC::$server->getContactsManager();
52 52
 $cm->register(function() use ($cm, $app) {
53
-	$user = \OC::$server->getUserSession()->getUser();
54
-	if (!is_null($user)) {
55
-		$app->setupContactsProvider($cm, $user->getUID());
56
-	}
53
+    $user = \OC::$server->getUserSession()->getUser();
54
+    if (!is_null($user)) {
55
+        $app->setupContactsProvider($cm, $user->getUID());
56
+    }
57 57
 });
58 58
 
59 59
 $calendarManager = \OC::$server->getCalendarManager();
60 60
 $calendarManager->register(function() use ($calendarManager, $app) {
61
-	$user = \OC::$server->getUserSession()->getUser();
62
-	if ($user !== null) {
63
-		$app->setupCalendarProvider($calendarManager, $user->getUID());
64
-	}
61
+    $user = \OC::$server->getUserSession()->getUser();
62
+    if ($user !== null) {
63
+        $app->setupCalendarProvider($calendarManager, $user->getUID());
64
+    }
65 65
 });
Please login to merge, or discard this patch.
apps/dav/lib/AppInfo/Application.php 1 patch
Indentation   +158 added lines, -158 removed lines patch added patch discarded remove patch
@@ -43,165 +43,165 @@
 block discarded – undo
43 43
 
44 44
 class Application extends App {
45 45
 
46
-	/**
47
-	 * Application constructor.
48
-	 */
49
-	public function __construct() {
50
-		parent::__construct('dav');
51
-
52
-		$container = $this->getContainer();
53
-		$server = $container->getServer();
54
-
55
-		$container->registerService(PhotoCache::class, function(SimpleContainer $s) use ($server) {
56
-			return new PhotoCache(
57
-				$server->getAppDataDir('dav-photocache')
58
-			);
59
-		});
60
-
61
-		/*
46
+    /**
47
+     * Application constructor.
48
+     */
49
+    public function __construct() {
50
+        parent::__construct('dav');
51
+
52
+        $container = $this->getContainer();
53
+        $server = $container->getServer();
54
+
55
+        $container->registerService(PhotoCache::class, function(SimpleContainer $s) use ($server) {
56
+            return new PhotoCache(
57
+                $server->getAppDataDir('dav-photocache')
58
+            );
59
+        });
60
+
61
+        /*
62 62
 		 * Register capabilities
63 63
 		 */
64
-		$container->registerCapability(Capabilities::class);
65
-	}
66
-
67
-	/**
68
-	 * @param IContactsManager $contactsManager
69
-	 * @param string $userID
70
-	 */
71
-	public function setupContactsProvider(IContactsManager $contactsManager, $userID) {
72
-		/** @var ContactsManager $cm */
73
-		$cm = $this->getContainer()->query(ContactsManager::class);
74
-		$urlGenerator = $this->getContainer()->getServer()->getURLGenerator();
75
-		$cm->setupContactsProvider($contactsManager, $userID, $urlGenerator);
76
-	}
77
-
78
-	/**
79
-	 * @param ICalendarManager $calendarManager
80
-	 * @param string $userId
81
-	 */
82
-	public function setupCalendarProvider(ICalendarManager $calendarManager, $userId) {
83
-		$cm = $this->getContainer()->query(CalendarManager::class);
84
-		$cm->setupCalendarProvider($calendarManager, $userId);
85
-	}
86
-
87
-	public function registerHooks() {
88
-		/** @var HookManager $hm */
89
-		$hm = $this->getContainer()->query(HookManager::class);
90
-		$hm->setup();
91
-
92
-		$dispatcher = $this->getContainer()->getServer()->getEventDispatcher();
93
-
94
-		// first time login event setup
95
-		$dispatcher->addListener(IUser::class . '::firstLogin', function ($event) use ($hm) {
96
-			if ($event instanceof GenericEvent) {
97
-				$hm->firstLogin($event->getSubject());
98
-			}
99
-		});
100
-
101
-		// carddav/caldav sync event setup
102
-		$listener = function($event) {
103
-			if ($event instanceof GenericEvent) {
104
-				/** @var BirthdayService $b */
105
-				$b = $this->getContainer()->query(BirthdayService::class);
106
-				$b->onCardChanged(
107
-					$event->getArgument('addressBookId'),
108
-					$event->getArgument('cardUri'),
109
-					$event->getArgument('cardData')
110
-				);
111
-			}
112
-		};
113
-
114
-		$dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::createCard', $listener);
115
-		$dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::updateCard', $listener);
116
-		$dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::deleteCard', function($event) {
117
-			if ($event instanceof GenericEvent) {
118
-				/** @var BirthdayService $b */
119
-				$b = $this->getContainer()->query(BirthdayService::class);
120
-				$b->onCardDeleted(
121
-					$event->getArgument('addressBookId'),
122
-					$event->getArgument('cardUri')
123
-				);
124
-			}
125
-		});
126
-
127
-		$clearPhotoCache = function($event) {
128
-			if ($event instanceof GenericEvent) {
129
-				/** @var PhotoCache $p */
130
-				$p = $this->getContainer()->query(PhotoCache::class);
131
-				$p->delete(
132
-					$event->getArgument('addressBookId'),
133
-					$event->getArgument('cardUri')
134
-				);
135
-			}
136
-		};
137
-		$dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::updateCard', $clearPhotoCache);
138
-		$dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::deleteCard', $clearPhotoCache);
139
-
140
-		$dispatcher->addListener('OC\AccountManager::userUpdated', function(GenericEvent $event) {
141
-			$user = $event->getSubject();
142
-			$syncService = $this->getContainer()->query(SyncService::class);
143
-			$syncService->updateUser($user);
144
-		});
145
-
146
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', function(GenericEvent $event) {
147
-			/** @var Backend $backend */
148
-			$backend = $this->getContainer()->query(Backend::class);
149
-			$backend->onCalendarAdd(
150
-				$event->getArgument('calendarData')
151
-			);
152
-		});
153
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', function(GenericEvent $event) {
154
-			/** @var Backend $backend */
155
-			$backend = $this->getContainer()->query(Backend::class);
156
-			$backend->onCalendarUpdate(
157
-				$event->getArgument('calendarData'),
158
-				$event->getArgument('shares'),
159
-				$event->getArgument('propertyMutations')
160
-			);
161
-		});
162
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', function(GenericEvent $event) {
163
-			/** @var Backend $backend */
164
-			$backend = $this->getContainer()->query(Backend::class);
165
-			$backend->onCalendarDelete(
166
-				$event->getArgument('calendarData'),
167
-				$event->getArgument('shares')
168
-			);
169
-		});
170
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::updateShares', function(GenericEvent $event) {
171
-			/** @var Backend $backend */
172
-			$backend = $this->getContainer()->query(Backend::class);
173
-			$backend->onCalendarUpdateShares(
174
-				$event->getArgument('calendarData'),
175
-				$event->getArgument('shares'),
176
-				$event->getArgument('add'),
177
-				$event->getArgument('remove')
178
-			);
179
-		});
180
-
181
-		$listener = function(GenericEvent $event, $eventName) {
182
-			/** @var Backend $backend */
183
-			$backend = $this->getContainer()->query(Backend::class);
184
-
185
-			$subject = Event::SUBJECT_OBJECT_ADD;
186
-			if ($eventName === '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject') {
187
-				$subject = Event::SUBJECT_OBJECT_UPDATE;
188
-			} else if ($eventName === '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject') {
189
-				$subject = Event::SUBJECT_OBJECT_DELETE;
190
-			}
191
-			$backend->onTouchCalendarObject(
192
-				$subject,
193
-				$event->getArgument('calendarData'),
194
-				$event->getArgument('shares'),
195
-				$event->getArgument('objectData')
196
-			);
197
-		};
198
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', $listener);
199
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', $listener);
200
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', $listener);
201
-	}
202
-
203
-	public function getSyncService() {
204
-		return $this->getContainer()->query(SyncService::class);
205
-	}
64
+        $container->registerCapability(Capabilities::class);
65
+    }
66
+
67
+    /**
68
+     * @param IContactsManager $contactsManager
69
+     * @param string $userID
70
+     */
71
+    public function setupContactsProvider(IContactsManager $contactsManager, $userID) {
72
+        /** @var ContactsManager $cm */
73
+        $cm = $this->getContainer()->query(ContactsManager::class);
74
+        $urlGenerator = $this->getContainer()->getServer()->getURLGenerator();
75
+        $cm->setupContactsProvider($contactsManager, $userID, $urlGenerator);
76
+    }
77
+
78
+    /**
79
+     * @param ICalendarManager $calendarManager
80
+     * @param string $userId
81
+     */
82
+    public function setupCalendarProvider(ICalendarManager $calendarManager, $userId) {
83
+        $cm = $this->getContainer()->query(CalendarManager::class);
84
+        $cm->setupCalendarProvider($calendarManager, $userId);
85
+    }
86
+
87
+    public function registerHooks() {
88
+        /** @var HookManager $hm */
89
+        $hm = $this->getContainer()->query(HookManager::class);
90
+        $hm->setup();
91
+
92
+        $dispatcher = $this->getContainer()->getServer()->getEventDispatcher();
93
+
94
+        // first time login event setup
95
+        $dispatcher->addListener(IUser::class . '::firstLogin', function ($event) use ($hm) {
96
+            if ($event instanceof GenericEvent) {
97
+                $hm->firstLogin($event->getSubject());
98
+            }
99
+        });
100
+
101
+        // carddav/caldav sync event setup
102
+        $listener = function($event) {
103
+            if ($event instanceof GenericEvent) {
104
+                /** @var BirthdayService $b */
105
+                $b = $this->getContainer()->query(BirthdayService::class);
106
+                $b->onCardChanged(
107
+                    $event->getArgument('addressBookId'),
108
+                    $event->getArgument('cardUri'),
109
+                    $event->getArgument('cardData')
110
+                );
111
+            }
112
+        };
113
+
114
+        $dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::createCard', $listener);
115
+        $dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::updateCard', $listener);
116
+        $dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::deleteCard', function($event) {
117
+            if ($event instanceof GenericEvent) {
118
+                /** @var BirthdayService $b */
119
+                $b = $this->getContainer()->query(BirthdayService::class);
120
+                $b->onCardDeleted(
121
+                    $event->getArgument('addressBookId'),
122
+                    $event->getArgument('cardUri')
123
+                );
124
+            }
125
+        });
126
+
127
+        $clearPhotoCache = function($event) {
128
+            if ($event instanceof GenericEvent) {
129
+                /** @var PhotoCache $p */
130
+                $p = $this->getContainer()->query(PhotoCache::class);
131
+                $p->delete(
132
+                    $event->getArgument('addressBookId'),
133
+                    $event->getArgument('cardUri')
134
+                );
135
+            }
136
+        };
137
+        $dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::updateCard', $clearPhotoCache);
138
+        $dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::deleteCard', $clearPhotoCache);
139
+
140
+        $dispatcher->addListener('OC\AccountManager::userUpdated', function(GenericEvent $event) {
141
+            $user = $event->getSubject();
142
+            $syncService = $this->getContainer()->query(SyncService::class);
143
+            $syncService->updateUser($user);
144
+        });
145
+
146
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', function(GenericEvent $event) {
147
+            /** @var Backend $backend */
148
+            $backend = $this->getContainer()->query(Backend::class);
149
+            $backend->onCalendarAdd(
150
+                $event->getArgument('calendarData')
151
+            );
152
+        });
153
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', function(GenericEvent $event) {
154
+            /** @var Backend $backend */
155
+            $backend = $this->getContainer()->query(Backend::class);
156
+            $backend->onCalendarUpdate(
157
+                $event->getArgument('calendarData'),
158
+                $event->getArgument('shares'),
159
+                $event->getArgument('propertyMutations')
160
+            );
161
+        });
162
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', function(GenericEvent $event) {
163
+            /** @var Backend $backend */
164
+            $backend = $this->getContainer()->query(Backend::class);
165
+            $backend->onCalendarDelete(
166
+                $event->getArgument('calendarData'),
167
+                $event->getArgument('shares')
168
+            );
169
+        });
170
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::updateShares', function(GenericEvent $event) {
171
+            /** @var Backend $backend */
172
+            $backend = $this->getContainer()->query(Backend::class);
173
+            $backend->onCalendarUpdateShares(
174
+                $event->getArgument('calendarData'),
175
+                $event->getArgument('shares'),
176
+                $event->getArgument('add'),
177
+                $event->getArgument('remove')
178
+            );
179
+        });
180
+
181
+        $listener = function(GenericEvent $event, $eventName) {
182
+            /** @var Backend $backend */
183
+            $backend = $this->getContainer()->query(Backend::class);
184
+
185
+            $subject = Event::SUBJECT_OBJECT_ADD;
186
+            if ($eventName === '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject') {
187
+                $subject = Event::SUBJECT_OBJECT_UPDATE;
188
+            } else if ($eventName === '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject') {
189
+                $subject = Event::SUBJECT_OBJECT_DELETE;
190
+            }
191
+            $backend->onTouchCalendarObject(
192
+                $subject,
193
+                $event->getArgument('calendarData'),
194
+                $event->getArgument('shares'),
195
+                $event->getArgument('objectData')
196
+            );
197
+        };
198
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', $listener);
199
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', $listener);
200
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', $listener);
201
+    }
202
+
203
+    public function getSyncService() {
204
+        return $this->getContainer()->query(SyncService::class);
205
+    }
206 206
 
207 207
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/CalendarManager.php 2 patches
Indentation   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -28,44 +28,44 @@
 block discarded – undo
28 28
 
29 29
 class CalendarManager {
30 30
 
31
-	/** @var CalDavBackend */
32
-	private $backend;
31
+    /** @var CalDavBackend */
32
+    private $backend;
33 33
 
34
-	/** @var IL10N */
35
-	private $l10n;
34
+    /** @var IL10N */
35
+    private $l10n;
36 36
 
37
-	/**
38
-	 * CalendarManager constructor.
39
-	 *
40
-	 * @param CalDavBackend $backend
41
-	 * @param IL10N $l10n
42
-	 */
43
-	public function __construct(CalDavBackend $backend, IL10N $l10n) {
44
-		$this->backend = $backend;
45
-		$this->l10n = $l10n;
46
-	}
37
+    /**
38
+     * CalendarManager constructor.
39
+     *
40
+     * @param CalDavBackend $backend
41
+     * @param IL10N $l10n
42
+     */
43
+    public function __construct(CalDavBackend $backend, IL10N $l10n) {
44
+        $this->backend = $backend;
45
+        $this->l10n = $l10n;
46
+    }
47 47
 
48
-	/**
49
-	 * @param IManager $cm
50
-	 * @param string $userId
51
-	 */
52
-	public function setupCalendarProvider(IManager $cm, $userId) {
53
-		$calendars = $this->backend->getCalendarsForUser("principals/users/$userId");
54
-		$this->register($cm, $calendars);
55
-	}
48
+    /**
49
+     * @param IManager $cm
50
+     * @param string $userId
51
+     */
52
+    public function setupCalendarProvider(IManager $cm, $userId) {
53
+        $calendars = $this->backend->getCalendarsForUser("principals/users/$userId");
54
+        $this->register($cm, $calendars);
55
+    }
56 56
 
57
-	/**
58
-	 * @param IManager $cm
59
-	 * @param array $calendars
60
-	 */
61
-	private function register(IManager $cm, array $calendars) {
62
-		foreach($calendars as $calendarInfo) {
63
-			$calendar = new Calendar($this->backend, $calendarInfo, $this->l10n);
64
-			$cm->registerCalendar(new CalendarImpl(
65
-				$calendar,
66
-				$calendarInfo,
67
-				$this->backend
68
-			));
69
-		}
70
-	}
57
+    /**
58
+     * @param IManager $cm
59
+     * @param array $calendars
60
+     */
61
+    private function register(IManager $cm, array $calendars) {
62
+        foreach($calendars as $calendarInfo) {
63
+            $calendar = new Calendar($this->backend, $calendarInfo, $this->l10n);
64
+            $cm->registerCalendar(new CalendarImpl(
65
+                $calendar,
66
+                $calendarInfo,
67
+                $this->backend
68
+            ));
69
+        }
70
+    }
71 71
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -59,7 +59,7 @@
 block discarded – undo
59 59
 	 * @param array $calendars
60 60
 	 */
61 61
 	private function register(IManager $cm, array $calendars) {
62
-		foreach($calendars as $calendarInfo) {
62
+		foreach ($calendars as $calendarInfo) {
63 63
 			$calendar = new Calendar($this->backend, $calendarInfo, $this->l10n);
64 64
 			$cm->registerCalendar(new CalendarImpl(
65 65
 				$calendar,
Please login to merge, or discard this patch.
lib/private/Calendar/Manager.php 2 patches
Indentation   +99 added lines, -99 removed lines patch added patch discarded remove patch
@@ -27,114 +27,114 @@
 block discarded – undo
27 27
 
28 28
 class Manager implements \OCP\Calendar\IManager {
29 29
 
30
-	/**
31
-	 * @var ICalendar[] holds all registered calendars
32
-	 */
33
-	private $calendars=[];
30
+    /**
31
+     * @var ICalendar[] holds all registered calendars
32
+     */
33
+    private $calendars=[];
34 34
 
35
-	/**
36
-	 * @var \Closure[] to call to load/register calendar providers
37
-	 */
38
-	private $calendarLoaders=[];
35
+    /**
36
+     * @var \Closure[] to call to load/register calendar providers
37
+     */
38
+    private $calendarLoaders=[];
39 39
 
40
-	/**
41
-	 * This function is used to search and find objects within the user's calendars.
42
-	 * In case $pattern is empty all events/journals/todos will be returned.
43
-	 *
44
-	 * @param string $pattern which should match within the $searchProperties
45
-	 * @param array $searchProperties defines the properties within the query pattern should match
46
-	 * @param array $options - optional parameters:
47
-	 * 	['timerange' => ['start' => new DateTime(...), 'end' => new DateTime(...)]]
48
-	 * @param integer|null $limit - limit number of search results
49
-	 * @param integer|null $offset - offset for paging of search results
50
-	 * @return array an array of events/journals/todos which are arrays of arrays of key-value-pairs
51
-	 * @since 13.0.0
52
-	 */
53
-	public function search($pattern, array $searchProperties=[], array $options=[], $limit=null, $offset=null) {
54
-		$this->loadCalendars();
55
-		$result = [];
56
-		foreach($this->calendars as $calendar) {
57
-			$r = $calendar->search($pattern, $searchProperties, $options, $limit, $offset);
58
-			foreach($r as $o) {
59
-				$o['calendar-key'] = $calendar->getKey();
60
-				$result[] = $o;
61
-			}
62
-		}
40
+    /**
41
+     * This function is used to search and find objects within the user's calendars.
42
+     * In case $pattern is empty all events/journals/todos will be returned.
43
+     *
44
+     * @param string $pattern which should match within the $searchProperties
45
+     * @param array $searchProperties defines the properties within the query pattern should match
46
+     * @param array $options - optional parameters:
47
+     * 	['timerange' => ['start' => new DateTime(...), 'end' => new DateTime(...)]]
48
+     * @param integer|null $limit - limit number of search results
49
+     * @param integer|null $offset - offset for paging of search results
50
+     * @return array an array of events/journals/todos which are arrays of arrays of key-value-pairs
51
+     * @since 13.0.0
52
+     */
53
+    public function search($pattern, array $searchProperties=[], array $options=[], $limit=null, $offset=null) {
54
+        $this->loadCalendars();
55
+        $result = [];
56
+        foreach($this->calendars as $calendar) {
57
+            $r = $calendar->search($pattern, $searchProperties, $options, $limit, $offset);
58
+            foreach($r as $o) {
59
+                $o['calendar-key'] = $calendar->getKey();
60
+                $result[] = $o;
61
+            }
62
+        }
63 63
 
64
-		return $result;
65
-	}
64
+        return $result;
65
+    }
66 66
 
67
-	/**
68
-	 * Check if calendars are available
69
-	 *
70
-	 * @return bool true if enabled, false if not
71
-	 * @since 13.0.0
72
-	 */
73
-	public function isEnabled() {
74
-		return !empty($this->calendars) || !empty($this->calendarLoaders);
75
-	}
67
+    /**
68
+     * Check if calendars are available
69
+     *
70
+     * @return bool true if enabled, false if not
71
+     * @since 13.0.0
72
+     */
73
+    public function isEnabled() {
74
+        return !empty($this->calendars) || !empty($this->calendarLoaders);
75
+    }
76 76
 
77
-	/**
78
-	 * Registers a calendar
79
-	 *
80
-	 * @param ICalendar $calendar
81
-	 * @return void
82
-	 * @since 13.0.0
83
-	 */
84
-	public function registerCalendar(ICalendar $calendar) {
85
-		$this->calendars[$calendar->getKey()] = $calendar;
86
-	}
77
+    /**
78
+     * Registers a calendar
79
+     *
80
+     * @param ICalendar $calendar
81
+     * @return void
82
+     * @since 13.0.0
83
+     */
84
+    public function registerCalendar(ICalendar $calendar) {
85
+        $this->calendars[$calendar->getKey()] = $calendar;
86
+    }
87 87
 
88
-	/**
89
-	 * Unregisters a calendar
90
-	 *
91
-	 * @param ICalendar $calendar
92
-	 * @return void
93
-	 * @since 13.0.0
94
-	 */
95
-	public function unregisterCalendar(ICalendar $calendar) {
96
-		unset($this->calendars[$calendar->getKey()]);
97
-	}
88
+    /**
89
+     * Unregisters a calendar
90
+     *
91
+     * @param ICalendar $calendar
92
+     * @return void
93
+     * @since 13.0.0
94
+     */
95
+    public function unregisterCalendar(ICalendar $calendar) {
96
+        unset($this->calendars[$calendar->getKey()]);
97
+    }
98 98
 
99
-	/**
100
-	 * In order to improve lazy loading a closure can be registered which will be called in case
101
-	 * calendars are actually requested
102
-	 *
103
-	 * @param \Closure $callable
104
-	 * @return void
105
-	 * @since 13.0.0
106
-	 */
107
-	public function register(\Closure $callable) {
108
-		$this->calendarLoaders[] = $callable;
109
-	}
99
+    /**
100
+     * In order to improve lazy loading a closure can be registered which will be called in case
101
+     * calendars are actually requested
102
+     *
103
+     * @param \Closure $callable
104
+     * @return void
105
+     * @since 13.0.0
106
+     */
107
+    public function register(\Closure $callable) {
108
+        $this->calendarLoaders[] = $callable;
109
+    }
110 110
 
111
-	/**
112
-	 * @return ICalendar[]
113
-	 * @since 13.0.0
114
-	 */
115
-	public function getCalendars() {
116
-		$this->loadCalendars();
111
+    /**
112
+     * @return ICalendar[]
113
+     * @since 13.0.0
114
+     */
115
+    public function getCalendars() {
116
+        $this->loadCalendars();
117 117
 
118
-		return array_values($this->calendars);
119
-	}
118
+        return array_values($this->calendars);
119
+    }
120 120
 
121
-	/**
122
-	 * removes all registered calendar instances
123
-	 * @return void
124
-	 * @since 13.0.0
125
-	 */
126
-	public function clear() {
127
-		$this->calendars = [];
128
-		$this->calendarLoaders = [];
129
-	}
121
+    /**
122
+     * removes all registered calendar instances
123
+     * @return void
124
+     * @since 13.0.0
125
+     */
126
+    public function clear() {
127
+        $this->calendars = [];
128
+        $this->calendarLoaders = [];
129
+    }
130 130
 
131
-	/**
132
-	 * loads all calendars
133
-	 */
134
-	private function loadCalendars() {
135
-		foreach($this->calendarLoaders as $callable) {
136
-			$callable($this);
137
-		}
138
-		$this->calendarLoaders = [];
139
-	}
131
+    /**
132
+     * loads all calendars
133
+     */
134
+    private function loadCalendars() {
135
+        foreach($this->calendarLoaders as $callable) {
136
+            $callable($this);
137
+        }
138
+        $this->calendarLoaders = [];
139
+    }
140 140
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -30,12 +30,12 @@  discard block
 block discarded – undo
30 30
 	/**
31 31
 	 * @var ICalendar[] holds all registered calendars
32 32
 	 */
33
-	private $calendars=[];
33
+	private $calendars = [];
34 34
 
35 35
 	/**
36 36
 	 * @var \Closure[] to call to load/register calendar providers
37 37
 	 */
38
-	private $calendarLoaders=[];
38
+	private $calendarLoaders = [];
39 39
 
40 40
 	/**
41 41
 	 * This function is used to search and find objects within the user's calendars.
@@ -50,12 +50,12 @@  discard block
 block discarded – undo
50 50
 	 * @return array an array of events/journals/todos which are arrays of arrays of key-value-pairs
51 51
 	 * @since 13.0.0
52 52
 	 */
53
-	public function search($pattern, array $searchProperties=[], array $options=[], $limit=null, $offset=null) {
53
+	public function search($pattern, array $searchProperties = [], array $options = [], $limit = null, $offset = null) {
54 54
 		$this->loadCalendars();
55 55
 		$result = [];
56
-		foreach($this->calendars as $calendar) {
56
+		foreach ($this->calendars as $calendar) {
57 57
 			$r = $calendar->search($pattern, $searchProperties, $options, $limit, $offset);
58
-			foreach($r as $o) {
58
+			foreach ($r as $o) {
59 59
 				$o['calendar-key'] = $calendar->getKey();
60 60
 				$result[] = $o;
61 61
 			}
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
 	 * loads all calendars
133 133
 	 */
134 134
 	private function loadCalendars() {
135
-		foreach($this->calendarLoaders as $callable) {
135
+		foreach ($this->calendarLoaders as $callable) {
136 136
 			$callable($this);
137 137
 		}
138 138
 		$this->calendarLoaders = [];
Please login to merge, or discard this patch.
lib/private/Server.php 1 patch
Indentation   +1721 added lines, -1721 removed lines patch added patch discarded remove patch
@@ -138,1730 +138,1730 @@
 block discarded – undo
138 138
  * TODO: hookup all manager classes
139 139
  */
140 140
 class Server extends ServerContainer implements IServerContainer {
141
-	/** @var string */
142
-	private $webRoot;
143
-
144
-	/**
145
-	 * @param string $webRoot
146
-	 * @param \OC\Config $config
147
-	 */
148
-	public function __construct($webRoot, \OC\Config $config) {
149
-		parent::__construct();
150
-		$this->webRoot = $webRoot;
151
-
152
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
153
-			return $c;
154
-		});
155
-
156
-		$this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
157
-		$this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
158
-
159
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
160
-		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
161
-
162
-		$this->registerAlias(IActionFactory::class, ActionFactory::class);
163
-
164
-
165
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
166
-			return new PreviewManager(
167
-				$c->getConfig(),
168
-				$c->getRootFolder(),
169
-				$c->getAppDataDir('preview'),
170
-				$c->getEventDispatcher(),
171
-				$c->getSession()->get('user_id')
172
-			);
173
-		});
174
-		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
175
-
176
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
177
-			return new \OC\Preview\Watcher(
178
-				$c->getAppDataDir('preview')
179
-			);
180
-		});
181
-
182
-		$this->registerService('EncryptionManager', function (Server $c) {
183
-			$view = new View();
184
-			$util = new Encryption\Util(
185
-				$view,
186
-				$c->getUserManager(),
187
-				$c->getGroupManager(),
188
-				$c->getConfig()
189
-			);
190
-			return new Encryption\Manager(
191
-				$c->getConfig(),
192
-				$c->getLogger(),
193
-				$c->getL10N('core'),
194
-				new View(),
195
-				$util,
196
-				new ArrayCache()
197
-			);
198
-		});
199
-
200
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
201
-			$util = new Encryption\Util(
202
-				new View(),
203
-				$c->getUserManager(),
204
-				$c->getGroupManager(),
205
-				$c->getConfig()
206
-			);
207
-			return new Encryption\File(
208
-				$util,
209
-				$c->getRootFolder(),
210
-				$c->getShareManager()
211
-			);
212
-		});
213
-
214
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
215
-			$view = new View();
216
-			$util = new Encryption\Util(
217
-				$view,
218
-				$c->getUserManager(),
219
-				$c->getGroupManager(),
220
-				$c->getConfig()
221
-			);
222
-
223
-			return new Encryption\Keys\Storage($view, $util);
224
-		});
225
-		$this->registerService('TagMapper', function (Server $c) {
226
-			return new TagMapper($c->getDatabaseConnection());
227
-		});
228
-
229
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
230
-			$tagMapper = $c->query('TagMapper');
231
-			return new TagManager($tagMapper, $c->getUserSession());
232
-		});
233
-		$this->registerAlias('TagManager', \OCP\ITagManager::class);
234
-
235
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
236
-			$config = $c->getConfig();
237
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
238
-			/** @var \OC\SystemTag\ManagerFactory $factory */
239
-			$factory = new $factoryClass($this);
240
-			return $factory;
241
-		});
242
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
243
-			return $c->query('SystemTagManagerFactory')->getManager();
244
-		});
245
-		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
246
-
247
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
248
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
249
-		});
250
-		$this->registerService('RootFolder', function (Server $c) {
251
-			$manager = \OC\Files\Filesystem::getMountManager(null);
252
-			$view = new View();
253
-			$root = new Root(
254
-				$manager,
255
-				$view,
256
-				null,
257
-				$c->getUserMountCache(),
258
-				$this->getLogger(),
259
-				$this->getUserManager()
260
-			);
261
-			$connector = new HookConnector($root, $view);
262
-			$connector->viewToNode();
263
-
264
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
265
-			$previewConnector->connectWatcher();
266
-
267
-			return $root;
268
-		});
269
-		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
270
-
271
-		$this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
272
-			return new LazyRoot(function () use ($c) {
273
-				return $c->query('RootFolder');
274
-			});
275
-		});
276
-		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
277
-
278
-		$this->registerService(\OCP\IUserManager::class, function (Server $c) {
279
-			$config = $c->getConfig();
280
-			return new \OC\User\Manager($config);
281
-		});
282
-		$this->registerAlias('UserManager', \OCP\IUserManager::class);
283
-
284
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
285
-			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
286
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
287
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
288
-			});
289
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
290
-				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
291
-			});
292
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
293
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
294
-			});
295
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
296
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
297
-			});
298
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
299
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
300
-			});
301
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
302
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
303
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
304
-				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
305
-			});
306
-			return $groupManager;
307
-		});
308
-		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
309
-
310
-		$this->registerService(Store::class, function (Server $c) {
311
-			$session = $c->getSession();
312
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
313
-				$tokenProvider = $c->query('OC\Authentication\Token\IProvider');
314
-			} else {
315
-				$tokenProvider = null;
316
-			}
317
-			$logger = $c->getLogger();
318
-			return new Store($session, $logger, $tokenProvider);
319
-		});
320
-		$this->registerAlias(IStore::class, Store::class);
321
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
322
-			$dbConnection = $c->getDatabaseConnection();
323
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
324
-		});
325
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
326
-			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
327
-			$crypto = $c->getCrypto();
328
-			$config = $c->getConfig();
329
-			$logger = $c->getLogger();
330
-			$timeFactory = new TimeFactory();
331
-			return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
332
-		});
333
-		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
334
-
335
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
336
-			$manager = $c->getUserManager();
337
-			$session = new \OC\Session\Memory('');
338
-			$timeFactory = new TimeFactory();
339
-			// Token providers might require a working database. This code
340
-			// might however be called when ownCloud is not yet setup.
341
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
342
-				$defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
343
-			} else {
344
-				$defaultTokenProvider = null;
345
-			}
346
-
347
-			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
348
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
349
-				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
350
-			});
351
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
352
-				/** @var $user \OC\User\User */
353
-				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
354
-			});
355
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
356
-				/** @var $user \OC\User\User */
357
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
358
-			});
359
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
360
-				/** @var $user \OC\User\User */
361
-				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
362
-			});
363
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
364
-				/** @var $user \OC\User\User */
365
-				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
366
-			});
367
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
368
-				/** @var $user \OC\User\User */
369
-				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
370
-			});
371
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
372
-				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
373
-			});
374
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
375
-				/** @var $user \OC\User\User */
376
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
377
-			});
378
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
379
-				/** @var $user \OC\User\User */
380
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
381
-			});
382
-			$userSession->listen('\OC\User', 'logout', function () {
383
-				\OC_Hook::emit('OC_User', 'logout', array());
384
-			});
385
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
386
-				/** @var $user \OC\User\User */
387
-				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
388
-			});
389
-			return $userSession;
390
-		});
391
-		$this->registerAlias('UserSession', \OCP\IUserSession::class);
392
-
393
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
394
-			return new \OC\Authentication\TwoFactorAuth\Manager(
395
-				$c->getAppManager(),
396
-				$c->getSession(),
397
-				$c->getConfig(),
398
-				$c->getActivityManager(),
399
-				$c->getLogger(),
400
-				$c->query(\OC\Authentication\Token\IProvider::class),
401
-				$c->query(ITimeFactory::class)
402
-			);
403
-		});
404
-
405
-		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
406
-		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
407
-
408
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
409
-			return new \OC\AllConfig(
410
-				$c->getSystemConfig()
411
-			);
412
-		});
413
-		$this->registerAlias('AllConfig', \OC\AllConfig::class);
414
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
415
-
416
-		$this->registerService('SystemConfig', function ($c) use ($config) {
417
-			return new \OC\SystemConfig($config);
418
-		});
419
-
420
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
421
-			return new \OC\AppConfig($c->getDatabaseConnection());
422
-		});
423
-		$this->registerAlias('AppConfig', \OC\AppConfig::class);
424
-		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
425
-
426
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
427
-			return new \OC\L10N\Factory(
428
-				$c->getConfig(),
429
-				$c->getRequest(),
430
-				$c->getUserSession(),
431
-				\OC::$SERVERROOT
432
-			);
433
-		});
434
-		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
435
-
436
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
437
-			$config = $c->getConfig();
438
-			$cacheFactory = $c->getMemCacheFactory();
439
-			$request = $c->getRequest();
440
-			return new \OC\URLGenerator(
441
-				$config,
442
-				$cacheFactory,
443
-				$request
444
-			);
445
-		});
446
-		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
447
-
448
-		$this->registerService('AppHelper', function ($c) {
449
-			return new \OC\AppHelper();
450
-		});
451
-		$this->registerAlias('AppFetcher', AppFetcher::class);
452
-		$this->registerAlias('CategoryFetcher', CategoryFetcher::class);
453
-
454
-		$this->registerService(\OCP\ICache::class, function ($c) {
455
-			return new Cache\File();
456
-		});
457
-		$this->registerAlias('UserCache', \OCP\ICache::class);
458
-
459
-		$this->registerService(Factory::class, function (Server $c) {
460
-
461
-			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
462
-				'\\OC\\Memcache\\ArrayCache',
463
-				'\\OC\\Memcache\\ArrayCache',
464
-				'\\OC\\Memcache\\ArrayCache'
465
-			);
466
-			$config = $c->getConfig();
467
-			$request = $c->getRequest();
468
-			$urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
469
-
470
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
471
-				$v = \OC_App::getAppVersions();
472
-				$v['core'] = implode(',', \OC_Util::getVersion());
473
-				$version = implode(',', $v);
474
-				$instanceId = \OC_Util::getInstanceId();
475
-				$path = \OC::$SERVERROOT;
476
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
477
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
478
-					$config->getSystemValue('memcache.local', null),
479
-					$config->getSystemValue('memcache.distributed', null),
480
-					$config->getSystemValue('memcache.locking', null)
481
-				);
482
-			}
483
-			return $arrayCacheFactory;
484
-
485
-		});
486
-		$this->registerAlias('MemCacheFactory', Factory::class);
487
-		$this->registerAlias(ICacheFactory::class, Factory::class);
488
-
489
-		$this->registerService('RedisFactory', function (Server $c) {
490
-			$systemConfig = $c->getSystemConfig();
491
-			return new RedisFactory($systemConfig);
492
-		});
493
-
494
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
495
-			return new \OC\Activity\Manager(
496
-				$c->getRequest(),
497
-				$c->getUserSession(),
498
-				$c->getConfig(),
499
-				$c->query(IValidator::class)
500
-			);
501
-		});
502
-		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
503
-
504
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
505
-			return new \OC\Activity\EventMerger(
506
-				$c->getL10N('lib')
507
-			);
508
-		});
509
-		$this->registerAlias(IValidator::class, Validator::class);
510
-
511
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
512
-			return new AvatarManager(
513
-				$c->getUserManager(),
514
-				$c->getAppDataDir('avatar'),
515
-				$c->getL10N('lib'),
516
-				$c->getLogger(),
517
-				$c->getConfig()
518
-			);
519
-		});
520
-		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
521
-
522
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
523
-			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
524
-			$logger = Log::getLogClass($logType);
525
-			call_user_func(array($logger, 'init'));
526
-
527
-			return new Log($logger);
528
-		});
529
-		$this->registerAlias('Logger', \OCP\ILogger::class);
530
-
531
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
532
-			$config = $c->getConfig();
533
-			return new \OC\BackgroundJob\JobList(
534
-				$c->getDatabaseConnection(),
535
-				$config,
536
-				new TimeFactory()
537
-			);
538
-		});
539
-		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
540
-
541
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
542
-			$cacheFactory = $c->getMemCacheFactory();
543
-			$logger = $c->getLogger();
544
-			if ($cacheFactory->isAvailableLowLatency()) {
545
-				$router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
546
-			} else {
547
-				$router = new \OC\Route\Router($logger);
548
-			}
549
-			return $router;
550
-		});
551
-		$this->registerAlias('Router', \OCP\Route\IRouter::class);
552
-
553
-		$this->registerService(\OCP\ISearch::class, function ($c) {
554
-			return new Search();
555
-		});
556
-		$this->registerAlias('Search', \OCP\ISearch::class);
557
-
558
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
559
-			return new \OC\Security\RateLimiting\Limiter(
560
-				$this->getUserSession(),
561
-				$this->getRequest(),
562
-				new \OC\AppFramework\Utility\TimeFactory(),
563
-				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
564
-			);
565
-		});
566
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
567
-			return new \OC\Security\RateLimiting\Backend\MemoryCache(
568
-				$this->getMemCacheFactory(),
569
-				new \OC\AppFramework\Utility\TimeFactory()
570
-			);
571
-		});
572
-
573
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
574
-			return new SecureRandom();
575
-		});
576
-		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
577
-
578
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
579
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
580
-		});
581
-		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
582
-
583
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
584
-			return new Hasher($c->getConfig());
585
-		});
586
-		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
587
-
588
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
589
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
590
-		});
591
-		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
592
-
593
-		$this->registerService(IDBConnection::class, function (Server $c) {
594
-			$systemConfig = $c->getSystemConfig();
595
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
596
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
597
-			if (!$factory->isValidType($type)) {
598
-				throw new \OC\DatabaseException('Invalid database type');
599
-			}
600
-			$connectionParams = $factory->createConnectionParams();
601
-			$connection = $factory->getConnection($type, $connectionParams);
602
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
603
-			return $connection;
604
-		});
605
-		$this->registerAlias('DatabaseConnection', IDBConnection::class);
606
-
607
-		$this->registerService('HTTPHelper', function (Server $c) {
608
-			$config = $c->getConfig();
609
-			return new HTTPHelper(
610
-				$config,
611
-				$c->getHTTPClientService()
612
-			);
613
-		});
614
-
615
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
616
-			$user = \OC_User::getUser();
617
-			$uid = $user ? $user : null;
618
-			return new ClientService(
619
-				$c->getConfig(),
620
-				new \OC\Security\CertificateManager(
621
-					$uid,
622
-					new View(),
623
-					$c->getConfig(),
624
-					$c->getLogger(),
625
-					$c->getSecureRandom()
626
-				)
627
-			);
628
-		});
629
-		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
630
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
631
-			$eventLogger = new EventLogger();
632
-			if ($c->getSystemConfig()->getValue('debug', false)) {
633
-				// In debug mode, module is being activated by default
634
-				$eventLogger->activate();
635
-			}
636
-			return $eventLogger;
637
-		});
638
-		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
639
-
640
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
641
-			$queryLogger = new QueryLogger();
642
-			if ($c->getSystemConfig()->getValue('debug', false)) {
643
-				// In debug mode, module is being activated by default
644
-				$queryLogger->activate();
645
-			}
646
-			return $queryLogger;
647
-		});
648
-		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
649
-
650
-		$this->registerService(TempManager::class, function (Server $c) {
651
-			return new TempManager(
652
-				$c->getLogger(),
653
-				$c->getConfig()
654
-			);
655
-		});
656
-		$this->registerAlias('TempManager', TempManager::class);
657
-		$this->registerAlias(ITempManager::class, TempManager::class);
658
-
659
-		$this->registerService(AppManager::class, function (Server $c) {
660
-			return new \OC\App\AppManager(
661
-				$c->getUserSession(),
662
-				$c->getAppConfig(),
663
-				$c->getGroupManager(),
664
-				$c->getMemCacheFactory(),
665
-				$c->getEventDispatcher()
666
-			);
667
-		});
668
-		$this->registerAlias('AppManager', AppManager::class);
669
-		$this->registerAlias(IAppManager::class, AppManager::class);
670
-
671
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
672
-			return new DateTimeZone(
673
-				$c->getConfig(),
674
-				$c->getSession()
675
-			);
676
-		});
677
-		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
678
-
679
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
680
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
681
-
682
-			return new DateTimeFormatter(
683
-				$c->getDateTimeZone()->getTimeZone(),
684
-				$c->getL10N('lib', $language)
685
-			);
686
-		});
687
-		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
688
-
689
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
690
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
691
-			$listener = new UserMountCacheListener($mountCache);
692
-			$listener->listen($c->getUserManager());
693
-			return $mountCache;
694
-		});
695
-		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
696
-
697
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
698
-			$loader = \OC\Files\Filesystem::getLoader();
699
-			$mountCache = $c->query('UserMountCache');
700
-			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
701
-
702
-			// builtin providers
703
-
704
-			$config = $c->getConfig();
705
-			$manager->registerProvider(new CacheMountProvider($config));
706
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
707
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
708
-
709
-			return $manager;
710
-		});
711
-		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
712
-
713
-		$this->registerService('IniWrapper', function ($c) {
714
-			return new IniGetWrapper();
715
-		});
716
-		$this->registerService('AsyncCommandBus', function (Server $c) {
717
-			$busClass = $c->getConfig()->getSystemValue('commandbus');
718
-			if ($busClass) {
719
-				list($app, $class) = explode('::', $busClass, 2);
720
-				if ($c->getAppManager()->isInstalled($app)) {
721
-					\OC_App::loadApp($app);
722
-					return $c->query($class);
723
-				} else {
724
-					throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
725
-				}
726
-			} else {
727
-				$jobList = $c->getJobList();
728
-				return new CronBus($jobList);
729
-			}
730
-		});
731
-		$this->registerService('TrustedDomainHelper', function ($c) {
732
-			return new TrustedDomainHelper($this->getConfig());
733
-		});
734
-		$this->registerService('Throttler', function (Server $c) {
735
-			return new Throttler(
736
-				$c->getDatabaseConnection(),
737
-				new TimeFactory(),
738
-				$c->getLogger(),
739
-				$c->getConfig()
740
-			);
741
-		});
742
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
743
-			// IConfig and IAppManager requires a working database. This code
744
-			// might however be called when ownCloud is not yet setup.
745
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
746
-				$config = $c->getConfig();
747
-				$appManager = $c->getAppManager();
748
-			} else {
749
-				$config = null;
750
-				$appManager = null;
751
-			}
752
-
753
-			return new Checker(
754
-				new EnvironmentHelper(),
755
-				new FileAccessHelper(),
756
-				new AppLocator(),
757
-				$config,
758
-				$c->getMemCacheFactory(),
759
-				$appManager,
760
-				$c->getTempManager()
761
-			);
762
-		});
763
-		$this->registerService(\OCP\IRequest::class, function ($c) {
764
-			if (isset($this['urlParams'])) {
765
-				$urlParams = $this['urlParams'];
766
-			} else {
767
-				$urlParams = [];
768
-			}
769
-
770
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
771
-				&& in_array('fakeinput', stream_get_wrappers())
772
-			) {
773
-				$stream = 'fakeinput://data';
774
-			} else {
775
-				$stream = 'php://input';
776
-			}
777
-
778
-			return new Request(
779
-				[
780
-					'get' => $_GET,
781
-					'post' => $_POST,
782
-					'files' => $_FILES,
783
-					'server' => $_SERVER,
784
-					'env' => $_ENV,
785
-					'cookies' => $_COOKIE,
786
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
787
-						? $_SERVER['REQUEST_METHOD']
788
-						: null,
789
-					'urlParams' => $urlParams,
790
-				],
791
-				$this->getSecureRandom(),
792
-				$this->getConfig(),
793
-				$this->getCsrfTokenManager(),
794
-				$stream
795
-			);
796
-		});
797
-		$this->registerAlias('Request', \OCP\IRequest::class);
798
-
799
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
800
-			return new Mailer(
801
-				$c->getConfig(),
802
-				$c->getLogger(),
803
-				$c->query(Defaults::class),
804
-				$c->getURLGenerator(),
805
-				$c->getL10N('lib')
806
-			);
807
-		});
808
-		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
809
-
810
-		$this->registerService('LDAPProvider', function (Server $c) {
811
-			$config = $c->getConfig();
812
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
813
-			if (is_null($factoryClass)) {
814
-				throw new \Exception('ldapProviderFactory not set');
815
-			}
816
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
817
-			$factory = new $factoryClass($this);
818
-			return $factory->getLDAPProvider();
819
-		});
820
-		$this->registerService(ILockingProvider::class, function (Server $c) {
821
-			$ini = $c->getIniWrapper();
822
-			$config = $c->getConfig();
823
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
824
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
825
-				/** @var \OC\Memcache\Factory $memcacheFactory */
826
-				$memcacheFactory = $c->getMemCacheFactory();
827
-				$memcache = $memcacheFactory->createLocking('lock');
828
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
829
-					return new MemcacheLockingProvider($memcache, $ttl);
830
-				}
831
-				return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
832
-			}
833
-			return new NoopLockingProvider();
834
-		});
835
-		$this->registerAlias('LockingProvider', ILockingProvider::class);
836
-
837
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
838
-			return new \OC\Files\Mount\Manager();
839
-		});
840
-		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
841
-
842
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
843
-			return new \OC\Files\Type\Detection(
844
-				$c->getURLGenerator(),
845
-				\OC::$configDir,
846
-				\OC::$SERVERROOT . '/resources/config/'
847
-			);
848
-		});
849
-		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
850
-
851
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
852
-			return new \OC\Files\Type\Loader(
853
-				$c->getDatabaseConnection()
854
-			);
855
-		});
856
-		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
857
-		$this->registerService(BundleFetcher::class, function () {
858
-			return new BundleFetcher($this->getL10N('lib'));
859
-		});
860
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
861
-			return new Manager(
862
-				$c->query(IValidator::class)
863
-			);
864
-		});
865
-		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
866
-
867
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
868
-			$manager = new \OC\CapabilitiesManager($c->getLogger());
869
-			$manager->registerCapability(function () use ($c) {
870
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
871
-			});
872
-			$manager->registerCapability(function () use ($c) {
873
-				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
874
-			});
875
-			return $manager;
876
-		});
877
-		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
878
-
879
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
880
-			$config = $c->getConfig();
881
-			$factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
882
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
883
-			$factory = new $factoryClass($this);
884
-			return $factory->getManager();
885
-		});
886
-		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
887
-
888
-		$this->registerService('ThemingDefaults', function (Server $c) {
889
-			/*
141
+    /** @var string */
142
+    private $webRoot;
143
+
144
+    /**
145
+     * @param string $webRoot
146
+     * @param \OC\Config $config
147
+     */
148
+    public function __construct($webRoot, \OC\Config $config) {
149
+        parent::__construct();
150
+        $this->webRoot = $webRoot;
151
+
152
+        $this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
153
+            return $c;
154
+        });
155
+
156
+        $this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
157
+        $this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
158
+
159
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
160
+        $this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
161
+
162
+        $this->registerAlias(IActionFactory::class, ActionFactory::class);
163
+
164
+
165
+        $this->registerService(\OCP\IPreview::class, function (Server $c) {
166
+            return new PreviewManager(
167
+                $c->getConfig(),
168
+                $c->getRootFolder(),
169
+                $c->getAppDataDir('preview'),
170
+                $c->getEventDispatcher(),
171
+                $c->getSession()->get('user_id')
172
+            );
173
+        });
174
+        $this->registerAlias('PreviewManager', \OCP\IPreview::class);
175
+
176
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
177
+            return new \OC\Preview\Watcher(
178
+                $c->getAppDataDir('preview')
179
+            );
180
+        });
181
+
182
+        $this->registerService('EncryptionManager', function (Server $c) {
183
+            $view = new View();
184
+            $util = new Encryption\Util(
185
+                $view,
186
+                $c->getUserManager(),
187
+                $c->getGroupManager(),
188
+                $c->getConfig()
189
+            );
190
+            return new Encryption\Manager(
191
+                $c->getConfig(),
192
+                $c->getLogger(),
193
+                $c->getL10N('core'),
194
+                new View(),
195
+                $util,
196
+                new ArrayCache()
197
+            );
198
+        });
199
+
200
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
201
+            $util = new Encryption\Util(
202
+                new View(),
203
+                $c->getUserManager(),
204
+                $c->getGroupManager(),
205
+                $c->getConfig()
206
+            );
207
+            return new Encryption\File(
208
+                $util,
209
+                $c->getRootFolder(),
210
+                $c->getShareManager()
211
+            );
212
+        });
213
+
214
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
215
+            $view = new View();
216
+            $util = new Encryption\Util(
217
+                $view,
218
+                $c->getUserManager(),
219
+                $c->getGroupManager(),
220
+                $c->getConfig()
221
+            );
222
+
223
+            return new Encryption\Keys\Storage($view, $util);
224
+        });
225
+        $this->registerService('TagMapper', function (Server $c) {
226
+            return new TagMapper($c->getDatabaseConnection());
227
+        });
228
+
229
+        $this->registerService(\OCP\ITagManager::class, function (Server $c) {
230
+            $tagMapper = $c->query('TagMapper');
231
+            return new TagManager($tagMapper, $c->getUserSession());
232
+        });
233
+        $this->registerAlias('TagManager', \OCP\ITagManager::class);
234
+
235
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
236
+            $config = $c->getConfig();
237
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
238
+            /** @var \OC\SystemTag\ManagerFactory $factory */
239
+            $factory = new $factoryClass($this);
240
+            return $factory;
241
+        });
242
+        $this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
243
+            return $c->query('SystemTagManagerFactory')->getManager();
244
+        });
245
+        $this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
246
+
247
+        $this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
248
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
249
+        });
250
+        $this->registerService('RootFolder', function (Server $c) {
251
+            $manager = \OC\Files\Filesystem::getMountManager(null);
252
+            $view = new View();
253
+            $root = new Root(
254
+                $manager,
255
+                $view,
256
+                null,
257
+                $c->getUserMountCache(),
258
+                $this->getLogger(),
259
+                $this->getUserManager()
260
+            );
261
+            $connector = new HookConnector($root, $view);
262
+            $connector->viewToNode();
263
+
264
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
265
+            $previewConnector->connectWatcher();
266
+
267
+            return $root;
268
+        });
269
+        $this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
270
+
271
+        $this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
272
+            return new LazyRoot(function () use ($c) {
273
+                return $c->query('RootFolder');
274
+            });
275
+        });
276
+        $this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
277
+
278
+        $this->registerService(\OCP\IUserManager::class, function (Server $c) {
279
+            $config = $c->getConfig();
280
+            return new \OC\User\Manager($config);
281
+        });
282
+        $this->registerAlias('UserManager', \OCP\IUserManager::class);
283
+
284
+        $this->registerService(\OCP\IGroupManager::class, function (Server $c) {
285
+            $groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
286
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
287
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
288
+            });
289
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
290
+                \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
291
+            });
292
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
293
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
294
+            });
295
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
296
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
297
+            });
298
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
299
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
300
+            });
301
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
302
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
303
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
304
+                \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
305
+            });
306
+            return $groupManager;
307
+        });
308
+        $this->registerAlias('GroupManager', \OCP\IGroupManager::class);
309
+
310
+        $this->registerService(Store::class, function (Server $c) {
311
+            $session = $c->getSession();
312
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
313
+                $tokenProvider = $c->query('OC\Authentication\Token\IProvider');
314
+            } else {
315
+                $tokenProvider = null;
316
+            }
317
+            $logger = $c->getLogger();
318
+            return new Store($session, $logger, $tokenProvider);
319
+        });
320
+        $this->registerAlias(IStore::class, Store::class);
321
+        $this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
322
+            $dbConnection = $c->getDatabaseConnection();
323
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
324
+        });
325
+        $this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
326
+            $mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
327
+            $crypto = $c->getCrypto();
328
+            $config = $c->getConfig();
329
+            $logger = $c->getLogger();
330
+            $timeFactory = new TimeFactory();
331
+            return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
332
+        });
333
+        $this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
334
+
335
+        $this->registerService(\OCP\IUserSession::class, function (Server $c) {
336
+            $manager = $c->getUserManager();
337
+            $session = new \OC\Session\Memory('');
338
+            $timeFactory = new TimeFactory();
339
+            // Token providers might require a working database. This code
340
+            // might however be called when ownCloud is not yet setup.
341
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
342
+                $defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
343
+            } else {
344
+                $defaultTokenProvider = null;
345
+            }
346
+
347
+            $userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
348
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
349
+                \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
350
+            });
351
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
352
+                /** @var $user \OC\User\User */
353
+                \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
354
+            });
355
+            $userSession->listen('\OC\User', 'preDelete', function ($user) {
356
+                /** @var $user \OC\User\User */
357
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
358
+            });
359
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
360
+                /** @var $user \OC\User\User */
361
+                \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
362
+            });
363
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
364
+                /** @var $user \OC\User\User */
365
+                \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
366
+            });
367
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
368
+                /** @var $user \OC\User\User */
369
+                \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
370
+            });
371
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
372
+                \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
373
+            });
374
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
375
+                /** @var $user \OC\User\User */
376
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
377
+            });
378
+            $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
379
+                /** @var $user \OC\User\User */
380
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
381
+            });
382
+            $userSession->listen('\OC\User', 'logout', function () {
383
+                \OC_Hook::emit('OC_User', 'logout', array());
384
+            });
385
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
386
+                /** @var $user \OC\User\User */
387
+                \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
388
+            });
389
+            return $userSession;
390
+        });
391
+        $this->registerAlias('UserSession', \OCP\IUserSession::class);
392
+
393
+        $this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
394
+            return new \OC\Authentication\TwoFactorAuth\Manager(
395
+                $c->getAppManager(),
396
+                $c->getSession(),
397
+                $c->getConfig(),
398
+                $c->getActivityManager(),
399
+                $c->getLogger(),
400
+                $c->query(\OC\Authentication\Token\IProvider::class),
401
+                $c->query(ITimeFactory::class)
402
+            );
403
+        });
404
+
405
+        $this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
406
+        $this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
407
+
408
+        $this->registerService(\OC\AllConfig::class, function (Server $c) {
409
+            return new \OC\AllConfig(
410
+                $c->getSystemConfig()
411
+            );
412
+        });
413
+        $this->registerAlias('AllConfig', \OC\AllConfig::class);
414
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
415
+
416
+        $this->registerService('SystemConfig', function ($c) use ($config) {
417
+            return new \OC\SystemConfig($config);
418
+        });
419
+
420
+        $this->registerService(\OC\AppConfig::class, function (Server $c) {
421
+            return new \OC\AppConfig($c->getDatabaseConnection());
422
+        });
423
+        $this->registerAlias('AppConfig', \OC\AppConfig::class);
424
+        $this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
425
+
426
+        $this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
427
+            return new \OC\L10N\Factory(
428
+                $c->getConfig(),
429
+                $c->getRequest(),
430
+                $c->getUserSession(),
431
+                \OC::$SERVERROOT
432
+            );
433
+        });
434
+        $this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
435
+
436
+        $this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
437
+            $config = $c->getConfig();
438
+            $cacheFactory = $c->getMemCacheFactory();
439
+            $request = $c->getRequest();
440
+            return new \OC\URLGenerator(
441
+                $config,
442
+                $cacheFactory,
443
+                $request
444
+            );
445
+        });
446
+        $this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
447
+
448
+        $this->registerService('AppHelper', function ($c) {
449
+            return new \OC\AppHelper();
450
+        });
451
+        $this->registerAlias('AppFetcher', AppFetcher::class);
452
+        $this->registerAlias('CategoryFetcher', CategoryFetcher::class);
453
+
454
+        $this->registerService(\OCP\ICache::class, function ($c) {
455
+            return new Cache\File();
456
+        });
457
+        $this->registerAlias('UserCache', \OCP\ICache::class);
458
+
459
+        $this->registerService(Factory::class, function (Server $c) {
460
+
461
+            $arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
462
+                '\\OC\\Memcache\\ArrayCache',
463
+                '\\OC\\Memcache\\ArrayCache',
464
+                '\\OC\\Memcache\\ArrayCache'
465
+            );
466
+            $config = $c->getConfig();
467
+            $request = $c->getRequest();
468
+            $urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
469
+
470
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
471
+                $v = \OC_App::getAppVersions();
472
+                $v['core'] = implode(',', \OC_Util::getVersion());
473
+                $version = implode(',', $v);
474
+                $instanceId = \OC_Util::getInstanceId();
475
+                $path = \OC::$SERVERROOT;
476
+                $prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
477
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
478
+                    $config->getSystemValue('memcache.local', null),
479
+                    $config->getSystemValue('memcache.distributed', null),
480
+                    $config->getSystemValue('memcache.locking', null)
481
+                );
482
+            }
483
+            return $arrayCacheFactory;
484
+
485
+        });
486
+        $this->registerAlias('MemCacheFactory', Factory::class);
487
+        $this->registerAlias(ICacheFactory::class, Factory::class);
488
+
489
+        $this->registerService('RedisFactory', function (Server $c) {
490
+            $systemConfig = $c->getSystemConfig();
491
+            return new RedisFactory($systemConfig);
492
+        });
493
+
494
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
495
+            return new \OC\Activity\Manager(
496
+                $c->getRequest(),
497
+                $c->getUserSession(),
498
+                $c->getConfig(),
499
+                $c->query(IValidator::class)
500
+            );
501
+        });
502
+        $this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
503
+
504
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
505
+            return new \OC\Activity\EventMerger(
506
+                $c->getL10N('lib')
507
+            );
508
+        });
509
+        $this->registerAlias(IValidator::class, Validator::class);
510
+
511
+        $this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
512
+            return new AvatarManager(
513
+                $c->getUserManager(),
514
+                $c->getAppDataDir('avatar'),
515
+                $c->getL10N('lib'),
516
+                $c->getLogger(),
517
+                $c->getConfig()
518
+            );
519
+        });
520
+        $this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
521
+
522
+        $this->registerService(\OCP\ILogger::class, function (Server $c) {
523
+            $logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
524
+            $logger = Log::getLogClass($logType);
525
+            call_user_func(array($logger, 'init'));
526
+
527
+            return new Log($logger);
528
+        });
529
+        $this->registerAlias('Logger', \OCP\ILogger::class);
530
+
531
+        $this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
532
+            $config = $c->getConfig();
533
+            return new \OC\BackgroundJob\JobList(
534
+                $c->getDatabaseConnection(),
535
+                $config,
536
+                new TimeFactory()
537
+            );
538
+        });
539
+        $this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
540
+
541
+        $this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
542
+            $cacheFactory = $c->getMemCacheFactory();
543
+            $logger = $c->getLogger();
544
+            if ($cacheFactory->isAvailableLowLatency()) {
545
+                $router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
546
+            } else {
547
+                $router = new \OC\Route\Router($logger);
548
+            }
549
+            return $router;
550
+        });
551
+        $this->registerAlias('Router', \OCP\Route\IRouter::class);
552
+
553
+        $this->registerService(\OCP\ISearch::class, function ($c) {
554
+            return new Search();
555
+        });
556
+        $this->registerAlias('Search', \OCP\ISearch::class);
557
+
558
+        $this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
559
+            return new \OC\Security\RateLimiting\Limiter(
560
+                $this->getUserSession(),
561
+                $this->getRequest(),
562
+                new \OC\AppFramework\Utility\TimeFactory(),
563
+                $c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
564
+            );
565
+        });
566
+        $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
567
+            return new \OC\Security\RateLimiting\Backend\MemoryCache(
568
+                $this->getMemCacheFactory(),
569
+                new \OC\AppFramework\Utility\TimeFactory()
570
+            );
571
+        });
572
+
573
+        $this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
574
+            return new SecureRandom();
575
+        });
576
+        $this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
577
+
578
+        $this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
579
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
580
+        });
581
+        $this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
582
+
583
+        $this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
584
+            return new Hasher($c->getConfig());
585
+        });
586
+        $this->registerAlias('Hasher', \OCP\Security\IHasher::class);
587
+
588
+        $this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
589
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
590
+        });
591
+        $this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
592
+
593
+        $this->registerService(IDBConnection::class, function (Server $c) {
594
+            $systemConfig = $c->getSystemConfig();
595
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
596
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
597
+            if (!$factory->isValidType($type)) {
598
+                throw new \OC\DatabaseException('Invalid database type');
599
+            }
600
+            $connectionParams = $factory->createConnectionParams();
601
+            $connection = $factory->getConnection($type, $connectionParams);
602
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
603
+            return $connection;
604
+        });
605
+        $this->registerAlias('DatabaseConnection', IDBConnection::class);
606
+
607
+        $this->registerService('HTTPHelper', function (Server $c) {
608
+            $config = $c->getConfig();
609
+            return new HTTPHelper(
610
+                $config,
611
+                $c->getHTTPClientService()
612
+            );
613
+        });
614
+
615
+        $this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
616
+            $user = \OC_User::getUser();
617
+            $uid = $user ? $user : null;
618
+            return new ClientService(
619
+                $c->getConfig(),
620
+                new \OC\Security\CertificateManager(
621
+                    $uid,
622
+                    new View(),
623
+                    $c->getConfig(),
624
+                    $c->getLogger(),
625
+                    $c->getSecureRandom()
626
+                )
627
+            );
628
+        });
629
+        $this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
630
+        $this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
631
+            $eventLogger = new EventLogger();
632
+            if ($c->getSystemConfig()->getValue('debug', false)) {
633
+                // In debug mode, module is being activated by default
634
+                $eventLogger->activate();
635
+            }
636
+            return $eventLogger;
637
+        });
638
+        $this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
639
+
640
+        $this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
641
+            $queryLogger = new QueryLogger();
642
+            if ($c->getSystemConfig()->getValue('debug', false)) {
643
+                // In debug mode, module is being activated by default
644
+                $queryLogger->activate();
645
+            }
646
+            return $queryLogger;
647
+        });
648
+        $this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
649
+
650
+        $this->registerService(TempManager::class, function (Server $c) {
651
+            return new TempManager(
652
+                $c->getLogger(),
653
+                $c->getConfig()
654
+            );
655
+        });
656
+        $this->registerAlias('TempManager', TempManager::class);
657
+        $this->registerAlias(ITempManager::class, TempManager::class);
658
+
659
+        $this->registerService(AppManager::class, function (Server $c) {
660
+            return new \OC\App\AppManager(
661
+                $c->getUserSession(),
662
+                $c->getAppConfig(),
663
+                $c->getGroupManager(),
664
+                $c->getMemCacheFactory(),
665
+                $c->getEventDispatcher()
666
+            );
667
+        });
668
+        $this->registerAlias('AppManager', AppManager::class);
669
+        $this->registerAlias(IAppManager::class, AppManager::class);
670
+
671
+        $this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
672
+            return new DateTimeZone(
673
+                $c->getConfig(),
674
+                $c->getSession()
675
+            );
676
+        });
677
+        $this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
678
+
679
+        $this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
680
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
681
+
682
+            return new DateTimeFormatter(
683
+                $c->getDateTimeZone()->getTimeZone(),
684
+                $c->getL10N('lib', $language)
685
+            );
686
+        });
687
+        $this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
688
+
689
+        $this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
690
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
691
+            $listener = new UserMountCacheListener($mountCache);
692
+            $listener->listen($c->getUserManager());
693
+            return $mountCache;
694
+        });
695
+        $this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
696
+
697
+        $this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
698
+            $loader = \OC\Files\Filesystem::getLoader();
699
+            $mountCache = $c->query('UserMountCache');
700
+            $manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
701
+
702
+            // builtin providers
703
+
704
+            $config = $c->getConfig();
705
+            $manager->registerProvider(new CacheMountProvider($config));
706
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
707
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
708
+
709
+            return $manager;
710
+        });
711
+        $this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
712
+
713
+        $this->registerService('IniWrapper', function ($c) {
714
+            return new IniGetWrapper();
715
+        });
716
+        $this->registerService('AsyncCommandBus', function (Server $c) {
717
+            $busClass = $c->getConfig()->getSystemValue('commandbus');
718
+            if ($busClass) {
719
+                list($app, $class) = explode('::', $busClass, 2);
720
+                if ($c->getAppManager()->isInstalled($app)) {
721
+                    \OC_App::loadApp($app);
722
+                    return $c->query($class);
723
+                } else {
724
+                    throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
725
+                }
726
+            } else {
727
+                $jobList = $c->getJobList();
728
+                return new CronBus($jobList);
729
+            }
730
+        });
731
+        $this->registerService('TrustedDomainHelper', function ($c) {
732
+            return new TrustedDomainHelper($this->getConfig());
733
+        });
734
+        $this->registerService('Throttler', function (Server $c) {
735
+            return new Throttler(
736
+                $c->getDatabaseConnection(),
737
+                new TimeFactory(),
738
+                $c->getLogger(),
739
+                $c->getConfig()
740
+            );
741
+        });
742
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
743
+            // IConfig and IAppManager requires a working database. This code
744
+            // might however be called when ownCloud is not yet setup.
745
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
746
+                $config = $c->getConfig();
747
+                $appManager = $c->getAppManager();
748
+            } else {
749
+                $config = null;
750
+                $appManager = null;
751
+            }
752
+
753
+            return new Checker(
754
+                new EnvironmentHelper(),
755
+                new FileAccessHelper(),
756
+                new AppLocator(),
757
+                $config,
758
+                $c->getMemCacheFactory(),
759
+                $appManager,
760
+                $c->getTempManager()
761
+            );
762
+        });
763
+        $this->registerService(\OCP\IRequest::class, function ($c) {
764
+            if (isset($this['urlParams'])) {
765
+                $urlParams = $this['urlParams'];
766
+            } else {
767
+                $urlParams = [];
768
+            }
769
+
770
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
771
+                && in_array('fakeinput', stream_get_wrappers())
772
+            ) {
773
+                $stream = 'fakeinput://data';
774
+            } else {
775
+                $stream = 'php://input';
776
+            }
777
+
778
+            return new Request(
779
+                [
780
+                    'get' => $_GET,
781
+                    'post' => $_POST,
782
+                    'files' => $_FILES,
783
+                    'server' => $_SERVER,
784
+                    'env' => $_ENV,
785
+                    'cookies' => $_COOKIE,
786
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
787
+                        ? $_SERVER['REQUEST_METHOD']
788
+                        : null,
789
+                    'urlParams' => $urlParams,
790
+                ],
791
+                $this->getSecureRandom(),
792
+                $this->getConfig(),
793
+                $this->getCsrfTokenManager(),
794
+                $stream
795
+            );
796
+        });
797
+        $this->registerAlias('Request', \OCP\IRequest::class);
798
+
799
+        $this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
800
+            return new Mailer(
801
+                $c->getConfig(),
802
+                $c->getLogger(),
803
+                $c->query(Defaults::class),
804
+                $c->getURLGenerator(),
805
+                $c->getL10N('lib')
806
+            );
807
+        });
808
+        $this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
809
+
810
+        $this->registerService('LDAPProvider', function (Server $c) {
811
+            $config = $c->getConfig();
812
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
813
+            if (is_null($factoryClass)) {
814
+                throw new \Exception('ldapProviderFactory not set');
815
+            }
816
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
817
+            $factory = new $factoryClass($this);
818
+            return $factory->getLDAPProvider();
819
+        });
820
+        $this->registerService(ILockingProvider::class, function (Server $c) {
821
+            $ini = $c->getIniWrapper();
822
+            $config = $c->getConfig();
823
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
824
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
825
+                /** @var \OC\Memcache\Factory $memcacheFactory */
826
+                $memcacheFactory = $c->getMemCacheFactory();
827
+                $memcache = $memcacheFactory->createLocking('lock');
828
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
829
+                    return new MemcacheLockingProvider($memcache, $ttl);
830
+                }
831
+                return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
832
+            }
833
+            return new NoopLockingProvider();
834
+        });
835
+        $this->registerAlias('LockingProvider', ILockingProvider::class);
836
+
837
+        $this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
838
+            return new \OC\Files\Mount\Manager();
839
+        });
840
+        $this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
841
+
842
+        $this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
843
+            return new \OC\Files\Type\Detection(
844
+                $c->getURLGenerator(),
845
+                \OC::$configDir,
846
+                \OC::$SERVERROOT . '/resources/config/'
847
+            );
848
+        });
849
+        $this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
850
+
851
+        $this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
852
+            return new \OC\Files\Type\Loader(
853
+                $c->getDatabaseConnection()
854
+            );
855
+        });
856
+        $this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
857
+        $this->registerService(BundleFetcher::class, function () {
858
+            return new BundleFetcher($this->getL10N('lib'));
859
+        });
860
+        $this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
861
+            return new Manager(
862
+                $c->query(IValidator::class)
863
+            );
864
+        });
865
+        $this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
866
+
867
+        $this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
868
+            $manager = new \OC\CapabilitiesManager($c->getLogger());
869
+            $manager->registerCapability(function () use ($c) {
870
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
871
+            });
872
+            $manager->registerCapability(function () use ($c) {
873
+                return $c->query(\OC\Security\Bruteforce\Capabilities::class);
874
+            });
875
+            return $manager;
876
+        });
877
+        $this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
878
+
879
+        $this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
880
+            $config = $c->getConfig();
881
+            $factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
882
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
883
+            $factory = new $factoryClass($this);
884
+            return $factory->getManager();
885
+        });
886
+        $this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
887
+
888
+        $this->registerService('ThemingDefaults', function (Server $c) {
889
+            /*
890 890
 			 * Dark magic for autoloader.
891 891
 			 * If we do a class_exists it will try to load the class which will
892 892
 			 * make composer cache the result. Resulting in errors when enabling
893 893
 			 * the theming app.
894 894
 			 */
895
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
896
-			if (isset($prefixes['OCA\\Theming\\'])) {
897
-				$classExists = true;
898
-			} else {
899
-				$classExists = false;
900
-			}
901
-
902
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
903
-				return new ThemingDefaults(
904
-					$c->getConfig(),
905
-					$c->getL10N('theming'),
906
-					$c->getURLGenerator(),
907
-					$c->getAppDataDir('theming'),
908
-					$c->getMemCacheFactory(),
909
-					new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
910
-					$this->getAppManager()
911
-				);
912
-			}
913
-			return new \OC_Defaults();
914
-		});
915
-		$this->registerService(SCSSCacher::class, function (Server $c) {
916
-			/** @var Factory $cacheFactory */
917
-			$cacheFactory = $c->query(Factory::class);
918
-			return new SCSSCacher(
919
-				$c->getLogger(),
920
-				$c->query(\OC\Files\AppData\Factory::class),
921
-				$c->getURLGenerator(),
922
-				$c->getConfig(),
923
-				$c->getThemingDefaults(),
924
-				\OC::$SERVERROOT,
925
-				$cacheFactory->create('SCSS')
926
-			);
927
-		});
928
-		$this->registerService(EventDispatcher::class, function () {
929
-			return new EventDispatcher();
930
-		});
931
-		$this->registerAlias('EventDispatcher', EventDispatcher::class);
932
-		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
933
-
934
-		$this->registerService('CryptoWrapper', function (Server $c) {
935
-			// FIXME: Instantiiated here due to cyclic dependency
936
-			$request = new Request(
937
-				[
938
-					'get' => $_GET,
939
-					'post' => $_POST,
940
-					'files' => $_FILES,
941
-					'server' => $_SERVER,
942
-					'env' => $_ENV,
943
-					'cookies' => $_COOKIE,
944
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
945
-						? $_SERVER['REQUEST_METHOD']
946
-						: null,
947
-				],
948
-				$c->getSecureRandom(),
949
-				$c->getConfig()
950
-			);
951
-
952
-			return new CryptoWrapper(
953
-				$c->getConfig(),
954
-				$c->getCrypto(),
955
-				$c->getSecureRandom(),
956
-				$request
957
-			);
958
-		});
959
-		$this->registerService('CsrfTokenManager', function (Server $c) {
960
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
961
-
962
-			return new CsrfTokenManager(
963
-				$tokenGenerator,
964
-				$c->query(SessionStorage::class)
965
-			);
966
-		});
967
-		$this->registerService(SessionStorage::class, function (Server $c) {
968
-			return new SessionStorage($c->getSession());
969
-		});
970
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
971
-			return new ContentSecurityPolicyManager();
972
-		});
973
-		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
974
-
975
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
976
-			return new ContentSecurityPolicyNonceManager(
977
-				$c->getCsrfTokenManager(),
978
-				$c->getRequest()
979
-			);
980
-		});
981
-
982
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
983
-			$config = $c->getConfig();
984
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
985
-			/** @var \OCP\Share\IProviderFactory $factory */
986
-			$factory = new $factoryClass($this);
987
-
988
-			$manager = new \OC\Share20\Manager(
989
-				$c->getLogger(),
990
-				$c->getConfig(),
991
-				$c->getSecureRandom(),
992
-				$c->getHasher(),
993
-				$c->getMountManager(),
994
-				$c->getGroupManager(),
995
-				$c->getL10N('lib'),
996
-				$c->getL10NFactory(),
997
-				$factory,
998
-				$c->getUserManager(),
999
-				$c->getLazyRootFolder(),
1000
-				$c->getEventDispatcher(),
1001
-				$c->getMailer(),
1002
-				$c->getURLGenerator(),
1003
-				$c->getThemingDefaults()
1004
-			);
1005
-
1006
-			return $manager;
1007
-		});
1008
-		$this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1009
-
1010
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1011
-			$instance = new Collaboration\Collaborators\Search($c);
1012
-
1013
-			// register default plugins
1014
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1015
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1016
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1017
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1018
-
1019
-			return $instance;
1020
-		});
1021
-		$this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1022
-
1023
-		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1024
-
1025
-		$this->registerService('SettingsManager', function (Server $c) {
1026
-			$manager = new \OC\Settings\Manager(
1027
-				$c->getLogger(),
1028
-				$c->getDatabaseConnection(),
1029
-				$c->getL10N('lib'),
1030
-				$c->getConfig(),
1031
-				$c->getEncryptionManager(),
1032
-				$c->getUserManager(),
1033
-				$c->getLockingProvider(),
1034
-				$c->getRequest(),
1035
-				new \OC\Settings\Mapper($c->getDatabaseConnection()),
1036
-				$c->getURLGenerator(),
1037
-				$c->query(AccountManager::class),
1038
-				$c->getGroupManager(),
1039
-				$c->getL10NFactory(),
1040
-				$c->getThemingDefaults(),
1041
-				$c->getAppManager()
1042
-			);
1043
-			return $manager;
1044
-		});
1045
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1046
-			return new \OC\Files\AppData\Factory(
1047
-				$c->getRootFolder(),
1048
-				$c->getSystemConfig()
1049
-			);
1050
-		});
1051
-
1052
-		$this->registerService('LockdownManager', function (Server $c) {
1053
-			return new LockdownManager(function () use ($c) {
1054
-				return $c->getSession();
1055
-			});
1056
-		});
1057
-
1058
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1059
-			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1060
-		});
1061
-
1062
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1063
-			return new CloudIdManager();
1064
-		});
1065
-
1066
-		/* To trick DI since we don't extend the DIContainer here */
1067
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
1068
-			return new CleanPreviewsBackgroundJob(
1069
-				$c->getRootFolder(),
1070
-				$c->getLogger(),
1071
-				$c->getJobList(),
1072
-				new TimeFactory()
1073
-			);
1074
-		});
1075
-
1076
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1077
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1078
-
1079
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1080
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1081
-
1082
-		$this->registerService(Defaults::class, function (Server $c) {
1083
-			return new Defaults(
1084
-				$c->getThemingDefaults()
1085
-			);
1086
-		});
1087
-		$this->registerAlias('Defaults', \OCP\Defaults::class);
1088
-
1089
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1090
-			return $c->query(\OCP\IUserSession::class)->getSession();
1091
-		});
1092
-
1093
-		$this->registerService(IShareHelper::class, function (Server $c) {
1094
-			return new ShareHelper(
1095
-				$c->query(\OCP\Share\IManager::class)
1096
-			);
1097
-		});
1098
-	}
1099
-
1100
-	/**
1101
-	 * @return \OCP\Calendar\IManager
1102
-	 */
1103
-	public function getCalendarManager() {
1104
-		return $this->query('CalendarManager');
1105
-	}
1106
-
1107
-	/**
1108
-	 * @return \OCP\Contacts\IManager
1109
-	 */
1110
-	public function getContactsManager() {
1111
-		return $this->query('ContactsManager');
1112
-	}
1113
-
1114
-	/**
1115
-	 * @return \OC\Encryption\Manager
1116
-	 */
1117
-	public function getEncryptionManager() {
1118
-		return $this->query('EncryptionManager');
1119
-	}
1120
-
1121
-	/**
1122
-	 * @return \OC\Encryption\File
1123
-	 */
1124
-	public function getEncryptionFilesHelper() {
1125
-		return $this->query('EncryptionFileHelper');
1126
-	}
1127
-
1128
-	/**
1129
-	 * @return \OCP\Encryption\Keys\IStorage
1130
-	 */
1131
-	public function getEncryptionKeyStorage() {
1132
-		return $this->query('EncryptionKeyStorage');
1133
-	}
1134
-
1135
-	/**
1136
-	 * The current request object holding all information about the request
1137
-	 * currently being processed is returned from this method.
1138
-	 * In case the current execution was not initiated by a web request null is returned
1139
-	 *
1140
-	 * @return \OCP\IRequest
1141
-	 */
1142
-	public function getRequest() {
1143
-		return $this->query('Request');
1144
-	}
1145
-
1146
-	/**
1147
-	 * Returns the preview manager which can create preview images for a given file
1148
-	 *
1149
-	 * @return \OCP\IPreview
1150
-	 */
1151
-	public function getPreviewManager() {
1152
-		return $this->query('PreviewManager');
1153
-	}
1154
-
1155
-	/**
1156
-	 * Returns the tag manager which can get and set tags for different object types
1157
-	 *
1158
-	 * @see \OCP\ITagManager::load()
1159
-	 * @return \OCP\ITagManager
1160
-	 */
1161
-	public function getTagManager() {
1162
-		return $this->query('TagManager');
1163
-	}
1164
-
1165
-	/**
1166
-	 * Returns the system-tag manager
1167
-	 *
1168
-	 * @return \OCP\SystemTag\ISystemTagManager
1169
-	 *
1170
-	 * @since 9.0.0
1171
-	 */
1172
-	public function getSystemTagManager() {
1173
-		return $this->query('SystemTagManager');
1174
-	}
1175
-
1176
-	/**
1177
-	 * Returns the system-tag object mapper
1178
-	 *
1179
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
1180
-	 *
1181
-	 * @since 9.0.0
1182
-	 */
1183
-	public function getSystemTagObjectMapper() {
1184
-		return $this->query('SystemTagObjectMapper');
1185
-	}
1186
-
1187
-	/**
1188
-	 * Returns the avatar manager, used for avatar functionality
1189
-	 *
1190
-	 * @return \OCP\IAvatarManager
1191
-	 */
1192
-	public function getAvatarManager() {
1193
-		return $this->query('AvatarManager');
1194
-	}
1195
-
1196
-	/**
1197
-	 * Returns the root folder of ownCloud's data directory
1198
-	 *
1199
-	 * @return \OCP\Files\IRootFolder
1200
-	 */
1201
-	public function getRootFolder() {
1202
-		return $this->query('LazyRootFolder');
1203
-	}
1204
-
1205
-	/**
1206
-	 * Returns the root folder of ownCloud's data directory
1207
-	 * This is the lazy variant so this gets only initialized once it
1208
-	 * is actually used.
1209
-	 *
1210
-	 * @return \OCP\Files\IRootFolder
1211
-	 */
1212
-	public function getLazyRootFolder() {
1213
-		return $this->query('LazyRootFolder');
1214
-	}
1215
-
1216
-	/**
1217
-	 * Returns a view to ownCloud's files folder
1218
-	 *
1219
-	 * @param string $userId user ID
1220
-	 * @return \OCP\Files\Folder|null
1221
-	 */
1222
-	public function getUserFolder($userId = null) {
1223
-		if ($userId === null) {
1224
-			$user = $this->getUserSession()->getUser();
1225
-			if (!$user) {
1226
-				return null;
1227
-			}
1228
-			$userId = $user->getUID();
1229
-		}
1230
-		$root = $this->getRootFolder();
1231
-		return $root->getUserFolder($userId);
1232
-	}
1233
-
1234
-	/**
1235
-	 * Returns an app-specific view in ownClouds data directory
1236
-	 *
1237
-	 * @return \OCP\Files\Folder
1238
-	 * @deprecated since 9.2.0 use IAppData
1239
-	 */
1240
-	public function getAppFolder() {
1241
-		$dir = '/' . \OC_App::getCurrentApp();
1242
-		$root = $this->getRootFolder();
1243
-		if (!$root->nodeExists($dir)) {
1244
-			$folder = $root->newFolder($dir);
1245
-		} else {
1246
-			$folder = $root->get($dir);
1247
-		}
1248
-		return $folder;
1249
-	}
1250
-
1251
-	/**
1252
-	 * @return \OC\User\Manager
1253
-	 */
1254
-	public function getUserManager() {
1255
-		return $this->query('UserManager');
1256
-	}
1257
-
1258
-	/**
1259
-	 * @return \OC\Group\Manager
1260
-	 */
1261
-	public function getGroupManager() {
1262
-		return $this->query('GroupManager');
1263
-	}
1264
-
1265
-	/**
1266
-	 * @return \OC\User\Session
1267
-	 */
1268
-	public function getUserSession() {
1269
-		return $this->query('UserSession');
1270
-	}
1271
-
1272
-	/**
1273
-	 * @return \OCP\ISession
1274
-	 */
1275
-	public function getSession() {
1276
-		return $this->query('UserSession')->getSession();
1277
-	}
1278
-
1279
-	/**
1280
-	 * @param \OCP\ISession $session
1281
-	 */
1282
-	public function setSession(\OCP\ISession $session) {
1283
-		$this->query(SessionStorage::class)->setSession($session);
1284
-		$this->query('UserSession')->setSession($session);
1285
-		$this->query(Store::class)->setSession($session);
1286
-	}
1287
-
1288
-	/**
1289
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1290
-	 */
1291
-	public function getTwoFactorAuthManager() {
1292
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1293
-	}
1294
-
1295
-	/**
1296
-	 * @return \OC\NavigationManager
1297
-	 */
1298
-	public function getNavigationManager() {
1299
-		return $this->query('NavigationManager');
1300
-	}
1301
-
1302
-	/**
1303
-	 * @return \OCP\IConfig
1304
-	 */
1305
-	public function getConfig() {
1306
-		return $this->query('AllConfig');
1307
-	}
1308
-
1309
-	/**
1310
-	 * @return \OC\SystemConfig
1311
-	 */
1312
-	public function getSystemConfig() {
1313
-		return $this->query('SystemConfig');
1314
-	}
1315
-
1316
-	/**
1317
-	 * Returns the app config manager
1318
-	 *
1319
-	 * @return \OCP\IAppConfig
1320
-	 */
1321
-	public function getAppConfig() {
1322
-		return $this->query('AppConfig');
1323
-	}
1324
-
1325
-	/**
1326
-	 * @return \OCP\L10N\IFactory
1327
-	 */
1328
-	public function getL10NFactory() {
1329
-		return $this->query('L10NFactory');
1330
-	}
1331
-
1332
-	/**
1333
-	 * get an L10N instance
1334
-	 *
1335
-	 * @param string $app appid
1336
-	 * @param string $lang
1337
-	 * @return IL10N
1338
-	 */
1339
-	public function getL10N($app, $lang = null) {
1340
-		return $this->getL10NFactory()->get($app, $lang);
1341
-	}
1342
-
1343
-	/**
1344
-	 * @return \OCP\IURLGenerator
1345
-	 */
1346
-	public function getURLGenerator() {
1347
-		return $this->query('URLGenerator');
1348
-	}
1349
-
1350
-	/**
1351
-	 * @return \OCP\IHelper
1352
-	 */
1353
-	public function getHelper() {
1354
-		return $this->query('AppHelper');
1355
-	}
1356
-
1357
-	/**
1358
-	 * @return AppFetcher
1359
-	 */
1360
-	public function getAppFetcher() {
1361
-		return $this->query(AppFetcher::class);
1362
-	}
1363
-
1364
-	/**
1365
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1366
-	 * getMemCacheFactory() instead.
1367
-	 *
1368
-	 * @return \OCP\ICache
1369
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1370
-	 */
1371
-	public function getCache() {
1372
-		return $this->query('UserCache');
1373
-	}
1374
-
1375
-	/**
1376
-	 * Returns an \OCP\CacheFactory instance
1377
-	 *
1378
-	 * @return \OCP\ICacheFactory
1379
-	 */
1380
-	public function getMemCacheFactory() {
1381
-		return $this->query('MemCacheFactory');
1382
-	}
1383
-
1384
-	/**
1385
-	 * Returns an \OC\RedisFactory instance
1386
-	 *
1387
-	 * @return \OC\RedisFactory
1388
-	 */
1389
-	public function getGetRedisFactory() {
1390
-		return $this->query('RedisFactory');
1391
-	}
1392
-
1393
-
1394
-	/**
1395
-	 * Returns the current session
1396
-	 *
1397
-	 * @return \OCP\IDBConnection
1398
-	 */
1399
-	public function getDatabaseConnection() {
1400
-		return $this->query('DatabaseConnection');
1401
-	}
1402
-
1403
-	/**
1404
-	 * Returns the activity manager
1405
-	 *
1406
-	 * @return \OCP\Activity\IManager
1407
-	 */
1408
-	public function getActivityManager() {
1409
-		return $this->query('ActivityManager');
1410
-	}
1411
-
1412
-	/**
1413
-	 * Returns an job list for controlling background jobs
1414
-	 *
1415
-	 * @return \OCP\BackgroundJob\IJobList
1416
-	 */
1417
-	public function getJobList() {
1418
-		return $this->query('JobList');
1419
-	}
1420
-
1421
-	/**
1422
-	 * Returns a logger instance
1423
-	 *
1424
-	 * @return \OCP\ILogger
1425
-	 */
1426
-	public function getLogger() {
1427
-		return $this->query('Logger');
1428
-	}
1429
-
1430
-	/**
1431
-	 * Returns a router for generating and matching urls
1432
-	 *
1433
-	 * @return \OCP\Route\IRouter
1434
-	 */
1435
-	public function getRouter() {
1436
-		return $this->query('Router');
1437
-	}
1438
-
1439
-	/**
1440
-	 * Returns a search instance
1441
-	 *
1442
-	 * @return \OCP\ISearch
1443
-	 */
1444
-	public function getSearch() {
1445
-		return $this->query('Search');
1446
-	}
1447
-
1448
-	/**
1449
-	 * Returns a SecureRandom instance
1450
-	 *
1451
-	 * @return \OCP\Security\ISecureRandom
1452
-	 */
1453
-	public function getSecureRandom() {
1454
-		return $this->query('SecureRandom');
1455
-	}
1456
-
1457
-	/**
1458
-	 * Returns a Crypto instance
1459
-	 *
1460
-	 * @return \OCP\Security\ICrypto
1461
-	 */
1462
-	public function getCrypto() {
1463
-		return $this->query('Crypto');
1464
-	}
1465
-
1466
-	/**
1467
-	 * Returns a Hasher instance
1468
-	 *
1469
-	 * @return \OCP\Security\IHasher
1470
-	 */
1471
-	public function getHasher() {
1472
-		return $this->query('Hasher');
1473
-	}
1474
-
1475
-	/**
1476
-	 * Returns a CredentialsManager instance
1477
-	 *
1478
-	 * @return \OCP\Security\ICredentialsManager
1479
-	 */
1480
-	public function getCredentialsManager() {
1481
-		return $this->query('CredentialsManager');
1482
-	}
1483
-
1484
-	/**
1485
-	 * Returns an instance of the HTTP helper class
1486
-	 *
1487
-	 * @deprecated Use getHTTPClientService()
1488
-	 * @return \OC\HTTPHelper
1489
-	 */
1490
-	public function getHTTPHelper() {
1491
-		return $this->query('HTTPHelper');
1492
-	}
1493
-
1494
-	/**
1495
-	 * Get the certificate manager for the user
1496
-	 *
1497
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1498
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1499
-	 */
1500
-	public function getCertificateManager($userId = '') {
1501
-		if ($userId === '') {
1502
-			$userSession = $this->getUserSession();
1503
-			$user = $userSession->getUser();
1504
-			if (is_null($user)) {
1505
-				return null;
1506
-			}
1507
-			$userId = $user->getUID();
1508
-		}
1509
-		return new CertificateManager(
1510
-			$userId,
1511
-			new View(),
1512
-			$this->getConfig(),
1513
-			$this->getLogger(),
1514
-			$this->getSecureRandom()
1515
-		);
1516
-	}
1517
-
1518
-	/**
1519
-	 * Returns an instance of the HTTP client service
1520
-	 *
1521
-	 * @return \OCP\Http\Client\IClientService
1522
-	 */
1523
-	public function getHTTPClientService() {
1524
-		return $this->query('HttpClientService');
1525
-	}
1526
-
1527
-	/**
1528
-	 * Create a new event source
1529
-	 *
1530
-	 * @return \OCP\IEventSource
1531
-	 */
1532
-	public function createEventSource() {
1533
-		return new \OC_EventSource();
1534
-	}
1535
-
1536
-	/**
1537
-	 * Get the active event logger
1538
-	 *
1539
-	 * The returned logger only logs data when debug mode is enabled
1540
-	 *
1541
-	 * @return \OCP\Diagnostics\IEventLogger
1542
-	 */
1543
-	public function getEventLogger() {
1544
-		return $this->query('EventLogger');
1545
-	}
1546
-
1547
-	/**
1548
-	 * Get the active query logger
1549
-	 *
1550
-	 * The returned logger only logs data when debug mode is enabled
1551
-	 *
1552
-	 * @return \OCP\Diagnostics\IQueryLogger
1553
-	 */
1554
-	public function getQueryLogger() {
1555
-		return $this->query('QueryLogger');
1556
-	}
1557
-
1558
-	/**
1559
-	 * Get the manager for temporary files and folders
1560
-	 *
1561
-	 * @return \OCP\ITempManager
1562
-	 */
1563
-	public function getTempManager() {
1564
-		return $this->query('TempManager');
1565
-	}
1566
-
1567
-	/**
1568
-	 * Get the app manager
1569
-	 *
1570
-	 * @return \OCP\App\IAppManager
1571
-	 */
1572
-	public function getAppManager() {
1573
-		return $this->query('AppManager');
1574
-	}
1575
-
1576
-	/**
1577
-	 * Creates a new mailer
1578
-	 *
1579
-	 * @return \OCP\Mail\IMailer
1580
-	 */
1581
-	public function getMailer() {
1582
-		return $this->query('Mailer');
1583
-	}
1584
-
1585
-	/**
1586
-	 * Get the webroot
1587
-	 *
1588
-	 * @return string
1589
-	 */
1590
-	public function getWebRoot() {
1591
-		return $this->webRoot;
1592
-	}
1593
-
1594
-	/**
1595
-	 * @return \OC\OCSClient
1596
-	 */
1597
-	public function getOcsClient() {
1598
-		return $this->query('OcsClient');
1599
-	}
1600
-
1601
-	/**
1602
-	 * @return \OCP\IDateTimeZone
1603
-	 */
1604
-	public function getDateTimeZone() {
1605
-		return $this->query('DateTimeZone');
1606
-	}
1607
-
1608
-	/**
1609
-	 * @return \OCP\IDateTimeFormatter
1610
-	 */
1611
-	public function getDateTimeFormatter() {
1612
-		return $this->query('DateTimeFormatter');
1613
-	}
1614
-
1615
-	/**
1616
-	 * @return \OCP\Files\Config\IMountProviderCollection
1617
-	 */
1618
-	public function getMountProviderCollection() {
1619
-		return $this->query('MountConfigManager');
1620
-	}
1621
-
1622
-	/**
1623
-	 * Get the IniWrapper
1624
-	 *
1625
-	 * @return IniGetWrapper
1626
-	 */
1627
-	public function getIniWrapper() {
1628
-		return $this->query('IniWrapper');
1629
-	}
1630
-
1631
-	/**
1632
-	 * @return \OCP\Command\IBus
1633
-	 */
1634
-	public function getCommandBus() {
1635
-		return $this->query('AsyncCommandBus');
1636
-	}
1637
-
1638
-	/**
1639
-	 * Get the trusted domain helper
1640
-	 *
1641
-	 * @return TrustedDomainHelper
1642
-	 */
1643
-	public function getTrustedDomainHelper() {
1644
-		return $this->query('TrustedDomainHelper');
1645
-	}
1646
-
1647
-	/**
1648
-	 * Get the locking provider
1649
-	 *
1650
-	 * @return \OCP\Lock\ILockingProvider
1651
-	 * @since 8.1.0
1652
-	 */
1653
-	public function getLockingProvider() {
1654
-		return $this->query('LockingProvider');
1655
-	}
1656
-
1657
-	/**
1658
-	 * @return \OCP\Files\Mount\IMountManager
1659
-	 **/
1660
-	function getMountManager() {
1661
-		return $this->query('MountManager');
1662
-	}
1663
-
1664
-	/** @return \OCP\Files\Config\IUserMountCache */
1665
-	function getUserMountCache() {
1666
-		return $this->query('UserMountCache');
1667
-	}
1668
-
1669
-	/**
1670
-	 * Get the MimeTypeDetector
1671
-	 *
1672
-	 * @return \OCP\Files\IMimeTypeDetector
1673
-	 */
1674
-	public function getMimeTypeDetector() {
1675
-		return $this->query('MimeTypeDetector');
1676
-	}
1677
-
1678
-	/**
1679
-	 * Get the MimeTypeLoader
1680
-	 *
1681
-	 * @return \OCP\Files\IMimeTypeLoader
1682
-	 */
1683
-	public function getMimeTypeLoader() {
1684
-		return $this->query('MimeTypeLoader');
1685
-	}
1686
-
1687
-	/**
1688
-	 * Get the manager of all the capabilities
1689
-	 *
1690
-	 * @return \OC\CapabilitiesManager
1691
-	 */
1692
-	public function getCapabilitiesManager() {
1693
-		return $this->query('CapabilitiesManager');
1694
-	}
1695
-
1696
-	/**
1697
-	 * Get the EventDispatcher
1698
-	 *
1699
-	 * @return EventDispatcherInterface
1700
-	 * @since 8.2.0
1701
-	 */
1702
-	public function getEventDispatcher() {
1703
-		return $this->query('EventDispatcher');
1704
-	}
1705
-
1706
-	/**
1707
-	 * Get the Notification Manager
1708
-	 *
1709
-	 * @return \OCP\Notification\IManager
1710
-	 * @since 8.2.0
1711
-	 */
1712
-	public function getNotificationManager() {
1713
-		return $this->query('NotificationManager');
1714
-	}
1715
-
1716
-	/**
1717
-	 * @return \OCP\Comments\ICommentsManager
1718
-	 */
1719
-	public function getCommentsManager() {
1720
-		return $this->query('CommentsManager');
1721
-	}
1722
-
1723
-	/**
1724
-	 * @return \OCA\Theming\ThemingDefaults
1725
-	 */
1726
-	public function getThemingDefaults() {
1727
-		return $this->query('ThemingDefaults');
1728
-	}
1729
-
1730
-	/**
1731
-	 * @return \OC\IntegrityCheck\Checker
1732
-	 */
1733
-	public function getIntegrityCodeChecker() {
1734
-		return $this->query('IntegrityCodeChecker');
1735
-	}
1736
-
1737
-	/**
1738
-	 * @return \OC\Session\CryptoWrapper
1739
-	 */
1740
-	public function getSessionCryptoWrapper() {
1741
-		return $this->query('CryptoWrapper');
1742
-	}
1743
-
1744
-	/**
1745
-	 * @return CsrfTokenManager
1746
-	 */
1747
-	public function getCsrfTokenManager() {
1748
-		return $this->query('CsrfTokenManager');
1749
-	}
1750
-
1751
-	/**
1752
-	 * @return Throttler
1753
-	 */
1754
-	public function getBruteForceThrottler() {
1755
-		return $this->query('Throttler');
1756
-	}
1757
-
1758
-	/**
1759
-	 * @return IContentSecurityPolicyManager
1760
-	 */
1761
-	public function getContentSecurityPolicyManager() {
1762
-		return $this->query('ContentSecurityPolicyManager');
1763
-	}
1764
-
1765
-	/**
1766
-	 * @return ContentSecurityPolicyNonceManager
1767
-	 */
1768
-	public function getContentSecurityPolicyNonceManager() {
1769
-		return $this->query('ContentSecurityPolicyNonceManager');
1770
-	}
1771
-
1772
-	/**
1773
-	 * Not a public API as of 8.2, wait for 9.0
1774
-	 *
1775
-	 * @return \OCA\Files_External\Service\BackendService
1776
-	 */
1777
-	public function getStoragesBackendService() {
1778
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1779
-	}
1780
-
1781
-	/**
1782
-	 * Not a public API as of 8.2, wait for 9.0
1783
-	 *
1784
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1785
-	 */
1786
-	public function getGlobalStoragesService() {
1787
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1788
-	}
1789
-
1790
-	/**
1791
-	 * Not a public API as of 8.2, wait for 9.0
1792
-	 *
1793
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1794
-	 */
1795
-	public function getUserGlobalStoragesService() {
1796
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1797
-	}
1798
-
1799
-	/**
1800
-	 * Not a public API as of 8.2, wait for 9.0
1801
-	 *
1802
-	 * @return \OCA\Files_External\Service\UserStoragesService
1803
-	 */
1804
-	public function getUserStoragesService() {
1805
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1806
-	}
1807
-
1808
-	/**
1809
-	 * @return \OCP\Share\IManager
1810
-	 */
1811
-	public function getShareManager() {
1812
-		return $this->query('ShareManager');
1813
-	}
1814
-
1815
-	/**
1816
-	 * @return \OCP\Collaboration\Collaborators\ISearch
1817
-	 */
1818
-	public function getCollaboratorSearch() {
1819
-		return $this->query('CollaboratorSearch');
1820
-	}
1821
-
1822
-	/**
1823
-	 * @return \OCP\Collaboration\AutoComplete\IManager
1824
-	 */
1825
-	public function getAutoCompleteManager(){
1826
-		return $this->query(IManager::class);
1827
-	}
1828
-
1829
-	/**
1830
-	 * Returns the LDAP Provider
1831
-	 *
1832
-	 * @return \OCP\LDAP\ILDAPProvider
1833
-	 */
1834
-	public function getLDAPProvider() {
1835
-		return $this->query('LDAPProvider');
1836
-	}
1837
-
1838
-	/**
1839
-	 * @return \OCP\Settings\IManager
1840
-	 */
1841
-	public function getSettingsManager() {
1842
-		return $this->query('SettingsManager');
1843
-	}
1844
-
1845
-	/**
1846
-	 * @return \OCP\Files\IAppData
1847
-	 */
1848
-	public function getAppDataDir($app) {
1849
-		/** @var \OC\Files\AppData\Factory $factory */
1850
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1851
-		return $factory->get($app);
1852
-	}
1853
-
1854
-	/**
1855
-	 * @return \OCP\Lockdown\ILockdownManager
1856
-	 */
1857
-	public function getLockdownManager() {
1858
-		return $this->query('LockdownManager');
1859
-	}
1860
-
1861
-	/**
1862
-	 * @return \OCP\Federation\ICloudIdManager
1863
-	 */
1864
-	public function getCloudIdManager() {
1865
-		return $this->query(ICloudIdManager::class);
1866
-	}
895
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
896
+            if (isset($prefixes['OCA\\Theming\\'])) {
897
+                $classExists = true;
898
+            } else {
899
+                $classExists = false;
900
+            }
901
+
902
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
903
+                return new ThemingDefaults(
904
+                    $c->getConfig(),
905
+                    $c->getL10N('theming'),
906
+                    $c->getURLGenerator(),
907
+                    $c->getAppDataDir('theming'),
908
+                    $c->getMemCacheFactory(),
909
+                    new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
910
+                    $this->getAppManager()
911
+                );
912
+            }
913
+            return new \OC_Defaults();
914
+        });
915
+        $this->registerService(SCSSCacher::class, function (Server $c) {
916
+            /** @var Factory $cacheFactory */
917
+            $cacheFactory = $c->query(Factory::class);
918
+            return new SCSSCacher(
919
+                $c->getLogger(),
920
+                $c->query(\OC\Files\AppData\Factory::class),
921
+                $c->getURLGenerator(),
922
+                $c->getConfig(),
923
+                $c->getThemingDefaults(),
924
+                \OC::$SERVERROOT,
925
+                $cacheFactory->create('SCSS')
926
+            );
927
+        });
928
+        $this->registerService(EventDispatcher::class, function () {
929
+            return new EventDispatcher();
930
+        });
931
+        $this->registerAlias('EventDispatcher', EventDispatcher::class);
932
+        $this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
933
+
934
+        $this->registerService('CryptoWrapper', function (Server $c) {
935
+            // FIXME: Instantiiated here due to cyclic dependency
936
+            $request = new Request(
937
+                [
938
+                    'get' => $_GET,
939
+                    'post' => $_POST,
940
+                    'files' => $_FILES,
941
+                    'server' => $_SERVER,
942
+                    'env' => $_ENV,
943
+                    'cookies' => $_COOKIE,
944
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
945
+                        ? $_SERVER['REQUEST_METHOD']
946
+                        : null,
947
+                ],
948
+                $c->getSecureRandom(),
949
+                $c->getConfig()
950
+            );
951
+
952
+            return new CryptoWrapper(
953
+                $c->getConfig(),
954
+                $c->getCrypto(),
955
+                $c->getSecureRandom(),
956
+                $request
957
+            );
958
+        });
959
+        $this->registerService('CsrfTokenManager', function (Server $c) {
960
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
961
+
962
+            return new CsrfTokenManager(
963
+                $tokenGenerator,
964
+                $c->query(SessionStorage::class)
965
+            );
966
+        });
967
+        $this->registerService(SessionStorage::class, function (Server $c) {
968
+            return new SessionStorage($c->getSession());
969
+        });
970
+        $this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
971
+            return new ContentSecurityPolicyManager();
972
+        });
973
+        $this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
974
+
975
+        $this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
976
+            return new ContentSecurityPolicyNonceManager(
977
+                $c->getCsrfTokenManager(),
978
+                $c->getRequest()
979
+            );
980
+        });
981
+
982
+        $this->registerService(\OCP\Share\IManager::class, function (Server $c) {
983
+            $config = $c->getConfig();
984
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
985
+            /** @var \OCP\Share\IProviderFactory $factory */
986
+            $factory = new $factoryClass($this);
987
+
988
+            $manager = new \OC\Share20\Manager(
989
+                $c->getLogger(),
990
+                $c->getConfig(),
991
+                $c->getSecureRandom(),
992
+                $c->getHasher(),
993
+                $c->getMountManager(),
994
+                $c->getGroupManager(),
995
+                $c->getL10N('lib'),
996
+                $c->getL10NFactory(),
997
+                $factory,
998
+                $c->getUserManager(),
999
+                $c->getLazyRootFolder(),
1000
+                $c->getEventDispatcher(),
1001
+                $c->getMailer(),
1002
+                $c->getURLGenerator(),
1003
+                $c->getThemingDefaults()
1004
+            );
1005
+
1006
+            return $manager;
1007
+        });
1008
+        $this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1009
+
1010
+        $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1011
+            $instance = new Collaboration\Collaborators\Search($c);
1012
+
1013
+            // register default plugins
1014
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1015
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1016
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1017
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1018
+
1019
+            return $instance;
1020
+        });
1021
+        $this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1022
+
1023
+        $this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1024
+
1025
+        $this->registerService('SettingsManager', function (Server $c) {
1026
+            $manager = new \OC\Settings\Manager(
1027
+                $c->getLogger(),
1028
+                $c->getDatabaseConnection(),
1029
+                $c->getL10N('lib'),
1030
+                $c->getConfig(),
1031
+                $c->getEncryptionManager(),
1032
+                $c->getUserManager(),
1033
+                $c->getLockingProvider(),
1034
+                $c->getRequest(),
1035
+                new \OC\Settings\Mapper($c->getDatabaseConnection()),
1036
+                $c->getURLGenerator(),
1037
+                $c->query(AccountManager::class),
1038
+                $c->getGroupManager(),
1039
+                $c->getL10NFactory(),
1040
+                $c->getThemingDefaults(),
1041
+                $c->getAppManager()
1042
+            );
1043
+            return $manager;
1044
+        });
1045
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1046
+            return new \OC\Files\AppData\Factory(
1047
+                $c->getRootFolder(),
1048
+                $c->getSystemConfig()
1049
+            );
1050
+        });
1051
+
1052
+        $this->registerService('LockdownManager', function (Server $c) {
1053
+            return new LockdownManager(function () use ($c) {
1054
+                return $c->getSession();
1055
+            });
1056
+        });
1057
+
1058
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1059
+            return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1060
+        });
1061
+
1062
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
1063
+            return new CloudIdManager();
1064
+        });
1065
+
1066
+        /* To trick DI since we don't extend the DIContainer here */
1067
+        $this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
1068
+            return new CleanPreviewsBackgroundJob(
1069
+                $c->getRootFolder(),
1070
+                $c->getLogger(),
1071
+                $c->getJobList(),
1072
+                new TimeFactory()
1073
+            );
1074
+        });
1075
+
1076
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1077
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1078
+
1079
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1080
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1081
+
1082
+        $this->registerService(Defaults::class, function (Server $c) {
1083
+            return new Defaults(
1084
+                $c->getThemingDefaults()
1085
+            );
1086
+        });
1087
+        $this->registerAlias('Defaults', \OCP\Defaults::class);
1088
+
1089
+        $this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1090
+            return $c->query(\OCP\IUserSession::class)->getSession();
1091
+        });
1092
+
1093
+        $this->registerService(IShareHelper::class, function (Server $c) {
1094
+            return new ShareHelper(
1095
+                $c->query(\OCP\Share\IManager::class)
1096
+            );
1097
+        });
1098
+    }
1099
+
1100
+    /**
1101
+     * @return \OCP\Calendar\IManager
1102
+     */
1103
+    public function getCalendarManager() {
1104
+        return $this->query('CalendarManager');
1105
+    }
1106
+
1107
+    /**
1108
+     * @return \OCP\Contacts\IManager
1109
+     */
1110
+    public function getContactsManager() {
1111
+        return $this->query('ContactsManager');
1112
+    }
1113
+
1114
+    /**
1115
+     * @return \OC\Encryption\Manager
1116
+     */
1117
+    public function getEncryptionManager() {
1118
+        return $this->query('EncryptionManager');
1119
+    }
1120
+
1121
+    /**
1122
+     * @return \OC\Encryption\File
1123
+     */
1124
+    public function getEncryptionFilesHelper() {
1125
+        return $this->query('EncryptionFileHelper');
1126
+    }
1127
+
1128
+    /**
1129
+     * @return \OCP\Encryption\Keys\IStorage
1130
+     */
1131
+    public function getEncryptionKeyStorage() {
1132
+        return $this->query('EncryptionKeyStorage');
1133
+    }
1134
+
1135
+    /**
1136
+     * The current request object holding all information about the request
1137
+     * currently being processed is returned from this method.
1138
+     * In case the current execution was not initiated by a web request null is returned
1139
+     *
1140
+     * @return \OCP\IRequest
1141
+     */
1142
+    public function getRequest() {
1143
+        return $this->query('Request');
1144
+    }
1145
+
1146
+    /**
1147
+     * Returns the preview manager which can create preview images for a given file
1148
+     *
1149
+     * @return \OCP\IPreview
1150
+     */
1151
+    public function getPreviewManager() {
1152
+        return $this->query('PreviewManager');
1153
+    }
1154
+
1155
+    /**
1156
+     * Returns the tag manager which can get and set tags for different object types
1157
+     *
1158
+     * @see \OCP\ITagManager::load()
1159
+     * @return \OCP\ITagManager
1160
+     */
1161
+    public function getTagManager() {
1162
+        return $this->query('TagManager');
1163
+    }
1164
+
1165
+    /**
1166
+     * Returns the system-tag manager
1167
+     *
1168
+     * @return \OCP\SystemTag\ISystemTagManager
1169
+     *
1170
+     * @since 9.0.0
1171
+     */
1172
+    public function getSystemTagManager() {
1173
+        return $this->query('SystemTagManager');
1174
+    }
1175
+
1176
+    /**
1177
+     * Returns the system-tag object mapper
1178
+     *
1179
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
1180
+     *
1181
+     * @since 9.0.0
1182
+     */
1183
+    public function getSystemTagObjectMapper() {
1184
+        return $this->query('SystemTagObjectMapper');
1185
+    }
1186
+
1187
+    /**
1188
+     * Returns the avatar manager, used for avatar functionality
1189
+     *
1190
+     * @return \OCP\IAvatarManager
1191
+     */
1192
+    public function getAvatarManager() {
1193
+        return $this->query('AvatarManager');
1194
+    }
1195
+
1196
+    /**
1197
+     * Returns the root folder of ownCloud's data directory
1198
+     *
1199
+     * @return \OCP\Files\IRootFolder
1200
+     */
1201
+    public function getRootFolder() {
1202
+        return $this->query('LazyRootFolder');
1203
+    }
1204
+
1205
+    /**
1206
+     * Returns the root folder of ownCloud's data directory
1207
+     * This is the lazy variant so this gets only initialized once it
1208
+     * is actually used.
1209
+     *
1210
+     * @return \OCP\Files\IRootFolder
1211
+     */
1212
+    public function getLazyRootFolder() {
1213
+        return $this->query('LazyRootFolder');
1214
+    }
1215
+
1216
+    /**
1217
+     * Returns a view to ownCloud's files folder
1218
+     *
1219
+     * @param string $userId user ID
1220
+     * @return \OCP\Files\Folder|null
1221
+     */
1222
+    public function getUserFolder($userId = null) {
1223
+        if ($userId === null) {
1224
+            $user = $this->getUserSession()->getUser();
1225
+            if (!$user) {
1226
+                return null;
1227
+            }
1228
+            $userId = $user->getUID();
1229
+        }
1230
+        $root = $this->getRootFolder();
1231
+        return $root->getUserFolder($userId);
1232
+    }
1233
+
1234
+    /**
1235
+     * Returns an app-specific view in ownClouds data directory
1236
+     *
1237
+     * @return \OCP\Files\Folder
1238
+     * @deprecated since 9.2.0 use IAppData
1239
+     */
1240
+    public function getAppFolder() {
1241
+        $dir = '/' . \OC_App::getCurrentApp();
1242
+        $root = $this->getRootFolder();
1243
+        if (!$root->nodeExists($dir)) {
1244
+            $folder = $root->newFolder($dir);
1245
+        } else {
1246
+            $folder = $root->get($dir);
1247
+        }
1248
+        return $folder;
1249
+    }
1250
+
1251
+    /**
1252
+     * @return \OC\User\Manager
1253
+     */
1254
+    public function getUserManager() {
1255
+        return $this->query('UserManager');
1256
+    }
1257
+
1258
+    /**
1259
+     * @return \OC\Group\Manager
1260
+     */
1261
+    public function getGroupManager() {
1262
+        return $this->query('GroupManager');
1263
+    }
1264
+
1265
+    /**
1266
+     * @return \OC\User\Session
1267
+     */
1268
+    public function getUserSession() {
1269
+        return $this->query('UserSession');
1270
+    }
1271
+
1272
+    /**
1273
+     * @return \OCP\ISession
1274
+     */
1275
+    public function getSession() {
1276
+        return $this->query('UserSession')->getSession();
1277
+    }
1278
+
1279
+    /**
1280
+     * @param \OCP\ISession $session
1281
+     */
1282
+    public function setSession(\OCP\ISession $session) {
1283
+        $this->query(SessionStorage::class)->setSession($session);
1284
+        $this->query('UserSession')->setSession($session);
1285
+        $this->query(Store::class)->setSession($session);
1286
+    }
1287
+
1288
+    /**
1289
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1290
+     */
1291
+    public function getTwoFactorAuthManager() {
1292
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1293
+    }
1294
+
1295
+    /**
1296
+     * @return \OC\NavigationManager
1297
+     */
1298
+    public function getNavigationManager() {
1299
+        return $this->query('NavigationManager');
1300
+    }
1301
+
1302
+    /**
1303
+     * @return \OCP\IConfig
1304
+     */
1305
+    public function getConfig() {
1306
+        return $this->query('AllConfig');
1307
+    }
1308
+
1309
+    /**
1310
+     * @return \OC\SystemConfig
1311
+     */
1312
+    public function getSystemConfig() {
1313
+        return $this->query('SystemConfig');
1314
+    }
1315
+
1316
+    /**
1317
+     * Returns the app config manager
1318
+     *
1319
+     * @return \OCP\IAppConfig
1320
+     */
1321
+    public function getAppConfig() {
1322
+        return $this->query('AppConfig');
1323
+    }
1324
+
1325
+    /**
1326
+     * @return \OCP\L10N\IFactory
1327
+     */
1328
+    public function getL10NFactory() {
1329
+        return $this->query('L10NFactory');
1330
+    }
1331
+
1332
+    /**
1333
+     * get an L10N instance
1334
+     *
1335
+     * @param string $app appid
1336
+     * @param string $lang
1337
+     * @return IL10N
1338
+     */
1339
+    public function getL10N($app, $lang = null) {
1340
+        return $this->getL10NFactory()->get($app, $lang);
1341
+    }
1342
+
1343
+    /**
1344
+     * @return \OCP\IURLGenerator
1345
+     */
1346
+    public function getURLGenerator() {
1347
+        return $this->query('URLGenerator');
1348
+    }
1349
+
1350
+    /**
1351
+     * @return \OCP\IHelper
1352
+     */
1353
+    public function getHelper() {
1354
+        return $this->query('AppHelper');
1355
+    }
1356
+
1357
+    /**
1358
+     * @return AppFetcher
1359
+     */
1360
+    public function getAppFetcher() {
1361
+        return $this->query(AppFetcher::class);
1362
+    }
1363
+
1364
+    /**
1365
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1366
+     * getMemCacheFactory() instead.
1367
+     *
1368
+     * @return \OCP\ICache
1369
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1370
+     */
1371
+    public function getCache() {
1372
+        return $this->query('UserCache');
1373
+    }
1374
+
1375
+    /**
1376
+     * Returns an \OCP\CacheFactory instance
1377
+     *
1378
+     * @return \OCP\ICacheFactory
1379
+     */
1380
+    public function getMemCacheFactory() {
1381
+        return $this->query('MemCacheFactory');
1382
+    }
1383
+
1384
+    /**
1385
+     * Returns an \OC\RedisFactory instance
1386
+     *
1387
+     * @return \OC\RedisFactory
1388
+     */
1389
+    public function getGetRedisFactory() {
1390
+        return $this->query('RedisFactory');
1391
+    }
1392
+
1393
+
1394
+    /**
1395
+     * Returns the current session
1396
+     *
1397
+     * @return \OCP\IDBConnection
1398
+     */
1399
+    public function getDatabaseConnection() {
1400
+        return $this->query('DatabaseConnection');
1401
+    }
1402
+
1403
+    /**
1404
+     * Returns the activity manager
1405
+     *
1406
+     * @return \OCP\Activity\IManager
1407
+     */
1408
+    public function getActivityManager() {
1409
+        return $this->query('ActivityManager');
1410
+    }
1411
+
1412
+    /**
1413
+     * Returns an job list for controlling background jobs
1414
+     *
1415
+     * @return \OCP\BackgroundJob\IJobList
1416
+     */
1417
+    public function getJobList() {
1418
+        return $this->query('JobList');
1419
+    }
1420
+
1421
+    /**
1422
+     * Returns a logger instance
1423
+     *
1424
+     * @return \OCP\ILogger
1425
+     */
1426
+    public function getLogger() {
1427
+        return $this->query('Logger');
1428
+    }
1429
+
1430
+    /**
1431
+     * Returns a router for generating and matching urls
1432
+     *
1433
+     * @return \OCP\Route\IRouter
1434
+     */
1435
+    public function getRouter() {
1436
+        return $this->query('Router');
1437
+    }
1438
+
1439
+    /**
1440
+     * Returns a search instance
1441
+     *
1442
+     * @return \OCP\ISearch
1443
+     */
1444
+    public function getSearch() {
1445
+        return $this->query('Search');
1446
+    }
1447
+
1448
+    /**
1449
+     * Returns a SecureRandom instance
1450
+     *
1451
+     * @return \OCP\Security\ISecureRandom
1452
+     */
1453
+    public function getSecureRandom() {
1454
+        return $this->query('SecureRandom');
1455
+    }
1456
+
1457
+    /**
1458
+     * Returns a Crypto instance
1459
+     *
1460
+     * @return \OCP\Security\ICrypto
1461
+     */
1462
+    public function getCrypto() {
1463
+        return $this->query('Crypto');
1464
+    }
1465
+
1466
+    /**
1467
+     * Returns a Hasher instance
1468
+     *
1469
+     * @return \OCP\Security\IHasher
1470
+     */
1471
+    public function getHasher() {
1472
+        return $this->query('Hasher');
1473
+    }
1474
+
1475
+    /**
1476
+     * Returns a CredentialsManager instance
1477
+     *
1478
+     * @return \OCP\Security\ICredentialsManager
1479
+     */
1480
+    public function getCredentialsManager() {
1481
+        return $this->query('CredentialsManager');
1482
+    }
1483
+
1484
+    /**
1485
+     * Returns an instance of the HTTP helper class
1486
+     *
1487
+     * @deprecated Use getHTTPClientService()
1488
+     * @return \OC\HTTPHelper
1489
+     */
1490
+    public function getHTTPHelper() {
1491
+        return $this->query('HTTPHelper');
1492
+    }
1493
+
1494
+    /**
1495
+     * Get the certificate manager for the user
1496
+     *
1497
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1498
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1499
+     */
1500
+    public function getCertificateManager($userId = '') {
1501
+        if ($userId === '') {
1502
+            $userSession = $this->getUserSession();
1503
+            $user = $userSession->getUser();
1504
+            if (is_null($user)) {
1505
+                return null;
1506
+            }
1507
+            $userId = $user->getUID();
1508
+        }
1509
+        return new CertificateManager(
1510
+            $userId,
1511
+            new View(),
1512
+            $this->getConfig(),
1513
+            $this->getLogger(),
1514
+            $this->getSecureRandom()
1515
+        );
1516
+    }
1517
+
1518
+    /**
1519
+     * Returns an instance of the HTTP client service
1520
+     *
1521
+     * @return \OCP\Http\Client\IClientService
1522
+     */
1523
+    public function getHTTPClientService() {
1524
+        return $this->query('HttpClientService');
1525
+    }
1526
+
1527
+    /**
1528
+     * Create a new event source
1529
+     *
1530
+     * @return \OCP\IEventSource
1531
+     */
1532
+    public function createEventSource() {
1533
+        return new \OC_EventSource();
1534
+    }
1535
+
1536
+    /**
1537
+     * Get the active event logger
1538
+     *
1539
+     * The returned logger only logs data when debug mode is enabled
1540
+     *
1541
+     * @return \OCP\Diagnostics\IEventLogger
1542
+     */
1543
+    public function getEventLogger() {
1544
+        return $this->query('EventLogger');
1545
+    }
1546
+
1547
+    /**
1548
+     * Get the active query logger
1549
+     *
1550
+     * The returned logger only logs data when debug mode is enabled
1551
+     *
1552
+     * @return \OCP\Diagnostics\IQueryLogger
1553
+     */
1554
+    public function getQueryLogger() {
1555
+        return $this->query('QueryLogger');
1556
+    }
1557
+
1558
+    /**
1559
+     * Get the manager for temporary files and folders
1560
+     *
1561
+     * @return \OCP\ITempManager
1562
+     */
1563
+    public function getTempManager() {
1564
+        return $this->query('TempManager');
1565
+    }
1566
+
1567
+    /**
1568
+     * Get the app manager
1569
+     *
1570
+     * @return \OCP\App\IAppManager
1571
+     */
1572
+    public function getAppManager() {
1573
+        return $this->query('AppManager');
1574
+    }
1575
+
1576
+    /**
1577
+     * Creates a new mailer
1578
+     *
1579
+     * @return \OCP\Mail\IMailer
1580
+     */
1581
+    public function getMailer() {
1582
+        return $this->query('Mailer');
1583
+    }
1584
+
1585
+    /**
1586
+     * Get the webroot
1587
+     *
1588
+     * @return string
1589
+     */
1590
+    public function getWebRoot() {
1591
+        return $this->webRoot;
1592
+    }
1593
+
1594
+    /**
1595
+     * @return \OC\OCSClient
1596
+     */
1597
+    public function getOcsClient() {
1598
+        return $this->query('OcsClient');
1599
+    }
1600
+
1601
+    /**
1602
+     * @return \OCP\IDateTimeZone
1603
+     */
1604
+    public function getDateTimeZone() {
1605
+        return $this->query('DateTimeZone');
1606
+    }
1607
+
1608
+    /**
1609
+     * @return \OCP\IDateTimeFormatter
1610
+     */
1611
+    public function getDateTimeFormatter() {
1612
+        return $this->query('DateTimeFormatter');
1613
+    }
1614
+
1615
+    /**
1616
+     * @return \OCP\Files\Config\IMountProviderCollection
1617
+     */
1618
+    public function getMountProviderCollection() {
1619
+        return $this->query('MountConfigManager');
1620
+    }
1621
+
1622
+    /**
1623
+     * Get the IniWrapper
1624
+     *
1625
+     * @return IniGetWrapper
1626
+     */
1627
+    public function getIniWrapper() {
1628
+        return $this->query('IniWrapper');
1629
+    }
1630
+
1631
+    /**
1632
+     * @return \OCP\Command\IBus
1633
+     */
1634
+    public function getCommandBus() {
1635
+        return $this->query('AsyncCommandBus');
1636
+    }
1637
+
1638
+    /**
1639
+     * Get the trusted domain helper
1640
+     *
1641
+     * @return TrustedDomainHelper
1642
+     */
1643
+    public function getTrustedDomainHelper() {
1644
+        return $this->query('TrustedDomainHelper');
1645
+    }
1646
+
1647
+    /**
1648
+     * Get the locking provider
1649
+     *
1650
+     * @return \OCP\Lock\ILockingProvider
1651
+     * @since 8.1.0
1652
+     */
1653
+    public function getLockingProvider() {
1654
+        return $this->query('LockingProvider');
1655
+    }
1656
+
1657
+    /**
1658
+     * @return \OCP\Files\Mount\IMountManager
1659
+     **/
1660
+    function getMountManager() {
1661
+        return $this->query('MountManager');
1662
+    }
1663
+
1664
+    /** @return \OCP\Files\Config\IUserMountCache */
1665
+    function getUserMountCache() {
1666
+        return $this->query('UserMountCache');
1667
+    }
1668
+
1669
+    /**
1670
+     * Get the MimeTypeDetector
1671
+     *
1672
+     * @return \OCP\Files\IMimeTypeDetector
1673
+     */
1674
+    public function getMimeTypeDetector() {
1675
+        return $this->query('MimeTypeDetector');
1676
+    }
1677
+
1678
+    /**
1679
+     * Get the MimeTypeLoader
1680
+     *
1681
+     * @return \OCP\Files\IMimeTypeLoader
1682
+     */
1683
+    public function getMimeTypeLoader() {
1684
+        return $this->query('MimeTypeLoader');
1685
+    }
1686
+
1687
+    /**
1688
+     * Get the manager of all the capabilities
1689
+     *
1690
+     * @return \OC\CapabilitiesManager
1691
+     */
1692
+    public function getCapabilitiesManager() {
1693
+        return $this->query('CapabilitiesManager');
1694
+    }
1695
+
1696
+    /**
1697
+     * Get the EventDispatcher
1698
+     *
1699
+     * @return EventDispatcherInterface
1700
+     * @since 8.2.0
1701
+     */
1702
+    public function getEventDispatcher() {
1703
+        return $this->query('EventDispatcher');
1704
+    }
1705
+
1706
+    /**
1707
+     * Get the Notification Manager
1708
+     *
1709
+     * @return \OCP\Notification\IManager
1710
+     * @since 8.2.0
1711
+     */
1712
+    public function getNotificationManager() {
1713
+        return $this->query('NotificationManager');
1714
+    }
1715
+
1716
+    /**
1717
+     * @return \OCP\Comments\ICommentsManager
1718
+     */
1719
+    public function getCommentsManager() {
1720
+        return $this->query('CommentsManager');
1721
+    }
1722
+
1723
+    /**
1724
+     * @return \OCA\Theming\ThemingDefaults
1725
+     */
1726
+    public function getThemingDefaults() {
1727
+        return $this->query('ThemingDefaults');
1728
+    }
1729
+
1730
+    /**
1731
+     * @return \OC\IntegrityCheck\Checker
1732
+     */
1733
+    public function getIntegrityCodeChecker() {
1734
+        return $this->query('IntegrityCodeChecker');
1735
+    }
1736
+
1737
+    /**
1738
+     * @return \OC\Session\CryptoWrapper
1739
+     */
1740
+    public function getSessionCryptoWrapper() {
1741
+        return $this->query('CryptoWrapper');
1742
+    }
1743
+
1744
+    /**
1745
+     * @return CsrfTokenManager
1746
+     */
1747
+    public function getCsrfTokenManager() {
1748
+        return $this->query('CsrfTokenManager');
1749
+    }
1750
+
1751
+    /**
1752
+     * @return Throttler
1753
+     */
1754
+    public function getBruteForceThrottler() {
1755
+        return $this->query('Throttler');
1756
+    }
1757
+
1758
+    /**
1759
+     * @return IContentSecurityPolicyManager
1760
+     */
1761
+    public function getContentSecurityPolicyManager() {
1762
+        return $this->query('ContentSecurityPolicyManager');
1763
+    }
1764
+
1765
+    /**
1766
+     * @return ContentSecurityPolicyNonceManager
1767
+     */
1768
+    public function getContentSecurityPolicyNonceManager() {
1769
+        return $this->query('ContentSecurityPolicyNonceManager');
1770
+    }
1771
+
1772
+    /**
1773
+     * Not a public API as of 8.2, wait for 9.0
1774
+     *
1775
+     * @return \OCA\Files_External\Service\BackendService
1776
+     */
1777
+    public function getStoragesBackendService() {
1778
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1779
+    }
1780
+
1781
+    /**
1782
+     * Not a public API as of 8.2, wait for 9.0
1783
+     *
1784
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1785
+     */
1786
+    public function getGlobalStoragesService() {
1787
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1788
+    }
1789
+
1790
+    /**
1791
+     * Not a public API as of 8.2, wait for 9.0
1792
+     *
1793
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1794
+     */
1795
+    public function getUserGlobalStoragesService() {
1796
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1797
+    }
1798
+
1799
+    /**
1800
+     * Not a public API as of 8.2, wait for 9.0
1801
+     *
1802
+     * @return \OCA\Files_External\Service\UserStoragesService
1803
+     */
1804
+    public function getUserStoragesService() {
1805
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1806
+    }
1807
+
1808
+    /**
1809
+     * @return \OCP\Share\IManager
1810
+     */
1811
+    public function getShareManager() {
1812
+        return $this->query('ShareManager');
1813
+    }
1814
+
1815
+    /**
1816
+     * @return \OCP\Collaboration\Collaborators\ISearch
1817
+     */
1818
+    public function getCollaboratorSearch() {
1819
+        return $this->query('CollaboratorSearch');
1820
+    }
1821
+
1822
+    /**
1823
+     * @return \OCP\Collaboration\AutoComplete\IManager
1824
+     */
1825
+    public function getAutoCompleteManager(){
1826
+        return $this->query(IManager::class);
1827
+    }
1828
+
1829
+    /**
1830
+     * Returns the LDAP Provider
1831
+     *
1832
+     * @return \OCP\LDAP\ILDAPProvider
1833
+     */
1834
+    public function getLDAPProvider() {
1835
+        return $this->query('LDAPProvider');
1836
+    }
1837
+
1838
+    /**
1839
+     * @return \OCP\Settings\IManager
1840
+     */
1841
+    public function getSettingsManager() {
1842
+        return $this->query('SettingsManager');
1843
+    }
1844
+
1845
+    /**
1846
+     * @return \OCP\Files\IAppData
1847
+     */
1848
+    public function getAppDataDir($app) {
1849
+        /** @var \OC\Files\AppData\Factory $factory */
1850
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1851
+        return $factory->get($app);
1852
+    }
1853
+
1854
+    /**
1855
+     * @return \OCP\Lockdown\ILockdownManager
1856
+     */
1857
+    public function getLockdownManager() {
1858
+        return $this->query('LockdownManager');
1859
+    }
1860
+
1861
+    /**
1862
+     * @return \OCP\Federation\ICloudIdManager
1863
+     */
1864
+    public function getCloudIdManager() {
1865
+        return $this->query(ICloudIdManager::class);
1866
+    }
1867 1867
 }
Please login to merge, or discard this patch.
lib/public/IServerContainer.php 1 patch
Indentation   +484 added lines, -484 removed lines patch added patch discarded remove patch
@@ -57,488 +57,488 @@
 block discarded – undo
57 57
  */
58 58
 interface IServerContainer extends IContainer {
59 59
 
60
-	/**
61
-	 * The calendar manager will act as a broker between consumers for calendar information and
62
-	 * providers which actual deliver the calendar information.
63
-	 *
64
-	 * @return \OCP\Calendar\IManager
65
-	 * @since 13.0.0
66
-	 */
67
-	public function getCalendarManager();
68
-
69
-	/**
70
-	 * The contacts manager will act as a broker between consumers for contacts information and
71
-	 * providers which actual deliver the contact information.
72
-	 *
73
-	 * @return \OCP\Contacts\IManager
74
-	 * @since 6.0.0
75
-	 */
76
-	public function getContactsManager();
77
-
78
-	/**
79
-	 * The current request object holding all information about the request currently being processed
80
-	 * is returned from this method.
81
-	 * In case the current execution was not initiated by a web request null is returned
82
-	 *
83
-	 * @return \OCP\IRequest
84
-	 * @since 6.0.0
85
-	 */
86
-	public function getRequest();
87
-
88
-	/**
89
-	 * Returns the preview manager which can create preview images for a given file
90
-	 *
91
-	 * @return \OCP\IPreview
92
-	 * @since 6.0.0
93
-	 */
94
-	public function getPreviewManager();
95
-
96
-	/**
97
-	 * Returns the tag manager which can get and set tags for different object types
98
-	 *
99
-	 * @see \OCP\ITagManager::load()
100
-	 * @return \OCP\ITagManager
101
-	 * @since 6.0.0
102
-	 */
103
-	public function getTagManager();
104
-
105
-	/**
106
-	 * Returns the root folder of ownCloud's data directory
107
-	 *
108
-	 * @return \OCP\Files\IRootFolder
109
-	 * @since 6.0.0 - between 6.0.0 and 8.0.0 this returned \OCP\Files\Folder
110
-	 */
111
-	public function getRootFolder();
112
-
113
-	/**
114
-	 * Returns a view to ownCloud's files folder
115
-	 *
116
-	 * @param string $userId user ID
117
-	 * @return \OCP\Files\Folder
118
-	 * @since 6.0.0 - parameter $userId was added in 8.0.0
119
-	 * @see getUserFolder in \OCP\Files\IRootFolder
120
-	 */
121
-	public function getUserFolder($userId = null);
122
-
123
-	/**
124
-	 * Returns an app-specific view in ownClouds data directory
125
-	 *
126
-	 * @return \OCP\Files\Folder
127
-	 * @since 6.0.0
128
-	 * @deprecated since 9.2.0 use IAppData
129
-	 */
130
-	public function getAppFolder();
131
-
132
-	/**
133
-	 * Returns a user manager
134
-	 *
135
-	 * @return \OCP\IUserManager
136
-	 * @since 8.0.0
137
-	 */
138
-	public function getUserManager();
139
-
140
-	/**
141
-	 * Returns a group manager
142
-	 *
143
-	 * @return \OCP\IGroupManager
144
-	 * @since 8.0.0
145
-	 */
146
-	public function getGroupManager();
147
-
148
-	/**
149
-	 * Returns the user session
150
-	 *
151
-	 * @return \OCP\IUserSession
152
-	 * @since 6.0.0
153
-	 */
154
-	public function getUserSession();
155
-
156
-	/**
157
-	 * Returns the navigation manager
158
-	 *
159
-	 * @return \OCP\INavigationManager
160
-	 * @since 6.0.0
161
-	 */
162
-	public function getNavigationManager();
163
-
164
-	/**
165
-	 * Returns the config manager
166
-	 *
167
-	 * @return \OCP\IConfig
168
-	 * @since 6.0.0
169
-	 */
170
-	public function getConfig();
171
-
172
-	/**
173
-	 * Returns a Crypto instance
174
-	 *
175
-	 * @return \OCP\Security\ICrypto
176
-	 * @since 8.0.0
177
-	 */
178
-	public function getCrypto();
179
-
180
-	/**
181
-	 * Returns a Hasher instance
182
-	 *
183
-	 * @return \OCP\Security\IHasher
184
-	 * @since 8.0.0
185
-	 */
186
-	public function getHasher();
187
-
188
-	/**
189
-	 * Returns a SecureRandom instance
190
-	 *
191
-	 * @return \OCP\Security\ISecureRandom
192
-	 * @since 8.1.0
193
-	 */
194
-	public function getSecureRandom();
195
-
196
-	/**
197
-	 * Returns a CredentialsManager instance
198
-	 *
199
-	 * @return \OCP\Security\ICredentialsManager
200
-	 * @since 9.0.0
201
-	 */
202
-	public function getCredentialsManager();
203
-
204
-	/**
205
-	 * Returns the app config manager
206
-	 *
207
-	 * @return \OCP\IAppConfig
208
-	 * @since 7.0.0
209
-	 */
210
-	public function getAppConfig();
211
-
212
-	/**
213
-	 * @return \OCP\L10N\IFactory
214
-	 * @since 8.2.0
215
-	 */
216
-	public function getL10NFactory();
217
-
218
-	/**
219
-	 * get an L10N instance
220
-	 * @param string $app appid
221
-	 * @param string $lang
222
-	 * @return \OCP\IL10N
223
-	 * @since 6.0.0 - parameter $lang was added in 8.0.0
224
-	 */
225
-	public function getL10N($app, $lang = null);
226
-
227
-	/**
228
-	 * @return \OC\Encryption\Manager
229
-	 * @since 8.1.0
230
-	 */
231
-	public function getEncryptionManager();
232
-
233
-	/**
234
-	 * @return \OC\Encryption\File
235
-	 * @since 8.1.0
236
-	 */
237
-	public function getEncryptionFilesHelper();
238
-
239
-	/**
240
-	 * @return \OCP\Encryption\Keys\IStorage
241
-	 * @since 8.1.0
242
-	 */
243
-	public function getEncryptionKeyStorage();
244
-
245
-	/**
246
-	 * Returns the URL generator
247
-	 *
248
-	 * @return \OCP\IURLGenerator
249
-	 * @since 6.0.0
250
-	 */
251
-	public function getURLGenerator();
252
-
253
-	/**
254
-	 * Returns the Helper
255
-	 *
256
-	 * @return \OCP\IHelper
257
-	 * @since 6.0.0
258
-	 */
259
-	public function getHelper();
260
-
261
-	/**
262
-	 * Returns an ICache instance
263
-	 *
264
-	 * @return \OCP\ICache
265
-	 * @since 6.0.0
266
-	 */
267
-	public function getCache();
268
-
269
-	/**
270
-	 * Returns an \OCP\CacheFactory instance
271
-	 *
272
-	 * @return \OCP\ICacheFactory
273
-	 * @since 7.0.0
274
-	 */
275
-	public function getMemCacheFactory();
276
-
277
-	/**
278
-	 * Returns the current session
279
-	 *
280
-	 * @return \OCP\ISession
281
-	 * @since 6.0.0
282
-	 */
283
-	public function getSession();
284
-
285
-	/**
286
-	 * Returns the activity manager
287
-	 *
288
-	 * @return \OCP\Activity\IManager
289
-	 * @since 6.0.0
290
-	 */
291
-	public function getActivityManager();
292
-
293
-	/**
294
-	 * Returns the current session
295
-	 *
296
-	 * @return \OCP\IDBConnection
297
-	 * @since 6.0.0
298
-	 */
299
-	public function getDatabaseConnection();
300
-
301
-	/**
302
-	 * Returns an avatar manager, used for avatar functionality
303
-	 *
304
-	 * @return \OCP\IAvatarManager
305
-	 * @since 6.0.0
306
-	 */
307
-	public function getAvatarManager();
308
-
309
-	/**
310
-	 * Returns an job list for controlling background jobs
311
-	 *
312
-	 * @return \OCP\BackgroundJob\IJobList
313
-	 * @since 7.0.0
314
-	 */
315
-	public function getJobList();
316
-
317
-	/**
318
-	 * Returns a logger instance
319
-	 *
320
-	 * @return \OCP\ILogger
321
-	 * @since 8.0.0
322
-	 */
323
-	public function getLogger();
324
-
325
-	/**
326
-	 * Returns a router for generating and matching urls
327
-	 *
328
-	 * @return \OCP\Route\IRouter
329
-	 * @since 7.0.0
330
-	 */
331
-	public function getRouter();
332
-
333
-	/**
334
-	 * Returns a search instance
335
-	 *
336
-	 * @return \OCP\ISearch
337
-	 * @since 7.0.0
338
-	 */
339
-	public function getSearch();
340
-
341
-	/**
342
-	 * Get the certificate manager for the user
343
-	 *
344
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
345
-	 * @return \OCP\ICertificateManager | null if $userId is null and no user is logged in
346
-	 * @since 8.0.0
347
-	 */
348
-	public function getCertificateManager($userId = null);
349
-
350
-	/**
351
-	 * Create a new event source
352
-	 *
353
-	 * @return \OCP\IEventSource
354
-	 * @since 8.0.0
355
-	 */
356
-	public function createEventSource();
357
-
358
-	/**
359
-	 * Returns an instance of the HTTP helper class
360
-	 * @return \OC\HTTPHelper
361
-	 * @deprecated 8.1.0 Use \OCP\Http\Client\IClientService
362
-	 * @since 8.0.0
363
-	 */
364
-	public function getHTTPHelper();
365
-
366
-	/**
367
-	 * Returns an instance of the HTTP client service
368
-	 *
369
-	 * @return \OCP\Http\Client\IClientService
370
-	 * @since 8.1.0
371
-	 */
372
-	public function getHTTPClientService();
373
-
374
-	/**
375
-	 * Get the active event logger
376
-	 *
377
-	 * @return \OCP\Diagnostics\IEventLogger
378
-	 * @since 8.0.0
379
-	 */
380
-	public function getEventLogger();
381
-
382
-	/**
383
-	 * Get the active query logger
384
-	 *
385
-	 * The returned logger only logs data when debug mode is enabled
386
-	 *
387
-	 * @return \OCP\Diagnostics\IQueryLogger
388
-	 * @since 8.0.0
389
-	 */
390
-	public function getQueryLogger();
391
-
392
-	/**
393
-	 * Get the manager for temporary files and folders
394
-	 *
395
-	 * @return \OCP\ITempManager
396
-	 * @since 8.0.0
397
-	 */
398
-	public function getTempManager();
399
-
400
-	/**
401
-	 * Get the app manager
402
-	 *
403
-	 * @return \OCP\App\IAppManager
404
-	 * @since 8.0.0
405
-	 */
406
-	public function getAppManager();
407
-
408
-	/**
409
-	 * Get the webroot
410
-	 *
411
-	 * @return string
412
-	 * @since 8.0.0
413
-	 */
414
-	public function getWebRoot();
415
-
416
-	/**
417
-	 * @return \OCP\Files\Config\IMountProviderCollection
418
-	 * @since 8.0.0
419
-	 */
420
-	public function getMountProviderCollection();
421
-
422
-	/**
423
-	 * Get the IniWrapper
424
-	 *
425
-	 * @return \bantu\IniGetWrapper\IniGetWrapper
426
-	 * @since 8.0.0
427
-	 */
428
-	public function getIniWrapper();
429
-	/**
430
-	 * @return \OCP\Command\IBus
431
-	 * @since 8.1.0
432
-	 */
433
-	public function getCommandBus();
434
-
435
-	/**
436
-	 * Creates a new mailer
437
-	 *
438
-	 * @return \OCP\Mail\IMailer
439
-	 * @since 8.1.0
440
-	 */
441
-	public function getMailer();
442
-
443
-	/**
444
-	 * Get the locking provider
445
-	 *
446
-	 * @return \OCP\Lock\ILockingProvider
447
-	 * @since 8.1.0
448
-	 */
449
-	public function getLockingProvider();
450
-
451
-	/**
452
-	 * @return \OCP\Files\Mount\IMountManager
453
-	 * @since 8.2.0
454
-	 */
455
-	public function getMountManager();
456
-
457
-	/**
458
-	 * Get the MimeTypeDetector
459
-	 *
460
-	 * @return \OCP\Files\IMimeTypeDetector
461
-	 * @since 8.2.0
462
-	 */
463
-	public function getMimeTypeDetector();
464
-
465
-	/**
466
-	 * Get the MimeTypeLoader
467
-	 *
468
-	 * @return \OCP\Files\IMimeTypeLoader
469
-	 * @since 8.2.0
470
-	 */
471
-	public function getMimeTypeLoader();
472
-
473
-	/**
474
-	 * Get the EventDispatcher
475
-	 *
476
-	 * @return EventDispatcherInterface
477
-	 * @since 8.2.0
478
-	 */
479
-	public function getEventDispatcher();
480
-
481
-	/**
482
-	 * Get the Notification Manager
483
-	 *
484
-	 * @return \OCP\Notification\IManager
485
-	 * @since 9.0.0
486
-	 */
487
-	public function getNotificationManager();
488
-
489
-	/**
490
-	 * @return \OCP\Comments\ICommentsManager
491
-	 * @since 9.0.0
492
-	 */
493
-	public function getCommentsManager();
494
-
495
-	/**
496
-	 * Returns the system-tag manager
497
-	 *
498
-	 * @return \OCP\SystemTag\ISystemTagManager
499
-	 *
500
-	 * @since 9.0.0
501
-	 */
502
-	public function getSystemTagManager();
503
-
504
-	/**
505
-	 * Returns the system-tag object mapper
506
-	 *
507
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
508
-	 *
509
-	 * @since 9.0.0
510
-	 */
511
-	public function getSystemTagObjectMapper();
512
-
513
-	/**
514
-	 * Returns the share manager
515
-	 *
516
-	 * @return \OCP\Share\IManager
517
-	 * @since 9.0.0
518
-	 */
519
-	public function getShareManager();
520
-
521
-	/**
522
-	 * @return IContentSecurityPolicyManager
523
-	 * @since 9.0.0
524
-	 */
525
-	public function getContentSecurityPolicyManager();
526
-
527
-	/**
528
-	 * @return \OCP\IDateTimeZone
529
-	 * @since 8.0.0
530
-	 */
531
-	public function getDateTimeZone();
532
-
533
-	/**
534
-	 * @return \OCP\IDateTimeFormatter
535
-	 * @since 8.0.0
536
-	 */
537
-	public function getDateTimeFormatter();
538
-
539
-	/**
540
-	 * @return \OCP\Federation\ICloudIdManager
541
-	 * @since 12.0.0
542
-	 */
543
-	public function getCloudIdManager();
60
+    /**
61
+     * The calendar manager will act as a broker between consumers for calendar information and
62
+     * providers which actual deliver the calendar information.
63
+     *
64
+     * @return \OCP\Calendar\IManager
65
+     * @since 13.0.0
66
+     */
67
+    public function getCalendarManager();
68
+
69
+    /**
70
+     * The contacts manager will act as a broker between consumers for contacts information and
71
+     * providers which actual deliver the contact information.
72
+     *
73
+     * @return \OCP\Contacts\IManager
74
+     * @since 6.0.0
75
+     */
76
+    public function getContactsManager();
77
+
78
+    /**
79
+     * The current request object holding all information about the request currently being processed
80
+     * is returned from this method.
81
+     * In case the current execution was not initiated by a web request null is returned
82
+     *
83
+     * @return \OCP\IRequest
84
+     * @since 6.0.0
85
+     */
86
+    public function getRequest();
87
+
88
+    /**
89
+     * Returns the preview manager which can create preview images for a given file
90
+     *
91
+     * @return \OCP\IPreview
92
+     * @since 6.0.0
93
+     */
94
+    public function getPreviewManager();
95
+
96
+    /**
97
+     * Returns the tag manager which can get and set tags for different object types
98
+     *
99
+     * @see \OCP\ITagManager::load()
100
+     * @return \OCP\ITagManager
101
+     * @since 6.0.0
102
+     */
103
+    public function getTagManager();
104
+
105
+    /**
106
+     * Returns the root folder of ownCloud's data directory
107
+     *
108
+     * @return \OCP\Files\IRootFolder
109
+     * @since 6.0.0 - between 6.0.0 and 8.0.0 this returned \OCP\Files\Folder
110
+     */
111
+    public function getRootFolder();
112
+
113
+    /**
114
+     * Returns a view to ownCloud's files folder
115
+     *
116
+     * @param string $userId user ID
117
+     * @return \OCP\Files\Folder
118
+     * @since 6.0.0 - parameter $userId was added in 8.0.0
119
+     * @see getUserFolder in \OCP\Files\IRootFolder
120
+     */
121
+    public function getUserFolder($userId = null);
122
+
123
+    /**
124
+     * Returns an app-specific view in ownClouds data directory
125
+     *
126
+     * @return \OCP\Files\Folder
127
+     * @since 6.0.0
128
+     * @deprecated since 9.2.0 use IAppData
129
+     */
130
+    public function getAppFolder();
131
+
132
+    /**
133
+     * Returns a user manager
134
+     *
135
+     * @return \OCP\IUserManager
136
+     * @since 8.0.0
137
+     */
138
+    public function getUserManager();
139
+
140
+    /**
141
+     * Returns a group manager
142
+     *
143
+     * @return \OCP\IGroupManager
144
+     * @since 8.0.0
145
+     */
146
+    public function getGroupManager();
147
+
148
+    /**
149
+     * Returns the user session
150
+     *
151
+     * @return \OCP\IUserSession
152
+     * @since 6.0.0
153
+     */
154
+    public function getUserSession();
155
+
156
+    /**
157
+     * Returns the navigation manager
158
+     *
159
+     * @return \OCP\INavigationManager
160
+     * @since 6.0.0
161
+     */
162
+    public function getNavigationManager();
163
+
164
+    /**
165
+     * Returns the config manager
166
+     *
167
+     * @return \OCP\IConfig
168
+     * @since 6.0.0
169
+     */
170
+    public function getConfig();
171
+
172
+    /**
173
+     * Returns a Crypto instance
174
+     *
175
+     * @return \OCP\Security\ICrypto
176
+     * @since 8.0.0
177
+     */
178
+    public function getCrypto();
179
+
180
+    /**
181
+     * Returns a Hasher instance
182
+     *
183
+     * @return \OCP\Security\IHasher
184
+     * @since 8.0.0
185
+     */
186
+    public function getHasher();
187
+
188
+    /**
189
+     * Returns a SecureRandom instance
190
+     *
191
+     * @return \OCP\Security\ISecureRandom
192
+     * @since 8.1.0
193
+     */
194
+    public function getSecureRandom();
195
+
196
+    /**
197
+     * Returns a CredentialsManager instance
198
+     *
199
+     * @return \OCP\Security\ICredentialsManager
200
+     * @since 9.0.0
201
+     */
202
+    public function getCredentialsManager();
203
+
204
+    /**
205
+     * Returns the app config manager
206
+     *
207
+     * @return \OCP\IAppConfig
208
+     * @since 7.0.0
209
+     */
210
+    public function getAppConfig();
211
+
212
+    /**
213
+     * @return \OCP\L10N\IFactory
214
+     * @since 8.2.0
215
+     */
216
+    public function getL10NFactory();
217
+
218
+    /**
219
+     * get an L10N instance
220
+     * @param string $app appid
221
+     * @param string $lang
222
+     * @return \OCP\IL10N
223
+     * @since 6.0.0 - parameter $lang was added in 8.0.0
224
+     */
225
+    public function getL10N($app, $lang = null);
226
+
227
+    /**
228
+     * @return \OC\Encryption\Manager
229
+     * @since 8.1.0
230
+     */
231
+    public function getEncryptionManager();
232
+
233
+    /**
234
+     * @return \OC\Encryption\File
235
+     * @since 8.1.0
236
+     */
237
+    public function getEncryptionFilesHelper();
238
+
239
+    /**
240
+     * @return \OCP\Encryption\Keys\IStorage
241
+     * @since 8.1.0
242
+     */
243
+    public function getEncryptionKeyStorage();
244
+
245
+    /**
246
+     * Returns the URL generator
247
+     *
248
+     * @return \OCP\IURLGenerator
249
+     * @since 6.0.0
250
+     */
251
+    public function getURLGenerator();
252
+
253
+    /**
254
+     * Returns the Helper
255
+     *
256
+     * @return \OCP\IHelper
257
+     * @since 6.0.0
258
+     */
259
+    public function getHelper();
260
+
261
+    /**
262
+     * Returns an ICache instance
263
+     *
264
+     * @return \OCP\ICache
265
+     * @since 6.0.0
266
+     */
267
+    public function getCache();
268
+
269
+    /**
270
+     * Returns an \OCP\CacheFactory instance
271
+     *
272
+     * @return \OCP\ICacheFactory
273
+     * @since 7.0.0
274
+     */
275
+    public function getMemCacheFactory();
276
+
277
+    /**
278
+     * Returns the current session
279
+     *
280
+     * @return \OCP\ISession
281
+     * @since 6.0.0
282
+     */
283
+    public function getSession();
284
+
285
+    /**
286
+     * Returns the activity manager
287
+     *
288
+     * @return \OCP\Activity\IManager
289
+     * @since 6.0.0
290
+     */
291
+    public function getActivityManager();
292
+
293
+    /**
294
+     * Returns the current session
295
+     *
296
+     * @return \OCP\IDBConnection
297
+     * @since 6.0.0
298
+     */
299
+    public function getDatabaseConnection();
300
+
301
+    /**
302
+     * Returns an avatar manager, used for avatar functionality
303
+     *
304
+     * @return \OCP\IAvatarManager
305
+     * @since 6.0.0
306
+     */
307
+    public function getAvatarManager();
308
+
309
+    /**
310
+     * Returns an job list for controlling background jobs
311
+     *
312
+     * @return \OCP\BackgroundJob\IJobList
313
+     * @since 7.0.0
314
+     */
315
+    public function getJobList();
316
+
317
+    /**
318
+     * Returns a logger instance
319
+     *
320
+     * @return \OCP\ILogger
321
+     * @since 8.0.0
322
+     */
323
+    public function getLogger();
324
+
325
+    /**
326
+     * Returns a router for generating and matching urls
327
+     *
328
+     * @return \OCP\Route\IRouter
329
+     * @since 7.0.0
330
+     */
331
+    public function getRouter();
332
+
333
+    /**
334
+     * Returns a search instance
335
+     *
336
+     * @return \OCP\ISearch
337
+     * @since 7.0.0
338
+     */
339
+    public function getSearch();
340
+
341
+    /**
342
+     * Get the certificate manager for the user
343
+     *
344
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
345
+     * @return \OCP\ICertificateManager | null if $userId is null and no user is logged in
346
+     * @since 8.0.0
347
+     */
348
+    public function getCertificateManager($userId = null);
349
+
350
+    /**
351
+     * Create a new event source
352
+     *
353
+     * @return \OCP\IEventSource
354
+     * @since 8.0.0
355
+     */
356
+    public function createEventSource();
357
+
358
+    /**
359
+     * Returns an instance of the HTTP helper class
360
+     * @return \OC\HTTPHelper
361
+     * @deprecated 8.1.0 Use \OCP\Http\Client\IClientService
362
+     * @since 8.0.0
363
+     */
364
+    public function getHTTPHelper();
365
+
366
+    /**
367
+     * Returns an instance of the HTTP client service
368
+     *
369
+     * @return \OCP\Http\Client\IClientService
370
+     * @since 8.1.0
371
+     */
372
+    public function getHTTPClientService();
373
+
374
+    /**
375
+     * Get the active event logger
376
+     *
377
+     * @return \OCP\Diagnostics\IEventLogger
378
+     * @since 8.0.0
379
+     */
380
+    public function getEventLogger();
381
+
382
+    /**
383
+     * Get the active query logger
384
+     *
385
+     * The returned logger only logs data when debug mode is enabled
386
+     *
387
+     * @return \OCP\Diagnostics\IQueryLogger
388
+     * @since 8.0.0
389
+     */
390
+    public function getQueryLogger();
391
+
392
+    /**
393
+     * Get the manager for temporary files and folders
394
+     *
395
+     * @return \OCP\ITempManager
396
+     * @since 8.0.0
397
+     */
398
+    public function getTempManager();
399
+
400
+    /**
401
+     * Get the app manager
402
+     *
403
+     * @return \OCP\App\IAppManager
404
+     * @since 8.0.0
405
+     */
406
+    public function getAppManager();
407
+
408
+    /**
409
+     * Get the webroot
410
+     *
411
+     * @return string
412
+     * @since 8.0.0
413
+     */
414
+    public function getWebRoot();
415
+
416
+    /**
417
+     * @return \OCP\Files\Config\IMountProviderCollection
418
+     * @since 8.0.0
419
+     */
420
+    public function getMountProviderCollection();
421
+
422
+    /**
423
+     * Get the IniWrapper
424
+     *
425
+     * @return \bantu\IniGetWrapper\IniGetWrapper
426
+     * @since 8.0.0
427
+     */
428
+    public function getIniWrapper();
429
+    /**
430
+     * @return \OCP\Command\IBus
431
+     * @since 8.1.0
432
+     */
433
+    public function getCommandBus();
434
+
435
+    /**
436
+     * Creates a new mailer
437
+     *
438
+     * @return \OCP\Mail\IMailer
439
+     * @since 8.1.0
440
+     */
441
+    public function getMailer();
442
+
443
+    /**
444
+     * Get the locking provider
445
+     *
446
+     * @return \OCP\Lock\ILockingProvider
447
+     * @since 8.1.0
448
+     */
449
+    public function getLockingProvider();
450
+
451
+    /**
452
+     * @return \OCP\Files\Mount\IMountManager
453
+     * @since 8.2.0
454
+     */
455
+    public function getMountManager();
456
+
457
+    /**
458
+     * Get the MimeTypeDetector
459
+     *
460
+     * @return \OCP\Files\IMimeTypeDetector
461
+     * @since 8.2.0
462
+     */
463
+    public function getMimeTypeDetector();
464
+
465
+    /**
466
+     * Get the MimeTypeLoader
467
+     *
468
+     * @return \OCP\Files\IMimeTypeLoader
469
+     * @since 8.2.0
470
+     */
471
+    public function getMimeTypeLoader();
472
+
473
+    /**
474
+     * Get the EventDispatcher
475
+     *
476
+     * @return EventDispatcherInterface
477
+     * @since 8.2.0
478
+     */
479
+    public function getEventDispatcher();
480
+
481
+    /**
482
+     * Get the Notification Manager
483
+     *
484
+     * @return \OCP\Notification\IManager
485
+     * @since 9.0.0
486
+     */
487
+    public function getNotificationManager();
488
+
489
+    /**
490
+     * @return \OCP\Comments\ICommentsManager
491
+     * @since 9.0.0
492
+     */
493
+    public function getCommentsManager();
494
+
495
+    /**
496
+     * Returns the system-tag manager
497
+     *
498
+     * @return \OCP\SystemTag\ISystemTagManager
499
+     *
500
+     * @since 9.0.0
501
+     */
502
+    public function getSystemTagManager();
503
+
504
+    /**
505
+     * Returns the system-tag object mapper
506
+     *
507
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
508
+     *
509
+     * @since 9.0.0
510
+     */
511
+    public function getSystemTagObjectMapper();
512
+
513
+    /**
514
+     * Returns the share manager
515
+     *
516
+     * @return \OCP\Share\IManager
517
+     * @since 9.0.0
518
+     */
519
+    public function getShareManager();
520
+
521
+    /**
522
+     * @return IContentSecurityPolicyManager
523
+     * @since 9.0.0
524
+     */
525
+    public function getContentSecurityPolicyManager();
526
+
527
+    /**
528
+     * @return \OCP\IDateTimeZone
529
+     * @since 8.0.0
530
+     */
531
+    public function getDateTimeZone();
532
+
533
+    /**
534
+     * @return \OCP\IDateTimeFormatter
535
+     * @since 8.0.0
536
+     */
537
+    public function getDateTimeFormatter();
538
+
539
+    /**
540
+     * @return \OCP\Federation\ICloudIdManager
541
+     * @since 12.0.0
542
+     */
543
+    public function getCloudIdManager();
544 544
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/CalDavBackend.php 3 patches
Unused Use Statements   -2 removed lines patch added patch discarded remove patch
@@ -50,10 +50,8 @@
 block discarded – undo
50 50
 use Sabre\DAV\Exception\Forbidden;
51 51
 use Sabre\DAV\Exception\NotFound;
52 52
 use Sabre\DAV\PropPatch;
53
-use Sabre\HTTP\URLUtil;
54 53
 use Sabre\VObject\Component;
55 54
 use Sabre\VObject\Component\VCalendar;
56
-use Sabre\VObject\Component\VEvent;
57 55
 use Sabre\VObject\Component\VTimeZone;
58 56
 use Sabre\VObject\DateTimeParser;
59 57
 use Sabre\VObject\Property;
Please login to merge, or discard this patch.
Indentation   +2241 added lines, -2241 removed lines patch added patch discarded remove patch
@@ -72,2246 +72,2246 @@
 block discarded – undo
72 72
  */
73 73
 class CalDavBackend extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport {
74 74
 
75
-	const PERSONAL_CALENDAR_URI = 'personal';
76
-	const PERSONAL_CALENDAR_NAME = 'Personal';
77
-
78
-	/**
79
-	 * We need to specify a max date, because we need to stop *somewhere*
80
-	 *
81
-	 * On 32 bit system the maximum for a signed integer is 2147483647, so
82
-	 * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
83
-	 * in 2038-01-19 to avoid problems when the date is converted
84
-	 * to a unix timestamp.
85
-	 */
86
-	const MAX_DATE = '2038-01-01';
87
-
88
-	const ACCESS_PUBLIC = 4;
89
-	const CLASSIFICATION_PUBLIC = 0;
90
-	const CLASSIFICATION_PRIVATE = 1;
91
-	const CLASSIFICATION_CONFIDENTIAL = 2;
92
-
93
-	/**
94
-	 * List of CalDAV properties, and how they map to database field names
95
-	 * Add your own properties by simply adding on to this array.
96
-	 *
97
-	 * Note that only string-based properties are supported here.
98
-	 *
99
-	 * @var array
100
-	 */
101
-	public $propertyMap = [
102
-		'{DAV:}displayname'                          => 'displayname',
103
-		'{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
104
-		'{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
105
-		'{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
106
-		'{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
107
-	];
108
-
109
-	/**
110
-	 * List of subscription properties, and how they map to database field names.
111
-	 *
112
-	 * @var array
113
-	 */
114
-	public $subscriptionPropertyMap = [
115
-		'{DAV:}displayname'                                           => 'displayname',
116
-		'{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
117
-		'{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
118
-		'{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
119
-		'{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
120
-		'{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
121
-		'{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
122
-	];
123
-
124
-	/** @var array properties to index */
125
-	public static $indexProperties = ['CATEGORIES', 'COMMENT', 'DESCRIPTION',
126
-		'LOCATION', 'RESOURCES', 'STATUS', 'SUMMARY', 'ATTENDEE', 'CONTACT',
127
-		'ORGANIZER'];
128
-
129
-	/** @var array parameters to index */
130
-	public static $indexParameters = [
131
-		'ATTENDEE' => ['CN'],
132
-		'ORGANIZER' => ['CN'],
133
-	];
134
-
135
-	/**
136
-	 * @var string[] Map of uid => display name
137
-	 */
138
-	protected $userDisplayNames;
139
-
140
-	/** @var IDBConnection */
141
-	private $db;
142
-
143
-	/** @var Backend */
144
-	private $sharingBackend;
145
-
146
-	/** @var Principal */
147
-	private $principalBackend;
148
-
149
-	/** @var IUserManager */
150
-	private $userManager;
151
-
152
-	/** @var ISecureRandom */
153
-	private $random;
154
-
155
-	/** @var EventDispatcherInterface */
156
-	private $dispatcher;
157
-
158
-	/** @var bool */
159
-	private $legacyEndpoint;
160
-
161
-	/** @var string */
162
-	private $dbObjectPropertiesTable = 'calendarobjects_props';
163
-
164
-	/**
165
-	 * CalDavBackend constructor.
166
-	 *
167
-	 * @param IDBConnection $db
168
-	 * @param Principal $principalBackend
169
-	 * @param IUserManager $userManager
170
-	 * @param IGroupManager $groupManager
171
-	 * @param ISecureRandom $random
172
-	 * @param EventDispatcherInterface $dispatcher
173
-	 * @param bool $legacyEndpoint
174
-	 */
175
-	public function __construct(IDBConnection $db,
176
-								Principal $principalBackend,
177
-								IUserManager $userManager,
178
-								IGroupManager $groupManager,
179
-								ISecureRandom $random,
180
-								EventDispatcherInterface $dispatcher,
181
-								$legacyEndpoint = false) {
182
-		$this->db = $db;
183
-		$this->principalBackend = $principalBackend;
184
-		$this->userManager = $userManager;
185
-		$this->sharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'calendar');
186
-		$this->random = $random;
187
-		$this->dispatcher = $dispatcher;
188
-		$this->legacyEndpoint = $legacyEndpoint;
189
-	}
190
-
191
-	/**
192
-	 * Return the number of calendars for a principal
193
-	 *
194
-	 * By default this excludes the automatically generated birthday calendar
195
-	 *
196
-	 * @param $principalUri
197
-	 * @param bool $excludeBirthday
198
-	 * @return int
199
-	 */
200
-	public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
201
-		$principalUri = $this->convertPrincipal($principalUri, true);
202
-		$query = $this->db->getQueryBuilder();
203
-		$query->select($query->createFunction('COUNT(*)'))
204
-			->from('calendars')
205
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
206
-
207
-		if ($excludeBirthday) {
208
-			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
209
-		}
210
-
211
-		return (int)$query->execute()->fetchColumn();
212
-	}
213
-
214
-	/**
215
-	 * Returns a list of calendars for a principal.
216
-	 *
217
-	 * Every project is an array with the following keys:
218
-	 *  * id, a unique id that will be used by other functions to modify the
219
-	 *    calendar. This can be the same as the uri or a database key.
220
-	 *  * uri, which the basename of the uri with which the calendar is
221
-	 *    accessed.
222
-	 *  * principaluri. The owner of the calendar. Almost always the same as
223
-	 *    principalUri passed to this method.
224
-	 *
225
-	 * Furthermore it can contain webdav properties in clark notation. A very
226
-	 * common one is '{DAV:}displayname'.
227
-	 *
228
-	 * Many clients also require:
229
-	 * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
230
-	 * For this property, you can just return an instance of
231
-	 * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
232
-	 *
233
-	 * If you return {http://sabredav.org/ns}read-only and set the value to 1,
234
-	 * ACL will automatically be put in read-only mode.
235
-	 *
236
-	 * @param string $principalUri
237
-	 * @return array
238
-	 */
239
-	function getCalendarsForUser($principalUri) {
240
-		$principalUriOriginal = $principalUri;
241
-		$principalUri = $this->convertPrincipal($principalUri, true);
242
-		$fields = array_values($this->propertyMap);
243
-		$fields[] = 'id';
244
-		$fields[] = 'uri';
245
-		$fields[] = 'synctoken';
246
-		$fields[] = 'components';
247
-		$fields[] = 'principaluri';
248
-		$fields[] = 'transparent';
249
-
250
-		// Making fields a comma-delimited list
251
-		$query = $this->db->getQueryBuilder();
252
-		$query->select($fields)->from('calendars')
253
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
254
-				->orderBy('calendarorder', 'ASC');
255
-		$stmt = $query->execute();
256
-
257
-		$calendars = [];
258
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
259
-
260
-			$components = [];
261
-			if ($row['components']) {
262
-				$components = explode(',',$row['components']);
263
-			}
264
-
265
-			$calendar = [
266
-				'id' => $row['id'],
267
-				'uri' => $row['uri'],
268
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
269
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
270
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
271
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
272
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
273
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
274
-			];
275
-
276
-			foreach($this->propertyMap as $xmlName=>$dbName) {
277
-				$calendar[$xmlName] = $row[$dbName];
278
-			}
279
-
280
-			$this->addOwnerPrincipal($calendar);
281
-
282
-			if (!isset($calendars[$calendar['id']])) {
283
-				$calendars[$calendar['id']] = $calendar;
284
-			}
285
-		}
286
-
287
-		$stmt->closeCursor();
288
-
289
-		// query for shared calendars
290
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
291
-		$principals = array_map(function($principal) {
292
-			return urldecode($principal);
293
-		}, $principals);
294
-		$principals[]= $principalUri;
295
-
296
-		$fields = array_values($this->propertyMap);
297
-		$fields[] = 'a.id';
298
-		$fields[] = 'a.uri';
299
-		$fields[] = 'a.synctoken';
300
-		$fields[] = 'a.components';
301
-		$fields[] = 'a.principaluri';
302
-		$fields[] = 'a.transparent';
303
-		$fields[] = 's.access';
304
-		$query = $this->db->getQueryBuilder();
305
-		$result = $query->select($fields)
306
-			->from('dav_shares', 's')
307
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
308
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
309
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
310
-			->setParameter('type', 'calendar')
311
-			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
312
-			->execute();
313
-
314
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
315
-		while($row = $result->fetch()) {
316
-			if ($row['principaluri'] === $principalUri) {
317
-				continue;
318
-			}
319
-
320
-			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
321
-			if (isset($calendars[$row['id']])) {
322
-				if ($readOnly) {
323
-					// New share can not have more permissions then the old one.
324
-					continue;
325
-				}
326
-				if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
327
-					$calendars[$row['id']][$readOnlyPropertyName] === 0) {
328
-					// Old share is already read-write, no more permissions can be gained
329
-					continue;
330
-				}
331
-			}
332
-
333
-			list(, $name) = Uri\split($row['principaluri']);
334
-			$uri = $row['uri'] . '_shared_by_' . $name;
335
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
336
-			$components = [];
337
-			if ($row['components']) {
338
-				$components = explode(',',$row['components']);
339
-			}
340
-			$calendar = [
341
-				'id' => $row['id'],
342
-				'uri' => $uri,
343
-				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
344
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
345
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
346
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
347
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
348
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
349
-				$readOnlyPropertyName => $readOnly,
350
-			];
351
-
352
-			foreach($this->propertyMap as $xmlName=>$dbName) {
353
-				$calendar[$xmlName] = $row[$dbName];
354
-			}
355
-
356
-			$this->addOwnerPrincipal($calendar);
357
-
358
-			$calendars[$calendar['id']] = $calendar;
359
-		}
360
-		$result->closeCursor();
361
-
362
-		return array_values($calendars);
363
-	}
364
-
365
-	public function getUsersOwnCalendars($principalUri) {
366
-		$principalUri = $this->convertPrincipal($principalUri, true);
367
-		$fields = array_values($this->propertyMap);
368
-		$fields[] = 'id';
369
-		$fields[] = 'uri';
370
-		$fields[] = 'synctoken';
371
-		$fields[] = 'components';
372
-		$fields[] = 'principaluri';
373
-		$fields[] = 'transparent';
374
-		// Making fields a comma-delimited list
375
-		$query = $this->db->getQueryBuilder();
376
-		$query->select($fields)->from('calendars')
377
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
378
-			->orderBy('calendarorder', 'ASC');
379
-		$stmt = $query->execute();
380
-		$calendars = [];
381
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
382
-			$components = [];
383
-			if ($row['components']) {
384
-				$components = explode(',',$row['components']);
385
-			}
386
-			$calendar = [
387
-				'id' => $row['id'],
388
-				'uri' => $row['uri'],
389
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
390
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
391
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
392
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
393
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
394
-			];
395
-			foreach($this->propertyMap as $xmlName=>$dbName) {
396
-				$calendar[$xmlName] = $row[$dbName];
397
-			}
398
-
399
-			$this->addOwnerPrincipal($calendar);
400
-
401
-			if (!isset($calendars[$calendar['id']])) {
402
-				$calendars[$calendar['id']] = $calendar;
403
-			}
404
-		}
405
-		$stmt->closeCursor();
406
-		return array_values($calendars);
407
-	}
408
-
409
-
410
-	private function getUserDisplayName($uid) {
411
-		if (!isset($this->userDisplayNames[$uid])) {
412
-			$user = $this->userManager->get($uid);
413
-
414
-			if ($user instanceof IUser) {
415
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
416
-			} else {
417
-				$this->userDisplayNames[$uid] = $uid;
418
-			}
419
-		}
420
-
421
-		return $this->userDisplayNames[$uid];
422
-	}
75
+    const PERSONAL_CALENDAR_URI = 'personal';
76
+    const PERSONAL_CALENDAR_NAME = 'Personal';
77
+
78
+    /**
79
+     * We need to specify a max date, because we need to stop *somewhere*
80
+     *
81
+     * On 32 bit system the maximum for a signed integer is 2147483647, so
82
+     * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
83
+     * in 2038-01-19 to avoid problems when the date is converted
84
+     * to a unix timestamp.
85
+     */
86
+    const MAX_DATE = '2038-01-01';
87
+
88
+    const ACCESS_PUBLIC = 4;
89
+    const CLASSIFICATION_PUBLIC = 0;
90
+    const CLASSIFICATION_PRIVATE = 1;
91
+    const CLASSIFICATION_CONFIDENTIAL = 2;
92
+
93
+    /**
94
+     * List of CalDAV properties, and how they map to database field names
95
+     * Add your own properties by simply adding on to this array.
96
+     *
97
+     * Note that only string-based properties are supported here.
98
+     *
99
+     * @var array
100
+     */
101
+    public $propertyMap = [
102
+        '{DAV:}displayname'                          => 'displayname',
103
+        '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
104
+        '{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
105
+        '{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
106
+        '{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
107
+    ];
108
+
109
+    /**
110
+     * List of subscription properties, and how they map to database field names.
111
+     *
112
+     * @var array
113
+     */
114
+    public $subscriptionPropertyMap = [
115
+        '{DAV:}displayname'                                           => 'displayname',
116
+        '{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
117
+        '{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
118
+        '{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
119
+        '{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
120
+        '{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
121
+        '{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
122
+    ];
123
+
124
+    /** @var array properties to index */
125
+    public static $indexProperties = ['CATEGORIES', 'COMMENT', 'DESCRIPTION',
126
+        'LOCATION', 'RESOURCES', 'STATUS', 'SUMMARY', 'ATTENDEE', 'CONTACT',
127
+        'ORGANIZER'];
128
+
129
+    /** @var array parameters to index */
130
+    public static $indexParameters = [
131
+        'ATTENDEE' => ['CN'],
132
+        'ORGANIZER' => ['CN'],
133
+    ];
134
+
135
+    /**
136
+     * @var string[] Map of uid => display name
137
+     */
138
+    protected $userDisplayNames;
139
+
140
+    /** @var IDBConnection */
141
+    private $db;
142
+
143
+    /** @var Backend */
144
+    private $sharingBackend;
145
+
146
+    /** @var Principal */
147
+    private $principalBackend;
148
+
149
+    /** @var IUserManager */
150
+    private $userManager;
151
+
152
+    /** @var ISecureRandom */
153
+    private $random;
154
+
155
+    /** @var EventDispatcherInterface */
156
+    private $dispatcher;
157
+
158
+    /** @var bool */
159
+    private $legacyEndpoint;
160
+
161
+    /** @var string */
162
+    private $dbObjectPropertiesTable = 'calendarobjects_props';
163
+
164
+    /**
165
+     * CalDavBackend constructor.
166
+     *
167
+     * @param IDBConnection $db
168
+     * @param Principal $principalBackend
169
+     * @param IUserManager $userManager
170
+     * @param IGroupManager $groupManager
171
+     * @param ISecureRandom $random
172
+     * @param EventDispatcherInterface $dispatcher
173
+     * @param bool $legacyEndpoint
174
+     */
175
+    public function __construct(IDBConnection $db,
176
+                                Principal $principalBackend,
177
+                                IUserManager $userManager,
178
+                                IGroupManager $groupManager,
179
+                                ISecureRandom $random,
180
+                                EventDispatcherInterface $dispatcher,
181
+                                $legacyEndpoint = false) {
182
+        $this->db = $db;
183
+        $this->principalBackend = $principalBackend;
184
+        $this->userManager = $userManager;
185
+        $this->sharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'calendar');
186
+        $this->random = $random;
187
+        $this->dispatcher = $dispatcher;
188
+        $this->legacyEndpoint = $legacyEndpoint;
189
+    }
190
+
191
+    /**
192
+     * Return the number of calendars for a principal
193
+     *
194
+     * By default this excludes the automatically generated birthday calendar
195
+     *
196
+     * @param $principalUri
197
+     * @param bool $excludeBirthday
198
+     * @return int
199
+     */
200
+    public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
201
+        $principalUri = $this->convertPrincipal($principalUri, true);
202
+        $query = $this->db->getQueryBuilder();
203
+        $query->select($query->createFunction('COUNT(*)'))
204
+            ->from('calendars')
205
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
206
+
207
+        if ($excludeBirthday) {
208
+            $query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
209
+        }
210
+
211
+        return (int)$query->execute()->fetchColumn();
212
+    }
213
+
214
+    /**
215
+     * Returns a list of calendars for a principal.
216
+     *
217
+     * Every project is an array with the following keys:
218
+     *  * id, a unique id that will be used by other functions to modify the
219
+     *    calendar. This can be the same as the uri or a database key.
220
+     *  * uri, which the basename of the uri with which the calendar is
221
+     *    accessed.
222
+     *  * principaluri. The owner of the calendar. Almost always the same as
223
+     *    principalUri passed to this method.
224
+     *
225
+     * Furthermore it can contain webdav properties in clark notation. A very
226
+     * common one is '{DAV:}displayname'.
227
+     *
228
+     * Many clients also require:
229
+     * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
230
+     * For this property, you can just return an instance of
231
+     * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
232
+     *
233
+     * If you return {http://sabredav.org/ns}read-only and set the value to 1,
234
+     * ACL will automatically be put in read-only mode.
235
+     *
236
+     * @param string $principalUri
237
+     * @return array
238
+     */
239
+    function getCalendarsForUser($principalUri) {
240
+        $principalUriOriginal = $principalUri;
241
+        $principalUri = $this->convertPrincipal($principalUri, true);
242
+        $fields = array_values($this->propertyMap);
243
+        $fields[] = 'id';
244
+        $fields[] = 'uri';
245
+        $fields[] = 'synctoken';
246
+        $fields[] = 'components';
247
+        $fields[] = 'principaluri';
248
+        $fields[] = 'transparent';
249
+
250
+        // Making fields a comma-delimited list
251
+        $query = $this->db->getQueryBuilder();
252
+        $query->select($fields)->from('calendars')
253
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
254
+                ->orderBy('calendarorder', 'ASC');
255
+        $stmt = $query->execute();
256
+
257
+        $calendars = [];
258
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
259
+
260
+            $components = [];
261
+            if ($row['components']) {
262
+                $components = explode(',',$row['components']);
263
+            }
264
+
265
+            $calendar = [
266
+                'id' => $row['id'],
267
+                'uri' => $row['uri'],
268
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
269
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
270
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
271
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
272
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
273
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
274
+            ];
275
+
276
+            foreach($this->propertyMap as $xmlName=>$dbName) {
277
+                $calendar[$xmlName] = $row[$dbName];
278
+            }
279
+
280
+            $this->addOwnerPrincipal($calendar);
281
+
282
+            if (!isset($calendars[$calendar['id']])) {
283
+                $calendars[$calendar['id']] = $calendar;
284
+            }
285
+        }
286
+
287
+        $stmt->closeCursor();
288
+
289
+        // query for shared calendars
290
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
291
+        $principals = array_map(function($principal) {
292
+            return urldecode($principal);
293
+        }, $principals);
294
+        $principals[]= $principalUri;
295
+
296
+        $fields = array_values($this->propertyMap);
297
+        $fields[] = 'a.id';
298
+        $fields[] = 'a.uri';
299
+        $fields[] = 'a.synctoken';
300
+        $fields[] = 'a.components';
301
+        $fields[] = 'a.principaluri';
302
+        $fields[] = 'a.transparent';
303
+        $fields[] = 's.access';
304
+        $query = $this->db->getQueryBuilder();
305
+        $result = $query->select($fields)
306
+            ->from('dav_shares', 's')
307
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
308
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
309
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
310
+            ->setParameter('type', 'calendar')
311
+            ->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
312
+            ->execute();
313
+
314
+        $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
315
+        while($row = $result->fetch()) {
316
+            if ($row['principaluri'] === $principalUri) {
317
+                continue;
318
+            }
319
+
320
+            $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
321
+            if (isset($calendars[$row['id']])) {
322
+                if ($readOnly) {
323
+                    // New share can not have more permissions then the old one.
324
+                    continue;
325
+                }
326
+                if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
327
+                    $calendars[$row['id']][$readOnlyPropertyName] === 0) {
328
+                    // Old share is already read-write, no more permissions can be gained
329
+                    continue;
330
+                }
331
+            }
332
+
333
+            list(, $name) = Uri\split($row['principaluri']);
334
+            $uri = $row['uri'] . '_shared_by_' . $name;
335
+            $row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
336
+            $components = [];
337
+            if ($row['components']) {
338
+                $components = explode(',',$row['components']);
339
+            }
340
+            $calendar = [
341
+                'id' => $row['id'],
342
+                'uri' => $uri,
343
+                'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
344
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
345
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
346
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
347
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
348
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
349
+                $readOnlyPropertyName => $readOnly,
350
+            ];
351
+
352
+            foreach($this->propertyMap as $xmlName=>$dbName) {
353
+                $calendar[$xmlName] = $row[$dbName];
354
+            }
355
+
356
+            $this->addOwnerPrincipal($calendar);
357
+
358
+            $calendars[$calendar['id']] = $calendar;
359
+        }
360
+        $result->closeCursor();
361
+
362
+        return array_values($calendars);
363
+    }
364
+
365
+    public function getUsersOwnCalendars($principalUri) {
366
+        $principalUri = $this->convertPrincipal($principalUri, true);
367
+        $fields = array_values($this->propertyMap);
368
+        $fields[] = 'id';
369
+        $fields[] = 'uri';
370
+        $fields[] = 'synctoken';
371
+        $fields[] = 'components';
372
+        $fields[] = 'principaluri';
373
+        $fields[] = 'transparent';
374
+        // Making fields a comma-delimited list
375
+        $query = $this->db->getQueryBuilder();
376
+        $query->select($fields)->from('calendars')
377
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
378
+            ->orderBy('calendarorder', 'ASC');
379
+        $stmt = $query->execute();
380
+        $calendars = [];
381
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
382
+            $components = [];
383
+            if ($row['components']) {
384
+                $components = explode(',',$row['components']);
385
+            }
386
+            $calendar = [
387
+                'id' => $row['id'],
388
+                'uri' => $row['uri'],
389
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
390
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
391
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
392
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
393
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
394
+            ];
395
+            foreach($this->propertyMap as $xmlName=>$dbName) {
396
+                $calendar[$xmlName] = $row[$dbName];
397
+            }
398
+
399
+            $this->addOwnerPrincipal($calendar);
400
+
401
+            if (!isset($calendars[$calendar['id']])) {
402
+                $calendars[$calendar['id']] = $calendar;
403
+            }
404
+        }
405
+        $stmt->closeCursor();
406
+        return array_values($calendars);
407
+    }
408
+
409
+
410
+    private function getUserDisplayName($uid) {
411
+        if (!isset($this->userDisplayNames[$uid])) {
412
+            $user = $this->userManager->get($uid);
413
+
414
+            if ($user instanceof IUser) {
415
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
416
+            } else {
417
+                $this->userDisplayNames[$uid] = $uid;
418
+            }
419
+        }
420
+
421
+        return $this->userDisplayNames[$uid];
422
+    }
423 423
 	
424
-	/**
425
-	 * @return array
426
-	 */
427
-	public function getPublicCalendars() {
428
-		$fields = array_values($this->propertyMap);
429
-		$fields[] = 'a.id';
430
-		$fields[] = 'a.uri';
431
-		$fields[] = 'a.synctoken';
432
-		$fields[] = 'a.components';
433
-		$fields[] = 'a.principaluri';
434
-		$fields[] = 'a.transparent';
435
-		$fields[] = 's.access';
436
-		$fields[] = 's.publicuri';
437
-		$calendars = [];
438
-		$query = $this->db->getQueryBuilder();
439
-		$result = $query->select($fields)
440
-			->from('dav_shares', 's')
441
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
442
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
443
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
444
-			->execute();
445
-
446
-		while($row = $result->fetch()) {
447
-			list(, $name) = Uri\split($row['principaluri']);
448
-			$row['displayname'] = $row['displayname'] . "($name)";
449
-			$components = [];
450
-			if ($row['components']) {
451
-				$components = explode(',',$row['components']);
452
-			}
453
-			$calendar = [
454
-				'id' => $row['id'],
455
-				'uri' => $row['publicuri'],
456
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
457
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
458
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
459
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
460
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
461
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
462
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
463
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
464
-			];
465
-
466
-			foreach($this->propertyMap as $xmlName=>$dbName) {
467
-				$calendar[$xmlName] = $row[$dbName];
468
-			}
469
-
470
-			$this->addOwnerPrincipal($calendar);
471
-
472
-			if (!isset($calendars[$calendar['id']])) {
473
-				$calendars[$calendar['id']] = $calendar;
474
-			}
475
-		}
476
-		$result->closeCursor();
477
-
478
-		return array_values($calendars);
479
-	}
480
-
481
-	/**
482
-	 * @param string $uri
483
-	 * @return array
484
-	 * @throws NotFound
485
-	 */
486
-	public function getPublicCalendar($uri) {
487
-		$fields = array_values($this->propertyMap);
488
-		$fields[] = 'a.id';
489
-		$fields[] = 'a.uri';
490
-		$fields[] = 'a.synctoken';
491
-		$fields[] = 'a.components';
492
-		$fields[] = 'a.principaluri';
493
-		$fields[] = 'a.transparent';
494
-		$fields[] = 's.access';
495
-		$fields[] = 's.publicuri';
496
-		$query = $this->db->getQueryBuilder();
497
-		$result = $query->select($fields)
498
-			->from('dav_shares', 's')
499
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
500
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
501
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
502
-			->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
503
-			->execute();
504
-
505
-		$row = $result->fetch(\PDO::FETCH_ASSOC);
506
-
507
-		$result->closeCursor();
508
-
509
-		if ($row === false) {
510
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
511
-		}
512
-
513
-		list(, $name) = Uri\split($row['principaluri']);
514
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
515
-		$components = [];
516
-		if ($row['components']) {
517
-			$components = explode(',',$row['components']);
518
-		}
519
-		$calendar = [
520
-			'id' => $row['id'],
521
-			'uri' => $row['publicuri'],
522
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
523
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
524
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
525
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
526
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
527
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
528
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
529
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
530
-		];
531
-
532
-		foreach($this->propertyMap as $xmlName=>$dbName) {
533
-			$calendar[$xmlName] = $row[$dbName];
534
-		}
535
-
536
-		$this->addOwnerPrincipal($calendar);
537
-
538
-		return $calendar;
539
-
540
-	}
541
-
542
-	/**
543
-	 * @param string $principal
544
-	 * @param string $uri
545
-	 * @return array|null
546
-	 */
547
-	public function getCalendarByUri($principal, $uri) {
548
-		$fields = array_values($this->propertyMap);
549
-		$fields[] = 'id';
550
-		$fields[] = 'uri';
551
-		$fields[] = 'synctoken';
552
-		$fields[] = 'components';
553
-		$fields[] = 'principaluri';
554
-		$fields[] = 'transparent';
555
-
556
-		// Making fields a comma-delimited list
557
-		$query = $this->db->getQueryBuilder();
558
-		$query->select($fields)->from('calendars')
559
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
560
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
561
-			->setMaxResults(1);
562
-		$stmt = $query->execute();
563
-
564
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
565
-		$stmt->closeCursor();
566
-		if ($row === false) {
567
-			return null;
568
-		}
569
-
570
-		$components = [];
571
-		if ($row['components']) {
572
-			$components = explode(',',$row['components']);
573
-		}
574
-
575
-		$calendar = [
576
-			'id' => $row['id'],
577
-			'uri' => $row['uri'],
578
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
579
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
580
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
581
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
582
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
583
-		];
584
-
585
-		foreach($this->propertyMap as $xmlName=>$dbName) {
586
-			$calendar[$xmlName] = $row[$dbName];
587
-		}
588
-
589
-		$this->addOwnerPrincipal($calendar);
590
-
591
-		return $calendar;
592
-	}
593
-
594
-	public function getCalendarById($calendarId) {
595
-		$fields = array_values($this->propertyMap);
596
-		$fields[] = 'id';
597
-		$fields[] = 'uri';
598
-		$fields[] = 'synctoken';
599
-		$fields[] = 'components';
600
-		$fields[] = 'principaluri';
601
-		$fields[] = 'transparent';
602
-
603
-		// Making fields a comma-delimited list
604
-		$query = $this->db->getQueryBuilder();
605
-		$query->select($fields)->from('calendars')
606
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
607
-			->setMaxResults(1);
608
-		$stmt = $query->execute();
609
-
610
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
611
-		$stmt->closeCursor();
612
-		if ($row === false) {
613
-			return null;
614
-		}
615
-
616
-		$components = [];
617
-		if ($row['components']) {
618
-			$components = explode(',',$row['components']);
619
-		}
620
-
621
-		$calendar = [
622
-			'id' => $row['id'],
623
-			'uri' => $row['uri'],
624
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
625
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
626
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
627
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
628
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
629
-		];
630
-
631
-		foreach($this->propertyMap as $xmlName=>$dbName) {
632
-			$calendar[$xmlName] = $row[$dbName];
633
-		}
634
-
635
-		$this->addOwnerPrincipal($calendar);
636
-
637
-		return $calendar;
638
-	}
639
-
640
-	/**
641
-	 * Creates a new calendar for a principal.
642
-	 *
643
-	 * If the creation was a success, an id must be returned that can be used to reference
644
-	 * this calendar in other methods, such as updateCalendar.
645
-	 *
646
-	 * @param string $principalUri
647
-	 * @param string $calendarUri
648
-	 * @param array $properties
649
-	 * @return int
650
-	 * @suppress SqlInjectionChecker
651
-	 */
652
-	function createCalendar($principalUri, $calendarUri, array $properties) {
653
-		$values = [
654
-			'principaluri' => $this->convertPrincipal($principalUri, true),
655
-			'uri'          => $calendarUri,
656
-			'synctoken'    => 1,
657
-			'transparent'  => 0,
658
-			'components'   => 'VEVENT,VTODO',
659
-			'displayname'  => $calendarUri
660
-		];
661
-
662
-		// Default value
663
-		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
664
-		if (isset($properties[$sccs])) {
665
-			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
666
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
667
-			}
668
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
669
-		}
670
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
671
-		if (isset($properties[$transp])) {
672
-			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
673
-		}
674
-
675
-		foreach($this->propertyMap as $xmlName=>$dbName) {
676
-			if (isset($properties[$xmlName])) {
677
-				$values[$dbName] = $properties[$xmlName];
678
-			}
679
-		}
680
-
681
-		$query = $this->db->getQueryBuilder();
682
-		$query->insert('calendars');
683
-		foreach($values as $column => $value) {
684
-			$query->setValue($column, $query->createNamedParameter($value));
685
-		}
686
-		$query->execute();
687
-		$calendarId = $query->getLastInsertId();
688
-
689
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
690
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
691
-			[
692
-				'calendarId' => $calendarId,
693
-				'calendarData' => $this->getCalendarById($calendarId),
694
-		]));
695
-
696
-		return $calendarId;
697
-	}
698
-
699
-	/**
700
-	 * Updates properties for a calendar.
701
-	 *
702
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
703
-	 * To do the actual updates, you must tell this object which properties
704
-	 * you're going to process with the handle() method.
705
-	 *
706
-	 * Calling the handle method is like telling the PropPatch object "I
707
-	 * promise I can handle updating this property".
708
-	 *
709
-	 * Read the PropPatch documentation for more info and examples.
710
-	 *
711
-	 * @param mixed $calendarId
712
-	 * @param PropPatch $propPatch
713
-	 * @return void
714
-	 */
715
-	function updateCalendar($calendarId, PropPatch $propPatch) {
716
-		$supportedProperties = array_keys($this->propertyMap);
717
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
718
-
719
-		/**
720
-		 * @suppress SqlInjectionChecker
721
-		 */
722
-		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
723
-			$newValues = [];
724
-			foreach ($mutations as $propertyName => $propertyValue) {
725
-
726
-				switch ($propertyName) {
727
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
728
-						$fieldName = 'transparent';
729
-						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
730
-						break;
731
-					default :
732
-						$fieldName = $this->propertyMap[$propertyName];
733
-						$newValues[$fieldName] = $propertyValue;
734
-						break;
735
-				}
736
-
737
-			}
738
-			$query = $this->db->getQueryBuilder();
739
-			$query->update('calendars');
740
-			foreach ($newValues as $fieldName => $value) {
741
-				$query->set($fieldName, $query->createNamedParameter($value));
742
-			}
743
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
744
-			$query->execute();
745
-
746
-			$this->addChange($calendarId, "", 2);
747
-
748
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
749
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
750
-				[
751
-					'calendarId' => $calendarId,
752
-					'calendarData' => $this->getCalendarById($calendarId),
753
-					'shares' => $this->getShares($calendarId),
754
-					'propertyMutations' => $mutations,
755
-			]));
756
-
757
-			return true;
758
-		});
759
-	}
760
-
761
-	/**
762
-	 * Delete a calendar and all it's objects
763
-	 *
764
-	 * @param mixed $calendarId
765
-	 * @return void
766
-	 */
767
-	function deleteCalendar($calendarId) {
768
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
769
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
770
-			[
771
-				'calendarId' => $calendarId,
772
-				'calendarData' => $this->getCalendarById($calendarId),
773
-				'shares' => $this->getShares($calendarId),
774
-		]));
775
-
776
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?');
777
-		$stmt->execute([$calendarId]);
778
-
779
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
780
-		$stmt->execute([$calendarId]);
781
-
782
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ?');
783
-		$stmt->execute([$calendarId]);
784
-
785
-		$this->sharingBackend->deleteAllShares($calendarId);
786
-
787
-		$query = $this->db->getQueryBuilder();
788
-		$query->delete($this->dbObjectPropertiesTable)
789
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
790
-			->execute();
791
-	}
792
-
793
-	/**
794
-	 * Delete all of an user's shares
795
-	 *
796
-	 * @param string $principaluri
797
-	 * @return void
798
-	 */
799
-	function deleteAllSharesByUser($principaluri) {
800
-		$this->sharingBackend->deleteAllSharesByUser($principaluri);
801
-	}
802
-
803
-	/**
804
-	 * Returns all calendar objects within a calendar.
805
-	 *
806
-	 * Every item contains an array with the following keys:
807
-	 *   * calendardata - The iCalendar-compatible calendar data
808
-	 *   * uri - a unique key which will be used to construct the uri. This can
809
-	 *     be any arbitrary string, but making sure it ends with '.ics' is a
810
-	 *     good idea. This is only the basename, or filename, not the full
811
-	 *     path.
812
-	 *   * lastmodified - a timestamp of the last modification time
813
-	 *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
814
-	 *   '"abcdef"')
815
-	 *   * size - The size of the calendar objects, in bytes.
816
-	 *   * component - optional, a string containing the type of object, such
817
-	 *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
818
-	 *     the Content-Type header.
819
-	 *
820
-	 * Note that the etag is optional, but it's highly encouraged to return for
821
-	 * speed reasons.
822
-	 *
823
-	 * The calendardata is also optional. If it's not returned
824
-	 * 'getCalendarObject' will be called later, which *is* expected to return
825
-	 * calendardata.
826
-	 *
827
-	 * If neither etag or size are specified, the calendardata will be
828
-	 * used/fetched to determine these numbers. If both are specified the
829
-	 * amount of times this is needed is reduced by a great degree.
830
-	 *
831
-	 * @param mixed $calendarId
832
-	 * @return array
833
-	 */
834
-	function getCalendarObjects($calendarId) {
835
-		$query = $this->db->getQueryBuilder();
836
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
837
-			->from('calendarobjects')
838
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
839
-		$stmt = $query->execute();
840
-
841
-		$result = [];
842
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
843
-			$result[] = [
844
-					'id'           => $row['id'],
845
-					'uri'          => $row['uri'],
846
-					'lastmodified' => $row['lastmodified'],
847
-					'etag'         => '"' . $row['etag'] . '"',
848
-					'calendarid'   => $row['calendarid'],
849
-					'size'         => (int)$row['size'],
850
-					'component'    => strtolower($row['componenttype']),
851
-					'classification'=> (int)$row['classification']
852
-			];
853
-		}
854
-
855
-		return $result;
856
-	}
857
-
858
-	/**
859
-	 * Returns information from a single calendar object, based on it's object
860
-	 * uri.
861
-	 *
862
-	 * The object uri is only the basename, or filename and not a full path.
863
-	 *
864
-	 * The returned array must have the same keys as getCalendarObjects. The
865
-	 * 'calendardata' object is required here though, while it's not required
866
-	 * for getCalendarObjects.
867
-	 *
868
-	 * This method must return null if the object did not exist.
869
-	 *
870
-	 * @param mixed $calendarId
871
-	 * @param string $objectUri
872
-	 * @return array|null
873
-	 */
874
-	function getCalendarObject($calendarId, $objectUri) {
875
-
876
-		$query = $this->db->getQueryBuilder();
877
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
878
-				->from('calendarobjects')
879
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
880
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)));
881
-		$stmt = $query->execute();
882
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
883
-
884
-		if(!$row) return null;
885
-
886
-		return [
887
-				'id'            => $row['id'],
888
-				'uri'           => $row['uri'],
889
-				'lastmodified'  => $row['lastmodified'],
890
-				'etag'          => '"' . $row['etag'] . '"',
891
-				'calendarid'    => $row['calendarid'],
892
-				'size'          => (int)$row['size'],
893
-				'calendardata'  => $this->readBlob($row['calendardata']),
894
-				'component'     => strtolower($row['componenttype']),
895
-				'classification'=> (int)$row['classification']
896
-		];
897
-	}
898
-
899
-	/**
900
-	 * Returns a list of calendar objects.
901
-	 *
902
-	 * This method should work identical to getCalendarObject, but instead
903
-	 * return all the calendar objects in the list as an array.
904
-	 *
905
-	 * If the backend supports this, it may allow for some speed-ups.
906
-	 *
907
-	 * @param mixed $calendarId
908
-	 * @param string[] $uris
909
-	 * @return array
910
-	 */
911
-	function getMultipleCalendarObjects($calendarId, array $uris) {
912
-		if (empty($uris)) {
913
-			return [];
914
-		}
915
-
916
-		$chunks = array_chunk($uris, 100);
917
-		$objects = [];
918
-
919
-		$query = $this->db->getQueryBuilder();
920
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
921
-			->from('calendarobjects')
922
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
923
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
924
-
925
-		foreach ($chunks as $uris) {
926
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
927
-			$result = $query->execute();
928
-
929
-			while ($row = $result->fetch()) {
930
-				$objects[] = [
931
-					'id'           => $row['id'],
932
-					'uri'          => $row['uri'],
933
-					'lastmodified' => $row['lastmodified'],
934
-					'etag'         => '"' . $row['etag'] . '"',
935
-					'calendarid'   => $row['calendarid'],
936
-					'size'         => (int)$row['size'],
937
-					'calendardata' => $this->readBlob($row['calendardata']),
938
-					'component'    => strtolower($row['componenttype']),
939
-					'classification' => (int)$row['classification']
940
-				];
941
-			}
942
-			$result->closeCursor();
943
-		}
944
-		return $objects;
945
-	}
946
-
947
-	/**
948
-	 * Creates a new calendar object.
949
-	 *
950
-	 * The object uri is only the basename, or filename and not a full path.
951
-	 *
952
-	 * It is possible return an etag from this function, which will be used in
953
-	 * the response to this PUT request. Note that the ETag must be surrounded
954
-	 * by double-quotes.
955
-	 *
956
-	 * However, you should only really return this ETag if you don't mangle the
957
-	 * calendar-data. If the result of a subsequent GET to this object is not
958
-	 * the exact same as this request body, you should omit the ETag.
959
-	 *
960
-	 * @param mixed $calendarId
961
-	 * @param string $objectUri
962
-	 * @param string $calendarData
963
-	 * @return string
964
-	 */
965
-	function createCalendarObject($calendarId, $objectUri, $calendarData) {
966
-		$extraData = $this->getDenormalizedData($calendarData);
967
-
968
-		$q = $this->db->getQueryBuilder();
969
-		$q->select($q->createFunction('COUNT(*)'))
970
-			->from('calendarobjects')
971
-			->where($q->expr()->eq('calendarid', $q->createNamedParameter($calendarId)))
972
-			->andWhere($q->expr()->eq('uid', $q->createNamedParameter($extraData['uid'])));
973
-
974
-		$result = $q->execute();
975
-		$count = (int) $result->fetchColumn();
976
-		$result->closeCursor();
977
-
978
-		if ($count !== 0) {
979
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar object with uid already exists in this calendar collection.');
980
-		}
981
-
982
-		$query = $this->db->getQueryBuilder();
983
-		$query->insert('calendarobjects')
984
-			->values([
985
-				'calendarid' => $query->createNamedParameter($calendarId),
986
-				'uri' => $query->createNamedParameter($objectUri),
987
-				'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
988
-				'lastmodified' => $query->createNamedParameter(time()),
989
-				'etag' => $query->createNamedParameter($extraData['etag']),
990
-				'size' => $query->createNamedParameter($extraData['size']),
991
-				'componenttype' => $query->createNamedParameter($extraData['componentType']),
992
-				'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
993
-				'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
994
-				'classification' => $query->createNamedParameter($extraData['classification']),
995
-				'uid' => $query->createNamedParameter($extraData['uid']),
996
-			])
997
-			->execute();
998
-
999
-		$this->updateProperties($calendarId, $objectUri, $calendarData);
1000
-
1001
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
1002
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
1003
-			[
1004
-				'calendarId' => $calendarId,
1005
-				'calendarData' => $this->getCalendarById($calendarId),
1006
-				'shares' => $this->getShares($calendarId),
1007
-				'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1008
-			]
1009
-		));
1010
-		$this->addChange($calendarId, $objectUri, 1);
1011
-
1012
-		return '"' . $extraData['etag'] . '"';
1013
-	}
1014
-
1015
-	/**
1016
-	 * Updates an existing calendarobject, based on it's uri.
1017
-	 *
1018
-	 * The object uri is only the basename, or filename and not a full path.
1019
-	 *
1020
-	 * It is possible return an etag from this function, which will be used in
1021
-	 * the response to this PUT request. Note that the ETag must be surrounded
1022
-	 * by double-quotes.
1023
-	 *
1024
-	 * However, you should only really return this ETag if you don't mangle the
1025
-	 * calendar-data. If the result of a subsequent GET to this object is not
1026
-	 * the exact same as this request body, you should omit the ETag.
1027
-	 *
1028
-	 * @param mixed $calendarId
1029
-	 * @param string $objectUri
1030
-	 * @param string $calendarData
1031
-	 * @return string
1032
-	 */
1033
-	function updateCalendarObject($calendarId, $objectUri, $calendarData) {
1034
-		$extraData = $this->getDenormalizedData($calendarData);
1035
-
1036
-		$query = $this->db->getQueryBuilder();
1037
-		$query->update('calendarobjects')
1038
-				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1039
-				->set('lastmodified', $query->createNamedParameter(time()))
1040
-				->set('etag', $query->createNamedParameter($extraData['etag']))
1041
-				->set('size', $query->createNamedParameter($extraData['size']))
1042
-				->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1043
-				->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1044
-				->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1045
-				->set('classification', $query->createNamedParameter($extraData['classification']))
1046
-				->set('uid', $query->createNamedParameter($extraData['uid']))
1047
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1048
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1049
-			->execute();
1050
-
1051
-		$this->updateProperties($calendarId, $objectUri, $calendarData);
1052
-
1053
-		$data = $this->getCalendarObject($calendarId, $objectUri);
1054
-		if (is_array($data)) {
1055
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1056
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1057
-				[
1058
-					'calendarId' => $calendarId,
1059
-					'calendarData' => $this->getCalendarById($calendarId),
1060
-					'shares' => $this->getShares($calendarId),
1061
-					'objectData' => $data,
1062
-				]
1063
-			));
1064
-		}
1065
-		$this->addChange($calendarId, $objectUri, 2);
1066
-
1067
-		return '"' . $extraData['etag'] . '"';
1068
-	}
1069
-
1070
-	/**
1071
-	 * @param int $calendarObjectId
1072
-	 * @param int $classification
1073
-	 */
1074
-	public function setClassification($calendarObjectId, $classification) {
1075
-		if (!in_array($classification, [
1076
-			self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1077
-		])) {
1078
-			throw new \InvalidArgumentException();
1079
-		}
1080
-		$query = $this->db->getQueryBuilder();
1081
-		$query->update('calendarobjects')
1082
-			->set('classification', $query->createNamedParameter($classification))
1083
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1084
-			->execute();
1085
-	}
1086
-
1087
-	/**
1088
-	 * Deletes an existing calendar object.
1089
-	 *
1090
-	 * The object uri is only the basename, or filename and not a full path.
1091
-	 *
1092
-	 * @param mixed $calendarId
1093
-	 * @param string $objectUri
1094
-	 * @return void
1095
-	 */
1096
-	function deleteCalendarObject($calendarId, $objectUri) {
1097
-		$data = $this->getCalendarObject($calendarId, $objectUri);
1098
-		if (is_array($data)) {
1099
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1100
-				'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1101
-				[
1102
-					'calendarId' => $calendarId,
1103
-					'calendarData' => $this->getCalendarById($calendarId),
1104
-					'shares' => $this->getShares($calendarId),
1105
-					'objectData' => $data,
1106
-				]
1107
-			));
1108
-		}
1109
-
1110
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ?');
1111
-		$stmt->execute([$calendarId, $objectUri]);
1112
-
1113
-		$this->purgeProperties($calendarId, $data['id']);
1114
-
1115
-		$this->addChange($calendarId, $objectUri, 3);
1116
-	}
1117
-
1118
-	/**
1119
-	 * Performs a calendar-query on the contents of this calendar.
1120
-	 *
1121
-	 * The calendar-query is defined in RFC4791 : CalDAV. Using the
1122
-	 * calendar-query it is possible for a client to request a specific set of
1123
-	 * object, based on contents of iCalendar properties, date-ranges and
1124
-	 * iCalendar component types (VTODO, VEVENT).
1125
-	 *
1126
-	 * This method should just return a list of (relative) urls that match this
1127
-	 * query.
1128
-	 *
1129
-	 * The list of filters are specified as an array. The exact array is
1130
-	 * documented by Sabre\CalDAV\CalendarQueryParser.
1131
-	 *
1132
-	 * Note that it is extremely likely that getCalendarObject for every path
1133
-	 * returned from this method will be called almost immediately after. You
1134
-	 * may want to anticipate this to speed up these requests.
1135
-	 *
1136
-	 * This method provides a default implementation, which parses *all* the
1137
-	 * iCalendar objects in the specified calendar.
1138
-	 *
1139
-	 * This default may well be good enough for personal use, and calendars
1140
-	 * that aren't very large. But if you anticipate high usage, big calendars
1141
-	 * or high loads, you are strongly advised to optimize certain paths.
1142
-	 *
1143
-	 * The best way to do so is override this method and to optimize
1144
-	 * specifically for 'common filters'.
1145
-	 *
1146
-	 * Requests that are extremely common are:
1147
-	 *   * requests for just VEVENTS
1148
-	 *   * requests for just VTODO
1149
-	 *   * requests with a time-range-filter on either VEVENT or VTODO.
1150
-	 *
1151
-	 * ..and combinations of these requests. It may not be worth it to try to
1152
-	 * handle every possible situation and just rely on the (relatively
1153
-	 * easy to use) CalendarQueryValidator to handle the rest.
1154
-	 *
1155
-	 * Note that especially time-range-filters may be difficult to parse. A
1156
-	 * time-range filter specified on a VEVENT must for instance also handle
1157
-	 * recurrence rules correctly.
1158
-	 * A good example of how to interprete all these filters can also simply
1159
-	 * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1160
-	 * as possible, so it gives you a good idea on what type of stuff you need
1161
-	 * to think of.
1162
-	 *
1163
-	 * @param mixed $calendarId
1164
-	 * @param array $filters
1165
-	 * @return array
1166
-	 */
1167
-	function calendarQuery($calendarId, array $filters) {
1168
-		$componentType = null;
1169
-		$requirePostFilter = true;
1170
-		$timeRange = null;
1171
-
1172
-		// if no filters were specified, we don't need to filter after a query
1173
-		if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1174
-			$requirePostFilter = false;
1175
-		}
1176
-
1177
-		// Figuring out if there's a component filter
1178
-		if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1179
-			$componentType = $filters['comp-filters'][0]['name'];
1180
-
1181
-			// Checking if we need post-filters
1182
-			if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1183
-				$requirePostFilter = false;
1184
-			}
1185
-			// There was a time-range filter
1186
-			if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1187
-				$timeRange = $filters['comp-filters'][0]['time-range'];
1188
-
1189
-				// If start time OR the end time is not specified, we can do a
1190
-				// 100% accurate mysql query.
1191
-				if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1192
-					$requirePostFilter = false;
1193
-				}
1194
-			}
1195
-
1196
-		}
1197
-		$columns = ['uri'];
1198
-		if ($requirePostFilter) {
1199
-			$columns = ['uri', 'calendardata'];
1200
-		}
1201
-		$query = $this->db->getQueryBuilder();
1202
-		$query->select($columns)
1203
-			->from('calendarobjects')
1204
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
1205
-
1206
-		if ($componentType) {
1207
-			$query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1208
-		}
1209
-
1210
-		if ($timeRange && $timeRange['start']) {
1211
-			$query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1212
-		}
1213
-		if ($timeRange && $timeRange['end']) {
1214
-			$query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1215
-		}
1216
-
1217
-		$stmt = $query->execute();
1218
-
1219
-		$result = [];
1220
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1221
-			if ($requirePostFilter) {
1222
-				if (!$this->validateFilterForObject($row, $filters)) {
1223
-					continue;
1224
-				}
1225
-			}
1226
-			$result[] = $row['uri'];
1227
-		}
1228
-
1229
-		return $result;
1230
-	}
1231
-
1232
-	/**
1233
-	 * custom Nextcloud search extension for CalDAV
1234
-	 *
1235
-	 * @param string $principalUri
1236
-	 * @param array $filters
1237
-	 * @param integer|null $limit
1238
-	 * @param integer|null $offset
1239
-	 * @return array
1240
-	 */
1241
-	public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1242
-		$calendars = $this->getCalendarsForUser($principalUri);
1243
-		$ownCalendars = [];
1244
-		$sharedCalendars = [];
1245
-
1246
-		$uriMapper = [];
1247
-
1248
-		foreach($calendars as $calendar) {
1249
-			if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1250
-				$ownCalendars[] = $calendar['id'];
1251
-			} else {
1252
-				$sharedCalendars[] = $calendar['id'];
1253
-			}
1254
-			$uriMapper[$calendar['id']] = $calendar['uri'];
1255
-		}
1256
-		if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1257
-			return [];
1258
-		}
1259
-
1260
-		$query = $this->db->getQueryBuilder();
1261
-		// Calendar id expressions
1262
-		$calendarExpressions = [];
1263
-		foreach($ownCalendars as $id) {
1264
-			$calendarExpressions[] = $query->expr()
1265
-				->eq('c.calendarid', $query->createNamedParameter($id));
1266
-		}
1267
-		foreach($sharedCalendars as $id) {
1268
-			$calendarExpressions[] = $query->expr()->andX(
1269
-				$query->expr()->eq('c.calendarid',
1270
-					$query->createNamedParameter($id)),
1271
-				$query->expr()->eq('c.classification',
1272
-					$query->createNamedParameter(self::CLASSIFICATION_PUBLIC))
1273
-			);
1274
-		}
1275
-
1276
-		if (count($calendarExpressions) === 1) {
1277
-			$calExpr = $calendarExpressions[0];
1278
-		} else {
1279
-			$calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1280
-		}
1281
-
1282
-		// Component expressions
1283
-		$compExpressions = [];
1284
-		foreach($filters['comps'] as $comp) {
1285
-			$compExpressions[] = $query->expr()
1286
-				->eq('c.componenttype', $query->createNamedParameter($comp));
1287
-		}
1288
-
1289
-		if (count($compExpressions) === 1) {
1290
-			$compExpr = $compExpressions[0];
1291
-		} else {
1292
-			$compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1293
-		}
1294
-
1295
-		if (!isset($filters['props'])) {
1296
-			$filters['props'] = [];
1297
-		}
1298
-		if (!isset($filters['params'])) {
1299
-			$filters['params'] = [];
1300
-		}
1301
-
1302
-		$propParamExpressions = [];
1303
-		foreach($filters['props'] as $prop) {
1304
-			$propParamExpressions[] = $query->expr()->andX(
1305
-				$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1306
-				$query->expr()->isNull('i.parameter')
1307
-			);
1308
-		}
1309
-		foreach($filters['params'] as $param) {
1310
-			$propParamExpressions[] = $query->expr()->andX(
1311
-				$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1312
-				$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1313
-			);
1314
-		}
1315
-
1316
-		if (count($propParamExpressions) === 1) {
1317
-			$propParamExpr = $propParamExpressions[0];
1318
-		} else {
1319
-			$propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1320
-		}
1321
-
1322
-		$query->select(['c.calendarid', 'c.uri'])
1323
-			->from($this->dbObjectPropertiesTable, 'i')
1324
-			->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1325
-			->where($calExpr)
1326
-			->andWhere($compExpr)
1327
-			->andWhere($propParamExpr)
1328
-			->andWhere($query->expr()->iLike('i.value',
1329
-				$query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
1330
-
1331
-		if ($offset) {
1332
-			$query->setFirstResult($offset);
1333
-		}
1334
-		if ($limit) {
1335
-			$query->setMaxResults($limit);
1336
-		}
1337
-
1338
-		$stmt = $query->execute();
1339
-
1340
-		$result = [];
1341
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1342
-			$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1343
-			if (!in_array($path, $result)) {
1344
-				$result[] = $path;
1345
-			}
1346
-		}
1347
-
1348
-		return $result;
1349
-	}
1350
-
1351
-	/**
1352
-	 * used for Nextcloud's calendar API
1353
-	 *
1354
-	 * @param array $calendarInfo
1355
-	 * @param string $pattern
1356
-	 * @param array $searchProperties
1357
-	 * @param array $options
1358
-	 * @param integer|null $limit
1359
-	 * @param integer|null $offset
1360
-	 *
1361
-	 * @return array
1362
-	 */
1363
-	public function search(array $calendarInfo, $pattern, array $searchProperties,
1364
-						   array $options, $limit, $offset) {
1365
-		$outerQuery = $this->db->getQueryBuilder();
1366
-		$innerQuery = $this->db->getQueryBuilder();
1367
-
1368
-		$innerQuery->selectDistinct('op.objectid')
1369
-			->from($this->dbObjectPropertiesTable, 'op')
1370
-			->andWhere($innerQuery->expr()->eq('op.calendarid',
1371
-				$outerQuery->createNamedParameter($calendarInfo['id'])));
1372
-
1373
-		// only return public items for shared calendars for now
1374
-		if ($calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1375
-			$innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
1376
-				$outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1377
-		}
1378
-
1379
-		$or = $innerQuery->expr()->orX();
1380
-		foreach($searchProperties as $searchProperty) {
1381
-			$or->add($innerQuery->expr()->eq('op.name',
1382
-				$outerQuery->createNamedParameter($searchProperty)));
1383
-		}
1384
-		$innerQuery->andWhere($or);
1385
-
1386
-		// TODO - add component-type
1387
-
1388
-		if ($pattern !== '') {
1389
-			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1390
-				$outerQuery->createNamedParameter('%' .
1391
-					$this->db->escapeLikeParameter($pattern) . '%')));
1392
-		}
1393
-
1394
-		$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1395
-			->from('calendarobjects', 'c');
1396
-
1397
-		if (isset($options['timerange'])) {
1398
-			if (isset($options['timerange']['start'])) {
1399
-				$outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
1400
-					$outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp)));
1401
-
1402
-			}
1403
-			if (isset($options['timerange']['end'])) {
1404
-				$outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
1405
-					$outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp)));
1406
-			}
1407
-
1408
-		}
1409
-
1410
-		$outerQuery->andWhere($outerQuery->expr()->in('c.id',
1411
-			$outerQuery->createFunction($innerQuery->getSQL())));
1412
-
1413
-		if ($offset) {
1414
-			$outerQuery->setFirstResult($offset);
1415
-		}
1416
-		if ($limit) {
1417
-			$outerQuery->setMaxResults($limit);
1418
-		}
1419
-
1420
-		$result = $outerQuery->execute();
1421
-		$calendarObjects = $result->fetchAll();
1422
-
1423
-		return array_map(function($o) {
1424
-			$calendarData = Reader::read($o['calendardata']);
1425
-			$comps = $calendarData->getComponents();
1426
-			$objects = [];
1427
-			$timezones = [];
1428
-			foreach($comps as $comp) {
1429
-				if ($comp instanceof VTimeZone) {
1430
-					$timezones[] = $comp;
1431
-				} else {
1432
-					$objects[] = $comp;
1433
-				}
1434
-			}
1435
-
1436
-			return [
1437
-				'id' => $o['id'],
1438
-				'type' => $o['componenttype'],
1439
-				'uid' => $o['uid'],
1440
-				'uri' => $o['uri'],
1441
-				'objects' => array_map(function($c) {
1442
-					return $this->transformSearchData($c);
1443
-				}, $objects),
1444
-				'timezones' => array_map(function($c) {
1445
-					return $this->transformSearchData($c);
1446
-				}, $timezones),
1447
-			];
1448
-		}, $calendarObjects);
1449
-	}
1450
-
1451
-	/**
1452
-	 * @param Component $comp
1453
-	 * @return array
1454
-	 */
1455
-	private function transformSearchData(Component $comp) {
1456
-		$data = [];
1457
-		/** @var Component[] $subComponents */
1458
-		$subComponents = $comp->getComponents();
1459
-		/** @var Property[] $properties */
1460
-		$properties = array_filter($comp->children(), function($c) {
1461
-			return $c instanceof Property;
1462
-		});
1463
-		$validationRules = $comp->getValidationRules();
1464
-
1465
-		foreach($subComponents as $subComponent) {
1466
-			$name = $subComponent->name;
1467
-			if (!isset($data[$name])) {
1468
-				$data[$name] = [];
1469
-			}
1470
-			$data[$name][] = $this->transformSearchData($subComponent);
1471
-		}
1472
-
1473
-		foreach($properties as $property) {
1474
-			$name = $property->name;
1475
-			if (!isset($validationRules[$name])) {
1476
-				$validationRules[$name] = '*';
1477
-			}
1478
-
1479
-			$rule = $validationRules[$property->name];
1480
-			if ($rule === '+' || $rule === '*') { // multiple
1481
-				if (!isset($data[$name])) {
1482
-					$data[$name] = [];
1483
-				}
1484
-
1485
-				$data[$name][] = $this->transformSearchProperty($property);
1486
-			} else { // once
1487
-				$data[$name] = $this->transformSearchProperty($property);
1488
-			}
1489
-		}
1490
-
1491
-		return $data;
1492
-	}
1493
-
1494
-	/**
1495
-	 * @param Property $prop
1496
-	 * @return array
1497
-	 */
1498
-	private function transformSearchProperty(Property $prop) {
1499
-		// No need to check Date, as it extends DateTime
1500
-		if ($prop instanceof Property\ICalendar\DateTime) {
1501
-			$value = $prop->getDateTime();
1502
-		} else {
1503
-			$value = $prop->getValue();
1504
-		}
1505
-
1506
-		return [
1507
-			$value,
1508
-			$prop->parameters()
1509
-		];
1510
-	}
1511
-
1512
-	/**
1513
-	 * Searches through all of a users calendars and calendar objects to find
1514
-	 * an object with a specific UID.
1515
-	 *
1516
-	 * This method should return the path to this object, relative to the
1517
-	 * calendar home, so this path usually only contains two parts:
1518
-	 *
1519
-	 * calendarpath/objectpath.ics
1520
-	 *
1521
-	 * If the uid is not found, return null.
1522
-	 *
1523
-	 * This method should only consider * objects that the principal owns, so
1524
-	 * any calendars owned by other principals that also appear in this
1525
-	 * collection should be ignored.
1526
-	 *
1527
-	 * @param string $principalUri
1528
-	 * @param string $uid
1529
-	 * @return string|null
1530
-	 */
1531
-	function getCalendarObjectByUID($principalUri, $uid) {
1532
-
1533
-		$query = $this->db->getQueryBuilder();
1534
-		$query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1535
-			->from('calendarobjects', 'co')
1536
-			->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1537
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1538
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1539
-
1540
-		$stmt = $query->execute();
1541
-
1542
-		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1543
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1544
-		}
1545
-
1546
-		return null;
1547
-	}
1548
-
1549
-	/**
1550
-	 * The getChanges method returns all the changes that have happened, since
1551
-	 * the specified syncToken in the specified calendar.
1552
-	 *
1553
-	 * This function should return an array, such as the following:
1554
-	 *
1555
-	 * [
1556
-	 *   'syncToken' => 'The current synctoken',
1557
-	 *   'added'   => [
1558
-	 *      'new.txt',
1559
-	 *   ],
1560
-	 *   'modified'   => [
1561
-	 *      'modified.txt',
1562
-	 *   ],
1563
-	 *   'deleted' => [
1564
-	 *      'foo.php.bak',
1565
-	 *      'old.txt'
1566
-	 *   ]
1567
-	 * );
1568
-	 *
1569
-	 * The returned syncToken property should reflect the *current* syncToken
1570
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1571
-	 * property This is * needed here too, to ensure the operation is atomic.
1572
-	 *
1573
-	 * If the $syncToken argument is specified as null, this is an initial
1574
-	 * sync, and all members should be reported.
1575
-	 *
1576
-	 * The modified property is an array of nodenames that have changed since
1577
-	 * the last token.
1578
-	 *
1579
-	 * The deleted property is an array with nodenames, that have been deleted
1580
-	 * from collection.
1581
-	 *
1582
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
1583
-	 * 1, you only have to report changes that happened only directly in
1584
-	 * immediate descendants. If it's 2, it should also include changes from
1585
-	 * the nodes below the child collections. (grandchildren)
1586
-	 *
1587
-	 * The $limit argument allows a client to specify how many results should
1588
-	 * be returned at most. If the limit is not specified, it should be treated
1589
-	 * as infinite.
1590
-	 *
1591
-	 * If the limit (infinite or not) is higher than you're willing to return,
1592
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1593
-	 *
1594
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
1595
-	 * return null.
1596
-	 *
1597
-	 * The limit is 'suggestive'. You are free to ignore it.
1598
-	 *
1599
-	 * @param string $calendarId
1600
-	 * @param string $syncToken
1601
-	 * @param int $syncLevel
1602
-	 * @param int $limit
1603
-	 * @return array
1604
-	 */
1605
-	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1606
-		// Current synctoken
1607
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1608
-		$stmt->execute([ $calendarId ]);
1609
-		$currentToken = $stmt->fetchColumn(0);
1610
-
1611
-		if (is_null($currentToken)) {
1612
-			return null;
1613
-		}
1614
-
1615
-		$result = [
1616
-			'syncToken' => $currentToken,
1617
-			'added'     => [],
1618
-			'modified'  => [],
1619
-			'deleted'   => [],
1620
-		];
1621
-
1622
-		if ($syncToken) {
1623
-
1624
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1625
-			if ($limit>0) {
1626
-				$query.= " LIMIT " . (int)$limit;
1627
-			}
1628
-
1629
-			// Fetching all changes
1630
-			$stmt = $this->db->prepare($query);
1631
-			$stmt->execute([$syncToken, $currentToken, $calendarId]);
1632
-
1633
-			$changes = [];
1634
-
1635
-			// This loop ensures that any duplicates are overwritten, only the
1636
-			// last change on a node is relevant.
1637
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1638
-
1639
-				$changes[$row['uri']] = $row['operation'];
1640
-
1641
-			}
1642
-
1643
-			foreach($changes as $uri => $operation) {
1644
-
1645
-				switch($operation) {
1646
-					case 1 :
1647
-						$result['added'][] = $uri;
1648
-						break;
1649
-					case 2 :
1650
-						$result['modified'][] = $uri;
1651
-						break;
1652
-					case 3 :
1653
-						$result['deleted'][] = $uri;
1654
-						break;
1655
-				}
1656
-
1657
-			}
1658
-		} else {
1659
-			// No synctoken supplied, this is the initial sync.
1660
-			$query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?";
1661
-			$stmt = $this->db->prepare($query);
1662
-			$stmt->execute([$calendarId]);
1663
-
1664
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1665
-		}
1666
-		return $result;
1667
-
1668
-	}
1669
-
1670
-	/**
1671
-	 * Returns a list of subscriptions for a principal.
1672
-	 *
1673
-	 * Every subscription is an array with the following keys:
1674
-	 *  * id, a unique id that will be used by other functions to modify the
1675
-	 *    subscription. This can be the same as the uri or a database key.
1676
-	 *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1677
-	 *  * principaluri. The owner of the subscription. Almost always the same as
1678
-	 *    principalUri passed to this method.
1679
-	 *
1680
-	 * Furthermore, all the subscription info must be returned too:
1681
-	 *
1682
-	 * 1. {DAV:}displayname
1683
-	 * 2. {http://apple.com/ns/ical/}refreshrate
1684
-	 * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1685
-	 *    should not be stripped).
1686
-	 * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1687
-	 *    should not be stripped).
1688
-	 * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1689
-	 *    attachments should not be stripped).
1690
-	 * 6. {http://calendarserver.org/ns/}source (Must be a
1691
-	 *     Sabre\DAV\Property\Href).
1692
-	 * 7. {http://apple.com/ns/ical/}calendar-color
1693
-	 * 8. {http://apple.com/ns/ical/}calendar-order
1694
-	 * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1695
-	 *    (should just be an instance of
1696
-	 *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1697
-	 *    default components).
1698
-	 *
1699
-	 * @param string $principalUri
1700
-	 * @return array
1701
-	 */
1702
-	function getSubscriptionsForUser($principalUri) {
1703
-		$fields = array_values($this->subscriptionPropertyMap);
1704
-		$fields[] = 'id';
1705
-		$fields[] = 'uri';
1706
-		$fields[] = 'source';
1707
-		$fields[] = 'principaluri';
1708
-		$fields[] = 'lastmodified';
1709
-
1710
-		$query = $this->db->getQueryBuilder();
1711
-		$query->select($fields)
1712
-			->from('calendarsubscriptions')
1713
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1714
-			->orderBy('calendarorder', 'asc');
1715
-		$stmt =$query->execute();
1716
-
1717
-		$subscriptions = [];
1718
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1719
-
1720
-			$subscription = [
1721
-				'id'           => $row['id'],
1722
-				'uri'          => $row['uri'],
1723
-				'principaluri' => $row['principaluri'],
1724
-				'source'       => $row['source'],
1725
-				'lastmodified' => $row['lastmodified'],
1726
-
1727
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1728
-			];
1729
-
1730
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1731
-				if (!is_null($row[$dbName])) {
1732
-					$subscription[$xmlName] = $row[$dbName];
1733
-				}
1734
-			}
1735
-
1736
-			$subscriptions[] = $subscription;
1737
-
1738
-		}
1739
-
1740
-		return $subscriptions;
1741
-	}
1742
-
1743
-	/**
1744
-	 * Creates a new subscription for a principal.
1745
-	 *
1746
-	 * If the creation was a success, an id must be returned that can be used to reference
1747
-	 * this subscription in other methods, such as updateSubscription.
1748
-	 *
1749
-	 * @param string $principalUri
1750
-	 * @param string $uri
1751
-	 * @param array $properties
1752
-	 * @return mixed
1753
-	 */
1754
-	function createSubscription($principalUri, $uri, array $properties) {
1755
-
1756
-		if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1757
-			throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1758
-		}
1759
-
1760
-		$values = [
1761
-			'principaluri' => $principalUri,
1762
-			'uri'          => $uri,
1763
-			'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1764
-			'lastmodified' => time(),
1765
-		];
1766
-
1767
-		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1768
-
1769
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1770
-			if (array_key_exists($xmlName, $properties)) {
1771
-					$values[$dbName] = $properties[$xmlName];
1772
-					if (in_array($dbName, $propertiesBoolean)) {
1773
-						$values[$dbName] = true;
1774
-				}
1775
-			}
1776
-		}
1777
-
1778
-		$valuesToInsert = array();
1779
-
1780
-		$query = $this->db->getQueryBuilder();
1781
-
1782
-		foreach (array_keys($values) as $name) {
1783
-			$valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1784
-		}
1785
-
1786
-		$query->insert('calendarsubscriptions')
1787
-			->values($valuesToInsert)
1788
-			->execute();
1789
-
1790
-		return $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1791
-	}
1792
-
1793
-	/**
1794
-	 * Updates a subscription
1795
-	 *
1796
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1797
-	 * To do the actual updates, you must tell this object which properties
1798
-	 * you're going to process with the handle() method.
1799
-	 *
1800
-	 * Calling the handle method is like telling the PropPatch object "I
1801
-	 * promise I can handle updating this property".
1802
-	 *
1803
-	 * Read the PropPatch documentation for more info and examples.
1804
-	 *
1805
-	 * @param mixed $subscriptionId
1806
-	 * @param PropPatch $propPatch
1807
-	 * @return void
1808
-	 */
1809
-	function updateSubscription($subscriptionId, PropPatch $propPatch) {
1810
-		$supportedProperties = array_keys($this->subscriptionPropertyMap);
1811
-		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
1812
-
1813
-		/**
1814
-		 * @suppress SqlInjectionChecker
1815
-		 */
1816
-		$propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1817
-
1818
-			$newValues = [];
1819
-
1820
-			foreach($mutations as $propertyName=>$propertyValue) {
1821
-				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1822
-					$newValues['source'] = $propertyValue->getHref();
1823
-				} else {
1824
-					$fieldName = $this->subscriptionPropertyMap[$propertyName];
1825
-					$newValues[$fieldName] = $propertyValue;
1826
-				}
1827
-			}
1828
-
1829
-			$query = $this->db->getQueryBuilder();
1830
-			$query->update('calendarsubscriptions')
1831
-				->set('lastmodified', $query->createNamedParameter(time()));
1832
-			foreach($newValues as $fieldName=>$value) {
1833
-				$query->set($fieldName, $query->createNamedParameter($value));
1834
-			}
1835
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1836
-				->execute();
1837
-
1838
-			return true;
1839
-
1840
-		});
1841
-	}
1842
-
1843
-	/**
1844
-	 * Deletes a subscription.
1845
-	 *
1846
-	 * @param mixed $subscriptionId
1847
-	 * @return void
1848
-	 */
1849
-	function deleteSubscription($subscriptionId) {
1850
-		$query = $this->db->getQueryBuilder();
1851
-		$query->delete('calendarsubscriptions')
1852
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1853
-			->execute();
1854
-	}
1855
-
1856
-	/**
1857
-	 * Returns a single scheduling object for the inbox collection.
1858
-	 *
1859
-	 * The returned array should contain the following elements:
1860
-	 *   * uri - A unique basename for the object. This will be used to
1861
-	 *           construct a full uri.
1862
-	 *   * calendardata - The iCalendar object
1863
-	 *   * lastmodified - The last modification date. Can be an int for a unix
1864
-	 *                    timestamp, or a PHP DateTime object.
1865
-	 *   * etag - A unique token that must change if the object changed.
1866
-	 *   * size - The size of the object, in bytes.
1867
-	 *
1868
-	 * @param string $principalUri
1869
-	 * @param string $objectUri
1870
-	 * @return array
1871
-	 */
1872
-	function getSchedulingObject($principalUri, $objectUri) {
1873
-		$query = $this->db->getQueryBuilder();
1874
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1875
-			->from('schedulingobjects')
1876
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1877
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1878
-			->execute();
1879
-
1880
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
1881
-
1882
-		if(!$row) {
1883
-			return null;
1884
-		}
1885
-
1886
-		return [
1887
-				'uri'          => $row['uri'],
1888
-				'calendardata' => $row['calendardata'],
1889
-				'lastmodified' => $row['lastmodified'],
1890
-				'etag'         => '"' . $row['etag'] . '"',
1891
-				'size'         => (int)$row['size'],
1892
-		];
1893
-	}
1894
-
1895
-	/**
1896
-	 * Returns all scheduling objects for the inbox collection.
1897
-	 *
1898
-	 * These objects should be returned as an array. Every item in the array
1899
-	 * should follow the same structure as returned from getSchedulingObject.
1900
-	 *
1901
-	 * The main difference is that 'calendardata' is optional.
1902
-	 *
1903
-	 * @param string $principalUri
1904
-	 * @return array
1905
-	 */
1906
-	function getSchedulingObjects($principalUri) {
1907
-		$query = $this->db->getQueryBuilder();
1908
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1909
-				->from('schedulingobjects')
1910
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1911
-				->execute();
1912
-
1913
-		$result = [];
1914
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1915
-			$result[] = [
1916
-					'calendardata' => $row['calendardata'],
1917
-					'uri'          => $row['uri'],
1918
-					'lastmodified' => $row['lastmodified'],
1919
-					'etag'         => '"' . $row['etag'] . '"',
1920
-					'size'         => (int)$row['size'],
1921
-			];
1922
-		}
1923
-
1924
-		return $result;
1925
-	}
1926
-
1927
-	/**
1928
-	 * Deletes a scheduling object from the inbox collection.
1929
-	 *
1930
-	 * @param string $principalUri
1931
-	 * @param string $objectUri
1932
-	 * @return void
1933
-	 */
1934
-	function deleteSchedulingObject($principalUri, $objectUri) {
1935
-		$query = $this->db->getQueryBuilder();
1936
-		$query->delete('schedulingobjects')
1937
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1938
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1939
-				->execute();
1940
-	}
1941
-
1942
-	/**
1943
-	 * Creates a new scheduling object. This should land in a users' inbox.
1944
-	 *
1945
-	 * @param string $principalUri
1946
-	 * @param string $objectUri
1947
-	 * @param string $objectData
1948
-	 * @return void
1949
-	 */
1950
-	function createSchedulingObject($principalUri, $objectUri, $objectData) {
1951
-		$query = $this->db->getQueryBuilder();
1952
-		$query->insert('schedulingobjects')
1953
-			->values([
1954
-				'principaluri' => $query->createNamedParameter($principalUri),
1955
-				'calendardata' => $query->createNamedParameter($objectData),
1956
-				'uri' => $query->createNamedParameter($objectUri),
1957
-				'lastmodified' => $query->createNamedParameter(time()),
1958
-				'etag' => $query->createNamedParameter(md5($objectData)),
1959
-				'size' => $query->createNamedParameter(strlen($objectData))
1960
-			])
1961
-			->execute();
1962
-	}
1963
-
1964
-	/**
1965
-	 * Adds a change record to the calendarchanges table.
1966
-	 *
1967
-	 * @param mixed $calendarId
1968
-	 * @param string $objectUri
1969
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete.
1970
-	 * @return void
1971
-	 */
1972
-	protected function addChange($calendarId, $objectUri, $operation) {
1973
-
1974
-		$stmt = $this->db->prepare('INSERT INTO `*PREFIX*calendarchanges` (`uri`, `synctoken`, `calendarid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*calendars` WHERE `id` = ?');
1975
-		$stmt->execute([
1976
-			$objectUri,
1977
-			$calendarId,
1978
-			$operation,
1979
-			$calendarId
1980
-		]);
1981
-		$stmt = $this->db->prepare('UPDATE `*PREFIX*calendars` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
1982
-		$stmt->execute([
1983
-			$calendarId
1984
-		]);
1985
-
1986
-	}
1987
-
1988
-	/**
1989
-	 * Parses some information from calendar objects, used for optimized
1990
-	 * calendar-queries.
1991
-	 *
1992
-	 * Returns an array with the following keys:
1993
-	 *   * etag - An md5 checksum of the object without the quotes.
1994
-	 *   * size - Size of the object in bytes
1995
-	 *   * componentType - VEVENT, VTODO or VJOURNAL
1996
-	 *   * firstOccurence
1997
-	 *   * lastOccurence
1998
-	 *   * uid - value of the UID property
1999
-	 *
2000
-	 * @param string $calendarData
2001
-	 * @return array
2002
-	 */
2003
-	public function getDenormalizedData($calendarData) {
2004
-
2005
-		$vObject = Reader::read($calendarData);
2006
-		$componentType = null;
2007
-		$component = null;
2008
-		$firstOccurrence = null;
2009
-		$lastOccurrence = null;
2010
-		$uid = null;
2011
-		$classification = self::CLASSIFICATION_PUBLIC;
2012
-		foreach($vObject->getComponents() as $component) {
2013
-			if ($component->name!=='VTIMEZONE') {
2014
-				$componentType = $component->name;
2015
-				$uid = (string)$component->UID;
2016
-				break;
2017
-			}
2018
-		}
2019
-		if (!$componentType) {
2020
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
2021
-		}
2022
-		if ($componentType === 'VEVENT' && $component->DTSTART) {
2023
-			$firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
2024
-			// Finding the last occurrence is a bit harder
2025
-			if (!isset($component->RRULE)) {
2026
-				if (isset($component->DTEND)) {
2027
-					$lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
2028
-				} elseif (isset($component->DURATION)) {
2029
-					$endDate = clone $component->DTSTART->getDateTime();
2030
-					$endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
2031
-					$lastOccurrence = $endDate->getTimeStamp();
2032
-				} elseif (!$component->DTSTART->hasTime()) {
2033
-					$endDate = clone $component->DTSTART->getDateTime();
2034
-					$endDate->modify('+1 day');
2035
-					$lastOccurrence = $endDate->getTimeStamp();
2036
-				} else {
2037
-					$lastOccurrence = $firstOccurrence;
2038
-				}
2039
-			} else {
2040
-				$it = new EventIterator($vObject, (string)$component->UID);
2041
-				$maxDate = new \DateTime(self::MAX_DATE);
2042
-				if ($it->isInfinite()) {
2043
-					$lastOccurrence = $maxDate->getTimestamp();
2044
-				} else {
2045
-					$end = $it->getDtEnd();
2046
-					while($it->valid() && $end < $maxDate) {
2047
-						$end = $it->getDtEnd();
2048
-						$it->next();
2049
-
2050
-					}
2051
-					$lastOccurrence = $end->getTimestamp();
2052
-				}
2053
-
2054
-			}
2055
-		}
2056
-
2057
-		if ($component->CLASS) {
2058
-			$classification = CalDavBackend::CLASSIFICATION_PRIVATE;
2059
-			switch ($component->CLASS->getValue()) {
2060
-				case 'PUBLIC':
2061
-					$classification = CalDavBackend::CLASSIFICATION_PUBLIC;
2062
-					break;
2063
-				case 'CONFIDENTIAL':
2064
-					$classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
2065
-					break;
2066
-			}
2067
-		}
2068
-		return [
2069
-			'etag' => md5($calendarData),
2070
-			'size' => strlen($calendarData),
2071
-			'componentType' => $componentType,
2072
-			'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
2073
-			'lastOccurence'  => $lastOccurrence,
2074
-			'uid' => $uid,
2075
-			'classification' => $classification
2076
-		];
2077
-
2078
-	}
2079
-
2080
-	private function readBlob($cardData) {
2081
-		if (is_resource($cardData)) {
2082
-			return stream_get_contents($cardData);
2083
-		}
2084
-
2085
-		return $cardData;
2086
-	}
2087
-
2088
-	/**
2089
-	 * @param IShareable $shareable
2090
-	 * @param array $add
2091
-	 * @param array $remove
2092
-	 */
2093
-	public function updateShares($shareable, $add, $remove) {
2094
-		$calendarId = $shareable->getResourceId();
2095
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
2096
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2097
-			[
2098
-				'calendarId' => $calendarId,
2099
-				'calendarData' => $this->getCalendarById($calendarId),
2100
-				'shares' => $this->getShares($calendarId),
2101
-				'add' => $add,
2102
-				'remove' => $remove,
2103
-			]));
2104
-		$this->sharingBackend->updateShares($shareable, $add, $remove);
2105
-	}
2106
-
2107
-	/**
2108
-	 * @param int $resourceId
2109
-	 * @return array
2110
-	 */
2111
-	public function getShares($resourceId) {
2112
-		return $this->sharingBackend->getShares($resourceId);
2113
-	}
2114
-
2115
-	/**
2116
-	 * @param boolean $value
2117
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
2118
-	 * @return string|null
2119
-	 */
2120
-	public function setPublishStatus($value, $calendar) {
2121
-		$query = $this->db->getQueryBuilder();
2122
-		if ($value) {
2123
-			$publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
2124
-			$query->insert('dav_shares')
2125
-				->values([
2126
-					'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
2127
-					'type' => $query->createNamedParameter('calendar'),
2128
-					'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
2129
-					'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
2130
-					'publicuri' => $query->createNamedParameter($publicUri)
2131
-				]);
2132
-			$query->execute();
2133
-			return $publicUri;
2134
-		}
2135
-		$query->delete('dav_shares')
2136
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2137
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
2138
-		$query->execute();
2139
-		return null;
2140
-	}
2141
-
2142
-	/**
2143
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
2144
-	 * @return mixed
2145
-	 */
2146
-	public function getPublishStatus($calendar) {
2147
-		$query = $this->db->getQueryBuilder();
2148
-		$result = $query->select('publicuri')
2149
-			->from('dav_shares')
2150
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2151
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
2152
-			->execute();
2153
-
2154
-		$row = $result->fetch();
2155
-		$result->closeCursor();
2156
-		return $row ? reset($row) : false;
2157
-	}
2158
-
2159
-	/**
2160
-	 * @param int $resourceId
2161
-	 * @param array $acl
2162
-	 * @return array
2163
-	 */
2164
-	public function applyShareAcl($resourceId, $acl) {
2165
-		return $this->sharingBackend->applyShareAcl($resourceId, $acl);
2166
-	}
2167
-
2168
-
2169
-
2170
-	/**
2171
-	 * update properties table
2172
-	 *
2173
-	 * @param int $calendarId
2174
-	 * @param string $objectUri
2175
-	 * @param string $calendarData
2176
-	 */
2177
-	public function updateProperties($calendarId, $objectUri, $calendarData) {
2178
-		$objectId = $this->getCalendarObjectId($calendarId, $objectUri);
2179
-
2180
-		try {
2181
-			$vCalendar = $this->readCalendarData($calendarData);
2182
-		} catch (\Exception $ex) {
2183
-			return;
2184
-		}
2185
-
2186
-		$this->purgeProperties($calendarId, $objectId);
2187
-
2188
-		$query = $this->db->getQueryBuilder();
2189
-		$query->insert($this->dbObjectPropertiesTable)
2190
-			->values(
2191
-				[
2192
-					'calendarid' => $query->createNamedParameter($calendarId),
2193
-					'objectid' => $query->createNamedParameter($objectId),
2194
-					'name' => $query->createParameter('name'),
2195
-					'parameter' => $query->createParameter('parameter'),
2196
-					'value' => $query->createParameter('value'),
2197
-				]
2198
-			);
2199
-
2200
-		$indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2201
-		foreach ($vCalendar->getComponents() as $component) {
2202
-			if (!in_array($component->name, $indexComponents)) {
2203
-				continue;
2204
-			}
2205
-
2206
-			foreach ($component->children() as $property) {
2207
-				if (in_array($property->name, self::$indexProperties)) {
2208
-					$value = $property->getValue();
2209
-					// is this a shitty db?
2210
-					if (!$this->db->supports4ByteText()) {
2211
-						$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2212
-					}
2213
-					$value = substr($value, 0, 254);
2214
-
2215
-					$query->setParameter('name', $property->name);
2216
-					$query->setParameter('parameter', null);
2217
-					$query->setParameter('value', $value);
2218
-					$query->execute();
2219
-				}
2220
-
2221
-				if (in_array($property->name, array_keys(self::$indexParameters))) {
2222
-					$parameters = $property->parameters();
2223
-					$indexedParametersForProperty = self::$indexParameters[$property->name];
2224
-
2225
-					foreach ($parameters as $key => $value) {
2226
-						if (in_array($key, $indexedParametersForProperty)) {
2227
-							// is this a shitty db?
2228
-							if ($this->db->supports4ByteText()) {
2229
-								$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2230
-							}
2231
-							$value = substr($value, 0, 254);
2232
-
2233
-							$query->setParameter('name', $property->name);
2234
-							$query->setParameter('parameter', substr($key, 0, 254));
2235
-							$query->setParameter('value', substr($value, 0, 254));
2236
-							$query->execute();
2237
-						}
2238
-					}
2239
-				}
2240
-			}
2241
-		}
2242
-	}
2243
-
2244
-	/**
2245
-	 * read VCalendar data into a VCalendar object
2246
-	 *
2247
-	 * @param string $objectData
2248
-	 * @return VCalendar
2249
-	 */
2250
-	protected function readCalendarData($objectData) {
2251
-		return Reader::read($objectData);
2252
-	}
2253
-
2254
-	/**
2255
-	 * delete all properties from a given calendar object
2256
-	 *
2257
-	 * @param int $calendarId
2258
-	 * @param int $objectId
2259
-	 */
2260
-	protected function purgeProperties($calendarId, $objectId) {
2261
-		$query = $this->db->getQueryBuilder();
2262
-		$query->delete($this->dbObjectPropertiesTable)
2263
-			->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
2264
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2265
-		$query->execute();
2266
-	}
2267
-
2268
-	/**
2269
-	 * get ID from a given calendar object
2270
-	 *
2271
-	 * @param int $calendarId
2272
-	 * @param string $uri
2273
-	 * @return int
2274
-	 */
2275
-	protected function getCalendarObjectId($calendarId, $uri) {
2276
-		$query = $this->db->getQueryBuilder();
2277
-		$query->select('id')->from('calendarobjects')
2278
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2279
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2280
-
2281
-		$result = $query->execute();
2282
-		$objectIds = $result->fetch();
2283
-		$result->closeCursor();
2284
-
2285
-		if (!isset($objectIds['id'])) {
2286
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2287
-		}
2288
-
2289
-		return (int)$objectIds['id'];
2290
-	}
2291
-
2292
-	private function convertPrincipal($principalUri, $toV2) {
2293
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2294
-			list(, $name) = Uri\split($principalUri);
2295
-			if ($toV2 === true) {
2296
-				return "principals/users/$name";
2297
-			}
2298
-			return "principals/$name";
2299
-		}
2300
-		return $principalUri;
2301
-	}
2302
-
2303
-	private function addOwnerPrincipal(&$calendarInfo) {
2304
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2305
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2306
-		if (isset($calendarInfo[$ownerPrincipalKey])) {
2307
-			$uri = $calendarInfo[$ownerPrincipalKey];
2308
-		} else {
2309
-			$uri = $calendarInfo['principaluri'];
2310
-		}
2311
-
2312
-		$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
2313
-		if (isset($principalInformation['{DAV:}displayname'])) {
2314
-			$calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
2315
-		}
2316
-	}
424
+    /**
425
+     * @return array
426
+     */
427
+    public function getPublicCalendars() {
428
+        $fields = array_values($this->propertyMap);
429
+        $fields[] = 'a.id';
430
+        $fields[] = 'a.uri';
431
+        $fields[] = 'a.synctoken';
432
+        $fields[] = 'a.components';
433
+        $fields[] = 'a.principaluri';
434
+        $fields[] = 'a.transparent';
435
+        $fields[] = 's.access';
436
+        $fields[] = 's.publicuri';
437
+        $calendars = [];
438
+        $query = $this->db->getQueryBuilder();
439
+        $result = $query->select($fields)
440
+            ->from('dav_shares', 's')
441
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
442
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
443
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
444
+            ->execute();
445
+
446
+        while($row = $result->fetch()) {
447
+            list(, $name) = Uri\split($row['principaluri']);
448
+            $row['displayname'] = $row['displayname'] . "($name)";
449
+            $components = [];
450
+            if ($row['components']) {
451
+                $components = explode(',',$row['components']);
452
+            }
453
+            $calendar = [
454
+                'id' => $row['id'],
455
+                'uri' => $row['publicuri'],
456
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
457
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
458
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
459
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
460
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
461
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
462
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
463
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
464
+            ];
465
+
466
+            foreach($this->propertyMap as $xmlName=>$dbName) {
467
+                $calendar[$xmlName] = $row[$dbName];
468
+            }
469
+
470
+            $this->addOwnerPrincipal($calendar);
471
+
472
+            if (!isset($calendars[$calendar['id']])) {
473
+                $calendars[$calendar['id']] = $calendar;
474
+            }
475
+        }
476
+        $result->closeCursor();
477
+
478
+        return array_values($calendars);
479
+    }
480
+
481
+    /**
482
+     * @param string $uri
483
+     * @return array
484
+     * @throws NotFound
485
+     */
486
+    public function getPublicCalendar($uri) {
487
+        $fields = array_values($this->propertyMap);
488
+        $fields[] = 'a.id';
489
+        $fields[] = 'a.uri';
490
+        $fields[] = 'a.synctoken';
491
+        $fields[] = 'a.components';
492
+        $fields[] = 'a.principaluri';
493
+        $fields[] = 'a.transparent';
494
+        $fields[] = 's.access';
495
+        $fields[] = 's.publicuri';
496
+        $query = $this->db->getQueryBuilder();
497
+        $result = $query->select($fields)
498
+            ->from('dav_shares', 's')
499
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
500
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
501
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
502
+            ->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
503
+            ->execute();
504
+
505
+        $row = $result->fetch(\PDO::FETCH_ASSOC);
506
+
507
+        $result->closeCursor();
508
+
509
+        if ($row === false) {
510
+            throw new NotFound('Node with name \'' . $uri . '\' could not be found');
511
+        }
512
+
513
+        list(, $name) = Uri\split($row['principaluri']);
514
+        $row['displayname'] = $row['displayname'] . ' ' . "($name)";
515
+        $components = [];
516
+        if ($row['components']) {
517
+            $components = explode(',',$row['components']);
518
+        }
519
+        $calendar = [
520
+            'id' => $row['id'],
521
+            'uri' => $row['publicuri'],
522
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
523
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
524
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
525
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
526
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
527
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
528
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
529
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
530
+        ];
531
+
532
+        foreach($this->propertyMap as $xmlName=>$dbName) {
533
+            $calendar[$xmlName] = $row[$dbName];
534
+        }
535
+
536
+        $this->addOwnerPrincipal($calendar);
537
+
538
+        return $calendar;
539
+
540
+    }
541
+
542
+    /**
543
+     * @param string $principal
544
+     * @param string $uri
545
+     * @return array|null
546
+     */
547
+    public function getCalendarByUri($principal, $uri) {
548
+        $fields = array_values($this->propertyMap);
549
+        $fields[] = 'id';
550
+        $fields[] = 'uri';
551
+        $fields[] = 'synctoken';
552
+        $fields[] = 'components';
553
+        $fields[] = 'principaluri';
554
+        $fields[] = 'transparent';
555
+
556
+        // Making fields a comma-delimited list
557
+        $query = $this->db->getQueryBuilder();
558
+        $query->select($fields)->from('calendars')
559
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
560
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
561
+            ->setMaxResults(1);
562
+        $stmt = $query->execute();
563
+
564
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
565
+        $stmt->closeCursor();
566
+        if ($row === false) {
567
+            return null;
568
+        }
569
+
570
+        $components = [];
571
+        if ($row['components']) {
572
+            $components = explode(',',$row['components']);
573
+        }
574
+
575
+        $calendar = [
576
+            'id' => $row['id'],
577
+            'uri' => $row['uri'],
578
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
579
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
580
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
581
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
582
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
583
+        ];
584
+
585
+        foreach($this->propertyMap as $xmlName=>$dbName) {
586
+            $calendar[$xmlName] = $row[$dbName];
587
+        }
588
+
589
+        $this->addOwnerPrincipal($calendar);
590
+
591
+        return $calendar;
592
+    }
593
+
594
+    public function getCalendarById($calendarId) {
595
+        $fields = array_values($this->propertyMap);
596
+        $fields[] = 'id';
597
+        $fields[] = 'uri';
598
+        $fields[] = 'synctoken';
599
+        $fields[] = 'components';
600
+        $fields[] = 'principaluri';
601
+        $fields[] = 'transparent';
602
+
603
+        // Making fields a comma-delimited list
604
+        $query = $this->db->getQueryBuilder();
605
+        $query->select($fields)->from('calendars')
606
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
607
+            ->setMaxResults(1);
608
+        $stmt = $query->execute();
609
+
610
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
611
+        $stmt->closeCursor();
612
+        if ($row === false) {
613
+            return null;
614
+        }
615
+
616
+        $components = [];
617
+        if ($row['components']) {
618
+            $components = explode(',',$row['components']);
619
+        }
620
+
621
+        $calendar = [
622
+            'id' => $row['id'],
623
+            'uri' => $row['uri'],
624
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
625
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
626
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
627
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
628
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
629
+        ];
630
+
631
+        foreach($this->propertyMap as $xmlName=>$dbName) {
632
+            $calendar[$xmlName] = $row[$dbName];
633
+        }
634
+
635
+        $this->addOwnerPrincipal($calendar);
636
+
637
+        return $calendar;
638
+    }
639
+
640
+    /**
641
+     * Creates a new calendar for a principal.
642
+     *
643
+     * If the creation was a success, an id must be returned that can be used to reference
644
+     * this calendar in other methods, such as updateCalendar.
645
+     *
646
+     * @param string $principalUri
647
+     * @param string $calendarUri
648
+     * @param array $properties
649
+     * @return int
650
+     * @suppress SqlInjectionChecker
651
+     */
652
+    function createCalendar($principalUri, $calendarUri, array $properties) {
653
+        $values = [
654
+            'principaluri' => $this->convertPrincipal($principalUri, true),
655
+            'uri'          => $calendarUri,
656
+            'synctoken'    => 1,
657
+            'transparent'  => 0,
658
+            'components'   => 'VEVENT,VTODO',
659
+            'displayname'  => $calendarUri
660
+        ];
661
+
662
+        // Default value
663
+        $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
664
+        if (isset($properties[$sccs])) {
665
+            if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
666
+                throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
667
+            }
668
+            $values['components'] = implode(',',$properties[$sccs]->getValue());
669
+        }
670
+        $transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
671
+        if (isset($properties[$transp])) {
672
+            $values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
673
+        }
674
+
675
+        foreach($this->propertyMap as $xmlName=>$dbName) {
676
+            if (isset($properties[$xmlName])) {
677
+                $values[$dbName] = $properties[$xmlName];
678
+            }
679
+        }
680
+
681
+        $query = $this->db->getQueryBuilder();
682
+        $query->insert('calendars');
683
+        foreach($values as $column => $value) {
684
+            $query->setValue($column, $query->createNamedParameter($value));
685
+        }
686
+        $query->execute();
687
+        $calendarId = $query->getLastInsertId();
688
+
689
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
690
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
691
+            [
692
+                'calendarId' => $calendarId,
693
+                'calendarData' => $this->getCalendarById($calendarId),
694
+        ]));
695
+
696
+        return $calendarId;
697
+    }
698
+
699
+    /**
700
+     * Updates properties for a calendar.
701
+     *
702
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
703
+     * To do the actual updates, you must tell this object which properties
704
+     * you're going to process with the handle() method.
705
+     *
706
+     * Calling the handle method is like telling the PropPatch object "I
707
+     * promise I can handle updating this property".
708
+     *
709
+     * Read the PropPatch documentation for more info and examples.
710
+     *
711
+     * @param mixed $calendarId
712
+     * @param PropPatch $propPatch
713
+     * @return void
714
+     */
715
+    function updateCalendar($calendarId, PropPatch $propPatch) {
716
+        $supportedProperties = array_keys($this->propertyMap);
717
+        $supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
718
+
719
+        /**
720
+         * @suppress SqlInjectionChecker
721
+         */
722
+        $propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
723
+            $newValues = [];
724
+            foreach ($mutations as $propertyName => $propertyValue) {
725
+
726
+                switch ($propertyName) {
727
+                    case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
728
+                        $fieldName = 'transparent';
729
+                        $newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
730
+                        break;
731
+                    default :
732
+                        $fieldName = $this->propertyMap[$propertyName];
733
+                        $newValues[$fieldName] = $propertyValue;
734
+                        break;
735
+                }
736
+
737
+            }
738
+            $query = $this->db->getQueryBuilder();
739
+            $query->update('calendars');
740
+            foreach ($newValues as $fieldName => $value) {
741
+                $query->set($fieldName, $query->createNamedParameter($value));
742
+            }
743
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
744
+            $query->execute();
745
+
746
+            $this->addChange($calendarId, "", 2);
747
+
748
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
749
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
750
+                [
751
+                    'calendarId' => $calendarId,
752
+                    'calendarData' => $this->getCalendarById($calendarId),
753
+                    'shares' => $this->getShares($calendarId),
754
+                    'propertyMutations' => $mutations,
755
+            ]));
756
+
757
+            return true;
758
+        });
759
+    }
760
+
761
+    /**
762
+     * Delete a calendar and all it's objects
763
+     *
764
+     * @param mixed $calendarId
765
+     * @return void
766
+     */
767
+    function deleteCalendar($calendarId) {
768
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
769
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
770
+            [
771
+                'calendarId' => $calendarId,
772
+                'calendarData' => $this->getCalendarById($calendarId),
773
+                'shares' => $this->getShares($calendarId),
774
+        ]));
775
+
776
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?');
777
+        $stmt->execute([$calendarId]);
778
+
779
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
780
+        $stmt->execute([$calendarId]);
781
+
782
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ?');
783
+        $stmt->execute([$calendarId]);
784
+
785
+        $this->sharingBackend->deleteAllShares($calendarId);
786
+
787
+        $query = $this->db->getQueryBuilder();
788
+        $query->delete($this->dbObjectPropertiesTable)
789
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
790
+            ->execute();
791
+    }
792
+
793
+    /**
794
+     * Delete all of an user's shares
795
+     *
796
+     * @param string $principaluri
797
+     * @return void
798
+     */
799
+    function deleteAllSharesByUser($principaluri) {
800
+        $this->sharingBackend->deleteAllSharesByUser($principaluri);
801
+    }
802
+
803
+    /**
804
+     * Returns all calendar objects within a calendar.
805
+     *
806
+     * Every item contains an array with the following keys:
807
+     *   * calendardata - The iCalendar-compatible calendar data
808
+     *   * uri - a unique key which will be used to construct the uri. This can
809
+     *     be any arbitrary string, but making sure it ends with '.ics' is a
810
+     *     good idea. This is only the basename, or filename, not the full
811
+     *     path.
812
+     *   * lastmodified - a timestamp of the last modification time
813
+     *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
814
+     *   '"abcdef"')
815
+     *   * size - The size of the calendar objects, in bytes.
816
+     *   * component - optional, a string containing the type of object, such
817
+     *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
818
+     *     the Content-Type header.
819
+     *
820
+     * Note that the etag is optional, but it's highly encouraged to return for
821
+     * speed reasons.
822
+     *
823
+     * The calendardata is also optional. If it's not returned
824
+     * 'getCalendarObject' will be called later, which *is* expected to return
825
+     * calendardata.
826
+     *
827
+     * If neither etag or size are specified, the calendardata will be
828
+     * used/fetched to determine these numbers. If both are specified the
829
+     * amount of times this is needed is reduced by a great degree.
830
+     *
831
+     * @param mixed $calendarId
832
+     * @return array
833
+     */
834
+    function getCalendarObjects($calendarId) {
835
+        $query = $this->db->getQueryBuilder();
836
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
837
+            ->from('calendarobjects')
838
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
839
+        $stmt = $query->execute();
840
+
841
+        $result = [];
842
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
843
+            $result[] = [
844
+                    'id'           => $row['id'],
845
+                    'uri'          => $row['uri'],
846
+                    'lastmodified' => $row['lastmodified'],
847
+                    'etag'         => '"' . $row['etag'] . '"',
848
+                    'calendarid'   => $row['calendarid'],
849
+                    'size'         => (int)$row['size'],
850
+                    'component'    => strtolower($row['componenttype']),
851
+                    'classification'=> (int)$row['classification']
852
+            ];
853
+        }
854
+
855
+        return $result;
856
+    }
857
+
858
+    /**
859
+     * Returns information from a single calendar object, based on it's object
860
+     * uri.
861
+     *
862
+     * The object uri is only the basename, or filename and not a full path.
863
+     *
864
+     * The returned array must have the same keys as getCalendarObjects. The
865
+     * 'calendardata' object is required here though, while it's not required
866
+     * for getCalendarObjects.
867
+     *
868
+     * This method must return null if the object did not exist.
869
+     *
870
+     * @param mixed $calendarId
871
+     * @param string $objectUri
872
+     * @return array|null
873
+     */
874
+    function getCalendarObject($calendarId, $objectUri) {
875
+
876
+        $query = $this->db->getQueryBuilder();
877
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
878
+                ->from('calendarobjects')
879
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
880
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)));
881
+        $stmt = $query->execute();
882
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
883
+
884
+        if(!$row) return null;
885
+
886
+        return [
887
+                'id'            => $row['id'],
888
+                'uri'           => $row['uri'],
889
+                'lastmodified'  => $row['lastmodified'],
890
+                'etag'          => '"' . $row['etag'] . '"',
891
+                'calendarid'    => $row['calendarid'],
892
+                'size'          => (int)$row['size'],
893
+                'calendardata'  => $this->readBlob($row['calendardata']),
894
+                'component'     => strtolower($row['componenttype']),
895
+                'classification'=> (int)$row['classification']
896
+        ];
897
+    }
898
+
899
+    /**
900
+     * Returns a list of calendar objects.
901
+     *
902
+     * This method should work identical to getCalendarObject, but instead
903
+     * return all the calendar objects in the list as an array.
904
+     *
905
+     * If the backend supports this, it may allow for some speed-ups.
906
+     *
907
+     * @param mixed $calendarId
908
+     * @param string[] $uris
909
+     * @return array
910
+     */
911
+    function getMultipleCalendarObjects($calendarId, array $uris) {
912
+        if (empty($uris)) {
913
+            return [];
914
+        }
915
+
916
+        $chunks = array_chunk($uris, 100);
917
+        $objects = [];
918
+
919
+        $query = $this->db->getQueryBuilder();
920
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
921
+            ->from('calendarobjects')
922
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
923
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
924
+
925
+        foreach ($chunks as $uris) {
926
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
927
+            $result = $query->execute();
928
+
929
+            while ($row = $result->fetch()) {
930
+                $objects[] = [
931
+                    'id'           => $row['id'],
932
+                    'uri'          => $row['uri'],
933
+                    'lastmodified' => $row['lastmodified'],
934
+                    'etag'         => '"' . $row['etag'] . '"',
935
+                    'calendarid'   => $row['calendarid'],
936
+                    'size'         => (int)$row['size'],
937
+                    'calendardata' => $this->readBlob($row['calendardata']),
938
+                    'component'    => strtolower($row['componenttype']),
939
+                    'classification' => (int)$row['classification']
940
+                ];
941
+            }
942
+            $result->closeCursor();
943
+        }
944
+        return $objects;
945
+    }
946
+
947
+    /**
948
+     * Creates a new calendar object.
949
+     *
950
+     * The object uri is only the basename, or filename and not a full path.
951
+     *
952
+     * It is possible return an etag from this function, which will be used in
953
+     * the response to this PUT request. Note that the ETag must be surrounded
954
+     * by double-quotes.
955
+     *
956
+     * However, you should only really return this ETag if you don't mangle the
957
+     * calendar-data. If the result of a subsequent GET to this object is not
958
+     * the exact same as this request body, you should omit the ETag.
959
+     *
960
+     * @param mixed $calendarId
961
+     * @param string $objectUri
962
+     * @param string $calendarData
963
+     * @return string
964
+     */
965
+    function createCalendarObject($calendarId, $objectUri, $calendarData) {
966
+        $extraData = $this->getDenormalizedData($calendarData);
967
+
968
+        $q = $this->db->getQueryBuilder();
969
+        $q->select($q->createFunction('COUNT(*)'))
970
+            ->from('calendarobjects')
971
+            ->where($q->expr()->eq('calendarid', $q->createNamedParameter($calendarId)))
972
+            ->andWhere($q->expr()->eq('uid', $q->createNamedParameter($extraData['uid'])));
973
+
974
+        $result = $q->execute();
975
+        $count = (int) $result->fetchColumn();
976
+        $result->closeCursor();
977
+
978
+        if ($count !== 0) {
979
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar object with uid already exists in this calendar collection.');
980
+        }
981
+
982
+        $query = $this->db->getQueryBuilder();
983
+        $query->insert('calendarobjects')
984
+            ->values([
985
+                'calendarid' => $query->createNamedParameter($calendarId),
986
+                'uri' => $query->createNamedParameter($objectUri),
987
+                'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
988
+                'lastmodified' => $query->createNamedParameter(time()),
989
+                'etag' => $query->createNamedParameter($extraData['etag']),
990
+                'size' => $query->createNamedParameter($extraData['size']),
991
+                'componenttype' => $query->createNamedParameter($extraData['componentType']),
992
+                'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
993
+                'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
994
+                'classification' => $query->createNamedParameter($extraData['classification']),
995
+                'uid' => $query->createNamedParameter($extraData['uid']),
996
+            ])
997
+            ->execute();
998
+
999
+        $this->updateProperties($calendarId, $objectUri, $calendarData);
1000
+
1001
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
1002
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
1003
+            [
1004
+                'calendarId' => $calendarId,
1005
+                'calendarData' => $this->getCalendarById($calendarId),
1006
+                'shares' => $this->getShares($calendarId),
1007
+                'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1008
+            ]
1009
+        ));
1010
+        $this->addChange($calendarId, $objectUri, 1);
1011
+
1012
+        return '"' . $extraData['etag'] . '"';
1013
+    }
1014
+
1015
+    /**
1016
+     * Updates an existing calendarobject, based on it's uri.
1017
+     *
1018
+     * The object uri is only the basename, or filename and not a full path.
1019
+     *
1020
+     * It is possible return an etag from this function, which will be used in
1021
+     * the response to this PUT request. Note that the ETag must be surrounded
1022
+     * by double-quotes.
1023
+     *
1024
+     * However, you should only really return this ETag if you don't mangle the
1025
+     * calendar-data. If the result of a subsequent GET to this object is not
1026
+     * the exact same as this request body, you should omit the ETag.
1027
+     *
1028
+     * @param mixed $calendarId
1029
+     * @param string $objectUri
1030
+     * @param string $calendarData
1031
+     * @return string
1032
+     */
1033
+    function updateCalendarObject($calendarId, $objectUri, $calendarData) {
1034
+        $extraData = $this->getDenormalizedData($calendarData);
1035
+
1036
+        $query = $this->db->getQueryBuilder();
1037
+        $query->update('calendarobjects')
1038
+                ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1039
+                ->set('lastmodified', $query->createNamedParameter(time()))
1040
+                ->set('etag', $query->createNamedParameter($extraData['etag']))
1041
+                ->set('size', $query->createNamedParameter($extraData['size']))
1042
+                ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1043
+                ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1044
+                ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1045
+                ->set('classification', $query->createNamedParameter($extraData['classification']))
1046
+                ->set('uid', $query->createNamedParameter($extraData['uid']))
1047
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1048
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1049
+            ->execute();
1050
+
1051
+        $this->updateProperties($calendarId, $objectUri, $calendarData);
1052
+
1053
+        $data = $this->getCalendarObject($calendarId, $objectUri);
1054
+        if (is_array($data)) {
1055
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1056
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1057
+                [
1058
+                    'calendarId' => $calendarId,
1059
+                    'calendarData' => $this->getCalendarById($calendarId),
1060
+                    'shares' => $this->getShares($calendarId),
1061
+                    'objectData' => $data,
1062
+                ]
1063
+            ));
1064
+        }
1065
+        $this->addChange($calendarId, $objectUri, 2);
1066
+
1067
+        return '"' . $extraData['etag'] . '"';
1068
+    }
1069
+
1070
+    /**
1071
+     * @param int $calendarObjectId
1072
+     * @param int $classification
1073
+     */
1074
+    public function setClassification($calendarObjectId, $classification) {
1075
+        if (!in_array($classification, [
1076
+            self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1077
+        ])) {
1078
+            throw new \InvalidArgumentException();
1079
+        }
1080
+        $query = $this->db->getQueryBuilder();
1081
+        $query->update('calendarobjects')
1082
+            ->set('classification', $query->createNamedParameter($classification))
1083
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1084
+            ->execute();
1085
+    }
1086
+
1087
+    /**
1088
+     * Deletes an existing calendar object.
1089
+     *
1090
+     * The object uri is only the basename, or filename and not a full path.
1091
+     *
1092
+     * @param mixed $calendarId
1093
+     * @param string $objectUri
1094
+     * @return void
1095
+     */
1096
+    function deleteCalendarObject($calendarId, $objectUri) {
1097
+        $data = $this->getCalendarObject($calendarId, $objectUri);
1098
+        if (is_array($data)) {
1099
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1100
+                '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1101
+                [
1102
+                    'calendarId' => $calendarId,
1103
+                    'calendarData' => $this->getCalendarById($calendarId),
1104
+                    'shares' => $this->getShares($calendarId),
1105
+                    'objectData' => $data,
1106
+                ]
1107
+            ));
1108
+        }
1109
+
1110
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ?');
1111
+        $stmt->execute([$calendarId, $objectUri]);
1112
+
1113
+        $this->purgeProperties($calendarId, $data['id']);
1114
+
1115
+        $this->addChange($calendarId, $objectUri, 3);
1116
+    }
1117
+
1118
+    /**
1119
+     * Performs a calendar-query on the contents of this calendar.
1120
+     *
1121
+     * The calendar-query is defined in RFC4791 : CalDAV. Using the
1122
+     * calendar-query it is possible for a client to request a specific set of
1123
+     * object, based on contents of iCalendar properties, date-ranges and
1124
+     * iCalendar component types (VTODO, VEVENT).
1125
+     *
1126
+     * This method should just return a list of (relative) urls that match this
1127
+     * query.
1128
+     *
1129
+     * The list of filters are specified as an array. The exact array is
1130
+     * documented by Sabre\CalDAV\CalendarQueryParser.
1131
+     *
1132
+     * Note that it is extremely likely that getCalendarObject for every path
1133
+     * returned from this method will be called almost immediately after. You
1134
+     * may want to anticipate this to speed up these requests.
1135
+     *
1136
+     * This method provides a default implementation, which parses *all* the
1137
+     * iCalendar objects in the specified calendar.
1138
+     *
1139
+     * This default may well be good enough for personal use, and calendars
1140
+     * that aren't very large. But if you anticipate high usage, big calendars
1141
+     * or high loads, you are strongly advised to optimize certain paths.
1142
+     *
1143
+     * The best way to do so is override this method and to optimize
1144
+     * specifically for 'common filters'.
1145
+     *
1146
+     * Requests that are extremely common are:
1147
+     *   * requests for just VEVENTS
1148
+     *   * requests for just VTODO
1149
+     *   * requests with a time-range-filter on either VEVENT or VTODO.
1150
+     *
1151
+     * ..and combinations of these requests. It may not be worth it to try to
1152
+     * handle every possible situation and just rely on the (relatively
1153
+     * easy to use) CalendarQueryValidator to handle the rest.
1154
+     *
1155
+     * Note that especially time-range-filters may be difficult to parse. A
1156
+     * time-range filter specified on a VEVENT must for instance also handle
1157
+     * recurrence rules correctly.
1158
+     * A good example of how to interprete all these filters can also simply
1159
+     * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1160
+     * as possible, so it gives you a good idea on what type of stuff you need
1161
+     * to think of.
1162
+     *
1163
+     * @param mixed $calendarId
1164
+     * @param array $filters
1165
+     * @return array
1166
+     */
1167
+    function calendarQuery($calendarId, array $filters) {
1168
+        $componentType = null;
1169
+        $requirePostFilter = true;
1170
+        $timeRange = null;
1171
+
1172
+        // if no filters were specified, we don't need to filter after a query
1173
+        if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1174
+            $requirePostFilter = false;
1175
+        }
1176
+
1177
+        // Figuring out if there's a component filter
1178
+        if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1179
+            $componentType = $filters['comp-filters'][0]['name'];
1180
+
1181
+            // Checking if we need post-filters
1182
+            if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1183
+                $requirePostFilter = false;
1184
+            }
1185
+            // There was a time-range filter
1186
+            if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1187
+                $timeRange = $filters['comp-filters'][0]['time-range'];
1188
+
1189
+                // If start time OR the end time is not specified, we can do a
1190
+                // 100% accurate mysql query.
1191
+                if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1192
+                    $requirePostFilter = false;
1193
+                }
1194
+            }
1195
+
1196
+        }
1197
+        $columns = ['uri'];
1198
+        if ($requirePostFilter) {
1199
+            $columns = ['uri', 'calendardata'];
1200
+        }
1201
+        $query = $this->db->getQueryBuilder();
1202
+        $query->select($columns)
1203
+            ->from('calendarobjects')
1204
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
1205
+
1206
+        if ($componentType) {
1207
+            $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1208
+        }
1209
+
1210
+        if ($timeRange && $timeRange['start']) {
1211
+            $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1212
+        }
1213
+        if ($timeRange && $timeRange['end']) {
1214
+            $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1215
+        }
1216
+
1217
+        $stmt = $query->execute();
1218
+
1219
+        $result = [];
1220
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1221
+            if ($requirePostFilter) {
1222
+                if (!$this->validateFilterForObject($row, $filters)) {
1223
+                    continue;
1224
+                }
1225
+            }
1226
+            $result[] = $row['uri'];
1227
+        }
1228
+
1229
+        return $result;
1230
+    }
1231
+
1232
+    /**
1233
+     * custom Nextcloud search extension for CalDAV
1234
+     *
1235
+     * @param string $principalUri
1236
+     * @param array $filters
1237
+     * @param integer|null $limit
1238
+     * @param integer|null $offset
1239
+     * @return array
1240
+     */
1241
+    public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1242
+        $calendars = $this->getCalendarsForUser($principalUri);
1243
+        $ownCalendars = [];
1244
+        $sharedCalendars = [];
1245
+
1246
+        $uriMapper = [];
1247
+
1248
+        foreach($calendars as $calendar) {
1249
+            if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1250
+                $ownCalendars[] = $calendar['id'];
1251
+            } else {
1252
+                $sharedCalendars[] = $calendar['id'];
1253
+            }
1254
+            $uriMapper[$calendar['id']] = $calendar['uri'];
1255
+        }
1256
+        if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1257
+            return [];
1258
+        }
1259
+
1260
+        $query = $this->db->getQueryBuilder();
1261
+        // Calendar id expressions
1262
+        $calendarExpressions = [];
1263
+        foreach($ownCalendars as $id) {
1264
+            $calendarExpressions[] = $query->expr()
1265
+                ->eq('c.calendarid', $query->createNamedParameter($id));
1266
+        }
1267
+        foreach($sharedCalendars as $id) {
1268
+            $calendarExpressions[] = $query->expr()->andX(
1269
+                $query->expr()->eq('c.calendarid',
1270
+                    $query->createNamedParameter($id)),
1271
+                $query->expr()->eq('c.classification',
1272
+                    $query->createNamedParameter(self::CLASSIFICATION_PUBLIC))
1273
+            );
1274
+        }
1275
+
1276
+        if (count($calendarExpressions) === 1) {
1277
+            $calExpr = $calendarExpressions[0];
1278
+        } else {
1279
+            $calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1280
+        }
1281
+
1282
+        // Component expressions
1283
+        $compExpressions = [];
1284
+        foreach($filters['comps'] as $comp) {
1285
+            $compExpressions[] = $query->expr()
1286
+                ->eq('c.componenttype', $query->createNamedParameter($comp));
1287
+        }
1288
+
1289
+        if (count($compExpressions) === 1) {
1290
+            $compExpr = $compExpressions[0];
1291
+        } else {
1292
+            $compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1293
+        }
1294
+
1295
+        if (!isset($filters['props'])) {
1296
+            $filters['props'] = [];
1297
+        }
1298
+        if (!isset($filters['params'])) {
1299
+            $filters['params'] = [];
1300
+        }
1301
+
1302
+        $propParamExpressions = [];
1303
+        foreach($filters['props'] as $prop) {
1304
+            $propParamExpressions[] = $query->expr()->andX(
1305
+                $query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1306
+                $query->expr()->isNull('i.parameter')
1307
+            );
1308
+        }
1309
+        foreach($filters['params'] as $param) {
1310
+            $propParamExpressions[] = $query->expr()->andX(
1311
+                $query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1312
+                $query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1313
+            );
1314
+        }
1315
+
1316
+        if (count($propParamExpressions) === 1) {
1317
+            $propParamExpr = $propParamExpressions[0];
1318
+        } else {
1319
+            $propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1320
+        }
1321
+
1322
+        $query->select(['c.calendarid', 'c.uri'])
1323
+            ->from($this->dbObjectPropertiesTable, 'i')
1324
+            ->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1325
+            ->where($calExpr)
1326
+            ->andWhere($compExpr)
1327
+            ->andWhere($propParamExpr)
1328
+            ->andWhere($query->expr()->iLike('i.value',
1329
+                $query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
1330
+
1331
+        if ($offset) {
1332
+            $query->setFirstResult($offset);
1333
+        }
1334
+        if ($limit) {
1335
+            $query->setMaxResults($limit);
1336
+        }
1337
+
1338
+        $stmt = $query->execute();
1339
+
1340
+        $result = [];
1341
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1342
+            $path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1343
+            if (!in_array($path, $result)) {
1344
+                $result[] = $path;
1345
+            }
1346
+        }
1347
+
1348
+        return $result;
1349
+    }
1350
+
1351
+    /**
1352
+     * used for Nextcloud's calendar API
1353
+     *
1354
+     * @param array $calendarInfo
1355
+     * @param string $pattern
1356
+     * @param array $searchProperties
1357
+     * @param array $options
1358
+     * @param integer|null $limit
1359
+     * @param integer|null $offset
1360
+     *
1361
+     * @return array
1362
+     */
1363
+    public function search(array $calendarInfo, $pattern, array $searchProperties,
1364
+                            array $options, $limit, $offset) {
1365
+        $outerQuery = $this->db->getQueryBuilder();
1366
+        $innerQuery = $this->db->getQueryBuilder();
1367
+
1368
+        $innerQuery->selectDistinct('op.objectid')
1369
+            ->from($this->dbObjectPropertiesTable, 'op')
1370
+            ->andWhere($innerQuery->expr()->eq('op.calendarid',
1371
+                $outerQuery->createNamedParameter($calendarInfo['id'])));
1372
+
1373
+        // only return public items for shared calendars for now
1374
+        if ($calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1375
+            $innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
1376
+                $outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1377
+        }
1378
+
1379
+        $or = $innerQuery->expr()->orX();
1380
+        foreach($searchProperties as $searchProperty) {
1381
+            $or->add($innerQuery->expr()->eq('op.name',
1382
+                $outerQuery->createNamedParameter($searchProperty)));
1383
+        }
1384
+        $innerQuery->andWhere($or);
1385
+
1386
+        // TODO - add component-type
1387
+
1388
+        if ($pattern !== '') {
1389
+            $innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1390
+                $outerQuery->createNamedParameter('%' .
1391
+                    $this->db->escapeLikeParameter($pattern) . '%')));
1392
+        }
1393
+
1394
+        $outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1395
+            ->from('calendarobjects', 'c');
1396
+
1397
+        if (isset($options['timerange'])) {
1398
+            if (isset($options['timerange']['start'])) {
1399
+                $outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
1400
+                    $outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp)));
1401
+
1402
+            }
1403
+            if (isset($options['timerange']['end'])) {
1404
+                $outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
1405
+                    $outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp)));
1406
+            }
1407
+
1408
+        }
1409
+
1410
+        $outerQuery->andWhere($outerQuery->expr()->in('c.id',
1411
+            $outerQuery->createFunction($innerQuery->getSQL())));
1412
+
1413
+        if ($offset) {
1414
+            $outerQuery->setFirstResult($offset);
1415
+        }
1416
+        if ($limit) {
1417
+            $outerQuery->setMaxResults($limit);
1418
+        }
1419
+
1420
+        $result = $outerQuery->execute();
1421
+        $calendarObjects = $result->fetchAll();
1422
+
1423
+        return array_map(function($o) {
1424
+            $calendarData = Reader::read($o['calendardata']);
1425
+            $comps = $calendarData->getComponents();
1426
+            $objects = [];
1427
+            $timezones = [];
1428
+            foreach($comps as $comp) {
1429
+                if ($comp instanceof VTimeZone) {
1430
+                    $timezones[] = $comp;
1431
+                } else {
1432
+                    $objects[] = $comp;
1433
+                }
1434
+            }
1435
+
1436
+            return [
1437
+                'id' => $o['id'],
1438
+                'type' => $o['componenttype'],
1439
+                'uid' => $o['uid'],
1440
+                'uri' => $o['uri'],
1441
+                'objects' => array_map(function($c) {
1442
+                    return $this->transformSearchData($c);
1443
+                }, $objects),
1444
+                'timezones' => array_map(function($c) {
1445
+                    return $this->transformSearchData($c);
1446
+                }, $timezones),
1447
+            ];
1448
+        }, $calendarObjects);
1449
+    }
1450
+
1451
+    /**
1452
+     * @param Component $comp
1453
+     * @return array
1454
+     */
1455
+    private function transformSearchData(Component $comp) {
1456
+        $data = [];
1457
+        /** @var Component[] $subComponents */
1458
+        $subComponents = $comp->getComponents();
1459
+        /** @var Property[] $properties */
1460
+        $properties = array_filter($comp->children(), function($c) {
1461
+            return $c instanceof Property;
1462
+        });
1463
+        $validationRules = $comp->getValidationRules();
1464
+
1465
+        foreach($subComponents as $subComponent) {
1466
+            $name = $subComponent->name;
1467
+            if (!isset($data[$name])) {
1468
+                $data[$name] = [];
1469
+            }
1470
+            $data[$name][] = $this->transformSearchData($subComponent);
1471
+        }
1472
+
1473
+        foreach($properties as $property) {
1474
+            $name = $property->name;
1475
+            if (!isset($validationRules[$name])) {
1476
+                $validationRules[$name] = '*';
1477
+            }
1478
+
1479
+            $rule = $validationRules[$property->name];
1480
+            if ($rule === '+' || $rule === '*') { // multiple
1481
+                if (!isset($data[$name])) {
1482
+                    $data[$name] = [];
1483
+                }
1484
+
1485
+                $data[$name][] = $this->transformSearchProperty($property);
1486
+            } else { // once
1487
+                $data[$name] = $this->transformSearchProperty($property);
1488
+            }
1489
+        }
1490
+
1491
+        return $data;
1492
+    }
1493
+
1494
+    /**
1495
+     * @param Property $prop
1496
+     * @return array
1497
+     */
1498
+    private function transformSearchProperty(Property $prop) {
1499
+        // No need to check Date, as it extends DateTime
1500
+        if ($prop instanceof Property\ICalendar\DateTime) {
1501
+            $value = $prop->getDateTime();
1502
+        } else {
1503
+            $value = $prop->getValue();
1504
+        }
1505
+
1506
+        return [
1507
+            $value,
1508
+            $prop->parameters()
1509
+        ];
1510
+    }
1511
+
1512
+    /**
1513
+     * Searches through all of a users calendars and calendar objects to find
1514
+     * an object with a specific UID.
1515
+     *
1516
+     * This method should return the path to this object, relative to the
1517
+     * calendar home, so this path usually only contains two parts:
1518
+     *
1519
+     * calendarpath/objectpath.ics
1520
+     *
1521
+     * If the uid is not found, return null.
1522
+     *
1523
+     * This method should only consider * objects that the principal owns, so
1524
+     * any calendars owned by other principals that also appear in this
1525
+     * collection should be ignored.
1526
+     *
1527
+     * @param string $principalUri
1528
+     * @param string $uid
1529
+     * @return string|null
1530
+     */
1531
+    function getCalendarObjectByUID($principalUri, $uid) {
1532
+
1533
+        $query = $this->db->getQueryBuilder();
1534
+        $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1535
+            ->from('calendarobjects', 'co')
1536
+            ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1537
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1538
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1539
+
1540
+        $stmt = $query->execute();
1541
+
1542
+        if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1543
+            return $row['calendaruri'] . '/' . $row['objecturi'];
1544
+        }
1545
+
1546
+        return null;
1547
+    }
1548
+
1549
+    /**
1550
+     * The getChanges method returns all the changes that have happened, since
1551
+     * the specified syncToken in the specified calendar.
1552
+     *
1553
+     * This function should return an array, such as the following:
1554
+     *
1555
+     * [
1556
+     *   'syncToken' => 'The current synctoken',
1557
+     *   'added'   => [
1558
+     *      'new.txt',
1559
+     *   ],
1560
+     *   'modified'   => [
1561
+     *      'modified.txt',
1562
+     *   ],
1563
+     *   'deleted' => [
1564
+     *      'foo.php.bak',
1565
+     *      'old.txt'
1566
+     *   ]
1567
+     * );
1568
+     *
1569
+     * The returned syncToken property should reflect the *current* syncToken
1570
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1571
+     * property This is * needed here too, to ensure the operation is atomic.
1572
+     *
1573
+     * If the $syncToken argument is specified as null, this is an initial
1574
+     * sync, and all members should be reported.
1575
+     *
1576
+     * The modified property is an array of nodenames that have changed since
1577
+     * the last token.
1578
+     *
1579
+     * The deleted property is an array with nodenames, that have been deleted
1580
+     * from collection.
1581
+     *
1582
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
1583
+     * 1, you only have to report changes that happened only directly in
1584
+     * immediate descendants. If it's 2, it should also include changes from
1585
+     * the nodes below the child collections. (grandchildren)
1586
+     *
1587
+     * The $limit argument allows a client to specify how many results should
1588
+     * be returned at most. If the limit is not specified, it should be treated
1589
+     * as infinite.
1590
+     *
1591
+     * If the limit (infinite or not) is higher than you're willing to return,
1592
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1593
+     *
1594
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
1595
+     * return null.
1596
+     *
1597
+     * The limit is 'suggestive'. You are free to ignore it.
1598
+     *
1599
+     * @param string $calendarId
1600
+     * @param string $syncToken
1601
+     * @param int $syncLevel
1602
+     * @param int $limit
1603
+     * @return array
1604
+     */
1605
+    function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1606
+        // Current synctoken
1607
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1608
+        $stmt->execute([ $calendarId ]);
1609
+        $currentToken = $stmt->fetchColumn(0);
1610
+
1611
+        if (is_null($currentToken)) {
1612
+            return null;
1613
+        }
1614
+
1615
+        $result = [
1616
+            'syncToken' => $currentToken,
1617
+            'added'     => [],
1618
+            'modified'  => [],
1619
+            'deleted'   => [],
1620
+        ];
1621
+
1622
+        if ($syncToken) {
1623
+
1624
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1625
+            if ($limit>0) {
1626
+                $query.= " LIMIT " . (int)$limit;
1627
+            }
1628
+
1629
+            // Fetching all changes
1630
+            $stmt = $this->db->prepare($query);
1631
+            $stmt->execute([$syncToken, $currentToken, $calendarId]);
1632
+
1633
+            $changes = [];
1634
+
1635
+            // This loop ensures that any duplicates are overwritten, only the
1636
+            // last change on a node is relevant.
1637
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1638
+
1639
+                $changes[$row['uri']] = $row['operation'];
1640
+
1641
+            }
1642
+
1643
+            foreach($changes as $uri => $operation) {
1644
+
1645
+                switch($operation) {
1646
+                    case 1 :
1647
+                        $result['added'][] = $uri;
1648
+                        break;
1649
+                    case 2 :
1650
+                        $result['modified'][] = $uri;
1651
+                        break;
1652
+                    case 3 :
1653
+                        $result['deleted'][] = $uri;
1654
+                        break;
1655
+                }
1656
+
1657
+            }
1658
+        } else {
1659
+            // No synctoken supplied, this is the initial sync.
1660
+            $query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?";
1661
+            $stmt = $this->db->prepare($query);
1662
+            $stmt->execute([$calendarId]);
1663
+
1664
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1665
+        }
1666
+        return $result;
1667
+
1668
+    }
1669
+
1670
+    /**
1671
+     * Returns a list of subscriptions for a principal.
1672
+     *
1673
+     * Every subscription is an array with the following keys:
1674
+     *  * id, a unique id that will be used by other functions to modify the
1675
+     *    subscription. This can be the same as the uri or a database key.
1676
+     *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1677
+     *  * principaluri. The owner of the subscription. Almost always the same as
1678
+     *    principalUri passed to this method.
1679
+     *
1680
+     * Furthermore, all the subscription info must be returned too:
1681
+     *
1682
+     * 1. {DAV:}displayname
1683
+     * 2. {http://apple.com/ns/ical/}refreshrate
1684
+     * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1685
+     *    should not be stripped).
1686
+     * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1687
+     *    should not be stripped).
1688
+     * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1689
+     *    attachments should not be stripped).
1690
+     * 6. {http://calendarserver.org/ns/}source (Must be a
1691
+     *     Sabre\DAV\Property\Href).
1692
+     * 7. {http://apple.com/ns/ical/}calendar-color
1693
+     * 8. {http://apple.com/ns/ical/}calendar-order
1694
+     * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1695
+     *    (should just be an instance of
1696
+     *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1697
+     *    default components).
1698
+     *
1699
+     * @param string $principalUri
1700
+     * @return array
1701
+     */
1702
+    function getSubscriptionsForUser($principalUri) {
1703
+        $fields = array_values($this->subscriptionPropertyMap);
1704
+        $fields[] = 'id';
1705
+        $fields[] = 'uri';
1706
+        $fields[] = 'source';
1707
+        $fields[] = 'principaluri';
1708
+        $fields[] = 'lastmodified';
1709
+
1710
+        $query = $this->db->getQueryBuilder();
1711
+        $query->select($fields)
1712
+            ->from('calendarsubscriptions')
1713
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1714
+            ->orderBy('calendarorder', 'asc');
1715
+        $stmt =$query->execute();
1716
+
1717
+        $subscriptions = [];
1718
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1719
+
1720
+            $subscription = [
1721
+                'id'           => $row['id'],
1722
+                'uri'          => $row['uri'],
1723
+                'principaluri' => $row['principaluri'],
1724
+                'source'       => $row['source'],
1725
+                'lastmodified' => $row['lastmodified'],
1726
+
1727
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1728
+            ];
1729
+
1730
+            foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1731
+                if (!is_null($row[$dbName])) {
1732
+                    $subscription[$xmlName] = $row[$dbName];
1733
+                }
1734
+            }
1735
+
1736
+            $subscriptions[] = $subscription;
1737
+
1738
+        }
1739
+
1740
+        return $subscriptions;
1741
+    }
1742
+
1743
+    /**
1744
+     * Creates a new subscription for a principal.
1745
+     *
1746
+     * If the creation was a success, an id must be returned that can be used to reference
1747
+     * this subscription in other methods, such as updateSubscription.
1748
+     *
1749
+     * @param string $principalUri
1750
+     * @param string $uri
1751
+     * @param array $properties
1752
+     * @return mixed
1753
+     */
1754
+    function createSubscription($principalUri, $uri, array $properties) {
1755
+
1756
+        if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1757
+            throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1758
+        }
1759
+
1760
+        $values = [
1761
+            'principaluri' => $principalUri,
1762
+            'uri'          => $uri,
1763
+            'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1764
+            'lastmodified' => time(),
1765
+        ];
1766
+
1767
+        $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1768
+
1769
+        foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1770
+            if (array_key_exists($xmlName, $properties)) {
1771
+                    $values[$dbName] = $properties[$xmlName];
1772
+                    if (in_array($dbName, $propertiesBoolean)) {
1773
+                        $values[$dbName] = true;
1774
+                }
1775
+            }
1776
+        }
1777
+
1778
+        $valuesToInsert = array();
1779
+
1780
+        $query = $this->db->getQueryBuilder();
1781
+
1782
+        foreach (array_keys($values) as $name) {
1783
+            $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1784
+        }
1785
+
1786
+        $query->insert('calendarsubscriptions')
1787
+            ->values($valuesToInsert)
1788
+            ->execute();
1789
+
1790
+        return $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1791
+    }
1792
+
1793
+    /**
1794
+     * Updates a subscription
1795
+     *
1796
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1797
+     * To do the actual updates, you must tell this object which properties
1798
+     * you're going to process with the handle() method.
1799
+     *
1800
+     * Calling the handle method is like telling the PropPatch object "I
1801
+     * promise I can handle updating this property".
1802
+     *
1803
+     * Read the PropPatch documentation for more info and examples.
1804
+     *
1805
+     * @param mixed $subscriptionId
1806
+     * @param PropPatch $propPatch
1807
+     * @return void
1808
+     */
1809
+    function updateSubscription($subscriptionId, PropPatch $propPatch) {
1810
+        $supportedProperties = array_keys($this->subscriptionPropertyMap);
1811
+        $supportedProperties[] = '{http://calendarserver.org/ns/}source';
1812
+
1813
+        /**
1814
+         * @suppress SqlInjectionChecker
1815
+         */
1816
+        $propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1817
+
1818
+            $newValues = [];
1819
+
1820
+            foreach($mutations as $propertyName=>$propertyValue) {
1821
+                if ($propertyName === '{http://calendarserver.org/ns/}source') {
1822
+                    $newValues['source'] = $propertyValue->getHref();
1823
+                } else {
1824
+                    $fieldName = $this->subscriptionPropertyMap[$propertyName];
1825
+                    $newValues[$fieldName] = $propertyValue;
1826
+                }
1827
+            }
1828
+
1829
+            $query = $this->db->getQueryBuilder();
1830
+            $query->update('calendarsubscriptions')
1831
+                ->set('lastmodified', $query->createNamedParameter(time()));
1832
+            foreach($newValues as $fieldName=>$value) {
1833
+                $query->set($fieldName, $query->createNamedParameter($value));
1834
+            }
1835
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1836
+                ->execute();
1837
+
1838
+            return true;
1839
+
1840
+        });
1841
+    }
1842
+
1843
+    /**
1844
+     * Deletes a subscription.
1845
+     *
1846
+     * @param mixed $subscriptionId
1847
+     * @return void
1848
+     */
1849
+    function deleteSubscription($subscriptionId) {
1850
+        $query = $this->db->getQueryBuilder();
1851
+        $query->delete('calendarsubscriptions')
1852
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1853
+            ->execute();
1854
+    }
1855
+
1856
+    /**
1857
+     * Returns a single scheduling object for the inbox collection.
1858
+     *
1859
+     * The returned array should contain the following elements:
1860
+     *   * uri - A unique basename for the object. This will be used to
1861
+     *           construct a full uri.
1862
+     *   * calendardata - The iCalendar object
1863
+     *   * lastmodified - The last modification date. Can be an int for a unix
1864
+     *                    timestamp, or a PHP DateTime object.
1865
+     *   * etag - A unique token that must change if the object changed.
1866
+     *   * size - The size of the object, in bytes.
1867
+     *
1868
+     * @param string $principalUri
1869
+     * @param string $objectUri
1870
+     * @return array
1871
+     */
1872
+    function getSchedulingObject($principalUri, $objectUri) {
1873
+        $query = $this->db->getQueryBuilder();
1874
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1875
+            ->from('schedulingobjects')
1876
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1877
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1878
+            ->execute();
1879
+
1880
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
1881
+
1882
+        if(!$row) {
1883
+            return null;
1884
+        }
1885
+
1886
+        return [
1887
+                'uri'          => $row['uri'],
1888
+                'calendardata' => $row['calendardata'],
1889
+                'lastmodified' => $row['lastmodified'],
1890
+                'etag'         => '"' . $row['etag'] . '"',
1891
+                'size'         => (int)$row['size'],
1892
+        ];
1893
+    }
1894
+
1895
+    /**
1896
+     * Returns all scheduling objects for the inbox collection.
1897
+     *
1898
+     * These objects should be returned as an array. Every item in the array
1899
+     * should follow the same structure as returned from getSchedulingObject.
1900
+     *
1901
+     * The main difference is that 'calendardata' is optional.
1902
+     *
1903
+     * @param string $principalUri
1904
+     * @return array
1905
+     */
1906
+    function getSchedulingObjects($principalUri) {
1907
+        $query = $this->db->getQueryBuilder();
1908
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1909
+                ->from('schedulingobjects')
1910
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1911
+                ->execute();
1912
+
1913
+        $result = [];
1914
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1915
+            $result[] = [
1916
+                    'calendardata' => $row['calendardata'],
1917
+                    'uri'          => $row['uri'],
1918
+                    'lastmodified' => $row['lastmodified'],
1919
+                    'etag'         => '"' . $row['etag'] . '"',
1920
+                    'size'         => (int)$row['size'],
1921
+            ];
1922
+        }
1923
+
1924
+        return $result;
1925
+    }
1926
+
1927
+    /**
1928
+     * Deletes a scheduling object from the inbox collection.
1929
+     *
1930
+     * @param string $principalUri
1931
+     * @param string $objectUri
1932
+     * @return void
1933
+     */
1934
+    function deleteSchedulingObject($principalUri, $objectUri) {
1935
+        $query = $this->db->getQueryBuilder();
1936
+        $query->delete('schedulingobjects')
1937
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1938
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1939
+                ->execute();
1940
+    }
1941
+
1942
+    /**
1943
+     * Creates a new scheduling object. This should land in a users' inbox.
1944
+     *
1945
+     * @param string $principalUri
1946
+     * @param string $objectUri
1947
+     * @param string $objectData
1948
+     * @return void
1949
+     */
1950
+    function createSchedulingObject($principalUri, $objectUri, $objectData) {
1951
+        $query = $this->db->getQueryBuilder();
1952
+        $query->insert('schedulingobjects')
1953
+            ->values([
1954
+                'principaluri' => $query->createNamedParameter($principalUri),
1955
+                'calendardata' => $query->createNamedParameter($objectData),
1956
+                'uri' => $query->createNamedParameter($objectUri),
1957
+                'lastmodified' => $query->createNamedParameter(time()),
1958
+                'etag' => $query->createNamedParameter(md5($objectData)),
1959
+                'size' => $query->createNamedParameter(strlen($objectData))
1960
+            ])
1961
+            ->execute();
1962
+    }
1963
+
1964
+    /**
1965
+     * Adds a change record to the calendarchanges table.
1966
+     *
1967
+     * @param mixed $calendarId
1968
+     * @param string $objectUri
1969
+     * @param int $operation 1 = add, 2 = modify, 3 = delete.
1970
+     * @return void
1971
+     */
1972
+    protected function addChange($calendarId, $objectUri, $operation) {
1973
+
1974
+        $stmt = $this->db->prepare('INSERT INTO `*PREFIX*calendarchanges` (`uri`, `synctoken`, `calendarid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*calendars` WHERE `id` = ?');
1975
+        $stmt->execute([
1976
+            $objectUri,
1977
+            $calendarId,
1978
+            $operation,
1979
+            $calendarId
1980
+        ]);
1981
+        $stmt = $this->db->prepare('UPDATE `*PREFIX*calendars` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
1982
+        $stmt->execute([
1983
+            $calendarId
1984
+        ]);
1985
+
1986
+    }
1987
+
1988
+    /**
1989
+     * Parses some information from calendar objects, used for optimized
1990
+     * calendar-queries.
1991
+     *
1992
+     * Returns an array with the following keys:
1993
+     *   * etag - An md5 checksum of the object without the quotes.
1994
+     *   * size - Size of the object in bytes
1995
+     *   * componentType - VEVENT, VTODO or VJOURNAL
1996
+     *   * firstOccurence
1997
+     *   * lastOccurence
1998
+     *   * uid - value of the UID property
1999
+     *
2000
+     * @param string $calendarData
2001
+     * @return array
2002
+     */
2003
+    public function getDenormalizedData($calendarData) {
2004
+
2005
+        $vObject = Reader::read($calendarData);
2006
+        $componentType = null;
2007
+        $component = null;
2008
+        $firstOccurrence = null;
2009
+        $lastOccurrence = null;
2010
+        $uid = null;
2011
+        $classification = self::CLASSIFICATION_PUBLIC;
2012
+        foreach($vObject->getComponents() as $component) {
2013
+            if ($component->name!=='VTIMEZONE') {
2014
+                $componentType = $component->name;
2015
+                $uid = (string)$component->UID;
2016
+                break;
2017
+            }
2018
+        }
2019
+        if (!$componentType) {
2020
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
2021
+        }
2022
+        if ($componentType === 'VEVENT' && $component->DTSTART) {
2023
+            $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
2024
+            // Finding the last occurrence is a bit harder
2025
+            if (!isset($component->RRULE)) {
2026
+                if (isset($component->DTEND)) {
2027
+                    $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
2028
+                } elseif (isset($component->DURATION)) {
2029
+                    $endDate = clone $component->DTSTART->getDateTime();
2030
+                    $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
2031
+                    $lastOccurrence = $endDate->getTimeStamp();
2032
+                } elseif (!$component->DTSTART->hasTime()) {
2033
+                    $endDate = clone $component->DTSTART->getDateTime();
2034
+                    $endDate->modify('+1 day');
2035
+                    $lastOccurrence = $endDate->getTimeStamp();
2036
+                } else {
2037
+                    $lastOccurrence = $firstOccurrence;
2038
+                }
2039
+            } else {
2040
+                $it = new EventIterator($vObject, (string)$component->UID);
2041
+                $maxDate = new \DateTime(self::MAX_DATE);
2042
+                if ($it->isInfinite()) {
2043
+                    $lastOccurrence = $maxDate->getTimestamp();
2044
+                } else {
2045
+                    $end = $it->getDtEnd();
2046
+                    while($it->valid() && $end < $maxDate) {
2047
+                        $end = $it->getDtEnd();
2048
+                        $it->next();
2049
+
2050
+                    }
2051
+                    $lastOccurrence = $end->getTimestamp();
2052
+                }
2053
+
2054
+            }
2055
+        }
2056
+
2057
+        if ($component->CLASS) {
2058
+            $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
2059
+            switch ($component->CLASS->getValue()) {
2060
+                case 'PUBLIC':
2061
+                    $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
2062
+                    break;
2063
+                case 'CONFIDENTIAL':
2064
+                    $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
2065
+                    break;
2066
+            }
2067
+        }
2068
+        return [
2069
+            'etag' => md5($calendarData),
2070
+            'size' => strlen($calendarData),
2071
+            'componentType' => $componentType,
2072
+            'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
2073
+            'lastOccurence'  => $lastOccurrence,
2074
+            'uid' => $uid,
2075
+            'classification' => $classification
2076
+        ];
2077
+
2078
+    }
2079
+
2080
+    private function readBlob($cardData) {
2081
+        if (is_resource($cardData)) {
2082
+            return stream_get_contents($cardData);
2083
+        }
2084
+
2085
+        return $cardData;
2086
+    }
2087
+
2088
+    /**
2089
+     * @param IShareable $shareable
2090
+     * @param array $add
2091
+     * @param array $remove
2092
+     */
2093
+    public function updateShares($shareable, $add, $remove) {
2094
+        $calendarId = $shareable->getResourceId();
2095
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
2096
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2097
+            [
2098
+                'calendarId' => $calendarId,
2099
+                'calendarData' => $this->getCalendarById($calendarId),
2100
+                'shares' => $this->getShares($calendarId),
2101
+                'add' => $add,
2102
+                'remove' => $remove,
2103
+            ]));
2104
+        $this->sharingBackend->updateShares($shareable, $add, $remove);
2105
+    }
2106
+
2107
+    /**
2108
+     * @param int $resourceId
2109
+     * @return array
2110
+     */
2111
+    public function getShares($resourceId) {
2112
+        return $this->sharingBackend->getShares($resourceId);
2113
+    }
2114
+
2115
+    /**
2116
+     * @param boolean $value
2117
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
2118
+     * @return string|null
2119
+     */
2120
+    public function setPublishStatus($value, $calendar) {
2121
+        $query = $this->db->getQueryBuilder();
2122
+        if ($value) {
2123
+            $publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
2124
+            $query->insert('dav_shares')
2125
+                ->values([
2126
+                    'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
2127
+                    'type' => $query->createNamedParameter('calendar'),
2128
+                    'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
2129
+                    'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
2130
+                    'publicuri' => $query->createNamedParameter($publicUri)
2131
+                ]);
2132
+            $query->execute();
2133
+            return $publicUri;
2134
+        }
2135
+        $query->delete('dav_shares')
2136
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2137
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
2138
+        $query->execute();
2139
+        return null;
2140
+    }
2141
+
2142
+    /**
2143
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
2144
+     * @return mixed
2145
+     */
2146
+    public function getPublishStatus($calendar) {
2147
+        $query = $this->db->getQueryBuilder();
2148
+        $result = $query->select('publicuri')
2149
+            ->from('dav_shares')
2150
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2151
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
2152
+            ->execute();
2153
+
2154
+        $row = $result->fetch();
2155
+        $result->closeCursor();
2156
+        return $row ? reset($row) : false;
2157
+    }
2158
+
2159
+    /**
2160
+     * @param int $resourceId
2161
+     * @param array $acl
2162
+     * @return array
2163
+     */
2164
+    public function applyShareAcl($resourceId, $acl) {
2165
+        return $this->sharingBackend->applyShareAcl($resourceId, $acl);
2166
+    }
2167
+
2168
+
2169
+
2170
+    /**
2171
+     * update properties table
2172
+     *
2173
+     * @param int $calendarId
2174
+     * @param string $objectUri
2175
+     * @param string $calendarData
2176
+     */
2177
+    public function updateProperties($calendarId, $objectUri, $calendarData) {
2178
+        $objectId = $this->getCalendarObjectId($calendarId, $objectUri);
2179
+
2180
+        try {
2181
+            $vCalendar = $this->readCalendarData($calendarData);
2182
+        } catch (\Exception $ex) {
2183
+            return;
2184
+        }
2185
+
2186
+        $this->purgeProperties($calendarId, $objectId);
2187
+
2188
+        $query = $this->db->getQueryBuilder();
2189
+        $query->insert($this->dbObjectPropertiesTable)
2190
+            ->values(
2191
+                [
2192
+                    'calendarid' => $query->createNamedParameter($calendarId),
2193
+                    'objectid' => $query->createNamedParameter($objectId),
2194
+                    'name' => $query->createParameter('name'),
2195
+                    'parameter' => $query->createParameter('parameter'),
2196
+                    'value' => $query->createParameter('value'),
2197
+                ]
2198
+            );
2199
+
2200
+        $indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2201
+        foreach ($vCalendar->getComponents() as $component) {
2202
+            if (!in_array($component->name, $indexComponents)) {
2203
+                continue;
2204
+            }
2205
+
2206
+            foreach ($component->children() as $property) {
2207
+                if (in_array($property->name, self::$indexProperties)) {
2208
+                    $value = $property->getValue();
2209
+                    // is this a shitty db?
2210
+                    if (!$this->db->supports4ByteText()) {
2211
+                        $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2212
+                    }
2213
+                    $value = substr($value, 0, 254);
2214
+
2215
+                    $query->setParameter('name', $property->name);
2216
+                    $query->setParameter('parameter', null);
2217
+                    $query->setParameter('value', $value);
2218
+                    $query->execute();
2219
+                }
2220
+
2221
+                if (in_array($property->name, array_keys(self::$indexParameters))) {
2222
+                    $parameters = $property->parameters();
2223
+                    $indexedParametersForProperty = self::$indexParameters[$property->name];
2224
+
2225
+                    foreach ($parameters as $key => $value) {
2226
+                        if (in_array($key, $indexedParametersForProperty)) {
2227
+                            // is this a shitty db?
2228
+                            if ($this->db->supports4ByteText()) {
2229
+                                $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2230
+                            }
2231
+                            $value = substr($value, 0, 254);
2232
+
2233
+                            $query->setParameter('name', $property->name);
2234
+                            $query->setParameter('parameter', substr($key, 0, 254));
2235
+                            $query->setParameter('value', substr($value, 0, 254));
2236
+                            $query->execute();
2237
+                        }
2238
+                    }
2239
+                }
2240
+            }
2241
+        }
2242
+    }
2243
+
2244
+    /**
2245
+     * read VCalendar data into a VCalendar object
2246
+     *
2247
+     * @param string $objectData
2248
+     * @return VCalendar
2249
+     */
2250
+    protected function readCalendarData($objectData) {
2251
+        return Reader::read($objectData);
2252
+    }
2253
+
2254
+    /**
2255
+     * delete all properties from a given calendar object
2256
+     *
2257
+     * @param int $calendarId
2258
+     * @param int $objectId
2259
+     */
2260
+    protected function purgeProperties($calendarId, $objectId) {
2261
+        $query = $this->db->getQueryBuilder();
2262
+        $query->delete($this->dbObjectPropertiesTable)
2263
+            ->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
2264
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2265
+        $query->execute();
2266
+    }
2267
+
2268
+    /**
2269
+     * get ID from a given calendar object
2270
+     *
2271
+     * @param int $calendarId
2272
+     * @param string $uri
2273
+     * @return int
2274
+     */
2275
+    protected function getCalendarObjectId($calendarId, $uri) {
2276
+        $query = $this->db->getQueryBuilder();
2277
+        $query->select('id')->from('calendarobjects')
2278
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2279
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2280
+
2281
+        $result = $query->execute();
2282
+        $objectIds = $result->fetch();
2283
+        $result->closeCursor();
2284
+
2285
+        if (!isset($objectIds['id'])) {
2286
+            throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2287
+        }
2288
+
2289
+        return (int)$objectIds['id'];
2290
+    }
2291
+
2292
+    private function convertPrincipal($principalUri, $toV2) {
2293
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2294
+            list(, $name) = Uri\split($principalUri);
2295
+            if ($toV2 === true) {
2296
+                return "principals/users/$name";
2297
+            }
2298
+            return "principals/$name";
2299
+        }
2300
+        return $principalUri;
2301
+    }
2302
+
2303
+    private function addOwnerPrincipal(&$calendarInfo) {
2304
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2305
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2306
+        if (isset($calendarInfo[$ownerPrincipalKey])) {
2307
+            $uri = $calendarInfo[$ownerPrincipalKey];
2308
+        } else {
2309
+            $uri = $calendarInfo['principaluri'];
2310
+        }
2311
+
2312
+        $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
2313
+        if (isset($principalInformation['{DAV:}displayname'])) {
2314
+            $calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
2315
+        }
2316
+    }
2317 2317
 }
Please login to merge, or discard this patch.
Spacing   +127 added lines, -127 removed lines patch added patch discarded remove patch
@@ -208,7 +208,7 @@  discard block
 block discarded – undo
208 208
 			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
209 209
 		}
210 210
 
211
-		return (int)$query->execute()->fetchColumn();
211
+		return (int) $query->execute()->fetchColumn();
212 212
 	}
213 213
 
214 214
 	/**
@@ -255,25 +255,25 @@  discard block
 block discarded – undo
255 255
 		$stmt = $query->execute();
256 256
 
257 257
 		$calendars = [];
258
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
258
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
259 259
 
260 260
 			$components = [];
261 261
 			if ($row['components']) {
262
-				$components = explode(',',$row['components']);
262
+				$components = explode(',', $row['components']);
263 263
 			}
264 264
 
265 265
 			$calendar = [
266 266
 				'id' => $row['id'],
267 267
 				'uri' => $row['uri'],
268 268
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
269
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
270
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
271
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
272
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
273
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
269
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
270
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
271
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
272
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
273
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
274 274
 			];
275 275
 
276
-			foreach($this->propertyMap as $xmlName=>$dbName) {
276
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
277 277
 				$calendar[$xmlName] = $row[$dbName];
278 278
 			}
279 279
 
@@ -291,7 +291,7 @@  discard block
 block discarded – undo
291 291
 		$principals = array_map(function($principal) {
292 292
 			return urldecode($principal);
293 293
 		}, $principals);
294
-		$principals[]= $principalUri;
294
+		$principals[] = $principalUri;
295 295
 
296 296
 		$fields = array_values($this->propertyMap);
297 297
 		$fields[] = 'a.id';
@@ -311,8 +311,8 @@  discard block
 block discarded – undo
311 311
 			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
312 312
 			->execute();
313 313
 
314
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
315
-		while($row = $result->fetch()) {
314
+		$readOnlyPropertyName = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only';
315
+		while ($row = $result->fetch()) {
316 316
 			if ($row['principaluri'] === $principalUri) {
317 317
 				continue;
318 318
 			}
@@ -331,25 +331,25 @@  discard block
 block discarded – undo
331 331
 			}
332 332
 
333 333
 			list(, $name) = Uri\split($row['principaluri']);
334
-			$uri = $row['uri'] . '_shared_by_' . $name;
335
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
334
+			$uri = $row['uri'].'_shared_by_'.$name;
335
+			$row['displayname'] = $row['displayname'].' ('.$this->getUserDisplayName($name).')';
336 336
 			$components = [];
337 337
 			if ($row['components']) {
338
-				$components = explode(',',$row['components']);
338
+				$components = explode(',', $row['components']);
339 339
 			}
340 340
 			$calendar = [
341 341
 				'id' => $row['id'],
342 342
 				'uri' => $uri,
343 343
 				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
344
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
345
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
346
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
347
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
348
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
344
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
345
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
346
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
347
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
348
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
349 349
 				$readOnlyPropertyName => $readOnly,
350 350
 			];
351 351
 
352
-			foreach($this->propertyMap as $xmlName=>$dbName) {
352
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
353 353
 				$calendar[$xmlName] = $row[$dbName];
354 354
 			}
355 355
 
@@ -378,21 +378,21 @@  discard block
 block discarded – undo
378 378
 			->orderBy('calendarorder', 'ASC');
379 379
 		$stmt = $query->execute();
380 380
 		$calendars = [];
381
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
381
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
382 382
 			$components = [];
383 383
 			if ($row['components']) {
384
-				$components = explode(',',$row['components']);
384
+				$components = explode(',', $row['components']);
385 385
 			}
386 386
 			$calendar = [
387 387
 				'id' => $row['id'],
388 388
 				'uri' => $row['uri'],
389 389
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
390
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
391
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
392
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
393
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
390
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
391
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
392
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
393
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
394 394
 			];
395
-			foreach($this->propertyMap as $xmlName=>$dbName) {
395
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
396 396
 				$calendar[$xmlName] = $row[$dbName];
397 397
 			}
398 398
 
@@ -443,27 +443,27 @@  discard block
 block discarded – undo
443 443
 			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
444 444
 			->execute();
445 445
 
446
-		while($row = $result->fetch()) {
446
+		while ($row = $result->fetch()) {
447 447
 			list(, $name) = Uri\split($row['principaluri']);
448
-			$row['displayname'] = $row['displayname'] . "($name)";
448
+			$row['displayname'] = $row['displayname']."($name)";
449 449
 			$components = [];
450 450
 			if ($row['components']) {
451
-				$components = explode(',',$row['components']);
451
+				$components = explode(',', $row['components']);
452 452
 			}
453 453
 			$calendar = [
454 454
 				'id' => $row['id'],
455 455
 				'uri' => $row['publicuri'],
456 456
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
457
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
458
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
459
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
460
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
461
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
462
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
463
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
457
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
458
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
459
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
460
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
461
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
462
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
463
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
464 464
 			];
465 465
 
466
-			foreach($this->propertyMap as $xmlName=>$dbName) {
466
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
467 467
 				$calendar[$xmlName] = $row[$dbName];
468 468
 			}
469 469
 
@@ -507,29 +507,29 @@  discard block
 block discarded – undo
507 507
 		$result->closeCursor();
508 508
 
509 509
 		if ($row === false) {
510
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
510
+			throw new NotFound('Node with name \''.$uri.'\' could not be found');
511 511
 		}
512 512
 
513 513
 		list(, $name) = Uri\split($row['principaluri']);
514
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
514
+		$row['displayname'] = $row['displayname'].' '."($name)";
515 515
 		$components = [];
516 516
 		if ($row['components']) {
517
-			$components = explode(',',$row['components']);
517
+			$components = explode(',', $row['components']);
518 518
 		}
519 519
 		$calendar = [
520 520
 			'id' => $row['id'],
521 521
 			'uri' => $row['publicuri'],
522 522
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
523
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
524
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
525
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
526
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
527
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
528
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
529
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
523
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
524
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
525
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
526
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
527
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
528
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
529
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
530 530
 		];
531 531
 
532
-		foreach($this->propertyMap as $xmlName=>$dbName) {
532
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
533 533
 			$calendar[$xmlName] = $row[$dbName];
534 534
 		}
535 535
 
@@ -569,20 +569,20 @@  discard block
 block discarded – undo
569 569
 
570 570
 		$components = [];
571 571
 		if ($row['components']) {
572
-			$components = explode(',',$row['components']);
572
+			$components = explode(',', $row['components']);
573 573
 		}
574 574
 
575 575
 		$calendar = [
576 576
 			'id' => $row['id'],
577 577
 			'uri' => $row['uri'],
578 578
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
579
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
580
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
581
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
582
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
579
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
580
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
581
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
582
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
583 583
 		];
584 584
 
585
-		foreach($this->propertyMap as $xmlName=>$dbName) {
585
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
586 586
 			$calendar[$xmlName] = $row[$dbName];
587 587
 		}
588 588
 
@@ -615,20 +615,20 @@  discard block
 block discarded – undo
615 615
 
616 616
 		$components = [];
617 617
 		if ($row['components']) {
618
-			$components = explode(',',$row['components']);
618
+			$components = explode(',', $row['components']);
619 619
 		}
620 620
 
621 621
 		$calendar = [
622 622
 			'id' => $row['id'],
623 623
 			'uri' => $row['uri'],
624 624
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
625
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
626
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
627
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
628
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
625
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
626
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
627
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
628
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
629 629
 		];
630 630
 
631
-		foreach($this->propertyMap as $xmlName=>$dbName) {
631
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
632 632
 			$calendar[$xmlName] = $row[$dbName];
633 633
 		}
634 634
 
@@ -663,16 +663,16 @@  discard block
 block discarded – undo
663 663
 		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
664 664
 		if (isset($properties[$sccs])) {
665 665
 			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
666
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
666
+				throw new DAV\Exception('The '.$sccs.' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
667 667
 			}
668
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
668
+			$values['components'] = implode(',', $properties[$sccs]->getValue());
669 669
 		}
670
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
670
+		$transp = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
671 671
 		if (isset($properties[$transp])) {
672 672
 			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
673 673
 		}
674 674
 
675
-		foreach($this->propertyMap as $xmlName=>$dbName) {
675
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
676 676
 			if (isset($properties[$xmlName])) {
677 677
 				$values[$dbName] = $properties[$xmlName];
678 678
 			}
@@ -680,7 +680,7 @@  discard block
 block discarded – undo
680 680
 
681 681
 		$query = $this->db->getQueryBuilder();
682 682
 		$query->insert('calendars');
683
-		foreach($values as $column => $value) {
683
+		foreach ($values as $column => $value) {
684 684
 			$query->setValue($column, $query->createNamedParameter($value));
685 685
 		}
686 686
 		$query->execute();
@@ -714,7 +714,7 @@  discard block
 block discarded – undo
714 714
 	 */
715 715
 	function updateCalendar($calendarId, PropPatch $propPatch) {
716 716
 		$supportedProperties = array_keys($this->propertyMap);
717
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
717
+		$supportedProperties[] = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
718 718
 
719 719
 		/**
720 720
 		 * @suppress SqlInjectionChecker
@@ -724,7 +724,7 @@  discard block
 block discarded – undo
724 724
 			foreach ($mutations as $propertyName => $propertyValue) {
725 725
 
726 726
 				switch ($propertyName) {
727
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
727
+					case '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' :
728 728
 						$fieldName = 'transparent';
729 729
 						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
730 730
 						break;
@@ -839,16 +839,16 @@  discard block
 block discarded – undo
839 839
 		$stmt = $query->execute();
840 840
 
841 841
 		$result = [];
842
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
842
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
843 843
 			$result[] = [
844 844
 					'id'           => $row['id'],
845 845
 					'uri'          => $row['uri'],
846 846
 					'lastmodified' => $row['lastmodified'],
847
-					'etag'         => '"' . $row['etag'] . '"',
847
+					'etag'         => '"'.$row['etag'].'"',
848 848
 					'calendarid'   => $row['calendarid'],
849
-					'size'         => (int)$row['size'],
849
+					'size'         => (int) $row['size'],
850 850
 					'component'    => strtolower($row['componenttype']),
851
-					'classification'=> (int)$row['classification']
851
+					'classification'=> (int) $row['classification']
852 852
 			];
853 853
 		}
854 854
 
@@ -881,18 +881,18 @@  discard block
 block discarded – undo
881 881
 		$stmt = $query->execute();
882 882
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
883 883
 
884
-		if(!$row) return null;
884
+		if (!$row) return null;
885 885
 
886 886
 		return [
887 887
 				'id'            => $row['id'],
888 888
 				'uri'           => $row['uri'],
889 889
 				'lastmodified'  => $row['lastmodified'],
890
-				'etag'          => '"' . $row['etag'] . '"',
890
+				'etag'          => '"'.$row['etag'].'"',
891 891
 				'calendarid'    => $row['calendarid'],
892
-				'size'          => (int)$row['size'],
892
+				'size'          => (int) $row['size'],
893 893
 				'calendardata'  => $this->readBlob($row['calendardata']),
894 894
 				'component'     => strtolower($row['componenttype']),
895
-				'classification'=> (int)$row['classification']
895
+				'classification'=> (int) $row['classification']
896 896
 		];
897 897
 	}
898 898
 
@@ -931,12 +931,12 @@  discard block
 block discarded – undo
931 931
 					'id'           => $row['id'],
932 932
 					'uri'          => $row['uri'],
933 933
 					'lastmodified' => $row['lastmodified'],
934
-					'etag'         => '"' . $row['etag'] . '"',
934
+					'etag'         => '"'.$row['etag'].'"',
935 935
 					'calendarid'   => $row['calendarid'],
936
-					'size'         => (int)$row['size'],
936
+					'size'         => (int) $row['size'],
937 937
 					'calendardata' => $this->readBlob($row['calendardata']),
938 938
 					'component'    => strtolower($row['componenttype']),
939
-					'classification' => (int)$row['classification']
939
+					'classification' => (int) $row['classification']
940 940
 				];
941 941
 			}
942 942
 			$result->closeCursor();
@@ -1009,7 +1009,7 @@  discard block
 block discarded – undo
1009 1009
 		));
1010 1010
 		$this->addChange($calendarId, $objectUri, 1);
1011 1011
 
1012
-		return '"' . $extraData['etag'] . '"';
1012
+		return '"'.$extraData['etag'].'"';
1013 1013
 	}
1014 1014
 
1015 1015
 	/**
@@ -1064,7 +1064,7 @@  discard block
 block discarded – undo
1064 1064
 		}
1065 1065
 		$this->addChange($calendarId, $objectUri, 2);
1066 1066
 
1067
-		return '"' . $extraData['etag'] . '"';
1067
+		return '"'.$extraData['etag'].'"';
1068 1068
 	}
1069 1069
 
1070 1070
 	/**
@@ -1217,7 +1217,7 @@  discard block
 block discarded – undo
1217 1217
 		$stmt = $query->execute();
1218 1218
 
1219 1219
 		$result = [];
1220
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1220
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1221 1221
 			if ($requirePostFilter) {
1222 1222
 				if (!$this->validateFilterForObject($row, $filters)) {
1223 1223
 					continue;
@@ -1238,14 +1238,14 @@  discard block
 block discarded – undo
1238 1238
 	 * @param integer|null $offset
1239 1239
 	 * @return array
1240 1240
 	 */
1241
-	public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1241
+	public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
1242 1242
 		$calendars = $this->getCalendarsForUser($principalUri);
1243 1243
 		$ownCalendars = [];
1244 1244
 		$sharedCalendars = [];
1245 1245
 
1246 1246
 		$uriMapper = [];
1247 1247
 
1248
-		foreach($calendars as $calendar) {
1248
+		foreach ($calendars as $calendar) {
1249 1249
 			if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1250 1250
 				$ownCalendars[] = $calendar['id'];
1251 1251
 			} else {
@@ -1260,11 +1260,11 @@  discard block
 block discarded – undo
1260 1260
 		$query = $this->db->getQueryBuilder();
1261 1261
 		// Calendar id expressions
1262 1262
 		$calendarExpressions = [];
1263
-		foreach($ownCalendars as $id) {
1263
+		foreach ($ownCalendars as $id) {
1264 1264
 			$calendarExpressions[] = $query->expr()
1265 1265
 				->eq('c.calendarid', $query->createNamedParameter($id));
1266 1266
 		}
1267
-		foreach($sharedCalendars as $id) {
1267
+		foreach ($sharedCalendars as $id) {
1268 1268
 			$calendarExpressions[] = $query->expr()->andX(
1269 1269
 				$query->expr()->eq('c.calendarid',
1270 1270
 					$query->createNamedParameter($id)),
@@ -1281,7 +1281,7 @@  discard block
 block discarded – undo
1281 1281
 
1282 1282
 		// Component expressions
1283 1283
 		$compExpressions = [];
1284
-		foreach($filters['comps'] as $comp) {
1284
+		foreach ($filters['comps'] as $comp) {
1285 1285
 			$compExpressions[] = $query->expr()
1286 1286
 				->eq('c.componenttype', $query->createNamedParameter($comp));
1287 1287
 		}
@@ -1300,13 +1300,13 @@  discard block
 block discarded – undo
1300 1300
 		}
1301 1301
 
1302 1302
 		$propParamExpressions = [];
1303
-		foreach($filters['props'] as $prop) {
1303
+		foreach ($filters['props'] as $prop) {
1304 1304
 			$propParamExpressions[] = $query->expr()->andX(
1305 1305
 				$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1306 1306
 				$query->expr()->isNull('i.parameter')
1307 1307
 			);
1308 1308
 		}
1309
-		foreach($filters['params'] as $param) {
1309
+		foreach ($filters['params'] as $param) {
1310 1310
 			$propParamExpressions[] = $query->expr()->andX(
1311 1311
 				$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1312 1312
 				$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
@@ -1338,8 +1338,8 @@  discard block
 block discarded – undo
1338 1338
 		$stmt = $query->execute();
1339 1339
 
1340 1340
 		$result = [];
1341
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1342
-			$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1341
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1342
+			$path = $uriMapper[$row['calendarid']].'/'.$row['uri'];
1343 1343
 			if (!in_array($path, $result)) {
1344 1344
 				$result[] = $path;
1345 1345
 			}
@@ -1377,7 +1377,7 @@  discard block
 block discarded – undo
1377 1377
 		}
1378 1378
 
1379 1379
 		$or = $innerQuery->expr()->orX();
1380
-		foreach($searchProperties as $searchProperty) {
1380
+		foreach ($searchProperties as $searchProperty) {
1381 1381
 			$or->add($innerQuery->expr()->eq('op.name',
1382 1382
 				$outerQuery->createNamedParameter($searchProperty)));
1383 1383
 		}
@@ -1387,8 +1387,8 @@  discard block
 block discarded – undo
1387 1387
 
1388 1388
 		if ($pattern !== '') {
1389 1389
 			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1390
-				$outerQuery->createNamedParameter('%' .
1391
-					$this->db->escapeLikeParameter($pattern) . '%')));
1390
+				$outerQuery->createNamedParameter('%'.
1391
+					$this->db->escapeLikeParameter($pattern).'%')));
1392 1392
 		}
1393 1393
 
1394 1394
 		$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
@@ -1425,7 +1425,7 @@  discard block
 block discarded – undo
1425 1425
 			$comps = $calendarData->getComponents();
1426 1426
 			$objects = [];
1427 1427
 			$timezones = [];
1428
-			foreach($comps as $comp) {
1428
+			foreach ($comps as $comp) {
1429 1429
 				if ($comp instanceof VTimeZone) {
1430 1430
 					$timezones[] = $comp;
1431 1431
 				} else {
@@ -1462,7 +1462,7 @@  discard block
 block discarded – undo
1462 1462
 		});
1463 1463
 		$validationRules = $comp->getValidationRules();
1464 1464
 
1465
-		foreach($subComponents as $subComponent) {
1465
+		foreach ($subComponents as $subComponent) {
1466 1466
 			$name = $subComponent->name;
1467 1467
 			if (!isset($data[$name])) {
1468 1468
 				$data[$name] = [];
@@ -1470,7 +1470,7 @@  discard block
 block discarded – undo
1470 1470
 			$data[$name][] = $this->transformSearchData($subComponent);
1471 1471
 		}
1472 1472
 
1473
-		foreach($properties as $property) {
1473
+		foreach ($properties as $property) {
1474 1474
 			$name = $property->name;
1475 1475
 			if (!isset($validationRules[$name])) {
1476 1476
 				$validationRules[$name] = '*';
@@ -1540,7 +1540,7 @@  discard block
 block discarded – undo
1540 1540
 		$stmt = $query->execute();
1541 1541
 
1542 1542
 		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1543
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1543
+			return $row['calendaruri'].'/'.$row['objecturi'];
1544 1544
 		}
1545 1545
 
1546 1546
 		return null;
@@ -1605,7 +1605,7 @@  discard block
 block discarded – undo
1605 1605
 	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1606 1606
 		// Current synctoken
1607 1607
 		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1608
-		$stmt->execute([ $calendarId ]);
1608
+		$stmt->execute([$calendarId]);
1609 1609
 		$currentToken = $stmt->fetchColumn(0);
1610 1610
 
1611 1611
 		if (is_null($currentToken)) {
@@ -1622,8 +1622,8 @@  discard block
 block discarded – undo
1622 1622
 		if ($syncToken) {
1623 1623
 
1624 1624
 			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1625
-			if ($limit>0) {
1626
-				$query.= " LIMIT " . (int)$limit;
1625
+			if ($limit > 0) {
1626
+				$query .= " LIMIT ".(int) $limit;
1627 1627
 			}
1628 1628
 
1629 1629
 			// Fetching all changes
@@ -1634,15 +1634,15 @@  discard block
 block discarded – undo
1634 1634
 
1635 1635
 			// This loop ensures that any duplicates are overwritten, only the
1636 1636
 			// last change on a node is relevant.
1637
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1637
+			while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1638 1638
 
1639 1639
 				$changes[$row['uri']] = $row['operation'];
1640 1640
 
1641 1641
 			}
1642 1642
 
1643
-			foreach($changes as $uri => $operation) {
1643
+			foreach ($changes as $uri => $operation) {
1644 1644
 
1645
-				switch($operation) {
1645
+				switch ($operation) {
1646 1646
 					case 1 :
1647 1647
 						$result['added'][] = $uri;
1648 1648
 						break;
@@ -1712,10 +1712,10 @@  discard block
 block discarded – undo
1712 1712
 			->from('calendarsubscriptions')
1713 1713
 			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1714 1714
 			->orderBy('calendarorder', 'asc');
1715
-		$stmt =$query->execute();
1715
+		$stmt = $query->execute();
1716 1716
 
1717 1717
 		$subscriptions = [];
1718
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1718
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1719 1719
 
1720 1720
 			$subscription = [
1721 1721
 				'id'           => $row['id'],
@@ -1724,10 +1724,10 @@  discard block
 block discarded – undo
1724 1724
 				'source'       => $row['source'],
1725 1725
 				'lastmodified' => $row['lastmodified'],
1726 1726
 
1727
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1727
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1728 1728
 			];
1729 1729
 
1730
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1730
+			foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1731 1731
 				if (!is_null($row[$dbName])) {
1732 1732
 					$subscription[$xmlName] = $row[$dbName];
1733 1733
 				}
@@ -1766,7 +1766,7 @@  discard block
 block discarded – undo
1766 1766
 
1767 1767
 		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1768 1768
 
1769
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1769
+		foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1770 1770
 			if (array_key_exists($xmlName, $properties)) {
1771 1771
 					$values[$dbName] = $properties[$xmlName];
1772 1772
 					if (in_array($dbName, $propertiesBoolean)) {
@@ -1817,7 +1817,7 @@  discard block
 block discarded – undo
1817 1817
 
1818 1818
 			$newValues = [];
1819 1819
 
1820
-			foreach($mutations as $propertyName=>$propertyValue) {
1820
+			foreach ($mutations as $propertyName=>$propertyValue) {
1821 1821
 				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1822 1822
 					$newValues['source'] = $propertyValue->getHref();
1823 1823
 				} else {
@@ -1829,7 +1829,7 @@  discard block
 block discarded – undo
1829 1829
 			$query = $this->db->getQueryBuilder();
1830 1830
 			$query->update('calendarsubscriptions')
1831 1831
 				->set('lastmodified', $query->createNamedParameter(time()));
1832
-			foreach($newValues as $fieldName=>$value) {
1832
+			foreach ($newValues as $fieldName=>$value) {
1833 1833
 				$query->set($fieldName, $query->createNamedParameter($value));
1834 1834
 			}
1835 1835
 			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
@@ -1879,7 +1879,7 @@  discard block
 block discarded – undo
1879 1879
 
1880 1880
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
1881 1881
 
1882
-		if(!$row) {
1882
+		if (!$row) {
1883 1883
 			return null;
1884 1884
 		}
1885 1885
 
@@ -1887,8 +1887,8 @@  discard block
 block discarded – undo
1887 1887
 				'uri'          => $row['uri'],
1888 1888
 				'calendardata' => $row['calendardata'],
1889 1889
 				'lastmodified' => $row['lastmodified'],
1890
-				'etag'         => '"' . $row['etag'] . '"',
1891
-				'size'         => (int)$row['size'],
1890
+				'etag'         => '"'.$row['etag'].'"',
1891
+				'size'         => (int) $row['size'],
1892 1892
 		];
1893 1893
 	}
1894 1894
 
@@ -1911,13 +1911,13 @@  discard block
 block discarded – undo
1911 1911
 				->execute();
1912 1912
 
1913 1913
 		$result = [];
1914
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1914
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1915 1915
 			$result[] = [
1916 1916
 					'calendardata' => $row['calendardata'],
1917 1917
 					'uri'          => $row['uri'],
1918 1918
 					'lastmodified' => $row['lastmodified'],
1919
-					'etag'         => '"' . $row['etag'] . '"',
1920
-					'size'         => (int)$row['size'],
1919
+					'etag'         => '"'.$row['etag'].'"',
1920
+					'size'         => (int) $row['size'],
1921 1921
 			];
1922 1922
 		}
1923 1923
 
@@ -2009,10 +2009,10 @@  discard block
 block discarded – undo
2009 2009
 		$lastOccurrence = null;
2010 2010
 		$uid = null;
2011 2011
 		$classification = self::CLASSIFICATION_PUBLIC;
2012
-		foreach($vObject->getComponents() as $component) {
2013
-			if ($component->name!=='VTIMEZONE') {
2012
+		foreach ($vObject->getComponents() as $component) {
2013
+			if ($component->name !== 'VTIMEZONE') {
2014 2014
 				$componentType = $component->name;
2015
-				$uid = (string)$component->UID;
2015
+				$uid = (string) $component->UID;
2016 2016
 				break;
2017 2017
 			}
2018 2018
 		}
@@ -2037,13 +2037,13 @@  discard block
 block discarded – undo
2037 2037
 					$lastOccurrence = $firstOccurrence;
2038 2038
 				}
2039 2039
 			} else {
2040
-				$it = new EventIterator($vObject, (string)$component->UID);
2040
+				$it = new EventIterator($vObject, (string) $component->UID);
2041 2041
 				$maxDate = new \DateTime(self::MAX_DATE);
2042 2042
 				if ($it->isInfinite()) {
2043 2043
 					$lastOccurrence = $maxDate->getTimestamp();
2044 2044
 				} else {
2045 2045
 					$end = $it->getDtEnd();
2046
-					while($it->valid() && $end < $maxDate) {
2046
+					while ($it->valid() && $end < $maxDate) {
2047 2047
 						$end = $it->getDtEnd();
2048 2048
 						$it->next();
2049 2049
 
@@ -2283,10 +2283,10 @@  discard block
 block discarded – undo
2283 2283
 		$result->closeCursor();
2284 2284
 
2285 2285
 		if (!isset($objectIds['id'])) {
2286
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2286
+			throw new \InvalidArgumentException('Calendarobject does not exists: '.$uri);
2287 2287
 		}
2288 2288
 
2289
-		return (int)$objectIds['id'];
2289
+		return (int) $objectIds['id'];
2290 2290
 	}
2291 2291
 
2292 2292
 	private function convertPrincipal($principalUri, $toV2) {
@@ -2301,8 +2301,8 @@  discard block
 block discarded – undo
2301 2301
 	}
2302 2302
 
2303 2303
 	private function addOwnerPrincipal(&$calendarInfo) {
2304
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2305
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2304
+		$ownerPrincipalKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal';
2305
+		$displaynameKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}owner-displayname';
2306 2306
 		if (isset($calendarInfo[$ownerPrincipalKey])) {
2307 2307
 			$uri = $calendarInfo[$ownerPrincipalKey];
2308 2308
 		} else {
Please login to merge, or discard this patch.