Passed
Push — master ( 33c34d...f0c85a )
by Morris
09:38
created
apps/files_trashbin/lib/AppInfo/Application.php 1 patch
Indentation   +51 added lines, -51 removed lines patch added patch discarded remove patch
@@ -33,68 +33,68 @@
 block discarded – undo
33 33
 use OCA\Files_Trashbin\Capabilities;
34 34
 
35 35
 class Application extends App {
36
-	public function __construct (array $urlParams = []) {
37
-		parent::__construct('files_trashbin', $urlParams);
36
+    public function __construct (array $urlParams = []) {
37
+        parent::__construct('files_trashbin', $urlParams);
38 38
 
39
-		$container = $this->getContainer();
40
-		/*
39
+        $container = $this->getContainer();
40
+        /*
41 41
 		 * Register capabilities
42 42
 		 */
43
-		$container->registerCapability(Capabilities::class);
43
+        $container->registerCapability(Capabilities::class);
44 44
 
45
-		/*
45
+        /*
46 46
 		 * Register expiration
47 47
 		 */
48
-		$container->registerService('Expiration', function($c) {
49
-			return  new Expiration(
50
-				$c->query('ServerContainer')->getConfig(),
51
-				$c->query(ITimeFactory::class)
52
-			);
53
-		});
48
+        $container->registerService('Expiration', function($c) {
49
+            return  new Expiration(
50
+                $c->query('ServerContainer')->getConfig(),
51
+                $c->query(ITimeFactory::class)
52
+            );
53
+        });
54 54
 
55
-		/*
55
+        /*
56 56
 		 * Register $principalBackend for the DAV collection
57 57
 		 */
58
-		$container->registerService('principalBackend', function () {
59
-			return new Principal(
60
-				\OC::$server->getUserManager(),
61
-				\OC::$server->getGroupManager(),
62
-				\OC::$server->getShareManager(),
63
-				\OC::$server->getUserSession(),
64
-				\OC::$server->getConfig(),
65
-				\OC::$server->getAppManager()
66
-			);
67
-		});
58
+        $container->registerService('principalBackend', function () {
59
+            return new Principal(
60
+                \OC::$server->getUserManager(),
61
+                \OC::$server->getGroupManager(),
62
+                \OC::$server->getShareManager(),
63
+                \OC::$server->getUserSession(),
64
+                \OC::$server->getConfig(),
65
+                \OC::$server->getAppManager()
66
+            );
67
+        });
68 68
 
69
-		$container->registerService(ITrashManager::class, function(IAppContainer $c) {
70
-			return new TrashManager();
71
-		});
69
+        $container->registerService(ITrashManager::class, function(IAppContainer $c) {
70
+            return new TrashManager();
71
+        });
72 72
 
73
-		$this->registerTrashBackends();
74
-	}
73
+        $this->registerTrashBackends();
74
+    }
75 75
 
76
-	public function registerTrashBackends() {
77
-		$server = $this->getContainer()->getServer();
78
-		$logger = $server->getLogger();
79
-		$appManager = $server->getAppManager();
80
-		/** @var ITrashManager $trashManager */
81
-		$trashManager = $this->getContainer()->getServer()->query(ITrashManager::class);
82
-		foreach($appManager->getInstalledApps() as $app) {
83
-			$appInfo = $appManager->getAppInfo($app);
84
-			if (isset($appInfo['trash'])) {
85
-				$backends = $appInfo['trash'];
86
-				foreach($backends as $backend) {
87
-					$class = $backend['@value'];
88
-					$for = $backend['@attributes']['for'];
76
+    public function registerTrashBackends() {
77
+        $server = $this->getContainer()->getServer();
78
+        $logger = $server->getLogger();
79
+        $appManager = $server->getAppManager();
80
+        /** @var ITrashManager $trashManager */
81
+        $trashManager = $this->getContainer()->getServer()->query(ITrashManager::class);
82
+        foreach($appManager->getInstalledApps() as $app) {
83
+            $appInfo = $appManager->getAppInfo($app);
84
+            if (isset($appInfo['trash'])) {
85
+                $backends = $appInfo['trash'];
86
+                foreach($backends as $backend) {
87
+                    $class = $backend['@value'];
88
+                    $for = $backend['@attributes']['for'];
89 89
 
90
-					try {
91
-						$backendObject = $server->query($class);
92
-						$trashManager->registerBackend($for, $backendObject);
93
-					} catch (\Exception $e) {
94
-						$logger->logException($e);
95
-					}
96
-				}
97
-			}
98
-		}
99
-	}
90
+                    try {
91
+                        $backendObject = $server->query($class);
92
+                        $trashManager->registerBackend($for, $backendObject);
93
+                    } catch (\Exception $e) {
94
+                        $logger->logException($e);
95
+                    }
96
+                }
97
+            }
98
+        }
99
+    }
100 100
 }
Please login to merge, or discard this patch.
apps/dav/lib/RootCollection.php 1 patch
Indentation   +123 added lines, -123 removed lines patch added patch discarded remove patch
@@ -42,128 +42,128 @@
 block discarded – undo
42 42
 
43 43
 class RootCollection extends SimpleCollection {
44 44
 
45
-	public function __construct() {
46
-		$config = \OC::$server->getConfig();
47
-		$l10n = \OC::$server->getL10N('dav');
48
-		$random = \OC::$server->getSecureRandom();
49
-		$logger = \OC::$server->getLogger();
50
-		$userManager = \OC::$server->getUserManager();
51
-		$userSession = \OC::$server->getUserSession();
52
-		$groupManager = \OC::$server->getGroupManager();
53
-		$shareManager = \OC::$server->getShareManager();
54
-		$db = \OC::$server->getDatabaseConnection();
55
-		$dispatcher = \OC::$server->getEventDispatcher();
56
-		$userPrincipalBackend = new Principal(
57
-			$userManager,
58
-			$groupManager,
59
-			$shareManager,
60
-			\OC::$server->getUserSession(),
61
-			$config,
62
-			\OC::$server->getAppManager()
63
-		);
64
-		$groupPrincipalBackend = new GroupPrincipalBackend($groupManager, $userSession, $shareManager, $l10n);
65
-		$calendarResourcePrincipalBackend = new ResourcePrincipalBackend($db, $userSession, $groupManager, $logger);
66
-		$calendarRoomPrincipalBackend = new RoomPrincipalBackend($db, $userSession, $groupManager, $logger);
67
-		// as soon as debug mode is enabled we allow listing of principals
68
-		$disableListing = !$config->getSystemValue('debug', false);
69
-
70
-		// setup the first level of the dav tree
71
-		$userPrincipals = new Collection($userPrincipalBackend, 'principals/users');
72
-		$userPrincipals->disableListing = $disableListing;
73
-		$groupPrincipals = new Collection($groupPrincipalBackend, 'principals/groups');
74
-		$groupPrincipals->disableListing = $disableListing;
75
-		$systemPrincipals = new Collection(new SystemPrincipalBackend(), 'principals/system');
76
-		$systemPrincipals->disableListing = $disableListing;
77
-		$calendarResourcePrincipals = new Collection($calendarResourcePrincipalBackend, 'principals/calendar-resources');
78
-		$calendarResourcePrincipals->disableListing = $disableListing;
79
-		$calendarRoomPrincipals = new Collection($calendarRoomPrincipalBackend, 'principals/calendar-rooms');
80
-		$calendarRoomPrincipals->disableListing = $disableListing;
81
-
82
-
83
-		$filesCollection = new Files\RootCollection($userPrincipalBackend, 'principals/users');
84
-		$filesCollection->disableListing = $disableListing;
85
-		$caldavBackend = new CalDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $random, $logger, $dispatcher);
86
-		$userCalendarRoot = new CalendarRoot($userPrincipalBackend, $caldavBackend, 'principals/users');
87
-		$userCalendarRoot->disableListing = $disableListing;
88
-
89
-		$resourceCalendarCaldavBackend = new CalDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $random, $logger, $dispatcher);
90
-		$resourceCalendarRoot = new CalendarRoot($calendarResourcePrincipalBackend, $caldavBackend, 'principals/calendar-resources');
91
-		$resourceCalendarRoot->disableListing = $disableListing;
92
-		$roomCalendarCaldavBackend = new CalDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $random, $logger, $dispatcher);
93
-		$roomCalendarRoot = new CalendarRoot($calendarRoomPrincipalBackend, $roomCalendarCaldavBackend, 'principals/calendar-rooms');
94
-		$roomCalendarRoot->disableListing = $disableListing;
95
-
96
-		$publicCalendarRoot = new PublicCalendarRoot($caldavBackend, $l10n, $config);
97
-		$publicCalendarRoot->disableListing = $disableListing;
98
-
99
-		$systemTagCollection = new SystemTag\SystemTagsByIdCollection(
100
-			\OC::$server->getSystemTagManager(),
101
-			\OC::$server->getUserSession(),
102
-			$groupManager
103
-		);
104
-		$systemTagRelationsCollection = new SystemTag\SystemTagsRelationsCollection(
105
-			\OC::$server->getSystemTagManager(),
106
-			\OC::$server->getSystemTagObjectMapper(),
107
-			\OC::$server->getUserSession(),
108
-			$groupManager,
109
-			\OC::$server->getEventDispatcher()
110
-		);
111
-		$commentsCollection = new Comments\RootCollection(
112
-			\OC::$server->getCommentsManager(),
113
-			$userManager,
114
-			\OC::$server->getUserSession(),
115
-			\OC::$server->getEventDispatcher(),
116
-			\OC::$server->getLogger()
117
-		);
118
-
119
-		$usersCardDavBackend = new CardDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $dispatcher);
120
-		$usersAddressBookRoot = new AddressBookRoot($userPrincipalBackend, $usersCardDavBackend, 'principals/users');
121
-		$usersAddressBookRoot->disableListing = $disableListing;
122
-
123
-		$systemCardDavBackend = new CardDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $dispatcher);
124
-		$systemAddressBookRoot = new AddressBookRoot(new SystemPrincipalBackend(), $systemCardDavBackend, 'principals/system');
125
-		$systemAddressBookRoot->disableListing = $disableListing;
126
-
127
-		$uploadCollection = new Upload\RootCollection(
128
-			$userPrincipalBackend,
129
-			'principals/users',
130
-			\OC::$server->query(CleanupService::class));
131
-		$uploadCollection->disableListing = $disableListing;
132
-
133
-		$avatarCollection = new Avatars\RootCollection($userPrincipalBackend, 'principals/users');
134
-		$avatarCollection->disableListing = $disableListing;
135
-
136
-		$appleProvisioning = new AppleProvisioningNode(
137
-			\OC::$server->query(ITimeFactory::class));
138
-
139
-		$children = [
140
-				new SimpleCollection('principals', [
141
-						$userPrincipals,
142
-						$groupPrincipals,
143
-						$systemPrincipals,
144
-						$calendarResourcePrincipals,
145
-						$calendarRoomPrincipals]),
146
-				$filesCollection,
147
-				$userCalendarRoot,
148
-				new SimpleCollection('system-calendars', [
149
-					$resourceCalendarRoot,
150
-					$roomCalendarRoot,
151
-				]),
152
-				$publicCalendarRoot,
153
-				new SimpleCollection('addressbooks', [
154
-						$usersAddressBookRoot,
155
-						$systemAddressBookRoot]),
156
-				$systemTagCollection,
157
-				$systemTagRelationsCollection,
158
-				$commentsCollection,
159
-				$uploadCollection,
160
-				$avatarCollection,
161
-				new SimpleCollection('provisioning', [
162
-					$appleProvisioning
163
-				])
164
-		];
165
-
166
-		parent::__construct('root', $children);
167
-	}
45
+    public function __construct() {
46
+        $config = \OC::$server->getConfig();
47
+        $l10n = \OC::$server->getL10N('dav');
48
+        $random = \OC::$server->getSecureRandom();
49
+        $logger = \OC::$server->getLogger();
50
+        $userManager = \OC::$server->getUserManager();
51
+        $userSession = \OC::$server->getUserSession();
52
+        $groupManager = \OC::$server->getGroupManager();
53
+        $shareManager = \OC::$server->getShareManager();
54
+        $db = \OC::$server->getDatabaseConnection();
55
+        $dispatcher = \OC::$server->getEventDispatcher();
56
+        $userPrincipalBackend = new Principal(
57
+            $userManager,
58
+            $groupManager,
59
+            $shareManager,
60
+            \OC::$server->getUserSession(),
61
+            $config,
62
+            \OC::$server->getAppManager()
63
+        );
64
+        $groupPrincipalBackend = new GroupPrincipalBackend($groupManager, $userSession, $shareManager, $l10n);
65
+        $calendarResourcePrincipalBackend = new ResourcePrincipalBackend($db, $userSession, $groupManager, $logger);
66
+        $calendarRoomPrincipalBackend = new RoomPrincipalBackend($db, $userSession, $groupManager, $logger);
67
+        // as soon as debug mode is enabled we allow listing of principals
68
+        $disableListing = !$config->getSystemValue('debug', false);
69
+
70
+        // setup the first level of the dav tree
71
+        $userPrincipals = new Collection($userPrincipalBackend, 'principals/users');
72
+        $userPrincipals->disableListing = $disableListing;
73
+        $groupPrincipals = new Collection($groupPrincipalBackend, 'principals/groups');
74
+        $groupPrincipals->disableListing = $disableListing;
75
+        $systemPrincipals = new Collection(new SystemPrincipalBackend(), 'principals/system');
76
+        $systemPrincipals->disableListing = $disableListing;
77
+        $calendarResourcePrincipals = new Collection($calendarResourcePrincipalBackend, 'principals/calendar-resources');
78
+        $calendarResourcePrincipals->disableListing = $disableListing;
79
+        $calendarRoomPrincipals = new Collection($calendarRoomPrincipalBackend, 'principals/calendar-rooms');
80
+        $calendarRoomPrincipals->disableListing = $disableListing;
81
+
82
+
83
+        $filesCollection = new Files\RootCollection($userPrincipalBackend, 'principals/users');
84
+        $filesCollection->disableListing = $disableListing;
85
+        $caldavBackend = new CalDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $random, $logger, $dispatcher);
86
+        $userCalendarRoot = new CalendarRoot($userPrincipalBackend, $caldavBackend, 'principals/users');
87
+        $userCalendarRoot->disableListing = $disableListing;
88
+
89
+        $resourceCalendarCaldavBackend = new CalDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $random, $logger, $dispatcher);
90
+        $resourceCalendarRoot = new CalendarRoot($calendarResourcePrincipalBackend, $caldavBackend, 'principals/calendar-resources');
91
+        $resourceCalendarRoot->disableListing = $disableListing;
92
+        $roomCalendarCaldavBackend = new CalDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $random, $logger, $dispatcher);
93
+        $roomCalendarRoot = new CalendarRoot($calendarRoomPrincipalBackend, $roomCalendarCaldavBackend, 'principals/calendar-rooms');
94
+        $roomCalendarRoot->disableListing = $disableListing;
95
+
96
+        $publicCalendarRoot = new PublicCalendarRoot($caldavBackend, $l10n, $config);
97
+        $publicCalendarRoot->disableListing = $disableListing;
98
+
99
+        $systemTagCollection = new SystemTag\SystemTagsByIdCollection(
100
+            \OC::$server->getSystemTagManager(),
101
+            \OC::$server->getUserSession(),
102
+            $groupManager
103
+        );
104
+        $systemTagRelationsCollection = new SystemTag\SystemTagsRelationsCollection(
105
+            \OC::$server->getSystemTagManager(),
106
+            \OC::$server->getSystemTagObjectMapper(),
107
+            \OC::$server->getUserSession(),
108
+            $groupManager,
109
+            \OC::$server->getEventDispatcher()
110
+        );
111
+        $commentsCollection = new Comments\RootCollection(
112
+            \OC::$server->getCommentsManager(),
113
+            $userManager,
114
+            \OC::$server->getUserSession(),
115
+            \OC::$server->getEventDispatcher(),
116
+            \OC::$server->getLogger()
117
+        );
118
+
119
+        $usersCardDavBackend = new CardDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $dispatcher);
120
+        $usersAddressBookRoot = new AddressBookRoot($userPrincipalBackend, $usersCardDavBackend, 'principals/users');
121
+        $usersAddressBookRoot->disableListing = $disableListing;
122
+
123
+        $systemCardDavBackend = new CardDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $dispatcher);
124
+        $systemAddressBookRoot = new AddressBookRoot(new SystemPrincipalBackend(), $systemCardDavBackend, 'principals/system');
125
+        $systemAddressBookRoot->disableListing = $disableListing;
126
+
127
+        $uploadCollection = new Upload\RootCollection(
128
+            $userPrincipalBackend,
129
+            'principals/users',
130
+            \OC::$server->query(CleanupService::class));
131
+        $uploadCollection->disableListing = $disableListing;
132
+
133
+        $avatarCollection = new Avatars\RootCollection($userPrincipalBackend, 'principals/users');
134
+        $avatarCollection->disableListing = $disableListing;
135
+
136
+        $appleProvisioning = new AppleProvisioningNode(
137
+            \OC::$server->query(ITimeFactory::class));
138
+
139
+        $children = [
140
+                new SimpleCollection('principals', [
141
+                        $userPrincipals,
142
+                        $groupPrincipals,
143
+                        $systemPrincipals,
144
+                        $calendarResourcePrincipals,
145
+                        $calendarRoomPrincipals]),
146
+                $filesCollection,
147
+                $userCalendarRoot,
148
+                new SimpleCollection('system-calendars', [
149
+                    $resourceCalendarRoot,
150
+                    $roomCalendarRoot,
151
+                ]),
152
+                $publicCalendarRoot,
153
+                new SimpleCollection('addressbooks', [
154
+                        $usersAddressBookRoot,
155
+                        $systemAddressBookRoot]),
156
+                $systemTagCollection,
157
+                $systemTagRelationsCollection,
158
+                $commentsCollection,
159
+                $uploadCollection,
160
+                $avatarCollection,
161
+                new SimpleCollection('provisioning', [
162
+                    $appleProvisioning
163
+                ])
164
+        ];
165
+
166
+        parent::__construct('root', $children);
167
+    }
168 168
 
169 169
 }
Please login to merge, or discard this patch.
apps/dav/lib/CardDAV/CardDavBackend.php 1 patch
Indentation   +1112 added lines, -1112 removed lines patch added patch discarded remove patch
@@ -53,1116 +53,1116 @@
 block discarded – undo
53 53
 
54 54
 class CardDavBackend implements BackendInterface, SyncSupport {
55 55
 
56
-	const PERSONAL_ADDRESSBOOK_URI = 'contacts';
57
-	const PERSONAL_ADDRESSBOOK_NAME = 'Contacts';
58
-
59
-	/** @var Principal */
60
-	private $principalBackend;
61
-
62
-	/** @var string */
63
-	private $dbCardsTable = 'cards';
64
-
65
-	/** @var string */
66
-	private $dbCardsPropertiesTable = 'cards_properties';
67
-
68
-	/** @var IDBConnection */
69
-	private $db;
70
-
71
-	/** @var Backend */
72
-	private $sharingBackend;
73
-
74
-	/** @var array properties to index */
75
-	public static $indexProperties = array(
76
-			'BDAY', 'UID', 'N', 'FN', 'TITLE', 'ROLE', 'NOTE', 'NICKNAME',
77
-			'ORG', 'CATEGORIES', 'EMAIL', 'TEL', 'IMPP', 'ADR', 'URL', 'GEO', 'CLOUD');
78
-
79
-	/**
80
-	 * @var string[] Map of uid => display name
81
-	 */
82
-	protected $userDisplayNames;
83
-
84
-	/** @var IUserManager */
85
-	private $userManager;
86
-
87
-	/** @var EventDispatcherInterface */
88
-	private $dispatcher;
89
-
90
-	/**
91
-	 * CardDavBackend constructor.
92
-	 *
93
-	 * @param IDBConnection $db
94
-	 * @param Principal $principalBackend
95
-	 * @param IUserManager $userManager
96
-	 * @param IGroupManager $groupManager
97
-	 * @param EventDispatcherInterface $dispatcher
98
-	 */
99
-	public function __construct(IDBConnection $db,
100
-								Principal $principalBackend,
101
-								IUserManager $userManager,
102
-								IGroupManager $groupManager,
103
-								EventDispatcherInterface $dispatcher) {
104
-		$this->db = $db;
105
-		$this->principalBackend = $principalBackend;
106
-		$this->userManager = $userManager;
107
-		$this->dispatcher = $dispatcher;
108
-		$this->sharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'addressbook');
109
-	}
110
-
111
-	/**
112
-	 * Return the number of address books for a principal
113
-	 *
114
-	 * @param $principalUri
115
-	 * @return int
116
-	 */
117
-	public function getAddressBooksForUserCount($principalUri) {
118
-		$principalUri = $this->convertPrincipal($principalUri, true);
119
-		$query = $this->db->getQueryBuilder();
120
-		$query->select($query->func()->count('*'))
121
-			->from('addressbooks')
122
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
123
-
124
-		return (int)$query->execute()->fetchColumn();
125
-	}
126
-
127
-	/**
128
-	 * Returns the list of address books for a specific user.
129
-	 *
130
-	 * Every addressbook should have the following properties:
131
-	 *   id - an arbitrary unique id
132
-	 *   uri - the 'basename' part of the url
133
-	 *   principaluri - Same as the passed parameter
134
-	 *
135
-	 * Any additional clark-notation property may be passed besides this. Some
136
-	 * common ones are :
137
-	 *   {DAV:}displayname
138
-	 *   {urn:ietf:params:xml:ns:carddav}addressbook-description
139
-	 *   {http://calendarserver.org/ns/}getctag
140
-	 *
141
-	 * @param string $principalUri
142
-	 * @return array
143
-	 */
144
-	function getAddressBooksForUser($principalUri) {
145
-		$principalUriOriginal = $principalUri;
146
-		$principalUri = $this->convertPrincipal($principalUri, true);
147
-		$query = $this->db->getQueryBuilder();
148
-		$query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
149
-			->from('addressbooks')
150
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
151
-
152
-		$addressBooks = [];
153
-
154
-		$result = $query->execute();
155
-		while($row = $result->fetch()) {
156
-			$addressBooks[$row['id']] = [
157
-				'id'  => $row['id'],
158
-				'uri' => $row['uri'],
159
-				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
160
-				'{DAV:}displayname' => $row['displayname'],
161
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
162
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
163
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
164
-			];
165
-
166
-			$this->addOwnerPrincipal($addressBooks[$row['id']]);
167
-		}
168
-		$result->closeCursor();
169
-
170
-		// query for shared addressbooks
171
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
172
-		$principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
173
-
174
-		$principals = array_map(function($principal) {
175
-			return urldecode($principal);
176
-		}, $principals);
177
-		$principals[]= $principalUri;
178
-
179
-		$query = $this->db->getQueryBuilder();
180
-		$result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
181
-			->from('dav_shares', 's')
182
-			->join('s', 'addressbooks', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
183
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
184
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
185
-			->setParameter('type', 'addressbook')
186
-			->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
187
-			->execute();
188
-
189
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
190
-		while($row = $result->fetch()) {
191
-			if ($row['principaluri'] === $principalUri) {
192
-				continue;
193
-			}
194
-
195
-			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
196
-			if (isset($addressBooks[$row['id']])) {
197
-				if ($readOnly) {
198
-					// New share can not have more permissions then the old one.
199
-					continue;
200
-				}
201
-				if (isset($addressBooks[$row['id']][$readOnlyPropertyName]) &&
202
-					$addressBooks[$row['id']][$readOnlyPropertyName] === 0) {
203
-					// Old share is already read-write, no more permissions can be gained
204
-					continue;
205
-				}
206
-			}
207
-
208
-			list(, $name) = \Sabre\Uri\split($row['principaluri']);
209
-			$uri = $row['uri'] . '_shared_by_' . $name;
210
-			$displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
211
-
212
-			$addressBooks[$row['id']] = [
213
-				'id'  => $row['id'],
214
-				'uri' => $uri,
215
-				'principaluri' => $principalUriOriginal,
216
-				'{DAV:}displayname' => $displayName,
217
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
218
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
219
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
220
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
221
-				$readOnlyPropertyName => $readOnly,
222
-			];
223
-
224
-			$this->addOwnerPrincipal($addressBooks[$row['id']]);
225
-		}
226
-		$result->closeCursor();
227
-
228
-		return array_values($addressBooks);
229
-	}
230
-
231
-	public function getUsersOwnAddressBooks($principalUri) {
232
-		$principalUri = $this->convertPrincipal($principalUri, true);
233
-		$query = $this->db->getQueryBuilder();
234
-		$query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
235
-			  ->from('addressbooks')
236
-			  ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
237
-
238
-		$addressBooks = [];
239
-
240
-		$result = $query->execute();
241
-		while($row = $result->fetch()) {
242
-			$addressBooks[$row['id']] = [
243
-				'id'  => $row['id'],
244
-				'uri' => $row['uri'],
245
-				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
246
-				'{DAV:}displayname' => $row['displayname'],
247
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
248
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
249
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
250
-			];
251
-
252
-			$this->addOwnerPrincipal($addressBooks[$row['id']]);
253
-		}
254
-		$result->closeCursor();
255
-
256
-		return array_values($addressBooks);
257
-	}
258
-
259
-	private function getUserDisplayName($uid) {
260
-		if (!isset($this->userDisplayNames[$uid])) {
261
-			$user = $this->userManager->get($uid);
262
-
263
-			if ($user instanceof IUser) {
264
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
265
-			} else {
266
-				$this->userDisplayNames[$uid] = $uid;
267
-			}
268
-		}
269
-
270
-		return $this->userDisplayNames[$uid];
271
-	}
272
-
273
-	/**
274
-	 * @param int $addressBookId
275
-	 */
276
-	public function getAddressBookById($addressBookId) {
277
-		$query = $this->db->getQueryBuilder();
278
-		$result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
279
-			->from('addressbooks')
280
-			->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
281
-			->execute();
282
-
283
-		$row = $result->fetch();
284
-		$result->closeCursor();
285
-		if ($row === false) {
286
-			return null;
287
-		}
288
-
289
-		$addressBook = [
290
-			'id'  => $row['id'],
291
-			'uri' => $row['uri'],
292
-			'principaluri' => $row['principaluri'],
293
-			'{DAV:}displayname' => $row['displayname'],
294
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
295
-			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
296
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
297
-		];
298
-
299
-		$this->addOwnerPrincipal($addressBook);
300
-
301
-		return $addressBook;
302
-	}
303
-
304
-	/**
305
-	 * @param $addressBookUri
306
-	 * @return array|null
307
-	 */
308
-	public function getAddressBooksByUri($principal, $addressBookUri) {
309
-		$query = $this->db->getQueryBuilder();
310
-		$result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
311
-			->from('addressbooks')
312
-			->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
313
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
314
-			->setMaxResults(1)
315
-			->execute();
316
-
317
-		$row = $result->fetch();
318
-		$result->closeCursor();
319
-		if ($row === false) {
320
-			return null;
321
-		}
322
-
323
-		$addressBook = [
324
-			'id'  => $row['id'],
325
-			'uri' => $row['uri'],
326
-			'principaluri' => $row['principaluri'],
327
-			'{DAV:}displayname' => $row['displayname'],
328
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
329
-			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
330
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
331
-		];
332
-
333
-		$this->addOwnerPrincipal($addressBook);
334
-
335
-		return $addressBook;
336
-	}
337
-
338
-	/**
339
-	 * Updates properties for an address book.
340
-	 *
341
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
342
-	 * To do the actual updates, you must tell this object which properties
343
-	 * you're going to process with the handle() method.
344
-	 *
345
-	 * Calling the handle method is like telling the PropPatch object "I
346
-	 * promise I can handle updating this property".
347
-	 *
348
-	 * Read the PropPatch documentation for more info and examples.
349
-	 *
350
-	 * @param string $addressBookId
351
-	 * @param \Sabre\DAV\PropPatch $propPatch
352
-	 * @return void
353
-	 */
354
-	function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
355
-		$supportedProperties = [
356
-			'{DAV:}displayname',
357
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description',
358
-		];
359
-
360
-		/**
361
-		 * @suppress SqlInjectionChecker
362
-		 */
363
-		$propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
364
-
365
-			$updates = [];
366
-			foreach($mutations as $property=>$newValue) {
367
-
368
-				switch($property) {
369
-					case '{DAV:}displayname' :
370
-						$updates['displayname'] = $newValue;
371
-						break;
372
-					case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
373
-						$updates['description'] = $newValue;
374
-						break;
375
-				}
376
-			}
377
-			$query = $this->db->getQueryBuilder();
378
-			$query->update('addressbooks');
379
-
380
-			foreach($updates as $key=>$value) {
381
-				$query->set($key, $query->createNamedParameter($value));
382
-			}
383
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
384
-			->execute();
385
-
386
-			$this->addChange($addressBookId, "", 2);
387
-
388
-			return true;
389
-
390
-		});
391
-	}
392
-
393
-	/**
394
-	 * Creates a new address book
395
-	 *
396
-	 * @param string $principalUri
397
-	 * @param string $url Just the 'basename' of the url.
398
-	 * @param array $properties
399
-	 * @return int
400
-	 * @throws BadRequest
401
-	 */
402
-	function createAddressBook($principalUri, $url, array $properties) {
403
-		$values = [
404
-			'displayname' => null,
405
-			'description' => null,
406
-			'principaluri' => $principalUri,
407
-			'uri' => $url,
408
-			'synctoken' => 1
409
-		];
410
-
411
-		foreach($properties as $property=>$newValue) {
412
-
413
-			switch($property) {
414
-				case '{DAV:}displayname' :
415
-					$values['displayname'] = $newValue;
416
-					break;
417
-				case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
418
-					$values['description'] = $newValue;
419
-					break;
420
-				default :
421
-					throw new BadRequest('Unknown property: ' . $property);
422
-			}
423
-
424
-		}
425
-
426
-		// Fallback to make sure the displayname is set. Some clients may refuse
427
-		// to work with addressbooks not having a displayname.
428
-		if(is_null($values['displayname'])) {
429
-			$values['displayname'] = $url;
430
-		}
431
-
432
-		$query = $this->db->getQueryBuilder();
433
-		$query->insert('addressbooks')
434
-			->values([
435
-				'uri' => $query->createParameter('uri'),
436
-				'displayname' => $query->createParameter('displayname'),
437
-				'description' => $query->createParameter('description'),
438
-				'principaluri' => $query->createParameter('principaluri'),
439
-				'synctoken' => $query->createParameter('synctoken'),
440
-			])
441
-			->setParameters($values)
442
-			->execute();
443
-
444
-		return $query->getLastInsertId();
445
-	}
446
-
447
-	/**
448
-	 * Deletes an entire addressbook and all its contents
449
-	 *
450
-	 * @param mixed $addressBookId
451
-	 * @return void
452
-	 */
453
-	function deleteAddressBook($addressBookId) {
454
-		$query = $this->db->getQueryBuilder();
455
-		$query->delete('cards')
456
-			->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
457
-			->setParameter('addressbookid', $addressBookId)
458
-			->execute();
459
-
460
-		$query->delete('addressbookchanges')
461
-			->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
462
-			->setParameter('addressbookid', $addressBookId)
463
-			->execute();
464
-
465
-		$query->delete('addressbooks')
466
-			->where($query->expr()->eq('id', $query->createParameter('id')))
467
-			->setParameter('id', $addressBookId)
468
-			->execute();
469
-
470
-		$this->sharingBackend->deleteAllShares($addressBookId);
471
-
472
-		$query->delete($this->dbCardsPropertiesTable)
473
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
474
-			->execute();
475
-
476
-	}
477
-
478
-	/**
479
-	 * Returns all cards for a specific addressbook id.
480
-	 *
481
-	 * This method should return the following properties for each card:
482
-	 *   * carddata - raw vcard data
483
-	 *   * uri - Some unique url
484
-	 *   * lastmodified - A unix timestamp
485
-	 *
486
-	 * It's recommended to also return the following properties:
487
-	 *   * etag - A unique etag. This must change every time the card changes.
488
-	 *   * size - The size of the card in bytes.
489
-	 *
490
-	 * If these last two properties are provided, less time will be spent
491
-	 * calculating them. If they are specified, you can also ommit carddata.
492
-	 * This may speed up certain requests, especially with large cards.
493
-	 *
494
-	 * @param mixed $addressBookId
495
-	 * @return array
496
-	 */
497
-	function getCards($addressBookId) {
498
-		$query = $this->db->getQueryBuilder();
499
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
500
-			->from('cards')
501
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
502
-
503
-		$cards = [];
504
-
505
-		$result = $query->execute();
506
-		while($row = $result->fetch()) {
507
-			$row['etag'] = '"' . $row['etag'] . '"';
508
-			$row['carddata'] = $this->readBlob($row['carddata']);
509
-			$cards[] = $row;
510
-		}
511
-		$result->closeCursor();
512
-
513
-		return $cards;
514
-	}
515
-
516
-	/**
517
-	 * Returns a specific card.
518
-	 *
519
-	 * The same set of properties must be returned as with getCards. The only
520
-	 * exception is that 'carddata' is absolutely required.
521
-	 *
522
-	 * If the card does not exist, you must return false.
523
-	 *
524
-	 * @param mixed $addressBookId
525
-	 * @param string $cardUri
526
-	 * @return array
527
-	 */
528
-	function getCard($addressBookId, $cardUri) {
529
-		$query = $this->db->getQueryBuilder();
530
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
531
-			->from('cards')
532
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
533
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
534
-			->setMaxResults(1);
535
-
536
-		$result = $query->execute();
537
-		$row = $result->fetch();
538
-		if (!$row) {
539
-			return false;
540
-		}
541
-		$row['etag'] = '"' . $row['etag'] . '"';
542
-		$row['carddata'] = $this->readBlob($row['carddata']);
543
-
544
-		return $row;
545
-	}
546
-
547
-	/**
548
-	 * Returns a list of cards.
549
-	 *
550
-	 * This method should work identical to getCard, but instead return all the
551
-	 * cards in the list as an array.
552
-	 *
553
-	 * If the backend supports this, it may allow for some speed-ups.
554
-	 *
555
-	 * @param mixed $addressBookId
556
-	 * @param string[] $uris
557
-	 * @return array
558
-	 */
559
-	function getMultipleCards($addressBookId, array $uris) {
560
-		if (empty($uris)) {
561
-			return [];
562
-		}
563
-
564
-		$chunks = array_chunk($uris, 100);
565
-		$cards = [];
566
-
567
-		$query = $this->db->getQueryBuilder();
568
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
569
-			->from('cards')
570
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
571
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
572
-
573
-		foreach ($chunks as $uris) {
574
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
575
-			$result = $query->execute();
576
-
577
-			while ($row = $result->fetch()) {
578
-				$row['etag'] = '"' . $row['etag'] . '"';
579
-				$row['carddata'] = $this->readBlob($row['carddata']);
580
-				$cards[] = $row;
581
-			}
582
-			$result->closeCursor();
583
-		}
584
-		return $cards;
585
-	}
586
-
587
-	/**
588
-	 * Creates a new card.
589
-	 *
590
-	 * The addressbook id will be passed as the first argument. This is the
591
-	 * same id as it is returned from the getAddressBooksForUser method.
592
-	 *
593
-	 * The cardUri is a base uri, and doesn't include the full path. The
594
-	 * cardData argument is the vcard body, and is passed as a string.
595
-	 *
596
-	 * It is possible to return an ETag from this method. This ETag is for the
597
-	 * newly created resource, and must be enclosed with double quotes (that
598
-	 * is, the string itself must contain the double quotes).
599
-	 *
600
-	 * You should only return the ETag if you store the carddata as-is. If a
601
-	 * subsequent GET request on the same card does not have the same body,
602
-	 * byte-by-byte and you did return an ETag here, clients tend to get
603
-	 * confused.
604
-	 *
605
-	 * If you don't return an ETag, you can just return null.
606
-	 *
607
-	 * @param mixed $addressBookId
608
-	 * @param string $cardUri
609
-	 * @param string $cardData
610
-	 * @return string
611
-	 */
612
-	function createCard($addressBookId, $cardUri, $cardData) {
613
-		$etag = md5($cardData);
614
-		$uid = $this->getUID($cardData);
615
-
616
-		$q = $this->db->getQueryBuilder();
617
-		$q->select('uid')
618
-			->from('cards')
619
-			->where($q->expr()->eq('addressbookid', $q->createNamedParameter($addressBookId)))
620
-			->andWhere($q->expr()->eq('uid', $q->createNamedParameter($uid)))
621
-			->setMaxResults(1);
622
-		$result = $q->execute();
623
-		$count = (bool) $result->fetchColumn();
624
-		$result->closeCursor();
625
-		if ($count) {
626
-			throw new \Sabre\DAV\Exception\BadRequest('VCard object with uid already exists in this addressbook collection.');
627
-		}
628
-
629
-		$query = $this->db->getQueryBuilder();
630
-		$query->insert('cards')
631
-			->values([
632
-				'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
633
-				'uri' => $query->createNamedParameter($cardUri),
634
-				'lastmodified' => $query->createNamedParameter(time()),
635
-				'addressbookid' => $query->createNamedParameter($addressBookId),
636
-				'size' => $query->createNamedParameter(strlen($cardData)),
637
-				'etag' => $query->createNamedParameter($etag),
638
-				'uid' => $query->createNamedParameter($uid),
639
-			])
640
-			->execute();
641
-
642
-		$this->addChange($addressBookId, $cardUri, 1);
643
-		$this->updateProperties($addressBookId, $cardUri, $cardData);
644
-
645
-		$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
646
-			new GenericEvent(null, [
647
-				'addressBookId' => $addressBookId,
648
-				'cardUri' => $cardUri,
649
-				'cardData' => $cardData]));
650
-
651
-		return '"' . $etag . '"';
652
-	}
653
-
654
-	/**
655
-	 * Updates a card.
656
-	 *
657
-	 * The addressbook id will be passed as the first argument. This is the
658
-	 * same id as it is returned from the getAddressBooksForUser method.
659
-	 *
660
-	 * The cardUri is a base uri, and doesn't include the full path. The
661
-	 * cardData argument is the vcard body, and is passed as a string.
662
-	 *
663
-	 * It is possible to return an ETag from this method. This ETag should
664
-	 * match that of the updated resource, and must be enclosed with double
665
-	 * quotes (that is: the string itself must contain the actual quotes).
666
-	 *
667
-	 * You should only return the ETag if you store the carddata as-is. If a
668
-	 * subsequent GET request on the same card does not have the same body,
669
-	 * byte-by-byte and you did return an ETag here, clients tend to get
670
-	 * confused.
671
-	 *
672
-	 * If you don't return an ETag, you can just return null.
673
-	 *
674
-	 * @param mixed $addressBookId
675
-	 * @param string $cardUri
676
-	 * @param string $cardData
677
-	 * @return string
678
-	 */
679
-	function updateCard($addressBookId, $cardUri, $cardData) {
680
-
681
-		$uid = $this->getUID($cardData);
682
-		$etag = md5($cardData);
683
-		$query = $this->db->getQueryBuilder();
684
-		$query->update('cards')
685
-			->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
686
-			->set('lastmodified', $query->createNamedParameter(time()))
687
-			->set('size', $query->createNamedParameter(strlen($cardData)))
688
-			->set('etag', $query->createNamedParameter($etag))
689
-			->set('uid', $query->createNamedParameter($uid))
690
-			->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
691
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
692
-			->execute();
693
-
694
-		$this->addChange($addressBookId, $cardUri, 2);
695
-		$this->updateProperties($addressBookId, $cardUri, $cardData);
696
-
697
-		$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
698
-			new GenericEvent(null, [
699
-				'addressBookId' => $addressBookId,
700
-				'cardUri' => $cardUri,
701
-				'cardData' => $cardData]));
702
-
703
-		return '"' . $etag . '"';
704
-	}
705
-
706
-	/**
707
-	 * Deletes a card
708
-	 *
709
-	 * @param mixed $addressBookId
710
-	 * @param string $cardUri
711
-	 * @return bool
712
-	 */
713
-	function deleteCard($addressBookId, $cardUri) {
714
-		try {
715
-			$cardId = $this->getCardId($addressBookId, $cardUri);
716
-		} catch (\InvalidArgumentException $e) {
717
-			$cardId = null;
718
-		}
719
-		$query = $this->db->getQueryBuilder();
720
-		$ret = $query->delete('cards')
721
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
722
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
723
-			->execute();
724
-
725
-		$this->addChange($addressBookId, $cardUri, 3);
726
-
727
-		$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
728
-			new GenericEvent(null, [
729
-				'addressBookId' => $addressBookId,
730
-				'cardUri' => $cardUri]));
731
-
732
-		if ($ret === 1) {
733
-			if ($cardId !== null) {
734
-				$this->purgeProperties($addressBookId, $cardId);
735
-			}
736
-			return true;
737
-		}
738
-
739
-		return false;
740
-	}
741
-
742
-	/**
743
-	 * The getChanges method returns all the changes that have happened, since
744
-	 * the specified syncToken in the specified address book.
745
-	 *
746
-	 * This function should return an array, such as the following:
747
-	 *
748
-	 * [
749
-	 *   'syncToken' => 'The current synctoken',
750
-	 *   'added'   => [
751
-	 *      'new.txt',
752
-	 *   ],
753
-	 *   'modified'   => [
754
-	 *      'modified.txt',
755
-	 *   ],
756
-	 *   'deleted' => [
757
-	 *      'foo.php.bak',
758
-	 *      'old.txt'
759
-	 *   ]
760
-	 * ];
761
-	 *
762
-	 * The returned syncToken property should reflect the *current* syncToken
763
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
764
-	 * property. This is needed here too, to ensure the operation is atomic.
765
-	 *
766
-	 * If the $syncToken argument is specified as null, this is an initial
767
-	 * sync, and all members should be reported.
768
-	 *
769
-	 * The modified property is an array of nodenames that have changed since
770
-	 * the last token.
771
-	 *
772
-	 * The deleted property is an array with nodenames, that have been deleted
773
-	 * from collection.
774
-	 *
775
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
776
-	 * 1, you only have to report changes that happened only directly in
777
-	 * immediate descendants. If it's 2, it should also include changes from
778
-	 * the nodes below the child collections. (grandchildren)
779
-	 *
780
-	 * The $limit argument allows a client to specify how many results should
781
-	 * be returned at most. If the limit is not specified, it should be treated
782
-	 * as infinite.
783
-	 *
784
-	 * If the limit (infinite or not) is higher than you're willing to return,
785
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
786
-	 *
787
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
788
-	 * return null.
789
-	 *
790
-	 * The limit is 'suggestive'. You are free to ignore it.
791
-	 *
792
-	 * @param string $addressBookId
793
-	 * @param string $syncToken
794
-	 * @param int $syncLevel
795
-	 * @param int $limit
796
-	 * @return array
797
-	 */
798
-	function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
799
-		// Current synctoken
800
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
801
-		$stmt->execute([ $addressBookId ]);
802
-		$currentToken = $stmt->fetchColumn(0);
803
-
804
-		if (is_null($currentToken)) return null;
805
-
806
-		$result = [
807
-			'syncToken' => $currentToken,
808
-			'added'     => [],
809
-			'modified'  => [],
810
-			'deleted'   => [],
811
-		];
812
-
813
-		if ($syncToken) {
814
-
815
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
816
-			if ($limit>0) {
817
-				$query .= " `LIMIT` " . (int)$limit;
818
-			}
819
-
820
-			// Fetching all changes
821
-			$stmt = $this->db->prepare($query);
822
-			$stmt->execute([$syncToken, $currentToken, $addressBookId]);
823
-
824
-			$changes = [];
825
-
826
-			// This loop ensures that any duplicates are overwritten, only the
827
-			// last change on a node is relevant.
828
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
829
-
830
-				$changes[$row['uri']] = $row['operation'];
831
-
832
-			}
833
-
834
-			foreach($changes as $uri => $operation) {
835
-
836
-				switch($operation) {
837
-					case 1:
838
-						$result['added'][] = $uri;
839
-						break;
840
-					case 2:
841
-						$result['modified'][] = $uri;
842
-						break;
843
-					case 3:
844
-						$result['deleted'][] = $uri;
845
-						break;
846
-				}
847
-
848
-			}
849
-		} else {
850
-			// No synctoken supplied, this is the initial sync.
851
-			$query = "SELECT `uri` FROM `*PREFIX*cards` WHERE `addressbookid` = ?";
852
-			$stmt = $this->db->prepare($query);
853
-			$stmt->execute([$addressBookId]);
854
-
855
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
856
-		}
857
-		return $result;
858
-	}
859
-
860
-	/**
861
-	 * Adds a change record to the addressbookchanges table.
862
-	 *
863
-	 * @param mixed $addressBookId
864
-	 * @param string $objectUri
865
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete
866
-	 * @return void
867
-	 */
868
-	protected function addChange($addressBookId, $objectUri, $operation) {
869
-		$sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?';
870
-		$stmt = $this->db->prepare($sql);
871
-		$stmt->execute([
872
-			$objectUri,
873
-			$addressBookId,
874
-			$operation,
875
-			$addressBookId
876
-		]);
877
-		$stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
878
-		$stmt->execute([
879
-			$addressBookId
880
-		]);
881
-	}
882
-
883
-	private function readBlob($cardData) {
884
-		if (is_resource($cardData)) {
885
-			return stream_get_contents($cardData);
886
-		}
887
-
888
-		return $cardData;
889
-	}
890
-
891
-	/**
892
-	 * @param IShareable $shareable
893
-	 * @param string[] $add
894
-	 * @param string[] $remove
895
-	 */
896
-	public function updateShares(IShareable $shareable, $add, $remove) {
897
-		$this->sharingBackend->updateShares($shareable, $add, $remove);
898
-	}
899
-
900
-	/**
901
-	 * search contact
902
-	 *
903
-	 * @param int $addressBookId
904
-	 * @param string $pattern which should match within the $searchProperties
905
-	 * @param array $searchProperties defines the properties within the query pattern should match
906
-	 * @return array an array of contacts which are arrays of key-value-pairs
907
-	 */
908
-	public function search($addressBookId, $pattern, $searchProperties) {
909
-		$query = $this->db->getQueryBuilder();
910
-		$query2 = $this->db->getQueryBuilder();
911
-
912
-		$query2->selectDistinct('cp.cardid')->from($this->dbCardsPropertiesTable, 'cp');
913
-		$query2->andWhere($query2->expr()->eq('cp.addressbookid', $query->createNamedParameter($addressBookId)));
914
-		$or = $query2->expr()->orX();
915
-		foreach ($searchProperties as $property) {
916
-			$or->add($query2->expr()->eq('cp.name', $query->createNamedParameter($property)));
917
-		}
918
-		$query2->andWhere($or);
919
-
920
-		// No need for like when the pattern is empty
921
-		if ('' !== $pattern) {
922
-			$query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
923
-		}
924
-
925
-		$query->select('c.carddata', 'c.uri')->from($this->dbCardsTable, 'c')
926
-			->where($query->expr()->in('c.id', $query->createFunction($query2->getSQL())));
927
-
928
-		$result = $query->execute();
929
-		$cards = $result->fetchAll();
930
-
931
-		$result->closeCursor();
932
-
933
-		return array_map(function($array) {
934
-			$array['carddata'] = $this->readBlob($array['carddata']);
935
-			return $array;
936
-		}, $cards);
937
-	}
938
-
939
-	/**
940
-	 * @param int $bookId
941
-	 * @param string $name
942
-	 * @return array
943
-	 */
944
-	public function collectCardProperties($bookId, $name) {
945
-		$query = $this->db->getQueryBuilder();
946
-		$result = $query->selectDistinct('value')
947
-			->from($this->dbCardsPropertiesTable)
948
-			->where($query->expr()->eq('name', $query->createNamedParameter($name)))
949
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
950
-			->execute();
951
-
952
-		$all = $result->fetchAll(PDO::FETCH_COLUMN);
953
-		$result->closeCursor();
954
-
955
-		return $all;
956
-	}
957
-
958
-	/**
959
-	 * get URI from a given contact
960
-	 *
961
-	 * @param int $id
962
-	 * @return string
963
-	 */
964
-	public function getCardUri($id) {
965
-		$query = $this->db->getQueryBuilder();
966
-		$query->select('uri')->from($this->dbCardsTable)
967
-				->where($query->expr()->eq('id', $query->createParameter('id')))
968
-				->setParameter('id', $id);
969
-
970
-		$result = $query->execute();
971
-		$uri = $result->fetch();
972
-		$result->closeCursor();
973
-
974
-		if (!isset($uri['uri'])) {
975
-			throw new \InvalidArgumentException('Card does not exists: ' . $id);
976
-		}
977
-
978
-		return $uri['uri'];
979
-	}
980
-
981
-	/**
982
-	 * return contact with the given URI
983
-	 *
984
-	 * @param int $addressBookId
985
-	 * @param string $uri
986
-	 * @returns array
987
-	 */
988
-	public function getContact($addressBookId, $uri) {
989
-		$result = [];
990
-		$query = $this->db->getQueryBuilder();
991
-		$query->select('*')->from($this->dbCardsTable)
992
-				->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
993
-				->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
994
-		$queryResult = $query->execute();
995
-		$contact = $queryResult->fetch();
996
-		$queryResult->closeCursor();
997
-
998
-		if (is_array($contact)) {
999
-			$result = $contact;
1000
-		}
1001
-
1002
-		return $result;
1003
-	}
1004
-
1005
-	/**
1006
-	 * Returns the list of people whom this address book is shared with.
1007
-	 *
1008
-	 * Every element in this array should have the following properties:
1009
-	 *   * href - Often a mailto: address
1010
-	 *   * commonName - Optional, for example a first + last name
1011
-	 *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
1012
-	 *   * readOnly - boolean
1013
-	 *   * summary - Optional, a description for the share
1014
-	 *
1015
-	 * @return array
1016
-	 */
1017
-	public function getShares($addressBookId) {
1018
-		return $this->sharingBackend->getShares($addressBookId);
1019
-	}
1020
-
1021
-	/**
1022
-	 * update properties table
1023
-	 *
1024
-	 * @param int $addressBookId
1025
-	 * @param string $cardUri
1026
-	 * @param string $vCardSerialized
1027
-	 */
1028
-	protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
1029
-		$cardId = $this->getCardId($addressBookId, $cardUri);
1030
-		$vCard = $this->readCard($vCardSerialized);
1031
-
1032
-		$this->purgeProperties($addressBookId, $cardId);
1033
-
1034
-		$query = $this->db->getQueryBuilder();
1035
-		$query->insert($this->dbCardsPropertiesTable)
1036
-			->values(
1037
-				[
1038
-					'addressbookid' => $query->createNamedParameter($addressBookId),
1039
-					'cardid' => $query->createNamedParameter($cardId),
1040
-					'name' => $query->createParameter('name'),
1041
-					'value' => $query->createParameter('value'),
1042
-					'preferred' => $query->createParameter('preferred')
1043
-				]
1044
-			);
1045
-
1046
-		foreach ($vCard->children() as $property) {
1047
-			if(!in_array($property->name, self::$indexProperties)) {
1048
-				continue;
1049
-			}
1050
-			$preferred = 0;
1051
-			foreach($property->parameters as $parameter) {
1052
-				if ($parameter->name === 'TYPE' && strtoupper($parameter->getValue()) === 'PREF') {
1053
-					$preferred = 1;
1054
-					break;
1055
-				}
1056
-			}
1057
-			$query->setParameter('name', $property->name);
1058
-			$query->setParameter('value', substr($property->getValue(), 0, 254));
1059
-			$query->setParameter('preferred', $preferred);
1060
-			$query->execute();
1061
-		}
1062
-	}
1063
-
1064
-	/**
1065
-	 * read vCard data into a vCard object
1066
-	 *
1067
-	 * @param string $cardData
1068
-	 * @return VCard
1069
-	 */
1070
-	protected function readCard($cardData) {
1071
-		return  Reader::read($cardData);
1072
-	}
1073
-
1074
-	/**
1075
-	 * delete all properties from a given card
1076
-	 *
1077
-	 * @param int $addressBookId
1078
-	 * @param int $cardId
1079
-	 */
1080
-	protected function purgeProperties($addressBookId, $cardId) {
1081
-		$query = $this->db->getQueryBuilder();
1082
-		$query->delete($this->dbCardsPropertiesTable)
1083
-			->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
1084
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1085
-		$query->execute();
1086
-	}
1087
-
1088
-	/**
1089
-	 * get ID from a given contact
1090
-	 *
1091
-	 * @param int $addressBookId
1092
-	 * @param string $uri
1093
-	 * @return int
1094
-	 */
1095
-	protected function getCardId($addressBookId, $uri) {
1096
-		$query = $this->db->getQueryBuilder();
1097
-		$query->select('id')->from($this->dbCardsTable)
1098
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1099
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1100
-
1101
-		$result = $query->execute();
1102
-		$cardIds = $result->fetch();
1103
-		$result->closeCursor();
1104
-
1105
-		if (!isset($cardIds['id'])) {
1106
-			throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1107
-		}
1108
-
1109
-		return (int)$cardIds['id'];
1110
-	}
1111
-
1112
-	/**
1113
-	 * For shared address books the sharee is set in the ACL of the address book
1114
-	 * @param $addressBookId
1115
-	 * @param $acl
1116
-	 * @return array
1117
-	 */
1118
-	public function applyShareAcl($addressBookId, $acl) {
1119
-		return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1120
-	}
1121
-
1122
-	private function convertPrincipal($principalUri, $toV2) {
1123
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1124
-			list(, $name) = \Sabre\Uri\split($principalUri);
1125
-			if ($toV2 === true) {
1126
-				return "principals/users/$name";
1127
-			}
1128
-			return "principals/$name";
1129
-		}
1130
-		return $principalUri;
1131
-	}
1132
-
1133
-	private function addOwnerPrincipal(&$addressbookInfo) {
1134
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
1135
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
1136
-		if (isset($addressbookInfo[$ownerPrincipalKey])) {
1137
-			$uri = $addressbookInfo[$ownerPrincipalKey];
1138
-		} else {
1139
-			$uri = $addressbookInfo['principaluri'];
1140
-		}
1141
-
1142
-		$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
1143
-		if (isset($principalInformation['{DAV:}displayname'])) {
1144
-			$addressbookInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
1145
-		}
1146
-	}
1147
-
1148
-	/**
1149
-	 * Extract UID from vcard
1150
-	 *
1151
-	 * @param string $cardData the vcard raw data
1152
-	 * @return string the uid
1153
-	 * @throws BadRequest if no UID is available
1154
-	 */
1155
-	private function getUID($cardData) {
1156
-		if ($cardData != '') {
1157
-			$vCard = Reader::read($cardData);
1158
-			if ($vCard->UID) {
1159
-				$uid = $vCard->UID->getValue();
1160
-				return $uid;
1161
-			}
1162
-			// should already be handled, but just in case
1163
-			throw new BadRequest('vCards on CardDAV servers MUST have a UID property');
1164
-		}
1165
-		// should already be handled, but just in case
1166
-		throw new BadRequest('vCard can not be empty');
1167
-	}
56
+    const PERSONAL_ADDRESSBOOK_URI = 'contacts';
57
+    const PERSONAL_ADDRESSBOOK_NAME = 'Contacts';
58
+
59
+    /** @var Principal */
60
+    private $principalBackend;
61
+
62
+    /** @var string */
63
+    private $dbCardsTable = 'cards';
64
+
65
+    /** @var string */
66
+    private $dbCardsPropertiesTable = 'cards_properties';
67
+
68
+    /** @var IDBConnection */
69
+    private $db;
70
+
71
+    /** @var Backend */
72
+    private $sharingBackend;
73
+
74
+    /** @var array properties to index */
75
+    public static $indexProperties = array(
76
+            'BDAY', 'UID', 'N', 'FN', 'TITLE', 'ROLE', 'NOTE', 'NICKNAME',
77
+            'ORG', 'CATEGORIES', 'EMAIL', 'TEL', 'IMPP', 'ADR', 'URL', 'GEO', 'CLOUD');
78
+
79
+    /**
80
+     * @var string[] Map of uid => display name
81
+     */
82
+    protected $userDisplayNames;
83
+
84
+    /** @var IUserManager */
85
+    private $userManager;
86
+
87
+    /** @var EventDispatcherInterface */
88
+    private $dispatcher;
89
+
90
+    /**
91
+     * CardDavBackend constructor.
92
+     *
93
+     * @param IDBConnection $db
94
+     * @param Principal $principalBackend
95
+     * @param IUserManager $userManager
96
+     * @param IGroupManager $groupManager
97
+     * @param EventDispatcherInterface $dispatcher
98
+     */
99
+    public function __construct(IDBConnection $db,
100
+                                Principal $principalBackend,
101
+                                IUserManager $userManager,
102
+                                IGroupManager $groupManager,
103
+                                EventDispatcherInterface $dispatcher) {
104
+        $this->db = $db;
105
+        $this->principalBackend = $principalBackend;
106
+        $this->userManager = $userManager;
107
+        $this->dispatcher = $dispatcher;
108
+        $this->sharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'addressbook');
109
+    }
110
+
111
+    /**
112
+     * Return the number of address books for a principal
113
+     *
114
+     * @param $principalUri
115
+     * @return int
116
+     */
117
+    public function getAddressBooksForUserCount($principalUri) {
118
+        $principalUri = $this->convertPrincipal($principalUri, true);
119
+        $query = $this->db->getQueryBuilder();
120
+        $query->select($query->func()->count('*'))
121
+            ->from('addressbooks')
122
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
123
+
124
+        return (int)$query->execute()->fetchColumn();
125
+    }
126
+
127
+    /**
128
+     * Returns the list of address books for a specific user.
129
+     *
130
+     * Every addressbook should have the following properties:
131
+     *   id - an arbitrary unique id
132
+     *   uri - the 'basename' part of the url
133
+     *   principaluri - Same as the passed parameter
134
+     *
135
+     * Any additional clark-notation property may be passed besides this. Some
136
+     * common ones are :
137
+     *   {DAV:}displayname
138
+     *   {urn:ietf:params:xml:ns:carddav}addressbook-description
139
+     *   {http://calendarserver.org/ns/}getctag
140
+     *
141
+     * @param string $principalUri
142
+     * @return array
143
+     */
144
+    function getAddressBooksForUser($principalUri) {
145
+        $principalUriOriginal = $principalUri;
146
+        $principalUri = $this->convertPrincipal($principalUri, true);
147
+        $query = $this->db->getQueryBuilder();
148
+        $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
149
+            ->from('addressbooks')
150
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
151
+
152
+        $addressBooks = [];
153
+
154
+        $result = $query->execute();
155
+        while($row = $result->fetch()) {
156
+            $addressBooks[$row['id']] = [
157
+                'id'  => $row['id'],
158
+                'uri' => $row['uri'],
159
+                'principaluri' => $this->convertPrincipal($row['principaluri'], false),
160
+                '{DAV:}displayname' => $row['displayname'],
161
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
162
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
163
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
164
+            ];
165
+
166
+            $this->addOwnerPrincipal($addressBooks[$row['id']]);
167
+        }
168
+        $result->closeCursor();
169
+
170
+        // query for shared addressbooks
171
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
172
+        $principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
173
+
174
+        $principals = array_map(function($principal) {
175
+            return urldecode($principal);
176
+        }, $principals);
177
+        $principals[]= $principalUri;
178
+
179
+        $query = $this->db->getQueryBuilder();
180
+        $result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
181
+            ->from('dav_shares', 's')
182
+            ->join('s', 'addressbooks', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
183
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
184
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
185
+            ->setParameter('type', 'addressbook')
186
+            ->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
187
+            ->execute();
188
+
189
+        $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
190
+        while($row = $result->fetch()) {
191
+            if ($row['principaluri'] === $principalUri) {
192
+                continue;
193
+            }
194
+
195
+            $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
196
+            if (isset($addressBooks[$row['id']])) {
197
+                if ($readOnly) {
198
+                    // New share can not have more permissions then the old one.
199
+                    continue;
200
+                }
201
+                if (isset($addressBooks[$row['id']][$readOnlyPropertyName]) &&
202
+                    $addressBooks[$row['id']][$readOnlyPropertyName] === 0) {
203
+                    // Old share is already read-write, no more permissions can be gained
204
+                    continue;
205
+                }
206
+            }
207
+
208
+            list(, $name) = \Sabre\Uri\split($row['principaluri']);
209
+            $uri = $row['uri'] . '_shared_by_' . $name;
210
+            $displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
211
+
212
+            $addressBooks[$row['id']] = [
213
+                'id'  => $row['id'],
214
+                'uri' => $uri,
215
+                'principaluri' => $principalUriOriginal,
216
+                '{DAV:}displayname' => $displayName,
217
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
218
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
219
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
220
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
221
+                $readOnlyPropertyName => $readOnly,
222
+            ];
223
+
224
+            $this->addOwnerPrincipal($addressBooks[$row['id']]);
225
+        }
226
+        $result->closeCursor();
227
+
228
+        return array_values($addressBooks);
229
+    }
230
+
231
+    public function getUsersOwnAddressBooks($principalUri) {
232
+        $principalUri = $this->convertPrincipal($principalUri, true);
233
+        $query = $this->db->getQueryBuilder();
234
+        $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
235
+                ->from('addressbooks')
236
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
237
+
238
+        $addressBooks = [];
239
+
240
+        $result = $query->execute();
241
+        while($row = $result->fetch()) {
242
+            $addressBooks[$row['id']] = [
243
+                'id'  => $row['id'],
244
+                'uri' => $row['uri'],
245
+                'principaluri' => $this->convertPrincipal($row['principaluri'], false),
246
+                '{DAV:}displayname' => $row['displayname'],
247
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
248
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
249
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
250
+            ];
251
+
252
+            $this->addOwnerPrincipal($addressBooks[$row['id']]);
253
+        }
254
+        $result->closeCursor();
255
+
256
+        return array_values($addressBooks);
257
+    }
258
+
259
+    private function getUserDisplayName($uid) {
260
+        if (!isset($this->userDisplayNames[$uid])) {
261
+            $user = $this->userManager->get($uid);
262
+
263
+            if ($user instanceof IUser) {
264
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
265
+            } else {
266
+                $this->userDisplayNames[$uid] = $uid;
267
+            }
268
+        }
269
+
270
+        return $this->userDisplayNames[$uid];
271
+    }
272
+
273
+    /**
274
+     * @param int $addressBookId
275
+     */
276
+    public function getAddressBookById($addressBookId) {
277
+        $query = $this->db->getQueryBuilder();
278
+        $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
279
+            ->from('addressbooks')
280
+            ->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
281
+            ->execute();
282
+
283
+        $row = $result->fetch();
284
+        $result->closeCursor();
285
+        if ($row === false) {
286
+            return null;
287
+        }
288
+
289
+        $addressBook = [
290
+            'id'  => $row['id'],
291
+            'uri' => $row['uri'],
292
+            'principaluri' => $row['principaluri'],
293
+            '{DAV:}displayname' => $row['displayname'],
294
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
295
+            '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
296
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
297
+        ];
298
+
299
+        $this->addOwnerPrincipal($addressBook);
300
+
301
+        return $addressBook;
302
+    }
303
+
304
+    /**
305
+     * @param $addressBookUri
306
+     * @return array|null
307
+     */
308
+    public function getAddressBooksByUri($principal, $addressBookUri) {
309
+        $query = $this->db->getQueryBuilder();
310
+        $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
311
+            ->from('addressbooks')
312
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
313
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
314
+            ->setMaxResults(1)
315
+            ->execute();
316
+
317
+        $row = $result->fetch();
318
+        $result->closeCursor();
319
+        if ($row === false) {
320
+            return null;
321
+        }
322
+
323
+        $addressBook = [
324
+            'id'  => $row['id'],
325
+            'uri' => $row['uri'],
326
+            'principaluri' => $row['principaluri'],
327
+            '{DAV:}displayname' => $row['displayname'],
328
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
329
+            '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
330
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
331
+        ];
332
+
333
+        $this->addOwnerPrincipal($addressBook);
334
+
335
+        return $addressBook;
336
+    }
337
+
338
+    /**
339
+     * Updates properties for an address book.
340
+     *
341
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
342
+     * To do the actual updates, you must tell this object which properties
343
+     * you're going to process with the handle() method.
344
+     *
345
+     * Calling the handle method is like telling the PropPatch object "I
346
+     * promise I can handle updating this property".
347
+     *
348
+     * Read the PropPatch documentation for more info and examples.
349
+     *
350
+     * @param string $addressBookId
351
+     * @param \Sabre\DAV\PropPatch $propPatch
352
+     * @return void
353
+     */
354
+    function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
355
+        $supportedProperties = [
356
+            '{DAV:}displayname',
357
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description',
358
+        ];
359
+
360
+        /**
361
+         * @suppress SqlInjectionChecker
362
+         */
363
+        $propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
364
+
365
+            $updates = [];
366
+            foreach($mutations as $property=>$newValue) {
367
+
368
+                switch($property) {
369
+                    case '{DAV:}displayname' :
370
+                        $updates['displayname'] = $newValue;
371
+                        break;
372
+                    case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
373
+                        $updates['description'] = $newValue;
374
+                        break;
375
+                }
376
+            }
377
+            $query = $this->db->getQueryBuilder();
378
+            $query->update('addressbooks');
379
+
380
+            foreach($updates as $key=>$value) {
381
+                $query->set($key, $query->createNamedParameter($value));
382
+            }
383
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
384
+            ->execute();
385
+
386
+            $this->addChange($addressBookId, "", 2);
387
+
388
+            return true;
389
+
390
+        });
391
+    }
392
+
393
+    /**
394
+     * Creates a new address book
395
+     *
396
+     * @param string $principalUri
397
+     * @param string $url Just the 'basename' of the url.
398
+     * @param array $properties
399
+     * @return int
400
+     * @throws BadRequest
401
+     */
402
+    function createAddressBook($principalUri, $url, array $properties) {
403
+        $values = [
404
+            'displayname' => null,
405
+            'description' => null,
406
+            'principaluri' => $principalUri,
407
+            'uri' => $url,
408
+            'synctoken' => 1
409
+        ];
410
+
411
+        foreach($properties as $property=>$newValue) {
412
+
413
+            switch($property) {
414
+                case '{DAV:}displayname' :
415
+                    $values['displayname'] = $newValue;
416
+                    break;
417
+                case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
418
+                    $values['description'] = $newValue;
419
+                    break;
420
+                default :
421
+                    throw new BadRequest('Unknown property: ' . $property);
422
+            }
423
+
424
+        }
425
+
426
+        // Fallback to make sure the displayname is set. Some clients may refuse
427
+        // to work with addressbooks not having a displayname.
428
+        if(is_null($values['displayname'])) {
429
+            $values['displayname'] = $url;
430
+        }
431
+
432
+        $query = $this->db->getQueryBuilder();
433
+        $query->insert('addressbooks')
434
+            ->values([
435
+                'uri' => $query->createParameter('uri'),
436
+                'displayname' => $query->createParameter('displayname'),
437
+                'description' => $query->createParameter('description'),
438
+                'principaluri' => $query->createParameter('principaluri'),
439
+                'synctoken' => $query->createParameter('synctoken'),
440
+            ])
441
+            ->setParameters($values)
442
+            ->execute();
443
+
444
+        return $query->getLastInsertId();
445
+    }
446
+
447
+    /**
448
+     * Deletes an entire addressbook and all its contents
449
+     *
450
+     * @param mixed $addressBookId
451
+     * @return void
452
+     */
453
+    function deleteAddressBook($addressBookId) {
454
+        $query = $this->db->getQueryBuilder();
455
+        $query->delete('cards')
456
+            ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
457
+            ->setParameter('addressbookid', $addressBookId)
458
+            ->execute();
459
+
460
+        $query->delete('addressbookchanges')
461
+            ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
462
+            ->setParameter('addressbookid', $addressBookId)
463
+            ->execute();
464
+
465
+        $query->delete('addressbooks')
466
+            ->where($query->expr()->eq('id', $query->createParameter('id')))
467
+            ->setParameter('id', $addressBookId)
468
+            ->execute();
469
+
470
+        $this->sharingBackend->deleteAllShares($addressBookId);
471
+
472
+        $query->delete($this->dbCardsPropertiesTable)
473
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
474
+            ->execute();
475
+
476
+    }
477
+
478
+    /**
479
+     * Returns all cards for a specific addressbook id.
480
+     *
481
+     * This method should return the following properties for each card:
482
+     *   * carddata - raw vcard data
483
+     *   * uri - Some unique url
484
+     *   * lastmodified - A unix timestamp
485
+     *
486
+     * It's recommended to also return the following properties:
487
+     *   * etag - A unique etag. This must change every time the card changes.
488
+     *   * size - The size of the card in bytes.
489
+     *
490
+     * If these last two properties are provided, less time will be spent
491
+     * calculating them. If they are specified, you can also ommit carddata.
492
+     * This may speed up certain requests, especially with large cards.
493
+     *
494
+     * @param mixed $addressBookId
495
+     * @return array
496
+     */
497
+    function getCards($addressBookId) {
498
+        $query = $this->db->getQueryBuilder();
499
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
500
+            ->from('cards')
501
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
502
+
503
+        $cards = [];
504
+
505
+        $result = $query->execute();
506
+        while($row = $result->fetch()) {
507
+            $row['etag'] = '"' . $row['etag'] . '"';
508
+            $row['carddata'] = $this->readBlob($row['carddata']);
509
+            $cards[] = $row;
510
+        }
511
+        $result->closeCursor();
512
+
513
+        return $cards;
514
+    }
515
+
516
+    /**
517
+     * Returns a specific card.
518
+     *
519
+     * The same set of properties must be returned as with getCards. The only
520
+     * exception is that 'carddata' is absolutely required.
521
+     *
522
+     * If the card does not exist, you must return false.
523
+     *
524
+     * @param mixed $addressBookId
525
+     * @param string $cardUri
526
+     * @return array
527
+     */
528
+    function getCard($addressBookId, $cardUri) {
529
+        $query = $this->db->getQueryBuilder();
530
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
531
+            ->from('cards')
532
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
533
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
534
+            ->setMaxResults(1);
535
+
536
+        $result = $query->execute();
537
+        $row = $result->fetch();
538
+        if (!$row) {
539
+            return false;
540
+        }
541
+        $row['etag'] = '"' . $row['etag'] . '"';
542
+        $row['carddata'] = $this->readBlob($row['carddata']);
543
+
544
+        return $row;
545
+    }
546
+
547
+    /**
548
+     * Returns a list of cards.
549
+     *
550
+     * This method should work identical to getCard, but instead return all the
551
+     * cards in the list as an array.
552
+     *
553
+     * If the backend supports this, it may allow for some speed-ups.
554
+     *
555
+     * @param mixed $addressBookId
556
+     * @param string[] $uris
557
+     * @return array
558
+     */
559
+    function getMultipleCards($addressBookId, array $uris) {
560
+        if (empty($uris)) {
561
+            return [];
562
+        }
563
+
564
+        $chunks = array_chunk($uris, 100);
565
+        $cards = [];
566
+
567
+        $query = $this->db->getQueryBuilder();
568
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
569
+            ->from('cards')
570
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
571
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
572
+
573
+        foreach ($chunks as $uris) {
574
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
575
+            $result = $query->execute();
576
+
577
+            while ($row = $result->fetch()) {
578
+                $row['etag'] = '"' . $row['etag'] . '"';
579
+                $row['carddata'] = $this->readBlob($row['carddata']);
580
+                $cards[] = $row;
581
+            }
582
+            $result->closeCursor();
583
+        }
584
+        return $cards;
585
+    }
586
+
587
+    /**
588
+     * Creates a new card.
589
+     *
590
+     * The addressbook id will be passed as the first argument. This is the
591
+     * same id as it is returned from the getAddressBooksForUser method.
592
+     *
593
+     * The cardUri is a base uri, and doesn't include the full path. The
594
+     * cardData argument is the vcard body, and is passed as a string.
595
+     *
596
+     * It is possible to return an ETag from this method. This ETag is for the
597
+     * newly created resource, and must be enclosed with double quotes (that
598
+     * is, the string itself must contain the double quotes).
599
+     *
600
+     * You should only return the ETag if you store the carddata as-is. If a
601
+     * subsequent GET request on the same card does not have the same body,
602
+     * byte-by-byte and you did return an ETag here, clients tend to get
603
+     * confused.
604
+     *
605
+     * If you don't return an ETag, you can just return null.
606
+     *
607
+     * @param mixed $addressBookId
608
+     * @param string $cardUri
609
+     * @param string $cardData
610
+     * @return string
611
+     */
612
+    function createCard($addressBookId, $cardUri, $cardData) {
613
+        $etag = md5($cardData);
614
+        $uid = $this->getUID($cardData);
615
+
616
+        $q = $this->db->getQueryBuilder();
617
+        $q->select('uid')
618
+            ->from('cards')
619
+            ->where($q->expr()->eq('addressbookid', $q->createNamedParameter($addressBookId)))
620
+            ->andWhere($q->expr()->eq('uid', $q->createNamedParameter($uid)))
621
+            ->setMaxResults(1);
622
+        $result = $q->execute();
623
+        $count = (bool) $result->fetchColumn();
624
+        $result->closeCursor();
625
+        if ($count) {
626
+            throw new \Sabre\DAV\Exception\BadRequest('VCard object with uid already exists in this addressbook collection.');
627
+        }
628
+
629
+        $query = $this->db->getQueryBuilder();
630
+        $query->insert('cards')
631
+            ->values([
632
+                'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
633
+                'uri' => $query->createNamedParameter($cardUri),
634
+                'lastmodified' => $query->createNamedParameter(time()),
635
+                'addressbookid' => $query->createNamedParameter($addressBookId),
636
+                'size' => $query->createNamedParameter(strlen($cardData)),
637
+                'etag' => $query->createNamedParameter($etag),
638
+                'uid' => $query->createNamedParameter($uid),
639
+            ])
640
+            ->execute();
641
+
642
+        $this->addChange($addressBookId, $cardUri, 1);
643
+        $this->updateProperties($addressBookId, $cardUri, $cardData);
644
+
645
+        $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
646
+            new GenericEvent(null, [
647
+                'addressBookId' => $addressBookId,
648
+                'cardUri' => $cardUri,
649
+                'cardData' => $cardData]));
650
+
651
+        return '"' . $etag . '"';
652
+    }
653
+
654
+    /**
655
+     * Updates a card.
656
+     *
657
+     * The addressbook id will be passed as the first argument. This is the
658
+     * same id as it is returned from the getAddressBooksForUser method.
659
+     *
660
+     * The cardUri is a base uri, and doesn't include the full path. The
661
+     * cardData argument is the vcard body, and is passed as a string.
662
+     *
663
+     * It is possible to return an ETag from this method. This ETag should
664
+     * match that of the updated resource, and must be enclosed with double
665
+     * quotes (that is: the string itself must contain the actual quotes).
666
+     *
667
+     * You should only return the ETag if you store the carddata as-is. If a
668
+     * subsequent GET request on the same card does not have the same body,
669
+     * byte-by-byte and you did return an ETag here, clients tend to get
670
+     * confused.
671
+     *
672
+     * If you don't return an ETag, you can just return null.
673
+     *
674
+     * @param mixed $addressBookId
675
+     * @param string $cardUri
676
+     * @param string $cardData
677
+     * @return string
678
+     */
679
+    function updateCard($addressBookId, $cardUri, $cardData) {
680
+
681
+        $uid = $this->getUID($cardData);
682
+        $etag = md5($cardData);
683
+        $query = $this->db->getQueryBuilder();
684
+        $query->update('cards')
685
+            ->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
686
+            ->set('lastmodified', $query->createNamedParameter(time()))
687
+            ->set('size', $query->createNamedParameter(strlen($cardData)))
688
+            ->set('etag', $query->createNamedParameter($etag))
689
+            ->set('uid', $query->createNamedParameter($uid))
690
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
691
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
692
+            ->execute();
693
+
694
+        $this->addChange($addressBookId, $cardUri, 2);
695
+        $this->updateProperties($addressBookId, $cardUri, $cardData);
696
+
697
+        $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
698
+            new GenericEvent(null, [
699
+                'addressBookId' => $addressBookId,
700
+                'cardUri' => $cardUri,
701
+                'cardData' => $cardData]));
702
+
703
+        return '"' . $etag . '"';
704
+    }
705
+
706
+    /**
707
+     * Deletes a card
708
+     *
709
+     * @param mixed $addressBookId
710
+     * @param string $cardUri
711
+     * @return bool
712
+     */
713
+    function deleteCard($addressBookId, $cardUri) {
714
+        try {
715
+            $cardId = $this->getCardId($addressBookId, $cardUri);
716
+        } catch (\InvalidArgumentException $e) {
717
+            $cardId = null;
718
+        }
719
+        $query = $this->db->getQueryBuilder();
720
+        $ret = $query->delete('cards')
721
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
722
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
723
+            ->execute();
724
+
725
+        $this->addChange($addressBookId, $cardUri, 3);
726
+
727
+        $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
728
+            new GenericEvent(null, [
729
+                'addressBookId' => $addressBookId,
730
+                'cardUri' => $cardUri]));
731
+
732
+        if ($ret === 1) {
733
+            if ($cardId !== null) {
734
+                $this->purgeProperties($addressBookId, $cardId);
735
+            }
736
+            return true;
737
+        }
738
+
739
+        return false;
740
+    }
741
+
742
+    /**
743
+     * The getChanges method returns all the changes that have happened, since
744
+     * the specified syncToken in the specified address book.
745
+     *
746
+     * This function should return an array, such as the following:
747
+     *
748
+     * [
749
+     *   'syncToken' => 'The current synctoken',
750
+     *   'added'   => [
751
+     *      'new.txt',
752
+     *   ],
753
+     *   'modified'   => [
754
+     *      'modified.txt',
755
+     *   ],
756
+     *   'deleted' => [
757
+     *      'foo.php.bak',
758
+     *      'old.txt'
759
+     *   ]
760
+     * ];
761
+     *
762
+     * The returned syncToken property should reflect the *current* syncToken
763
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
764
+     * property. This is needed here too, to ensure the operation is atomic.
765
+     *
766
+     * If the $syncToken argument is specified as null, this is an initial
767
+     * sync, and all members should be reported.
768
+     *
769
+     * The modified property is an array of nodenames that have changed since
770
+     * the last token.
771
+     *
772
+     * The deleted property is an array with nodenames, that have been deleted
773
+     * from collection.
774
+     *
775
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
776
+     * 1, you only have to report changes that happened only directly in
777
+     * immediate descendants. If it's 2, it should also include changes from
778
+     * the nodes below the child collections. (grandchildren)
779
+     *
780
+     * The $limit argument allows a client to specify how many results should
781
+     * be returned at most. If the limit is not specified, it should be treated
782
+     * as infinite.
783
+     *
784
+     * If the limit (infinite or not) is higher than you're willing to return,
785
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
786
+     *
787
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
788
+     * return null.
789
+     *
790
+     * The limit is 'suggestive'. You are free to ignore it.
791
+     *
792
+     * @param string $addressBookId
793
+     * @param string $syncToken
794
+     * @param int $syncLevel
795
+     * @param int $limit
796
+     * @return array
797
+     */
798
+    function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
799
+        // Current synctoken
800
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
801
+        $stmt->execute([ $addressBookId ]);
802
+        $currentToken = $stmt->fetchColumn(0);
803
+
804
+        if (is_null($currentToken)) return null;
805
+
806
+        $result = [
807
+            'syncToken' => $currentToken,
808
+            'added'     => [],
809
+            'modified'  => [],
810
+            'deleted'   => [],
811
+        ];
812
+
813
+        if ($syncToken) {
814
+
815
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
816
+            if ($limit>0) {
817
+                $query .= " `LIMIT` " . (int)$limit;
818
+            }
819
+
820
+            // Fetching all changes
821
+            $stmt = $this->db->prepare($query);
822
+            $stmt->execute([$syncToken, $currentToken, $addressBookId]);
823
+
824
+            $changes = [];
825
+
826
+            // This loop ensures that any duplicates are overwritten, only the
827
+            // last change on a node is relevant.
828
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
829
+
830
+                $changes[$row['uri']] = $row['operation'];
831
+
832
+            }
833
+
834
+            foreach($changes as $uri => $operation) {
835
+
836
+                switch($operation) {
837
+                    case 1:
838
+                        $result['added'][] = $uri;
839
+                        break;
840
+                    case 2:
841
+                        $result['modified'][] = $uri;
842
+                        break;
843
+                    case 3:
844
+                        $result['deleted'][] = $uri;
845
+                        break;
846
+                }
847
+
848
+            }
849
+        } else {
850
+            // No synctoken supplied, this is the initial sync.
851
+            $query = "SELECT `uri` FROM `*PREFIX*cards` WHERE `addressbookid` = ?";
852
+            $stmt = $this->db->prepare($query);
853
+            $stmt->execute([$addressBookId]);
854
+
855
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
856
+        }
857
+        return $result;
858
+    }
859
+
860
+    /**
861
+     * Adds a change record to the addressbookchanges table.
862
+     *
863
+     * @param mixed $addressBookId
864
+     * @param string $objectUri
865
+     * @param int $operation 1 = add, 2 = modify, 3 = delete
866
+     * @return void
867
+     */
868
+    protected function addChange($addressBookId, $objectUri, $operation) {
869
+        $sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?';
870
+        $stmt = $this->db->prepare($sql);
871
+        $stmt->execute([
872
+            $objectUri,
873
+            $addressBookId,
874
+            $operation,
875
+            $addressBookId
876
+        ]);
877
+        $stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
878
+        $stmt->execute([
879
+            $addressBookId
880
+        ]);
881
+    }
882
+
883
+    private function readBlob($cardData) {
884
+        if (is_resource($cardData)) {
885
+            return stream_get_contents($cardData);
886
+        }
887
+
888
+        return $cardData;
889
+    }
890
+
891
+    /**
892
+     * @param IShareable $shareable
893
+     * @param string[] $add
894
+     * @param string[] $remove
895
+     */
896
+    public function updateShares(IShareable $shareable, $add, $remove) {
897
+        $this->sharingBackend->updateShares($shareable, $add, $remove);
898
+    }
899
+
900
+    /**
901
+     * search contact
902
+     *
903
+     * @param int $addressBookId
904
+     * @param string $pattern which should match within the $searchProperties
905
+     * @param array $searchProperties defines the properties within the query pattern should match
906
+     * @return array an array of contacts which are arrays of key-value-pairs
907
+     */
908
+    public function search($addressBookId, $pattern, $searchProperties) {
909
+        $query = $this->db->getQueryBuilder();
910
+        $query2 = $this->db->getQueryBuilder();
911
+
912
+        $query2->selectDistinct('cp.cardid')->from($this->dbCardsPropertiesTable, 'cp');
913
+        $query2->andWhere($query2->expr()->eq('cp.addressbookid', $query->createNamedParameter($addressBookId)));
914
+        $or = $query2->expr()->orX();
915
+        foreach ($searchProperties as $property) {
916
+            $or->add($query2->expr()->eq('cp.name', $query->createNamedParameter($property)));
917
+        }
918
+        $query2->andWhere($or);
919
+
920
+        // No need for like when the pattern is empty
921
+        if ('' !== $pattern) {
922
+            $query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
923
+        }
924
+
925
+        $query->select('c.carddata', 'c.uri')->from($this->dbCardsTable, 'c')
926
+            ->where($query->expr()->in('c.id', $query->createFunction($query2->getSQL())));
927
+
928
+        $result = $query->execute();
929
+        $cards = $result->fetchAll();
930
+
931
+        $result->closeCursor();
932
+
933
+        return array_map(function($array) {
934
+            $array['carddata'] = $this->readBlob($array['carddata']);
935
+            return $array;
936
+        }, $cards);
937
+    }
938
+
939
+    /**
940
+     * @param int $bookId
941
+     * @param string $name
942
+     * @return array
943
+     */
944
+    public function collectCardProperties($bookId, $name) {
945
+        $query = $this->db->getQueryBuilder();
946
+        $result = $query->selectDistinct('value')
947
+            ->from($this->dbCardsPropertiesTable)
948
+            ->where($query->expr()->eq('name', $query->createNamedParameter($name)))
949
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
950
+            ->execute();
951
+
952
+        $all = $result->fetchAll(PDO::FETCH_COLUMN);
953
+        $result->closeCursor();
954
+
955
+        return $all;
956
+    }
957
+
958
+    /**
959
+     * get URI from a given contact
960
+     *
961
+     * @param int $id
962
+     * @return string
963
+     */
964
+    public function getCardUri($id) {
965
+        $query = $this->db->getQueryBuilder();
966
+        $query->select('uri')->from($this->dbCardsTable)
967
+                ->where($query->expr()->eq('id', $query->createParameter('id')))
968
+                ->setParameter('id', $id);
969
+
970
+        $result = $query->execute();
971
+        $uri = $result->fetch();
972
+        $result->closeCursor();
973
+
974
+        if (!isset($uri['uri'])) {
975
+            throw new \InvalidArgumentException('Card does not exists: ' . $id);
976
+        }
977
+
978
+        return $uri['uri'];
979
+    }
980
+
981
+    /**
982
+     * return contact with the given URI
983
+     *
984
+     * @param int $addressBookId
985
+     * @param string $uri
986
+     * @returns array
987
+     */
988
+    public function getContact($addressBookId, $uri) {
989
+        $result = [];
990
+        $query = $this->db->getQueryBuilder();
991
+        $query->select('*')->from($this->dbCardsTable)
992
+                ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
993
+                ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
994
+        $queryResult = $query->execute();
995
+        $contact = $queryResult->fetch();
996
+        $queryResult->closeCursor();
997
+
998
+        if (is_array($contact)) {
999
+            $result = $contact;
1000
+        }
1001
+
1002
+        return $result;
1003
+    }
1004
+
1005
+    /**
1006
+     * Returns the list of people whom this address book is shared with.
1007
+     *
1008
+     * Every element in this array should have the following properties:
1009
+     *   * href - Often a mailto: address
1010
+     *   * commonName - Optional, for example a first + last name
1011
+     *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
1012
+     *   * readOnly - boolean
1013
+     *   * summary - Optional, a description for the share
1014
+     *
1015
+     * @return array
1016
+     */
1017
+    public function getShares($addressBookId) {
1018
+        return $this->sharingBackend->getShares($addressBookId);
1019
+    }
1020
+
1021
+    /**
1022
+     * update properties table
1023
+     *
1024
+     * @param int $addressBookId
1025
+     * @param string $cardUri
1026
+     * @param string $vCardSerialized
1027
+     */
1028
+    protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
1029
+        $cardId = $this->getCardId($addressBookId, $cardUri);
1030
+        $vCard = $this->readCard($vCardSerialized);
1031
+
1032
+        $this->purgeProperties($addressBookId, $cardId);
1033
+
1034
+        $query = $this->db->getQueryBuilder();
1035
+        $query->insert($this->dbCardsPropertiesTable)
1036
+            ->values(
1037
+                [
1038
+                    'addressbookid' => $query->createNamedParameter($addressBookId),
1039
+                    'cardid' => $query->createNamedParameter($cardId),
1040
+                    'name' => $query->createParameter('name'),
1041
+                    'value' => $query->createParameter('value'),
1042
+                    'preferred' => $query->createParameter('preferred')
1043
+                ]
1044
+            );
1045
+
1046
+        foreach ($vCard->children() as $property) {
1047
+            if(!in_array($property->name, self::$indexProperties)) {
1048
+                continue;
1049
+            }
1050
+            $preferred = 0;
1051
+            foreach($property->parameters as $parameter) {
1052
+                if ($parameter->name === 'TYPE' && strtoupper($parameter->getValue()) === 'PREF') {
1053
+                    $preferred = 1;
1054
+                    break;
1055
+                }
1056
+            }
1057
+            $query->setParameter('name', $property->name);
1058
+            $query->setParameter('value', substr($property->getValue(), 0, 254));
1059
+            $query->setParameter('preferred', $preferred);
1060
+            $query->execute();
1061
+        }
1062
+    }
1063
+
1064
+    /**
1065
+     * read vCard data into a vCard object
1066
+     *
1067
+     * @param string $cardData
1068
+     * @return VCard
1069
+     */
1070
+    protected function readCard($cardData) {
1071
+        return  Reader::read($cardData);
1072
+    }
1073
+
1074
+    /**
1075
+     * delete all properties from a given card
1076
+     *
1077
+     * @param int $addressBookId
1078
+     * @param int $cardId
1079
+     */
1080
+    protected function purgeProperties($addressBookId, $cardId) {
1081
+        $query = $this->db->getQueryBuilder();
1082
+        $query->delete($this->dbCardsPropertiesTable)
1083
+            ->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
1084
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1085
+        $query->execute();
1086
+    }
1087
+
1088
+    /**
1089
+     * get ID from a given contact
1090
+     *
1091
+     * @param int $addressBookId
1092
+     * @param string $uri
1093
+     * @return int
1094
+     */
1095
+    protected function getCardId($addressBookId, $uri) {
1096
+        $query = $this->db->getQueryBuilder();
1097
+        $query->select('id')->from($this->dbCardsTable)
1098
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1099
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1100
+
1101
+        $result = $query->execute();
1102
+        $cardIds = $result->fetch();
1103
+        $result->closeCursor();
1104
+
1105
+        if (!isset($cardIds['id'])) {
1106
+            throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1107
+        }
1108
+
1109
+        return (int)$cardIds['id'];
1110
+    }
1111
+
1112
+    /**
1113
+     * For shared address books the sharee is set in the ACL of the address book
1114
+     * @param $addressBookId
1115
+     * @param $acl
1116
+     * @return array
1117
+     */
1118
+    public function applyShareAcl($addressBookId, $acl) {
1119
+        return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1120
+    }
1121
+
1122
+    private function convertPrincipal($principalUri, $toV2) {
1123
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1124
+            list(, $name) = \Sabre\Uri\split($principalUri);
1125
+            if ($toV2 === true) {
1126
+                return "principals/users/$name";
1127
+            }
1128
+            return "principals/$name";
1129
+        }
1130
+        return $principalUri;
1131
+    }
1132
+
1133
+    private function addOwnerPrincipal(&$addressbookInfo) {
1134
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
1135
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
1136
+        if (isset($addressbookInfo[$ownerPrincipalKey])) {
1137
+            $uri = $addressbookInfo[$ownerPrincipalKey];
1138
+        } else {
1139
+            $uri = $addressbookInfo['principaluri'];
1140
+        }
1141
+
1142
+        $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
1143
+        if (isset($principalInformation['{DAV:}displayname'])) {
1144
+            $addressbookInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
1145
+        }
1146
+    }
1147
+
1148
+    /**
1149
+     * Extract UID from vcard
1150
+     *
1151
+     * @param string $cardData the vcard raw data
1152
+     * @return string the uid
1153
+     * @throws BadRequest if no UID is available
1154
+     */
1155
+    private function getUID($cardData) {
1156
+        if ($cardData != '') {
1157
+            $vCard = Reader::read($cardData);
1158
+            if ($vCard->UID) {
1159
+                $uid = $vCard->UID->getValue();
1160
+                return $uid;
1161
+            }
1162
+            // should already be handled, but just in case
1163
+            throw new BadRequest('vCards on CardDAV servers MUST have a UID property');
1164
+        }
1165
+        // should already be handled, but just in case
1166
+        throw new BadRequest('vCard can not be empty');
1167
+    }
1168 1168
 }
Please login to merge, or discard this patch.
apps/dav/lib/DAV/Sharing/Backend.php 1 patch
Indentation   +210 added lines, -210 removed lines patch added patch discarded remove patch
@@ -32,214 +32,214 @@
 block discarded – undo
32 32
 
33 33
 class Backend {
34 34
 
35
-	/** @var IDBConnection */
36
-	private $db;
37
-	/** @var IUserManager */
38
-	private $userManager;
39
-	/** @var IGroupManager */
40
-	private $groupManager;
41
-	/** @var Principal */
42
-	private $principalBackend;
43
-	/** @var string */
44
-	private $resourceType;
45
-
46
-	const ACCESS_OWNER = 1;
47
-	const ACCESS_READ_WRITE = 2;
48
-	const ACCESS_READ = 3;
49
-
50
-	/**
51
-	 * @param IDBConnection $db
52
-	 * @param IUserManager $userManager
53
-	 * @param IGroupManager $groupManager
54
-	 * @param Principal $principalBackend
55
-	 * @param string $resourceType
56
-	 */
57
-	public function __construct(IDBConnection $db, IUserManager $userManager, IGroupManager $groupManager, Principal $principalBackend, $resourceType) {
58
-		$this->db = $db;
59
-		$this->userManager = $userManager;
60
-		$this->groupManager = $groupManager;
61
-		$this->principalBackend = $principalBackend;
62
-		$this->resourceType = $resourceType;
63
-	}
64
-
65
-	/**
66
-	 * @param IShareable $shareable
67
-	 * @param string[] $add
68
-	 * @param string[] $remove
69
-	 */
70
-	public function updateShares(IShareable $shareable, array $add, array $remove) {
71
-		foreach($add as $element) {
72
-			$principal = $this->principalBackend->findByUri($element['href'], '');
73
-			if ($principal !== '') {
74
-				$this->shareWith($shareable, $element);
75
-			}
76
-		}
77
-		foreach($remove as $element) {
78
-			$principal = $this->principalBackend->findByUri($element, '');
79
-			if ($principal !== '') {
80
-				$this->unshare($shareable, $element);
81
-			}
82
-		}
83
-	}
84
-
85
-	/**
86
-	 * @param IShareable $shareable
87
-	 * @param string $element
88
-	 */
89
-	private function shareWith($shareable, $element) {
90
-		$user = $element['href'];
91
-		$parts = explode(':', $user, 2);
92
-		if ($parts[0] !== 'principal') {
93
-			return;
94
-		}
95
-
96
-		// don't share with owner
97
-		if ($shareable->getOwner() === $parts[1]) {
98
-			return;
99
-		}
100
-
101
-		$principal = explode('/', $parts[1], 3);
102
-		if (count($principal) !== 3 || $principal[0] !== 'principals' || !in_array($principal[1], ['users', 'groups', 'circles'], true)) {
103
-			// Invalid principal
104
-			return;
105
-		}
106
-
107
-		if (($principal[1] === 'users' && !$this->userManager->userExists($principal[2])) ||
108
-			($principal[1] === 'groups' && !$this->groupManager->groupExists($principal[2]))) {
109
-			// User or group does not exist
110
-			return;
111
-		}
112
-
113
-		// remove the share if it already exists
114
-		$this->unshare($shareable, $element['href']);
115
-		$access = self::ACCESS_READ;
116
-		if (isset($element['readOnly'])) {
117
-			$access = $element['readOnly'] ? self::ACCESS_READ : self::ACCESS_READ_WRITE;
118
-		}
119
-
120
-		$query = $this->db->getQueryBuilder();
121
-		$query->insert('dav_shares')
122
-			->values([
123
-				'principaluri' => $query->createNamedParameter($parts[1]),
124
-				'type' => $query->createNamedParameter($this->resourceType),
125
-				'access' => $query->createNamedParameter($access),
126
-				'resourceid' => $query->createNamedParameter($shareable->getResourceId())
127
-			]);
128
-		$query->execute();
129
-	}
130
-
131
-	/**
132
-	 * @param $resourceId
133
-	 */
134
-	public function deleteAllShares($resourceId) {
135
-		$query = $this->db->getQueryBuilder();
136
-		$query->delete('dav_shares')
137
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($resourceId)))
138
-			->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
139
-			->execute();
140
-	}
141
-
142
-	public function deleteAllSharesByUser($principaluri) {
143
-		$query = $this->db->getQueryBuilder();
144
-		$query->delete('dav_shares')
145
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principaluri)))
146
-			->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
147
-			->execute();
148
-	}
149
-
150
-	/**
151
-	 * @param IShareable $shareable
152
-	 * @param string $element
153
-	 */
154
-	private function unshare($shareable, $element) {
155
-		$parts = explode(':', $element, 2);
156
-		if ($parts[0] !== 'principal') {
157
-			return;
158
-		}
159
-
160
-		// don't share with owner
161
-		if ($shareable->getOwner() === $parts[1]) {
162
-			return;
163
-		}
164
-
165
-		$query = $this->db->getQueryBuilder();
166
-		$query->delete('dav_shares')
167
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($shareable->getResourceId())))
168
-			->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
169
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($parts[1])))
170
-		;
171
-		$query->execute();
172
-	}
173
-
174
-	/**
175
-	 * Returns the list of people whom this resource is shared with.
176
-	 *
177
-	 * Every element in this array should have the following properties:
178
-	 *   * href - Often a mailto: address
179
-	 *   * commonName - Optional, for example a first + last name
180
-	 *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
181
-	 *   * readOnly - boolean
182
-	 *   * summary - Optional, a description for the share
183
-	 *
184
-	 * @param int $resourceId
185
-	 * @return array
186
-	 */
187
-	public function getShares($resourceId) {
188
-		$query = $this->db->getQueryBuilder();
189
-		$result = $query->select(['principaluri', 'access'])
190
-			->from('dav_shares')
191
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($resourceId)))
192
-			->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
193
-			->execute();
194
-
195
-		$shares = [];
196
-		while($row = $result->fetch()) {
197
-			$p = $this->principalBackend->getPrincipalByPath($row['principaluri']);
198
-			$shares[]= [
199
-				'href' => "principal:${row['principaluri']}",
200
-				'commonName' => isset($p['{DAV:}displayname']) ? $p['{DAV:}displayname'] : '',
201
-				'status' => 1,
202
-				'readOnly' => (int) $row['access'] === self::ACCESS_READ,
203
-				'{http://owncloud.org/ns}principal' => $row['principaluri'],
204
-				'{http://owncloud.org/ns}group-share' => is_null($p)
205
-			];
206
-		}
207
-
208
-		return $shares;
209
-	}
210
-
211
-	/**
212
-	 * For shared resources the sharee is set in the ACL of the resource
213
-	 *
214
-	 * @param int $resourceId
215
-	 * @param array $acl
216
-	 * @return array
217
-	 */
218
-	public function applyShareAcl($resourceId, $acl) {
219
-
220
-		$shares = $this->getShares($resourceId);
221
-		foreach ($shares as $share) {
222
-			$acl[] = [
223
-				'privilege' => '{DAV:}read',
224
-				'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
225
-				'protected' => true,
226
-			];
227
-			if (!$share['readOnly']) {
228
-				$acl[] = [
229
-					'privilege' => '{DAV:}write',
230
-					'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
231
-					'protected' => true,
232
-				];
233
-			} else if ($this->resourceType === 'calendar') {
234
-				// Allow changing the properties of read only calendars,
235
-				// so users can change the visibility.
236
-				$acl[] = [
237
-					'privilege' => '{DAV:}write-properties',
238
-					'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
239
-					'protected' => true,
240
-				];
241
-			}
242
-		}
243
-		return $acl;
244
-	}
35
+    /** @var IDBConnection */
36
+    private $db;
37
+    /** @var IUserManager */
38
+    private $userManager;
39
+    /** @var IGroupManager */
40
+    private $groupManager;
41
+    /** @var Principal */
42
+    private $principalBackend;
43
+    /** @var string */
44
+    private $resourceType;
45
+
46
+    const ACCESS_OWNER = 1;
47
+    const ACCESS_READ_WRITE = 2;
48
+    const ACCESS_READ = 3;
49
+
50
+    /**
51
+     * @param IDBConnection $db
52
+     * @param IUserManager $userManager
53
+     * @param IGroupManager $groupManager
54
+     * @param Principal $principalBackend
55
+     * @param string $resourceType
56
+     */
57
+    public function __construct(IDBConnection $db, IUserManager $userManager, IGroupManager $groupManager, Principal $principalBackend, $resourceType) {
58
+        $this->db = $db;
59
+        $this->userManager = $userManager;
60
+        $this->groupManager = $groupManager;
61
+        $this->principalBackend = $principalBackend;
62
+        $this->resourceType = $resourceType;
63
+    }
64
+
65
+    /**
66
+     * @param IShareable $shareable
67
+     * @param string[] $add
68
+     * @param string[] $remove
69
+     */
70
+    public function updateShares(IShareable $shareable, array $add, array $remove) {
71
+        foreach($add as $element) {
72
+            $principal = $this->principalBackend->findByUri($element['href'], '');
73
+            if ($principal !== '') {
74
+                $this->shareWith($shareable, $element);
75
+            }
76
+        }
77
+        foreach($remove as $element) {
78
+            $principal = $this->principalBackend->findByUri($element, '');
79
+            if ($principal !== '') {
80
+                $this->unshare($shareable, $element);
81
+            }
82
+        }
83
+    }
84
+
85
+    /**
86
+     * @param IShareable $shareable
87
+     * @param string $element
88
+     */
89
+    private function shareWith($shareable, $element) {
90
+        $user = $element['href'];
91
+        $parts = explode(':', $user, 2);
92
+        if ($parts[0] !== 'principal') {
93
+            return;
94
+        }
95
+
96
+        // don't share with owner
97
+        if ($shareable->getOwner() === $parts[1]) {
98
+            return;
99
+        }
100
+
101
+        $principal = explode('/', $parts[1], 3);
102
+        if (count($principal) !== 3 || $principal[0] !== 'principals' || !in_array($principal[1], ['users', 'groups', 'circles'], true)) {
103
+            // Invalid principal
104
+            return;
105
+        }
106
+
107
+        if (($principal[1] === 'users' && !$this->userManager->userExists($principal[2])) ||
108
+            ($principal[1] === 'groups' && !$this->groupManager->groupExists($principal[2]))) {
109
+            // User or group does not exist
110
+            return;
111
+        }
112
+
113
+        // remove the share if it already exists
114
+        $this->unshare($shareable, $element['href']);
115
+        $access = self::ACCESS_READ;
116
+        if (isset($element['readOnly'])) {
117
+            $access = $element['readOnly'] ? self::ACCESS_READ : self::ACCESS_READ_WRITE;
118
+        }
119
+
120
+        $query = $this->db->getQueryBuilder();
121
+        $query->insert('dav_shares')
122
+            ->values([
123
+                'principaluri' => $query->createNamedParameter($parts[1]),
124
+                'type' => $query->createNamedParameter($this->resourceType),
125
+                'access' => $query->createNamedParameter($access),
126
+                'resourceid' => $query->createNamedParameter($shareable->getResourceId())
127
+            ]);
128
+        $query->execute();
129
+    }
130
+
131
+    /**
132
+     * @param $resourceId
133
+     */
134
+    public function deleteAllShares($resourceId) {
135
+        $query = $this->db->getQueryBuilder();
136
+        $query->delete('dav_shares')
137
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($resourceId)))
138
+            ->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
139
+            ->execute();
140
+    }
141
+
142
+    public function deleteAllSharesByUser($principaluri) {
143
+        $query = $this->db->getQueryBuilder();
144
+        $query->delete('dav_shares')
145
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principaluri)))
146
+            ->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
147
+            ->execute();
148
+    }
149
+
150
+    /**
151
+     * @param IShareable $shareable
152
+     * @param string $element
153
+     */
154
+    private function unshare($shareable, $element) {
155
+        $parts = explode(':', $element, 2);
156
+        if ($parts[0] !== 'principal') {
157
+            return;
158
+        }
159
+
160
+        // don't share with owner
161
+        if ($shareable->getOwner() === $parts[1]) {
162
+            return;
163
+        }
164
+
165
+        $query = $this->db->getQueryBuilder();
166
+        $query->delete('dav_shares')
167
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($shareable->getResourceId())))
168
+            ->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
169
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($parts[1])))
170
+        ;
171
+        $query->execute();
172
+    }
173
+
174
+    /**
175
+     * Returns the list of people whom this resource is shared with.
176
+     *
177
+     * Every element in this array should have the following properties:
178
+     *   * href - Often a mailto: address
179
+     *   * commonName - Optional, for example a first + last name
180
+     *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
181
+     *   * readOnly - boolean
182
+     *   * summary - Optional, a description for the share
183
+     *
184
+     * @param int $resourceId
185
+     * @return array
186
+     */
187
+    public function getShares($resourceId) {
188
+        $query = $this->db->getQueryBuilder();
189
+        $result = $query->select(['principaluri', 'access'])
190
+            ->from('dav_shares')
191
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($resourceId)))
192
+            ->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
193
+            ->execute();
194
+
195
+        $shares = [];
196
+        while($row = $result->fetch()) {
197
+            $p = $this->principalBackend->getPrincipalByPath($row['principaluri']);
198
+            $shares[]= [
199
+                'href' => "principal:${row['principaluri']}",
200
+                'commonName' => isset($p['{DAV:}displayname']) ? $p['{DAV:}displayname'] : '',
201
+                'status' => 1,
202
+                'readOnly' => (int) $row['access'] === self::ACCESS_READ,
203
+                '{http://owncloud.org/ns}principal' => $row['principaluri'],
204
+                '{http://owncloud.org/ns}group-share' => is_null($p)
205
+            ];
206
+        }
207
+
208
+        return $shares;
209
+    }
210
+
211
+    /**
212
+     * For shared resources the sharee is set in the ACL of the resource
213
+     *
214
+     * @param int $resourceId
215
+     * @param array $acl
216
+     * @return array
217
+     */
218
+    public function applyShareAcl($resourceId, $acl) {
219
+
220
+        $shares = $this->getShares($resourceId);
221
+        foreach ($shares as $share) {
222
+            $acl[] = [
223
+                'privilege' => '{DAV:}read',
224
+                'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
225
+                'protected' => true,
226
+            ];
227
+            if (!$share['readOnly']) {
228
+                $acl[] = [
229
+                    'privilege' => '{DAV:}write',
230
+                    'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
231
+                    'protected' => true,
232
+                ];
233
+            } else if ($this->resourceType === 'calendar') {
234
+                // Allow changing the properties of read only calendars,
235
+                // so users can change the visibility.
236
+                $acl[] = [
237
+                    'privilege' => '{DAV:}write-properties',
238
+                    'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
239
+                    'protected' => true,
240
+                ];
241
+            }
242
+        }
243
+        return $acl;
244
+    }
245 245
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/CalDavBackend.php 1 patch
Indentation   +2554 added lines, -2554 removed lines patch added patch discarded remove patch
@@ -75,2559 +75,2559 @@
 block discarded – undo
75 75
  */
76 76
 class CalDavBackend extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport {
77 77
 
78
-	const CALENDAR_TYPE_CALENDAR = 0;
79
-	const CALENDAR_TYPE_SUBSCRIPTION = 1;
80
-
81
-	const PERSONAL_CALENDAR_URI = 'personal';
82
-	const PERSONAL_CALENDAR_NAME = 'Personal';
83
-
84
-	const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
85
-	const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
86
-
87
-	/**
88
-	 * We need to specify a max date, because we need to stop *somewhere*
89
-	 *
90
-	 * On 32 bit system the maximum for a signed integer is 2147483647, so
91
-	 * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
92
-	 * in 2038-01-19 to avoid problems when the date is converted
93
-	 * to a unix timestamp.
94
-	 */
95
-	const MAX_DATE = '2038-01-01';
96
-
97
-	const ACCESS_PUBLIC = 4;
98
-	const CLASSIFICATION_PUBLIC = 0;
99
-	const CLASSIFICATION_PRIVATE = 1;
100
-	const CLASSIFICATION_CONFIDENTIAL = 2;
101
-
102
-	/**
103
-	 * List of CalDAV properties, and how they map to database field names
104
-	 * Add your own properties by simply adding on to this array.
105
-	 *
106
-	 * Note that only string-based properties are supported here.
107
-	 *
108
-	 * @var array
109
-	 */
110
-	public $propertyMap = [
111
-		'{DAV:}displayname'                          => 'displayname',
112
-		'{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
113
-		'{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
114
-		'{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
115
-		'{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
116
-	];
117
-
118
-	/**
119
-	 * List of subscription properties, and how they map to database field names.
120
-	 *
121
-	 * @var array
122
-	 */
123
-	public $subscriptionPropertyMap = [
124
-		'{DAV:}displayname'                                           => 'displayname',
125
-		'{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
126
-		'{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
127
-		'{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
128
-		'{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
129
-		'{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
130
-		'{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
131
-	];
132
-
133
-	/** @var array properties to index */
134
-	public static $indexProperties = ['CATEGORIES', 'COMMENT', 'DESCRIPTION',
135
-		'LOCATION', 'RESOURCES', 'STATUS', 'SUMMARY', 'ATTENDEE', 'CONTACT',
136
-		'ORGANIZER'];
137
-
138
-	/** @var array parameters to index */
139
-	public static $indexParameters = [
140
-		'ATTENDEE' => ['CN'],
141
-		'ORGANIZER' => ['CN'],
142
-	];
143
-
144
-	/**
145
-	 * @var string[] Map of uid => display name
146
-	 */
147
-	protected $userDisplayNames;
148
-
149
-	/** @var IDBConnection */
150
-	private $db;
151
-
152
-	/** @var Backend */
153
-	private $calendarSharingBackend;
154
-
155
-	/** @var Principal */
156
-	private $principalBackend;
157
-
158
-	/** @var IUserManager */
159
-	private $userManager;
160
-
161
-	/** @var ISecureRandom */
162
-	private $random;
163
-
164
-	/** @var ILogger */
165
-	private $logger;
166
-
167
-	/** @var EventDispatcherInterface */
168
-	private $dispatcher;
169
-
170
-	/** @var bool */
171
-	private $legacyEndpoint;
172
-
173
-	/** @var string */
174
-	private $dbObjectPropertiesTable = 'calendarobjects_props';
175
-
176
-	/**
177
-	 * CalDavBackend constructor.
178
-	 *
179
-	 * @param IDBConnection $db
180
-	 * @param Principal $principalBackend
181
-	 * @param IUserManager $userManager
182
-	 * @param IGroupManager $groupManager
183
-	 * @param ISecureRandom $random
184
-	 * @param ILogger $logger
185
-	 * @param EventDispatcherInterface $dispatcher
186
-	 * @param bool $legacyEndpoint
187
-	 */
188
-	public function __construct(IDBConnection $db,
189
-								Principal $principalBackend,
190
-								IUserManager $userManager,
191
-								IGroupManager $groupManager,
192
-								ISecureRandom $random,
193
-								ILogger $logger,
194
-								EventDispatcherInterface $dispatcher,
195
-								$legacyEndpoint = false) {
196
-		$this->db = $db;
197
-		$this->principalBackend = $principalBackend;
198
-		$this->userManager = $userManager;
199
-		$this->calendarSharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'calendar');
200
-		$this->random = $random;
201
-		$this->logger = $logger;
202
-		$this->dispatcher = $dispatcher;
203
-		$this->legacyEndpoint = $legacyEndpoint;
204
-	}
205
-
206
-	/**
207
-	 * Return the number of calendars for a principal
208
-	 *
209
-	 * By default this excludes the automatically generated birthday calendar
210
-	 *
211
-	 * @param $principalUri
212
-	 * @param bool $excludeBirthday
213
-	 * @return int
214
-	 */
215
-	public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
216
-		$principalUri = $this->convertPrincipal($principalUri, true);
217
-		$query = $this->db->getQueryBuilder();
218
-		$query->select($query->func()->count('*'))
219
-			->from('calendars')
220
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
221
-
222
-		if ($excludeBirthday) {
223
-			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
224
-		}
225
-
226
-		return (int)$query->execute()->fetchColumn();
227
-	}
228
-
229
-	/**
230
-	 * Returns a list of calendars for a principal.
231
-	 *
232
-	 * Every project is an array with the following keys:
233
-	 *  * id, a unique id that will be used by other functions to modify the
234
-	 *    calendar. This can be the same as the uri or a database key.
235
-	 *  * uri, which the basename of the uri with which the calendar is
236
-	 *    accessed.
237
-	 *  * principaluri. The owner of the calendar. Almost always the same as
238
-	 *    principalUri passed to this method.
239
-	 *
240
-	 * Furthermore it can contain webdav properties in clark notation. A very
241
-	 * common one is '{DAV:}displayname'.
242
-	 *
243
-	 * Many clients also require:
244
-	 * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
245
-	 * For this property, you can just return an instance of
246
-	 * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
247
-	 *
248
-	 * If you return {http://sabredav.org/ns}read-only and set the value to 1,
249
-	 * ACL will automatically be put in read-only mode.
250
-	 *
251
-	 * @param string $principalUri
252
-	 * @return array
253
-	 */
254
-	function getCalendarsForUser($principalUri) {
255
-		$principalUriOriginal = $principalUri;
256
-		$principalUri = $this->convertPrincipal($principalUri, true);
257
-		$fields = array_values($this->propertyMap);
258
-		$fields[] = 'id';
259
-		$fields[] = 'uri';
260
-		$fields[] = 'synctoken';
261
-		$fields[] = 'components';
262
-		$fields[] = 'principaluri';
263
-		$fields[] = 'transparent';
264
-
265
-		// Making fields a comma-delimited list
266
-		$query = $this->db->getQueryBuilder();
267
-		$query->select($fields)->from('calendars')
268
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
269
-				->orderBy('calendarorder', 'ASC');
270
-		$stmt = $query->execute();
271
-
272
-		$calendars = [];
273
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
274
-
275
-			$components = [];
276
-			if ($row['components']) {
277
-				$components = explode(',',$row['components']);
278
-			}
279
-
280
-			$calendar = [
281
-				'id' => $row['id'],
282
-				'uri' => $row['uri'],
283
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
284
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
285
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
286
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
287
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
288
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
289
-			];
290
-
291
-			foreach($this->propertyMap as $xmlName=>$dbName) {
292
-				$calendar[$xmlName] = $row[$dbName];
293
-			}
294
-
295
-			$this->addOwnerPrincipal($calendar);
296
-
297
-			if (!isset($calendars[$calendar['id']])) {
298
-				$calendars[$calendar['id']] = $calendar;
299
-			}
300
-		}
301
-
302
-		$stmt->closeCursor();
303
-
304
-		// query for shared calendars
305
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
306
-		$principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
307
-
308
-		$principals = array_map(function($principal) {
309
-			return urldecode($principal);
310
-		}, $principals);
311
-		$principals[]= $principalUri;
312
-
313
-		$fields = array_values($this->propertyMap);
314
-		$fields[] = 'a.id';
315
-		$fields[] = 'a.uri';
316
-		$fields[] = 'a.synctoken';
317
-		$fields[] = 'a.components';
318
-		$fields[] = 'a.principaluri';
319
-		$fields[] = 'a.transparent';
320
-		$fields[] = 's.access';
321
-		$query = $this->db->getQueryBuilder();
322
-		$result = $query->select($fields)
323
-			->from('dav_shares', 's')
324
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
325
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
326
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
327
-			->setParameter('type', 'calendar')
328
-			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
329
-			->execute();
330
-
331
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
332
-		while($row = $result->fetch()) {
333
-			if ($row['principaluri'] === $principalUri) {
334
-				continue;
335
-			}
336
-
337
-			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
338
-			if (isset($calendars[$row['id']])) {
339
-				if ($readOnly) {
340
-					// New share can not have more permissions then the old one.
341
-					continue;
342
-				}
343
-				if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
344
-					$calendars[$row['id']][$readOnlyPropertyName] === 0) {
345
-					// Old share is already read-write, no more permissions can be gained
346
-					continue;
347
-				}
348
-			}
349
-
350
-			list(, $name) = Uri\split($row['principaluri']);
351
-			$uri = $row['uri'] . '_shared_by_' . $name;
352
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
353
-			$components = [];
354
-			if ($row['components']) {
355
-				$components = explode(',',$row['components']);
356
-			}
357
-			$calendar = [
358
-				'id' => $row['id'],
359
-				'uri' => $uri,
360
-				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
361
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
362
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
363
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
364
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
365
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
366
-				$readOnlyPropertyName => $readOnly,
367
-			];
368
-
369
-			foreach($this->propertyMap as $xmlName=>$dbName) {
370
-				$calendar[$xmlName] = $row[$dbName];
371
-			}
372
-
373
-			$this->addOwnerPrincipal($calendar);
374
-
375
-			$calendars[$calendar['id']] = $calendar;
376
-		}
377
-		$result->closeCursor();
378
-
379
-		return array_values($calendars);
380
-	}
381
-
382
-	/**
383
-	 * @param $principalUri
384
-	 * @return array
385
-	 */
386
-	public function getUsersOwnCalendars($principalUri) {
387
-		$principalUri = $this->convertPrincipal($principalUri, true);
388
-		$fields = array_values($this->propertyMap);
389
-		$fields[] = 'id';
390
-		$fields[] = 'uri';
391
-		$fields[] = 'synctoken';
392
-		$fields[] = 'components';
393
-		$fields[] = 'principaluri';
394
-		$fields[] = 'transparent';
395
-		// Making fields a comma-delimited list
396
-		$query = $this->db->getQueryBuilder();
397
-		$query->select($fields)->from('calendars')
398
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
399
-			->orderBy('calendarorder', 'ASC');
400
-		$stmt = $query->execute();
401
-		$calendars = [];
402
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
403
-			$components = [];
404
-			if ($row['components']) {
405
-				$components = explode(',',$row['components']);
406
-			}
407
-			$calendar = [
408
-				'id' => $row['id'],
409
-				'uri' => $row['uri'],
410
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
411
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
412
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
413
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
414
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
415
-			];
416
-			foreach($this->propertyMap as $xmlName=>$dbName) {
417
-				$calendar[$xmlName] = $row[$dbName];
418
-			}
419
-
420
-			$this->addOwnerPrincipal($calendar);
421
-
422
-			if (!isset($calendars[$calendar['id']])) {
423
-				$calendars[$calendar['id']] = $calendar;
424
-			}
425
-		}
426
-		$stmt->closeCursor();
427
-		return array_values($calendars);
428
-	}
429
-
430
-
431
-	/**
432
-	 * @param $uid
433
-	 * @return string
434
-	 */
435
-	private function getUserDisplayName($uid) {
436
-		if (!isset($this->userDisplayNames[$uid])) {
437
-			$user = $this->userManager->get($uid);
438
-
439
-			if ($user instanceof IUser) {
440
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
441
-			} else {
442
-				$this->userDisplayNames[$uid] = $uid;
443
-			}
444
-		}
445
-
446
-		return $this->userDisplayNames[$uid];
447
-	}
78
+    const CALENDAR_TYPE_CALENDAR = 0;
79
+    const CALENDAR_TYPE_SUBSCRIPTION = 1;
80
+
81
+    const PERSONAL_CALENDAR_URI = 'personal';
82
+    const PERSONAL_CALENDAR_NAME = 'Personal';
83
+
84
+    const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
85
+    const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
86
+
87
+    /**
88
+     * We need to specify a max date, because we need to stop *somewhere*
89
+     *
90
+     * On 32 bit system the maximum for a signed integer is 2147483647, so
91
+     * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
92
+     * in 2038-01-19 to avoid problems when the date is converted
93
+     * to a unix timestamp.
94
+     */
95
+    const MAX_DATE = '2038-01-01';
96
+
97
+    const ACCESS_PUBLIC = 4;
98
+    const CLASSIFICATION_PUBLIC = 0;
99
+    const CLASSIFICATION_PRIVATE = 1;
100
+    const CLASSIFICATION_CONFIDENTIAL = 2;
101
+
102
+    /**
103
+     * List of CalDAV properties, and how they map to database field names
104
+     * Add your own properties by simply adding on to this array.
105
+     *
106
+     * Note that only string-based properties are supported here.
107
+     *
108
+     * @var array
109
+     */
110
+    public $propertyMap = [
111
+        '{DAV:}displayname'                          => 'displayname',
112
+        '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
113
+        '{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
114
+        '{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
115
+        '{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
116
+    ];
117
+
118
+    /**
119
+     * List of subscription properties, and how they map to database field names.
120
+     *
121
+     * @var array
122
+     */
123
+    public $subscriptionPropertyMap = [
124
+        '{DAV:}displayname'                                           => 'displayname',
125
+        '{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
126
+        '{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
127
+        '{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
128
+        '{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
129
+        '{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
130
+        '{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
131
+    ];
132
+
133
+    /** @var array properties to index */
134
+    public static $indexProperties = ['CATEGORIES', 'COMMENT', 'DESCRIPTION',
135
+        'LOCATION', 'RESOURCES', 'STATUS', 'SUMMARY', 'ATTENDEE', 'CONTACT',
136
+        'ORGANIZER'];
137
+
138
+    /** @var array parameters to index */
139
+    public static $indexParameters = [
140
+        'ATTENDEE' => ['CN'],
141
+        'ORGANIZER' => ['CN'],
142
+    ];
143
+
144
+    /**
145
+     * @var string[] Map of uid => display name
146
+     */
147
+    protected $userDisplayNames;
148
+
149
+    /** @var IDBConnection */
150
+    private $db;
151
+
152
+    /** @var Backend */
153
+    private $calendarSharingBackend;
154
+
155
+    /** @var Principal */
156
+    private $principalBackend;
157
+
158
+    /** @var IUserManager */
159
+    private $userManager;
160
+
161
+    /** @var ISecureRandom */
162
+    private $random;
163
+
164
+    /** @var ILogger */
165
+    private $logger;
166
+
167
+    /** @var EventDispatcherInterface */
168
+    private $dispatcher;
169
+
170
+    /** @var bool */
171
+    private $legacyEndpoint;
172
+
173
+    /** @var string */
174
+    private $dbObjectPropertiesTable = 'calendarobjects_props';
175
+
176
+    /**
177
+     * CalDavBackend constructor.
178
+     *
179
+     * @param IDBConnection $db
180
+     * @param Principal $principalBackend
181
+     * @param IUserManager $userManager
182
+     * @param IGroupManager $groupManager
183
+     * @param ISecureRandom $random
184
+     * @param ILogger $logger
185
+     * @param EventDispatcherInterface $dispatcher
186
+     * @param bool $legacyEndpoint
187
+     */
188
+    public function __construct(IDBConnection $db,
189
+                                Principal $principalBackend,
190
+                                IUserManager $userManager,
191
+                                IGroupManager $groupManager,
192
+                                ISecureRandom $random,
193
+                                ILogger $logger,
194
+                                EventDispatcherInterface $dispatcher,
195
+                                $legacyEndpoint = false) {
196
+        $this->db = $db;
197
+        $this->principalBackend = $principalBackend;
198
+        $this->userManager = $userManager;
199
+        $this->calendarSharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'calendar');
200
+        $this->random = $random;
201
+        $this->logger = $logger;
202
+        $this->dispatcher = $dispatcher;
203
+        $this->legacyEndpoint = $legacyEndpoint;
204
+    }
205
+
206
+    /**
207
+     * Return the number of calendars for a principal
208
+     *
209
+     * By default this excludes the automatically generated birthday calendar
210
+     *
211
+     * @param $principalUri
212
+     * @param bool $excludeBirthday
213
+     * @return int
214
+     */
215
+    public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
216
+        $principalUri = $this->convertPrincipal($principalUri, true);
217
+        $query = $this->db->getQueryBuilder();
218
+        $query->select($query->func()->count('*'))
219
+            ->from('calendars')
220
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
221
+
222
+        if ($excludeBirthday) {
223
+            $query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
224
+        }
225
+
226
+        return (int)$query->execute()->fetchColumn();
227
+    }
228
+
229
+    /**
230
+     * Returns a list of calendars for a principal.
231
+     *
232
+     * Every project is an array with the following keys:
233
+     *  * id, a unique id that will be used by other functions to modify the
234
+     *    calendar. This can be the same as the uri or a database key.
235
+     *  * uri, which the basename of the uri with which the calendar is
236
+     *    accessed.
237
+     *  * principaluri. The owner of the calendar. Almost always the same as
238
+     *    principalUri passed to this method.
239
+     *
240
+     * Furthermore it can contain webdav properties in clark notation. A very
241
+     * common one is '{DAV:}displayname'.
242
+     *
243
+     * Many clients also require:
244
+     * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
245
+     * For this property, you can just return an instance of
246
+     * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
247
+     *
248
+     * If you return {http://sabredav.org/ns}read-only and set the value to 1,
249
+     * ACL will automatically be put in read-only mode.
250
+     *
251
+     * @param string $principalUri
252
+     * @return array
253
+     */
254
+    function getCalendarsForUser($principalUri) {
255
+        $principalUriOriginal = $principalUri;
256
+        $principalUri = $this->convertPrincipal($principalUri, true);
257
+        $fields = array_values($this->propertyMap);
258
+        $fields[] = 'id';
259
+        $fields[] = 'uri';
260
+        $fields[] = 'synctoken';
261
+        $fields[] = 'components';
262
+        $fields[] = 'principaluri';
263
+        $fields[] = 'transparent';
264
+
265
+        // Making fields a comma-delimited list
266
+        $query = $this->db->getQueryBuilder();
267
+        $query->select($fields)->from('calendars')
268
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
269
+                ->orderBy('calendarorder', 'ASC');
270
+        $stmt = $query->execute();
271
+
272
+        $calendars = [];
273
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
274
+
275
+            $components = [];
276
+            if ($row['components']) {
277
+                $components = explode(',',$row['components']);
278
+            }
279
+
280
+            $calendar = [
281
+                'id' => $row['id'],
282
+                'uri' => $row['uri'],
283
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
284
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
285
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
286
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
287
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
288
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
289
+            ];
290
+
291
+            foreach($this->propertyMap as $xmlName=>$dbName) {
292
+                $calendar[$xmlName] = $row[$dbName];
293
+            }
294
+
295
+            $this->addOwnerPrincipal($calendar);
296
+
297
+            if (!isset($calendars[$calendar['id']])) {
298
+                $calendars[$calendar['id']] = $calendar;
299
+            }
300
+        }
301
+
302
+        $stmt->closeCursor();
303
+
304
+        // query for shared calendars
305
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
306
+        $principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
307
+
308
+        $principals = array_map(function($principal) {
309
+            return urldecode($principal);
310
+        }, $principals);
311
+        $principals[]= $principalUri;
312
+
313
+        $fields = array_values($this->propertyMap);
314
+        $fields[] = 'a.id';
315
+        $fields[] = 'a.uri';
316
+        $fields[] = 'a.synctoken';
317
+        $fields[] = 'a.components';
318
+        $fields[] = 'a.principaluri';
319
+        $fields[] = 'a.transparent';
320
+        $fields[] = 's.access';
321
+        $query = $this->db->getQueryBuilder();
322
+        $result = $query->select($fields)
323
+            ->from('dav_shares', 's')
324
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
325
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
326
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
327
+            ->setParameter('type', 'calendar')
328
+            ->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
329
+            ->execute();
330
+
331
+        $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
332
+        while($row = $result->fetch()) {
333
+            if ($row['principaluri'] === $principalUri) {
334
+                continue;
335
+            }
336
+
337
+            $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
338
+            if (isset($calendars[$row['id']])) {
339
+                if ($readOnly) {
340
+                    // New share can not have more permissions then the old one.
341
+                    continue;
342
+                }
343
+                if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
344
+                    $calendars[$row['id']][$readOnlyPropertyName] === 0) {
345
+                    // Old share is already read-write, no more permissions can be gained
346
+                    continue;
347
+                }
348
+            }
349
+
350
+            list(, $name) = Uri\split($row['principaluri']);
351
+            $uri = $row['uri'] . '_shared_by_' . $name;
352
+            $row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
353
+            $components = [];
354
+            if ($row['components']) {
355
+                $components = explode(',',$row['components']);
356
+            }
357
+            $calendar = [
358
+                'id' => $row['id'],
359
+                'uri' => $uri,
360
+                'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
361
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
362
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
363
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
364
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
365
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
366
+                $readOnlyPropertyName => $readOnly,
367
+            ];
368
+
369
+            foreach($this->propertyMap as $xmlName=>$dbName) {
370
+                $calendar[$xmlName] = $row[$dbName];
371
+            }
372
+
373
+            $this->addOwnerPrincipal($calendar);
374
+
375
+            $calendars[$calendar['id']] = $calendar;
376
+        }
377
+        $result->closeCursor();
378
+
379
+        return array_values($calendars);
380
+    }
381
+
382
+    /**
383
+     * @param $principalUri
384
+     * @return array
385
+     */
386
+    public function getUsersOwnCalendars($principalUri) {
387
+        $principalUri = $this->convertPrincipal($principalUri, true);
388
+        $fields = array_values($this->propertyMap);
389
+        $fields[] = 'id';
390
+        $fields[] = 'uri';
391
+        $fields[] = 'synctoken';
392
+        $fields[] = 'components';
393
+        $fields[] = 'principaluri';
394
+        $fields[] = 'transparent';
395
+        // Making fields a comma-delimited list
396
+        $query = $this->db->getQueryBuilder();
397
+        $query->select($fields)->from('calendars')
398
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
399
+            ->orderBy('calendarorder', 'ASC');
400
+        $stmt = $query->execute();
401
+        $calendars = [];
402
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
403
+            $components = [];
404
+            if ($row['components']) {
405
+                $components = explode(',',$row['components']);
406
+            }
407
+            $calendar = [
408
+                'id' => $row['id'],
409
+                'uri' => $row['uri'],
410
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
411
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
412
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
413
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
414
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
415
+            ];
416
+            foreach($this->propertyMap as $xmlName=>$dbName) {
417
+                $calendar[$xmlName] = $row[$dbName];
418
+            }
419
+
420
+            $this->addOwnerPrincipal($calendar);
421
+
422
+            if (!isset($calendars[$calendar['id']])) {
423
+                $calendars[$calendar['id']] = $calendar;
424
+            }
425
+        }
426
+        $stmt->closeCursor();
427
+        return array_values($calendars);
428
+    }
429
+
430
+
431
+    /**
432
+     * @param $uid
433
+     * @return string
434
+     */
435
+    private function getUserDisplayName($uid) {
436
+        if (!isset($this->userDisplayNames[$uid])) {
437
+            $user = $this->userManager->get($uid);
438
+
439
+            if ($user instanceof IUser) {
440
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
441
+            } else {
442
+                $this->userDisplayNames[$uid] = $uid;
443
+            }
444
+        }
445
+
446
+        return $this->userDisplayNames[$uid];
447
+    }
448 448
 	
449
-	/**
450
-	 * @return array
451
-	 */
452
-	public function getPublicCalendars() {
453
-		$fields = array_values($this->propertyMap);
454
-		$fields[] = 'a.id';
455
-		$fields[] = 'a.uri';
456
-		$fields[] = 'a.synctoken';
457
-		$fields[] = 'a.components';
458
-		$fields[] = 'a.principaluri';
459
-		$fields[] = 'a.transparent';
460
-		$fields[] = 's.access';
461
-		$fields[] = 's.publicuri';
462
-		$calendars = [];
463
-		$query = $this->db->getQueryBuilder();
464
-		$result = $query->select($fields)
465
-			->from('dav_shares', 's')
466
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
467
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
468
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
469
-			->execute();
470
-
471
-		while($row = $result->fetch()) {
472
-			list(, $name) = Uri\split($row['principaluri']);
473
-			$row['displayname'] = $row['displayname'] . "($name)";
474
-			$components = [];
475
-			if ($row['components']) {
476
-				$components = explode(',',$row['components']);
477
-			}
478
-			$calendar = [
479
-				'id' => $row['id'],
480
-				'uri' => $row['publicuri'],
481
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
482
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
483
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
484
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
485
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
486
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
487
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
488
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
489
-			];
490
-
491
-			foreach($this->propertyMap as $xmlName=>$dbName) {
492
-				$calendar[$xmlName] = $row[$dbName];
493
-			}
494
-
495
-			$this->addOwnerPrincipal($calendar);
496
-
497
-			if (!isset($calendars[$calendar['id']])) {
498
-				$calendars[$calendar['id']] = $calendar;
499
-			}
500
-		}
501
-		$result->closeCursor();
502
-
503
-		return array_values($calendars);
504
-	}
505
-
506
-	/**
507
-	 * @param string $uri
508
-	 * @return array
509
-	 * @throws NotFound
510
-	 */
511
-	public function getPublicCalendar($uri) {
512
-		$fields = array_values($this->propertyMap);
513
-		$fields[] = 'a.id';
514
-		$fields[] = 'a.uri';
515
-		$fields[] = 'a.synctoken';
516
-		$fields[] = 'a.components';
517
-		$fields[] = 'a.principaluri';
518
-		$fields[] = 'a.transparent';
519
-		$fields[] = 's.access';
520
-		$fields[] = 's.publicuri';
521
-		$query = $this->db->getQueryBuilder();
522
-		$result = $query->select($fields)
523
-			->from('dav_shares', 's')
524
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
525
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
526
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
527
-			->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
528
-			->execute();
529
-
530
-		$row = $result->fetch(\PDO::FETCH_ASSOC);
531
-
532
-		$result->closeCursor();
533
-
534
-		if ($row === false) {
535
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
536
-		}
537
-
538
-		list(, $name) = Uri\split($row['principaluri']);
539
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
540
-		$components = [];
541
-		if ($row['components']) {
542
-			$components = explode(',',$row['components']);
543
-		}
544
-		$calendar = [
545
-			'id' => $row['id'],
546
-			'uri' => $row['publicuri'],
547
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
548
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
549
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
550
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
551
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
552
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
553
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
554
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
555
-		];
556
-
557
-		foreach($this->propertyMap as $xmlName=>$dbName) {
558
-			$calendar[$xmlName] = $row[$dbName];
559
-		}
560
-
561
-		$this->addOwnerPrincipal($calendar);
562
-
563
-		return $calendar;
564
-
565
-	}
566
-
567
-	/**
568
-	 * @param string $principal
569
-	 * @param string $uri
570
-	 * @return array|null
571
-	 */
572
-	public function getCalendarByUri($principal, $uri) {
573
-		$fields = array_values($this->propertyMap);
574
-		$fields[] = 'id';
575
-		$fields[] = 'uri';
576
-		$fields[] = 'synctoken';
577
-		$fields[] = 'components';
578
-		$fields[] = 'principaluri';
579
-		$fields[] = 'transparent';
580
-
581
-		// Making fields a comma-delimited list
582
-		$query = $this->db->getQueryBuilder();
583
-		$query->select($fields)->from('calendars')
584
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
585
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
586
-			->setMaxResults(1);
587
-		$stmt = $query->execute();
588
-
589
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
590
-		$stmt->closeCursor();
591
-		if ($row === false) {
592
-			return null;
593
-		}
594
-
595
-		$components = [];
596
-		if ($row['components']) {
597
-			$components = explode(',',$row['components']);
598
-		}
599
-
600
-		$calendar = [
601
-			'id' => $row['id'],
602
-			'uri' => $row['uri'],
603
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
604
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
605
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
606
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
607
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
608
-		];
609
-
610
-		foreach($this->propertyMap as $xmlName=>$dbName) {
611
-			$calendar[$xmlName] = $row[$dbName];
612
-		}
613
-
614
-		$this->addOwnerPrincipal($calendar);
615
-
616
-		return $calendar;
617
-	}
618
-
619
-	/**
620
-	 * @param $calendarId
621
-	 * @return array|null
622
-	 */
623
-	public function getCalendarById($calendarId) {
624
-		$fields = array_values($this->propertyMap);
625
-		$fields[] = 'id';
626
-		$fields[] = 'uri';
627
-		$fields[] = 'synctoken';
628
-		$fields[] = 'components';
629
-		$fields[] = 'principaluri';
630
-		$fields[] = 'transparent';
631
-
632
-		// Making fields a comma-delimited list
633
-		$query = $this->db->getQueryBuilder();
634
-		$query->select($fields)->from('calendars')
635
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
636
-			->setMaxResults(1);
637
-		$stmt = $query->execute();
638
-
639
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
640
-		$stmt->closeCursor();
641
-		if ($row === false) {
642
-			return null;
643
-		}
644
-
645
-		$components = [];
646
-		if ($row['components']) {
647
-			$components = explode(',',$row['components']);
648
-		}
649
-
650
-		$calendar = [
651
-			'id' => $row['id'],
652
-			'uri' => $row['uri'],
653
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
654
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
655
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
656
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
657
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
658
-		];
659
-
660
-		foreach($this->propertyMap as $xmlName=>$dbName) {
661
-			$calendar[$xmlName] = $row[$dbName];
662
-		}
663
-
664
-		$this->addOwnerPrincipal($calendar);
665
-
666
-		return $calendar;
667
-	}
668
-
669
-	/**
670
-	 * @param $subscriptionId
671
-	 */
672
-	public function getSubscriptionById($subscriptionId) {
673
-		$fields = array_values($this->subscriptionPropertyMap);
674
-		$fields[] = 'id';
675
-		$fields[] = 'uri';
676
-		$fields[] = 'source';
677
-		$fields[] = 'synctoken';
678
-		$fields[] = 'principaluri';
679
-		$fields[] = 'lastmodified';
680
-
681
-		$query = $this->db->getQueryBuilder();
682
-		$query->select($fields)
683
-			->from('calendarsubscriptions')
684
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
685
-			->orderBy('calendarorder', 'asc');
686
-		$stmt =$query->execute();
687
-
688
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
689
-		$stmt->closeCursor();
690
-		if ($row === false) {
691
-			return null;
692
-		}
693
-
694
-		$subscription = [
695
-			'id'           => $row['id'],
696
-			'uri'          => $row['uri'],
697
-			'principaluri' => $row['principaluri'],
698
-			'source'       => $row['source'],
699
-			'lastmodified' => $row['lastmodified'],
700
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
701
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
702
-		];
703
-
704
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
705
-			if (!is_null($row[$dbName])) {
706
-				$subscription[$xmlName] = $row[$dbName];
707
-			}
708
-		}
709
-
710
-		return $subscription;
711
-	}
712
-
713
-	/**
714
-	 * Creates a new calendar for a principal.
715
-	 *
716
-	 * If the creation was a success, an id must be returned that can be used to reference
717
-	 * this calendar in other methods, such as updateCalendar.
718
-	 *
719
-	 * @param string $principalUri
720
-	 * @param string $calendarUri
721
-	 * @param array $properties
722
-	 * @return int
723
-	 * @suppress SqlInjectionChecker
724
-	 */
725
-	function createCalendar($principalUri, $calendarUri, array $properties) {
726
-		$values = [
727
-			'principaluri' => $this->convertPrincipal($principalUri, true),
728
-			'uri'          => $calendarUri,
729
-			'synctoken'    => 1,
730
-			'transparent'  => 0,
731
-			'components'   => 'VEVENT,VTODO',
732
-			'displayname'  => $calendarUri
733
-		];
734
-
735
-		// Default value
736
-		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
737
-		if (isset($properties[$sccs])) {
738
-			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
739
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
740
-			}
741
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
742
-		}
743
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
744
-		if (isset($properties[$transp])) {
745
-			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
746
-		}
747
-
748
-		foreach($this->propertyMap as $xmlName=>$dbName) {
749
-			if (isset($properties[$xmlName])) {
750
-				$values[$dbName] = $properties[$xmlName];
751
-			}
752
-		}
753
-
754
-		$query = $this->db->getQueryBuilder();
755
-		$query->insert('calendars');
756
-		foreach($values as $column => $value) {
757
-			$query->setValue($column, $query->createNamedParameter($value));
758
-		}
759
-		$query->execute();
760
-		$calendarId = $query->getLastInsertId();
761
-
762
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
763
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
764
-			[
765
-				'calendarId' => $calendarId,
766
-				'calendarData' => $this->getCalendarById($calendarId),
767
-		]));
768
-
769
-		return $calendarId;
770
-	}
771
-
772
-	/**
773
-	 * Updates properties for a calendar.
774
-	 *
775
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
776
-	 * To do the actual updates, you must tell this object which properties
777
-	 * you're going to process with the handle() method.
778
-	 *
779
-	 * Calling the handle method is like telling the PropPatch object "I
780
-	 * promise I can handle updating this property".
781
-	 *
782
-	 * Read the PropPatch documentation for more info and examples.
783
-	 *
784
-	 * @param mixed $calendarId
785
-	 * @param PropPatch $propPatch
786
-	 * @return void
787
-	 */
788
-	function updateCalendar($calendarId, PropPatch $propPatch) {
789
-		$supportedProperties = array_keys($this->propertyMap);
790
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
791
-
792
-		/**
793
-		 * @suppress SqlInjectionChecker
794
-		 */
795
-		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
796
-			$newValues = [];
797
-			foreach ($mutations as $propertyName => $propertyValue) {
798
-
799
-				switch ($propertyName) {
800
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
801
-						$fieldName = 'transparent';
802
-						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
803
-						break;
804
-					default :
805
-						$fieldName = $this->propertyMap[$propertyName];
806
-						$newValues[$fieldName] = $propertyValue;
807
-						break;
808
-				}
809
-
810
-			}
811
-			$query = $this->db->getQueryBuilder();
812
-			$query->update('calendars');
813
-			foreach ($newValues as $fieldName => $value) {
814
-				$query->set($fieldName, $query->createNamedParameter($value));
815
-			}
816
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
817
-			$query->execute();
818
-
819
-			$this->addChange($calendarId, "", 2);
820
-
821
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
822
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
823
-				[
824
-					'calendarId' => $calendarId,
825
-					'calendarData' => $this->getCalendarById($calendarId),
826
-					'shares' => $this->getShares($calendarId),
827
-					'propertyMutations' => $mutations,
828
-			]));
829
-
830
-			return true;
831
-		});
832
-	}
833
-
834
-	/**
835
-	 * Delete a calendar and all it's objects
836
-	 *
837
-	 * @param mixed $calendarId
838
-	 * @return void
839
-	 */
840
-	function deleteCalendar($calendarId) {
841
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
842
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
843
-			[
844
-				'calendarId' => $calendarId,
845
-				'calendarData' => $this->getCalendarById($calendarId),
846
-				'shares' => $this->getShares($calendarId),
847
-		]));
848
-
849
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?');
850
-		$stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
851
-
852
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
853
-		$stmt->execute([$calendarId]);
854
-
855
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ? AND `calendartype` = ?');
856
-		$stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
857
-
858
-		$this->calendarSharingBackend->deleteAllShares($calendarId);
859
-
860
-		$query = $this->db->getQueryBuilder();
861
-		$query->delete($this->dbObjectPropertiesTable)
862
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
863
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
864
-			->execute();
865
-	}
866
-
867
-	/**
868
-	 * Delete all of an user's shares
869
-	 *
870
-	 * @param string $principaluri
871
-	 * @return void
872
-	 */
873
-	function deleteAllSharesByUser($principaluri) {
874
-		$this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
875
-	}
876
-
877
-	/**
878
-	 * Returns all calendar objects within a calendar.
879
-	 *
880
-	 * Every item contains an array with the following keys:
881
-	 *   * calendardata - The iCalendar-compatible calendar data
882
-	 *   * uri - a unique key which will be used to construct the uri. This can
883
-	 *     be any arbitrary string, but making sure it ends with '.ics' is a
884
-	 *     good idea. This is only the basename, or filename, not the full
885
-	 *     path.
886
-	 *   * lastmodified - a timestamp of the last modification time
887
-	 *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
888
-	 *   '"abcdef"')
889
-	 *   * size - The size of the calendar objects, in bytes.
890
-	 *   * component - optional, a string containing the type of object, such
891
-	 *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
892
-	 *     the Content-Type header.
893
-	 *
894
-	 * Note that the etag is optional, but it's highly encouraged to return for
895
-	 * speed reasons.
896
-	 *
897
-	 * The calendardata is also optional. If it's not returned
898
-	 * 'getCalendarObject' will be called later, which *is* expected to return
899
-	 * calendardata.
900
-	 *
901
-	 * If neither etag or size are specified, the calendardata will be
902
-	 * used/fetched to determine these numbers. If both are specified the
903
-	 * amount of times this is needed is reduced by a great degree.
904
-	 *
905
-	 * @param mixed $id
906
-	 * @param int $calendarType
907
-	 * @return array
908
-	 */
909
-	public function getCalendarObjects($id, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
910
-		$query = $this->db->getQueryBuilder();
911
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
912
-			->from('calendarobjects')
913
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
914
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
915
-		$stmt = $query->execute();
916
-
917
-		$result = [];
918
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
919
-			$result[] = [
920
-				'id'           => $row['id'],
921
-				'uri'          => $row['uri'],
922
-				'lastmodified' => $row['lastmodified'],
923
-				'etag'         => '"' . $row['etag'] . '"',
924
-				'calendarid'   => $row['calendarid'],
925
-				'size'         => (int)$row['size'],
926
-				'component'    => strtolower($row['componenttype']),
927
-				'classification'=> (int)$row['classification']
928
-			];
929
-		}
930
-
931
-		return $result;
932
-	}
933
-
934
-	/**
935
-	 * Returns information from a single calendar object, based on it's object
936
-	 * uri.
937
-	 *
938
-	 * The object uri is only the basename, or filename and not a full path.
939
-	 *
940
-	 * The returned array must have the same keys as getCalendarObjects. The
941
-	 * 'calendardata' object is required here though, while it's not required
942
-	 * for getCalendarObjects.
943
-	 *
944
-	 * This method must return null if the object did not exist.
945
-	 *
946
-	 * @param mixed $id
947
-	 * @param string $objectUri
948
-	 * @param int $calendarType
949
-	 * @return array|null
950
-	 */
951
-	public function getCalendarObject($id, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
952
-		$query = $this->db->getQueryBuilder();
953
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
954
-			->from('calendarobjects')
955
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
956
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
957
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
958
-		$stmt = $query->execute();
959
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
960
-
961
-		if(!$row) {
962
-			return null;
963
-		}
964
-
965
-		return [
966
-			'id'            => $row['id'],
967
-			'uri'           => $row['uri'],
968
-			'lastmodified'  => $row['lastmodified'],
969
-			'etag'          => '"' . $row['etag'] . '"',
970
-			'calendarid'    => $row['calendarid'],
971
-			'size'          => (int)$row['size'],
972
-			'calendardata'  => $this->readBlob($row['calendardata']),
973
-			'component'     => strtolower($row['componenttype']),
974
-			'classification'=> (int)$row['classification']
975
-		];
976
-	}
977
-
978
-	/**
979
-	 * Returns a list of calendar objects.
980
-	 *
981
-	 * This method should work identical to getCalendarObject, but instead
982
-	 * return all the calendar objects in the list as an array.
983
-	 *
984
-	 * If the backend supports this, it may allow for some speed-ups.
985
-	 *
986
-	 * @param mixed $calendarId
987
-	 * @param string[] $uris
988
-	 * @param int $calendarType
989
-	 * @return array
990
-	 */
991
-	public function getMultipleCalendarObjects($id, array $uris, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
992
-		if (empty($uris)) {
993
-			return [];
994
-		}
995
-
996
-		$chunks = array_chunk($uris, 100);
997
-		$objects = [];
998
-
999
-		$query = $this->db->getQueryBuilder();
1000
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1001
-			->from('calendarobjects')
1002
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
1003
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1004
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1005
-
1006
-		foreach ($chunks as $uris) {
1007
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1008
-			$result = $query->execute();
1009
-
1010
-			while ($row = $result->fetch()) {
1011
-				$objects[] = [
1012
-					'id'           => $row['id'],
1013
-					'uri'          => $row['uri'],
1014
-					'lastmodified' => $row['lastmodified'],
1015
-					'etag'         => '"' . $row['etag'] . '"',
1016
-					'calendarid'   => $row['calendarid'],
1017
-					'size'         => (int)$row['size'],
1018
-					'calendardata' => $this->readBlob($row['calendardata']),
1019
-					'component'    => strtolower($row['componenttype']),
1020
-					'classification' => (int)$row['classification']
1021
-				];
1022
-			}
1023
-			$result->closeCursor();
1024
-		}
1025
-
1026
-		return $objects;
1027
-	}
1028
-
1029
-	/**
1030
-	 * Creates a new calendar object.
1031
-	 *
1032
-	 * The object uri is only the basename, or filename and not a full path.
1033
-	 *
1034
-	 * It is possible return an etag from this function, which will be used in
1035
-	 * the response to this PUT request. Note that the ETag must be surrounded
1036
-	 * by double-quotes.
1037
-	 *
1038
-	 * However, you should only really return this ETag if you don't mangle the
1039
-	 * calendar-data. If the result of a subsequent GET to this object is not
1040
-	 * the exact same as this request body, you should omit the ETag.
1041
-	 *
1042
-	 * @param mixed $calendarId
1043
-	 * @param string $objectUri
1044
-	 * @param string $calendarData
1045
-	 * @param int $calendarType
1046
-	 * @return string
1047
-	 */
1048
-	function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1049
-		$extraData = $this->getDenormalizedData($calendarData);
1050
-
1051
-		$q = $this->db->getQueryBuilder();
1052
-		$q->select($q->func()->count('*'))
1053
-			->from('calendarobjects')
1054
-			->where($q->expr()->eq('calendarid', $q->createNamedParameter($calendarId)))
1055
-			->andWhere($q->expr()->eq('uid', $q->createNamedParameter($extraData['uid'])))
1056
-			->andWhere($q->expr()->eq('calendartype', $q->createNamedParameter($calendarType)));
1057
-
1058
-		$result = $q->execute();
1059
-		$count = (int) $result->fetchColumn();
1060
-		$result->closeCursor();
1061
-
1062
-		if ($count !== 0) {
1063
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar object with uid already exists in this calendar collection.');
1064
-		}
1065
-
1066
-		$query = $this->db->getQueryBuilder();
1067
-		$query->insert('calendarobjects')
1068
-			->values([
1069
-				'calendarid' => $query->createNamedParameter($calendarId),
1070
-				'uri' => $query->createNamedParameter($objectUri),
1071
-				'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1072
-				'lastmodified' => $query->createNamedParameter(time()),
1073
-				'etag' => $query->createNamedParameter($extraData['etag']),
1074
-				'size' => $query->createNamedParameter($extraData['size']),
1075
-				'componenttype' => $query->createNamedParameter($extraData['componentType']),
1076
-				'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1077
-				'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1078
-				'classification' => $query->createNamedParameter($extraData['classification']),
1079
-				'uid' => $query->createNamedParameter($extraData['uid']),
1080
-				'calendartype' => $query->createNamedParameter($calendarType),
1081
-			])
1082
-			->execute();
1083
-
1084
-		$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1085
-
1086
-		if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1087
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
1088
-				'\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
1089
-				[
1090
-					'calendarId' => $calendarId,
1091
-					'calendarData' => $this->getCalendarById($calendarId),
1092
-					'shares' => $this->getShares($calendarId),
1093
-					'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1094
-				]
1095
-			));
1096
-		} else {
1097
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject', new GenericEvent(
1098
-				'\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject',
1099
-				[
1100
-					'subscriptionId' => $calendarId,
1101
-					'calendarData' => $this->getCalendarById($calendarId),
1102
-					'shares' => $this->getShares($calendarId),
1103
-					'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1104
-				]
1105
-			));
1106
-		}
1107
-		$this->addChange($calendarId, $objectUri, 1, $calendarType);
1108
-
1109
-		return '"' . $extraData['etag'] . '"';
1110
-	}
1111
-
1112
-	/**
1113
-	 * Updates an existing calendarobject, based on it's uri.
1114
-	 *
1115
-	 * The object uri is only the basename, or filename and not a full path.
1116
-	 *
1117
-	 * It is possible return an etag from this function, which will be used in
1118
-	 * the response to this PUT request. Note that the ETag must be surrounded
1119
-	 * by double-quotes.
1120
-	 *
1121
-	 * However, you should only really return this ETag if you don't mangle the
1122
-	 * calendar-data. If the result of a subsequent GET to this object is not
1123
-	 * the exact same as this request body, you should omit the ETag.
1124
-	 *
1125
-	 * @param mixed $calendarId
1126
-	 * @param string $objectUri
1127
-	 * @param string $calendarData
1128
-	 * @param int $calendarType
1129
-	 * @return string
1130
-	 */
1131
-	function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1132
-		$extraData = $this->getDenormalizedData($calendarData);
1133
-
1134
-		$query = $this->db->getQueryBuilder();
1135
-		$query->update('calendarobjects')
1136
-				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1137
-				->set('lastmodified', $query->createNamedParameter(time()))
1138
-				->set('etag', $query->createNamedParameter($extraData['etag']))
1139
-				->set('size', $query->createNamedParameter($extraData['size']))
1140
-				->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1141
-				->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1142
-				->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1143
-				->set('classification', $query->createNamedParameter($extraData['classification']))
1144
-				->set('uid', $query->createNamedParameter($extraData['uid']))
1145
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1146
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1147
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1148
-			->execute();
1149
-
1150
-		$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1151
-
1152
-		$data = $this->getCalendarObject($calendarId, $objectUri);
1153
-		if (is_array($data)) {
1154
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1155
-				$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1156
-					'\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1157
-					[
1158
-						'calendarId' => $calendarId,
1159
-						'calendarData' => $this->getCalendarById($calendarId),
1160
-						'shares' => $this->getShares($calendarId),
1161
-						'objectData' => $data,
1162
-					]
1163
-				));
1164
-			} else {
1165
-				$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject', new GenericEvent(
1166
-					'\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject',
1167
-					[
1168
-						'subscriptionId' => $calendarId,
1169
-						'calendarData' => $this->getCalendarById($calendarId),
1170
-						'shares' => $this->getShares($calendarId),
1171
-						'objectData' => $data,
1172
-					]
1173
-				));
1174
-			}
1175
-		}
1176
-		$this->addChange($calendarId, $objectUri, 2, $calendarType);
1177
-
1178
-		return '"' . $extraData['etag'] . '"';
1179
-	}
1180
-
1181
-	/**
1182
-	 * @param int $calendarObjectId
1183
-	 * @param int $classification
1184
-	 */
1185
-	public function setClassification($calendarObjectId, $classification) {
1186
-		if (!in_array($classification, [
1187
-			self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1188
-		])) {
1189
-			throw new \InvalidArgumentException();
1190
-		}
1191
-		$query = $this->db->getQueryBuilder();
1192
-		$query->update('calendarobjects')
1193
-			->set('classification', $query->createNamedParameter($classification))
1194
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1195
-			->execute();
1196
-	}
1197
-
1198
-	/**
1199
-	 * Deletes an existing calendar object.
1200
-	 *
1201
-	 * The object uri is only the basename, or filename and not a full path.
1202
-	 *
1203
-	 * @param mixed $calendarId
1204
-	 * @param string $objectUri
1205
-	 * @param int $calendarType
1206
-	 * @return void
1207
-	 */
1208
-	function deleteCalendarObject($calendarId, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1209
-		$data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1210
-		if (is_array($data)) {
1211
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1212
-				$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1213
-					'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1214
-					[
1215
-						'calendarId' => $calendarId,
1216
-						'calendarData' => $this->getCalendarById($calendarId),
1217
-						'shares' => $this->getShares($calendarId),
1218
-						'objectData' => $data,
1219
-					]
1220
-				));
1221
-			} else {
1222
-				$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject', new GenericEvent(
1223
-					'\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject',
1224
-					[
1225
-						'subscriptionId' => $calendarId,
1226
-						'calendarData' => $this->getCalendarById($calendarId),
1227
-						'shares' => $this->getShares($calendarId),
1228
-						'objectData' => $data,
1229
-					]
1230
-				));
1231
-			}
1232
-		}
1233
-
1234
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1235
-		$stmt->execute([$calendarId, $objectUri, $calendarType]);
1236
-
1237
-		$this->purgeProperties($calendarId, $data['id'], $calendarType);
1238
-
1239
-		$this->addChange($calendarId, $objectUri, 3, $calendarType);
1240
-	}
1241
-
1242
-	/**
1243
-	 * Performs a calendar-query on the contents of this calendar.
1244
-	 *
1245
-	 * The calendar-query is defined in RFC4791 : CalDAV. Using the
1246
-	 * calendar-query it is possible for a client to request a specific set of
1247
-	 * object, based on contents of iCalendar properties, date-ranges and
1248
-	 * iCalendar component types (VTODO, VEVENT).
1249
-	 *
1250
-	 * This method should just return a list of (relative) urls that match this
1251
-	 * query.
1252
-	 *
1253
-	 * The list of filters are specified as an array. The exact array is
1254
-	 * documented by Sabre\CalDAV\CalendarQueryParser.
1255
-	 *
1256
-	 * Note that it is extremely likely that getCalendarObject for every path
1257
-	 * returned from this method will be called almost immediately after. You
1258
-	 * may want to anticipate this to speed up these requests.
1259
-	 *
1260
-	 * This method provides a default implementation, which parses *all* the
1261
-	 * iCalendar objects in the specified calendar.
1262
-	 *
1263
-	 * This default may well be good enough for personal use, and calendars
1264
-	 * that aren't very large. But if you anticipate high usage, big calendars
1265
-	 * or high loads, you are strongly advised to optimize certain paths.
1266
-	 *
1267
-	 * The best way to do so is override this method and to optimize
1268
-	 * specifically for 'common filters'.
1269
-	 *
1270
-	 * Requests that are extremely common are:
1271
-	 *   * requests for just VEVENTS
1272
-	 *   * requests for just VTODO
1273
-	 *   * requests with a time-range-filter on either VEVENT or VTODO.
1274
-	 *
1275
-	 * ..and combinations of these requests. It may not be worth it to try to
1276
-	 * handle every possible situation and just rely on the (relatively
1277
-	 * easy to use) CalendarQueryValidator to handle the rest.
1278
-	 *
1279
-	 * Note that especially time-range-filters may be difficult to parse. A
1280
-	 * time-range filter specified on a VEVENT must for instance also handle
1281
-	 * recurrence rules correctly.
1282
-	 * A good example of how to interprete all these filters can also simply
1283
-	 * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1284
-	 * as possible, so it gives you a good idea on what type of stuff you need
1285
-	 * to think of.
1286
-	 *
1287
-	 * @param mixed $id
1288
-	 * @param array $filters
1289
-	 * @param int $calendarType
1290
-	 * @return array
1291
-	 */
1292
-	public function calendarQuery($id, array $filters, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
1293
-		$componentType = null;
1294
-		$requirePostFilter = true;
1295
-		$timeRange = null;
1296
-
1297
-		// if no filters were specified, we don't need to filter after a query
1298
-		if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1299
-			$requirePostFilter = false;
1300
-		}
1301
-
1302
-		// Figuring out if there's a component filter
1303
-		if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1304
-			$componentType = $filters['comp-filters'][0]['name'];
1305
-
1306
-			// Checking if we need post-filters
1307
-			if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1308
-				$requirePostFilter = false;
1309
-			}
1310
-			// There was a time-range filter
1311
-			if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1312
-				$timeRange = $filters['comp-filters'][0]['time-range'];
1313
-
1314
-				// If start time OR the end time is not specified, we can do a
1315
-				// 100% accurate mysql query.
1316
-				if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1317
-					$requirePostFilter = false;
1318
-				}
1319
-			}
1320
-
1321
-		}
1322
-		$columns = ['uri'];
1323
-		if ($requirePostFilter) {
1324
-			$columns = ['uri', 'calendardata'];
1325
-		}
1326
-		$query = $this->db->getQueryBuilder();
1327
-		$query->select($columns)
1328
-			->from('calendarobjects')
1329
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
1330
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1331
-
1332
-		if ($componentType) {
1333
-			$query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1334
-		}
1335
-
1336
-		if ($timeRange && $timeRange['start']) {
1337
-			$query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1338
-		}
1339
-		if ($timeRange && $timeRange['end']) {
1340
-			$query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1341
-		}
1342
-
1343
-		$stmt = $query->execute();
1344
-
1345
-		$result = [];
1346
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1347
-			if ($requirePostFilter) {
1348
-				// validateFilterForObject will parse the calendar data
1349
-				// catch parsing errors
1350
-				try {
1351
-					$matches = $this->validateFilterForObject($row, $filters);
1352
-				} catch(ParseException $ex) {
1353
-					$this->logger->logException($ex, [
1354
-						'app' => 'dav',
1355
-						'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
1356
-					]);
1357
-					continue;
1358
-				} catch (InvalidDataException $ex) {
1359
-					$this->logger->logException($ex, [
1360
-						'app' => 'dav',
1361
-						'message' => 'Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
1362
-					]);
1363
-					continue;
1364
-				}
1365
-
1366
-				if (!$matches) {
1367
-					continue;
1368
-				}
1369
-			}
1370
-			$result[] = $row['uri'];
1371
-		}
1372
-
1373
-		return $result;
1374
-	}
1375
-
1376
-	/**
1377
-	 * custom Nextcloud search extension for CalDAV
1378
-	 *
1379
-	 * TODO - this should optionally cover cached calendar objects as well
1380
-	 *
1381
-	 * @param string $principalUri
1382
-	 * @param array $filters
1383
-	 * @param integer|null $limit
1384
-	 * @param integer|null $offset
1385
-	 * @return array
1386
-	 */
1387
-	public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1388
-		$calendars = $this->getCalendarsForUser($principalUri);
1389
-		$ownCalendars = [];
1390
-		$sharedCalendars = [];
1391
-
1392
-		$uriMapper = [];
1393
-
1394
-		foreach($calendars as $calendar) {
1395
-			if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1396
-				$ownCalendars[] = $calendar['id'];
1397
-			} else {
1398
-				$sharedCalendars[] = $calendar['id'];
1399
-			}
1400
-			$uriMapper[$calendar['id']] = $calendar['uri'];
1401
-		}
1402
-		if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1403
-			return [];
1404
-		}
1405
-
1406
-		$query = $this->db->getQueryBuilder();
1407
-		// Calendar id expressions
1408
-		$calendarExpressions = [];
1409
-		foreach($ownCalendars as $id) {
1410
-			$calendarExpressions[] = $query->expr()->andX(
1411
-				$query->expr()->eq('c.calendarid',
1412
-					$query->createNamedParameter($id)),
1413
-				$query->expr()->eq('c.calendartype',
1414
-						$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1415
-		}
1416
-		foreach($sharedCalendars as $id) {
1417
-			$calendarExpressions[] = $query->expr()->andX(
1418
-				$query->expr()->eq('c.calendarid',
1419
-					$query->createNamedParameter($id)),
1420
-				$query->expr()->eq('c.classification',
1421
-					$query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1422
-				$query->expr()->eq('c.calendartype',
1423
-					$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1424
-		}
1425
-
1426
-		if (count($calendarExpressions) === 1) {
1427
-			$calExpr = $calendarExpressions[0];
1428
-		} else {
1429
-			$calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1430
-		}
1431
-
1432
-		// Component expressions
1433
-		$compExpressions = [];
1434
-		foreach($filters['comps'] as $comp) {
1435
-			$compExpressions[] = $query->expr()
1436
-				->eq('c.componenttype', $query->createNamedParameter($comp));
1437
-		}
1438
-
1439
-		if (count($compExpressions) === 1) {
1440
-			$compExpr = $compExpressions[0];
1441
-		} else {
1442
-			$compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1443
-		}
1444
-
1445
-		if (!isset($filters['props'])) {
1446
-			$filters['props'] = [];
1447
-		}
1448
-		if (!isset($filters['params'])) {
1449
-			$filters['params'] = [];
1450
-		}
1451
-
1452
-		$propParamExpressions = [];
1453
-		foreach($filters['props'] as $prop) {
1454
-			$propParamExpressions[] = $query->expr()->andX(
1455
-				$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1456
-				$query->expr()->isNull('i.parameter')
1457
-			);
1458
-		}
1459
-		foreach($filters['params'] as $param) {
1460
-			$propParamExpressions[] = $query->expr()->andX(
1461
-				$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1462
-				$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1463
-			);
1464
-		}
1465
-
1466
-		if (count($propParamExpressions) === 1) {
1467
-			$propParamExpr = $propParamExpressions[0];
1468
-		} else {
1469
-			$propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1470
-		}
1471
-
1472
-		$query->select(['c.calendarid', 'c.uri'])
1473
-			->from($this->dbObjectPropertiesTable, 'i')
1474
-			->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1475
-			->where($calExpr)
1476
-			->andWhere($compExpr)
1477
-			->andWhere($propParamExpr)
1478
-			->andWhere($query->expr()->iLike('i.value',
1479
-				$query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
1480
-
1481
-		if ($offset) {
1482
-			$query->setFirstResult($offset);
1483
-		}
1484
-		if ($limit) {
1485
-			$query->setMaxResults($limit);
1486
-		}
1487
-
1488
-		$stmt = $query->execute();
1489
-
1490
-		$result = [];
1491
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1492
-			$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1493
-			if (!in_array($path, $result)) {
1494
-				$result[] = $path;
1495
-			}
1496
-		}
1497
-
1498
-		return $result;
1499
-	}
1500
-
1501
-	/**
1502
-	 * used for Nextcloud's calendar API
1503
-	 *
1504
-	 * @param array $calendarInfo
1505
-	 * @param string $pattern
1506
-	 * @param array $searchProperties
1507
-	 * @param array $options
1508
-	 * @param integer|null $limit
1509
-	 * @param integer|null $offset
1510
-	 *
1511
-	 * @return array
1512
-	 */
1513
-	public function search(array $calendarInfo, $pattern, array $searchProperties,
1514
-						   array $options, $limit, $offset) {
1515
-		$outerQuery = $this->db->getQueryBuilder();
1516
-		$innerQuery = $this->db->getQueryBuilder();
1517
-
1518
-		$innerQuery->selectDistinct('op.objectid')
1519
-			->from($this->dbObjectPropertiesTable, 'op')
1520
-			->andWhere($innerQuery->expr()->eq('op.calendarid',
1521
-				$outerQuery->createNamedParameter($calendarInfo['id'])))
1522
-			->andWhere($innerQuery->expr()->eq('op.calendartype',
1523
-				$outerQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1524
-
1525
-		// only return public items for shared calendars for now
1526
-		if ($calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1527
-			$innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
1528
-				$outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1529
-		}
1530
-
1531
-		$or = $innerQuery->expr()->orX();
1532
-		foreach($searchProperties as $searchProperty) {
1533
-			$or->add($innerQuery->expr()->eq('op.name',
1534
-				$outerQuery->createNamedParameter($searchProperty)));
1535
-		}
1536
-		$innerQuery->andWhere($or);
1537
-
1538
-		if ($pattern !== '') {
1539
-			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1540
-				$outerQuery->createNamedParameter('%' .
1541
-					$this->db->escapeLikeParameter($pattern) . '%')));
1542
-		}
1543
-
1544
-		$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1545
-			->from('calendarobjects', 'c');
1546
-
1547
-		if (isset($options['timerange'])) {
1548
-			if (isset($options['timerange']['start'])) {
1549
-				$outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
1550
-					$outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp)));
1551
-
1552
-			}
1553
-			if (isset($options['timerange']['end'])) {
1554
-				$outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
1555
-					$outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp)));
1556
-			}
1557
-		}
1558
-
1559
-		if (isset($options['types'])) {
1560
-			$or = $outerQuery->expr()->orX();
1561
-			foreach($options['types'] as $type) {
1562
-				$or->add($outerQuery->expr()->eq('componenttype',
1563
-					$outerQuery->createNamedParameter($type)));
1564
-			}
1565
-			$outerQuery->andWhere($or);
1566
-		}
1567
-
1568
-		$outerQuery->andWhere($outerQuery->expr()->in('c.id',
1569
-			$outerQuery->createFunction($innerQuery->getSQL())));
1570
-
1571
-		if ($offset) {
1572
-			$outerQuery->setFirstResult($offset);
1573
-		}
1574
-		if ($limit) {
1575
-			$outerQuery->setMaxResults($limit);
1576
-		}
1577
-
1578
-		$result = $outerQuery->execute();
1579
-		$calendarObjects = $result->fetchAll();
1580
-
1581
-		return array_map(function($o) {
1582
-			$calendarData = Reader::read($o['calendardata']);
1583
-			$comps = $calendarData->getComponents();
1584
-			$objects = [];
1585
-			$timezones = [];
1586
-			foreach($comps as $comp) {
1587
-				if ($comp instanceof VTimeZone) {
1588
-					$timezones[] = $comp;
1589
-				} else {
1590
-					$objects[] = $comp;
1591
-				}
1592
-			}
1593
-
1594
-			return [
1595
-				'id' => $o['id'],
1596
-				'type' => $o['componenttype'],
1597
-				'uid' => $o['uid'],
1598
-				'uri' => $o['uri'],
1599
-				'objects' => array_map(function($c) {
1600
-					return $this->transformSearchData($c);
1601
-				}, $objects),
1602
-				'timezones' => array_map(function($c) {
1603
-					return $this->transformSearchData($c);
1604
-				}, $timezones),
1605
-			];
1606
-		}, $calendarObjects);
1607
-	}
1608
-
1609
-	/**
1610
-	 * @param Component $comp
1611
-	 * @return array
1612
-	 */
1613
-	private function transformSearchData(Component $comp) {
1614
-		$data = [];
1615
-		/** @var Component[] $subComponents */
1616
-		$subComponents = $comp->getComponents();
1617
-		/** @var Property[] $properties */
1618
-		$properties = array_filter($comp->children(), function($c) {
1619
-			return $c instanceof Property;
1620
-		});
1621
-		$validationRules = $comp->getValidationRules();
1622
-
1623
-		foreach($subComponents as $subComponent) {
1624
-			$name = $subComponent->name;
1625
-			if (!isset($data[$name])) {
1626
-				$data[$name] = [];
1627
-			}
1628
-			$data[$name][] = $this->transformSearchData($subComponent);
1629
-		}
1630
-
1631
-		foreach($properties as $property) {
1632
-			$name = $property->name;
1633
-			if (!isset($validationRules[$name])) {
1634
-				$validationRules[$name] = '*';
1635
-			}
1636
-
1637
-			$rule = $validationRules[$property->name];
1638
-			if ($rule === '+' || $rule === '*') { // multiple
1639
-				if (!isset($data[$name])) {
1640
-					$data[$name] = [];
1641
-				}
1642
-
1643
-				$data[$name][] = $this->transformSearchProperty($property);
1644
-			} else { // once
1645
-				$data[$name] = $this->transformSearchProperty($property);
1646
-			}
1647
-		}
1648
-
1649
-		return $data;
1650
-	}
1651
-
1652
-	/**
1653
-	 * @param Property $prop
1654
-	 * @return array
1655
-	 */
1656
-	private function transformSearchProperty(Property $prop) {
1657
-		// No need to check Date, as it extends DateTime
1658
-		if ($prop instanceof Property\ICalendar\DateTime) {
1659
-			$value = $prop->getDateTime();
1660
-		} else {
1661
-			$value = $prop->getValue();
1662
-		}
1663
-
1664
-		return [
1665
-			$value,
1666
-			$prop->parameters()
1667
-		];
1668
-	}
1669
-
1670
-	/**
1671
-	 * Searches through all of a users calendars and calendar objects to find
1672
-	 * an object with a specific UID.
1673
-	 *
1674
-	 * This method should return the path to this object, relative to the
1675
-	 * calendar home, so this path usually only contains two parts:
1676
-	 *
1677
-	 * calendarpath/objectpath.ics
1678
-	 *
1679
-	 * If the uid is not found, return null.
1680
-	 *
1681
-	 * This method should only consider * objects that the principal owns, so
1682
-	 * any calendars owned by other principals that also appear in this
1683
-	 * collection should be ignored.
1684
-	 *
1685
-	 * @param string $principalUri
1686
-	 * @param string $uid
1687
-	 * @return string|null
1688
-	 */
1689
-	function getCalendarObjectByUID($principalUri, $uid) {
1690
-
1691
-		$query = $this->db->getQueryBuilder();
1692
-		$query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1693
-			->from('calendarobjects', 'co')
1694
-			->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1695
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1696
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)))
1697
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1698
-
1699
-		$stmt = $query->execute();
1700
-
1701
-		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1702
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1703
-		}
1704
-
1705
-		return null;
1706
-	}
1707
-
1708
-	/**
1709
-	 * The getChanges method returns all the changes that have happened, since
1710
-	 * the specified syncToken in the specified calendar.
1711
-	 *
1712
-	 * This function should return an array, such as the following:
1713
-	 *
1714
-	 * [
1715
-	 *   'syncToken' => 'The current synctoken',
1716
-	 *   'added'   => [
1717
-	 *      'new.txt',
1718
-	 *   ],
1719
-	 *   'modified'   => [
1720
-	 *      'modified.txt',
1721
-	 *   ],
1722
-	 *   'deleted' => [
1723
-	 *      'foo.php.bak',
1724
-	 *      'old.txt'
1725
-	 *   ]
1726
-	 * );
1727
-	 *
1728
-	 * The returned syncToken property should reflect the *current* syncToken
1729
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1730
-	 * property This is * needed here too, to ensure the operation is atomic.
1731
-	 *
1732
-	 * If the $syncToken argument is specified as null, this is an initial
1733
-	 * sync, and all members should be reported.
1734
-	 *
1735
-	 * The modified property is an array of nodenames that have changed since
1736
-	 * the last token.
1737
-	 *
1738
-	 * The deleted property is an array with nodenames, that have been deleted
1739
-	 * from collection.
1740
-	 *
1741
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
1742
-	 * 1, you only have to report changes that happened only directly in
1743
-	 * immediate descendants. If it's 2, it should also include changes from
1744
-	 * the nodes below the child collections. (grandchildren)
1745
-	 *
1746
-	 * The $limit argument allows a client to specify how many results should
1747
-	 * be returned at most. If the limit is not specified, it should be treated
1748
-	 * as infinite.
1749
-	 *
1750
-	 * If the limit (infinite or not) is higher than you're willing to return,
1751
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1752
-	 *
1753
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
1754
-	 * return null.
1755
-	 *
1756
-	 * The limit is 'suggestive'. You are free to ignore it.
1757
-	 *
1758
-	 * @param string $calendarId
1759
-	 * @param string $syncToken
1760
-	 * @param int $syncLevel
1761
-	 * @param int $limit
1762
-	 * @param int $calendarType
1763
-	 * @return array
1764
-	 */
1765
-	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1766
-		// Current synctoken
1767
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1768
-		$stmt->execute([ $calendarId ]);
1769
-		$currentToken = $stmt->fetchColumn(0);
1770
-
1771
-		if (is_null($currentToken)) {
1772
-			return null;
1773
-		}
1774
-
1775
-		$result = [
1776
-			'syncToken' => $currentToken,
1777
-			'added'     => [],
1778
-			'modified'  => [],
1779
-			'deleted'   => [],
1780
-		];
1781
-
1782
-		if ($syncToken) {
1783
-
1784
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? AND `calendartype` = ? ORDER BY `synctoken`";
1785
-			if ($limit>0) {
1786
-				$query.= " LIMIT " . (int)$limit;
1787
-			}
1788
-
1789
-			// Fetching all changes
1790
-			$stmt = $this->db->prepare($query);
1791
-			$stmt->execute([$syncToken, $currentToken, $calendarId, $calendarType]);
1792
-
1793
-			$changes = [];
1794
-
1795
-			// This loop ensures that any duplicates are overwritten, only the
1796
-			// last change on a node is relevant.
1797
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1798
-
1799
-				$changes[$row['uri']] = $row['operation'];
1800
-
1801
-			}
1802
-
1803
-			foreach($changes as $uri => $operation) {
1804
-
1805
-				switch($operation) {
1806
-					case 1 :
1807
-						$result['added'][] = $uri;
1808
-						break;
1809
-					case 2 :
1810
-						$result['modified'][] = $uri;
1811
-						break;
1812
-					case 3 :
1813
-						$result['deleted'][] = $uri;
1814
-						break;
1815
-				}
1816
-
1817
-			}
1818
-		} else {
1819
-			// No synctoken supplied, this is the initial sync.
1820
-			$query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?";
1821
-			$stmt = $this->db->prepare($query);
1822
-			$stmt->execute([$calendarId, $calendarType]);
1823
-
1824
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1825
-		}
1826
-		return $result;
1827
-
1828
-	}
1829
-
1830
-	/**
1831
-	 * Returns a list of subscriptions for a principal.
1832
-	 *
1833
-	 * Every subscription is an array with the following keys:
1834
-	 *  * id, a unique id that will be used by other functions to modify the
1835
-	 *    subscription. This can be the same as the uri or a database key.
1836
-	 *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1837
-	 *  * principaluri. The owner of the subscription. Almost always the same as
1838
-	 *    principalUri passed to this method.
1839
-	 *
1840
-	 * Furthermore, all the subscription info must be returned too:
1841
-	 *
1842
-	 * 1. {DAV:}displayname
1843
-	 * 2. {http://apple.com/ns/ical/}refreshrate
1844
-	 * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1845
-	 *    should not be stripped).
1846
-	 * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1847
-	 *    should not be stripped).
1848
-	 * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1849
-	 *    attachments should not be stripped).
1850
-	 * 6. {http://calendarserver.org/ns/}source (Must be a
1851
-	 *     Sabre\DAV\Property\Href).
1852
-	 * 7. {http://apple.com/ns/ical/}calendar-color
1853
-	 * 8. {http://apple.com/ns/ical/}calendar-order
1854
-	 * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1855
-	 *    (should just be an instance of
1856
-	 *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1857
-	 *    default components).
1858
-	 *
1859
-	 * @param string $principalUri
1860
-	 * @return array
1861
-	 */
1862
-	function getSubscriptionsForUser($principalUri) {
1863
-		$fields = array_values($this->subscriptionPropertyMap);
1864
-		$fields[] = 'id';
1865
-		$fields[] = 'uri';
1866
-		$fields[] = 'source';
1867
-		$fields[] = 'principaluri';
1868
-		$fields[] = 'lastmodified';
1869
-		$fields[] = 'synctoken';
1870
-
1871
-		$query = $this->db->getQueryBuilder();
1872
-		$query->select($fields)
1873
-			->from('calendarsubscriptions')
1874
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1875
-			->orderBy('calendarorder', 'asc');
1876
-		$stmt =$query->execute();
1877
-
1878
-		$subscriptions = [];
1879
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1880
-
1881
-			$subscription = [
1882
-				'id'           => $row['id'],
1883
-				'uri'          => $row['uri'],
1884
-				'principaluri' => $row['principaluri'],
1885
-				'source'       => $row['source'],
1886
-				'lastmodified' => $row['lastmodified'],
1887
-
1888
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1889
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
1890
-			];
1891
-
1892
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1893
-				if (!is_null($row[$dbName])) {
1894
-					$subscription[$xmlName] = $row[$dbName];
1895
-				}
1896
-			}
1897
-
1898
-			$subscriptions[] = $subscription;
1899
-
1900
-		}
1901
-
1902
-		return $subscriptions;
1903
-	}
1904
-
1905
-	/**
1906
-	 * Creates a new subscription for a principal.
1907
-	 *
1908
-	 * If the creation was a success, an id must be returned that can be used to reference
1909
-	 * this subscription in other methods, such as updateSubscription.
1910
-	 *
1911
-	 * @param string $principalUri
1912
-	 * @param string $uri
1913
-	 * @param array $properties
1914
-	 * @return mixed
1915
-	 */
1916
-	function createSubscription($principalUri, $uri, array $properties) {
1917
-
1918
-		if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1919
-			throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1920
-		}
1921
-
1922
-		$values = [
1923
-			'principaluri' => $principalUri,
1924
-			'uri'          => $uri,
1925
-			'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1926
-			'lastmodified' => time(),
1927
-		];
1928
-
1929
-		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1930
-
1931
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1932
-			if (array_key_exists($xmlName, $properties)) {
1933
-					$values[$dbName] = $properties[$xmlName];
1934
-					if (in_array($dbName, $propertiesBoolean)) {
1935
-						$values[$dbName] = true;
1936
-				}
1937
-			}
1938
-		}
1939
-
1940
-		$valuesToInsert = array();
1941
-
1942
-		$query = $this->db->getQueryBuilder();
1943
-
1944
-		foreach (array_keys($values) as $name) {
1945
-			$valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1946
-		}
1947
-
1948
-		$query->insert('calendarsubscriptions')
1949
-			->values($valuesToInsert)
1950
-			->execute();
1951
-
1952
-		$subscriptionId = $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1953
-
1954
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createSubscription', new GenericEvent(
1955
-			'\OCA\DAV\CalDAV\CalDavBackend::createSubscription',
1956
-			[
1957
-				'subscriptionId' => $subscriptionId,
1958
-				'subscriptionData' => $this->getSubscriptionById($subscriptionId),
1959
-			]));
1960
-
1961
-		return $subscriptionId;
1962
-	}
1963
-
1964
-	/**
1965
-	 * Updates a subscription
1966
-	 *
1967
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1968
-	 * To do the actual updates, you must tell this object which properties
1969
-	 * you're going to process with the handle() method.
1970
-	 *
1971
-	 * Calling the handle method is like telling the PropPatch object "I
1972
-	 * promise I can handle updating this property".
1973
-	 *
1974
-	 * Read the PropPatch documentation for more info and examples.
1975
-	 *
1976
-	 * @param mixed $subscriptionId
1977
-	 * @param PropPatch $propPatch
1978
-	 * @return void
1979
-	 */
1980
-	function updateSubscription($subscriptionId, PropPatch $propPatch) {
1981
-		$supportedProperties = array_keys($this->subscriptionPropertyMap);
1982
-		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
1983
-
1984
-		/**
1985
-		 * @suppress SqlInjectionChecker
1986
-		 */
1987
-		$propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1988
-
1989
-			$newValues = [];
1990
-
1991
-			foreach($mutations as $propertyName=>$propertyValue) {
1992
-				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1993
-					$newValues['source'] = $propertyValue->getHref();
1994
-				} else {
1995
-					$fieldName = $this->subscriptionPropertyMap[$propertyName];
1996
-					$newValues[$fieldName] = $propertyValue;
1997
-				}
1998
-			}
1999
-
2000
-			$query = $this->db->getQueryBuilder();
2001
-			$query->update('calendarsubscriptions')
2002
-				->set('lastmodified', $query->createNamedParameter(time()));
2003
-			foreach($newValues as $fieldName=>$value) {
2004
-				$query->set($fieldName, $query->createNamedParameter($value));
2005
-			}
2006
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2007
-				->execute();
2008
-
2009
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateSubscription', new GenericEvent(
2010
-				'\OCA\DAV\CalDAV\CalDavBackend::updateSubscription',
2011
-				[
2012
-					'subscriptionId' => $subscriptionId,
2013
-					'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2014
-					'propertyMutations' => $mutations,
2015
-				]));
2016
-
2017
-			return true;
2018
-
2019
-		});
2020
-	}
2021
-
2022
-	/**
2023
-	 * Deletes a subscription.
2024
-	 *
2025
-	 * @param mixed $subscriptionId
2026
-	 * @return void
2027
-	 */
2028
-	function deleteSubscription($subscriptionId) {
2029
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription', new GenericEvent(
2030
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription',
2031
-			[
2032
-				'subscriptionId' => $subscriptionId,
2033
-				'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2034
-			]));
2035
-
2036
-		$query = $this->db->getQueryBuilder();
2037
-		$query->delete('calendarsubscriptions')
2038
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2039
-			->execute();
2040
-
2041
-		$query = $this->db->getQueryBuilder();
2042
-		$query->delete('calendarobjects')
2043
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2044
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2045
-			->execute();
2046
-
2047
-		$query->delete('calendarchanges')
2048
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2049
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2050
-			->execute();
2051
-
2052
-		$query->delete($this->dbObjectPropertiesTable)
2053
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2054
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2055
-			->execute();
2056
-	}
2057
-
2058
-	/**
2059
-	 * Returns a single scheduling object for the inbox collection.
2060
-	 *
2061
-	 * The returned array should contain the following elements:
2062
-	 *   * uri - A unique basename for the object. This will be used to
2063
-	 *           construct a full uri.
2064
-	 *   * calendardata - The iCalendar object
2065
-	 *   * lastmodified - The last modification date. Can be an int for a unix
2066
-	 *                    timestamp, or a PHP DateTime object.
2067
-	 *   * etag - A unique token that must change if the object changed.
2068
-	 *   * size - The size of the object, in bytes.
2069
-	 *
2070
-	 * @param string $principalUri
2071
-	 * @param string $objectUri
2072
-	 * @return array
2073
-	 */
2074
-	function getSchedulingObject($principalUri, $objectUri) {
2075
-		$query = $this->db->getQueryBuilder();
2076
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2077
-			->from('schedulingobjects')
2078
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2079
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2080
-			->execute();
2081
-
2082
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
2083
-
2084
-		if(!$row) {
2085
-			return null;
2086
-		}
2087
-
2088
-		return [
2089
-				'uri'          => $row['uri'],
2090
-				'calendardata' => $row['calendardata'],
2091
-				'lastmodified' => $row['lastmodified'],
2092
-				'etag'         => '"' . $row['etag'] . '"',
2093
-				'size'         => (int)$row['size'],
2094
-		];
2095
-	}
2096
-
2097
-	/**
2098
-	 * Returns all scheduling objects for the inbox collection.
2099
-	 *
2100
-	 * These objects should be returned as an array. Every item in the array
2101
-	 * should follow the same structure as returned from getSchedulingObject.
2102
-	 *
2103
-	 * The main difference is that 'calendardata' is optional.
2104
-	 *
2105
-	 * @param string $principalUri
2106
-	 * @return array
2107
-	 */
2108
-	function getSchedulingObjects($principalUri) {
2109
-		$query = $this->db->getQueryBuilder();
2110
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2111
-				->from('schedulingobjects')
2112
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2113
-				->execute();
2114
-
2115
-		$result = [];
2116
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2117
-			$result[] = [
2118
-					'calendardata' => $row['calendardata'],
2119
-					'uri'          => $row['uri'],
2120
-					'lastmodified' => $row['lastmodified'],
2121
-					'etag'         => '"' . $row['etag'] . '"',
2122
-					'size'         => (int)$row['size'],
2123
-			];
2124
-		}
2125
-
2126
-		return $result;
2127
-	}
2128
-
2129
-	/**
2130
-	 * Deletes a scheduling object from the inbox collection.
2131
-	 *
2132
-	 * @param string $principalUri
2133
-	 * @param string $objectUri
2134
-	 * @return void
2135
-	 */
2136
-	function deleteSchedulingObject($principalUri, $objectUri) {
2137
-		$query = $this->db->getQueryBuilder();
2138
-		$query->delete('schedulingobjects')
2139
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2140
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2141
-				->execute();
2142
-	}
2143
-
2144
-	/**
2145
-	 * Creates a new scheduling object. This should land in a users' inbox.
2146
-	 *
2147
-	 * @param string $principalUri
2148
-	 * @param string $objectUri
2149
-	 * @param string $objectData
2150
-	 * @return void
2151
-	 */
2152
-	function createSchedulingObject($principalUri, $objectUri, $objectData) {
2153
-		$query = $this->db->getQueryBuilder();
2154
-		$query->insert('schedulingobjects')
2155
-			->values([
2156
-				'principaluri' => $query->createNamedParameter($principalUri),
2157
-				'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2158
-				'uri' => $query->createNamedParameter($objectUri),
2159
-				'lastmodified' => $query->createNamedParameter(time()),
2160
-				'etag' => $query->createNamedParameter(md5($objectData)),
2161
-				'size' => $query->createNamedParameter(strlen($objectData))
2162
-			])
2163
-			->execute();
2164
-	}
2165
-
2166
-	/**
2167
-	 * Adds a change record to the calendarchanges table.
2168
-	 *
2169
-	 * @param mixed $calendarId
2170
-	 * @param string $objectUri
2171
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete.
2172
-	 * @param int $calendarType
2173
-	 * @return void
2174
-	 */
2175
-	protected function addChange($calendarId, $objectUri, $operation, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2176
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2177
-
2178
-		$query = $this->db->getQueryBuilder();
2179
-		$query->select('synctoken')
2180
-			->from($table)
2181
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2182
-		$syncToken = (int)$query->execute()->fetchColumn();
2183
-
2184
-		$query = $this->db->getQueryBuilder();
2185
-		$query->insert('calendarchanges')
2186
-			->values([
2187
-				'uri' => $query->createNamedParameter($objectUri),
2188
-				'synctoken' => $query->createNamedParameter($syncToken),
2189
-				'calendarid' => $query->createNamedParameter($calendarId),
2190
-				'operation' => $query->createNamedParameter($operation),
2191
-				'calendartype' => $query->createNamedParameter($calendarType),
2192
-			])
2193
-			->execute();
2194
-
2195
-		$stmt = $this->db->prepare("UPDATE `*PREFIX*$table` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?");
2196
-		$stmt->execute([
2197
-			$calendarId
2198
-		]);
2199
-
2200
-	}
2201
-
2202
-	/**
2203
-	 * Parses some information from calendar objects, used for optimized
2204
-	 * calendar-queries.
2205
-	 *
2206
-	 * Returns an array with the following keys:
2207
-	 *   * etag - An md5 checksum of the object without the quotes.
2208
-	 *   * size - Size of the object in bytes
2209
-	 *   * componentType - VEVENT, VTODO or VJOURNAL
2210
-	 *   * firstOccurence
2211
-	 *   * lastOccurence
2212
-	 *   * uid - value of the UID property
2213
-	 *
2214
-	 * @param string $calendarData
2215
-	 * @return array
2216
-	 */
2217
-	public function getDenormalizedData($calendarData) {
2218
-
2219
-		$vObject = Reader::read($calendarData);
2220
-		$componentType = null;
2221
-		$component = null;
2222
-		$firstOccurrence = null;
2223
-		$lastOccurrence = null;
2224
-		$uid = null;
2225
-		$classification = self::CLASSIFICATION_PUBLIC;
2226
-		foreach($vObject->getComponents() as $component) {
2227
-			if ($component->name!=='VTIMEZONE') {
2228
-				$componentType = $component->name;
2229
-				$uid = (string)$component->UID;
2230
-				break;
2231
-			}
2232
-		}
2233
-		if (!$componentType) {
2234
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
2235
-		}
2236
-		if ($componentType === 'VEVENT' && $component->DTSTART) {
2237
-			$firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
2238
-			// Finding the last occurrence is a bit harder
2239
-			if (!isset($component->RRULE)) {
2240
-				if (isset($component->DTEND)) {
2241
-					$lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
2242
-				} elseif (isset($component->DURATION)) {
2243
-					$endDate = clone $component->DTSTART->getDateTime();
2244
-					$endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
2245
-					$lastOccurrence = $endDate->getTimeStamp();
2246
-				} elseif (!$component->DTSTART->hasTime()) {
2247
-					$endDate = clone $component->DTSTART->getDateTime();
2248
-					$endDate->modify('+1 day');
2249
-					$lastOccurrence = $endDate->getTimeStamp();
2250
-				} else {
2251
-					$lastOccurrence = $firstOccurrence;
2252
-				}
2253
-			} else {
2254
-				$it = new EventIterator($vObject, (string)$component->UID);
2255
-				$maxDate = new \DateTime(self::MAX_DATE);
2256
-				if ($it->isInfinite()) {
2257
-					$lastOccurrence = $maxDate->getTimestamp();
2258
-				} else {
2259
-					$end = $it->getDtEnd();
2260
-					while($it->valid() && $end < $maxDate) {
2261
-						$end = $it->getDtEnd();
2262
-						$it->next();
2263
-
2264
-					}
2265
-					$lastOccurrence = $end->getTimestamp();
2266
-				}
2267
-
2268
-			}
2269
-		}
2270
-
2271
-		if ($component->CLASS) {
2272
-			$classification = CalDavBackend::CLASSIFICATION_PRIVATE;
2273
-			switch ($component->CLASS->getValue()) {
2274
-				case 'PUBLIC':
2275
-					$classification = CalDavBackend::CLASSIFICATION_PUBLIC;
2276
-					break;
2277
-				case 'CONFIDENTIAL':
2278
-					$classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
2279
-					break;
2280
-			}
2281
-		}
2282
-		return [
2283
-			'etag' => md5($calendarData),
2284
-			'size' => strlen($calendarData),
2285
-			'componentType' => $componentType,
2286
-			'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
2287
-			'lastOccurence'  => $lastOccurrence,
2288
-			'uid' => $uid,
2289
-			'classification' => $classification
2290
-		];
2291
-
2292
-	}
2293
-
2294
-	/**
2295
-	 * @param $cardData
2296
-	 * @return bool|string
2297
-	 */
2298
-	private function readBlob($cardData) {
2299
-		if (is_resource($cardData)) {
2300
-			return stream_get_contents($cardData);
2301
-		}
2302
-
2303
-		return $cardData;
2304
-	}
2305
-
2306
-	/**
2307
-	 * @param IShareable $shareable
2308
-	 * @param array $add
2309
-	 * @param array $remove
2310
-	 */
2311
-	public function updateShares($shareable, $add, $remove) {
2312
-		$calendarId = $shareable->getResourceId();
2313
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
2314
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2315
-			[
2316
-				'calendarId' => $calendarId,
2317
-				'calendarData' => $this->getCalendarById($calendarId),
2318
-				'shares' => $this->getShares($calendarId),
2319
-				'add' => $add,
2320
-				'remove' => $remove,
2321
-			]));
2322
-		$this->calendarSharingBackend->updateShares($shareable, $add, $remove);
2323
-	}
2324
-
2325
-	/**
2326
-	 * @param int $resourceId
2327
-	 * @param int $calendarType
2328
-	 * @return array
2329
-	 */
2330
-	public function getShares($resourceId, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2331
-		return $this->calendarSharingBackend->getShares($resourceId);
2332
-	}
2333
-
2334
-	/**
2335
-	 * @param boolean $value
2336
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
2337
-	 * @return string|null
2338
-	 */
2339
-	public function setPublishStatus($value, $calendar) {
2340
-
2341
-		$calendarId = $calendar->getResourceId();
2342
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', new GenericEvent(
2343
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2344
-			[
2345
-				'calendarId' => $calendarId,
2346
-				'calendarData' => $this->getCalendarById($calendarId),
2347
-				'public' => $value,
2348
-			]));
2349
-
2350
-		$query = $this->db->getQueryBuilder();
2351
-		if ($value) {
2352
-			$publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
2353
-			$query->insert('dav_shares')
2354
-				->values([
2355
-					'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
2356
-					'type' => $query->createNamedParameter('calendar'),
2357
-					'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
2358
-					'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
2359
-					'publicuri' => $query->createNamedParameter($publicUri)
2360
-				]);
2361
-			$query->execute();
2362
-			return $publicUri;
2363
-		}
2364
-		$query->delete('dav_shares')
2365
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2366
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
2367
-		$query->execute();
2368
-		return null;
2369
-	}
2370
-
2371
-	/**
2372
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
2373
-	 * @return mixed
2374
-	 */
2375
-	public function getPublishStatus($calendar) {
2376
-		$query = $this->db->getQueryBuilder();
2377
-		$result = $query->select('publicuri')
2378
-			->from('dav_shares')
2379
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2380
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
2381
-			->execute();
2382
-
2383
-		$row = $result->fetch();
2384
-		$result->closeCursor();
2385
-		return $row ? reset($row) : false;
2386
-	}
2387
-
2388
-	/**
2389
-	 * @param int $resourceId
2390
-	 * @param array $acl
2391
-	 * @return array
2392
-	 */
2393
-	public function applyShareAcl($resourceId, $acl) {
2394
-		return $this->calendarSharingBackend->applyShareAcl($resourceId, $acl);
2395
-	}
2396
-
2397
-
2398
-
2399
-	/**
2400
-	 * update properties table
2401
-	 *
2402
-	 * @param int $calendarId
2403
-	 * @param string $objectUri
2404
-	 * @param string $calendarData
2405
-	 * @param int $calendarType
2406
-	 */
2407
-	public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2408
-		$objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
2409
-
2410
-		try {
2411
-			$vCalendar = $this->readCalendarData($calendarData);
2412
-		} catch (\Exception $ex) {
2413
-			return;
2414
-		}
2415
-
2416
-		$this->purgeProperties($calendarId, $objectId);
2417
-
2418
-		$query = $this->db->getQueryBuilder();
2419
-		$query->insert($this->dbObjectPropertiesTable)
2420
-			->values(
2421
-				[
2422
-					'calendarid' => $query->createNamedParameter($calendarId),
2423
-					'calendartype' => $query->createNamedParameter($calendarType),
2424
-					'objectid' => $query->createNamedParameter($objectId),
2425
-					'name' => $query->createParameter('name'),
2426
-					'parameter' => $query->createParameter('parameter'),
2427
-					'value' => $query->createParameter('value'),
2428
-				]
2429
-			);
2430
-
2431
-		$indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2432
-		foreach ($vCalendar->getComponents() as $component) {
2433
-			if (!in_array($component->name, $indexComponents)) {
2434
-				continue;
2435
-			}
2436
-
2437
-			foreach ($component->children() as $property) {
2438
-				if (in_array($property->name, self::$indexProperties)) {
2439
-					$value = $property->getValue();
2440
-					// is this a shitty db?
2441
-					if (!$this->db->supports4ByteText()) {
2442
-						$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2443
-					}
2444
-					$value = mb_substr($value, 0, 254);
2445
-
2446
-					$query->setParameter('name', $property->name);
2447
-					$query->setParameter('parameter', null);
2448
-					$query->setParameter('value', $value);
2449
-					$query->execute();
2450
-				}
2451
-
2452
-				if (array_key_exists($property->name, self::$indexParameters)) {
2453
-					$parameters = $property->parameters();
2454
-					$indexedParametersForProperty = self::$indexParameters[$property->name];
2455
-
2456
-					foreach ($parameters as $key => $value) {
2457
-						if (in_array($key, $indexedParametersForProperty)) {
2458
-							// is this a shitty db?
2459
-							if ($this->db->supports4ByteText()) {
2460
-								$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2461
-							}
2462
-							$value = mb_substr($value, 0, 254);
2463
-
2464
-							$query->setParameter('name', $property->name);
2465
-							$query->setParameter('parameter', substr($key, 0, 254));
2466
-							$query->setParameter('value', substr($value, 0, 254));
2467
-							$query->execute();
2468
-						}
2469
-					}
2470
-				}
2471
-			}
2472
-		}
2473
-	}
2474
-
2475
-	/**
2476
-	 * deletes all birthday calendars
2477
-	 */
2478
-	public function deleteAllBirthdayCalendars() {
2479
-		$query = $this->db->getQueryBuilder();
2480
-		$result = $query->select(['id'])->from('calendars')
2481
-			->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
2482
-			->execute();
2483
-
2484
-		$ids = $result->fetchAll();
2485
-		foreach($ids as $id) {
2486
-			$this->deleteCalendar($id['id']);
2487
-		}
2488
-	}
2489
-
2490
-	/**
2491
-	 * @param $subscriptionId
2492
-	 */
2493
-	public function purgeAllCachedEventsForSubscription($subscriptionId) {
2494
-		$query = $this->db->getQueryBuilder();
2495
-		$query->select('uri')
2496
-			->from('calendarobjects')
2497
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2498
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
2499
-		$stmt = $query->execute();
2500
-
2501
-		$uris = [];
2502
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2503
-			$uris[] = $row['uri'];
2504
-		}
2505
-		$stmt->closeCursor();
2506
-
2507
-		$query = $this->db->getQueryBuilder();
2508
-		$query->delete('calendarobjects')
2509
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2510
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2511
-			->execute();
2512
-
2513
-		$query->delete('calendarchanges')
2514
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2515
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2516
-			->execute();
2517
-
2518
-		$query->delete($this->dbObjectPropertiesTable)
2519
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2520
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2521
-			->execute();
2522
-
2523
-		foreach($uris as $uri) {
2524
-			$this->addChange($subscriptionId, $uri, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
2525
-		}
2526
-	}
2527
-
2528
-	/**
2529
-	 * Move a calendar from one user to another
2530
-	 *
2531
-	 * @param string $uriName
2532
-	 * @param string $uriOrigin
2533
-	 * @param string $uriDestination
2534
-	 */
2535
-	public function moveCalendar($uriName, $uriOrigin, $uriDestination)
2536
-	{
2537
-		$query = $this->db->getQueryBuilder();
2538
-		$query->update('calendars')
2539
-			->set('principaluri', $query->createNamedParameter($uriDestination))
2540
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
2541
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
2542
-			->execute();
2543
-	}
2544
-
2545
-	/**
2546
-	 * read VCalendar data into a VCalendar object
2547
-	 *
2548
-	 * @param string $objectData
2549
-	 * @return VCalendar
2550
-	 */
2551
-	protected function readCalendarData($objectData) {
2552
-		return Reader::read($objectData);
2553
-	}
2554
-
2555
-	/**
2556
-	 * delete all properties from a given calendar object
2557
-	 *
2558
-	 * @param int $calendarId
2559
-	 * @param int $objectId
2560
-	 */
2561
-	protected function purgeProperties($calendarId, $objectId) {
2562
-		$query = $this->db->getQueryBuilder();
2563
-		$query->delete($this->dbObjectPropertiesTable)
2564
-			->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
2565
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2566
-		$query->execute();
2567
-	}
2568
-
2569
-	/**
2570
-	 * get ID from a given calendar object
2571
-	 *
2572
-	 * @param int $calendarId
2573
-	 * @param string $uri
2574
-	 * @param int $calendarType
2575
-	 * @return int
2576
-	 */
2577
-	protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
2578
-		$query = $this->db->getQueryBuilder();
2579
-		$query->select('id')
2580
-			->from('calendarobjects')
2581
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2582
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
2583
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
2584
-
2585
-		$result = $query->execute();
2586
-		$objectIds = $result->fetch();
2587
-		$result->closeCursor();
2588
-
2589
-		if (!isset($objectIds['id'])) {
2590
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2591
-		}
2592
-
2593
-		return (int)$objectIds['id'];
2594
-	}
2595
-
2596
-	/**
2597
-	 * return legacy endpoint principal name to new principal name
2598
-	 *
2599
-	 * @param $principalUri
2600
-	 * @param $toV2
2601
-	 * @return string
2602
-	 */
2603
-	private function convertPrincipal($principalUri, $toV2) {
2604
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2605
-			list(, $name) = Uri\split($principalUri);
2606
-			if ($toV2 === true) {
2607
-				return "principals/users/$name";
2608
-			}
2609
-			return "principals/$name";
2610
-		}
2611
-		return $principalUri;
2612
-	}
2613
-
2614
-	/**
2615
-	 * adds information about an owner to the calendar data
2616
-	 *
2617
-	 * @param $calendarInfo
2618
-	 */
2619
-	private function addOwnerPrincipal(&$calendarInfo) {
2620
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2621
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2622
-		if (isset($calendarInfo[$ownerPrincipalKey])) {
2623
-			$uri = $calendarInfo[$ownerPrincipalKey];
2624
-		} else {
2625
-			$uri = $calendarInfo['principaluri'];
2626
-		}
2627
-
2628
-		$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
2629
-		if (isset($principalInformation['{DAV:}displayname'])) {
2630
-			$calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
2631
-		}
2632
-	}
449
+    /**
450
+     * @return array
451
+     */
452
+    public function getPublicCalendars() {
453
+        $fields = array_values($this->propertyMap);
454
+        $fields[] = 'a.id';
455
+        $fields[] = 'a.uri';
456
+        $fields[] = 'a.synctoken';
457
+        $fields[] = 'a.components';
458
+        $fields[] = 'a.principaluri';
459
+        $fields[] = 'a.transparent';
460
+        $fields[] = 's.access';
461
+        $fields[] = 's.publicuri';
462
+        $calendars = [];
463
+        $query = $this->db->getQueryBuilder();
464
+        $result = $query->select($fields)
465
+            ->from('dav_shares', 's')
466
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
467
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
468
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
469
+            ->execute();
470
+
471
+        while($row = $result->fetch()) {
472
+            list(, $name) = Uri\split($row['principaluri']);
473
+            $row['displayname'] = $row['displayname'] . "($name)";
474
+            $components = [];
475
+            if ($row['components']) {
476
+                $components = explode(',',$row['components']);
477
+            }
478
+            $calendar = [
479
+                'id' => $row['id'],
480
+                'uri' => $row['publicuri'],
481
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
482
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
483
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
484
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
485
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
486
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
487
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
488
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
489
+            ];
490
+
491
+            foreach($this->propertyMap as $xmlName=>$dbName) {
492
+                $calendar[$xmlName] = $row[$dbName];
493
+            }
494
+
495
+            $this->addOwnerPrincipal($calendar);
496
+
497
+            if (!isset($calendars[$calendar['id']])) {
498
+                $calendars[$calendar['id']] = $calendar;
499
+            }
500
+        }
501
+        $result->closeCursor();
502
+
503
+        return array_values($calendars);
504
+    }
505
+
506
+    /**
507
+     * @param string $uri
508
+     * @return array
509
+     * @throws NotFound
510
+     */
511
+    public function getPublicCalendar($uri) {
512
+        $fields = array_values($this->propertyMap);
513
+        $fields[] = 'a.id';
514
+        $fields[] = 'a.uri';
515
+        $fields[] = 'a.synctoken';
516
+        $fields[] = 'a.components';
517
+        $fields[] = 'a.principaluri';
518
+        $fields[] = 'a.transparent';
519
+        $fields[] = 's.access';
520
+        $fields[] = 's.publicuri';
521
+        $query = $this->db->getQueryBuilder();
522
+        $result = $query->select($fields)
523
+            ->from('dav_shares', 's')
524
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
525
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
526
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
527
+            ->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
528
+            ->execute();
529
+
530
+        $row = $result->fetch(\PDO::FETCH_ASSOC);
531
+
532
+        $result->closeCursor();
533
+
534
+        if ($row === false) {
535
+            throw new NotFound('Node with name \'' . $uri . '\' could not be found');
536
+        }
537
+
538
+        list(, $name) = Uri\split($row['principaluri']);
539
+        $row['displayname'] = $row['displayname'] . ' ' . "($name)";
540
+        $components = [];
541
+        if ($row['components']) {
542
+            $components = explode(',',$row['components']);
543
+        }
544
+        $calendar = [
545
+            'id' => $row['id'],
546
+            'uri' => $row['publicuri'],
547
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
548
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
549
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
550
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
551
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
552
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
553
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
554
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
555
+        ];
556
+
557
+        foreach($this->propertyMap as $xmlName=>$dbName) {
558
+            $calendar[$xmlName] = $row[$dbName];
559
+        }
560
+
561
+        $this->addOwnerPrincipal($calendar);
562
+
563
+        return $calendar;
564
+
565
+    }
566
+
567
+    /**
568
+     * @param string $principal
569
+     * @param string $uri
570
+     * @return array|null
571
+     */
572
+    public function getCalendarByUri($principal, $uri) {
573
+        $fields = array_values($this->propertyMap);
574
+        $fields[] = 'id';
575
+        $fields[] = 'uri';
576
+        $fields[] = 'synctoken';
577
+        $fields[] = 'components';
578
+        $fields[] = 'principaluri';
579
+        $fields[] = 'transparent';
580
+
581
+        // Making fields a comma-delimited list
582
+        $query = $this->db->getQueryBuilder();
583
+        $query->select($fields)->from('calendars')
584
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
585
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
586
+            ->setMaxResults(1);
587
+        $stmt = $query->execute();
588
+
589
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
590
+        $stmt->closeCursor();
591
+        if ($row === false) {
592
+            return null;
593
+        }
594
+
595
+        $components = [];
596
+        if ($row['components']) {
597
+            $components = explode(',',$row['components']);
598
+        }
599
+
600
+        $calendar = [
601
+            'id' => $row['id'],
602
+            'uri' => $row['uri'],
603
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
604
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
605
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
606
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
607
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
608
+        ];
609
+
610
+        foreach($this->propertyMap as $xmlName=>$dbName) {
611
+            $calendar[$xmlName] = $row[$dbName];
612
+        }
613
+
614
+        $this->addOwnerPrincipal($calendar);
615
+
616
+        return $calendar;
617
+    }
618
+
619
+    /**
620
+     * @param $calendarId
621
+     * @return array|null
622
+     */
623
+    public function getCalendarById($calendarId) {
624
+        $fields = array_values($this->propertyMap);
625
+        $fields[] = 'id';
626
+        $fields[] = 'uri';
627
+        $fields[] = 'synctoken';
628
+        $fields[] = 'components';
629
+        $fields[] = 'principaluri';
630
+        $fields[] = 'transparent';
631
+
632
+        // Making fields a comma-delimited list
633
+        $query = $this->db->getQueryBuilder();
634
+        $query->select($fields)->from('calendars')
635
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
636
+            ->setMaxResults(1);
637
+        $stmt = $query->execute();
638
+
639
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
640
+        $stmt->closeCursor();
641
+        if ($row === false) {
642
+            return null;
643
+        }
644
+
645
+        $components = [];
646
+        if ($row['components']) {
647
+            $components = explode(',',$row['components']);
648
+        }
649
+
650
+        $calendar = [
651
+            'id' => $row['id'],
652
+            'uri' => $row['uri'],
653
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
654
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
655
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
656
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
657
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
658
+        ];
659
+
660
+        foreach($this->propertyMap as $xmlName=>$dbName) {
661
+            $calendar[$xmlName] = $row[$dbName];
662
+        }
663
+
664
+        $this->addOwnerPrincipal($calendar);
665
+
666
+        return $calendar;
667
+    }
668
+
669
+    /**
670
+     * @param $subscriptionId
671
+     */
672
+    public function getSubscriptionById($subscriptionId) {
673
+        $fields = array_values($this->subscriptionPropertyMap);
674
+        $fields[] = 'id';
675
+        $fields[] = 'uri';
676
+        $fields[] = 'source';
677
+        $fields[] = 'synctoken';
678
+        $fields[] = 'principaluri';
679
+        $fields[] = 'lastmodified';
680
+
681
+        $query = $this->db->getQueryBuilder();
682
+        $query->select($fields)
683
+            ->from('calendarsubscriptions')
684
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
685
+            ->orderBy('calendarorder', 'asc');
686
+        $stmt =$query->execute();
687
+
688
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
689
+        $stmt->closeCursor();
690
+        if ($row === false) {
691
+            return null;
692
+        }
693
+
694
+        $subscription = [
695
+            'id'           => $row['id'],
696
+            'uri'          => $row['uri'],
697
+            'principaluri' => $row['principaluri'],
698
+            'source'       => $row['source'],
699
+            'lastmodified' => $row['lastmodified'],
700
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
701
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
702
+        ];
703
+
704
+        foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
705
+            if (!is_null($row[$dbName])) {
706
+                $subscription[$xmlName] = $row[$dbName];
707
+            }
708
+        }
709
+
710
+        return $subscription;
711
+    }
712
+
713
+    /**
714
+     * Creates a new calendar for a principal.
715
+     *
716
+     * If the creation was a success, an id must be returned that can be used to reference
717
+     * this calendar in other methods, such as updateCalendar.
718
+     *
719
+     * @param string $principalUri
720
+     * @param string $calendarUri
721
+     * @param array $properties
722
+     * @return int
723
+     * @suppress SqlInjectionChecker
724
+     */
725
+    function createCalendar($principalUri, $calendarUri, array $properties) {
726
+        $values = [
727
+            'principaluri' => $this->convertPrincipal($principalUri, true),
728
+            'uri'          => $calendarUri,
729
+            'synctoken'    => 1,
730
+            'transparent'  => 0,
731
+            'components'   => 'VEVENT,VTODO',
732
+            'displayname'  => $calendarUri
733
+        ];
734
+
735
+        // Default value
736
+        $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
737
+        if (isset($properties[$sccs])) {
738
+            if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
739
+                throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
740
+            }
741
+            $values['components'] = implode(',',$properties[$sccs]->getValue());
742
+        }
743
+        $transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
744
+        if (isset($properties[$transp])) {
745
+            $values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
746
+        }
747
+
748
+        foreach($this->propertyMap as $xmlName=>$dbName) {
749
+            if (isset($properties[$xmlName])) {
750
+                $values[$dbName] = $properties[$xmlName];
751
+            }
752
+        }
753
+
754
+        $query = $this->db->getQueryBuilder();
755
+        $query->insert('calendars');
756
+        foreach($values as $column => $value) {
757
+            $query->setValue($column, $query->createNamedParameter($value));
758
+        }
759
+        $query->execute();
760
+        $calendarId = $query->getLastInsertId();
761
+
762
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
763
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
764
+            [
765
+                'calendarId' => $calendarId,
766
+                'calendarData' => $this->getCalendarById($calendarId),
767
+        ]));
768
+
769
+        return $calendarId;
770
+    }
771
+
772
+    /**
773
+     * Updates properties for a calendar.
774
+     *
775
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
776
+     * To do the actual updates, you must tell this object which properties
777
+     * you're going to process with the handle() method.
778
+     *
779
+     * Calling the handle method is like telling the PropPatch object "I
780
+     * promise I can handle updating this property".
781
+     *
782
+     * Read the PropPatch documentation for more info and examples.
783
+     *
784
+     * @param mixed $calendarId
785
+     * @param PropPatch $propPatch
786
+     * @return void
787
+     */
788
+    function updateCalendar($calendarId, PropPatch $propPatch) {
789
+        $supportedProperties = array_keys($this->propertyMap);
790
+        $supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
791
+
792
+        /**
793
+         * @suppress SqlInjectionChecker
794
+         */
795
+        $propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
796
+            $newValues = [];
797
+            foreach ($mutations as $propertyName => $propertyValue) {
798
+
799
+                switch ($propertyName) {
800
+                    case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
801
+                        $fieldName = 'transparent';
802
+                        $newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
803
+                        break;
804
+                    default :
805
+                        $fieldName = $this->propertyMap[$propertyName];
806
+                        $newValues[$fieldName] = $propertyValue;
807
+                        break;
808
+                }
809
+
810
+            }
811
+            $query = $this->db->getQueryBuilder();
812
+            $query->update('calendars');
813
+            foreach ($newValues as $fieldName => $value) {
814
+                $query->set($fieldName, $query->createNamedParameter($value));
815
+            }
816
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
817
+            $query->execute();
818
+
819
+            $this->addChange($calendarId, "", 2);
820
+
821
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
822
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
823
+                [
824
+                    'calendarId' => $calendarId,
825
+                    'calendarData' => $this->getCalendarById($calendarId),
826
+                    'shares' => $this->getShares($calendarId),
827
+                    'propertyMutations' => $mutations,
828
+            ]));
829
+
830
+            return true;
831
+        });
832
+    }
833
+
834
+    /**
835
+     * Delete a calendar and all it's objects
836
+     *
837
+     * @param mixed $calendarId
838
+     * @return void
839
+     */
840
+    function deleteCalendar($calendarId) {
841
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
842
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
843
+            [
844
+                'calendarId' => $calendarId,
845
+                'calendarData' => $this->getCalendarById($calendarId),
846
+                'shares' => $this->getShares($calendarId),
847
+        ]));
848
+
849
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?');
850
+        $stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
851
+
852
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
853
+        $stmt->execute([$calendarId]);
854
+
855
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ? AND `calendartype` = ?');
856
+        $stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
857
+
858
+        $this->calendarSharingBackend->deleteAllShares($calendarId);
859
+
860
+        $query = $this->db->getQueryBuilder();
861
+        $query->delete($this->dbObjectPropertiesTable)
862
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
863
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
864
+            ->execute();
865
+    }
866
+
867
+    /**
868
+     * Delete all of an user's shares
869
+     *
870
+     * @param string $principaluri
871
+     * @return void
872
+     */
873
+    function deleteAllSharesByUser($principaluri) {
874
+        $this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
875
+    }
876
+
877
+    /**
878
+     * Returns all calendar objects within a calendar.
879
+     *
880
+     * Every item contains an array with the following keys:
881
+     *   * calendardata - The iCalendar-compatible calendar data
882
+     *   * uri - a unique key which will be used to construct the uri. This can
883
+     *     be any arbitrary string, but making sure it ends with '.ics' is a
884
+     *     good idea. This is only the basename, or filename, not the full
885
+     *     path.
886
+     *   * lastmodified - a timestamp of the last modification time
887
+     *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
888
+     *   '"abcdef"')
889
+     *   * size - The size of the calendar objects, in bytes.
890
+     *   * component - optional, a string containing the type of object, such
891
+     *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
892
+     *     the Content-Type header.
893
+     *
894
+     * Note that the etag is optional, but it's highly encouraged to return for
895
+     * speed reasons.
896
+     *
897
+     * The calendardata is also optional. If it's not returned
898
+     * 'getCalendarObject' will be called later, which *is* expected to return
899
+     * calendardata.
900
+     *
901
+     * If neither etag or size are specified, the calendardata will be
902
+     * used/fetched to determine these numbers. If both are specified the
903
+     * amount of times this is needed is reduced by a great degree.
904
+     *
905
+     * @param mixed $id
906
+     * @param int $calendarType
907
+     * @return array
908
+     */
909
+    public function getCalendarObjects($id, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
910
+        $query = $this->db->getQueryBuilder();
911
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
912
+            ->from('calendarobjects')
913
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
914
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
915
+        $stmt = $query->execute();
916
+
917
+        $result = [];
918
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
919
+            $result[] = [
920
+                'id'           => $row['id'],
921
+                'uri'          => $row['uri'],
922
+                'lastmodified' => $row['lastmodified'],
923
+                'etag'         => '"' . $row['etag'] . '"',
924
+                'calendarid'   => $row['calendarid'],
925
+                'size'         => (int)$row['size'],
926
+                'component'    => strtolower($row['componenttype']),
927
+                'classification'=> (int)$row['classification']
928
+            ];
929
+        }
930
+
931
+        return $result;
932
+    }
933
+
934
+    /**
935
+     * Returns information from a single calendar object, based on it's object
936
+     * uri.
937
+     *
938
+     * The object uri is only the basename, or filename and not a full path.
939
+     *
940
+     * The returned array must have the same keys as getCalendarObjects. The
941
+     * 'calendardata' object is required here though, while it's not required
942
+     * for getCalendarObjects.
943
+     *
944
+     * This method must return null if the object did not exist.
945
+     *
946
+     * @param mixed $id
947
+     * @param string $objectUri
948
+     * @param int $calendarType
949
+     * @return array|null
950
+     */
951
+    public function getCalendarObject($id, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
952
+        $query = $this->db->getQueryBuilder();
953
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
954
+            ->from('calendarobjects')
955
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
956
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
957
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
958
+        $stmt = $query->execute();
959
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
960
+
961
+        if(!$row) {
962
+            return null;
963
+        }
964
+
965
+        return [
966
+            'id'            => $row['id'],
967
+            'uri'           => $row['uri'],
968
+            'lastmodified'  => $row['lastmodified'],
969
+            'etag'          => '"' . $row['etag'] . '"',
970
+            'calendarid'    => $row['calendarid'],
971
+            'size'          => (int)$row['size'],
972
+            'calendardata'  => $this->readBlob($row['calendardata']),
973
+            'component'     => strtolower($row['componenttype']),
974
+            'classification'=> (int)$row['classification']
975
+        ];
976
+    }
977
+
978
+    /**
979
+     * Returns a list of calendar objects.
980
+     *
981
+     * This method should work identical to getCalendarObject, but instead
982
+     * return all the calendar objects in the list as an array.
983
+     *
984
+     * If the backend supports this, it may allow for some speed-ups.
985
+     *
986
+     * @param mixed $calendarId
987
+     * @param string[] $uris
988
+     * @param int $calendarType
989
+     * @return array
990
+     */
991
+    public function getMultipleCalendarObjects($id, array $uris, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
992
+        if (empty($uris)) {
993
+            return [];
994
+        }
995
+
996
+        $chunks = array_chunk($uris, 100);
997
+        $objects = [];
998
+
999
+        $query = $this->db->getQueryBuilder();
1000
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1001
+            ->from('calendarobjects')
1002
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
1003
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1004
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1005
+
1006
+        foreach ($chunks as $uris) {
1007
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1008
+            $result = $query->execute();
1009
+
1010
+            while ($row = $result->fetch()) {
1011
+                $objects[] = [
1012
+                    'id'           => $row['id'],
1013
+                    'uri'          => $row['uri'],
1014
+                    'lastmodified' => $row['lastmodified'],
1015
+                    'etag'         => '"' . $row['etag'] . '"',
1016
+                    'calendarid'   => $row['calendarid'],
1017
+                    'size'         => (int)$row['size'],
1018
+                    'calendardata' => $this->readBlob($row['calendardata']),
1019
+                    'component'    => strtolower($row['componenttype']),
1020
+                    'classification' => (int)$row['classification']
1021
+                ];
1022
+            }
1023
+            $result->closeCursor();
1024
+        }
1025
+
1026
+        return $objects;
1027
+    }
1028
+
1029
+    /**
1030
+     * Creates a new calendar object.
1031
+     *
1032
+     * The object uri is only the basename, or filename and not a full path.
1033
+     *
1034
+     * It is possible return an etag from this function, which will be used in
1035
+     * the response to this PUT request. Note that the ETag must be surrounded
1036
+     * by double-quotes.
1037
+     *
1038
+     * However, you should only really return this ETag if you don't mangle the
1039
+     * calendar-data. If the result of a subsequent GET to this object is not
1040
+     * the exact same as this request body, you should omit the ETag.
1041
+     *
1042
+     * @param mixed $calendarId
1043
+     * @param string $objectUri
1044
+     * @param string $calendarData
1045
+     * @param int $calendarType
1046
+     * @return string
1047
+     */
1048
+    function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1049
+        $extraData = $this->getDenormalizedData($calendarData);
1050
+
1051
+        $q = $this->db->getQueryBuilder();
1052
+        $q->select($q->func()->count('*'))
1053
+            ->from('calendarobjects')
1054
+            ->where($q->expr()->eq('calendarid', $q->createNamedParameter($calendarId)))
1055
+            ->andWhere($q->expr()->eq('uid', $q->createNamedParameter($extraData['uid'])))
1056
+            ->andWhere($q->expr()->eq('calendartype', $q->createNamedParameter($calendarType)));
1057
+
1058
+        $result = $q->execute();
1059
+        $count = (int) $result->fetchColumn();
1060
+        $result->closeCursor();
1061
+
1062
+        if ($count !== 0) {
1063
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar object with uid already exists in this calendar collection.');
1064
+        }
1065
+
1066
+        $query = $this->db->getQueryBuilder();
1067
+        $query->insert('calendarobjects')
1068
+            ->values([
1069
+                'calendarid' => $query->createNamedParameter($calendarId),
1070
+                'uri' => $query->createNamedParameter($objectUri),
1071
+                'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1072
+                'lastmodified' => $query->createNamedParameter(time()),
1073
+                'etag' => $query->createNamedParameter($extraData['etag']),
1074
+                'size' => $query->createNamedParameter($extraData['size']),
1075
+                'componenttype' => $query->createNamedParameter($extraData['componentType']),
1076
+                'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1077
+                'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1078
+                'classification' => $query->createNamedParameter($extraData['classification']),
1079
+                'uid' => $query->createNamedParameter($extraData['uid']),
1080
+                'calendartype' => $query->createNamedParameter($calendarType),
1081
+            ])
1082
+            ->execute();
1083
+
1084
+        $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1085
+
1086
+        if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1087
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
1088
+                '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
1089
+                [
1090
+                    'calendarId' => $calendarId,
1091
+                    'calendarData' => $this->getCalendarById($calendarId),
1092
+                    'shares' => $this->getShares($calendarId),
1093
+                    'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1094
+                ]
1095
+            ));
1096
+        } else {
1097
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject', new GenericEvent(
1098
+                '\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject',
1099
+                [
1100
+                    'subscriptionId' => $calendarId,
1101
+                    'calendarData' => $this->getCalendarById($calendarId),
1102
+                    'shares' => $this->getShares($calendarId),
1103
+                    'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1104
+                ]
1105
+            ));
1106
+        }
1107
+        $this->addChange($calendarId, $objectUri, 1, $calendarType);
1108
+
1109
+        return '"' . $extraData['etag'] . '"';
1110
+    }
1111
+
1112
+    /**
1113
+     * Updates an existing calendarobject, based on it's uri.
1114
+     *
1115
+     * The object uri is only the basename, or filename and not a full path.
1116
+     *
1117
+     * It is possible return an etag from this function, which will be used in
1118
+     * the response to this PUT request. Note that the ETag must be surrounded
1119
+     * by double-quotes.
1120
+     *
1121
+     * However, you should only really return this ETag if you don't mangle the
1122
+     * calendar-data. If the result of a subsequent GET to this object is not
1123
+     * the exact same as this request body, you should omit the ETag.
1124
+     *
1125
+     * @param mixed $calendarId
1126
+     * @param string $objectUri
1127
+     * @param string $calendarData
1128
+     * @param int $calendarType
1129
+     * @return string
1130
+     */
1131
+    function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1132
+        $extraData = $this->getDenormalizedData($calendarData);
1133
+
1134
+        $query = $this->db->getQueryBuilder();
1135
+        $query->update('calendarobjects')
1136
+                ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1137
+                ->set('lastmodified', $query->createNamedParameter(time()))
1138
+                ->set('etag', $query->createNamedParameter($extraData['etag']))
1139
+                ->set('size', $query->createNamedParameter($extraData['size']))
1140
+                ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1141
+                ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1142
+                ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1143
+                ->set('classification', $query->createNamedParameter($extraData['classification']))
1144
+                ->set('uid', $query->createNamedParameter($extraData['uid']))
1145
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1146
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1147
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1148
+            ->execute();
1149
+
1150
+        $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1151
+
1152
+        $data = $this->getCalendarObject($calendarId, $objectUri);
1153
+        if (is_array($data)) {
1154
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1155
+                $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1156
+                    '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1157
+                    [
1158
+                        'calendarId' => $calendarId,
1159
+                        'calendarData' => $this->getCalendarById($calendarId),
1160
+                        'shares' => $this->getShares($calendarId),
1161
+                        'objectData' => $data,
1162
+                    ]
1163
+                ));
1164
+            } else {
1165
+                $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject', new GenericEvent(
1166
+                    '\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject',
1167
+                    [
1168
+                        'subscriptionId' => $calendarId,
1169
+                        'calendarData' => $this->getCalendarById($calendarId),
1170
+                        'shares' => $this->getShares($calendarId),
1171
+                        'objectData' => $data,
1172
+                    ]
1173
+                ));
1174
+            }
1175
+        }
1176
+        $this->addChange($calendarId, $objectUri, 2, $calendarType);
1177
+
1178
+        return '"' . $extraData['etag'] . '"';
1179
+    }
1180
+
1181
+    /**
1182
+     * @param int $calendarObjectId
1183
+     * @param int $classification
1184
+     */
1185
+    public function setClassification($calendarObjectId, $classification) {
1186
+        if (!in_array($classification, [
1187
+            self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1188
+        ])) {
1189
+            throw new \InvalidArgumentException();
1190
+        }
1191
+        $query = $this->db->getQueryBuilder();
1192
+        $query->update('calendarobjects')
1193
+            ->set('classification', $query->createNamedParameter($classification))
1194
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1195
+            ->execute();
1196
+    }
1197
+
1198
+    /**
1199
+     * Deletes an existing calendar object.
1200
+     *
1201
+     * The object uri is only the basename, or filename and not a full path.
1202
+     *
1203
+     * @param mixed $calendarId
1204
+     * @param string $objectUri
1205
+     * @param int $calendarType
1206
+     * @return void
1207
+     */
1208
+    function deleteCalendarObject($calendarId, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1209
+        $data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1210
+        if (is_array($data)) {
1211
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1212
+                $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1213
+                    '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1214
+                    [
1215
+                        'calendarId' => $calendarId,
1216
+                        'calendarData' => $this->getCalendarById($calendarId),
1217
+                        'shares' => $this->getShares($calendarId),
1218
+                        'objectData' => $data,
1219
+                    ]
1220
+                ));
1221
+            } else {
1222
+                $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject', new GenericEvent(
1223
+                    '\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject',
1224
+                    [
1225
+                        'subscriptionId' => $calendarId,
1226
+                        'calendarData' => $this->getCalendarById($calendarId),
1227
+                        'shares' => $this->getShares($calendarId),
1228
+                        'objectData' => $data,
1229
+                    ]
1230
+                ));
1231
+            }
1232
+        }
1233
+
1234
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1235
+        $stmt->execute([$calendarId, $objectUri, $calendarType]);
1236
+
1237
+        $this->purgeProperties($calendarId, $data['id'], $calendarType);
1238
+
1239
+        $this->addChange($calendarId, $objectUri, 3, $calendarType);
1240
+    }
1241
+
1242
+    /**
1243
+     * Performs a calendar-query on the contents of this calendar.
1244
+     *
1245
+     * The calendar-query is defined in RFC4791 : CalDAV. Using the
1246
+     * calendar-query it is possible for a client to request a specific set of
1247
+     * object, based on contents of iCalendar properties, date-ranges and
1248
+     * iCalendar component types (VTODO, VEVENT).
1249
+     *
1250
+     * This method should just return a list of (relative) urls that match this
1251
+     * query.
1252
+     *
1253
+     * The list of filters are specified as an array. The exact array is
1254
+     * documented by Sabre\CalDAV\CalendarQueryParser.
1255
+     *
1256
+     * Note that it is extremely likely that getCalendarObject for every path
1257
+     * returned from this method will be called almost immediately after. You
1258
+     * may want to anticipate this to speed up these requests.
1259
+     *
1260
+     * This method provides a default implementation, which parses *all* the
1261
+     * iCalendar objects in the specified calendar.
1262
+     *
1263
+     * This default may well be good enough for personal use, and calendars
1264
+     * that aren't very large. But if you anticipate high usage, big calendars
1265
+     * or high loads, you are strongly advised to optimize certain paths.
1266
+     *
1267
+     * The best way to do so is override this method and to optimize
1268
+     * specifically for 'common filters'.
1269
+     *
1270
+     * Requests that are extremely common are:
1271
+     *   * requests for just VEVENTS
1272
+     *   * requests for just VTODO
1273
+     *   * requests with a time-range-filter on either VEVENT or VTODO.
1274
+     *
1275
+     * ..and combinations of these requests. It may not be worth it to try to
1276
+     * handle every possible situation and just rely on the (relatively
1277
+     * easy to use) CalendarQueryValidator to handle the rest.
1278
+     *
1279
+     * Note that especially time-range-filters may be difficult to parse. A
1280
+     * time-range filter specified on a VEVENT must for instance also handle
1281
+     * recurrence rules correctly.
1282
+     * A good example of how to interprete all these filters can also simply
1283
+     * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1284
+     * as possible, so it gives you a good idea on what type of stuff you need
1285
+     * to think of.
1286
+     *
1287
+     * @param mixed $id
1288
+     * @param array $filters
1289
+     * @param int $calendarType
1290
+     * @return array
1291
+     */
1292
+    public function calendarQuery($id, array $filters, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
1293
+        $componentType = null;
1294
+        $requirePostFilter = true;
1295
+        $timeRange = null;
1296
+
1297
+        // if no filters were specified, we don't need to filter after a query
1298
+        if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1299
+            $requirePostFilter = false;
1300
+        }
1301
+
1302
+        // Figuring out if there's a component filter
1303
+        if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1304
+            $componentType = $filters['comp-filters'][0]['name'];
1305
+
1306
+            // Checking if we need post-filters
1307
+            if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1308
+                $requirePostFilter = false;
1309
+            }
1310
+            // There was a time-range filter
1311
+            if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1312
+                $timeRange = $filters['comp-filters'][0]['time-range'];
1313
+
1314
+                // If start time OR the end time is not specified, we can do a
1315
+                // 100% accurate mysql query.
1316
+                if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1317
+                    $requirePostFilter = false;
1318
+                }
1319
+            }
1320
+
1321
+        }
1322
+        $columns = ['uri'];
1323
+        if ($requirePostFilter) {
1324
+            $columns = ['uri', 'calendardata'];
1325
+        }
1326
+        $query = $this->db->getQueryBuilder();
1327
+        $query->select($columns)
1328
+            ->from('calendarobjects')
1329
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
1330
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1331
+
1332
+        if ($componentType) {
1333
+            $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1334
+        }
1335
+
1336
+        if ($timeRange && $timeRange['start']) {
1337
+            $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1338
+        }
1339
+        if ($timeRange && $timeRange['end']) {
1340
+            $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1341
+        }
1342
+
1343
+        $stmt = $query->execute();
1344
+
1345
+        $result = [];
1346
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1347
+            if ($requirePostFilter) {
1348
+                // validateFilterForObject will parse the calendar data
1349
+                // catch parsing errors
1350
+                try {
1351
+                    $matches = $this->validateFilterForObject($row, $filters);
1352
+                } catch(ParseException $ex) {
1353
+                    $this->logger->logException($ex, [
1354
+                        'app' => 'dav',
1355
+                        'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
1356
+                    ]);
1357
+                    continue;
1358
+                } catch (InvalidDataException $ex) {
1359
+                    $this->logger->logException($ex, [
1360
+                        'app' => 'dav',
1361
+                        'message' => 'Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
1362
+                    ]);
1363
+                    continue;
1364
+                }
1365
+
1366
+                if (!$matches) {
1367
+                    continue;
1368
+                }
1369
+            }
1370
+            $result[] = $row['uri'];
1371
+        }
1372
+
1373
+        return $result;
1374
+    }
1375
+
1376
+    /**
1377
+     * custom Nextcloud search extension for CalDAV
1378
+     *
1379
+     * TODO - this should optionally cover cached calendar objects as well
1380
+     *
1381
+     * @param string $principalUri
1382
+     * @param array $filters
1383
+     * @param integer|null $limit
1384
+     * @param integer|null $offset
1385
+     * @return array
1386
+     */
1387
+    public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1388
+        $calendars = $this->getCalendarsForUser($principalUri);
1389
+        $ownCalendars = [];
1390
+        $sharedCalendars = [];
1391
+
1392
+        $uriMapper = [];
1393
+
1394
+        foreach($calendars as $calendar) {
1395
+            if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1396
+                $ownCalendars[] = $calendar['id'];
1397
+            } else {
1398
+                $sharedCalendars[] = $calendar['id'];
1399
+            }
1400
+            $uriMapper[$calendar['id']] = $calendar['uri'];
1401
+        }
1402
+        if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1403
+            return [];
1404
+        }
1405
+
1406
+        $query = $this->db->getQueryBuilder();
1407
+        // Calendar id expressions
1408
+        $calendarExpressions = [];
1409
+        foreach($ownCalendars as $id) {
1410
+            $calendarExpressions[] = $query->expr()->andX(
1411
+                $query->expr()->eq('c.calendarid',
1412
+                    $query->createNamedParameter($id)),
1413
+                $query->expr()->eq('c.calendartype',
1414
+                        $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1415
+        }
1416
+        foreach($sharedCalendars as $id) {
1417
+            $calendarExpressions[] = $query->expr()->andX(
1418
+                $query->expr()->eq('c.calendarid',
1419
+                    $query->createNamedParameter($id)),
1420
+                $query->expr()->eq('c.classification',
1421
+                    $query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1422
+                $query->expr()->eq('c.calendartype',
1423
+                    $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1424
+        }
1425
+
1426
+        if (count($calendarExpressions) === 1) {
1427
+            $calExpr = $calendarExpressions[0];
1428
+        } else {
1429
+            $calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1430
+        }
1431
+
1432
+        // Component expressions
1433
+        $compExpressions = [];
1434
+        foreach($filters['comps'] as $comp) {
1435
+            $compExpressions[] = $query->expr()
1436
+                ->eq('c.componenttype', $query->createNamedParameter($comp));
1437
+        }
1438
+
1439
+        if (count($compExpressions) === 1) {
1440
+            $compExpr = $compExpressions[0];
1441
+        } else {
1442
+            $compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1443
+        }
1444
+
1445
+        if (!isset($filters['props'])) {
1446
+            $filters['props'] = [];
1447
+        }
1448
+        if (!isset($filters['params'])) {
1449
+            $filters['params'] = [];
1450
+        }
1451
+
1452
+        $propParamExpressions = [];
1453
+        foreach($filters['props'] as $prop) {
1454
+            $propParamExpressions[] = $query->expr()->andX(
1455
+                $query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1456
+                $query->expr()->isNull('i.parameter')
1457
+            );
1458
+        }
1459
+        foreach($filters['params'] as $param) {
1460
+            $propParamExpressions[] = $query->expr()->andX(
1461
+                $query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1462
+                $query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1463
+            );
1464
+        }
1465
+
1466
+        if (count($propParamExpressions) === 1) {
1467
+            $propParamExpr = $propParamExpressions[0];
1468
+        } else {
1469
+            $propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1470
+        }
1471
+
1472
+        $query->select(['c.calendarid', 'c.uri'])
1473
+            ->from($this->dbObjectPropertiesTable, 'i')
1474
+            ->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1475
+            ->where($calExpr)
1476
+            ->andWhere($compExpr)
1477
+            ->andWhere($propParamExpr)
1478
+            ->andWhere($query->expr()->iLike('i.value',
1479
+                $query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
1480
+
1481
+        if ($offset) {
1482
+            $query->setFirstResult($offset);
1483
+        }
1484
+        if ($limit) {
1485
+            $query->setMaxResults($limit);
1486
+        }
1487
+
1488
+        $stmt = $query->execute();
1489
+
1490
+        $result = [];
1491
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1492
+            $path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1493
+            if (!in_array($path, $result)) {
1494
+                $result[] = $path;
1495
+            }
1496
+        }
1497
+
1498
+        return $result;
1499
+    }
1500
+
1501
+    /**
1502
+     * used for Nextcloud's calendar API
1503
+     *
1504
+     * @param array $calendarInfo
1505
+     * @param string $pattern
1506
+     * @param array $searchProperties
1507
+     * @param array $options
1508
+     * @param integer|null $limit
1509
+     * @param integer|null $offset
1510
+     *
1511
+     * @return array
1512
+     */
1513
+    public function search(array $calendarInfo, $pattern, array $searchProperties,
1514
+                            array $options, $limit, $offset) {
1515
+        $outerQuery = $this->db->getQueryBuilder();
1516
+        $innerQuery = $this->db->getQueryBuilder();
1517
+
1518
+        $innerQuery->selectDistinct('op.objectid')
1519
+            ->from($this->dbObjectPropertiesTable, 'op')
1520
+            ->andWhere($innerQuery->expr()->eq('op.calendarid',
1521
+                $outerQuery->createNamedParameter($calendarInfo['id'])))
1522
+            ->andWhere($innerQuery->expr()->eq('op.calendartype',
1523
+                $outerQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1524
+
1525
+        // only return public items for shared calendars for now
1526
+        if ($calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1527
+            $innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
1528
+                $outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1529
+        }
1530
+
1531
+        $or = $innerQuery->expr()->orX();
1532
+        foreach($searchProperties as $searchProperty) {
1533
+            $or->add($innerQuery->expr()->eq('op.name',
1534
+                $outerQuery->createNamedParameter($searchProperty)));
1535
+        }
1536
+        $innerQuery->andWhere($or);
1537
+
1538
+        if ($pattern !== '') {
1539
+            $innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1540
+                $outerQuery->createNamedParameter('%' .
1541
+                    $this->db->escapeLikeParameter($pattern) . '%')));
1542
+        }
1543
+
1544
+        $outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1545
+            ->from('calendarobjects', 'c');
1546
+
1547
+        if (isset($options['timerange'])) {
1548
+            if (isset($options['timerange']['start'])) {
1549
+                $outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
1550
+                    $outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp)));
1551
+
1552
+            }
1553
+            if (isset($options['timerange']['end'])) {
1554
+                $outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
1555
+                    $outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp)));
1556
+            }
1557
+        }
1558
+
1559
+        if (isset($options['types'])) {
1560
+            $or = $outerQuery->expr()->orX();
1561
+            foreach($options['types'] as $type) {
1562
+                $or->add($outerQuery->expr()->eq('componenttype',
1563
+                    $outerQuery->createNamedParameter($type)));
1564
+            }
1565
+            $outerQuery->andWhere($or);
1566
+        }
1567
+
1568
+        $outerQuery->andWhere($outerQuery->expr()->in('c.id',
1569
+            $outerQuery->createFunction($innerQuery->getSQL())));
1570
+
1571
+        if ($offset) {
1572
+            $outerQuery->setFirstResult($offset);
1573
+        }
1574
+        if ($limit) {
1575
+            $outerQuery->setMaxResults($limit);
1576
+        }
1577
+
1578
+        $result = $outerQuery->execute();
1579
+        $calendarObjects = $result->fetchAll();
1580
+
1581
+        return array_map(function($o) {
1582
+            $calendarData = Reader::read($o['calendardata']);
1583
+            $comps = $calendarData->getComponents();
1584
+            $objects = [];
1585
+            $timezones = [];
1586
+            foreach($comps as $comp) {
1587
+                if ($comp instanceof VTimeZone) {
1588
+                    $timezones[] = $comp;
1589
+                } else {
1590
+                    $objects[] = $comp;
1591
+                }
1592
+            }
1593
+
1594
+            return [
1595
+                'id' => $o['id'],
1596
+                'type' => $o['componenttype'],
1597
+                'uid' => $o['uid'],
1598
+                'uri' => $o['uri'],
1599
+                'objects' => array_map(function($c) {
1600
+                    return $this->transformSearchData($c);
1601
+                }, $objects),
1602
+                'timezones' => array_map(function($c) {
1603
+                    return $this->transformSearchData($c);
1604
+                }, $timezones),
1605
+            ];
1606
+        }, $calendarObjects);
1607
+    }
1608
+
1609
+    /**
1610
+     * @param Component $comp
1611
+     * @return array
1612
+     */
1613
+    private function transformSearchData(Component $comp) {
1614
+        $data = [];
1615
+        /** @var Component[] $subComponents */
1616
+        $subComponents = $comp->getComponents();
1617
+        /** @var Property[] $properties */
1618
+        $properties = array_filter($comp->children(), function($c) {
1619
+            return $c instanceof Property;
1620
+        });
1621
+        $validationRules = $comp->getValidationRules();
1622
+
1623
+        foreach($subComponents as $subComponent) {
1624
+            $name = $subComponent->name;
1625
+            if (!isset($data[$name])) {
1626
+                $data[$name] = [];
1627
+            }
1628
+            $data[$name][] = $this->transformSearchData($subComponent);
1629
+        }
1630
+
1631
+        foreach($properties as $property) {
1632
+            $name = $property->name;
1633
+            if (!isset($validationRules[$name])) {
1634
+                $validationRules[$name] = '*';
1635
+            }
1636
+
1637
+            $rule = $validationRules[$property->name];
1638
+            if ($rule === '+' || $rule === '*') { // multiple
1639
+                if (!isset($data[$name])) {
1640
+                    $data[$name] = [];
1641
+                }
1642
+
1643
+                $data[$name][] = $this->transformSearchProperty($property);
1644
+            } else { // once
1645
+                $data[$name] = $this->transformSearchProperty($property);
1646
+            }
1647
+        }
1648
+
1649
+        return $data;
1650
+    }
1651
+
1652
+    /**
1653
+     * @param Property $prop
1654
+     * @return array
1655
+     */
1656
+    private function transformSearchProperty(Property $prop) {
1657
+        // No need to check Date, as it extends DateTime
1658
+        if ($prop instanceof Property\ICalendar\DateTime) {
1659
+            $value = $prop->getDateTime();
1660
+        } else {
1661
+            $value = $prop->getValue();
1662
+        }
1663
+
1664
+        return [
1665
+            $value,
1666
+            $prop->parameters()
1667
+        ];
1668
+    }
1669
+
1670
+    /**
1671
+     * Searches through all of a users calendars and calendar objects to find
1672
+     * an object with a specific UID.
1673
+     *
1674
+     * This method should return the path to this object, relative to the
1675
+     * calendar home, so this path usually only contains two parts:
1676
+     *
1677
+     * calendarpath/objectpath.ics
1678
+     *
1679
+     * If the uid is not found, return null.
1680
+     *
1681
+     * This method should only consider * objects that the principal owns, so
1682
+     * any calendars owned by other principals that also appear in this
1683
+     * collection should be ignored.
1684
+     *
1685
+     * @param string $principalUri
1686
+     * @param string $uid
1687
+     * @return string|null
1688
+     */
1689
+    function getCalendarObjectByUID($principalUri, $uid) {
1690
+
1691
+        $query = $this->db->getQueryBuilder();
1692
+        $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1693
+            ->from('calendarobjects', 'co')
1694
+            ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1695
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1696
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)))
1697
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1698
+
1699
+        $stmt = $query->execute();
1700
+
1701
+        if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1702
+            return $row['calendaruri'] . '/' . $row['objecturi'];
1703
+        }
1704
+
1705
+        return null;
1706
+    }
1707
+
1708
+    /**
1709
+     * The getChanges method returns all the changes that have happened, since
1710
+     * the specified syncToken in the specified calendar.
1711
+     *
1712
+     * This function should return an array, such as the following:
1713
+     *
1714
+     * [
1715
+     *   'syncToken' => 'The current synctoken',
1716
+     *   'added'   => [
1717
+     *      'new.txt',
1718
+     *   ],
1719
+     *   'modified'   => [
1720
+     *      'modified.txt',
1721
+     *   ],
1722
+     *   'deleted' => [
1723
+     *      'foo.php.bak',
1724
+     *      'old.txt'
1725
+     *   ]
1726
+     * );
1727
+     *
1728
+     * The returned syncToken property should reflect the *current* syncToken
1729
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1730
+     * property This is * needed here too, to ensure the operation is atomic.
1731
+     *
1732
+     * If the $syncToken argument is specified as null, this is an initial
1733
+     * sync, and all members should be reported.
1734
+     *
1735
+     * The modified property is an array of nodenames that have changed since
1736
+     * the last token.
1737
+     *
1738
+     * The deleted property is an array with nodenames, that have been deleted
1739
+     * from collection.
1740
+     *
1741
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
1742
+     * 1, you only have to report changes that happened only directly in
1743
+     * immediate descendants. If it's 2, it should also include changes from
1744
+     * the nodes below the child collections. (grandchildren)
1745
+     *
1746
+     * The $limit argument allows a client to specify how many results should
1747
+     * be returned at most. If the limit is not specified, it should be treated
1748
+     * as infinite.
1749
+     *
1750
+     * If the limit (infinite or not) is higher than you're willing to return,
1751
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1752
+     *
1753
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
1754
+     * return null.
1755
+     *
1756
+     * The limit is 'suggestive'. You are free to ignore it.
1757
+     *
1758
+     * @param string $calendarId
1759
+     * @param string $syncToken
1760
+     * @param int $syncLevel
1761
+     * @param int $limit
1762
+     * @param int $calendarType
1763
+     * @return array
1764
+     */
1765
+    function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1766
+        // Current synctoken
1767
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1768
+        $stmt->execute([ $calendarId ]);
1769
+        $currentToken = $stmt->fetchColumn(0);
1770
+
1771
+        if (is_null($currentToken)) {
1772
+            return null;
1773
+        }
1774
+
1775
+        $result = [
1776
+            'syncToken' => $currentToken,
1777
+            'added'     => [],
1778
+            'modified'  => [],
1779
+            'deleted'   => [],
1780
+        ];
1781
+
1782
+        if ($syncToken) {
1783
+
1784
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? AND `calendartype` = ? ORDER BY `synctoken`";
1785
+            if ($limit>0) {
1786
+                $query.= " LIMIT " . (int)$limit;
1787
+            }
1788
+
1789
+            // Fetching all changes
1790
+            $stmt = $this->db->prepare($query);
1791
+            $stmt->execute([$syncToken, $currentToken, $calendarId, $calendarType]);
1792
+
1793
+            $changes = [];
1794
+
1795
+            // This loop ensures that any duplicates are overwritten, only the
1796
+            // last change on a node is relevant.
1797
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1798
+
1799
+                $changes[$row['uri']] = $row['operation'];
1800
+
1801
+            }
1802
+
1803
+            foreach($changes as $uri => $operation) {
1804
+
1805
+                switch($operation) {
1806
+                    case 1 :
1807
+                        $result['added'][] = $uri;
1808
+                        break;
1809
+                    case 2 :
1810
+                        $result['modified'][] = $uri;
1811
+                        break;
1812
+                    case 3 :
1813
+                        $result['deleted'][] = $uri;
1814
+                        break;
1815
+                }
1816
+
1817
+            }
1818
+        } else {
1819
+            // No synctoken supplied, this is the initial sync.
1820
+            $query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?";
1821
+            $stmt = $this->db->prepare($query);
1822
+            $stmt->execute([$calendarId, $calendarType]);
1823
+
1824
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1825
+        }
1826
+        return $result;
1827
+
1828
+    }
1829
+
1830
+    /**
1831
+     * Returns a list of subscriptions for a principal.
1832
+     *
1833
+     * Every subscription is an array with the following keys:
1834
+     *  * id, a unique id that will be used by other functions to modify the
1835
+     *    subscription. This can be the same as the uri or a database key.
1836
+     *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1837
+     *  * principaluri. The owner of the subscription. Almost always the same as
1838
+     *    principalUri passed to this method.
1839
+     *
1840
+     * Furthermore, all the subscription info must be returned too:
1841
+     *
1842
+     * 1. {DAV:}displayname
1843
+     * 2. {http://apple.com/ns/ical/}refreshrate
1844
+     * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1845
+     *    should not be stripped).
1846
+     * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1847
+     *    should not be stripped).
1848
+     * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1849
+     *    attachments should not be stripped).
1850
+     * 6. {http://calendarserver.org/ns/}source (Must be a
1851
+     *     Sabre\DAV\Property\Href).
1852
+     * 7. {http://apple.com/ns/ical/}calendar-color
1853
+     * 8. {http://apple.com/ns/ical/}calendar-order
1854
+     * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1855
+     *    (should just be an instance of
1856
+     *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1857
+     *    default components).
1858
+     *
1859
+     * @param string $principalUri
1860
+     * @return array
1861
+     */
1862
+    function getSubscriptionsForUser($principalUri) {
1863
+        $fields = array_values($this->subscriptionPropertyMap);
1864
+        $fields[] = 'id';
1865
+        $fields[] = 'uri';
1866
+        $fields[] = 'source';
1867
+        $fields[] = 'principaluri';
1868
+        $fields[] = 'lastmodified';
1869
+        $fields[] = 'synctoken';
1870
+
1871
+        $query = $this->db->getQueryBuilder();
1872
+        $query->select($fields)
1873
+            ->from('calendarsubscriptions')
1874
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1875
+            ->orderBy('calendarorder', 'asc');
1876
+        $stmt =$query->execute();
1877
+
1878
+        $subscriptions = [];
1879
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1880
+
1881
+            $subscription = [
1882
+                'id'           => $row['id'],
1883
+                'uri'          => $row['uri'],
1884
+                'principaluri' => $row['principaluri'],
1885
+                'source'       => $row['source'],
1886
+                'lastmodified' => $row['lastmodified'],
1887
+
1888
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1889
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
1890
+            ];
1891
+
1892
+            foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1893
+                if (!is_null($row[$dbName])) {
1894
+                    $subscription[$xmlName] = $row[$dbName];
1895
+                }
1896
+            }
1897
+
1898
+            $subscriptions[] = $subscription;
1899
+
1900
+        }
1901
+
1902
+        return $subscriptions;
1903
+    }
1904
+
1905
+    /**
1906
+     * Creates a new subscription for a principal.
1907
+     *
1908
+     * If the creation was a success, an id must be returned that can be used to reference
1909
+     * this subscription in other methods, such as updateSubscription.
1910
+     *
1911
+     * @param string $principalUri
1912
+     * @param string $uri
1913
+     * @param array $properties
1914
+     * @return mixed
1915
+     */
1916
+    function createSubscription($principalUri, $uri, array $properties) {
1917
+
1918
+        if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1919
+            throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1920
+        }
1921
+
1922
+        $values = [
1923
+            'principaluri' => $principalUri,
1924
+            'uri'          => $uri,
1925
+            'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1926
+            'lastmodified' => time(),
1927
+        ];
1928
+
1929
+        $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1930
+
1931
+        foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1932
+            if (array_key_exists($xmlName, $properties)) {
1933
+                    $values[$dbName] = $properties[$xmlName];
1934
+                    if (in_array($dbName, $propertiesBoolean)) {
1935
+                        $values[$dbName] = true;
1936
+                }
1937
+            }
1938
+        }
1939
+
1940
+        $valuesToInsert = array();
1941
+
1942
+        $query = $this->db->getQueryBuilder();
1943
+
1944
+        foreach (array_keys($values) as $name) {
1945
+            $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1946
+        }
1947
+
1948
+        $query->insert('calendarsubscriptions')
1949
+            ->values($valuesToInsert)
1950
+            ->execute();
1951
+
1952
+        $subscriptionId = $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1953
+
1954
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createSubscription', new GenericEvent(
1955
+            '\OCA\DAV\CalDAV\CalDavBackend::createSubscription',
1956
+            [
1957
+                'subscriptionId' => $subscriptionId,
1958
+                'subscriptionData' => $this->getSubscriptionById($subscriptionId),
1959
+            ]));
1960
+
1961
+        return $subscriptionId;
1962
+    }
1963
+
1964
+    /**
1965
+     * Updates a subscription
1966
+     *
1967
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1968
+     * To do the actual updates, you must tell this object which properties
1969
+     * you're going to process with the handle() method.
1970
+     *
1971
+     * Calling the handle method is like telling the PropPatch object "I
1972
+     * promise I can handle updating this property".
1973
+     *
1974
+     * Read the PropPatch documentation for more info and examples.
1975
+     *
1976
+     * @param mixed $subscriptionId
1977
+     * @param PropPatch $propPatch
1978
+     * @return void
1979
+     */
1980
+    function updateSubscription($subscriptionId, PropPatch $propPatch) {
1981
+        $supportedProperties = array_keys($this->subscriptionPropertyMap);
1982
+        $supportedProperties[] = '{http://calendarserver.org/ns/}source';
1983
+
1984
+        /**
1985
+         * @suppress SqlInjectionChecker
1986
+         */
1987
+        $propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1988
+
1989
+            $newValues = [];
1990
+
1991
+            foreach($mutations as $propertyName=>$propertyValue) {
1992
+                if ($propertyName === '{http://calendarserver.org/ns/}source') {
1993
+                    $newValues['source'] = $propertyValue->getHref();
1994
+                } else {
1995
+                    $fieldName = $this->subscriptionPropertyMap[$propertyName];
1996
+                    $newValues[$fieldName] = $propertyValue;
1997
+                }
1998
+            }
1999
+
2000
+            $query = $this->db->getQueryBuilder();
2001
+            $query->update('calendarsubscriptions')
2002
+                ->set('lastmodified', $query->createNamedParameter(time()));
2003
+            foreach($newValues as $fieldName=>$value) {
2004
+                $query->set($fieldName, $query->createNamedParameter($value));
2005
+            }
2006
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2007
+                ->execute();
2008
+
2009
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateSubscription', new GenericEvent(
2010
+                '\OCA\DAV\CalDAV\CalDavBackend::updateSubscription',
2011
+                [
2012
+                    'subscriptionId' => $subscriptionId,
2013
+                    'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2014
+                    'propertyMutations' => $mutations,
2015
+                ]));
2016
+
2017
+            return true;
2018
+
2019
+        });
2020
+    }
2021
+
2022
+    /**
2023
+     * Deletes a subscription.
2024
+     *
2025
+     * @param mixed $subscriptionId
2026
+     * @return void
2027
+     */
2028
+    function deleteSubscription($subscriptionId) {
2029
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription', new GenericEvent(
2030
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription',
2031
+            [
2032
+                'subscriptionId' => $subscriptionId,
2033
+                'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2034
+            ]));
2035
+
2036
+        $query = $this->db->getQueryBuilder();
2037
+        $query->delete('calendarsubscriptions')
2038
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2039
+            ->execute();
2040
+
2041
+        $query = $this->db->getQueryBuilder();
2042
+        $query->delete('calendarobjects')
2043
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2044
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2045
+            ->execute();
2046
+
2047
+        $query->delete('calendarchanges')
2048
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2049
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2050
+            ->execute();
2051
+
2052
+        $query->delete($this->dbObjectPropertiesTable)
2053
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2054
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2055
+            ->execute();
2056
+    }
2057
+
2058
+    /**
2059
+     * Returns a single scheduling object for the inbox collection.
2060
+     *
2061
+     * The returned array should contain the following elements:
2062
+     *   * uri - A unique basename for the object. This will be used to
2063
+     *           construct a full uri.
2064
+     *   * calendardata - The iCalendar object
2065
+     *   * lastmodified - The last modification date. Can be an int for a unix
2066
+     *                    timestamp, or a PHP DateTime object.
2067
+     *   * etag - A unique token that must change if the object changed.
2068
+     *   * size - The size of the object, in bytes.
2069
+     *
2070
+     * @param string $principalUri
2071
+     * @param string $objectUri
2072
+     * @return array
2073
+     */
2074
+    function getSchedulingObject($principalUri, $objectUri) {
2075
+        $query = $this->db->getQueryBuilder();
2076
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2077
+            ->from('schedulingobjects')
2078
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2079
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2080
+            ->execute();
2081
+
2082
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
2083
+
2084
+        if(!$row) {
2085
+            return null;
2086
+        }
2087
+
2088
+        return [
2089
+                'uri'          => $row['uri'],
2090
+                'calendardata' => $row['calendardata'],
2091
+                'lastmodified' => $row['lastmodified'],
2092
+                'etag'         => '"' . $row['etag'] . '"',
2093
+                'size'         => (int)$row['size'],
2094
+        ];
2095
+    }
2096
+
2097
+    /**
2098
+     * Returns all scheduling objects for the inbox collection.
2099
+     *
2100
+     * These objects should be returned as an array. Every item in the array
2101
+     * should follow the same structure as returned from getSchedulingObject.
2102
+     *
2103
+     * The main difference is that 'calendardata' is optional.
2104
+     *
2105
+     * @param string $principalUri
2106
+     * @return array
2107
+     */
2108
+    function getSchedulingObjects($principalUri) {
2109
+        $query = $this->db->getQueryBuilder();
2110
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2111
+                ->from('schedulingobjects')
2112
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2113
+                ->execute();
2114
+
2115
+        $result = [];
2116
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2117
+            $result[] = [
2118
+                    'calendardata' => $row['calendardata'],
2119
+                    'uri'          => $row['uri'],
2120
+                    'lastmodified' => $row['lastmodified'],
2121
+                    'etag'         => '"' . $row['etag'] . '"',
2122
+                    'size'         => (int)$row['size'],
2123
+            ];
2124
+        }
2125
+
2126
+        return $result;
2127
+    }
2128
+
2129
+    /**
2130
+     * Deletes a scheduling object from the inbox collection.
2131
+     *
2132
+     * @param string $principalUri
2133
+     * @param string $objectUri
2134
+     * @return void
2135
+     */
2136
+    function deleteSchedulingObject($principalUri, $objectUri) {
2137
+        $query = $this->db->getQueryBuilder();
2138
+        $query->delete('schedulingobjects')
2139
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2140
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2141
+                ->execute();
2142
+    }
2143
+
2144
+    /**
2145
+     * Creates a new scheduling object. This should land in a users' inbox.
2146
+     *
2147
+     * @param string $principalUri
2148
+     * @param string $objectUri
2149
+     * @param string $objectData
2150
+     * @return void
2151
+     */
2152
+    function createSchedulingObject($principalUri, $objectUri, $objectData) {
2153
+        $query = $this->db->getQueryBuilder();
2154
+        $query->insert('schedulingobjects')
2155
+            ->values([
2156
+                'principaluri' => $query->createNamedParameter($principalUri),
2157
+                'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2158
+                'uri' => $query->createNamedParameter($objectUri),
2159
+                'lastmodified' => $query->createNamedParameter(time()),
2160
+                'etag' => $query->createNamedParameter(md5($objectData)),
2161
+                'size' => $query->createNamedParameter(strlen($objectData))
2162
+            ])
2163
+            ->execute();
2164
+    }
2165
+
2166
+    /**
2167
+     * Adds a change record to the calendarchanges table.
2168
+     *
2169
+     * @param mixed $calendarId
2170
+     * @param string $objectUri
2171
+     * @param int $operation 1 = add, 2 = modify, 3 = delete.
2172
+     * @param int $calendarType
2173
+     * @return void
2174
+     */
2175
+    protected function addChange($calendarId, $objectUri, $operation, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2176
+        $table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2177
+
2178
+        $query = $this->db->getQueryBuilder();
2179
+        $query->select('synctoken')
2180
+            ->from($table)
2181
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2182
+        $syncToken = (int)$query->execute()->fetchColumn();
2183
+
2184
+        $query = $this->db->getQueryBuilder();
2185
+        $query->insert('calendarchanges')
2186
+            ->values([
2187
+                'uri' => $query->createNamedParameter($objectUri),
2188
+                'synctoken' => $query->createNamedParameter($syncToken),
2189
+                'calendarid' => $query->createNamedParameter($calendarId),
2190
+                'operation' => $query->createNamedParameter($operation),
2191
+                'calendartype' => $query->createNamedParameter($calendarType),
2192
+            ])
2193
+            ->execute();
2194
+
2195
+        $stmt = $this->db->prepare("UPDATE `*PREFIX*$table` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?");
2196
+        $stmt->execute([
2197
+            $calendarId
2198
+        ]);
2199
+
2200
+    }
2201
+
2202
+    /**
2203
+     * Parses some information from calendar objects, used for optimized
2204
+     * calendar-queries.
2205
+     *
2206
+     * Returns an array with the following keys:
2207
+     *   * etag - An md5 checksum of the object without the quotes.
2208
+     *   * size - Size of the object in bytes
2209
+     *   * componentType - VEVENT, VTODO or VJOURNAL
2210
+     *   * firstOccurence
2211
+     *   * lastOccurence
2212
+     *   * uid - value of the UID property
2213
+     *
2214
+     * @param string $calendarData
2215
+     * @return array
2216
+     */
2217
+    public function getDenormalizedData($calendarData) {
2218
+
2219
+        $vObject = Reader::read($calendarData);
2220
+        $componentType = null;
2221
+        $component = null;
2222
+        $firstOccurrence = null;
2223
+        $lastOccurrence = null;
2224
+        $uid = null;
2225
+        $classification = self::CLASSIFICATION_PUBLIC;
2226
+        foreach($vObject->getComponents() as $component) {
2227
+            if ($component->name!=='VTIMEZONE') {
2228
+                $componentType = $component->name;
2229
+                $uid = (string)$component->UID;
2230
+                break;
2231
+            }
2232
+        }
2233
+        if (!$componentType) {
2234
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
2235
+        }
2236
+        if ($componentType === 'VEVENT' && $component->DTSTART) {
2237
+            $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
2238
+            // Finding the last occurrence is a bit harder
2239
+            if (!isset($component->RRULE)) {
2240
+                if (isset($component->DTEND)) {
2241
+                    $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
2242
+                } elseif (isset($component->DURATION)) {
2243
+                    $endDate = clone $component->DTSTART->getDateTime();
2244
+                    $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
2245
+                    $lastOccurrence = $endDate->getTimeStamp();
2246
+                } elseif (!$component->DTSTART->hasTime()) {
2247
+                    $endDate = clone $component->DTSTART->getDateTime();
2248
+                    $endDate->modify('+1 day');
2249
+                    $lastOccurrence = $endDate->getTimeStamp();
2250
+                } else {
2251
+                    $lastOccurrence = $firstOccurrence;
2252
+                }
2253
+            } else {
2254
+                $it = new EventIterator($vObject, (string)$component->UID);
2255
+                $maxDate = new \DateTime(self::MAX_DATE);
2256
+                if ($it->isInfinite()) {
2257
+                    $lastOccurrence = $maxDate->getTimestamp();
2258
+                } else {
2259
+                    $end = $it->getDtEnd();
2260
+                    while($it->valid() && $end < $maxDate) {
2261
+                        $end = $it->getDtEnd();
2262
+                        $it->next();
2263
+
2264
+                    }
2265
+                    $lastOccurrence = $end->getTimestamp();
2266
+                }
2267
+
2268
+            }
2269
+        }
2270
+
2271
+        if ($component->CLASS) {
2272
+            $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
2273
+            switch ($component->CLASS->getValue()) {
2274
+                case 'PUBLIC':
2275
+                    $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
2276
+                    break;
2277
+                case 'CONFIDENTIAL':
2278
+                    $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
2279
+                    break;
2280
+            }
2281
+        }
2282
+        return [
2283
+            'etag' => md5($calendarData),
2284
+            'size' => strlen($calendarData),
2285
+            'componentType' => $componentType,
2286
+            'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
2287
+            'lastOccurence'  => $lastOccurrence,
2288
+            'uid' => $uid,
2289
+            'classification' => $classification
2290
+        ];
2291
+
2292
+    }
2293
+
2294
+    /**
2295
+     * @param $cardData
2296
+     * @return bool|string
2297
+     */
2298
+    private function readBlob($cardData) {
2299
+        if (is_resource($cardData)) {
2300
+            return stream_get_contents($cardData);
2301
+        }
2302
+
2303
+        return $cardData;
2304
+    }
2305
+
2306
+    /**
2307
+     * @param IShareable $shareable
2308
+     * @param array $add
2309
+     * @param array $remove
2310
+     */
2311
+    public function updateShares($shareable, $add, $remove) {
2312
+        $calendarId = $shareable->getResourceId();
2313
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
2314
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2315
+            [
2316
+                'calendarId' => $calendarId,
2317
+                'calendarData' => $this->getCalendarById($calendarId),
2318
+                'shares' => $this->getShares($calendarId),
2319
+                'add' => $add,
2320
+                'remove' => $remove,
2321
+            ]));
2322
+        $this->calendarSharingBackend->updateShares($shareable, $add, $remove);
2323
+    }
2324
+
2325
+    /**
2326
+     * @param int $resourceId
2327
+     * @param int $calendarType
2328
+     * @return array
2329
+     */
2330
+    public function getShares($resourceId, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2331
+        return $this->calendarSharingBackend->getShares($resourceId);
2332
+    }
2333
+
2334
+    /**
2335
+     * @param boolean $value
2336
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
2337
+     * @return string|null
2338
+     */
2339
+    public function setPublishStatus($value, $calendar) {
2340
+
2341
+        $calendarId = $calendar->getResourceId();
2342
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', new GenericEvent(
2343
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2344
+            [
2345
+                'calendarId' => $calendarId,
2346
+                'calendarData' => $this->getCalendarById($calendarId),
2347
+                'public' => $value,
2348
+            ]));
2349
+
2350
+        $query = $this->db->getQueryBuilder();
2351
+        if ($value) {
2352
+            $publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
2353
+            $query->insert('dav_shares')
2354
+                ->values([
2355
+                    'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
2356
+                    'type' => $query->createNamedParameter('calendar'),
2357
+                    'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
2358
+                    'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
2359
+                    'publicuri' => $query->createNamedParameter($publicUri)
2360
+                ]);
2361
+            $query->execute();
2362
+            return $publicUri;
2363
+        }
2364
+        $query->delete('dav_shares')
2365
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2366
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
2367
+        $query->execute();
2368
+        return null;
2369
+    }
2370
+
2371
+    /**
2372
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
2373
+     * @return mixed
2374
+     */
2375
+    public function getPublishStatus($calendar) {
2376
+        $query = $this->db->getQueryBuilder();
2377
+        $result = $query->select('publicuri')
2378
+            ->from('dav_shares')
2379
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2380
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
2381
+            ->execute();
2382
+
2383
+        $row = $result->fetch();
2384
+        $result->closeCursor();
2385
+        return $row ? reset($row) : false;
2386
+    }
2387
+
2388
+    /**
2389
+     * @param int $resourceId
2390
+     * @param array $acl
2391
+     * @return array
2392
+     */
2393
+    public function applyShareAcl($resourceId, $acl) {
2394
+        return $this->calendarSharingBackend->applyShareAcl($resourceId, $acl);
2395
+    }
2396
+
2397
+
2398
+
2399
+    /**
2400
+     * update properties table
2401
+     *
2402
+     * @param int $calendarId
2403
+     * @param string $objectUri
2404
+     * @param string $calendarData
2405
+     * @param int $calendarType
2406
+     */
2407
+    public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2408
+        $objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
2409
+
2410
+        try {
2411
+            $vCalendar = $this->readCalendarData($calendarData);
2412
+        } catch (\Exception $ex) {
2413
+            return;
2414
+        }
2415
+
2416
+        $this->purgeProperties($calendarId, $objectId);
2417
+
2418
+        $query = $this->db->getQueryBuilder();
2419
+        $query->insert($this->dbObjectPropertiesTable)
2420
+            ->values(
2421
+                [
2422
+                    'calendarid' => $query->createNamedParameter($calendarId),
2423
+                    'calendartype' => $query->createNamedParameter($calendarType),
2424
+                    'objectid' => $query->createNamedParameter($objectId),
2425
+                    'name' => $query->createParameter('name'),
2426
+                    'parameter' => $query->createParameter('parameter'),
2427
+                    'value' => $query->createParameter('value'),
2428
+                ]
2429
+            );
2430
+
2431
+        $indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2432
+        foreach ($vCalendar->getComponents() as $component) {
2433
+            if (!in_array($component->name, $indexComponents)) {
2434
+                continue;
2435
+            }
2436
+
2437
+            foreach ($component->children() as $property) {
2438
+                if (in_array($property->name, self::$indexProperties)) {
2439
+                    $value = $property->getValue();
2440
+                    // is this a shitty db?
2441
+                    if (!$this->db->supports4ByteText()) {
2442
+                        $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2443
+                    }
2444
+                    $value = mb_substr($value, 0, 254);
2445
+
2446
+                    $query->setParameter('name', $property->name);
2447
+                    $query->setParameter('parameter', null);
2448
+                    $query->setParameter('value', $value);
2449
+                    $query->execute();
2450
+                }
2451
+
2452
+                if (array_key_exists($property->name, self::$indexParameters)) {
2453
+                    $parameters = $property->parameters();
2454
+                    $indexedParametersForProperty = self::$indexParameters[$property->name];
2455
+
2456
+                    foreach ($parameters as $key => $value) {
2457
+                        if (in_array($key, $indexedParametersForProperty)) {
2458
+                            // is this a shitty db?
2459
+                            if ($this->db->supports4ByteText()) {
2460
+                                $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2461
+                            }
2462
+                            $value = mb_substr($value, 0, 254);
2463
+
2464
+                            $query->setParameter('name', $property->name);
2465
+                            $query->setParameter('parameter', substr($key, 0, 254));
2466
+                            $query->setParameter('value', substr($value, 0, 254));
2467
+                            $query->execute();
2468
+                        }
2469
+                    }
2470
+                }
2471
+            }
2472
+        }
2473
+    }
2474
+
2475
+    /**
2476
+     * deletes all birthday calendars
2477
+     */
2478
+    public function deleteAllBirthdayCalendars() {
2479
+        $query = $this->db->getQueryBuilder();
2480
+        $result = $query->select(['id'])->from('calendars')
2481
+            ->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
2482
+            ->execute();
2483
+
2484
+        $ids = $result->fetchAll();
2485
+        foreach($ids as $id) {
2486
+            $this->deleteCalendar($id['id']);
2487
+        }
2488
+    }
2489
+
2490
+    /**
2491
+     * @param $subscriptionId
2492
+     */
2493
+    public function purgeAllCachedEventsForSubscription($subscriptionId) {
2494
+        $query = $this->db->getQueryBuilder();
2495
+        $query->select('uri')
2496
+            ->from('calendarobjects')
2497
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2498
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
2499
+        $stmt = $query->execute();
2500
+
2501
+        $uris = [];
2502
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2503
+            $uris[] = $row['uri'];
2504
+        }
2505
+        $stmt->closeCursor();
2506
+
2507
+        $query = $this->db->getQueryBuilder();
2508
+        $query->delete('calendarobjects')
2509
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2510
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2511
+            ->execute();
2512
+
2513
+        $query->delete('calendarchanges')
2514
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2515
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2516
+            ->execute();
2517
+
2518
+        $query->delete($this->dbObjectPropertiesTable)
2519
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2520
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2521
+            ->execute();
2522
+
2523
+        foreach($uris as $uri) {
2524
+            $this->addChange($subscriptionId, $uri, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
2525
+        }
2526
+    }
2527
+
2528
+    /**
2529
+     * Move a calendar from one user to another
2530
+     *
2531
+     * @param string $uriName
2532
+     * @param string $uriOrigin
2533
+     * @param string $uriDestination
2534
+     */
2535
+    public function moveCalendar($uriName, $uriOrigin, $uriDestination)
2536
+    {
2537
+        $query = $this->db->getQueryBuilder();
2538
+        $query->update('calendars')
2539
+            ->set('principaluri', $query->createNamedParameter($uriDestination))
2540
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
2541
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
2542
+            ->execute();
2543
+    }
2544
+
2545
+    /**
2546
+     * read VCalendar data into a VCalendar object
2547
+     *
2548
+     * @param string $objectData
2549
+     * @return VCalendar
2550
+     */
2551
+    protected function readCalendarData($objectData) {
2552
+        return Reader::read($objectData);
2553
+    }
2554
+
2555
+    /**
2556
+     * delete all properties from a given calendar object
2557
+     *
2558
+     * @param int $calendarId
2559
+     * @param int $objectId
2560
+     */
2561
+    protected function purgeProperties($calendarId, $objectId) {
2562
+        $query = $this->db->getQueryBuilder();
2563
+        $query->delete($this->dbObjectPropertiesTable)
2564
+            ->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
2565
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2566
+        $query->execute();
2567
+    }
2568
+
2569
+    /**
2570
+     * get ID from a given calendar object
2571
+     *
2572
+     * @param int $calendarId
2573
+     * @param string $uri
2574
+     * @param int $calendarType
2575
+     * @return int
2576
+     */
2577
+    protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
2578
+        $query = $this->db->getQueryBuilder();
2579
+        $query->select('id')
2580
+            ->from('calendarobjects')
2581
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2582
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
2583
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
2584
+
2585
+        $result = $query->execute();
2586
+        $objectIds = $result->fetch();
2587
+        $result->closeCursor();
2588
+
2589
+        if (!isset($objectIds['id'])) {
2590
+            throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2591
+        }
2592
+
2593
+        return (int)$objectIds['id'];
2594
+    }
2595
+
2596
+    /**
2597
+     * return legacy endpoint principal name to new principal name
2598
+     *
2599
+     * @param $principalUri
2600
+     * @param $toV2
2601
+     * @return string
2602
+     */
2603
+    private function convertPrincipal($principalUri, $toV2) {
2604
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2605
+            list(, $name) = Uri\split($principalUri);
2606
+            if ($toV2 === true) {
2607
+                return "principals/users/$name";
2608
+            }
2609
+            return "principals/$name";
2610
+        }
2611
+        return $principalUri;
2612
+    }
2613
+
2614
+    /**
2615
+     * adds information about an owner to the calendar data
2616
+     *
2617
+     * @param $calendarInfo
2618
+     */
2619
+    private function addOwnerPrincipal(&$calendarInfo) {
2620
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2621
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2622
+        if (isset($calendarInfo[$ownerPrincipalKey])) {
2623
+            $uri = $calendarInfo[$ownerPrincipalKey];
2624
+        } else {
2625
+            $uri = $calendarInfo['principaluri'];
2626
+        }
2627
+
2628
+        $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
2629
+        if (isset($principalInformation['{DAV:}displayname'])) {
2630
+            $calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
2631
+        }
2632
+    }
2633 2633
 }
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/Principal.php 2 patches
Indentation   +417 added lines, -417 removed lines patch added patch discarded remove patch
@@ -50,422 +50,422 @@
 block discarded – undo
50 50
 
51 51
 class Principal implements BackendInterface {
52 52
 
53
-	/** @var IUserManager */
54
-	private $userManager;
55
-
56
-	/** @var IGroupManager */
57
-	private $groupManager;
58
-
59
-	/** @var IShareManager */
60
-	private $shareManager;
61
-
62
-	/** @var IUserSession */
63
-	private $userSession;
64
-
65
-	/** @var IConfig */
66
-	private $config;
67
-
68
-	/** @var IAppManager */
69
-	private $appManager;
70
-
71
-	/** @var string */
72
-	private $principalPrefix;
73
-
74
-	/** @var bool */
75
-	private $hasGroups;
76
-
77
-	/** @var bool */
78
-	private $hasCircles;
79
-
80
-	/**
81
-	 * @param IUserManager $userManager
82
-	 * @param IGroupManager $groupManager
83
-	 * @param IShareManager $shareManager
84
-	 * @param IUserSession $userSession
85
-	 * @param IConfig $config
86
-	 * @param string $principalPrefix
87
-	 */
88
-	public function __construct(IUserManager $userManager,
89
-								IGroupManager $groupManager,
90
-								IShareManager $shareManager,
91
-								IUserSession $userSession,
92
-								IConfig $config,
93
-								IAppManager $appManager,
94
-								$principalPrefix = 'principals/users/') {
95
-		$this->userManager = $userManager;
96
-		$this->groupManager = $groupManager;
97
-		$this->shareManager = $shareManager;
98
-		$this->userSession = $userSession;
99
-		$this->config = $config;
100
-		$this->appManager = $appManager;
101
-		$this->principalPrefix = trim($principalPrefix, '/');
102
-		$this->hasGroups = $this->hasCircles = ($principalPrefix === 'principals/users/');
103
-	}
104
-
105
-	/**
106
-	 * Returns a list of principals based on a prefix.
107
-	 *
108
-	 * This prefix will often contain something like 'principals'. You are only
109
-	 * expected to return principals that are in this base path.
110
-	 *
111
-	 * You are expected to return at least a 'uri' for every user, you can
112
-	 * return any additional properties if you wish so. Common properties are:
113
-	 *   {DAV:}displayname
114
-	 *
115
-	 * @param string $prefixPath
116
-	 * @return string[]
117
-	 */
118
-	public function getPrincipalsByPrefix($prefixPath) {
119
-		$principals = [];
120
-
121
-		if ($prefixPath === $this->principalPrefix) {
122
-			foreach($this->userManager->search('') as $user) {
123
-				$principals[] = $this->userToPrincipal($user);
124
-			}
125
-		}
126
-
127
-		return $principals;
128
-	}
129
-
130
-	/**
131
-	 * Returns a specific principal, specified by it's path.
132
-	 * The returned structure should be the exact same as from
133
-	 * getPrincipalsByPrefix.
134
-	 *
135
-	 * @param string $path
136
-	 * @return array
137
-	 */
138
-	public function getPrincipalByPath($path) {
139
-		list($prefix, $name) = \Sabre\Uri\split($path);
140
-
141
-		if ($prefix === $this->principalPrefix) {
142
-			$user = $this->userManager->get($name);
143
-
144
-			if ($user !== null) {
145
-				return $this->userToPrincipal($user);
146
-			}
147
-		} else if ($prefix === 'principals/circles') {
148
-			return $this->circleToPrincipal($name);
149
-		}
150
-		return null;
151
-	}
152
-
153
-	/**
154
-	 * Returns the list of members for a group-principal
155
-	 *
156
-	 * @param string $principal
157
-	 * @return string[]
158
-	 * @throws Exception
159
-	 */
160
-	public function getGroupMemberSet($principal) {
161
-		// TODO: for now the group principal has only one member, the user itself
162
-		$principal = $this->getPrincipalByPath($principal);
163
-		if (!$principal) {
164
-			throw new Exception('Principal not found');
165
-		}
166
-
167
-		return [$principal['uri']];
168
-	}
169
-
170
-	/**
171
-	 * Returns the list of groups a principal is a member of
172
-	 *
173
-	 * @param string $principal
174
-	 * @param bool $needGroups
175
-	 * @return array
176
-	 * @throws Exception
177
-	 */
178
-	public function getGroupMembership($principal, $needGroups = false) {
179
-		list($prefix, $name) = \Sabre\Uri\split($principal);
180
-
181
-		if ($prefix === $this->principalPrefix) {
182
-			$user = $this->userManager->get($name);
183
-			if (!$user) {
184
-				throw new Exception('Principal not found');
185
-			}
186
-
187
-			if ($this->hasGroups || $needGroups) {
188
-				$groups = $this->groupManager->getUserGroups($user);
189
-				$groups = array_map(function($group) {
190
-					/** @var IGroup $group */
191
-					return 'principals/groups/' . urlencode($group->getGID());
192
-				}, $groups);
193
-
194
-				return $groups;
195
-			}
196
-		}
197
-		return [];
198
-	}
199
-
200
-	/**
201
-	 * Updates the list of group members for a group principal.
202
-	 *
203
-	 * The principals should be passed as a list of uri's.
204
-	 *
205
-	 * @param string $principal
206
-	 * @param string[] $members
207
-	 * @throws Exception
208
-	 */
209
-	public function setGroupMemberSet($principal, array $members) {
210
-		throw new Exception('Setting members of the group is not supported yet');
211
-	}
212
-
213
-	/**
214
-	 * @param string $path
215
-	 * @param PropPatch $propPatch
216
-	 * @return int
217
-	 */
218
-	function updatePrincipal($path, PropPatch $propPatch) {
219
-		return 0;
220
-	}
221
-
222
-	/**
223
-	 * Search user principals
224
-	 *
225
-	 * @param array $searchProperties
226
-	 * @param string $test
227
-	 * @return array
228
-	 */
229
-	protected function searchUserPrincipals(array $searchProperties, $test = 'allof') {
230
-		$results = [];
231
-
232
-		// If sharing is disabled, return the empty array
233
-		$shareAPIEnabled = $this->shareManager->shareApiEnabled();
234
-		if (!$shareAPIEnabled) {
235
-			return [];
236
-		}
237
-
238
-		// If sharing is restricted to group members only,
239
-		// return only members that have groups in common
240
-		$restrictGroups = false;
241
-		if ($this->shareManager->shareWithGroupMembersOnly()) {
242
-			$user = $this->userSession->getUser();
243
-			if (!$user) {
244
-				return [];
245
-			}
246
-
247
-			$restrictGroups = $this->groupManager->getUserGroupIds($user);
248
-		}
249
-
250
-		foreach ($searchProperties as $prop => $value) {
251
-			switch ($prop) {
252
-				case '{http://sabredav.org/ns}email-address':
253
-					$users = $this->userManager->getByEmail($value);
254
-
255
-					$results[] = array_reduce($users, function(array $carry, IUser $user) use ($restrictGroups) {
256
-						// is sharing restricted to groups only?
257
-						if ($restrictGroups !== false) {
258
-							$userGroups = $this->groupManager->getUserGroupIds($user);
259
-							if (count(array_intersect($userGroups, $restrictGroups)) === 0) {
260
-								return $carry;
261
-							}
262
-						}
263
-
264
-						$carry[] = $this->principalPrefix . '/' . $user->getUID();
265
-						return $carry;
266
-					}, []);
267
-					break;
268
-
269
-				case '{DAV:}displayname':
270
-					$users = $this->userManager->searchDisplayName($value);
271
-
272
-					$results[] = array_reduce($users, function(array $carry, IUser $user) use ($restrictGroups) {
273
-						// is sharing restricted to groups only?
274
-						if ($restrictGroups !== false) {
275
-							$userGroups = $this->groupManager->getUserGroupIds($user);
276
-							if (count(array_intersect($userGroups, $restrictGroups)) === 0) {
277
-								return $carry;
278
-							}
279
-						}
280
-
281
-						$carry[] = $this->principalPrefix . '/' . $user->getUID();
282
-						return $carry;
283
-					}, []);
284
-					break;
285
-
286
-				default:
287
-					$results[] = [];
288
-					break;
289
-			}
290
-		}
291
-
292
-		// results is an array of arrays, so this is not the first search result
293
-		// but the results of the first searchProperty
294
-		if (count($results) === 1) {
295
-			return $results[0];
296
-		}
297
-
298
-		switch ($test) {
299
-			case 'anyof':
300
-				return array_values(array_unique(array_merge(...$results)));
301
-
302
-			case 'allof':
303
-			default:
304
-				return array_values(array_intersect(...$results));
305
-		}
306
-	}
307
-
308
-	/**
309
-	 * @param string $prefixPath
310
-	 * @param array $searchProperties
311
-	 * @param string $test
312
-	 * @return array
313
-	 */
314
-	function searchPrincipals($prefixPath, array $searchProperties, $test = 'allof') {
315
-		if (count($searchProperties) === 0) {
316
-			return [];
317
-		}
318
-
319
-		switch ($prefixPath) {
320
-			case 'principals/users':
321
-				return $this->searchUserPrincipals($searchProperties, $test);
322
-
323
-			default:
324
-				return [];
325
-		}
326
-	}
327
-
328
-	/**
329
-	 * @param string $uri
330
-	 * @param string $principalPrefix
331
-	 * @return string
332
-	 */
333
-	function findByUri($uri, $principalPrefix) {
334
-		// If sharing is disabled, return the empty array
335
-		$shareAPIEnabled = $this->shareManager->shareApiEnabled();
336
-		if (!$shareAPIEnabled) {
337
-			return null;
338
-		}
339
-
340
-		// If sharing is restricted to group members only,
341
-		// return only members that have groups in common
342
-		$restrictGroups = false;
343
-		if ($this->shareManager->shareWithGroupMembersOnly()) {
344
-			$user = $this->userSession->getUser();
345
-			if (!$user) {
346
-				return null;
347
-			}
348
-
349
-			$restrictGroups = $this->groupManager->getUserGroupIds($user);
350
-		}
351
-
352
-		if (strpos($uri, 'mailto:') === 0) {
353
-			if ($principalPrefix === 'principals/users') {
354
-				$users = $this->userManager->getByEmail(substr($uri, 7));
355
-				if (count($users) !== 1) {
356
-					return null;
357
-				}
358
-				$user = $users[0];
359
-
360
-				if ($restrictGroups !== false) {
361
-					$userGroups = $this->groupManager->getUserGroupIds($user);
362
-					if (count(array_intersect($userGroups, $restrictGroups)) === 0) {
363
-						return null;
364
-					}
365
-				}
366
-
367
-				return $this->principalPrefix . '/' . $user->getUID();
368
-			}
369
-		}
370
-		if (substr($uri, 0, 10) === 'principal:') {
371
-			$principal = substr($uri, 10);
372
-			$principal = $this->getPrincipalByPath($principal);
373
-			if ($principal !== null) {
374
-				return $principal['uri'];
375
-			}
376
-		}
377
-
378
-		return null;
379
-	}
380
-
381
-	/**
382
-	 * @param IUser $user
383
-	 * @return array
384
-	 */
385
-	protected function userToPrincipal($user) {
386
-		$userId = $user->getUID();
387
-		$displayName = $user->getDisplayName();
388
-		$principal = [
389
-				'uri' => $this->principalPrefix . '/' . $userId,
390
-				'{DAV:}displayname' => is_null($displayName) ? $userId : $displayName,
391
-				'{urn:ietf:params:xml:ns:caldav}calendar-user-type' => 'INDIVIDUAL',
392
-		];
393
-
394
-		$email = $user->getEMailAddress();
395
-		if (!empty($email)) {
396
-			$principal['{http://sabredav.org/ns}email-address'] = $email;
397
-		}
398
-
399
-		return $principal;
400
-	}
401
-
402
-	public function getPrincipalPrefix() {
403
-		return $this->principalPrefix;
404
-	}
405
-
406
-	/**
407
-	 * @param string $circleUniqueId
408
-	 * @return array|null
409
-	 * @suppress PhanUndeclaredClassMethod
410
-	 * @suppress PhanUndeclaredClassCatch
411
-	 */
412
-	protected function circleToPrincipal($circleUniqueId) {
413
-		if (!$this->appManager->isEnabledForUser('circles') || !class_exists('\OCA\Circles\Api\v1\Circles')) {
414
-			return null;
415
-		}
416
-
417
-		try {
418
-			$circle = \OCA\Circles\Api\v1\Circles::detailsCircle($circleUniqueId, true);
419
-		} catch(QueryException $ex) {
420
-			return null;
421
-		} catch(CircleDoesNotExistException $ex) {
422
-			return null;
423
-		}
424
-
425
-		if (!$circle) {
426
-			return null;
427
-		}
428
-
429
-		$principal = [
430
-			'uri' => 'principals/circles/' . $circleUniqueId,
431
-			'{DAV:}displayname' => $circle->getName(),
432
-		];
433
-
434
-		return $principal;
435
-	}
436
-
437
-	/**
438
-	 * Returns the list of circles a principal is a member of
439
-	 *
440
-	 * @param string $principal
441
-	 * @param bool $needGroups
442
-	 * @return array
443
-	 * @throws Exception
444
-	 * @suppress PhanUndeclaredClassMethod
445
-	 */
446
-	public function getCircleMembership($principal):array {
447
-		if (!$this->appManager->isEnabledForUser('circles') || !class_exists('\OCA\Circles\Api\v1\Circles')) {
448
-			return [];
449
-		}
450
-
451
-		list($prefix, $name) = \Sabre\Uri\split($principal);
452
-		if ($this->hasCircles && $prefix === $this->principalPrefix) {
453
-			$user = $this->userManager->get($name);
454
-			if (!$user) {
455
-				throw new Exception('Principal not found');
456
-			}
457
-
458
-			$circles = \OCA\Circles\Api\v1\Circles::joinedCircles($name, true);
459
-
460
-			$circles = array_map(function($circle) {
461
-				/** @var \OCA\Circles\Model\Circle $group */
462
-				return 'principals/circles/' . urlencode($circle->getUniqueId());
463
-			}, $circles);
464
-
465
-			return $circles;
466
-
467
-		}
468
-		return [];
469
-	}
53
+    /** @var IUserManager */
54
+    private $userManager;
55
+
56
+    /** @var IGroupManager */
57
+    private $groupManager;
58
+
59
+    /** @var IShareManager */
60
+    private $shareManager;
61
+
62
+    /** @var IUserSession */
63
+    private $userSession;
64
+
65
+    /** @var IConfig */
66
+    private $config;
67
+
68
+    /** @var IAppManager */
69
+    private $appManager;
70
+
71
+    /** @var string */
72
+    private $principalPrefix;
73
+
74
+    /** @var bool */
75
+    private $hasGroups;
76
+
77
+    /** @var bool */
78
+    private $hasCircles;
79
+
80
+    /**
81
+     * @param IUserManager $userManager
82
+     * @param IGroupManager $groupManager
83
+     * @param IShareManager $shareManager
84
+     * @param IUserSession $userSession
85
+     * @param IConfig $config
86
+     * @param string $principalPrefix
87
+     */
88
+    public function __construct(IUserManager $userManager,
89
+                                IGroupManager $groupManager,
90
+                                IShareManager $shareManager,
91
+                                IUserSession $userSession,
92
+                                IConfig $config,
93
+                                IAppManager $appManager,
94
+                                $principalPrefix = 'principals/users/') {
95
+        $this->userManager = $userManager;
96
+        $this->groupManager = $groupManager;
97
+        $this->shareManager = $shareManager;
98
+        $this->userSession = $userSession;
99
+        $this->config = $config;
100
+        $this->appManager = $appManager;
101
+        $this->principalPrefix = trim($principalPrefix, '/');
102
+        $this->hasGroups = $this->hasCircles = ($principalPrefix === 'principals/users/');
103
+    }
104
+
105
+    /**
106
+     * Returns a list of principals based on a prefix.
107
+     *
108
+     * This prefix will often contain something like 'principals'. You are only
109
+     * expected to return principals that are in this base path.
110
+     *
111
+     * You are expected to return at least a 'uri' for every user, you can
112
+     * return any additional properties if you wish so. Common properties are:
113
+     *   {DAV:}displayname
114
+     *
115
+     * @param string $prefixPath
116
+     * @return string[]
117
+     */
118
+    public function getPrincipalsByPrefix($prefixPath) {
119
+        $principals = [];
120
+
121
+        if ($prefixPath === $this->principalPrefix) {
122
+            foreach($this->userManager->search('') as $user) {
123
+                $principals[] = $this->userToPrincipal($user);
124
+            }
125
+        }
126
+
127
+        return $principals;
128
+    }
129
+
130
+    /**
131
+     * Returns a specific principal, specified by it's path.
132
+     * The returned structure should be the exact same as from
133
+     * getPrincipalsByPrefix.
134
+     *
135
+     * @param string $path
136
+     * @return array
137
+     */
138
+    public function getPrincipalByPath($path) {
139
+        list($prefix, $name) = \Sabre\Uri\split($path);
140
+
141
+        if ($prefix === $this->principalPrefix) {
142
+            $user = $this->userManager->get($name);
143
+
144
+            if ($user !== null) {
145
+                return $this->userToPrincipal($user);
146
+            }
147
+        } else if ($prefix === 'principals/circles') {
148
+            return $this->circleToPrincipal($name);
149
+        }
150
+        return null;
151
+    }
152
+
153
+    /**
154
+     * Returns the list of members for a group-principal
155
+     *
156
+     * @param string $principal
157
+     * @return string[]
158
+     * @throws Exception
159
+     */
160
+    public function getGroupMemberSet($principal) {
161
+        // TODO: for now the group principal has only one member, the user itself
162
+        $principal = $this->getPrincipalByPath($principal);
163
+        if (!$principal) {
164
+            throw new Exception('Principal not found');
165
+        }
166
+
167
+        return [$principal['uri']];
168
+    }
169
+
170
+    /**
171
+     * Returns the list of groups a principal is a member of
172
+     *
173
+     * @param string $principal
174
+     * @param bool $needGroups
175
+     * @return array
176
+     * @throws Exception
177
+     */
178
+    public function getGroupMembership($principal, $needGroups = false) {
179
+        list($prefix, $name) = \Sabre\Uri\split($principal);
180
+
181
+        if ($prefix === $this->principalPrefix) {
182
+            $user = $this->userManager->get($name);
183
+            if (!$user) {
184
+                throw new Exception('Principal not found');
185
+            }
186
+
187
+            if ($this->hasGroups || $needGroups) {
188
+                $groups = $this->groupManager->getUserGroups($user);
189
+                $groups = array_map(function($group) {
190
+                    /** @var IGroup $group */
191
+                    return 'principals/groups/' . urlencode($group->getGID());
192
+                }, $groups);
193
+
194
+                return $groups;
195
+            }
196
+        }
197
+        return [];
198
+    }
199
+
200
+    /**
201
+     * Updates the list of group members for a group principal.
202
+     *
203
+     * The principals should be passed as a list of uri's.
204
+     *
205
+     * @param string $principal
206
+     * @param string[] $members
207
+     * @throws Exception
208
+     */
209
+    public function setGroupMemberSet($principal, array $members) {
210
+        throw new Exception('Setting members of the group is not supported yet');
211
+    }
212
+
213
+    /**
214
+     * @param string $path
215
+     * @param PropPatch $propPatch
216
+     * @return int
217
+     */
218
+    function updatePrincipal($path, PropPatch $propPatch) {
219
+        return 0;
220
+    }
221
+
222
+    /**
223
+     * Search user principals
224
+     *
225
+     * @param array $searchProperties
226
+     * @param string $test
227
+     * @return array
228
+     */
229
+    protected function searchUserPrincipals(array $searchProperties, $test = 'allof') {
230
+        $results = [];
231
+
232
+        // If sharing is disabled, return the empty array
233
+        $shareAPIEnabled = $this->shareManager->shareApiEnabled();
234
+        if (!$shareAPIEnabled) {
235
+            return [];
236
+        }
237
+
238
+        // If sharing is restricted to group members only,
239
+        // return only members that have groups in common
240
+        $restrictGroups = false;
241
+        if ($this->shareManager->shareWithGroupMembersOnly()) {
242
+            $user = $this->userSession->getUser();
243
+            if (!$user) {
244
+                return [];
245
+            }
246
+
247
+            $restrictGroups = $this->groupManager->getUserGroupIds($user);
248
+        }
249
+
250
+        foreach ($searchProperties as $prop => $value) {
251
+            switch ($prop) {
252
+                case '{http://sabredav.org/ns}email-address':
253
+                    $users = $this->userManager->getByEmail($value);
254
+
255
+                    $results[] = array_reduce($users, function(array $carry, IUser $user) use ($restrictGroups) {
256
+                        // is sharing restricted to groups only?
257
+                        if ($restrictGroups !== false) {
258
+                            $userGroups = $this->groupManager->getUserGroupIds($user);
259
+                            if (count(array_intersect($userGroups, $restrictGroups)) === 0) {
260
+                                return $carry;
261
+                            }
262
+                        }
263
+
264
+                        $carry[] = $this->principalPrefix . '/' . $user->getUID();
265
+                        return $carry;
266
+                    }, []);
267
+                    break;
268
+
269
+                case '{DAV:}displayname':
270
+                    $users = $this->userManager->searchDisplayName($value);
271
+
272
+                    $results[] = array_reduce($users, function(array $carry, IUser $user) use ($restrictGroups) {
273
+                        // is sharing restricted to groups only?
274
+                        if ($restrictGroups !== false) {
275
+                            $userGroups = $this->groupManager->getUserGroupIds($user);
276
+                            if (count(array_intersect($userGroups, $restrictGroups)) === 0) {
277
+                                return $carry;
278
+                            }
279
+                        }
280
+
281
+                        $carry[] = $this->principalPrefix . '/' . $user->getUID();
282
+                        return $carry;
283
+                    }, []);
284
+                    break;
285
+
286
+                default:
287
+                    $results[] = [];
288
+                    break;
289
+            }
290
+        }
291
+
292
+        // results is an array of arrays, so this is not the first search result
293
+        // but the results of the first searchProperty
294
+        if (count($results) === 1) {
295
+            return $results[0];
296
+        }
297
+
298
+        switch ($test) {
299
+            case 'anyof':
300
+                return array_values(array_unique(array_merge(...$results)));
301
+
302
+            case 'allof':
303
+            default:
304
+                return array_values(array_intersect(...$results));
305
+        }
306
+    }
307
+
308
+    /**
309
+     * @param string $prefixPath
310
+     * @param array $searchProperties
311
+     * @param string $test
312
+     * @return array
313
+     */
314
+    function searchPrincipals($prefixPath, array $searchProperties, $test = 'allof') {
315
+        if (count($searchProperties) === 0) {
316
+            return [];
317
+        }
318
+
319
+        switch ($prefixPath) {
320
+            case 'principals/users':
321
+                return $this->searchUserPrincipals($searchProperties, $test);
322
+
323
+            default:
324
+                return [];
325
+        }
326
+    }
327
+
328
+    /**
329
+     * @param string $uri
330
+     * @param string $principalPrefix
331
+     * @return string
332
+     */
333
+    function findByUri($uri, $principalPrefix) {
334
+        // If sharing is disabled, return the empty array
335
+        $shareAPIEnabled = $this->shareManager->shareApiEnabled();
336
+        if (!$shareAPIEnabled) {
337
+            return null;
338
+        }
339
+
340
+        // If sharing is restricted to group members only,
341
+        // return only members that have groups in common
342
+        $restrictGroups = false;
343
+        if ($this->shareManager->shareWithGroupMembersOnly()) {
344
+            $user = $this->userSession->getUser();
345
+            if (!$user) {
346
+                return null;
347
+            }
348
+
349
+            $restrictGroups = $this->groupManager->getUserGroupIds($user);
350
+        }
351
+
352
+        if (strpos($uri, 'mailto:') === 0) {
353
+            if ($principalPrefix === 'principals/users') {
354
+                $users = $this->userManager->getByEmail(substr($uri, 7));
355
+                if (count($users) !== 1) {
356
+                    return null;
357
+                }
358
+                $user = $users[0];
359
+
360
+                if ($restrictGroups !== false) {
361
+                    $userGroups = $this->groupManager->getUserGroupIds($user);
362
+                    if (count(array_intersect($userGroups, $restrictGroups)) === 0) {
363
+                        return null;
364
+                    }
365
+                }
366
+
367
+                return $this->principalPrefix . '/' . $user->getUID();
368
+            }
369
+        }
370
+        if (substr($uri, 0, 10) === 'principal:') {
371
+            $principal = substr($uri, 10);
372
+            $principal = $this->getPrincipalByPath($principal);
373
+            if ($principal !== null) {
374
+                return $principal['uri'];
375
+            }
376
+        }
377
+
378
+        return null;
379
+    }
380
+
381
+    /**
382
+     * @param IUser $user
383
+     * @return array
384
+     */
385
+    protected function userToPrincipal($user) {
386
+        $userId = $user->getUID();
387
+        $displayName = $user->getDisplayName();
388
+        $principal = [
389
+                'uri' => $this->principalPrefix . '/' . $userId,
390
+                '{DAV:}displayname' => is_null($displayName) ? $userId : $displayName,
391
+                '{urn:ietf:params:xml:ns:caldav}calendar-user-type' => 'INDIVIDUAL',
392
+        ];
393
+
394
+        $email = $user->getEMailAddress();
395
+        if (!empty($email)) {
396
+            $principal['{http://sabredav.org/ns}email-address'] = $email;
397
+        }
398
+
399
+        return $principal;
400
+    }
401
+
402
+    public function getPrincipalPrefix() {
403
+        return $this->principalPrefix;
404
+    }
405
+
406
+    /**
407
+     * @param string $circleUniqueId
408
+     * @return array|null
409
+     * @suppress PhanUndeclaredClassMethod
410
+     * @suppress PhanUndeclaredClassCatch
411
+     */
412
+    protected function circleToPrincipal($circleUniqueId) {
413
+        if (!$this->appManager->isEnabledForUser('circles') || !class_exists('\OCA\Circles\Api\v1\Circles')) {
414
+            return null;
415
+        }
416
+
417
+        try {
418
+            $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($circleUniqueId, true);
419
+        } catch(QueryException $ex) {
420
+            return null;
421
+        } catch(CircleDoesNotExistException $ex) {
422
+            return null;
423
+        }
424
+
425
+        if (!$circle) {
426
+            return null;
427
+        }
428
+
429
+        $principal = [
430
+            'uri' => 'principals/circles/' . $circleUniqueId,
431
+            '{DAV:}displayname' => $circle->getName(),
432
+        ];
433
+
434
+        return $principal;
435
+    }
436
+
437
+    /**
438
+     * Returns the list of circles a principal is a member of
439
+     *
440
+     * @param string $principal
441
+     * @param bool $needGroups
442
+     * @return array
443
+     * @throws Exception
444
+     * @suppress PhanUndeclaredClassMethod
445
+     */
446
+    public function getCircleMembership($principal):array {
447
+        if (!$this->appManager->isEnabledForUser('circles') || !class_exists('\OCA\Circles\Api\v1\Circles')) {
448
+            return [];
449
+        }
450
+
451
+        list($prefix, $name) = \Sabre\Uri\split($principal);
452
+        if ($this->hasCircles && $prefix === $this->principalPrefix) {
453
+            $user = $this->userManager->get($name);
454
+            if (!$user) {
455
+                throw new Exception('Principal not found');
456
+            }
457
+
458
+            $circles = \OCA\Circles\Api\v1\Circles::joinedCircles($name, true);
459
+
460
+            $circles = array_map(function($circle) {
461
+                /** @var \OCA\Circles\Model\Circle $group */
462
+                return 'principals/circles/' . urlencode($circle->getUniqueId());
463
+            }, $circles);
464
+
465
+            return $circles;
466
+
467
+        }
468
+        return [];
469
+    }
470 470
 
471 471
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
 		$principals = [];
120 120
 
121 121
 		if ($prefixPath === $this->principalPrefix) {
122
-			foreach($this->userManager->search('') as $user) {
122
+			foreach ($this->userManager->search('') as $user) {
123 123
 				$principals[] = $this->userToPrincipal($user);
124 124
 			}
125 125
 		}
@@ -188,7 +188,7 @@  discard block
 block discarded – undo
188 188
 				$groups = $this->groupManager->getUserGroups($user);
189 189
 				$groups = array_map(function($group) {
190 190
 					/** @var IGroup $group */
191
-					return 'principals/groups/' . urlencode($group->getGID());
191
+					return 'principals/groups/'.urlencode($group->getGID());
192 192
 				}, $groups);
193 193
 
194 194
 				return $groups;
@@ -261,7 +261,7 @@  discard block
 block discarded – undo
261 261
 							}
262 262
 						}
263 263
 
264
-						$carry[] = $this->principalPrefix . '/' . $user->getUID();
264
+						$carry[] = $this->principalPrefix.'/'.$user->getUID();
265 265
 						return $carry;
266 266
 					}, []);
267 267
 					break;
@@ -278,7 +278,7 @@  discard block
 block discarded – undo
278 278
 							}
279 279
 						}
280 280
 
281
-						$carry[] = $this->principalPrefix . '/' . $user->getUID();
281
+						$carry[] = $this->principalPrefix.'/'.$user->getUID();
282 282
 						return $carry;
283 283
 					}, []);
284 284
 					break;
@@ -364,7 +364,7 @@  discard block
 block discarded – undo
364 364
 					}
365 365
 				}
366 366
 
367
-				return $this->principalPrefix . '/' . $user->getUID();
367
+				return $this->principalPrefix.'/'.$user->getUID();
368 368
 			}
369 369
 		}
370 370
 		if (substr($uri, 0, 10) === 'principal:') {
@@ -386,7 +386,7 @@  discard block
 block discarded – undo
386 386
 		$userId = $user->getUID();
387 387
 		$displayName = $user->getDisplayName();
388 388
 		$principal = [
389
-				'uri' => $this->principalPrefix . '/' . $userId,
389
+				'uri' => $this->principalPrefix.'/'.$userId,
390 390
 				'{DAV:}displayname' => is_null($displayName) ? $userId : $displayName,
391 391
 				'{urn:ietf:params:xml:ns:caldav}calendar-user-type' => 'INDIVIDUAL',
392 392
 		];
@@ -416,9 +416,9 @@  discard block
 block discarded – undo
416 416
 
417 417
 		try {
418 418
 			$circle = \OCA\Circles\Api\v1\Circles::detailsCircle($circleUniqueId, true);
419
-		} catch(QueryException $ex) {
419
+		} catch (QueryException $ex) {
420 420
 			return null;
421
-		} catch(CircleDoesNotExistException $ex) {
421
+		} catch (CircleDoesNotExistException $ex) {
422 422
 			return null;
423 423
 		}
424 424
 
@@ -427,7 +427,7 @@  discard block
 block discarded – undo
427 427
 		}
428 428
 
429 429
 		$principal = [
430
-			'uri' => 'principals/circles/' . $circleUniqueId,
430
+			'uri' => 'principals/circles/'.$circleUniqueId,
431 431
 			'{DAV:}displayname' => $circle->getName(),
432 432
 		];
433 433
 
@@ -459,7 +459,7 @@  discard block
 block discarded – undo
459 459
 
460 460
 			$circles = array_map(function($circle) {
461 461
 				/** @var \OCA\Circles\Model\Circle $group */
462
-				return 'principals/circles/' . urlencode($circle->getUniqueId());
462
+				return 'principals/circles/'.urlencode($circle->getUniqueId());
463 463
 			}, $circles);
464 464
 
465 465
 			return $circles;
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/SharesPlugin.php 1 patch
Indentation   +179 added lines, -179 removed lines patch added patch discarded remove patch
@@ -36,183 +36,183 @@
 block discarded – undo
36 36
  */
37 37
 class SharesPlugin extends \Sabre\DAV\ServerPlugin {
38 38
 
39
-	const NS_OWNCLOUD = 'http://owncloud.org/ns';
40
-	const SHARETYPES_PROPERTYNAME = '{http://owncloud.org/ns}share-types';
41
-
42
-	/**
43
-	 * Reference to main server object
44
-	 *
45
-	 * @var \Sabre\DAV\Server
46
-	 */
47
-	private $server;
48
-
49
-	/**
50
-	 * @var \OCP\Share\IManager
51
-	 */
52
-	private $shareManager;
53
-
54
-	/**
55
-	 * @var \Sabre\DAV\Tree
56
-	 */
57
-	private $tree;
58
-
59
-	/**
60
-	 * @var string
61
-	 */
62
-	private $userId;
63
-
64
-	/**
65
-	 * @var \OCP\Files\Folder
66
-	 */
67
-	private $userFolder;
68
-
69
-	/**
70
-	 * @var IShare[]
71
-	 */
72
-	private $cachedShareTypes;
73
-
74
-	private $cachedFolders = [];
75
-
76
-	/**
77
-	 * @param \Sabre\DAV\Tree $tree tree
78
-	 * @param IUserSession $userSession user session
79
-	 * @param \OCP\Files\Folder $userFolder user home folder
80
-	 * @param \OCP\Share\IManager $shareManager share manager
81
-	 */
82
-	public function __construct(
83
-		\Sabre\DAV\Tree $tree,
84
-		IUserSession $userSession,
85
-		\OCP\Files\Folder $userFolder,
86
-		\OCP\Share\IManager $shareManager
87
-	) {
88
-		$this->tree = $tree;
89
-		$this->shareManager = $shareManager;
90
-		$this->userFolder = $userFolder;
91
-		$this->userId = $userSession->getUser()->getUID();
92
-		$this->cachedShareTypes = [];
93
-	}
94
-
95
-	/**
96
-	 * This initializes the plugin.
97
-	 *
98
-	 * This function is called by \Sabre\DAV\Server, after
99
-	 * addPlugin is called.
100
-	 *
101
-	 * This method should set up the required event subscriptions.
102
-	 *
103
-	 * @param \Sabre\DAV\Server $server
104
-	 */
105
-	public function initialize(\Sabre\DAV\Server $server) {
106
-		$server->xml->namespacesMap[self::NS_OWNCLOUD] = 'oc';
107
-		$server->xml->elementMap[self::SHARETYPES_PROPERTYNAME] = ShareTypeList::class;
108
-		$server->protectedProperties[] = self::SHARETYPES_PROPERTYNAME;
109
-
110
-		$this->server = $server;
111
-		$this->server->on('propFind', array($this, 'handleGetProperties'));
112
-	}
113
-
114
-	/**
115
-	 * Return a list of share types for outgoing shares
116
-	 *
117
-	 * @param \OCP\Files\Node $node file node
118
-	 *
119
-	 * @return int[] array of share types
120
-	 */
121
-	private function getShareTypes(\OCP\Files\Node $node) {
122
-		$shareTypes = [];
123
-		$requestedShareTypes = [
124
-			\OCP\Share::SHARE_TYPE_USER,
125
-			\OCP\Share::SHARE_TYPE_GROUP,
126
-			\OCP\Share::SHARE_TYPE_LINK,
127
-			\OCP\Share::SHARE_TYPE_REMOTE,
128
-			\OCP\Share::SHARE_TYPE_EMAIL,
129
-			\OCP\Share::SHARE_TYPE_ROOM,
130
-			\OCP\Share::SHARE_TYPE_CIRCLE,
131
-		];
132
-		foreach ($requestedShareTypes as $requestedShareType) {
133
-			// one of each type is enough to find out about the types
134
-			$shares = $this->shareManager->getSharesBy(
135
-				$this->userId,
136
-				$requestedShareType,
137
-				$node,
138
-				false,
139
-				1
140
-			);
141
-			if (!empty($shares)) {
142
-				$shareTypes[] = $requestedShareType;
143
-			}
144
-		}
145
-		return $shareTypes;
146
-	}
147
-
148
-	private function getSharesTypesInFolder(\OCP\Files\Folder $node) {
149
-		$shares = $this->shareManager->getSharesInFolder(
150
-			$this->userId,
151
-			$node,
152
-			true
153
-		);
154
-
155
-		$shareTypesByFileId = [];
156
-
157
-		foreach($shares as $fileId => $sharesForFile) {
158
-			$types = array_map(function(IShare $share) {
159
-				return $share->getShareType();
160
-			}, $sharesForFile);
161
-			$types = array_unique($types);
162
-			sort($types);
163
-			$shareTypesByFileId[$fileId] = $types;
164
-		}
165
-
166
-		return $shareTypesByFileId;
167
-	}
168
-
169
-	/**
170
-	 * Adds shares to propfind response
171
-	 *
172
-	 * @param PropFind $propFind propfind object
173
-	 * @param \Sabre\DAV\INode $sabreNode sabre node
174
-	 */
175
-	public function handleGetProperties(
176
-		PropFind $propFind,
177
-		\Sabre\DAV\INode $sabreNode
178
-	) {
179
-		if (!($sabreNode instanceof \OCA\DAV\Connector\Sabre\Node)) {
180
-			return;
181
-		}
182
-
183
-		// need prefetch ?
184
-		if ($sabreNode instanceof \OCA\DAV\Connector\Sabre\Directory
185
-			&& $propFind->getDepth() !== 0
186
-			&& !is_null($propFind->getStatus(self::SHARETYPES_PROPERTYNAME))
187
-		) {
188
-			$folderNode = $this->userFolder->get($sabreNode->getPath());
189
-
190
-			$childShares = $this->getSharesTypesInFolder($folderNode);
191
-			$this->cachedFolders[] = $sabreNode->getPath();
192
-			$this->cachedShareTypes[$folderNode->getId()] = $this->getShareTypes($folderNode);
193
-			foreach ($childShares as $id => $shares) {
194
-				$this->cachedShareTypes[$id] = $shares;
195
-			}
196
-		}
197
-
198
-		$propFind->handle(self::SHARETYPES_PROPERTYNAME, function () use ($sabreNode) {
199
-			if (isset($this->cachedShareTypes[$sabreNode->getId()])) {
200
-				$shareTypes = $this->cachedShareTypes[$sabreNode->getId()];
201
-			} else {
202
-				list($parentPath,) = \Sabre\Uri\split($sabreNode->getPath());
203
-				if ($parentPath === '') {
204
-					$parentPath = '/';
205
-				}
206
-				// if we already cached the folder this file is in we know there are no shares for this file
207
-				if (array_search($parentPath, $this->cachedFolders) === false) {
208
-					$node = $this->userFolder->get($sabreNode->getPath());
209
-					$shareTypes = $this->getShareTypes($node);
210
-				} else {
211
-					return [];
212
-				}
213
-			}
214
-
215
-			return new ShareTypeList($shareTypes);
216
-		});
217
-	}
39
+    const NS_OWNCLOUD = 'http://owncloud.org/ns';
40
+    const SHARETYPES_PROPERTYNAME = '{http://owncloud.org/ns}share-types';
41
+
42
+    /**
43
+     * Reference to main server object
44
+     *
45
+     * @var \Sabre\DAV\Server
46
+     */
47
+    private $server;
48
+
49
+    /**
50
+     * @var \OCP\Share\IManager
51
+     */
52
+    private $shareManager;
53
+
54
+    /**
55
+     * @var \Sabre\DAV\Tree
56
+     */
57
+    private $tree;
58
+
59
+    /**
60
+     * @var string
61
+     */
62
+    private $userId;
63
+
64
+    /**
65
+     * @var \OCP\Files\Folder
66
+     */
67
+    private $userFolder;
68
+
69
+    /**
70
+     * @var IShare[]
71
+     */
72
+    private $cachedShareTypes;
73
+
74
+    private $cachedFolders = [];
75
+
76
+    /**
77
+     * @param \Sabre\DAV\Tree $tree tree
78
+     * @param IUserSession $userSession user session
79
+     * @param \OCP\Files\Folder $userFolder user home folder
80
+     * @param \OCP\Share\IManager $shareManager share manager
81
+     */
82
+    public function __construct(
83
+        \Sabre\DAV\Tree $tree,
84
+        IUserSession $userSession,
85
+        \OCP\Files\Folder $userFolder,
86
+        \OCP\Share\IManager $shareManager
87
+    ) {
88
+        $this->tree = $tree;
89
+        $this->shareManager = $shareManager;
90
+        $this->userFolder = $userFolder;
91
+        $this->userId = $userSession->getUser()->getUID();
92
+        $this->cachedShareTypes = [];
93
+    }
94
+
95
+    /**
96
+     * This initializes the plugin.
97
+     *
98
+     * This function is called by \Sabre\DAV\Server, after
99
+     * addPlugin is called.
100
+     *
101
+     * This method should set up the required event subscriptions.
102
+     *
103
+     * @param \Sabre\DAV\Server $server
104
+     */
105
+    public function initialize(\Sabre\DAV\Server $server) {
106
+        $server->xml->namespacesMap[self::NS_OWNCLOUD] = 'oc';
107
+        $server->xml->elementMap[self::SHARETYPES_PROPERTYNAME] = ShareTypeList::class;
108
+        $server->protectedProperties[] = self::SHARETYPES_PROPERTYNAME;
109
+
110
+        $this->server = $server;
111
+        $this->server->on('propFind', array($this, 'handleGetProperties'));
112
+    }
113
+
114
+    /**
115
+     * Return a list of share types for outgoing shares
116
+     *
117
+     * @param \OCP\Files\Node $node file node
118
+     *
119
+     * @return int[] array of share types
120
+     */
121
+    private function getShareTypes(\OCP\Files\Node $node) {
122
+        $shareTypes = [];
123
+        $requestedShareTypes = [
124
+            \OCP\Share::SHARE_TYPE_USER,
125
+            \OCP\Share::SHARE_TYPE_GROUP,
126
+            \OCP\Share::SHARE_TYPE_LINK,
127
+            \OCP\Share::SHARE_TYPE_REMOTE,
128
+            \OCP\Share::SHARE_TYPE_EMAIL,
129
+            \OCP\Share::SHARE_TYPE_ROOM,
130
+            \OCP\Share::SHARE_TYPE_CIRCLE,
131
+        ];
132
+        foreach ($requestedShareTypes as $requestedShareType) {
133
+            // one of each type is enough to find out about the types
134
+            $shares = $this->shareManager->getSharesBy(
135
+                $this->userId,
136
+                $requestedShareType,
137
+                $node,
138
+                false,
139
+                1
140
+            );
141
+            if (!empty($shares)) {
142
+                $shareTypes[] = $requestedShareType;
143
+            }
144
+        }
145
+        return $shareTypes;
146
+    }
147
+
148
+    private function getSharesTypesInFolder(\OCP\Files\Folder $node) {
149
+        $shares = $this->shareManager->getSharesInFolder(
150
+            $this->userId,
151
+            $node,
152
+            true
153
+        );
154
+
155
+        $shareTypesByFileId = [];
156
+
157
+        foreach($shares as $fileId => $sharesForFile) {
158
+            $types = array_map(function(IShare $share) {
159
+                return $share->getShareType();
160
+            }, $sharesForFile);
161
+            $types = array_unique($types);
162
+            sort($types);
163
+            $shareTypesByFileId[$fileId] = $types;
164
+        }
165
+
166
+        return $shareTypesByFileId;
167
+    }
168
+
169
+    /**
170
+     * Adds shares to propfind response
171
+     *
172
+     * @param PropFind $propFind propfind object
173
+     * @param \Sabre\DAV\INode $sabreNode sabre node
174
+     */
175
+    public function handleGetProperties(
176
+        PropFind $propFind,
177
+        \Sabre\DAV\INode $sabreNode
178
+    ) {
179
+        if (!($sabreNode instanceof \OCA\DAV\Connector\Sabre\Node)) {
180
+            return;
181
+        }
182
+
183
+        // need prefetch ?
184
+        if ($sabreNode instanceof \OCA\DAV\Connector\Sabre\Directory
185
+            && $propFind->getDepth() !== 0
186
+            && !is_null($propFind->getStatus(self::SHARETYPES_PROPERTYNAME))
187
+        ) {
188
+            $folderNode = $this->userFolder->get($sabreNode->getPath());
189
+
190
+            $childShares = $this->getSharesTypesInFolder($folderNode);
191
+            $this->cachedFolders[] = $sabreNode->getPath();
192
+            $this->cachedShareTypes[$folderNode->getId()] = $this->getShareTypes($folderNode);
193
+            foreach ($childShares as $id => $shares) {
194
+                $this->cachedShareTypes[$id] = $shares;
195
+            }
196
+        }
197
+
198
+        $propFind->handle(self::SHARETYPES_PROPERTYNAME, function () use ($sabreNode) {
199
+            if (isset($this->cachedShareTypes[$sabreNode->getId()])) {
200
+                $shareTypes = $this->cachedShareTypes[$sabreNode->getId()];
201
+            } else {
202
+                list($parentPath,) = \Sabre\Uri\split($sabreNode->getPath());
203
+                if ($parentPath === '') {
204
+                    $parentPath = '/';
205
+                }
206
+                // if we already cached the folder this file is in we know there are no shares for this file
207
+                if (array_search($parentPath, $this->cachedFolders) === false) {
208
+                    $node = $this->userFolder->get($sabreNode->getPath());
209
+                    $shareTypes = $this->getShareTypes($node);
210
+                } else {
211
+                    return [];
212
+                }
213
+            }
214
+
215
+            return new ShareTypeList($shareTypes);
216
+        });
217
+    }
218 218
 }
Please login to merge, or discard this patch.
apps/dav/lib/Command/CreateCalendar.php 1 patch
Indentation   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -35,58 +35,58 @@
 block discarded – undo
35 35
 
36 36
 class CreateCalendar extends Command {
37 37
 
38
-	/** @var IUserManager */
39
-	protected $userManager;
38
+    /** @var IUserManager */
39
+    protected $userManager;
40 40
 
41
-	/** @var IGroupManager $groupManager */
42
-	private $groupManager;
41
+    /** @var IGroupManager $groupManager */
42
+    private $groupManager;
43 43
 
44
-	/** @var \OCP\IDBConnection */
45
-	protected $dbConnection;
44
+    /** @var \OCP\IDBConnection */
45
+    protected $dbConnection;
46 46
 
47
-	/**
48
-	 * @param IUserManager $userManager
49
-	 * @param IGroupManager $groupManager
50
-	 * @param IDBConnection $dbConnection
51
-	 */
52
-	function __construct(IUserManager $userManager, IGroupManager $groupManager, IDBConnection $dbConnection) {
53
-		parent::__construct();
54
-		$this->userManager = $userManager;
55
-		$this->groupManager = $groupManager;
56
-		$this->dbConnection = $dbConnection;
57
-	}
47
+    /**
48
+     * @param IUserManager $userManager
49
+     * @param IGroupManager $groupManager
50
+     * @param IDBConnection $dbConnection
51
+     */
52
+    function __construct(IUserManager $userManager, IGroupManager $groupManager, IDBConnection $dbConnection) {
53
+        parent::__construct();
54
+        $this->userManager = $userManager;
55
+        $this->groupManager = $groupManager;
56
+        $this->dbConnection = $dbConnection;
57
+    }
58 58
 
59
-	protected function configure() {
60
-		$this
61
-			->setName('dav:create-calendar')
62
-			->setDescription('Create a dav calendar')
63
-			->addArgument('user',
64
-				InputArgument::REQUIRED,
65
-				'User for whom the calendar will be created')
66
-			->addArgument('name',
67
-				InputArgument::REQUIRED,
68
-				'Name of the calendar');
69
-	}
59
+    protected function configure() {
60
+        $this
61
+            ->setName('dav:create-calendar')
62
+            ->setDescription('Create a dav calendar')
63
+            ->addArgument('user',
64
+                InputArgument::REQUIRED,
65
+                'User for whom the calendar will be created')
66
+            ->addArgument('name',
67
+                InputArgument::REQUIRED,
68
+                'Name of the calendar');
69
+    }
70 70
 
71
-	protected function execute(InputInterface $input, OutputInterface $output) {
72
-		$user = $input->getArgument('user');
73
-		if (!$this->userManager->userExists($user)) {
74
-			throw new \InvalidArgumentException("User <$user> in unknown.");
75
-		}
76
-		$principalBackend = new Principal(
77
-			$this->userManager,
78
-			$this->groupManager,
79
-			\OC::$server->getShareManager(),
80
-			\OC::$server->getUserSession(),
81
-			\OC::$server->getConfig(),
82
-			\OC::$server->getAppManager()
83
-		);
84
-		$random = \OC::$server->getSecureRandom();
85
-		$logger = \OC::$server->getLogger();
86
-		$dispatcher = \OC::$server->getEventDispatcher();
71
+    protected function execute(InputInterface $input, OutputInterface $output) {
72
+        $user = $input->getArgument('user');
73
+        if (!$this->userManager->userExists($user)) {
74
+            throw new \InvalidArgumentException("User <$user> in unknown.");
75
+        }
76
+        $principalBackend = new Principal(
77
+            $this->userManager,
78
+            $this->groupManager,
79
+            \OC::$server->getShareManager(),
80
+            \OC::$server->getUserSession(),
81
+            \OC::$server->getConfig(),
82
+            \OC::$server->getAppManager()
83
+        );
84
+        $random = \OC::$server->getSecureRandom();
85
+        $logger = \OC::$server->getLogger();
86
+        $dispatcher = \OC::$server->getEventDispatcher();
87 87
 
88
-		$name = $input->getArgument('name');
89
-		$caldav = new CalDavBackend($this->dbConnection, $principalBackend, $this->userManager, $this->groupManager, $random, $logger, $dispatcher);
90
-		$caldav->createCalendar("principals/users/$user", $name, []);
91
-	}
88
+        $name = $input->getArgument('name');
89
+        $caldav = new CalDavBackend($this->dbConnection, $principalBackend, $this->userManager, $this->groupManager, $random, $logger, $dispatcher);
90
+        $caldav->createCalendar("principals/users/$user", $name, []);
91
+    }
92 92
 }
Please login to merge, or discard this patch.
apps/dav/appinfo/v1/caldav.php 1 patch
Indentation   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -34,21 +34,21 @@  discard block
 block discarded – undo
34 34
 use OCA\DAV\Connector\Sabre\Principal;
35 35
 
36 36
 $authBackend = new Auth(
37
-	\OC::$server->getSession(),
38
-	\OC::$server->getUserSession(),
39
-	\OC::$server->getRequest(),
40
-	\OC::$server->getTwoFactorAuthManager(),
41
-	\OC::$server->getBruteForceThrottler(),
42
-	'principals/'
37
+    \OC::$server->getSession(),
38
+    \OC::$server->getUserSession(),
39
+    \OC::$server->getRequest(),
40
+    \OC::$server->getTwoFactorAuthManager(),
41
+    \OC::$server->getBruteForceThrottler(),
42
+    'principals/'
43 43
 );
44 44
 $principalBackend = new Principal(
45
-	\OC::$server->getUserManager(),
46
-	\OC::$server->getGroupManager(),
47
-	\OC::$server->getShareManager(),
48
-	\OC::$server->getUserSession(),
49
-	\OC::$server->getConfig(),
50
-	\OC::$server->getAppManager(),
51
-	'principals/'
45
+    \OC::$server->getUserManager(),
46
+    \OC::$server->getGroupManager(),
47
+    \OC::$server->getShareManager(),
48
+    \OC::$server->getUserSession(),
49
+    \OC::$server->getConfig(),
50
+    \OC::$server->getAppManager(),
51
+    'principals/'
52 52
 );
53 53
 $db = \OC::$server->getDatabaseConnection();
54 54
 $userManager = \OC::$server->getUserManager();
@@ -68,8 +68,8 @@  discard block
 block discarded – undo
68 68
 $addressBookRoot->disableListing = !$debugging; // Disable listing
69 69
 
70 70
 $nodes = array(
71
-	$principalCollection,
72
-	$addressBookRoot,
71
+    $principalCollection,
72
+    $addressBookRoot,
73 73
 );
74 74
 
75 75
 // Fire up server
@@ -85,7 +85,7 @@  discard block
 block discarded – undo
85 85
 
86 86
 $server->addPlugin(new LegacyDAVACL());
87 87
 if ($debugging) {
88
-	$server->addPlugin(new Sabre\DAV\Browser\Plugin());
88
+    $server->addPlugin(new Sabre\DAV\Browser\Plugin());
89 89
 }
90 90
 
91 91
 $server->addPlugin(new \Sabre\DAV\Sync\Plugin());
@@ -93,7 +93,7 @@  discard block
 block discarded – undo
93 93
 $server->addPlugin(new \OCA\DAV\CalDAV\Schedule\Plugin());
94 94
 
95 95
 if ($sendInvitations) {
96
-	$server->addPlugin(\OC::$server->query(\OCA\DAV\CalDAV\Schedule\IMipPlugin::class));
96
+    $server->addPlugin(\OC::$server->query(\OCA\DAV\CalDAV\Schedule\IMipPlugin::class));
97 97
 }
98 98
 $server->addPlugin(new ExceptionLoggerPlugin('caldav', \OC::$server->getLogger()));
99 99
 
Please login to merge, or discard this patch.